[rutube] Extract all formats
[youtube-dl] / youtube_dl / extractor / rutube.py
1 # encoding: 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 )
11 from ..utils import (
12     determine_ext,
13     unified_strdate,
14 )
15
16
17 class RutubeIE(InfoExtractor):
18     IE_NAME = 'rutube'
19     IE_DESC = 'Rutube videos'
20     _VALID_URL = r'https?://rutube\.ru/video/(?P<id>[\da-z]{32})'
21
22     _TEST = {
23         'url': 'http://rutube.ru/video/3eac3b4561676c17df9132a9a1e62e3e/',
24         'info_dict': {
25             'id': '3eac3b4561676c17df9132a9a1e62e3e',
26             'ext': 'mp4',
27             'title': 'Раненный кенгуру забежал в аптеку',
28             'description': 'http://www.ntdtv.ru ',
29             'duration': 80,
30             'uploader': 'NTDRussian',
31             'uploader_id': '29790',
32             'upload_date': '20131016',
33             'age_limit': 0,
34         },
35         'params': {
36             # It requires ffmpeg (m3u8 download)
37             'skip_download': True,
38         },
39     }
40
41     def _real_extract(self, url):
42         video_id = self._match_id(url)
43         video = self._download_json(
44             'http://rutube.ru/api/video/%s/?format=json' % video_id,
45             video_id, 'Downloading video JSON')
46
47         # Some videos don't have the author field
48         author = video.get('author') or {}
49
50         options = self._download_json(
51             'http://rutube.ru/api/play/options/%s/?format=json' % video_id,
52             video_id, 'Downloading options JSON')
53
54         formats = []
55         for format_id, format_url in options['video_balancer'].items():
56             ext = determine_ext(format_url)
57             print(ext)
58             if ext == 'm3u8':
59                 m3u8_formats = self._extract_m3u8_formats(
60                     format_url, video_id, 'mp4', m3u8_id=format_id, fatal=False)
61                 if m3u8_formats:
62                     formats.extend(m3u8_formats)
63             elif ext == 'f4m':
64                 f4m_formats = self._extract_f4m_formats(
65                     format_url, video_id, f4m_id=format_id, fatal=False)
66                 if f4m_formats:
67                     formats.extend(f4m_formats)
68             else:
69                 formats.append({
70                     'url': format_url,
71                     'format_id': format_id,
72                 })
73         self._sort_formats(formats)
74
75         return {
76             'id': video['id'],
77             'title': video['title'],
78             'description': video['description'],
79             'duration': video['duration'],
80             'view_count': video['hits'],
81             'formats': formats,
82             'thumbnail': video['thumbnail_url'],
83             'uploader': author.get('name'),
84             'uploader_id': compat_str(author['id']) if author else None,
85             'upload_date': unified_strdate(video['created_ts']),
86             'age_limit': 18 if video['is_adult'] else 0,
87         }
88
89
90 class RutubeEmbedIE(InfoExtractor):
91     IE_NAME = 'rutube:embed'
92     IE_DESC = 'Rutube embedded videos'
93     _VALID_URL = 'https?://rutube\.ru/(?:video|play)/embed/(?P<id>[0-9]+)'
94
95     _TESTS = [{
96         'url': 'http://rutube.ru/video/embed/6722881?vk_puid37=&vk_puid38=',
97         'info_dict': {
98             'id': 'a10e53b86e8f349080f718582ce4c661',
99             'ext': 'mp4',
100             'upload_date': '20131223',
101             'uploader_id': '297833',
102             'description': 'Видео группы ★http://vk.com/foxkidsreset★ музей Fox Kids и Jetix<br/><br/> восстановлено и сделано в шикоформате subziro89 http://vk.com/subziro89',
103             'uploader': 'subziro89 ILya',
104             'title': 'Мистический городок Эйри в Индиан 5 серия озвучка subziro89',
105         },
106         'params': {
107             'skip_download': 'Requires ffmpeg',
108         },
109     }, {
110         'url': 'http://rutube.ru/play/embed/8083783',
111         'only_matching': True,
112     }]
113
114     def _real_extract(self, url):
115         embed_id = self._match_id(url)
116         webpage = self._download_webpage(url, embed_id)
117
118         canonical_url = self._html_search_regex(
119             r'<link\s+rel="canonical"\s+href="([^"]+?)"', webpage,
120             'Canonical URL')
121         return self.url_result(canonical_url, 'Rutube')
122
123
124 class RutubeChannelIE(InfoExtractor):
125     IE_NAME = 'rutube:channel'
126     IE_DESC = 'Rutube channels'
127     _VALID_URL = r'http://rutube\.ru/tags/video/(?P<id>\d+)'
128     _TESTS = [{
129         'url': 'http://rutube.ru/tags/video/1800/',
130         'info_dict': {
131             'id': '1800',
132         },
133         'playlist_mincount': 68,
134     }]
135
136     _PAGE_TEMPLATE = 'http://rutube.ru/api/tags/video/%s/?page=%s&format=json'
137
138     def _extract_videos(self, channel_id, channel_title=None):
139         entries = []
140         for pagenum in itertools.count(1):
141             page = self._download_json(
142                 self._PAGE_TEMPLATE % (channel_id, pagenum),
143                 channel_id, 'Downloading page %s' % pagenum)
144             results = page['results']
145             if not results:
146                 break
147             entries.extend(self.url_result(result['video_url'], 'Rutube') for result in results)
148             if not page['has_next']:
149                 break
150         return self.playlist_result(entries, channel_id, channel_title)
151
152     def _real_extract(self, url):
153         mobj = re.match(self._VALID_URL, url)
154         channel_id = mobj.group('id')
155         return self._extract_videos(channel_id)
156
157
158 class RutubeMovieIE(RutubeChannelIE):
159     IE_NAME = 'rutube:movie'
160     IE_DESC = 'Rutube movies'
161     _VALID_URL = r'http://rutube\.ru/metainfo/tv/(?P<id>\d+)'
162     _TESTS = []
163
164     _MOVIE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/?format=json'
165     _PAGE_TEMPLATE = 'http://rutube.ru/api/metainfo/tv/%s/video?page=%s&format=json'
166
167     def _real_extract(self, url):
168         movie_id = self._match_id(url)
169         movie = self._download_json(
170             self._MOVIE_TEMPLATE % movie_id, movie_id,
171             'Downloading movie JSON')
172         movie_name = movie['name']
173         return self._extract_videos(movie_id, movie_name)
174
175
176 class RutubePersonIE(RutubeChannelIE):
177     IE_NAME = 'rutube:person'
178     IE_DESC = 'Rutube person videos'
179     _VALID_URL = r'http://rutube\.ru/video/person/(?P<id>\d+)'
180     _TESTS = [{
181         'url': 'http://rutube.ru/video/person/313878/',
182         'info_dict': {
183             'id': '313878',
184         },
185         'playlist_mincount': 37,
186     }]
187
188     _PAGE_TEMPLATE = 'http://rutube.ru/api/video/person/%s/?page=%s&format=json'