-
Notifications
You must be signed in to change notification settings - Fork 2
/
pushhelper.js
185 lines (162 loc) · 5.69 KB
/
pushhelper.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
import Rx from 'rxjs/Rx';
const storage = require('node-persist');
const config = require('./config.json');
const request = require('request');
export class PushHelper {
constructor() {
storage.initSync();
}
getNotificationFromUserObject(user) {
const rooms = user.rooms.map(room => {
room.messages
.filter(message => message.id > this.getLastPushedMessage(user.id, room.id))
.map(() => room);
return room;
});
const unreadMessagesCount = rooms.reduce((unreadMessagesCarry, room) => {
return unreadMessagesCarry + room.messages.length;
}, 0);
let text = null;
let title = null;
let roomIds = rooms.map(room => room.id);
if (unreadMessagesCount === 1) {
title = 'New message';
text = rooms[0].name + ': ' + rooms[0].messages[0].text;
} else if (rooms.length === 1) {
title = 'Unread messages';
text = rooms[0].name + ': ' + "You have " + unreadMessagesCount + " unread messages";
} else {
title = 'Unread messages';
text = "You have " + unreadMessagesCount + " unread messages";
}
rooms.forEach((room) => {
storage.setItemSync(user.id + ':' + room.id, room.messages[0].id);
});
text = text.replace(/[\s|\n|\r]{1,}/g, " ");
return {
title: title,
message: text,
user_id: parseInt(user.id, 10),
rooms: roomIds
}
}
sendPushToUsers(users) {
storage.initSync();
let notifications = users.map(user => this.getNotificationFromUserObject(user));
notifications.forEach(notification => console.log(notification));
return this.getAccessToken()
.flatMap(token => Rx.Observable.fromPromise(new Promise((resolve, reject) => {
request(config.push.endpoint, {
json: true,
strictSSL: config.push.strictSSL,
body: {
notifications: notifications
},
headers: {
'Authorization': 'Bearer ' + token.accessToken
},
method: 'POST'
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
resolve();
} else {
reject([response, body]);
}
})
})));
}
/**
* @returns {Observable<Token>}
*/
getAccessToken() {
if (this.token) {
// If the access token expires within five seconds, we want to refresh it
const futureDate = (Date.now() + 5000);
if (this.token.expiresAt < futureDate) {
console.log("access token expired, refresh it");
return this.refreshToken(this.token);
} else {
console.log("already have a valid access token, using it");
return Rx.Observable.of(this.token);
}
} else {
console.log("issuing a new access token");
return this.issueNewToken();
}
}
/**
* @param {Token} token
* @returns {Observable<Token>}
*/
refreshToken(token) {
return Rx.Observable.fromPromise(new Promise((resolve, reject) => {
request(config.push.auth.endpoint, {
json: true,
strictSSL: config.push.strictSSL,
body: {
client_id: config.push.auth.clientId,
client_secret: config.push.auth.clientSecret,
grant_type: config.push.auth.refreshGrantType,
refresh_token: token.refreshToken
},
method: 'POST'
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
resolve(new Token(body))
} else {
console.log(error, response, body);
reject(error);
}
})
})).catch(() => {
console.log("refresh token failed!");
return this.issueNewToken();
}).do(token => this.token = token);
}
/**
* @returns {Observable<Token>}
*/
issueNewToken() {
console.log("issueNewToken called");
return Rx.Observable.fromPromise(new Promise((resolve, reject) => {
request(config.push.auth.endpoint, {
json: true,
strictSSL: config.push.strictSSL,
body: {
client_id: config.push.auth.clientId,
client_secret: config.push.auth.clientSecret,
grant_type: config.push.auth.grantType
},
method: 'POST'
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
resolve(new Token(body))
} else {
reject(error);
}
})
})).do(token => this.token = token);
}
getLastPushedMessage(userId, roomId) {
return storage.getItemSync(userId + ':' + roomId) || 0;
}
}
class Token {
/**
* @param data
*/
constructor(data) {
/**
* @type {Date}
*/
this.expiresAt = new Date(Date.now() + data.expires_in * 1000);
/**
* @type {string}
*/
this.accessToken = data.access_token;
/**
* @type {string}
*/
this.refreshToken = data.refresh_token;
}
}