summaryrefslogtreecommitdiff
path: root/paperbot/ezproxy.py
blob: ee249a5c992690f536de61f862baa7d76e4674a9 (plain)
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
"""
Use some ezproxy urls and credentials.
"""

import os
import json
import logging
log = logging.getLogger("paperbot.ezproxy")

# This directory stores json files that each contain information about a
# unique ezproxy endpoint that could be tried.
EZPROXY_DIR = os.environ.get(
    "EZPROXY_DIR",
    os.path.abspath(
        os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "../ezproxy"
        )
    )
)


def load_json_file(path):
    """
    Load and parse json representing an ezproxy endpoint.
    """
    # open up the file to read ezproxy config
    with open(realpath, "r") as configfile:
        config = configfile.read()

    # parse config as json
    ezconfig = json.loads(config)

    return ezconfig


def load_ezproxy_config(ezproxy_dir=EZPROXY_DIR):
    """
    Load ezproxy config from json files. These files contain information such
    as the ezproxy url template, username, password, and possibly other
    details.
    """
    ezproxy_config = {}

    if not os.path.exists(ezproxy_dir):
        log.debug("Not loading ezproxy configs because EZPROXY_DIR doesn't exist: {}".format(ezproxy_dir))
        return ezproxy_config

    # look at the directory to see config files
    filenames = os.listdir(ezproxy_dir)

    for filename in filenames:
        # ignore filenames that can't have .json
        badcondition1 = (len(filename) <= len(".json"))

        # ignore non-json files
        badcondition2 = (".json" not in filename[-5:])

        if badcondition1 or badcondition2:
            log.debug("Not loading file from EZPROXY_DIR: {}".format(filename))
            continue
        else:
            log.debug("Loading ezproxy file: {}".format(filename))

        # name of ezproxy is given by filename
        name = filename[0:-5]

        # get abspath to this json file
        realpath = os.path.abspath(os.path.join(ezproxy_dir, filename))

        # open up the file and read ezproxy config
        ezconfig = load_json_file(realpath)

        # dump in some extra data why not
        ezconfig.update({
            "name": name,
            "realpath": realpath,
        })

        # store this config for later
        ezproxy_config[name] = ezconfig

    return ezproxy_config

# default action is dothings
EZPROXY_CONFIG = load_ezproxy_config()