Repository navigation
Expand file tree
/
Copy pathclients.py
More file actions
1857 lines (1583 loc) · 90.4 KB
/
Copy pathclients.py
File metadata and controls
1857 lines (1583 loc) · 90.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
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
# -*- coding: utf-8 -*-
from torf import Torrent
import xmlrpc.client
import bencode
import os
import qbittorrentapi
from deluge_client import DelugeRPCClient
import transmission_rpc
import base64
import errno
import asyncio
import ssl
import shutil
import time
from src.console import console
import re
import platform
class Clients():
"""
Add to torrent client
"""
def __init__(self, config):
self.config = config
pass
async def add_to_client(self, meta, tracker):
torrent_path = f"{meta['base_dir']}/tmp/{meta['uuid']}/[{tracker}].torrent"
if meta.get('no_seed', False) is True:
console.print("[bold red]--no-seed was passed, so the torrent will not be added to the client")
console.print("[bold yellow]Add torrent manually to the client")
return
if os.path.exists(torrent_path):
torrent = Torrent.read(torrent_path)
else:
return
if meta.get('client', None) is None:
default_torrent_client = self.config['DEFAULT']['default_torrent_client']
else:
default_torrent_client = meta['client']
if meta.get('client', None) == 'none':
return
if default_torrent_client == "none":
return
client = self.config['TORRENT_CLIENTS'][default_torrent_client]
torrent_client = client['torrent_client']
local_path, remote_path = await self.remote_path_map(meta)
if meta['debug']:
console.print(f"[bold green]Adding to {torrent_client}")
if torrent_client.lower() == "rtorrent":
self.rtorrent(meta['path'], torrent_path, torrent, meta, local_path, remote_path, client, tracker)
elif torrent_client == "qbit":
await self.qbittorrent(meta['path'], torrent, local_path, remote_path, client, meta['is_disc'], meta['filelist'], meta, tracker)
elif torrent_client.lower() == "deluge":
if meta['type'] == "DISC":
path = os.path.dirname(meta['path']) # noqa F841
self.deluge(meta['path'], torrent_path, torrent, local_path, remote_path, client, meta)
elif torrent_client.lower() == "transmission":
self.transmission(meta['path'], torrent, local_path, remote_path, client, meta)
elif torrent_client.lower() == "watch":
shutil.copy(torrent_path, client['watch_folder'])
return
async def find_existing_torrent(self, meta):
if meta.get('client', None) is None:
default_torrent_client = self.config['DEFAULT']['default_torrent_client']
else:
default_torrent_client = meta['client']
if meta.get('client', None) == 'none' or default_torrent_client == 'none':
return None
client = self.config['TORRENT_CLIENTS'][default_torrent_client]
torrent_storage_dir = client.get('torrent_storage_dir')
torrent_client = client.get('torrent_client', '').lower()
mtv_config = self.config['TRACKERS'].get('MTV')
if isinstance(mtv_config, dict):
prefer_small_pieces = mtv_config.get('prefer_mtv_torrent', False)
else:
prefer_small_pieces = False
best_match = None # Track the best match for fallback if prefer_small_pieces is enabled
# Iterate through pre-specified hashes
for hash_key in ['torrenthash', 'ext_torrenthash']:
hash_value = meta.get(hash_key)
if hash_value:
# If no torrent_storage_dir defined, use saved torrent from qbit
extracted_torrent_dir = os.path.join(meta.get('base_dir', ''), "tmp", meta.get('uuid', ''))
if torrent_storage_dir:
torrent_path = os.path.join(torrent_storage_dir, f"{hash_value}.torrent")
else:
# Fetch from qBittorrent since we don't have torrent_storage_dir
console.print(f"[yellow]Fetching .torrent file from qBittorrent for hash: {hash_value}")
try:
qbt_client = qbittorrentapi.Client(
host=client['qbit_url'],
port=client['qbit_port'],
username=client['qbit_user'],
password=client['qbit_pass'],
VERIFY_WEBUI_CERTIFICATE=client.get('VERIFY_WEBUI_CERTIFICATE', True)
)
qbt_client.auth_log_in()
# Retrieve the .torrent file
torrent_file_content = qbt_client.torrents_export(torrent_hash=hash_value)
if not torrent_file_content:
console.print(f"[bold red]qBittorrent returned an empty response for hash {hash_value}")
continue # Skip to the next hash
# Save the .torrent file
os.makedirs(extracted_torrent_dir, exist_ok=True)
torrent_path = os.path.join(extracted_torrent_dir, f"{hash_value}.torrent")
with open(torrent_path, "wb") as f:
f.write(torrent_file_content)
console.print(f"[green]Successfully saved .torrent file: {torrent_path}")
except qbittorrentapi.APIError as e:
console.print(f"[bold red]Failed to fetch .torrent from qBittorrent for hash {hash_value}: {e}")
continue
# Validate the .torrent file
valid, resolved_path = await self.is_valid_torrent(meta, torrent_path, hash_value, torrent_client, client, print_err=True)
if valid:
console.print(f"[green]Found a valid torrent: [bold yellow]{hash_value}")
return resolved_path
# Search the client if no pre-specified hash matches
if torrent_client == 'qbit' and client.get('enable_search'):
try:
found_hash = await self.search_qbit_for_torrent(meta, client)
except KeyboardInterrupt:
console.print("[bold red]Search cancelled by user")
found_hash = None
except Exception as e:
console.print(f"[bold red]Error searching qBittorrent: {e}")
found_hash = None
if found_hash:
extracted_torrent_dir = os.path.join(meta.get('base_dir', ''), "tmp", meta.get('uuid', ''))
found_torrent_path = os.path.join(torrent_storage_dir, f"{found_hash}.torrent") if torrent_storage_dir else os.path.join(extracted_torrent_dir, f"{found_hash}.torrent")
valid, resolved_path = await self.is_valid_torrent(
meta, found_torrent_path, found_hash, torrent_client, client, print_err=False
)
if valid:
torrent = Torrent.read(resolved_path)
piece_size = torrent.piece_size
piece_in_mib = int(piece_size) / 1024 / 1024
if not prefer_small_pieces:
console.print(f"[green]Found a valid torrent from client search with piece size {piece_in_mib} MiB: [bold yellow]{found_hash}")
return resolved_path
# Track best match for small pieces
if piece_size <= 8388608:
console.print(f"[green]Found a valid torrent with preferred piece size from client search: [bold yellow]{found_hash}")
return resolved_path
if best_match is None or piece_size < best_match['piece_size']:
best_match = {'torrenthash': found_hash, 'torrent_path': resolved_path, 'piece_size': piece_size}
console.print(f"[yellow]Storing valid torrent from client search as best match: [bold yellow]{found_hash}")
# Use best match if no preferred torrent found
if prefer_small_pieces and best_match:
console.print(f"[yellow]Using best match torrent with hash: [bold yellow]{best_match['torrenthash']}[/bold yellow]")
return best_match['torrent_path']
console.print("[bold yellow]No Valid .torrent found")
return None
async def is_valid_torrent(self, meta, torrent_path, torrenthash, torrent_client, client, print_err=False):
valid = False
wrong_file = False
# Normalize the torrent hash based on the client
if torrent_client in ('qbit', 'deluge'):
torrenthash = torrenthash.lower().strip()
torrent_path = torrent_path.replace(torrenthash.upper(), torrenthash)
elif torrent_client == 'rtorrent':
torrenthash = torrenthash.upper().strip()
torrent_path = torrent_path.replace(torrenthash.upper(), torrenthash)
if meta['debug']:
console.log(f"Torrent path after normalization: {torrent_path}")
# Check if torrent file exists
if os.path.exists(torrent_path):
try:
torrent = Torrent.read(torrent_path)
except Exception as e:
console.print(f'[bold red]Error reading torrent file: {e}')
return valid, torrent_path
# Reuse if disc and basename matches or --keep-folder was specified
if meta.get('is_disc', None) is not None or (meta['keep_folder'] and meta['isdir']):
torrent_name = torrent.metainfo['info']['name']
if meta['uuid'] != torrent_name and meta['debug']:
console.print("Modified file structure, skipping hash")
valid = False
torrent_filepath = os.path.commonpath(torrent.files)
if os.path.basename(meta['path']) in torrent_filepath:
valid = True
if meta['debug']:
console.log(f"Torrent is valid based on disc/basename or keep-folder: {valid}")
# If one file, check for folder
elif len(torrent.files) == len(meta['filelist']) == 1:
if os.path.basename(torrent.files[0]) == os.path.basename(meta['filelist'][0]):
if str(torrent.files[0]) == os.path.basename(torrent.files[0]):
valid = True
else:
wrong_file = True
if meta['debug']:
console.log(f"Single file match status: valid={valid}, wrong_file={wrong_file}")
# Check if number of files matches number of videos
elif len(torrent.files) == len(meta['filelist']):
torrent_filepath = os.path.commonpath(torrent.files)
actual_filepath = os.path.commonpath(meta['filelist'])
local_path, remote_path = await self.remote_path_map(meta)
if local_path.lower() in meta['path'].lower() and local_path.lower() != remote_path.lower():
actual_filepath = actual_filepath.replace(local_path, remote_path).replace(os.sep, '/')
if meta['debug']:
console.log(f"Torrent_filepath: {torrent_filepath}")
console.log(f"Actual_filepath: {actual_filepath}")
if torrent_filepath in actual_filepath:
valid = True
if meta['debug']:
console.log(f"Multiple file match status: valid={valid}")
else:
console.print(f'[bold yellow]{torrent_path} was not found')
# Additional checks if the torrent is valid so far
if valid:
if os.path.exists(torrent_path):
try:
reuse_torrent = Torrent.read(torrent_path)
piece_size = reuse_torrent.piece_size
piece_in_mib = int(piece_size) / 1024 / 1024
torrent_storage_dir_valid = torrent_path
torrent_file_size_kib = round(os.path.getsize(torrent_storage_dir_valid) / 1024, 2)
if meta['debug']:
console.log(f"Checking piece size, count and size: pieces={reuse_torrent.pieces}, piece_size={piece_in_mib} MiB, .torrent size={torrent_file_size_kib} KiB")
# Piece size and count validations
if not meta.get('prefer_small_pieces', False):
if reuse_torrent.pieces >= 8000 and reuse_torrent.piece_size < 8488608:
if meta['debug']:
console.print("[bold red]Torrent needs to have less than 8000 pieces with a 8 MiB piece size")
valid = False
elif reuse_torrent.pieces >= 4000 and reuse_torrent.piece_size < 4294304:
if meta['debug']:
console.print("[bold red]Torrent needs to have less than 5000 pieces with a 4 MiB piece size")
valid = False
elif 'max_piece_size' not in meta and reuse_torrent.pieces >= 12000:
if meta['debug']:
console.print("[bold red]Torrent needs to have less than 12000 pieces to be valid")
valid = False
elif reuse_torrent.piece_size < 32768:
if meta['debug']:
console.print("[bold red]Piece size too small to reuse")
valid = False
elif 'max_piece_size' not in meta and torrent_file_size_kib > 250:
if meta['debug']:
console.log("[bold red]Torrent file size exceeds 250 KiB")
valid = False
elif wrong_file:
if meta['debug']:
console.log("[bold red]Provided .torrent has files that were not expected")
valid = False
else:
console.print(f"[bold green]REUSING .torrent with infohash: [bold yellow]{torrenthash}")
except Exception as e:
console.print(f'[bold red]Error checking reuse torrent: {e}')
valid = False
if meta['debug']:
console.log(f"Final validity after piece checks: valid={valid}")
else:
if meta['debug']:
console.log("[bold yellow]Unwanted Files/Folders Identified")
return valid, torrent_path
async def search_qbit_for_torrent(self, meta, client):
mtv_config = self.config['TRACKERS'].get('MTV')
if isinstance(mtv_config, dict):
prefer_small_pieces = mtv_config.get('prefer_mtv_torrent', False)
else:
prefer_small_pieces = False
console.print("[green]Searching qBittorrent for an existing .torrent")
torrent_storage_dir = client.get('torrent_storage_dir')
extracted_torrent_dir = os.path.join(meta.get('base_dir', ''), "tmp", meta.get('uuid', ''))
if not extracted_torrent_dir or extracted_torrent_dir.strip() == "tmp/":
console.print("[bold red]Invalid extracted torrent directory path. Check `meta['base_dir']` and `meta['uuid']`.")
return None
try:
qbt_client = qbittorrentapi.Client(
host=client['qbit_url'],
port=client['qbit_port'],
username=client['qbit_user'],
password=client['qbit_pass'],
VERIFY_WEBUI_CERTIFICATE=client.get('VERIFY_WEBUI_CERTIFICATE', True)
)
qbt_client.auth_log_in()
except qbittorrentapi.LoginFailed:
console.print("[bold red]INCORRECT QBIT LOGIN CREDENTIALS")
return None
except qbittorrentapi.APIConnectionError:
console.print("[bold red]APIConnectionError: INCORRECT HOST/PORT")
return None
# Ensure extracted torrent directory exists
os.makedirs(extracted_torrent_dir, exist_ok=True)
# **Step 1: Find correct torrents using content_path**
best_match = None
matching_torrents = []
for torrent in qbt_client.torrents.info():
try:
torrent_path = torrent.name
except AttributeError:
continue # Ignore torrents with missing attributes
if meta['is_disc'] in ("", None) and len(meta['filelist']) == 1:
if torrent_path != meta['uuid'] or len(torrent.files) != len(meta['filelist']):
continue
elif meta['uuid'] != torrent_path:
continue
if meta['debug']:
console.print(f"[cyan]Matched Torrent: {torrent.hash}")
console.print(f"Name: {torrent.name}")
console.print(f"Save Path: {torrent.save_path}")
console.print(f"Content Path: {torrent_path}")
matching_torrents.append({'hash': torrent.hash, 'name': torrent.name})
if not matching_torrents:
console.print("[yellow]No matching torrents found in qBittorrent.")
return None
console.print(f"[green]Total Matching Torrents: {len(matching_torrents)}")
# **Step 2: Extract and Save .torrent Files**
processed_hashes = set()
best_match = None
for torrent in matching_torrents:
try:
torrent_hash = torrent['hash']
if torrent_hash in processed_hashes:
continue # Avoid processing duplicates
processed_hashes.add(torrent_hash)
except Exception as e:
console.print(f"[bold red]Unexpected error while handling {torrent_hash}: {e}")
# **Use `torrent_storage_dir` if available**
if torrent_storage_dir:
torrent_file_path = os.path.join(torrent_storage_dir, f"{torrent_hash}.torrent")
if not os.path.exists(torrent_file_path):
console.print(f"[yellow]Torrent file not found in storage directory: {torrent_file_path}")
continue
else:
# **Fetch from qBittorrent API if no `torrent_storage_dir`**
if meta['debug']:
console.print(f"[cyan]Exporting .torrent file for {torrent_hash}")
try:
torrent_file_content = qbt_client.torrents_export(torrent_hash=torrent_hash)
torrent_file_path = os.path.join(extracted_torrent_dir, f"{torrent_hash}.torrent")
with open(torrent_file_path, "wb") as f:
f.write(torrent_file_content)
if meta['debug']:
console.print(f"[green]Successfully saved .torrent file: {torrent_file_path}")
except qbittorrentapi.APIError as e:
console.print(f"[bold red]Failed to export .torrent for {torrent_hash}: {e}")
continue # Skip this torrent if unable to fetch
# **Validate the .torrent file**
try:
valid, torrent_path = await self.is_valid_torrent(meta, torrent_file_path, torrent_hash, 'qbit', client, print_err=False)
except Exception as e:
console.print(f"[bold red]Error validating torrent {torrent_hash}: {e}")
valid = False
torrent_path = None
if valid:
console.print("prefersmallpieces", prefer_small_pieces)
if prefer_small_pieces:
# **Track best match based on piece size**
try:
torrent_data = Torrent.read(torrent_file_path)
piece_size = torrent_data.piece_size
if best_match is None or piece_size < best_match['piece_size']:
best_match = {
'hash': torrent_hash,
'torrent_path': torrent_path if torrent_path else torrent_file_path,
'piece_size': piece_size
}
console.print(f"[green]Updated best match: {best_match}")
except Exception as e:
console.print(f"[bold red]Error reading torrent data for {torrent_hash}: {e}")
continue
else:
# If `prefer_small_pieces` is False, return first valid torrent
console.print(f"[green]Returning first valid torrent: {torrent_hash}")
return torrent_hash
else:
if meta['debug']:
console.print(f"[bold red]{torrent_hash} failed validation")
os.remove(torrent_file_path)
# **Return the best match if `prefer_small_pieces` is enabled**
if best_match:
console.print(f"[green]Using best match torrent with hash: {best_match['hash']}")
return best_match['hash']
console.print("[yellow]No valid torrents found.")
return None
def rtorrent(self, path, torrent_path, torrent, meta, local_path, remote_path, client, tracker):
# Get the appropriate source path (same as in qbittorrent method)
if len(meta.get('filelist', [])) == 1 and os.path.isfile(meta['filelist'][0]) and not meta.get('keep_folder'):
# If there's a single file and not keep_folder, use the file itself as the source
src = meta['filelist'][0]
else:
# Otherwise, use the directory
src = meta.get('path')
if not src:
error_msg = "[red]No source path found in meta."
console.print(f"[bold red]{error_msg}")
raise ValueError(error_msg)
# Determine linking method
linking_method = client.get('linking', None) # "symlink", "hardlink", or None
if meta.get('debug', False):
console.print("Linking method:", linking_method)
use_symlink = linking_method == "symlink"
use_hardlink = linking_method == "hardlink"
if use_symlink and use_hardlink:
error_msg = "Cannot use both hard links and symlinks simultaneously"
console.print(f"[bold red]{error_msg}")
raise ValueError(error_msg)
# Process linking if enabled
if use_symlink or use_hardlink:
# Get linked folder for this drive
linked_folder = client.get('linked_folder', [])
if meta.get('debug', False):
console.print(f"Linked folders: {linked_folder}")
if not isinstance(linked_folder, list):
linked_folder = [linked_folder] # Convert to list if single value
# Determine drive letter (Windows) or root (Linux)
if platform.system() == "Windows":
src_drive = os.path.splitdrive(src)[0]
else:
# On Unix/Linux, use the root directory or first directory component
src_drive = "/"
# Extract the first directory component for more specific matching
src_parts = src.strip('/').split('/')
if src_parts:
src_root_dir = '/' + src_parts[0]
# Check if any linked folder contains this root
for folder in linked_folder:
if src_root_dir in folder or folder in src_root_dir:
src_drive = src_root_dir
break
# Find a linked folder that matches the drive
link_target = None
if platform.system() == "Windows":
# Windows matching based on drive letters
for folder in linked_folder:
folder_drive = os.path.splitdrive(folder)[0]
if folder_drive == src_drive:
link_target = folder
break
else:
# Unix/Linux matching based on path containment
for folder in linked_folder:
# Check if source path is in the linked folder or vice versa
if src.startswith(folder) or folder.startswith(src) or folder.startswith(src_drive):
link_target = folder
break
if meta.get('debug', False):
console.print(f"Source drive: {src_drive}")
console.print(f"Link target: {link_target}")
# If using symlinks and no matching drive folder, allow any available one
if use_symlink and not link_target and linked_folder:
link_target = linked_folder[0]
if (use_symlink or use_hardlink) and not link_target:
error_msg = f"No suitable linked folder found for drive {src_drive}"
console.print(f"[bold red]{error_msg}")
raise ValueError(error_msg)
# Create tracker-specific directory inside linked folder
if use_symlink or use_hardlink:
# allow overridden folder name with link_dir_name config var
tracker_cfg = self.config["TRACKERS"].get(tracker.upper(), {})
link_dir_name = str(tracker_cfg.get("link_dir_name", "")).strip()
tracker_dir = os.path.join(link_target, link_dir_name or tracker)
os.makedirs(tracker_dir, exist_ok=True)
if meta.get('debug', False):
console.print(f"[bold yellow]Linking to tracker directory: {tracker_dir}")
console.print(f"[cyan]Source path: {src}")
# Extract only the folder or file name from `src`
src_name = os.path.basename(src.rstrip(os.sep)) # Ensure we get just the name
dst = os.path.join(tracker_dir, src_name) # Destination inside linked folder
# path magic
if os.path.exists(dst) or os.path.islink(dst):
if meta.get('debug', False):
console.print(f"[yellow]Skipping linking, path already exists: {dst}")
else:
if use_hardlink:
try:
# Check if we're linking a file or directory
if os.path.isfile(src):
# For a single file, create a hardlink directly
try:
os.link(src, dst)
if meta.get('debug', False):
console.print(f"[green]Hard link created: {dst} -> {src}")
except OSError as e:
# If hardlink fails, try to copy the file instead
console.print(f"[yellow]Hard link failed: {e}")
console.print(f"[yellow]Falling back to file copy for: {src}")
shutil.copy2(src, dst) # copy2 preserves metadata
console.print(f"[green]File copied instead: {dst}")
else:
# For directories, we need to link each file inside
os.makedirs(dst, exist_ok=True)
for root, _, files in os.walk(src):
# Get the relative path from source
rel_path = os.path.relpath(root, src)
# Create corresponding directory in destination
if rel_path != '.':
dst_dir = os.path.join(dst, rel_path)
os.makedirs(dst_dir, exist_ok=True)
# Create hardlinks for each file
for file in files:
src_file = os.path.join(root, file)
dst_file = os.path.join(dst if rel_path == '.' else dst_dir, file)
try:
os.link(src_file, dst_file)
if meta.get('debug', False) and files.index(file) == 0:
console.print(f"[green]Hard link created for file: {dst_file} -> {src_file}")
except OSError as e:
# If hardlink fails, copy file instead
console.print(f"[yellow]Hard link failed for file {file}: {e}")
shutil.copy2(src_file, dst_file) # copy2 preserves metadata
console.print(f"[yellow]File copied instead: {dst_file}")
if meta.get('debug', False):
console.print(f"[green]Directory structure and files processed: {dst}")
except OSError as e:
error_msg = f"Failed to create link: {e}"
console.print(f"[bold red]{error_msg}")
if meta.get('debug', False):
console.print(f"[yellow]Source: {src} (exists: {os.path.exists(src)})")
console.print(f"[yellow]Destination: {dst}")
# Don't raise exception - just warn and continue
console.print("[yellow]Continuing with rTorrent addition despite linking failure")
elif use_symlink:
try:
if platform.system() == "Windows":
os.symlink(src, dst, target_is_directory=os.path.isdir(src))
else:
os.symlink(src, dst)
if meta.get('debug', False):
console.print(f"[green]Symbolic link created: {dst} -> {src}")
except OSError as e:
error_msg = f"Failed to create symlink: {e}"
console.print(f"[bold red]{error_msg}")
# Don't raise exception - just warn and continue
console.print("[yellow]Continuing with rTorrent addition despite linking failure")
# Use the linked path for rTorrent if linking was successful
if (use_symlink or use_hardlink) and os.path.exists(dst):
path = dst
# Apply remote pathing to `tracker_dir` before assigning `save_path`
if use_symlink or use_hardlink:
save_path = tracker_dir # Default to linked directory
else:
save_path = path # Default to the original path
# Handle remote path mapping
if local_path and remote_path and local_path.lower() != remote_path.lower():
# Normalize paths for comparison
norm_save_path = os.path.normpath(save_path).lower()
norm_local_path = os.path.normpath(local_path).lower()
# Check if the save_path starts with local_path
if norm_save_path.startswith(norm_local_path):
# Get the relative part of the path
rel_path = os.path.relpath(save_path, local_path)
# Combine remote path with relative path
save_path = os.path.join(remote_path, rel_path)
# For direct replacement if the above approach doesn't work
elif local_path.lower() in save_path.lower():
save_path = save_path.replace(local_path, remote_path, 1) # Replace only at the beginning
if meta['debug']:
console.print(f"[cyan]Original path: {path}")
console.print(f"[cyan]Mapped save path: {save_path}")
rtorrent = xmlrpc.client.Server(client['rtorrent_url'], context=ssl._create_stdlib_context())
metainfo = bencode.bread(torrent_path)
try:
# Use dst path if linking was successful, otherwise use original path
resume_path = dst if (use_symlink or use_hardlink) and os.path.exists(dst) else path
fast_resume = self.add_fast_resume(metainfo, resume_path, torrent)
except EnvironmentError as exc:
console.print("[red]Error making fast-resume data (%s)" % (exc,))
raise
new_meta = bencode.bencode(fast_resume)
if new_meta != metainfo:
fr_file = torrent_path.replace('.torrent', '-resume.torrent')
console.print("Creating fast resume")
bencode.bwrite(fast_resume, fr_file)
# Use dst path if linking was successful, otherwise use original path
path = dst if (use_symlink or use_hardlink) and os.path.exists(dst) else path
isdir = os.path.isdir(path)
# Remote path mount
modified_fr = False
if local_path.lower() in path.lower() and local_path.lower() != remote_path.lower():
path_dir = os.path.dirname(path)
path = path.replace(local_path, remote_path)
path = path.replace(os.sep, '/')
shutil.copy(fr_file, f"{path_dir}/fr.torrent")
fr_file = f"{os.path.dirname(path)}/fr.torrent"
modified_fr = True
if isdir is False:
path = os.path.dirname(path)
console.print("[bold yellow]Adding and starting torrent")
rtorrent.load.start_verbose('', fr_file, f"d.directory_base.set={path}")
time.sleep(1)
# Add labels
if client.get('rtorrent_label', None) is not None:
rtorrent.d.custom1.set(torrent.infohash, client['rtorrent_label'])
if meta.get('rtorrent_label') is not None:
rtorrent.d.custom1.set(torrent.infohash, meta['rtorrent_label'])
# Delete modified fr_file location
if modified_fr:
os.remove(f"{path_dir}/fr.torrent")
if meta.get('debug', False):
console.print(f"[cyan]Path: {path}")
return
async def qbittorrent(self, path, torrent, local_path, remote_path, client, is_disc, filelist, meta, tracker):
if meta.get('keep_folder'):
path = os.path.dirname(path)
else:
isdir = os.path.isdir(path)
if len(filelist) != 1 or not isdir:
path = os.path.dirname(path)
# Get the appropriate source path
if len(meta['filelist']) == 1 and os.path.isfile(meta['filelist'][0]) and not meta.get('keep_folder'):
# If there's a single file and not keep_folder, use the file itself as the source
src = meta['filelist'][0]
else:
# Otherwise, use the directory
src = meta.get('path')
if not src:
error_msg = "[red]No source path found in meta."
console.print(f"[bold red]{error_msg}")
raise ValueError(error_msg)
# Determine linking method
linking_method = client.get('linking', None) # "symlink", "hardlink", or None
if meta['debug']:
console.print("Linking method:", linking_method)
use_symlink = linking_method == "symlink"
use_hardlink = linking_method == "hardlink"
if use_symlink and use_hardlink:
error_msg = "Cannot use both hard links and symlinks simultaneously"
console.print(f"[bold red]{error_msg}")
raise ValueError(error_msg)
# Get linked folder for this drive
linked_folder = client.get('linked_folder', [])
if meta['debug']:
console.print(f"Linked folders: {linked_folder}")
if not isinstance(linked_folder, list):
linked_folder = [linked_folder] # Convert to list if single value
# Determine drive letter (Windows) or root (Linux)
if platform.system() == "Windows":
src_drive = os.path.splitdrive(src)[0]
else:
# On Unix/Linux, use the full mount point path for more accurate matching
src_drive = "/"
# Get all mount points on the system to find the most specific match
mounted_volumes = []
try:
# Read mount points from /proc/mounts or use 'mount' command output
if os.path.exists('/proc/mounts'):
with open('/proc/mounts', 'r') as f:
for line in f:
parts = line.split()
if len(parts) >= 2:
mount_point = parts[1]
mounted_volumes.append(mount_point)
else:
# Fall back to mount command if /proc/mounts doesn't exist
import subprocess
output = subprocess.check_output(['mount'], text=True)
for line in output.splitlines():
parts = line.split()
if len(parts) >= 3:
mount_point = parts[2]
mounted_volumes.append(mount_point)
except Exception as e:
if meta.get('debug', False):
console.print(f"[yellow]Error getting mount points: {str(e)}")
# Sort mount points by length (descending) to find most specific match first
mounted_volumes.sort(key=len, reverse=True)
# Find the most specific mount point that contains our source path
for mount_point in mounted_volumes:
if src.startswith(mount_point):
src_drive = mount_point
if meta.get('debug', False):
console.print(f"[cyan]Found mount point: {mount_point} for path: {src}")
break
# If we couldn't find a specific mount point, fall back to linked folder matching
if src_drive == "/":
# Extract the first directory component for basic matching
src_parts = src.strip('/').split('/')
if src_parts:
src_root_dir = '/' + src_parts[0]
# Check if any linked folder contains this root
for folder in linked_folder:
if src_root_dir in folder or folder in src_root_dir:
src_drive = src_root_dir
break
# Find a linked folder that matches the drive
link_target = None
if platform.system() == "Windows":
# Windows matching based on drive letters
for folder in linked_folder:
folder_drive = os.path.splitdrive(folder)[0]
if folder_drive == src_drive:
link_target = folder
break
else:
# Unix/Linux matching based on path containment
for folder in linked_folder:
# Check if the linked folder starts with the mount point
if folder.startswith(src_drive) or src.startswith(folder):
link_target = folder
break
# Also check if this is a sibling mount point with the same structure
folder_parts = folder.split('/')
src_drive_parts = src_drive.split('/')
# Check if both are mounted under the same parent directory
if (len(folder_parts) >= 2 and len(src_drive_parts) >= 2 and
folder_parts[1] == src_drive_parts[1]):
potential_match = os.path.join(src_drive, folder_parts[-1])
if os.path.exists(potential_match):
link_target = potential_match
if meta['debug']:
console.print(f"[cyan]Found sibling mount point linked folder: {link_target}")
break
if meta['debug']:
console.print(f"Source drive: {src_drive}")
console.print(f"Link target: {link_target}")
# If using symlinks and no matching drive folder, allow any available one
if use_symlink and not link_target and linked_folder:
link_target = linked_folder[0]
if (use_symlink or use_hardlink) and not link_target:
error_msg = f"No suitable linked folder found for drive {src_drive}"
console.print(f"[bold red]{error_msg}")
raise ValueError(error_msg)
# Create tracker-specific directory inside linked folder
if use_symlink or use_hardlink:
# allow overridden folder name with link_dir_name config var
tracker_cfg = self.config["TRACKERS"].get(tracker.upper(), {})
link_dir_name = str(tracker_cfg.get("link_dir_name", "")).strip()
tracker_dir = os.path.join(link_target, link_dir_name or tracker)
os.makedirs(tracker_dir, exist_ok=True)
if meta['debug']:
console.print(f"[bold yellow]Linking to tracker directory: {tracker_dir}")
console.print(f"[cyan]Source path: {src}")
# Extract only the folder or file name from `src`
src_name = os.path.basename(src.rstrip(os.sep)) # Ensure we get just the name
dst = os.path.join(tracker_dir, src_name) # Destination inside linked folder
# path magic
if os.path.exists(dst) or os.path.islink(dst):
if meta['debug']:
console.print(f"[yellow]Skipping linking, path already exists: {dst}")
else:
allow_fallback = self.config['TRACKERS'].get('allow_fallback', True)
fallback_to_original = False
if use_hardlink:
try:
# Check if we're linking a file or directory
if os.path.isfile(src):
# For a single file, create a hardlink directly
try:
os.link(src, dst)
if meta['debug']:
console.print(f"[green]Hard link created: {dst} -> {src}")
except OSError as e:
console.print(f"[yellow]Hard link failed: {e}")
if allow_fallback:
console.print(f"[yellow]Using original path without linking: {src}")
use_hardlink = False
fallback_to_original = True
else:
# For directories, we need to link each file inside
console.print("[yellow]Cannot hardlink directories directly. Creating directory structure...")
os.makedirs(dst, exist_ok=True)
for root, _, files in os.walk(src):
# Get the relative path from source
rel_path = os.path.relpath(root, src)
# Create corresponding directory in destination
if rel_path != '.':
dst_dir = os.path.join(dst, rel_path)
os.makedirs(dst_dir, exist_ok=True)
# Create hardlinks for each file
for file in files:
src_file = os.path.join(root, file)
dst_file = os.path.join(dst if rel_path == '.' else dst_dir, file)
try:
os.link(src_file, dst_file)
if meta['debug'] and files.index(file) == 0:
console.print(f"[green]Hard link created for file: {dst_file} -> {src_file}")
except OSError as e:
console.print(f"[yellow]Hard link failed for file {file}: {e}")
if allow_fallback:
console.print(f"[yellow]Using original path without linking: {src}")
fallback_to_original = True
break
if fallback_to_original:
use_hardlink = False
link_target = None
# Clean up the partially created directory
try:
shutil.rmtree(dst)
except Exception as cleanup_error:
console.print(f"[red]Warning: Failed to clean up partial directory {dst}: {cleanup_error}")
except OSError as e:
# Global exception handler for any linking operation
error_msg = f"Failed to create hard link: {e}"
console.print(f"[bold red]{error_msg}")
if allow_fallback:
console.print(f"[yellow]Using original path without linking: {src}")
use_hardlink = False
if meta['debug']:
console.print(f"[yellow]Source: {src} (exists: {os.path.exists(src)})")
console.print(f"[yellow]Destination: {dst}")
elif use_symlink:
try:
if platform.system() == "Windows":
os.symlink(src, dst, target_is_directory=os.path.isdir(src))
else:
os.symlink(src, dst)
if meta['debug']:
console.print(f"[green]Symbolic link created: {dst} -> {src}")
except OSError as e:
error_msg = f"Failed to create symlink: {e}"
console.print(f"[bold red]{error_msg}")
if allow_fallback:
console.print(f"[yellow]Using original path without linking: {src}")
use_symlink = False
# Initialize qBittorrent client
qbt_client = qbittorrentapi.Client(
host=client['qbit_url'],
port=client['qbit_port'],
username=client['qbit_user'],
password=client['qbit_pass'],
VERIFY_WEBUI_CERTIFICATE=client.get('VERIFY_WEBUI_CERTIFICATE', True)
)
if meta['debug']:
console.print("[bold yellow]Adding and rechecking torrent")
try:
qbt_client.auth_log_in()
except qbittorrentapi.LoginFailed:
console.print("[bold red]INCORRECT QBIT LOGIN CREDENTIALS")
return
# Apply remote pathing to `tracker_dir` before assigning `save_path`
if use_symlink or use_hardlink:
save_path = tracker_dir # Default to linked directory
else:
save_path = path # Default to the original path
# Handle remote path mapping
if local_path and remote_path and local_path.lower() != remote_path.lower():
# Normalize paths for comparison
norm_save_path = os.path.normpath(save_path).lower()
norm_local_path = os.path.normpath(local_path).lower()
# Check if the save_path starts with local_path
if norm_save_path.startswith(norm_local_path):
# Get the relative part of the path
rel_path = os.path.relpath(save_path, local_path)
# Combine remote path with relative path
save_path = os.path.join(remote_path, rel_path)
# For direct replacement if the above approach doesn't work
elif local_path.lower() in save_path.lower():
save_path = save_path.replace(local_path, remote_path, 1) # Replace only at the beginning
# Always normalize separators for qBittorrent (it expects forward slashes)
save_path = save_path.replace(os.sep, '/')
# Ensure qBittorrent save path is formatted correctly
if not save_path.endswith('/'):
save_path += '/'
if meta['debug']:
console.print(f"[cyan]Original path: {path}")
console.print(f"[cyan]Mapped save path: {save_path}")
# Automatic management
auto_management = False
if not use_symlink and not use_hardlink:
am_config = client.get('automatic_management_paths', '')
if meta['debug']:
console.print(f"AM Config: {am_config}")
if isinstance(am_config, list):
for each in am_config:
if os.path.normpath(each).lower() in os.path.normpath(path).lower():
auto_management = True
else:
if os.path.normpath(am_config).lower() in os.path.normpath(path).lower() and am_config.strip() != "":
auto_management = True