-
Notifications
You must be signed in to change notification settings - Fork 117
/
qbittorrent_mod.py
757 lines (691 loc) · 36.6 KB
/
qbittorrent_mod.py
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
from __future__ import annotations
import copy
import math
import os
from datetime import datetime
from flexget import plugin
from flexget.entry import Entry
from flexget.event import event
from flexget.task import Task
from loguru import logger
from .ptsites.client.qbittorrent_client import QBittorrentClientFactory, QBittorrentClient
from .ptsites.utils import net_utils
class QBittorrentModBase:
def __init__(self):
self.client = None
def prepare_config(self, config: dict) -> dict:
if isinstance(config, bool):
config = {'enabled': config}
config.setdefault('enabled', True)
config.setdefault('host', 'localhost')
config.setdefault('port', 8080)
config.setdefault('use_ssl', False)
config.setdefault('verify_cert', True)
return config
def create_client(self, config: dict) -> QBittorrentClient:
client = QBittorrentClientFactory().get_client(config)
return client
def on_task_start(self, task: Task, config: dict) -> None:
self.client = None
config = self.prepare_config(config)
if config['enabled']:
if task.options.test:
logger.info('Trying to connect to qBittorrent...')
self.client = self.create_client(config)
if self.client:
logger.info('Successfully connected to qBittorrent.')
else:
logger.error('It looks like there was a problem connecting to qBittorrent.')
class PluginQBittorrentModInput(QBittorrentModBase):
schema = {
'type': 'object',
'properties': {
'host': {'type': 'string'},
'use_ssl': {'type': 'boolean'},
'port': {'type': 'integer'},
'username': {'type': 'string'},
'password': {'type': 'string'},
'verify_cert': {'type': 'boolean'},
'server_state': {'oneOf': [{'type': 'boolean'}, {'type': 'string'}]},
'force_update': {'type': 'string', 'enum': ['uploading', 'active', 'all']},
'enabled': {'type': 'boolean'},
},
'additionalProperties': False
}
def prepare_config(self, config: dict) -> dict:
config = QBittorrentModBase.prepare_config(self, config)
return config
def on_task_input(self, task: Task, config: dict) -> list | None:
config = self.prepare_config(config)
if not config['enabled']:
return None
server_state = config.get('server_state')
if server_state:
entry = Entry(
title='qBittorrent Server State' if isinstance(server_state, bool) else server_state,
url=config.get('host')
)
entry['time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
entry['server_state'] = {}
try:
self.client = self.create_client(config)
entry['server_state'] = self.client.get_main_data_snapshot(id(task)).get('server_state')
entry['server_state']['flexget_connected'] = True
except plugin.PluginError:
entry['server_state']['flexget_connected'] = False
return [entry]
else:
self.client = self.create_client(config)
force_update = config.get('force_update', False)
return list(
self.client.get_main_data_snapshot(id(task), force_update=force_update).get('entry_dict').values())
class PluginQBittorrentMod(QBittorrentModBase):
schema = {
'type': 'object',
'properties': {
'host': {'type': 'string'},
'use_ssl': {'type': 'boolean'},
'port': {'type': 'integer'},
'username': {'type': 'string'},
'password': {'type': 'string'},
'verify_cert': {'type': 'boolean'},
'action': {
'type': 'object',
'properties': {
'add': {
'type': 'object',
'properties': {
'savepath': {'type': 'string'},
'cookie': {'type': 'string'},
'category': {'type': 'string'},
'tags': {'type': 'string'},
'skip_checking': {'type': 'boolean'},
'paused': {'type': 'string'},
'root_folder': {'type': 'string'},
'rename': {'type': 'string'},
'upLimit': {'type': 'integer'},
'dlLimit': {'type': 'integer'},
'autoTMM': {'type': 'boolean'},
'sequentialDownload': {'type': 'string'},
'firstLastPiecePrio': {'type': 'string'},
'tracker_options': {
'type': 'object',
'properties': {
'tag_by_tracker': {'type': 'boolean'},
'specific_trackers:': {
'type': 'array',
'items': {
'type': 'object',
'additionalProperties': {
'type': 'object',
'properties': {
'savepath': {'type': 'string'},
'cookie': {'type': 'string'},
'category': {'type': 'string'},
'tags': {'type': 'string'},
'skip_checking': {'type': 'boolean'},
'paused': {'type': 'string'},
'root_folder': {'type': 'string'},
'rename': {'type': 'string'},
'upLimit': {'type': 'integer'},
'dlLimit': {'type': 'integer'},
'autoTMM': {'type': 'boolean'},
'sequentialDownload': {'type': 'string'},
'firstLastPiecePrio': {'type': 'string'},
},
'additionalProperties': False,
},
'maxProperties': 1,
},
}
}
},
'reject_on': {
'type': 'object',
'properties': {
'bandwidth_limit': {'type': 'integer'},
'dl_speed': {
'oneOf': [
{'type': 'boolean'},
{'type': 'integer'},
{'type': 'number', 'minimum': 0.1, 'maximum': 0.9},
]
},
'dl_limit': {'oneOf': [{'type': 'boolean'}, {'type': 'integer'}]},
'up_bandwidth_limit': {'type': 'integer'},
'up_speed': {
'oneOf': [
{'type': 'boolean'},
{'type': 'integer'},
{'type': 'number', 'minimum': 0.1, 'maximum': 0.9},
]
},
'all': {'type': 'boolean'},
'remember': {'type': 'boolean', 'default': True}
}
}
}
},
'remove': {
'type': 'object',
'properties': {
'keeper': {
'type': 'object',
'properties': {
'keep_disk_space': {'type': 'integer'},
'check_reseed': {
'oneOf': [{'type': 'boolean'}, {'type': 'array', 'items': {'type': 'string'}}]},
'delete_files': {'type': 'boolean'},
'dl_limit_on_succeeded': {'type': 'integer'},
'alt_dl_limit_on_succeeded': {'type': 'integer'},
'dl_limit_interval': {'type': 'integer'}
},
},
'cleaner': {
'type': 'object',
'properties': {
'delete_files': {'type': 'boolean'}
}
}
},
"minProperties": 1,
"maxProperties": 1,
},
'resume': {
'type': 'object',
'properties': {
'recheck_torrents': {'type': 'boolean'}
}
},
'pause': {
'type': 'boolean'
},
'modify': {
'type': 'object',
'properties': {
'tag_by_tracker': {'type': 'boolean'},
'replace_trackers': {
'type': 'object',
'properties': {
}
}
}
},
'manage_conn': {
'type': 'object',
'properties': {
'min': {'type': 'integer'},
'max': {'type': 'integer'}
}
},
'limit_upload_by_tracker': {
'type': 'object',
'properties': {
'working': {'type': 'integer'},
'not_working': {'type': 'integer'}
}
},
'refresh_tracker': {
'type': 'boolean'
}
},
"minProperties": 1,
"maxProperties": 1,
},
'fail_html': {'type': 'boolean'},
},
'additionalProperties': False
}
def prepare_config(self, config: dict) -> dict:
config = super().prepare_config(config)
config.setdefault('fail_html', True)
return config
@plugin.priority(120)
def on_task_download(self, task: Task, config: dict) -> None:
config = self.prepare_config(config)
add_options = config.get('action', {}).get('add')
if not add_options or not task.accepted:
return
if not self.client:
self.client = self.create_client(config)
if self.client:
logger.debug('Successfully connected to qBittorrent.')
else:
raise plugin.PluginError("Couldn't connect to qBittorrent.")
main_data_snapshot = self.client.get_main_data_snapshot(id(task))
server_state = main_data_snapshot.get('server_state')
reject_on = add_options.get('reject_on', {})
remember_reject = reject_on.get('remember', True)
bandwidth_limit = reject_on.get('bandwidth_limit')
reject_on_dl_speed = reject_on.get('dl_speed')
reject_on_dl_limit = reject_on.get('dl_limit')
up_bandwidth_limit = reject_on.get('up_bandwidth_limit')
reject_on_up_speed = reject_on.get('up_speed')
reject_on_all = reject_on.get('all')
reject_reason = ''
up_rate_limit = server_state.get('up_rate_limit')
dl_rate_limit = server_state.get('dl_rate_limit')
if reject_on_up_speed:
if isinstance(reject_on_up_speed, float):
up_rate_limit = up_rate_limit if up_rate_limit else up_bandwidth_limit
reject_on_up_speed = int(up_rate_limit * reject_on_up_speed)
up_info_speed = server_state.get('up_info_speed')
if up_info_speed and up_info_speed > reject_on_up_speed:
reject_reason = 'up_speed: {:.2F} MiB > reject_on_up_speed: {:.2F} MiB'.format(
up_info_speed / (1024 * 1024), reject_on_up_speed / (1024 * 1024))
if reject_on_dl_limit and dl_rate_limit and dl_rate_limit < reject_on_dl_limit:
reject_reason = 'dl_limit: {:.2F} MiB < reject_on_dl_limit: {:.2F} MiB'.format(
dl_rate_limit / (1024 * 1024), reject_on_dl_limit / (1024 * 1024))
elif reject_on_dl_speed:
if isinstance(reject_on_dl_speed, float):
dl_rate_limit = dl_rate_limit if dl_rate_limit else bandwidth_limit
reject_on_dl_speed = int(dl_rate_limit * reject_on_dl_speed)
dl_info_speed = server_state.get('dl_info_speed')
if dl_info_speed and dl_info_speed > reject_on_dl_speed:
reject_reason = 'dl_speed: {:.2F} MiB > reject_on_dl_speed: {:.2F} MiB'.format(
dl_info_speed / (1024 * 1024), reject_on_dl_speed / (1024 * 1024))
if reject_on_all:
reject_reason = 'reject on all'
if 'download' not in task.config:
download = plugin.get('download', self)
headers = copy.deepcopy(task.requests.headers)
for entry in task.accepted:
if reject_reason:
entry.reject(reason=reject_reason, remember=remember_reject)
site_name = net_utils.get_site_name(entry.get('url'))
logger.info('reject {}, because: {}, site: {}', entry['title'], reject_reason, site_name)
continue
if entry.get('headers'):
task.requests.headers.update(entry['headers'])
else:
task.requests.headers.clear()
task.requests.headers = headers
if entry.get('cookie'):
task.requests.cookies.update(net_utils.cookie_str_to_dict(entry['cookie']))
else:
task.requests.cookies.clear()
download.get_temp_file(task, entry, handle_magnets=True, fail_html=config['fail_html'])
@plugin.priority(135)
def on_task_output(self, task: Task, config: dict) -> None:
config = self.prepare_config(config)
action_config = config.get('action', {})
if len(action_config) != 1:
raise plugin.PluginError('There must be and only one action')
# don't add when learning
if task.options.learn or not (task.accepted or action_config.get('remove')):
return
if not self.client:
self.client = self.create_client(config)
if self.client:
logger.debug('Successfully connected to qBittorrent.')
else:
raise plugin.PluginError("Couldn't connect to qBittorrent.")
(action_name, option), = action_config.items()
action = getattr(self, action_name + '_entries', None)
if action:
action(task, option)
else:
raise plugin.PluginError('Unknown action.')
def add_entries(self, task: Task, add_options: dict) -> None:
add_option_str_list = ['savepath',
'cookie',
'category',
'tags',
'skip_checking',
'paused',
'root_folder',
'rename',
'upLimit',
'dlLimit',
'autoTMM',
'sequentialDownload',
'firstLastPiecePrio']
for entry in task.accepted:
is_magnet = entry['url'].startswith('magnet:')
entry_add_option = add_options.copy()
if not is_magnet and (tracker_options := add_options.get('tracker_options')):
tags = []
if 'torrent' in entry:
torrent = entry['torrent']
trackers = torrent.trackers
for tracker in trackers:
site_name = net_utils.get_site_name(tracker)
tags.append(site_name)
if specific_trackers := tracker_options.get('specific_trackers'):
for specific_tracker in specific_trackers:
for tracker_name, tracker_option in specific_tracker.items():
if tracker_name == site_name:
net_utils.dict_merge(entry_add_option, tracker_option)
if tracker_options.get('tag_by_tracker'):
if original_tags := entry_add_option.get('tags'):
tags.append(original_tags)
entry_add_option['tags'] = ','.join(set(tags))
options = {}
for attr_str in add_option_str_list:
entry_attr = entry.get(attr_str)
add_options_attr = entry_add_option.get(attr_str)
if attr_str == 'tags' and entry_attr and add_options_attr:
attr = ','.join([entry_attr, add_options_attr])
else:
attr = entry_attr if entry_attr is not None else add_options_attr
if attr is not None:
options[attr_str] = attr
if options.get('autoTMM') and options.get('category') and options.get('savepath'):
del options['savepath']
logger.debug(f"url: {entry['url']}, options: {options}")
if not is_magnet:
if 'file' not in entry:
entry.fail('File missing?')
return
if not os.path.exists(entry['file']):
tmp_path = os.path.join(task.manager.config_base, 'temp')
logger.debug('entry: {}', entry)
logger.debug('temp: {}', ', '.join(os.listdir(tmp_path)))
entry.fail("Downloaded temp file '%s' doesn't exist!?" % entry['file'])
return
self.client.add_torrent_file(entry['file'], options)
else:
self.client.add_torrent_url(entry['url'], options)
def remove_entries(self, task: Task, remove_options: dict) -> None:
(mode_name, option), = remove_options.items()
mode = getattr(self, 'remove_entries_' + mode_name, None)
if mode:
mode(task, option)
else:
raise plugin.PluginError('Unknown mode.')
def remove_entries_keeper(self, task: Task, keeper_options: dict) -> None:
delete_files = keeper_options.get('delete_files')
check_reseed = keeper_options.get('check_reseed')
keep_disk_space = keeper_options.get('keep_disk_space')
dl_limit_interval = keeper_options.get('dl_limit_interval', 24 * 60 * 60)
main_data_snapshot = self.client.get_main_data_snapshot(id(task))
server_state = main_data_snapshot.get('server_state')
dl_rate_limit = server_state.get('dl_rate_limit')
free_space_on_disk = server_state.get('free_space_on_disk')
dl_limit_mode = 'dl_limit'
dl_limit_on_succeeded = keeper_options.get('dl_limit_on_succeeded', 0)
alt_dl_limit_on_succeeded = keeper_options.get('alt_dl_limit_on_succeeded', 0)
if server_state.get('use_alt_speed_limits'):
dl_limit_mode = 'alt_dl_limit'
dl_limit_on_succeeded = alt_dl_limit_on_succeeded
keep_disk_space = keep_disk_space * 1024 * 1024 * 1024
if keep_disk_space < free_space_on_disk:
if dl_limit_on_succeeded is not None:
dl_limit = math.floor(dl_limit_on_succeeded / 1024) * 1024
if dl_limit != dl_rate_limit:
self.client.set_application_preferences('{{"{}": {}}}'.format(dl_limit_mode, dl_limit))
logger.info("set {} to {} KiB/s", dl_limit_mode, dl_limit / 1024)
for entry in task.accepted:
entry.reject(reason='keep_disk_space < free_space_on_disk')
return
accepted_entry_hashes = []
delete_hashes = []
delete_size = 0
if not task.accepted:
self.calc_and_set_dl_limit(keep_disk_space, free_space_on_disk, delete_size, dl_limit_interval,
dl_limit_on_succeeded, dl_rate_limit, dl_limit_mode)
return
entry_dict = main_data_snapshot.get('entry_dict')
reseed_dict = main_data_snapshot.get('reseed_dict')
for entry in task.accepted:
accepted_entry_hashes.append(entry['torrent_info_hash'])
for entry_hash in accepted_entry_hashes:
if entry_hash in delete_hashes:
continue
if keep_disk_space < free_space_on_disk + delete_size:
entry_dict.get(entry_hash).reject(reason='keep_disk_space < free_space_on_disk')
continue
if not (server_entry := entry_dict.get(entry_hash)):
self.client.reset_rid()
save_path_with_name = server_entry.get('qbittorrent_save_path_with_name')
reseed_entry_list = reseed_dict.get(save_path_with_name)
check_hashes = []
torrent_hashes = []
torrent_size = 0
for reseed_entry in reseed_entry_list:
if reseed_entry['qbittorrent_completed'] != 0:
torrent_size = reseed_entry['qbittorrent_completed']
if isinstance(check_reseed, list):
site_names = []
for tracker in reseed_entry['qbittorrent_trackers']:
site_names.append(net_utils.get_site_name(tracker.get('url')))
if len(set(check_reseed) & set(site_names)) > 0:
check_hashes.append(reseed_entry['torrent_info_hash'])
else:
check_hashes.append(reseed_entry['torrent_info_hash'])
torrent_hashes.append(reseed_entry['torrent_info_hash'])
if check_reseed and not set(accepted_entry_hashes) >= set(check_hashes):
for torrent_hash in torrent_hashes:
entry_dict.get(torrent_hash).reject(
reason='torrents with the same save path are not all tested')
continue
elif keep_disk_space > free_space_on_disk + delete_size:
delete_size += torrent_size
self._build_delete_hashes(delete_hashes, torrent_hashes, entry_dict, keep_disk_space,
free_space_on_disk, delete_size)
self.calc_and_set_dl_limit(keep_disk_space, free_space_on_disk, delete_size, dl_limit_interval,
dl_limit_on_succeeded, dl_rate_limit, dl_limit_mode)
if len(delete_hashes) > 0:
self.client.delete_torrents('|'.join(delete_hashes), delete_files)
def calc_and_set_dl_limit(self, keep_disk_space, free_space_on_disk, delete_size, dl_limit_interval,
dl_limit_on_succeeded, dl_rate_limit, dl_limit_mode):
if keep_disk_space > free_space_on_disk + delete_size:
dl_limit = (free_space_on_disk + delete_size) / dl_limit_interval
if dl_limit_on_succeeded and dl_limit > dl_limit_on_succeeded:
dl_limit = dl_limit_on_succeeded
dl_limit = math.floor(dl_limit / 1024) * 1024
if dl_limit != dl_rate_limit:
self.client.set_application_preferences('{{"{}": {}}}'.format(dl_limit_mode, dl_limit))
logger.warning("not enough disk space, set {} to {} KiB/s", dl_limit_mode, dl_limit / 1024)
def _build_delete_hashes(self, delete_hashes, torrent_hashes, all_entry_map, keep_disk_space, free_space_on_disk,
delete_size):
delete_hashes.extend(torrent_hashes)
logger.info('keep_disk_space: {:.2F} GiB, free_space_on_disk: {:.2f} GiB, delete_size: {:.2f} GiB',
keep_disk_space / (1024 * 1024 * 1024), free_space_on_disk / (1024 * 1024 * 1024),
delete_size / (1024 * 1024 * 1024))
entries = []
for torrent_hash in torrent_hashes:
entry = all_entry_map.get(torrent_hash)
entry.accept(reason='torrent with the same save path are all pass tested')
entries.append(entry)
entries.sort(key=lambda e: e['qbittorrent_last_activity'], reverse=True)
for entry in entries:
logger.info(
'{}, size: {:.2f} GiB, seeding_time: {:.2f} h, share_ratio: {:.2f}, last_activity: {}, tags: {}',
entry['title'],
entry['qbittorrent_completed'] / (1024 * 1024 * 1024),
entry['qbittorrent_seeding_time'] / (60 * 60),
entry['qbittorrent_share_ratio'],
entry['qbittorrent_last_activity'],
entry['qbittorrent_tags'])
def remove_entries_cleaner(self, task: Task, cleaner_options: dict) -> None:
delete_files = cleaner_options.get('delete_files')
delete_hashes = []
delete_files_hashes = []
accepted_entry_hashes = []
main_data_snapshot = self.client.get_main_data_snapshot(id(task))
entry_dict = main_data_snapshot.get('entry_dict')
reseed_dict = main_data_snapshot.get('reseed_dict')
for entry in task.accepted:
accepted_entry_hashes.append(entry['torrent_info_hash'])
for entry_hash in accepted_entry_hashes:
if entry_hash in delete_hashes or entry_hash in delete_files_hashes:
continue
server_entry = entry_dict.get(entry_hash)
if not server_entry:
self.client.reset_rid()
continue
save_path_with_name = server_entry.get('qbittorrent_save_path_with_name')
reseed_entry_list = reseed_dict.get(save_path_with_name)
torrent_hashes = []
for reseed_entry in reseed_entry_list:
torrent_hashes.append(reseed_entry['torrent_info_hash'])
if not set(accepted_entry_hashes) >= set(torrent_hashes):
delete_hashes.extend(set(accepted_entry_hashes) & set(torrent_hashes))
else:
delete_files_hashes.extend(torrent_hashes)
if len(delete_hashes) > 0:
self.client.delete_torrents('|'.join(delete_hashes), False)
self.print_clean_log(entry_dict, delete_hashes, False)
if len(delete_files_hashes) > 0:
self.client.delete_torrents('|'.join(delete_files_hashes), delete_files)
self.print_clean_log(entry_dict, delete_files_hashes, delete_files)
def print_clean_log(self, entry_dict: dict, hashes: list[str], delete_files) -> None:
for torrent_hash in hashes:
entry = entry_dict.get(torrent_hash)
logger.info(
'{}, size: {:.2f} GiB, seeding_time: {:.2f} h, share_ratio: {:.2f}, last_activity: {}, tracker_msg: {}, tags: {}, delete_files: {}',
entry['title'],
entry['qbittorrent_completed'] / (1024 * 1024 * 1024),
entry['qbittorrent_seeding_time'] / (60 * 60),
entry['qbittorrent_share_ratio'],
entry['qbittorrent_last_activity'],
entry['qbittorrent_tracker_msg'],
entry['qbittorrent_tags'],
delete_files
)
def resume_entries(self, task: Task, resume_options: dict) -> None:
recheck_torrents = resume_options.get('recheck_torrents')
main_data_snapshot = self.client.get_main_data_snapshot(id(task))
reseed_dict = main_data_snapshot.get('reseed_dict')
hashes = []
recheck_hashes = []
if recheck_torrents:
for entry in task.accepted:
save_path_with_name = entry['qbittorrent_save_path_with_name']
reseed_entry_list = reseed_dict.get(save_path_with_name)
resume = False
for reseed_entry in reseed_entry_list:
seeding = 'up' in reseed_entry['qbittorrent_state'].lower() and reseed_entry[
'qbittorrent_state'] != 'pausedUP'
if seeding:
hashes.append(entry['torrent_info_hash'])
logger.info('{}', entry['title'])
resume = True
break
if not resume and entry['qbittorrent_state'] != 'checkingUP':
entry.reject(reason='can not find seeding torrent in same save path')
recheck_hashes.append(entry['torrent_info_hash'])
if len(recheck_hashes) > 0:
logger.info('recheck {}', recheck_hashes)
self.client.recheck_torrents('|'.join(recheck_hashes))
else:
for entry in task.accepted:
hashes.append(entry['torrent_info_hash'])
self.client.resume_torrents('|'.join(hashes))
def pause_entries(self, task: Task, pause_options: dict) -> None:
if not pause_options:
return
hashes = []
for entry in task.accepted:
hashes.append(entry['torrent_info_hash'])
logger.info('pause: {}', entry['title'])
self.client.pause_torrents('|'.join(hashes))
def modify_entries(self, task: Task, modify_options: dict) -> None:
tag_by_tracker = modify_options.get('tag_by_tracker')
replace_trackers = modify_options.get('replace_trackers')
for entry in task.accepted:
tags = entry.get('qbittorrent_tags')
tags_modified = []
torrent_trackers = entry.get('qbittorrent_trackers')
for tracker in torrent_trackers:
if tag_by_tracker:
site_name = net_utils.get_site_name(tracker.get('url'))
if site_name and site_name not in tags and site_name not in tags_modified:
tags_modified.append(site_name)
if replace_trackers:
for old_str, new_str in replace_trackers.items():
tracker_url = tracker.get('url')
if tracker_url.startswith(old_str):
if new_str:
if old_str in new_str:
raise plugin.PluginError(f'{old_str} in {new_str}, this may cause a loop problem')
tracker_url_new = f"{new_str}{tracker_url[len(old_str):]}"
self.client.edit_trackers(entry.get('torrent_info_hash'), tracker_url, tracker_url_new)
logger.info('{} update tracker {}', entry.get('title'), tracker_url_new)
else:
logger.info('{} remove tracker {}', entry.get('title'), tracker_url)
self.client.remove_trackers(entry.get('torrent_info_hash'), tracker_url)
if tags_modified:
self.client.add_torrent_tags(entry['torrent_info_hash'], ','.join(tags_modified))
logger.info(f"{entry.get('title')} add tags {tags_modified}")
def manage_conn_entries(self, task: Task, manage_conn_options: dict) -> None:
min_conn = manage_conn_options.get('min')
max_conn = manage_conn_options.get('max')
for entry in task.accepted:
step = entry.get('step')
if not step:
return
server_state = entry.get('server_state')
server_queued_io_jobs = server_state.get('queued_io_jobs')
server_total_peer_connections = server_state.get('total_peer_connections')
application_preferences = self.client.get_application_preferences()
max_connect = application_preferences.get('max_connec')
if max_connect == -1:
max_connect = float('inf')
if (step > 0 and max_connect <= server_total_peer_connections) or step < 0:
max_connect_changed = server_total_peer_connections + step
if max_connect_changed < min_conn:
max_connect_changed = min_conn
elif max_connect_changed > max_conn:
max_connect_changed = max_conn
self.client.set_application_preferences('{{"max_connec": {}}}'.format(max_connect_changed))
logger.debug('queued_io_jobs: {} , total_peer_connections: {}, set max_connec to {}',
server_queued_io_jobs, server_total_peer_connections, max_connect_changed)
def limit_upload_by_tracker_entries(self, task: Task, limit_when_not_working_options: dict) -> None:
working_speed = limit_when_not_working_options.get('working')
not_working_speed = limit_when_not_working_options.get('not_working')
working_hashes = []
not_working_hashes = []
for entry in task.accepted:
torrent_trackers = entry.get('qbittorrent_trackers')
is_working = False
updating = False
for tracker in torrent_trackers:
status = tracker.get('status')
if status == 2:
is_working = True
elif status == 3:
updating = True
if updating:
continue
up_limit = 0 if entry['qbittorrent_up_limit'] == -1 else entry['qbittorrent_up_limit']
if is_working:
entry_working = entry.get('working') if entry.get('working') else working_speed
if up_limit != entry_working:
if entry.get('working'):
self.client.set_torrent_upload_limit(entry['torrent_info_hash'], entry_working)
else:
working_hashes.append(entry['torrent_info_hash'])
logger.debug(
f'{entry["title"]} tags: {entry["qbittorrent_tags"]} tracker is working, set torrent upload limit to {entry_working} B/s')
elif up_limit != not_working_speed:
not_working_hashes.append(entry['torrent_info_hash'])
logger.debug(
f'{entry["title"]} tags: {entry["qbittorrent_tags"]} tracker is not working, set torrent upload limit to {not_working_speed} B/s')
if working_hashes:
self.client.set_torrent_upload_limit('|'.join(working_hashes), working_speed)
if not_working_hashes:
self.client.set_torrent_upload_limit('|'.join(not_working_hashes), not_working_speed)
def refresh_tracker_entries(self, task: Task, refresh_tracker_options: dict) -> None:
prefix = 'refresh:'
for entry in task.accepted:
torrent_trackers = entry.get('qbittorrent_trackers')
for tracker in torrent_trackers:
tracker_url = tracker.get('url')
if tracker_url.startswith(prefix):
self.client.edit_trackers(entry.get('torrent_info_hash'), tracker_url, tracker_url[len(prefix):])
else:
self.client.edit_trackers(entry.get('torrent_info_hash'), tracker_url, prefix + tracker_url)
self.client.edit_trackers(entry.get('torrent_info_hash'), prefix + tracker_url, tracker_url)
def on_task_learn(self, task: Task, config: dict) -> None:
""" Make sure all temp files are cleaned up when entries are learned """
# If download plugin is enabled, it will handle cleanup.
if 'download' not in task.config:
download = plugin.get('download', self)
download.cleanup_temp_files(task)
on_task_abort = on_task_learn
@event('plugin.register')
def register_plugin() -> None:
plugin.register(PluginQBittorrentMod, 'qbittorrent_mod', api_ver=2)
plugin.register(PluginQBittorrentModInput, 'from_qbittorrent_mod', api_ver=2)