main.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import axios from "axios"
  2. import { defineStore } from "pinia";
  3. import { api } from "@/api"
  4. import router from "@/router"
  5. import { getLocalToken, removeLocalToken, saveLocalToken } from "@/utils";
  6. import type { AppNotification } from '@/interfaces';
  7. import type { IUserProfile, IUserProfileCreate, IUserProfileUpdate, MainState, Video, VideoCreate } from '@/interfaces';
  8. import i18n from '@/plugins/i18n'
  9. import WS from "@/stores/ws";
  10. const defaultState: MainState = {
  11. isLoggedIn: null,
  12. token: '',
  13. logInError: false,
  14. userProfile: null,
  15. dashboardMiniDrawer: false,
  16. dashboardShowDrawer: true,
  17. notifications: [],
  18. videos: [],
  19. };
  20. export const useMainStore = defineStore("MainStoreId", {
  21. state: () => defaultState,
  22. getters: {
  23. readhasAdminAccess: (state) =>
  24. state.userProfile && state.userProfile.is_superuser && state.userProfile.is_active,
  25. readLoginError: (state) => state.logInError,
  26. readDashboardShowDrawer: (state) => state.dashboardShowDrawer,
  27. readDashboardMiniDrawer: (state) => state.dashboardMiniDrawer,
  28. readUserProfile: (state) => state.userProfile,
  29. readToken: (state) => state.token,
  30. readIsLoggedIn: (state) => state.isLoggedIn,
  31. readFirstNotification: (state) => state.notifications.length > 0 && state.notifications[0],
  32. readVideos: (state) => state.videos,
  33. },
  34. actions: {
  35. // setters
  36. setToken(payload: string) { this.token = payload; },
  37. setLoggedIn(payload: boolean) { this.isLoggedIn = payload; },
  38. setLogInError(payload: boolean) { this.logInError = payload; },
  39. setUserProfile(payload: IUserProfile) { this.userProfile = payload },
  40. setDashboardMiniDrawer(payload: boolean) { this.dashboardMiniDrawer = payload; },
  41. setDashboardShowDrawer(payload: boolean) { this.dashboardShowDrawer = payload; },
  42. setVideos(payload: Video[]) { this.videos = payload },
  43. addNotification(payload: AppNotification) { this.notifications.push(payload); },
  44. removeNotification(payload: AppNotification) {
  45. if (payload) {
  46. this.notifications = this.notifications.filter(
  47. (notification) => notification !== payload,
  48. );
  49. }
  50. },
  51. // actions
  52. async logIn(username: string, password: string) {
  53. try {
  54. const response = await api.logInGetToken(username, password);
  55. const token: string = response.data.access_token;
  56. if (token) {
  57. saveLocalToken(token);
  58. this.setToken(token);
  59. this.setLoggedIn(true);
  60. this.setLogInError(false);
  61. await this.getUserProfile();
  62. console.log(this.userProfile);
  63. await this.routeLoggedIn();
  64. this.addNotification({ content: i18n.global.t("loggedIn"), color: "success" });
  65. } else {
  66. await this.logOut();
  67. }
  68. } catch (err) {
  69. this.setLogInError(true);
  70. await this.logOut();
  71. }
  72. },
  73. async getUserProfile() {
  74. try {
  75. const response = await api.getMe(this.token);
  76. if (response.data) {
  77. this.setUserProfile(response.data)
  78. }
  79. } catch (error) {
  80. await this.checkApiError(error);
  81. }
  82. },
  83. async updateUserProfile(payload: IUserProfileUpdate) {
  84. try {
  85. const loadingNotification = { content: i18n.global.t("saving"), showProgress: true };
  86. await this.addNotification(loadingNotification);
  87. const response = (
  88. await Promise.all([
  89. api.updateMe(this.token, payload),
  90. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
  91. ])
  92. )[0];
  93. this.setUserProfile(response.data);
  94. this.removeNotification(loadingNotification);
  95. this.addNotification({
  96. content: i18n.global.t("profileUpdated"),
  97. color: "success",
  98. });
  99. } catch (error) {
  100. await this.checkApiError(error);
  101. }
  102. },
  103. async checkLoggedIn() {
  104. if (!this.isLoggedIn) {
  105. let token = this.token;
  106. if (!token) {
  107. const localToken = getLocalToken();
  108. if (localToken) {
  109. this.setToken(localToken);
  110. token = localToken;
  111. }
  112. }
  113. if (token) {
  114. try {
  115. const response = await api.getMe(token);
  116. this.setLoggedIn(true);
  117. this.setUserProfile(response.data);
  118. router.push("/main/dashboard");
  119. } catch (error) {
  120. await this.removeLogIn();
  121. }
  122. } else {
  123. await this.removeLogIn();
  124. }
  125. }
  126. },
  127. async removeLogIn() {
  128. removeLocalToken();
  129. this.setToken("");
  130. this.setLoggedIn(false);
  131. },
  132. async logOut() {
  133. await this.removeLogIn();
  134. this.routeLogOut();
  135. },
  136. async userLogOut() {
  137. await this.logOut();
  138. this.addNotification({ content: "Logged out", color: "success" });
  139. },
  140. routeLogOut() {
  141. if (router.currentRoute.value.path !== "/login") {
  142. router.push("/login");
  143. }
  144. },
  145. async checkApiError(payload: unknown) {
  146. if (axios.isAxiosError(payload)) {
  147. if (payload.response?.status === 401) {
  148. await this.logOut();
  149. }
  150. }
  151. },
  152. routeLoggedIn() {
  153. if (router.currentRoute.value.path === "/login" || router.currentRoute.value.path === "/") {
  154. router.push("/main/dashboard");
  155. }
  156. },
  157. async dispatchRemoveNotification(payload: { notification: AppNotification; timeout: number },) {
  158. return new Promise((resolve, _) => {
  159. setTimeout(() => {
  160. this.removeNotification(payload.notification);
  161. resolve(true);
  162. }, payload.timeout);
  163. });
  164. },
  165. async register(payload: IUserProfileCreate) {
  166. const loadingNotification = {
  167. content: i18n.global.t("signingUp"),
  168. showProgress: true,
  169. };
  170. try {
  171. this.addNotification(loadingNotification);
  172. const response = (
  173. await Promise.all([
  174. api.registerUser(payload),
  175. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
  176. ])
  177. )[0];
  178. this.removeNotification(loadingNotification);
  179. this.addNotification({
  180. content: i18n.global.t("registerSuccess"),
  181. color: "success",
  182. });
  183. setTimeout(() => {
  184. router.push("/login")
  185. }, 2000)
  186. } catch (error) {
  187. await this.checkApiError(error);
  188. }
  189. },
  190. async passwordRecovery(username: string) {
  191. const loadingNotification = {
  192. content: i18n.global.t("sendingEmail"),
  193. showProgress: true,
  194. };
  195. try {
  196. this.addNotification(loadingNotification);
  197. await Promise.all([
  198. api.passwordRecovery(username),
  199. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
  200. ]);
  201. this.removeNotification(loadingNotification);
  202. this.addNotification({
  203. content: i18n.global.t("passwordMailSent"),
  204. color: "success",
  205. });
  206. await this.logOut();
  207. } catch (error) {
  208. this.removeNotification(loadingNotification);
  209. this.addNotification({ color: "error", content: i18n.global.t("incorrectUsername") });
  210. }
  211. },
  212. async resetPassword(password: string, token: string) {
  213. const loadingNotification = { content: "Resetting password", showProgress: true };
  214. try {
  215. this.addNotification(loadingNotification);
  216. await Promise.all([
  217. api.resetPassword(token, password),
  218. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
  219. ]);
  220. this.removeNotification(loadingNotification);
  221. this.addNotification({
  222. content: "Password successfully reset",
  223. color: "success",
  224. });
  225. await this.logOut();
  226. } catch (error) {
  227. this.removeNotification(loadingNotification);
  228. this.addNotification({
  229. color: "error",
  230. content: "Error resetting password",
  231. });
  232. }
  233. },
  234. async uploadPlot(video_data: VideoCreate, file: File) {
  235. const mainStore = useMainStore();
  236. try {
  237. const loadingNotification = { content: i18n.global.t("sending"), showProgress: true };
  238. mainStore.addNotification(loadingNotification);
  239. const response = (
  240. await Promise.all([
  241. api.uploadPlot(mainStore.token, video_data, file),
  242. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 0)),
  243. ])
  244. );
  245. mainStore.removeNotification(loadingNotification);
  246. mainStore.addNotification({
  247. content: i18n.global.t("fileReceived"),
  248. color: "success",
  249. })
  250. this.actionGetVideos();
  251. } catch (error) {
  252. await mainStore.checkApiError(error);
  253. }
  254. },
  255. async uploadImage(file: File[]) {
  256. const mainStore = useMainStore();
  257. try {
  258. const loadingNotification = { content: i18n.global.t("sending"), showProgress: true };
  259. mainStore.addNotification(loadingNotification);
  260. const response = (
  261. await Promise.all([
  262. api.uploadImage(mainStore.token, file),
  263. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 0)),
  264. ]).then(data => {
  265. for (let i = 0; i < data[0].data.filenames.length; i++) {
  266. const element = data[0].data.filenames[i];
  267. const tmpImage: Image = {
  268. file_name: file[i].name,
  269. stored_file_name: element,
  270. content: "sr",
  271. state: "subscribe"
  272. };
  273. this.addImage(tmpImage);
  274. }
  275. // localStorage.setItem('imagesList', JSON.stringify(this.images));
  276. })
  277. );
  278. mainStore.removeNotification(loadingNotification);
  279. mainStore.addNotification({
  280. content: i18n.global.t("fileReceived"),
  281. color: "success",
  282. })
  283. // this.actionGetVideos();
  284. } catch (error) {
  285. await mainStore.checkApiError(error);
  286. }
  287. },
  288. async getImage(data: ImageDownload) {
  289. const mainStore = useMainStore();
  290. try {
  291. const response = (
  292. await Promise.all([
  293. api.getImage(mainStore.token, data),
  294. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 0)),
  295. ])
  296. );
  297. } catch (error) {
  298. await mainStore.checkApiError(error);
  299. }
  300. },
  301. addImage(payload: Image) {
  302. this.images.push(payload);
  303. },
  304. finishImage(payload: string) {
  305. let image = this.images.filter(e => {
  306. return e.stored_file_name === payload
  307. });
  308. if (image) {
  309. image.map(e => {
  310. e.state = "completed";
  311. })
  312. }
  313. // 全部完成後關閉 WebSocket
  314. // let processing = this.images.find(e => e.state !== "completed")
  315. // if (!processing) {
  316. // setTimeout(() => {
  317. // WS.close();
  318. // }, 1000)
  319. // }
  320. return !this.images.some(e => e.state === "completed")
  321. },
  322. async uploadArticle(article_data: ArticleCreate) {
  323. const mainStore = useMainStore();
  324. try {
  325. const loadingNotification = { content: i18n.global.t("sending"), showProgress: true };
  326. mainStore.addNotification(loadingNotification);
  327. const response = (
  328. await Promise.all([
  329. api.uploadArticle(mainStore.token, article_data),
  330. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 0)),
  331. ])
  332. );
  333. mainStore.removeNotification(loadingNotification);
  334. mainStore.addNotification({
  335. content: i18n.global.t("fileReceived"),
  336. color: "success",
  337. })
  338. // this.actionGetVideos();
  339. } catch (error) {
  340. await mainStore.checkApiError(error);
  341. }
  342. },
  343. async actionGetVideos() {
  344. const mainStore = useMainStore();
  345. try {
  346. const response = await api.getVideos(mainStore.token)
  347. if (response) {
  348. this.setVideos(response.data);
  349. }
  350. } catch (error) {
  351. await mainStore.checkApiError(error);
  352. }
  353. },
  354. async googleLogin(username:string, password: string) {
  355. try {
  356. const response = await api.googleLogInGetToken(username, password);
  357. const token: string = response.data.access_token;
  358. if (token) {
  359. saveLocalToken(token);
  360. this.setToken(token);
  361. this.setLoggedIn(true);
  362. this.setLogInError(false);
  363. await this.getUserProfile();
  364. await this.routeLoggedIn();
  365. this.addNotification({ content: i18n.global.t("loggedIn"), color: "success" });
  366. } else {
  367. await this.logOut();
  368. }
  369. } catch (err) {
  370. this.setLogInError(true);
  371. await this.logOut();
  372. }
  373. }
  374. }
  375. });