-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathpush-notifications.js
304 lines (277 loc) · 9.61 KB
/
push-notifications.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
const jwt = require('jsonwebtoken');
const http = require('http');
const https = require('https');
const SDK_VERSION = '1.2.7';
const INTERESTS_REGEX = new RegExp('^(_|\\-|=|@|,|\\.|;|[A-Z]|[a-z]|[0-9])*$');
const {
INTEREST_STRING_MAX_LENGTH,
INTEREST_ARRAY_MAX_LENGTH,
USERS_ARRAY_MAX_LENGTH,
USERS_STRING_MAX_LENGTH,
} = require('./utils');
function PushNotifications(options) {
if (options === null || typeof options !== 'object') {
throw new Error('PushNotifications options object is required');
}
if (!options.hasOwnProperty('instanceId')) {
throw new Error(
'"instanceId" is required in PushNotifications options',
);
}
if (typeof options.instanceId !== 'string') {
throw new Error('"instanceId" must be a string');
}
if (!options.hasOwnProperty('secretKey')) {
throw new Error('"secretKey" is required in PushNotifications options');
}
if (typeof options.secretKey !== 'string') {
throw new Error('"secretKey" must be a string');
}
this.instanceId = options.instanceId;
this.secretKey = options.secretKey;
this.port = options.port || null;
if (!options.hasOwnProperty('endpoint')) {
this.protocol = 'https';
this.endpoint = `${this.instanceId}.pushnotifications.pusher.com`;
} else if (typeof options.endpoint !== 'string') {
throw new Error('endpoint must be a string');
} else {
this.protocol = 'http';
this.endpoint = options.endpoint;
}
}
/**
* Alias of publishToInterests
* @deprecated Use publishToInterests instead
*/
PushNotifications.prototype.publish = function (interests, publishRequest) {
console.warn('`publish` is deprecated. Use `publishToInterests` instead.');
return this.publishToInterests(interests, publishRequest);
};
PushNotifications.prototype.generateToken = function (userId) {
if (userId === undefined || userId === null) {
throw new Error('userId argument is required');
}
if (userId === '') {
throw new Error('userId cannot be the empty string');
}
if (typeof userId !== 'string') {
throw new Error('userId must be a string');
}
if (userId.length > USERS_STRING_MAX_LENGTH) {
throw new Error(
`userId is longer than the maximum length of ${USERS_STRING_MAX_LENGTH}`,
);
}
const options = {
expiresIn: '24h',
issuer: `https://${this.instanceId}.pushnotifications.pusher.com`,
subject: userId,
allowInsecureKeySizes: true,
};
const token = jwt.sign({}, this.secretKey, options);
return {
token: token,
};
};
PushNotifications.prototype.publishToInterests = function (
interests,
publishRequest,
) {
if (interests === undefined || interests === null) {
return Promise.reject(new Error('interests argument is required'));
}
if (!(interests instanceof Array)) {
return Promise.reject(
new Error('interests argument is must be an array'),
);
}
if (interests.length < 1) {
return Promise.reject(
new Error(
'Publish requests must target at least one interest to be delivered',
),
);
}
if (interests.length > INTEREST_ARRAY_MAX_LENGTH) {
return Promise.reject(
new Error(
`Number of interests (${
interests.length
}) exceeds maximum of ${INTEREST_ARRAY_MAX_LENGTH}.`,
),
);
}
if (publishRequest === undefined || publishRequest === null) {
return Promise.reject(new Error('publishRequest argument is required'));
}
for (const interest of interests) {
if (typeof interest !== 'string') {
return Promise.reject(
new Error(`interest ${interest} is not a string`),
);
}
if (interest.length > INTEREST_STRING_MAX_LENGTH) {
return Promise.reject(
new Error(
`interest ${interest} is longer than the maximum of ` +
`${INTEREST_STRING_MAX_LENGTH} characters`,
),
);
}
if (!INTERESTS_REGEX.test(interest)) {
return Promise.reject(
new Error(
`interest "${interest}" contains a forbidden character. ` +
'Allowed characters are: ASCII upper/lower-case letters, ' +
'numbers or one of _-=@,.;',
),
);
}
}
const body = Object.assign({}, publishRequest, { interests });
const options = {
path: `/publish_api/v1/instances/${
this.instanceId
}/publishes/interests`,
method: 'POST',
body,
};
return this._doRequest(options);
};
PushNotifications.prototype.publishToUsers = function (users, publishRequest) {
if (users === undefined || users === null) {
return Promise.reject(new Error('users argument is required'));
}
if (!(users instanceof Array)) {
return Promise.reject(new Error('users argument is must be an array'));
}
if (users.length < 1) {
return Promise.reject(
new Error(
'Publish requests must target at least one interest to be delivered',
),
);
}
if (users.length > USERS_ARRAY_MAX_LENGTH) {
return Promise.reject(
new Error(
`Number of users (${
users.length
}) exceeds maximum of ${USERS_ARRAY_MAX_LENGTH}.`,
),
);
}
if (publishRequest === undefined || publishRequest === null) {
return Promise.reject(new Error('publishRequest argument is required'));
}
for (const user of users) {
if (typeof user !== 'string') {
return Promise.reject(new Error(`user ${user} is not a string`));
}
if (user.length > INTEREST_STRING_MAX_LENGTH) {
return Promise.reject(
new Error(
`user ${user} is longer than the maximum of ` +
`${INTEREST_STRING_MAX_LENGTH} characters`,
),
);
}
}
const body = Object.assign({}, publishRequest, { users });
const options = {
path: `/publish_api/v1/instances/${this.instanceId}/publishes/users`,
method: 'POST',
body,
};
return this._doRequest(options);
};
PushNotifications.prototype.deleteUser = function (userId) {
if (userId === undefined || userId === null) {
return Promise.reject(new Error('User ID argument is required'));
}
if (typeof userId !== 'string') {
return Promise.reject(new Error('User ID argument must be a string'));
}
if (userId.length > USERS_STRING_MAX_LENGTH) {
return Promise.reject(new Error('User ID argument is too long'));
}
const options = {
path: `/user_api/v1/instances/${
this.instanceId
}/users/${encodeURIComponent(userId)}`,
method: 'DELETE',
};
return this._doRequest(options);
};
PushNotifications.prototype._doRequest = function (options) {
const httpLib = this.protocol === 'http' ? http : https;
const reqOptions = {
method: options.method,
path: options.path,
host: this.endpoint,
headers: {
Accept: 'application/json',
Authorization: `Bearer ${this.secretKey}`,
'X-Pusher-Library': `pusher-push-notifications-node ${SDK_VERSION}`,
},
};
if (this.port) {
reqOptions.port = this.port;
}
let reqBodyStr;
if (options.body) {
reqBodyStr = JSON.stringify(options.body);
reqOptions.headers['Content-Type'] = 'application/json';
reqOptions.headers['Content-Length'] = Buffer.byteLength(reqBodyStr);
}
return new Promise(function (resolve, reject) {
try {
const req = httpLib.request(reqOptions, function (response) {
let resBodyStr = '';
response.on('data', function (chunk) {
resBodyStr += chunk;
});
response.on('end', function () {
let resBody;
if (resBodyStr) {
try {
resBody = JSON.parse(resBodyStr);
} catch (_) {
reject(new Error('Could not parse response body'));
return;
}
}
if (
response.statusCode >= 200 &&
response.statusCode < 300
) {
resolve(resBody);
} else {
if (!resBody.error || !resBody.description) {
reject(new Error('Could not parse response body'));
} else {
reject(
new Error(
`${response.statusCode} ${
resBody.error
} - ${resBody.description}`,
),
);
}
}
});
});
req.on('error', function (error) {
reject(error);
});
if (reqBodyStr) {
req.write(reqBodyStr);
}
req.end();
} catch (e) {
reject(e);
}
});
};
module.exports = PushNotifications;