Merge branch 'chore.dehydrate-login-methods-from-rocketchatjs' of https://github.com/RocketChat/Rocket.Chat.ReactNative into chore.dehydrate-login-methods-from-rocketchatjs

This commit is contained in:
Gerzon Z 2022-03-04 11:50:30 -04:00
commit 411323f905
55 changed files with 676 additions and 502 deletions

View File

@ -1,5 +1,7 @@
export const MESSAGE_TYPE_LOAD_MORE = 'load_more'; export enum MessageTypeLoad {
export const MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK = 'load_previous_chunk'; MORE = 'load_more',
export const MESSAGE_TYPE_LOAD_NEXT_CHUNK = 'load_next_chunk'; PREVIOUS_CHUNK = 'load_previous_chunk',
NEXT_CHUNK = 'load_next_chunk'
}
export const MESSAGE_TYPE_ANY_LOAD = [MESSAGE_TYPE_LOAD_MORE, MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK, MESSAGE_TYPE_LOAD_NEXT_CHUNK]; export const MESSAGE_TYPE_ANY_LOAD = [MessageTypeLoad.MORE, MessageTypeLoad.PREVIOUS_CHUNK, MessageTypeLoad.NEXT_CHUNK];

View File

@ -1,3 +1,5 @@
import React from 'react';
import { TGetCustomEmoji } from '../../definitions/IEmoji'; import { TGetCustomEmoji } from '../../definitions/IEmoji';
export interface IAvatar { export interface IAvatar {
@ -9,7 +11,7 @@ export interface IAvatar {
size?: number; size?: number;
borderRadius?: number; borderRadius?: number;
type?: string; type?: string;
children?: JSX.Element; children?: React.ReactElement | null;
user?: { user?: {
id?: string; id?: string;
token?: string; token?: string;

View File

@ -922,8 +922,8 @@ class MessageBox extends Component<IMessageBoxProps, IMessageBoxState> {
let msg = `[ ](${permalink}) `; let msg = `[ ](${permalink}) `;
// if original message wasn't sent by current user and neither from a direct room // if original message wasn't sent by current user and neither from a direct room
if (user.username !== replyingMessage.u.username && roomType !== 'd' && replyWithMention) { if (user.username !== replyingMessage?.u?.username && roomType !== 'd' && replyWithMention) {
msg += `@${replyingMessage.u.username} `; msg += `@${replyingMessage?.u?.username} `;
} }
msg = `${msg} ${message}`; msg = `${msg} ${message}`;

View File

@ -0,0 +1,7 @@
export interface IDDPMessage {
msg: string;
fields: {
eventName: string;
args: any;
};
}

View File

@ -32,6 +32,8 @@ export interface ILivechatVisitor extends IRocketChatRecord {
ip?: string; ip?: string;
host?: string; host?: string;
visitorEmails?: IVisitorEmail[]; visitorEmails?: IVisitorEmail[];
livechatData?: any;
utc?: number;
} }
export interface ILivechatVisitorDTO { export interface ILivechatVisitorDTO {

View File

@ -1,27 +1,14 @@
import Model from '@nozbe/watermelondb/Model'; import Model from '@nozbe/watermelondb/Model';
import { MarkdownAST } from '@rocket.chat/message-parser'; import { MarkdownAST } from '@rocket.chat/message-parser';
import { MessageTypeLoad } from '../constants/messageTypeLoad';
import { IAttachment } from './IAttachment'; import { IAttachment } from './IAttachment';
import { IReaction } from './IReaction'; import { IReaction } from './IReaction';
import {
MESSAGE_TYPE_LOAD_MORE,
MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK,
MESSAGE_TYPE_LOAD_NEXT_CHUNK
} from '../constants/messageTypeLoad';
import { TThreadMessageModel } from './IThreadMessage'; import { TThreadMessageModel } from './IThreadMessage';
import { TThreadModel } from './IThread'; import { TThreadModel } from './IThread';
import { IUrlFromServer } from './IUrl'; import { IUrlFromServer } from './IUrl';
export type MessageType = export type MessageType = 'jitsi_call_started' | 'discussion-created' | 'e2e' | 'load_more' | 'rm' | 'uj' | MessageTypeLoad;
| 'jitsi_call_started'
| 'discussion-created'
| 'e2e'
| 'load_more'
| 'rm'
| 'uj'
| typeof MESSAGE_TYPE_LOAD_MORE
| typeof MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK
| typeof MESSAGE_TYPE_LOAD_NEXT_CHUNK;
export interface IUserMessage { export interface IUserMessage {
_id: string; _id: string;

View File

@ -15,7 +15,7 @@ interface IRequestTranscript {
} }
export interface IRoom { export interface IRoom {
_id?: string; _id: string;
fname?: string; fname?: string;
id: string; id: string;
rid: string; rid: string;

View File

@ -30,13 +30,15 @@ export enum ERoomTypes {
CHANNEL = 'channel' CHANNEL = 'channel'
} }
type RelationModified<T extends Model> = { fetch(): Promise<T[]> } & Relation<T>;
export interface ISubscription { export interface ISubscription {
_id: string; // _id belongs watermelonDB _id: string; // _id belongs watermelonDB
id: string; // id from server id: string; // id from server
_updatedAt?: string; // from server _updatedAt?: string; // from server
v?: IVisitor; v?: IVisitor;
f: boolean; f: boolean;
t: string; // TODO: we need to review this type later t: SubscriptionType; // TODO: we need to review this type later
ts: string | Date; ts: string | Date;
ls: Date; ls: Date;
name: string; name: string;
@ -91,12 +93,13 @@ export interface ISubscription {
avatarETag?: string; avatarETag?: string;
teamId?: string; teamId?: string;
teamMain?: boolean; teamMain?: boolean;
unsubscribe: () => Promise<any>;
separator?: boolean; separator?: boolean;
// https://nozbe.github.io/WatermelonDB/Relation.html#relation-api // https://nozbe.github.io/WatermelonDB/Relation.html#relation-api
messages: Relation<TMessageModel>; messages: RelationModified<TMessageModel>;
threads: Relation<TThreadModel>; threads: RelationModified<TThreadModel>;
threadMessages: Relation<TThreadMessageModel>; threadMessages: RelationModified<TThreadMessageModel>;
uploads: Relation<TUploadModel>; uploads: RelationModified<TUploadModel>;
} }
export type TSubscriptionModel = ISubscription & Model; export type TSubscriptionModel = ISubscription & Model;

View File

@ -1,5 +1,6 @@
import { IRocketChatRecord } from './IRocketChatRecord'; import { IRocketChatRecord } from './IRocketChatRecord';
import { IUser } from './IUser'; import { IUser } from './IUser';
import { IServerRoomItem } from './IRoom';
export enum TEAM_TYPE { export enum TEAM_TYPE {
PUBLIC = 0, PUBLIC = 0,
@ -46,3 +47,16 @@ export interface ITeamStats {
totalTeams: number; totalTeams: number;
teamStats: Array<ITeamStatData>; teamStats: Array<ITeamStatData>;
} }
export interface IServerTeamUpdateRoom
extends Omit<
IServerRoomItem,
'topic' | 'joinCodeRequired' | 'description' | 'jitsiTimeout' | 'usersCount' | 'e2eKeyId' | 'avatarETag'
> {
broadcast: boolean;
msgs: number;
default: boolean;
sysMes: boolean;
teamId: string;
teamDefault: boolean;
}

View File

@ -103,6 +103,22 @@ export interface IUserSettings {
[key: string]: any; [key: string]: any;
}; };
} }
type TNotifications = 'default' | 'all' | 'mentions' | 'nothing';
export interface INotificationPreferences {
id: string;
enableMessageParserEarlyAdoption: boolean;
desktopNotifications: TNotifications;
pushNotifications: TNotifications;
emailNotificationMode?: 'mentions' | 'nothing';
}
export interface IUserPreferences {
user: { _id: string };
settings: {
preferences: INotificationPreferences;
};
}
export interface IUser extends IRocketChatRecord, Omit<ILoggedUser, 'username' | 'name' | 'status'> { export interface IUser extends IRocketChatRecord, Omit<ILoggedUser, 'username' | 'name' | 'status'> {
_id: string; _id: string;

View File

@ -1,24 +0,0 @@
export interface IVisitorEmail {
address: string;
}
export interface IVisitorPhone {
phoneNumber: string;
}
export interface IVisitor {
_id?: string;
token: string;
username: string;
updatedAt?: Date;
name: string;
department?: string;
phone?: IVisitorPhone[];
visitorEmails?: IVisitorEmail[];
customFields?: {
[key: string]: any;
};
livechatData: {
[key: string]: any;
};
}

View File

@ -29,6 +29,12 @@ export type ChannelsEndpoints = {
messages: IMessageFromServer[]; messages: IMessageFromServer[];
}; };
}; };
'channels.archive': {
POST: (params: { roomId: string }) => void;
};
'channels.unarchive': {
POST: (params: { roomId: string }) => void;
};
'channels.create': { 'channels.create': {
POST: (params: { POST: (params: {
name: string; name: string;

View File

@ -32,4 +32,11 @@ export type ChatEndpoints = {
total: number; total: number;
}>; }>;
}; };
'chat.delete': {
POST: (params: { msgId: string; roomId: string }) => {
_id: string;
ts: string;
message: Pick<IMessage, '_id' | 'rid' | 'u'>;
};
};
}; };

View File

@ -9,4 +9,10 @@ export type E2eEndpoints = {
users: Pick<IUser, '_id' | 'e2e'>[]; users: Pick<IUser, '_id' | 'e2e'>[];
}; };
}; };
'e2e.updateGroupKey': {
POST: (params: { uid: string; rid: string; key: string }) => {};
};
'e2e.setRoomKeyID': {
POST: (params: { rid: string; keyID: string }) => {};
};
}; };

View File

@ -23,6 +23,12 @@ export type GroupsEndpoints = {
messages: IMessageFromServer[]; messages: IMessageFromServer[];
}; };
}; };
'groups.archive': {
POST: (params: { roomId: string }) => void;
};
'groups.unarchive': {
POST: (params: { roomId: string }) => void;
};
'groups.create': { 'groups.create': {
POST: (params: { POST: (params: {
name: string; name: string;

View File

@ -11,7 +11,6 @@ import { PermissionsEndpoints } from './permissions';
import { RolesEndpoints } from './roles'; import { RolesEndpoints } from './roles';
import { RoomsEndpoints } from './rooms'; import { RoomsEndpoints } from './rooms';
import { OauthCustomConfiguration } from './settings'; import { OauthCustomConfiguration } from './settings';
import { UserEndpoints } from './user';
import { UsersEndpoints } from './users'; import { UsersEndpoints } from './users';
import { TeamsEndpoints } from './teams'; import { TeamsEndpoints } from './teams';
import { E2eEndpoints } from './e2e'; import { E2eEndpoints } from './e2e';
@ -30,7 +29,6 @@ export type Endpoints = ChannelsEndpoints &
RolesEndpoints & RolesEndpoints &
RoomsEndpoints & RoomsEndpoints &
OauthCustomConfiguration & OauthCustomConfiguration &
UserEndpoints &
UsersEndpoints & UsersEndpoints &
TeamsEndpoints & TeamsEndpoints &
E2eEndpoints & E2eEndpoints &

View File

@ -20,11 +20,7 @@ export type OmnichannelEndpoints = {
}; };
'livechat/visitors.info': { 'livechat/visitors.info': {
GET: (params: { visitorId: string }) => { GET: (params: { visitorId: string }) => {
visitor: { visitor: ILivechatVisitor;
visitorEmails: Array<{
address: string;
}>;
};
}; };
}; };
'livechat/room.onHold': { 'livechat/room.onHold': {
@ -77,7 +73,7 @@ export type OmnichannelEndpoints = {
POST: (params: { upsert: string[]; remove: string[] }) => void; POST: (params: { upsert: string[]; remove: string[] }) => void;
}; };
'livechat/department/:departmentId/?includeAgents=false': { 'livechat/department/:departmentId/?includeAgents=false': {
GET: () => PaginatedResult<{ department: ILivechatDepartment[] }>; GET: () => PaginatedResult<{ department: ILivechatDepartment }>;
}; };
'livechat/departments.available-by-unit/:id': { 'livechat/departments.available-by-unit/:id': {
GET: (params: PaginatedRequest<{ text: string }>) => PaginatedResult<{ GET: (params: PaginatedRequest<{ text: string }>) => PaginatedResult<{

View File

@ -1,5 +1,8 @@
export type SubscriptionsEndpoints = { export type SubscriptionsEndpoints = {
'subscriptions.unread': { 'subscriptions.unread': {
POST: (params: { firstUnreadMessage: { _id: string } }) => {}; POST: (params: { firstUnreadMessage: { _id: string } } | { roomId: string }) => {};
};
'subscriptions.read': {
POST: (params: { rid: string }) => {};
}; };
}; };

View File

@ -1,9 +1,29 @@
import { IRoom } from '../../IRoom'; import { IRoom, IServerRoomItem } from '../../IRoom';
import { ITeam, TEAM_TYPE } from '../../ITeam'; import { IServerTeamUpdateRoom, ITeam, TEAM_TYPE } from '../../ITeam';
export type TeamsEndpoints = { export type TeamsEndpoints = {
'teams.removeRoom': { 'teams.removeRoom': {
POST: (params: { roomId: string; teamId: string }) => { room: IRoom }; POST: (params: { roomId: string; teamId: string }) => { room: IServerRoomItem };
};
'teams.listRoomsOfUser': {
GET: (params: { teamId: string; userId: string }) => {
rooms: IServerRoomItem[];
total: number;
count: number;
offset: number;
};
};
'teams.updateRoom': {
POST: (params: { roomId: string; isDefault: boolean }) => { room: IServerTeamUpdateRoom };
};
'teams.convertToChannel': {
POST: (params: { teamId: string; roomsToRemove?: string[] }) => {};
};
'teams.removeMember': {
POST: (params: { teamId: string; userId: string; rooms?: string[] }) => {};
};
'teams.addRooms': {
POST: (params: { teamId: string; rooms: string[] }) => { rooms: IRoom[] };
}; };
'teams.create': { 'teams.create': {
POST: (params: { POST: (params: {

View File

@ -1,17 +0,0 @@
import { IUser, IUserRegistered } from '../../IUser';
export type UserEndpoints = {
'users.info': {
GET: (params: { userId: IUser['_id'] }) => {
user: IUser;
success: boolean;
};
POST: (params: { userId: IUser['_id'] }) => {
user: IUser;
success: boolean;
};
};
'users.register': {
POST: (params: { name: string; email: string; username: string; pass: string }) => { user: IUserRegistered };
};
};

View File

@ -1,5 +1,6 @@
import type { ITeam } from '../../ITeam'; import type { ITeam } from '../../ITeam';
import type { IUser } from '../../IUser'; import type { IUser } from '../../IUser';
import { INotificationPreferences, IUserPreferences, IUserRegistered } from '../../IUser';
export type UsersEndpoints = { export type UsersEndpoints = {
'users.2fa.sendEmailCode': { 'users.2fa.sendEmailCode': {
@ -11,4 +12,26 @@ export type UsersEndpoints = {
'users.listTeams': { 'users.listTeams': {
GET: (params: { userId: IUser['_id'] }) => { teams: Array<ITeam> }; GET: (params: { userId: IUser['_id'] }) => { teams: Array<ITeam> };
}; };
'users.forgotPassword': {
POST: (params: { email: string }) => {};
};
'users.info': {
GET: (params: { userId: IUser['_id'] }) => {
user: IUser;
success: boolean;
};
POST: (params: { userId: IUser['_id'] }) => {
user: IUser;
success: boolean;
};
};
'users.setPreferences': {
POST: (params: { userId: IUser['_id']; data: Partial<INotificationPreferences> }) => {
user: IUserPreferences;
success: boolean;
};
};
'users.register': {
POST: (params: { name: string; email: string; username: string; pass: string }) => { user: IUserRegistered };
};
}; };

View File

@ -1,8 +1,8 @@
import { IMessage, IThreadResult } from '../../../definitions'; import { ILastMessage, IMessage, IThreadResult } from '../../../definitions';
import messagesStatus from '../../../constants/messagesStatus'; import messagesStatus from '../../../constants/messagesStatus';
import normalizeMessage from './normalizeMessage'; import normalizeMessage from './normalizeMessage';
export default (message: Partial<IMessage> | IThreadResult): Partial<IMessage> | IThreadResult => { export default (message: Partial<IMessage> | IThreadResult | ILastMessage): IMessage | IThreadResult => {
message.status = messagesStatus.SENT; message.status = messagesStatus.SENT;
return normalizeMessage(message); return normalizeMessage(message);
}; };

View File

@ -5,12 +5,19 @@ import { store as reduxStore } from '../../auxStore';
import { compareServerVersion } from '../../utils'; import { compareServerVersion } from '../../utils';
import findSubscriptionsRooms from './findSubscriptionsRooms'; import findSubscriptionsRooms from './findSubscriptionsRooms';
import normalizeMessage from './normalizeMessage'; import normalizeMessage from './normalizeMessage';
import { ISubscription, IServerRoom, IServerSubscription, IServerSubscriptionItem, IServerRoomItem } from '../../../definitions'; import {
ISubscription,
IServerRoom,
IServerSubscription,
IServerSubscriptionItem,
IServerRoomItem,
IRoom
} from '../../../definitions';
// TODO: delete and update // TODO: delete and update
export const merge = ( export const merge = (
subscription: ISubscription | IServerSubscriptionItem, subscription: ISubscription | IServerSubscriptionItem,
room?: ISubscription | IServerRoomItem room?: ISubscription | IServerRoomItem | IRoom
): ISubscription => { ): ISubscription => {
const serverVersion = reduxStore.getState().server.version as string; const serverVersion = reduxStore.getState().server.version as string;
subscription = EJSON.fromJSONValue(subscription) as ISubscription; subscription = EJSON.fromJSONValue(subscription) as ISubscription;

View File

@ -1,6 +1,7 @@
import moment from 'moment'; import moment from 'moment';
import { IMessage, MessageType, TMessageModel } from '../../definitions'; import { MessageTypeLoad } from '../../constants/messageTypeLoad';
import { IMessage, TMessageModel } from '../../definitions';
import log from '../../utils/log'; import log from '../../utils/log';
import { getMessageById } from '../database/services/Message'; import { getMessageById } from '../database/services/Message';
import roomTypeToApiType, { RoomTypes } from '../rocketchat/methods/roomTypeToApiType'; import roomTypeToApiType, { RoomTypes } from '../rocketchat/methods/roomTypeToApiType';
@ -46,7 +47,7 @@ export default function loadMessagesForRoom(args: {
_id: generateLoadMoreId(lastMessage._id as string), _id: generateLoadMoreId(lastMessage._id as string),
rid: lastMessage.rid, rid: lastMessage.rid,
ts: moment(lastMessage.ts).subtract(1, 'millisecond').toString(), ts: moment(lastMessage.ts).subtract(1, 'millisecond').toString(),
t: 'load_more' as MessageType, t: MessageTypeLoad.MORE,
msg: lastMessage.msg msg: lastMessage.msg
}; };
data.push(loadMoreMessage); data.push(loadMoreMessage);

View File

@ -16,7 +16,7 @@ const getLastUpdate = async (rid: string) => {
return null; return null;
}; };
async function load({ rid: roomId, lastOpen }: { rid: string; lastOpen: Date }) { async function load({ rid: roomId, lastOpen }: { rid: string; lastOpen?: Date }) {
let lastUpdate; let lastUpdate;
if (lastOpen) { if (lastOpen) {
lastUpdate = new Date(lastOpen).toISOString(); lastUpdate = new Date(lastOpen).toISOString();
@ -29,7 +29,7 @@ async function load({ rid: roomId, lastOpen }: { rid: string; lastOpen: Date })
return result; return result;
} }
export default function loadMissedMessages(args: { rid: string; lastOpen: Date }): Promise<void> { export default function loadMissedMessages(args: { rid: string; lastOpen?: Date }): Promise<void> {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const data = await load({ rid: args.rid, lastOpen: args.lastOpen }); const data = await load({ rid: args.rid, lastOpen: args.lastOpen });

View File

@ -4,7 +4,7 @@ import orderBy from 'lodash/orderBy';
import log from '../../utils/log'; import log from '../../utils/log';
import { getMessageById } from '../database/services/Message'; import { getMessageById } from '../database/services/Message';
import { MESSAGE_TYPE_LOAD_NEXT_CHUNK } from '../../constants/messageTypeLoad'; import { MessageTypeLoad } from '../../constants/messageTypeLoad';
import { generateLoadMoreId } from '../utils'; import { generateLoadMoreId } from '../utils';
import updateMessages from './updateMessages'; import updateMessages from './updateMessages';
import { TMessageModel } from '../../definitions'; import { TMessageModel } from '../../definitions';
@ -34,7 +34,7 @@ export default function loadNextMessages(args: ILoadNextMessages): Promise<void>
rid: lastMessage.rid, rid: lastMessage.rid,
tmid: args.tmid, tmid: args.tmid,
ts: moment(lastMessage.ts).add(1, 'millisecond'), ts: moment(lastMessage.ts).add(1, 'millisecond'),
t: MESSAGE_TYPE_LOAD_NEXT_CHUNK t: MessageTypeLoad.NEXT_CHUNK
}; };
messages.push(loadMoreItem); messages.push(loadMoreItem);
} }

View File

@ -4,21 +4,23 @@ import orderBy from 'lodash/orderBy';
import log from '../../utils/log'; import log from '../../utils/log';
import { getMessageById } from '../database/services/Message'; import { getMessageById } from '../database/services/Message';
import { MESSAGE_TYPE_LOAD_NEXT_CHUNK, MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK } from '../../constants/messageTypeLoad'; import { MessageTypeLoad } from '../../constants/messageTypeLoad';
import sdk from '../rocketchat/services/sdk';
import { IMessage } from '../../definitions';
import { generateLoadMoreId } from '../utils'; import { generateLoadMoreId } from '../utils';
import updateMessages from './updateMessages'; import updateMessages from './updateMessages';
const COUNT = 50; const COUNT = 50;
export default function loadSurroundingMessages({ messageId, rid }) { export default function loadSurroundingMessages({ messageId, rid }: { messageId: string; rid: string }) {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
const data = await this.methodCallWrapper('loadSurroundingMessages', { _id: messageId, rid }, COUNT); const data = await sdk.methodCallWrapper('loadSurroundingMessages', { _id: messageId, rid }, COUNT);
let messages = EJSON.fromJSONValue(data?.messages); let messages: IMessage[] = EJSON.fromJSONValue(data?.messages);
messages = orderBy(messages, 'ts'); messages = orderBy(messages, 'ts');
const message = messages.find(m => m._id === messageId); const message = messages.find(m => m._id === messageId);
const { tmid } = message; const tmid = message?.tmid;
if (messages?.length) { if (messages?.length) {
if (data?.moreBefore) { if (data?.moreBefore) {
@ -29,10 +31,10 @@ export default function loadSurroundingMessages({ messageId, rid }) {
_id: generateLoadMoreId(firstMessage._id), _id: generateLoadMoreId(firstMessage._id),
rid: firstMessage.rid, rid: firstMessage.rid,
tmid, tmid,
ts: moment(firstMessage.ts).subtract(1, 'millisecond'), ts: moment(firstMessage.ts).subtract(1, 'millisecond').toDate(),
t: MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK, t: MessageTypeLoad.PREVIOUS_CHUNK,
msg: firstMessage.msg msg: firstMessage.msg
}; } as IMessage;
messages.unshift(loadMoreItem); messages.unshift(loadMoreItem);
} }
} }
@ -45,18 +47,18 @@ export default function loadSurroundingMessages({ messageId, rid }) {
_id: generateLoadMoreId(lastMessage._id), _id: generateLoadMoreId(lastMessage._id),
rid: lastMessage.rid, rid: lastMessage.rid,
tmid, tmid,
ts: moment(lastMessage.ts).add(1, 'millisecond'), ts: moment(lastMessage.ts).add(1, 'millisecond').toDate(),
t: MESSAGE_TYPE_LOAD_NEXT_CHUNK, t: MessageTypeLoad.NEXT_CHUNK,
msg: lastMessage.msg msg: lastMessage.msg
}; } as IMessage;
messages.push(loadMoreItem); messages.push(loadMoreItem);
} }
} }
await updateMessages({ rid, update: messages }); await updateMessages({ rid, update: messages });
return resolve(messages); return resolve(messages);
} else {
return resolve([]);
} }
return resolve([]);
} catch (e) { } catch (e) {
log(e); log(e);
reject(e); reject(e);

View File

@ -13,7 +13,7 @@ import { E2E_PRIVATE_KEY, E2E_PUBLIC_KEY, E2E_RANDOM_PASSWORD_KEY } from '../enc
import UserPreferences from '../userPreferences'; import UserPreferences from '../userPreferences';
import { ICertificate, IRocketChat } from '../../definitions'; import { ICertificate, IRocketChat } from '../../definitions';
async function removeServerKeys({ server, userId }: { server: string; userId: string | null }) { async function removeServerKeys({ server, userId }: { server: string; userId?: string | null }) {
await UserPreferences.removeItem(`${RocketChat.TOKEN_KEY}-${server}`); await UserPreferences.removeItem(`${RocketChat.TOKEN_KEY}-${server}`);
if (userId) { if (userId) {
await UserPreferences.removeItem(`${RocketChat.TOKEN_KEY}-${userId}`); await UserPreferences.removeItem(`${RocketChat.TOKEN_KEY}-${userId}`);

View File

@ -15,11 +15,30 @@ import debounce from '../../../utils/debounce';
import RocketChat from '../../rocketchat'; import RocketChat from '../../rocketchat';
import { subscribeRoom, unsubscribeRoom } from '../../../actions/room'; import { subscribeRoom, unsubscribeRoom } from '../../../actions/room';
import { Encryption } from '../../encryption'; import { Encryption } from '../../encryption';
import { IMessage, TMessageModel, TSubscriptionModel, TThreadMessageModel, TThreadModel } from '../../../definitions';
import { IDDPMessage } from '../../../definitions/IDDPMessage';
const WINDOW_TIME = 1000; const WINDOW_TIME = 1000;
export default class RoomSubscription { export default class RoomSubscription {
constructor(rid) { private rid: string;
private isAlive: boolean;
private timer: null | number;
private queue: { [key: string]: IMessage };
private messagesBatch: {};
private _messagesBatch: { [key: string]: TMessageModel };
private threadsBatch: {};
private _threadsBatch: { [key: string]: TThreadModel };
private threadMessagesBatch: {};
private _threadMessagesBatch: { [key: string]: TThreadMessageModel };
private promises?: Promise<TSubscriptionModel[]>;
private connectedListener?: Promise<any>;
private disconnectedListener?: Promise<any>;
private notifyRoomListener?: Promise<any>;
private messageReceivedListener?: Promise<any>;
private lastOpen?: Date;
constructor(rid: string) {
this.rid = rid; this.rid = rid;
this.isAlive = true; this.isAlive = true;
this.timer = null; this.timer = null;
@ -27,6 +46,10 @@ export default class RoomSubscription {
this.messagesBatch = {}; this.messagesBatch = {};
this.threadsBatch = {}; this.threadsBatch = {};
this.threadMessagesBatch = {}; this.threadMessagesBatch = {};
this._messagesBatch = {};
this._threadsBatch = {};
this._threadMessagesBatch = {};
} }
subscribe = async () => { subscribe = async () => {
@ -41,7 +64,7 @@ export default class RoomSubscription {
this.notifyRoomListener = RocketChat.onStreamData('stream-notify-room', this.handleNotifyRoomReceived); this.notifyRoomListener = RocketChat.onStreamData('stream-notify-room', this.handleNotifyRoomReceived);
this.messageReceivedListener = RocketChat.onStreamData('stream-room-messages', this.handleMessageReceived); this.messageReceivedListener = RocketChat.onStreamData('stream-room-messages', this.handleMessageReceived);
if (!this.isAlive) { if (!this.isAlive) {
this.unsubscribe(); await this.unsubscribe();
} }
reduxStore.dispatch(subscribeRoom(this.rid)); reduxStore.dispatch(subscribeRoom(this.rid));
@ -69,7 +92,7 @@ export default class RoomSubscription {
} }
}; };
removeListener = async promise => { removeListener = async (promise?: Promise<any>): Promise<void> => {
if (promise) { if (promise) {
try { try {
const listener = await promise; const listener = await promise;
@ -85,7 +108,7 @@ export default class RoomSubscription {
RocketChat.loadMissedMessages({ rid: this.rid }).catch(e => console.log(e)); RocketChat.loadMissedMessages({ rid: this.rid }).catch(e => console.log(e));
}; };
handleNotifyRoomReceived = protectedFunction(ddpMessage => { handleNotifyRoomReceived = protectedFunction((ddpMessage: IDDPMessage) => {
const [_rid, ev] = ddpMessage.fields.eventName.split('/'); const [_rid, ev] = ddpMessage.fields.eventName.split('/');
if (this.rid !== _rid) { if (this.rid !== _rid) {
return; return;
@ -115,9 +138,9 @@ export default class RoomSubscription {
const msgCollection = db.get('messages'); const msgCollection = db.get('messages');
const threadsCollection = db.get('threads'); const threadsCollection = db.get('threads');
const threadMessagesCollection = db.get('thread_messages'); const threadMessagesCollection = db.get('thread_messages');
let deleteMessage; let deleteMessage: TMessageModel;
let deleteThread; let deleteThread: TThreadModel;
let deleteThreadMessage; let deleteThreadMessage: TThreadMessageModel;
// Delete message // Delete message
try { try {
@ -142,7 +165,7 @@ export default class RoomSubscription {
} catch (e) { } catch (e) {
// Do nothing // Do nothing
} }
await db.action(async () => { await db.write(async () => {
await db.batch(deleteMessage, deleteThread, deleteThreadMessage); await db.batch(deleteMessage, deleteThread, deleteThreadMessage);
}); });
} catch (e) { } catch (e) {
@ -153,11 +176,11 @@ export default class RoomSubscription {
} }
}); });
read = debounce(lastOpen => { read = debounce((lastOpen: Date) => {
RocketChat.readMessages(this.rid, lastOpen); RocketChat.readMessages(this.rid, lastOpen);
}, 300); }, 300);
updateMessage = message => updateMessage = (message: IMessage): Promise<void> =>
new Promise(async resolve => { new Promise(async resolve => {
if (this.rid !== message.rid) { if (this.rid !== message.rid) {
return resolve(); return resolve();
@ -177,15 +200,15 @@ export default class RoomSubscription {
const messageRecord = await getMessageById(message._id); const messageRecord = await getMessageById(message._id);
if (messageRecord) { if (messageRecord) {
operation = messageRecord.prepareUpdate( operation = messageRecord.prepareUpdate(
protectedFunction(m => { protectedFunction((m: TMessageModel) => {
Object.assign(m, message); Object.assign(m, message);
}) })
); );
} else { } else {
operation = msgCollection.prepareCreate( operation = msgCollection.prepareCreate(
protectedFunction(m => { protectedFunction((m: TMessageModel) => {
m._raw = sanitizedRaw({ id: message._id }, msgCollection.schema); m._raw = sanitizedRaw({ id: message._id }, msgCollection.schema);
m.subscription.id = this.rid; if (m.subscription) m.subscription.id = this.rid;
Object.assign(m, message); Object.assign(m, message);
}) })
); );
@ -202,15 +225,15 @@ export default class RoomSubscription {
const threadRecord = await getThreadById(message._id); const threadRecord = await getThreadById(message._id);
if (threadRecord) { if (threadRecord) {
operation = threadRecord.prepareUpdate( operation = threadRecord.prepareUpdate(
protectedFunction(t => { protectedFunction((t: TThreadModel) => {
Object.assign(t, message); Object.assign(t, message);
}) })
); );
} else { } else {
operation = threadsCollection.prepareCreate( operation = threadsCollection.prepareCreate(
protectedFunction(t => { protectedFunction((t: TThreadModel) => {
t._raw = sanitizedRaw({ id: message._id }, threadsCollection.schema); t._raw = sanitizedRaw({ id: message._id }, threadsCollection.schema);
t.subscription.id = this.rid; if (t.subscription) t.subscription.id = this.rid;
Object.assign(t, message); Object.assign(t, message);
}) })
); );
@ -228,20 +251,26 @@ export default class RoomSubscription {
const threadMessageRecord = await getThreadMessageById(message._id); const threadMessageRecord = await getThreadMessageById(message._id);
if (threadMessageRecord) { if (threadMessageRecord) {
operation = threadMessageRecord.prepareUpdate( operation = threadMessageRecord.prepareUpdate(
protectedFunction(tm => { protectedFunction((tm: TThreadMessageModel) => {
Object.assign(tm, message); Object.assign(tm, message);
if (message.tmid) {
tm.rid = message.tmid; tm.rid = message.tmid;
delete tm.tmid; delete tm.tmid;
}
}) })
); );
} else { } else {
operation = threadMessagesCollection.prepareCreate( operation = threadMessagesCollection.prepareCreate(
protectedFunction(tm => { protectedFunction((tm: TThreadMessageModel) => {
tm._raw = sanitizedRaw({ id: message._id }, threadMessagesCollection.schema); tm._raw = sanitizedRaw({ id: message._id }, threadMessagesCollection.schema);
Object.assign(tm, message); Object.assign(tm, message);
if (tm.subscription) {
tm.subscription.id = this.rid; tm.subscription.id = this.rid;
}
if (message.tmid) {
tm.rid = message.tmid; tm.rid = message.tmid;
delete tm.tmid; delete tm.tmid;
}
}) })
); );
} }
@ -254,7 +283,7 @@ export default class RoomSubscription {
return resolve(); return resolve();
}); });
handleMessageReceived = ddpMessage => { handleMessageReceived = (ddpMessage: IDDPMessage) => {
if (!this.timer) { if (!this.timer) {
this.timer = setTimeout(async () => { this.timer = setTimeout(async () => {
// copy variables values to local and clean them // copy variables values to local and clean them
@ -280,7 +309,7 @@ export default class RoomSubscription {
try { try {
const db = database.active; const db = database.active;
await db.action(async () => { await db.write(async () => {
await db.batch( await db.batch(
...Object.values(this._messagesBatch), ...Object.values(this._messagesBatch),
...Object.values(this._threadsBatch), ...Object.values(this._threadsBatch),
@ -300,7 +329,7 @@ export default class RoomSubscription {
}, WINDOW_TIME); }, WINDOW_TIME);
} }
this.lastOpen = new Date(); this.lastOpen = new Date();
const message = buildMessage(EJSON.fromJSONValue(ddpMessage.fields.args[0])); const message = buildMessage(EJSON.fromJSONValue(ddpMessage.fields.args[0])) as IMessage;
this.queue[message._id] = message; this.queue[message._id] = message;
}; };
} }

View File

@ -1,11 +1,11 @@
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord'; import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { InteractionManager } from 'react-native'; import { InteractionManager } from 'react-native';
import EJSON from 'ejson'; import EJSON from 'ejson';
import Model from '@nozbe/watermelondb/Model';
import database from '../../database'; import database from '../../database';
import { merge } from '../helpers/mergeSubscriptionsRooms'; import { merge } from '../helpers/mergeSubscriptionsRooms';
import protectedFunction from '../helpers/protectedFunction'; import protectedFunction from '../helpers/protectedFunction';
import messagesStatus from '../../../constants/messagesStatus';
import log from '../../../utils/log'; import log from '../../../utils/log';
import random from '../../../utils/random'; import random from '../../../utils/random';
import { store } from '../../auxStore'; import { store } from '../../auxStore';
@ -19,16 +19,29 @@ import { INAPP_NOTIFICATION_EMITTER } from '../../../containers/InAppNotificatio
import { Encryption } from '../../encryption'; import { Encryption } from '../../encryption';
import { E2E_MESSAGE_TYPE } from '../../encryption/constants'; import { E2E_MESSAGE_TYPE } from '../../encryption/constants';
import updateMessages from '../updateMessages'; import updateMessages from '../updateMessages';
import {
IMessage,
IRoom,
ISubscription,
TMessageModel,
TRoomModel,
TThreadMessageModel,
TThreadModel
} from '../../../definitions';
import sdk from '../../rocketchat/services/sdk';
import { IDDPMessage } from '../../../definitions/IDDPMessage';
import { getSubscriptionByRoomId } from '../../database/services/Subscription';
import { getMessageById } from '../../database/services/Message';
const removeListener = listener => listener.stop(); const removeListener = (listener: { stop: () => void }) => listener.stop();
let streamListener; let streamListener: Promise<any> | false;
let subServer; let subServer: string;
let queue = {}; let queue: { [key: string]: ISubscription } = {};
let subTimer = null; let subTimer: number | null | false = null;
const WINDOW_TIME = 500; const WINDOW_TIME = 500;
const createOrUpdateSubscription = async (subscription, room) => { const createOrUpdateSubscription = async (subscription: ISubscription, room: IRoom | ISubscription) => {
try { try {
const db = database.active; const db = database.active;
const subCollection = db.get('subscriptions'); const subCollection = db.get('subscriptions');
@ -86,12 +99,12 @@ const createOrUpdateSubscription = async (subscription, room) => {
e2eKeyId: s.e2eKeyId, e2eKeyId: s.e2eKeyId,
E2EKey: s.E2EKey, E2EKey: s.E2EKey,
avatarETag: s.avatarETag avatarETag: s.avatarETag
}; } as ISubscription;
} catch (error) { } catch (error) {
try { try {
await db.action(async () => { await db.write(async () => {
await roomsCollection.create( await roomsCollection.create(
protectedFunction(r => { protectedFunction((r: TRoomModel) => {
r._raw = sanitizedRaw({ id: room._id }, roomsCollection.schema); r._raw = sanitizedRaw({ id: room._id }, roomsCollection.schema);
Object.assign(r, room); Object.assign(r, room);
}) })
@ -121,23 +134,15 @@ const createOrUpdateSubscription = async (subscription, room) => {
departmentId: r.departmentId, departmentId: r.departmentId,
livechatData: r.livechatData, livechatData: r.livechatData,
avatarETag: r.avatarETag avatarETag: r.avatarETag
}; } as IRoom;
} catch (error) { } catch (error) {
// Do nothing // Do nothing
} }
} }
let tmp; let tmp = merge(subscription, room);
if (subscription) { tmp = (await Encryption.decryptSubscription(tmp)) as ISubscription;
tmp = merge(subscription, room); const sub = await getSubscriptionByRoomId(tmp.rid);
tmp = await Encryption.decryptSubscription(tmp);
}
let sub;
try {
sub = await subCollection.find(tmp.rid);
} catch (error) {
// Do nothing
}
// If we're receiving a E2EKey of a room // If we're receiving a E2EKey of a room
if (sub && !sub.E2EKey && subscription?.E2EKey) { if (sub && !sub.E2EKey && subscription?.E2EKey) {
@ -151,12 +156,12 @@ const createOrUpdateSubscription = async (subscription, room) => {
e2eKeyId: sub.e2eKeyId e2eKeyId: sub.e2eKeyId
}); });
// Decrypt lastMessage using the received E2EKey // Decrypt lastMessage using the received E2EKey
tmp = await Encryption.decryptSubscription(tmp); tmp = (await Encryption.decryptSubscription(tmp)) as ISubscription;
// Decrypt all pending messages of this room in parallel // Decrypt all pending messages of this room in parallel
Encryption.decryptPendingMessages(tmp.rid); Encryption.decryptPendingMessages(tmp.rid);
} }
const batch = []; const batch: Model[] = [];
if (sub) { if (sub) {
try { try {
const update = sub.prepareUpdate(s => { const update = sub.prepareUpdate(s => {
@ -190,12 +195,7 @@ const createOrUpdateSubscription = async (subscription, room) => {
if (tmp.lastMessage && !rooms.includes(tmp.rid)) { if (tmp.lastMessage && !rooms.includes(tmp.rid)) {
const lastMessage = buildMessage(tmp.lastMessage); const lastMessage = buildMessage(tmp.lastMessage);
const messagesCollection = db.get('messages'); const messagesCollection = db.get('messages');
let messageRecord; const messageRecord = await getMessageById(lastMessage._id);
try {
messageRecord = await messagesCollection.find(lastMessage._id);
} catch (error) {
// Do nothing
}
if (messageRecord) { if (messageRecord) {
batch.push( batch.push(
@ -207,14 +207,16 @@ const createOrUpdateSubscription = async (subscription, room) => {
batch.push( batch.push(
messagesCollection.prepareCreate(m => { messagesCollection.prepareCreate(m => {
m._raw = sanitizedRaw({ id: lastMessage._id }, messagesCollection.schema); m._raw = sanitizedRaw({ id: lastMessage._id }, messagesCollection.schema);
if (m.subscription) {
m.subscription.id = lastMessage.rid; m.subscription.id = lastMessage.rid;
}
return Object.assign(m, lastMessage); return Object.assign(m, lastMessage);
}) })
); );
} }
} }
await db.action(async () => { await db.write(async () => {
await db.batch(...batch); await db.batch(...batch);
}); });
} catch (e) { } catch (e) {
@ -222,11 +224,11 @@ const createOrUpdateSubscription = async (subscription, room) => {
} }
}; };
const getSubQueueId = rid => `SUB-${rid}`; const getSubQueueId = (rid: string) => `SUB-${rid}`;
const getRoomQueueId = rid => `ROOM-${rid}`; const getRoomQueueId = (rid: string) => `ROOM-${rid}`;
const debouncedUpdate = subscription => { const debouncedUpdate = (subscription: ISubscription) => {
if (!subTimer) { if (!subTimer) {
subTimer = setTimeout(() => { subTimer = setTimeout(() => {
const batch = queue; const batch = queue;
@ -257,11 +259,11 @@ const debouncedUpdate = subscription => {
}; };
export default function subscribeRooms() { export default function subscribeRooms() {
const handleStreamMessageReceived = protectedFunction(async ddpMessage => { const handleStreamMessageReceived = protectedFunction(async (ddpMessage: IDDPMessage) => {
const db = database.active; const db = database.active;
// check if the server from variable is the same as the js sdk client // check if the server from variable is the same as the js sdk client
if (this.sdk && this.sdk.client && this.sdk.client.host !== subServer) { if (sdk && sdk.current.client && sdk.current.client.host !== subServer) {
return; return;
} }
if (ddpMessage.msg === 'added') { if (ddpMessage.msg === 'added') {
@ -274,7 +276,7 @@ export default function subscribeRooms() {
if (diff?.statusLivechat) { if (diff?.statusLivechat) {
store.dispatch(setUser({ statusLivechat: diff.statusLivechat })); store.dispatch(setUser({ statusLivechat: diff.statusLivechat }));
} }
if (['settings.preferences.showMessageInMainThread'] in diff) { if ((['settings.preferences.showMessageInMainThread'] as any) in diff) {
store.dispatch(setUser({ showMessageInMainThread: diff['settings.preferences.showMessageInMainThread'] })); store.dispatch(setUser({ showMessageInMainThread: diff['settings.preferences.showMessageInMainThread'] }));
} }
} }
@ -283,13 +285,19 @@ export default function subscribeRooms() {
try { try {
const subCollection = db.get('subscriptions'); const subCollection = db.get('subscriptions');
const sub = await subCollection.find(data.rid); const sub = await subCollection.find(data.rid);
const messages = await sub.messages.fetch(); // TODO - today the Relation type from watermelon just support one to one relations
const threads = await sub.threads.fetch(); // @ts-ignore
const threadMessages = await sub.threadMessages.fetch(); const messages = (await sub.messages.fetch()) as TMessageModel[];
const messagesToDelete = messages.map(m => m.prepareDestroyPermanently()); // @ts-ignore
const threadsToDelete = threads.map(m => m.prepareDestroyPermanently()); const threads = (await sub.threads.fetch()) as TThreadModel[];
const threadMessagesToDelete = threadMessages.map(m => m.prepareDestroyPermanently()); // @ts-ignore
await db.action(async () => { const threadMessages = (await sub.threadMessages.fetch()) as TThreadMessageModel[];
const messagesToDelete = messages?.map((m: TMessageModel) => m.prepareDestroyPermanently());
const threadsToDelete = threads?.map((m: TThreadModel) => m.prepareDestroyPermanently());
const threadMessagesToDelete = threadMessages?.map((m: TThreadMessageModel) => m.prepareDestroyPermanently());
await db.write(async () => {
await db.batch(sub.prepareDestroyPermanently(), ...messagesToDelete, ...threadsToDelete, ...threadMessagesToDelete); await db.batch(sub.prepareDestroyPermanently(), ...messagesToDelete, ...threadsToDelete, ...threadMessagesToDelete);
}); });
@ -318,13 +326,14 @@ export default function subscribeRooms() {
const [args] = ddpMessage.fields.args; const [args] = ddpMessage.fields.args;
const _id = random(17); const _id = random(17);
const message = { const message = {
// @ts-ignore
u: { u: {
_id, _id,
username: 'rocket.cat', username: 'rocket.cat',
name: 'Rocket Cat' name: 'Rocket Cat'
}, },
...buildMessage(EJSON.fromJSONValue(args)) ...buildMessage(EJSON.fromJSONValue(args))
}; } as IMessage;
await updateMessages({ rid: args.rid, update: [message] }); await updateMessages({ rid: args.rid, update: [message] });
} catch (e) { } catch (e) {
log(e); log(e);
@ -383,12 +392,12 @@ export default function subscribeRooms() {
} }
}; };
streamListener = this.sdk.onStreamData('stream-notify-user', handleStreamMessageReceived); streamListener = sdk.onStreamData('stream-notify-user', handleStreamMessageReceived);
try { try {
// set the server that started this task // set the server that started this task
subServer = this.sdk.client.host; subServer = sdk.current.client.host;
this.sdk.subscribeNotifyUser().catch(e => console.log(e)); sdk.current.subscribeNotifyUser().catch((e: unknown) => console.log(e));
return { return {
stop: () => stop() stop: () => stop()

View File

@ -4,17 +4,25 @@ enum ETypes {
Groups = 'groups' Groups = 'groups'
} }
export const types = { export type RoomTypes = 'c' | 'd' | 'p' | 'l';
type ApiTypes<T> = T extends 'c'
? ETypes.Channels
: T extends 'd'
? ETypes.Im
: T extends 'p'
? ETypes.Groups
: T extends 'l'
? ETypes.Channels
: never;
export const types: { [K in RoomTypes]: ApiTypes<K> } = {
c: ETypes.Channels, c: ETypes.Channels,
d: ETypes.Im, d: ETypes.Im,
p: ETypes.Groups, p: ETypes.Groups,
l: ETypes.Channels l: ETypes.Channels
}; };
// TODO: refactor this const roomTypeToApiType = <T extends RoomTypes>(t: T) => types[t];
export type RoomTypes = keyof typeof types;
type ApiTypes = typeof types[RoomTypes];
const roomTypeToApiType = (t: RoomTypes): ApiTypes => types[t];
export default roomTypeToApiType; export default roomTypeToApiType;

View File

@ -1,7 +1,7 @@
import { SubscriptionType } from '../../../definitions'; import sdk from './sdk';
import { TEAM_TYPE } from '../../../definitions/ITeam'; import { TEAM_TYPE } from '../../../definitions/ITeam';
import roomTypeToApiType, { RoomTypes } from '../methods/roomTypeToApiType'; import roomTypeToApiType, { RoomTypes } from '../methods/roomTypeToApiType';
import sdk from './sdk'; import { SubscriptionType, INotificationPreferences } from '../../../definitions';
export const createChannel = ({ export const createChannel = ({
name, name,
@ -37,7 +37,7 @@ export const e2eSetUserPublicAndPrivateKeys = (public_key: string, private_key:
// RC 2.2.0 // RC 2.2.0
sdk.post('e2e.setUserPublicAndPrivateKeys', { public_key, private_key }); sdk.post('e2e.setUserPublicAndPrivateKeys', { public_key, private_key });
export const e2eRequestSubscriptionKeys = (): any => export const e2eRequestSubscriptionKeys = (): Promise<boolean> =>
// RC 0.72.0 // RC 0.72.0
sdk.methodCallWrapper('e2e.requestSubscriptionKeys'); sdk.methodCallWrapper('e2e.requestSubscriptionKeys');
@ -45,16 +45,12 @@ export const e2eGetUsersOfRoomWithoutKey = (rid: string) =>
// RC 0.70.0 // RC 0.70.0
sdk.get('e2e.getUsersOfRoomWithoutKey', { rid }); sdk.get('e2e.getUsersOfRoomWithoutKey', { rid });
export const e2eSetRoomKeyID = (rid: string, keyID: string): any => export const e2eSetRoomKeyID = (rid: string, keyID: string) =>
// RC 0.70.0 // RC 0.70.0
// TODO: missing definitions from server
// @ts-ignore
sdk.post('e2e.setRoomKeyID', { rid, keyID }); sdk.post('e2e.setRoomKeyID', { rid, keyID });
export const e2eUpdateGroupKey = (uid: string, rid: string, key: string): any => export const e2eUpdateGroupKey = (uid: string, rid: string, key: string): any =>
// RC 0.70.0 // RC 0.70.0
// TODO: missing definitions from server
// @ts-ignore
sdk.post('e2e.updateGroupKey', { uid, rid, key }); sdk.post('e2e.updateGroupKey', { uid, rid, key });
export const e2eRequestRoomKey = (rid: string, e2eKeyId: string) => export const e2eRequestRoomKey = (rid: string, e2eKeyId: string) =>
@ -71,10 +67,8 @@ export const register = (credentials: { name: string; email: string; pass: strin
// RC 0.50.0 // RC 0.50.0
sdk.post('users.register', credentials); sdk.post('users.register', credentials);
export const forgotPassword = (email: string): any => export const forgotPassword = (email: string) =>
// RC 0.64.0 // RC 0.64.0
// TODO: missing definitions from server
// @ts-ignore
sdk.post('users.forgotPassword', { email }); sdk.post('users.forgotPassword', { email });
export const sendConfirmationEmail = (email: string): Promise<{ message: string; success: boolean }> => export const sendConfirmationEmail = (email: string): Promise<{ message: string; success: boolean }> =>
@ -119,7 +113,7 @@ export const getDiscussions = ({
count, count,
text text
}: { }: {
roomId: string | undefined; roomId: string;
text?: string | undefined; text?: string | undefined;
offset: number; offset: number;
count: number; count: number;
@ -164,10 +158,8 @@ export const createTeam = ({
// RC 3.13.0 // RC 3.13.0
return sdk.post('teams.create', params); return sdk.post('teams.create', params);
}; };
export const addRoomsToTeam = ({ teamId, rooms }: { teamId: string; rooms: string[] }): any => export const addRoomsToTeam = ({ teamId, rooms }: { teamId: string; rooms: string[] }) =>
// RC 3.13.0 // RC 3.13.0
// TODO: missing definitions from server
// @ts-ignore
sdk.post('teams.addRooms', { teamId, rooms }); sdk.post('teams.addRooms', { teamId, rooms });
export const removeTeamRoom = ({ roomId, teamId }: { roomId: string; teamId: string }) => export const removeTeamRoom = ({ roomId, teamId }: { roomId: string; teamId: string }) =>
@ -184,10 +176,8 @@ export const leaveTeam = ({ teamId, rooms }: { teamId: string; rooms: string[] }
...(rooms?.length && { rooms }) ...(rooms?.length && { rooms })
}); });
export const removeTeamMember = ({ teamId, userId, rooms }: { teamId: string; userId: string; rooms: string[] }): any => export const removeTeamMember = ({ teamId, userId, rooms }: { teamId: string; userId: string; rooms: string[] }) =>
// RC 3.13.0 // RC 3.13.0
// TODO: missing definitions from server
// @ts-ignore
sdk.post('teams.removeMember', { sdk.post('teams.removeMember', {
teamId, teamId,
userId, userId,
@ -195,10 +185,8 @@ export const removeTeamMember = ({ teamId, userId, rooms }: { teamId: string; us
...(rooms?.length && { rooms }) ...(rooms?.length && { rooms })
}); });
export const updateTeamRoom = ({ roomId, isDefault }: { roomId: string; isDefault: boolean }): any => export const updateTeamRoom = ({ roomId, isDefault }: { roomId: string; isDefault: boolean }) =>
// RC 3.13.0 // RC 3.13.0
// TODO: missing definitions from server
// @ts-ignore
sdk.post('teams.updateRoom', { roomId, isDefault }); sdk.post('teams.updateRoom', { roomId, isDefault });
export const deleteTeam = ({ teamId, roomsToRemove }: { teamId: string; roomsToRemove: string[] }): any => export const deleteTeam = ({ teamId, roomsToRemove }: { teamId: string; roomsToRemove: string[] }): any =>
@ -207,10 +195,8 @@ export const deleteTeam = ({ teamId, roomsToRemove }: { teamId: string; roomsToR
// @ts-ignore // @ts-ignore
sdk.post('teams.delete', { teamId, roomsToRemove }); sdk.post('teams.delete', { teamId, roomsToRemove });
export const teamListRoomsOfUser = ({ teamId, userId }: { teamId: string; userId: string }): any => export const teamListRoomsOfUser = ({ teamId, userId }: { teamId: string; userId: string }) =>
// RC 3.13.0 // RC 3.13.0
// TODO: missing definitions from server
// @ts-ignore
sdk.get('teams.listRoomsOfUser', { teamId, userId }); sdk.get('teams.listRoomsOfUser', { teamId, userId });
export const convertChannelToTeam = ({ rid, name, type }: { rid: string; name: string; type: 'c' | 'p' }) => { export const convertChannelToTeam = ({ rid, name, type }: { rid: string; name: string; type: 'c' | 'p' }) => {
@ -228,13 +214,11 @@ export const convertChannelToTeam = ({ rid, name, type }: { rid: string; name: s
return sdk.post(type === 'c' ? 'channels.convertToTeam' : 'groups.convertToTeam', params); return sdk.post(type === 'c' ? 'channels.convertToTeam' : 'groups.convertToTeam', params);
}; };
export const convertTeamToChannel = ({ teamId, selected }: { teamId: string; selected: string[] }): any => { export const convertTeamToChannel = ({ teamId, selected }: { teamId: string; selected: string[] }) => {
const params = { const params = {
teamId, teamId,
...(selected.length && { roomsToRemove: selected }) ...(selected.length && { roomsToRemove: selected })
}; };
// TODO: missing definitions from server
// @ts-ignore
return sdk.post('teams.convertToChannel', params); return sdk.post('teams.convertToChannel', params);
}; };
@ -249,10 +233,8 @@ export const joinRoom = (roomId: string, joinCode: string | null, type: 'c' | 'p
return sdk.post('channels.join', { roomId, joinCode }); return sdk.post('channels.join', { roomId, joinCode });
}; };
export const deleteMessage = (messageId: string, rid: string): any => export const deleteMessage = (messageId: string, rid: string) =>
// RC 0.48.0 // RC 0.48.0
// TODO: missing definitions from server
// @ts-ignore
sdk.post('chat.delete', { msgId: messageId, roomId: rid }); sdk.post('chat.delete', { msgId: messageId, roomId: rid });
export const markAsUnread = ({ messageId }: { messageId: string }) => export const markAsUnread = ({ messageId }: { messageId: string }) =>
@ -291,10 +273,8 @@ export const reportMessage = (messageId: string): any =>
// @ts-ignore // @ts-ignore
sdk.post('chat.reportMessage', { messageId, description: 'Message reported by user' }); sdk.post('chat.reportMessage', { messageId, description: 'Message reported by user' });
export const setUserPreferences = (userId: string, data: any): any => export const setUserPreferences = (userId: string, data: Partial<INotificationPreferences>) =>
// RC 0.62.0 // RC 0.62.0
// TODO: missing definitions from server
// @ts-ignore
sdk.post('users.setPreferences', { userId, data }); sdk.post('users.setPreferences', { userId, data });
export const setUserStatus = (status?: string, message?: string): any => export const setUserStatus = (status?: string, message?: string): any =>
@ -309,14 +289,10 @@ export const setReaction = (emoji: string, messageId: string): any =>
// @ts-ignore // @ts-ignore
sdk.post('chat.react', { emoji, messageId }); sdk.post('chat.react', { emoji, messageId });
export const toggleRead = (read: boolean, roomId: string): any => { export const toggleRead = (read: boolean, roomId: string) => {
if (read) { if (read) {
// TODO: missing definitions from server
// @ts-ignore
return sdk.post('subscriptions.unread', { roomId }); return sdk.post('subscriptions.unread', { roomId });
} }
// TODO: missing definitions from server
// @ts-ignore
return sdk.post('subscriptions.read', { rid: roomId }); return sdk.post('subscriptions.read', { rid: roomId });
}; };
@ -461,7 +437,7 @@ export const getListCannedResponse = ({ scope = '', departmentId = '', offset =
return sdk.get('canned-responses', params); return sdk.get('canned-responses', params);
}; };
export const toggleBlockUser = (rid: string, blocked: string, block: boolean) => { export const toggleBlockUser = (rid: string, blocked: string, block: boolean): Promise<boolean> => {
if (block) { if (block) {
// RC 0.49.0 // RC 0.49.0
return sdk.methodCallWrapper('blockUser', { rid, blocked }); return sdk.methodCallWrapper('blockUser', { rid, blocked });
@ -572,17 +548,14 @@ export const ignoreUser = ({ rid, userId, ignore }: { rid: string; userId: strin
// @ts-ignore // @ts-ignore
sdk.get('chat.ignoreUser', { rid, userId, ignore }); sdk.get('chat.ignoreUser', { rid, userId, ignore });
export const toggleArchiveRoom = (roomId: string, t: SubscriptionType, archive: boolean): any => { export const toggleArchiveRoom = (roomId: string, t: SubscriptionType, archive: boolean) => {
const type = t as SubscriptionType.CHANNEL | SubscriptionType.GROUP;
if (archive) { if (archive) {
// RC 0.48.0 // RC 0.48.0
// TODO: missing definitions from server return sdk.post(`${roomTypeToApiType(type)}.archive`, { roomId });
// @ts-ignore
return sdk.post(`${roomTypeToApiType(t)}.archive`, { roomId });
} }
// RC 0.48.0 // RC 0.48.0
// TODO: missing definitions from server return sdk.post(`${roomTypeToApiType(type)}.unarchive`, { roomId });
// @ts-ignore
return sdk.post(`${roomTypeToApiType(t)}.unarchive`, { roomId });
}; };
export const hideRoom = (roomId: string, t: RoomTypes): any => export const hideRoom = (roomId: string, t: RoomTypes): any =>
@ -591,7 +564,22 @@ export const hideRoom = (roomId: string, t: RoomTypes): any =>
// @ts-ignore // @ts-ignore
sdk.post(`${roomTypeToApiType(t)}.close`, { roomId }); sdk.post(`${roomTypeToApiType(t)}.close`, { roomId });
export const saveRoomSettings = (rid: string, params: any) => export const saveRoomSettings = (
rid: string,
params: {
roomName?: string;
roomAvatar?: string;
roomDescription?: string;
roomTopic?: string;
roomAnnouncement?: string;
roomType?: SubscriptionType;
readOnly?: boolean;
reactWhenReadOnly?: boolean;
systemMessages?: string[];
joinCode?: string;
encrypted?: boolean;
}
): Promise<{ result: boolean; rid: string }> =>
// RC 0.55.0 // RC 0.55.0
sdk.methodCallWrapper('saveRoomSettings', rid, params); sdk.methodCallWrapper('saveRoomSettings', rid, params);

View File

@ -39,6 +39,7 @@ export type ModalStackParamList = {
member: any; member: any;
rid: string; rid: string;
t: SubscriptionType; t: SubscriptionType;
showCloseModal?: boolean;
}; };
SelectListView: { SelectListView: {
data: any; data: any;

View File

@ -53,10 +53,11 @@ export type ChatsStackParamList = {
isRadio?: boolean; isRadio?: boolean;
}; };
RoomInfoView: { RoomInfoView: {
room: ISubscription; room?: ISubscription;
member: any; member: any;
rid: string; rid: string;
t: SubscriptionType; t: SubscriptionType;
showCloseModal?: boolean;
}; };
RoomInfoEditView: { RoomInfoEditView: {
rid: string; rid: string;

View File

@ -18,7 +18,7 @@ import { getUserSelector } from '../selectors/login';
import Button from '../containers/Button'; import Button from '../containers/Button';
import SafeAreaView from '../containers/SafeAreaView'; import SafeAreaView from '../containers/SafeAreaView';
import { MultiSelect } from '../containers/UIKit/MultiSelect'; import { MultiSelect } from '../containers/UIKit/MultiSelect';
import { IVisitor } from '../definitions/IVisitor'; import { ILivechatVisitor } from '../definitions/ILivechatVisitor';
import { ITagsOmnichannel } from '../definitions/ITagsOmnichannel'; import { ITagsOmnichannel } from '../definitions/ITagsOmnichannel';
import { IApplicationState, ISubscription } from '../definitions'; import { IApplicationState, ISubscription } from '../definitions';
import { ChatsStackParamList } from '../stacks/types'; import { ChatsStackParamList } from '../stacks/types';
@ -55,15 +55,18 @@ interface IField {
} }
interface IInputs { interface IInputs {
[key: string]: string | string[] | undefined; livechatData: {
[key: string]: any;
};
name: string; name: string;
email: string; email: string;
phone?: string; phone?: string;
topic: string; topic: string;
tag: string[]; tag: string[];
[key: string]: any;
} }
type TParams = IVisitor & IInputs; type TParams = ILivechatVisitor & IInputs;
interface ILivechat extends ISubscription { interface ILivechat extends ISubscription {
// Param dynamic depends on server // Param dynamic depends on server

View File

@ -513,6 +513,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
} }
const result = await RocketChat.teamListRoomsOfUser({ teamId: room.teamId, userId }); const result = await RocketChat.teamListRoomsOfUser({ teamId: room.teamId, userId });
if (result.success) {
if (result.rooms?.length) { if (result.rooms?.length) {
const teamChannels = result.rooms.map((r: any) => ({ const teamChannels = result.rooms.map((r: any) => ({
rid: r._id, rid: r._id,
@ -528,6 +529,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
} else { } else {
this.convertTeamToChannelConfirmation(); this.convertTeamToChannelConfirmation();
} }
}
} catch (e) { } catch (e) {
this.convertTeamToChannelConfirmation(); this.convertTeamToChannelConfirmation();
} }
@ -572,6 +574,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
} }
const result = await RocketChat.teamListRoomsOfUser({ teamId: room.teamId, userId }); const result = await RocketChat.teamListRoomsOfUser({ teamId: room.teamId, userId });
if (result.success) {
if (result.rooms?.length) { if (result.rooms?.length) {
const teamChannels = result.rooms.map((r: any) => ({ const teamChannels = result.rooms.map((r: any) => ({
rid: r._id, rid: r._id,
@ -581,7 +584,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
})); }));
navigation.navigate('SelectListView', { navigation.navigate('SelectListView', {
title: 'Leave_Team', title: 'Leave_Team',
data: teamChannels, data: teamChannels as any,
infoText: 'Select_Team_Channels', infoText: 'Select_Team_Channels',
nextAction: data => dispatch(leaveRoom(ERoomType.t, room, data)), nextAction: data => dispatch(leaveRoom(ERoomType.t, room, data)),
showAlert: () => showErrorAlert(I18n.t('Last_owner_team_room'), I18n.t('Cannot_leave')) showAlert: () => showErrorAlert(I18n.t('Last_owner_team_room'), I18n.t('Cannot_leave'))
@ -593,6 +596,7 @@ class RoomActionsView extends React.Component<IRoomActionsViewProps, IRoomAction
onPress: () => dispatch(leaveRoom(ERoomType.t, room)) onPress: () => dispatch(leaveRoom(ERoomType.t, room))
}); });
} }
}
} catch (e) { } catch (e) {
showConfirmationAlert({ showConfirmationAlert({
message: I18n.t('You_are_leaving_the_team', { team: RocketChat.getRoomTitle(room) }), message: I18n.t('You_are_leaving_the_team', { team: RocketChat.getRoomTitle(room) }),

View File

@ -1,43 +1,35 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types';
import I18n from '../../i18n'; import I18n from '../../i18n';
import { ISubscription } from '../../definitions';
import Item from './Item'; import Item from './Item';
const Channel = ({ room, theme }) => { const Channel = ({ room }: { room: ISubscription }) => {
const { description, topic, announcement } = room; const { description, topic, announcement } = room;
return ( return (
<> <>
<Item <Item
label={I18n.t('Description')} label={I18n.t('Description')}
content={description || `__${I18n.t('No_label_provided', { label: 'description' })}__`} content={description || `__${I18n.t('No_label_provided', { label: 'description' })}__`}
theme={theme}
testID='room-info-view-description' testID='room-info-view-description'
/> />
<Item <Item
label={I18n.t('Topic')} label={I18n.t('Topic')}
content={topic || `__${I18n.t('No_label_provided', { label: 'topic' })}__`} content={topic || `__${I18n.t('No_label_provided', { label: 'topic' })}__`}
theme={theme}
testID='room-info-view-topic' testID='room-info-view-topic'
/> />
<Item <Item
label={I18n.t('Announcement')} label={I18n.t('Announcement')}
content={announcement || `__${I18n.t('No_label_provided', { label: 'announcement' })}__`} content={announcement || `__${I18n.t('No_label_provided', { label: 'announcement' })}__`}
theme={theme}
testID='room-info-view-announcement' testID='room-info-view-announcement'
/> />
<Item <Item
label={I18n.t('Broadcast_Channel')} label={I18n.t('Broadcast_Channel')}
content={room.broadcast && I18n.t('Broadcast_channel_Description')} content={room.broadcast && I18n.t('Broadcast_channel_Description')}
theme={theme}
testID='room-info-view-broadcast' testID='room-info-view-broadcast'
/> />
</> </>
); );
}; };
Channel.propTypes = {
room: PropTypes.object,
theme: PropTypes.string
};
export default Channel; export default Channel;

View File

@ -1,23 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import Item from './Item';
const CustomFields = ({ customFields, theme }) => {
if (customFields) {
return Object.keys(customFields).map(title => {
if (!customFields[title]) {
return;
}
return <Item label={title} content={customFields[title]} theme={theme} />;
});
}
return null;
};
CustomFields.propTypes = {
customFields: PropTypes.object,
theme: PropTypes.string
};
export default CustomFields;

View File

@ -0,0 +1,22 @@
import React from 'react';
import Item from './Item';
const CustomFields = ({ customFields }: { customFields: { [key: string]: string } }) => {
if (customFields) {
return (
<>
{Object.keys(customFields).map((title: string) => {
if (!customFields[title]) {
return null;
}
return <Item label={title} content={customFields[title]} />;
})}
</>
);
}
return null;
};
export default CustomFields;

View File

@ -1,15 +1,17 @@
import React from 'react'; import React from 'react';
import { Text, View } from 'react-native'; import { Text, View } from 'react-native';
import PropTypes from 'prop-types';
import { themes } from '../../constants/colors'; import { themes } from '../../constants/colors';
import I18n from '../../i18n'; import I18n from '../../i18n';
import { useTheme } from '../../theme';
import Timezone from './Timezone'; import Timezone from './Timezone';
import CustomFields from './CustomFields'; import CustomFields from './CustomFields';
import styles from './styles'; import styles from './styles';
const Roles = ({ roles, theme }) => const Roles = ({ roles }: { roles: string[] }) => {
roles && roles.length ? ( const { theme } = useTheme();
if (roles && roles.length) {
<View style={styles.item}> <View style={styles.item}>
<Text style={[styles.itemLabel, { color: themes[theme].titleText }]}>{I18n.t('Roles')}</Text> <Text style={[styles.itemLabel, { color: themes[theme].titleText }]}>{I18n.t('Roles')}</Text>
<View style={styles.rolesContainer}> <View style={styles.rolesContainer}>
@ -21,23 +23,18 @@ const Roles = ({ roles, theme }) =>
) : null ) : null
)} )}
</View> </View>
</View> </View>;
) : null; }
Roles.propTypes = {
roles: PropTypes.array, return null;
theme: PropTypes.string
}; };
const Direct = ({ roomUser, theme }) => ( const Direct = ({ roomUser }: { roomUser: any }) => (
<> <>
<Roles roles={roomUser.parsedRoles} theme={theme} /> <Roles roles={roomUser.parsedRoles} />
<Timezone utcOffset={roomUser.utcOffset} theme={theme} /> <Timezone utcOffset={roomUser.utcOffset} />
<CustomFields customFields={roomUser.customFields} theme={theme} /> <CustomFields customFields={roomUser.customFields} />
</> </>
); );
Direct.propTypes = {
roomUser: PropTypes.object,
theme: PropTypes.string
};
export default Direct; export default Direct;

View File

@ -1,25 +1,32 @@
import React from 'react'; import React from 'react';
import { Text, View } from 'react-native'; import { Text, View } from 'react-native';
import PropTypes from 'prop-types';
import Markdown from '../../containers/markdown'; import Markdown from '../../containers/markdown';
import { themes } from '../../constants/colors'; import { themes } from '../../constants/colors';
import { useTheme } from '../../theme';
import styles from './styles'; import styles from './styles';
const Item = ({ label, content, theme, testID }) => interface IItem {
content ? ( label?: string;
content?: string;
testID?: string;
}
const Item = ({ label, content, testID }: IItem) => {
const { theme } = useTheme();
if (!content) {
return null;
}
return (
<View style={styles.item} testID={testID}> <View style={styles.item} testID={testID}>
<Text accessibilityLabel={label} style={[styles.itemLabel, { color: themes[theme].titleText }]}> <Text accessibilityLabel={label} style={[styles.itemLabel, { color: themes[theme].titleText }]}>
{label} {label}
</Text> </Text>
<Markdown style={[styles.itemContent, { color: themes[theme].auxiliaryText }]} msg={content} theme={theme} /> <Markdown style={[styles.itemContent, { color: themes[theme].auxiliaryText }]} msg={content} theme={theme} />
</View> </View>
) : null; );
Item.propTypes = {
label: PropTypes.string,
content: PropTypes.string,
theme: PropTypes.string,
testID: PropTypes.string
}; };
export default Item; export default Item;

View File

@ -1,15 +1,17 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { StyleSheet, Text } from 'react-native'; import { StyleSheet, Text } from 'react-native';
import PropTypes from 'prop-types';
import RocketChat from '../../lib/rocketchat'; import RocketChat from '../../lib/rocketchat';
import { withTheme } from '../../theme'; import { useTheme } from '../../theme';
import sharedStyles from '../Styles'; import sharedStyles from '../Styles';
import { themes } from '../../constants/colors'; import { themes } from '../../constants/colors';
import I18n from '../../i18n'; import I18n from '../../i18n';
import { ISubscription } from '../../definitions';
import { ILivechatVisitorModified } from './index';
import CustomFields from './CustomFields'; import CustomFields from './CustomFields';
import Item from './Item'; import Item from './Item';
import Timezone from './Timezone'; import Timezone from './Timezone';
import { ILivechatDepartment } from '../../definitions/ILivechatDepartment';
const styles = StyleSheet.create({ const styles = StyleSheet.create({
title: { title: {
@ -19,20 +21,19 @@ const styles = StyleSheet.create({
} }
}); });
const Title = ({ title, theme }) => <Text style={[styles.title, { color: themes[theme].titleText }]}>{title}</Text>; const Title = ({ title, theme }: { title: string; theme: string }) => (
Title.propTypes = { <Text style={[styles.title, { color: themes[theme].titleText }]}>{title}</Text>
title: PropTypes.string, );
theme: PropTypes.string
};
const Livechat = ({ room, roomUser, theme }) => { const Livechat = ({ room, roomUser }: { room: ISubscription; roomUser: ILivechatVisitorModified }) => {
const [department, setDepartment] = useState({}); const [department, setDepartment] = useState<ILivechatDepartment>({} as ILivechatDepartment);
const { theme } = useTheme();
const getDepartment = async id => { const getDepartment = async (id: string) => {
if (id) { if (id) {
const result = await RocketChat.getDepartmentInfo(id); const result = await RocketChat.getDepartmentInfo(id);
if (result.success) { if (result.success) {
setDepartment(result.department); setDepartment(result.department as ILivechatDepartment);
} }
} }
}; };
@ -50,37 +51,34 @@ const Livechat = ({ room, roomUser, theme }) => {
return ( return (
<> <>
<Title title={I18n.t('User')} theme={theme} /> <Title title={I18n.t('User')} theme={theme} />
<Timezone utcOffset={roomUser.utc} theme={theme} /> <Timezone utcOffset={roomUser.utc} />
<Item label={I18n.t('Username')} content={roomUser.username} theme={theme} /> <Item label={I18n.t('Username')} content={roomUser.username} />
<Item <Item
label={I18n.t('Email')} label={I18n.t('Email')}
content={roomUser.visitorEmails?.map(email => email.address).reduce((ret, item) => `${ret}${item}\n`)} content={roomUser.visitorEmails?.map(email => email.address).reduce((ret, item) => `${ret}${item}\n`)}
theme={theme}
/> />
<Item <Item
label={I18n.t('Phone')} label={I18n.t('Phone')}
content={roomUser.phone?.map(phone => phone.phoneNumber).reduce((ret, item) => `${ret}${item}\n`)} content={roomUser.phone?.map(phone => phone.phoneNumber).reduce((ret, item) => `${ret}${item}\n`)}
theme={theme}
/> />
<Item label={I18n.t('IP')} content={roomUser.ip} theme={theme} /> <Item label={I18n.t('IP')} content={roomUser.ip} />
<Item label={I18n.t('OS')} content={roomUser.os} theme={theme} /> <Item label={I18n.t('OS')} content={roomUser.os} />
<Item label={I18n.t('Browser')} content={roomUser.browser} theme={theme} /> <Item label={I18n.t('Browser')} content={roomUser.browser} />
<CustomFields customFields={roomUser.livechatData} theme={theme} /> <CustomFields customFields={roomUser.livechatData} />
<Title title={I18n.t('Conversation')} theme={theme} /> <Title title={I18n.t('Conversation')} theme={theme} />
<Item label={I18n.t('Agent')} content={room.servedBy?.username} theme={theme} /> <Item label={I18n.t('Agent')} content={room.servedBy?.username} />
<Item label={I18n.t('Facebook')} content={room.facebook?.page.name} theme={theme} /> {/* TODO: Will be deprecated */}
<Item label={I18n.t('SMS')} content={room.sms && 'SMS Enabled'} theme={theme} /> {/* @ts-ignore */}
<Item label={I18n.t('Topic')} content={room.topic} theme={theme} /> <Item label={I18n.t('Facebook')} content={room.facebook?.page.name} />
<Item label={I18n.t('Tags')} content={room.tags?.join(', ')} theme={theme} /> {/* TODO: Will be deprecated */}
<Item label={I18n.t('Department')} content={department.name} theme={theme} /> {/* @ts-ignore */}
<CustomFields customFields={room.livechatData} theme={theme} /> <Item label={I18n.t('SMS')} content={room.sms && 'SMS Enabled'} />
<Item label={I18n.t('Topic')} content={room.topic} />
<Item label={I18n.t('Tags')} content={room.tags?.join(', ')} />
<Item label={I18n.t('Department')} content={department.name} />
<CustomFields customFields={room.livechatData} />
</> </>
); );
}; };
Livechat.propTypes = {
room: PropTypes.object,
roomUser: PropTypes.object,
theme: PropTypes.string
};
export default withTheme(Livechat); export default Livechat;

View File

@ -1,27 +0,0 @@
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import moment from 'moment';
import I18n from '../../i18n';
import Item from './Item';
const Timezone = ({ utcOffset, Message_TimeFormat, theme }) =>
utcOffset ? (
<Item
label={I18n.t('Timezone')}
content={`${moment().utcOffset(utcOffset).format(Message_TimeFormat)} (UTC ${utcOffset})`}
theme={theme}
/>
) : null;
Timezone.propTypes = {
utcOffset: PropTypes.number,
Message_TimeFormat: PropTypes.string,
theme: PropTypes.string
};
const mapStateToProps = state => ({
Message_TimeFormat: state.settings.Message_TimeFormat
});
export default connect(mapStateToProps)(Timezone);

View File

@ -0,0 +1,34 @@
import React from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { IApplicationState } from '../../definitions';
import I18n from '../../i18n';
import Item from './Item';
import { TSettingsValues } from '../../reducers/settings';
interface ITimezone {
utcOffset?: number;
Message_TimeFormat?: TSettingsValues;
}
const Timezone = ({ utcOffset, Message_TimeFormat }: ITimezone) => {
if (!utcOffset) {
return null;
}
return (
<Item
label={I18n.t('Timezone')}
content={`${moment()
.utcOffset(utcOffset)
.format(Message_TimeFormat as string)} (UTC ${utcOffset})`}
/>
);
};
const mapStateToProps = (state: IApplicationState) => ({
Message_TimeFormat: state.settings.Message_TimeFormat
});
export default connect(mapStateToProps)(Timezone);

View File

@ -1,10 +1,12 @@
import React from 'react'; import React from 'react';
import PropTypes from 'prop-types';
import { ScrollView, Text, View } from 'react-native'; import { ScrollView, Text, View } from 'react-native';
import { BorderlessButton } from 'react-native-gesture-handler'; import { BorderlessButton } from 'react-native-gesture-handler';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import UAParser from 'ua-parser-js'; import UAParser from 'ua-parser-js';
import isEmpty from 'lodash/isEmpty'; import isEmpty from 'lodash/isEmpty';
import { StackNavigationProp } from '@react-navigation/stack';
import { CompositeNavigationProp, RouteProp } from '@react-navigation/native';
import { Observable, Subscription } from 'rxjs';
import { CustomIcon } from '../../lib/Icons'; import { CustomIcon } from '../../lib/Icons';
import Status from '../../containers/Status'; import Status from '../../containers/Status';
@ -28,9 +30,22 @@ import Livechat from './Livechat';
import Channel from './Channel'; import Channel from './Channel';
import Direct from './Direct'; import Direct from './Direct';
import styles from './styles'; import styles from './styles';
import { ChatsStackParamList } from '../../stacks/types';
import { MasterDetailInsideStackParamList } from '../../stacks/MasterDetailStack/types';
import { SubscriptionType, TSubscriptionModel, ISubscription, IUser, IApplicationState } from '../../definitions';
import { ILivechatVisitor } from '../../definitions/ILivechatVisitor';
const getRoomTitle = (room, type, name, username, statusText, theme) => interface IGetRoomTitle {
type === 'd' ? ( room: ISubscription;
type: SubscriptionType;
name?: string;
username: string;
statusText?: string;
theme: string;
}
const getRoomTitle = ({ room, type, name, username, statusText, theme }: IGetRoomTitle) =>
type === SubscriptionType.DIRECT ? (
<> <>
<Text testID='room-info-view-name' style={[styles.roomTitle, { color: themes[theme].titleText }]}> <Text testID='room-info-view-name' style={[styles.roomTitle, { color: themes[theme].titleText }]}>
{name} {name}
@ -60,28 +75,57 @@ const getRoomTitle = (room, type, name, username, statusText, theme) =>
</View> </View>
); );
class RoomInfoView extends React.Component { interface IRoomInfoViewProps {
static propTypes = { navigation: CompositeNavigationProp<
navigation: PropTypes.object, StackNavigationProp<ChatsStackParamList, 'RoomInfoView'>,
route: PropTypes.object, StackNavigationProp<MasterDetailInsideStackParamList>
rooms: PropTypes.array, >;
theme: PropTypes.string, route: RouteProp<ChatsStackParamList, 'RoomInfoView'>;
isMasterDetail: PropTypes.bool, rooms: string[];
jitsiEnabled: PropTypes.bool, theme: string;
editRoomPermission: PropTypes.array, isMasterDetail: boolean;
editOmnichannelContact: PropTypes.array, jitsiEnabled: boolean;
editLivechatRoomCustomfields: PropTypes.array, editRoomPermission?: string[];
roles: PropTypes.array editOmnichannelContact?: string[];
}; editLivechatRoomCustomfields?: string[];
roles: { [key: string]: string };
}
constructor(props) { interface IUserParsed extends IUser {
parsedRoles?: string[];
}
export interface ILivechatVisitorModified extends ILivechatVisitor {
os?: string;
browser?: string;
}
interface IRoomInfoViewState {
room: ISubscription;
// TODO: Could be IUserParsed or ILivechatVisitorModified
roomUser: any;
showEdit: boolean;
}
class RoomInfoView extends React.Component<IRoomInfoViewProps, IRoomInfoViewState> {
private rid: string;
private t: SubscriptionType;
private unsubscribeFocus?: () => void;
private subscription?: Subscription;
private roomObservable?: Observable<TSubscriptionModel>;
constructor(props: IRoomInfoViewProps) {
super(props); super(props);
const room = props.route.params?.room; const room = props.route.params?.room;
const roomUser = props.route.params?.member; const roomUser = props.route.params?.member;
this.rid = props.route.params?.rid; this.rid = props.route.params?.rid;
this.t = props.route.params?.t; this.t = props.route.params?.t;
this.state = { this.state = {
room: room || { rid: this.rid, t: this.t }, room: (room || { rid: this.rid, t: this.t }) as any,
roomUser: roomUser || {}, roomUser: roomUser || {},
showEdit: false showEdit: false
}; };
@ -120,14 +164,14 @@ class RoomInfoView extends React.Component {
const showCloseModal = route.params?.showCloseModal; const showCloseModal = route.params?.showCloseModal;
navigation.setOptions({ navigation.setOptions({
headerLeft: showCloseModal ? () => <HeaderButton.CloseModal navigation={navigation} /> : undefined, headerLeft: showCloseModal ? () => <HeaderButton.CloseModal navigation={navigation} /> : undefined,
title: t === 'd' ? I18n.t('User_Info') : I18n.t('Room_Info'), title: t === SubscriptionType.DIRECT ? I18n.t('User_Info') : I18n.t('Room_Info'),
headerRight: showEdit headerRight: showEdit
? () => ( ? () => (
<HeaderButton.Container> <HeaderButton.Container>
<HeaderButton.Item <HeaderButton.Item
iconName='edit' iconName='edit'
onPress={() => { onPress={() => {
const isLivechat = t === 'l'; const isLivechat = t === SubscriptionType.OMNICHANNEL;
logEvent(events[`RI_GO_${isLivechat ? 'LIVECHAT' : 'RI'}_EDIT`]); logEvent(events[`RI_GO_${isLivechat ? 'LIVECHAT' : 'RI'}_EDIT`]);
navigation.navigate(isLivechat ? 'LivechatEditView' : 'RoomInfoEditView', { rid, room, roomUser }); navigation.navigate(isLivechat ? 'LivechatEditView' : 'RoomInfoEditView', { rid, room, roomUser });
}} }}
@ -135,21 +179,21 @@ class RoomInfoView extends React.Component {
/> />
</HeaderButton.Container> </HeaderButton.Container>
) )
: null : undefined
}); });
}; };
get isDirect() { get isDirect() {
const { room } = this.state; const { room } = this.state;
return room.t === 'd'; return room.t === SubscriptionType.DIRECT;
} }
get isLivechat() { get isLivechat() {
const { room } = this.state; const { room } = this.state;
return room.t === 'l'; return room.t === SubscriptionType.OMNICHANNEL;
} }
getRoleDescription = id => { getRoleDescription = (id: string) => {
const { roles } = this.props; const { roles } = this.props;
return roles[id]; return roles[id];
}; };
@ -157,23 +201,26 @@ class RoomInfoView extends React.Component {
loadVisitor = async () => { loadVisitor = async () => {
const { room } = this.state; const { room } = this.state;
try { try {
const result = await RocketChat.getVisitorInfo(room?.visitor?._id); if (room.visitor?._id) {
const result = await RocketChat.getVisitorInfo(room.visitor._id);
if (result.success) { if (result.success) {
const { visitor } = result; const { visitor } = result;
const params: { os?: string; browser?: string } = {};
if (visitor.userAgent) { if (visitor.userAgent) {
const ua = new UAParser(); const ua = new UAParser();
ua.setUA(visitor.userAgent); ua.setUA(visitor.userAgent);
visitor.os = `${ua.getOS().name} ${ua.getOS().version}`; params.os = `${ua.getOS().name} ${ua.getOS().version}`;
visitor.browser = `${ua.getBrowser().name} ${ua.getBrowser().version}`; params.browser = `${ua.getBrowser().name} ${ua.getBrowser().version}`;
}
this.setState({ roomUser: { ...visitor, ...params } }, () => this.setHeader());
} }
this.setState({ roomUser: visitor }, () => this.setHeader());
} }
} catch (error) { } catch (error) {
// Do nothing // Do nothing
} }
}; };
parseRoles = roleArray => parseRoles = (roleArray: string[]) =>
Promise.all( Promise.all(
roleArray.map(async role => { roleArray.map(async role => {
const description = await this.getRoleDescription(role); const description = await this.getRoleDescription(role);
@ -191,11 +238,12 @@ class RoomInfoView extends React.Component {
if (result.success) { if (result.success) {
const { user } = result; const { user } = result;
const { roles } = user; const { roles } = user;
const parsedRoles: { parsedRoles?: string[] } = {};
if (roles && roles.length) { if (roles && roles.length) {
user.parsedRoles = await this.parseRoles(roles); parsedRoles.parsedRoles = await this.parseRoles(roles);
} }
this.setState({ roomUser: user }); this.setState({ roomUser: { ...user, ...parsedRoles } });
} }
} catch { } catch {
// do nothing // do nothing
@ -218,9 +266,10 @@ class RoomInfoView extends React.Component {
loadRoom = async () => { loadRoom = async () => {
const { room: roomState } = this.state; const { room: roomState } = this.state;
const { route, editRoomPermission, editOmnichannelContact, editLivechatRoomCustomfields } = this.props; const { route, editRoomPermission, editOmnichannelContact, editLivechatRoomCustomfields } = this.props;
let room = route.params?.room; let room = route.params?.room as any;
if (room && room.observe) { const roomModel = room as TSubscriptionModel;
this.roomObservable = room.observe(); if (roomModel && roomModel.observe) {
this.roomObservable = roomModel.observe();
this.subscription = this.roomObservable.subscribe(changes => { this.subscription = this.roomObservable.subscribe(changes => {
this.setState({ room: changes }, () => this.setHeader()); this.setState({ room: changes }, () => this.setHeader());
}); });
@ -245,7 +294,7 @@ class RoomInfoView extends React.Component {
}; };
createDirect = () => createDirect = () =>
new Promise(async (resolve, reject) => { new Promise<void>(async (resolve, reject) => {
const { route } = this.props; const { route } = this.props;
// We don't need to create a direct // We don't need to create a direct
@ -309,12 +358,12 @@ class RoomInfoView extends React.Component {
RocketChat.callJitsi(room); RocketChat.callJitsi(room);
}; };
renderAvatar = (room, roomUser) => { renderAvatar = (room: ISubscription, roomUser: IUserParsed) => {
const { theme } = this.props; const { theme } = this.props;
return ( return (
<Avatar text={room.name || roomUser.username} style={styles.avatar} type={this.t} size={100} rid={room?.rid}> <Avatar text={room.name || roomUser.username} style={styles.avatar} type={this.t} size={100} rid={room?.rid}>
{this.t === 'd' && roomUser._id ? ( {this.t === SubscriptionType.DIRECT && roomUser._id ? (
<View style={[sharedStyles.status, { backgroundColor: themes[theme].auxiliaryBackground }]}> <View style={[sharedStyles.status, { backgroundColor: themes[theme].auxiliaryBackground }]}>
<Status size={20} id={roomUser._id} /> <Status size={20} id={roomUser._id} />
</View> </View>
@ -323,7 +372,7 @@ class RoomInfoView extends React.Component {
); );
}; };
renderButton = (onPress, iconName, text) => { renderButton = (onPress: () => void, iconName: string, text: string) => {
const { theme } = this.props; const { theme } = this.props;
const onActionPress = async () => { const onActionPress = async () => {
@ -359,14 +408,15 @@ class RoomInfoView extends React.Component {
renderContent = () => { renderContent = () => {
const { room, roomUser } = this.state; const { room, roomUser } = this.state;
const { theme } = this.props;
if (this.isDirect) { if (this.isDirect) {
return <Direct roomUser={roomUser} theme={theme} />; return <Direct roomUser={roomUser} />;
} else if (this.t === 'l') {
return <Livechat room={room} roomUser={roomUser} theme={theme} />;
} }
return <Channel room={room} theme={theme} />;
if (this.t === SubscriptionType.OMNICHANNEL) {
return <Livechat room={room} roomUser={roomUser} />;
}
return <Channel room={room} />;
}; };
render() { render() {
@ -379,7 +429,14 @@ class RoomInfoView extends React.Component {
<View style={[styles.avatarContainer, { backgroundColor: themes[theme].auxiliaryBackground }]}> <View style={[styles.avatarContainer, { backgroundColor: themes[theme].auxiliaryBackground }]}>
{this.renderAvatar(room, roomUser)} {this.renderAvatar(room, roomUser)}
<View style={styles.roomTitleContainer}> <View style={styles.roomTitleContainer}>
{getRoomTitle(room, this.t, roomUser?.name, roomUser?.username, roomUser?.statusText, theme)} {getRoomTitle({
room,
type: this.t,
name: roomUser?.name,
username: roomUser?.username,
statusText: roomUser?.statusText,
theme
})}
</View> </View>
{this.renderButtons()} {this.renderButtons()}
</View> </View>
@ -390,10 +447,10 @@ class RoomInfoView extends React.Component {
} }
} }
const mapStateToProps = state => ({ const mapStateToProps = (state: IApplicationState) => ({
rooms: state.room.rooms, rooms: state.room.rooms,
isMasterDetail: state.app.isMasterDetail, isMasterDetail: state.app.isMasterDetail,
jitsiEnabled: state.settings.Jitsi_Enabled || false, jitsiEnabled: (state.settings.Jitsi_Enabled as boolean) || false,
editRoomPermission: state.permissions['edit-room'], editRoomPermission: state.permissions['edit-room'],
editOmnichannelContact: state.permissions['edit-omnichannel-contact'], editOmnichannelContact: state.permissions['edit-omnichannel-contact'],
editLivechatRoomCustomfields: state.permissions['edit-livechat-room-customfields'], editLivechatRoomCustomfields: state.permissions['edit-livechat-room-customfields'],

View File

@ -216,6 +216,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
const result = await RocketChat.teamListRoomsOfUser({ teamId: room.teamId as string, userId: selectedUser._id }); const result = await RocketChat.teamListRoomsOfUser({ teamId: room.teamId as string, userId: selectedUser._id });
if (result.success) {
if (result.rooms?.length) { if (result.rooms?.length) {
const teamChannels = result.rooms.map((r: any) => ({ const teamChannels = result.rooms.map((r: any) => ({
rid: r._id, rid: r._id,
@ -237,6 +238,7 @@ class RoomMembersView extends React.Component<IRoomMembersViewProps, IRoomMember
onPress: () => this.removeFromTeam(selectedUser) onPress: () => this.removeFromTeam(selectedUser)
}); });
} }
}
} catch (e) { } catch (e) {
showConfirmationAlert({ showConfirmationAlert({
message: I18n.t('Removing_user_from_this_team', { user: selectedUser.username }), message: I18n.t('Removing_user_from_this_team', { user: selectedUser.username }),

View File

@ -7,11 +7,7 @@ import { longText } from '../../../../storybook/utils';
import { ThemeContext } from '../../../theme'; import { ThemeContext } from '../../../theme';
import { Message, MessageDecorator, StoryProvider } from '../../../../storybook/stories/Message'; import { Message, MessageDecorator, StoryProvider } from '../../../../storybook/stories/Message';
import { themes } from '../../../constants/colors'; import { themes } from '../../../constants/colors';
import { import { MessageTypeLoad } from '../../../constants/messageTypeLoad';
MESSAGE_TYPE_LOAD_MORE,
MESSAGE_TYPE_LOAD_NEXT_CHUNK,
MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK
} from '../../../constants/messageTypeLoad';
import LoadMore from './index'; import LoadMore from './index';
const stories = storiesOf('LoadMore', module); const stories = storiesOf('LoadMore', module);
@ -23,20 +19,20 @@ stories.add('basic', () => (
<> <>
<LoadMore load={load} /> <LoadMore load={load} />
<LoadMore load={load} runOnRender /> <LoadMore load={load} runOnRender />
<LoadMore load={load} type={MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK} /> <LoadMore load={load} type={MessageTypeLoad.PREVIOUS_CHUNK} />
<LoadMore load={load} type={MESSAGE_TYPE_LOAD_NEXT_CHUNK} /> <LoadMore load={load} type={MessageTypeLoad.NEXT_CHUNK} />
</> </>
)); ));
const ThemeStory = ({ theme }) => ( const ThemeStory = ({ theme }) => (
<ThemeContext.Provider value={{ theme }}> <ThemeContext.Provider value={{ theme }}>
<ScrollView style={{ backgroundColor: themes[theme].backgroundColor }}> <ScrollView style={{ backgroundColor: themes[theme].backgroundColor }}>
<LoadMore load={load} type={MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK} /> <LoadMore load={load} type={MessageTypeLoad.PREVIOUS_CHUNK} />
<Message msg='Hey!' theme={theme} /> <Message msg='Hey!' theme={theme} />
<Message msg={longText} theme={theme} isHeader={false} /> <Message msg={longText} theme={theme} isHeader={false} />
<Message msg='Older message' theme={theme} isHeader={false} /> <Message msg='Older message' theme={theme} isHeader={false} />
<LoadMore load={load} type={MESSAGE_TYPE_LOAD_NEXT_CHUNK} /> <LoadMore load={load} type={MessageTypeLoad.NEXT_CHUNK} />
<LoadMore load={load} type={MESSAGE_TYPE_LOAD_MORE} /> <LoadMore load={load} type={MessageTypeLoad.MORE} />
<Message msg={longText} theme={theme} /> <Message msg={longText} theme={theme} />
<Message msg='This is the third message' isHeader={false} theme={theme} /> <Message msg='This is the third message' isHeader={false} theme={theme} />
<Message msg='This is the second message' isHeader={false} theme={theme} /> <Message msg='This is the second message' isHeader={false} theme={theme} />

View File

@ -2,7 +2,8 @@ import React, { useCallback, useEffect, useState } from 'react';
import { ActivityIndicator, StyleSheet, Text } from 'react-native'; import { ActivityIndicator, StyleSheet, Text } from 'react-native';
import { themes } from '../../../constants/colors'; import { themes } from '../../../constants/colors';
import { MESSAGE_TYPE_LOAD_NEXT_CHUNK, MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK } from '../../../constants/messageTypeLoad'; import { MessageTypeLoad } from '../../../constants/messageTypeLoad';
import { MessageType } from '../../../definitions';
import { useTheme } from '../../../theme'; import { useTheme } from '../../../theme';
import Touch from '../../../utils/touch'; import Touch from '../../../utils/touch';
import sharedStyles from '../../Styles'; import sharedStyles from '../../Styles';
@ -20,7 +21,15 @@ const styles = StyleSheet.create({
} }
}); });
const LoadMore = ({ load, type, runOnRender }: { load: Function; type: string; runOnRender: boolean }): React.ReactElement => { const LoadMore = ({
load,
type,
runOnRender
}: {
load: Function;
type: MessageType;
runOnRender: boolean;
}): React.ReactElement => {
const { theme } = useTheme(); const { theme } = useTheme();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -43,10 +52,10 @@ const LoadMore = ({ load, type, runOnRender }: { load: Function; type: string; r
}, []); }, []);
let text = 'Load_More'; let text = 'Load_More';
if (type === MESSAGE_TYPE_LOAD_NEXT_CHUNK) { if (type === MessageTypeLoad.NEXT_CHUNK) {
text = 'Load_Newer'; text = 'Load_Newer';
} }
if (type === MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK) { if (type === MessageTypeLoad.PREVIOUS_CHUNK) {
text = 'Load_Older'; text = 'Load_Older';
} }

View File

@ -24,7 +24,7 @@ import I18n from '../../i18n';
import RoomHeader from '../../containers/RoomHeader'; import RoomHeader from '../../containers/RoomHeader';
import StatusBar from '../../containers/StatusBar'; import StatusBar from '../../containers/StatusBar';
import { themes } from '../../constants/colors'; import { themes } from '../../constants/colors';
import { MESSAGE_TYPE_ANY_LOAD, MESSAGE_TYPE_LOAD_MORE } from '../../constants/messageTypeLoad'; import { MESSAGE_TYPE_ANY_LOAD, MessageTypeLoad } from '../../constants/messageTypeLoad';
import debounce from '../../utils/debounce'; import debounce from '../../utils/debounce';
import ReactionsModal from '../../containers/ReactionsModal'; import ReactionsModal from '../../containers/ReactionsModal';
import { LISTENER } from '../../containers/Toast'; import { LISTENER } from '../../containers/Toast';
@ -851,7 +851,7 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
* if it's from server, we don't have it saved locally and so we fetch surroundings * if it's from server, we don't have it saved locally and so we fetch surroundings
* we test if it's not from threads because we're fetching from threads currently with `getThreadMessages` * we test if it's not from threads because we're fetching from threads currently with `getThreadMessages`
*/ */
if (message.fromServer && !message.tmid) { if (message.fromServer && !message.tmid && this.rid) {
await RocketChat.loadSurroundingMessages({ messageId, rid: this.rid }); await RocketChat.loadSurroundingMessages({ messageId, rid: this.rid });
} }
// @ts-ignore // @ts-ignore
@ -1161,12 +1161,12 @@ class RoomView extends React.Component<IRoomViewProps, IRoomViewState> {
} }
let content = null; let content = null;
if (item.t && MESSAGE_TYPE_ANY_LOAD.includes(item.t)) { if (item.t && MESSAGE_TYPE_ANY_LOAD.includes(item.t as MessageTypeLoad)) {
content = ( content = (
<LoadMore <LoadMore
load={() => this.onLoadMoreMessages(item)} load={() => this.onLoadMoreMessages(item)}
type={item.t} type={item.t}
runOnRender={item.t === MESSAGE_TYPE_LOAD_MORE && !previousItem} runOnRender={item.t === MessageTypeLoad.MORE && !previousItem}
/> />
); );
} else { } else {

View File

@ -1,11 +1,7 @@
import { MessageType, SubscriptionType, TAnyMessageModel } from '../../../definitions'; import { SubscriptionType, TAnyMessageModel } from '../../../definitions';
import loadMessagesForRoom from '../../../lib/methods/loadMessagesForRoom'; import loadMessagesForRoom from '../../../lib/methods/loadMessagesForRoom';
import loadNextMessages from '../../../lib/methods/loadNextMessages'; import loadNextMessages from '../../../lib/methods/loadNextMessages';
import { import { MessageTypeLoad } from '../../../constants/messageTypeLoad';
MESSAGE_TYPE_LOAD_MORE,
MESSAGE_TYPE_LOAD_NEXT_CHUNK,
MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK
} from '../../../constants/messageTypeLoad';
const getMoreMessages = ({ const getMoreMessages = ({
rid, rid,
@ -18,7 +14,7 @@ const getMoreMessages = ({
tmid?: string; tmid?: string;
loaderItem: TAnyMessageModel; loaderItem: TAnyMessageModel;
}): Promise<void> => { }): Promise<void> => {
if ([MESSAGE_TYPE_LOAD_MORE, MESSAGE_TYPE_LOAD_PREVIOUS_CHUNK].includes(loaderItem.t as MessageType)) { if ([MessageTypeLoad.MORE, MessageTypeLoad.PREVIOUS_CHUNK].includes(loaderItem.t as MessageTypeLoad)) {
return loadMessagesForRoom({ return loadMessagesForRoom({
rid, rid,
t: t as any, t: t as any,
@ -27,7 +23,7 @@ const getMoreMessages = ({
}); });
} }
if (loaderItem.t === MESSAGE_TYPE_LOAD_NEXT_CHUNK) { if (loaderItem.t === MessageTypeLoad.NEXT_CHUNK) {
return loadNextMessages({ return loadNextMessages({
rid, rid,
tmid, tmid,

View File

@ -7,7 +7,6 @@ import { EdgeInsets, withSafeAreaInsets } from 'react-native-safe-area-context';
import { HeaderBackButton, StackNavigationOptions, StackNavigationProp } from '@react-navigation/stack'; import { HeaderBackButton, StackNavigationOptions, StackNavigationProp } from '@react-navigation/stack';
import { RouteProp } from '@react-navigation/native'; import { RouteProp } from '@react-navigation/native';
import { Observable, Subscription } from 'rxjs'; import { Observable, Subscription } from 'rxjs';
import Database from '@nozbe/watermelondb/Database';
import ActivityIndicator from '../../containers/ActivityIndicator'; import ActivityIndicator from '../../containers/ActivityIndicator';
import I18n from '../../i18n'; import I18n from '../../i18n';
@ -33,13 +32,12 @@ import EventEmitter from '../../utils/events';
import { LISTENER } from '../../containers/Toast'; import { LISTENER } from '../../containers/Toast';
import SearchHeader from '../../containers/SearchHeader'; import SearchHeader from '../../containers/SearchHeader';
import { ChatsStackParamList } from '../../stacks/types'; import { ChatsStackParamList } from '../../stacks/types';
import { IThreadResult, TThreadModel } from '../../definitions/IThread';
import { Filter } from './filters'; import { Filter } from './filters';
import DropdownItemHeader from './Dropdown/DropdownItemHeader'; import DropdownItemHeader from './Dropdown/DropdownItemHeader';
import Dropdown from './Dropdown'; import Dropdown from './Dropdown';
import Item from './Item'; import Item from './Item';
import styles from './styles'; import styles from './styles';
import { SubscriptionType, TSubscriptionModel } from '../../definitions/ISubscription'; import { IMessage, SubscriptionType, TSubscriptionModel, TThreadModel } from '../../definitions';
const API_FETCH_COUNT = 50; const API_FETCH_COUNT = 50;
@ -259,8 +257,8 @@ class ThreadMessagesView extends React.Component<IThreadMessagesViewProps, IThre
remove, remove,
lastThreadSync lastThreadSync
}: { }: {
update: IThreadResult[]; update: IMessage[];
remove?: IThreadResult[]; remove?: IMessage[];
lastThreadSync: Date; lastThreadSync: Date;
}) => { }) => {
const { subscription } = this.state; const { subscription } = this.state;
@ -272,11 +270,9 @@ class ThreadMessagesView extends React.Component<IThreadMessagesViewProps, IThre
} }
try { try {
const db: Database = database.active; const db = database.active;
const threadsCollection = db.get('threads'); const threadsCollection = db.get('threads');
// TODO: Refactor when migrate room const allThreadsRecords = await subscription.threads.fetch();
// @ts-ignore
const allThreadsRecords = (await subscription.threads.fetch()) as TThreadModel[];
let threadsToCreate: any[] = []; let threadsToCreate: any[] = [];
let threadsToUpdate: any[] = []; let threadsToUpdate: any[] = [];
let threadsToDelete: any[] = []; let threadsToDelete: any[] = [];
@ -287,7 +283,7 @@ class ThreadMessagesView extends React.Component<IThreadMessagesViewProps, IThre
} }
if (update && update.length) { if (update && update.length) {
update = update.map(m => buildMessage(m)) as IThreadResult[]; update = update.map(m => buildMessage(m)) as IMessage[];
// filter threads // filter threads
threadsToCreate = update.filter(i1 => !allThreadsRecords.find((i2: { id: string }) => i1._id === i2.id)); threadsToCreate = update.filter(i1 => !allThreadsRecords.find((i2: { id: string }) => i1._id === i2.id));
threadsToUpdate = allThreadsRecords.filter((i1: { id: string }) => update.find(i2 => i1.id === i2._id)); threadsToUpdate = allThreadsRecords.filter((i1: { id: string }) => update.find(i2 => i1.id === i2._id));

View File

@ -106,10 +106,12 @@ class UserNotificationPreferencesView extends React.Component<
const { user } = this.props; const { user } = this.props;
const { id } = user; const { id } = user;
const result = await RocketChat.setUserPreferences(id, params); const result = await RocketChat.setUserPreferences(id, params);
if (result.success) {
const { const {
user: { settings } user: { settings }
} = result; } = result;
this.setState({ preferences: settings.preferences }); this.setState({ preferences: settings.preferences });
}
}; };
render() { render() {

View File

@ -143,8 +143,8 @@
"@rocket.chat/eslint-config": "^0.4.0", "@rocket.chat/eslint-config": "^0.4.0",
"@storybook/addon-storyshots": "5.3.21", "@storybook/addon-storyshots": "5.3.21",
"@storybook/react-native": "5.3.25", "@storybook/react-native": "5.3.25",
"@types/bytebuffer": "^5.0.43",
"@testing-library/react-native": "^9.0.0", "@testing-library/react-native": "^9.0.0",
"@types/bytebuffer": "^5.0.43",
"@types/ejson": "^2.1.3", "@types/ejson": "^2.1.3",
"@types/jest": "^26.0.24", "@types/jest": "^26.0.24",
"@types/lodash": "^4.14.171", "@types/lodash": "^4.14.171",
@ -157,6 +157,7 @@
"@types/react-redux": "^7.1.18", "@types/react-redux": "^7.1.18",
"@types/react-test-renderer": "^17.0.1", "@types/react-test-renderer": "^17.0.1",
"@types/semver": "^7.3.9", "@types/semver": "^7.3.9",
"@types/ua-parser-js": "^0.7.36",
"@types/url-parse": "^1.4.6", "@types/url-parse": "^1.4.6",
"@typescript-eslint/eslint-plugin": "^4.28.3", "@typescript-eslint/eslint-plugin": "^4.28.3",
"@typescript-eslint/parser": "^4.28.5", "@typescript-eslint/parser": "^4.28.5",
@ -245,13 +246,13 @@
} }
} }
}, },
"and.emu.debug": { "android.emu.debug": {
"device": "Pixel_API_28_AOSP", "device": "Pixel_API_28_AOSP",
"type": "android.emulator", "type": "android.emulator",
"binaryPath": "android/app/build/outputs/apk/e2ePlay/debug/app-e2e-play-debug.apk", "binaryPath": "android/app/build/outputs/apk/e2ePlay/debug/app-e2e-play-debug.apk",
"build": "cd android && ./gradlew app:assembleE2ePlayDebug app:assembleE2ePlayDebugAndroidTest -DtestBuildType=debug && cd .." "build": "cd android && ./gradlew app:assembleE2ePlayDebug app:assembleE2ePlayDebugAndroidTest -DtestBuildType=debug && cd .."
}, },
"and.emu.release": { "android.emu.release": {
"device": "Pixel_API_28_AOSP", "device": "Pixel_API_28_AOSP",
"type": "android.emulator", "type": "android.emulator",
"binaryPath": "android/app/build/outputs/apk/e2ePlay/release/app-e2e-play-release.apk", "binaryPath": "android/app/build/outputs/apk/e2ePlay/release/app-e2e-play-release.apk",

View File

@ -4534,6 +4534,11 @@
resolved "https://registry.yarnpkg.com/@types/tapable/-/tapable-1.0.5.tgz#9adbc12950582aa65ead76bffdf39fe0c27a3c02" resolved "https://registry.yarnpkg.com/@types/tapable/-/tapable-1.0.5.tgz#9adbc12950582aa65ead76bffdf39fe0c27a3c02"
integrity sha512-/gG2M/Imw7cQFp8PGvz/SwocNrmKFjFsm5Pb8HdbHkZ1K8pmuPzOX4VeVoiEecFCVf4CsN1r3/BRvx+6sNqwtQ== integrity sha512-/gG2M/Imw7cQFp8PGvz/SwocNrmKFjFsm5Pb8HdbHkZ1K8pmuPzOX4VeVoiEecFCVf4CsN1r3/BRvx+6sNqwtQ==
"@types/ua-parser-js@^0.7.36":
version "0.7.36"
resolved "https://registry.yarnpkg.com/@types/ua-parser-js/-/ua-parser-js-0.7.36.tgz#9bd0b47f26b5a3151be21ba4ce9f5fa457c5f190"
integrity sha512-N1rW+njavs70y2cApeIw1vLMYXRwfBy+7trgavGuuTfOd7j1Yh7QTRc/yqsPl6ncokt72ZXuxEU0PiCp9bSwNQ==
"@types/uglify-js@*": "@types/uglify-js@*":
version "3.9.2" version "3.9.2"
resolved "https://registry.yarnpkg.com/@types/uglify-js/-/uglify-js-3.9.2.tgz#01992579debba674e1e359cd6bcb1a1d0ab2e02b" resolved "https://registry.yarnpkg.com/@types/uglify-js/-/uglify-js-3.9.2.tgz#01992579debba674e1e359cd6bcb1a1d0ab2e02b"