|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Upload a file to WebDAV server. |
| 4 | +
|
| 5 | +Usage: ./upload-webdav.py <local_file> <remote_path> --url <webdav_url> --user <username> --pass <password> |
| 6 | +
|
| 7 | +Example: |
| 8 | + ./upload-webdav.py video.mp4 /processed/video.mp4 --url https://nextcloud.example.com/remote.php/webdav --user admin --pass secret |
| 9 | +""" |
| 10 | + |
| 11 | +import argparse |
| 12 | +import os |
| 13 | +import sys |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +import requests |
| 17 | +from requests.auth import HTTPBasicAuth |
| 18 | + |
| 19 | + |
| 20 | +def upload_file(local_path: str, remote_path: str, webdav_url: str, username: str, password: str) -> bool: |
| 21 | + """Upload a file to WebDAV server.""" |
| 22 | + |
| 23 | + if not Path(local_path).exists(): |
| 24 | + print(f"Error: File not found: {local_path}") |
| 25 | + return False |
| 26 | + |
| 27 | + # Build the full URL |
| 28 | + webdav_url = webdav_url.rstrip('/') |
| 29 | + remote_path = remote_path.lstrip('/') |
| 30 | + url = f"{webdav_url}/{remote_path}" |
| 31 | + |
| 32 | + file_size = Path(local_path).stat().st_size |
| 33 | + print(f"Uploading: {local_path}") |
| 34 | + print(f"Size: {file_size / (1024*1024):.1f} MB") |
| 35 | + print(f"To: {url}") |
| 36 | + print() |
| 37 | + |
| 38 | + try: |
| 39 | + with open(local_path, 'rb') as f: |
| 40 | + response = requests.put( |
| 41 | + url, |
| 42 | + data=f, |
| 43 | + auth=HTTPBasicAuth(username, password), |
| 44 | + headers={'Content-Type': 'application/octet-stream'}, |
| 45 | + ) |
| 46 | + |
| 47 | + if response.status_code in (200, 201, 204): |
| 48 | + print("Upload successful!") |
| 49 | + return True |
| 50 | + else: |
| 51 | + print(f"Upload failed: {response.status_code} {response.reason}") |
| 52 | + print(response.text[:500] if response.text else "") |
| 53 | + return False |
| 54 | + |
| 55 | + except Exception as e: |
| 56 | + print(f"Error: {e}") |
| 57 | + return False |
| 58 | + |
| 59 | + |
| 60 | +def main(): |
| 61 | + parser = argparse.ArgumentParser(description="Upload a file to WebDAV server") |
| 62 | + parser.add_argument("local_file", help="Local file to upload") |
| 63 | + parser.add_argument("remote_path", help="Remote path (e.g., /processed/video.mp4)") |
| 64 | + parser.add_argument("--url", required=True, help="WebDAV URL") |
| 65 | + parser.add_argument("--user", required=True, help="Username") |
| 66 | + parser.add_argument("--pass", dest="password", required=True, help="Password") |
| 67 | + |
| 68 | + args = parser.parse_args() |
| 69 | + |
| 70 | + success = upload_file( |
| 71 | + args.local_file, |
| 72 | + args.remote_path, |
| 73 | + args.url, |
| 74 | + args.user, |
| 75 | + args.password |
| 76 | + ) |
| 77 | + |
| 78 | + sys.exit(0 if success else 1) |
| 79 | + |
| 80 | + |
| 81 | +if __name__ == "__main__": |
| 82 | + main() |
0 commit comments