main.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 { GoogleLogin } from "vue3-google-login";
  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. console.log(this.userProfile);
  64. await this.routeLoggedIn();
  65. this.addNotification({ content: i18n.global.t("loggedIn"), color: "success" });
  66. } else {
  67. await this.logOut();
  68. }
  69. } catch (err) {
  70. this.setLogInError(true);
  71. await this.logOut();
  72. }
  73. },
  74. async getUserProfile() {
  75. try {
  76. const response = await api.getMe(this.token);
  77. if (response.data) {
  78. this.setUserProfile(response.data)
  79. }
  80. } catch (error) {
  81. await this.checkApiError(error);
  82. }
  83. },
  84. async updateUserProfile(payload: IUserProfileUpdate) {
  85. try {
  86. const loadingNotification = { content: i18n.global.t("saving"), showProgress: true };
  87. await this.addNotification(loadingNotification);
  88. const response = (
  89. await Promise.all([
  90. api.updateMe(this.token, payload),
  91. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
  92. ])
  93. )[0];
  94. this.setUserProfile(response.data);
  95. this.removeNotification(loadingNotification);
  96. this.addNotification({
  97. content: i18n.global.t("profileUpdated"),
  98. color: "success",
  99. });
  100. } catch (error) {
  101. await this.checkApiError(error);
  102. }
  103. },
  104. async checkLoggedIn() {
  105. if (!this.isLoggedIn) {
  106. let token = this.token;
  107. if (!token) {
  108. const localToken = getLocalToken();
  109. if (localToken) {
  110. this.setToken(localToken);
  111. token = localToken;
  112. }
  113. }
  114. if (token) {
  115. try {
  116. const response = await api.getMe(token);
  117. this.setLoggedIn(true);
  118. this.setUserProfile(response.data);
  119. router.push("/main/dashboard");
  120. } catch (error) {
  121. await this.removeLogIn();
  122. }
  123. } else {
  124. await this.removeLogIn();
  125. }
  126. }
  127. },
  128. async removeLogIn() {
  129. removeLocalToken();
  130. this.setToken("");
  131. this.setLoggedIn(false);
  132. },
  133. async logOut() {
  134. await this.removeLogIn();
  135. this.routeLogOut();
  136. },
  137. async userLogOut() {
  138. await this.logOut();
  139. this.addNotification({ content: "Logged out", color: "success" });
  140. },
  141. routeLogOut() {
  142. if (router.currentRoute.value.path !== "/login") {
  143. router.push("/login");
  144. }
  145. },
  146. async checkApiError(payload: unknown) {
  147. if (axios.isAxiosError(payload)) {
  148. if (payload.response?.status === 401) {
  149. await this.logOut();
  150. }
  151. }
  152. },
  153. routeLoggedIn() {
  154. if (router.currentRoute.value.path === "/login" || router.currentRoute.value.path === "/") {
  155. router.push("/main/dashboard");
  156. }
  157. },
  158. async dispatchRemoveNotification(payload: { notification: AppNotification; timeout: number },) {
  159. return new Promise((resolve, _) => {
  160. setTimeout(() => {
  161. this.removeNotification(payload.notification);
  162. resolve(true);
  163. }, payload.timeout);
  164. });
  165. },
  166. async register(payload: IUserProfileCreate) {
  167. const loadingNotification = {
  168. content: i18n.global.t("signingUp"),
  169. showProgress: true,
  170. };
  171. try {
  172. this.addNotification(loadingNotification);
  173. const response = (
  174. await Promise.all([
  175. api.registerUser(payload),
  176. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
  177. ])
  178. )[0];
  179. this.removeNotification(loadingNotification);
  180. this.addNotification({
  181. content: i18n.global.t("registerSuccess"),
  182. color: "success",
  183. });
  184. setTimeout(() => {
  185. router.push("/login")
  186. }, 2000)
  187. } catch (error) {
  188. await this.checkApiError(error);
  189. }
  190. },
  191. async passwordRecovery(username: string) {
  192. const loadingNotification = {
  193. content: i18n.global.t("sendingEmail"),
  194. showProgress: true,
  195. };
  196. try {
  197. this.addNotification(loadingNotification);
  198. await Promise.all([
  199. api.passwordRecovery(username),
  200. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
  201. ]);
  202. this.removeNotification(loadingNotification);
  203. this.addNotification({
  204. content: i18n.global.t("passwordMailSent"),
  205. color: "success",
  206. });
  207. await this.logOut();
  208. } catch (error) {
  209. this.removeNotification(loadingNotification);
  210. this.addNotification({ color: "error", content: i18n.global.t("incorrectUsername") });
  211. }
  212. },
  213. async resetPassword(password: string, token: string) {
  214. const loadingNotification = { content: "Resetting password", showProgress: true };
  215. try {
  216. this.addNotification(loadingNotification);
  217. await Promise.all([
  218. api.resetPassword(token, password),
  219. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 500)),
  220. ]);
  221. this.removeNotification(loadingNotification);
  222. this.addNotification({
  223. content: "Password successfully reset",
  224. color: "success",
  225. });
  226. await this.logOut();
  227. } catch (error) {
  228. this.removeNotification(loadingNotification);
  229. this.addNotification({
  230. color: "error",
  231. content: "Error resetting password",
  232. });
  233. }
  234. },
  235. async uploadPlot(video_data: VideoCreate, file: File) {
  236. const mainStore = useMainStore();
  237. try {
  238. const loadingNotification = { content: i18n.global.t("sending"), showProgress: true };
  239. mainStore.addNotification(loadingNotification);
  240. const response = (
  241. await Promise.all([
  242. api.uploadPlot(mainStore.token, video_data, file),
  243. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 0)),
  244. ])
  245. );
  246. mainStore.removeNotification(loadingNotification);
  247. mainStore.addNotification({
  248. content: i18n.global.t("fileReceived"),
  249. color: "success",
  250. })
  251. this.actionGetVideos();
  252. } catch (error) {
  253. await mainStore.checkApiError(error);
  254. }
  255. },
  256. async uploadImage(file: File[]) {
  257. const mainStore = useMainStore();
  258. try {
  259. const loadingNotification = { content: i18n.global.t("sending"), showProgress: true };
  260. mainStore.addNotification(loadingNotification);
  261. const response = (
  262. await Promise.all([
  263. api.uploadImage(mainStore.token, file),
  264. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 0)),
  265. ]).then(data => {
  266. for (let i = 0; i < data[0].data.filenames.length; i++) {
  267. const element = data[0].data.filenames[i];
  268. const tmpImage: Image = {
  269. file_name: file[i].name,
  270. stored_file_name: element,
  271. content: "sr"
  272. };
  273. this.addImage(tmpImage);
  274. }
  275. localStorage.setItem('imagesList',JSON.stringify(this.images));
  276. console.log('this.images',this.images);
  277. })
  278. );
  279. mainStore.removeNotification(loadingNotification);
  280. mainStore.addNotification({
  281. content: i18n.global.t("fileReceived"),
  282. color: "success",
  283. })
  284. // this.actionGetVideos();
  285. } catch (error) {
  286. await mainStore.checkApiError(error);
  287. }
  288. },
  289. async getImage(data: ImageDownload) {
  290. console.log('getImage data', data);
  291. const mainStore = useMainStore();
  292. try {
  293. const response = (
  294. await Promise.all([
  295. api.getImage(mainStore.token, data),
  296. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 0)),
  297. ])
  298. );
  299. } catch (error) {
  300. await mainStore.checkApiError(error);
  301. }
  302. },
  303. addImage(payload: Image) {
  304. this.images.push(payload);
  305. },
  306. async uploadArticle(article_data: ArticleCreate) {
  307. const mainStore = useMainStore();
  308. try {
  309. const loadingNotification = { content: i18n.global.t("sending"), showProgress: true };
  310. mainStore.addNotification(loadingNotification);
  311. const response = (
  312. await Promise.all([
  313. api.uploadArticle(mainStore.token, article_data),
  314. await new Promise<void>((resolve, _) => setTimeout(() => resolve(), 0)),
  315. ])
  316. );
  317. mainStore.removeNotification(loadingNotification);
  318. mainStore.addNotification({
  319. content: i18n.global.t("fileReceived"),
  320. color: "success",
  321. })
  322. // this.actionGetVideos();
  323. } catch (error) {
  324. await mainStore.checkApiError(error);
  325. }
  326. },
  327. async actionGetVideos() {
  328. const mainStore = useMainStore();
  329. try {
  330. const response = await api.getVideos(mainStore.token)
  331. if (response) {
  332. this.setVideos(response.data);
  333. }
  334. } catch (error) {
  335. await mainStore.checkApiError(error);
  336. }
  337. },
  338. async googleLogin(username:string, password: string) {
  339. try {
  340. const response = await api.googleLogInGetToken(username, password);
  341. const token: string = response.data.access_token;
  342. if (token) {
  343. saveLocalToken(token);
  344. this.setToken(token);
  345. this.setLoggedIn(true);
  346. this.setLogInError(false);
  347. await this.getUserProfile();
  348. await this.routeLoggedIn();
  349. this.addNotification({ content: i18n.global.t("loggedIn"), color: "success" });
  350. } else {
  351. await this.logOut();
  352. }
  353. } catch (err) {
  354. this.setLogInError(true);
  355. await this.logOut();
  356. }
  357. }
  358. }
  359. });