File: config.py

package info (click to toggle)
python-internetarchive 1.8.1-1%2Bdeb10u1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 832 kB
  • sloc: python: 4,646; makefile: 180; xml: 180
file content (174 lines) | stat: -rw-r--r-- 5,629 bytes parent folder | download
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
# -*- coding: utf-8 -*-
#
# The internetarchive module is a Python/CLI interface to Archive.org.
#
# Copyright (C) 2012-2017 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-2017 by Internet Archive.
:license: AGPL 3, see LICENSE for more details.
"""
from __future__ import absolute_import

import os
from collections import defaultdict
from six.moves import configparser

import requests

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


def get_auth_config(username, password):
    payload = dict(
        username=username,
        password=password,
        remember='CHECKED',
        action='login',
    )

    with requests.Session() as s:
        # Attache logged-in-* cookies to Session.
        u = 'https://archive.org/account/login.php'
        r = s.post(u, data=payload, cookies={'test-cookie': '1'})
        if 'logged-in-sig' not in s.cookies:
            raise AuthenticationError('Authentication failed. '
                                      'Please check your credentials and try again.')

        # Get S3 keys.
        u = 'https://archive.org/account/s3.php'
        p = dict(output_json=1)
        r = s.get(u, params=p)
        j = r.json()
        access_key = j['key']['s3accesskey']
        secret_key = j['key']['s3secretkey']
        if not j or not j.get('key'):
            raise AuthenticationError('Authentication failed. '
                                      'Please check your credentials and try again.')

        # Get user info (screenname).
        u = 'https://s3.us.archive.org'
        p = dict(check_auth=1)
        r = requests.get(u, params=p, auth=auth.S3Auth(access_key, secret_key))
        r.raise_for_status()
        j = r.json()
        if j.get('error'):
            raise AuthenticationError(j.get('error'))
        user_info = j['screenname']

        auth_config = {
            's3': {
                'access': access_key,
                'secret': secret_key,
            },
            'cookies': {
                'logged-in-user': s.cookies['logged-in-user'],
                'logged-in-sig': s.cookies['logged-in-sig'],
            },
            'general': {
                'screenname': user_info,
            }
        }

    return auth_config


def write_config_file(username, password, config_file=None):
    config_file, config = parse_config_file(config_file)
    auth_config = get_auth_config(username, password)

    # 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['general']['screenname']
    config.set('general', 'screenname', screenname)

    # 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 = configparser.RawConfigParser()

    if not config_file:
        config_dir = os.path.expanduser('~/.config')
        if not os.path.isdir(config_dir):
            config_file = os.path.expanduser('~/.ia')
        else:
            config_file = '{0}/ia.ini'.format(config_dir)
    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, config)


def get_config(config=None, config_file=None):
    _config = {} if not config else config
    config_file, config = parse_config_file(config_file)

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

    config_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 dict((k, v) for k, v in config_dict.items() if v is not None)