summaryrefslogblamecommitdiffstats
path: root/main.py
blob: f47af9ad76c22bbb40898af11c55dd26ef8c5bb5 (plain) (tree)















































































































































                                                                                                           
#!/usr/bin/env python

import os
import sys
import getopt
import traceback

from pathlib import Path
from datetime import datetime
from configparser import ConfigParser


def usage():
    print(os.path.basename(sys.argv[0]) + "[-h|--help] [-s|--skip] [-t|--title title] [-c|--correspondent "
                                          "correspondent] [--tags tags] file")
    print("    -h|--help           prints this help and exits")
    print("    -t|--title          title to give to the file")
    print("    -c|--correspondent  correspondent of the file")
    print("    --tags              comma-separated additional tags for the file")
    print("    file                path to pdf to upload")


def read_config():
    config_object = ConfigParser()
    config_object.read(os.environ.get('XDG_CONFIG_HOME') + "/paperless_upload.ini")

    sever_info = config_object["SERVER_CONFIG"]
    state = config_object["STATE"]
    return sever_info["remote"], sever_info["remote_path"], sever_info["user"], state["current_id"]


def update_id(new_id):
    config_object = ConfigParser()
    config_object.read(os.environ.get('XDG_CONFIG_HOME') + "/paperless_upload.ini")

    state = config_object["STATE"]

    # Update the password
    state["current_id"] = str(new_id)

    # Write changes back to file
    with open(os.environ.get('XDG_CONFIG_HOME') + "/paperless_upload.ini", 'w') as conf:
        config_object.write(conf)


def upload(remote, remote_path, username, file_id, path, title, correspondent, tags):
    if not remote_path:
        remote_path = input("Remote path: ")
    if not remote:
        remote = input("Remote: ")
    if not remote_path:
        remote_path = input("Consumer path: ")
    if not username:
        username = input("Username: ")
    if not file_id:
        file_id = input("File ID: ")
    if not title:
        title = input("Title: ")
    if not correspondent:
        correspondent = input("Correspondent: ")

    if not remote:
        print("You need to name a remote server to push to!")
        sys.exit(6)
    if not remote_path:
        print("You need to name a remote path to push to!")
        sys.exit(6)
    if not username:
        print("You need to provide a username to login with!")
        sys.exit(6)
    if not file_id:
        file_id = "NONE"
    if not title:
        title = Path(path).with_suffix('').__str__()
    if not correspondent:
        correspondent = "UNSET"

    # current date and time
    now = datetime.now()
    zulu_format = "%Y%m%d%H%M%S"
    time1 = now.strftime(zulu_format)

    # https://paperless.readthedocs.io/en/latest/guesswork.html?highlight=guesswork
    # --> "Date - Correspondent - Title - tag,tag,tag.pdf"
    guess_work_name = time1 + "Z - " + correspondent + " - " + title
    if tags:
        guess_work_name = guess_work_name + " - id" + str(file_id) + "," + tags + ".pdf"
    else:
        guess_work_name = guess_work_name + " - id" + str(file_id) + ".pdf"

    remote_file = (remote_path + guess_work_name).replace(" ", "\\\\ ")
    command = f"scp {path} {username}@{remote}:\"{remote_file}\""
    print("# use the following command to upload:")
    print(command)


def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ht:c:", ["help", "title", "correspondent", "tags"])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)

    title = ""
    correspondent = ""
    tags = ""

    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-t", "--title"):
            title = a
        elif o in ("-c", "--correspondent"):
            correspondent = a
        elif o == "--tags":
            tags = a
        else:
            assert False, "unhandled option: " + o

    if len(args) != 1:
        usage()
        sys.exit(3)

    try:
        remote, remote_path, username, file_id = read_config()
    except Exception:
        traceback.print_exc()
        sys.exit(4)

    try:
        upload(remote=remote, remote_path=remote_path, username=username, file_id=file_id,
               path=args[0], title=title, correspondent=correspondent, tags=tags)
    except Exception:
        traceback.print_exc()
        sys.exit(5)
    else:
        update_id(int(file_id) + 1)


if __name__ == "__main__":
    main()