client.py 6.01 KB
Newer Older
1
2
from __future__ import unicode_literals

Agate's avatar
Agate committed
3
import json
Agate's avatar
Agate committed
4
import logging
Agate's avatar
Agate committed
5
import os
6
import requests
Agate's avatar
Agate committed
7
import requests_oauthlib
8

9
from mopidy import httpclient, exceptions
10
11
12

from . import Extension, __version__

Agate's avatar
Agate committed
13
14
logger = logging.getLogger(__name__)

Agate's avatar
Agate committed
15
16
REQUIRED_SCOPES = ["read:libraries", "read:favorites", "read:playlists"]

17
18
19
20
21
22
23
24
25
26
27

class SessionWithUrlBase(requests.Session):
    # In Python 3 you could place `url_base` after `*args`, but not in Python 2.
    def __init__(self, url_base=None, *args, **kwargs):
        super(SessionWithUrlBase, self).__init__(*args, **kwargs)
        self.url_base = url_base

    def request(self, method, url, **kwargs):
        # Next line of code is here for example purposes only.
        # You really shouldn't just use string concatenation here,
        # take a look at urllib.parse.urljoin instead.
Agate's avatar
Agate committed
28
29
30
31
        if url.startswith("http://") or url.startswith("https://"):
            modified_url = url
        else:
            modified_url = self.url_base + url
32
33
34
35

        return super(SessionWithUrlBase, self).request(method, modified_url, **kwargs)


Agate's avatar
Agate committed
36
37
38
39
40
class OAuth2Session(SessionWithUrlBase, requests_oauthlib.OAuth2Session):
    pass


def get_requests_session(url, proxy_config, user_agent, base_cls, **kwargs):
Agate's avatar
Agate committed
41
42
43
    if not url.endswith("/"):
        url += "/"
    url += "api/v1/"
44
45
46
47

    proxy = httpclient.format_proxy(proxy_config)
    full_user_agent = httpclient.format_user_agent(user_agent)

Agate's avatar
Agate committed
48
    session = base_cls(url_base=url, **kwargs)
Agate's avatar
Agate committed
49
50
    session.proxies.update({"http": proxy, "https": proxy})
    session.headers.update({"user-agent": full_user_agent})
51
52
53
54

    return session


Agate's avatar
Agate committed
55
def login_legacy(session, username, password):
Agate's avatar
Agate committed
56
57
58
    if not username:
        return
    response = session.post("token/", {"username": username, "password": password})
59
60
61
    try:
        response.raise_for_status()
    except requests.exceptions.HTTPError:
Agate's avatar
Agate committed
62
63
64
        raise exceptions.BackendError("Authentication failed for user %s" % (username,))
    token = response.json()["token"]
    session.headers.update({"Authorization": "JWT %s" % (token,)})
65
    return token
66

Agate's avatar
Agate committed
67

68
class APIClient(object):
Agate's avatar
Agate committed
69
70
    def __init__(self, config):
        self.config = config
Agate's avatar
Agate committed
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
        self.jwt_token = None
        self.oauth_token = get_token(config)
        if self.use_oauth:
            self.session = get_requests_session(
                config["funkwhale"]["url"],
                proxy_config=config["proxy"],
                user_agent="%s/%s" % (Extension.dist_name, __version__),
                base_cls=OAuth2Session,
                client_id=self.config["funkwhale"]["client_id"],
                token=self.oauth_token,
                auto_refresh_url=config["funkwhale"]["url"]
                + config["funkwhale"].get("token_endpoint")
                or "/api/v1/oauth/token/",
                auto_refresh_kwargs={
                    "client_id": self.config["funkwhale"]["client_id"],
                    "client_secret": self.config["funkwhale"]["client_id"],
                },
                token_updater=self.refresh_token,
            )
        else:
            self.session = get_requests_session(
                config["funkwhale"]["url"],
                proxy_config=config["proxy"],
                user_agent="%s/%s" % (Extension.dist_name, __version__),
                base_cls=SessionWithUrlBase,
            )
            self.username = self.config["funkwhale"]["username"]
        self.session.verify = config["funkwhale"].get("verify_cert", True)

    @property
    def use_oauth(self):
        return self.config["funkwhale"]["client_id"] and self.oauth_token

    def refresh_token(self, token):
        self.oauth_token = token
        set_token(token, config)
Agate's avatar
Agate committed
107
108
109
110

    def login(self):
        self.username = self.config["funkwhale"]["username"]
        if self.username:
Agate's avatar
Agate committed
111
            self.jwt_token = login_legacy(
Agate's avatar
Agate committed
112
113
114
115
116
                self.session,
                self.config["funkwhale"]["username"],
                self.config["funkwhale"]["password"],
            )
        else:
Agate's avatar
Agate committed
117
            self.jwt_token = None
118
119

    def search(self, query):
Agate's avatar
Agate committed
120
        response = self.session.get("search", params={"query": query})
121
122
123
124
        response.raise_for_status()
        return response.json()

    def get_track(self, id):
Agate's avatar
Agate committed
125
        response = self.session.get("tracks/{}/".format(id))
126
127
128
129
        response.raise_for_status()
        return response.json()

    def list_tracks(self, filters):
Agate's avatar
Agate committed
130
        response = self.session.get("tracks/", params=filters)
131
132
        response.raise_for_status()
        return response.json()
Agate's avatar
Agate committed
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

    def list_artists(self, filters):
        response = self.session.get("artists/", params=filters)
        response.raise_for_status()
        return response.json()

    def list_albums(self, filters):
        response = self.session.get("albums/", params=filters)
        response.raise_for_status()
        return response.json()

    def load_all(self, first_page, max=0):
        for i in first_page["results"]:
            yield i

        next_page = first_page.get("next")
        counter = 0
        while next_page:
            logger.info("Fetching next page of result at url: %s", next_page)
            response = self.session.get(next_page)
            response.raise_for_status()
            payload = response.json()
            for i in payload["results"]:
                yield i
            counter += 1
            next_page = payload.get("next")
            if max and counter >= max:
                next_page = None
Agate's avatar
Agate committed
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185


def get_token(config):
    import mopidy_funkwhale

    data_dir = mopidy_funkwhale.Extension.get_data_dir(config)
    try:
        with open(os.path.join(data_dir, "token"), "r") as f:
            raw = f.read()
    except IOError:
        return None
    try:
        return json.loads(raw)
    except (TypeError, ValueError):
        logger.error("Cannot decode token data, you may need to relogin")


def set_token(token_data, config):
    import mopidy_funkwhale

    data_dir = mopidy_funkwhale.Extension.get_data_dir(config)
    print(data_dir)
    content = json.dumps(token_data)
    with open(os.path.join(data_dir, "token"), "w") as f:
        f.write(content)