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