-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.js
3573 lines (3331 loc) · 126 KB
/
main.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
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
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is a part of Telegram X Publisher
* Copyright © Vyacheslav Krylov (tgx-android@pm.me) 2022-2023
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
'use strict';
process.env.NTBA_FIX_319 = 1;
process.env.NTBA_FIX_350 = 1;
const fs = require('fs'),
os = require('os'),
crypto = require('crypto'),
TelegramBot = require('node-telegram-bot-api'),
path = require('path'),
https = require('https'),
http = require('http'),
iconv = require('iconv-lite'),
AdmZip = require('adm-zip'),
FormData = require('form-data'),
UriTemplate = require('uri-template');
const { spawn, exec, execSync } = require('child_process');
const { google } = require('googleapis');
const { Level } = require('level');
// ERROR
function globalErrorHandler () {
const stack = new Error('Global error happened here:').stack;
return (error) => {
console.log(error.code, stack, error);
};
}
// ARGV CONSTANTS
function checkPath (path) {
return path && fs.existsSync(path);
}
const LOCAL = process.env.TGX_PRODUCTION !== '1';
const settings = JSON.parse(fs.readFileSync(path.join(__dirname, 'settings.json'), 'UTF-8'));
if (!settings.app.id || !settings.app.id.match(/^(?!\.)[a-z0-9._]+(?!\.)$/))
throw Error('app.id is not specified in settings.json or not valid: ' + settings.app.id);
const TESTING_URL = settings.url.testing;
const MARKET_URL = settings.url.market;
const ADMIN_USER_ID = settings.telegram.admin_user_id;
const BETA_CHAT_ID = settings.telegram.target_chat_id.public_builds;
const PR_CHAT_ID = settings.telegram.target_chat_id.pr_builds;
const ALPHA_CHAT_ID = LOCAL ? ADMIN_USER_ID : settings.telegram.target_chat_id.private_builds;
const INTERNAL_CHAT_ID = settings.telegram.target_chat_id.internal_builds;
const TELEGRAM_API_TOKEN_2 = settings.tokens.verifier.production;
const TELEGRAM_APP_ID = process.env.TELEGRAM_APP_ID || settings.telegram.server.api_id;
const TELEGRAM_APP_HASH = process.env.TELEGRAM_APP_HASH || settings.telegram.server.api_hash;
const PACKAGE_NAME = settings.app.id;
['TGX_SOURCE_PATH', 'TGX_KEYSTORE_PATH', 'ANDROID_SDK_ROOT', 'GOOGLE_TOKEN_PATH', 'TDLIB_SYMBOLS_PATH'].forEach((path) => {
if (!checkPath(process.env[path]) && !(LOCAL && path === 'GOOGLE_TOKEN_PATH')) {
console.error(path + ' not found! ' + process.env[path]);
process.exit(1);
return;
}
settings[path] = process.env[path];
});
// TELEGRAM CONSTANTS
const APK_MIME_TYPE = 'application/vnd.android.package-archive';
const ZIP_MIME_TYPE = 'application/octet-stream'; //'application/zip';
const TXT_MIME_TYPE = 'application/octet-stream'; // 'text/plain';
const TELEGRAM_API_TOKEN = process.env.TELEGRAM_API_TOKEN || settings.tokens.builder[LOCAL ? 'debug' : 'production'];
if (!TELEGRAM_API_TOKEN) {
console.error('Invalid TELEGRAM_API_TOKEN', TELEGRAM_API_TOKEN);
process.exit(1);
return;
}
if (!TELEGRAM_APP_ID || !TELEGRAM_APP_HASH) {
console.error('Invalid Telegram APP_ID / APP_HASH', TELEGRAM_APP_ID, TELEGRAM_APP_HASH);
process.exit(1);
return;
}
// GOOGLE PLAY CONSTANTS
const googleAuth = LOCAL ? null : new google.auth.GoogleAuth({
keyFile: settings.GOOGLE_TOKEN_PATH,
scopes: ['https://www.googleapis.com/auth/androidpublisher'],
});
if (!LOCAL) {
google.options({
// timeout: 1000,
auth: googleAuth
});
}
const play = LOCAL ? null : google.androidpublisher({
version: 'v3',
params: {
packageName: PACKAGE_NAME
}
});
// MAIN
const db = new Level('./db');
const cpus = os.cpus();
const cpuCount = cpus.length;
let threadCount;
const cpuNames = [];
cpus.forEach((cpu) => {
if (!cpuNames.includes(cpu.model)) {
cpuNames.push(cpu.model);
}
});
const platform = os.platform();
if (platform === 'linux') {
const output = execSync('lscpu -p | grep -Evc \'^#\'', {encoding: 'utf8'});
threadCount = parseInt(output.trim());
} else if (platform === 'darwin') {
const output = execSync('sysctl -n hw.logicalcpu_max', {encoding: 'utf8'});
threadCount = parseInt(output.trim());
}
let cpuSignature = cpuNames.join(', ') + ' @ ' + cpuCount + (cpuCount > 1 ? ' cores' : ' core') + (threadCount !== cpuCount ? ' (' + threadCount + ' threads)' : '');
const cur = {
cache: {},
build_no: -1,
pending_build: null,
uploaded_version: -1,
killServer: false,
server: null
};
function runServer (onClose, detached) {
detached = !!detached;
const server = spawn('telegram-bot-api',
[
'--api-id=' + TELEGRAM_APP_ID,
'--api-hash=' + TELEGRAM_APP_HASH,
'--local',
'--dir=' + process.cwd() + '/server',
'--log=' + process.cwd() + '/server.log',
'--verbosity=' + (settings.server_verbosity || 1)
],
{detached}
);
server.stdout.on('data', (data) => {
if (LOCAL) {
console.log('Server says:', data);
}
});
server.stderr.on('data', (data) => {
if (LOCAL) {
console.log('Server cries:', data);
}
});
server.on('close', (code) => {
console.log(`Server process exited with code ${code}`);
if (onClose) {
onClose(server);
}
});
if (detached) {
server.unref();
}
return server;
}
cur.server = runServer((closedServer) => {
if (cur.server === closedServer) {
console.error('Server closed, quitting process', cur.exiting);
cur.server = null;
if (!cur.exiting) {
process.kill(process.pid, 'SIGINT');
}
} else {
console.error('Unknown server closed');
}
});
function isOffline () {
return cur.server === null;
}
async function stopServer () {
console.log('Killing server…', isOffline());
if (!isOffline()) {
cur.server.kill('SIGTERM');
}
}
// Wait for the server
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000);
const TELEGRAM_API_URL = 'http://127.0.0.1:8081';
const bots = [
{
id: 'private',
bot: new TelegramBot(TELEGRAM_API_TOKEN, {
polling: true,
filepath: false,
baseApiUrl: TELEGRAM_API_URL
})
},
{
id: 'public',
bot: new TelegramBot(TELEGRAM_API_TOKEN_2, {
polling: true,
filepath: false,
baseApiUrl: TELEGRAM_API_URL
})
}
];
const botMap = {};
bots.forEach((bot) => {
botMap[bot.id] = bot.bot;
});
function nextBuildId () {
let id = cur.build_no ? cur.build_no + 1 : 1;
cur.build_no = id;
db.put('build_count', id);
return id;
}
function areEqual (a, b) {
if (a === b)
return true;
if (!a || !b)
return false;
for (let key in a) {
if (a[key] === b[key] || (typeof a[key] === typeof b[key] && typeof a[key] === 'object' && areEqual(a[key], b[key])))
continue;
return false;
}
for (let key in b) {
if (!a.hasOwnProperty(key))
return false;
}
return true;
}
function ucfirst (str) {
return str && str.length ? str.charAt(0).toUpperCase() + str.substring(1) : str;
}
function escapeRegExp (string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function empty (obj) {
if (typeof obj === 'object') {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
}
return true;
}
async function getObject (type, id) {
if (!cur.cache[type]) {
cur.cache[type] = {};
}
const cached = cur.cache[type][id];
if (cached !== undefined) {
return cached;
}
try {
const value = await db.get(type + '_' + id, {valueEncoding: 'json'});
cur.cache[type][id] = value;
return value;
} catch (err) {
cur.cache[type][id] = null;
return null;
}
}
function checksum (path, callback, algorithm) {
const stream = fs.createReadStream(path);
const checksum = crypto.createHash(algorithm);
stream.on('error', function (err) {
return callback(err, null)
});
stream.on('data', function (chunk) {
try {
checksum.update(chunk)
} catch (ex) {
return callback(ex, null)
}
});
stream.on('end', function () {
return callback(null, checksum.digest('hex'))
});
}
async function storeObject (type, obj, id) {
if (obj === undefined)
return;
if (id === undefined)
id = obj.id;
if (id === undefined)
return;
const existing = await getObject(type, id);
if (!areEqual(obj, existing)) {
cur.cache[type][id] = obj;
await db.put(type + '_' + id, obj, {valueEncoding: 'json'});
}
}
function getCommitDate (callback) {
exec('git show -s --format=%ct', {cwd: settings.TGX_SOURCE_PATH}, (error, stdout, stderr) => {
if (error) {
throw error;
}
const result = parseInt(trimIndent(stdout).trim());
callback(result);
});
}
function gitPull (callback) {
exec('git pull', {cwd: settings.TGX_SOURCE_PATH}, (error, stdout, stderr) => {
if (error) {
throw error;
}
callback(stdout);
});
}
function getGitData (callback) {
exec('echo "$(git rev-parse --short HEAD) $(git rev-parse HEAD) $(git show -s --format=%ct) $(git config --get remote.origin.url) $(git rev-parse --abbrev-ref HEAD) $(git log -1 --pretty=format:\'%an\')"', {cwd: settings.TGX_SOURCE_PATH}, (error, stdout, stderr) => {
if (error) {
throw error;
}
const result = trimIndent(stdout).trim().split(' ', 6);
let remoteUrl = result[3];
if (remoteUrl.startsWith('git@')) {
let index = remoteUrl.indexOf(':', 4);
let domain = remoteUrl.substring(4, index);
let endIndex = remoteUrl.endsWith('.git') ? remoteUrl.length - 4 : remoteUrl.length;
remoteUrl = 'https://' + domain + '/' + remoteUrl.substring(index + 1, endIndex);
}
callback({
commit: {
short: result[0],
long: result[1]
},
remoteUrl: remoteUrl,
branch: result[4],
author: result[5],
date: parseInt(result[2])
});
});
}
function getLocalChanges (callback) {
exec('git status --porcelain --untracked-files=no', {cwd: settings.TGX_SOURCE_PATH}, (error, stdout, stderr) => {
if (error) {
throw error;
}
const changes = trimIndent(stdout).trim();
callback(changes && changes.length ? changes : null);
});
}
function postHttp (url, jsonData, needBinary, httpOptions, method) {
return new Promise((accept, reject) => {
const parsed = new URL(url);
const protocol = (parsed.protocol === 'https:' ? https : http);
try {
const postData = JSON.stringify(jsonData);
const options = Object.assign({
host: parsed.host,
path: parsed.pathname + parsed.search,
method: (method || 'POST'),
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
}
}, httpOptions || {});
const req = protocol.request(options, (res) => {
toUtf8(res, (contentType, content) => {
accept({statusCode: res.statusCode, statusMessage: res.statusMessage, content, contentType});
}, needBinary);
}).on('error', reject);
req.write(postData);
req.end();
} catch (e) {
console.error('Cannot fetch', url, e);
reject(e);
}
});
}
function fetchHttp (url, needBinary, httpOptions) {
return new Promise((accept, reject) => {
const parsed = new URL(url);
const protocol = (parsed.protocol === 'https:' ? https : http);
try {
protocol.get(Object.assign({
host: parsed.host,
path: parsed.pathname + parsed.search
}, httpOptions || {}), (res) => {
toUtf8(res, (contentType, content) => {
accept({statusCode: res.statusCode, statusMessage: res.statusMessage, content, contentType});
}, needBinary);
}).on('error', reject);
} catch (e) {
console.error('Cannot fetch', url, e);
reject(e);
}
});
}
function uploadHttpFile (url, filePath, httpHeaders, httpOptions, needBinary) {
return new Promise((accept, reject) => {
const parsed = new URL(url);
const protocol = (parsed.protocol === 'https:' ? https : http);
const file = fs.createReadStream(filePath);
const stat = fs.statSync(filePath);
const options = Object.assign({
host: parsed.host,
path: parsed.pathname + parsed.search,
method: 'POST',
headers: Object.assign({
'Content-Type': 'application/octet-stream',
'Content-Length': stat.size
}, httpHeaders || {})
}, httpOptions || {});
const req = protocol.request(options, (res) => {
toUtf8(res, (contentType, content) => {
accept({statusCode: res.statusCode, statusMessage: res.statusMessage, content, contentType});
}, needBinary);
});
req.on('error', reject);
file.pipe(req);
});
}
function toUtf8 (res, onDone, needBinary) {
const contentType = (res.headers['content-type'] || '').split(';');
let encoding = null;
for (let i = 0; i < contentType.length; i++) {
const keyValue = contentType[i].split('=');
if (keyValue.length === 2 && keyValue[0].toLowerCase() === 'charset') {
encoding = keyValue[1].toLowerCase();
}
}
let data = [];
res.setEncoding('binary');
res.on('data', (chunk) => {
data.push(Buffer.from(chunk, 'binary'));
});
res.on('end', () => {
const binary = Buffer.concat(data);
if (needBinary) {
onDone(contentType, binary);
} else {
if (encoding && encoding !== 'utf-8') {
onDone(contentType, iconv.encode(iconv.decode(binary, encoding), 'utf-8'));
} else {
onDone(contentType, binary.toString('utf-8'));
}
}
});
}
function getProperty (data, variableName) {
variableName = variableName.replace(/\./gi, '\\.');
const regexp = new RegExp(variableName + '\s*=\s*[^\n]+');
const lookup = data.match(regexp);
const result = lookup && lookup.length == 1 ? lookup[0] : null;
if (result) {
return result.substring(result.indexOf('=') + 1)
}
return null;
}
function monthYears (now, then) {
let years = now.getUTCFullYear() - then.getUTCFullYear()
let months = 0;
if (now.getUTCMonth() < then.getUTCMonth() ||
(now.getUTCMonth() === then.getUTCMonth() && now.getUTCDate() < then.getUTCDate())) {
years--
months = 12 - then.getUTCMonth() + now.getUTCMonth()
} else {
months = now.getUTCMonth() - then.getUTCMonth()
}
if (now.getUTCDate() < then.getUTCDate()) {
months--
}
return years + '.' + months;
}
function getAppVersion (callback) {
fs.readFile(settings.TGX_SOURCE_PATH + '/version.properties', 'utf-8', function (err, data) {
if (err) {
callback(null);
} else {
const buildVersion = parseInt(getProperty(data, 'version.app'));
const creationDate = parseInt(getProperty(data, 'version.creation'));
if (!creationDate) {
callback('#' + buildVersion);
return;
}
const majorVersion = getProperty(data, 'version.major');
getCommitDate((commitDate) => {
const buildDate = new Date(commitDate * 1000);
const fromDate = new Date(creationDate);
const minorVersion = monthYears(buildDate, fromDate);
callback({code: buildVersion, name: majorVersion + '.' + minorVersion + '.' + buildVersion});
});
}
});
}
function escapeMarkdown (text) {
if (!text)
return text;
return text.replace(/\\/g, '\\\\').replace(/\-/g, '\\-').replace(/\*/g, '\\*').replace(/\./g, '\\.').replace(/\!/g, '\\!');
}
function escapeHtml (text) {
if (!text)
return text;
return text.replace(/</g, '<').replace(/>/g, '>');
}
function trimIndent (text) {
if (!text)
return text;
const lines = text.split('\n');
let minIndendWidth = -1;
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
const line = lines[lineIndex];
if (line.length) {
let indentWidth = 0;
for (let i = 0; i < line.length; i++) {
if (line[i] === ' ') {
indentWidth++;
} else {
break;
}
}
minIndendWidth = minIndendWidth === -1 || minIndendWidth > indentWidth ? indentWidth : minIndendWidth;
if (indentWidth === 0)
break;
}
}
if (minIndendWidth <= 0) {
return text;
}
let result = '';
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
const line = lines[lineIndex];
if (lineIndex > 0)
result += '\n';
if (line.length) {
result += line.substring(minIndendWidth);
}
}
return result;
}
function duration (start, end, full) {
const time = end - start;
if (time === 0) {
return full ? 'instant' : '0s';
}
if (time < 1000) {
return time + (full ? time === 1 ? ' millisecond' : ' milliseconds' : 'ms');
}
const totalSeconds = time / 1000;
const totalMinutes = Math.floor(totalSeconds / 60);
let seconds = (time - totalMinutes * 60000) / 1000;
let result = '';
if (totalMinutes !== 0) {
if (result.length) result += ' ';
result += totalMinutes + (full ? totalMinutes !== 1 ? ' minutes' : ' minute' : 'm');
}
if (seconds !== 0) {
if (result.length) result += ' ';
result += (seconds % 1 !== 0 ? seconds.toFixed(1) : seconds) + (full ? seconds !== 1 ? ' seconds' : ' second' : 's');
}
return result;
}
async function traceMaxApkVersionCode (type, versionCode, uploadDate) {
const cur = await getObject('apk', type);
const max = await getObject('apk', 'max');
if (!max || versionCode > max.versionCode) {
await storeObject('apk', {versionCode: versionCode, uploadDate: uploadDate}, 'max');
}
if (!cur || versionCode > cur.versionCode) {
await storeObject('apk', {versionCode: versionCode, uploadDate: uploadDate}, type);
}
}
async function canUploadApk (type, versionCode) {
const cur = await getObject('apk', type);
const max = type === 'universal' ? await getObject('apk', 'max') : null;
return versionCode > Math.max(cur ? cur.versionCode : 0, max ? max.versionCode : 0);
}
async function traceDuration (type, name, startTime, endTime, isComplete) {
if (typeof endTime !== 'number')
endTime = endTime.getTime();
if (typeof startTime !== 'number')
startTime = startTime.getTime();
if (!isComplete) {
type += '_failed';
}
let value = await getObject(type, name);
if (!value) {
value = {
total: 0,
items: []
};
}
value.total += (endTime - startTime);
value.items.push([startTime, endTime]);
await storeObject(type, value, name);
}
function main () {
db.get('build_count', (err, value) => {
cur.build_no = err ? 0 : parseInt(value);
});
db.get('uploaded_version', (err, value) => {
cur.uploaded_version = err ? 0 : parseInt(value);
});
}
async function estimateBuildDuration (build) {
let haveMissing = false;
let totalEstimate = 0;
for (let i = 0; i < build.tasks.length; i++) {
const task = build.tasks[i];
const stat = await getObject('task_stat', task.name);
if (stat && stat.total) {
task.estimateDuration = stat.total / stat.items.length;
totalEstimate += task.estimateDuration;
} else {
haveMissing = true;
}
}
if (!haveMissing) {
build.estimateDuration = totalEstimate;
}
}
async function killTask (task) {
setTimeout(async () => {
if (!task.processTerminated && task.process) {
await task.process.kill('SIGKILL');
task.processTerminated = true;
}
}, 2500);
if (task.process) {
await task.process.kill();
task.processTerminated = true;
}
}
function findFile (dir, regexp, callback) {
fs.readdir(dir, {withFileTypes: true}, (err, files) => {
if (err) {
console.error('Cannot lookup for file', dir);
callback(null);
} else {
for (let i = 0; i < files.length; i++) {
const fileName = files[i].name;
let match = fileName.match(regexp);
if (match && match.length) {
if (match[0].length === fileName.length) {
callback(fileName);
return;
}
}
}
console.error('None of the files match regexp!', regexp, JSON.stringify(files));
callback(null);
}
});
}
function toDisplayAlgorithm (algorithm) {
switch (algorithm) {
case 'md5': return 'MD5';
case 'sha1': return 'SHA-1';
case 'sha256': return 'SHA-256';
default: return algorithm;
}
}
function getDisplayVariant (variant) {
switch (variant) {
case 'arm64': return 'arm64-v8a';
case 'arm32': return 'armeabi-v7a';
default: return variant;
}
}
function getBuildFiles (build, variant, callback) {
const architecture = getDisplayVariant(variant); // == 'universal' ? null : getDisplayVariant(variant);
const outputsDir = settings.TGX_SOURCE_PATH + '/app/build/outputs';
const mappingDir = outputsDir + '/mapping/' + variant + 'Release';
const apkDir = outputsDir + '/apk/' + variant + '/release';
const nativeDebugSymbolsFile = outputsDir + '/native-debug-symbols/' + variant + 'Release' + '/native-debug-symbols.zip';
const result = { };
const check = () => {
if (result.nativeDebugSymbolsFile !== undefined && result.apkFile !== undefined && (result.apkFile === null || (result.apkFile.checksum && result.apkFile.checksum.md5 !== undefined && result.apkFile.checksum.sha1 !== undefined && result.apkFile.checksum.sha256 !== undefined)) && result.mappingFile !== undefined && result.metadata !== undefined) {
if (result.nativeDebugSymbolsFile && result.apkFile && (result.apkFile.checksum && result.apkFile.checksum.sha256 && result.apkFile.checksum.sha1 && result.apkFile.checksum.md5) && (result.mappingFile || build.outputApplication.dontObfuscate) && result.metadata) {
callback(result);
} else {
console.error('Cannot find build files for #' + build.version.name, JSON.stringify(result));
callback(null);
}
}
};
const prefix = '^' + escapeRegExp(build.outputApplication.name || 'Telegram X').replace(/ /g, '-').replace(/#/g, '') + '-' + build.version.name.replace(/\./gi, '\\.') + '(?:\\+[0-9,]+)?' + (architecture ? '(?:-' + architecture + ')?' : '') ;
fs.exists(nativeDebugSymbolsFile, (exists) => {
result.nativeDebugSymbolsFile = exists ? {path: nativeDebugSymbolsFile} : null;
check();
});
findFile(apkDir, RegExp(prefix + '\\.apk$'), (apkFile) => {
if (apkFile) {
result.apkFile = {path: apkDir + '/' + apkFile};
['sha256', 'sha1', 'md5'].forEach((algorithm) => {
checksum(result.apkFile.path, (err, checksum) => {
if (!result.apkFile.checksum) {
result.apkFile.checksum = {};
}
result.apkFile.checksum[algorithm] = checksum ? checksum : null;
check();
}, algorithm);
});
} else {
result.apkFile = null;
check();
}
});
findFile(apkDir, RegExp('^output-metadata\\.json$'), (metadataFile) => {
if (metadataFile) {
fs.readFile(apkDir + '/' + metadataFile, 'utf-8', (err, data) => {
const metadata = err ? null : JSON.parse(data);
if (err || !(metadata &&
metadata.elements &&
metadata.elements.length == 1 &&
metadata.elements[0].versionCode)) {
console.error('Cannot read metadata file', err, data);
result.metadata = null;
check();
} else {
result.metadata = metadata.elements[0];
check();
}
});
} else {
result.metadata = null;
check();
}
});
findFile(mappingDir, RegExp(prefix + '\\.txt$'), (mappingFile) => {
result.mappingFile = mappingFile ? {path: mappingDir + '/' + mappingFile} : null;
check();
});
}
function getFromToCommit (build, allowProduction) {
if (build.outputApplication && build.outputApplication.isPRBuild)
return null;
if (build.googlePlayTrack) {
let googlePlayBuild = allowProduction ? build.previousGooglePlayProductionBuild : null;
if (!(googlePlayBuild &&
googlePlayBuild.remoteUrl === build.git.remoteUrl &&
googlePlayBuild.branch === build.git.branch)) {
googlePlayBuild = build.previousGooglePlayBuild;
}
if (googlePlayBuild &&
googlePlayBuild.remoteUrl === build.git.remoteUrl &&
googlePlayBuild.branch === build.git.branch) {
return {
commit_range: googlePlayBuild.commit.short + '...' + build.git.commit.short,
from_version: googlePlayBuild.version,
build_information: googlePlayBuild
};
}
} else if (build.telegramTrack) {
const telegramBuild = build.previousTelegramBuild;
if (telegramBuild &&
telegramBuild.remoteUrl === build.git.remoteUrl &&
telegramBuild.branch === build.git.branch) {
return {
commit_range: telegramBuild.commit.short + '...' + build.git.commit.short,
from_version: telegramBuild.version,
build_information: telegramBuild
};
}
}
return null;
}
function getBuildCaption (build, variant, isPrivate, shortenChecksums) {
let caption = '<b>Version</b>: <code>' + build.version.name + '-' + getDisplayVariant(variant) + '</code>';
caption += '\n<b>Commit</b>: <a href="' + build.git.remoteUrl + '/tree/' + build.git.commit.long + '">' + build.git.commit.short + '</a>';
if (build.git.date) {
caption += ', ' + toDisplayDate(build.git.date);
}
if (build.pullRequestsMetadata || !empty(build.pullRequests)) {
caption += '\n<b>Pull requests</b>: ' + toDisplayPullRequestList(build);
}
const checksumAlgorithms = ['md5', 'sha1', 'sha256'];
if (!shortenChecksums) {
caption += '\n';
checksumAlgorithms.forEach((algorithm) => {
const hash = build.files[variant].apkFile.checksum[algorithm];
const url = 'https://t.me/tgx_bot?start=' + hash;
caption += '\n<b>' + toDisplayAlgorithm(algorithm) + '</b>: <a href="' + url + '">' + hash + '</a>';
});
}
const fromToCommit = getFromToCommit(build,
build.googlePlayTrack && build.previousGooglePlayProductionBuild && build.previousGooglePlayBuild &&
build.previousGooglePlayBuild.version.code < build.previousGooglePlayProductionBuild.version.code
);
if (fromToCommit) {
caption += '\n\n<b>Changes from ' + fromToCommit.from_version.code + '</b>: <a href="' + build.git.remoteUrl + '/compare/' + fromToCommit.commit_range + '">' + fromToCommit.commit_range + '</a>';
}
caption += '\n\n#' + variant;
switch (build.googlePlayTrack) {
case 'production': caption += ' #stable'; break;
case 'beta': caption += ' #beta'; break;
case 'alpha': caption += ' #alpha'; break;
}
caption += ' #apk';
if (shortenChecksums) {
caption += ' (';
checksumAlgorithms.forEach((algorithm, index) => {
const hash = build.files[variant].apkFile.checksum[algorithm];
const url = 'https://t.me/tgx_bot?start=' + hash;
caption += '<b>';
if (index > 0) {
caption += ', ';
}
caption += '<a href="' + url + '">' + toDisplayAlgorithm(algorithm) + '</a>';
caption += '</b>';
});
caption += ')';
}
return caption;
}
function publishToTelegram (bot, task, build, onDone, chatId, onlyPrivate, disableNotification, shortenChecksums) {
const docs = [];
const variants = [];
for (let variant in build.files) {
const file_id = build.files[variant].apkFile.remote_id;
if (file_id) {
const doc = {
type: 'document',
media: file_id,
caption: getBuildCaption(build, variant, false, shortenChecksums),
parse_mode: 'HTML'
};
let ok = variant !== 'universal' || build.variants.length === 1;
if (onlyPrivate) {
ok = !ok;
}
if (ok) {
docs.push(doc);
variants.push(variant);
}
} else {
console.log('Some of docs do not have file_id available!');
onDone(1);
return;
}
}
if (docs.length > 1) {
bot.sendMediaGroup(chatId, docs, {
disable_notification: disableNotification
}).then((messages) => {
if (!build.publicMessages) {
build.publicMessages = [];
}
for (let i = 0; i < messages.length; i++) {
const messageId = messages[i].message_id;
build.publicMessages.push({
variant: variants[i],
message_id: messageId,
url: messages[i].sender_chat && messages[i].sender_chat.username ?
'https://t.me/' + messages[i].sender_chat.username + '/' + messageId :
null
});
}
if (!onlyPrivate) {
tracePublishedTelegramBuild(build).then(() => {
onDone(0);
});
} else {
onDone(0);
}
}).catch((error) => {
onDone(1);
globalErrorHandler()(error);
});
} else if (docs.length === 1) {
bot.sendDocument(chatId, docs[0].media, {
caption: docs[0].caption,
parse_mode: docs[0].parse_mode,
disable_notification: disableNotification
}).then((message) => {
if (!build.publicMessages) {
build.publicMessages = [];
}
build.publicMessages.push({
variant: variants[0],
message_id: message.message_id,
url: message.sender_chat && message.sender_chat.username ?
'https://t.me/' + message.sender_chat.username + '/' + message.message_id :
null
});
if (!onlyPrivate) {
tracePublishedTelegramBuild(build).then(() => {
onDone(0);
});
} else {
onDone(0);
}
}).catch((error) => {
onDone(1);
globalErrorHandler()(error);
});
} else {
onDone(0);
}
}
function uploadToTelegram (bot, task, build, variant, onDone) {
const files = build.files[variant];
if (!files) {
console.log('Build files not found for variant', variant);
onDone(1);
return;
}
const failWithError = (message, e) => {
if (!task.endTime) {
console.error(message, e);
onDone(1);
}
};
bot.sendDocument(build.serviceChatId, fs.createReadStream(files.apkFile.path), {
reply_to_message_id: build.serviceMessageId,
caption: getBuildCaption(build, variant),
parse_mode: 'HTML'
}, {
contentType: APK_MIME_TYPE
}).then((message) => {
files.apkFile.remote_id = message.document.file_id;
modifyNativeDebugSymbolsArchive(files.nativeDebugSymbolsFile.path).then((nativeDebugSymbolsPath) => {
const nativeDebugSymbolsStream = fs.createReadStream(nativeDebugSymbolsPath);