forked from PrivateSky/ios-edge-agent
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nativeBridge.js
479 lines (409 loc) · 14 KB
/
nativeBridge.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
/*
Allowed parameters: Strings, Numbers, Arrays of String|Number
*/
const isString = (str) => {
return typeof str === 'string' || str instanceof String
}
const isNumber = (num) => {
return typeof num === 'number' || num instanceof Number
}
const exists = (element) => {
return element !== null && element !== undefined;
}
class CallableObject extends Function {
constructor() {
super('...args', 'return this._bound._call(...args)');
// Or without the spread/rest operator:
// super('return this._bound._call.apply(this._bound, arguments)')
this._bound = this.bind(this);
return this._bound;
}
_call(args) {
console.log(this, args);
}
}
class StreamPacketCollector {
constructor(reader, size) {
this.size = size;
this.reader = reader;
this.buffer = new Uint8Array(size);
this.filledCount = 0;
}
collectStartingWith(startingArray) {
const self = this;
const safeStart = startingArray || [];
if(safeStart.length >= this.size) {
return new Promise((resolve, reject) => {
const filled = safeStart.slice(0, self.size);
const extra = safeStart.slice(self.size, safeStart.length - self.size);
resolve(filled, extra);
});
}
(startingArray || []).forEach((element, index) => {
self.buffer[self.filledCount] = element;
self.filledCount += 1;
})
return new Promise((resolve, reject) => {
function pump() {
self.reader.read().then(({value, done}) => {
self.handleNewChunk(value).then((done, extra) => {
if (done) {
resolve(self.buffer, extra);
} else {
pump();
}
});
});
}
pump();
});
}
handleNewChunk(chunk) {
const self = this;
const safeChunk = chunk || [];
if(safeChunk.length + self.filledCount >= self.size) {
const remainingCount = self.size - self.filledCount;
self.appendNewChunk(safeChunk.slice(0, remainingCount - 1));
return new Promise((resolve, reject) => {
const extra = safeChunk.slice(remainingCount);
resolve(true, extra);
});
}
self.appendNewChunk(safeChunk);
return new Promise((resolve, reject) => {
resolve(false);
});
}
appendNewChunk(chunk) {
(chunk || []).forEach((element, index) => {
this.buffer[this.filledCount] = element;
this.filledCount += 1;
})
}
}
class DataStreamApiCall {
constructor(response) {
this.response = response;
}
setChunkHandler(handler) {
this.chunkHandler = handler;
const self = this;
const reader = this.response.body.getReader();
self.reader = reader;
function beginCollectingNewPacket(startingBuffer) {
const size = new DataView(startingBuffer.buffer).getUint32(0, true);
const collector = new StreamPacketCollector(reader, size);
return collector.collectStartingWith(startingBuffer.slice(4));
}
function pump() {
reader.read().then(({value, done}) => {
if (done) {
return;
}
function goNext(finishedPacket, extra) {
handler(finishedPacket);
console.log("collected packet of length: " + finishedPacket.length);
if ((extra || []).length > 0) {
beginCollectingNewPacket(extra).then(goNext);
} else {
pump();
}
}
beginCollectingNewPacket(value).then(goNext);
});
}
pump();
}
closeStream() {
this.reader.cancel();
}
}
class NativeApiCall extends CallableObject {
constructor(url) {
super();
this.url = url;
}
_call(args) {
const self = this;
args = args || [];
return new Promise((resolve, reject) => {
const formData = new FormData();
args.forEach((element, index) => {
self.insert(element, index + '', formData);
});
self.makeApiCall(formData, resolve, reject);
});
}
makeApiCall(formData, resultCallback, errorCallback) {
const self = this;
const url = this.url;
const options = {
method: 'POST',
mode: 'cors',
body: formData,
credentials: 'include'
};
fetch(url, options)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status} for ${self.url} and ${formData}`);
}
const isStreamedResponse = response.headers.get("X-Stream-Header");
if (isStreamedResponse && isStreamedResponse.includes("*")) {
resultCallback(new DataStreamApiCall(response))
return;
}
return response.json().then((jsonResponse) => {
if(jsonResponse.error) {
errorCallback(jsonResponse.error);
} else if(jsonResponse.result) {
self.processApiResult(jsonResponse.result, resultCallback, errorCallback);
}
}, errorCallback);
}, (error) => {
console.log("Native API Error: " + error);
});
}
processApiResult(resultArray, resultCallback, errorCallback) {
const self = this;
const promises = resultArray.map(element => {
return self.promiseFor(element, resultArray)
});
Promise.all(promises).then((values) => {
resultCallback(values);
}, (errorReason) => {
errorCallback(errorReason);
});
}
promiseFor(valueItem, results) {
const self = this;
return new Promise((resolve, reject) => {
if(!exists(valueItem.type)) { reject(`Unknown result type for value ${valueItem}; ${results} in call ${self.url}`); return;}
if(valueItem.type == "number" || valueItem.type == "string") {
const value = valueItem.value;
if(!exists(value) || !(isNumber(value) || isString(value))) {
reject(`Value in ${valueItem} is neither string nor number; ${results}, ${self.url}`);
return;
}
resolve(value);
} else {
if(valueItem.type == "bytes") {
self.downloadBytes(valueItem, results, resolve, reject);
}
}
});
}
downloadBytes(bytesItem, results, resolve, reject) {
const self = this;
if(!bytesItem.path || !(isString(bytesItem.path))) {
reject(`Path field non-existend or wrong type: ${bytesItem}; ${results}, ${self.url}`);
return;
}
const url = bytesItem.path;
const options = {
method: 'GET',
mode: 'cors',
credentials: 'include'
};
fetch(url, options)
.then((response) => {
if (!response.ok) {
reject(`HTTP error! status: ${response.status} for ${self.url} retrieving ${bytesItem.path}`);
}
response.blob().then((theBlob) => {
resolve(theBlob);
});
});
}
insert(element, name, formData) {
const isBasicType =
(element instanceof Blob) ||
isString(element) ||
isNumber(element);
if(isBasicType) {
formData.set(name, element);
} else {
if(element instanceof Uint8Array) {
formData.set(name, new Blob(element, {type : 'application/octet-stream'}));
} else if(this.isArrayOfNumbersOrStrings(element)) {
formData.set(name, JSON.stringify(element));
} else {
const message = `The value ${element} is not an instance of an accepted type. Only Number, String, [String|Number], Uint8Array and Blob are acceptable types. Api call: ${this.url}`;
throw new Error(message);
}
}
}
isArrayOfNumbersOrStrings(element) {
if(element instanceof Array) {
return element.reduce((acc, value) => {
return acc && (isNumber(value) || isString(value));
}, true);
}
return false;
}
}
class NativePushStreamChannel {
constructor(websocketURL, identifier) {
this.websocketURL = websocketURL;
this.identifier = identifier;
}
connect() {
let socket = new WebSocket(this.websocketURL);
socket.binaryType = "arraybuffer";
let self = this;
self.socket = socket;
return new Promise((resolve, reject) => {
socket.onopen = (event) => {
socket.onmessage = (message) => {
if(message.data == "READY") {
socket.onmessage = (binaryMessageEvent) => {
self.handleIncomingData(binaryMessageEvent);
}
resolve(self);
} else {
reject(message.data);
}
};
socket.send(self.identifier);
};
socket.onerror = (error) => {
reject(error);
};
});
}
setNewEventHandler(handler) {
this.handler = handler;
}
send(data) {
this.socket.send(data);
}
handleIncomingData(event) {
if(this.handler) {
this.handler(event.data);
}
}
close() {
this.socket.close();
}
}
class NativePushStreamAPI {
constructor(origin, name) {
this.origin = origin;
this.apiName = name;
this.openedChannels = [];
const openURL = `${origin}/pushStream/open/${name}`;
const closeURL = `${origin}/pushStream/close/${name}`;
this.openCall = new NativeApiCall(openURL);
this.closeCall = new NativeApiCall(closeURL);
}
openStream(options) {
let self = this;
return new Promise((resolve, reject) => {
self.openCall(options).then((resultArray) => {
resolve();
}, (error) => {
reject(error);
});
});
}
openChannel(channelName,options) {
const openChannelURL = `${this.origin}/pushStream/connect/${this.apiName}/${channelName}`;
let openChannelCall = new NativeApiCall(openChannelURL);
const self = this;
return new Promise((resolve, reject) => {
openChannelCall(options).then((resultArray) => {
const wsURL = resultArray[0];
const wsID = resultArray[1];
const channel = new NativePushStreamChannel(wsURL, wsID);
channel.connect().then(resolve, reject);
self.openedChannels.push(channel);
}, (error) => {
reject(error);
});
});
}
closeStream() {
this.closeCall();
this.openedChannels.forEach((item) => {
item.close();
})
}
}
class NativeStreamAPI {
constructor(origin, name) {
const baseURL = `${origin}/${name}`;
const openURL = `${baseURL}/open`;
const nextValueURL = `${baseURL}/nextValue`;
const closeURL = `${baseURL}/close`;
this.openCall = new NativeApiCall(openURL);
this.nextValueCall = new NativeApiCall(nextValueURL);
this.closeCall = new NativeApiCall(closeURL);
}
openStream(args) {
return this.openCall(args);
}
retrieveNextValue(args) {
return this.nextValueCall(args);
}
close() {
return this.closeCall();
}
}
class PSSmartWalletNativeLayer {
constructor(origin) {
this.nativeAPIMap = {};
this.nativeStreamAPIMap = {};
this.nativePushStreamAPIMap = {};
this.origin = origin;
}
importNativeAPI(name) {
const url = `${this.origin}/${name}`
const nativeApiCall = this.nativeAPIMap[name] || new NativeApiCall(url);
this.nativeAPIMap[name] = nativeApiCall;
return nativeApiCall;
}
importNativeStreamAPI(name) {
const api = this.nativeStreamAPIMap[name] || new NativeStreamAPI(this.origin, name);
this.nativeStreamAPIMap[name] = api;
return api;
}
importNativePushStreamAPI(name) {
const api = this.nativePushStreamAPIMap[name] || new NativePushStreamAPI(this.origin, name);
this.nativePushStreamAPIMap[name] = api;
return api;
}
}
function detectNativeServerUrl(callback){
const {protocol, host} = window.location;
let url = `${protocol}//${host}`;
url +="/nsp";
let called = false;
function finish(err, result){
if(!called){
called = true;
return callback(err, result);
} else if(err){
console.log(err);
}
}
fetch(url).then((response)=>{
return response.text();
}, (reason)=>{
finish(reason);
}).then((nsp)=>{
finish(undefined, nsp);
}).catch((err)=>{
finish(err);
});
}
window.opendsu_native_apis = {
createNativeBridge : (callback)=>{
detectNativeServerUrl((err, nsp)=>{
if(err){
return callback(err);
}
const connector = new PSSmartWalletNativeLayer(`http://localhost:${nsp}/nativeApiCall`);
callback(undefined, connector);
});
}
};