-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathdeepLinking.js
More file actions
395 lines (362 loc) · 12.4 KB
/
Copy pathdeepLinking.js
File metadata and controls
395 lines (362 loc) · 12.4 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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
import { InteractionManager } from 'react-native';
import RNCallKeep from 'react-native-callkeep';
import I18n from 'i18n-js';
import { all, call, delay, put, select, take, takeLatest } from 'redux-saga/effects';
import { shareSetParams } from '../actions/share';
import * as types from '../actions/actionsTypes';
import { appInit, appStart, appReady } from '../actions/app';
import { inviteLinksRequest, inviteLinksSetToken } from '../actions/inviteLinks';
import { loginRequest } from '../actions/login';
import { selectServerRequest, serverInitAdd } from '../actions/server';
import { RootEnum } from '../definitions';
import { CURRENT_SERVER, TOKEN_KEY } from '../lib/constants/keys';
import database from '../lib/database';
import { getServerById } from '../lib/database/services/Server';
import { canOpenRoom } from '../lib/methods/canOpenRoom';
import { getServerInfo } from '../lib/methods/getServerInfo';
import { getUidDirectMessage, normalizeDeepLinkingServerHost } from '../lib/methods/helpers';
import EventEmitter from '../lib/methods/helpers/events';
import { goRoom, navigateToRoom } from '../lib/methods/helpers/goRoom';
import { getIsMasterDetail } from '../lib/hooks/useMasterDetail';
import { localAuthenticate } from '../lib/methods/helpers/localAuthentication';
import log from '../lib/methods/helpers/log';
import { showConfirmationAlert } from '../lib/methods/helpers/info';
import { showToast } from '../lib/methods/helpers/showToast';
import UserPreferences from '../lib/methods/userPreferences';
import { videoConfJoin } from '../lib/methods/videoConf';
import { loginOAuthOrSso } from '../lib/services/connect';
import { notifyUser } from '../lib/services/restApi';
import sdk from '../lib/services/sdk';
import Navigation, { waitForNavigationReady } from '../lib/navigation/appNavigation';
import { resetVoipState } from '../lib/services/voip/resetVoipState';
const roomTypes = {
channel: 'c',
direct: 'd',
group: 'p',
channels: 'l'
};
/**
* A `rocketchat://auth?host=…&token=…` deep link can silently authenticate the user to an
* arbitrary server. Any app (or web page) can fire it, so before consuming a resume token for a
* server the user is not already signed in to, ask for explicit confirmation. Resolves true if
* the user confirms, false otherwise.
*/
const confirmDeepLinkLogin = host =>
new Promise(resolve => {
// E2E tests bootstrap the session via a deep link and can't dismiss a native Alert, so
// auto-confirm under RUNNING_E2E_TESTS. This preserves the pre-fix silent behavior for
// tests only; real users still get the security prompt.
if (process.env.RUNNING_E2E_TESTS === 'true') {
resolve(true);
return;
}
showConfirmationAlert({
title: I18n.t('Deep_link_login_title'),
message: I18n.t('Deep_link_login_description', { server: host }),
confirmationText: I18n.t('Login'),
onPress: () => resolve(true),
onCancel: () => resolve(false)
});
});
const handleInviteLink = function* handleInviteLink({ params, requireLogin = false }) {
if (params.path && params.path.startsWith('invite/')) {
const token = params.path.replace('invite/', '');
if (requireLogin) {
yield put(inviteLinksSetToken(token));
} else {
yield put(inviteLinksRequest(token));
}
}
};
const navigate = function* navigate({ params }) {
if (params.path || params.rid) {
let type;
let name;
let jumpToThreadId;
if (params.path) {
// Following this pattern: {channelType}/{channelName}/thread/{threadId}
[type, name, , jumpToThreadId] = params.path.split('/');
}
if (type !== 'invite' || params.rid) {
const room = yield canOpenRoom(params);
if (room) {
const item = {
name,
t: roomTypes[type],
roomUserId: getUidDirectMessage(room),
...room
};
const isMasterDetail = getIsMasterDetail();
const jumpToMessageId = params.messageId;
yield waitForNavigationReady();
yield goRoom({ item, isMasterDetail, jumpToMessageId, jumpToThreadId });
}
} else {
yield handleInviteLink({ params });
}
}
yield put(appStart({ root: RootEnum.ROOT_INSIDE }));
};
/**
* After native VoIP accept fails: reset call state, end CallKit session, land inside root,
* optionally open DM via same pipeline as deep links (`direct/username`), then toast/dialog per a11y.
*/
const handleVoipAcceptFailed = function* handleVoipAcceptFailed(params) {
try {
const { callId, username } = params;
resetVoipState();
if (callId) {
RNCallKeep.endCall(callId);
}
yield call(waitForNavigationReady);
const navigateParams = {
...params,
path: username ? `direct/${username}` : params.path
};
yield navigate({ params: navigateParams });
yield call(
() =>
new Promise(resolve => {
InteractionManager.runAfterInteractions(() => resolve());
})
);
showToast(I18n.t('VoIP_Call_Issue'));
} catch (e) {
log(e);
}
};
const completeDeepLinkNavigation = function* completeDeepLinkNavigation(params) {
if (params.voipAcceptFailed) {
yield call(handleVoipAcceptFailed, params);
} else {
yield navigate({ params });
}
};
const fallbackNavigation = function* fallbackNavigation() {
const currentRoot = yield select(state => state.app.root);
if (currentRoot) {
return;
}
yield put(appInit());
};
let consumedOAuthToken;
const handleOAuth = function* handleOAuth({ params }) {
const { credentialToken, credentialSecret } = params;
if (!credentialToken || !credentialSecret || credentialToken === consumedOAuthToken) {
return;
}
consumedOAuthToken = credentialToken;
try {
yield loginOAuthOrSso({ oauth: { credentialToken, credentialSecret } });
} catch (e) {
log(e);
}
};
const handleShareExtension = function* handleOpen({ params }) {
const server = UserPreferences.getString(CURRENT_SERVER);
const user = UserPreferences.getString(`${TOKEN_KEY}-${server}`);
if (!user) {
yield put(appInit());
return;
}
yield put(appStart({ root: RootEnum.ROOT_LOADING_SHARE_EXTENSION }));
yield localAuthenticate(server);
const serverRecord = yield getServerById(server);
if (!serverRecord) {
return;
}
yield put(selectServerRequest(server, serverRecord.version));
if (sdk.current?.client?.host !== server) {
yield take(types.LOGIN.SUCCESS);
}
yield put(shareSetParams(params));
yield put(appStart({ root: RootEnum.ROOT_SHARE_EXTENSION }));
};
const handleOpen = function* handleOpen({ params }) {
if (params.type === 'shareextension') {
yield handleShareExtension({ params });
return;
}
if (params.type === 'oauth') {
yield handleOAuth({ params });
return;
}
// If there's no host on the deep link params and the app is opened, just call appInit()
let { host } = params;
if (!host) {
if (params.voipAcceptFailed) {
yield call(handleVoipAcceptFailed, params);
return;
}
yield fallbackNavigation();
return;
}
// If there's host, continue
host = normalizeDeepLinkingServerHost(host);
params.host = host;
const [server, user] = yield all([
UserPreferences.getString(CURRENT_SERVER),
UserPreferences.getString(`${TOKEN_KEY}-${host}`)
]);
const serverRecord = yield getServerById(host);
// TODO: needs better test
// if deep link is from same server
if (server === host && user && serverRecord) {
const connected = yield select(state => state.server.connected);
if (!connected) {
yield localAuthenticate(host);
yield put(selectServerRequest(host, serverRecord.version, true));
yield take(types.LOGIN.SUCCESS);
}
yield completeDeepLinkNavigation(params);
} else {
// search if deep link's server already exists
try {
if (user && serverRecord) {
yield localAuthenticate(host);
yield put(selectServerRequest(host, serverRecord.version, true, true));
yield take(types.LOGIN.SUCCESS);
yield completeDeepLinkNavigation(params);
return;
}
} catch (e) {
// do nothing?
}
// if deep link is from a different server
const result = yield getServerInfo(host);
if (!result.success) {
if (params.voipAcceptFailed) {
yield call(handleVoipAcceptFailed, params);
return;
}
// Fallback to prevent the app from being stuck on splash screen
yield fallbackNavigation();
return;
}
// if the host is different from the current one, we need to connect to it before navigating
const hostAlreadyConnected = sdk.current?.client?.host === host;
if (!hostAlreadyConnected) {
yield put(appStart({ root: RootEnum.ROOT_OUTSIDE }));
yield put(serverInitAdd(server));
yield delay(1000);
EventEmitter.emit('NewServer', { server: host });
}
if (params.token) {
// A resume token in a deep link silently authenticates the user to `host`. Since any
// app or web page can fire this link, require explicit confirmation before consuming it.
const confirmed = yield call(confirmDeepLinkLogin, host);
if (!confirmed) {
yield put(appStart({ root: RootEnum.ROOT_OUTSIDE }));
return;
}
if (!hostAlreadyConnected) {
yield take(types.SERVER.SELECT_SUCCESS);
// SERVER.SELECT_SUCCESS doesn't mean 'connected'; skip the take if it already is.
const connected = yield select(state => state.meteor.connected);
if (!connected) {
yield take(types.METEOR.SUCCESS);
}
}
yield put(loginRequest({ resume: params.token }, true));
yield take(types.LOGIN.SUCCESS);
yield put(appReady({}));
// Wait for the login saga's appStart(ROOT_INSIDE) before navigating, so
// InsideStack is mounted and goRoom dispatches into the correct stack.
const currentRoot = yield select(state => state.app.root);
if (currentRoot !== RootEnum.ROOT_INSIDE) {
yield take(action => action.type === types.APP.START && action.root === RootEnum.ROOT_INSIDE);
}
yield completeDeepLinkNavigation(params);
} else {
yield handleInviteLink({ params, requireLogin: true });
}
}
};
const handleNavigateCallRoom = function* handleNavigateCallRoom({ params }) {
try {
yield put(appStart({ root: RootEnum.ROOT_INSIDE }));
const db = database.active;
const subsCollection = db.get('subscriptions');
const room = yield subsCollection.find(params.rid);
if (room) {
const isMasterDetail = getIsMasterDetail();
yield navigateToRoom({ item: room, isMasterDetail });
const uid = params.caller?._id;
const { rid, callId, event } = params;
if (event === 'accept') {
yield call(notifyUser, `${uid}/video-conference`, {
action: 'accepted',
params: { uid, rid, callId }
});
yield videoConfJoin(callId, true, false, true);
} else if (event === 'decline') {
yield call(notifyUser, `${uid}/video-conference`, {
action: 'rejected',
params: { uid, rid, callId }
});
}
}
} catch (e) {
log(e);
}
};
const handleClickCallPush = function* handleClickCallPush({ params }) {
let { host } = params;
if (!host) {
return;
}
host = normalizeDeepLinkingServerHost(host);
if (!host) {
return;
}
params.host = host;
const [server, user] = yield all([
UserPreferences.getString(CURRENT_SERVER),
UserPreferences.getString(`${TOKEN_KEY}-${host}`)
]);
const serverRecord = yield getServerById(host);
if (server === host && user && serverRecord) {
const connected = yield select(state => state.server.connected);
if (!connected) {
yield localAuthenticate(host);
yield put(selectServerRequest(host, serverRecord.version, true));
yield take(types.LOGIN.SUCCESS);
}
yield handleNavigateCallRoom({ params });
} else {
if (user && serverRecord) {
yield localAuthenticate(host);
yield put(selectServerRequest(host, serverRecord.version, true, true));
yield take(types.LOGIN.SUCCESS);
yield handleNavigateCallRoom({ params });
return;
}
// if deep link is from a different server
const result = yield getServerInfo(host);
if (!result.success) {
// Fallback to prevent the app from being stuck on splash screen
yield fallbackNavigation();
return;
}
yield put(appStart({ root: RootEnum.ROOT_OUTSIDE }));
yield put(serverInitAdd(server));
yield delay(1000);
EventEmitter.emit('NewServer', { server: host });
if (params.token) {
yield take(types.SERVER.SELECT_SUCCESS);
// SERVER.SELECT_SUCCESS doesn't mean 'connected'; skip the take if it already is.
const connected = yield select(state => state.meteor.connected);
if (!connected) {
yield take(types.METEOR.SUCCESS);
}
yield put(loginRequest({ resume: params.token }, true));
yield take(types.LOGIN.SUCCESS);
yield handleNavigateCallRoom({ params });
}
}
};
const root = function* root() {
yield takeLatest(types.DEEP_LINKING.OPEN, handleOpen);
yield takeLatest(types.DEEP_LINKING.OPEN_VIDEO_CONF, handleClickCallPush);
};
export default root;