putio.py 8.8.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- putio_py-8.8.0.dist-info/METADATA +52 -0
- putio_py-8.8.0.dist-info/RECORD +5 -0
- putio_py-8.8.0.dist-info/WHEEL +5 -0
- putio_py-8.8.0.dist-info/top_level.txt +1 -0
- putiopy.py +729 -0
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Metadata-Version: 2.2
|
|
2
|
+
Name: putio.py
|
|
3
|
+
Version: 8.8.0
|
|
4
|
+
Summary: Python client for put.io API v2
|
|
5
|
+
Author-email: Cenk Altı <cenkalti@gmail.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/cenkalti/putio.py
|
|
8
|
+
Project-URL: Issues, https://github.com/cenkalti/putio.py/issues
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/x-rst
|
|
11
|
+
Requires-Dist: requests
|
|
12
|
+
Requires-Dist: tus.py
|
|
13
|
+
|
|
14
|
+
putio.py
|
|
15
|
+
========
|
|
16
|
+
|
|
17
|
+
Simple wrapper for `Put.io API v2 <https://api.put.io/v2/docs>`_.
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
Installing
|
|
21
|
+
----------
|
|
22
|
+
|
|
23
|
+
putio.py is available on PyPI.
|
|
24
|
+
|
|
25
|
+
.. code-block:: bash
|
|
26
|
+
|
|
27
|
+
$ pip install putio.py
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
Usage
|
|
31
|
+
-----
|
|
32
|
+
|
|
33
|
+
.. code-block:: python
|
|
34
|
+
|
|
35
|
+
import putiopy
|
|
36
|
+
|
|
37
|
+
helper = putiopy.AuthHelper(CLIENT_ID, CLIENT_SECRET, \
|
|
38
|
+
CALLBACK_URL, type='token')
|
|
39
|
+
|
|
40
|
+
# this will open a browser to authetication url
|
|
41
|
+
# after authenticating you will find the oauth_token in the address bar
|
|
42
|
+
helper.open_authentication_url()
|
|
43
|
+
|
|
44
|
+
client = putiopy.Client(OAUTH_TOKEN)
|
|
45
|
+
|
|
46
|
+
# list files
|
|
47
|
+
files = client.File.list()
|
|
48
|
+
|
|
49
|
+
# add a new transfer
|
|
50
|
+
transfer = client.Transfer.add_url('http://example.com/good.torrent')
|
|
51
|
+
|
|
52
|
+
# read the code for other methods.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
putiopy.py,sha256=lA_W9XV83O-AfSsmDqgWvtqC-J5yhzmME_DxXS7S5BQ,22131
|
|
2
|
+
putio_py-8.8.0.dist-info/METADATA,sha256=duoI6yZGpseLOUn_kfs-pDJ4_caXwfYNxTqLJNyDv38,1151
|
|
3
|
+
putio_py-8.8.0.dist-info/WHEEL,sha256=nn6H5-ilmfVryoAQl3ZQ2l8SH5imPWFpm1A5FgEuFV4,91
|
|
4
|
+
putio_py-8.8.0.dist-info/top_level.txt,sha256=L8zFYm751cei9rOUee39EuKbYu9CvMu-ipOa3lU2Jtc,8
|
|
5
|
+
putio_py-8.8.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
putiopy
|
putiopy.py
ADDED
|
@@ -0,0 +1,729 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
from __future__ import absolute_import, division, print_function
|
|
3
|
+
|
|
4
|
+
import binascii
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import os
|
|
9
|
+
import webbrowser
|
|
10
|
+
from datetime import datetime
|
|
11
|
+
from importlib.metadata import version
|
|
12
|
+
from urllib.parse import urlencode
|
|
13
|
+
|
|
14
|
+
import requests
|
|
15
|
+
import tus
|
|
16
|
+
from requests.adapters import HTTPAdapter
|
|
17
|
+
from urllib3.util import Retry
|
|
18
|
+
|
|
19
|
+
__version__ = version("putio.py")
|
|
20
|
+
|
|
21
|
+
KB = 1024
|
|
22
|
+
MB = 1024 * KB
|
|
23
|
+
|
|
24
|
+
# Read and write operations are limited to this chunk size.
|
|
25
|
+
# This can make a big difference when dealing with large files.
|
|
26
|
+
CHUNK_SIZE = 256 * KB
|
|
27
|
+
|
|
28
|
+
BASE_URL = None
|
|
29
|
+
UPLOAD_URL = None
|
|
30
|
+
TUS_UPLOAD_URL = None
|
|
31
|
+
ACCESS_TOKEN_URL = None
|
|
32
|
+
AUTHENTICATION_URL = None
|
|
33
|
+
AUTHORIZATION_URL = None
|
|
34
|
+
|
|
35
|
+
logger = logging.getLogger(__name__)
|
|
36
|
+
logger.addHandler(logging.NullHandler())
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _set_domain(domain="put.io", scheme="https"):
|
|
40
|
+
global BASE_URL
|
|
41
|
+
global UPLOAD_URL
|
|
42
|
+
global TUS_UPLOAD_URL
|
|
43
|
+
global ACCESS_TOKEN_URL
|
|
44
|
+
global AUTHENTICATION_URL
|
|
45
|
+
global AUTHORIZATION_URL
|
|
46
|
+
|
|
47
|
+
api_base = "{scheme}://api.{domain}/v2".format(scheme=scheme, domain=domain)
|
|
48
|
+
upload_base = "{scheme}://upload.{domain}".format(scheme=scheme, domain=domain)
|
|
49
|
+
|
|
50
|
+
BASE_URL = api_base
|
|
51
|
+
UPLOAD_URL = upload_base + "/v2/files/upload"
|
|
52
|
+
TUS_UPLOAD_URL = upload_base + "/files/"
|
|
53
|
+
ACCESS_TOKEN_URL = api_base + "/oauth2/access_token"
|
|
54
|
+
AUTHENTICATION_URL = api_base + "/oauth2/authenticate"
|
|
55
|
+
AUTHORIZATION_URL = (
|
|
56
|
+
api_base + "/oauth2/authorizations/clients/{client_id}/{fingerprint}"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
_set_domain()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class APIError(Exception):
|
|
64
|
+
"""
|
|
65
|
+
Must be created with following arguments:
|
|
66
|
+
1. Response instance (requests.Response)
|
|
67
|
+
2. Type of the error (str)
|
|
68
|
+
3. Extra detail about the error (str, optional)
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
def __str__(self):
|
|
72
|
+
s = "%s, %s, %d, %s" % (
|
|
73
|
+
self.response.request.method,
|
|
74
|
+
self.response.request.url,
|
|
75
|
+
self.response.status_code,
|
|
76
|
+
self.type,
|
|
77
|
+
)
|
|
78
|
+
if self.message:
|
|
79
|
+
s += ", %r" % self.message
|
|
80
|
+
return s
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def response(self):
|
|
84
|
+
return self.args[0]
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def type(self):
|
|
88
|
+
return self.args[1]
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def message(self):
|
|
92
|
+
if len(self.args) > 2:
|
|
93
|
+
return self.args[2]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class ClientError(APIError):
|
|
97
|
+
pass
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class ServerError(APIError):
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class AuthHelper(object):
|
|
105
|
+
|
|
106
|
+
def __init__(self, client_id, client_secret, redirect_uri, type="code"):
|
|
107
|
+
self.client_id = client_id
|
|
108
|
+
self.client_secret = client_secret
|
|
109
|
+
self.callback_url = redirect_uri
|
|
110
|
+
self.type = type
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def authentication_url(self):
|
|
114
|
+
"""Redirect your users to here to authenticate them."""
|
|
115
|
+
params = {
|
|
116
|
+
"client_id": self.client_id,
|
|
117
|
+
"response_type": self.type,
|
|
118
|
+
"redirect_uri": self.callback_url,
|
|
119
|
+
}
|
|
120
|
+
return AUTHENTICATION_URL + "?" + urlencode(params)
|
|
121
|
+
|
|
122
|
+
def open_authentication_url(self):
|
|
123
|
+
webbrowser.open(self.authentication_url)
|
|
124
|
+
|
|
125
|
+
def get_access_token(self, code):
|
|
126
|
+
params = {
|
|
127
|
+
"client_id": self.client_id,
|
|
128
|
+
"client_secret": self.client_secret,
|
|
129
|
+
"grant_type": "authorization_code",
|
|
130
|
+
"redirect_uri": self.callback_url,
|
|
131
|
+
"code": code,
|
|
132
|
+
}
|
|
133
|
+
response = requests.get(ACCESS_TOKEN_URL, params=params)
|
|
134
|
+
return _process_response(response)["access_token"]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def create_access_token(client_id, client_secret, user, password, fingerprint=""):
|
|
138
|
+
url = AUTHORIZATION_URL.format(client_id=client_id, fingerprint=fingerprint)
|
|
139
|
+
data = {"client_secret": client_secret}
|
|
140
|
+
auth = (user, password)
|
|
141
|
+
response = requests.put(url, data=data, auth=auth)
|
|
142
|
+
return _process_response(response)["access_token"]
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def revoke_access_token(access_token):
|
|
146
|
+
url = BASE_URL + "/oauth/grants/logout"
|
|
147
|
+
headers = {"Authorization": "token %s" % access_token}
|
|
148
|
+
response = requests.post(url, headers=headers)
|
|
149
|
+
_process_response(response)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class Client(object):
|
|
153
|
+
|
|
154
|
+
def __init__(self, access_token, use_retry=False, extra_headers=None, timeout=5):
|
|
155
|
+
self.access_token = access_token
|
|
156
|
+
self.session = requests.session()
|
|
157
|
+
self.session.headers["User-Agent"] = "putio.py/%s" % __version__
|
|
158
|
+
self.session.headers["Accept"] = "application/json"
|
|
159
|
+
self.timeout = timeout
|
|
160
|
+
if extra_headers:
|
|
161
|
+
self.session.headers.update(extra_headers)
|
|
162
|
+
|
|
163
|
+
if use_retry:
|
|
164
|
+
# Retry maximum 10 times, backoff on each retry
|
|
165
|
+
# Sleeps 1s, 2s, 4s, 8s, etc to a maximum of 120s between retries
|
|
166
|
+
# Retries on HTTP status codes 500, 502, 503, 504
|
|
167
|
+
retries = Retry(
|
|
168
|
+
total=10, backoff_factor=1, status_forcelist=[500, 502, 503, 504]
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
# Use the retry strategy for all HTTPS requests
|
|
172
|
+
self.session.mount("https://", HTTPAdapter(max_retries=retries))
|
|
173
|
+
|
|
174
|
+
# Keep resource classes as attributes of client.
|
|
175
|
+
# Pass client to resource classes so resource object
|
|
176
|
+
# can use the client.
|
|
177
|
+
attributes = {"client": self}
|
|
178
|
+
self.File = type("File", (_File,), attributes)
|
|
179
|
+
self.Subtitle = type("Subtitle", (_Subtitle,), attributes)
|
|
180
|
+
self.Transfer = type("Transfer", (_Transfer,), attributes)
|
|
181
|
+
self.Account = type("Account", (_Account,), attributes)
|
|
182
|
+
|
|
183
|
+
def close(self):
|
|
184
|
+
self.session.close()
|
|
185
|
+
|
|
186
|
+
def request(
|
|
187
|
+
self,
|
|
188
|
+
path,
|
|
189
|
+
method="GET",
|
|
190
|
+
params=None,
|
|
191
|
+
data=None,
|
|
192
|
+
files=None,
|
|
193
|
+
headers=None,
|
|
194
|
+
raw=False,
|
|
195
|
+
allow_redirects=True,
|
|
196
|
+
stream=False,
|
|
197
|
+
timeout=None,
|
|
198
|
+
):
|
|
199
|
+
"""
|
|
200
|
+
Wrapper around requests.request()
|
|
201
|
+
|
|
202
|
+
Prepends BASE_URL to path.
|
|
203
|
+
Adds self.oauth_token to authorization header.
|
|
204
|
+
Parses response as JSON and returns it.
|
|
205
|
+
|
|
206
|
+
"""
|
|
207
|
+
if not headers:
|
|
208
|
+
headers = {}
|
|
209
|
+
|
|
210
|
+
if timeout is None:
|
|
211
|
+
timeout = self.timeout
|
|
212
|
+
|
|
213
|
+
# All requests must include oauth_token
|
|
214
|
+
headers["Authorization"] = "token %s" % self.access_token
|
|
215
|
+
|
|
216
|
+
if path.startswith(("http://", "https://")):
|
|
217
|
+
url = path
|
|
218
|
+
else:
|
|
219
|
+
url = BASE_URL + path
|
|
220
|
+
logger.debug("url: %s", url)
|
|
221
|
+
|
|
222
|
+
response = self.session.request(
|
|
223
|
+
method,
|
|
224
|
+
url,
|
|
225
|
+
params=params,
|
|
226
|
+
data=data,
|
|
227
|
+
files=files,
|
|
228
|
+
headers=headers,
|
|
229
|
+
allow_redirects=allow_redirects,
|
|
230
|
+
stream=stream,
|
|
231
|
+
timeout=self.timeout,
|
|
232
|
+
)
|
|
233
|
+
logger.debug("response: %s", response)
|
|
234
|
+
if raw:
|
|
235
|
+
return response
|
|
236
|
+
|
|
237
|
+
return _process_response(response)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _process_response(response):
|
|
241
|
+
logger.debug("response: %s", response)
|
|
242
|
+
logger.debug("content: %s", response.content)
|
|
243
|
+
|
|
244
|
+
http_error_type = str(response.status_code)[0]
|
|
245
|
+
exception_classes = {
|
|
246
|
+
"2": None,
|
|
247
|
+
"4": ClientError,
|
|
248
|
+
"5": ServerError,
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
try:
|
|
252
|
+
exception_class = exception_classes[http_error_type]
|
|
253
|
+
except KeyError:
|
|
254
|
+
raise ServerError(response, "UnknownStatusCode", str(response.status_code))
|
|
255
|
+
|
|
256
|
+
if exception_class:
|
|
257
|
+
try:
|
|
258
|
+
d = _parse_content(response)
|
|
259
|
+
error_type = d["error_type"]
|
|
260
|
+
error_message = d["error_message"]
|
|
261
|
+
except Exception:
|
|
262
|
+
error_type = "UnknownError"
|
|
263
|
+
error_message = None
|
|
264
|
+
|
|
265
|
+
raise exception_class(response, error_type, error_message)
|
|
266
|
+
|
|
267
|
+
return _parse_content(response)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _parse_content(response):
|
|
271
|
+
try:
|
|
272
|
+
u = response.content.decode("utf-8")
|
|
273
|
+
except ValueError:
|
|
274
|
+
raise ServerError(response, "InvalidEncoding", "cannot decode as UTF-8")
|
|
275
|
+
|
|
276
|
+
try:
|
|
277
|
+
return json.loads(u)
|
|
278
|
+
except ValueError:
|
|
279
|
+
raise ServerError(response, "InvalidJSON")
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
class _BaseResource(object):
|
|
283
|
+
|
|
284
|
+
client = None
|
|
285
|
+
|
|
286
|
+
def __init__(self, resource_dict):
|
|
287
|
+
"""Constructs the object from a dict."""
|
|
288
|
+
# All resources must have id and name attributes
|
|
289
|
+
self.id = None
|
|
290
|
+
self.name = None
|
|
291
|
+
self.__dict__.update(resource_dict)
|
|
292
|
+
try:
|
|
293
|
+
self.created_at = strptime(self.created_at)
|
|
294
|
+
except Exception:
|
|
295
|
+
self.created_at = None
|
|
296
|
+
|
|
297
|
+
def __str__(self):
|
|
298
|
+
return self.name.encode("utf-8")
|
|
299
|
+
|
|
300
|
+
def __repr__(self):
|
|
301
|
+
# shorten name for display
|
|
302
|
+
name = self.name[:17] + "..." if len(self.name) > 20 else self.name
|
|
303
|
+
return "<%s id=%r, name=%r>" % (self.__class__.__name__, self.id, name)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
class _File(_BaseResource):
|
|
307
|
+
|
|
308
|
+
@classmethod
|
|
309
|
+
def get(cls, id):
|
|
310
|
+
d = cls.client.request("/files/%i" % id, method="GET")
|
|
311
|
+
t = d["file"]
|
|
312
|
+
return cls(t)
|
|
313
|
+
|
|
314
|
+
@classmethod
|
|
315
|
+
def list(
|
|
316
|
+
cls,
|
|
317
|
+
parent_id=0,
|
|
318
|
+
per_page=1000,
|
|
319
|
+
sort_by=None,
|
|
320
|
+
content_type=None,
|
|
321
|
+
file_type=None,
|
|
322
|
+
stream_url=False,
|
|
323
|
+
stream_url_parent=False,
|
|
324
|
+
mp4_stream_url=False,
|
|
325
|
+
mp4_stream_url_parent=False,
|
|
326
|
+
hidden=False,
|
|
327
|
+
mp4_status=False,
|
|
328
|
+
):
|
|
329
|
+
"""List files and their properties.
|
|
330
|
+
|
|
331
|
+
parent_id List files under a folder. If not specified, it will show files listed at the root folder
|
|
332
|
+
|
|
333
|
+
"""
|
|
334
|
+
params = {
|
|
335
|
+
"parent_id": parent_id,
|
|
336
|
+
"per_page": str(per_page),
|
|
337
|
+
"sort_by": sort_by or "",
|
|
338
|
+
"content_type": content_type or "",
|
|
339
|
+
"file_type": file_type or "",
|
|
340
|
+
"stream_url": str(stream_url),
|
|
341
|
+
"stream_url_parent": str(stream_url_parent),
|
|
342
|
+
"mp4_stream_url": str(mp4_stream_url),
|
|
343
|
+
"mp4_stream_url_parent": str(mp4_stream_url_parent),
|
|
344
|
+
"hidden": str(hidden),
|
|
345
|
+
"mp4_status": str(mp4_status),
|
|
346
|
+
}
|
|
347
|
+
d = cls.client.request("/files/list", params=params)
|
|
348
|
+
files = d["files"]
|
|
349
|
+
while d["cursor"]:
|
|
350
|
+
d = cls.client.request(
|
|
351
|
+
"/files/list/continue", method="POST", data={"cursor": d["cursor"]}
|
|
352
|
+
)
|
|
353
|
+
files.extend(d["files"])
|
|
354
|
+
|
|
355
|
+
return [cls(f) for f in files]
|
|
356
|
+
|
|
357
|
+
@classmethod
|
|
358
|
+
def upload(cls, path, name=None, parent_id=0):
|
|
359
|
+
"""If the uploaded file is a torrent file, starts it as a transfer. This endpoint must be used with upload.put.io domain.
|
|
360
|
+
name: override the file name
|
|
361
|
+
parent_id: where to put the file
|
|
362
|
+
"""
|
|
363
|
+
with io.open(path, "rb") as f:
|
|
364
|
+
if name:
|
|
365
|
+
files = {"file": (name, f)}
|
|
366
|
+
else:
|
|
367
|
+
files = {"file": f}
|
|
368
|
+
d = cls.client.request(
|
|
369
|
+
UPLOAD_URL, method="POST", data={"parent_id": parent_id}, files=files
|
|
370
|
+
)
|
|
371
|
+
|
|
372
|
+
try:
|
|
373
|
+
return cls(d["file"])
|
|
374
|
+
except KeyError:
|
|
375
|
+
# server returns a transfer info if file is a torrent
|
|
376
|
+
return cls.client.Transfer(d["transfer"])
|
|
377
|
+
|
|
378
|
+
@classmethod
|
|
379
|
+
def upload_tus(cls, path, name=None, parent_id=0):
|
|
380
|
+
headers = {"Authorization": "token %s" % cls.client.access_token}
|
|
381
|
+
metadata = {"parent_id": str(parent_id)}
|
|
382
|
+
if name:
|
|
383
|
+
metadata["name"] = name
|
|
384
|
+
else:
|
|
385
|
+
metadata["name"] = os.path.basename(path)
|
|
386
|
+
with io.open(path, "rb") as f:
|
|
387
|
+
tus.upload(
|
|
388
|
+
f, TUS_UPLOAD_URL, file_name=name, headers=headers, metadata=metadata
|
|
389
|
+
)
|
|
390
|
+
|
|
391
|
+
@classmethod
|
|
392
|
+
def search(cls, query, per_page=100):
|
|
393
|
+
"""
|
|
394
|
+
Search makes a search request with the given query
|
|
395
|
+
query: The keyword to search
|
|
396
|
+
per_page: Number of files to be returned in response.
|
|
397
|
+
"""
|
|
398
|
+
path = "/files/search"
|
|
399
|
+
result = cls.client.request(path, params={"query": query, "per_page": per_page})
|
|
400
|
+
files = result["files"]
|
|
401
|
+
return [cls(f) for f in files]
|
|
402
|
+
|
|
403
|
+
def dir(self):
|
|
404
|
+
"""List the files under directory."""
|
|
405
|
+
return self.list(parent_id=self.id)
|
|
406
|
+
|
|
407
|
+
def download(
|
|
408
|
+
self, dest=".", delete_after_download=False, chunk_size=CHUNK_SIZE, save_as=""
|
|
409
|
+
):
|
|
410
|
+
if self.content_type == "application/x-directory":
|
|
411
|
+
self._download_directory(dest, delete_after_download, chunk_size, save_as)
|
|
412
|
+
else:
|
|
413
|
+
self._download_file(dest, delete_after_download, chunk_size, save_as)
|
|
414
|
+
|
|
415
|
+
def _download_directory(self, dest, delete_after_download, chunk_size, save_as):
|
|
416
|
+
name = _str(save_as) or _str(self.name)
|
|
417
|
+
|
|
418
|
+
dest = os.path.join(dest, name)
|
|
419
|
+
if not os.path.exists(dest):
|
|
420
|
+
os.mkdir(dest)
|
|
421
|
+
|
|
422
|
+
for sub_file in self.dir():
|
|
423
|
+
sub_file.download(dest, delete_after_download, chunk_size)
|
|
424
|
+
|
|
425
|
+
if delete_after_download:
|
|
426
|
+
self.delete()
|
|
427
|
+
|
|
428
|
+
def _verify_file(self, filepath):
|
|
429
|
+
logger.info("verifying crc32...")
|
|
430
|
+
filesize = os.path.getsize(filepath)
|
|
431
|
+
if self.size != filesize:
|
|
432
|
+
logging.error(
|
|
433
|
+
"file %s is %d bytes, should be %s bytes"
|
|
434
|
+
% (filepath, filesize, self.size)
|
|
435
|
+
)
|
|
436
|
+
return False
|
|
437
|
+
|
|
438
|
+
crcbin = 0
|
|
439
|
+
with io.open(filepath, "rb") as f:
|
|
440
|
+
while True:
|
|
441
|
+
chunk = f.read(CHUNK_SIZE)
|
|
442
|
+
if not chunk:
|
|
443
|
+
break
|
|
444
|
+
|
|
445
|
+
crcbin = binascii.crc32(chunk, crcbin) & 0xFFFFFFFF
|
|
446
|
+
|
|
447
|
+
crc32 = "%08x" % crcbin
|
|
448
|
+
|
|
449
|
+
if crc32 != self.crc32:
|
|
450
|
+
logging.error(
|
|
451
|
+
"file %s CRC32 is %s, should be %s" % (filepath, crc32, self.crc32)
|
|
452
|
+
)
|
|
453
|
+
return False
|
|
454
|
+
|
|
455
|
+
logger.info("crc OK")
|
|
456
|
+
return True
|
|
457
|
+
|
|
458
|
+
def _download_file(self, dest, delete_after_download, chunk_size, save_as):
|
|
459
|
+
name = _str(save_as) or _str(self.name)
|
|
460
|
+
|
|
461
|
+
filepath = os.path.join(dest, name)
|
|
462
|
+
logger.info("downloading file to: %s", filepath)
|
|
463
|
+
if os.path.exists(filepath):
|
|
464
|
+
first_byte = os.path.getsize(filepath)
|
|
465
|
+
|
|
466
|
+
if first_byte == self.size:
|
|
467
|
+
logger.warning(
|
|
468
|
+
"file %s exists and is the correct size %d" % (filepath, self.size)
|
|
469
|
+
)
|
|
470
|
+
else:
|
|
471
|
+
first_byte = 0
|
|
472
|
+
|
|
473
|
+
logger.debug(
|
|
474
|
+
"file %s is currently %d, should be %d" % (filepath, first_byte, self.size)
|
|
475
|
+
)
|
|
476
|
+
|
|
477
|
+
if self.size == 0:
|
|
478
|
+
# Create an empty file
|
|
479
|
+
io.open(filepath, "wb").close()
|
|
480
|
+
logger.debug("created empty file %s" % filepath)
|
|
481
|
+
else:
|
|
482
|
+
if first_byte < self.size:
|
|
483
|
+
with io.open(filepath, "ab") as f:
|
|
484
|
+
headers = {"Range": "bytes=%d-" % first_byte}
|
|
485
|
+
|
|
486
|
+
logger.debug("request range: bytes=%d-" % first_byte)
|
|
487
|
+
path = "/files/%d/url" % self.id
|
|
488
|
+
response = self.client.request(path, raw=True)
|
|
489
|
+
if str(response.status_code)[0] != "2":
|
|
490
|
+
# Raises exception on 4xx and 5xx
|
|
491
|
+
_process_response(response)
|
|
492
|
+
|
|
493
|
+
download_link = str(response.json().get("url"))
|
|
494
|
+
response = self.client.request(
|
|
495
|
+
download_link, headers=headers, raw=True, stream=True
|
|
496
|
+
)
|
|
497
|
+
if str(response.status_code)[0] != "2":
|
|
498
|
+
# Raises exception on 4xx and 5xx
|
|
499
|
+
_process_response(response)
|
|
500
|
+
|
|
501
|
+
for chunk in response.iter_content(chunk_size=chunk_size):
|
|
502
|
+
if chunk: # filter out keep-alive new chunks
|
|
503
|
+
f.write(chunk)
|
|
504
|
+
|
|
505
|
+
if self._verify_file(filepath):
|
|
506
|
+
if delete_after_download:
|
|
507
|
+
self.delete()
|
|
508
|
+
|
|
509
|
+
def _get_link(self, path, params):
|
|
510
|
+
response = self.client.request(
|
|
511
|
+
path, method="HEAD", params=params, raw=True, allow_redirects=False
|
|
512
|
+
)
|
|
513
|
+
if str(response.status_code)[0] == "2":
|
|
514
|
+
return response.url
|
|
515
|
+
elif response.status_code == 302:
|
|
516
|
+
return response.headers["Location"]
|
|
517
|
+
|
|
518
|
+
# Raises exception on 4xx and 5xx
|
|
519
|
+
_process_response(response)
|
|
520
|
+
|
|
521
|
+
def get_stream_link(self, tunnel=True, prefer_mp4=False):
|
|
522
|
+
if prefer_mp4 and self.get_mp4_status()["status"] == "COMPLETED":
|
|
523
|
+
path = "/files/%d/mp4/stream" % self.id
|
|
524
|
+
else:
|
|
525
|
+
path = "/files/%d/stream" % self.id
|
|
526
|
+
|
|
527
|
+
params = {}
|
|
528
|
+
if not tunnel:
|
|
529
|
+
params["notunnel"] = "1"
|
|
530
|
+
|
|
531
|
+
return self._get_link(path, params)
|
|
532
|
+
|
|
533
|
+
def get_download_link(self):
|
|
534
|
+
path = "/files/%d/download" % self.id
|
|
535
|
+
params = {}
|
|
536
|
+
|
|
537
|
+
return self._get_link(path, params)
|
|
538
|
+
|
|
539
|
+
def convert_to_mp4(self):
|
|
540
|
+
path = "/files/%d/mp4" % self.id
|
|
541
|
+
self.client.request(path, method="POST")
|
|
542
|
+
|
|
543
|
+
def get_mp4_status(self):
|
|
544
|
+
path = "/files/%d/mp4" % self.id
|
|
545
|
+
response = self.client.request(path)
|
|
546
|
+
return response["mp4"]
|
|
547
|
+
|
|
548
|
+
def get_subtitles(cls):
|
|
549
|
+
path = "/files/%d/subtitles" % cls.id
|
|
550
|
+
response = cls.client.request(path, method="GET")
|
|
551
|
+
json_subtitles = response["subtitles"]
|
|
552
|
+
|
|
553
|
+
return [cls.client.Subtitle(s, cls.id) for s in json_subtitles]
|
|
554
|
+
|
|
555
|
+
def delete(self, skip_nonexistents=False):
|
|
556
|
+
data = {"file_id": self.id}
|
|
557
|
+
if skip_nonexistents:
|
|
558
|
+
data["skip_nonexistents"] = 1
|
|
559
|
+
return self.client.request("/files/delete", method="POST", data=data)
|
|
560
|
+
|
|
561
|
+
@classmethod
|
|
562
|
+
def delete_multi(cls, ids, skip_nonexistents=False):
|
|
563
|
+
data = {"file_ids": ",".join(map(str, ids))}
|
|
564
|
+
if skip_nonexistents:
|
|
565
|
+
data["skip_nonexistents"] = 1
|
|
566
|
+
return cls.client.request("/files/delete", method="POST", data=data)
|
|
567
|
+
|
|
568
|
+
def move(self, parent_id):
|
|
569
|
+
return self.client.request(
|
|
570
|
+
"/files/move",
|
|
571
|
+
method="POST",
|
|
572
|
+
data={"file_ids": str(self.id), "parent_id": str(parent_id)},
|
|
573
|
+
)
|
|
574
|
+
|
|
575
|
+
def rename(self, name):
|
|
576
|
+
return self.client.request(
|
|
577
|
+
"/files/rename",
|
|
578
|
+
method="POST",
|
|
579
|
+
data={"file_id": str(self.id), "name": str(name)},
|
|
580
|
+
)
|
|
581
|
+
|
|
582
|
+
@classmethod
|
|
583
|
+
def create_folder(cls, name, parent_id=0):
|
|
584
|
+
r = cls.client.request(
|
|
585
|
+
"/files/create-folder",
|
|
586
|
+
method="POST",
|
|
587
|
+
data={"name": name, "parent_id": str(parent_id)},
|
|
588
|
+
)
|
|
589
|
+
f = r["file"]
|
|
590
|
+
return cls(f)
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
class _Transfer(_BaseResource):
|
|
594
|
+
|
|
595
|
+
@classmethod
|
|
596
|
+
def list(cls):
|
|
597
|
+
"""List all transfers"""
|
|
598
|
+
|
|
599
|
+
d = cls.client.request("/transfers/list")
|
|
600
|
+
transfers = d["transfers"]
|
|
601
|
+
return [cls(t) for t in transfers]
|
|
602
|
+
|
|
603
|
+
@classmethod
|
|
604
|
+
def get(cls, id):
|
|
605
|
+
"""Get transfer details"""
|
|
606
|
+
d = cls.client.request("/transfers/%i" % id, method="GET")
|
|
607
|
+
t = d["transfer"]
|
|
608
|
+
return cls(t)
|
|
609
|
+
|
|
610
|
+
@classmethod
|
|
611
|
+
def add_url(cls, url, parent_id=0, callback_url=None):
|
|
612
|
+
"""Add new transfer from URI"""
|
|
613
|
+
|
|
614
|
+
data = {"url": url, "save_parent_id": parent_id}
|
|
615
|
+
if callback_url:
|
|
616
|
+
data["callback_url"] = callback_url
|
|
617
|
+
|
|
618
|
+
d = cls.client.request("/transfers/add", method="POST", data=data)
|
|
619
|
+
return cls(d["transfer"])
|
|
620
|
+
|
|
621
|
+
@classmethod
|
|
622
|
+
def add_torrent(cls, path, parent_id=0, callback_url=None):
|
|
623
|
+
params = {"torrent": "true"}
|
|
624
|
+
data = {"parent_id": parent_id}
|
|
625
|
+
if callback_url:
|
|
626
|
+
data["callback_url"] = callback_url
|
|
627
|
+
|
|
628
|
+
with io.open(path, "rb") as f:
|
|
629
|
+
files = {"file": f}
|
|
630
|
+
d = cls.client.request(
|
|
631
|
+
UPLOAD_URL, method="POST", params=params, data=data, files=files
|
|
632
|
+
)
|
|
633
|
+
|
|
634
|
+
return cls(d["transfer"])
|
|
635
|
+
|
|
636
|
+
@classmethod
|
|
637
|
+
def clean(cls):
|
|
638
|
+
"""Clean finished transfers"""
|
|
639
|
+
|
|
640
|
+
return cls.client.request("/transfers/clean", method="POST")
|
|
641
|
+
|
|
642
|
+
def cancel(self):
|
|
643
|
+
"""Cancel or remove transfers"""
|
|
644
|
+
|
|
645
|
+
return self.client.request(
|
|
646
|
+
"/transfers/cancel", method="POST", data={"transfer_ids": self.id}
|
|
647
|
+
)
|
|
648
|
+
|
|
649
|
+
@classmethod
|
|
650
|
+
def cancel_multi(cls, ids):
|
|
651
|
+
return cls.client.request(
|
|
652
|
+
"/transfers/cancel",
|
|
653
|
+
method="POST",
|
|
654
|
+
data={"transfer_ids": ",".join(map(str, ids))},
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
class _Account(_BaseResource):
|
|
659
|
+
|
|
660
|
+
@classmethod
|
|
661
|
+
def info(cls):
|
|
662
|
+
"""Get Account info"""
|
|
663
|
+
return cls.client.request("/account/info", method="GET")
|
|
664
|
+
|
|
665
|
+
@classmethod
|
|
666
|
+
def settings(cls):
|
|
667
|
+
"""Get account settings"""
|
|
668
|
+
return cls.client.request("/account/settings", method="GET")
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
class _Subtitle(_BaseResource):
|
|
672
|
+
|
|
673
|
+
def __init__(self, resource_dict, file_id):
|
|
674
|
+
self.__dict__.update(resource_dict)
|
|
675
|
+
self.file_id = file_id
|
|
676
|
+
|
|
677
|
+
def get_download_link(self):
|
|
678
|
+
path = "/files/%d/subtitles/%s" % (self.file_id, self.key)
|
|
679
|
+
params = {}
|
|
680
|
+
|
|
681
|
+
response = self.client.request(
|
|
682
|
+
path, method="HEAD", params=params, raw=True, allow_redirects=False
|
|
683
|
+
)
|
|
684
|
+
|
|
685
|
+
if str(response.status_code)[0] == "2":
|
|
686
|
+
return response.url
|
|
687
|
+
elif response.status_code == 302:
|
|
688
|
+
return response.headers["Location"]
|
|
689
|
+
|
|
690
|
+
def download(self, dest):
|
|
691
|
+
name = _str(self.name)
|
|
692
|
+
path = self.get_download_link()
|
|
693
|
+
|
|
694
|
+
filepath = os.path.join(dest, name)
|
|
695
|
+
logger.info("downloading subtitle file to: %s", filepath)
|
|
696
|
+
response = self.client.request(path, method="GET", raw=True)
|
|
697
|
+
with io.open(filepath, "wb") as f:
|
|
698
|
+
f.write(response.content)
|
|
699
|
+
|
|
700
|
+
return filepath
|
|
701
|
+
|
|
702
|
+
|
|
703
|
+
# Due to a nasty bug in datetime module, datetime.strptime calls
|
|
704
|
+
# are not thread-safe and can throw a TypeError. Details: https://bugs.python.org/issue7980
|
|
705
|
+
# Here we are implementing simple RFC3339 parser which is used in Put.io APIv2.
|
|
706
|
+
def strptime(date):
|
|
707
|
+
"""Returns datetime object from the given date, which is in a specific format: YYYY-MM-ddTHH:mm:ss"""
|
|
708
|
+
d = {
|
|
709
|
+
"year": date[0:4],
|
|
710
|
+
"month": date[5:7],
|
|
711
|
+
"day": date[8:10],
|
|
712
|
+
"hour": date[11:13],
|
|
713
|
+
"minute": date[14:16],
|
|
714
|
+
"second": date[17:],
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
d = dict((k, int(v)) for k, v in d.items())
|
|
718
|
+
|
|
719
|
+
return datetime(**d)
|
|
720
|
+
|
|
721
|
+
|
|
722
|
+
def _str(s):
|
|
723
|
+
"""Python 3 compatibility function for converting to str."""
|
|
724
|
+
try:
|
|
725
|
+
if isinstance(s, unicode):
|
|
726
|
+
return s.encode("utf-8", "replace")
|
|
727
|
+
except NameError:
|
|
728
|
+
pass
|
|
729
|
+
return s
|