File: config.py

package info (click to toggle)
python-internetarchive 5.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 1,000 kB
  • sloc: python: 7,445; xml: 180; makefile: 180
file content (183 lines) | stat: -rw-r--r-- 6,763 bytes parent folder | download | duplicates (2)
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
#
# The internetarchive module is a Python/CLI interface to Archive.org.
#
# Copyright (C) 2012-2024 Internet Archive
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""
internetarchive.config
~~~~~~~~~~~~~~~~~~~~~~

:copyright: (C) 2012-2024 by Internet Archive.
:license: AGPL 3, see LICENSE for more details.
"""
from __future__ import annotations

import os
from collections import defaultdict
from configparser import RawConfigParser
from time import sleep
from typing import Mapping

import requests

from internetarchive import auth
from internetarchive.exceptions import AuthenticationError
from internetarchive.utils import deep_update


def get_auth_config(email: str, password: str, host: str = 'archive.org') -> dict:
    u = f'https://{host}/services/xauthn/'
    p = {'op': 'login'}
    d = {'email': email, 'password': password}
    r = requests.post(u, params=p, data=d, timeout=10)
    sleep(2)
    j = r.json()
    if not j.get('success'):
        try:
            msg = j['values']['reason']
        except KeyError:
            msg = j['error']
        if msg == 'account_not_found':
            msg = 'Account not found, check your email and try again.'
        elif msg == 'account_bad_password':
            msg = 'Incorrect password, try again.'
        else:
            msg = f'Authentication failed: {msg}'
        raise AuthenticationError(msg)
    auth_config = {
        's3': {
            'access': j['values']['s3']['access'],
            'secret': j['values']['s3']['secret'],
        },
        'cookies': {
            'logged-in-user': j['values']['cookies']['logged-in-user'],
            'logged-in-sig': j['values']['cookies']['logged-in-sig'],
        },
        'general': {
            'screenname': j['values']['screenname'],
        }
    }
    return auth_config


def write_config_file(auth_config: Mapping, config_file=None):
    config_file, is_xdg, config = parse_config_file(config_file)

    # S3 Keys.
    access = auth_config.get('s3', {}).get('access')
    secret = auth_config.get('s3', {}).get('secret')
    config.set('s3', 'access', access)
    config.set('s3', 'secret', secret)

    # Cookies.
    cookies = auth_config.get('cookies', {})
    config.set('cookies', 'logged-in-user', cookies.get('logged-in-user'))
    config.set('cookies', 'logged-in-sig', cookies.get('logged-in-sig'))

    # General.
    screenname = auth_config.get('general', {}).get('screenname')
    config.set('general', 'screenname', screenname)

    # Create directory if needed.
    config_directory = os.path.dirname(config_file)
    if is_xdg and not os.path.exists(config_directory):
        # os.makedirs does not apply the mode for intermediate directories since Python 3.7.
        # The XDG Base Dir spec requires that the XDG_CONFIG_HOME directory be created with mode 700.
        # is_xdg will be True iff config_file is ${XDG_CONFIG_HOME}/internetarchive/ia.ini.
        # So create grandparent first if necessary then parent to ensure both have the right mode.
        os.makedirs(os.path.dirname(config_directory), mode=0o700, exist_ok=True)
        os.mkdir(config_directory, 0o700)

    # Write config file.
    with open(config_file, 'w') as fh:
        os.chmod(config_file, 0o600)
        config.write(fh)

    return config_file


def parse_config_file(config_file=None):
    config = RawConfigParser()

    is_xdg = False
    if not config_file:
        candidates = []
        if os.environ.get('IA_CONFIG_FILE'):
            candidates.append(os.environ['IA_CONFIG_FILE'])
        xdg_config_home = os.environ.get('XDG_CONFIG_HOME')
        if not xdg_config_home or not os.path.isabs(xdg_config_home):
            # Per the XDG Base Dir specification, this should be $HOME/.config. Unfortunately, $HOME
            # does not exist on all systems. Therefore, we use ~/.config here. On a POSIX-compliant
            # system, where $HOME must always be set, the XDG spec will be followed precisely.
            xdg_config_home = os.path.join(os.path.expanduser('~'), '.config')
        xdg_config_file = os.path.join(xdg_config_home, 'internetarchive', 'ia.ini')
        candidates.append(xdg_config_file)
        candidates.append(os.path.join(os.path.expanduser('~'), '.config', 'ia.ini'))
        candidates.append(os.path.join(os.path.expanduser('~'), '.ia'))
        for candidate in candidates:
            if os.path.isfile(candidate):
                config_file = candidate
                break
        else:
            # None of the candidates exist, default to IA_CONFIG_FILE if set else XDG
            config_file = os.environ.get('IA_CONFIG_FILE', xdg_config_file)
        if config_file == xdg_config_file:
            is_xdg = True
    config.read(config_file)

    if not config.has_section('s3'):
        config.add_section('s3')
        config.set('s3', 'access', None)
        config.set('s3', 'secret', None)
    if not config.has_section('cookies'):
        config.add_section('cookies')
        config.set('cookies', 'logged-in-user', None)
        config.set('cookies', 'logged-in-sig', None)

    if config.has_section('general'):
        for k, _v in config.items('general'):
            if k in ['secure']:
                config.set('general', k, config.getboolean('general', k))
        if not config.get('general', 'screenname'):
            config.set('general', 'screenname', None)
    else:
        config.add_section('general')
        config.set('general', 'screenname', None)

    return (config_file, is_xdg, config)


def get_config(config=None, config_file=None) -> dict:
    _config = config or {}
    config_file, is_xdg, config = parse_config_file(config_file)

    if not os.path.isfile(config_file):
        return _config

    config_dict: dict = defaultdict(dict)
    for sec in config.sections():
        try:
            for k, v in config.items(sec):
                if k is None or v is None:
                    continue
                config_dict[sec][k] = v
        except TypeError:
            pass

    # Recursive/deep update.
    deep_update(config_dict, _config)

    return {k: v for k, v in config_dict.items() if v is not None}