├── .eslintignore ├── .gitattributes ├── src ├── assets │ ├── nophoto.png │ ├── icon-send.png │ ├── icon-liked.png │ ├── icon-smile.png │ ├── icon-add-audio.png │ ├── icon-add-files.png │ ├── icon-add-image.png │ ├── icon-file-pdf.png │ ├── icon-not-liked.png │ ├── nophoto-group.png │ ├── icon-camera-grey.png │ ├── icon-close-blue.png │ ├── icon-player-pause.png │ ├── icon-player-play.png │ ├── icon-document-grey.png │ └── icon-message-actions.png ├── consts │ ├── index.js │ ├── MsgTypes.js │ ├── EventTypes.js │ └── ChatPossibleTypes.js ├── api │ ├── endpoints │ │ ├── pusher.js │ │ ├── profile.js │ │ ├── media.js │ │ ├── auth.js │ │ └── room.js │ ├── codes.js │ ├── axios.js │ ├── index.js │ └── handling.js ├── index.js ├── lib │ ├── colors.js │ ├── isIphoneX.js │ ├── poly.js │ ├── utils.js │ └── fileUtils.js ├── models │ ├── ContentImage.js │ ├── ContentAudio.js │ ├── ContentText.js │ ├── Content.js │ ├── Member.js │ ├── ContentFile.js │ ├── Event.js │ └── Room.js ├── trans │ ├── en.js │ ├── de.js │ └── index.js ├── components │ ├── EventAvatar.js │ ├── ContentFile.js │ ├── ContentText.js │ ├── ContentImage.js │ ├── LeftX.js │ ├── InViewPort.js │ ├── VoiceRecord.js │ ├── ContentAudio.js │ ├── EventsContainer.js │ ├── Event.js │ └── InputToolbar.js ├── MatrixCreateGroupChat.js ├── MatrixChats.js ├── MatrixEditGroupChat.js ├── Matrix.js └── MatrixChat.js ├── README.md ├── .gitignore ├── LICENSE ├── postinstall.js ├── .eslintrc ├── package.json └── CONTRIBUTING.md /.eslintignore: -------------------------------------------------------------------------------- 1 | src/lib/poly.js 2 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | # specific for windows script files 3 | *.bat text eol=crlf -------------------------------------------------------------------------------- /src/assets/nophoto.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/nophoto.png -------------------------------------------------------------------------------- /src/assets/icon-send.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-send.png -------------------------------------------------------------------------------- /src/assets/icon-liked.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-liked.png -------------------------------------------------------------------------------- /src/assets/icon-smile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-smile.png -------------------------------------------------------------------------------- /src/assets/icon-add-audio.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-add-audio.png -------------------------------------------------------------------------------- /src/assets/icon-add-files.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-add-files.png -------------------------------------------------------------------------------- /src/assets/icon-add-image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-add-image.png -------------------------------------------------------------------------------- /src/assets/icon-file-pdf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-file-pdf.png -------------------------------------------------------------------------------- /src/assets/icon-not-liked.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-not-liked.png -------------------------------------------------------------------------------- /src/assets/nophoto-group.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/nophoto-group.png -------------------------------------------------------------------------------- /src/assets/icon-camera-grey.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-camera-grey.png -------------------------------------------------------------------------------- /src/assets/icon-close-blue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-close-blue.png -------------------------------------------------------------------------------- /src/assets/icon-player-pause.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-player-pause.png -------------------------------------------------------------------------------- /src/assets/icon-player-play.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-player-play.png -------------------------------------------------------------------------------- /src/assets/icon-document-grey.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-document-grey.png -------------------------------------------------------------------------------- /src/assets/icon-message-actions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/maxweb4u/react-native-matrix/HEAD/src/assets/icon-message-actions.png -------------------------------------------------------------------------------- /src/consts/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is common consts 5 | */ 6 | 7 | export default { customHTML: 'org.matrix.custom.html' }; 8 | -------------------------------------------------------------------------------- /src/api/endpoints/pusher.js: -------------------------------------------------------------------------------- 1 | import handling from '../handling'; 2 | 3 | const PusherApi = { 4 | setPusher: async (params) => { 5 | const res = await handling.request('post', '/pushers/set', params); 6 | return res; 7 | }, 8 | }; 9 | 10 | export default PusherApi; 11 | -------------------------------------------------------------------------------- /src/api/endpoints/profile.js: -------------------------------------------------------------------------------- 1 | import handling from '../handling'; 2 | 3 | const ProfileApi = { 4 | updateDisplayName: async (userId, displayname) => { 5 | const res = await handling.request('put', `/profile/${userId}/displayname`, { displayname }); 6 | return res; 7 | }, 8 | }; 9 | 10 | export default ProfileApi; 11 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import Matrix from './Matrix'; 2 | import MatrixChat from './MatrixChat'; 3 | import MatrixChats from './MatrixChats'; 4 | import MatrixCreateGroupChat from './MatrixCreateGroupChat'; 5 | import MatrixEditGroupChat from './MatrixEditGroupChat'; 6 | 7 | export { Matrix, MatrixChat, MatrixChats, MatrixCreateGroupChat, MatrixEditGroupChat }; 8 | -------------------------------------------------------------------------------- /src/consts/MsgTypes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is types for event 5 | */ 6 | 7 | export default { 8 | mText: 'm.text', 9 | mImage: 'm.image', 10 | mFile: 'm.file', 11 | mAudio: 'm.audio', 12 | mLocation: 'm.location', 13 | mVideo: 'm.video', 14 | mNotice: 'm.notice', 15 | mEmote: 'm.emote', 16 | mGeneral: 'm.general', 17 | }; 18 | -------------------------------------------------------------------------------- /src/api/codes.js: -------------------------------------------------------------------------------- 1 | const codes = { 2 | statusOK: '200', 3 | statusNoContent: '204', 4 | statusInternalError: '1000', 5 | // statusNotAuthorize: '401', 6 | // statusForbidden: '403', 7 | // statusNotFound: '404', 8 | // statusNoInternet: '490', 9 | // statusServiceUnavailable: '503', 10 | errorCodeNONE: 'NONE', 11 | errorCodeUNKNOWN: 'UNKNOWN', 12 | }; 13 | 14 | export default codes; 15 | -------------------------------------------------------------------------------- /src/api/axios.js: -------------------------------------------------------------------------------- 1 | import axios from 'axios'; 2 | 3 | const instance = axios.create(); 4 | 5 | /* eslint-disable */ 6 | instance.interceptors.response.use((response) => { 7 | // console.log("response ::: ", response) 8 | return response; 9 | }, function (error) { 10 | // console.log("error ::: ", error) 11 | return Promise.reject(error.response); 12 | }); 13 | /* eslint-enable */ 14 | 15 | export default instance; 16 | -------------------------------------------------------------------------------- /src/consts/EventTypes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is types for event 5 | */ 6 | 7 | export default { 8 | mRoomPinnedEvents: 'm.room.pinned_events', 9 | mRoomAvatar: 'm.room.avatar', 10 | mRoomTopic: 'm.room.topic', 11 | mRoomName: 'm.room.name', 12 | mRoomMessageFeedback: 'm.room.message.feedback', 13 | mRoomMessage: 'm.room.message', 14 | mRoomReaction: 'm.reaction', 15 | }; 16 | -------------------------------------------------------------------------------- /src/consts/ChatPossibleTypes.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is types for event 5 | */ 6 | 7 | import EventTypes from './EventTypes'; 8 | import MsgTypes from './MsgTypes'; 9 | 10 | const PossibleChatEventsTypes = [EventTypes.mRoomMessage]; 11 | const PossibleChatContentTypes = [MsgTypes.mText, MsgTypes.mAudio, MsgTypes.mFile, MsgTypes.mImage]; 12 | 13 | export { PossibleChatEventsTypes, PossibleChatContentTypes }; 14 | -------------------------------------------------------------------------------- /src/api/index.js: -------------------------------------------------------------------------------- 1 | import auth from './endpoints/auth'; 2 | import room from './endpoints/room'; 3 | import pusher from './endpoints/pusher'; 4 | import media from './endpoints/media'; 5 | import profile from './endpoints/profile'; 6 | 7 | class API { 8 | static auth = auth; 9 | 10 | static room = room; 11 | 12 | static pusher = pusher; 13 | 14 | static media = media; 15 | 16 | static profile = profile; 17 | } 18 | export default API; 19 | -------------------------------------------------------------------------------- /src/api/endpoints/media.js: -------------------------------------------------------------------------------- 1 | import handling from '../handling'; 2 | 3 | const MediaApi = { 4 | downloadFile: async (serverName, mediaId) => { 5 | const res = await handling.requestFile(`/download/${serverName}/${mediaId}`); 6 | return res; 7 | }, 8 | 9 | uploadFile: async (filename, type, base64) => { 10 | const res = await handling.uploadFile(`/upload?filename=${filename}`, type, base64); 11 | return res; 12 | }, 13 | }; 14 | 15 | export default MediaApi; 16 | -------------------------------------------------------------------------------- /src/lib/colors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is colors 5 | */ 6 | 7 | const colors = { 8 | white: '#ffffff', 9 | black: '#000000', 10 | blackTransparent: 'rgba(0,0,0,0.5)', 11 | grey: '#cccccc', 12 | greyDark: '#828282', 13 | greyLight: '#F2F2F2', 14 | blue: '#0DAAFF', 15 | blueDark: '#337598', 16 | shadowColor: 'rgba(128,128,128,1)', 17 | red: '#E2485C', 18 | orange: '#FF8100', 19 | white03: 'rgba(255,255,255,0.3)', 20 | }; 21 | 22 | export default colors; 23 | -------------------------------------------------------------------------------- /src/lib/isIphoneX.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * Determine iphoneX or not 5 | */ 6 | 7 | 8 | import { Platform } from 'react-native'; 9 | import DeviceInfo from 'react-native-device-info'; 10 | 11 | export default function isIphoneX() { 12 | const iphoneXIds = ['iPhone11,2', 'iPhone10,3', 'iPhone10,6', 'iPhone11,4', 'iPhone11,6', 'iPhone11,8', 'iPhone12,1', 'iPhone12,3', 'iPhone12,5']; 13 | const deviceId = DeviceInfo.getDeviceId(); 14 | return Platform.OS === 'ios' && iphoneXIds.includes(deviceId); 15 | } 16 | -------------------------------------------------------------------------------- /src/models/ContentImage.js: -------------------------------------------------------------------------------- 1 | import ContentFile from './ContentFile'; 2 | import MsgTypes from '../consts/MsgTypes'; 3 | 4 | class ContentImage extends ContentFile { 5 | constructor(contentObj) { 6 | super(contentObj); 7 | this.msgtype = MsgTypes.mImage; 8 | } 9 | 10 | async getFile() { 11 | if (this.appURI) { 12 | return { status: true, data: this.appURI }; 13 | } 14 | 15 | const res = await super.getFile(); 16 | if (res.status) { 17 | return { status: true, data: this.dataStringForURI }; 18 | } 19 | 20 | return { status: false }; 21 | } 22 | } 23 | 24 | export default ContentImage; 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # react-native-matrix 2 | 3 | ### Description 4 | 5 | This is a crossplatform mobile client for matrix.org server. 6 | 7 | ### Instalation 8 | 9 | **How to run:** 10 | 11 | 1. run `yarn install` 12 | 2. run `cd ios && pod install` 13 | 14 | if you use RN < 0.60, please follow the installation of these modules: 15 | 1. react-native-audio-recorder-player 16 | 2. react-native-device-info 17 | 3. react-native-document-picker 18 | 4. react-native-image-picker 19 | 5. react-native-share 20 | 6. react-native-sound-recorder 21 | 7. rn-fetch-blob 22 | 23 | ### How to use 24 | 25 | ### Main components that can me used 26 | 27 | ### To Do List 28 | 29 | - update readme file 30 | - create login component 31 | - refactor the code 32 | - add renderItem for MatrixCahts 33 | -------------------------------------------------------------------------------- /src/api/endpoints/auth.js: -------------------------------------------------------------------------------- 1 | import handling from '../handling'; 2 | 3 | const AuthApi = { 4 | register: async (data) => { 5 | const res = await handling.request('post', '/register', data, null, true); 6 | return res; 7 | }, 8 | 9 | login: async (data) => { 10 | const res = await handling.request('post', '/login', data, null, true); 11 | return res; 12 | }, 13 | 14 | setAccessToken: (token) => { 15 | handling.setAccessToken(token); 16 | }, 17 | 18 | removeAccessToken: () => { 19 | handling.setAccessToken(''); 20 | }, 21 | 22 | setBaseURL: (baseURL) => { 23 | handling.setBaseURL(baseURL); 24 | }, 25 | 26 | getBaseURL: () => handling.getBaseURL(), 27 | }; 28 | 29 | export default AuthApi; 30 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # OSX 2 | # 3 | .DS_Store 4 | 5 | # XDE 6 | .expo/ 7 | 8 | # VSCode 9 | .vscode/ 10 | jsconfig.json 11 | 12 | # Xcode 13 | # 14 | build/ 15 | *.pbxuser 16 | !default.pbxuser 17 | *.mode1v3 18 | !default.mode1v3 19 | *.mode2v3 20 | !default.mode2v3 21 | *.perspectivev3 22 | !default.perspectivev3 23 | xcuserdata 24 | *.xccheckout 25 | *.moved-aside 26 | DerivedData 27 | *.hmap 28 | *.ipa 29 | *.xcuserstate 30 | project.xcworkspace 31 | 32 | # Android/IJ 33 | # 34 | .idea 35 | .gradle 36 | local.properties 37 | android.iml 38 | 39 | # Cocoapods 40 | # 41 | example/ios/Pods 42 | 43 | # node.js 44 | # 45 | node_modules/ 46 | npm-debug.log 47 | yarn-debug.log 48 | yarn-error.log 49 | 50 | # BUCK 51 | buck-out/ 52 | \.buckd/ 53 | android/app/libs 54 | android/keystores/debug.keystore 55 | 56 | # Expo 57 | .expo/* 58 | -------------------------------------------------------------------------------- /src/models/ContentAudio.js: -------------------------------------------------------------------------------- 1 | import ContentFile from './ContentFile'; 2 | import MsgTypes from '../consts/MsgTypes'; 3 | 4 | class ContentAudio extends ContentFile { 5 | constructor(contentObj) { 6 | super(contentObj); 7 | this.msgtype = MsgTypes.mAudio; 8 | } 9 | 10 | get fileURI() { 11 | return `file://${this.appURI}`; 12 | } 13 | 14 | get timeline() { 15 | return Object.prototype.hasOwnProperty.call(this.info, 'duration') && Number.isInteger(parseInt(this.info.duration, 10)) ? parseInt(this.info.duration, 10) : 0; 16 | } 17 | 18 | mmss = (milisecs) => { 19 | const secs = Math.floor(milisecs / 1000); 20 | const minutes = Math.floor(secs / 60); 21 | const seconds = secs % 60; 22 | // const miliseconds = Math.floor((milisecs % 1000) / 10); 23 | return `${this.pad(minutes)}:${this.pad(seconds)}`; 24 | } 25 | 26 | pad = num => (`0${num}`).slice(-2) 27 | } 28 | 29 | export default ContentAudio; 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Max Gornostayev 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/trans/en.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * English texts 5 | */ 6 | 7 | export default { 8 | fileModule: { 9 | textSelectDocument: 'Select Document', 10 | textCancelButtonTitle: 'Cancel', 11 | textTakePhotoButtonTitle: 'Take photo...', 12 | textChooseFromLibraryButtonTitle: 'Choose', 13 | textUploadPDF: 'Upload PDF File', 14 | }, 15 | createGroupChat: { 16 | changeGroupImage: 'Change group image', 17 | inputPlaceholder: 'Change group Title', 18 | buttonTitle: 'Create', 19 | }, 20 | inputToolbar: { 21 | placeholder: 'Type a message...', 22 | voiceRecordSend: 'Send', 23 | voiceRecordCancel: 'Cancel', 24 | }, 25 | event: { 26 | copy: 'Copy to clipboard', 27 | share: 'Share', 28 | quote: 'Qoute', 29 | cancel: 'Cancel', 30 | shareTitle: 'Share', 31 | }, 32 | editGroupChat: { 33 | changeGroupImage: 'Change group image', 34 | inputPlaceholder: 'Change group Title', 35 | buttonTitle: 'Add contact to the group', 36 | buttonLeave: 'Exit group chat', 37 | }, 38 | }; 39 | -------------------------------------------------------------------------------- /postinstall.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | 3 | //fix timer bug that is appeared when you install matrix-js-sdk for android 4 | // https://stackoverflow.com/questions/44603362/setting-a-timer-for-a-long-period-of-time-i-e-multiple-minutes 5 | let fileLocation = '../react-native/Libraries/Core/Timers/JSTimers.js'; 6 | let targetText = 'MAX_TIMER_DURATION_MS = 60'; 7 | let replacementText = 'MAX_TIMER_DURATION_MS = 10000'; 8 | 9 | let fileContent = fs.readFileSync(fileLocation, 'utf8'); 10 | if (fileContent.includes(targetText) && !fileContent.includes(replacementText)) { 11 | const patchedFileContent = fileContent.replace(targetText, replacementText); 12 | fs.writeFileSync(fileLocation, patchedFileContent, 'utf8'); 13 | } 14 | 15 | //fix crash in matrix-js-sdk when internet connection is lost 16 | fileLocation = '../matrix-js-sdk/lib/logger.js'; 17 | targetText = 'methodName === "error" ||'; 18 | replacementText = ''; 19 | fileContent = fs.readFileSync(fileLocation, 'utf8'); 20 | if (fileContent.includes(targetText)) { 21 | const patchedFileContent = fileContent.replace(targetText, replacementText); 22 | fs.writeFileSync(fileLocation, patchedFileContent, 'utf8'); 23 | } -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "plugins": [ 3 | "react", 4 | "react-native" 5 | ], 6 | "extends": "airbnb", 7 | "parser": "babel-eslint", 8 | "rules": { 9 | //offs 10 | "no-case-declarations": "off", 11 | "import/extensions": "off", 12 | "no-useless-constructor": "off", 13 | "react/jsx-one-expression-per-line": "off", 14 | "react/no-string-refs": "off", 15 | "jsx-a11y/href-no-hash": "off", 16 | "jsx-a11y/img-has-alt": "off", 17 | "react/destructuring-assignment": "off", 18 | "global-require": "off", 19 | "no-return-assign": "off", 20 | "react/forbid-prop-types": "off", 21 | "react/jsx-no-bind": "off", 22 | "no-param-reassign": "off", 23 | 24 | //warnings 25 | "class-methods-use-this": "warn", 26 | "array-callback-return": "warn", 27 | 28 | //errors 29 | "no-console": "error", 30 | "max-len": [1, 410], 31 | "react/jsx-filename-extension": ["error", { "extensions": [".js", ".jsx"] }], 32 | "indent": ["error", 4, { "SwitchCase": 1 }], 33 | "react/jsx-indent-props": ["error", 4], 34 | "react/jsx-indent":["error", 4], 35 | "object-curly-newline": ["error", { "multiline": true }] 36 | } 37 | } -------------------------------------------------------------------------------- /src/trans/de.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * English texts 5 | */ 6 | 7 | export default { 8 | fileModule: { 9 | textSelectDocument: 'Dokument auswählen', 10 | textCancelButtonTitle: 'Abbrechen', 11 | textTakePhotoButtonTitle: 'Foto aufnehmen', 12 | textChooseFromLibraryButtonTitle: 'Auswählen', 13 | textUploadPDF: 'PDF Dokument hochladen', 14 | }, 15 | createGroupChat: { 16 | changeGroupImage: 'Gruppen-Bild ändern', 17 | inputPlaceholder: 'Name Gruppe ändern', 18 | buttonTitle: 'Erstellen', 19 | }, 20 | inputToolbar: { 21 | placeholder: 'Nachricht hier schreiben', 22 | voiceRecordSend: 'Senden', 23 | voiceRecordCancel: 'Abbrechen', 24 | }, 25 | event: { 26 | copy: 'In die Zwischenablage kopieren', 27 | share: 'Teilen', 28 | quote: 'Bewerten', 29 | cancel: 'Abbrechen', 30 | shareTitle: 'teilen', 31 | }, 32 | editGroupChat: { 33 | changeGroupImage: 'Gruppen-Bild ändern', 34 | inputPlaceholder: 'Name Gruppe ändern', 35 | buttonTitle: 'Kontakt zur Gruppe hinzufügen', 36 | buttonLeave: 'Gruppen Chat beenden', 37 | }, 38 | }; 39 | -------------------------------------------------------------------------------- /src/trans/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * get translations 5 | */ 6 | 7 | import en from './en'; 8 | 9 | class Trans { 10 | static instance; 11 | 12 | propsTrans = {} 13 | 14 | local = 'en'; 15 | 16 | static getInstance() { 17 | if (!Trans.instance) { 18 | Trans.instance = new Trans(); 19 | } 20 | return Trans.instance; 21 | } 22 | 23 | setLocale(local) { 24 | this.local = local || 'en'; 25 | } 26 | 27 | t(param1, param2) { 28 | if (!param1) { 29 | return ''; 30 | } 31 | let f = null; 32 | switch (this.local) { 33 | default: 34 | case 'en': 35 | f = { ...en, ...this.propsTrans }; 36 | } 37 | if (!f || !Object.prototype.hasOwnProperty.call(f, param1)) { 38 | return ''; 39 | } 40 | if (!param2 || !Object.prototype.hasOwnProperty.call(f[param1], param2)) { 41 | return f[param1]; 42 | } 43 | 44 | return f[param1][param2]; 45 | } 46 | 47 | setTransFromProps(trans) { 48 | if (trans) { 49 | this.propsTrans = trans; 50 | } 51 | } 52 | } 53 | 54 | export default Trans.getInstance(); 55 | -------------------------------------------------------------------------------- /src/models/ContentText.js: -------------------------------------------------------------------------------- 1 | import Content from './Content'; 2 | import ConstValues from '../consts'; 3 | import MsgTypes from '../consts/MsgTypes'; 4 | import Utils from '../lib/utils'; 5 | 6 | class ContentText extends Content { 7 | msgtype = MsgTypes.mText; 8 | 9 | isQuote = false; 10 | 11 | constructor(contentObj) { 12 | super(contentObj); 13 | if (contentObj && contentObj.format && contentObj.format === ConstValues.customHTML && contentObj.formatted_body && contentObj.formatted_body.indexOf('
') !== -1) { 14 | this.isQuote = true; 15 | } 16 | } 17 | 18 | get matrixContentObj() { 19 | return ContentText.makeMessageObj(this.body, this.isQuote); 20 | } 21 | 22 | static makeMessageObj(body, isQuote) { 23 | return isQuote ? ContentText.makeHtmlMessageObj(body, Utils.convertMessageToQuoteHTML(body)) : ContentText.makeTextMessageObj(body); 24 | } 25 | 26 | static makeTextMessageObj(body) { 27 | return { 28 | msgtype: MsgTypes.mText, 29 | body, 30 | }; 31 | } 32 | 33 | static makeHtmlMessageObj(body, htmlBody) { 34 | return { 35 | msgtype: MsgTypes.mText, 36 | format: ConstValues.customHTML, 37 | body, 38 | formatted_body: htmlBody, 39 | }; 40 | } 41 | } 42 | 43 | export default ContentText; 44 | -------------------------------------------------------------------------------- /src/components/EventAvatar.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is component to show m.text message 5 | */ 6 | 7 | import React, { PureComponent } from 'react'; 8 | import { Image } from 'react-native'; 9 | import PropTypes from 'prop-types'; 10 | import ContentFile from '../models/ContentFile'; 11 | 12 | class EventAvatar extends PureComponent { 13 | // imageSource = null; 14 | 15 | constructor(props) { 16 | super(props); 17 | this.state = { uri: '' }; 18 | } 19 | 20 | async componentDidMount() { 21 | if (this.props.avatarObj && this.props.avatarObj.serverName && this.props.avatarObj.mediaId) { 22 | this.setState({ uri: ContentFile.getHTTPURI(this.props.avatarObj.serverName, this.props.avatarObj.mediaId) }); 23 | } 24 | } 25 | 26 | getNoPhoto = () => { 27 | if (this.props.icons.noPhoto) { 28 | return this.props.icons.noPhoto; 29 | } 30 | return this.props.avatarObj.noPhoto; 31 | } 32 | 33 | render() { 34 | return ( 35 | 36 | ); 37 | } 38 | } 39 | 40 | EventAvatar.defaultProps = { 41 | style: [{ width: 40, height: 40, borderRadius: 20, marginRight: 10 }], 42 | avatarObj: { }, 43 | icons: {}, 44 | }; 45 | EventAvatar.propTypes = { 46 | style: PropTypes.arrayOf(PropTypes.object), 47 | avatarObj: PropTypes.object, 48 | icons: PropTypes.object, 49 | }; 50 | 51 | export default EventAvatar; 52 | -------------------------------------------------------------------------------- /src/models/Content.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is general class for all content objects 5 | */ 6 | 7 | import MsgTypes from '../consts/MsgTypes'; 8 | 9 | class Content { 10 | body = ''; 11 | 12 | msgtype = MsgTypes.mGeneral; 13 | 14 | isQuote = false; 15 | 16 | constructor(contentObj) { 17 | if (contentObj) { 18 | Object.keys(contentObj).map(field => this[field] = contentObj[field]); 19 | } 20 | } 21 | 22 | get message() { 23 | return this.body ? this.body : ''; 24 | } 25 | 26 | get quoteMessageObj() { 27 | const arr = this.message.split('\n'); 28 | const ret = { quote: '', message: '' }; 29 | arr.map((val) => { 30 | if (val.indexOf('> ') !== -1) { 31 | ret.quote += `${val.replace('> ', '')}\n`; 32 | } else { 33 | ret.message += val; 34 | } 35 | }); 36 | if (ret.quote.length > 0) { 37 | ret.quote = ret.quote.slice(0, -1); 38 | } 39 | return ret; 40 | } 41 | 42 | get messageOnly() { 43 | if (this.isQuote) { 44 | const { quoteMessageObj } = this; 45 | return quoteMessageObj.message; 46 | } 47 | return this.message; 48 | } 49 | 50 | get type() { 51 | return this.msgtype; 52 | } 53 | 54 | get quoteText() { 55 | if (this.messageOnly.indexOf('> ') !== -1) { 56 | return this.messageOnly; 57 | } 58 | return `> ${this.messageOnly.replace(/(?:\r\n|\r|\n)/g, '\n> ')}\n\n`; 59 | } 60 | } 61 | 62 | export default Content; 63 | -------------------------------------------------------------------------------- /src/api/endpoints/room.js: -------------------------------------------------------------------------------- 1 | import handling from '../handling'; 2 | 3 | const RoomApi = { 4 | create: async (data) => { 5 | const res = await handling.request('post', '/createRoom', data); 6 | return res; 7 | }, 8 | 9 | acceptInvite: async (roomId) => { 10 | const res = await handling.request('post', `/rooms/${roomId}/join`); 11 | return res; 12 | }, 13 | 14 | leave: async (roomId) => { 15 | const res = await handling.request('post', `/rooms/${roomId}/leave`); 16 | return res; 17 | }, 18 | 19 | edit: async (data) => { 20 | const res = await handling.request('post', '/createRoom', data); 21 | return res; 22 | }, 23 | 24 | sync: async (fullState, since, filter, presence, timeout) => { 25 | fullState = fullState || false; 26 | const params = { full_state: fullState }; 27 | if (since) { 28 | params.since = since; 29 | } 30 | if (filter) { 31 | params.filter = filter; 32 | } 33 | if (presence) { 34 | params.presence = presence; 35 | } 36 | if (timeout) { 37 | params.timeout = timeout; 38 | } 39 | const res = await handling.request('get', '/sync', null, params); 40 | return res; 41 | }, 42 | 43 | setRoomReadMarkers: async (roomId, eventId) => { 44 | const data = { 45 | 'm.fully_read': eventId, 46 | 'm.read': eventId, 47 | }; 48 | const res = await handling.request('post', `/rooms/${roomId}/read_markers`, data); 49 | return res; 50 | }, 51 | 52 | sendStateEvent: async (roomId, type, content) => { 53 | const res = await handling.request('put', `/rooms/${roomId}/state/${type}`, content); 54 | return res; 55 | }, 56 | }; 57 | 58 | export default RoomApi; 59 | -------------------------------------------------------------------------------- /src/models/Member.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is user class 5 | */ 6 | 7 | import * as sdk from 'matrix-js-sdk'; 8 | import Utils from '../lib/utils'; 9 | import api from '../api'; 10 | 11 | class Member { 12 | userId = null; 13 | 14 | isMy = false; 15 | 16 | presence = ''; 17 | 18 | displayName = ''; 19 | 20 | mxcURI = ''; 21 | 22 | serverName = ''; 23 | 24 | mediaId = ''; 25 | 26 | source = null; 27 | 28 | constructor(matrixUser, myUserId) { 29 | if (matrixUser) { 30 | this.userId = matrixUser.userId; 31 | this.presence = matrixUser.presence; 32 | this.displayName = matrixUser.displayName; 33 | this.mxcURI = matrixUser.avatarUrl; 34 | const { serverName, mediaId } = Utils.parseMXCURI(this.mxcURI); 35 | this.serverName = serverName; 36 | this.mediaId = mediaId; 37 | this.isMy = myUserId && this.userId === myUserId; 38 | } 39 | } 40 | 41 | get name() { 42 | return this.displayName; 43 | } 44 | 45 | get uri() { 46 | return this.mxcURI ? this.httpURL : ''; 47 | } 48 | 49 | get httpURL() { 50 | return `${api.auth.getBaseURL() + sdk.PREFIX_MEDIA_R0}/download/${this.serverName}/${this.mediaId}`; 51 | } 52 | 53 | async getFile() { 54 | if (this.source) { 55 | return { status: true, data: this.source }; 56 | } 57 | if (this.serverName && this.mediaId) { 58 | const res = await api.media.downloadFile(this.serverName, this.mediaId); 59 | if (res.status) { 60 | this.source = res.data; 61 | return { status: true, data: this.source }; 62 | } 63 | } 64 | return { status: false }; 65 | } 66 | } 67 | 68 | export default Member; 69 | -------------------------------------------------------------------------------- /src/lib/poly.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is help class that allows matrix-sdk-js module works with react native 5 | */ 6 | 7 | import { EventEmitter } from 'fbemitter'; 8 | import unorm from 'unorm'; 9 | 10 | String.prototype.normalize = function (form) { return require('unorm')[String(form).toLowerCase()](this); }; 11 | 12 | class Document { 13 | constructor() { 14 | this.emitter = new EventEmitter(); 15 | this.addEventListener = this.addEventListener.bind(this); 16 | this.removeEventListener = this.removeEventListener.bind(this); 17 | this._checkEmitter = this._checkEmitter.bind(this); 18 | } 19 | 20 | createElement(tagName) { 21 | return {}; 22 | } 23 | 24 | _checkEmitter() { 25 | if ( 26 | !this.emitter 27 | || !(this.emitter.on || this.emitter.addEventListener || this.emitter.addListener) 28 | ) { 29 | this.emitter = new EventEmitter(); 30 | } 31 | } 32 | 33 | addEventListener(eventName, listener) { 34 | this._checkEmitter(); 35 | if (this.emitter.on) { 36 | this.emitter.on(eventName, listener); 37 | } else if (this.emitter.addEventListener) { 38 | this.emitter.addEventListener(eventName, listener); 39 | } else if (this.emitter.addListener) { 40 | this.emitter.addListener(eventName, listener); 41 | } 42 | } 43 | 44 | removeEventListener(eventName, listener) { 45 | this._checkEmitter(); 46 | if (this.emitter.off) { 47 | this.emitter.off(eventName, listener); 48 | } else if (this.emitter.removeEventListener) { 49 | this.emitter.removeEventListener(eventName, listener); 50 | } else if (this.emitter.removeListener) { 51 | this.emitter.removeListener(eventName, listener); 52 | } 53 | } 54 | } 55 | 56 | window.document = window.document || new Document(); 57 | -------------------------------------------------------------------------------- /src/lib/utils.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is utils class 5 | */ 6 | import { Platform } from 'react-native'; 7 | import moment from 'moment'; 8 | 9 | const utils = { 10 | testProps: name => (Platform.OS === 'ios' ? { testID: name } : { accessible: true, accessibilityLabel: name }), 11 | formatTimestamp: (ts, dateformat) => moment(ts).format(dateformat), 12 | addDotsToString: str => (str.length > 20 ? `${str.substr(0, 20)}...` : str), 13 | isNewDay: (curDate, prevDate) => moment(curDate).diff(moment(prevDate), 'days', true) > 1, 14 | isTextHaveURL: str => str.indexOf('http:') !== -1 || str.indexOf('https:') !== -1, 15 | timestamp: isMilliseconds => parseInt(isMilliseconds ? moment().valueOf() : moment().unix(), 10), 16 | convertMessageToQuoteHTML: (message) => { 17 | const arr = message.split('\n'); 18 | let ret = '

'; 19 | let isQuoteFinished = false; 20 | arr.map((val) => { 21 | if (val.indexOf('> ') !== -1) { 22 | ret += `${val.replace('> ', '')}
`; 23 | } else { 24 | if (!isQuoteFinished) { 25 | isQuoteFinished = true; 26 | ret += '

'; 27 | } 28 | ret += `

${val}

`; 29 | } 30 | }); 31 | return ret; 32 | }, 33 | parseMXCURI(mxcURI) { 34 | if (mxcURI) { 35 | mxcURI = mxcURI.replace('mxc://', ''); 36 | const arr = mxcURI.split('/'); 37 | if (arr.length > 1) { 38 | return { serverName: arr[0], mediaId: arr[1] }; 39 | } 40 | } 41 | return { serverName: '', mediaId: '' }; 42 | }, 43 | getCountdownTitle: (time) => { 44 | const minutes = Math.floor(time / 60); 45 | const seconds = time - minutes * 60; 46 | const secondTitle = seconds < 10 ? `0${seconds}` : seconds; 47 | return `${minutes}:${secondTitle}`; 48 | }, 49 | }; 50 | 51 | export default utils; 52 | -------------------------------------------------------------------------------- /src/components/ContentFile.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is component to show m.text message 5 | */ 6 | 7 | import React, { PureComponent } from 'react'; 8 | import { Text, Image, TouchableOpacity } from 'react-native'; 9 | import PropTypes from 'prop-types'; 10 | import Colors from '../lib/colors'; 11 | import Utils from '../lib/utils'; 12 | 13 | const stylesObj = { 14 | icon24: { width: 24, height: 24 }, 15 | filePreview: { margin: 10, marginBottom: 0, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', borderRadius: 10, backgroundColor: Colors.greyLight, padding: 10 }, 16 | textFileTitle: { fontSize: 12, color: Colors.black, paddingLeft: 10 }, 17 | filePreviewMy: { backgroundColor: Colors.white03 }, 18 | textFileTitleMy: { color: Colors.white, paddingLeft: 0 }, 19 | }; 20 | 21 | class ContentFile extends PureComponent { 22 | onPress = () => { 23 | if (this.props.onFilePress) { 24 | this.props.onFilePress(this.props.contentObj); 25 | } 26 | } 27 | 28 | render() { 29 | const { isOwn, contentObj, contentFileStyles } = this.props; 30 | let image = null; 31 | const styles = { ...stylesObj, ...contentFileStyles }; 32 | 33 | if (contentObj.info.mimetype === 'application/pdf') { 34 | image = (); 35 | } 36 | 37 | return ( 38 | this.onPress()} {...Utils.testProps('btnEventFilePress')}> 39 | {image} 40 | {contentObj.title} 41 | 42 | ); 43 | } 44 | } 45 | 46 | ContentFile.defaultProps = { 47 | contentFileStyles: {}, 48 | contentObj: null, 49 | isOwn: false, 50 | onFilePress: null, 51 | icons: {}, 52 | }; 53 | ContentFile.propTypes = { 54 | contentFileStyles: PropTypes.object, 55 | contentObj: PropTypes.object, 56 | isOwn: PropTypes.bool, 57 | onFilePress: PropTypes.func, 58 | icons: PropTypes.object, 59 | }; 60 | 61 | export default ContentFile; 62 | -------------------------------------------------------------------------------- /src/components/ContentText.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is component to show m.text message 5 | */ 6 | 7 | import React, { PureComponent } from 'react'; 8 | import { View, Text } from 'react-native'; 9 | import PropTypes from 'prop-types'; 10 | import ContentTextModel from '../models/ContentText'; 11 | import Colors from '../lib/colors'; 12 | 13 | const stylesObj = { 14 | contentTextContainer: { padding: 10, paddingBottom: 0 }, 15 | contentTextMy: { color: Colors.white, fontSize: 14 }, 16 | contentTextNotMy: { color: Colors.black, fontSize: 14 }, 17 | contentTextQuoteNotMyContainer: { borderLeftWidth: 2, borderColor: Colors.black, paddingLeft: 5, marginBottom: 10 }, 18 | contentTextQuoteMyContainer: { borderLeftWidth: 2, borderColor: Colors.white, paddingLeft: 5, marginBottom: 10 }, 19 | contentTextQuoteNotMy: { fontSize: 12, color: Colors.black, textAlign: 'left' }, 20 | contentTextQuoteMy: { fontSize: 12, color: Colors.white, textAlign: 'left' }, 21 | }; 22 | 23 | class ContentText extends PureComponent { 24 | render() { 25 | const { isOwn, contentObj, contentTextStyles } = this.props; 26 | 27 | const styles = { ...stylesObj, ...contentTextStyles }; 28 | 29 | if (contentObj.isQuote) { 30 | const textObj = contentObj.quoteMessageObj; 31 | return ( 32 | 33 | 34 | {textObj.quote} 35 | 36 | {textObj.message} 37 | 38 | ); 39 | } 40 | 41 | return {contentObj.message}; 42 | } 43 | } 44 | 45 | ContentText.defaultProps = { 46 | contentTextStyles: {}, 47 | contentObj: new ContentTextModel(), 48 | isOwn: false, 49 | }; 50 | ContentText.propTypes = { 51 | contentTextStyles: PropTypes.object, 52 | contentObj: PropTypes.object, 53 | isOwn: PropTypes.bool, 54 | }; 55 | 56 | export default ContentText; 57 | -------------------------------------------------------------------------------- /src/components/ContentImage.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is component to show m.image message 5 | */ 6 | 7 | import React, { Component } from 'react'; 8 | import { StyleSheet, Platform, Image, TouchableOpacity, ActivityIndicator } from 'react-native'; 9 | import PropTypes from 'prop-types'; 10 | import Utils from '../lib/utils'; 11 | 12 | const styles = StyleSheet.create({ 13 | imagePreviewNotMy: { 14 | borderTopLeftRadius: Platform.OS === 'ios' ? 0 : 20, 15 | borderTopRightRadius: 20, 16 | width: 150, 17 | height: 150, 18 | }, 19 | imagePreviewMy: { 20 | width: 150, 21 | height: 150, 22 | borderTopLeftRadius: 20, 23 | borderTopRightRadius: Platform.OS === 'ios' ? 0 : 20, 24 | }, 25 | }); 26 | 27 | class ContentImage extends Component { 28 | imageSource = null; 29 | 30 | constructor(props) { 31 | super(props); 32 | this.state = { loaded: false }; 33 | } 34 | 35 | async componentDidMount() { 36 | if (this.props.contentObj) { 37 | const res = await this.props.contentObj.getFile(); 38 | if (res.status) { 39 | this.imageSource = res.data; 40 | this.setState({ loaded: true }); 41 | } 42 | } 43 | } 44 | 45 | onPress = () => { 46 | if (this.props.onImagePress) { 47 | this.props.onImagePress(this.props.contentObj); 48 | } 49 | } 50 | 51 | render() { 52 | if (!this.state.loaded || !this.imageSource) { 53 | return ; 54 | } 55 | return ( 56 | this.onPress()} {...Utils.testProps('btnEventImagePress')}> 57 | 58 | 59 | ); 60 | } 61 | } 62 | 63 | ContentImage.defaultProps = { 64 | imagePreviewNotMy: styles.imagePreviewNotMy, 65 | imagePreviewMy: styles.imagePreviewMy, 66 | contentObj: null, 67 | isOwn: false, 68 | onImagePress: null, 69 | }; 70 | ContentImage.propTypes = { 71 | imagePreviewNotMy: PropTypes.object, 72 | imagePreviewMy: PropTypes.object, 73 | contentObj: PropTypes.object, 74 | isOwn: PropTypes.bool, 75 | onImagePress: PropTypes.func, 76 | }; 77 | 78 | export default ContentImage; 79 | -------------------------------------------------------------------------------- /src/components/LeftX.js: -------------------------------------------------------------------------------- 1 | import React, { PureComponent } from 'react'; 2 | import { Animated, InteractionManager } from 'react-native'; 3 | 4 | class LeftX extends PureComponent { 5 | constructor(props) { 6 | super(props); 7 | 8 | const { fromValue } = props; 9 | 10 | this.state = { 11 | leftValue: new Animated.Value(fromValue), 12 | opacityValue: new Animated.Value(0), 13 | }; 14 | } 15 | 16 | componentDidMount() { 17 | const { startOnDidMount } = this.props; 18 | 19 | if (startOnDidMount) { 20 | InteractionManager.runAfterInteractions().then(() => { 21 | this.show(); 22 | }); 23 | } 24 | } 25 | 26 | show(callback) { 27 | const { leftValue, opacityValue } = this.state; 28 | const { duration, toValue } = this.props; 29 | 30 | Animated.parallel([ 31 | Animated.timing(opacityValue, { 32 | toValue: 1, 33 | duration, 34 | useNativeDriver: false, 35 | }), 36 | Animated.timing(leftValue, { 37 | toValue, 38 | duration, 39 | useNativeDriver: false, 40 | }), 41 | ]).start(() => { 42 | if (callback) { 43 | callback(); 44 | } 45 | }); 46 | } 47 | 48 | hide(callback) { 49 | const { leftValue, opacityValue } = this.state; 50 | const { duration, fromValue } = this.props; 51 | 52 | Animated.parallel([ 53 | Animated.timing(opacityValue, { 54 | toValue: 0, 55 | duration, 56 | useNativeDriver: false, 57 | }), 58 | Animated.timing(leftValue, { 59 | toValue: fromValue, 60 | duration, 61 | useNativeDriver: false, 62 | }), 63 | ]).start(() => { 64 | if (callback) { 65 | callback(); 66 | } 67 | }); 68 | } 69 | 70 | render() { 71 | const { opacityValue, leftValue } = this.state; 72 | const style = this.props.style || {}; 73 | 74 | const animatedStyle = { 75 | position: 'absolute', 76 | opacity: opacityValue, 77 | left: leftValue, 78 | ...style, 79 | }; 80 | 81 | return ( 82 | 83 | {this.props.children} 84 | 85 | ); 86 | } 87 | } 88 | 89 | export default LeftX; 90 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-matrix", 3 | "version": "0.0.12", 4 | "description": "React native Components for matrix chat. This is beta version.", 5 | "main": "src/index.js", 6 | "repository": { 7 | "type": "git", 8 | "url": "git+https://github.com/maxweb4u/react-native-matrix.git" 9 | }, 10 | "keywords": [ 11 | "android", 12 | "ios", 13 | "react-native", 14 | "react", 15 | "react-component", 16 | "messenger", 17 | "message", 18 | "chat", 19 | "matrix" 20 | ], 21 | "author": "Max Gornostayev", 22 | "license": "MIT", 23 | "bugs": { 24 | "url": "https://github.com/maxweb4u/react-native-matrix/issues" 25 | }, 26 | "homepage": "https://github.com/maxweb4u/react-native-matrix#readme", 27 | "scripts": { 28 | "fix": "../.bin/eslint -c .eslintrc --ext .js src --fix", 29 | "postinstall": "node ./postinstall.js", 30 | "npmupload": "npm publish --access public" 31 | }, 32 | "devDependencies": { 33 | "@babel/core": "^7.6.2", 34 | "@babel/plugin-proposal-class-properties": "^7.6.2", 35 | "@babel/plugin-proposal-decorators": "^7.4.4", 36 | "@babel/runtime": "^7.5.5", 37 | "@react-native-community/eslint-config": "^0.0.5", 38 | "@types/react": "^16.8.6", 39 | "@types/react-native": "^0.60.6", 40 | "babel-eslint": "^10.0.1", 41 | "babel-jest": "^24.9.0", 42 | "babel-plugin-transform-flow-strip-types": "^6.22.0", 43 | "eslint": "^6.4.0", 44 | "eslint-config-airbnb": "^17.1.0", 45 | "eslint-plugin-import": "^2.14.0", 46 | "eslint-plugin-jsx-a11y": "^6.1.1", 47 | "eslint-plugin-react": "^7.11.1", 48 | "eslint-plugin-react-native": "^3.2.1", 49 | "react": "16.8.6", 50 | "react-native": "0.60.6" 51 | }, 52 | "dependencies": { 53 | "axios": "^0.19.0", 54 | "base64-arraybuffer": "^0.2.0", 55 | "buffer": "^5.6.0", 56 | "events": "^3.1.0", 57 | "fbemitter": "^2.1.1", 58 | "get-uid": "^1.0.1", 59 | "matrix-js-sdk": "^7.0.0", 60 | "moment": "^2.24.0", 61 | "prop-types": "^15.7.2", 62 | "react-native-action-sheet": "^2.2.0", 63 | "react-native-audio-recorder-player": "^2.4.4-rc.1", 64 | "react-native-device-info": "^5.2.1", 65 | "react-native-document-picker": "^3.2.4", 66 | "react-native-emoji-selector": "^0.1.9", 67 | "react-native-image-base64": "^0.1.3", 68 | "react-native-image-picker": "^1.0.1", 69 | "react-native-image-resizer": "^1.0.1", 70 | "react-native-share": "^2.0.0", 71 | "react-native-sound-recorder": "^1.3.3", 72 | "rn-fetch-blob": "^0.10.16", 73 | "rxjs": "^6.5.4", 74 | "unorm": "^1.6.0", 75 | "url": "^0.11.0" 76 | }, 77 | "peerDependencies": { 78 | "prop-types": "*", 79 | "react": "*", 80 | "react-native": "*" 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/components/InViewPort.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 27/01/20 3 | * 4 | * Component that provides triggering when component in showing 5 | */ 6 | 7 | import React, { PureComponent } from 'react'; 8 | import { View, Dimensions, Platform } from 'react-native'; 9 | import PropTypes from 'prop-types'; 10 | import { timer } from 'rxjs'; 11 | 12 | class InViewPort extends PureComponent { 13 | subscription = null; 14 | 15 | constructor(props) { 16 | super(props); 17 | this.state = { 18 | rectTop: 0, 19 | rectBottom: 0, 20 | rectWidth: 0, 21 | }; 22 | } 23 | 24 | componentDidMount() { 25 | if (this.props.active) { 26 | this.startWatching(); 27 | } else { 28 | this.stopWatching(); 29 | } 30 | } 31 | 32 | componentWillUnmount() { 33 | this.stopWatching(); 34 | } 35 | 36 | startWatching() { 37 | this.subscription = timer(500, this.props.delay).subscribe(() => this.check()); 38 | } 39 | 40 | stopWatching() { 41 | if (this.subscription && this.subscription.unsubscribe) { 42 | this.subscription.unsubscribe(); 43 | } 44 | } 45 | 46 | check() { 47 | let isVisible = false; 48 | const dimen = Dimensions.get('window'); 49 | if (Platform.OS === 'ios') { 50 | this.refs.myview.measure((ox, oy, width, height, pageX, pageY) => { 51 | this.setState({ 52 | rectTop: pageY, 53 | rectBottom: pageY + height, 54 | rectWidth: pageX + width, 55 | }); 56 | }); 57 | isVisible = ( 58 | this.state.rectBottom !== 0 && this.state.rectBottom >= 0 && this.state.rectTop <= dimen.height 59 | && this.state.rectWidth > 0 && this.state.rectWidth <= dimen.width 60 | ); 61 | } else { 62 | this.refs.myview.measureInWindow((pageX, pageY) => { 63 | this.setState({ 64 | rectWidth: pageX, 65 | rectTop: pageY, 66 | }); 67 | }); 68 | isVisible = this.state.rectWidth >= 0 && this.state.rectWidth <= dimen.width && this.state.rectTop >= 0 && this.state.rectTop <= dimen.height; 69 | } 70 | this.props.onChange(isVisible); 71 | } 72 | 73 | render() { 74 | return ( 75 | 76 | {this.props.children} 77 | 78 | ); 79 | } 80 | } 81 | 82 | InViewPort.defaultProps = { 83 | style: {}, 84 | delay: 1000, 85 | active: false, 86 | onChange: () => {}, 87 | }; 88 | InViewPort.propTypes = { 89 | onChange: PropTypes.func, 90 | active: PropTypes.bool, 91 | delay: PropTypes.number, 92 | style: PropTypes.object, 93 | }; 94 | 95 | export default InViewPort; 96 | -------------------------------------------------------------------------------- /src/components/VoiceRecord.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is voice recording component 5 | */ 6 | 7 | import React, { PureComponent } from 'react'; 8 | import PropTypes from 'prop-types'; 9 | import { View, Text, TouchableOpacity } from 'react-native'; 10 | import { timer } from 'rxjs'; 11 | import Utils from '../lib/utils'; 12 | import Colors from '../lib/colors'; 13 | 14 | const stylesObj = { 15 | voiceContainer: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', width: '100%', paddingLeft: 16, paddingRight: 16 }, 16 | actionContainer: { height: 36, alignItems: 'center', justifyContent: 'center' }, 17 | voiceCancelText: { color: Colors.blueDark, fontSize: 14 }, 18 | voiceSendText: { color: Colors.blue, fontSize: 14 }, 19 | voiceTimerContainer: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start' }, 20 | recordLabel: { width: 16, height: 16, borderRadius: 8, backgroundColor: Colors.red }, 21 | voiceTimeText: { paddingLeft: 5, color: Colors.black, fontSize: 12 }, 22 | }; 23 | 24 | class VoiceRecord extends PureComponent { 25 | subscription = null; 26 | 27 | constructor(props) { 28 | super(props); 29 | this.state = { timeline: 0 }; 30 | } 31 | 32 | componentDidMount() { 33 | this.subscription = timer(0, 1000).subscribe(() => this.timerUp()); 34 | } 35 | 36 | componentWillUnmount() { 37 | if (this.subscription && this.subscription.unsubscribe) this.subscription.unsubscribe(); 38 | } 39 | 40 | cancel = () => { 41 | this.props.cancelRecording(); 42 | this.setState({ timeline: 0 }); 43 | } 44 | 45 | stop = () => { 46 | this.props.stopRecording(this.state.timeline * 1000); 47 | this.setState({ timeline: 0 }); 48 | } 49 | 50 | timerUp = () => { 51 | if (this.props.showVoiceRecord) { 52 | let { timeline } = this.state; 53 | timeline += 1; 54 | this.setState({ timeline }); 55 | } 56 | } 57 | 58 | render() { 59 | const { voiceRecordStyles, showVoiceRecord, trans } = this.props; 60 | 61 | if (!showVoiceRecord) { 62 | return null; 63 | } 64 | const styles = voiceRecordStyles; 65 | return ( 66 | 67 | this.cancel()} {...Utils.testProps('btnAudioCancel')}> 68 | {trans.voiceRecordCancel} 69 | 70 | this.stop()} {...Utils.testProps('btnAudioSend')}> 71 | {trans.voiceRecordSend} 72 | 73 | 74 | 75 | {Utils.getCountdownTitle(this.state.timeline)} 76 | 77 | 78 | ); 79 | } 80 | } 81 | 82 | VoiceRecord.defaultProps = { 83 | trans: {}, 84 | showVoiceRecord: false, 85 | cancelRecording: () => {}, 86 | stopRecording: () => {}, 87 | voiceRecordStyles: stylesObj, 88 | }; 89 | VoiceRecord.propTypes = { 90 | showVoiceRecord: PropTypes.bool, 91 | cancelRecording: PropTypes.func, 92 | stopRecording: PropTypes.func, 93 | trans: PropTypes.object, 94 | voiceRecordStyles: PropTypes.object, 95 | }; 96 | 97 | export default VoiceRecord; 98 | -------------------------------------------------------------------------------- /src/api/handling.js: -------------------------------------------------------------------------------- 1 | import * as sdk from 'matrix-js-sdk'; 2 | import RNFetchBlob from 'rn-fetch-blob'; 3 | import base64 from 'base64-arraybuffer'; 4 | import codes from './codes'; 5 | import client from './axios'; 6 | 7 | class Handling { 8 | static async request(method, path, data, params, isNotSecure) { 9 | const url = sdk.PREFIX_R0 + path; 10 | const conf = { method, url, secure: !isNotSecure }; 11 | if (data) { 12 | conf.data = data; 13 | } 14 | if (!isNotSecure) { 15 | params = params ? { ...params, access_token: Handling.getAccessToken() } : { access_token: Handling.getAccessToken() }; 16 | } 17 | if (params) { 18 | conf.params = params; 19 | } 20 | const response = await Handling.getResponse(conf, true); 21 | 22 | return Handling.processResponse(response); 23 | } 24 | 25 | static async getResponse(conf) { 26 | try { 27 | const result = await client.request(conf); 28 | return Handling.success(result); 29 | } catch (e) { 30 | return Handling.error(e); 31 | } 32 | } 33 | 34 | static async processResponse(res) { 35 | switch (res.code.toString()) { 36 | case codes.statusOK: 37 | case codes.statusNoContent: 38 | return res; 39 | default: 40 | res.status = false; 41 | return res; 42 | } 43 | } 44 | 45 | 46 | static error(error) { 47 | const code = Object.prototype.hasOwnProperty.call(error, 'status') ? error.status : codes.statusInternalError; 48 | const data = Object.prototype.hasOwnProperty.call(error, 'data') ? error.data : {}; 49 | const msg = Object.prototype.hasOwnProperty.call(data, 'error') ? data.error : 'error'; 50 | const errorCode = Object.prototype.hasOwnProperty.call(data, 'errcode') ? data.errorCode : codes.errorCodeUNKNOWN; 51 | return { status: false, code, data, msg, errorCode }; 52 | } 53 | 54 | static success(res) { 55 | if (res && Object.prototype.hasOwnProperty.call(res, 'status')) { 56 | const data = Object.prototype.hasOwnProperty.call(res, 'data') && res.data ? res.data : {}; 57 | const code = res.status ? res.status.toString() : codes.statusInternalError; 58 | return { status: true, code, data, msg: '', errorCode: codes.errorCodeNONE }; 59 | } 60 | return Handling.error({}); 61 | } 62 | 63 | static async requestFile(path) { 64 | const url = Handling.getBaseURL() + sdk.PREFIX_MEDIA_R0 + path; 65 | const headers = { accessToken: Handling.getAccessToken() }; 66 | return RNFetchBlob.config({ timeout: 20000 }).fetch('GET', url, headers).then((res) => { 67 | const { status } = res.info(); 68 | const response = { status, data: '' }; 69 | if (status.toString() === codes.statusOK) { 70 | response.status = true; 71 | response.data = res.base64(); 72 | response.code = codes.statusOK; 73 | } 74 | return Handling.processResponse(response); 75 | }).catch((errorMessage) => { 76 | const response = Handling.error(errorMessage); 77 | return Handling.processResponse(response); 78 | }); 79 | } 80 | 81 | static async uploadFile(path, type, data) { 82 | try { 83 | const url = Handling.getBaseURL() + sdk.PREFIX_MEDIA_R0 + path; 84 | const result = await client.post(url, base64.decode(data), { headers: { Authorization: `Bearer ${Handling.getAccessToken()}`, accessToken: Handling.getAccessToken(), 'Content-Type': type } }); 85 | return Handling.success(result); 86 | } catch (e) { 87 | return Handling.error(e); 88 | } 89 | } 90 | 91 | static getAccessToken() { 92 | return client.defaults.headers.common.accessToken; 93 | } 94 | 95 | static setAccessToken(token) { 96 | client.defaults.headers.common.accessToken = token; 97 | return true; 98 | } 99 | 100 | static setBaseURL(baseURL) { 101 | client.defaults.baseURL = baseURL; 102 | return true; 103 | } 104 | 105 | static getBaseURL() { 106 | return client.defaults.baseURL; 107 | } 108 | } 109 | 110 | export default Handling; 111 | -------------------------------------------------------------------------------- /src/models/ContentFile.js: -------------------------------------------------------------------------------- 1 | import * as sdk from 'matrix-js-sdk'; 2 | import Content from './Content'; 3 | import MsgTypes from '../consts/MsgTypes'; 4 | import FileUtils from '../lib/fileUtils'; 5 | import Utils from '../lib/utils'; 6 | import api from '../api'; 7 | 8 | class ContentFile extends Content { 9 | body = ''; 10 | 11 | filename = ''; 12 | 13 | msgtype = MsgTypes.mFile; 14 | 15 | mxcURI = ''; 16 | 17 | appURI = ''; 18 | 19 | serverName = ''; 20 | 21 | mediaId = ''; 22 | 23 | info = { mimetype: '', size: 0 }; 24 | 25 | source = null; 26 | 27 | /* 28 | * contentobj = { 29 | * body: A human-readable description of the file 30 | * filename: filename 31 | * info: FileInfo - { mimetype: '', size: 0 }; 32 | * msgtype: 'm.file' 33 | * url: mxcURI 34 | * uri: appURI 35 | * source: base64 source string 36 | * } 37 | * 38 | */ 39 | constructor(contentobj) { 40 | super(contentobj); 41 | Object.keys(contentobj).map(field => this[field] = contentobj[field]); 42 | this.mxcURI = contentobj.url || ''; 43 | this.appURI = contentobj.uri || ''; 44 | const { serverName, mediaId } = Utils.parseMXCURI(this.mxcURI); 45 | this.serverName = serverName; 46 | this.mediaId = mediaId; 47 | } 48 | 49 | get title() { 50 | return this.body && this.body.length > 20 ? `${this.body.substr(0, 17)}... .${this.body.substr(-3, 3)}` : this.body; 51 | } 52 | 53 | get dataStringForURI() { 54 | return `data:${this.info.mimetype};base64,${this.source}`; 55 | } 56 | 57 | get infoTitle() { 58 | let ret = this.info.size ? FileUtils.formatBytes(this.info.size) : ''; 59 | if (this.info.mimetype) { 60 | if (this.info.size) { 61 | ret += ' | '; 62 | } 63 | ret += FileUtils.formatFileMimeType(this.info.mimetype); 64 | } 65 | return ret; 66 | } 67 | 68 | get matrixContentObj() { 69 | return { msgtype: this.msgtype, body: this.body, url: this.mxcURI, info: this.info }; 70 | } 71 | 72 | get httpURL() { 73 | return ContentFile.getHTTPURI(this.serverName, this.mediaId); 74 | } 75 | 76 | get base64ForShare() { 77 | return `data:${this.mimeType};base64,${this.source}`; 78 | } 79 | 80 | get mimeType() { 81 | return this.info.mimetype; 82 | } 83 | 84 | async getFile() { 85 | if (this.source) { 86 | return { status: true, data: this.source }; 87 | } 88 | if (this.serverName && this.mediaId) { 89 | const res = await api.media.downloadFile(this.serverName, this.mediaId); 90 | if (res.status) { 91 | this.source = res.data; 92 | return { status: true, data: this.source }; 93 | } 94 | } 95 | return { status: false }; 96 | } 97 | 98 | async uploadFile() { 99 | if (this.body && this.info.mimetype && this.source) { 100 | const res = await await api.media.uploadFile(this.body, this.info.mimetype, this.source); 101 | if (res.status) { 102 | this.mxcURI = res.data.content_uri; 103 | const { serverName, mediaId } = Utils.parseMXCURI(res.data.content_uri); 104 | this.serverName = serverName; 105 | this.mediaId = mediaId; 106 | return res; 107 | } 108 | } 109 | return { status: false }; 110 | } 111 | 112 | async saveFile() { 113 | if (this.body && this.info.mimetype && this.source) { 114 | const uri = await FileUtils.saveFile(this.body, this.source); 115 | if (uri) { 116 | this.appURI = uri; 117 | return { status: true, uri }; 118 | } 119 | } 120 | return { status: false }; 121 | } 122 | 123 | static makeMessageObj(msgtype, filename, uri, mimetype, base64, size, duration) { 124 | const obj = { msgtype, body: filename, filename, info: { mimetype }, uri }; 125 | if (size) { 126 | obj.info.size = size; 127 | } 128 | if (base64) { 129 | obj.source = base64; 130 | } 131 | if (duration) { 132 | obj.info.duration = duration; 133 | } 134 | return obj; 135 | } 136 | 137 | static getHTTPURI = (serverName, mediaId) => `${api.auth.getBaseURL() + sdk.PREFIX_MEDIA_R0}/download/${serverName}/${mediaId}` 138 | } 139 | 140 | export default ContentFile; 141 | -------------------------------------------------------------------------------- /src/components/ContentAudio.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is component to show m.audio message 5 | */ 6 | 7 | import React, { Component } from 'react'; 8 | import { Platform, View, Image, TouchableOpacity, Text } from 'react-native'; 9 | import PropTypes from 'prop-types'; 10 | import Colors from '../lib/colors'; 11 | import Utils from '../lib/utils'; 12 | 13 | const stylesObj = { 14 | audioPreview: { paddingTop: 10, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', borderTopLeftRadius: Platform.OS === 'ios' ? 0 : 20, borderTopRightRadius: 20, width: 170 }, 15 | audioPreviewMy: { borderTopLeftRadius: 20, borderTopRightRadius: Platform.OS === 'ios' ? 0 : 20 }, 16 | audioTrackContainer: { height: 2, width: 105, backgroundColor: Colors.grey, borderRadius: 1 }, 17 | audioTrackContainerInner: { height: 2, width: 100, position: 'relative' }, 18 | audioTrack: { height: 10, width: 10, position: 'relative', backgroundColor: Colors.orange, borderRadius: 5, left: 0, top: -4 }, 19 | audioTimeContainer: { alignSelf: 'flex-end', paddingTop: 4 }, 20 | audioTimeText: { fontSize: 12, color: Colors.greyDark }, 21 | audioTimeTextMy: { color: Colors.white }, 22 | audioTrackProgress: { alignItems: 'center', justifyContent: 'center', marginTop: 16, paddingRight: 10 }, 23 | icon32: { width: 32, height: 32 }, 24 | touchArea: { width: 36, height: 36, alignItems: 'center', justifyContent: 'center' }, 25 | }; 26 | 27 | class ContentAudio extends Component { 28 | constructor(props) { 29 | super(props); 30 | this.state = { 31 | isPlaying: false, 32 | currentPositionSec: 0, 33 | currentDurationSec: 0, 34 | playTime: this.getAllPlayTime(), 35 | }; 36 | } 37 | 38 | action = () => { 39 | const { isPlaying } = this.state; 40 | 41 | if (this.props.contentObj.mediaId || this.props.contentObj.appURI) { 42 | this.setState({ isPlaying: !isPlaying }, () => { 43 | if (this.state.isPlaying) { 44 | const uri = this.props.contentObj.mediaId ? this.props.contentObj.httpURL : this.props.contentObj.fileURI; 45 | this.props.startAudioPlay(uri, this.playBack.bind(this), this.removeListener.bind(this)); 46 | } else { 47 | this.props.stopAudioPlay(); 48 | } 49 | }); 50 | } 51 | } 52 | 53 | playBack = (e) => { 54 | this.setState({ 55 | currentPositionSec: e.current_position, 56 | currentDurationSec: e.duration, 57 | playTime: this.props.contentObj.mmss(Math.floor(e.duration) - Math.floor(e.current_position)), 58 | }); 59 | } 60 | 61 | getAllPlayTime = () => (this.props.contentObj.timeline ? this.props.contentObj.mmss(this.props.contentObj.timeline) : '00:00'); 62 | 63 | removeListener = () => { 64 | this.setState({ isPlaying: false }); 65 | } 66 | 67 | render() { 68 | const leftPosition = this.state.currentDurationSec && this.state.currentPositionSec ? this.state.currentPositionSec / this.state.currentDurationSec * 99 : 0; 69 | const styles = { ...stylesObj, ...this.props.contentAudioStyles }; 70 | const iconPlaying = this.props.icons.pause || require('../assets/icon-player-pause.png'); 71 | const iconNotPlaying = this.props.icons.playing || require('../assets/icon-player-play.png'); 72 | return ( 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | {this.state.playTime} 85 | 86 | 87 | 88 | ); 89 | } 90 | } 91 | 92 | ContentAudio.defaultProps = { 93 | contentAudioStyles: stylesObj, 94 | contentObj: null, 95 | isOwn: false, 96 | startAudioPlay: () => {}, 97 | stopAudioPlay: () => {}, 98 | icons: {}, 99 | }; 100 | ContentAudio.propTypes = { 101 | contentAudioStyles: PropTypes.object, 102 | contentObj: PropTypes.object, 103 | isOwn: PropTypes.bool, 104 | startAudioPlay: PropTypes.func, 105 | stopAudioPlay: PropTypes.func, 106 | icons: PropTypes.object, 107 | }; 108 | 109 | export default ContentAudio; 110 | -------------------------------------------------------------------------------- /src/models/Event.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is model for matrix event 5 | */ 6 | 7 | import getUid from 'get-uid'; 8 | import Utils from '../lib/utils'; 9 | import Content from './Content'; 10 | import ContentText from './ContentText'; 11 | import ContentImage from './ContentImage'; 12 | import ContentFile from './ContentFile'; 13 | import ContentAudio from './ContentAudio'; 14 | import EventTypes from '../consts/EventTypes'; 15 | import MsgTypes from '../consts/MsgTypes'; 16 | 17 | class Event { 18 | matrixEvent = null; 19 | 20 | contentObj = null; 21 | 22 | id = null; 23 | 24 | uid = null; 25 | 26 | type = EventTypes.mRoomMessage; 27 | 28 | createdDate = 0; 29 | 30 | constructor(matrixEvent, eventObj) { 31 | if (matrixEvent) { 32 | this.matrixEvent = matrixEvent; 33 | this.type = matrixEvent.getType(); 34 | this.uid = matrixEvent.getSender(); 35 | this.id = matrixEvent.getId(); 36 | const contentObj = matrixEvent.getContent(); 37 | this.setContent(contentObj); 38 | } else if (eventObj) { 39 | this.type = eventObj.type || EventTypes.mRoomMessage; 40 | this.uid = eventObj.userId; 41 | this.id = getUid(); 42 | this.createdDate = Utils.timestamp(true); 43 | this.setContent(eventObj.contentObj); 44 | } 45 | } 46 | 47 | get userId() { 48 | return this.uid; 49 | } 50 | 51 | get message() { 52 | if (!this.contentObj) { 53 | return ''; 54 | } 55 | return this.contentObj.message; 56 | } 57 | 58 | get messageOnly() { 59 | if (!this.contentObj) { 60 | return ''; 61 | } 62 | return this.contentObj.messageOnly; 63 | } 64 | 65 | get ts() { 66 | if (!this.matrixEvent) { 67 | return this.createdDate; 68 | } 69 | return this.matrixEvent.getTs(); 70 | } 71 | 72 | get content() { 73 | if (!this.contentObj) { 74 | return new Content(); 75 | } 76 | return this.contentObj; 77 | } 78 | 79 | get senderAvatarObj() { 80 | const noPhoto = require('../assets/nophoto.png'); 81 | if (!this.matrixEvent || !this.matrixEvent.sender || !this.matrixEvent.sender.events || !this.matrixEvent.sender.events.member || !this.matrixEvent.sender.events.member.event || !this.matrixEvent.sender.events.member.event.content || !this.matrixEvent.sender.events.member.event.content.avatar_url) { 82 | return { noPhoto }; 83 | } 84 | 85 | const { serverName, mediaId } = Utils.parseMXCURI(this.matrixEvent.sender.events.member.event.content.avatar_url); 86 | if (!serverName || !mediaId) { 87 | return { noPhoto }; 88 | } 89 | 90 | return { serverName, mediaId, noPhoto }; 91 | } 92 | 93 | get senderDisplayName() { 94 | if (!this.matrixEvent || !this.matrixEvent.sender) { 95 | return ''; 96 | } 97 | return this.matrixEvent.sender.rawDisplayName || this.matrixEvent.sender.name; 98 | } 99 | 100 | get matrixContentObj() { 101 | if (!this.contentObj) { 102 | return {}; 103 | } 104 | return this.contentObj.matrixContentObj; 105 | } 106 | 107 | get reactionContentObj() { 108 | return { 109 | 'm.relates_to': { 110 | rel_type: 'm.annotation', 111 | event_id: this.id, 112 | key: 'liked', 113 | }, 114 | }; 115 | } 116 | 117 | get msgtype() { 118 | return this.content.type; 119 | } 120 | 121 | get citationMessage() { 122 | return this.content.quoteText; 123 | } 124 | 125 | setContent(contentObj) { 126 | switch (this.type) { 127 | case EventTypes.mRoomMessage: 128 | switch (contentObj.msgtype) { 129 | case MsgTypes.mText: 130 | this.contentObj = new ContentText(contentObj); 131 | break; 132 | case MsgTypes.mImage: 133 | this.contentObj = new ContentImage(contentObj); 134 | break; 135 | case MsgTypes.mAudio: 136 | this.contentObj = new ContentAudio(contentObj); 137 | break; 138 | case MsgTypes.mFile: 139 | this.contentObj = new ContentFile(contentObj); 140 | break; 141 | default: 142 | this.contentObj = new Content(contentObj); 143 | break; 144 | } 145 | break; 146 | default: 147 | this.contentObj = new Content(); 148 | break; 149 | } 150 | } 151 | 152 | setMatrixEvent(matrixEvent) { 153 | this.matrixEvent = matrixEvent; 154 | this.id = matrixEvent.getId(); 155 | } 156 | 157 | static getEventObjText(userId, body, isQuote) { 158 | const obj = { userId, contentObj: ContentText.makeMessageObj(body, isQuote) }; 159 | return obj; 160 | } 161 | 162 | static getEventObjFile(userId, msgtype, filename, uri, mimetype, base64, size, duration) { 163 | const contentObj = ContentFile.makeMessageObj(msgtype, filename, uri, mimetype, base64, size, duration); 164 | const obj = { userId, contentObj }; 165 | return obj; 166 | } 167 | } 168 | 169 | export default Event; 170 | -------------------------------------------------------------------------------- /src/MatrixCreateGroupChat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is component that shows all rooms for current user 5 | */ 6 | 7 | import React, { Component } from 'react'; 8 | import { View, TextInput, Image, Text, StyleSheet, TouchableOpacity } from 'react-native'; 9 | import PropTypes from 'prop-types'; 10 | import fileUtils from './lib/fileUtils'; 11 | import Utils from './lib/utils'; 12 | import trans from './trans'; 13 | import Matrix from './Matrix'; 14 | 15 | const styles = StyleSheet.create({ 16 | containerImage: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', width: '100%', padding: 16 }, 17 | groupPhoto: { width: 40, height: 40, borderRadius: 20, marginRight: 10 }, 18 | titleInput: { width: '90%', margin: 16 }, 19 | containerContacts: { flex: 1 }, 20 | containerButton: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '100%', height: 100 }, 21 | button: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '90%', height: 40, borderRadius: 20, borderWidth: 0.5, borderColor: '#ccc' }, 22 | }); 23 | 24 | class MatrixCreateGroupChat extends Component { 25 | constructor(props) { 26 | super(props); 27 | trans.setLocale(this.props.locale); 28 | trans.setTransFromProps(this.props.trans); 29 | this.state = { 30 | imageObj: null, 31 | imageURI: '', 32 | title: '', 33 | userIdsToInvite: this.props.preselectedUserIds, 34 | }; 35 | } 36 | 37 | uploadImage = () => { 38 | fileUtils.uploadFile({ 39 | callback: (err, imageObj) => { 40 | if (!err) { 41 | this.setState({ imageObj, imageURI: imageObj.uri }); 42 | } 43 | }, 44 | returnBase64: true, 45 | trans: trans.t('fileModule'), 46 | }); 47 | } 48 | 49 | changeTitle = title => this.setState({ title }); 50 | 51 | changeContacts = userIdsToInvite => this.setState({ userIdsToInvite }); 52 | 53 | createRoom = async ({ defaultTitle }) => { 54 | const { userIdsToInvite, title, imageURI, imageObj } = this.state; 55 | if (!userIdsToInvite.length) { 56 | return { status: false, msg: 'usersNotSelected' }; 57 | } 58 | const roomTitle = !title ? defaultTitle : title; 59 | const res = await Matrix.createRoom(userIdsToInvite, roomTitle); 60 | if (!res.status) { 61 | return res; 62 | } 63 | if (imageURI) { 64 | Matrix.saveImageForRoom(res.data.room_id, imageObj); 65 | } 66 | return { status: true, roomId: res.data.room_id, roomTitle }; 67 | } 68 | 69 | renderGroupInfo = () => { 70 | const { title, imageURI } = this.state; 71 | if (this.props.renderGroupInfo) { 72 | return this.props.renderGroupInfo(title, imageURI, this.changeTitle.bind(this), this.uploadImage.bind(this)); 73 | } 74 | return ( 75 | 76 | 77 | 78 | {trans.t('createGroupChat', 'changeGroupImage')} 79 | 80 | this.changeTitle(val)} 87 | value={title} 88 | returnKeyType="done" 89 | /> 90 | 91 | ); 92 | } 93 | 94 | renderContacts = () => { 95 | const { userIdsToInvite } = this.state; 96 | if (this.props.renderContacts) { 97 | return this.props.renderContacts(userIdsToInvite, this.changeContacts.bind(this)); 98 | } 99 | return ( 100 | 101 | ); 102 | } 103 | 104 | renderActions = () => { 105 | if (this.props.renderActions) { 106 | return this.props.renderActions(this.createRoom.bind(this)); 107 | } 108 | return ( 109 | 110 | 111 | {trans.t('createGroupChat', 'buttonTitle')} 112 | 113 | 114 | ); 115 | } 116 | 117 | render() { 118 | return ( 119 | 120 | {this.renderGroupInfo()} 121 | {this.renderContacts()} 122 | {this.renderActions()} 123 | 124 | ); 125 | } 126 | } 127 | 128 | MatrixCreateGroupChat.defaultProps = { 129 | style: { flex: 1 }, 130 | trans: null, 131 | renderGroupInfo: null, 132 | renderContacts: null, 133 | renderActions: null, 134 | locale: 'en', 135 | preselectedUserIds: [], 136 | }; 137 | 138 | MatrixCreateGroupChat.propTypes = { 139 | style: PropTypes.object, 140 | trans: PropTypes.object, 141 | renderGroupInfo: PropTypes.func, 142 | renderContacts: PropTypes.func, 143 | renderActions: PropTypes.func, 144 | locale: PropTypes.string, 145 | preselectedUserIds: PropTypes.array, 146 | }; 147 | 148 | export default MatrixCreateGroupChat; 149 | -------------------------------------------------------------------------------- /src/MatrixChats.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is component that shows all rooms for current user 5 | */ 6 | 7 | import React, { Component } from 'react'; 8 | import { View, FlatList, TextInput } from 'react-native'; 9 | import { timer } from 'rxjs'; 10 | import PropTypes from 'prop-types'; 11 | import getUid from 'get-uid'; 12 | import Utils from './lib/utils'; 13 | import Matrix from './Matrix'; 14 | 15 | class MatrixChats extends Component { 16 | rooms = {}; 17 | 18 | userIdsDM = {}; 19 | 20 | constructor(props) { 21 | super(props); 22 | this.subscription = null; 23 | this.setData(); 24 | this.state = { 25 | searchText: '', 26 | alwaysNewValue: '', 27 | }; 28 | } 29 | 30 | async componentDidMount() { 31 | this.subscription = timer(1000).subscribe(() => Matrix.setTimelineChatsCallback(this.syncCallback)); 32 | const totalRooms = this.rooms ? Object.keys(this.rooms).length : null; 33 | await this.props.onLoaded({ userIdsDM: this.userIdsDM, totalRooms }); 34 | } 35 | 36 | shouldComponentUpdate(nextProps, nextState) { 37 | const shouldBeRefreshed = nextProps.shouldBeRefreshed && nextProps.shouldBeRefreshed !== this.props.shouldBeRefreshed; 38 | if (shouldBeRefreshed) { 39 | this.setData(); 40 | } 41 | return shouldBeRefreshed || (this.state.searchText !== nextState.searchText) || (this.state.alwaysNewValue !== nextState.alwaysNewValue); 42 | } 43 | 44 | componentWillUnmount() { 45 | Matrix.removeTimelineChatsCallback(); 46 | if (this.subscription && this.subscription.unsubscribe) { 47 | this.subscription.unsubscribe(); 48 | } 49 | } 50 | 51 | setData = () => { 52 | const obj = Matrix.getRoomsForChatsList(); 53 | this.rooms = obj.rooms; 54 | this.userIdsDM = obj.userIdsDM; 55 | } 56 | 57 | syncCallback = (event, matrixRoom) => { 58 | if (matrixRoom && matrixRoom.roomId) { 59 | const room = Matrix.getRoom({ matrixRoom }); 60 | this.rooms[matrixRoom.roomId] = room; 61 | this.refreshList(); 62 | } 63 | } 64 | 65 | refreshList = () => { 66 | if (this.props.isShown()) { 67 | this.setState({ alwaysNewValue: getUid() }); 68 | } 69 | } 70 | 71 | searchingChats = (searchText) => { 72 | this.setState({ searchText }); 73 | } 74 | 75 | acceptInvite = async (roomId) => { 76 | if (roomId) { 77 | const matrixRoom = await Matrix.joinRoom(roomId); 78 | if (matrixRoom) { 79 | this.syncCallback(matrixRoom); 80 | return true; 81 | } 82 | } 83 | return false; 84 | } 85 | 86 | declineInvite = async (roomId) => { 87 | if (roomId) { 88 | const isExited = await Matrix.exitFromRoom(roomId); 89 | if (isExited) { 90 | delete this.rooms[roomId]; 91 | this.refreshList(); 92 | return true; 93 | } 94 | } 95 | return false; 96 | } 97 | 98 | renderItem = (obj, i) => { 99 | if (this.state.searchText && !obj.item.isFound(this.state.searchText)) { 100 | return null; 101 | } 102 | 103 | if (this.props.renderItem) { 104 | return this.props.renderItem(obj.item, i, this.acceptInvite, this.declineInvite); 105 | } 106 | return ( 107 | 108 | ); 109 | } 110 | 111 | renderSearch = () => { 112 | if (this.props.renderSearch) { 113 | return this.props.renderSearch(this.searchingChats); 114 | } 115 | return ( 116 | this.searchingChats(searchText)} 123 | value={this.state.searchText} 124 | returnKeyType="done" 125 | {...Utils.testProps('inputSearch')} 126 | /> 127 | ); 128 | } 129 | 130 | renderEmptyList = () => { 131 | if (this.props.renderEmptyList) { 132 | return this.props.renderEmptyList(); 133 | } 134 | return ; 135 | } 136 | 137 | keyExtractor = (room, index) => index.toString(); 138 | 139 | render() { 140 | const items = Object.values(this.rooms); 141 | items.sort((room1, room2) => room1.lastActiveEventTimestamp < room2.lastActiveEventTimestamp || room2.isInvite); 142 | if (!items.length) { 143 | this.renderEmptyList(); 144 | } 145 | return ( 146 | 147 | {this.renderSearch()} 148 | 154 | 155 | ); 156 | } 157 | } 158 | 159 | MatrixChats.defaultProps = { 160 | style: { flex: 1 }, 161 | styleSearchInput: { width: 200, margin: 10 }, 162 | onLoaded: () => { }, 163 | renderItem: null, 164 | renderSearch: null, 165 | renderEmptyList: null, 166 | shouldBeRefreshed: '', 167 | isShown: () => true, 168 | }; 169 | 170 | MatrixChats.propTypes = { 171 | style: PropTypes.object, 172 | styleSearchInput: PropTypes.object, 173 | onLoaded: PropTypes.func, 174 | renderItem: PropTypes.func, 175 | renderSearch: PropTypes.func, 176 | renderEmptyList: PropTypes.func, 177 | shouldBeRefreshed: PropTypes.string, 178 | isShown: PropTypes.func, 179 | }; 180 | 181 | export default MatrixChats; 182 | -------------------------------------------------------------------------------- /src/components/EventsContainer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is container for events in a chat 5 | */ 6 | 7 | import React, { Component } from 'react'; 8 | import PropTypes from 'prop-types'; 9 | import { FlatList, View, StyleSheet, ActivityIndicator, Image, Text, TouchableOpacity } from 'react-native'; 10 | import Event from './Event'; 11 | import InViewPort from './InViewPort'; 12 | import Utils from '../lib/utils'; 13 | import Colors from '../lib/colors'; 14 | import Matrix from '../Matrix'; 15 | import trans from '../trans'; 16 | 17 | const styles = StyleSheet.create({ 18 | container: { flex: 1, paddingBottom: 16 }, 19 | contentContainerStyle: { flexGrow: 1, justifyContent: 'flex-start' }, 20 | loadEarlyContainer: { justifyContent: 'center', alignItems: 'center', marginTop: 10, marginBottom: 10 }, 21 | containerQuote: { width: '100%', backgroundColor: Colors.grey, paddingLeft: 10, paddingTop: 10, paddingBottom: 10, borderLeftWidth: 5, borderColor: Colors.blue, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }, 22 | containerQuoteInner: {}, 23 | quoteTextAuthor: { fontSize: 12, color: Colors.blue }, 24 | quoteText: { fontSize: 12, color: Colors.greyDark }, 25 | quoteCancelButton: { height: 36, width: 36, alignItems: 'center', justifyContent: 'center' }, 26 | iconCloseCitation: { height: 22, width: 22 }, 27 | }); 28 | 29 | class EventsContainer extends Component { 30 | constructor(props) { 31 | super(props); 32 | this.loading = false; 33 | this.state = { loadMore: true, isQuote: false, quoteMessage: '', quoteAuthor: '' }; 34 | this.flatListRef = React.createRef(); 35 | } 36 | 37 | getPropsStyle = (style) => { 38 | if (Object.prototype.hasOwnProperty.call(this.props.eventsStyles, style)) { 39 | return this.props.eventsStyles[style]; 40 | } 41 | return null; 42 | } 43 | 44 | scrollToBottom = (options) => { 45 | if (!options) { 46 | options = { animated: true }; 47 | } 48 | if (this.flatListRef && this.flatListRef.current && options) { 49 | this.flatListRef.current.scrollToOffset({ offset: 0, ...options }); 50 | } 51 | } 52 | 53 | addCitation = (quoteMessageToSend, quoteMessage, quoteAuthor) => { 54 | this.props.addCitation(quoteMessageToSend, quoteMessage, quoteAuthor); 55 | this.setState({ isQuote: true, quoteMessage, quoteAuthor }); 56 | } 57 | 58 | cancelCitation = () => { 59 | this.props.cancelCitation(); 60 | this.setState({ isQuote: false }); 61 | } 62 | 63 | messageSent = () => { 64 | this.setState({ isQuote: false }); 65 | } 66 | 67 | renderEvent = ({ item, index }) => { 68 | const { events, eventProps } = this.props; 69 | const prevEvent = index + 1 < events.length ? events[index + 1] : null; 70 | const event = item; 71 | const props = { 72 | ...eventProps, 73 | event, 74 | roomId: this.props.roomId, 75 | isOwn: Matrix.getIsOwn(event.userId), 76 | isNewDay: !prevEvent || (prevEvent && Utils.isNewDay(event.ts, prevEvent.ts)), 77 | isPrevUserTheSame: prevEvent && prevEvent.userId === event.userId, 78 | startAudioPlay: this.props.startAudioPlay, 79 | stopAudioPlay: this.props.stopAudioPlay, 80 | reactedEventIds: this.props.reactedEventIds, 81 | addCitation: this.addCitation, 82 | trans: this.props.trans, 83 | icons: this.props.icons, 84 | }; 85 | if (this.props.renderEvent) { 86 | return this.props.renderEvent(props); 87 | } 88 | return ; 89 | }; 90 | 91 | keyExtractor = item => `${item.id}`; 92 | 93 | loadEarlierMessages = async (isVisible) => { 94 | if (isVisible && !this.loading && this.state.loadMore) { 95 | this.loading = true; 96 | this.props.loadEarlyMessages().then((res) => { 97 | this.loading = false; 98 | if (!res) { 99 | this.setState({ loadMore: false }); 100 | } 101 | }).catch(() => { 102 | this.loading = false; 103 | this.setState({ loadMore: false }); 104 | }); 105 | } 106 | } 107 | 108 | renderHeader = () => { 109 | if (!this.state.loadMore) { 110 | return null; 111 | } 112 | return ( 113 | this.loadEarlierMessages(isVisible)} active={this.state.loadMore} style={styles.loadEarlyContainer}> 114 | 115 | 116 | ); 117 | } 118 | 119 | renderFooter = () => { 120 | const { isQuote, quoteAuthor, quoteMessage } = this.state; 121 | 122 | if (this.props.renderQuote) { 123 | return this.props.renderQuote(isQuote, quoteAuthor, quoteMessage, this.cancelCitation); 124 | } 125 | 126 | if (!isQuote) { 127 | return null; 128 | } 129 | 130 | return ( 131 | 132 | 133 | {quoteAuthor} 134 | {quoteMessage} 135 | 136 | this.cancelCitation()} {...Utils.testProps('btnCloseQuote')}> 137 | 138 | 139 | 140 | ); 141 | } 142 | 143 | render() { 144 | if (!this.props.events || (this.props.events && this.props.events.length === 0)) { 145 | return ; 146 | } 147 | return ( 148 | 149 | 160 | 161 | ); 162 | } 163 | } 164 | EventsContainer.defaultProps = { 165 | trans, 166 | icons: {}, 167 | eventsStyles: {}, 168 | events: [], 169 | reactedEventIds: [], 170 | renderEvent: null, 171 | renderQuote: null, 172 | eventProps: {}, 173 | roomId: '', 174 | startAudioPlay: () => {}, 175 | stopAudioPlay: () => {}, 176 | addCitation: () => {}, 177 | cancelCitation: () => {}, 178 | loadEarlyMessages: () => {}, 179 | }; 180 | EventsContainer.propTypes = { 181 | trans: PropTypes.object, 182 | icons: PropTypes.object, 183 | eventsStyles: PropTypes.object, 184 | events: PropTypes.arrayOf(PropTypes.object), 185 | reactedEventIds: PropTypes.arrayOf(PropTypes.string), 186 | renderEvent: PropTypes.func, 187 | renderQuote: PropTypes.func, 188 | eventProps: PropTypes.object, 189 | roomId: PropTypes.string, 190 | startAudioPlay: PropTypes.func, 191 | stopAudioPlay: PropTypes.func, 192 | addCitation: PropTypes.func, 193 | cancelCitation: PropTypes.func, 194 | loadEarlyMessages: PropTypes.func, 195 | }; 196 | 197 | export default EventsContainer; 198 | -------------------------------------------------------------------------------- /src/lib/fileUtils.js: -------------------------------------------------------------------------------- 1 | import { Platform } from 'react-native'; 2 | import ImagePicker from 'react-native-image-picker'; 3 | import DocumentPicker from 'react-native-document-picker'; 4 | import ImageResizer from 'react-native-image-resizer'; 5 | import ImgToBase64 from 'react-native-image-base64'; 6 | import RNFetchBlob from 'rn-fetch-blob'; 7 | import trans from '../trans'; 8 | 9 | const FileUtils = { 10 | resizeImage: (response, callback, resizeX, resizeY, quality) => { 11 | if (response.uri) { 12 | resizeY = response.height * (resizeX / response.width); 13 | ImageResizer.createResizedImage(response.uri, resizeX, resizeY, 'JPEG', quality) 14 | .then((res) => { 15 | const obj = { uri: res.uri, filename: res.name, type: 'image/jpeg', size: res.size }; 16 | FileUtils.getBase64String(res.uri).then((base64String) => { 17 | obj.base64 = base64String; 18 | callback(null, obj); 19 | }).catch(err => callback(err.msg, null)); 20 | }) 21 | .catch(err => callback(err.msg, null)); 22 | } else { 23 | callback('noURI', null); 24 | } 25 | }, 26 | 27 | getFileFromCamera: (callback, setLoadingState, resizeX, resizeY, quality) => { 28 | ImagePicker.launchCamera({ mediaType: 'photo', storageOptions: { skipBackup: true, path: 'files' } }, (response) => { 29 | if (response.didCancel) { 30 | setLoadingState(false); 31 | } else if (response.error) { 32 | callback(response.error, null); 33 | } else { 34 | FileUtils.resizeImage(response, callback, resizeX, resizeY, quality); 35 | } 36 | }); 37 | }, 38 | 39 | getFileFromGallery: (callback, setLoadingState, resizeX, resizeY, quality, transObj) => { 40 | const options = { 41 | title: transObj.textSelectDocument, 42 | cancelButtonTitle: transObj.textCancelButtonTitle, 43 | takePhotoButtonTitle: transObj.textTakePhotoButtonTitle, 44 | chooseFromLibraryButtonTitle: transObj.textChooseFromLibraryButtonTitle, 45 | mediaType: 'photo', 46 | storageOptions: { 47 | skipBackup: true, 48 | path: 'files', 49 | }, 50 | }; 51 | ImagePicker.launchImageLibrary(options, (response) => { 52 | if (response.didCancel) { 53 | setLoadingState(false); 54 | } else if (response.error) { 55 | callback(response.error, null); 56 | } else { 57 | FileUtils.resizeImage(response, callback, resizeX, resizeY, quality); 58 | } 59 | }); 60 | }, 61 | 62 | getPDFFile: (callback, setLoadingState) => { 63 | setLoadingState(false); 64 | DocumentPicker.pick({ type: [DocumentPicker.types.pdf] }).then((res) => { 65 | const obj = { uri: res.uri, filename: res.name, type: res.type, size: res.size }; 66 | FileUtils.getBase64String(res.uri).then((base64String) => { 67 | obj.base64 = base64String; 68 | callback(null, obj); 69 | }).catch(err => callback(err.msg, null)); 70 | }).catch((error) => { 71 | callback(error, null); 72 | }); 73 | }, 74 | 75 | uploadFile: ({ callback, setLoadingState, resizeX, resizeY, quality, returnBase64, transObj, showUploadPDF }) => { 76 | if (!transObj) { 77 | transObj = trans.t('fileModule'); 78 | } 79 | resizeX = resizeX || 500; 80 | resizeY = resizeY || 500; 81 | quality = quality || 80; 82 | if (!setLoadingState) { 83 | setLoadingState = () => {}; 84 | } 85 | 86 | const options = { 87 | title: transObj.textSelectDocument, 88 | cancelButtonTitle: transObj.textCancelButtonTitle, 89 | takePhotoButtonTitle: transObj.textTakePhotoButtonTitle, 90 | chooseFromLibraryButtonTitle: transObj.textChooseFromLibraryButtonTitle, 91 | mediaType: 'photo', 92 | storageOptions: { 93 | skipBackup: true, 94 | path: 'files', 95 | }, 96 | }; 97 | if (showUploadPDF) { 98 | options.customButtons = [{ name: 'pdffile', title: transObj.textUploadPDF }]; 99 | } 100 | ImagePicker.showImagePicker(options, (response) => { 101 | if (response.didCancel) { 102 | setLoadingState(false); 103 | } else if (response.error) { 104 | callback(response.error, null); 105 | } else if (response.customButton) { 106 | setLoadingState(false); 107 | DocumentPicker.pick({ type: [DocumentPicker.types.pdf] }).then((res) => { 108 | const obj = { uri: res.uri, filename: res.name, type: res.type, size: res.size }; 109 | if (returnBase64) { 110 | FileUtils.getBase64String(res.uri).then((base64String) => { 111 | obj.base64 = base64String; 112 | callback(null, obj); 113 | }).catch(err => callback(err.msg, null)); 114 | } else { 115 | callback(null, obj); 116 | } 117 | }).catch((error) => { 118 | callback(error, null); 119 | }); 120 | } else { 121 | resizeY = response.height * (resizeX / response.width); 122 | ImageResizer.createResizedImage(response.uri, resizeX, resizeY, 'JPEG', quality) 123 | .then((res) => { 124 | const obj = { uri: res.uri, filename: res.name, type: 'image/jpeg', size: res.size }; 125 | if (returnBase64) { 126 | FileUtils.getBase64String(res.uri).then((base64String) => { 127 | obj.base64 = base64String; 128 | callback(null, obj); 129 | }).catch(err => callback(err.msg, null)); 130 | } else { 131 | callback(null, obj); 132 | } 133 | }) 134 | .catch(err => callback(err.msg, null)); 135 | } 136 | }); 137 | }, 138 | 139 | formatBytes: (bytes, decimals = 0) => { 140 | if (bytes === 0) return '0 Bytes'; 141 | 142 | const k = 1024; 143 | const dm = decimals < 0 ? 0 : decimals; 144 | const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; 145 | 146 | const i = Math.floor(Math.log(bytes) / Math.log(k)); 147 | 148 | // eslint-disable-next-line 149 | return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`; 150 | }, 151 | 152 | formatFileMimeType: (mimetype) => { 153 | let ret = ''; 154 | switch (mimetype) { 155 | case 'application/pdf': 156 | ret = 'PDF'; 157 | break; 158 | default: 159 | ret = 'FILE'; 160 | } 161 | return ret; 162 | }, 163 | 164 | readFile: (filePath, type) => { 165 | type = type || 'base64'; 166 | return RNFetchBlob.fs.readFile(filePath, type).then(data => data).catch(e => e); 167 | }, 168 | 169 | getFileInfo: filePath => RNFetchBlob.fs.stat(filePath).then(data => data).catch(e => e), 170 | 171 | saveFile: (filename, source, type) => { 172 | type = type || 'base64'; 173 | const filePath = `${RNFetchBlob.fs.dirs.CacheDir}/${filename}`; 174 | return RNFetchBlob.fs.writeFile(filePath, source, type).then(() => filePath).catch(() => ''); 175 | }, 176 | 177 | getBase64String: (uri) => { 178 | if (Platform.OS === 'ios') { 179 | return ImgToBase64.getBase64String(uri).then(data => data).catch(e => e); 180 | } 181 | return FileUtils.readFile(uri); 182 | }, 183 | }; 184 | 185 | export default FileUtils; 186 | -------------------------------------------------------------------------------- /src/MatrixEditGroupChat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is component that allows you to edit the group data 5 | */ 6 | 7 | import React, { Component } from 'react'; 8 | import { View, TextInput, Image, Text, StyleSheet, TouchableOpacity, Dimensions } from 'react-native'; 9 | import PropTypes from 'prop-types'; 10 | import fileUtils from './lib/fileUtils'; 11 | import Utils from './lib/utils'; 12 | import trans from './trans'; 13 | import Matrix from './Matrix'; 14 | import LeftX from './components/LeftX'; 15 | 16 | const styles = StyleSheet.create({ 17 | containerImage: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', width: '100%', padding: 16 }, 18 | groupPhoto: { width: 40, height: 40, borderRadius: 20, marginRight: 10 }, 19 | titleInput: { width: '90%', margin: 16 }, 20 | containerContacts: { top: 0, left: Dimensions.get('window').width, width: '100%' }, 21 | containerMembers: { height: 200 }, 22 | containerExitButton: { flex: 1, paddingTop: 20 }, 23 | containerButton: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '100%', height: 100 }, 24 | buttonExit: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '100%', height: 40, borderTopWidth: 1, borderBottomWidth: 1, borderColor: '#ccc' }, 25 | button: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '90%', height: 40, borderRadius: 20, borderWidth: 0.5, borderColor: '#ccc' }, 26 | }); 27 | 28 | class MatrixEditGroupChat extends Component { 29 | constructor(props) { 30 | super(props); 31 | trans.setLocale(this.props.locale); 32 | trans.setTransFromProps(this.props.trans); 33 | this.room = this.props.room; 34 | if (!this.room && this.props.roomId) { 35 | this.room = Matrix.getRoom({ roomId: this.props.roomId }); 36 | } 37 | this.state = { 38 | imageObj: null, 39 | imageURI: this.room.avatar, 40 | title: this.room ? this.room.title : '', 41 | members: this.room ? this.room.allMembers : {}, 42 | }; 43 | } 44 | 45 | uploadImage = () => { 46 | fileUtils.uploadFile({ 47 | callback: (err, imageObj) => { 48 | if (!err) { 49 | this.setState({ imageObj, imageURI: imageObj.uri }); 50 | } 51 | }, 52 | returnBase64: true, 53 | trans: trans.t('fileModule'), 54 | }); 55 | } 56 | 57 | changeTitle = title => this.setState({ title }); 58 | 59 | changeRoom = async () => { 60 | const { title, imageObj } = this.state; 61 | let isUpdated = false; 62 | if (this.room.title !== title) { 63 | Matrix.changeRoomTitle(this.room.id, title); 64 | isUpdated = true; 65 | } 66 | if (imageObj) { 67 | Matrix.saveImageForRoom(this.room.id, imageObj); 68 | isUpdated = true; 69 | } 70 | if (isUpdated) { 71 | this.room.recalculate(); 72 | } 73 | return title; 74 | } 75 | 76 | // return true if you leave room 77 | exitRoom = async () => { 78 | const res = await Matrix.exitFromRoom(this.room.id); 79 | return res.status; 80 | } 81 | 82 | addContacts = async (matrixUserIds) => { 83 | const status = await Matrix.inviteNewMembers(this.room.id, matrixUserIds); 84 | if (status) { 85 | this.room.recalculate(); 86 | } 87 | } 88 | 89 | renderGroupInfo = () => { 90 | const { title, imageURI } = this.state; 91 | if (this.props.renderGroupInfo) { 92 | return this.props.renderGroupInfo(title, imageURI, this.changeTitle.bind(this), this.uploadImage.bind(this)); 93 | } 94 | return ( 95 | 96 | 97 | 98 | {trans.t('editGroupChat', 'changeGroupImage')} 99 | 100 | this.changeTitle(val)} 107 | value={title} 108 | returnKeyType="done" 109 | /> 110 | 111 | ); 112 | } 113 | 114 | renderMembers = () => { 115 | if (this.props.renderMembers) { 116 | return this.props.renderMembers(this.state.members); 117 | } 118 | return ( 119 | 120 | ); 121 | } 122 | 123 | renderContacts = () => ( 124 | 125 | ) 126 | 127 | renderExitRoom = () => { 128 | if (this.props.renderExitRoom) { 129 | return this.props.renderExitRoom(this.exitRoom.bind(this)); 130 | } 131 | return ( 132 | 133 | 134 | {trans.t('editGroupChat', 'buttonTitle')} 135 | 136 | 137 | ); 138 | } 139 | 140 | renderActions = () => { 141 | if (this.props.renderActions) { 142 | return this.props.renderActions(this.changeRoom.bind(this)); 143 | } 144 | return ( 145 | 146 | 147 | {trans.t('editGroupChat', 'buttonLeave')} 148 | 149 | 150 | ); 151 | } 152 | 153 | renderContactsContainer = () => { 154 | if (this.props.renderContactsContainer) { 155 | return this.props.renderContactsContainer(this.state.members, this.addContacts.bind(this)); 156 | } 157 | return ( 158 | 159 | {this.renderContacts()} 160 | 161 | ); 162 | } 163 | 164 | render() { 165 | if (this.props.render) { 166 | return this.props.render(this.renderGroupInfo.bind(this), this.renderContacts.bind(this), this.renderExitRoom.bind(this), this.renderActions.bind(this)); 167 | } 168 | return ( 169 | 170 | 171 | {this.renderGroupInfo()} 172 | {this.renderMembers()} 173 | {this.renderExitRoom()} 174 | 175 | {this.renderActions()} 176 | {this.renderContactsContainer()} 177 | 178 | ); 179 | } 180 | } 181 | 182 | MatrixEditGroupChat.defaultProps = { 183 | style: { flex: 1, position: 'relative' }, 184 | styleContent: {}, 185 | trans: null, 186 | render: null, 187 | renderGroupInfo: null, 188 | renderContactsContainer: null, 189 | renderActions: null, 190 | renderExitRoom: null, 191 | renderMembers: null, 192 | locale: 'en', 193 | roomId: null, 194 | room: null, 195 | }; 196 | 197 | MatrixEditGroupChat.propTypes = { 198 | style: PropTypes.object, 199 | styleContent: PropTypes.object, 200 | trans: PropTypes.object, 201 | render: PropTypes.func, 202 | renderGroupInfo: PropTypes.func, 203 | renderContactsContainer: PropTypes.func, 204 | renderActions: PropTypes.func, 205 | renderExitRoom: PropTypes.func, 206 | renderMembers: PropTypes.func, 207 | locale: PropTypes.string, 208 | roomId: PropTypes.string, 209 | room: PropTypes.object, 210 | }; 211 | 212 | export default MatrixEditGroupChat; 213 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. 4 | 5 | ## Development workflow 6 | 7 | To get started with the project, run `yarn bootstrap` in the root directory to install the required dependencies for each package: 8 | 9 | ```sh 10 | yarn bootstrap 11 | ``` 12 | 13 | While developing, you can run the [example app](/example/) to test your changes. 14 | 15 | To start the packager: 16 | 17 | ```sh 18 | yarn example start 19 | ``` 20 | 21 | To run the example app on Android: 22 | 23 | ```sh 24 | yarn example android 25 | ``` 26 | 27 | To run the example app on iOS: 28 | 29 | ```sh 30 | yarn example ios 31 | ``` 32 | 33 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 34 | 35 | ```sh 36 | yarn typescript 37 | yarn lint 38 | ``` 39 | 40 | To fix formatting errors, run the following: 41 | 42 | ```sh 43 | yarn lint --fix 44 | ``` 45 | 46 | Remember to add tests for your change if possible. Run the unit tests by: 47 | 48 | ```sh 49 | yarn test 50 | ``` 51 | 52 | To edit the Objective-C files, open `example/ios/MatrixExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-matrix`. 53 | 54 | To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativematrix` under `Android`. 55 | 56 | ### Commit message convention 57 | 58 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 59 | 60 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 61 | - `feat`: new features, e.g. add new method to the module. 62 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 63 | - `docs`: changes into documentation, e.g. add usage example for the module.. 64 | - `test`: adding or updating tests, eg add integration tests using detox. 65 | - `chore`: tooling changes, e.g. change CI config. 66 | 67 | Our pre-commit hooks verify that your commit message matches this format when committing. 68 | 69 | ### Linting and tests 70 | 71 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 72 | 73 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. 74 | 75 | Our pre-commit hooks verify that the linter and tests pass when committing. 76 | 77 | ### Scripts 78 | 79 | The `package.json` file contains various scripts for common tasks: 80 | 81 | - `yarn bootstrap`: setup project by installing all dependencies and pods. 82 | - `yarn typescript`: type-check files with TypeScript. 83 | - `yarn lint`: lint files with ESLint. 84 | - `yarn test`: run unit tests with Jest. 85 | - `yarn example start`: start the Metro server for the example app. 86 | - `yarn example android`: run the example app on Android. 87 | - `yarn example ios`: run the example app on iOS. 88 | 89 | ### Sending a pull request 90 | 91 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github). 92 | 93 | When you're sending a pull request: 94 | 95 | - Prefer small pull requests focused on one change. 96 | - Verify that linters and tests are passing. 97 | - Review the documentation to make sure it looks good. 98 | - Follow the pull request template when opening a pull request. 99 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 100 | 101 | ## Code of Conduct 102 | 103 | ### Our Pledge 104 | 105 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 106 | 107 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 108 | 109 | ### Our Standards 110 | 111 | Examples of behavior that contributes to a positive environment for our community include: 112 | 113 | - Demonstrating empathy and kindness toward other people 114 | - Being respectful of differing opinions, viewpoints, and experiences 115 | - Giving and gracefully accepting constructive feedback 116 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 117 | - Focusing on what is best not just for us as individuals, but for the overall community 118 | 119 | Examples of unacceptable behavior include: 120 | 121 | - The use of sexualized language or imagery, and sexual attention or 122 | advances of any kind 123 | - Trolling, insulting or derogatory comments, and personal or political attacks 124 | - Public or private harassment 125 | - Publishing others' private information, such as a physical or email 126 | address, without their explicit permission 127 | - Other conduct which could reasonably be considered inappropriate in a 128 | professional setting 129 | 130 | ### Enforcement Responsibilities 131 | 132 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 133 | 134 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 135 | 136 | ### Scope 137 | 138 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 139 | 140 | ### Enforcement 141 | 142 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. 143 | 144 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 145 | 146 | ### Enforcement Guidelines 147 | 148 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 149 | 150 | #### 1. Correction 151 | 152 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 153 | 154 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 155 | 156 | #### 2. Warning 157 | 158 | **Community Impact**: A violation through a single incident or series of actions. 159 | 160 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 161 | 162 | #### 3. Temporary Ban 163 | 164 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 165 | 166 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 167 | 168 | #### 4. Permanent Ban 169 | 170 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 171 | 172 | **Consequence**: A permanent ban from any sort of public interaction within the community. 173 | 174 | ### Attribution 175 | 176 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 177 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 178 | 179 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 180 | 181 | [homepage]: https://www.contributor-covenant.org 182 | 183 | For answers to common questions about this code of conduct, see the FAQ at 184 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 185 | -------------------------------------------------------------------------------- /src/Matrix.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is a library for Matrix logic 5 | */ 6 | import './lib/poly.js'; 7 | import * as sdk from 'matrix-js-sdk'; 8 | import api from './api'; 9 | import Room from './models/Room'; 10 | import Event from './models/Event'; 11 | import EventTypes from './consts/EventTypes'; 12 | import MsgTypes from './consts/MsgTypes'; 13 | 14 | class Matrix { 15 | static instance; 16 | 17 | client = null; 18 | 19 | timelineChatsCallback = null; 20 | 21 | timelineChatCallback = null; 22 | 23 | totalUnreadPrev = null; 24 | 25 | static getInstance() { 26 | if (!Matrix.instance) { 27 | Matrix.instance = new Matrix(); 28 | } 29 | return Matrix.instance; 30 | } 31 | 32 | get userId() { 33 | if (this.client) { 34 | return this.client.getUserId(); 35 | } 36 | return ''; 37 | } 38 | 39 | get totalUnread() { 40 | let totalUnread = 0; 41 | if (this.client) { 42 | const matrixRooms = this.client.getVisibleRooms(); 43 | matrixRooms.forEach((matrixRoom) => { 44 | const roomUnreadCount = matrixRoom.getUnreadNotificationCount() || 0; 45 | totalUnread += roomUnreadCount; 46 | }); 47 | } 48 | this.totalUnreadPrev = totalUnread; 49 | return totalUnread; 50 | } 51 | 52 | get totalRooms() { 53 | if (this.client) { 54 | const matrixRooms = this.client.getVisibleRooms(); 55 | return matrixRooms.length; 56 | } 57 | return 0; 58 | } 59 | 60 | get isClientRunning() { 61 | if (this.client) { 62 | return this.client.clientRunning; 63 | } 64 | return false; 65 | } 66 | 67 | initClient({ baseUrl, accessToken, userId, displayName }) { 68 | this.client = sdk.createClient({ baseUrl, accessToken, userId }); 69 | api.auth.setBaseURL(baseUrl); 70 | api.auth.setAccessToken(accessToken); 71 | // this.updateDisplayName(displayName); 72 | } 73 | 74 | async startClient(syncTime) { 75 | this.client.on('Room.timeline', (event, room, toStartOfTimeline) => { 76 | if (this.timelineChatsCallback) { 77 | this.timelineChatsCallback(event, room, toStartOfTimeline); 78 | } 79 | if (this.timelineChatCallback) { 80 | this.timelineChatCallback(event, room, toStartOfTimeline); 81 | } 82 | }); 83 | // this.client.on('sync', (state, prevState, data) => { 84 | // if (state === 'SYNCING' && data.nextSyncToken !== data.oldSyncToken) { 85 | // // console.log(data.nextSyncToken, data.oldSyncToken) 86 | // } 87 | // }); 88 | // this.client.startClient({ initialSyncLimit: syncTime }); 89 | await this.client.startClient({ initialSyncLimit: syncTime || 4, pollTimeout: 10 }); 90 | } 91 | 92 | stopClient() { 93 | this.removeSyncCallbacks(); 94 | this.client.stopClient(); 95 | api.auth.removeAccessToken(); 96 | } 97 | 98 | setTimelineChatsCallback = syncCallback => this.timelineChatsCallback = syncCallback; 99 | 100 | setTimelineChatCallback = syncCallback => this.timelineChatCallback = syncCallback; 101 | 102 | removeTimelineChatsCallback = () => this.setTimelineChatsCallback(null); 103 | 104 | removeTimelineChatCallback = () => this.setTimelineChatCallback(null); 105 | 106 | removeSyncCallbacks = () => { 107 | this.removeTimelineChatsCallback(); 108 | this.removeTimelineChatCallback(null); 109 | } 110 | 111 | // get unread count of all messages from all rooms and also save each room's unread to store of matrix-js-sdk 112 | setUnreadCount() { 113 | if (this.client) { 114 | const matrixRooms = this.client.getVisibleRooms(); 115 | matrixRooms.map((matrixRoom) => { 116 | const roomUnreadCount = matrixRoom.getUnreadNotificationCount(); 117 | if (typeof roomUnreadCount !== 'number') { 118 | const lastReadEventId = matrixRoom.getEventReadUpTo(this.userId); 119 | let numberUnread = 0; 120 | const timeline = matrixRoom.getLiveTimeline(); 121 | const matrixEvents = timeline.getEvents(); 122 | let foundLastRead = false; 123 | matrixEvents.map((matrixEvent) => { 124 | if (Room.isEventPermitted(matrixEvent)) { 125 | if (!foundLastRead && matrixEvent.getId() === lastReadEventId) { 126 | foundLastRead = true; 127 | numberUnread = 0; 128 | } else { 129 | numberUnread += 1; 130 | } 131 | } 132 | }); 133 | matrixRoom.setUnreadNotificationCount('total', numberUnread); 134 | } 135 | }); 136 | } 137 | } 138 | 139 | getRoomsForChatsList() { 140 | if (this.client) { 141 | const arr = this.client.getVisibleRooms(); 142 | const rooms = {}; 143 | const userIdsDM = {}; 144 | arr.forEach((matrixRoom) => { 145 | const room = new Room({ matrixRoom, myUserId: this.userId, client: this.client }); 146 | rooms[matrixRoom.roomId] = room; 147 | if (room.isDirect) { 148 | userIdsDM[room.dmUserId] = room.id; 149 | } 150 | }); 151 | return { rooms, userIdsDM }; 152 | } 153 | return { rooms: {}, userIdsDM: {} }; 154 | } 155 | 156 | getRoom({ roomId, matrixRoom, possibleEventsTypes, possibleContentTypes }) { 157 | if (!matrixRoom && roomId) { 158 | matrixRoom = this.getMatrixRoom(roomId); 159 | } 160 | if (matrixRoom) { 161 | const room = new Room({ matrixRoom, possibleEventsTypes, possibleContentTypes, myUserId: this.userId }); 162 | return room; 163 | } 164 | return null; 165 | } 166 | 167 | getMatrixRoom(roomId) { 168 | return this.client.getRoom(roomId); 169 | } 170 | 171 | getIsOwn(userId) { 172 | return this.userId === userId; 173 | } 174 | 175 | async createRoom(inviteIds, name, isDirect, preset) { 176 | isDirect = isDirect || false; 177 | preset = preset || 'private_chat'; 178 | const options = { invite: inviteIds, preset, is_direct: isDirect }; 179 | if (name) { 180 | options.name = name; 181 | } 182 | const res = await api.room.create(options); 183 | return res; 184 | } 185 | 186 | async updateDisplayName(displayName) { 187 | if (displayName) { 188 | const res = await api.profile.updateDisplayName(this.userId, displayName); 189 | return res; 190 | } 191 | return { status: false }; 192 | } 193 | 194 | async sendMessage(roomId, contentObj, callback) { 195 | if (roomId) { 196 | return this.client.sendMessage(roomId, contentObj, callback); 197 | } 198 | return null; 199 | } 200 | 201 | async sendEvent(roomId, eventType, contentObj, callback) { 202 | if (roomId) { 203 | return this.client.sendEvent(roomId, eventType, contentObj, callback); 204 | } 205 | return null; 206 | } 207 | 208 | async sendReaction(roomId, contentReactionObj, callback) { 209 | this.sendEvent(roomId, EventTypes.mRoomReaction, contentReactionObj, callback); 210 | } 211 | 212 | async loadEarlyMessages(room, limit) { 213 | return this.client.scrollback(room, limit).then(res => res).catch(e => e); 214 | } 215 | 216 | async changeRoomTitle(roomId, title) { 217 | const res = await api.room.sendStateEvent(roomId, EventTypes.mRoomName, { name: title }); 218 | return res.status; 219 | } 220 | 221 | async exitFromRoom(roomId) { 222 | return this.client.leave(roomId).then(() => this.client.forget(roomId).then(() => true).catch(() => false)).catch(() => false); 223 | } 224 | 225 | async setPusher(options) { 226 | if (!(options && options.pushkey && options.data && options.data.url && options.app_id)) { 227 | return { status: false }; 228 | } 229 | const defaultOptions = { 230 | lang: 'en', 231 | kind: 'http', 232 | app_display_name: 'MatrixClient', 233 | device_display_name: 'ClientDeviceName', 234 | append: false, 235 | }; 236 | const res = await api.pusher.setPusher({ ...defaultOptions, ...options }); 237 | return res; 238 | } 239 | 240 | async setRoomReadMarkers(roomId, eventId) { 241 | const res = await api.room.setRoomReadMarkers(roomId, eventId); 242 | return res; 243 | } 244 | 245 | async saveImageForRoom(roomId, imageObj) { 246 | const eventObj = Event.getEventObjFile(this.userId, MsgTypes.mImage, imageObj.filename, imageObj.uri, imageObj.type, imageObj.base64); 247 | const event = new Event(null, eventObj); 248 | let res = await event.contentObj.uploadFile(); 249 | if (res.status) { 250 | res = await api.room.sendStateEvent(roomId, EventTypes.mRoomAvatar, { url: event.matrixContentObj.url }); 251 | return res.status; 252 | } 253 | return null; 254 | } 255 | 256 | inviteNewMembers(roomId, matrixUserIds) { 257 | if (this.client && matrixUserIds && matrixUserIds.length) { 258 | matrixUserIds.map(matrixUserId => this.client.invite(roomId, matrixUserId)); 259 | return true; 260 | } 261 | return false; 262 | } 263 | 264 | // return matrixRoom 265 | async joinRoom(roomId) { 266 | return this.client.joinRoom(roomId).then(matrixRoom => matrixRoom).catch(() => null); 267 | } 268 | 269 | //return the id of direct room using userid 270 | getDirectRoomIdByUserId(matrixUserId) { 271 | const obj = this.getRoomsForChatsList(); 272 | return Object.prototype.hasOwnProperty.call(obj.userIdsDM, matrixUserId) ? obj.userIdsDM[matrixUserId] : ''; 273 | } 274 | } 275 | 276 | export default Matrix.getInstance(); 277 | -------------------------------------------------------------------------------- /src/models/Room.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is model for chat 5 | */ 6 | 7 | import Event from './Event'; 8 | import ContentFile from './ContentFile'; 9 | import Member from './Member'; 10 | import Utils from '../lib/utils'; 11 | import EventTypes from '../consts/EventTypes'; 12 | import MsgTypes from '../consts/MsgTypes'; 13 | import { PossibleChatEventsTypes, PossibleChatContentTypes } from '../consts/ChatPossibleTypes'; 14 | import api from '../api'; 15 | 16 | class Room { 17 | id = 0; 18 | 19 | title = ''; 20 | 21 | matrixRoom = null; 22 | 23 | events = []; 24 | 25 | messagesForSearch = []; 26 | 27 | reactedEventIds = []; 28 | 29 | isDirect = false; 30 | 31 | possibleEventsTypes = PossibleChatEventsTypes; 32 | 33 | possibleContentTypes = PossibleChatContentTypes; 34 | 35 | memberhsip = ''; 36 | 37 | dmUserId = ''; 38 | 39 | dmUserAvatarURI = null; 40 | 41 | myUserId = ''; 42 | 43 | isReversed = false; 44 | 45 | constructor({ matrixRoom, possibleEventsTypes, possibleContentTypes, myUserId, client }) { 46 | if (matrixRoom) { 47 | this.id = matrixRoom.roomId || 0; 48 | this.matrixRoom = matrixRoom || null; 49 | const alias = this.matrixRoom.getCanonicalAlias(); 50 | this.title = alias || matrixRoom.name; 51 | this.membership = this.matrixRoom.getMyMembership(); 52 | if (possibleEventsTypes) { 53 | this.possibleEventsTypes = possibleEventsTypes; 54 | } 55 | if (possibleContentTypes) { 56 | this.possibleContentTypes = possibleContentTypes; 57 | } 58 | this.myUserId = myUserId; 59 | this.isDirect = false; 60 | this.setEvents(); 61 | if (this.isDirect) { 62 | this.dmUserId = this.matrixRoom.guessDMUserId(); 63 | if (client) { 64 | const user = client.getUser(this.dmUserId); 65 | if (user) { 66 | const { serverName, mediaId } = Utils.parseMXCURI(user.avatarUrl); 67 | if (serverName && mediaId) { 68 | this.dmUserAvatarURI = ContentFile.getHTTPURI(serverName, mediaId); 69 | } 70 | } 71 | } 72 | } 73 | } 74 | } 75 | 76 | get avatar() { 77 | let uri = require('../assets/nophoto.png'); 78 | if (this.isDirect) { 79 | if (this.dmUserAvatarURI) { 80 | uri = { uri: this.dmUserAvatarURI }; 81 | } 82 | return uri; 83 | } 84 | uri = require('../assets/nophoto-group.png'); 85 | if (this.matrixRoom) { 86 | const matriURI = this.matrixRoom.getAvatarUrl(api.auth.getBaseURL()); 87 | if (matriURI.indexOf('download') !== -1) { 88 | uri = { uri: matriURI }; 89 | } 90 | } 91 | return uri; 92 | } 93 | 94 | get lastActiveEventTimestamp() { 95 | return this.matrixRoom ? this.matrixRoom.getLastActiveTimestamp() : 0; 96 | } 97 | 98 | get roomListObj() { 99 | if (!this.id) { 100 | return null; 101 | } 102 | const { id, avatar, title, lastEvent, membership, isDirect, unread, dmUserId, isInvite } = this; 103 | const { messageOnly, ts, msgtype } = lastEvent; 104 | return { id, avatar, title, message: messageOnly, ts, unread, membership, isInvite, isDirect, msgtype, dmUserId }; 105 | } 106 | 107 | get lastEvent() { 108 | if (this.events.length) { 109 | const index = this.isReversed ? 0 : this.events.length - 1; 110 | const lastEvent = this.events[index]; 111 | 112 | return lastEvent; 113 | } 114 | const lastEvent = new Event(); 115 | return lastEvent; 116 | } 117 | 118 | get allMembers() { 119 | const joined = this.getMembersObj(); 120 | const invited = this.getMembersObj('invite'); 121 | return { ...joined, ...invited }; 122 | } 123 | 124 | get myUserId() { 125 | return this.matrixRoom ? this.matrixRoom.myUserId : ''; 126 | } 127 | 128 | get unread() { 129 | return this.matrixRoom.getUnreadNotificationCount() || 0; 130 | } 131 | 132 | get lastReadEventId() { 133 | return this.matrixRoom.getEventReadUpTo(this.myUserId); 134 | } 135 | 136 | get chatEvents() { 137 | if (this.events && Array.isArray(this.events)) { 138 | this.setReversed(); 139 | return this.events; 140 | } 141 | return []; 142 | } 143 | 144 | get isInvite() { 145 | return this.membership === 'invite'; 146 | } 147 | 148 | setUnread(number) { 149 | this.matrixRoom.setUnreadNotificationCount('total', number); 150 | } 151 | 152 | increaseUnread() { 153 | this.setUnread(this.unread + 1); 154 | } 155 | 156 | isFound(searchText) { 157 | if (this.title.toLowerCase().indexOf(searchText.toLowerCase()) !== -1) { 158 | return true; 159 | } 160 | if (this.messagesForSearch.length && this.messagesForSearch.find(e => e.indexOf(searchText.toLowerCase()) !== -1)) { 161 | return true; 162 | } 163 | return false; 164 | } 165 | 166 | setEvents() { 167 | const timeline = this.matrixRoom.getLiveTimeline(); 168 | const matrixEvents = timeline.getEvents(); 169 | let numberUnread = 0; 170 | let foundLastRead = false; 171 | const lastUnread = this.matrixRoom.getUnreadNotificationCount(); 172 | const checkUnread = typeof lastUnread !== 'number'; 173 | const { lastReadEventId } = this; 174 | if (!checkUnread) { 175 | numberUnread = lastUnread; 176 | } 177 | matrixEvents.forEach((matrixEvent) => { 178 | const eventId = this.addMatrixEvent(matrixEvent); 179 | if (eventId && checkUnread) { 180 | if (!foundLastRead && lastReadEventId && eventId === lastReadEventId) { 181 | foundLastRead = true; 182 | numberUnread = 0; 183 | } else { 184 | if (matrixEvent.getSender() !== this.myUserId) { 185 | numberUnread += 1; 186 | } 187 | } 188 | } 189 | }); 190 | this.setUnread(numberUnread); 191 | } 192 | 193 | addMatrixEvent(matrixEvent) { 194 | const shouldBeAdded = Room.isEventPermitted(matrixEvent); 195 | if (!this.isDirect && Room.getIsDirect(matrixEvent)) { 196 | this.isDirect = true; 197 | } 198 | if (shouldBeAdded) { 199 | const event = new Event(matrixEvent); 200 | // console.log(event.messageOnly); 201 | this.events.push(event); 202 | const content = matrixEvent.getContent(); 203 | if (content.msgtype === MsgTypes.mText) { 204 | this.messagesForSearch.push(content.body.toLowerCase()); 205 | } 206 | return event.id; 207 | } 208 | if (matrixEvent.getType() === EventTypes.mRoomReaction) { 209 | const content = matrixEvent.getContent(); 210 | const realedObj = Object.prototype.hasOwnProperty.call(content, 'm.relates_to') ? content['m.relates_to'] : null; 211 | if (realedObj && realedObj.event_id && realedObj.rel_type === 'm.annotation' && this.reactedEventIds.indexOf(realedObj.event_id) === -1) { 212 | this.reactedEventIds.push(realedObj.event_id); 213 | } 214 | } 215 | return null; 216 | } 217 | 218 | addSentMessageById(eventId) { 219 | const timeline = this.matrixRoom.getLiveTimeline(); 220 | const matrixEvents = timeline.getEvents(); 221 | const matrixEvent = matrixEvents[matrixEvents.length - 1]; 222 | if (matrixEvent.getId() === eventId) { 223 | this.addMatrixEvent(matrixEvent); 224 | return true; 225 | } 226 | return false; 227 | } 228 | 229 | getMembers(membership) { 230 | if (!membership) { 231 | membership = 'join'; 232 | } 233 | return this.matrixRoom.getMembersWithMembership(membership); 234 | } 235 | 236 | getMembersObj(membership) { 237 | const obj = {}; 238 | const members = this.getMembers(membership); 239 | members.map((member) => { if (member.userId !== this.myUserId) obj[member.userId] = new Member(member.user, this.myUserId); }); 240 | return obj; 241 | } 242 | 243 | recalculate() { 244 | if (this.matrixRoom) { 245 | this.matrixRoom.recalculate(); 246 | } 247 | } 248 | 249 | setReversed() { 250 | if (!this.isReversed) { 251 | const { events } = this; 252 | this.events = events.reverse(); 253 | this.isReversed = true; 254 | } 255 | } 256 | 257 | addEvent({ event, matrixEvent }) { 258 | if (event || matrixEvent) { 259 | this.setReversed(); 260 | const { events } = this; 261 | if (matrixEvent) { 262 | const shouldBeAdded = Room.isEventPermitted(matrixEvent); 263 | if (!shouldBeAdded) { 264 | return false; 265 | } 266 | event = new Event(matrixEvent); 267 | } 268 | this.events = [event].concat(events); 269 | return true; 270 | } 271 | return false; 272 | } 273 | 274 | static getIsDirect(e) { 275 | return (e.event && e.event.content && e.event.content.is_direct) || (e.sender && e.sender.events && e.sender.events.member && e.sender.events.member.event && e.sender.events.member.event.unsigned && e.sender.events.member.event.unsigned.prev_content && e.sender.events.member.event.unsigned.prev_content.is_direct); 276 | } 277 | 278 | static isEventPermitted(matrixEvent, possibleEventsTypes, possibleContentTypes) { 279 | if (!possibleEventsTypes) { 280 | possibleEventsTypes = PossibleChatEventsTypes; 281 | } 282 | if (!possibleContentTypes) { 283 | possibleContentTypes = PossibleChatContentTypes; 284 | } 285 | if (possibleEventsTypes.indexOf(matrixEvent.getType()) !== -1) { 286 | const content = matrixEvent.getContent(); 287 | return content.body && content.msgtype && possibleContentTypes.indexOf(content.msgtype) !== -1; 288 | } 289 | return false; 290 | } 291 | } 292 | 293 | 294 | export default Room; 295 | -------------------------------------------------------------------------------- /src/MatrixChat.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is component that shows chat room 5 | */ 6 | 7 | import React, { Component } from 'react'; 8 | import { Animated, View, Platform, SafeAreaView } from 'react-native'; 9 | import { timer } from 'rxjs'; 10 | import getUid from 'get-uid'; 11 | import PropTypes from 'prop-types'; 12 | import AudioRecorderPlayer from 'react-native-audio-recorder-player'; 13 | import trans from './trans'; 14 | import Matrix from './Matrix'; 15 | import Event from './models/Event'; 16 | import isIphoneX from './lib/isIphoneX'; 17 | import EventsContainer from './components/EventsContainer'; 18 | import InputToolbar from './components/InputToolbar'; 19 | import { PossibleChatEventsTypes, PossibleChatContentTypes } from './consts/ChatPossibleTypes'; 20 | 21 | class MatrixChat extends Component { 22 | room = null; 23 | 24 | audioRecorderPlayer = new AudioRecorderPlayer(); 25 | 26 | constructor(props) { 27 | super(props); 28 | trans.setLocale(this.props.locale); 29 | trans.setTransFromProps(this.props.trans); 30 | 31 | this.keyboardHeight = 0; 32 | this.bottomOffset = this.getBottomOffsetIphoneX; 33 | this.maxHeight = undefined; 34 | this.messageContainerRef = React.createRef(); 35 | this.inputToolbarRef = React.createRef(); 36 | this.isPropsOnLoaded = false; 37 | this.members = []; 38 | 39 | if (this.props.roomId) { 40 | this.loadRoom({ roomId: this.props.roomId }); 41 | } 42 | 43 | this.state = { 44 | isLoading: true, 45 | alwaysNewValue: '', 46 | composerHeight: this.props.minComposerHeight, 47 | messagesContainerHeight: undefined, 48 | removePrevAudioListener: null, 49 | }; 50 | 51 | const onKeyboardWillShow = (e) => { 52 | this.setKeyboardHeight(e.endCoordinates ? e.endCoordinates.height : e.end.height); 53 | this.setBottomOffset(this.getBottomKeyboardOffset); 54 | const newMessagesContainerHeight = this.getMessagesContainerHeightWithKeyboard(); 55 | this.setContainerHeight(newMessagesContainerHeight); 56 | }; 57 | const onKeyboardWillHide = () => { 58 | this.setKeyboardHeight(0); 59 | this.setBottomOffset(this.getBottomOffsetIphoneX); 60 | const newMessagesContainerHeight = this.getBasicMessagesContainerHeight(); 61 | this.setContainerHeight(newMessagesContainerHeight); 62 | }; 63 | 64 | this.keyboardListeners = { onKeyboardWillShow, onKeyboardWillHide }; 65 | 66 | this.onInputSizeChanged = (size) => { 67 | const newComposerHeight = Math.max(this.props.minComposerHeight, Math.min(this.props.maxComposerHeight, size.height)); 68 | const newMessagesContainerHeight = this.getMessagesContainerHeightWithKeyboard(newComposerHeight); 69 | this.setState({ 70 | composerHeight: newComposerHeight, 71 | messagesContainerHeight: this.prepareMessagesContainerHeight(newMessagesContainerHeight), 72 | }); 73 | }; 74 | this.onInitialLayoutViewLayout = (e) => { 75 | const { layout } = e.nativeEvent; 76 | if (layout.height <= 0) { 77 | return; 78 | } 79 | this.setMaxHeight(layout.height); 80 | const newComposerHeight = this.props.minComposerHeight; 81 | const newMessagesContainerHeight = this.getMessagesContainerHeightWithKeyboard(newComposerHeight); 82 | this.setState({ 83 | composerHeight: newComposerHeight, 84 | messagesContainerHeight: this.prepareMessagesContainerHeight(newMessagesContainerHeight), 85 | isLoading: false, 86 | }); 87 | }; 88 | } 89 | 90 | componentDidMount() { 91 | if (this.props.roomId) { 92 | if (this.room && this.room.lastEvent.id && (!this.room.lastReadEventId || this.room.lastReadEventId !== this.room.lastEvent.id)) { 93 | Matrix.setRoomReadMarkers(this.room.id, this.room.lastEvent.id); 94 | } 95 | this.subscription = timer(1000).subscribe(() => { 96 | Matrix.setTimelineChatCallback(this.syncCallback); 97 | }); 98 | } 99 | if (!this.isPropsOnLoaded && this.room) { 100 | this.isPropsOnLoaded = true; 101 | this.props.onLoaded({ roomTitle: this.room.title, isDirect: this.room.isDirect }); 102 | } 103 | } 104 | 105 | shouldComponentUpdate(nextProps, nextState) { 106 | const shouldBeRefreshed = nextProps.shouldBeRefreshed && nextProps.shouldBeRefreshed !== this.props.shouldBeRefreshed; 107 | if (shouldBeRefreshed) { 108 | this.loadRoom({ roomId: this.props.roomId }); 109 | } 110 | return true; 111 | // return shouldBeRefreshed 112 | // || (this.state.composerHeight !== nextState.composerHeight) 113 | // || (this.state.removePrevAudioListener && this.state.removePrevAudioListener !== nextState.removePrevAudioListener) 114 | // || (this.state.alwaysNewValue !== nextState.alwaysNewValue); 115 | } 116 | 117 | componentWillUnmount() { 118 | Matrix.removeTimelineChatCallback(); 119 | if (this.state.removePrevAudioListener) { 120 | this.audioRecorderPlayer.stopPlayer(); 121 | this.state.removePrevAudioListener(); 122 | } 123 | } 124 | 125 | get getBottomOffsetIphoneX() { 126 | if (isIphoneX()) { 127 | return !this.props.bottomOffset ? 30 : this.props.bottomOffset + 10; 128 | } 129 | return this.props.bottomOffset; 130 | } 131 | 132 | get getBottomKeyboardOffset() { 133 | return 10; 134 | } 135 | 136 | // refresh component through change the state and if this component is shown in screen (isShown is func from props, by default it always returns true) 137 | refreshComponent = (isScrollToBottom) => { 138 | if (this.props.isShown()) { 139 | this.setState({ alwaysNewValue: getUid() }, () => { 140 | if (isScrollToBottom) { 141 | this.scrollToBottom(); 142 | } 143 | }); 144 | } 145 | } 146 | 147 | // load room from matrix store or from matrixRoom 148 | loadRoom = ({ roomId, matrixRoom }) => { 149 | const room = Matrix.getRoom({ roomId, matrixRoom, possibleEventsTypes: this.props.possibleChatEvents, possibleContentTypes: this.props.possibleChatContentTypes }); 150 | if (room) { 151 | this.room = room; 152 | this.members = this.room.getMembersObj(); 153 | } 154 | } 155 | 156 | // synchronizate chat when new event is come 157 | syncCallback = (matrixEvent, matrixRoom) => { 158 | if (matrixRoom && matrixEvent && matrixRoom.getLastActiveTimestamp() <= matrixEvent.getTs() && matrixRoom.roomId === this.props.roomId && Matrix.userId !== matrixEvent.getSender()) { 159 | const isAdded = this.addEvent({ matrixEvent }); 160 | if (isAdded) { 161 | Matrix.setRoomReadMarkers(matrixRoom.roomId, matrixEvent.getId()); 162 | } 163 | } 164 | } 165 | 166 | // load early message to event's timeline, return promise pageToken or falsy value if there is no previous messages 167 | loadEarlyMessages = () => Matrix.loadEarlyMessages(this.room.matrixRoom, 20).then((matrixRoom) => { 168 | this.loadRoom({ matrixRoom }); 169 | this.refreshComponent(); 170 | return matrixRoom.oldState.paginationToken; 171 | }).catch(() => false) 172 | 173 | // executed when message is sent and we need to set that it's read and add it matrix's store 174 | messageSent = (eventId) => { 175 | if (!eventId) { 176 | return null; 177 | } 178 | Matrix.setRoomReadMarkers(this.room.id, eventId); 179 | this.room.addSentMessageById(eventId); 180 | return true; 181 | } 182 | 183 | // add my own messages to component's events 184 | addEvent = ({ event, matrixEvent }) => { 185 | if (this.room && (event || matrixEvent)) { 186 | const isAdded = this.room.addEvent({ event, matrixEvent }); 187 | if (isAdded) { 188 | this.refreshComponent(true); 189 | return true; 190 | } 191 | } 192 | return false; 193 | } 194 | 195 | // send text messages 196 | sendText = async (text, isQuote) => { 197 | const event = new Event(null, Event.getEventObjText(Matrix.userId, text, isQuote)); 198 | this.addEvent({ event }); 199 | Matrix.sendMessage(this.props.roomId, event.matrixContentObj).then(res => this.messageSent(res.event_id)).catch(err => this.props.errorCallback(err)); 200 | } 201 | 202 | // send file/image/audio messages 203 | sendFile = async (msgtype, filename, uri, mimetype, base64, size, duration) => { 204 | const eventObj = Event.getEventObjFile(Matrix.userId, msgtype, filename, uri, mimetype, base64, size, duration); 205 | const event = new Event(null, eventObj); 206 | this.addEvent({ event }); 207 | const res = await event.contentObj.uploadFile(); 208 | if (res.status) { 209 | Matrix.sendMessage(this.props.roomId, event.matrixContentObj).then(result => this.messageSent(result.event_id)).catch(err => this.props.errorCallback(err)); 210 | } 211 | } 212 | 213 | setContainerHeight = (newHeight) => { 214 | if (this.props.isAnimated) { 215 | Animated.timing(this.state.messagesContainerHeight, { 216 | toValue: newHeight, 217 | duration: 200, 218 | useNativeDriver: false, 219 | }).start(() => { 220 | this.scrollToBottom(); 221 | }); 222 | } else { 223 | this.setState({ messagesContainerHeight: newHeight }); 224 | } 225 | } 226 | 227 | setMaxHeight = height => this.maxHeight = height; 228 | 229 | getMaxHeight = () => this.maxHeight; 230 | 231 | setKeyboardHeight = height => this.keyboardHeight = height; 232 | 233 | getKeyboardHeight = () => ((Platform.OS === 'android' && !this.props.forceGetKeyboardHeight) ? 0 : this.keyboardHeight); 234 | 235 | setBottomOffset = value => this.bottomOffset = value; 236 | 237 | getBottomOffset = () => this.bottomOffset; 238 | 239 | calculateInputToolbarHeight = composerHeight => (composerHeight || this.state.composerHeight) + this.getBottomOffset() + this.props.inputToolbarPaddingTop + 12; 240 | 241 | getBasicMessagesContainerHeight = composerHeight => (this.getMaxHeight() - this.calculateInputToolbarHeight(composerHeight)); 242 | 243 | getMessagesContainerHeightWithKeyboard = composerHeight => (this.getBasicMessagesContainerHeight(composerHeight) - this.getKeyboardHeight()); 244 | 245 | prepareMessagesContainerHeight = value => (this.props.isAnimated ? new Animated.Value(value) : value); 246 | 247 | scrollToBottom = (animated) => { 248 | if (animated) { 249 | animated = true; 250 | } 251 | if (this.messageContainerRef && this.messageContainerRef.current) { 252 | this.messageContainerRef.current.scrollToBottom({ animated }); 253 | } 254 | } 255 | 256 | startAudioPlay = async (url, playBack, removePrevAudioListener) => { 257 | try { 258 | if (this.state.removePrevAudioListener) { 259 | this.state.removePrevAudioListener(); 260 | } 261 | this.audioRecorderPlayer.stopPlayer(); 262 | this.audioRecorderPlayer.removePlayBackListener(); 263 | this.setState({ removePrevAudioListener }); 264 | await this.audioRecorderPlayer.startPlayer(url); 265 | this.audioRecorderPlayer.addPlayBackListener((e) => { 266 | if (e.current_position === e.duration) { 267 | this.audioRecorderPlayer.stopPlayer(); 268 | this.state.removePrevAudioListener(); 269 | } 270 | playBack(e); 271 | }); 272 | } catch (e) { 273 | // console.log(`cannot play the sound file`, e) 274 | } 275 | }; 276 | 277 | stopAudioPlay = async () => { 278 | this.audioRecorderPlayer.stopPlayer(); 279 | this.audioRecorderPlayer.removePlayBackListener(); 280 | this.setState({ removePrevAudioListener: null }); 281 | }; 282 | 283 | addCitation = (quoteMessageToSend, quoteMessage, quoteAuthor) => { 284 | if (this.inputToolbarRef && this.inputToolbarRef.current) { 285 | this.inputToolbarRef.current.addCitation(quoteMessageToSend, quoteMessage, quoteAuthor); 286 | } 287 | } 288 | 289 | cancelCitation = () => { 290 | if (this.inputToolbarRef && this.inputToolbarRef.current) { 291 | this.inputToolbarRef.current.cancelCitation(); 292 | } 293 | } 294 | 295 | messageSent = () => { 296 | if (this.messageContainerRef && this.messageContainerRef.current) { 297 | this.messageContainerRef.current.messageSent(); 298 | } 299 | } 300 | 301 | renderContainer = () => { 302 | if (this.props.renderContainer) { 303 | return this.props.renderContainer(this.renderEvents, this.renderInputToolbar); 304 | } 305 | 306 | return ( 307 | 308 | {this.renderEvents()} 309 | {this.renderInputToolbar()} 310 | 311 | ); 312 | } 313 | 314 | renderEvents = () => { 315 | const { messagesContainerHeight } = this.state; 316 | const AnimatedView = this.props.isAnimated ? Animated.View : View; 317 | return ( 318 | 319 | 334 | 335 | ); 336 | } 337 | 338 | renderInputToolbar = () => { 339 | const { composerHeight } = this.state; 340 | const { minComposerHeight, inputToolbarProps } = this.props; 341 | const props = { 342 | onInputSizeChanged: this.onInputSizeChanged, 343 | composerHeight: Math.max(minComposerHeight, composerHeight), 344 | inputbarHeight: this.calculateInputToolbarHeight(), 345 | keyboardListeners: this.keyboardListeners, 346 | trans: { inputToolbar: trans.t('inputToolbar'), fileModule: trans.t('fileModule') }, 347 | sendMessage: { text: this.sendText.bind(this), file: this.sendFile.bind(this) }, 348 | members: this.members, 349 | messageSent: this.messageSent, 350 | icons: this.props.icons, 351 | ...inputToolbarProps, 352 | }; 353 | if (this.props.renderInputToolbar) { 354 | return this.props.renderInputToolbar(props); 355 | } 356 | return ; 357 | } 358 | 359 | render() { 360 | if (!this.state.isLoading) { 361 | if (this.props.renderWithSafeArea) { 362 | return {this.renderContainer()}; 363 | } 364 | return this.renderContainer(); 365 | } 366 | return ; 367 | } 368 | } 369 | 370 | MatrixChat.defaultProps = { 371 | style: { flex: 1 }, 372 | trans: null, 373 | render: null, 374 | renderContainer: null, 375 | locale: 'en', 376 | roomId: '', 377 | possibleChatEvents: PossibleChatEventsTypes, 378 | possibleChatContentTypes: PossibleChatContentTypes, 379 | bottomOffset: 20, 380 | minComposerHeight: Platform.select({ ios: 33, android: 41 }), 381 | maxComposerHeight: 200, 382 | onInputTextChanged: () => {}, 383 | onLoaded: () => {}, 384 | isAnimated: Platform.select({ ios: true, android: false }), 385 | renderWithSafeArea: false, 386 | maxInputLength: null, 387 | forceGetKeyboardHeight: false, 388 | inputToolbarPaddingTop: 10, 389 | renderInputToolbar: null, 390 | errorCallback: () => {}, 391 | eventProps: {}, 392 | inputToolbarProps: {}, 393 | eventsStyles: {}, 394 | icons: {}, 395 | shouldBeRefreshed: '', 396 | isShown: () => true, 397 | }; 398 | 399 | MatrixChat.propTypes = { 400 | style: PropTypes.object, 401 | trans: PropTypes.object, 402 | render: PropTypes.func, 403 | renderContainer: PropTypes.func, 404 | locale: PropTypes.string, 405 | roomId: PropTypes.string, 406 | possibleChatEvents: PropTypes.array, 407 | possibleChatContentTypes: PropTypes.array, 408 | bottomOffset: PropTypes.number, 409 | minComposerHeight: PropTypes.number, 410 | maxComposerHeight: PropTypes.number, 411 | onInputTextChanged: PropTypes.func, 412 | onLoaded: PropTypes.func, 413 | isAnimated: PropTypes.bool, 414 | renderWithSafeArea: PropTypes.bool, 415 | maxInputLength: PropTypes.number, 416 | forceGetKeyboardHeight: PropTypes.bool, 417 | inputToolbarPaddingTop: PropTypes.number, 418 | renderInputToolbar: PropTypes.func, 419 | errorCallback: PropTypes.func, 420 | eventProps: PropTypes.object, 421 | inputToolbarProps: PropTypes.object, 422 | eventsStyles: PropTypes.object, 423 | icons: PropTypes.object, 424 | shouldBeRefreshed: PropTypes.string, 425 | isShown: PropTypes.func, 426 | }; 427 | 428 | export default MatrixChat; 429 | -------------------------------------------------------------------------------- /src/components/Event.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is container for rendering an event in a chat 5 | */ 6 | 7 | import React, { PureComponent } from 'react'; 8 | import PropTypes from 'prop-types'; 9 | import { View, StyleSheet, TouchableOpacity, Text, Image, Platform, Clipboard } from 'react-native'; 10 | import ActionSheet from 'react-native-action-sheet'; 11 | import Share from 'react-native-share'; 12 | import Matrix from '../Matrix'; 13 | import EventModel from '../models/Event'; 14 | import Utils from '../lib/utils'; 15 | import Colors from '../lib/colors'; 16 | import MsgTypes from '../consts/MsgTypes'; 17 | import ContentText from './ContentText'; 18 | import ContentImage from './ContentImage'; 19 | import ContentAudio from './ContentAudio'; 20 | import ContentFile from './ContentFile'; 21 | import EventAvatar from './EventAvatar'; 22 | import trans from '../trans'; 23 | 24 | const styles = StyleSheet.create({ 25 | container: { width: '100%' }, 26 | containerMyEvent: { marginBottom: 5, marginTop: 15, paddingLeft: 100, paddingBottom: 0, flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'flex-end' }, 27 | containerNotMyEvent: { marginBottom: 5, marginTop: 23, paddingLeft: 10, flexDirection: 'row', alignItems: 'flex-start', justifyContent: 'flex-start' }, 28 | chatDay: { width: '100%', padding: 16, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }, 29 | chatDayLine: { width: '33%', height: 1, backgroundColor: Colors.grey }, 30 | chatDayText: { color: Colors.blue }, 31 | avatarPhoto: { width: 40, height: 40, borderRadius: 20, marginRight: 10 }, 32 | containerMyMessage: {}, 33 | containerNotMyMessage: { position: 'relative' }, 34 | containerMyMessageContent: { paddingBottom: 2, backgroundColor: Colors.blue, borderRadius: 20, borderTopRightRadius: 0 }, 35 | containerNotMyMessageContent: { paddingBottom: 2, borderRadius: 20, borderTopLeftRadius: 0, borderWidth: 0.5, borderColor: Colors.grey }, 36 | containerMyMessageContentInner: { paddingBottom: 10, alignItems: 'flex-end' }, 37 | containerNotMyMessageContentInner: { paddingBottom: 10 }, 38 | containerSenderDisplayName: { position: 'absolute', top: -12 }, 39 | senderDisplayNameText: { color: Colors.blueDark, fontSize: 10 }, 40 | containerMyContentBottom: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-end', paddingBottom: 3, paddingLeft: 10, paddingRight: 10 }, 41 | messageMyTimeText: { color: Colors.white, fontSize: 10 }, 42 | containerNotMyContentBottom: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingBottom: 3, paddingLeft: 10, paddingRight: 10 }, 43 | messageNotMyTimeText: { color: Colors.grey, fontSize: 10 }, 44 | containerLike: {}, 45 | likeButton: { height: 36, width: 36, alignItems: 'center', justifyContent: 'center' }, 46 | likeImage: { width: 16, height: 16 }, 47 | containerMessageActions: { alignItems: 'center', justifyContent: 'center', width: 36, height: 36 }, 48 | iconActions: { width: 20, height: 20 }, 49 | }); 50 | 51 | class Event extends PureComponent { 52 | constructor(props) { 53 | super(props); 54 | this.state = { liked: false }; 55 | } 56 | 57 | getPropsStyle = (style) => { 58 | if (Object.prototype.hasOwnProperty.call(this.props.eventStyles, style)) { 59 | return this.props.eventStyles[style]; 60 | } 61 | return null; 62 | } 63 | 64 | showActions = () => { 65 | if (this.props.showEventActions) { 66 | this.props.showEventActions(this.copyToClipboard, this.share, this.quote); 67 | return null; 68 | } 69 | const iosButtons = [this.props.trans.t('event', 'copy'), this.props.trans.t('event', 'share'), this.props.trans.t('event', 'quote'), this.props.trans.t('event', 'cancel')]; 70 | const androidButtons = [this.props.trans.t('event', 'copy'), this.props.trans.t('event', 'share'), this.props.trans.t('event', 'citate')]; 71 | const cnf = { 72 | options: Platform.OS === 'android' ? androidButtons : iosButtons, 73 | cancelButtonIndex: 3, 74 | tintColor: Colors.blue, 75 | }; 76 | ActionSheet.showActionSheetWithOptions(cnf, index => this.doAction(index)); 77 | return null; 78 | } 79 | 80 | doAction = (index) => { 81 | switch (index) { 82 | case 0: 83 | this.copyToClipboard(); 84 | break; 85 | case 1: 86 | this.share(); 87 | break; 88 | case 2: 89 | this.quote(); 90 | break; 91 | default: 92 | break; 93 | } 94 | } 95 | 96 | share = () => { 97 | const { event } = this.props; 98 | const shareOptions = { 99 | title: this.props.trans.t('event', 'shareTitle'), 100 | message: event.messageOnly, 101 | }; 102 | if ((event.msgtype === MsgTypes.mImage || event.msgtype === MsgTypes.mFile) && event.content.base64ForShare) { 103 | shareOptions.url = event.content.base64ForShare; 104 | } 105 | Share.open(shareOptions); 106 | // if (callback) callback(); 107 | } 108 | 109 | quote = (callback) => { 110 | if (callback) callback(); 111 | this.props.addCitation(this.props.event.citationMessage, this.props.event.messageOnly, this.props.event.senderDisplayName); 112 | } 113 | 114 | copyToClipboard = async (callback) => { 115 | if (callback) callback(); 116 | await Clipboard.setString(this.props.event.message); 117 | }; 118 | 119 | likeEvent = () => { 120 | this.setState({ liked: true }); 121 | Matrix.sendReaction(this.props.roomId, this.props.event.reactionContentObj); 122 | } 123 | 124 | isLiked = () => this.state.liked || this.props.reactedEventIds.indexOf(this.props.event.id) !== -1 125 | 126 | renderDay = () => { 127 | if (!this.props.isNewDay) { 128 | return null; 129 | } 130 | if (this.props.renderDay) { 131 | return this.props.renderDay(this.props.event.ts); 132 | } 133 | return ( 134 | 135 | 136 | {Utils.formatTimestamp(this.props.event.ts, this.props.formatDayDate)} 137 | 138 | 139 | ); 140 | } 141 | 142 | renderMessage = () => { 143 | if (this.props.isOwn) { 144 | return this.renderMyMessage(); 145 | } 146 | return this.renderNotMyMessage(); 147 | } 148 | 149 | renderMyMessage = () => { 150 | if (this.props.renderMyMessage) { 151 | return this.props.renderMyMessage(this.props.event, this.props.isPrevUserTheSame); 152 | } 153 | return ( 154 | 155 | {this.renderMyMessageContent()} 156 | {this.renderMessageActions()} 157 | 158 | ); 159 | } 160 | 161 | renderNotMyMessage = () => { 162 | if (this.props.renderNotMyMessage) { 163 | return this.props.renderNotMyMessage(this.props.event, this.props.isPrevUserTheSame); 164 | } 165 | return ( 166 | 167 | {this.props.showNotMyAvatar ? this.renderMessageAvatar() : null} 168 | {this.renderMessageActions()} 169 | {this.renderNotMyMessageContent()} 170 | 171 | ); 172 | } 173 | 174 | renderMessageAvatar = () => { 175 | if (this.props.renderMessageAvatar) { 176 | return this.props.renderMessageAvatar(this.props.event.senderAvatarObj, this.props.isPrevUserTheSame); 177 | } 178 | if (!this.props.isPrevUserTheSame) { 179 | return ; 180 | } 181 | return ; 182 | } 183 | 184 | renderMyMessageContent = () => { 185 | if (this.props.renderMyMessageContent) { 186 | return this.props.renderMyMessageContent(this.renderMessageContent.bind(this), this.renderMyContentBottom.bind(this)); 187 | } 188 | const contentInner = ( 189 | 190 | {this.renderMessageContent({ isOwn: true })} 191 | {this.renderMyContentBottom()} 192 | 193 | ); 194 | return ( 195 | 196 | {this.props.renderContentInner ? this.props.renderContentInner(contentInner, true) : ({contentInner})} 197 | 198 | ); 199 | } 200 | 201 | renderNotMyMessageContent = () => { 202 | if (this.props.renderNotMyMessageContent) { 203 | return this.props.renderNotMyMessageContent(this.renderSenderName.bind(this), this.renderMessageContent.bind(this), this.renderNotMyContentBottom.bind(this)); 204 | } 205 | const contentInner = ( 206 | 207 | {this.renderMessageContent({ isOwn: false })} 208 | {this.renderNotMyContentBottom()} 209 | 210 | ); 211 | return ( 212 | 213 | {this.renderSenderName()} 214 | {this.props.renderContentInner ? this.props.renderContentInner(contentInner, false) : ({contentInner})} 215 | {this.renderLike()} 216 | 217 | ); 218 | } 219 | 220 | renderLike = () => { 221 | if (this.props.renderLike) { 222 | this.props.renderLike(this.isLiked); 223 | } 224 | if (this.isLiked()) { 225 | return ( 226 | 227 | 228 | 229 | 230 | 231 | ); 232 | } 233 | return ( 234 | 235 | 236 | 237 | 238 | 239 | ); 240 | } 241 | 242 | renderSenderName = () => { 243 | if (this.props.renderSenderName) { 244 | return this.props.renderSenderName(this.props.event.senderDisplayName, this.props.isPrevUserTheSame); 245 | } 246 | return ( 247 | 248 | {this.props.event.senderDisplayName} 249 | 250 | ); 251 | } 252 | 253 | renderMyContentBottom = () => { 254 | if (this.props.renderMyContentBottom) { 255 | return this.props.renderMyContentBottom(this.props.event); 256 | } 257 | return ( 258 | 259 | {Utils.formatTimestamp(this.props.event.ts, this.props.formatMessageDate)} 260 | 261 | ); 262 | } 263 | 264 | renderNotMyContentBottom = () => { 265 | if (this.props.renderNotMyContentBottom) { 266 | return this.props.renderNotMyContentBottom(this.props.event); 267 | } 268 | return ( 269 | 270 | {Utils.formatTimestamp(this.props.event.ts, this.props.formatMessageDate)} 271 | 272 | ); 273 | } 274 | 275 | renderMessageContent = ({ isOwn }) => { 276 | if (this.props.renderMessageContent) { 277 | return this.props.renderMessageContent(this.props.event, isOwn); 278 | } 279 | 280 | const { content } = this.props.event; 281 | switch (content.type) { 282 | default: 283 | case MsgTypes.mText: 284 | return ; 285 | case MsgTypes.mImage: 286 | return ; 287 | case MsgTypes.mAudio: 288 | return ; 289 | case MsgTypes.mFile: 290 | return ; 291 | } 292 | } 293 | 294 | renderMessageActions = () => { 295 | if (this.props.renderMessageActions) { 296 | return this.props.renderMessageActions(this.props.event, this.showActions.bind(this)); 297 | } 298 | return ( 299 | this.showActions()} {...Utils.testProps('btnEventActions')}> 300 | 301 | 302 | ); 303 | } 304 | 305 | render() { 306 | return ( 307 | 308 | {this.renderDay()} 309 | {this.renderMessage()} 310 | 311 | ); 312 | } 313 | } 314 | Event.defaultProps = { 315 | trans, 316 | event: new EventModel(), 317 | eventStyles: {}, 318 | contentTextStyles: {}, 319 | contentImageStyles: {}, 320 | contentAudioStyles: {}, 321 | contentFileStyles: {}, 322 | isOwn: false, 323 | isNewDay: false, 324 | isPrevUserTheSame: false, 325 | showNotMyAvatar: true, 326 | formatDayDate: 'll', 327 | formatMessageDate: 'HH:mm', 328 | iconMessageActions: null, 329 | renderDay: null, 330 | renderMyMessage: null, 331 | renderNotMyMessage: null, 332 | renderMessageAvatar: null, 333 | renderMyMessageContent: null, 334 | renderNotMyMessageContent: null, 335 | renderSenderName: null, 336 | renderMyContentBottom: null, 337 | renderNotMyContentBottom: null, 338 | renderMessageContent: null, 339 | renderMessageActions: null, 340 | renderContentInner: null, 341 | renderLike: null, 342 | showEventActions: null, 343 | noEventPhotoSource: null, 344 | startAudioPlay: () => {}, 345 | stopAudioPlay: () => {}, 346 | onImagePress: null, 347 | onFilePress: null, 348 | roomId: '', 349 | reactedEventIds: [], 350 | addCitation: () => {}, 351 | icons: {}, 352 | }; 353 | Event.propTypes = { 354 | trans: PropTypes.object, 355 | event: PropTypes.object, 356 | eventStyles: PropTypes.object, 357 | contentTextStyles: PropTypes.object, 358 | contentImageStyles: PropTypes.object, 359 | contentAudioStyles: PropTypes.object, 360 | contentFileStyles: PropTypes.object, 361 | isOwn: PropTypes.bool, 362 | isNewDay: PropTypes.bool, 363 | isPrevUserTheSame: PropTypes.bool, 364 | showNotMyAvatar: PropTypes.bool, 365 | formatDayDate: PropTypes.string, 366 | formatMessageDate: PropTypes.string, 367 | iconMessageActions: PropTypes.object, 368 | renderDay: PropTypes.func, 369 | renderMyMessage: PropTypes.func, 370 | renderNotMyMessage: PropTypes.func, 371 | renderMessageAvatar: PropTypes.func, 372 | renderMyMessageContent: PropTypes.func, 373 | renderNotMyMessageContent: PropTypes.func, 374 | renderSenderName: PropTypes.func, 375 | renderMyContentBottom: PropTypes.func, 376 | renderNotMyContentBottom: PropTypes.func, 377 | renderMessageContent: PropTypes.func, 378 | renderMessageActions: PropTypes.func, 379 | renderContentInner: PropTypes.func, 380 | renderLike: PropTypes.func, 381 | showEventActions: PropTypes.func, 382 | noEventPhotoSource: PropTypes.object, 383 | startAudioPlay: PropTypes.func, 384 | stopAudioPlay: PropTypes.func, 385 | onImagePress: PropTypes.func, 386 | onFilePress: PropTypes.func, 387 | roomId: PropTypes.string, 388 | reactedEventIds: PropTypes.arrayOf(PropTypes.string), 389 | addCitation: PropTypes.func, 390 | icons: PropTypes.object, 391 | }; 392 | 393 | export default Event; 394 | -------------------------------------------------------------------------------- /src/components/InputToolbar.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by Max Gor on 6/20/20 3 | * 4 | * This is input toolbar component 5 | */ 6 | 7 | import React, { PureComponent } from 'react'; 8 | import PropTypes from 'prop-types'; 9 | import { View, StyleSheet, Keyboard, TouchableOpacity, TextInput, Image, Platform, Modal, TouchableWithoutFeedback } from 'react-native'; 10 | import getUid from 'get-uid'; 11 | import SoundRecorder from 'react-native-sound-recorder'; 12 | import EmojiSelector from 'react-native-emoji-selector'; 13 | import Colors from '../lib/colors'; 14 | import FileUtils from '../lib/fileUtils'; 15 | import Utils from '../lib/utils'; 16 | import MsgTypes from '../consts/MsgTypes'; 17 | import VoiceRecord from './VoiceRecord'; 18 | import trans from '../trans'; 19 | 20 | const styles = StyleSheet.create({ 21 | container: { 22 | flexDirection: 'row', 23 | alignItems: 'flex-start', 24 | justifyContent: 'flex-start', 25 | backgroundColor: Colors.white, 26 | width: '100%', 27 | paddingTop: 10, 28 | paddingBottom: 10, 29 | }, 30 | containerAddActions: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start' }, 31 | containerAddFiles: { alignItems: 'center', justifyContent: 'center', width: 60, height: 40 }, 32 | containerAddSmiles: { alignItems: 'center', justifyContent: 'center', width: 40, height: 36 }, 33 | containerAddAudio: { alignItems: 'center', justifyContent: 'center', width: 40, height: 40 }, 34 | containerAddImage: { alignItems: 'center', justifyContent: 'center', width: 40, height: 40 }, 35 | containerSend: { alignItems: 'center', justifyContent: 'center', width: 60, height: 40 }, 36 | iconActionsAddFiles: { width: 30, height: 30 }, 37 | iconActionsAddSmiles: { width: 24, height: 24 }, 38 | iconActionsAddAudio: { width: 24, height: 24 }, 39 | iconActionsAddImage: { width: 24, height: 24 }, 40 | iconActionsSend: { width: 30, height: 30 }, 41 | containerTextInput: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', borderRadius: 25, backgroundColor: Colors.greyLight, padding: 5 }, 42 | textInput: { flex: 1, marginRight: 10, marginLeft: 10, color: Colors.black, lineHeight: 20 }, 43 | containerTouchEmojis: { flex: 1 }, 44 | containerTouchEmojisInner: { flex: 1, backgroundColor: Colors.blackTransparent, justifyContent: 'flex-end' }, 45 | containerEmojis: { width: '100%', backgroundColor: Colors.white, height: 500 }, 46 | }); 47 | 48 | class InputToolbar extends PureComponent { 49 | constructor(props) { 50 | super(props); 51 | this.contentSize = undefined; 52 | this.state = { 53 | text: '', 54 | quoteMessageToSend: '', 55 | showRecordAudio: false, 56 | showEmojis: false, 57 | isQuote: false, 58 | }; 59 | } 60 | 61 | componentDidMount() { 62 | this.keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow); 63 | this.keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide); 64 | // this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this.keyboardDidShow); 65 | // this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this.keyboardDidHide); 66 | } 67 | 68 | componentWillUnmount() { 69 | if (this.keyboardWillShowListener) { 70 | this.keyboardWillShowListener.remove(); 71 | } 72 | if (this.keyboardWillHideListener) { 73 | this.keyboardWillHideListener.remove(); 74 | } 75 | // if (this.keyboardDidShowListener) { 76 | // this.keyboardDidShowListener.remove(); 77 | // } 78 | // if (this.keyboardDidHideListener) { 79 | // this.keyboardDidHideListener.remove(); 80 | // } 81 | } 82 | 83 | keyboardWillShow = (e) => { 84 | if (this.props.keyboardListeners.onKeyboardWillShow) { 85 | this.props.keyboardListeners.onKeyboardWillShow(e); 86 | } 87 | } 88 | 89 | keyboardWillHide = (e) => { 90 | if (this.props.keyboardListeners.onKeyboardWillHide) { 91 | this.props.keyboardListeners.onKeyboardWillHide(e); 92 | } 93 | } 94 | 95 | // keyboardDidShow = (e) => { 96 | // if (this.props.keyboardListeners.onKeyboardDidShow) { 97 | // this.props.keyboardListeners.onKeyboardDidShow(e); 98 | // } 99 | // } 100 | // 101 | // keyboardDidHide = (e) => { 102 | // if (this.props.keyboardListeners.onKeyboardDidHide) { 103 | // this.props.keyboardListeners.onKeyboardDidHide(e); 104 | // } 105 | // } 106 | 107 | getPropsStyle = (style) => { 108 | if (Object.prototype.hasOwnProperty.call(this.props.inputToolbarStyles, style)) { 109 | return this.props.inputToolbarStyles[style]; 110 | } 111 | return null; 112 | } 113 | 114 | setLoadingState = (val) => { 115 | this.props.setLoading(val); 116 | } 117 | 118 | openCamera = () => { 119 | FileUtils.getFileFromCamera(this.uploadCallback, this.setLoadingState, this.props.resizeX, this.props.resizeY, this.props.imageQuality); 120 | } 121 | 122 | openGallery = () => { 123 | FileUtils.getFileFromGallery(this.uploadCallback, this.setLoadingState, this.props.resizeX, this.props.resizeY, this.props.imageQuality, this.props.trans.fileModule); 124 | } 125 | 126 | openFile = () => { 127 | FileUtils.getPDFFile(this.uploadCallback, this.setLoadingState); 128 | } 129 | 130 | openActions = (showUploadPDF) => { 131 | if (this.props.showInputbarActions) { 132 | this.props.showInputbarActions(this.openCamera.bind(this), this.openGallery.bind(this), this.openFile, Object.keys(this.props.members)); 133 | return null; 134 | } 135 | FileUtils.uploadFile({ callback: this.uploadCallback, setLoadingState: this.setLoadingState, resizeX: 1000, resizeY: 1600, returnBase64: true, showUploadPDF }); 136 | return null; 137 | } 138 | 139 | uploadCallback = async (error, res) => { 140 | this.setLoadingState(false); 141 | if (error) { 142 | return null; 143 | } 144 | if (res) { 145 | if (res.type === 'image/jpeg') { 146 | await this.props.sendMessage.file(MsgTypes.mImage, res.filename, res.uri, res.type, res.base64); 147 | } else { 148 | await this.props.sendMessage.file(MsgTypes.mFile, res.filename, res.uri, res.type, res.base64, res.size); 149 | } 150 | } 151 | 152 | return null; 153 | } 154 | 155 | addAudio = async (uri, size, base64, duration) => { 156 | const filename = `${getUid()}.mp4`; 157 | await this.props.sendMessage.file(MsgTypes.mAudio, filename, uri, 'video/mp4', base64, size, duration); 158 | } 159 | 160 | addSmiles = async (smile) => { 161 | this.setState({ showEmojis: false }); 162 | await this.props.sendMessage.text(smile); 163 | } 164 | 165 | addText = async () => { 166 | let message = this.state.text; 167 | if (message) { 168 | const { isQuote, quoteMessageToSend } = this.state; 169 | if (isQuote) { 170 | message = `${quoteMessageToSend}\n${message}`; 171 | } 172 | this.setState({ text: '', isQuote: false }); 173 | this.props.messageSent(); 174 | await this.props.sendMessage.text(message, isQuote); 175 | } 176 | } 177 | 178 | onContentSizeChange = (e) => { 179 | const { contentSize } = e.nativeEvent; 180 | if (!contentSize) { 181 | return; 182 | } 183 | if (!this.contentSize || (this.contentSize && (this.contentSize.width !== contentSize.width || this.contentSize.height !== contentSize.height))) { 184 | this.contentSize = contentSize; 185 | this.props.onInputSizeChanged(this.contentSize); 186 | } 187 | }; 188 | 189 | onChangeText = (text) => { 190 | if (this.props.onInputTextChanged) { 191 | this.props.onInputTextChanged(text); 192 | } 193 | this.setState({ text }); 194 | }; 195 | 196 | startRecording = () => { 197 | SoundRecorder.start(`${SoundRecorder.PATH_CACHE}/temp.mp4`) 198 | .then(() => this.setState({ showRecordAudio: true })) 199 | .catch(e => e); 200 | } 201 | 202 | stopRecording = (duration) => { 203 | this.setState({ showRecordAudio: false }, () => { 204 | SoundRecorder.stop() 205 | .then(result => FileUtils.readFile(result.path) 206 | .then(data => ({ base64: data, filePath: result.path })).catch(e => e)) 207 | .then(obj => FileUtils.getFileInfo(obj.filePath) 208 | .then(fileInfo => ({ filePath: obj.filePath, fileInfo, base64: obj.base64 })).catch(e => e)) 209 | .then((obj) => { 210 | if (Object.prototype.hasOwnProperty.call(obj.fileInfo, 'size') && obj.base64) { 211 | this.addAudio(obj.filePath, obj.fileInfo.size, obj.base64, duration); 212 | } 213 | }) 214 | .catch(e => e); 215 | }); 216 | } 217 | 218 | cancelRecording = () => { 219 | if (this.state.showRecordAudio) { 220 | SoundRecorder.stop(); 221 | this.setState({ showRecordAudio: false }); 222 | } 223 | } 224 | 225 | showEmojis = showEmojis => this.setState({ showEmojis }); 226 | 227 | addCitation = (quoteMessageToSend) => { 228 | this.setState({ quoteMessageToSend, isQuote: true }); 229 | } 230 | 231 | cancelCitation = () => { 232 | this.setState({ isQuote: false }); 233 | } 234 | 235 | renderRecordAudio = () => { 236 | if (this.props.renderRecordAudio) { 237 | return this.props.renderRecordAudio(); 238 | } 239 | 240 | return ( 241 | 248 | ); 249 | } 250 | 251 | renderAddFiles() { 252 | if (this.props.renderAddFiles) { 253 | return this.props.renderAddFiles(this.selectFile.bind(this)); 254 | } 255 | 256 | return ( 257 | this.openActions(true)} {...Utils.testProps('btnAddFiles')}> 258 | 259 | 260 | ); 261 | } 262 | 263 | renderInput() { 264 | if (this.props.renderInput) { 265 | return this.props.renderInput(this.onChangeText, this.onContentSizeChange); 266 | } 267 | 268 | return ( 269 | 270 | 288 | this.showEmojis(true)} {...Utils.testProps('btnSmileOpen')}> 289 | 290 | 291 | 292 | ); 293 | } 294 | 295 | renderSend() { 296 | if (this.props.renderSend) { 297 | return this.props.renderSend(this.state.text, this.addAudio, this.addImage, this.send); 298 | } 299 | 300 | if (!this.state.text) { 301 | return ( 302 | 303 | this.startRecording()} {...Utils.testProps('btnAddAudio')}> 304 | 305 | 306 | this.openGallery()} {...Utils.testProps('btnAddFileImage')}> 307 | 308 | 309 | 310 | ); 311 | } 312 | 313 | return ( 314 | this.addText()} {...Utils.testProps('btnSend')}> 315 | 316 | 317 | ); 318 | } 319 | 320 | renderEmojis() { 321 | if (this.props.renderEmojis) { 322 | return this.props.renderEmojis(this.state.showEmojis, this.showEmojis, this.addSmiles); 323 | } 324 | 325 | return ( 326 | this.showEmojis(false)}> 327 | this.showEmojis(false)} {...Utils.testProps('btnSmileClose')}> 328 | 329 | 330 | this.addSmiles(emoji)} /> 331 | 332 | 333 | 334 | 335 | ); 336 | } 337 | 338 | render() { 339 | const { showRecordAudio } = this.state; 340 | if (this.props.render) { 341 | return this.props.render(showRecordAudio); 342 | } 343 | 344 | if (showRecordAudio) { 345 | return ( 346 | 347 | {this.renderRecordAudio()} 348 | 349 | ); 350 | } 351 | 352 | return ( 353 | 354 | {this.renderAddFiles()} 355 | {this.renderInput()} 356 | {this.renderSend()} 357 | {this.renderEmojis()} 358 | 359 | ); 360 | } 361 | } 362 | InputToolbar.defaultProps = { 363 | trans: { inputToolbar: trans.t('inputToolbar'), fileModule: trans.t('fileModule') }, 364 | inputbarHeight: 44, 365 | composerHeight: Platform.select({ ios: 33, android: 41 }), 366 | inputTestId: '', 367 | placeholderTextColor: Colors.greyDark, 368 | inputToolbarStyles: {}, 369 | textInputProps: {}, 370 | render: null, 371 | renderAddFiles: null, 372 | renderInput: null, 373 | renderSend: null, 374 | renderRecordAudio: null, 375 | renderEmojis: null, 376 | renderQuote: null, 377 | onInputTextChanged: () => { }, 378 | onInputSizeChanged: () => { }, 379 | iconActionsAddFiles: null, 380 | iconActionsAddSmiles: null, 381 | iconActionsAddAudio: null, 382 | iconActionsAddImage: null, 383 | iconActionsSend: null, 384 | keyboardListeners: null, 385 | setLoading: () => { }, 386 | sendMessage: { text: () => {}, file: () => {} }, 387 | voiceRecordStyles: null, 388 | resizeX: 1000, 389 | resizeY: 1600, 390 | imageQuality: 80, 391 | members: {}, 392 | messageSent: () => {}, 393 | showInputbarActions: null, 394 | icons: {}, 395 | }; 396 | InputToolbar.propTypes = { 397 | trans: PropTypes.object, 398 | inputbarHeight: PropTypes.number, 399 | composerHeight: PropTypes.number, 400 | inputTestId: PropTypes.string, 401 | placeholderTextColor: PropTypes.string, 402 | inputToolbarStyles: PropTypes.object, 403 | textInputProps: PropTypes.object, 404 | render: PropTypes.func, 405 | renderAddFiles: PropTypes.func, 406 | renderInput: PropTypes.func, 407 | renderSend: PropTypes.func, 408 | renderRecordAudio: PropTypes.func, 409 | renderEmojis: PropTypes.func, 410 | renderQuote: PropTypes.func, 411 | onInputTextChanged: PropTypes.func, 412 | onInputSizeChanged: PropTypes.func, 413 | iconActionsAddFiles: PropTypes.object, 414 | iconActionsAddSmiles: PropTypes.object, 415 | iconActionsAddAudio: PropTypes.object, 416 | iconActionsAddImage: PropTypes.object, 417 | iconActionsSend: PropTypes.object, 418 | keyboardListeners: PropTypes.object, 419 | setLoading: PropTypes.func, 420 | sendMessage: PropTypes.object, 421 | voiceRecordStyles: PropTypes.object, 422 | resizeX: PropTypes.number, 423 | resizeY: PropTypes.number, 424 | imageQuality: PropTypes.number, 425 | members: PropTypes.object, 426 | messageSent: PropTypes.func, 427 | showInputbarActions: PropTypes.func, 428 | icons: PropTypes.object, 429 | }; 430 | 431 | export default InputToolbar; 432 | --------------------------------------------------------------------------------