-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.js
11864 lines (10990 loc) · 488 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
/**
Source code of the bot running at https://t.me/spbik_bot
Available in Russian and English languages.
Sample project of what could be built based on
the generated JSON files located inside /data folder.
Copyright © Vyacheslav <[email protected]> (https://github.com/vkryl) 2021–2022
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
'use strict';
// CONSTANTS
const VERSION = '3.72';
const CHARTS_VERSION = '1.21';
const REGION_NAME = 'st-petersburg';
const REGION_CODE = 78;
const VIOLATIONS_URL = 'https://www.kartanarusheniy.org/2021-09-19/s/3405541806';
const COMMITTEE_URL = 'http://cikrf.ru/iservices/voter-services/committee';
const IZBIRKOM_HOST = 'www.' + REGION_NAME + '.vybory.izbirkom.ru';
const REGIONS = {};
// TELEGRAM BOT
const isDebug = process.platform === 'darwin';
process.env.NTBA_FIX_319 = 1;
process.env.NTBA_FIX_350 = 1;
// LIBRARIES
require('format-unicorn');
const fs = require('fs'),
http = require('http'),
path = require('path'),
https = require('https'),
iconv = require('iconv-lite'),
moment = require('moment'),
geolib = require('geolib'),
XPath = require('xpath'),
DOMParser = require('xmldom').DOMParser,
hasClass = require('xpath-has-class'),
{Canvas, CanvasRenderingContext2D, FontLibrary, loadImage, Path2D} = require('skia-canvas'),
{ fillTextWithTwemoji, measureText } = require('skia-canvas-with-twemoji-and-discord-emoji'),
TelegramBot = require('node-telegram-bot-api'),
ProxyLists = require('proxy-lists'),
SocksProxyAgent = require('socks-proxy-agent'),
HttpProxyAgent = require('http-proxy-agent'),
HttpsProxyAgent = require('https-proxy-agent'),
imageToAscii = require('image-to-ascii'),
readline = require('readline'),
tesseract = require('node-tesseract-ocr'),
fakeUa = require('fake-useragent'),
level = require('level'),
Duration = require('duration'),
tor = require('tor-request'),
I18n = require('i18n').I18n;
const settings = JSON.parse(fs.readFileSync(path.join(__dirname, 'settings.json'), 'UTF-8'));
const TELEGRAM_API_TOKEN = process.env.TELEGRAM_API_TOKEN || settings.tokens[isDebug ? 'debug' : 'production'];
const i18n = new I18n({
locales: ['ru', 'en'],
fallbacks: { ua: 'ru', be: 'ru' },
defaultLocale: 'ru',
retryInDefaultLocale: true,
autoReload: true,
header: 'locale',
directory: path.join(__dirname, 'locales'),
updateFiles: false,
objectNotation: true,
preserveLegacyCase: false,
logDebugFn: (msg) => {
console.log('debug', msg)
},
// setting of log level WARN - default to require('debug')('i18n:warn')
logWarnFn: (msg) => {
console.warn('warn', msg)
},
// setting of log level ERROR - default to require('debug')('i18n:error')
logErrorFn: (msg) => {
console.error('error', msg)
}
});
const TOR_PROXY_URL = 'socks5://localhost:9050';
const CM = [];
const solvedCaptcha = {};
const USER_AGENT = fakeUa();
for (let i = 0; i < 1; i++) {
CM.push({});
}
// HTTP(S)
const allHostsStats = {};
let proxyBlacklist = {};
function setProxyAgent (options, proxyUrl) {
if (!proxyUrl) {
delete options.agent;
return;
}
let agent = null;
const proxyProtocol = new URL(proxyUrl).protocol;
switch (proxyProtocol) {
case 'socks4:':
case 'socks5:':
agent = new SocksProxyAgent(proxyUrl);
break;
case 'http:':
agent = new HttpProxyAgent(proxyUrl);
break;
case 'https:':
agent = new HttpsProxyAgent(proxyUrl);
break;
default:
throw Error('Unknown proxy protocol: ' + proxyProtocol);
}
options.agent = agent;
}
function httpGet (rawUrl, contentTypeFilter, logInfo) {
return new Promise((accept, reject) => {
let url = null;
try {
url = new URL(rawUrl);
} catch (e) {
throw Error('Cannot parse ' + JSON.stringify(rawUrl), e);
}
if (!allHostsStats[url.host]) {
allHostsStats[url.host] = {
requests: 0,
captchas: {
// proxyData -> request_no
// 0 = no captcha, 1 = 1st request
no_proxy: 0
},
current_proxy: url.host.endsWith('izbirkom.ru') || url.host.endsWith('cikrf.ru') ? TOR_PROXY_URL : null
};
}
const hostStats = allHostsStats[url.host];
const requestNo = ++hostStats.requests;
const requestOptions = {
host: url.host,
path: url.pathname + url.search
};
setProxyAgent(requestOptions, hostStats.current_proxy);
const protocol = url.protocol === 'https:' ? https : http;
console.log('Fetching', rawUrl, '->', logInfo, 'Proxy:', hostStats.current_proxy ? hostStats.current_proxy : 'no', 'request_no:', requestNo);
const onError = (e) => {
console.log(e);
reject(e);
};
const fetchHttp = (url, callback, needBinary) => {
const parsed = new URL(url);
const protocol = (parsed.protocol === 'https:' ? https : http);
try {
protocol.get(applyCookie(requestNo, rawUrl, {
host: parsed.host,
path: parsed.pathname + parsed.search
}), (res) => {
if (res.statusCode < 200 || res.statusCode >= 300) {
reject(res);
return;
}
storeCookie(requestNo, url, res);
toUtf8(res, (contentType, content) => {
callback(content, res.statusCode);
}, needBinary);
}).on('error', onError);
} catch (e) {
console.error('Cannot fetch', url, e);
}
};
const onDone = (text, retryWithProxy, invalidCaptcha, forceCaptchaFlow) => {
if (!responseCallback)
throw Error();
if (invalidCaptcha || (url.host.endsWith('izbirkom.ru') && text.includes('<input id="captcha" name="captcha"'))) {
// Try to solve
const captcha = invalidCaptcha || generateCaptchaId(requestNo);
console.log('Received captcha for', rawUrl, 'request_no:', requestNo);
if (hostStats.current_proxy === TOR_PROXY_URL) {
console.log('Switching identity...');
clearCookies(requestNo);
tor.newTorSession((err) => {
if (err) {
console.log('Failed to switch identity', err);
} else {
console.log('Identity switched');
console.log('Retrying', rawUrl, '->', logInfo, 'Proxy:', hostStats.current_proxy ? hostStats.current_proxy : 'no');
protocol.get(applyCookie(requestNo, rawUrl, requestOptions), responseCallback).on('error', onError);
}
});
return;
}
fetchHttp('http://' + url.host + '/captcha-service/image/?d=' + captcha.id, (captchaImageBinary) => {
fs.writeFileSync(path.join('cache', 'captcha.png'), captchaImageBinary);
const onCaptchaGuessMade = (captchaGuess) => {
imageToAscii(captchaImageBinary, {
size: {width: 85, height: 85},
colored: false
}, (err, converted) => {
console.log(err || converted);
if (err) {
onDone(text, false, null, true);
return;
}
let rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const onCaptchaSolved = (captchaCode, cached) => {
console.log('Captcha solution:', captchaCode.startsWith('0') ? captchaCode : parseInt(captchaCode), 'request_no:', requestNo);
fetchHttp('http://' + url.host + '/validate/captcha/value/' + captchaCode, (validationResponse, validationResponseCode) => {
if (validationResponseCode === 401 || validationResponse.includes('id="captcha"')) {
console.log('Invalid captcha, retrying', validationResponseCode);
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Invalid captcha, try again (guess: ' + captchaGuess + '): ', captchaCallback);
} else {
protocol.get(applyCookie(requestNo, rawUrl, requestOptions), responseCallback).on('error', onError);
}
}, false, contentTypeFilter);
};
const captchaCallback = (captchaCode) => {
rl.close();
captchaCode = captchaCode.trim();
if (!captchaCode) {
clearCookies(requestNo);
protocol.get(applyCookie(requestNo, rawUrl, requestOptions), responseCallback).on('error', onError);
return;
}
if (captchaCode.match(/^[0-9]{4,6}$/gi)) {
captcha.solution = captchaCode;
onCaptchaSolved(captchaCode);
} else {
if (captchaCode === 'clear') {
clearCookies(requestNo);
} else if (captchaCode === 'tor') {
clearCookies(requestNo);
const retryWithTor = () => {
console.log('Retrying', rawUrl, '->', logInfo, 'Proxy:', hostStats.current_proxy ? hostStats.current_proxy : 'no');
protocol.get(applyCookie(requestNo, rawUrl, requestOptions), responseCallback).on('error', onError);
};
if (hostStats.current_proxy !== TOR_PROXY_URL) {
setProxyAgent(requestOptions, TOR_PROXY_URL);
hostStats.current_proxy = TOR_PROXY_URL
retryWithTor();
} else {
tor.newTorSession((err) => {
if (err) {
console.log(err);
} else {
retryWithTor();
}
});
return;
}
} else {
console.log('Invalid value entered.', captchaCode);
}
rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Please solve captcha (guess: ' + captchaGuess + '): ', captchaCallback);
}
};
rl.question('Please solve captcha (guess: ' + captchaGuess + '): ', captchaCallback);
});
};
tesseract.recognize(captchaImageBinary, {
tessedit_char_whitelist: '0123456789',
oem: 1, psm: 7
}).then((text) => {
onCaptchaGuessMade(text.trim());
}).catch((error) => {
console.log(error.message);
onCaptchaGuessMade(null);
});
}, true);
return;
} else if (retryWithProxy) {
const captchaKey = hostStats.current_proxy ? hostStats.current_proxy : 'no_proxy';
hostStats.captchas[captchaKey] = requestNo;
console.log(retryWithProxy ? 'Error' : 'Captcha', 'occurred for', captchaKey, 'on request #' + requestNo + '. Trying to find a new proxy...');
if (hostStats.current_proxy) {
if (!proxyBlacklist[url.host]) {
proxyBlacklist[url.host] = [];
}
proxyBlacklist[url.host].push(hostStats.current_proxy);
saveJsonFile(path.join('cache', 'proxy_blacklist.json'), proxyBlacklist);
}
const proxyProtocols = ['socks5'];
let retriedWithNewProxy = false;
ProxyLists.getProxies({
countries: ['ru'],
protocols: proxyProtocols
}).on('data', (proxies) => {
if (retriedWithNewProxy)
return;
console.log('Received', proxies.length, 'proxies, looking whether there is a good one');
for (let proxyIndex = 0; proxyIndex < proxies.length; proxyIndex++) {
const proxy = proxies[proxyIndex];
if (!proxy.protocols)
continue;
const proxyProtocol = proxy.protocols.sort((a, b) => {
const index1 = proxyProtocols.indexOf(a);
const index2 = proxyProtocols.indexOf(b);
const has1 = index1 != -1;
const has2 = index2 != -1;
if (has1 != has2) {
return has1 ? -1 : 1;
}
if (has1) {
return index1 < index2 ? -1 : 1;
}
return a < b ? -1 : a > b ? 1 : 0;
})[0];
const proxyData = proxyProtocol + '://' + proxy.ipAddress + ':' + proxy.port;
if (proxyBlacklist[url.host] && proxyBlacklist[url.host].includes(proxyData)) {
continue;
}
if (!hostStats.captchas[proxyData]) {
try {
setProxyAgent(options, proxyData);
hostStats.current_proxy = proxyData;
retriedWithNewProxy = true;
console.log('Retrying', rawUrl, '->', logInfo, 'Proxy:', hostStats.current_proxy ? hostStats.current_proxy : 'no');
protocol.get(applyCookie(requestNo, rawUrl, options), responseCallback).on('error', onError);
break;
} catch (e) {
console.log('Error occurred when trying to set proxy', e, 'retried:', retriedWithNewProxy);
throw e;
}
}
}
if (!retriedWithNewProxy) {
console.log('None of the proxies matches the criteria, waiting for new ones..');
}
})
.on('error', (error) => {
if (!retriedWithNewProxy) {
reject(error);
}
})
.once('end', () => {
if (!retriedWithNewProxy) {
reject('No valid proxies found!');
}
});
} else {
accept(text);
}
};
const responseCallback = (res) => {
storeCookie(requestNo, rawUrl, res);
if (res.statusCode < 200 || res.statusCode >= 300) {
reject(res);
return;
}
toUtf8(res, (contentType, content) => {
if (content && contentTypeFilter && !contentTypeFilter.includes(contentType[0])) {
reject('Invalid content-type: ' + res.headers['content-type']);
} else {
onDone(content);
}
});
};
protocol.get(applyCookie(requestNo, rawUrl, requestOptions), responseCallback).on('error', onError);
});
}
function generateCaptchaId (requestNo) {
const newCaptchaId = Date.now();
const cacheId = requestNo % CM.length;
return {
id: newCaptchaId,
cache_id: cacheId
};
}
function getCookies (requestNo, url) {
const host = new URL(url).host;
const cacheId = requestNo % CM.length;
if (!CM[cacheId])
CM[cacheId] = {};
if (!CM[cacheId][host]) {
const chars = '0123456789abcdef'.split('');
let deviceId = '';
for (let i = 0; i < 32; i++) {
deviceId += chars[Math.round(Math.random() * (chars.length - 1))]
}
CM[cacheId][host] = {
// 'izbFP': 'XXX',
//'session-cookie': 'XXX',
//'JSESSIONID': 'XXX',
//'izbSession': 'XXX'
};
}
return Object.keys(CM[cacheId][host])
.map((cookieKey) => cookieKey + '=' + CM[cacheId][host][cookieKey]
);
}
function storeCookie (requestNo, url, request) {
const cookie = request.headers['set-cookie'];
const host = new URL(url).host;
if (empty(cookie))
return;
const before = getCookies(requestNo, url).join('; ');
const cacheId = requestNo % CM.length;
if (!CM[cacheId]) {
CM[cacheId] = {};
}
if (!CM[cacheId][host]) {
CM[cacheId][host] = {};
}
cookie.forEach((specificCookie) => {
const keyValue = specificCookie.split('; ')[0].split('=');
CM[cacheId][host][keyValue[0]] = keyValue[1];
});
const after = getCookies(requestNo, url).join('; ');
if (before != after) {
// console.log('Stored', cookie.length, 'cookie', url, 'request_no', requestNo, getCookies(requestNo, url));
} else {
// console.log('Unchanged', cookie.length, 'cookie', url, 'request_no', requestNo, getCookies(requestNo, url));
}
}
function clearCookies (requestNo) {
CM[requestNo % CM.length] = {};
}
function applyCookie (requestNo, url, options) {
const cookie = getCookies(requestNo, url);
if (!options.headers)
options.headers = {};
if (!options.headers['User-Agent'])
options.headers['User-Agent'] = USER_AGENT;
if (!empty(cookie)) {
if (!options.headers) {
options.headers = {};
}
options.headers['Cookie'] = cookie.join('; ');
} else {
delete options.headers['Cookie'];
}
// console.log('Sending', cookie.length, 'cookie', 'request_no', requestNo, cookie, toJson(options));
return options;
}
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];
}
}
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'));
}
}
});
}
// HTML
const htmlCache = {};
function parseHtml (html) {
let warningCount = 0, errorCount = 0;
const doc = new DOMParser({
errorHandler: {
warning: (msg) => warningCount++,
error: (msg) => errorCount++,
fatalError: (msg) => reject(msg)
}
}).parseFromString(html);
if (warningCount > 0 || errorCount > 0) {
// console.log('Parsed HTML, warnings: ' + warningCount + ', errors: ' + errorCount);
}
return doc;
}
async function getHtmlFile (filePath, htmlUrl, noCache) {
const cached = htmlCache[filePath];
if (cached) {
return cached;
}
let html = null;
try {
html = await readJsonFile(filePath);
html.document = parseHtml(html.response);
} catch (e) {
html = htmlUrl ? await httpGet(htmlUrl, ['text/html'], filePath ? filePath : 'RAM') : null;
if (html) {
html = {
origin: htmlUrl,
date: Date.now(),
response: html.toString()
};
if (!noCache) {
htmlCache[filePath] = html;
}
const document = parseHtml(html.response);
const captcha = XPath.select1('//input[@id="captcha"]', document);
if (captcha)
throw Error('Captcha occurred on request #' + hostStats[new URL(htmlUrl).host] + ' ' + htmlUrl + ' -> ' + filePath);
await saveJsonFile(filePath, html);
html.document = document;
}
}
return html;
}
// JSON
const jsonCache = {};
function toJson (json) {
return JSON.stringify(json, null, ' ');
}
async function readJsonFile (filePath) {
if (fs.lstatSync(filePath).isDirectory()) {
const result = {};
const files = fs.readdirSync(filePath);
for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
const fileName = files[fileIndex];
const key = fileName.replace(/\.json$/gi, '');
result[key] = await readJsonFile(path.join(filePath, fileName));
}
return result;
}
return JSON.parse(fs.readFileSync(filePath, 'UTF-8'));
}
async function saveJsonFile (filePath, jsonData) {
const json = toJson(jsonData);
const dir = filePath.includes('/') ? filePath.substring(0, filePath.lastIndexOf('/')) : null;
if (dir) {
fs.mkdirSync(dir, {recursive: true});
}
fs.writeFileSync(filePath, json);
}
async function getJsonFile (filePath, jsonUrl, noCache, allowError) {
const cached = jsonCache[filePath];
if (cached) {
return cached;
}
let json = null;
try {
json = await readJsonFile(filePath);
} catch (e) {
if (!jsonUrl)
throw e;
let httpResponse = null;
try {
httpResponse = await httpGet(jsonUrl, ['application/json', 'application/hal+json'], filePath ? filePath : 'RAM', allowError);
} catch (e) {
console.error('Cannot fetch', jsonUrl);
if (!allowError) {
throw e;
}
}
json = !httpResponse ? {} : JSON.parse(httpResponse);
if (json) {
json = {
origin: jsonUrl,
date: Date.now(),
response: json
};
if (!noCache) {
jsonCache[filePath] = json;
}
await saveJsonFile(filePath, json);
}
}
if (json) {
return json;
} else {
throw Error(jsonUrl ? 'Failed to fetch ' + jsonUrl : 'Failed to load ' + filePath);
}
}
// UTILS
function empty (obj) {
if (!obj)
return true;
if (Array.isArray(obj))
return obj.length === 0;
switch (typeof obj) {
case 'string':
return obj.length === 0;
case 'object':
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
return false;
}
}
return true;
}
return false;
}
function cloneArray (array) {
if (!Array.isArray(array))
throw Error();
return array.map((a) => a);
}
function sortKeysByValueDesc (object, transformer) {
return sortKeys(object, transformer, (a, b) => object[b] - object[a]);
}
function formatNumber (number) {
if (typeof number !== 'number')
throw Error(toJson(number));
let str = toDisplayPercentage(number, true);
if (str.length <= 3 || str.indexOf('.') !== -1)
return str;
let result = '';
let count = 0;
for (let i = str.length - 1; i >= 0; i--) {
const digit = str[i];
if (++count > 3) {
result = digit + ',' + result;
count = 1;
} else {
result = digit + result;
}
}
return result;
}
function sortKeys (object, transformer, sorter, keyTransformer, filter) {
const sorted = {};
let keys = Object.keys(object);
if (filter) {
keys = keys.filter(filter);
}
keys.sort(sorter).forEach((key) => {
sorted[keyTransformer ? keyTransformer(key) : key] = transformer ? transformer(object[key]) : object[key];
});
return sorted;
}
function countKeys (object) {
if (object) {
let count = 0;
for (const key in object) {
if (object.hasOwnProperty(key)) {
count++;
}
}
return count;
}
return 0;
}
function countValues (object, transformer) {
if (object) {
let count = 0;
for (const key in object) {
if (object.hasOwnProperty(key)) {
count += transformer ? transformer(object[key]) : object[key];
}
}
return count;
}
return 0;
}
function makeArray (data) {
return Array.isArray(data) ? data : [data];
}
function objSum (object, transformer) {
if (!object)
return 0;
let result = 0;
for (const key in object) {
if (object.hasOwnProperty(key)) {
result += transformer ? transformer(object[key]) : object[key];
}
}
return result;
}
function arraySum (array, transformer) {
if (!Array.isArray(array))
throw Error();
let result = 0;
array.forEach((item, index) => {
result += transformer ? transformer(item, index) : item;
});
return result;
}
function arrayMax (array, transformer) {
if (!Array.isArray(array))
throw Error();
let result = null;
array.forEach((item, index) => {
let value;
if (transformer) {
value = transformer(item, index);
} else {
value = item;
}
if (value !== null) {
result = result !== null ? Math.max(value, result) : value;
}
});
return result;
}
function arrayMin (array, transformer) {
if (!Array.isArray(array))
throw Error();
let result = null;
array.forEach((item, index) => {
let value;
if (transformer) {
value = transformer(item, index);
} else {
value = item;
}
if (value !== null) {
result = result !== null ? Math.min(value, result) : value;
}
});
return result;
}
function indexOf (array, object) {
for (let i = 0; i < array.length; i++) {
if (equals(array[i], object)) {
return i;
}
}
return -1;
}
function equals (a, b) {
if (a === b)
return true;
if (typeof a !== typeof b)
return false;
if (Array.isArray(a) || Array.isArray(b))
return arrayEquals(a, b);
if (typeof a === 'object') {
if (countKeys(a) !== countKeys(b))
return false;
for (let key in a) {
const aValue = a[key];
const bValue = b[key];
if (!equals(aValue, bValue)) {
return false;
}
}
return true;
}
return false;
}
function arrayEquals (a, b) {
if (a === b)
return true;
if (!Array.isArray(a) || !Array.isArray(b))
return false;
if (a.length != b.length)
return false;
for (let i = 0; i < a.length; i++) {
if (a[i] != b[i])
return false;
}
return true;
}
function clone (obj, excludeKeys) {
if (!obj) {
return obj;
}
if (Array.isArray(obj)) {
let newArray = [];
obj.forEach((element) => {
newArray.push(clone(element));
});
return newArray;
} else if (typeof obj === 'object') {
if (typeof excludeKeys === 'string') {
excludeKeys = [excludeKeys];
}
let cloned = {};
Object.keys(obj).forEach((key) => {
if (!excludeKeys || !excludeKeys.includes(key)) {
cloned[key] = clone(obj[key]);
}
});
return cloned;
} else {
return obj;
}
}
function ucfirst (str) {
return str && str.length ? str.charAt(0).toUpperCase() + str.substring(1) : str;
}
function ucwords (str) {
return str ? str.split(' ').map((str) => {
let text = str.toLowerCase();
return text == 'лдпр' ? str : text.length > 1 ? ucfirst(text) : text;
}).join(' ') : str;
}
const cyrillicToLatinMap = {
'А': 'A',
'Б': 'B',
'В': 'V',
'Г': 'G',
'Д': 'D',
'Е': 'E',
'Ё': 'Yo',
'Ж': 'Zh',
'З': 'Z',
'И': 'I',
'Й': 'Y',
'К': 'K',
'Л': 'L',
'М': 'M',
'Н': 'N',
'О': 'O',
'П': 'P',
'Р': 'R',
'С': 'S',
'Т': 'T',
'У': 'U',
'Ф': 'F',
'Х': 'H',
'Ц': 'Ts',
'Ч': 'Ch',
'Ш': 'Sh',
'Щ': 'Shch',
'Ъ': '',
'Ы': 'Y',
'Ь': '',
'Э': 'E',
'Ю': 'Yu',
'Я': 'Ya'
};
function venueName (context, address) {
if (context.isLatinLocale) {
if (address.type === 'district_administration') {
return context.__('administration', {district: districtName(context, address.address.district)});
}
}
return address.name.replace(/\s*Санкт-Петербурга$/i, '');
}
function districtName (context, text) {
if (text === 'Голосование за рубежом') {
return context.__('abroad');
}
text = text.replace(/ район$/i, '');
return context.__('district', {name: text, name_latin: cyrillicToLatin(text)});
}
function cyrillicToLatin (text) {
if (!text || !text.length || typeof text !== 'string')
return text;
if (text === 'СПбИК') {
return 'SPBEC';
}
text = text.replace(/кс/g, 'x').replace(/ый$/g, 'y').replace(/ий$/, 'y').replace(/ый/g, 'iy');
let res = '';
for (let i = 0; i < text.length; i++) {
const c = text[i];
const upperCase = c.toUpperCase();
const transliterated = cyrillicToLatinMap[upperCase];
if (transliterated !== undefined) {
res += (c === upperCase ? transliterated : transliterated.toLowerCase());
} else {
res += c;
}
}
return res;
}
function htmldecode (str) {
return str ? str.replace(/ /g, ' ').replace(/–/g, '–') : str;
}
function abbreviation (str) {
if (str && str.length && str.toUpperCase() != str) {
return str.split(' ').map((a) => a.charAt(0).toUpperCase()).join('');
}
return str;
}
function findEnding (name, endings) {
for (let i = 0; i < endings.length; i++) {
if (name.endsWith(endings[i]))
return endings[i];
}
return false;
}
function removeFromSet (target, name, value) {
const existing = target[name];
if (!existing)
return;
if (existing === value) {
delete target[name];
} else if (Array.isArray(existing)) {
const existingIndex = existing.indexOf(value);
if (existingIndex != -1) {
existing.splice(existingIndex, 1);
if (existing.length == 1) {
target[name] = existing[0];
}
}
}
}
function addOrSet (target, name, value, force) {
const existingValue = target[name];
const sort = (a, b) => {
const i1 =
typeof a === 'number' ? a :
typeof a === 'string' ? parseInt(a.substring(a.indexOf('№') + 1)) :
null;
const i2 =
typeof b === 'number' ? b :
typeof b === 'string' ? parseInt(b.substring(b.indexOf('№') + 1)) :
null;
if (i1 !== null && i2 !== null && i1 != i2) {
return i1 < i2 ? -1 : i1 > i2 ? 1 : 0;
} else {
return (a < b ? -1 : a > b ? 1 : 0);
}
};
if (existingValue === undefined || existingValue === null) {
target[name] = value;
return true;
} else if (Array.isArray(existingValue)) {
let found;