| import internetarchive |
| import os |
| import re |
|
|
| 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" |
|
|
| |
| |
| |
| MODE = "upload" |
|
|
| START_FOLDER = "0" |
| PAUSE_AFTER_EACH_FOLDER = True |
| BATCH_UPLOAD_SIZE = 1000 |
|
|
| FOLDER_ORDER = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] |
| UPLOAD_EXTS = {".zip"} |
|
|
|
|
| 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_zip_name(line): |
| name = clean_name(line) |
|
|
| if not name: |
| return None |
|
|
| root, ext = os.path.splitext(name) |
|
|
| if ext == "": |
| return name + ".zip" |
|
|
| if ext.lower() == ".zip": |
| 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_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 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_zip_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 upload_batch(item_id, batch_entries, remote_set, batch_num, batch_total): |
| uploaded = [] |
| skipped = [] |
| failed = [] |
|
|
| batch_dict = {} |
|
|
| for remote_name, local_path in batch_entries: |
| remote_low = remote_name.lower() |
|
|
| if remote_low in remote_set: |
| print(f"[SKIP] Already uploaded: {remote_name}") |
| skipped.append(remote_name) |
| continue |
|
|
| if not os.path.exists(local_path): |
| print(f"[ERROR] Missing local file: {local_path}") |
| failed.append(remote_name) |
| continue |
|
|
| batch_dict[remote_name] = local_path |
|
|
| if not batch_dict: |
| return uploaded, skipped, failed |
|
|
| print(f"[BATCH {batch_num}/{batch_total}] Uploading {len(batch_dict)} file(s)...") |
|
|
| for remote_name, local_path in batch_dict.items(): |
| print(f" {remote_name}") |
| print(f" {local_path}") |
|
|
| print() |
|
|
| try: |
| result = internetarchive.upload( |
| item_id, |
| batch_dict, |
| verbose=True |
| ) |
|
|
| ok = True |
|
|
| if result is not None: |
| try: |
| for r in result: |
| if hasattr(r, "status_code") and r.status_code not in (200, 201): |
| ok = False |
| except TypeError: |
| pass |
|
|
| if ok: |
| for remote_name in batch_dict: |
| print(f"[OK] Uploaded: {remote_name}") |
| uploaded.append(remote_name) |
| remote_set.add(remote_name.lower()) |
| else: |
| for remote_name in batch_dict: |
| print(f"[ERROR] Batch upload may have failed: {remote_name}") |
| failed.append(remote_name) |
|
|
| except Exception as e: |
| print(f"[ERROR] Batch upload failed: {e}") |
| print("[INFO] Marking this batch as failed. Rerun the script later and already-uploaded files will be skipped.") |
|
|
| for remote_name in batch_dict: |
| failed.append(remote_name) |
|
|
| print() |
|
|
| return uploaded, skipped, failed |
|
|
|
|
| def upload_entries(item_id, upload_entries, remote_set): |
| uploaded = [] |
| skipped = [] |
| failed = [] |
|
|
| upload_entries = list(upload_entries) |
| batch_list = list(chunks(upload_entries, BATCH_UPLOAD_SIZE)) |
| batch_total = len(batch_list) |
|
|
| for batch_num, batch_entries in enumerate(batch_list, start=1): |
| batch_uploaded, batch_skipped, batch_failed = upload_batch( |
| item_id, |
| batch_entries, |
| remote_set, |
| batch_num, |
| batch_total |
| ) |
|
|
| uploaded.extend(batch_uploaded) |
| skipped.extend(batch_skipped) |
| failed.extend(batch_failed) |
|
|
| return uploaded, skipped, failed |
|
|
|
|
| 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_zip_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_zip_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] Start folder: {START_FOLDER}") |
| print(f"[INFO] Batch upload size: {BATCH_UPLOAD_SIZE}") |
| print() |
|
|
| try: |
| folders = get_start_folders() |
| except Exception as e: |
| print(f"[FATAL] {e}") |
| pause_exit() |
| return |
|
|
| 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 = [] |
|
|
| uploaded_log = os.path.join(SCRIPT_DIR, "_uploaded_ok.txt") |
| skipped_log = os.path.join(SCRIPT_DIR, "_upload_skipped_existing.txt") |
| failed_log = os.path.join(SCRIPT_DIR, "_upload_failed.txt") |
|
|
| for folder in folders: |
| print("========================================") |
| print(f"[FOLDER] {folder}") |
| print("========================================") |
|
|
| upload_list = scan_upload_folder(source_dir, folder) |
|
|
| print(f"[OK] Found {len(upload_list)} zip file(s) in folder {folder}.") |
| print() |
|
|
| uploaded, skipped, failed = upload_entries(item_id, upload_list, remote_set) |
|
|
| all_uploaded.extend(uploaded) |
| all_skipped.extend(skipped) |
| all_failed.extend(failed) |
|
|
| write_log(uploaded_log, all_uploaded) |
| write_log(skipped_log, all_skipped) |
| write_log(failed_log, all_failed) |
|
|
| print(f"========== FOLDER {folder} SUMMARY ==========") |
| print(f"Found: {len(upload_list)}") |
| print(f"Uploaded: {len(uploaded)}") |
| print(f"Skipped existing: {len(skipped)}") |
| print(f"Failed: {len(failed)}") |
| print() |
|
|
| if PAUSE_AFTER_EACH_FOLDER: |
| input(f"[PAUSE] Finished folder {folder}. 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() |
| print(f"Uploaded log: {uploaded_log}") |
| print(f"Skipped log: {skipped_log}") |
| print(f"Failed log: {failed_log}") |
|
|
| if all_failed: |
| print("\nFailed 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)} zip 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_resolved_targets.txt") |
| missing_target_log = os.path.join(SCRIPT_DIR, "_delete_missing_targets.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 zip entries found in: {FILE_LIST}") |
| 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() |