-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathindex.js
76 lines (71 loc) · 2.67 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
const { register, listen } = require('push-receiver');
const { ipcMain } = require('electron');
const Config = require('electron-config');
const {
START_NOTIFICATION_SERVICE,
NOTIFICATION_SERVICE_STARTED,
NOTIFICATION_SERVICE_ERROR,
NOTIFICATION_RECEIVED,
TOKEN_UPDATED,
} = require('./constants');
const config = new Config();
module.exports = {
START_NOTIFICATION_SERVICE,
NOTIFICATION_SERVICE_STARTED,
NOTIFICATION_SERVICE_ERROR,
NOTIFICATION_RECEIVED,
TOKEN_UPDATED,
setup,
};
// To be sure that start is called only once
let started = false;
// To be call from the main process
function setup(webContents) {
// Will be called by the renderer process
ipcMain.on(START_NOTIFICATION_SERVICE, async (_, senderId) => {
// Retrieve saved credentials
let credentials = config.get('credentials');
// Retrieve saved senderId
const savedSenderId = config.get('senderId');
if (started) {
webContents.send(NOTIFICATION_SERVICE_STARTED, (credentials.fcm || {}).token);
return;
}
started = true;
try {
// Retrieve saved persistentId : avoid receiving all already received notifications on start
const persistentIds = config.get('persistentIds') || [];
// Register if no credentials or if senderId has changed
if (!credentials || savedSenderId !== senderId) {
credentials = await register(senderId);
// Save credentials for later use
config.set('credentials', credentials);
// Save senderId
config.set('senderId', senderId);
// Notify the renderer process that the FCM token has changed
webContents.send(TOKEN_UPDATED, credentials.fcm.token);
}
// Listen for GCM/FCM notifications
await listen(Object.assign({}, credentials, { persistentIds }), onNotification(webContents));
// Notify the renderer process that we are listening for notifications
webContents.send(NOTIFICATION_SERVICE_STARTED, credentials.fcm.token);
} catch (e) {
console.error('PUSH_RECEIVER:::Error while starting the service', e);
// Forward error to the renderer process
webContents.send(NOTIFICATION_SERVICE_ERROR, e.message);
}
});
}
// Will be called on new notification
function onNotification(webContents) {
return ({ notification, persistentId }) => {
const persistentIds = config.get('persistentIds') || [];
// Update persistentId
config.set('persistentIds', [...persistentIds, persistentId]);
// Notify the renderer process that a new notification has been received
// And check if window is not destroyed for darwin Apps
if(!webContents.isDestroyed()){
webContents.send(NOTIFICATION_RECEIVED, notification);
}
};
}