]> Raphaël G. Git Repositories - youtubedl/blob - youtube_dl/extractor/rutube.py
Start new release and annotate with bugs being fixed.
[youtubedl] / youtube_dl / extractor / rutube.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import itertools
6
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_str,
10 compat_parse_qs,
11 compat_urllib_parse_urlparse,
12 )
13 from ..utils import (
14 determine_ext,
15 bool_or_none,
16 int_or_none,
17 try_get,
18 unified_timestamp,
19 url_or_none,
20 )
21
22
23 class RutubeBaseIE(InfoExtractor):
24 def _extract_video(self, video, video_id=None, require_title=True):
25 title = video['title'] if require_title else video.get('title')
26
27 age_limit = video.get('is_adult')
28 if age_limit is not None:
29 age_limit = 18 if age_limit is True else 0
30
31 uploader_id = try_get(video, lambda x: x['author']['id'])
32 category = try_get(video, lambda x: x['category']['name'])
33
34 return {
35 'id': video.get('id') or video_id,
36 'title': title,
37 'description': video.get('description'),
38 'thumbnail': video.get('thumbnail_url'),
39 'duration': int_or_none(video.get('duration')),
40 'uploader': try_get(video, lambda x: x['author']['name']),
41 'uploader_id': compat_str(uploader_id) if uploader_id else None,
42 'timestamp': unified_timestamp(video.get('created_ts')),
43 'category': [category] if category else None,
44 'age_limit': age_limit,
45 'view_count': int_or_none(video.get('hits')),
46 'comment_count': int_or_none(video.get('comments_count')),
47 'is_live': bool_or_none(video.get('is_livestream')),
48 }
49
50
51 class RutubeIE(RutubeBaseIE):
52 IE_NAME = 'rutube'
53 IE_DESC = 'Rutube videos'
54 _VALID_URL = r'https?://rutube\.ru/(?:video|(?:play/)?embed)/(?P<id>[\da-z]{32})'
55
56 _TESTS = [{
57 'url': 'http://rutube.ru/video/3eac3b4561676c17df9132a9a1e62e3e/',
58 'md5': '79938ade01294ef7e27574890d0d3769',
59 'info_dict': {
60 'id': '3eac3b4561676c17df9132a9a1e62e3e',
61 'ext': 'flv',
62 'title': 'Раненный кенгуру забежал в аптеку',
63 'description': 'http://www.ntdtv.ru ',
64 'duration': 80,
65 'uploader': 'NTDRussian',
66 'uploader_id': '29790',
67 'timestamp': 1381943602,
68 'upload_date': '20131016',
69 'age_limit': 0,
70 },
71 }, {
72 'url': 'http://rutube.ru/play/embed/a10e53b86e8f349080f718582ce4c661',
73 'only_matching': True,
74 }, {
75 'url': 'http://rutube.ru/embed/a10e53b86e8f349080f718582ce4c661',
76 'only_matching': True,
77 }, {
78 'url': 'http://rutube.ru/video/3eac3b4561676c17df9132a9a1e62e3e/?pl_id=4252',
79 'only_matching': True,
80 }, {
81 'url': 'https://rutube.ru/video/10b3a03fc01d5bbcc632a2f3514e8aab/?pl_type=source',
82 'only_matching': True,
83 }]
84
85 @classmethod
86 def suitable(cls, url):
87 return False if RutubePlaylistIE.suitable(url) else super(RutubeIE, cls).suitable(url)
88
89 @staticmethod
90 def _extract_urls(webpage):
91 return [mobj.group('url') for mobj in re.finditer(
92 r'<iframe[^>]+?src=(["\'])(?P<url>(?:https?:)?//rutube\.ru/embed/[\da-z]{32}.*?)\1',
93 webpage)]
94
95 def _real_extract(self, url):
96 video_id = self._match_id(url)
97
98 video = self._download_json(
99 'http://rutube.ru/api/video/%s/?format=json' % video_id,
100 video_id, 'Downloading video JSON')
101
102 info = self._extract_video(video, video_id)
103
104 options = self._download_json(
105 'http://rutube.ru/api/play/options/%s/?format=json' % video_id,
106 video_id, 'Downloading options JSON')
107
108 formats = []
109 for format_id, format_url in options['video_balancer'].items():
110 ext = determine_ext(format_url)
111 if ext == 'm3u8':
112 formats.extend(self._extract_m3u8_formats(
113 format_url, video_id, 'mp4', m3u8_id=format_id, fatal=False))
114 elif ext == 'f4m':
115 formats.extend(self._extract_f4m_formats(
116 format_url, video_id, f4m_id=format_id, fatal=False))
117 else:
118 formats.append({
119 'url': format_url,
120 'format_id': format_id,
121 })
122 self._sort_formats(formats)
123
124 info['formats'] = formats
125 return info
126
127
128 class RutubeEmbedIE(InfoExtractor):
129 IE_NAME = 'rutube:embed'
130 IE_DESC = 'Rutube embedded videos'
131 _VALID_URL = r'https?://rutube\.ru/(?:video|play)/embed/(?P<id>[0-9]+)'
132
133 _TESTS = [{
134 'url': 'http://rutube.ru/video/embed/6722881?vk_puid37=&vk_puid38=',
135 'info_dict': {
136 'id': 'a10e53b86e8f349080f718582ce4c661',
137 'ext': 'flv',
138 'timestamp': 1387830582,
139 'upload_date': '20131223',
140 'uploader_id': '297833',
141 'description': 'Видео группы ★http://vk.com/foxkidsreset★ музей Fox Kids и Jetix<br/><br/> восстановлено и сделано в шикоформате subziro89 http://vk.com/subziro89',
142 'uploader': 'subziro89 ILya',
143 'title': 'Мистический городок Эйри в Индиан 5 серия озвучка subziro89',
144 },
145 'params': {
146 'skip_download': True,
147 },
148 }, {
149 'url': 'http://rutube.ru/play/embed/8083783',
150 'only_matching': True,
151 }]
152
153 def _real_extract(self, url):
154 embed_id = self._match_id(url)
155 webpage = self._download_webpage(url, embed_id)
156
157 canonical_url = self._html_search_regex(
158 r'<link\s+rel="canonical"\s+href="([^"]+?)"', webpage,
159 'Canonical URL')
160 return self.url_result(canonical_url, RutubeIE.ie_key())
161
162
163 class RutubePlaylistBaseIE(RutubeBaseIE):
164 def _next_page_url(self, page_num, playlist_id, *args, **kwargs):
165 return self._PAGE_TEMPLATE % (playlist_id, page_num)
166
167 def _entries(self, playlist_id, *args, **kwargs):
168 next_page_url = None
169 for pagenum in itertools.count(1):
170 page = self._download_json(
171 next_page_url or self._next_page_url(
172 pagenum, playlist_id, *args, **kwargs),
173 playlist_id, 'Downloading page %s' % pagenum)
174
175 results = page.get('results')
176 if not results or not isinstance(results, list):
177 break
178
179 for result in results:
180 video_url = url_or_none(result.get('video_url'))
181 if not video_url:
182 continue
183 entry = self._extract_video(result, require_title=False)
184 entry.update({
185 '_type': 'url',
186 'url': video_url,
187 'ie_key': RutubeIE.ie_key(),
188 })
189 yield entry
190
191 next_page_url = page.get('next')
192 if not next_page_url or not page.get('has_next'):
193 break
194
195 def _extract_playlist(self, playlist_id, *args, **kwargs):
196 return self.playlist_result(
197 self._entries(playlist_id, *args, **kwargs),
198 playlist_id, kwargs.get('playlist_name'))
199
200 def _real_extract(self, url):
201 return self._extract_playlist(self._match_id(url))
202
203
204 class RutubeChannelIE(RutubePlaylistBaseIE):
205 IE_NAME = 'rutube:channel'
206 IE_DESC = 'Rutube channels'
207 _VALID_URL = r'https?://rutube\.ru/tags/video/(?P<id>\d+)'
208 _TESTS = [{
209 'url': 'http://rutube.ru/tags/video/1800/',
210 'info_dict': {
211 'id': '1800',
212 },
213 'playlist_mincount': 68,
214 }]
215
216 _PAGE_TEMPLATE = 'http://rutube.ru/api/tags/video/%s/?page=%s&format=json'
217
218
219 class RutubeMovieIE(RutubePlaylistBaseIE):
220 IE_NAME = 'rutube:movie'
221 IE_DESC = 'Rutube movies'
222 _VALID_URL = r'https?://rutube\.ru/metainfo/tv/(?P<id>\d+)'
223 _TESTS = []
224
225 _MOVIE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/?format=json'
226 _PAGE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/video?page=%s&format=json'
227
228 def _real_extract(self, url):
229 movie_id = self._match_id(url)
230 movie = self._download_json(
231 self._MOVIE_TEMPLATE % movie_id, movie_id,
232 'Downloading movie JSON')
233 return self._extract_playlist(
234 movie_id, playlist_name=movie.get('name'))
235
236
237 class RutubePersonIE(RutubePlaylistBaseIE):
238 IE_NAME = 'rutube:person'
239 IE_DESC = 'Rutube person videos'
240 _VALID_URL = r'https?://rutube\.ru/video/person/(?P<id>\d+)'
241 _TESTS = [{
242 'url': 'http://rutube.ru/video/person/313878/',
243 'info_dict': {
244 'id': '313878',
245 },
246 'playlist_mincount': 37,
247 }]
248
249 _PAGE_TEMPLATE = 'http://rutube.ru/api/video/person/%s/?page=%s&format=json'
250
251
252 class RutubePlaylistIE(RutubePlaylistBaseIE):
253 IE_NAME = 'rutube:playlist'
254 IE_DESC = 'Rutube playlists'
255 _VALID_URL = r'https?://rutube\.ru/(?:video|(?:play/)?embed)/[\da-z]{32}/\?.*?\bpl_id=(?P<id>\d+)'
256 _TESTS = [{
257 'url': 'https://rutube.ru/video/cecd58ed7d531fc0f3d795d51cee9026/?pl_id=3097&pl_type=tag',
258 'info_dict': {
259 'id': '3097',
260 },
261 'playlist_count': 27,
262 }, {
263 'url': 'https://rutube.ru/video/10b3a03fc01d5bbcc632a2f3514e8aab/?pl_id=4252&pl_type=source',
264 'only_matching': True,
265 }]
266
267 _PAGE_TEMPLATE = 'http://rutube.ru/api/playlist/%s/%s/?page=%s&format=json'
268
269 @classmethod
270 def suitable(cls, url):
271 if not super(RutubePlaylistIE, cls).suitable(url):
272 return False
273 params = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
274 return params.get('pl_type', [None])[0] and int_or_none(params.get('pl_id', [None])[0])
275
276 def _next_page_url(self, page_num, playlist_id, item_kind):
277 return self._PAGE_TEMPLATE % (item_kind, playlist_id, page_num)
278
279 def _real_extract(self, url):
280 qs = compat_parse_qs(compat_urllib_parse_urlparse(url).query)
281 playlist_kind = qs['pl_type'][0]
282 playlist_id = qs['pl_id'][0]
283 return self._extract_playlist(playlist_id, item_kind=playlist_kind)