-
Notifications
You must be signed in to change notification settings - Fork 3k
/
App.ts
529 lines (468 loc) · 20.5 KB
/
App.ts
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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Issue - https://github.com/Expensify/App/issues/26719
import Str from 'expensify-common/lib/str';
import type {AppStateStatus} from 'react-native';
import {AppState} from 'react-native';
import type {OnyxCollection, OnyxEntry, OnyxUpdate} from 'react-native-onyx';
import Onyx from 'react-native-onyx';
import type {ValueOf} from 'type-fest';
import * as API from '@libs/API';
import type {
GetMissingOnyxMessagesParams,
HandleRestrictedEventParams,
OpenAppParams,
OpenOldDotLinkParams,
OpenProfileParams,
ReconnectAppParams,
UpdatePreferredLocaleParams,
} from '@libs/API/parameters';
import {READ_COMMANDS, SIDE_EFFECT_REQUEST_COMMANDS, WRITE_COMMANDS} from '@libs/API/types';
import * as Browser from '@libs/Browser';
import DateUtils from '@libs/DateUtils';
import Log from '@libs/Log';
import getCurrentUrl from '@libs/Navigation/currentUrl';
import Navigation from '@libs/Navigation/Navigation';
import Performance from '@libs/Performance';
import * as ReportActionsUtils from '@libs/ReportActionsUtils';
import * as SessionUtils from '@libs/SessionUtils';
import CONST from '@src/CONST';
import ONYXKEYS from '@src/ONYXKEYS';
import type {Route} from '@src/ROUTES';
import ROUTES from '@src/ROUTES';
import type * as OnyxTypes from '@src/types/onyx';
import type {SelectedTimezone} from '@src/types/onyx/PersonalDetails';
import type {OnyxData} from '@src/types/onyx/Request';
import * as Policy from './Policy';
import * as Session from './Session';
import Timing from './Timing';
type PolicyParamsForOpenOrReconnect = {
policyIDList: string[];
};
type Locale = ValueOf<typeof CONST.LOCALES>;
let currentUserAccountID: number | null;
let currentUserEmail: string;
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (val) => {
currentUserAccountID = val?.accountID ?? null;
currentUserEmail = val?.email ?? '';
},
});
let isSidebarLoaded: boolean | null;
Onyx.connect({
key: ONYXKEYS.IS_SIDEBAR_LOADED,
callback: (val) => (isSidebarLoaded = val),
initWithStoredValues: false,
});
let preferredLocale: string | null;
Onyx.connect({
key: ONYXKEYS.NVP_PREFERRED_LOCALE,
callback: (val) => (preferredLocale = val),
});
let priorityMode: ValueOf<typeof CONST.PRIORITY_MODE> | null;
Onyx.connect({
key: ONYXKEYS.NVP_PRIORITY_MODE,
callback: (nextPriorityMode) => {
// When someone switches their priority mode we need to fetch all their chats because only #focus mode works with a subset of a user's chats. This is only possible via the OpenApp command.
if (nextPriorityMode === CONST.PRIORITY_MODE.DEFAULT && priorityMode === CONST.PRIORITY_MODE.GSD) {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
openApp();
}
priorityMode = nextPriorityMode;
},
});
let resolveIsReadyPromise: () => void;
const isReadyToOpenApp = new Promise<void>((resolve) => {
resolveIsReadyPromise = resolve;
});
function confirmReadyToOpenApp() {
resolveIsReadyPromise();
}
function getNonOptimisticPolicyIDs(policies: OnyxCollection<OnyxTypes.Policy>): string[] {
return Object.values(policies ?? {})
.filter((policy) => policy && policy.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD)
.map((policy) => policy?.id)
.filter((id): id is string => !!id);
}
function setLocale(locale: Locale) {
if (locale === preferredLocale) {
return;
}
// If user is not signed in, change just locally.
if (!currentUserAccountID) {
Onyx.merge(ONYXKEYS.NVP_PREFERRED_LOCALE, locale);
return;
}
// Optimistically change preferred locale
const optimisticData: OnyxUpdate[] = [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.NVP_PREFERRED_LOCALE,
value: locale,
},
];
const parameters: UpdatePreferredLocaleParams = {
value: locale,
};
API.write(WRITE_COMMANDS.UPDATE_PREFERRED_LOCALE, parameters, {optimisticData});
}
function setLocaleAndNavigate(locale: Locale) {
setLocale(locale);
Navigation.goBack();
}
function setSidebarLoaded() {
if (isSidebarLoaded) {
return;
}
Onyx.set(ONYXKEYS.IS_SIDEBAR_LOADED, true);
Performance.markEnd(CONST.TIMING.SIDEBAR_LOADED);
Performance.markStart(CONST.TIMING.REPORT_INITIAL_RENDER);
}
let appState: AppStateStatus;
AppState.addEventListener('change', (nextAppState) => {
if (nextAppState.match(/inactive|background/) && appState === 'active') {
Log.info('Flushing logs as app is going inactive', true, {}, true);
}
appState = nextAppState;
});
/**
* Gets the policy params that are passed to the server in the OpenApp and ReconnectApp API commands. This includes a full list of policy IDs the client knows about as well as when they were last modified.
*/
function getPolicyParamsForOpenOrReconnect(): Promise<PolicyParamsForOpenOrReconnect> {
return new Promise((resolve) => {
isReadyToOpenApp.then(() => {
const connectionID = Onyx.connect({
key: ONYXKEYS.COLLECTION.POLICY,
waitForCollectionCallback: true,
callback: (policies) => {
Onyx.disconnect(connectionID);
resolve({policyIDList: getNonOptimisticPolicyIDs(policies)});
},
});
});
});
}
/**
* Returns the Onyx data that is used for both the OpenApp and ReconnectApp API commands.
*/
function getOnyxDataForOpenOrReconnect(isOpenApp = false): OnyxData {
const defaultData = {
optimisticData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.IS_LOADING_REPORT_DATA,
value: true,
},
],
finallyData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.IS_LOADING_REPORT_DATA,
value: false,
},
],
};
if (!isOpenApp) {
return defaultData;
}
return {
optimisticData: [
...defaultData.optimisticData,
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.IS_LOADING_APP,
value: true,
},
],
finallyData: [
...defaultData.finallyData,
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.IS_LOADING_APP,
value: false,
},
],
};
}
/**
* Fetches data needed for app initialization
*/
function openApp() {
getPolicyParamsForOpenOrReconnect().then((policyParams: PolicyParamsForOpenOrReconnect) => {
const params: OpenAppParams = {enablePriorityModeFilter: true, ...policyParams};
API.read(READ_COMMANDS.OPEN_APP, params, getOnyxDataForOpenOrReconnect(true));
});
}
/**
* Fetches data when the app reconnects to the network
* @param [updateIDFrom] the ID of the Onyx update that we want to start fetching from
*/
function reconnectApp(updateIDFrom: OnyxEntry<number> = 0) {
console.debug(`[OnyxUpdates] App reconnecting with updateIDFrom: ${updateIDFrom}`);
getPolicyParamsForOpenOrReconnect().then((policyParams) => {
const params: ReconnectAppParams = {...policyParams};
// When the app reconnects we do a fast "sync" of the LHN and only return chats that have new messages. We achieve this by sending the most recent reportActionID.
// we have locally. And then only update the user about chats with messages that have occurred after that reportActionID.
//
// - Look through the local report actions and reports to find the most recently modified report action or report.
// - We send this to the server so that it can compute which new chats the user needs to see and return only those as an optimization.
Timing.start(CONST.TIMING.CALCULATE_MOST_RECENT_LAST_MODIFIED_ACTION);
params.mostRecentReportActionLastModified = ReportActionsUtils.getMostRecentReportActionLastModified();
Timing.end(CONST.TIMING.CALCULATE_MOST_RECENT_LAST_MODIFIED_ACTION, '', 500);
// Include the update IDs when reconnecting so that the server can send incremental updates if they are available.
// Otherwise, a full set of app data will be returned.
if (updateIDFrom) {
params.updateIDFrom = updateIDFrom;
}
API.write(WRITE_COMMANDS.RECONNECT_APP, params, getOnyxDataForOpenOrReconnect());
});
}
/**
* Fetches data when the app will call reconnectApp without params for the last time. This is a separate function
* because it will follow patterns that are not recommended so we can be sure we're not putting the app in a unusable
* state because of race conditions between reconnectApp and other pusher updates being applied at the same time.
*/
function finalReconnectAppAfterActivatingReliableUpdates(): Promise<void | OnyxTypes.Response> {
console.debug(`[OnyxUpdates] Executing last reconnect app with promise`);
return getPolicyParamsForOpenOrReconnect().then((policyParams) => {
const params: ReconnectAppParams = {...policyParams};
// When the app reconnects we do a fast "sync" of the LHN and only return chats that have new messages. We achieve this by sending the most recent reportActionID.
// we have locally. And then only update the user about chats with messages that have occurred after that reportActionID.
//
// - Look through the local report actions and reports to find the most recently modified report action or report.
// - We send this to the server so that it can compute which new chats the user needs to see and return only those as an optimization.
Timing.start(CONST.TIMING.CALCULATE_MOST_RECENT_LAST_MODIFIED_ACTION);
params.mostRecentReportActionLastModified = ReportActionsUtils.getMostRecentReportActionLastModified();
Timing.end(CONST.TIMING.CALCULATE_MOST_RECENT_LAST_MODIFIED_ACTION, '', 500);
// It is SUPER BAD FORM to return promises from action methods.
// DO NOT FOLLOW THIS PATTERN!!!!!
// It was absolutely necessary in order to not break the app while migrating to the new reliable updates pattern. This method will be removed
// as soon as we have everyone migrated to the reliableUpdate beta.
// eslint-disable-next-line rulesdir/no-api-side-effects-method
return API.makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.RECONNECT_APP, params, getOnyxDataForOpenOrReconnect());
});
}
/**
* Fetches data when the client has discovered it missed some Onyx updates from the server
* @param [updateIDFrom] the ID of the Onyx update that we want to start fetching from
* @param [updateIDTo] the ID of the Onyx update that we want to fetch up to
*/
function getMissingOnyxUpdates(updateIDFrom = 0, updateIDTo: number | string = 0): Promise<void | OnyxTypes.Response> {
console.debug(`[OnyxUpdates] Fetching missing updates updateIDFrom: ${updateIDFrom} and updateIDTo: ${updateIDTo}`);
const parameters: GetMissingOnyxMessagesParams = {
updateIDFrom,
updateIDTo,
};
// It is SUPER BAD FORM to return promises from action methods.
// DO NOT FOLLOW THIS PATTERN!!!!!
// It was absolutely necessary in order to block OnyxUpdates while fetching the missing updates from the server or else the udpates aren't applied in the proper order.
// eslint-disable-next-line rulesdir/no-api-side-effects-method
return API.makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.GET_MISSING_ONYX_MESSAGES, parameters, getOnyxDataForOpenOrReconnect());
}
/**
* This promise is used so that deeplink component know when a transition is end.
* This is necessary because we want to begin deeplink redirection after the transition is end.
*/
let resolveSignOnTransitionToFinishPromise: () => void;
const signOnTransitionToFinishPromise = new Promise<void>((resolve) => {
resolveSignOnTransitionToFinishPromise = resolve;
});
function waitForSignOnTransitionToFinish(): Promise<void> {
return signOnTransitionToFinishPromise;
}
function endSignOnTransition() {
return resolveSignOnTransitionToFinishPromise();
}
/**
* Create a new draft workspace and navigate to it
*
* @param [policyOwnerEmail] Optional, the email of the account to make the owner of the policy
* @param [policyName] Optional, custom policy name we will use for created workspace
* @param [transitionFromOldDot] Optional, if the user is transitioning from old dot
* @param [makeMeAdmin] Optional, leave the calling account as an admin on the policy
*/
function createWorkspaceWithPolicyDraftAndNavigateToIt(policyOwnerEmail = '', policyName = '', transitionFromOldDot = false, makeMeAdmin = false) {
const policyID = Policy.generatePolicyID();
Policy.createDraftInitialWorkspace(policyOwnerEmail, policyName, policyID, makeMeAdmin);
Navigation.isNavigationReady()
.then(() => {
if (transitionFromOldDot) {
// We must call goBack() to remove the /transition route from history
Navigation.goBack();
}
Navigation.navigate(ROUTES.WORKSPACE_INITIAL.getRoute(policyID));
})
.then(endSignOnTransition);
}
/**
* Create a new workspace and delete the draft
*
* @param [policyID] the ID of the policy to use
* @param [policyName] custom policy name we will use for created workspace
* @param [policyOwnerEmail] Optional, the email of the account to make the owner of the policy
* @param [makeMeAdmin] Optional, leave the calling account as an admin on the policy
*/
function savePolicyDraftByNewWorkspace(policyID?: string, policyName?: string, policyOwnerEmail = '', makeMeAdmin = false) {
Policy.createWorkspace(policyOwnerEmail, makeMeAdmin, policyName, policyID);
}
/**
* This action runs when the Navigator is ready and the current route changes
*
* currentPath should be the path as reported by the NavigationContainer
*
* The transition link contains an exitTo param that contains the route to
* navigate to after the user is signed in. A user can transition from OldDot
* with a different account than the one they are currently signed in with, so
* we only navigate if they are not signing in as a new user. Once they are
* signed in as that new user, this action will run again and the navigation
* will occur.
* When the exitTo route is 'workspace/new', we create a new
* workspace and navigate to it
*
* We subscribe to the session using withOnyx in the AuthScreens and
* pass it in as a parameter. withOnyx guarantees that the value has been read
* from Onyx because it will not render the AuthScreens until that point.
*/
function setUpPoliciesAndNavigate(session: OnyxEntry<OnyxTypes.Session>) {
const currentUrl = getCurrentUrl();
if (!session || !currentUrl || !currentUrl.includes('exitTo')) {
return;
}
const isLoggingInAsNewUser = !!session.email && SessionUtils.isLoggingInAsNewUser(currentUrl, session.email);
const url = new URL(currentUrl);
const exitTo = url.searchParams.get('exitTo') as Route | null;
// Approved Accountants and Guides can enter a flow where they make a workspace for other users,
// and those are passed as a search parameter when using transition links
const policyOwnerEmail = url.searchParams.get('ownerEmail') ?? '';
const makeMeAdmin = !!url.searchParams.get('makeMeAdmin');
const policyName = url.searchParams.get('policyName') ?? '';
// Sign out the current user if we're transitioning with a different user
const isTransitioning = Str.startsWith(url.pathname, Str.normalizeUrl(ROUTES.TRANSITION_BETWEEN_APPS));
const shouldCreateFreePolicy = !isLoggingInAsNewUser && isTransitioning && exitTo === ROUTES.WORKSPACE_NEW;
if (shouldCreateFreePolicy) {
createWorkspaceWithPolicyDraftAndNavigateToIt(policyOwnerEmail, policyName, true, makeMeAdmin);
return;
}
if (!isLoggingInAsNewUser && exitTo) {
Navigation.waitForProtectedRoutes()
.then(() => {
// We must call goBack() to remove the /transition route from history
Navigation.goBack();
Navigation.navigate(exitTo);
})
.then(endSignOnTransition);
}
}
function redirectThirdPartyDesktopSignIn() {
const currentUrl = getCurrentUrl();
if (!currentUrl) {
return;
}
const url = new URL(currentUrl);
if (url.pathname === `/${ROUTES.GOOGLE_SIGN_IN}` || url.pathname === `/${ROUTES.APPLE_SIGN_IN}`) {
Navigation.isNavigationReady().then(() => {
Navigation.goBack();
Navigation.navigate(ROUTES.DESKTOP_SIGN_IN_REDIRECT);
});
}
}
function openProfile(personalDetails: OnyxTypes.PersonalDetails) {
const oldTimezoneData = personalDetails.timezone ?? {};
let newTimezoneData = oldTimezoneData;
if (oldTimezoneData?.automatic ?? true) {
newTimezoneData = {
automatic: true,
selected: Intl.DateTimeFormat().resolvedOptions().timeZone as SelectedTimezone,
};
}
newTimezoneData = DateUtils.formatToSupportedTimezone(newTimezoneData);
const parameters: OpenProfileParams = {
timezone: JSON.stringify(newTimezoneData),
};
// We expect currentUserAccountID to be a number because it doesn't make sense to open profile if currentUserAccountID is not set
if (typeof currentUserAccountID === 'number') {
API.write(WRITE_COMMANDS.OPEN_PROFILE, parameters, {
optimisticData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
value: {
[currentUserAccountID]: {
timezone: newTimezoneData,
},
},
},
],
failureData: [
{
onyxMethod: Onyx.METHOD.MERGE,
key: ONYXKEYS.PERSONAL_DETAILS_LIST,
value: {
[currentUserAccountID]: {
timezone: oldTimezoneData,
},
},
},
],
});
}
}
/**
* @param shouldAuthenticateWithCurrentAccount Optional, indicates whether default authentication method (shortLivedAuthToken) should be used
*/
function beginDeepLinkRedirect(shouldAuthenticateWithCurrentAccount = true) {
// There's no support for anonymous users on desktop
if (Session.isAnonymousUser()) {
return;
}
// If the route that is being handled is a magic link, email and shortLivedAuthToken should not be attached to the url
// to prevent signing into the wrong account
if (!currentUserAccountID || !shouldAuthenticateWithCurrentAccount) {
Browser.openRouteInDesktopApp();
return;
}
const parameters: OpenOldDotLinkParams = {shouldRetry: false};
// eslint-disable-next-line rulesdir/no-api-side-effects-method
API.makeRequestWithSideEffects(SIDE_EFFECT_REQUEST_COMMANDS.OPEN_OLD_DOT_LINK, parameters, {}).then((response) => {
if (!response) {
Log.alert(
'Trying to redirect via deep link, but the response is empty. User likely not authenticated.',
{response, shouldAuthenticateWithCurrentAccount, currentUserAccountID},
true,
);
return;
}
Browser.openRouteInDesktopApp(response.shortLivedAuthToken, currentUserEmail);
});
}
/**
* @param shouldAuthenticateWithCurrentAccount Optional, indicates whether default authentication method (shortLivedAuthToken) should be used
*/
function beginDeepLinkRedirectAfterTransition(shouldAuthenticateWithCurrentAccount = true) {
waitForSignOnTransitionToFinish().then(() => beginDeepLinkRedirect(shouldAuthenticateWithCurrentAccount));
}
function handleRestrictedEvent(eventName: string) {
const parameters: HandleRestrictedEventParams = {eventName};
API.write(WRITE_COMMANDS.HANDLE_RESTRICTED_EVENT, parameters);
}
function updateLastVisitedPath(path: string) {
Onyx.merge(ONYXKEYS.LAST_VISITED_PATH, path);
}
export {
setLocale,
setLocaleAndNavigate,
setSidebarLoaded,
setUpPoliciesAndNavigate,
openProfile,
redirectThirdPartyDesktopSignIn,
openApp,
reconnectApp,
confirmReadyToOpenApp,
handleRestrictedEvent,
beginDeepLinkRedirect,
beginDeepLinkRedirectAfterTransition,
getMissingOnyxUpdates,
finalReconnectAppAfterActivatingReliableUpdates,
savePolicyDraftByNewWorkspace,
createWorkspaceWithPolicyDraftAndNavigateToIt,
updateLastVisitedPath,
};