@qonsoll/chat-core
Version:
Library with core logic for chat
2 lines (1 loc) • 14.3 kB
JavaScript
import{useState as e,useCallback as t,useEffect as n,useRef as a,useMemo as o,useReducer as i}from"react";import{w as s,k as r,l as c,e as l,u,r as d,s as f,g as v,b as p,f as h}from"./Provider.js";import{u as g,c as m,d as I,f as T,s as y,a as E,e as _,g as A}from"./createChat.js";import S from"firebase";import{P as M,b as D,c as x,_ as U,a as C}from"./Proxy.js";import{e as O,C as L,M as P,b as N,d as w,c as R,a as H}from"./constants.js";import V from"lodash";import{removeVideo as b}from"@qonsoll/qvideo";import{DEFAULT_FOLDER_ID as F}from"../../constants/dist/index.esm.js";var q=function(){return M.user||{}},G=function(e){var t=e.collection,n=e.id,a=e.ref;return D(void 0,void 0,void 0,(function(){return x(this,(function(e){switch(e.label){case 0:return[4,(a||S.firestore()).collection(t).doc(n).delete()];case 1:return e.sent(),[2]}}))}))},W=function(a){var o=a.messageText,i=s(),r=i.collectionName,c=i.chatId,l=i.isChatExist,u=q(),d=e(!1),f=d[0],v=d[1],p=t((function(e){l&&(g({isTyping:e,user:u,collectionName:r,chatId:c}),v(e))}),[u,c,l]);return n((function(){var e;return l&&(o?1===o.length&&(p(!0),v(!0),e=setTimeout((function(){p(!1),v(!1)}),3e4)):(p(!1),v(!1)),o.length>0&&document.getElementById("messageInput")===document.activeElement&&!f&&(v(!0),p(!0),e=setTimeout((function(){p(!1),v(!1)}),3e4))),function(){clearTimeout(e)}}),[o]),n((function(){var e;return f&&(e=setTimeout((function(){p(!1),v(!1)}),3e4)),function(){return e&&clearTimeout(e)}}),[f]),p},j={on_delete:{field:"isMassageDeleting",type:O.MESSAGE_DELETED}},B=function(e,a){var o,i,s=null===(o=r())||void 0===o?void 0:o[null===(i=null==j?void 0:j[e])||void 0===i?void 0:i.field],l=c();return n((function(){s&&(null==a||a(s))}),[s]),t((function(){var t;return l({type:null===(t=null==j?void 0:j[e])||void 0===t?void 0:t.type,payload:!1})}),[e,l])},k=function(){var e=q()._id,n=l().messages,o=s(),i=a(null);return t((function(t){var a={start:t.visibleStartIndex,end:t.visibleStopIndex};JSON.stringify(a)!==JSON.stringify(i.current)&&(null==n||n.slice(a.start,a.end+1).forEach((function(t){m({userId:e,message:t,chatData:o})})),i.current=a)}),[o,n,e])},J=function(e){var n=e.messageText,a=e.attachedFiles,o=s(),i=o.chatId,r=o.oppositeUserId,c=o.collectionName,l=o.oppositeUserData,u=o.isChatExist,d=q();return t((function(e,t){var o={chatId:i,collectionName:c||L.CHATS,messageType:P.TEXT,messageText:t?"":n,userId:null==d?void 0:d._id,oppositeUserId:r||(null==l?void 0:l._id),scheduleDate:e};(null==a?void 0:a.length)&&(o.attachedFiles=a),t&&(o.qVideoId=t,o.messageType=P.LIVE_VIDEO);var s=function(e){try{T({oppositeUserData:l,user:d,data:e,create:y})}catch(e){console.error("error in sendMessageWithAttachments",e)}};if(u)s(o);else try{I({oppositeUserData:l,user:d,messageText:o.messageText,messageType:o.messageType,attachedFiles:o.attachedFiles,collectionName:c,qVideoId:o.qVideoId},(function(e){var t=e.chatId;return s(U(U({},o),{chatId:t}))}))}catch(e){console.error("error in chat create",e)}}),[a,n])},K=function(e){var t=e.isChatOpen;n((function(){E({isOnline:t})}),[t])},Q=function(e){var n=e||{},a=n.messageText,o=n.setMessageText,i=s(),r=i.oppositeUserData,c=i.collectionName,l=i.groupMembersIds,d=i.chatId,f=i.isChatExist,v=u().oppositeUserData,p=q();return t((function(e){var t=e.attachedFiles,n=e.messageType,i=e.qVideoId;if(a.trim()||(null==t?void 0:t.length)||i){!i&&o("");var s={oppositeUserData:r||v,user:p,qVideoId:i,messageType:n,messageText:a,attachedFiles:t,chatId:d,groupMembersIds:l,collectionName:c};if(f)try{_(s)}catch(e){console.error("error in message send",e)}else I(s).then((function(){console.log("chat created successfully")})).catch((function(e){console.error("error in chat create",e)}))}}),[v,d,c,l,f,a,r,o,p])},X=L.MESSAGES,Y=L.MESSAGES_VIEWS,z=function(e){var n=(e||{}).message,a=s(),o=a.collectionName,i=a.lastMessageId,r=a.chatId,u=l().messages,f=d().selectedMessage,v=c(),p=((null==f?void 0:f._id)||(null==n?void 0:n._id))===i;return t((function(){return D(void 0,void 0,void 0,(function(){var e,t,a,i,s,c,l,d,f,h,g,m,I;return x(this,(function(T){v({type:O.MESSAGE_DELETED,payload:n}),e=n._id,t=n.status,a=n.attachedFiles;try{(null==a?void 0:a.length)&&a.forEach((function(e){var t=e.url;return!e.qVideoId&&S.storage().refFromURL(t).delete()})),(null==n?void 0:n.messageType)===P.LIVE_VIDEO&&b(null==n?void 0:n.qVideoId,process.env.REACT_APP_QVIDEO_API_KEY)}catch(e){console.error("ERROR on delete attach in message from chat.\nmessage id:".concat(null==n?void 0:n._id,", message index: ").concat(null==u?void 0:u.findIndex((function(e){var t=e._id;return(null==n?void 0:n._id)===t}))))}return i=t!==N.SEEN,s=null==u?void 0:u[u.length-2],l=(c=s||{})._id,d=c.text,f=c._createdAt,h=c._createdBy,g=c.messageType,(p||i)&&(m=p?{lastMessageId:l||null,lastMessageText:d||null,lastMessageDateAndTime:f||null,lastMessageSenderId:h||null,lastMessageType:g||null}:{},(null===(I=Object.keys(m))||void 0===I?void 0:I.length)&&A({collection:o,id:r,data:m})),r&&e&&(G({collection:"".concat(o,"/").concat(r,"/").concat(Y),id:e}),G({collection:"".concat(o,"/").concat(r,"/").concat(X),id:e})),[2]}))}))}),[r,o,p,n,v,u])},Z=L.MESSAGES,$=function(e){var n=e||{},a=n.messageText,o=n.message,i=s(),r=i.collectionName,c=i.lastMessageId,l=i.chatId,u=q(),d=f(),v=d[0],p=v.selectedMessage,h=v.onPressEditMessage,g=d[1],m=((null==p?void 0:p._id)||(null==o?void 0:o._id))===c;return t((function(){m&&(null==p?void 0:p.text)!==a&&A({collection:r,id:l,data:{lastMessageText:a||""}}),l&&(null==p?void 0:p._id)&&(null==p?void 0:p.text)!==a&&A({collection:"".concat(r,"/").concat(l,"/").concat(Z),id:null==p?void 0:p._id,data:{_isUpdated:!0,text:a||"",_updatedBy:null==u?void 0:u._id}}),g((function(e){return U(U({},e),{selectedMessage:{},isEditingMessage:!1})})),null==h||h("")}),[l,r,m,a,h,null==p?void 0:p._id,null==p?void 0:p.text,g,null==u?void 0:u._id])},ee=function(e){var t=e||{},n=t.messageText,a=t.setMessageText,o=t.message;return{onMessageReply:function(){},onMessageCopy:function(){},onMessageEdit:$({message:o,messageText:n}),onMessagePin:function(){},onMessageForward:function(){},onMessageDelete:z({message:o}),onMessageSend:Q({messageText:n,setMessageText:a})}},te=L.MESSAGES,ne=function(){var e=s(),o=e.chatId,i=e.collectionName,r=v(),c=r[0],l=c.messages,u=c.isInitLoading,d=c.isEndOfList,f=c.onUploadMessages,p=r[1],h=a(null),g=t((function(e){var t=e.docChanges()[0];"removed"===(null==t?void 0:t.type)&&1===e.docChanges().length&&(h.current=t.doc.data()._id);var n=e.docs.map((function(e){var t=e.data();return!t._createdAt&&e.metadata.hasPendingWrites?U(U({},t),{_createdAt:S.firestore.Timestamp.now()}):t}));p({type:w.SET_MESSAGES,payload:{newFetchedMessages:n,deletedMessageId:h.current}})}),[l,p]);return n((function(){var e=S.firestore().collection("".concat(i,"/").concat(o,"/").concat(te)).orderBy("_createdAt","desc").limit((null==l?void 0:l.length)||35).onSnapshot({includeMetadataChanges:!0},{next:g,error:function(e){console.warn("ERROR in useChatMessages listener(probably chat haven't created yet)\n----------\n".concat(e,"\n----------")),!o&&p({type:w.SET_INIT_LOADING,payload:!1})}});return function(){null==e||e()}}),[null==l?void 0:l.length,o]),n((function(){return function(){return p({type:w.CLEAR_MESSAGES})}}),[o]),{onUploadMessages:f,messages:l,isInitLoading:u,isEndOfList:d}},ae=L.CHATS,oe=L.MEMBERS,ie=L.MESSAGES_VIEWS,se=L.PERMISSIONS,re=L.CHAT_USERS,ce=function(a){var i=q()._id,s=p(),r=s[0],c=r.chats,l=r.oppositeUserData,u=s[1],d=h(),f=e([]),v=f[0],g=f[1],m=e([]),I=m[0],T=m[1],y=e(!1),E=y[0],_=y[1],A=t((function(e){var t=e.chatId,n=e.oppositeUserId,a=e.displayName,o=e.chatPhotoUrl;return S.firestore().collection(ae).doc(t).onSnapshot((function(e){if(!e.exists)return u({type:R.DELETE_CHAT,payload:{chatId:t}}),d({type:w.CLEAR_MESSAGES}),void g((function(e){return V.uniqBy(C(C([],e,!0),[{chatId:t,withListeners:!0}],!1),"chatId")}));var i=e.data(),s=i.lastMessageDateAndTime,r=void 0===s?null:s,c=i.lastMessageSenderId,l=void 0===c?null:c,f=i.lastMessageText,v=void 0===f?null:f,p=i.lastMessageId,h=void 0===p?null:p,m=i.lastMessageType,I=void 0===m?null:m;u({type:R.UPDATE_CHAT_DATA,payload:{chatId:t,chatData:{chatId:t,typeOfChat:H.CHAT,collectionName:ae,isChatExist:!0,oppositeUserId:n,displayName:a,chatPhotoUrl:o,lastMessageDateAndTime:r,lastMessageSenderId:l,lastMessageText:v,lastMessageId:h,lastMessageType:I}}}),g((function(e){return V.uniqBy(C(C([],e,!0),[{chatId:t,oppositeUserId:n,withListeners:!1}],!1),"chatId")}))}))}),[]);return n((function(){v.filter((function(e){return!e.withListeners})).forEach((function(e){var t=e.chatId,n=e.oppositeUserId,a=c.findIndex((function(e){var n=e.chatId;return t===n}));if(-1!==a){var o=S.firestore().collection("".concat(ae,"/").concat(t,"/").concat(oe)).doc(i).onSnapshot((function(e){if(e.exists){var n=(null==e?void 0:e.data()).lastMessageStatus,a=void 0===n?null:n;u({type:R.UPDATE_CHAT_DATA,payload:{chatData:{lastMessageStatus:a},chatId:t}})}})),s=S.firestore().collection("".concat(ae,"/").concat(t,"/").concat(ie)).where("views.".concat(i),"==",!1).onSnapshot((function(e){var n=e.docs.map((function(e){return e.data()}));u({type:R.UPDATE_CHAT_DATA,payload:{chatData:{unreadMessagesAmount:null==n?void 0:n.length},chatId:t}})})),r=S.firestore().collection(re).doc(n).onSnapshot((function(e){if(e.exists){var n=e.data();u({type:R.UPDATE_CHAT_DATA,payload:{chatData:{oppositeUserData:n},chatId:t}})}})),l=S.firestore().collection("".concat(ae,"/").concat(t,"/").concat(oe)).doc(n).onSnapshot((function(e){if(e.exists){var n=e.data(),a=n.isOnline,o=void 0===a?null:a,i=n.isTyping,s=void 0===i?null:i,r=n.lastActiveTime,c=void 0===r?null:r;u({type:R.UPDATE_CHAT_DATA,payload:{chatData:{isOppositeUserOnline:o,isOppositeUserTyping:s,lastActiveTime:c},chatId:t}})}})),d=S.firestore().collection("".concat(ae,"/").concat(t,"/").concat(se)).doc(n).onSnapshot((function(e){if(e.exists){var n=e.data().allowWrite;u({type:R.UPDATE_CHAT_DATA,payload:{chatData:{oppositeUserPermissions:{allowWrite:n}},chatId:t}})}})),f=S.firestore().collection("".concat(ae,"/").concat(t,"/").concat(se)).doc(i).onSnapshot((function(e){if(e.exists){var n=e.data().allowWrite;u({type:R.UPDATE_CHAT_DATA,payload:{chatData:{myPermissions:{allowWrite:n}},chatId:t}})}}));T((function(e){return C(C([],e,!0),[o,s,d,r,l,f],!1)}));var p=v.map((function(e){return e.chatId===t?U(U({},e),{withListeners:!0}):e}));g(p)}}));var e=v.filter((function(e){return e.withListeners})).length===a;e&&_(!0)}),[c,v,a,i]),n((function(){return function(){(null==I?void 0:I.length)&&a===v.length&&E&&(I.forEach((function(e){return null==e?void 0:e()})),T([]))}}),[v.length,a,I,E]),n((function(){var e=null==c?void 0:c.filter((function(e){return e.oppositeUserId===(null==l?void 0:l._id)}));_(!1),g((function(t){return V.intersectionWith(t,e,(function(e,t){return e.chatId===t.chatId})).map((function(e){return U(U({},e),{withListeners:!1})}))}))}),[l]),o((function(){var e=[A,E];return e.fetchMainChatInfo=A,e.isAllListenersWorking=E,e}),[A,E])},le=function(){return le=Object.assign||function(e){for(var t,n=1,a=arguments.length;n<a;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},le.apply(this,arguments)},ue=function(e){return{loading:null==e,value:e}},de=function(e){var t=e?e():void 0,n=i((function(e,t){switch(t.type){case"error":return le({},e,{error:t.error,loading:!1,value:void 0});case"reset":return ue(t.defaultValue);case"value":return le({},e,{error:void 0,loading:!1,value:t.value});default:return e}}),ue(t)),a=n[0],s=n[1],r=function(){var t=e?e():void 0;s({type:"reset",defaultValue:t})},c=function(e){s({type:"error",error:e})},l=function(e){s({type:"value",value:e})};return o((function(){return{error:a.error,loading:a.loading,reset:r,setError:c,setValue:l,value:a.value}}),[a.error,a.loading,r,c,l,a.value])},fe=function(e,t){var n=!e&&!t,a=!!e&&!!t&&e.isEqual(t);return n||a},ve=function(e,t){return function(e,t,o){var i=a(e);return n((function(){t(e,i.current)||(i.current=e,o&&o())})),i}(e,fe,t)},pe=function(e,t,a){var i=a?a.idField:void 0,s=a?a.refField:void 0,r=a?a.snapshotOptions:void 0,c=a?a.transform:void 0,l=function(e,t,a){var i=de(),s=i.error,r=i.loading,c=i.reset,l=i.setError,u=i.setValue,d=i.value,f=ve(t,c);n((function(){if(f.current){if(e){var t=a&&a.snapshotListenOptions?f.current.onSnapshot(a.snapshotListenOptions,u,l):f.current.onSnapshot(u,l);return function(){t()}}f.current.get(a?a.getOptions:void 0).then(u).catch(l)}else u(void 0)}),[f.current]);var v=[d,r,s];return o((function(){return v}),v)}(e,t,a),u=l[0],d=l[1],f=l[2],v=o((function(){return u?u.docs.map((function(e){return function(e,t,n,a,o){if(e.exists){var i=e.data(t);return o&&(i=o(i)),n&&(i[n]=e.id),a&&(i[a]=e.ref),i}}(e,r,i,s,c)})):void 0}),[u,r,i,s,c]),p=[v,d,f];return o((function(){return p}),p)},he=L.CHAT_USERS,ge=L.FOLDERS,me=L.CHATS,Ie=function(){var t,a=q()._id,i=p(),s=i[0],r=i[1],c=s.oppositeUserDataLoading,l=s.oppositeUserData,u=e(!0),d=u[0],f=u[1],v=function(e,t){return pe(!0,e,t)}(o((function(){var e=S.firestore().collection("".concat(he,"/").concat(a,"/").concat(ge,"/").concat(F,"/").concat(me));return(null==l?void 0:l._id)&&!c?e.where("oppositeUserId","==",null==l?void 0:l._id):c?null:e.orderBy("_createdAt","desc")}),[c,l,a])),h=v[0],g=v[1],m=ce(null===(t=null==h?void 0:h.filter((function(e){return e.type===H.CHAT})))||void 0===t?void 0:t.length),I=m[0],T=m[1];return n((function(){var e=[];return(null==h?void 0:h.length)&&!g?(D(void 0,void 0,void 0,(function(){return x(this,(function(t){return null==h||h.map((function(t){var n=t._id,a=t.type,o=t.displayName,i=t.chatPhotoUrl,s=t.oppositeUserId;return D(void 0,void 0,void 0,(function(){var t;return x(this,(function(r){return a===H.CHAT&&(t=I({chatId:n,oppositeUserId:s,displayName:o,chatPhotoUrl:i}),e.push(t)),[2]}))}))})),[2]}))})),1===(null==h?void 0:h.length)&&r({type:R.SET_CURRENT_CHAT_ID,payload:{chatId:h[0]._id}})):(null==h?void 0:h.length)||g||f(!1),function(){e.forEach((function(e){return null==e?void 0:e()}))}}),[h,g]),n((function(){T&&f(!1)}),[T]),n((function(){return l&&r({type:R.CLEAR_CHATS,payload:{oppositeUserId:null==l?void 0:l._id}})}),[l]),o((function(){var e=[s,d];return e.chats=s,e.loading=d,e}),[s,d])};export{B as a,k as b,J as c,K as d,ee as e,ne as f,ce as g,Ie as h,q as i,W as u};