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