-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathOneSignalPushAdapter.js
211 lines (178 loc) · 5.62 KB
/
OneSignalPushAdapter.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
"use strict";
// ParsePushAdapter is the default implementation of
// PushAdapter, it uses GCM for android push and APNS
// for ios push.
import { utils } from 'parse-server-push-adapter';
import ParsePushAdapter from 'parse-server-push-adapter';
const Parse = require('parse/node').Parse;
var deepcopy = require('deepcopy');
export class OneSignalPushAdapter {
constructor(pushConfig = {}) {
this.https = require('https');
this.validPushTypes = ['ios', 'android'];
this.senderMap = {};
this.OneSignalConfig = {};
const { oneSignalAppId, oneSignalApiKey } = pushConfig;
if (!oneSignalAppId || !oneSignalApiKey) {
throw "Trying to initialize OneSignalPushAdapter without oneSignalAppId or oneSignalApiKey";
}
this.OneSignalConfig['appId'] = pushConfig['oneSignalAppId'];
this.OneSignalConfig['apiKey'] = pushConfig['oneSignalApiKey'];
this.senderMap['ios'] = this.sendToAPNS.bind(this);
this.senderMap['android'] = this.sendToGCM.bind(this);
}
send(data, installations) {
let deviceMap = utils.classifyInstallations(installations, this.validPushTypes);
let sendPromises = [];
for (let pushType in deviceMap) {
let sender = this.senderMap[pushType];
if (!sender) {
console.log('Can not find sender for push type %s, %j', pushType, data);
continue;
}
let devices = deviceMap[pushType];
if(devices.length > 0) {
sendPromises.push(sender(data, devices));
}
}
return Parse.Promise.when(sendPromises);
}
static classifyInstallations(installations, validTypes) {
return utils.classifyInstallations(installations, validTypes)
}
getValidPushTypes() {
return this.validPushTypes;
}
sendToAPNS(data,tokens) {
data= deepcopy(data['data']);
var post = {};
if(data['badge']) {
if(data['badge'] == "Increment") {
post['ios_badgeType'] = 'Increase';
post['ios_badgeCount'] = 1;
} else {
post['ios_badgeType'] = 'SetTo';
post['ios_badgeCount'] = data['badge'];
}
delete data['badge'];
}
if(data['alert']) {
post['contents'] = {en: data['alert']};
delete data['alert'];
}
if(data['sound']) {
post['ios_sound'] = data['sound'];
delete data['sound'];
}
if(data['background_data'] == true || data['content-available'] == 1) {
post['content_available'] = true;
delete data['background_data'];
delete data['content-available'];
}
post['data'] = data;
let promise = new Parse.Promise();
var chunk = 2000 // OneSignal can process 2000 devices at a time
var tokenlength=tokens.length;
var offset = 0
// handle onesignal response. Start next batch if there's not an error.
let handleResponse = function(wasSuccessful) {
if (!wasSuccessful) {
return promise.reject("OneSignal Error");
}
if(offset >= tokenlength) {
promise.resolve()
} else {
this.sendNext();
}
}.bind(this)
this.sendNext = function() {
post['include_ios_tokens'] = [];
tokens.slice(offset,offset+chunk).forEach(function(i) {
post['include_ios_tokens'].push(i['deviceToken'])
})
offset+=chunk;
this.sendToOneSignal(post, handleResponse);
}.bind(this)
this.sendNext()
return promise;
}
sendToGCM(data,tokens) {
data= deepcopy(data['data']);
var post = {};
if(data['alert']) {
post['contents'] = {en: data['alert']};
delete data['alert'];
}
if(data['title']) {
post['title'] = {en: data['title']};
delete data['title'];
}
if(data['uri']) {
post['url'] = data['uri'];
}
if(data['background_data'] == true || data['android_background_data'] == true) {
post['android_background_data'] = true;
delete data['background_data'];
delete data['android_background_data'];
}
post['data'] = data;
let promise = new Parse.Promise();
var chunk = 2000 // OneSignal can process 2000 devices at a time
var tokenlength=tokens.length;
var offset = 0
// handle onesignal response. Start next batch if there's not an error.
let handleResponse = function(wasSuccessful) {
if (!wasSuccessful) {
return promise.reject("OneSIgnal Error");
}
if(offset >= tokenlength) {
promise.resolve()
} else {
this.sendNext();
}
}.bind(this);
this.sendNext = function() {
post['include_android_reg_ids'] = [];
tokens.slice(offset,offset+chunk).forEach(function(i) {
post['include_android_reg_ids'].push(i['deviceToken'].replace(/[^0-9a-z]/gi, ''))
})
offset+=chunk;
this.sendToOneSignal(post, handleResponse);
}.bind(this)
this.sendNext();
return promise;
}
sendToOneSignal(data, cb) {
let headers = {
"Content-Type": "application/json",
"Authorization": "Basic "+this.OneSignalConfig['apiKey']
};
let options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
data['app_id'] = this.OneSignalConfig['appId'];
let request = this.https.request(options, function(res) {
if(res.statusCode < 299) {
cb(true);
} else {
console.log('OneSignal Error');
res.on('data', function(chunk) {
console.log(chunk.toString())
});
cb(false)
}
});
request.on('error', function(e) {
console.log("Error connecting to OneSignal")
console.log(e);
cb(false);
});
request.write(JSON.stringify(data))
request.end();
}
}
export default OneSignalPushAdapter;