Download OBJECTS-MAPPED/scripts/archive.org-cli.py from pebxcvi/PSHomeCacheDepot: direct link, hf CLI and curl.
- Browser
- Download file 29.9 kB
-
https://huggingface.co/datasets/pebxcvi/PSHomeCacheDepot/resolve/main/OBJECTS-MAPPED/scripts/archive.org-cli.py
- Command line
-
hf download hf://datasets/pebxcvi/PSHomeCacheDepot/OBJECTS-MAPPED/scripts/archive.org-cli.py
-
curl -L -o archive.org-cli.py https://huggingface.co/datasets/pebxcvi/PSHomeCacheDepot/resolve/main/OBJECTS-MAPPED/scripts/archive.org-cli.py
29.9 kB
| import internetarchive | |
| import os | |
| import re | |
| import time | |
| ITEM_ID = "PSHomeMappedObjects" | |
| SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| FILE_LIST = os.path.join(SCRIPT_DIR, "log.txt") | |
| SOURCE_DIR = r"Q:\PSHOME-INT\PSHomeCacheDepot\OBJECTS-MAPPED\ARCHIVE" | |
| # SET THIS: | |
| # "upload" = upload ZIP files using either normal folder scanning or log.txt, selected by UPLOAD_FROM_LOG | |
| # "delete" = delete files listed in log.txt | |
| MODE = "upload" | |
| START_FOLDER = "0" | |
| PAUSE_AFTER_EACH_FOLDER = False | |
| # UPLOAD METHOD SWITCH: | |
| # True = send multiple ZIP files in each internetarchive.upload() request. | |
| # False = send one ZIP file per internetarchive.upload() request. | |
| UPLOAD_IN_BATCHES = True | |
| # When UPLOAD_IN_BATCHES is True: | |
| # Number of ZIP files sent in each upload request. | |
| # | |
| # When UPLOAD_IN_BATCHES is False: | |
| # Files are still uploaded one per request, but this value controls | |
| # how many individual uploads occur before the optional batch pause. | |
| UPLOAD_BATCH_SIZE = 50 | |
| # True = pause after each group of UPLOAD_BATCH_SIZE files. | |
| # False = continue automatically. | |
| PAUSE_AFTER_EACH_UPLOAD_BATCH = False | |
| # UPLOAD SOURCE SWITCH: | |
| # False = normal mode: scan SOURCE_DIR folders 0-9/A-F starting at START_FOLDER. | |
| # True = log mode: upload only ZIP files listed in log.txt. | |
| UPLOAD_FROM_LOG = False | |
| # In log mode, entries may be: | |
| # 17031A08-070245ED-A2766E0F-B1ACC605_T032 | |
| # 17031A08-070245ED-A2766E0F-B1ACC605_T032.zip | |
| # 1/17031A08-070245ED-A2766E0F-B1ACC605_T032.zip | |
| # Q:\PSHOME-INT\PSHomeCacheDepot\OBJECTS-MAPPED\ARCHIVE\1\17031A08-070245ED-A2766E0F-B1ACC605_T032.zip | |
| UPLOAD_LOG_FILE = FILE_LIST | |
| # Archive.org upload safety settings. | |
| # ZIP files normally do not need Archive.org derivatives, so leave this True. | |
| NO_DERIVE = True | |
| # Number of automatic retries after a 503 response. | |
| # Leave at 0 so a global queue limit stops cleanly without re-uploading the same ZIP. | |
| UPLOAD_RETRIES = 0 | |
| # Delay after each attempted file upload. Increase this if Archive.org throttles often. | |
| UPLOAD_DELAY_SECONDS = 2.0 | |
| # Stop the entire run when Archive.org reports its global task queue is full. | |
| # Continuing would only produce thousands of repeated failures. | |
| STOP_ON_RATE_LIMIT = True | |
| FOLDER_ORDER = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] | |
| UPLOAD_EXTS = {".zip"} | |
| DELETE_EXTS = {".zip", ".torrent"} | |
| def pause_exit(): | |
| input("\nPress Enter to exit...") | |
| def is_allowed_upload_file(name): | |
| return os.path.splitext(name)[1].lower() in UPLOAD_EXTS | |
| def clean_name(line): | |
| text = line.strip().strip('"').strip("'").replace("\\", "/") | |
| return text.split("/")[-1].strip() | |
| def normalize_delete_file_name(line): | |
| name = clean_name(line) | |
| if not name: | |
| return None | |
| root, ext = os.path.splitext(name) | |
| ext_low = ext.lower() | |
| if ext == "": | |
| return name + ".zip" | |
| if ext_low in DELETE_EXTS: | |
| return name | |
| return None | |
| def normalize_delete_zip_name(line): | |
| name = clean_name(line) | |
| if not name: | |
| return None | |
| root, ext = os.path.splitext(name) | |
| ext_low = ext.lower() | |
| if ext == "": | |
| return name + ".zip" | |
| if ext_low == ".zip": | |
| return name | |
| return None | |
| def normalize_delete_torrent_name(line): | |
| name = clean_name(line) | |
| if not name: | |
| return None | |
| root, ext = os.path.splitext(name) | |
| if ext.lower() == ".torrent": | |
| return name | |
| return None | |
| def normalize_folder(folder): | |
| return folder.strip().upper() | |
| def get_start_folders(): | |
| start = normalize_folder(START_FOLDER) | |
| if start not in FOLDER_ORDER: | |
| raise ValueError(f"Invalid START_FOLDER: {START_FOLDER}") | |
| start_index = FOLDER_ORDER.index(start) | |
| return FOLDER_ORDER[start_index:] | |
| def get_folder_from_zip_name(name): | |
| base = normalize_delete_zip_name(name) | |
| if not base: | |
| raise ValueError(f"Invalid zip filename: {name}") | |
| first = base[:1].upper() | |
| if first not in FOLDER_ORDER: | |
| raise ValueError(f"Cannot determine archive folder from filename: {name}") | |
| return first | |
| def remote_name_from_zip_name(name): | |
| base = normalize_delete_zip_name(name) | |
| if not base: | |
| raise ValueError(f"Invalid zip filename: {name}") | |
| folder = get_folder_from_zip_name(base) | |
| return f"{folder}/{base}" | |
| def remote_name_from_torrent_name(name): | |
| base = normalize_delete_torrent_name(name) | |
| if not base: | |
| raise ValueError(f"Invalid torrent filename: {name}") | |
| return base | |
| def remote_name_from_delete_name(name): | |
| base = normalize_delete_file_name(name) | |
| if not base: | |
| raise ValueError(f"Unsupported delete filename: {name}") | |
| ext_low = os.path.splitext(base)[1].lower() | |
| if ext_low == ".zip": | |
| return remote_name_from_zip_name(base) | |
| if ext_low == ".torrent": | |
| return remote_name_from_torrent_name(base) | |
| raise ValueError(f"Unsupported delete filename: {name}") | |
| def remote_name_from_local(source_dir, local_path): | |
| rel = os.path.relpath(local_path, source_dir) | |
| return rel.replace("\\", "/") | |
| def scan_upload_folder(source_dir, folder): | |
| folder_path = os.path.join(source_dir, folder) | |
| if not os.path.isdir(folder_path): | |
| print(f"[WARN] Missing local folder: {folder_path}") | |
| return [] | |
| entries = [] | |
| seen_remote = set() | |
| for root, dirs, files in os.walk(folder_path): | |
| dirs.sort() | |
| files.sort() | |
| for file_name in files: | |
| if not is_allowed_upload_file(file_name): | |
| continue | |
| local_path = os.path.join(root, file_name) | |
| remote_name = remote_name_from_local(source_dir, local_path) | |
| low = remote_name.lower() | |
| if low in seen_remote: | |
| print(f"[WARN] Duplicate remote path skipped: {remote_name}") | |
| continue | |
| seen_remote.add(low) | |
| entries.append((remote_name, local_path)) | |
| return entries | |
| def normalize_upload_log_entry(line, source_dir): | |
| raw = line.strip().strip('"').strip("'") | |
| if not raw: | |
| return None | |
| raw = os.path.expandvars(os.path.expanduser(raw)) | |
| normalized = raw.replace("\\", "/") | |
| if os.path.isabs(raw): | |
| local_path = os.path.normpath(raw) | |
| try: | |
| rel = os.path.relpath(local_path, source_dir) | |
| except ValueError: | |
| raise ValueError(f"Path is not on the same drive as SOURCE_DIR: {raw}") | |
| if rel == os.pardir or rel.startswith(os.pardir + os.sep): | |
| raise ValueError(f"Absolute path is outside SOURCE_DIR: {raw}") | |
| remote_name = rel.replace("\\", "/") | |
| else: | |
| normalized = normalized.lstrip("/") | |
| parts = [part for part in normalized.split("/") if part] | |
| if not parts: | |
| return None | |
| if len(parts) == 1: | |
| file_name = parts[0] | |
| root, ext = os.path.splitext(file_name) | |
| if not ext: | |
| file_name += ".zip" | |
| elif ext.lower() != ".zip": | |
| raise ValueError(f"Unsupported upload extension: {raw}") | |
| folder = file_name[:1].upper() | |
| if folder not in FOLDER_ORDER: | |
| raise ValueError(f"Cannot determine archive folder from filename: {raw}") | |
| remote_name = f"{folder}/{file_name}" | |
| else: | |
| remote_name = "/".join(parts) | |
| root, ext = os.path.splitext(remote_name) | |
| if not ext: | |
| remote_name += ".zip" | |
| elif ext.lower() != ".zip": | |
| raise ValueError(f"Unsupported upload extension: {raw}") | |
| local_path = os.path.join(source_dir, *remote_name.split("/")) | |
| remote_name = remote_name.replace("\\", "/") | |
| remote_parts = [part for part in remote_name.split("/") if part] | |
| if len(remote_parts) < 2: | |
| raise ValueError(f"Upload path must include a 0-9/A-F folder: {raw}") | |
| top_folder = remote_parts[0].upper() | |
| if top_folder not in FOLDER_ORDER: | |
| raise ValueError(f"Invalid top-level archive folder in upload entry: {raw}") | |
| remote_parts[0] = top_folder | |
| remote_name = "/".join(remote_parts) | |
| if os.path.splitext(remote_name)[1].lower() not in UPLOAD_EXTS: | |
| raise ValueError(f"Unsupported upload extension: {raw}") | |
| return remote_name, os.path.normpath(local_path) | |
| def load_upload_entries_from_log(path, source_dir): | |
| if not os.path.isfile(path): | |
| raise FileNotFoundError(f"Missing upload log: {path}") | |
| entries = [] | |
| seen = set() | |
| invalid = [] | |
| with open(path, "r", encoding="utf-8-sig", errors="ignore") as f: | |
| for line_number, line in enumerate(f, start=1): | |
| if not line.strip(): | |
| continue | |
| try: | |
| resolved = normalize_upload_log_entry(line, source_dir) | |
| except Exception as e: | |
| message = f"Line {line_number}: {e}" | |
| print(f"[WARN] {message}") | |
| invalid.append(message) | |
| continue | |
| if not resolved: | |
| continue | |
| remote_name, local_path = resolved | |
| low = remote_name.lower() | |
| if low in seen: | |
| print(f"[SKIP LOG DUPLICATE] {remote_name}") | |
| continue | |
| seen.add(low) | |
| entries.append((remote_name, local_path)) | |
| return entries, invalid | |
| def load_file_list(path): | |
| if not os.path.exists(path): | |
| raise FileNotFoundError(f"Missing file: {path}") | |
| with open(path, "r", encoding="utf-8", errors="ignore") as f: | |
| raw = [line.strip() for line in f if line.strip()] | |
| names = [] | |
| seen = set() | |
| for line in raw: | |
| name = normalize_delete_file_name(line) | |
| if not name: | |
| continue | |
| low = name.lower() | |
| if low not in seen: | |
| seen.add(low) | |
| names.append(name) | |
| return names | |
| def list_item_files(item_id): | |
| item = internetarchive.get_item(item_id) | |
| out = [] | |
| for f in item.files: | |
| name = f.get("name") | |
| if name: | |
| out.append(name) | |
| return out | |
| def chunks(items, size): | |
| for i in range(0, len(items), size): | |
| yield items[i:i + size] | |
| def is_rate_limit_error(error_text): | |
| text = str(error_text).lower() | |
| rate_limit_markers = ( | |
| "please reduce your request rate", | |
| "total_tasks_queued exceeds global_limit", | |
| "bucket_tasks_queued exceeds rationed amount", | |
| "503 slow down", | |
| "503 slowdown", | |
| ) | |
| return any(marker in text for marker in rate_limit_markers) | |
| def response_error_text(response): | |
| parts = [] | |
| status_code = getattr(response, "status_code", None) | |
| if status_code is not None: | |
| parts.append(f"HTTP {status_code}") | |
| reason = getattr(response, "reason", None) | |
| if reason: | |
| parts.append(str(reason)) | |
| body = getattr(response, "text", None) | |
| if body: | |
| parts.append(str(body)) | |
| return " - ".join(parts) | |
| def upload_file_batch(item_id, batch_entries, batch_number, total_batches): | |
| """ | |
| Upload multiple files in one internetarchive.upload() request. | |
| Returns: | |
| status: "uploaded", "failed", or "rate_limited" | |
| uploaded_names: files accepted as uploaded | |
| failed_names: files that could not be submitted/uploaded | |
| message: error/rate-limit text or None | |
| """ | |
| valid_entries = [] | |
| failed_names = [] | |
| print("--------------------------------------------------") | |
| if UPLOAD_IN_BATCHES: | |
| print( | |
| f"[UPLOAD BATCH {batch_number}/{total_batches}] " | |
| f"{len(batch_entries)} file(s)" | |
| ) | |
| else: | |
| print(f"[UPLOAD FILE {batch_number}/{total_batches}]") | |
| print("--------------------------------------------------") | |
| for remote_name, local_path in batch_entries: | |
| if not os.path.isfile(local_path): | |
| print(f"[ERROR] Missing local file: {local_path}") | |
| failed_names.append(remote_name) | |
| continue | |
| valid_entries.append((remote_name, local_path)) | |
| if not valid_entries: | |
| return "failed", [], failed_names, "No valid local files in this batch." | |
| upload_map = { | |
| remote_name: local_path | |
| for remote_name, local_path in valid_entries | |
| } | |
| if UPLOAD_IN_BATCHES: | |
| print( | |
| f"[INFO] Sending {len(upload_map)} file(s) " | |
| "in one Archive.org upload request." | |
| ) | |
| else: | |
| print("[INFO] Sending 1 file in this Archive.org upload request.") | |
| try: | |
| result = internetarchive.upload( | |
| item_id, | |
| upload_map, | |
| verbose=True, | |
| queue_derive=not NO_DERIVE, | |
| retries=UPLOAD_RETRIES, | |
| ) | |
| if result is not None: | |
| try: | |
| for response in result: | |
| status_code = getattr(response, "status_code", None) | |
| if status_code is not None and not (200 <= status_code < 300): | |
| message = response_error_text(response) | |
| if is_rate_limit_error(message): | |
| print(f"[RATE LIMIT] {message}") | |
| return ( | |
| "rate_limited", | |
| [], | |
| failed_names, | |
| message, | |
| ) | |
| print(f"[ERROR] Batch upload failed: {message}") | |
| failed_names.extend( | |
| remote_name | |
| for remote_name, local_path in valid_entries | |
| ) | |
| return "failed", [], failed_names, message | |
| except TypeError: | |
| # Some internetarchive versions return a non-iterable result. | |
| pass | |
| uploaded_names = [ | |
| remote_name | |
| for remote_name, local_path in valid_entries | |
| ] | |
| if UPLOAD_IN_BATCHES: | |
| print(f"[OK] Uploaded batch: {len(uploaded_names)} file(s)") | |
| else: | |
| print(f"[OK] Uploaded: {uploaded_names[0]}") | |
| return "uploaded", uploaded_names, failed_names, None | |
| except Exception as e: | |
| message = str(e) | |
| if is_rate_limit_error(message): | |
| print(f"[RATE LIMIT] {message}") | |
| return "rate_limited", [], failed_names, message | |
| print(f"[ERROR] Batch upload failed: {message}") | |
| failed_names.extend( | |
| remote_name | |
| for remote_name, local_path in valid_entries | |
| ) | |
| return "failed", [], failed_names, message | |
| finally: | |
| if UPLOAD_DELAY_SECONDS > 0: | |
| time.sleep(UPLOAD_DELAY_SECONDS) | |
| def upload_entries(item_id, entries, remote_set): | |
| uploaded = [] | |
| skipped = [] | |
| failed = [] | |
| deferred = [] | |
| entries = list(entries) | |
| total = len(entries) | |
| pending_entries = [] | |
| for index, (remote_name, local_path) in enumerate(entries, start=1): | |
| remote_low = remote_name.lower() | |
| if remote_low in remote_set: | |
| print(f"[SKIP {index}/{total}] Already uploaded: {remote_name}") | |
| skipped.append(remote_name) | |
| continue | |
| pending_entries.append((remote_name, local_path)) | |
| if not pending_entries: | |
| print("[INFO] No new files remain to upload in this group.") | |
| return uploaded, skipped, failed, deferred, False | |
| configured_group_size = max(1, UPLOAD_BATCH_SIZE) | |
| if UPLOAD_IN_BATCHES: | |
| request_size = configured_group_size | |
| else: | |
| request_size = 1 | |
| upload_batches = list(chunks(pending_entries, request_size)) | |
| total_batches = len(upload_batches) | |
| print() | |
| print(f"[INFO] New files to upload: {len(pending_entries)}") | |
| if UPLOAD_IN_BATCHES: | |
| print("[INFO] Upload method: multiple files per request") | |
| print(f"[INFO] Files per upload request: {request_size}") | |
| print(f"[INFO] Number of upload requests: {total_batches}") | |
| else: | |
| print("[INFO] Upload method: one file per request") | |
| print(f"[INFO] Number of upload requests: {total_batches}") | |
| print( | |
| f"[INFO] Optional pause interval: every " | |
| f"{configured_group_size} individual upload(s)" | |
| ) | |
| print() | |
| for batch_index, batch_entries in enumerate(upload_batches, start=1): | |
| status, batch_uploaded, batch_failed, message = upload_file_batch( | |
| item_id, | |
| batch_entries, | |
| batch_index, | |
| total_batches, | |
| ) | |
| uploaded.extend(batch_uploaded) | |
| failed.extend(batch_failed) | |
| for remote_name in batch_uploaded: | |
| remote_set.add(remote_name.lower()) | |
| print() | |
| if status == "rate_limited": | |
| deferred = [] | |
| for remaining_batch in upload_batches[batch_index - 1:]: | |
| for pending_remote, pending_local in remaining_batch: | |
| if pending_remote.lower() not in remote_set: | |
| deferred.append(pending_remote) | |
| print("[INFO] Archive.org's upload/task queue is currently full.") | |
| print("[INFO] Stopping now instead of attempting the remaining batches.") | |
| print("[INFO] Rerun later; files already present remotely will be skipped.") | |
| if message: | |
| print(f"[INFO] Rate-limit message: {message}") | |
| return uploaded, skipped, failed, deferred, True | |
| should_pause = False | |
| if PAUSE_AFTER_EACH_UPLOAD_BATCH and batch_index < total_batches: | |
| if UPLOAD_IN_BATCHES: | |
| # Each request is one complete multi-file group. | |
| should_pause = True | |
| elif batch_index % configured_group_size == 0: | |
| # Individual mode: pause only after the configured number | |
| # of one-file upload requests, not after every single file. | |
| should_pause = True | |
| if should_pause: | |
| if UPLOAD_IN_BATCHES: | |
| pause_message = ( | |
| f"[BATCH PAUSE] Finished upload batch " | |
| f"{batch_index}/{total_batches} " | |
| f"({len(batch_entries)} file(s)). " | |
| "Press Enter to continue..." | |
| ) | |
| else: | |
| pause_message = ( | |
| f"[BATCH PAUSE] Finished {batch_index} individual " | |
| f"upload(s). Press Enter to continue..." | |
| ) | |
| input(pause_message) | |
| print() | |
| return uploaded, skipped, failed, deferred, False | |
| def find_delete_targets(all_remote_files, file_names): | |
| remote_set = {x.lower() for x in all_remote_files} | |
| matches = [] | |
| missing = [] | |
| seen = set() | |
| for name in file_names: | |
| try: | |
| remote_name = remote_name_from_delete_name(name) | |
| except Exception as e: | |
| print(f"[WARN] {e}") | |
| missing.append(name) | |
| continue | |
| low = remote_name.lower() | |
| if low in remote_set: | |
| if low not in seen: | |
| seen.add(low) | |
| matches.append(remote_name) | |
| else: | |
| missing.append(remote_name) | |
| return matches, missing | |
| def delete_remote_files(item_id, remote_names): | |
| deleted = [] | |
| failed = [] | |
| for name in remote_names: | |
| print(f"Deleting main file: {name}") | |
| try: | |
| internetarchive.delete( | |
| item_id, | |
| files=name, | |
| cascade_delete=False, | |
| verbose=True | |
| ) | |
| print(f"[OK] Deleted: {name}") | |
| deleted.append(name) | |
| except Exception as e: | |
| print(f"[ERROR] Failed deleting {name}: {e}") | |
| failed.append(name) | |
| print() | |
| return deleted, failed | |
| def find_matching_history_backups(all_remote_files, target_names): | |
| target_set = set() | |
| for name in target_names: | |
| try: | |
| target_set.add(remote_name_from_delete_name(name).lower()) | |
| except Exception: | |
| pass | |
| matches = [] | |
| pattern = re.compile(r"^history/files/(.+?)\.~\d+~$", re.IGNORECASE) | |
| for remote_name in all_remote_files: | |
| m = pattern.match(remote_name) | |
| if not m: | |
| continue | |
| backed_up_name = m.group(1).replace("\\", "/").lower() | |
| if backed_up_name in target_set: | |
| matches.append(remote_name) | |
| return matches | |
| def delete_backup_files(item_id, backup_names): | |
| deleted = [] | |
| failed = [] | |
| for remote_name in backup_names: | |
| print(f"Deleting backup file: {remote_name}") | |
| try: | |
| internetarchive.delete( | |
| item_id, | |
| files=remote_name, | |
| cascade_delete=False, | |
| verbose=True | |
| ) | |
| print(f"[OK] Deleted backup: {remote_name}") | |
| deleted.append(remote_name) | |
| except Exception as e: | |
| print(f"[ERROR] Failed deleting backup {remote_name}: {e}") | |
| failed.append(remote_name) | |
| print() | |
| return deleted, failed | |
| def write_log(path, lines): | |
| with open(path, "w", encoding="utf-8", newline="") as f: | |
| for line in lines: | |
| f.write(str(line) + "\n") | |
| def run_upload_mode(item_id, source_dir): | |
| print("[MODE] UPLOAD") | |
| print(f"[INFO] Source folder: {source_dir}") | |
| print(f"[INFO] Upload from log: {UPLOAD_FROM_LOG}") | |
| if UPLOAD_FROM_LOG: | |
| print(f"[INFO] Upload log: {UPLOAD_LOG_FILE}") | |
| else: | |
| print(f"[INFO] Start folder: {START_FOLDER}") | |
| print(f"[INFO] No derive: {NO_DERIVE}") | |
| print(f"[INFO] Upload retries: {UPLOAD_RETRIES}") | |
| print(f"[INFO] Delay between attempted uploads: {UPLOAD_DELAY_SECONDS} second(s)") | |
| print(f"[INFO] Upload in batches: {UPLOAD_IN_BATCHES}") | |
| print(f"[INFO] Upload group size: {UPLOAD_BATCH_SIZE} file(s)") | |
| print(f"[INFO] Pause after each upload group: {PAUSE_AFTER_EACH_UPLOAD_BATCH}") | |
| print() | |
| if not os.path.isdir(source_dir): | |
| print(f"[FATAL] Source folder not found: {source_dir}") | |
| pause_exit() | |
| return | |
| if UPLOAD_FROM_LOG: | |
| try: | |
| log_entries, invalid_log_entries = load_upload_entries_from_log( | |
| UPLOAD_LOG_FILE, | |
| source_dir, | |
| ) | |
| except Exception as e: | |
| print(f"[FATAL] Could not load upload log: {e}") | |
| pause_exit() | |
| return | |
| if not log_entries: | |
| print(f"[WARN] No valid ZIP upload entries found in: {UPLOAD_LOG_FILE}") | |
| if invalid_log_entries: | |
| print(f"[INFO] Invalid upload log entries: {len(invalid_log_entries)}") | |
| pause_exit() | |
| return | |
| upload_groups = [("LOG", log_entries)] | |
| print(f"[OK] Loaded {len(log_entries)} unique ZIP upload entry/entries from log.txt.") | |
| if invalid_log_entries: | |
| print(f"[WARN] Ignored {len(invalid_log_entries)} invalid log entry/entries.") | |
| print() | |
| else: | |
| try: | |
| folders = get_start_folders() | |
| except Exception as e: | |
| print(f"[FATAL] {e}") | |
| pause_exit() | |
| return | |
| upload_groups = [] | |
| for folder in folders: | |
| entries = scan_upload_folder(source_dir, folder) | |
| upload_groups.append((folder, entries)) | |
| print("[INFO] Checking archive.org item for existing files...") | |
| try: | |
| remote_files = list_item_files(item_id) | |
| remote_set = {x.lower() for x in remote_files} | |
| print(f"[OK] Remote item has {len(remote_files)} file(s).") | |
| except Exception as e: | |
| print(f"[FATAL] Could not list archive.org item files: {e}") | |
| pause_exit() | |
| return | |
| print() | |
| all_uploaded = [] | |
| all_skipped = [] | |
| all_failed = [] | |
| all_deferred = [] | |
| stopped_for_rate_limit = False | |
| uploaded_log = os.path.join(SCRIPT_DIR, "uploaded_ok.txt") | |
| skipped_log = os.path.join(SCRIPT_DIR, "upload_skipped.txt") | |
| failed_log = os.path.join(SCRIPT_DIR, "upload_failed.txt") | |
| deferred_log = os.path.join(SCRIPT_DIR, "upload_deferred.txt") | |
| for group_name, upload_list in upload_groups: | |
| print("========================================") | |
| if group_name == "LOG": | |
| print("[UPLOAD LIST] log.txt") | |
| else: | |
| print(f"[FOLDER] {group_name}") | |
| print("========================================") | |
| if group_name == "LOG": | |
| print(f"[OK] Found {len(upload_list)} ZIP file(s) in the upload log.") | |
| else: | |
| print(f"[OK] Found {len(upload_list)} ZIP file(s) in folder {group_name}.") | |
| print() | |
| uploaded, skipped, failed, deferred, rate_limited = upload_entries( | |
| item_id, | |
| upload_list, | |
| remote_set, | |
| ) | |
| all_uploaded.extend(uploaded) | |
| all_skipped.extend(skipped) | |
| all_failed.extend(failed) | |
| all_deferred.extend(deferred) | |
| write_log(uploaded_log, all_uploaded) | |
| write_log(skipped_log, all_skipped) | |
| write_log(failed_log, all_failed) | |
| write_log(deferred_log, all_deferred) | |
| if group_name == "LOG": | |
| print("========== LOG UPLOAD SUMMARY ==========") | |
| else: | |
| print(f"========== FOLDER {group_name} SUMMARY ==========") | |
| print(f"Found: {len(upload_list)}") | |
| print(f"Uploaded: {len(uploaded)}") | |
| print(f"Skipped existing: {len(skipped)}") | |
| print(f"Failed: {len(failed)}") | |
| print(f"Deferred: {len(deferred)}") | |
| print() | |
| if rate_limited and STOP_ON_RATE_LIMIT: | |
| stopped_for_rate_limit = True | |
| break | |
| if not UPLOAD_FROM_LOG and PAUSE_AFTER_EACH_FOLDER: | |
| input( | |
| f"[PAUSE] Finished folder {group_name}. " | |
| "Press Enter to continue, or close this window to stop..." | |
| ) | |
| print() | |
| print("========== FINAL SUMMARY ==========") | |
| print(f"Uploaded: {len(all_uploaded)}") | |
| print(f"Skipped existing: {len(all_skipped)}") | |
| print(f"Failed: {len(all_failed)}") | |
| print(f"Deferred: {len(all_deferred)}") | |
| print() | |
| print(f"Uploaded log: {uploaded_log}") | |
| print(f"Skipped log: {skipped_log}") | |
| print(f"Failed log: {failed_log}") | |
| print(f"Deferred log: {deferred_log}") | |
| if stopped_for_rate_limit: | |
| print() | |
| print("[STOPPED] Archive.org reported that its global task queue is full.") | |
| print("[INFO] This is a server-side limit, not a damaged ZIP or local network error.") | |
| print("[INFO] Run the script again later with the same upload source setting.") | |
| print("[INFO] The script will rescan the item and skip files that are already present.") | |
| if all_failed: | |
| print("\nActual failed uploads:") | |
| for name in all_failed: | |
| print(name) | |
| def run_delete_mode(item_id, file_names): | |
| print("[MODE] DELETE") | |
| print(f"[OK] Loaded {len(file_names)} supported delete file name(s) from {FILE_LIST}") | |
| print() | |
| print("[INFO] Scanning item files...") | |
| try: | |
| all_files = list_item_files(item_id) | |
| except Exception as e: | |
| print(f"[ERROR] Could not scan item files: {e}") | |
| pause_exit() | |
| return | |
| delete_targets, missing_targets = find_delete_targets(all_files, file_names) | |
| backup_matches = find_matching_history_backups(all_files, file_names) | |
| print(f"[INFO] Found {len(delete_targets)} matching main file(s).") | |
| print(f"[INFO] Missing {len(missing_targets)} requested file(s).") | |
| print(f"[INFO] Found {len(backup_matches)} matching backup file(s).") | |
| print() | |
| delete_target_log = os.path.join(SCRIPT_DIR, "delete_ok.txt") | |
| missing_target_log = os.path.join(SCRIPT_DIR, "delete_missing.txt") | |
| write_log(delete_target_log, delete_targets) | |
| write_log(missing_target_log, missing_targets) | |
| deleted_main, delete_failed = delete_remote_files(item_id, delete_targets) | |
| if backup_matches: | |
| deleted_backups, backup_failed = delete_backup_files(item_id, backup_matches) | |
| else: | |
| deleted_backups = [] | |
| backup_failed = [] | |
| print("========== SUMMARY ==========") | |
| print(f"Files requested: {len(file_names)}") | |
| print(f"Main matched: {len(delete_targets)}") | |
| print(f"Main missing: {len(missing_targets)}") | |
| print(f"Main deleted: {len(deleted_main)}") | |
| print(f"Main delete fail: {len(delete_failed)}") | |
| print(f"Backups matched: {len(backup_matches)}") | |
| print(f"Backups deleted: {len(deleted_backups)}") | |
| print(f"Backup del fail: {len(backup_failed)}") | |
| print() | |
| print(f"Resolved delete target log: {delete_target_log}") | |
| print(f"Missing delete target log: {missing_target_log}") | |
| if delete_failed: | |
| print("\nFailed main deletes:") | |
| for name in delete_failed: | |
| print(name) | |
| if backup_failed: | |
| print("\nFailed backup deletes:") | |
| for name in backup_failed: | |
| print(name) | |
| def main(): | |
| mode = MODE.strip().lower() | |
| if mode == "upload": | |
| run_upload_mode(ITEM_ID, SOURCE_DIR) | |
| elif mode == "delete": | |
| try: | |
| file_names = load_file_list(FILE_LIST) | |
| except Exception as e: | |
| print(f"[FATAL] {e}") | |
| pause_exit() | |
| return | |
| if not file_names: | |
| print(f"[WARN] No supported delete entries found in: {FILE_LIST}") | |
| print("[INFO] Supported delete entries: .zip, no-extension zip names, and .torrent files.") | |
| pause_exit() | |
| return | |
| run_delete_mode(ITEM_ID, file_names) | |
| else: | |
| print(f"[FATAL] Invalid MODE: {MODE}") | |
| print('Use MODE = "upload" or MODE = "delete"') | |
| pause_exit() | |
| return | |
| print("\nDone.") | |
| pause_exit() | |
| if __name__ == "__main__": | |
| main() |