import internetarchive import os import re import time # Change this only if your Archive.org item uses a different identifier. ITEM_ID = "PSHomeMappedScenes" ITEM_URL = f"https://archive.org/details/{ITEM_ID}" # Archive.org creates an item during its first successful file upload. These # fields are sent only with that one-file creation upload, and only when the # identifier is still available. They are never resent for an existing item. ITEM_CREATION_METADATA = { "mediatype": "data", "collection": "opensource_media", "subject": [ "playstation home", "pshome", "open source", "preservation", "revival", "archive", "scenes", "mapped", "non-profit", "homelab", "Home Laboratory", ], } 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\SCENES-MAPPED\ARCHIVE" # "upload" = upload ZIP files from SOURCE_DIR or from log.txt # "delete" = delete files listed in log.txt MODE = "upload" # 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, this is the number of ZIP files sent in # each upload request. When it is False, it controls only the optional pause # interval between groups of individual uploads. UPLOAD_BATCH_SIZE = 50 # True = pause after each group of UPLOAD_BATCH_SIZE files. # False = continue automatically. PAUSE_AFTER_EACH_UPLOAD_BATCH = False # False = scan only the ZIP files directly inside SOURCE_DIR. # True = upload only the ZIP files listed in log.txt. UPLOAD_FROM_LOG = False # In log mode, each entry may be: # SceneName$SdatName # SceneName$SdatName.zip # Q:\PSHOME-INT\PSHomeCacheDepot\SCENES-MAPPED\ARCHIVE\SceneName$SdatName.zip # # Scene ZIPs are always uploaded to the root of the Archive.org item. Local # subfolders and remote subfolder paths are not used. UPLOAD_LOG_FILE = FILE_LIST # ZIP files normally do not need Archive.org derivatives. NO_DERIVE = True # Leave at 0 so a global queue limit stops cleanly without retrying the same # ZIP in the same run. UPLOAD_RETRIES = 0 # Delay after each attempted upload request. UPLOAD_DELAY_SECONDS = 2.0 # Stop the run when Archive.org reports that its task queue is full. STOP_ON_RATE_LIMIT = True 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): """Return only the final filename from a name or full path.""" text = line.strip().strip('"').strip("'").replace("\\", "/") return text.rsplit("/", 1)[-1].strip() def normalize_zip_name(line): name = clean_name(line) if not name: return None root, ext = os.path.splitext(name) if not root: return None if not ext: return name + ".zip" if ext.lower() == ".zip": return name return None def normalize_delete_file_name(line): name = clean_name(line) if not name: return None root, ext = os.path.splitext(name) if not root: return None if not ext: return name + ".zip" if ext.lower() in DELETE_EXTS: return name return None def normalize_torrent_name(line): name = clean_name(line) if not name: return None root, ext = os.path.splitext(name) if root and ext.lower() == ".torrent": return name return None def remote_name_from_delete_name(name): """Scene files live at the Archive.org item root, so no prefix is added.""" normalized = normalize_delete_file_name(name) if not normalized: raise ValueError(f"Unsupported delete filename: {name}") return normalized def scan_upload_directory(source_dir): """Scan only ZIP files directly inside SOURCE_DIR; never recurse.""" entries = [] seen_remote = set() with os.scandir(source_dir) as scan: files = sorted( (entry for entry in scan if entry.is_file()), key=lambda entry: entry.name.lower(), ) for entry in files: if not is_allowed_upload_file(entry.name): continue remote_name = entry.name remote_low = remote_name.lower() if remote_low in seen_remote: print(f"[WARN] Duplicate filename skipped: {remote_name}") continue seen_remote.add(remote_low) entries.append((remote_name, entry.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)) if os.path.isabs(raw): local_path = os.path.abspath(os.path.normpath(raw)) source_path = os.path.abspath(os.path.normpath(source_dir)) if os.path.normcase(os.path.dirname(local_path)) != os.path.normcase(source_path): raise ValueError( f"Absolute path is not directly inside SOURCE_DIR: {raw}" ) remote_name = os.path.basename(local_path) else: normalized = raw.replace("\\", "/").strip("/") parts = [part for part in normalized.split("/") if part] if len(parts) != 1: raise ValueError( f"Scene upload entries cannot contain subfolders: {raw}" ) remote_name = parts[0] local_path = os.path.join(source_dir, remote_name) root, ext = os.path.splitext(remote_name) if not root: raise ValueError(f"Invalid scene ZIP filename: {raw}") if not ext: remote_name += ".zip" local_path += ".zip" elif ext.lower() != ".zip": raise ValueError(f"Unsupported upload extension: {raw}") # Force a root-level remote filename even when an absolute path was used. remote_name = clean_name(remote_name) 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 file: for line_number, line in enumerate(file, start=1): if not line.strip(): continue try: resolved = normalize_upload_log_entry(line, source_dir) except Exception as error: message = f"Line {line_number}: {error}" print(f"[WARN] {message}") invalid.append(message) continue if not resolved: continue remote_name, local_path = resolved remote_low = remote_name.lower() if remote_low in seen: print(f"[SKIP LOG DUPLICATE] {remote_name}") continue seen.add(remote_low) entries.append((remote_name, local_path)) return entries, invalid def load_file_list(path): if not os.path.isfile(path): raise FileNotFoundError(f"Missing file: {path}") with open(path, "r", encoding="utf-8-sig", errors="ignore") as file: raw_lines = [line.strip() for line in file if line.strip()] names = [] seen = set() for line in raw_lines: name = normalize_delete_file_name(line) if not name: continue name_low = name.lower() if name_low not in seen: seen.add(name_low) names.append(name) return names def list_item_files(item_id): item = internetarchive.get_item(item_id) names = [] for remote_file in item.files: name = remote_file.get("name") if name: names.append(name) return names def identifier_is_available(item_id): """Return True only when Archive.org says the identifier can be created.""" item = internetarchive.get_item(item_id) return item.identifier_available() def chunks(items, size): for index in range(0, len(items), size): yield items[index:index + size] def is_rate_limit_error(error_text): text = str(error_text).lower() 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 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, creation_metadata=None, ): """ Upload one or more 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 creation_metadata is not None: print(f"[CREATE ITEM] {ITEM_URL}") print("[CREATE ITEM] Uploading one ZIP with the initial item metadata.") elif 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 creation_metadata is not None: print("[INFO] Sending the one-file item creation request.") elif 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: upload_options = { "verbose": True, "queue_derive": not NO_DERIVE, "retries": UPLOAD_RETRIES, } # Do not even pass the metadata argument during ordinary uploads. if creation_metadata is not None: upload_options["metadata"] = creation_metadata result = internetarchive.upload(item_id, upload_map, **upload_options) 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 creation_metadata is not None: print(f"[OK] Created item: {ITEM_URL}") print(f"[OK] Uploaded creation ZIP: {uploaded_names[0]}") elif 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 error: message = str(error) 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, creation_metadata=None): uploaded = [] skipped = [] failed = [] deferred = [] entries = list(entries) total = len(entries) pending_entries = [] for index, (remote_name, local_path) in enumerate(entries, start=1): if remote_name.lower() 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.") return uploaded, skipped, failed, deferred, None print() print(f"[INFO] New files to upload: {len(pending_entries)}") if creation_metadata is not None: # Archive.org creates an item through its first file upload. Use exactly # one real scene ZIP for that request so creation metadata is sent once. creation_entry = pending_entries.pop(0) status, creation_uploaded, creation_failed, message = upload_file_batch( item_id, [creation_entry], 1, 1, creation_metadata=creation_metadata, ) uploaded.extend(creation_uploaded) failed.extend(creation_failed) for remote_name in creation_uploaded: remote_set.add(remote_name.lower()) print() if status != "uploaded": if status == "rate_limited": if creation_entry[0].lower() not in remote_set: deferred.append(creation_entry[0]) stop_reason = "rate_limited" print("[INFO] Archive.org's upload/task queue is currently full.") else: stop_reason = "creation_failed" print("[ERROR] The Archive.org item could not be created.") for pending_remote, pending_local in pending_entries: if pending_remote.lower() not in remote_set: deferred.append(pending_remote) print( "[INFO] No ordinary uploads were attempted, so the item cannot " "be created with incomplete metadata." ) print("[INFO] Correct the error or rerun later; creation will be tried again.") if message: print(f"[INFO] Creation response: {message}") return uploaded, skipped, failed, deferred, stop_reason print("[INFO] Initial item metadata has now been sent exactly once.") if not pending_entries: return uploaded, skipped, failed, deferred, None configured_group_size = max(1, UPLOAD_BATCH_SIZE) request_size = configured_group_size if UPLOAD_IN_BATCHES else 1 upload_batches = list(chunks(pending_entries, request_size)) total_batches = len(upload_batches) 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": 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 instead of attempting the remaining batches.") print("[INFO] Rerun later; existing remote files will be skipped.") if message: print(f"[INFO] Rate-limit message: {message}") return uploaded, skipped, failed, deferred, "rate_limited" should_pause = False if PAUSE_AFTER_EACH_UPLOAD_BATCH and batch_index < total_batches: if UPLOAD_IN_BATCHES: should_pause = True elif batch_index % configured_group_size == 0: 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, None def find_delete_targets(all_remote_files, file_names): remote_set = {name.lower() for name 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 error: print(f"[WARN] {error}") missing.append(name) continue remote_low = remote_name.lower() if remote_low in remote_set: if remote_low not in seen: seen.add(remote_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 error: print(f"[ERROR] Failed deleting {name}: {error}") 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: match = pattern.match(remote_name) if not match: continue backed_up_name = match.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 error: print(f"[ERROR] Failed deleting backup {remote_name}: {error}") failed.append(remote_name) print() return deleted, failed def write_log(path, lines): with open(path, "w", encoding="utf-8", newline="") as file: for line in lines: file.write(str(line) + "\n") def run_upload_mode(item_id, source_dir): print("[MODE] UPLOAD") print(f"[INFO] Archive.org item: {item_id}") print(f"[INFO] Item URL: {ITEM_URL}") print(f"[INFO] Source folder: {source_dir}") print("[INFO] Directory layout: flat; subfolders are ignored") print(f"[INFO] Upload from log: {UPLOAD_FROM_LOG}") if UPLOAD_FROM_LOG: print(f"[INFO] Upload log: {UPLOAD_LOG_FILE}") print(f"[INFO] No derive: {NO_DERIVE}") print(f"[INFO] Upload retries: {UPLOAD_RETRIES}") print(f"[INFO] Delay after each request: {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: upload_list, invalid_log_entries = load_upload_entries_from_log( UPLOAD_LOG_FILE, source_dir, ) except Exception as error: print(f"[FATAL] Could not load upload log: {error}") pause_exit() return if not upload_list: print(f"[WARN] No valid ZIP entries found in: {UPLOAD_LOG_FILE}") if invalid_log_entries: print(f"[INFO] Invalid log entries: {len(invalid_log_entries)}") pause_exit() return print(f"[OK] Loaded {len(upload_list)} unique ZIP entry/entries from log.txt.") if invalid_log_entries: print(f"[WARN] Ignored {len(invalid_log_entries)} invalid log entry/entries.") else: try: upload_list = scan_upload_directory(source_dir) except Exception as error: print(f"[FATAL] Could not scan source folder: {error}") pause_exit() return print(f"[OK] Found {len(upload_list)} root-level ZIP file(s).") if not upload_list: print("[WARN] No ZIP files were found to upload.") pause_exit() return print() print("[INFO] Checking whether the Archive.org identifier already exists...") try: item_needs_creation = identifier_is_available(item_id) except Exception as error: print(f"[FATAL] Could not check identifier availability: {error}") pause_exit() return if item_needs_creation: creation_metadata = ITEM_CREATION_METADATA remote_set = set() print(f"[INFO] Identifier is available: {item_id}") print("[INFO] The first ZIP will create the item with:") print(f" mediatype: {ITEM_CREATION_METADATA['mediatype']}") print(f" collection: {ITEM_CREATION_METADATA['collection']}") print( " subject: " + "; ".join(ITEM_CREATION_METADATA["subject"]) ) else: creation_metadata = None print("[OK] Item already exists. Creation metadata will not be resent.") print("[INFO] Checking the existing item for uploaded files...") try: remote_files = list_item_files(item_id) remote_set = {name.lower() for name in remote_files} print(f"[OK] Remote item has {len(remote_files)} file(s).") except Exception as error: print(f"[FATAL] Could not list Archive.org item files: {error}") pause_exit() return print() 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") uploaded, skipped, failed, deferred, stop_reason = upload_entries( item_id, upload_list, remote_set, creation_metadata=creation_metadata, ) write_log(uploaded_log, uploaded) write_log(skipped_log, skipped) write_log(failed_log, failed) write_log(deferred_log, deferred) print("========== FINAL 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() 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 stop_reason == "rate_limited" and STOP_ON_RATE_LIMIT: print() print("[STOPPED] Archive.org reported that its global task queue is full.") print("[INFO] Run the script again later; existing files will be skipped.") elif stop_reason == "creation_failed": print() print("[STOPPED] Item creation failed, so no ordinary uploads were attempted.") print("[INFO] Rerun after correcting the reported creation error.") if failed: print("\nActual failed uploads:") for name in failed: print(name) def run_delete_mode(item_id, file_names): print("[MODE] DELETE") print(f"[INFO] Archive.org item: {item_id}") print(f"[OK] Loaded {len(file_names)} supported name(s) from {FILE_LIST}") print() print("[INFO] Scanning item files...") try: all_files = list_item_files(item_id) except Exception as error: print(f"[ERROR] Could not scan item files: {error}") 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 error: print(f"[FATAL] {error}") pause_exit() return if not file_names: print(f"[WARN] No supported delete entries found in: {FILE_LIST}") print( "[INFO] Supported entries: .zip, ZIP names without an extension, " "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()