-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathindex.js
649 lines (535 loc) · 16.2 KB
/
index.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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
import { AppRegistry, Platform, LogBox } from "react-native"
import { name as appName } from "./app.json"
import "./src/lib/globals"
import "./src/lib/node"
import "./src/lib/services/socket/socket"
import { App } from "./src/App"
import { runCameraUpload } from "./src/lib/services/cameraUpload"
import notifee, { AndroidImportance } from "@notifee/react-native"
import eventListener from "./src/lib/eventListener"
import { i18n } from "./src/i18n"
import storage from "./src/lib/storage"
import { Notifications, NotificationBackgroundFetchResult } from "react-native-notifications"
import { hasNotificationPermissions } from "./src/lib/permissions"
import { Semaphore } from "./src/lib/helpers"
import { decryptChatMessage } from "./src/lib/crypto"
import { dbFs } from "./src/lib/db"
import * as BackgroundFetch from "expo-background-fetch"
import * as TaskManager from "expo-task-manager"
import NetInfo from "@react-native-community/netinfo"
NetInfo.configure({
reachabilityLongTimeout: 60000,
reachabilityShortTimeout: 15000,
reachabilityMethod: "GET",
reachabilityRequestTimeout: 30000,
reachabilityShouldRun: () => true,
reachabilityTest: async response => response.status === 200,
reachabilityUrl: "https://gateway.filen.io",
useNativeReachability: false
})
if (!__DEV__) {
console.log = () => {}
console.error = () => {}
console.warn = () => {}
} else {
LogBox.ignoreLogs(["new NativeEventEmitter", "Module AssetExporter", "DEPRECATED", "messaging()"])
}
const BACKGROUND_FETCH_TASK = "background-fetch"
let foregroundServiceRegistered = false
let foregroundServiceRegisteredMutex = new Semaphore(1)
let transfersNotificationMutex = new Semaphore(1)
let transfersNotificationId = null
let foregroundServiceChannelId = null
let transfersNotification = null
let lastTransfersNotificationProgress = -1
let currentDownloadsCountGlobal = 0
let currentUploadsCountGlobal = 0
let nextHasPermissionsQuery = 0
let lastHasPermissions = false
let normalNotificationsChannelId = null
let buildNotificationMutex = new Semaphore(1)
let cameraUploadNotificationMutex = new Semaphore(1)
let nextAllowedCameraUploadNotification = 0
let cameraUploadStatusGlobal = "inactive"
let normalNotificationsMutex = new Semaphore(1)
let handleForegroundServiceMutex = new Semaphore(1)
const hasNotifyPermissions = async () => {
const now = Date.now()
if (nextHasPermissionsQuery !== 0 && nextHasPermissionsQuery > now) {
return lastHasPermissions
}
nextHasPermissionsQuery = now + 300000
const permissions = await hasNotificationPermissions(false)
lastHasPermissions = permissions
return lastHasPermissions
}
const registerForegroundService = async () => {
await foregroundServiceRegisteredMutex.acquire()
try {
if (foregroundServiceRegistered) {
return
}
foregroundServiceRegistered = true
notifee.registerForegroundService(() => {
return new Promise(resolve => {
const wait = setInterval(() => {
handleForegroundServiceMutex.acquire().then(() => {
if (currentDownloadsCountGlobal + currentUploadsCountGlobal <= 0 && cameraUploadStatusGlobal === "inactive") {
clearInterval(wait)
notifee
.stopForegroundService()
.then(() => resolve())
.catch(err => {
console.error(err)
resolve()
})
.finally(() => {
foregroundServiceRegistered = false
handleForegroundServiceMutex.release()
})
} else {
handleForegroundServiceMutex.release()
}
})
}, 1000)
})
})
} catch (e) {
throw e
} finally {
foregroundServiceRegisteredMutex.release()
}
}
const handleForegroundService = async progress => {
await handleForegroundServiceMutex.acquire()
try {
await registerForegroundService()
const permissions = await hasNotifyPermissions()
if (!permissions) {
return
}
if (!foregroundServiceChannelId) {
foregroundServiceChannelId = await notifee.createChannel({
id: "foregroundService",
name: "Foreground Service",
vibration: false,
sound: undefined
})
}
const lang = storage.getString("lang") || "en"
const transferring =
currentUploadsCountGlobal + currentDownloadsCountGlobal <= 0 && cameraUploadStatusGlobal !== "inactive"
? 1
: currentUploadsCountGlobal + currentDownloadsCountGlobal
transfersNotification = {
title:
transferring <= 1
? i18n(lang, "transferringDots")
: i18n(lang, "transferringFiles", true, ["__NUM__"], [transferring.toString()]),
android: {
channelId: foregroundServiceChannelId,
asForegroundService: true,
localOnly: true,
ongoing: true,
importance: AndroidImportance.HIGH,
onlyAlertOnce: false,
loopSound: false,
autoCancel: false,
progress: {
max: 100,
current: progress,
indeterminate: progress >= 100 || progress <= 0
},
pressAction: {
id: "foregroundService",
launchActivity: "default"
},
groupId: "foregroundService",
timestamp: Date.now(),
smallIcon: "ic_small_icon",
color: "#ffffff"
},
data: {
type: "foregroundService"
}
}
if (!transfersNotificationId) {
transfersNotificationId = await notifee.displayNotification(transfersNotification)
lastTransfersNotificationProgress = progress
}
if (progress !== lastTransfersNotificationProgress && transfersNotificationId) {
const transferring =
currentUploadsCountGlobal + currentDownloadsCountGlobal <= 0 && cameraUploadStatusGlobal !== "inactive"
? 1
: currentUploadsCountGlobal + currentDownloadsCountGlobal
await notifee.displayNotification({
...transfersNotification,
id: transfersNotificationId,
title:
transferring <= 1
? i18n(lang, "transferringDots")
: i18n(lang, "transferringFiles", true, ["__NUM__"], [transferring.toString()]),
android: {
...transfersNotification.android,
progress: {
...transfersNotification.android.progress,
current: progress,
indeterminate: progress >= 100 || progress <= 0
}
}
})
lastTransfersNotificationProgress = progress
}
} catch (e) {
throw e
} finally {
handleForegroundServiceMutex.release()
}
}
if (Platform.OS === "android") {
eventListener.on("cameraUploadStatus", async status => {
cameraUploadStatusGlobal = status
await transfersNotificationMutex.acquire()
try {
if (currentDownloadsCountGlobal + currentUploadsCountGlobal <= 0 && cameraUploadStatusGlobal === "inactive") {
transfersNotificationId = null
foregroundServiceChannelId = null
transfersNotification = null
lastTransfersNotificationProgress = -1
currentDownloadsCountGlobal = 0
currentUploadsCountGlobal = 0
cameraUploadStatusGlobal = "inactive"
return
}
if (cameraUploadStatusGlobal === "inactive") {
return
}
const progress = 0
await handleForegroundService(progress)
} catch (e) {
console.error(e)
} finally {
transfersNotificationMutex.release()
}
})
eventListener.on("transfersUpdate", async ({ progress, currentDownloadsCount, currentUploadsCount }) => {
currentDownloadsCountGlobal = currentDownloadsCount
currentUploadsCountGlobal = currentUploadsCount
await transfersNotificationMutex.acquire()
try {
if (currentDownloadsCountGlobal + currentUploadsCountGlobal <= 0 && cameraUploadStatusGlobal === "inactive") {
transfersNotificationId = null
foregroundServiceChannelId = null
transfersNotification = null
lastTransfersNotificationProgress = -1
currentDownloadsCountGlobal = 0
currentUploadsCountGlobal = 0
cameraUploadStatusGlobal = "inactive"
return
}
if (currentDownloadsCountGlobal + currentUploadsCountGlobal <= 0) {
return
}
progress = Math.round(progress)
progress = progress <= 0 ? 0 : progress
progress = progress >= 100 ? 100 : progress
await handleForegroundService(progress)
} catch (e) {
console.error(e)
} finally {
transfersNotificationMutex.release()
}
})
}
const increaseBadgeCount = async by => {
const current = await notifee.getBadgeCount()
const newCount = current + by > 0 ? current + by : 1
await notifee.setBadgeCount(newCount)
}
const onCameraUploadNotification = async () => {
await cameraUploadNotificationMutex.acquire()
try {
//eventListener.emit("cameraUploadStatus", "active")
const now = Date.now()
if (nextAllowedCameraUploadNotification > now) {
return
}
nextAllowedCameraUploadNotification = now + 60000
await runCameraUpload(1, true)
} catch (e) {
throw e
} finally {
cameraUploadNotificationMutex.release()
//eventListener.emit("cameraUploadStatus", "inactive")
}
}
const buildNotification = async payload => {
await buildNotificationMutex.acquire()
try {
const permissions = await hasNotifyPermissions()
if (!permissions) {
return null
}
if (!normalNotificationsChannelId) {
normalNotificationsChannelId = await notifee.createChannel({
id: "notifications",
name: "Notifications",
vibration: false,
sound: undefined
})
}
const lang = storage.getString("lang") || "en"
let notification = {
title: "Filen",
body: i18n(lang, "newNotification"),
android: {
channelId: normalNotificationsChannelId,
pressAction: {
id: "open",
launchActivity: "default"
},
groupId: "notifications",
timestamp: Date.now(),
smallIcon: "ic_small_icon",
color: "#ffffff"
},
data: {
payload
}
}
if (payload.type === "chatMessageNew") {
const userId = storage.getNumber("userId")
if (userId === parseInt(payload.senderId)) {
return null
}
const cache = await dbFs.get("chatConversations")
const hasCache = cache && Array.isArray(cache)
const senderName =
typeof payload.senderNickName === "string" && payload.senderNickName.length > 0
? payload.senderNickName
: typeof payload.senderEmail === "string" && payload.senderEmail.length > 0
? payload.senderEmail
: i18n(lang, "aUser")
notification = {
...notification,
title: senderName,
body: i18n(lang, "chatMessageNewBody"),
android: {
...notification.android,
...(typeof payload.senderAvatar === "string" && payload.senderAvatar.startsWith("https://")
? { largeIcon: payload.senderAvatar }
: {}),
pressAction: {
...notification.android.pressAction,
id: "openChats"
}
}
}
if (hasCache) {
const conversations = cache.filter(conversation => conversation.uuid === payload.conversation)
if (conversations.length > 0) {
const conversation = conversations[0]
const participants = conversation.participants.filter(participant => participant.userId === userId)
if (participants.length > 0) {
const participant = participants[0]
const privateKey = storage.getString("privateKey")
if (typeof privateKey === "string" && privateKey.length > 0) {
const messageDecrypted = await decryptChatMessage(payload.message, participant.metadata, privateKey)
if (messageDecrypted.length > 0) {
notification = {
...notification,
title: senderName,
body: messageDecrypted,
android: {
...notification.android,
pressAction: {
...notification.android.pressAction,
id: "openChat:" + payload.conversation
}
}
}
}
}
}
}
}
}
if (payload.type === "contactRequestReceived") {
const senderName =
typeof payload.senderNickName === "string" && payload.senderNickName.length > 0
? payload.senderNickName
: typeof payload.senderEmail === "string" && payload.senderEmail.length > 0
? payload.senderEmail
: i18n(lang, "aUser")
notification = {
...notification,
title: senderName,
body: i18n(lang, "contactRequestReceivedBody"),
android: {
...notification.android,
...(typeof payload.senderAvatar === "string" && payload.senderAvatar.startsWith("https://")
? { largeIcon: payload.senderAvatar }
: {}),
pressAction: {
...notification.android.pressAction,
id: "openContacts"
}
}
}
}
return notification
} catch (e) {
throw e
} finally {
buildNotificationMutex.release()
}
}
const onBackgroundNotification = async (payload, completion) => {
const isLoggedIn = storage.getBoolean("isLoggedIn")
if (!isLoggedIn) {
return
}
if (payload.type === "cameraUpload") {
try {
await onCameraUploadNotification().catch(console.error)
} catch (e) {
console.error(e)
}
completion(NotificationBackgroundFetchResult.NEW_DATA)
return
}
if (Platform.OS === "ios") {
return
}
await normalNotificationsMutex.acquire()
try {
const notification = await buildNotification(payload)
if (notification) {
await notifee.displayNotification(notification)
await increaseBadgeCount(1)
}
completion(NotificationBackgroundFetchResult.NEW_DATA)
} catch (e) {
completion(NotificationBackgroundFetchResult.FAILED)
throw e
} finally {
normalNotificationsMutex.release()
}
}
const onForegroundNotification = async (payload, completion) => {
const isLoggedIn = storage.getBoolean("isLoggedIn")
if (!isLoggedIn) {
return
}
if (payload.type === "cameraUpload") {
completion({ alert: false, sound: false, badge: false })
return
}
if (Platform.OS === "ios") {
completion({ alert: false, sound: false, badge: false })
return
}
completion({ alert: false, sound: false, badge: false })
}
notifee.onBackgroundEvent(async () => {})
Notifications.events().registerRemoteNotificationsRegistered(event => {
storage.set("pushToken", event.deviceToken)
})
Notifications.events().registerRemoteNotificationsRegistrationFailed(event => {
console.error(event)
})
Notifications.events().registerNotificationReceivedForeground(async (notification, completion) => {
console.log(Platform.OS, "registerNotificationReceivedForeground", notification.payload)
try {
await onForegroundNotification(notification.payload, completion)
} catch (e) {
console.error(e)
}
})
Notifications.events().registerNotificationOpened((notification, completion, action) => {
completion()
})
Notifications.events().registerNotificationReceivedBackground(async (notification, completion) => {
console.log(Platform.OS, "registerNotificationReceivedBackground", notification.payload)
try {
await onBackgroundNotification(notification.payload, completion)
} catch (e) {
console.error(e)
}
})
Notifications.events().registerRemoteNotificationsRegistrationDenied(() => {
storage.delete("pushToken")
})
Notifications.events().registerRemoteNotificationsRegistrationFailed(err => {
console.error(err)
storage.delete("pushToken")
})
TaskManager.defineTask(BACKGROUND_FETCH_TASK, async () => {
try {
await onCameraUploadNotification().catch(console.error)
} catch (e) {
console.error(e)
}
return BackgroundFetch.BackgroundFetchResult.NewData
})
const init = async () => {
storage.set("sdkInit", false)
setTimeout(() => {
runCameraUpload()
globalThis.nodeThread.getCurrentTransfers().catch(console.error)
}, 5000)
BackgroundFetch.registerTaskAsync(BACKGROUND_FETCH_TASK, {
minimumInterval: 60 * 15,
stopOnTerminate: false,
startOnBoot: true
})
.then(() => console.log("Background fetch registered"))
.catch(console.error)
try {
storage.set("setupDone", false)
storage.set("cameraUploadUploaded", 0)
storage.set("cameraUploadTotal", 0)
await new Promise(resolve => {
const interval = setInterval(() => {
if (storage.getBoolean("setupDone")) {
clearInterval(interval)
resolve()
}
}, 100)
})
const permissions = await hasNotificationPermissions(true)
if (!permissions) {
return
}
if (Platform.OS === "ios") {
Notifications.ios.registerRemoteNotifications({
carPlay: false,
alert: true,
badge: true,
sound: true,
criticalAlert: false,
provisional: false,
announcement: false
})
} else {
Notifications.registerRemoteNotifications()
}
Notifications.setNotificationChannel({
channelId: "notifications",
name: "Notifications",
importance: 5,
description: "Notifications",
enableVibration: false,
groupId: "notifications",
groupName: "Notifications",
showBadge: true,
soundFile: undefined,
vibrationPattern: undefined
})
normalNotificationsChannelId = "notifications"
} catch (e) {
throw e
}
}
init().catch(console.error)
AppRegistry.registerComponent(appName, () => App)