summaryrefslogtreecommitdiffstats
path: root/main.py
blob: f47af9ad76c22bbb40898af11c55dd26ef8c5bb5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/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()