actionsMedia.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { history } from "../App";
  2. import { gql } from "../helpers/gql";
  3. import { uploadFile } from "../helpers/uploadFile";
  4. import { actionAboutMe } from "./actionAboutMe";
  5. import { actionUpdateChat } from "./actionsForChats";
  6. import { actionGetAllMessage } from "./actionsMessages";
  7. import { actionPromise } from "./actionsPromise";
  8. const actionAddMedia = (typeId, mediaId, type) =>
  9. actionPromise('newMedia', gql(`mutation setMedia($media: MediaInput) {
  10. MediaUpsert(media: $media) {
  11. _id
  12. }
  13. }`, {media: {_id: mediaId, [type]: {_id: typeId}}}))
  14. export const actionUploadFile = (file) =>
  15. actionPromise('file', uploadFile(file))
  16. export const actionUploadFiles = (files) =>
  17. actionPromise('files', Promise.all(files.map(file => uploadFile(file))))
  18. export const actionSetUserAvatar = (file) =>
  19. async (dispatch, getState) => {
  20. let userId = getState().auth.payload.sub.id;
  21. let media = await dispatch(actionUploadFile(file));
  22. console.log(media)
  23. if (media._id){
  24. let dataId = await dispatch(actionAddMedia(userId, media._id, "userAvatar"))
  25. if (dataId){
  26. dispatch(actionAboutMe())
  27. }
  28. }
  29. }
  30. export const actionSetChatAvatar = (file, data) =>
  31. async (dispatch, getState) => {
  32. const [,route, chatId] = history.location.pathname.split('/');
  33. const chat = data ? data : getState().chats[chatId];
  34. console.log(chat)
  35. const media = await dispatch(actionUploadFile(file));
  36. if(media._id){
  37. const dataId = await dispatch(actionAddMedia(chat?._id, media._id, "chatAvatars"))
  38. if (dataId){
  39. //it helps to everyone to get changed chat with avatar from socket (something to change for example title)
  40. dispatch(actionUpdateChat({_id: chat?._id, title: chat?.title}));
  41. }
  42. return dataId
  43. }
  44. }
  45. export const actionAddAllMediaChat = (id, data) => ({type: 'ALLMEDIACHAT', id, data})
  46. export const actionGetAllMediaFromChat = (id) =>
  47. async(dispatch, getState) => {
  48. const messages = await dispatch(actionGetAllMessage(id));
  49. if(messages.length !== 0) {
  50. const media = messages.reduce((a, b) => b.media ? [...a, ...b.media] : a,[] )
  51. dispatch(actionAddAllMediaChat(id, media));
  52. }
  53. }