⎗
✓
#!/usr/bin/env python3
"""
MIME Type Extension Fixer for Rclone Backups
Queries source MIME types via `rclone lsjson` and renames files on the destination
using `rclone moveto` if they are missing standard extensions.
"""

import sys
import json
import mimetypes
import argparse
import subprocess
from concurrent.futures import ThreadPoolExecutor

MIME_EXTENSIONS = {
    "application/pdf": ".pdf",
    "image/png": ".png",
    "image/jpeg": ".jpg",
    "image/jpg": ".jpg",
    "image/gif": ".gif",
    "image/webp": ".webp",
    "video/mp4": ".mp4",
    "video/x-matroska": ".mkv",
    "video/quicktime": ".mov",
    "audio/mpeg": ".mp3",
    "audio/wav": ".wav",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
    "application/msword": ".doc",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
    "application/vnd.ms-excel": ".xls",
    "application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",
    "application/vnd.ms-powerpoint": ".ppt",
    "application/zip": ".zip",
    "application/x-rar-compressed": ".rar",
    "application/x-7z-compressed": ".7z",
    "text/plain": ".txt",
    "text/csv": ".csv",
}

def get_extension_from_mime(mime_type: str) -> str:
    if not mime_type:
        return ""
    mime_clean = mime_type.strip().lower()
    if mime_clean in MIME_EXTENSIONS:
        return MIME_EXTENSIONS[mime_clean]
    return mimetypes.guess_extension(mime_clean) or ""

def run_rclone_json(endpoint: str):
    cmd = ["rclone", "lsjson", endpoint, "--fast-list", "-R"]
    proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding="utf-8", errors="replace")
    if proc.returncode != 0:
        print(f"Error reading '{endpoint}': {proc.stderr}", file=sys.stderr)
        return None
    return json.loads(proc.stdout)

def fix_extensions(src_endpoint: str, dst_endpoint: str, dry_run: bool = False, max_workers: int = 4):
    src_endpoint = src_endpoint.rstrip("/")
    dst_endpoint = dst_endpoint.rstrip("/")

    src_files = run_rclone_json(src_endpoint)
    dst_files = run_rclone_json(dst_endpoint)
    if src_files is None or dst_files is None:
        return

    dst_map = {df["Path"].replace("\\", "/"): df for df in dst_files if not df.get("IsDir")}

    rename_pairs = []
    for sf in src_files:
        if sf.get("IsDir"):
            continue
        mime = sf.get("MimeType", "")
        exp_ext = get_extension_from_mime(mime)
        name = sf.get("Name", "")

        # If source has no extension matching its MIME
        if exp_ext and not name.lower().endswith(exp_ext.lower()):
            norm_src = sf.get("Path", "").replace("\\", "/")
            target_norm = f"{norm_src}{exp_ext}"

            # Only rename if unextended file exists on destination and target doesn't yet exist
            if norm_src in dst_map and target_norm not in dst_map:
                rename_pairs.append((norm_src, target_norm, name, exp_ext))

    if not rename_pairs:
        print("No files need renaming.")
        return

    print(f"Found {len(rename_pairs)} file(s) missing extensions:")
    for norm_src, target_norm, name, exp_ext in rename_pairs[:10]:
        print(f"  '{name}' -> '{name}{exp_ext}'")

    if dry_run:
        print(f"[DRY RUN] Would rename {len(rename_pairs)} file(s).")
        return

    def do_rename(pair):
        norm_src, target_norm, _, _ = pair
        move_cmd = ["rclone", "moveto", f"{dst_endpoint}/{norm_src}", f"{dst_endpoint}/{target_norm}"]
        return subprocess.run(move_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode == 0

    with ThreadPoolExecutor(max_workers=max_workers) as pool:
        results = list(pool.map(do_rename, rename_pairs))
    print(f"Renamed {sum(1 for r in results if r)}/{len(rename_pairs)} files.")

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--src", help="Source endpoint (e.g., gdrive:folder)")
    parser.add_argument("--dst", help="Destination endpoint (e.g., mega:folder)")
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    src = args.src or input("Source endpoint: ").strip()
    dst = args.dst or input("Destination endpoint: ").strip()
    dry_run = args.dry_run

    if not args.dry_run and not sys.argv[1:]:
        ans = input("Dry run first? [Y/n]: ").strip().lower()
        dry_run = ans not in ("n", "no")

    fix_extensions(src, dst, dry_run=dry_run)

if __name__ == "__main__":
    main()

The Problem in Practice:

  1. rclone copy uploads the file A Gentle Reminder (retaining the source filename).
  2. The script runs rclone moveto on the destination: A Gentle Reminder $\rightarrow$ A Gentle Reminder.pdf.
  3. On the next cron run, rclone copy checks if A Gentle Reminder exists on MEGA. Because only A Gentle Reminder.pdf is present, rclone considers it missing and re-copies A Gentle Reminder, resulting in duplicates.
Edit

Pub: 28 Oct 2026 06:37 UTC

Edit: 28 Oct 2026 06:45 UTC

Views: 33