-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathindex.ts
799 lines (624 loc) · 22.8 KB
/
index.ts
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
import { isIPv6, isIPv4 } from 'net'
import { request_page, request_json, fwrite, delay, log_line, inspect, start, log_section, fread } from 'xshell'
import QQWRY from 'lib-qqwry'
export * from './resume-data'
export class Peer {
country: string
ip: string
reverse_dns: string
utp: number
port: number
client: string
flags: string
/** 0 - 1000 */
progress: number
download_speed: number
upload_speed: number
requests_out: number
requests_in: number
waited: Date
uploaded: number
downloaded: number
hash_error: number
/** 用户 */
peer_download_speed: number
max_upload_speed: number
max_download_speed: number
queued: number
inactive: number
relevance: number
torrent: Torrent
should_block: boolean
constructor (raw_data: (string | number)[], torrent: Torrent) {
this.torrent = torrent
let [
country,
ip,
reverse_dns,
utp,
port,
client,
flags,
progress,
download_speed,
upload_speed,
requests_out,
requests_in,
waited,
uploaded,
downloaded,
hash_error,
peer_download_speed,
max_upload_speed,
max_download_speed,
queued,
inactive,
relevance
]: any[] = raw_data
waited = new Date(waited * 1000)
Object.assign(this, {
country,
ip,
reverse_dns,
utp,
port,
client,
flags,
progress,
download_speed,
upload_speed,
requests_out,
requests_in,
waited,
uploaded,
downloaded,
hash_error,
peer_download_speed,
max_upload_speed,
max_download_speed,
queued,
inactive,
relevance
})
this.should_block = (() => {
if (!/-XL0012-|Xunlei|^7\.|aria2|Xfplay|dandanplay|FDM|go\.torrent|Mozilla/i.test(this.client)) return false
const [state] = this.torrent.state
if (state === '做种')
return this.upload_speed > 10 * 2 ** 10 // 我方上传速度大于 10 KB/s
if (state === '下载')
return this.uploaded > this.downloaded * 10 + 5 * 2**20 // 累计吸血量大于 `10 × 累计上传量 + 5MB`
return false
})()
}
to_str () {
return '' +
/* 名称 */ this.flags.pad(8) + ' ' +
/* Client UA */ this.format_client() + ' ' +
/* IP:PORT IP 信息 */ this.format_ipinfo() +
/* 下载速度 */ this.format_download_speed() + ' / ' + /* 上传速度 */ this.format_upload_speed() + ' | ' +
/* 累计下载 */ this.format_downloaded() + ' / ' + /* 累计上传 */ this.uploaded.to_fsize_str().pad(12) + ' ' +
/* 种子名称 */ this.torrent.name.limit(80)
}
format_client () {
if (this.client.includes('-XL0012-'))
return ( this.client.slice(0, '-XL0012-'.length) + ' ***' ).limit(20)
return this.client.limit(20).replaceAll('\u0007', '')
}
format_download_speed () {
const s = ( this.torrent.state[0] === '做种' ? '' : this.download_speed.to_fsize_str() + '/s' ).pad(12)
return ( this.download_speed > 50 * 2 ** 10 ? s.magenta : s )
}
format_upload_speed () {
const s = (this.upload_speed.to_fsize_str() + '/s').pad(12)
return this.upload_speed > 200 * 2 ** 10 ? s.green : s
}
format_downloaded () {
return ( this.torrent.state[0] === '做种' ? '' : this.downloaded.to_fsize_str() ).pad(10)
}
format_ipinfo () {
const ip_width = 24
const info_width = 50
return isIPv6(this.ip) ?
( this.ip.bracket('SQUARE') + ':' + this.port ).pad(ip_width + info_width)
:
( this.ip + ':' + this.port ).pad(ip_width) + get_ip_info(this.ip).limit(info_width)
}
[inspect.custom] () {
return inspect({
...this,
should_block: this.should_block,
progress: `${this.progress / 10}%`,
uploaded: this.uploaded.to_fsize_str(),
downloaded: this.downloaded.to_fsize_str(),
upload_speed: `${this.upload_speed.to_fsize_str()}/s`,
download_speed: `${this.download_speed.to_fsize_str()}/s`,
peer_download_speed: `${this.peer_download_speed.to_fsize_str()}/s`,
max_upload_speed: `${this.max_upload_speed.to_fsize_str()}/s`,
max_download_speed: `${this.max_download_speed.to_fsize_str()}/s`,
waited: this.waited.to_str(),
}, {
omit: [
'torrent',
... this.utp === 0 ? ['utp'] : [ ],
'relevance',
... this.torrent.state[0] === '做种' ? ['download_speed'] : [ ],
]
})
}
}
export enum Status {
STARTED = 1 << 0,
CHECKING = 1 << 1,
ERROR = 1 << 4,
PAUSED = 1 << 5,
QUEUED = 1 << 6,
}
export class Torrent {
hash: string
status: number
name: string
/** bytes */
size: number
/** 0 - 1000 */
progress: number
/** uTorrent 累计下载量 bytes */
downloaded: number
/** uTorrent 累积上传量 bytes */
uploaded: number
/** 需除以 1000 ? */
ratio: number
/** bytes/second */
upload_speed: number
/** bytes/second */
download_speed: number
/** estimated time of arrival (seconds) */
time_remaining: number
label: string
peers_connected: number
peers_in_swarm: number
seeds_connected: number
seeds_in_swarm: number
availability: number
/** -1 表示未在队列中 */
queue_position: number
/** 剩余大小 */
remaining: number
download_url: string
rss_feed_url: string
status_message: string
stream_id: string
date_added: Date
date_completed: Date
app_update_url: string
save_path: string
/** status 按位与 Status 相与并结合 progress 信息得到 */
state: [ '下载' | '做种' | '暂停' | '停止' | '完成' | '检查' | '错误' | '排队', string ]
utorrent: UTorrent
peers: Peer[]
constructor (raw_data: (string | number)[], utorrent: UTorrent) {
this.utorrent = utorrent
let [
hash,
status,
name,
size,
progress,
downloaded,
uploaded,
ratio,
upload_speed,
download_speed,
time_remaining,
label,
peers_connected,
peers_in_swarm,
seeds_connected,
seeds_in_swarm,
availability,
queue_position,
remaining,
download_url,
rss_feed_url,
status_message,
stream_id,
date_added,
date_completed,
app_update_url,
save_path
]: any[] = raw_data
this.state = status & Status.PAUSED ?
[ '暂停', status & Status.CHECKING ? `已检查 ${ progress / 10 }` : '下载' ]
: status & Status.STARTED ?
[ progress === 1000 ? '做种' : '下载', status & Status.QUEUED ? '' : '强制' ]
: status & Status.CHECKING ?
[ '检查', `已检查 ${ progress / 10 }` ]
: status & Status.ERROR ?
[ '错误', status_message ]
: status & Status.QUEUED ?
[ '排队', progress === 1000 ? '做种' : '下载' ]
: progress === 1000 ?
[ '完成', '' ]
:
[ '停止', '' ]
date_added = new Date(date_added * 1000)
date_completed = new Date(date_completed * 1000)
save_path = (save_path as string).to_slash()
Object.assign(this, {
hash,
status,
name,
size,
progress,
downloaded,
uploaded,
ratio,
upload_speed,
download_speed,
time_remaining,
label,
peers_connected,
peers_in_swarm,
seeds_connected,
seeds_in_swarm,
availability,
queue_position,
remaining,
download_url,
rss_feed_url,
status_message,
stream_id,
date_added,
date_completed,
app_update_url,
save_path
})
}
async get_peers (): Promise<Peer[]> {
const result = await this.utorrent.rpc({
params: {
action: 'getpeers',
hash: this.hash
}
})
return this.peers = result.peers[1].map( peer => new Peer(peer, this))
}
[inspect.custom] () {
return inspect({
...this,
... this.peers ? { peers: this.peers.length } : { },
size: this.size.to_fsize_str(),
progress: this.progress / 10 + '%',
remaining: this.remaining.to_fsize_str(),
downloaded: this.downloaded.to_fsize_str(),
uploaded: this.uploaded.to_fsize_str(),
upload_speed: this.upload_speed.to_fsize_str() + '/s',
download_speed: this.download_speed.to_fsize_str() + '/s',
time_remaining: Math.ceil(this.time_remaining / 60) + ' min',
date_added: this.date_added.to_str(),
date_completed: this.date_completed.to_str(),
save_path: this.save_path,
}, {
omit: [
'utorrent', 'status', 'ratio', 'label', 'availability', 'queue_position', 'download_url', 'rss_feed_url', 'stream_id', 'app_update_url',
... (() => {
if (this.state[0] === '做种') return ['progress', 'downloaded', 'download_speed', 'time_remaining', 'seeds_connected', 'remaining', 'status_message']
if (this.state[0] === '下载') return []
return ['peers', 'upload_speed', 'download_speed', 'time_remaining', 'peers_connected', 'peers_in_swarm', 'seeds_connected', 'seeds_in_swarm']
})()
]
})
}
to_str () {
return '' +
/* 种子名称 */ this.name.limit(100) + ' ' +
/* 状态 */ this.format_state() + ' ' +
/* 进度 */ (this.state[0] !== '做种' ? (this.progress / 10 + '%') : '').pad(6) + ' ' +
/* 下载速度 */ this.format_download_speed() + ' / ' + /* 上传速度 */ this.format_upload_speed() + ' | ' +
/* 累计上传大小 */ this.uploaded.to_fsize_str().pad(8) + ' ' +
/* 已连接种子数 (总种子数) */ ( this.seeds_connected.toString().pad(3) + '(' + this.seeds_in_swarm + ')' ).pad(7) + '/ ' +
/* 已连接用户数 (总用户数) */ ( this.peers_connected.toString().pad(3) + '(' + this.peers_in_swarm + ')' ).pad(8) + ' ' +
/* 剩余时间 */ this.format_time_remaining()
}
format_upload_speed () {
const s = `${ this.upload_speed.to_fsize_str()}/s`.pad(12)
return this.upload_speed > 500 * 2**10 ? s.green : s
}
format_download_speed () {
const width = 12
if (this.state[0] !== '下载') return ''.pad(width)
const s = `${ this.download_speed.to_fsize_str() }/s`.pad(width)
return ( this.download_speed > 100 * 2**10 ? s.magenta : s.yellow )
}
format_state () {
const s = ( this.state[0] + ( this.state[1] ? ` (${ this.state[1] })` : '' ) ).pad(10)
return this.state[0] === '下载' ? s.yellow : s
}
format_time_remaining () {
if (this.state[0] !== '下载') return ''
const hours = Math.floor( this.time_remaining / 3600 )
const minutes = Math.ceil( this.time_remaining / 60)
if (hours === -1) return '-'
if (hours) return ( hours + ' 小时' ).yellow
if (minutes) return ( minutes + ' 分钟' ).yellow
return ''
}
}
export class UTorrent {
root_url: string
username: string
password: string
fp_ipfilter: string
/** 启动时 ipfilter 中已有的数据 */
static_ipfilter: string
/** 检测 peers 并屏蔽的时间间隔 */
interval: number
/** 间隔 interval 秒自动重置当前时间间隔内被动态屏蔽的 IP */
interval_reset: number
state: 'INIT' | 'IDLE' | 'RUNNING' = 'INIT'
state_resetting: 'INIT' | 'IDLE' | 'RUNNING' = 'INIT'
print: {
/** ['下载'] */
torrents: '下载' | '做种' | '所有' | boolean
/** [true] */
peers: boolean
} = {
torrents: '所有',
peers: true
}
token: string
blocked_ips = new Set<string>()
torrents: Torrent[]
static async launch (exe: string) {
start(exe, [], { detached: true })
await delay(1000 * 20)
}
private constructor (data: Partial<UTorrent>) {
Object.assign(this, data)
}
static async connect (
options: {
root_url: string
username: string
password: string
fp_ipfilter: string
interval: number
interval_reset: number
/** print?: true */
print?: boolean | {
/** ['下载'] */
torrents: '下载' | '做种' | '所有' | boolean
/** [true] */
peers: boolean
}
}
) {
let utorrent = new UTorrent({
...options,
static_ipfilter: await fread(options.fp_ipfilter),
blocked_ips: new Set(),
print: (() => {
if (!('print' in options)) return { torrents: true, peers: true }
if (typeof options.print === 'boolean') return { torrents: options.print, peers: options.print }
return options.print
})()
}
)
await utorrent.get_token()
return utorrent
}
/** get token */
async get_token () {
const $ = await request_page(`${this.root_url}token.html`, {
auth: {
username: this.username,
password: this.password
}
})
this.token = $('#token').text()
}
async rpc ({ api = '', params, method = 'GET' }: {api?: string, params?: Record<string, any>, method?: 'GET' | 'POST'} = { }) {
return await request_json(this.root_url + api, {
method,
queries: {
token: this.token,
...params
},
auth: {
username: this.username,
password: this.password
}
})
}
async get_torrents (): Promise<Torrent[]> {
return this.torrents = (await this.rpc({ params: { list: 1 } })).torrents.map( (t: (string | number)[]) => new Torrent(t, this))
}
async get_peers (torrents?: Torrent[]): Promise<Peer[]> {
if (!torrents)
torrents = await this.get_torrents()
return (await Promise.all(
torrents
.filter( torrent => torrent.state[0] === '下载' || torrent.state[0] === '做种')
.map( async torrent => await torrent.get_peers()))
).flat()
}
async print_peers (peers?: Peer[], { limit }: { limit?: number } = { }) {
if (!peers)
peers = await this.get_peers()
peers
.sort( (a, b) => - (
((a.should_block ? 1 : 0) * 2**30 + a.download_speed * 10 + a.upload_speed) -
((b.should_block ? 1 : 0) * 2**30 + b.download_speed * 10 + b.upload_speed)
))
.filter( (peer, i) => peer.should_block || (peer.upload_speed + peer.download_speed) > 5 * 2**10 && (limit ? i < limit : true) )
.forEach( peer => {
const s = peer.to_str()
console.log( peer.should_block ? s.red : s)
})
}
async print_torrents ({
torrents,
filter = torrent => torrent.state[0] === '下载' || (torrent.state[0] === '做种' ? torrent.upload_speed > 10 * 2**10 : false)
}: {
torrents?: Torrent[]
filter?: (torrent: Torrent) => boolean
} = { }) {
if (!torrents)
torrents = await this.get_torrents()
torrents
.filter(filter)
.filter( torrent => this.print.torrents && ( this.print.torrents === '所有' || this.print.torrents === torrent.state[0]))
.sort( (a, b) => - (
((a.state[0] === '下载' ? 1 : 0) * 2**30 + a.download_speed * 10 + a.upload_speed) -
((b.state[0] === '下载' ? 1 : 0) * 2**30 + b.download_speed * 10 + b.upload_speed)
))
.forEach( torrent => {
console.log(torrent.to_str())
})
}
async print_blockeds () {
this.blocked_ips.forEach( ip => {
console.log(ip.pad(20) + get_ip_info(ip))
})
}
async block_peers (torrents?: Torrent[]) {
if (!torrents)
torrents = await this.get_torrents()
const peers = await this.get_peers(torrents.filter( torrent => torrent.download_speed + torrent.upload_speed > 20 * 2**10))
const peers2block = peers.filter( peer => peer.should_block)
if (this.print.peers)
await this.print_peers(peers, { limit: 50 })
if (!peers2block.length) return
peers2block.forEach( peer => {
this.blocked_ips.add(peer.ip)
})
await fwrite(
this.fp_ipfilter,
(
this.static_ipfilter + '\n' +
[...this.blocked_ips].join_lines() + '\n'
),
{ print: Boolean(this.print.peers || this.print.torrents) }
)
await this.reload_ipfilter()
return peers2block
}
async reload_ipfilter () {
return await this.rpc({
params: {
action: 'setsetting',
s: 'ipfilter.enable',
v: '1'
}
})
}
async reset_ipfilter () {
this.blocked_ips = new Set()
await fwrite(this.fp_ipfilter, '')
await this.reload_ipfilter()
}
async reset_blocked_ips () {
await fwrite(this.fp_ipfilter, this.static_ipfilter)
log_section('reset dynamic blocked ips', { time: true })
this.blocked_ips = new Set()
await utorrent.reload_ipfilter()
}
find_torrent (name_pattern: string | RegExp) {
if (typeof name_pattern === 'string')
name_pattern = new RegExp(name_pattern, 'i')
return this.torrents.find(torrent => (name_pattern as RegExp).test(torrent.name))
}
async start_blocking () {
await this.get_token()
if (this.state === 'RUNNING') return
if (this.state === 'IDLE') {
this.state = 'RUNNING'
return
}
// this.state === 'INIT'
this.state = 'RUNNING'
// start blocking
;(async () => {
while (this.state === 'RUNNING') {
if (this.print.torrents || this.print.peers)
console.log('\n\n\n' + new Date().to_str())
try {
if (this.print.torrents) {
await this.print_torrents()
log_line(200)
await this.block_peers(this.torrents)
} else
await this.block_peers()
} catch (error) {
this.state = 'INIT'
throw error
}
await delay(this.interval)
}
if (this.state === 'IDLE')
this.state = 'INIT'
})()
await this.start_resetting_blocked_ips()
}
async start_resetting_blocked_ips () {
if (this.state_resetting === 'RUNNING') return
if (this.state_resetting === 'IDLE') {
this.state_resetting = 'RUNNING'
return
}
// this.state_resetting === 'INIT'
this.state_resetting = 'RUNNING'
;(async () => {
while (true) {
await delay(this.interval_reset)
if (this.state_resetting !== 'RUNNING') break
await this.reset_blocked_ips()
}
if (this.state_resetting === 'IDLE')
this.state_resetting = 'INIT'
})()
}
async stop_blocking () {
if (this.state === 'INIT') {
console.log('blocking hasn\'t started')
return
}
if (this.state === 'IDLE') {
console.log('blocking already stopped')
return
}
// this.state === 'RUNNING'
this.state = 'IDLE'
await this.reset_blocked_ips()
console.log('uTorrent stopped blocking')
}
hide_display () {
this.print = {
torrents: false,
peers: false
}
}
show_display () {
this.print = {
torrents: '所有',
peers: true
}
}
}
const qqwry = new QQWRY(true)
function get_ip_info (ip: string) {
/*
const data = await request_market_api({
url: 'https://service-jr977f7k-1301115409.gz.apigw.tencentcs.com/release/',
secret_id: 'AKIDBggAWhLvbewlabivKmwTKs5ZGzm37tbZ642',
secret_key: 'aL3TRtUyWtDHcUlA8US467CMT4hn87JE64XX7E0U',
queries: { ip: '' }
})
*/
if (!isIPv4(ip))
return ''
const { Country, Area } = qqwry.searchIP(ip)
const country = Country.trim().replace('浙金省', '浙江省').space()
const area = Area.trim().rm('CZ88.NET').space()
return country + (area ? '/' + area : '')
}
export default UTorrent