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