-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPhotosDownloadMonitor.command
More file actions
417 lines (360 loc) · 12.2 KB
/
PhotosDownloadMonitor.command
File metadata and controls
417 lines (360 loc) · 12.2 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
#!/usr/bin/env bash
set -Eeuo pipefail
# Percorsi comuni nel PATH (pipx/homebrew)
export PATH="$PATH:/usr/local/bin:/opt/homebrew/bin:$HOME/.local/bin"
# Sorgente locale della tua export (adatta se necessario)
SRC_LOCAL="/Users/Shared/PhotosExport/"
# === Config persistente NAS ===
CONFIG_FILE="$HOME/.photos_monitor.conf"
default_if_empty() {
local var="$1" def="$2"; [ -z "$var" ] && echo "$def" || echo "$var"
}
# --- sostituisci TUTTA la tua save_config con questa ---
save_config() {
umask 077
# funzione per fare escaping sicuro tra apici singoli: foo'bar -> 'foo'"'"'bar'
_sq() { printf "%s" "$1" | sed "s/'/'\"'\"'/g"; }
cat > "$CONFIG_FILE" <<'EOF'
# Photos Monitor NAS config (auto-generato). Modificalo con attenzione.
# Esempi:
# NAS_HOST=nas.local
# NAS_USER=utente
# NAS_PHOTO_DIR=/volume1/photo
# SSH_OPTS='-o ServerAliveInterval=30 -o ServerAliveCountMax=10'
# RSYNC_EXCLUDES="--exclude .DS_Store --exclude '._*' --exclude 'Thumbs.db' --exclude '@eaDir' --exclude '#recycle' --exclude '_deleted_quarantine'"
EOF
{
printf "NAS_HOST='%s'\n" "$(_sq "${NAS_HOST}")"
printf "NAS_USER='%s'\n" "$(_sq "${NAS_USER}")"
printf "NAS_PHOTO_DIR='%s'\n" "$(_sq "${NAS_PHOTO_DIR}")"
printf "SSH_OPTS='%s'\n" "$(_sq "${SSH_OPTS}")"
printf "RSYNC_EXCLUDES='%s'\n" "$(_sq "${RSYNC_EXCLUDES}")"
} >> "$CONFIG_FILE"
echo "Configurazione salvata in $CONFIG_FILE (permessi 600)."
}
# --- sostituisci TUTTA la tua reconfigure_config con questa ---
reconfigure_config() {
echo "== Riconfigurazione NAS =="
echo "Valori attuali tra parentesi quadre []. Lascia vuoto per mantenere."
read -r -p "Host/IP NAS [${NAS_HOST:-}]: " _host
read -r -p "Utente DSM [${NAS_USER:-}]: " _user
read -r -p "Cartella Photos sul NAS [${NAS_PHOTO_DIR:-}]: " _dir
read -r -p "SSH_OPTS [${SSH_OPTS:-'-o ServerAliveInterval=30 -o ServerAliveCountMax=10'}]: " _ssh
read -r -p "RSYNC_EXCLUDES [${RSYNC_EXCLUDES:-'--exclude .DS_Store …'}]: " _ex
NAS_HOST="${_host:-${NAS_HOST:-}}"
NAS_USER="${_user:-${NAS_USER:-}}"
NAS_PHOTO_DIR="${_dir:-${NAS_PHOTO_DIR:-}}"
SSH_OPTS="${_ssh:-${SSH_OPTS:-'-o ServerAliveInterval=30 -o ServerAliveCountMax=10'}}"
RSYNC_EXCLUDES="${_ex:-${RSYNC_EXCLUDES:-"--exclude .DS_Store --exclude '._*' --exclude 'Thumbs.db' --exclude '@eaDir' --exclude '#recycle' --exclude '_deleted_quarantine'"}}"
save_config
}
prompt_config() {
echo "== Configurazione NAS =="
read -r -p "Host/IP NAS (es. nas.local o 192.168.1.10): " NAS_HOST
read -r -p "Utente DSM (es. enrico): " NAS_USER
read -r -p "Cartella Photos sul NAS (es. /volume1/photo): " NAS_PHOTO_DIR
# Opzioni di default ragionevoli
SSH_OPTS=$(default_if_empty "${SSH_OPTS:-}" "-o ServerAliveInterval=30 -o ServerAliveCountMax=10")
RSYNC_EXCLUDES=$(default_if_empty "${RSYNC_EXCLUDES:-}" "--exclude .DS_Store --exclude '._*' --exclude 'Thumbs.db' --exclude '@eaDir' --exclude '#recycle' --exclude '_deleted_quarantine'")
save_config
}
load_or_init_config() {
if [ -f "$CONFIG_FILE" ]; then
# shellcheck disable=SC1090
. "$CONFIG_FILE"
# Validazione minima
if [ -z "${NAS_HOST:-}" ] || [ -z "${NAS_USER:-}" ] || [ -z "${NAS_PHOTO_DIR:-}" ]; then
echo "Config incompleta. Rigenero…"
prompt_config
fi
else
prompt_config
fi
}
# Inizializza/Carica config
load_or_init_config
# === Resto delle tue variabili/utility esistenti può rimanere qui sotto ===
# Esempio: variabili derivate che usi più avanti
REPORT_DIR="${REPORT_DIR:-$HOME/Desktop}"
TMP_EXPORT="${TMP_EXPORT:-/tmp/osxphotos_nullo_export}"
INTERVAL="${INTERVAL:-60}"
# Individua osxphotos in modo robusto
OSXPHOTOS="osxphotos"
if ! command -v osxphotos >/dev/null 2>&1; then
PYNEW="$(command -v python3.12 || command -v python3.11 || command -v python3 || true)"
if [ -n "$PYNEW" ] && "$PYNEW" -c "import osxphotos" 2>/dev/null; then
OSXPHOTOS="$PYNEW -m osxphotos"
fi
fi
require() {
command -v "$1" >/dev/null 2>&1 || { echo "Manca '$1' nel PATH"; exit 1; }
}
require osxphotos
require rsync
require ssh
command -v jq >/dev/null 2>&1 || true # opzionale
launch_photos() {
echo "Avvio App Foto se non è già in esecuzione..."
osascript -e 'tell application "Photos" to launch' >/dev/null 2>&1 || true
sleep 2
}
show_counts() {
local total missing incloud local_count
total=$(osxphotos query --count || echo "NA")
missing=$(osxphotos query --missing --count || echo "NA")
incloud=$(osxphotos query --incloud --count || echo "NA")
local_count=$(osxphotos query --not-missing --count || echo "NA")
echo "Totale elementi: $total"
echo "Non scaricati (missing): $missing"
echo "Presenti in iCloud: $incloud"
echo "Presenti su disco: $local_count"
}
force_download_dryrun() {
mkdir -p "$TMP_EXPORT"
local stamp report
stamp=$(date +"%Y%m%d-%H%M%S")
report="$REPORT_DIR/osxphotos-download-report-$stamp.json"
echo "Forzo il download degli originali (dry-run export)."
echo "Report: $report"
osxphotos export "$TMP_EXPORT" \
--download-missing \
--dry-run \
--report "$report" \
--overwrite \
--update || true
echo "Richiesta inviata a Foto. Lasciala aperta e collegata alla rete."
}
force_download_real_min() {
mkdir -p "$TMP_EXPORT"
local stamp report
stamp=$(date +"%Y%m%d-%H%M%S")
report="$REPORT_DIR/osxphotos-download-export-$stamp.json"
echo "Forzo il download con una esportazione minima su $TMP_EXPORT"
echo "Report: $report"
osxphotos export "$TMP_EXPORT" \
--download-missing \
--report "$report" \
--overwrite \
--update \
--skip-live \
--timeout 0 || true
echo "Pulizia della cartella temporanea..."
rm -rf "$TMP_EXPORT" || true
echo "Fatto."
}
rsync_preview() {
local dest quarantine
quarantine="$NAS_PHOTO_DIR/_deleted_quarantine/DRYRUN_$(date +%Y-%m-%d_%H-%M-%S)"
dest="${NAS_USER}@${NAS_HOST}:$(printf %q "$NAS_PHOTO_DIR")/"
echo "Anteprima sincronizzazione (dry-run)"
rsync -av --human-readable --info=stats2,progress2 --protect-args --partial --inplace --no-compress \
$RSYNC_EXCLUDES -e "ssh $SSH_OPTS" \
--delete --backup --backup-dir="$quarantine" \
--dry-run \
"$SRC_LOCAL" "$dest"
}
ensure_quarantine() {
local q="$NAS_PHOTO_DIR/_deleted_quarantine/$(date +%Y-%m-%d_%H-%M-%S)"
ssh $SSH_OPTS "${NAS_USER}@${NAS_HOST}" "mkdir -p $(printf %q "$q")"
echo "$q"
}
rsync_sync() {
local quarantine dest
quarantine="$(ensure_quarantine)"
dest="${NAS_USER}@${NAS_HOST}:$(printf %q "$NAS_PHOTO_DIR")/"
echo "Sincronizzo con quarantena: $quarantine"
rsync -av --human-readable --info=stats2,progress2 --protect-args --partial --inplace --no-compress \
$RSYNC_EXCLUDES -e "ssh $SSH_OPTS" \
--delete --backup --backup-dir="$quarantine" \
"$SRC_LOCAL" "$dest"
}
check_live_report() {
# Arg1: titolo per output, Arg2: directory di scansione (locale) o stringa "REMOTE"
# Se REMOTE, legge i path da STDIN (uno per riga)
local title="$1"
local scan_dir="$2"
local stamp report_csv
stamp=$(date +"%Y%m%d-%H%M%S")
report_csv="$HOME/Desktop/LivePhotoReport_${title// /_}_$stamp.csv"
echo "Analisi Live Photos: $title"
echo "Generazione report: $report_csv"
if [ "$scan_dir" != "REMOTE" ]; then
# Elenco file localmente
find "$scan_dir" -type f \( -iname "*.heic" -o -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.mov" \) -print0 \
| python3 - "$report_csv" << 'PY'
import sys, os, csv
from collections import defaultdict
out_csv = sys.argv[1]
pairs = defaultdict(lambda: {"img": False, "mov": False, "img_paths": [], "mov_paths": []})
def stem(p):
b = os.path.basename(p)
s, e = os.path.splitext(b)
return s.lower()
def is_img(p):
return os.path.splitext(p)[1].lower() in (".heic",".jpg",".jpeg")
def is_mov(p):
return os.path.splitext(p)[1].lower() == ".mov"
# leggi input nul-separated
data = sys.stdin.buffer.read().split(b'\x00')
for raw in data:
if not raw:
continue
p = raw.decode("utf-8", "ignore")
st = stem(p)
if is_img(p):
pairs[st]["img"] = True
pairs[st]["img_paths"].append(p)
elif is_mov(p):
pairs[st]["mov"] = True
pairs[st]["mov_paths"].append(p)
ok = miss_mov = miss_img = 0
rows = []
for st, info in pairs.items():
if info["img"] and info["mov"]:
ok += 1
rows.append(["OK", st, ";".join(info["img_paths"]), ";".join(info["mov_paths"])])
elif info["img"] and not info["mov"]:
miss_mov += 1
rows.append(["MISSING_MOV", st, ";".join(info["img_paths"]), ""])
elif info["mov"] and not info["img"]:
miss_img += 1
rows.append(["MISSING_IMAGE", st, "", ";".join(info["mov_paths"])])
with open(out_csv, "w", newline="") as f:
w = csv.writer(f)
w.writerow(["status","basename","image_paths","mov_paths"])
w.writerows(rows)
print(f"Live OK: {ok}")
print(f"Immagini senza MOV: {miss_mov}")
print(f"MOV senza immagine: {miss_img}")
PY
else
# Elenco file ricevuti da STDIN (uno per riga) per analisi remota
python3 - "$report_csv" << 'PY'
import sys, os, csv
from collections import defaultdict
out_csv = sys.argv[1]
pairs = defaultdict(lambda: {"img": False, "mov": False, "img_paths": [], "mov_paths": []})
def stem(p):
b = os.path.basename(p)
s, e = os.path.splitext(b)
return s.lower()
def is_img(p):
return os.path.splitext(p)[1].lower() in (".heic",".jpg",".jpeg")
def is_mov(p):
return os.path.splitext(p)[1].lower() == ".mov"
for line in sys.stdin:
p = line.rstrip("\n")
if not p:
continue
st = stem(p)
if is_img(p):
pairs[st]["img"] = True
pairs[st]["img_paths"].append(p)
elif is_mov(p):
pairs[st]["mov"] = True
pairs[st]["mov_paths"].append(p)
ok = miss_mov = miss_img = 0
rows = []
for st, info in pairs.items():
if info["img"] and info["mov"]:
ok += 1
rows.append(["OK", st, ";".join(info["img_paths"]), ";".join(info["mov_paths"])])
elif info["img"] and not info["mov"]:
miss_mov += 1
rows.append(["MISSING_MOV", st, ";".join(info["img_paths"]), ""])
elif info["mov"] and not info["img"]:
miss_img += 1
rows.append(["MISSING_IMAGE", st, "", ";".join(info["mov_paths"])])
with open(out_csv, "w", newline="") as f:
w = csv.writer(f)
w.writerow(["status","basename","image_paths","mov_paths"])
w.writerows(rows)
print(f"Live OK: {ok}")
print(f"Immagini senza MOV: {miss_mov}")
print(f"MOV senza immagine: {miss_img}")
PY
fi
echo "Report salvato in: $report_csv"
}
check_live_local() {
# Analizza la sorgente locale (la tua export dal Mac)
local SRC="/Users/Shared/PhotosExport"
if [ ! -d "$SRC" ]; then
echo "Sorgente non trovata: $SRC"
return 1
fi
check_live_report "LOCAL" "$SRC"
}
check_live_nas() {
# Analizza direttamente sul NAS (non richiede Python sul NAS)
# Elenca i file e li passa in streaming al parser locale
local stamp title="NAS"
echo "Scansione NAS: ${NAS_HOST}:${NAS_PHOTO_DIR} (può richiedere tempo)..."
ssh $SSH_OPTS "${NAS_USER}@${NAS_HOST}" \
"find $(printf %q "$NAS_PHOTO_DIR") -type f \\( -iname '*.heic' -o -iname '*.jpg' -o -iname '*.jpeg' -o -iname '*.mov' \\) -print" \
| check_live_report "NAS" "REMOTE"
}
menu() {
echo
echo "=== Photos Download Monitor + NAS Sync ==="
echo "0) Configura/Riconfigura NAS"
echo "1) Mostra conteggio attuale"
echo "2) Monitor continuo"
echo "3) Forza download (dry-run)"
echo "4) Forza download (export minimo)"
echo "5) Esci"
echo "------------------------------------------"
echo "6) Preview sincronizzazione NAS (dry-run)"
echo "7) Sincronizza ORA con quarantena"
echo "------------------------------------------"
echo "8) Controllo Live Photos (LOCALE)"
echo "9) Controllo Live Photos (NAS)"
echo -n "Scelta: "
}
launch_photos
while true; do
menu
read -r choice
case "$choice" in
0)
reconfigure_config
;;
1)
date
show_counts
;;
2)
echo "Monitor continuo: Ctrl+C per uscire."
while true; do
date
show_counts
sleep "$INTERVAL"
done
;;
3)
force_download_dryrun
;;
4)
force_download_real_min
;;
5)
echo "Ciao!"
exit 0
;;
6)
rsync_preview
;;
7)
rsync_sync
;;
8)
check_live_local
;;
9)
check_live_nas
;;
*)
echo "Scelta non valida."
;;
esac
done