-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
User.js
492 lines (456 loc) · 14.4 KB
/
User.js
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
import _ from 'underscore';
import lodashGet from 'lodash/get';
import Onyx from 'react-native-onyx';
import moment from 'moment';
import ONYXKEYS from '../../ONYXKEYS';
import * as DeprecatedAPI from '../deprecatedAPI';
import * as API from '../API';
import CONFIG from '../../CONFIG';
import CONST from '../../CONST';
import Navigation from '../Navigation/Navigation';
import ROUTES from '../../ROUTES';
import * as Pusher from '../Pusher/pusher';
import Log from '../Log';
import NetworkConnection from '../NetworkConnection';
import Growl from '../Growl';
import * as Localize from '../Localize';
import * as Link from './Link';
import * as SequentialQueue from '../Network/SequentialQueue';
import PusherUtils from '../PusherUtils';
import * as Report from './Report';
import * as ReportActionsUtils from '../ReportActionsUtils';
let currentUserAccountID = '';
Onyx.connect({
key: ONYXKEYS.SESSION,
callback: (val) => {
currentUserAccountID = lodashGet(val, 'accountID', '');
},
});
/**
* Changes a password for a given account
*
* @param {String} oldPassword
* @param {String} password
*/
function updatePassword(oldPassword, password) {
API.write('UpdatePassword', {
oldPassword,
password,
}, {
optimisticData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {...CONST.DEFAULT_ACCOUNT_DATA, isLoading: true},
},
],
successData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {isLoading: false},
},
],
failureData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {isLoading: false},
},
],
});
}
/**
* Attempt to close the user's account
*
* @param {String} message optional reason for closing account
*/
function closeAccount(message) {
// Note: successData does not need to set isLoading to false because if the CloseAccount
// command succeeds, a Pusher response will clear all Onyx data.
API.write('CloseAccount', {message}, {
optimisticData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.FORMS.CLOSE_ACCOUNT_FORM,
value: {isLoading: true},
},
],
failureData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.FORMS.CLOSE_ACCOUNT_FORM,
value: {isLoading: false},
},
],
});
}
/**
* Resends a validation link to a given login
*
* @param {String} login
* @param {Boolean} isPasswordless - temporary param to trigger passwordless flow in backend
*/
function resendValidateCode(login, isPasswordless = false) {
DeprecatedAPI.ResendValidateCode({email: login, isPasswordless});
}
/**
* Sets whether or not the user is subscribed to Expensify news
*
* @param {Boolean} isSubscribed
*/
function updateNewsletterSubscription(isSubscribed) {
API.write('UpdateNewsletterSubscription', {
isSubscribed,
}, {
optimisticData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.USER,
value: {isSubscribedToNewsletter: isSubscribed},
},
],
failureData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.USER,
value: {isSubscribedToNewsletter: !isSubscribed},
},
],
});
}
/**
* Adds a secondary login to a user's account
*
* @param {String} login
* @param {String} password
* @returns {Promise}
*/
function setSecondaryLoginAndNavigate(login, password) {
Onyx.merge(ONYXKEYS.ACCOUNT, {...CONST.DEFAULT_ACCOUNT_DATA, isLoading: true});
return DeprecatedAPI.User_SecondaryLogin_Send({
email: login,
password,
}).then((response) => {
if (response.jsonCode === 200) {
Onyx.set(ONYXKEYS.LOGIN_LIST, response.loginList);
Navigation.navigate(ROUTES.SETTINGS_PROFILE);
return;
}
let error = lodashGet(response, 'message', 'Unable to add secondary login. Please try again.');
// Replace error with a friendlier message
if (error.includes('already belongs to an existing Expensify account.')) {
error = 'This login already belongs to an existing Expensify account.';
}
if (error.includes('I couldn\'t validate the phone number')) {
error = Localize.translateLocal('common.error.phoneNumber');
}
Onyx.merge(ONYXKEYS.USER, {error});
}).finally(() => {
Onyx.merge(ONYXKEYS.ACCOUNT, {isLoading: false});
});
}
/**
* Validates a login given an accountID and validation code
*
* @param {Number} accountID
* @param {String} validateCode
*/
function validateLogin(accountID, validateCode) {
Onyx.merge(ONYXKEYS.ACCOUNT, {...CONST.DEFAULT_ACCOUNT_DATA, isLoading: true});
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.ACCOUNT,
value: {
isLoading: false,
},
},
];
API.write('ValidateLogin', {
accountID,
validateCode,
}, {optimisticData});
Navigation.navigate(ROUTES.HOME);
}
/**
* Checks the blockedFromConcierge object to see if it has an expiresAt key,
* and if so whether the expiresAt date of a user's ban is before right now
*
* @param {Object} blockedFromConciergeNVP
* @returns {Boolean}
*/
function isBlockedFromConcierge(blockedFromConciergeNVP) {
if (_.isEmpty(blockedFromConciergeNVP)) {
return false;
}
if (!blockedFromConciergeNVP.expiresAt) {
return false;
}
return moment().isBefore(moment(blockedFromConciergeNVP.expiresAt), 'day');
}
/**
* Adds a paypal.me address for the user
*
* @param {String} address
*/
function addPaypalMeAddress(address) {
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.NVP_PAYPAL_ME_ADDRESS,
value: address,
},
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.PAYPAL,
value: {
title: 'PayPal.me',
description: address,
methodID: CONST.PAYMENT_METHODS.PAYPAL,
key: 'payPalMePaymentMethod',
accountType: CONST.PAYMENT_METHODS.PAYPAL,
accountData: {
username: address,
},
isDefault: false,
},
},
];
API.write('AddPaypalMeAddress', {
value: address,
}, {optimisticData});
}
/**
* Deletes a paypal.me address for the user
*
*/
function deletePaypalMeAddress() {
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.SET,
key: ONYXKEYS.NVP_PAYPAL_ME_ADDRESS,
value: '',
},
{
onyxMethod: CONST.ONYX.METHOD.SET,
key: ONYXKEYS.PAYPAL,
value: {},
},
];
API.write('DeletePaypalMeAddress', {}, {optimisticData});
Growl.show(Localize.translateLocal('paymentsPage.deletePayPalSuccess'), CONST.GROWL.SUCCESS, 3000);
}
function triggerNotifications(onyxUpdates) {
_.each(onyxUpdates, (update) => {
if (!update.shouldNotify) {
return;
}
const reportID = update.key.replace(ONYXKEYS.COLLECTION.REPORT_ACTIONS, '');
const reportActions = _.values(update.value);
const sortedReportActions = ReportActionsUtils.getSortedReportActions(reportActions);
Report.showReportActionNotification(reportID, _.last(sortedReportActions));
});
}
/**
* Initialize our pusher subscription to listen for user changes
*/
function subscribeToUserEvents() {
// If we don't have the user's accountID yet we can't subscribe so return early
if (!currentUserAccountID) {
return;
}
const pusherChannelName = `${CONST.PUSHER.PRIVATE_USER_CHANNEL_PREFIX}${currentUserAccountID}${CONFIG.PUSHER.SUFFIX}`;
// Receive any relevant Onyx updates from the server
PusherUtils.subscribeToPrivateUserChannelEvent(Pusher.TYPE.ONYX_API_UPDATE, currentUserAccountID, (pushJSON) => {
SequentialQueue.getCurrentRequest().then(() => {
Onyx.update(pushJSON);
triggerNotifications(pushJSON);
});
});
// Live-update an user's preferred locale
Pusher.subscribe(pusherChannelName, Pusher.TYPE.PREFERRED_LOCALE, (pushJSON) => {
Onyx.merge(ONYXKEYS.NVP_PREFERRED_LOCALE, pushJSON.preferredLocale);
},
() => {
NetworkConnection.triggerReconnectionCallbacks('pusher re-subscribed to private user channel');
})
.catch((error) => {
Log.hmmm(
'[User] Failed to subscribe to Pusher channel',
false,
{error, pusherChannelName, eventName: Pusher.TYPE.PREFERRED_LOCALE},
);
});
// Subscribe to screen share requests sent by GuidesPlus agents
Pusher.subscribe(pusherChannelName, Pusher.TYPE.SCREEN_SHARE_REQUEST, (pushJSON) => {
Onyx.merge(ONYXKEYS.SCREEN_SHARE_REQUEST, pushJSON);
},
() => {
NetworkConnection.triggerReconnectionCallbacks('pusher re-subscribed to private user channel');
})
.catch((error) => {
Log.hmmm(
'[User] Failed to subscribe to Pusher channel',
false,
{error, pusherChannelName, eventName: Pusher.TYPE.SCREEN_SHARE_REQUEST},
);
});
}
/**
* Subscribes to Expensify Card updates when checking loginList for private domains
*/
function subscribeToExpensifyCardUpdates() {
if (!currentUserAccountID) {
return;
}
const pusherChannelName = `${CONST.PUSHER.PRIVATE_USER_CHANNEL_PREFIX}${currentUserAccountID}${CONFIG.PUSHER.SUFFIX}`;
// Handle Expensify Card approval flow updates
Pusher.subscribe(pusherChannelName, Pusher.TYPE.EXPENSIFY_CARD_UPDATE, (pushJSON) => {
if (pushJSON.isUsingExpensifyCard) {
Onyx.merge(ONYXKEYS.USER, {isUsingExpensifyCard: pushJSON.isUsingExpensifyCard, isCheckingDomain: null});
Pusher.unsubscribe(pusherChannelName, Pusher.TYPE.EXPENSIFY_CARD_UPDATE);
} else {
Onyx.merge(ONYXKEYS.USER, {isCheckingDomain: pushJSON.isCheckingDomain});
}
},
() => {
NetworkConnection.triggerReconnectionCallbacks('pusher re-subscribed to private user channel');
})
.catch((error) => {
Log.info(
'[User] Failed to subscribe to Pusher channel',
false,
{error, pusherChannelName, eventName: Pusher.TYPE.EXPENSIFY_CARD_UPDATE},
);
});
}
/**
* Sync preferredSkinTone with Onyx and Server
* @param {String} skinTone
*/
function updatePreferredSkinTone(skinTone) {
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.SET,
key: ONYXKEYS.PREFERRED_EMOJI_SKIN_TONE,
value: skinTone,
},
];
API.write('UpdatePreferredEmojiSkinTone', {
value: skinTone,
}, {optimisticData});
}
/**
* Sync frequentlyUsedEmojis with Onyx and Server
* @param {Object[]} frequentlyUsedEmojis
*/
function updateFrequentlyUsedEmojis(frequentlyUsedEmojis) {
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.SET,
key: ONYXKEYS.FREQUENTLY_USED_EMOJIS,
value: frequentlyUsedEmojis,
},
];
API.write('UpdateFrequentlyUsedEmojis', {
value: JSON.stringify(frequentlyUsedEmojis),
}, {optimisticData});
}
/**
* Sync user chat priority mode with Onyx and Server
* @param {String} mode
*/
function updateChatPriorityMode(mode) {
const optimisticData = [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.NVP_PRIORITY_MODE,
value: mode,
},
];
API.write('UpdateChatPriorityMode', {
value: mode,
}, {optimisticData});
Navigation.navigate(ROUTES.SETTINGS_PREFERENCES);
}
/**
* @param {Boolean} shouldUseStagingServer
*/
function setShouldUseStagingServer(shouldUseStagingServer) {
Onyx.merge(ONYXKEYS.USER, {shouldUseStagingServer});
}
function clearUserErrorMessage() {
Onyx.merge(ONYXKEYS.USER, {error: ''});
}
/**
* Clear the data about a screen share request from Onyx.
*/
function clearScreenShareRequest() {
Onyx.set(ONYXKEYS.SCREEN_SHARE_REQUEST, null);
}
/**
* Open an OldDot tab linking to a screen share request.
* @param {String} accessToken Access token required to join a screen share room, generated by the backend
* @param {String} roomName Name of the screen share room to join
*/
function joinScreenShare(accessToken, roomName) {
Link.openOldDotLink(`inbox?action=screenShare&accessToken=${accessToken}&name=${roomName}`);
clearScreenShareRequest();
}
/**
* Downloads the statement PDF for the provided period
* @param {String} period YYYYMM format
*/
function generateStatementPDF(period) {
API.read('GetStatementPDF', {period}, {
optimisticData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.WALLET_STATEMENT,
value: {
isGenerating: true,
},
},
],
successData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.WALLET_STATEMENT,
value: {
isGenerating: false,
},
},
],
failureData: [
{
onyxMethod: CONST.ONYX.METHOD.MERGE,
key: ONYXKEYS.WALLET_STATEMENT,
value: {
isGenerating: false,
},
},
],
});
}
export {
updatePassword,
closeAccount,
resendValidateCode,
updateNewsletterSubscription,
setSecondaryLoginAndNavigate,
validateLogin,
isBlockedFromConcierge,
subscribeToUserEvents,
updatePreferredSkinTone,
setShouldUseStagingServer,
clearUserErrorMessage,
subscribeToExpensifyCardUpdates,
updateFrequentlyUsedEmojis,
joinScreenShare,
clearScreenShareRequest,
generateStatementPDF,
deletePaypalMeAddress,
addPaypalMeAddress,
updateChatPriorityMode,
};