main.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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, ArticleCreate, Image, ImageDownload } from '@/interfaces';
  8. import i18n from '@/plugins/i18n'
  9. import { wsUrl } from "@/env";
  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. images: [],
  20. };
  21. export const useMainStore = defineStore("MainStoreId", {
  22. state: () => defaultState,
  23. getters: {
  24. readhasAdminAccess: (state) =>
  25. state.userProfile && state.userProfile.is_superuser && state.userProfile.is_active,
  26. readLoginError: (state) => state.logInError,
  27. readDashboardShowDrawer: (state) => state.dashboardShowDrawer,
  28. readDashboardMiniDrawer: (state) => state.dashboardMiniDrawer,
  29. readUserProfile: (state) => state.userProfile,
  30. readToken: (state) => state.token,
  31. readIsLoggedIn: (state) => state.isLoggedIn,
  32. readFirstNotification: (state) => state.notifications.length > 0 && state.notifications[0],
  33. readVideos: (state) => state.videos,
  34. },
  35. actions: {
  36. // setters
  37. setToken(payload: string) { this.token = payload; },
  38. setLoggedIn(payload: boolean) { this.isLoggedIn = payload; },
  39. setLogInError(payload: boolean) { this.logInError = payload; },
  40. setUserProfile(payload: IUserProfile) { this.userProfile = payload },
  41. setDashboardMiniDrawer(payload: boolean) { this.dashboardMiniDrawer = payload; },
  42. setDashboardShowDrawer(payload: boolean) { this.dashboardShowDrawer = payload; },
  43. setVideos(payload: Video[]) { this.videos = payload },
  44. addNotification(payload: AppNotification) { this.notifications.push(payload); },
  45. removeNotification(payload: AppNotification) {
  46. if (payload) {
  47. this.notifications = this.notifications.filter(
  48. (notification) => notification !== payload,
  49. );
  50. }
  51. },
  52. // actions
  53. async logIn(username: string, password: string) {
  54. try {
  55. const response = await api.logInGetToken(username, password);
  56. const token: string = response.data.access_token;
  57. if (token) {
  58. saveLocalToken(token);
  59. this.setToken(token);
  60. this.setLoggedIn(true);
  61. this.setLogInError(false);
  62. await this.getUserProfile();
  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. const WS = new WebSocket(`${wsUrl}/api/v1/images/sr`);
  306. let image = this.images.filter(e => {
  307. return payload.includes(e.stored_file_name)
  308. });
  309. if (image) {
  310. image.map(e => {
  311. e.state = "completed";
  312. })
  313. }
  314. // 全部完成後回傳 WebSocket
  315. let processing = this.images.find(e => e.state !== "completed");
  316. console.log('processing', processing);
  317. if (!processing) {
  318. setTimeout(() => {
  319. // WS.close();
  320. WS.send("unsubscribe");
  321. }, 1000)
  322. }
  323. return !this.images.some(e => e.state === "completed")
  324. },
  325. async uploadArticle(article_data: ArticleCreate) {
  326. const mainStore = useMainStore();
  327. try {
  328. const loadingNotification = { content: i18n.global.t("sending"), showProgress: true };
  329. mainStore.addNotification(loadingNotification);
  330. const response = (
  331. await Promise.all([
  332. api.uploadArticle(mainStore.token, article_data),
  333. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 0)),
  334. ])
  335. );
  336. mainStore.removeNotification(loadingNotification);
  337. mainStore.addNotification({
  338. content: i18n.global.t("fileReceived"),
  339. color: "success",
  340. })
  341. // this.actionGetVideos();
  342. } catch (error) {
  343. await mainStore.checkApiError(error);
  344. }
  345. },
  346. async actionGetVideos() {
  347. const mainStore = useMainStore();
  348. try {
  349. const response = await api.getVideos(mainStore.token)
  350. if (response) {
  351. this.setVideos(response.data);
  352. }
  353. } catch (error) {
  354. await mainStore.checkApiError(error);
  355. }
  356. },
  357. async googleLogin(username: string) {
  358. try {
  359. const response = await api.googleLogin(username);
  360. const token: string = response.data.access_token;
  361. if (token) {
  362. saveLocalToken(token);
  363. this.setToken(token);
  364. this.setLoggedIn(true);
  365. this.setLogInError(false);
  366. await this.getUserProfile();
  367. await this.routeLoggedIn();
  368. this.addNotification({ content: i18n.global.t("loggedIn"), color: "success" });
  369. } else {
  370. await this.logOut();
  371. }
  372. } catch (err) {
  373. this.setLogInError(true);
  374. await this.logOut();
  375. }
  376. }
  377. }
  378. });