-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqbit-cleanup.sh
More file actions
1476 lines (1302 loc) · 59.3 KB
/
Copy pathqbit-cleanup.sh
File metadata and controls
1476 lines (1302 loc) · 59.3 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
#!/bin/bash
set -o pipefail
# =============================================================================
# qBittorrent Dedupe & Hardlink Manager
# =============================================================================
# Ce script analyse les torrents qBittorrent, vérifie s'ils sont liés
# (hardlinks) aux bibliothèques Radarr/Sonarr, et classe automatiquement
# chaque torrent dans qBittorrent via des tags.
#
# Fonctions :
# - Détection des liens directs (linked), cross-seed (cross-linked),
# partiels (partial) et orphelins (orphan)
# - Réparation automatique des orphelins par hardlink manuel (optionnel)
# - Vérification de la durée de seed minimale par tracker
# - Scan des orphelins de disque (fichiers médias non référencés)
# =============================================================================
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="${SCRIPT_DIR}/cleanup/cleanup.conf"
if [ ! -f "$CONFIG_FILE" ]; then
echo "❌ Fichier de configuration introuvable : $CONFIG_FILE"
exit 1
fi
source "$CONFIG_FILE"
CACHE_DIR="${SCRIPT_DIR}/cleanup"
mkdir -p "$CACHE_DIR"
# -----------------------------------------------------------------------------
# VARIABLES GLOBALES
# -----------------------------------------------------------------------------
# Connexions qBittorrent
declare -A QBIT_COOKIES
# Caches disque
declare -A HASH_CACHE
declare -A INODE_STATUS_CACHE
declare -A TORRENT_CACHE
# Métadonnées torrents
declare -A TORRENT_NAMES
declare -A TORRENT_INSTANCE
declare -A TORRENT_SAVE_PATH
declare -A TORRENT_HOST_PATH
# Inodes gérés par les Arr (Radarr/Sonarr)
declare -A ARR_MANAGED_INODES
# Position des inodes (dans MEDIA_DIRS ou CROSS_SEED_DIR)
declare -A INODE_IN_MEDIA
declare -A INODE_IN_CROSS
# Batches de tags à appliquer par instance
declare -A TAG_BATCHES
# Initialisation des batches pour éviter les variables unbound
for inst in "${INSTANCES[@]}"; do
for t in "$TAG_LINKED" "$TAG_CROSS_LINKED" "$TAG_PARTIAL" \
"$TAG_NO_MEDIA" "$TAG_ORPHAN" "$TAG_DELETE"; do
TAG_BATCHES["${inst}|${t}"]=""
done
done
# Fichiers de cache
HASH_CMD=""
HASH_CACHE_FILE="${CACHE_DIR}/hash_cache.txt"
HASH_JOURNAL_FILE="${CACHE_DIR}/hash_journal.txt"
INODE_CACHE_FILE="${CACHE_DIR}/inode_status.txt"
TORRENT_CACHE_FILE="${CACHE_DIR}/torrent_status.txt"
ARR_INODES_FILE="${CACHE_DIR}/arr_inodes.txt"
# Seuils
HASH_MERGE_THRESHOLD=50
HASH_CACHE_DIRTY=0
# Configuration par défaut (peut être surchargée dans cleanup.conf)
AUTO_REPAIR="${AUTO_REPAIR:-false}"
ARR_CACHE_DURATION="${ARR_CACHE_DURATION:-3600}"
SCAN_DISK_ORPHANS="${SCAN_DISK_ORPHANS:-false}"
DISK_ORPHAN_LOG="${DISK_ORPHAN_LOG:-${SCRIPT_DIR}/disk_orphans.log}"
DISK_ORPHAN_MIN_SIZE="${DISK_ORPHAN_MIN_SIZE:-0}"
# -----------------------------------------------------------------------------
# SIGNAL HANDLER
# -----------------------------------------------------------------------------
# Sauvegarde immédiate des caches en cas d'interruption (Ctrl+C)
cleanup_on_exit() {
echo ""
echo "⚠️ Interruption — sauvegarde des caches..."
save_hash_cache_merge
exit 1
}
trap cleanup_on_exit SIGINT SIGTERM SIGHUP
# -----------------------------------------------------------------------------
# UTILITAIRES
# -----------------------------------------------------------------------------
# ID du filesystem (device) pour vérifier qu'un hardlink est possible
get_fs_id() { stat -c '%d' "$1" 2>/dev/null || echo "0"; }
# Chown optionnel si les fichiers créés doivent appartenir à un utilisateur
do_chown() { $CHOWN_FILES && chown "$CHOWN_USER" "$1" 2>/dev/null || true; }
# Sélection du meilleur outil de hachage disponible
pick_hash_tool() {
if command -v xxh128sum &>/dev/null; then HASH_CMD="xxh128sum"
elif command -v xxh64sum &>/dev/null; then HASH_CMD="xxh64sum"
elif command -v xxhash &>/dev/null; then HASH_CMD="xxhash"
elif command -v md5sum &>/dev/null; then HASH_CMD="md5sum"
else
echo "❌ Aucun outil de hachage trouvé (xxhash/md5sum requis)."
exit 1
fi
}
# -----------------------------------------------------------------------------
# TRANSLATION DE CHEMINS (Docker → Hôte)
# -----------------------------------------------------------------------------
# Les containers qBittorrent voient /data/completed, l'hôte voit /mnt/tank/...
# PATH_MAP fait ce pont de manière bidirectionnelle.
translate_path() {
local container_path="$1"
# Si le chemin est déjà un chemin hôte, on le retourne tel quel
if [[ "$container_path" == /mnt/* ]] || [[ "$container_path" == /tank/* ]]; then
printf '%s' "$container_path"
return
fi
local host_path="$container_path"
for container_prefix in "${!PATH_MAP[@]}"; do
if [[ "$container_path" == "$container_prefix"/* ]]; then
local suffix="${container_path#$container_prefix/}"
host_path="${PATH_MAP[$container_prefix]%/}/${suffix}"
break
elif [[ "$container_path" == "$container_prefix" ]]; then
host_path="${PATH_MAP[$container_prefix]}"
host_path="${host_path%/}"
break
fi
done
printf '%s' "$host_path"
}
# -----------------------------------------------------------------------------
# NORMALISATION DES NOMS DE FICHIERS
# -----------------------------------------------------------------------------
# Permet de comparer "The.Movie.2023.1080p.mkv" et "Movie.2023.mkv"
# en retirant les stopwords, la casse, et l'année.
normalize_name() {
local name="$1"
local base="${name%.*}"
base=$(printf '%s' "$base" | tr '[:upper:]' '[:lower:]' | tr '._[](){}-' ' ' | tr -s ' ')
base=$(printf '%s' "$base" | sed -E 's/ [0-9]{4} / /g; s/^[0-9]{4} //; s/ [0-9]{4}$//')
local result=" $base "
for w in "${STOPWORDS[@]}"; do
result="${result// $w / }"
done
result=$(printf '%s' "$result" | sed -E 's/ [a-z]{3,}$//; s/ [a-z]{3,} [a-z]{3,}$//')
result=$(printf '%s' "$result" | sed 's/^ *//; s/ *$//')
printf '%s' "$result"
}
# Retourne : exact, partial, ou none
name_similarity() {
local n1 n2
n1=$(normalize_name "$1")
n2=$(normalize_name "$2")
[ -z "$n1" ] || [ -z "$n2" ] && { echo "none"; return 1; }
[ "$n1" = "$n2" ] && { echo "exact"; return 0; }
[[ "$n1" == *"$n2"* ]] || [[ "$n2" == *"$n1"* ]] && { echo "partial"; return 0; }
local f1="${n1%% *}" f2="${n2%% *}"
[ -n "$f1" ] && [ "$f1" = "$f2" ] && { echo "partial"; return 0; }
local y1 y2
y1=$(printf '%s' "$n1" | grep -oE '[0-9]{4}' | head -1)
y2=$(printf '%s' "$n2" | grep -oE '[0-9]{4}' | head -1)
[ -n "$y1" ] && [ "$y1" = "$y2" ] && { echo "partial"; return 0; }
echo "none"; return 1
}
# =============================================================================
# CACHES DISQUE (résilience face aux interruptions)
# =============================================================================
# --- Cache de hachage (fichier → hash) ---
load_hash_cache() {
HASH_CACHE=()
if [ -f "$HASH_CACHE_FILE" ]; then
while IFS='|' read -r key ts size hash; do
[ -z "$key" ] && continue
HASH_CACHE["$key"]="${ts}|${size}|${hash}"
done < "$HASH_CACHE_FILE"
fi
if [ -f "$HASH_JOURNAL_FILE" ]; then
while IFS='|' read -r key ts size hash; do
[ -z "$key" ] && continue
HASH_CACHE["$key"]="${ts}|${size}|${hash}"
done < "$HASH_JOURNAL_FILE"
rm -f "$HASH_JOURNAL_FILE"
fi
}
# Écriture incrémentale (journal) puis fusion périodique
save_hash_entry() {
local filepath="$1"
local cached="${HASH_CACHE[$filepath]:-}"
[ -z "$cached" ] && return
printf '%s|%s\n' "$filepath" "$cached" >> "$HASH_JOURNAL_FILE"
HASH_CACHE_DIRTY=$((HASH_CACHE_DIRTY + 1))
[ "$HASH_CACHE_DIRTY" -ge "$HASH_MERGE_THRESHOLD" ] && save_hash_cache_merge
}
save_hash_cache_merge() {
[ "$HASH_CACHE_DIRTY" -eq 0 ] && [ ! -f "$HASH_JOURNAL_FILE" ] && return
if [ -f "$HASH_JOURNAL_FILE" ] && [ -s "$HASH_JOURNAL_FILE" ]; then
while IFS='|' read -r key ts size hash; do
[ -z "$key" ] && continue
HASH_CACHE["$key"]="${ts}|${size}|${hash}"
done < "$HASH_JOURNAL_FILE"
rm -f "$HASH_JOURNAL_FILE"
fi
local tmpfile="${HASH_CACHE_FILE}.$$"
> "$tmpfile"
for key in "${!HASH_CACHE[@]}"; do
printf '%s|%s\n' "$key" "${HASH_CACHE[$key]}" >> "$tmpfile"
done
mv "$tmpfile" "$HASH_CACHE_FILE" 2>/dev/null
HASH_CACHE_DIRTY=0
}
get_cached_hash() {
local filepath="$1"
[ ! -f "$filepath" ] && return 1
local cached="${HASH_CACHE[$filepath]:-}"
[ -z "$cached" ] && return 1
local size
size=$(stat -c '%s' "$filepath" 2>/dev/null) || return 1
local cached_size="${cached#*|}"
cached_size="${cached_size%%|*}"
[ "$cached_size" != "$size" ] && return 1
printf '%s' "${cached##*|}"
return 0
}
set_cached_hash() {
local filepath="$1" hash="$2"
local ts size
ts=$(date +%s)
size=$(stat -c '%s' "$filepath" 2>/dev/null) || return 1
HASH_CACHE["$filepath"]="${ts}|${size}|${hash}"
}
file_hash() {
local filepath="$1"
local cached
cached=$(get_cached_hash "$filepath")
[ -n "$cached" ] && printf '%s' "$cached" && return 0
[ -z "$HASH_CMD" ] && return 1
local hash
hash=$("$HASH_CMD" "$filepath" 2>/dev/null | cut -d' ' -f1)
[ -z "$hash" ] && return 1
set_cached_hash "$filepath" "$hash"
save_hash_entry "$filepath"
printf '%s' "$hash"
return 0
}
# --- Cache d'inodes (position : media/cross/inconnu) ---
load_inode_cache() {
INODE_STATUS_CACHE=()
[ ! -f "$INODE_CACHE_FILE" ] && return
local inode status sample_path mtime ci
while IFS='|' read -r inode status sample_path mtime; do
[ -z "$inode" ] && continue
# Vérification : le fichier sample existe-t-il encore avec le même inode ?
if [ -n "$sample_path" ] && [ -f "$sample_path" ]; then
ci=$(stat -c '%i' "$sample_path" 2>/dev/null || echo "0")
[ "$ci" = "$inode" ] && INODE_STATUS_CACHE["$inode"]="$status"
fi
done < "$INODE_CACHE_FILE"
printf ' 📦 Cache inodes : %d entrées\n' "${#INODE_STATUS_CACHE[@]}"
}
save_inode_entry() {
local inode="$1" status="$2" sample_path="$3"
printf '%s|%s|%s|%s\n' "$inode" "$status" "$sample_path" "$(date +%s)" >> "$INODE_CACHE_FILE"
}
# --- Cache de statut des torrents ---
load_torrent_cache() {
TORRENT_CACHE=()
[ ! -f "$TORRENT_CACHE_FILE" ] && return
local hash instance status timestamp
while IFS='|' read -r hash instance status timestamp; do
[ -z "$hash" ] && continue
TORRENT_CACHE["${hash}|${instance}"]="${status}|${timestamp}"
done < "$TORRENT_CACHE_FILE"
printf ' 📦 Cache torrents : %d entrées\n' "${#TORRENT_CACHE[@]}"
}
save_torrent_entry() {
local hash="$1" instance="$2" status="$3"
printf '%s|%s|%s|%s\n' "$hash" "$instance" "$status" "$(date +%s)" >> "$TORRENT_CACHE_FILE"
}
# --- Cache des inodes Arr ---
load_arr_inodes() {
ARR_MANAGED_INODES=()
[ ! -f "$ARR_INODES_FILE" ] && return
local inode path
while IFS='|' read -r inode path; do
[ -z "$inode" ] && continue
[ -f "$path" ] && ARR_MANAGED_INODES["$inode"]="$path"
done < "$ARR_INODES_FILE"
printf ' 📦 Cache Arr inodes : %d entrées\n' "${#ARR_MANAGED_INODES[@]}"
}
save_arr_inodes_bulk() {
local tmpfile="${ARR_INODES_FILE}.$$"
> "$tmpfile"
for inode in "${!ARR_MANAGED_INODES[@]}"; do
printf '%s|%s\n' "$inode" "${ARR_MANAGED_INODES[$inode]}" >> "$tmpfile"
done
mv "$tmpfile" "$ARR_INODES_FILE" 2>/dev/null
}
# =============================================================================
# API QBITTORRENT
# =============================================================================
qbit_vars() {
local instance="$1"
case "$instance" in
VPN) printf '%s|%s|%s' "${QBIT_VPN_URL}" "${QBIT_VPN_USER}" "${QBIT_VPN_PASS}" ;;
DIRECT) printf '%s|%s|%s' "${QBIT_DIRECT_URL}" "${QBIT_DIRECT_USER}" "${QBIT_DIRECT_PASS}" ;;
*) return 1 ;;
esac
}
qbit_login() {
local instance="$1"
local vars
vars=$(qbit_vars "$instance") || return 1
IFS='|' read -r url user pass <<< "$vars"
local cookie
cookie=$(curl -s -c - -d "username=${user}&password=${pass}" \
--connect-timeout 5 --max-time 10 \
"${url}/api/v2/auth/login" 2>/dev/null | grep SID | awk '{print $NF}')
[ -z "$cookie" ] && return 1
QBIT_COOKIES["$instance"]="$cookie"
return 0
}
qbit_get() {
local instance="$1" path="$2"
local vars
vars=$(qbit_vars "$instance") || return 1
local url="${vars%%|*}"
curl -s --connect-timeout 5 --max-time 30 \
-H "Cookie: SID=${QBIT_COOKIES[$instance]}" "${url}${path}" 2>/dev/null
}
# Tags : API qBittorrent exige POST avec champs séparés (pas GET)
qbit_tag_single() {
local instance="$1" hashes="$2" tag="$3"
[ -z "$hashes" ] && return
local vars
vars=$(qbit_vars "$instance") || return
local url="${vars%%|*}"
curl -s --connect-timeout 5 --max-time 30 \
-H "Cookie: SID=${QBIT_COOKIES[$instance]}" \
-d "hashes=${hashes}" \
-d "tags=${tag}" \
"${url}/api/v2/torrents/addTags" > /dev/null
}
qbit_remove_tags() {
local instance="$1" hashes="$2" tags="$3"
[ -z "$hashes" ] || [ -z "$tags" ] && return
local vars
vars=$(qbit_vars "$instance") || return
local url="${vars%%|*}"
curl -s --connect-timeout 5 --max-time 30 \
-H "Cookie: SID=${QBIT_COOKIES[$instance]}" \
-d "hashes=${hashes}" \
-d "tags=${tags}" \
"${url}/api/v2/torrents/removeTags" > /dev/null
}
# Batching : qBittorrent accepte max ~100 hashes par requête
batch_add() {
local inst="$1" tag="$2" hash="$3"
TAG_BATCHES["${inst}|${tag}"]="${TAG_BATCHES[${inst}|${tag}]}${hash} "
}
batch_remove() {
local inst="$1" tag="$2" hash="$3"
local current="${TAG_BATCHES[${inst}|${tag}]:-}"
[ -z "$current" ] && return
current=$(printf '%s' "$current" | tr ' ' '\n' | grep -Fxv "$hash" | tr '\n' ' ')
current="${current% }"
TAG_BATCHES["${inst}|${tag}"]="${current:+${current} }"
}
apply_tag_batches() {
local instance="$1" tag="$2" hashes_str="$3"
[ -z "$hashes_str" ] && return
read -ra all_hashes <<< "$hashes_str"
local batch_size=90
local -a batch=()
for h in "${all_hashes[@]}"; do
[ -z "$h" ] && continue
batch+=("$h")
if [ "${#batch[@]}" -ge "$batch_size" ]; then
local batch_str
batch_str=$(IFS='|'; echo "${batch[*]}")
qbit_tag_single "$instance" "$batch_str" "$tag"
batch=()
sleep 0.2
fi
done
if [ "${#batch[@]}" -gt 0 ]; then
local batch_str
batch_str=$(IFS='|'; echo "${batch[*]}")
qbit_tag_single "$instance" "$batch_str" "$tag"
fi
}
# =============================================================================
# API RADARR / SONARR
# =============================================================================
# Récupère tous les chemins de fichiers gérés par les Arr.
# Radarr v3 : /api/v3/movie (movieFile / movieFiles)
# Sonarr v3 : fallback series → episodefile?seriesId= car /episodefile global
# retourne parfois HTTP 400
fetch_arr_inodes_bulk() {
local app="$1" url="$2" key="$3"
local cache_raw="${CACHE_DIR}/arr_raw_${app}.txt"
printf ' 🔄 Récupération %s... ' "$app"
url="${url%/}"
if [ "$app" = "radarr" ]; then
local response http_code payload
response=$(curl -s -w "\n%{http_code}" --connect-timeout 10 --max-time 30 \
-H "X-Api-Key: ${key}" \
-H "Accept: application/json" \
"${url}/api/v3/movie" 2>/dev/null)
http_code=$(printf '%s' "$response" | tail -n 1)
payload=$(printf '%s' "$response" | sed '$d')
if [ "$http_code" = "200" ] && [ -n "$payload" ]; then
printf '%s' "$payload" | python3 -c "
import sys, json
try:
for m in json.load(sys.stdin):
mf = m.get('movieFile')
if mf:
p = mf.get('path', '')
if p: print(p)
mfs = m.get('movieFiles')
if mfs:
for f in mfs:
p = f.get('path', '')
if p: print(p)
except Exception as e:
sys.stderr.write('radarr err: %s\n' % str(e))
" > "$cache_raw" 2>/dev/null
printf 'OK\n'
else
printf '⚠️ HTTP %s\n' "$http_code"
> "$cache_raw"
fi
elif [ "$app" = "sonarr" ]; then
local response http_code payload
response=$(curl -s -w "\n%{http_code}" --connect-timeout 10 --max-time 30 \
-H "X-Api-Key: ${key}" \
-H "Accept: application/json" \
"${url}/api/v3/series" 2>/dev/null)
http_code=$(printf '%s' "$response" | tail -n 1)
payload=$(printf '%s' "$response" | sed '$d')
if [ "$http_code" != "200" ]; then
printf '⚠️ HTTP %s (series)\n' "$http_code"
> "$cache_raw"
else
> "$cache_raw"
local series_id
while IFS= read -r series_id; do
[ -z "$series_id" ] && continue
local ef_resp
ef_resp=$(curl -s --connect-timeout 10 --max-time 30 \
-H "X-Api-Key: ${key}" \
-H "Accept: application/json" \
"${url}/api/v3/episodefile?seriesId=${series_id}" 2>/dev/null)
[ -n "$ef_resp" ] && printf '%s' "$ef_resp" | python3 -c "
import sys, json
try:
for f in json.load(sys.stdin):
p = f.get('path', '')
if p: print(p)
except: pass
" >> "$cache_raw" 2>/dev/null
done < <(printf '%s' "$payload" | python3 -c "
import sys, json
try:
for s in json.load(sys.stdin):
sid = s.get('id')
if sid:
print(sid)
except: pass
")
if [ -s "$cache_raw" ]; then
local series_count
series_count=$(printf '%s' "$payload" | python3 -c "
import sys, json
try:
print(len(json.load(sys.stdin)))
except: print('?')
")
printf 'OK (%s séries)\n' "$series_count"
else
printf '⚠️ vide\n'
> "$cache_raw"
fi
fi
fi
# Fallback si l'API est vide ou inaccessible
if [ ! -s "$cache_raw" ]; then
printf '⚠️ API vide, scan filesystem... '
> "$cache_raw"
for media_path in "${MEDIA_DIRS[@]}"; do
[ -d "$media_path" ] && \
find "$media_path" -type f \( -name "*.mkv" -o -name "*.mp4" -o \
-name "*.avi" -o -name "*.ts" \) 2>/dev/null >> "$cache_raw"
done
fi
# Traduction des chemins et indexation par inode
local count=0
while IFS= read -r raw_path; do
[ -z "$raw_path" ] && continue
local host_path
host_path=$(translate_path "$raw_path")
[ ! -f "$host_path" ] && continue
local inode
inode=$(stat -c '%i' "$host_path" 2>/dev/null || echo "0")
[ "$inode" = "0" ] && continue
ARR_MANAGED_INODES["$inode"]="$host_path"
count=$((count + 1))
done < "$cache_raw"
printf '%d fichier(s) → %d inode(s)\n' "$count" "${#ARR_MANAGED_INODES[@]}"
}
# =============================================================================
# RÉPARATION : hardlink manuel des orphelins
# =============================================================================
try_repair_file() {
local orphan_file="$1"
[ -z "$HASH_CMD" ] && return 3
[ ! -f "$orphan_file" ] && return 1
local fsize fname orphan_dev norm_orphan
fsize=$(stat -c '%s' "$orphan_file" 2>/dev/null) || return 1
fname=$(basename "$orphan_file")
orphan_dev=$(get_fs_id "$orphan_file")
norm_orphan=$(normalize_name "$fname")
printf ' 📄 %s (%d octets)\n' "$fname" "$fsize"
[ -n "$norm_orphan" ] && printf ' 🏷️ « %s »\n' "$norm_orphan"
# Candidats : même taille, même filesystem
local -a all_candidates=()
local media_dir media_dev
for media_dir in "${MEDIA_DIRS[@]}"; do
[ ! -d "$media_dir" ] && continue
media_dev=$(get_fs_id "$media_dir")
[ "$orphan_dev" -ne "$media_dev" ] && continue
local c
while IFS= read -r -d '' c; do
all_candidates+=("$c")
done < <(find "$media_dir" -type f -size "${fsize}c" -print0 2>/dev/null)
done
local total_candidates=${#all_candidates[@]}
printf ' 🔍 %d candidat(s) de même taille\n' "$total_candidates"
[ "$total_candidates" -eq 0 ] && return 1
# Split : noms similaires en priorité, fallback sinon
local -a priority=() fallback=() seen_inodes=()
local candidate c_inode already i
for candidate in "${all_candidates[@]}"; do
[ "$candidate" = "$orphan_file" ] && continue
c_inode=$(stat -c '%i' "$candidate" 2>/dev/null || echo "0")
already=false
for i in "${seen_inodes[@]}"; do
[ "$i" = "$c_inode" ] && { already=true; break; }
done
$already && continue
seen_inodes+=("$c_inode")
if [ "$(name_similarity "$fname" "$(basename "$candidate")")" != "none" ]; then
priority+=("$candidate")
else
fallback+=("$candidate")
fi
done
printf ' 📊 %d nom similaire + %d autre(s)\n' "${#priority[@]}" "${#fallback[@]}"
# Hachage du fichier orphelin
printf ' ⏳ Hachage... '
local fhash
fhash=$(file_hash "$orphan_file")
[ -z "$fhash" ] && { printf '❌\n'; return 1; }
printf '✓ %s...\n' "${fhash:0:8}"
# Test priorité (noms similaires)
local checked=0 cname chash
for candidate in "${priority[@]}"; do
checked=$((checked + 1))
cname=$(basename "$candidate")
printf ' [%d/%d] ⏳ %s... ' "$checked" "${#priority[@]}" "${cname:0:50}"
chash=$(file_hash "$candidate")
if [ -z "$chash" ]; then
printf '❌\n'
continue
fi
if [ "$chash" = "$fhash" ]; then
printf '✅ CORRESPONDANCE !\n'
printf ' 🔧 Hardlink...\n'
if rm -f "$orphan_file" 2>/dev/null && ln "$candidate" "$orphan_file" 2>/dev/null; then
printf ' ✅ Hardlink créé !\n'
do_chown "$orphan_file"
unset 'HASH_CACHE["$orphan_file"]'
return 0
else
printf ' ❌ Échec hardlink\n'
return 1
fi
fi
printf '✗\n'
done
# Test fallback (noms différents, même taille)
if [ "${#fallback[@]}" -gt 0 ]; then
printf '\n'
printf ' ⚠️ Aucun par nom — %d nom(s) différent(s)...\n' "${#fallback[@]}"
local total_fb checked_fb
total_fb=${#fallback[@]}
checked_fb=0
for candidate in "${fallback[@]}"; do
checked_fb=$((checked_fb + 1))
cname=$(basename "$candidate")
printf ' [%d/%d] ⏳ %s... ' "$checked_fb" "$total_fb" "${cname:0:50}"
chash=$(file_hash "$candidate")
if [ -z "$chash" ]; then
printf '❌\n'
continue
fi
if [ "$chash" = "$fhash" ]; then
printf '✅ CORRESPONDANCE (nom différent) !\n'
printf ' 🔧 Hardlink...\n'
if rm -f "$orphan_file" 2>/dev/null && ln "$candidate" "$orphan_file" 2>/dev/null; then
printf ' ✅ Hardlink créé !\n'
do_chown "$orphan_file"
unset 'HASH_CACHE["$orphan_file"]'
return 0
else
printf ' ❌ Échec hardlink\n'
return 1
fi
fi
printf '✗\n'
done
fi
printf ' ❌ Aucune correspondance\n'
return 1
}
# =============================================================================
# TRACKER SECRETS (durée minimale de seed)
# =============================================================================
TRACKER_SECRETS_FILE="${SCRIPT_DIR}/cleanup/tracker_secrets.conf"
load_tracker_secrets() {
declare -gA TRACKER_MIN_SEED
TRACKER_MIN_SEED=()
[ -f "$TRACKER_SECRETS_FILE" ] || return
while IFS='=' read -r domain hours; do
[ -z "$domain" ] && continue
[[ "$domain" =~ ^[[:space:]]*# ]] && continue
domain=$(printf '%s' "$domain" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
hours=$(printf '%s' "$hours" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
[ -n "$domain" ] && [ -n "$hours" ] && TRACKER_MIN_SEED["$domain"]="$hours"
done < "$TRACKER_SECRETS_FILE"
}
save_tracker_secrets() {
local tmpfile="${TRACKER_SECRETS_FILE}.$$"
> "$tmpfile"
for domain in "${!TRACKER_MIN_SEED[@]}"; do
printf '%s=%s\n' "$domain" "${TRACKER_MIN_SEED[$domain]}" >> "$tmpfile"
done
mv "$tmpfile" "$TRACKER_SECRETS_FILE" 2>/dev/null
chmod 600 "$TRACKER_SECRETS_FILE"
}
get_tracker_domain() {
local url="$1"
printf '%s' "$url" | sed -E 's|https?://||; s|/.*||; s|:.*||'
}
# Demande interactive (1ère fois) ou valeur conservatoire 999999 (non-interactif)
ask_tracker_min_seed() {
local domain="$1"
local hours=""
if [ -t 0 ]; then
while true; do
read -r -p "Durée min seed (h) pour [$domain] ? " hours
[[ "$hours" =~ ^[0-9]+$ ]] && break
printf ' Entrée invalide. Entrez un nombre entier d’heures (ex: 72).\n'
done
else
printf '⚠️ Tracker [%s] inconnu et mode non-interactif. Durée infinie appliquée.\n' "$domain" >&2
hours=999999
fi
TRACKER_MIN_SEED["$domain"]="$hours"
save_tracker_secrets
printf '%s' "$hours"
}
# Récupère la durée : mémoire → fichier → question interactive
get_tracker_min_seed_hours() {
local domain="$1"
local hours="${TRACKER_MIN_SEED[$domain]:-}"
if [ -z "$hours" ]; then
# Rechargement depuis le fichier (sous-shell précédent ?)
if [ -f "$TRACKER_SECRETS_FILE" ]; then
while IFS='=' read -r d h; do
[ -z "$d" ] && continue
[[ "$d" =~ ^[[:space:]]*# ]] && continue
d=$(printf '%s' "$d" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
h=$(printf '%s' "$h" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')
if [ "$d" = "$domain" ]; then
hours="$h"
TRACKER_MIN_SEED["$domain"]="$h"
break
fi
done < "$TRACKER_SECRETS_FILE"
fi
if [ -z "$hours" ]; then
hours=$(ask_tracker_min_seed "$domain")
TRACKER_MIN_SEED["$domain"]="$hours"
fi
fi
printf '%s' "$hours"
}
get_torrent_seed_hours() {
local instance="$1" hash="$2"
local props
props=$(qbit_get "$instance" "/api/v2/torrents/properties?hash=${hash}")
[ -z "$props" ] && return 1
local seeding_time
seeding_time=$(printf '%s' "$props" | python3 -c "
import sys, json
print(json.load(sys.stdin).get('seeding_time', 0))
" 2>/dev/null)
[ -z "$seeding_time" ] && seeding_time=0
printf '%s' "$((seeding_time / 3600))"
}
get_torrent_tracker_domain() {
local instance="$1" hash="$2"
local trackers
trackers=$(qbit_get "$instance" "/api/v2/torrents/trackers?hash=${hash}")
[ -z "$trackers" ] && return 1
local url
url=$(printf '%s' "$trackers" | python3 -c "
import sys, json
for t in json.load(sys.stdin):
u = t.get('url', '')
if not u:
continue
lu = u.lower()
if 'dht' in lu or 'pex' in lu or 'lsd' in lu or 'udp://' in lu:
continue
if u.startswith('http'):
print(u)
break
" 2>/dev/null)
[ -z "$url" ] && return 1
get_tracker_domain "$url"
}
# =============================================================================
# MAIN
# =============================================================================
main() {
local start_ts
start_ts=$(date +%s)
printf '╔══════════════════════════════════════════════════════════════╗\n'
printf '║ qBittorrent Nettoyage — Hardlinks Intelligents ║\n'
printf '╚══════════════════════════════════════════════════════════════╝\n'
printf '\n'
printf '📁 Configuration : %s\n' "$CONFIG_FILE"
printf '📁 Cache : %s\n' "$CACHE_DIR"
printf '\n'
if ! command -v curl &>/dev/null; then printf '❌ curl requis\n'; exit 1; fi
if ! command -v python3 &>/dev/null; then printf '❌ python3 requis\n'; exit 1; fi
pick_hash_tool
printf '🔧 Hachage : %s\n' "$HASH_CMD"
printf '\n'
printf '🗄️ Chargement des caches...\n'
load_hash_cache
load_inode_cache
load_torrent_cache
load_arr_inodes
printf '\n'
printf '🔌 Connexion aux instances...\n'
local instance
for instance in "${INSTANCES[@]}"; do
printf ' [%s] ' "$instance"
qbit_login "$instance" || { printf '❌ Échec connexion\n'; exit 1; }
printf '✓ Connecté\n'
done
printf '\n'
# -------------------------------------------------------------------------
# PHASE 0 : Récupération des torrents
# -------------------------------------------------------------------------
printf '📥 Récupération des torrents...\n'
local total=0
local json count hash name save_path size translated hpath
for instance in "${INSTANCES[@]}"; do
json=$(qbit_get "$instance" "/api/v2/torrents/info")
count=$(printf '%s' "$json" | python3 -c "import sys,json; print(len(json.load(sys.stdin)))" 2>/dev/null)
[ -z "$count" ] && count=0
printf ' [%s] %d torrent(s)\n' "$instance" "$count"
while IFS='|' read -r hash name save_path size; do
[ -z "$hash" ] && continue
hash="${hash^^}"
translated=$(translate_path "$save_path")
hpath="${translated}/${name}"
TORRENT_NAMES["$hash"]="$name"
TORRENT_INSTANCE["$hash"]="$instance"
TORRENT_SAVE_PATH["$hash"]="$save_path"
TORRENT_HOST_PATH["$hash"]="$hpath"
done < <(printf '%s' "$json" | python3 -c "
import sys, json
data = json.load(sys.stdin)
for t in data:
print(f\"{t.get('hash','')}|{t.get('name','')}|{t.get('save_path','')}|{t.get('size',0)}\")
" 2>/dev/null)
total=$((total + count))
done
printf ' ✓ %d torrent(s) au total\n' "$total"
printf '\n'
local torrent_direct=0 torrent_cross_linked=0 torrent_orphan=0 repaired_count=0
# -------------------------------------------------------------------------
# PHASE 1 : Inodes des Arr (Radarr/Sonarr)
# -------------------------------------------------------------------------
printf '═══════════════════════════════════════════════════════════════\n'
printf 'PHASE 1 — Récupération des inodes Radarr/Sonarr\n'
printf '═══════════════════════════════════════════════════════════════\n'
local need_fetch_arr=true
if [ "$ARR_CACHE_DURATION" -gt 0 ] && [ "${#ARR_MANAGED_INODES[@]}" -gt 0 ]; then
local age
age=$(( $(date +%s) - $(stat -c '%Y' "$ARR_INODES_FILE" 2>/dev/null || echo 0) ))
[ "$age" -lt "$ARR_CACHE_DURATION" ] && need_fetch_arr=false
fi
if $need_fetch_arr; then
if [ "$ARR_CACHE_DURATION" -eq 0 ]; then
printf ' 🔄 Cache Arr désactivé (ARR_CACHE_DURATION=0) → interrogation API...\n'
fi
ARR_MANAGED_INODES=()
local seen_urls=""
for instance in "${INSTANCES[@]}"; do
local has_arr=false
for cfg_key in "${!ARR_CONFIG[@]}"; do
[[ "$cfg_key" == "${instance}|"* ]] || continue
has_arr=true
local app url key ae
app="${cfg_key#*|}"
ae="${ARR_CONFIG[$cfg_key]}"
url="${ae%%|*}"
key="${ae#*|}"
if [ "$app" != "radarr" ] && [ "$app" != "sonarr" ]; then
printf ' [%s] ⚠️ App inconnu : "%s"\n' "$instance" "$app"
continue
fi
if [[ "$seen_urls" == *"|${url}|"* ]]; then
printf ' [%s] %s → %s (⏭️ déjà traité)\n' "$instance" "$app" "$url"
continue
fi
seen_urls="${seen_urls}|${url}|"
printf ' [%s] %s → %s\n' "$instance" "$app" "$url"
fetch_arr_inodes_bulk "$app" "$url" "$key"
done
if ! $has_arr; then
printf ' [%s] ⏭️ pas configuré (aucune entrée ARR_CONFIG["%s|..."])\n' "$instance" "$instance"
fi
done
save_arr_inodes_bulk
printf ' ✓ %d inodes Arr chargés\n' "${#ARR_MANAGED_INODES[@]}"
else
printf ' ⏭️ Cache Arr valide (%d inodes, < %ss)\n' \
"${#ARR_MANAGED_INODES[@]}" "$ARR_CACHE_DURATION"
fi
printf '\n'
# -------------------------------------------------------------------------
# PHASE 2 : Torrents déjà liés (cache ou inode match)
# -------------------------------------------------------------------------
printf '═══════════════════════════════════════════════════════════════\n'
printf 'PHASE 2 — Marquage des torrents liés (inodes Arr)\n'
printf '═══════════════════════════════════════════════════════════════\n'
local arr_matched=0 arr_skipped=0 idx=0
local cache_key cached_entry cached_status hpath found_arr f finode
for hash in "${!TORRENT_NAMES[@]}"; do
idx=$((idx + 1))
instance="${TORRENT_INSTANCE[$hash]}"
cache_key="${hash}|${instance}"
cached_entry="${TORRENT_CACHE[$cache_key]:-}"
if [ -n "$cached_entry" ]; then
cached_status="${cached_entry%|*}"
if [ "$cached_status" = "linked" ]; then
batch_add "$instance" "$TAG_LINKED" "$hash"
arr_skipped=$((arr_skipped + 1))
printf '\r [%3d/%3d] ⏭️ [%s] (caché) %-50s' "$idx" "$total" "$instance" "${TORRENT_NAMES[$hash]:0:50}"
continue
fi
fi
hpath="${TORRENT_HOST_PATH[$hash]:-}"
[ -z "$hpath" ] && continue
[ ! -e "$hpath" ] && continue
found_arr=false
while IFS= read -r -d '' f; do
finode=$(stat -c '%i' "$f" 2>/dev/null || echo "0")
if [ -n "${ARR_MANAGED_INODES[$finode]:-}" ]; then
found_arr=true
break
fi
done < <(find "$hpath" -type f -print0 2>/dev/null)
if $found_arr; then
batch_add "$instance" "$TAG_LINKED" "$hash"
save_torrent_entry "$hash" "$instance" "linked"
arr_matched=$((arr_matched + 1))
printf '\r [%3d/%3d] ✅ [%s] Arr lié %-50s' "$idx" "$total" "$instance" "${TORRENT_NAMES[$hash]:0:50}"
else
printf '\r [%3d/%3d] ❓ [%s] %-50s' "$idx" "$total" "$instance" "${TORRENT_NAMES[$hash]:0:50}"
fi
done
printf '\n'
printf ' ✓ Arr : %d lié(s) (dont %d depuis cache)\n' "$arr_matched" "$arr_skipped"
printf '\n'
torrent_direct=$arr_matched
# -------------------------------------------------------------------------
# PHASE 3 : Analyse des inodes des fichiers torrents
# -------------------------------------------------------------------------
printf '═══════════════════════════════════════════════════════════════\n'