-
Notifications
You must be signed in to change notification settings - Fork 4
/
redtube.py
228 lines (185 loc) · 6.51 KB
/
redtube.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
from urllib2 import urlopen, Request, URLError
from sys import version_info, argv
from optparse import OptionParser
from datetime import datetime
from urllib import urlencode
from base64 import b64decode
from weakref import ref
from json import loads
from copy import copy
from math import pow
__version__ = '0.5.0'
class RedException(Exception):
pass
class RedVideo(object):
def __init__(self, client, kwargs):
self.id = kwargs['video_id']
self.title = kwargs['title']
self.url = kwargs['url']
self.thumbnail_url = kwargs['thumb']
self.published = \
datetime.strptime(kwargs['publish_date'], '%Y-%m-%d %H:%M:%S') \
if kwargs['publish_date'] else None
self.timing = kwargs['duration']
self.duration = int(sum(map(
lambda x: x[1] * pow(60, x[0]),
enumerate(map(int, self.timing.split(':')[::-1]))
)))
self.tags = [
entry if isinstance(entry, basestring) else entry['tag_name']
for entry in kwargs.get('tags', [])
]
self.stars = [
entry if isinstance(entry, basestring) else entry['star_name']
for entry in kwargs.get('stars', [])
]
self.thumbnails = {}
for entry in kwargs.get('thumbs', []):
if entry['size'] not in self.thumbnails:
self.thumbnails[entry['size']] = {
'dimensions': (entry['width'], entry['height']),
'thumbnails': [],
}
self.thumbnails[entry['size']]['thumbnails'].append(entry['src'])
self._client = ref(client)
self._active = None
self._code = None
def __repr__(self):
return '<%s[%s] "%s">' % (self.__class__.__name__, self.id, self.title)
@property
def client(self):
if self._client() is None:
return RedClient()
return self._client()
@property
def active(self):
if self._active is None:
self._active = bool(self.client._request(
'redtube.Videos.isVideoActive', video_id=self.id
)['active']['is_active'])
return self._active
@property
def embed(self):
if not self._code:
self._code = b64decode(self.client._request(
'redtube.Videos.getVideoEmbedCode', video_id=self.id
)['embed']['code'])
return self._code
@property
def player_url(self):
return 'http://embed.redtube.com/player/?id=%s' % self.id
class RedCollection(list):
def __init__(self, client, data):
self._client = ref(client)
json = self.client._request('redtube.Videos.searchVideos', **data)
super(RedCollection, self).__init__(
RedVideo(client, entry['video']) for entry in json['videos']
)
self.query = data
self.total = json['count']
self.page = self.query.get('page', 1)
@property
def client(self):
if self._client() is None:
return RedClient()
return self._client()
def next(self):
if len(self) * (self.start + 1) > self.total:
return None
data = copy(self.query)
data['page'] = data.get('page', 1) + 1
return self.__class__(self.client, data)
class RedClient(object):
''' Python RedTube API Client '''
server = 'http://api.redtube.com/'
thumbnail_sizes = ['all', 'small', 'medium', 'medium1', 'medium2', 'big']
def __init__(self):
self._categories = []
self._tags = []
self._stars = []
def _request(self, data, **kwargs):
kwargs.update({'output': 'json', 'data': data})
url = '%s?%s' % (self.server, urlencode(kwargs))
request = Request(str(url), headers={
'User-Agent': 'RedTubeClient/%s (Python/%s)' % (
__version__, '.'.join(map(str, version_info[:-2]))
)
})
try:
response = urlopen(request).read()
return loads(response)
except URLError as e:
raise RedException(str(e))
def search(
self, query=None, category=None, tags=[],
stars=[], thumbnail_size=None, page=1):
if thumbnail_size not in self.thumbnail_sizes:
thumbnail_size = None
if page < 1:
page = 1
data = {'page': int(page)}
if query:
data['search'] = query
if category:
data['category'] = category
if tags:
data['tags[]'] = tags
if stars:
data['stars[]'] = stars
if thumbnail_size:
data['thumbsize'] = thumbnail_size
return RedCollection(self, data)
def by_id(self, id, thumbnail_size=None):
if thumbnail_size not in self.thumbnail_sizes:
thumbnail_size = None
data = {'video_id': id}
if thumbnail_size:
data['thumbsize'] = thumbnail_size
try:
return RedVideo(self, self._request(
'redtube.Videos.getVideoById', **data
)['video'])
except KeyError:
return None
def __getitem__(self, id):
return self.by_id(id)
@property
def categories(self):
if not self._categories:
self._categories = [
entry['category'] for entry in
self._request(
'redtube.Categories.getCategoriesList'
)['categories']
]
return self._categories
@property
def tags(self):
if not self._tags:
self._tags = [
entry['tag']['tag_name'] for entry in
self._request('redtube.Tags.getTagList')['tags']
]
return self._tags
@property
def stars(self):
if not self._stars:
self._stars = [
entry['star']['star_name'] for entry in
self._request('redtube.Stars.getStarList')['stars']
]
return self._stars
def main(args=argv[1:]):
parser = OptionParser(version=__version__, description=RedClient.__doc__)
parser.add_option(
'-q', '--query', dest="query", help='Query string', metavar='QRY'
)
parser.add_option(
'-t', '--tag', dest='tags', action="append", default=[],
help='Tags to search', metavar='TAG'
)
options = parser.parse_args(args)[0]
for video in RedClient().search(query=options.query, tags=options.tags):
print '[%s] %s: %s' % (video.timing, video.title, video.url)
if __name__ == '__main__':
main(argv[1:])