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