-
Notifications
You must be signed in to change notification settings - Fork 0
/
putio2.py
248 lines (188 loc) · 7.15 KB
/
putio2.py
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# -*- coding: utf-8 -*-
"""
A python wrapper for put.io APIv2
https://github.com/putdotio/putio-apiv2-python
Documentation: See https://api.put.io/v2/docs
Usage:
import putio2
client = putio2.Client('..oauth token here...')
# list files
files = client.File.list()
...
# add a new transfer
client.Transfer.add('http://example.com/good.torrent')
"""
import os
import re
import json
import logging
from urllib import urlencode
import requests
import iso8601
logger = logging.getLogger(__name__)
API_URL = 'https://api.put.io/v2'
ACCESS_TOKEN_URL = 'https://api.put.io/v2/oauth2/access_token'
AUTHENTICATION_URL = 'https://api.put.io/v2/oauth2/authenticate'
class PutioError(Exception):
pass
class AuthHelper(object):
def __init__(self, client_id, client_secret, redirect_uri):
self.client_id = client_id
self.client_secret = client_secret
self.callback_url = redirect_uri
def get_authentication_url(self):
params = {
'client_id': self.client_id,
'response_type': 'code',
'redirect_uri': self.callback_url
}
query_str = urlencode(query)
return AUTHENTICATION_URL + "?" + query_str
def get_access_token(self, code):
params = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'grant_type': 'authorization_code',
'redirect_uri': self.callback_url,
'code': code
}
r = requests.get(ACCESS_TOKEN_URL, params=params)
d = json.loads(r.content)
return d['access_token']
class Client(object):
def __init__(self, access_token):
self.access_token = access_token
# Keep resource classes as attributes of client.
# Pass client to resource classes so resource object
# can use the client.
attributes = {'client': self}
self.File = type('File', (_File,), attributes)
self.Transfer = type('Transfer', (_Transfer,), attributes)
self.Account = type('Account', (_Account,), attributes)
def request(self, path, method='GET', params=None, data=None, files=None, headers=None, raw=False, allow_redirects=True):
'''
Wrapper around requests.request()
Prepends API_URL to path.
Inserts oauth_token to query params.
Parses response as JSON and returns it.
'''
if not params:
params = {}
params['oauth_token'] = self.access_token
url = API_URL + path
logger.debug('url: %s', url)
r = requests.request(method, url, params=params, data=data, files=files, headers=headers, allow_redirects=allow_redirects)
logger.debug('response: %s', r)
if raw:
return r
logger.debug('content: %s', r.content)
try:
r = json.loads(r.content)
except ValueError:
raise PutioError('Server didn\'t send valid JSON:\n%s\n%s' % (r, r.content))
if not 'status' in r or r['status'] == 'ERROR':
raise PutioError(r.get('error_type') or r.get('error_description'))
return r
class _BaseResource(object):
def __init__(self, resource_dict):
'''Construct the object from a dict'''
self.__dict__.update(resource_dict)
try:
self.created_at = iso8601.parse_date(self.created_at)
except:
pass
def __str__(self):
return self.name.encode('utf-8')
def __repr__(self):
try:
# shorten name for display
name = self.name[:17] + '...' if len(self.name) > 20 else self.name
return '%s(id=%s, name="%s")' % (self.__class__.__name__, self.id, str(self))
except:
return object.__repr__()
class _File(_BaseResource):
@classmethod
def list(cls, parent_id=0, as_dict=False):
d = cls.client.request('/files/list', params={'parent_id': parent_id})
files = d['files']
files = [cls(f) for f in files]
if as_dict:
ids = [f.id for f in files]
return dict(zip(ids, files))
return files
@classmethod
def upload(cls, path, name):
f = open(path)
files = {'file': (name, f)}
d = cls.client.request('/files/upload', method='POST', files=files)
f.close()
f = d['file']
return cls(f)
@classmethod
def create_folder(cls, name, parent_id=0):
data = {'name': name, 'parent_id': parent_id}
return cls.client.request('/files/create-folder', 'POST', data=data)
@property
def files(self):
'''Helper function for listing inside of directory'''
return self.list(parent_id=self.id)
@property
def download_url(self):
if not hasattr(self, '_download_url'):
r = self.client.request('/files/%s/download' % self.id, raw=True, allow_redirects=False)
self._download_url = r.headers['Location']
return self._download_url
def download(self, dest='.', range=None):
if range:
headers = {'Range': 'bytes=%s-%s' % range}
else:
headers = None
r = self.client.request('/files/%s/download' % self.id, raw=True, headers=headers)
if range:
return r.content
filename = re.match('attachment; filename\="(.*)"', r.headers['Content-Disposition']).groups()[0]
with open(os.path.join(dest, filename), 'wb') as f:
for data in r.iter_content():
f.write(data)
def delete(self):
data = {'file_ids': self.id}
return self.client.request('/files/delete', 'POST', data=data)
def move(self, parent_id):
data = {'file_ids': self.id, 'parent_id': parent_id}
return self.client.request('/files/move', 'POST', data=data)
@classmethod
def get(cls, id):
d = cls.client.request('/files/%i' % id, method='GET')
t = d['file']
return cls(t)
class _Transfer(_BaseResource):
@classmethod
def list(cls, parent_id=0, as_dict=False):
d = cls.client.request('/transfers/list')
transfers = d['transfers']
transfers = [cls(t) for t in transfers]
if as_dict:
ids = [t.id for t in transfers]
return dict(zip(ids, transfers))
return transfers
@classmethod
def add(cls, url, parent_id=0, extract=False, callback_url=None):
d = cls.client.request('/transfers/add', method='POST', data=dict(
url=url, parent_id=parent_id, extract=extract,
callback_url=callback_url))
t = d['transfer']
return cls(t)
@classmethod
def get(cls, id):
d = cls.client.request('/transfers/%i' % id, method='GET')
t = d['transfer']
return cls(t)
class _Account(_BaseResource):
@classmethod
def info(cls):
d = cls.client.request('/account/info')
return cls(d['info'])
@classmethod
def settings(cls):
d = cls.client.request('/account/settings')
return cls(d['settings'])