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