-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectivity.js
More file actions
665 lines (660 loc) · 23 KB
/
Connectivity.js
File metadata and controls
665 lines (660 loc) · 23 KB
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
/*
Copyright 2020-2022 Nernar (github.com/nernar)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
LIBRARY({
name: "Connectivity",
version: 1,
api: "AdaptedScript",
shared: true
});
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* Connects and perform basic stream manipulation.
*/
var Connectivity = /** @class */ (function () {
/**
* Creates a connection to specific remote address.
* @param address of remote
*/
function Connectivity(address) {
this.callback = {};
address && this.setAddress(address);
}
/**
* Returns url was set by connection.
*/
Connectivity.prototype.getUrl = function () {
return this.url || null;
};
/**
* Sets current url as an java object.
* If you need set address, use appropriate method.
*/
Connectivity.prototype.setUrl = function (url) {
if (typeof url == "string") {
Logger.Log("Connectivity: You should use Connectivity.setAddress instead of Connectivity.setUrl for string values", "WARNING");
return this.setAddress(url);
}
if (this.callback.hasOwnProperty("onUrlChanged")) {
this.callback.onUrlChanged.call(this, url);
}
this.url = url;
};
/**
* Use to specify remote address as a string.
*/
Connectivity.prototype.setAddress = function (address) {
this.setUrl(new java.net.URL(address));
};
/**
* Event receiver, use to track actions.
*/
Connectivity.prototype.setCallback = function (callback) {
if (callback && callback instanceof Object) {
this.callback = callback;
return;
}
this.callback = {};
};
/**
* Opens and returns a data stream.
* If url isn't specified, `null` is returned.
*/
Connectivity.prototype.getStream = function () {
var connection = this.getConnection();
if (connection instanceof java.net.URLConnection) {
return connection ? connection.getInputStream() : null;
}
return this.url ? this.url.openStream() : null;
};
/**
* If connection doesn't exist, creates a new one.
* Method will be used automatically when it needed
* by corresponding {@link Connectivity.getConnection}.
*/
Connectivity.prototype.validateConnection = function () {
if (!(this.connection instanceof java.io.InputStream || this.connection instanceof java.net.URLConnection)) {
this.connection = this.url ? this.url.openConnection() : null;
if (this.callback.hasOwnProperty("onCreateConnection")) {
this.callback.onCreateConnection.call(this, this.connection);
}
}
};
/**
* Opens or returns an existing connection.
* @param force `true` means just return currently connection
*/
Connectivity.prototype.getConnection = function (force) {
if (!force)
this.validateConnection();
return this.connection || null;
};
/**
* Returns `true` if connection currently exists.
*/
Connectivity.prototype.hasConnection = function () {
return this.connection != null;
};
/**
* Connects to created url if it's created.
* @throws if connection not actually found
*/
Connectivity.prototype.connect = function () {
var connection = this.getConnection();
if (!this.hasConnection()) {
// @ts-ignore
MCSystem.throwException("Connectivity: Could not find any opened connection to connect!");
}
if (connection instanceof java.net.URLConnection) {
connection.connect();
}
if (this.callback.hasOwnProperty("onConnect")) {
this.callback.onConnect.call(this, connection);
}
};
/**
* Disconnects from existing connection.
* If connection doesn't exist, nothing happens.
*/
Connectivity.prototype.disconnect = function () {
if (!this.hasConnection()) {
return false;
}
var connection = this.getConnection();
if (connection instanceof java.net.HttpURLConnection) {
connection.disconnect();
}
delete this.connection;
if (this.callback.hasOwnProperty("onDisconnect")) {
this.callback.onDisconnect.call(this, connection);
}
return true;
};
/**
* Gets length of output connection.
* If connection failed, returns `-1`.
*/
Connectivity.prototype.getLength = function () {
var justConnected = this.hasConnection();
if (!justConnected)
this.connect();
var connection = this.getConnection();
if (!(connection instanceof java.net.URLConnection)) {
return -1;
}
var length = connection.getContentLength();
if (this.callback.hasOwnProperty("getLength")) {
this.callback.getLength.call(this, length);
}
if (!justConnected)
this.disconnect();
return length;
};
/**
* Checks if there's has network connection, it is not
* know internet actually availabled or not.
*/
Connectivity.isOnline = function () {
var service = UI.getContext().getSystemService("connectivity");
if (service == null) {
return false;
}
var network = service.getActiveNetworkInfo();
return network != null && network.isConnectedOrConnecting();
};
return Connectivity;
}());
(function (Connectivity) {
/**
* Directly reads stream as multiline string.
*/
var Reader = /** @class */ (function (_super) {
__extends(Reader, _super);
/**
* Creates a connection to read text data.
* @param address of remote
*/
function Reader(address) {
var _this = _super.call(this, address) || this;
_this.callback = {};
/**
* @internal
*/
_this.charset = "UTF-8";
/**
* @internal
*/
_this.processing = false;
return _this;
}
/**
* Returns current charset of being read data.
*/
Reader.prototype.getCharset = function () {
return this.charset || null;
};
/**
* Sets charset for new connections.
* If charset is `null`, system encoding will be used.
* @see {@link https://wikipedia.org/wiki/Character_encoding character encoding} for more details
*/
Reader.prototype.setCharset = function (charset) {
this.charset = charset;
if (typeof charset != "string") {
delete this.charset;
}
if (this.callback.hasOwnProperty("onCharsetChanged")) {
this.callback.onCharsetChanged.call(this, this.charset);
}
};
/**
* Returns stream reader, or `null` if create failed.
*/
Reader.prototype.getStreamReader = function () {
var stream = this.getStream();
if (stream == null) {
return null;
}
var charset = this.getCharset();
if (charset == null) {
return new java.io.InputStreamReader(stream);
}
return new java.io.InputStreamReader(stream, charset);
};
/**
* Returns `true` if read process is running.
*/
Reader.prototype.inProcess = function () {
return this.processing;
};
/**
* Returns currently read data as an array.
* Returns `null` if read process hasn't been started.
*/
Reader.prototype.getCurrentlyReaded = function () {
return this.result || null;
};
/**
* Returns number of readed lines.
* Returns `-1` if there is no connection.
*/
Reader.prototype.getReadedCount = function () {
var readed = this.getCurrentlyReaded();
return readed == null ? -1 : readed.length;
};
/**
* Returns readed result, or `null` if none.
*/
Reader.prototype.toResult = function () {
var _a;
return (_a = this.getCurrentlyReaded()) === null || _a === void 0 ? void 0 : _a.join("\n");
};
/**
* Reading process, isn't recommended run on main thread.
* Wait until work is ended, and method will be return result.
* @throws error will occur if there's no connection
*/
Reader.prototype.read = function () {
var stream = this.getStreamReader();
if (stream == null) {
// @ts-ignore
MCSystem.throwException("Connectivity: Connectivity.Reader: Stream is not specified!");
}
this.result = [];
var reader = new java.io.BufferedReader(stream);
this.processing = true;
if (this.callback.hasOwnProperty("onPrepare")) {
this.callback.onPrepare.call(this);
}
while (this.inProcess()) {
var line = reader.readLine();
if (line == null) {
break;
}
else {
this.result.push(line);
}
if (this.callback.hasOwnProperty("onReadLine")) {
this.callback.onReadLine.call(this, this.result, line);
}
}
if (this.callback.hasOwnProperty("onComplete")) {
this.callback.onComplete.call(this, this.result);
}
this.processing = false;
reader.close();
return this.toResult();
};
return Reader;
}(Connectivity));
Connectivity.Reader = Reader;
/**
* Connects to perform data transfering to output.
* @abstract must be overwritten with any prototype
*/
var Writer = /** @class */ (function (_super) {
__extends(Writer, _super);
/**
* Loads a data stream into specified stream.
* @abstract must be overwritten with any prototype
* @see {@link getOutputStream} method for details
* @param address of remote
*/
function Writer(address) {
var _this = _super.call(this, address) || this;
_this.callback = {};
/**
* @internal
*/
_this.size = 8192;
/**
* @internal
*/
_this.processing = false;
return _this;
}
/**
* Returns buffer size for reading data.
* Returns `-1` if value resetted.
*/
Writer.prototype.getBufferSize = function () {
return this.size <= 0 ? -1 : this.size;
};
/**
* Sets read buffer size.
*/
Writer.prototype.setBufferSize = function (size) {
if (typeof size == "undefined") {
this.size = 8192;
return;
}
this.size = size;
};
/**
* Returns length of readed data.
* Returns `-1` if there is no connection.
*/
Writer.prototype.getReadedCount = function () {
if (typeof this.count == "undefined") {
return -1;
}
return this.count;
};
/**
* Returns a buffered stream reader, can be overwritten in prototypes.
*/
Writer.prototype.getStreamReader = function () {
var stream = this.getStream();
if (stream == null) {
return null;
}
var size = this.getBufferSize();
if (size == -1) {
return new java.io.BufferedInputStream(stream);
}
return new java.io.BufferedInputStream(stream, size);
};
/**
* Returns `true` if download process is running.
*/
Writer.prototype.inProcess = function () {
return this.processing;
};
/**
* Loads a stream into given output data stream.
* @throws error will occur if there's no connection
* @throws error if output stream is invalid
*/
Writer.prototype.download = function () {
var stream = this.getStreamReader();
if (stream == null) {
// @ts-ignore
MCSystem.throwException("Connectivity: Could not download(), input stream is missing!");
}
var output = this.getOutputStream();
if (output == null) {
// @ts-ignore
MCSystem.throwException("Connectivity: Could not download(), output stream is missing!");
}
this.connect();
this.count = 0;
this.processing = true;
var size = this.getLength();
if (this.callback.hasOwnProperty("onPrepare")) {
this.callback.onPrepare.call(this, size);
}
var data = java.lang.reflect.Array.newInstance(java.lang.Byte.TYPE, 1024);
while (this.inProcess()) {
var count = stream.read(data);
if (count == -1) {
break;
}
else {
output.write(data, 0, count);
if (this.callback.hasOwnProperty("onProgress")) {
this.callback.onProgress.call(this, count, size);
}
this.count += count;
}
}
if (this.callback.hasOwnProperty("onComplete")) {
this.callback.onComplete.call(this, size);
}
this.processing = false;
this.disconnect();
output.flush();
output.close();
stream.close();
};
return Writer;
}(Connectivity));
Connectivity.Writer = Writer;
/**
* Perform transfering stream to filesystem.
*/
var Downloader = /** @class */ (function (_super) {
__extends(Downloader, _super);
/**
* Loads a stream to specified file path.
* @param address of remote
* @param path file path
*/
function Downloader(address, path) {
var _this = _super.call(this, address) || this;
_this.callback = {};
path && _this.setPath(path);
return _this;
}
/**
* Returns currently specified file.
*/
Downloader.prototype.getFile = function () {
return this.file || null;
};
/**
* Sets java file to write stream.
* If argument isn't given, resets it.
*/
Downloader.prototype.setFile = function (file) {
this.file = file;
if (!(file instanceof java.io.File)) {
delete this.file;
}
if (this.callback.hasOwnProperty("onFileChanged")) {
this.callback.onFileChanged.call(this, file);
}
};
/**
* Returns currently file path.
* Returns `null` if file isn't specified.
*/
Downloader.prototype.getPath = function () {
var file = this.getFile();
return file == null ? null : file.getPath();
};
/**
* Sets path to file, replaces current output file.
*/
Downloader.prototype.setPath = function (path) {
this.setFile(new java.io.File(path));
};
/**
* Returns output stream from file.
* @throws error when input file is not specified
*/
Downloader.prototype.getOutputStream = function () {
var file = this.getFile();
if (file == null) {
// @ts-ignore
MCSystem.throwException("Connectivity: Connectivity.Downloader: Input file is not specified!");
}
if (!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
var stream = new java.io.FileOutputStream(file);
return new java.io.BufferedOutputStream(stream);
};
return Downloader;
}(Writer));
Connectivity.Downloader = Downloader;
/**
* A quick way to create thread, errors are handled.
* @param action action to handle
* @param callback fail callback
* @param connect will be passed into callback scope
* @throws error if action isn't specified
*/
function handle(action, callback, connect) {
new java.lang.Thread(new java.lang.Runnable({
run: function () {
try {
action();
}
catch (e) {
try {
if (callback && typeof callback == "object") {
// @ts-expect-error
if (callback.hasOwnProperty("onFail")) {
if (connect) {
// @ts-expect-error
return callback.onFail.call(connect);
}
else {
// @ts-expect-error
return callback.onFail();
}
}
}
else if (typeof callback == "function") {
if (connect) {
callback.call(connect);
}
else {
callback();
}
}
Logger.Log("Connectivity: Failed to read network data from a server", "WARNING");
}
catch (t) {
Logger.Log("Connectivity: A fatal error occurred while trying to network connect", "ERROR");
}
}
}
})).start();
}
Connectivity.handle = handle;
/**
* A quick way to get content length from connection.
* @param address url address
* @param callback action or callback
* @see {@link Connectivity.getLength} for details
*/
function lengthUrl(address, callback) {
if (!Connectivity.isOnline()) {
if (callback && typeof callback == "object") {
// @ts-expect-error
if (callback.hasOwnProperty("isNotConnected")) {
// @ts-expect-error
callback.isNotConnected();
}
}
return false;
}
var connect = new Connectivity(address);
if (callback && typeof callback == "object") {
connect.setCallback(callback);
}
handle(function () {
if (callback) {
if (typeof callback == "object") {
connect.getLength();
}
else {
callback(connect.getLength());
}
}
else {
Logger.Log("Connectivity: Network action after doing stream length is missed", "WARNING");
connect.getLength();
}
// @ts-expect-error
}, callback, connect);
return true;
}
Connectivity.lengthUrl = lengthUrl;
/**
* A quick way to read data from connection.
* @param address url address
* @param callback action or callback
* @see {@link Reader.read} for details
*/
function readUrl(address, callback) {
if (!Connectivity.isOnline()) {
if (callback && typeof callback == "object") {
// @ts-expect-error
if (callback.hasOwnProperty("isNotConnected")) {
// @ts-expect-error
callback.isNotConnected();
}
}
return false;
}
var reader = new Connectivity.Reader(address);
if (callback && typeof callback == "object") {
reader.setCallback(callback);
}
handle(function () {
if (callback) {
if (typeof callback == "object") {
reader.read();
}
else {
callback(reader.read());
}
}
else {
Logger.Log("Connectivity: Network action after doing stream reading is missed", "WARNING");
reader.read();
}
// @ts-expect-error
}, callback, reader);
return true;
}
Connectivity.readUrl = readUrl;
/**
* A quick way to download file from connection.
* @param address url address
* @param path file path
* @param callback action or callback
* @see {@link Downloader.download} for details
*/
function downloadUrl(address, path, callback) {
if (!Connectivity.isOnline()) {
if (callback && typeof callback == "object") {
// @ts-expect-error
if (callback.hasOwnProperty("isNotConnected")) {
// @ts-expect-error
callback.isNotConnected();
}
}
return false;
}
var writer = new Connectivity.Downloader(address, path);
if (callback && typeof callback == "object") {
callback && writer.setCallback(callback);
}
handle(function () {
writer.download();
if (typeof callback == "function") {
return callback();
}
}, callback, writer);
return true;
}
Connectivity.downloadUrl = downloadUrl;
})(Connectivity || (Connectivity = {}));
EXPORT("Connectivity", Connectivity);