#! /usr/bin/env nix-shell #! nix-shell /etc/nixos/scripts/nix/python.nix -i python import argparse import mimetypes import os from pathlib import Path from typing import Any import requests # type: ignore from common.common import ( # type: ignore notify, read_secret_file, ) from pyperclip import copy # type: ignore def zipline( file_path: Path, instance_url: str, application_name: str | None = None, desktop_entry: str | None = None, ) -> Any: token = read_secret_file(secret="zipline", home=True) if not os.path.isfile(file_path): raise FileNotFoundError(f"File at {file_path} does not exist.") content_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream" try: headers = {"authorization": token} files = { "file": (os.path.basename(file_path), open(file_path, "rb"), content_type) } response = requests.post( f"{instance_url.rstrip('/')}/api/upload", headers=headers, files=files ) if response.status_code == 200: response_data = response.json() link = response_data.get("files", [None])[0] if link: try: copy(text=link) print(f"Link copied to clipboard: {link}") except BaseException as e: print(f"Failed to copy link to clipboard: {e}\nAre you using SSH?") if application_name and desktop_entry: notify( application_name=application_name, title="Upload Successful", message=f"Link copied to clipboard: {link}", urgency="low", category="transfer.complete", icon=file_path, ) else: raise ValueError("Invalid response format.") else: error_message = response.text raise Exception(error_message) except BaseException as e: if application_name and desktop_entry: notify( application_name=application_name, title="Upload Failed", message=f"An error occurred: {e}", urgency="normal", category="transfer.error", icon=file_path, ) raise e if __name__ == "__main__": parser = argparse.ArgumentParser( prog="zipline.py", description="Upload a file to a Zipline instance.", epilog="Example usage: zipline.py /path/to/file.txt", ) parser.add_argument("file", help="The file to upload.") parser.add_argument( "--url", help="The URL of the Zipline instance. Defaults to 'https://csw.im'.", default="https://csw.im", ) parser.add_argument( "--application-name", help="The name of the application that is uploading the file. Defaults to 'Zipline'.", default="Zipline", ) parser.add_argument( "--desktop-entry", help="The desktop entry file for the application that is uploading the file. If this is provided, notify-send will be invoked to display a notification if the upload succeeds or fails.", default=None, ) args = parser.parse_args() zipline( file_path=args.file, instance_url=args.url, application_name=args.application_name, desktop_entry=args.desktop_entry, )