]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/smotri.py
Merge tag 'upstream/2014.11.21'
[youtubedl] / youtube_dl / extractor / smotri.py
1 # encoding: utf-8
2 from __future__ import unicode_literals
3
4 import os.path
5 import re
6 import json
7 import hashlib
8 import uuid
9
10 from .common import InfoExtractor
11 from ..utils import (
12 compat_urllib_parse,
13 compat_urllib_request,
14 ExtractorError,
15 url_basename,
16 int_or_none,
17 )
18
19
20 class SmotriIE(InfoExtractor):
21 IE_DESC = 'Smotri.com'
22 IE_NAME = 'smotri'
23 _VALID_URL = r'^https?://(?:www\.)?(?:smotri\.com/video/view/\?id=|pics\.smotri\.com/(?:player|scrubber_custom8)\.swf\?file=)(?P<videoid>v(?P<realvideoid>[0-9]+)[a-z0-9]{4})'
24 _NETRC_MACHINE = 'smotri'
25
26 _TESTS = [
27 # real video id 2610366
28 {
29 'url': 'http://smotri.com/video/view/?id=v261036632ab',
30 'md5': '2a7b08249e6f5636557579c368040eb9',
31 'info_dict': {
32 'id': 'v261036632ab',
33 'ext': 'mp4',
34 'title': 'катастрофа с камер видеонаблюдения',
35 'uploader': 'rbc2008',
36 'uploader_id': 'rbc08',
37 'upload_date': '20131118',
38 'description': 'катастрофа с камер видеонаблюдения, видео катастрофа с камер видеонаблюдения',
39 'thumbnail': 'http://frame6.loadup.ru/8b/a9/2610366.3.3.jpg',
40 },
41 },
42 # real video id 57591
43 {
44 'url': 'http://smotri.com/video/view/?id=v57591cb20',
45 'md5': '830266dfc21f077eac5afd1883091bcd',
46 'info_dict': {
47 'id': 'v57591cb20',
48 'ext': 'flv',
49 'title': 'test',
50 'uploader': 'Support Photofile@photofile',
51 'uploader_id': 'support-photofile',
52 'upload_date': '20070704',
53 'description': 'test, видео test',
54 'thumbnail': 'http://frame4.loadup.ru/03/ed/57591.2.3.jpg',
55 },
56 },
57 # video-password
58 {
59 'url': 'http://smotri.com/video/view/?id=v1390466a13c',
60 'md5': 'f6331cef33cad65a0815ee482a54440b',
61 'info_dict': {
62 'id': 'v1390466a13c',
63 'ext': 'mp4',
64 'title': 'TOCCA_A_NOI_-_LE_COSE_NON_VANNO_CAMBIAMOLE_ORA-1',
65 'uploader': 'timoxa40',
66 'uploader_id': 'timoxa40',
67 'upload_date': '20100404',
68 'thumbnail': 'http://frame7.loadup.ru/af/3f/1390466.3.3.jpg',
69 'description': 'TOCCA_A_NOI_-_LE_COSE_NON_VANNO_CAMBIAMOLE_ORA-1, видео TOCCA_A_NOI_-_LE_COSE_NON_VANNO_CAMBIAMOLE_ORA-1',
70 },
71 'params': {
72 'videopassword': 'qwerty',
73 },
74 },
75 # age limit + video-password
76 {
77 'url': 'http://smotri.com/video/view/?id=v15408898bcf',
78 'md5': '91e909c9f0521adf5ee86fbe073aad70',
79 'info_dict': {
80 'id': 'v15408898bcf',
81 'ext': 'flv',
82 'title': 'этот ролик не покажут по ТВ',
83 'uploader': 'zzxxx',
84 'uploader_id': 'ueggb',
85 'upload_date': '20101001',
86 'thumbnail': 'http://frame3.loadup.ru/75/75/1540889.1.3.jpg',
87 'age_limit': 18,
88 'description': 'этот ролик не покажут по ТВ, видео этот ролик не покажут по ТВ',
89 },
90 'params': {
91 'videopassword': '333'
92 }
93 },
94 # swf player
95 {
96 'url': 'http://pics.smotri.com/scrubber_custom8.swf?file=v9188090500',
97 'md5': '4d47034979d9390d14acdf59c4935bc2',
98 'info_dict': {
99 'id': 'v9188090500',
100 'ext': 'mp4',
101 'title': 'Shakira - Don\'t Bother',
102 'uploader': 'HannahL',
103 'uploader_id': 'lisaha95',
104 'upload_date': '20090331',
105 'description': 'Shakira - Don\'t Bother, видео Shakira - Don\'t Bother',
106 'thumbnail': 'http://frame8.loadup.ru/44/0b/918809.7.3.jpg',
107 },
108 },
109 ]
110
111 _SUCCESS = 0
112 _PASSWORD_NOT_VERIFIED = 1
113 _PASSWORD_DETECTED = 2
114 _VIDEO_NOT_FOUND = 3
115
116 @classmethod
117 def _extract_url(cls, webpage):
118 mobj = re.search(
119 r'<embed[^>]src=(["\'])(?P<url>http://pics\.smotri\.com/(?:player|scrubber_custom8)\.swf\?file=v.+?\1)',
120 webpage)
121 if mobj is not None:
122 return mobj.group('url')
123
124 mobj = re.search(
125 r'''(?x)<div\s+class="video_file">http://smotri\.com/video/download/file/[^<]+</div>\s*
126 <div\s+class="video_image">[^<]+</div>\s*
127 <div\s+class="video_id">(?P<id>[^<]+)</div>''', webpage)
128 if mobj is not None:
129 return 'http://smotri.com/video/view/?id=%s' % mobj.group('id')
130
131 def _search_meta(self, name, html, display_name=None):
132 if display_name is None:
133 display_name = name
134 return self._html_search_regex(
135 r'<meta itemprop="%s" content="([^"]+)" />' % re.escape(name),
136 html, display_name, fatal=False)
137 return self._html_search_meta(name, html, display_name)
138
139 def _real_extract(self, url):
140 mobj = re.match(self._VALID_URL, url)
141 video_id = mobj.group('videoid')
142 real_video_id = mobj.group('realvideoid')
143
144 # Download video JSON data
145 video_json_url = 'http://smotri.com/vt.php?id=%s' % real_video_id
146 video_json_page = self._download_webpage(video_json_url, video_id, 'Downloading video JSON')
147 video_json = json.loads(video_json_page)
148
149 status = video_json['status']
150 if status == self._VIDEO_NOT_FOUND:
151 raise ExtractorError('Video %s does not exist' % video_id, expected=True)
152 elif status == self._PASSWORD_DETECTED: # The video is protected by a password, retry with
153 # video-password set
154 video_password = self._downloader.params.get('videopassword', None)
155 if not video_password:
156 raise ExtractorError('This video is protected by a password, use the --video-password option', expected=True)
157 video_json_url += '&md5pass=%s' % hashlib.md5(video_password.encode('utf-8')).hexdigest()
158 video_json_page = self._download_webpage(video_json_url, video_id, 'Downloading video JSON (video-password set)')
159 video_json = json.loads(video_json_page)
160 status = video_json['status']
161 if status == self._PASSWORD_NOT_VERIFIED:
162 raise ExtractorError('Video password is invalid', expected=True)
163
164 if status != self._SUCCESS:
165 raise ExtractorError('Unexpected status value %s' % status)
166
167 # Extract the URL of the video
168 video_url = video_json['file_data']
169
170 # Video JSON does not provide enough meta data
171 # We will extract some from the video web page instead
172 video_page_url = 'http://smotri.com/video/view/?id=%s' % video_id
173 video_page = self._download_webpage(video_page_url, video_id, 'Downloading video page')
174
175 # Warning if video is unavailable
176 warning = self._html_search_regex(
177 r'<div class="videoUnModer">(.*?)</div>', video_page,
178 'warning message', default=None)
179 if warning is not None:
180 self._downloader.report_warning(
181 'Video %s may not be available; smotri said: %s ' %
182 (video_id, warning))
183
184 # Adult content
185 if re.search('EroConfirmText">', video_page) is not None:
186 self.report_age_confirmation()
187 confirm_string = self._html_search_regex(
188 r'<a href="/video/view/\?id=%s&confirm=([^"]+)" title="[^"]+">' % video_id,
189 video_page, 'confirm string')
190 confirm_url = video_page_url + '&confirm=%s' % confirm_string
191 video_page = self._download_webpage(confirm_url, video_id, 'Downloading video page (age confirmed)')
192 adult_content = True
193 else:
194 adult_content = False
195
196 # Extract the rest of meta data
197 video_title = self._search_meta('name', video_page, 'title')
198 if not video_title:
199 video_title = os.path.splitext(url_basename(video_url))[0]
200
201 video_description = self._search_meta('description', video_page)
202 END_TEXT = ' на сайте Smotri.com'
203 if video_description and video_description.endswith(END_TEXT):
204 video_description = video_description[:-len(END_TEXT)]
205 START_TEXT = 'Смотреть онлайн ролик '
206 if video_description and video_description.startswith(START_TEXT):
207 video_description = video_description[len(START_TEXT):]
208 video_thumbnail = self._search_meta('thumbnail', video_page)
209
210 upload_date_str = self._search_meta('uploadDate', video_page, 'upload date')
211 if upload_date_str:
212 upload_date_m = re.search(r'(?P<year>\d{4})\.(?P<month>\d{2})\.(?P<day>\d{2})T', upload_date_str)
213 video_upload_date = (
214 (
215 upload_date_m.group('year') +
216 upload_date_m.group('month') +
217 upload_date_m.group('day')
218 )
219 if upload_date_m else None
220 )
221 else:
222 video_upload_date = None
223
224 duration_str = self._search_meta('duration', video_page)
225 if duration_str:
226 duration_m = re.search(r'T(?P<hours>[0-9]{2})H(?P<minutes>[0-9]{2})M(?P<seconds>[0-9]{2})S', duration_str)
227 video_duration = (
228 (
229 (int(duration_m.group('hours')) * 60 * 60) +
230 (int(duration_m.group('minutes')) * 60) +
231 int(duration_m.group('seconds'))
232 )
233 if duration_m else None
234 )
235 else:
236 video_duration = None
237
238 video_uploader = self._html_search_regex(
239 '<div class="DescrUser"><div>Автор.*?onmouseover="popup_user_info[^"]+">(.*?)</a>',
240 video_page, 'uploader', fatal=False, flags=re.MULTILINE|re.DOTALL)
241
242 video_uploader_id = self._html_search_regex(
243 '<div class="DescrUser"><div>Автор.*?onmouseover="popup_user_info\\(.*?\'([^\']+)\'\\);">',
244 video_page, 'uploader id', fatal=False, flags=re.MULTILINE|re.DOTALL)
245
246 video_view_count = self._html_search_regex(
247 'Общее количество просмотров.*?<span class="Number">(\\d+)</span>',
248 video_page, 'view count', fatal=False, flags=re.MULTILINE|re.DOTALL)
249
250 return {
251 'id': video_id,
252 'url': video_url,
253 'title': video_title,
254 'thumbnail': video_thumbnail,
255 'description': video_description,
256 'uploader': video_uploader,
257 'upload_date': video_upload_date,
258 'uploader_id': video_uploader_id,
259 'duration': video_duration,
260 'view_count': int_or_none(video_view_count),
261 'age_limit': 18 if adult_content else 0,
262 'video_page_url': video_page_url
263 }
264
265
266 class SmotriCommunityIE(InfoExtractor):
267 IE_DESC = 'Smotri.com community videos'
268 IE_NAME = 'smotri:community'
269 _VALID_URL = r'^https?://(?:www\.)?smotri\.com/community/video/(?P<communityid>[0-9A-Za-z_\'-]+)'
270 _TEST = {
271 'url': 'http://smotri.com/community/video/kommuna',
272 'info_dict': {
273 'id': 'kommuna',
274 'title': 'КПРФ',
275 },
276 'playlist_mincount': 4,
277 }
278
279 def _real_extract(self, url):
280 mobj = re.match(self._VALID_URL, url)
281 community_id = mobj.group('communityid')
282
283 url = 'http://smotri.com/export/rss/video/by/community/-/%s/video.xml' % community_id
284 rss = self._download_xml(url, community_id, 'Downloading community RSS')
285
286 entries = [self.url_result(video_url.text, 'Smotri')
287 for video_url in rss.findall('./channel/item/link')]
288
289 description_text = rss.find('./channel/description').text
290 community_title = self._html_search_regex(
291 '^Видео сообщества "([^"]+)"$', description_text, 'community title')
292
293 return self.playlist_result(entries, community_id, community_title)
294
295
296 class SmotriUserIE(InfoExtractor):
297 IE_DESC = 'Smotri.com user videos'
298 IE_NAME = 'smotri:user'
299 _VALID_URL = r'^https?://(?:www\.)?smotri\.com/user/(?P<userid>[0-9A-Za-z_\'-]+)'
300 _TESTS = [{
301 'url': 'http://smotri.com/user/inspector',
302 'info_dict': {
303 'id': 'inspector',
304 'title': 'Inspector',
305 },
306 'playlist_mincount': 9,
307 }]
308
309 def _real_extract(self, url):
310 mobj = re.match(self._VALID_URL, url)
311 user_id = mobj.group('userid')
312
313 url = 'http://smotri.com/export/rss/user/video/-/%s/video.xml' % user_id
314 rss = self._download_xml(url, user_id, 'Downloading user RSS')
315
316 entries = [self.url_result(video_url.text, 'Smotri')
317 for video_url in rss.findall('./channel/item/link')]
318
319 description_text = rss.find('./channel/description').text
320 user_nickname = self._html_search_regex(
321 '^Видео режиссера (.*)$', description_text,
322 'user nickname')
323
324 return self.playlist_result(entries, user_id, user_nickname)
325
326
327 class SmotriBroadcastIE(InfoExtractor):
328 IE_DESC = 'Smotri.com broadcasts'
329 IE_NAME = 'smotri:broadcast'
330 _VALID_URL = r'^https?://(?:www\.)?(?P<url>smotri\.com/live/(?P<broadcastid>[^/]+))/?.*'
331
332 def _real_extract(self, url):
333 mobj = re.match(self._VALID_URL, url)
334 broadcast_id = mobj.group('broadcastid')
335
336 broadcast_url = 'http://' + mobj.group('url')
337 broadcast_page = self._download_webpage(broadcast_url, broadcast_id, 'Downloading broadcast page')
338
339 if re.search('>Режиссер с логином <br/>"%s"<br/> <span>не существует<' % broadcast_id, broadcast_page) is not None:
340 raise ExtractorError('Broadcast %s does not exist' % broadcast_id, expected=True)
341
342 # Adult content
343 if re.search('EroConfirmText">', broadcast_page) is not None:
344
345 (username, password) = self._get_login_info()
346 if username is None:
347 raise ExtractorError('Erotic broadcasts allowed only for registered users, '
348 'use --username and --password options to provide account credentials.', expected=True)
349
350 login_form = {
351 'login-hint53': '1',
352 'confirm_erotic': '1',
353 'login': username,
354 'password': password,
355 }
356
357 request = compat_urllib_request.Request(broadcast_url + '/?no_redirect=1', compat_urllib_parse.urlencode(login_form))
358 request.add_header('Content-Type', 'application/x-www-form-urlencoded')
359 broadcast_page = self._download_webpage(request, broadcast_id, 'Logging in and confirming age')
360
361 if re.search('>Неверный логин или пароль<', broadcast_page) is not None:
362 raise ExtractorError('Unable to log in: bad username or password', expected=True)
363
364 adult_content = True
365 else:
366 adult_content = False
367
368 ticket = self._html_search_regex(
369 'window\.broadcast_control\.addFlashVar\\(\'file\', \'([^\']+)\'\\);',
370 broadcast_page, 'broadcast ticket')
371
372 url = 'http://smotri.com/broadcast/view/url/?ticket=%s' % ticket
373
374 broadcast_password = self._downloader.params.get('videopassword', None)
375 if broadcast_password:
376 url += '&pass=%s' % hashlib.md5(broadcast_password.encode('utf-8')).hexdigest()
377
378 broadcast_json_page = self._download_webpage(url, broadcast_id, 'Downloading broadcast JSON')
379
380 try:
381 broadcast_json = json.loads(broadcast_json_page)
382
383 protected_broadcast = broadcast_json['_pass_protected'] == 1
384 if protected_broadcast and not broadcast_password:
385 raise ExtractorError('This broadcast is protected by a password, use the --video-password option', expected=True)
386
387 broadcast_offline = broadcast_json['is_play'] == 0
388 if broadcast_offline:
389 raise ExtractorError('Broadcast %s is offline' % broadcast_id, expected=True)
390
391 rtmp_url = broadcast_json['_server']
392 if not rtmp_url.startswith('rtmp://'):
393 raise ExtractorError('Unexpected broadcast rtmp URL')
394
395 broadcast_playpath = broadcast_json['_streamName']
396 broadcast_thumbnail = broadcast_json['_imgURL']
397 broadcast_title = broadcast_json['title']
398 broadcast_description = broadcast_json['description']
399 broadcaster_nick = broadcast_json['nick']
400 broadcaster_login = broadcast_json['login']
401 rtmp_conn = 'S:%s' % uuid.uuid4().hex
402 except KeyError:
403 if protected_broadcast:
404 raise ExtractorError('Bad broadcast password', expected=True)
405 raise ExtractorError('Unexpected broadcast JSON')
406
407 return {
408 'id': broadcast_id,
409 'url': rtmp_url,
410 'title': broadcast_title,
411 'thumbnail': broadcast_thumbnail,
412 'description': broadcast_description,
413 'uploader': broadcaster_nick,
414 'uploader_id': broadcaster_login,
415 'age_limit': 18 if adult_content else 0,
416 'ext': 'flv',
417 'play_path': broadcast_playpath,
418 'rtmp_live': True,
419 'rtmp_conn': rtmp_conn
420 }