-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathgetUsersPresence.ts
More file actions
168 lines (146 loc) · 5.18 KB
/
getUsersPresence.ts
File metadata and controls
168 lines (146 loc) · 5.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
import { InteractionManager } from 'react-native';
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
import { Q } from '@nozbe/watermelondb';
import { type IActiveUsers } from '../../reducers/activeUsers';
import { store as reduxStore } from '../store/auxStore';
import { setActiveUsers } from '../../actions/activeUsers';
import { setUser } from '../../actions/login';
import database from '../database';
import { type IUser } from '../../definitions';
import sdk from '../services/sdk';
import { compareServerVersion } from './helpers';
import userPreferences from './userPreferences';
import { NOTIFICATION_PRESENCE_CAP } from '../constants/notifications';
import { setNotificationPresenceCap } from '../../actions/app';
export const _activeUsersSubTimeout: { activeUsersSubTimeout: boolean | ReturnType<typeof setTimeout> | number } = {
activeUsersSubTimeout: false
};
export function subscribeUsersPresence() {
const serverVersion = reduxStore.getState().server.version as string;
// if server is lower than 1.1.0
if (compareServerVersion(serverVersion, 'lowerThan', '1.1.0')) {
if (_activeUsersSubTimeout.activeUsersSubTimeout) {
clearTimeout(_activeUsersSubTimeout.activeUsersSubTimeout as number);
_activeUsersSubTimeout.activeUsersSubTimeout = false;
}
_activeUsersSubTimeout.activeUsersSubTimeout = setTimeout(() => {
sdk.subscribe('activeUsers');
}, 5000);
} else if (compareServerVersion(serverVersion, 'lowerThan', '4.1.0')) {
sdk.subscribe('stream-notify-logged', 'user-status');
}
// RC 0.49.1
sdk.subscribe('stream-notify-logged', 'updateAvatar');
// RC 0.58.0
sdk.subscribe('stream-notify-logged', 'Users:NameChanged');
}
let usersBatch: string[] = [];
export async function getUsersPresence(usersParams: string[]) {
const serverVersion = reduxStore.getState().server.version as string;
const { user: loggedUser } = reduxStore.getState().login;
// if server is greather than or equal 1.1.0
if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '1.1.0')) {
let params = {};
// if server is greather than or equal 3.0.0
if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '3.0.0')) {
// if not have any id
if (!usersParams.length) {
return;
}
// Request userPresence on demand with cache-busting timestamp
params = { ids: usersParams.join(','), _t: Date.now() };
}
try {
// RC 1.1.0
const result = (await sdk.get('users.presence' as any, params as any)) as any;
if (compareServerVersion(serverVersion, 'greaterThanOrEqualTo', '4.1.0')) {
sdk.subscribeRaw('stream-user-presence', ['', { added: usersParams }]);
}
if (result.success) {
const { users } = result;
const activeUsers = usersParams.reduce((ret: IActiveUsers, id) => {
const user = users.find((u: IUser) => u._id === id) ?? { _id: id, status: 'offline' };
const { _id, status, statusText } = user;
if (loggedUser && loggedUser.id === _id) {
reduxStore.dispatch(setUser({ status, statusText }));
}
ret[_id] = { status, statusText };
return ret;
}, {});
InteractionManager.runAfterInteractions(() => {
reduxStore.dispatch(setActiveUsers(activeUsers));
});
const db = database.active;
const userCollection = db.get('users');
users.forEach(async (user: IUser) => {
try {
const userRecord = await userCollection.find(user._id);
await db.write(async () => {
await userRecord.update(u => {
Object.assign(u, user);
});
});
} catch (e) {
// User not found
await db.write(async () => {
await userCollection.create(u => {
u._raw = sanitizedRaw({ id: user._id }, userCollection.schema);
Object.assign(u, user);
});
});
}
});
}
} catch {
// do nothing
}
}
}
let usersTimer: ReturnType<typeof setTimeout> | null = null;
export function getUserPresence(uid: string) {
if (!usersTimer) {
usersTimer = setTimeout(() => {
getUsersPresence(usersBatch);
usersBatch = [];
usersTimer = null;
}, 2000);
}
if (uid) {
usersBatch.push(uid);
}
}
export const setPresenceCap = async (enabled: boolean) => {
if (enabled) {
const notificationPresenceCap = await userPreferences.getBool(NOTIFICATION_PRESENCE_CAP);
if (notificationPresenceCap !== false) {
userPreferences.setBool(NOTIFICATION_PRESENCE_CAP, true);
reduxStore.dispatch(setNotificationPresenceCap(true));
}
} else {
userPreferences.removeItem(NOTIFICATION_PRESENCE_CAP);
reduxStore.dispatch(setNotificationPresenceCap(false));
}
};
export const getDirectMessageUserIds = async (): Promise<string[]> => {
try {
const db = database.active;
const subscriptionsCollection = db.get('subscriptions');
const subscriptions = await subscriptionsCollection
.query(Q.where('t', 'd'), Q.where('open', true), Q.where('archived', false))
.fetch();
const userIds = subscriptions.map((sub: any) => sub.uids?.[0]).filter(Boolean);
return [...new Set(userIds)];
} catch (e) {
return [];
}
};
export const refreshDmUsersPresence = async (): Promise<void> => {
try {
const dmUserIds = await getDirectMessageUserIds();
if (dmUserIds.length > 0) {
await getUsersPresence(dmUserIds);
}
} catch (e) {
// Silently fail
}
};