|
1 | 1 | # Rimozione file non musicali e pulizia cartelle vuote in una directory. |
2 | 2 | import os |
3 | 3 | import re |
| 4 | +import subprocess |
| 5 | +import getpass |
4 | 6 |
|
5 | 7 | # Definisci le estensioni dei file musicali che vuoi preservare |
6 | 8 | musical_extensions = re.compile(r'\.(flac|opus|mp3|m4a|aac)$', re.IGNORECASE) |
7 | 9 |
|
| 10 | +def mount_smb_share(unc_path, username=None, password=None): |
| 11 | + """Monta una condivisione SMB usando net use""" |
| 12 | + try: |
| 13 | + # Estrai server e share dal percorso UNC |
| 14 | + # Formato: \\server\share\path |
| 15 | + if not unc_path.startswith('\\\\'): |
| 16 | + return None, "Percorso non UNC valido" |
| 17 | + |
| 18 | + path_parts = unc_path[2:].split('\\') |
| 19 | + if len(path_parts) < 2: |
| 20 | + return None, "Formato percorso UNC non valido" |
| 21 | + |
| 22 | + server = path_parts[0] |
| 23 | + share = path_parts[1] |
| 24 | + |
| 25 | + # Crea il percorso di mount locale (es. Z:) |
| 26 | + drive_letter = "Z:" |
| 27 | + |
| 28 | + # Comando net use |
| 29 | + cmd = f'net use {drive_letter} \\\\{server}\\{share}' |
| 30 | + |
| 31 | + if username and password: |
| 32 | + cmd += f' /user:{username} "{password}"' |
| 33 | + |
| 34 | + result = subprocess.run(cmd, shell=True, capture_output=True, text=True) |
| 35 | + |
| 36 | + if result.returncode == 0: |
| 37 | + # Restituisci il percorso montato |
| 38 | + mounted_path = f"{drive_letter}\\{'\\'.join(path_parts[2:]) if len(path_parts) > 2 else ''}" |
| 39 | + return mounted_path.rstrip('\\'), None |
| 40 | + else: |
| 41 | + return None, f"Errore nel montare la condivisione: {result.stderr}" |
| 42 | + |
| 43 | + except Exception as e: |
| 44 | + return None, f"Errore durante il montaggio: {str(e)}" |
| 45 | + |
| 46 | +def unmount_smb_share(drive_letter="Z:"): |
| 47 | + """Smonta una condivisione SMB""" |
| 48 | + try: |
| 49 | + cmd = f'net use {drive_letter} /delete' |
| 50 | + result = subprocess.run(cmd, shell=True, capture_output=True, text=True) |
| 51 | + return result.returncode == 0 |
| 52 | + except: |
| 53 | + return False |
| 54 | + |
8 | 55 | def delete_non_music_files(folder_path): |
9 | | - for root, dirs, files in os.walk(folder_path, topdown=False): |
10 | | - for name in files: |
11 | | - file_path = os.path.join(root, name) |
12 | | - # Se il file non ha un'estensione musicale, viene eliminato |
13 | | - if not musical_extensions.search(name): |
14 | | - print(f"Deleting file: {file_path}") |
15 | | - os.remove(file_path) |
16 | | - |
17 | | - for name in dirs: |
18 | | - dir_path = os.path.join(root, name) |
19 | | - # Se la cartella è vuota, viene eliminata |
20 | | - if not os.listdir(dir_path): |
21 | | - print(f"Deleting empty directory: {dir_path}") |
22 | | - os.rmdir(dir_path) |
| 56 | + try: |
| 57 | + for root, dirs, files in os.walk(folder_path, topdown=False): |
| 58 | + # Gestione sicura dei file |
| 59 | + for name in files: |
| 60 | + try: |
| 61 | + file_path = os.path.join(root, name) |
| 62 | + # Se il file non ha un'estensione musicale, viene eliminato |
| 63 | + if not musical_extensions.search(name): |
| 64 | + print(f"Deleting file: {file_path}") |
| 65 | + os.remove(file_path) |
| 66 | + except (OSError, PermissionError) as e: |
| 67 | + print(f"Impossibile eliminare il file {file_path}: {e}") |
| 68 | + continue |
| 69 | + |
| 70 | + # Gestione sicura delle directory |
| 71 | + for name in dirs: |
| 72 | + try: |
| 73 | + dir_path = os.path.join(root, name) |
| 74 | + # Se la cartella è vuota, viene eliminata |
| 75 | + if not os.listdir(dir_path): |
| 76 | + print(f"Deleting empty directory: {dir_path}") |
| 77 | + os.rmdir(dir_path) |
| 78 | + except (OSError, PermissionError) as e: |
| 79 | + print(f"Impossibile eliminare la directory {dir_path}: {e}") |
| 80 | + continue |
| 81 | + except (OSError, PermissionError) as e: |
| 82 | + print(f"Errore durante l'accesso al percorso {folder_path}: {e}") |
| 83 | + return |
| 84 | + |
| 85 | +def is_valid_path(path, use_smb=True): |
| 86 | + """Verifica se un percorso è valido e accessibile""" |
| 87 | + try: |
| 88 | + # Per percorsi UNC, proviamo prima se esiste |
| 89 | + if path.startswith('\\\\') or (len(path) > 1 and path[1] == ':'): |
| 90 | + return os.path.exists(path) |
| 91 | + return False |
| 92 | + except (OSError, PermissionError): |
| 93 | + if use_smb and path.startswith('\\\\'): |
| 94 | + return None # Indica che potrebbe essere necessario SMB |
| 95 | + return False |
| 96 | + |
| 97 | +def get_smb_credentials(): |
| 98 | + """Chiede le credenziali SMB all'utente""" |
| 99 | + print("\nRichieste credenziali per la condivisione di rete:") |
| 100 | + username = input("Username: ").strip() |
| 101 | + password = getpass.getpass("Password: ") |
| 102 | + return username, password |
23 | 103 |
|
24 | 104 | def main(): |
25 | 105 | folder_path = input("Inserisci il percorso della cartella: ").strip() |
26 | | - if os.path.isdir(folder_path): |
27 | | - delete_non_music_files(folder_path) |
28 | | - print("Pulizia completata.") |
| 106 | + |
| 107 | + # Normalizza il percorso rimuovendo eventuali virgolette |
| 108 | + folder_path = folder_path.strip('"\'') |
| 109 | + |
| 110 | + mounted_path = None |
| 111 | + drive_letter = None |
| 112 | + |
| 113 | + # Verifica se il percorso è accessibile direttamente |
| 114 | + path_check = is_valid_path(folder_path, use_smb=False) |
| 115 | + |
| 116 | + if not path_check and folder_path.startswith('\\\\'): |
| 117 | + print("Il percorso di rete non è accessibile direttamente.") |
| 118 | + print("Tentativo di connessione tramite SMB...") |
| 119 | + |
| 120 | + # Chiedi credenziali |
| 121 | + username, password = get_smb_credentials() |
| 122 | + |
| 123 | + # Tenta di montare la condivisione |
| 124 | + mounted_path, error = mount_smb_share(folder_path, username, password) |
| 125 | + |
| 126 | + if error: |
| 127 | + print(f"Errore durante la connessione: {error}") |
| 128 | + print("Verifica username, password e che la condivisione sia raggiungibile.") |
| 129 | + return |
| 130 | + |
| 131 | + if mounted_path and os.path.exists(mounted_path): |
| 132 | + print(f"Connessione SMB stabilita. Utilizzando: {mounted_path}") |
| 133 | + # Usa il percorso montato per l'operazione |
| 134 | + work_path = mounted_path |
| 135 | + drive_letter = "Z:" |
| 136 | + else: |
| 137 | + print("Impossibile accedere al percorso anche dopo la connessione SMB.") |
| 138 | + return |
| 139 | + elif path_check: |
| 140 | + # Percorso accessibile direttamente |
| 141 | + work_path = folder_path |
29 | 142 | else: |
30 | | - print("Il percorso inserito non è valido. Per favore riprova.") |
| 143 | + print("Il percorso inserito non è valido o non è accessibile. Per favore riprova.") |
| 144 | + return |
| 145 | + |
| 146 | + try: |
| 147 | + delete_non_music_files(work_path) |
| 148 | + print("Pulizia completata.") |
| 149 | + except PermissionError: |
| 150 | + print(f"Errore: Accesso negato al percorso '{work_path}'. Verifica i permessi.") |
| 151 | + except OSError as e: |
| 152 | + print(f"Errore durante la pulizia: {e}") |
| 153 | + except Exception as e: |
| 154 | + print(f"Errore imprevisto: {e}") |
| 155 | + finally: |
| 156 | + # Smonta la condivisione SMB se era stata montata |
| 157 | + if drive_letter: |
| 158 | + print("Disconnessione dalla condivisione di rete...") |
| 159 | + if unmount_smb_share(drive_letter): |
| 160 | + print("Disconnessione completata.") |
| 161 | + else: |
| 162 | + print("Attenzione: impossibile disconnettere automaticamente la condivisione.") |
31 | 163 |
|
32 | 164 | if __name__ == "__main__": |
33 | 165 | while True: |
|
0 commit comments