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