Merge branch 'daum' of https://github.com/remitamine/youtube-dl into remitamine-daum
[youtube-dl] / youtube_dl / extractor / zdf.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import functools
5 import re
6
7 from .common import InfoExtractor
8 from ..utils import (
9     int_or_none,
10     unified_strdate,
11     OnDemandPagedList,
12     xpath_text,
13     determine_ext,
14     qualities,
15     float_or_none,
16 )
17
18
19 class ZDFIE(InfoExtractor):
20     _VALID_URL = r'(?:zdf:|zdf:video:|https?://www\.zdf\.de/ZDFmediathek(?:#)?/(.*beitrag/(?:video/)?))(?P<id>[0-9]+)(?:/[^/?]+)?(?:\?.*)?'
21
22     _TESTS = [{
23         'url': 'http://www.zdf.de/ZDFmediathek/beitrag/video/2037704/ZDFspezial---Ende-des-Machtpokers--?bc=sts;stt',
24         'info_dict': {
25             'id': '2037704',
26             'ext': 'webm',
27             'title': 'ZDFspezial - Ende des Machtpokers',
28             'description': 'Union und SPD haben sich auf einen Koalitionsvertrag geeinigt. Aber was bedeutet das für die Bürger? Sehen Sie hierzu das ZDFspezial "Ende des Machtpokers - Große Koalition für Deutschland".',
29             'duration': 1022,
30             'uploader': 'spezial',
31             'uploader_id': '225948',
32             'upload_date': '20131127',
33         },
34         'skip': 'Videos on ZDF.de are depublicised in short order',
35     }]
36
37     def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
38         param_groups = {}
39         for param_group in smil.findall(self._xpath_ns('./head/paramGroup', namespace)):
40             group_id = param_group.attrib.get(self._xpath_ns('id', 'http://www.w3.org/XML/1998/namespace'))
41             params = {}
42             for param in param_group:
43                 params[param.get('name')] = param.get('value')
44             param_groups[group_id] = params
45
46         formats = []
47         for video in smil.findall(self._xpath_ns('.//video', namespace)):
48             src = video.get('src')
49             if not src:
50                 continue
51             bitrate = float_or_none(video.get('system-bitrate') or video.get('systemBitrate'), 1000)
52             group_id = video.get('paramGroup')
53             param_group = param_groups[group_id]
54             for proto in param_group['protocols'].split(','):
55                 formats.append({
56                     'url': '%s://%s' % (proto, param_group['host']),
57                     'app': param_group['app'],
58                     'play_path': src,
59                     'ext': 'flv',
60                     'format_id': '%s-%d' % (proto, bitrate),
61                     'tbr': bitrate,
62                     'protocol': proto,
63                 })
64         self._sort_formats(formats)
65         return formats
66
67     def extract_from_xml_url(self, video_id, xml_url):
68         doc = self._download_xml(
69             xml_url, video_id,
70             note='Downloading video info',
71             errnote='Failed to download video info')
72
73         title = doc.find('.//information/title').text
74         description = xpath_text(doc, './/information/detail', 'description')
75         duration = int_or_none(xpath_text(doc, './/details/lengthSec', 'duration'))
76         uploader = xpath_text(doc, './/details/originChannelTitle', 'uploader')
77         uploader_id = xpath_text(doc, './/details/originChannelId', 'uploader id')
78         upload_date = unified_strdate(xpath_text(doc, './/details/airtime', 'upload date'))
79
80         def xml_to_thumbnails(fnode):
81             thumbnails = []
82             for node in fnode:
83                 thumbnail_url = node.text
84                 if not thumbnail_url:
85                     continue
86                 thumbnail = {
87                     'url': thumbnail_url,
88                 }
89                 if 'key' in node.attrib:
90                     m = re.match('^([0-9]+)x([0-9]+)$', node.attrib['key'])
91                     if m:
92                         thumbnail['width'] = int(m.group(1))
93                         thumbnail['height'] = int(m.group(2))
94                 thumbnails.append(thumbnail)
95             return thumbnails
96
97         thumbnails = xml_to_thumbnails(doc.findall('.//teaserimages/teaserimage'))
98
99         format_nodes = doc.findall('.//formitaeten/formitaet')
100         quality = qualities(['veryhigh', 'high', 'med', 'low'])
101
102         def get_quality(elem):
103             return quality(xpath_text(elem, 'quality'))
104         format_nodes.sort(key=get_quality)
105         format_ids = []
106         formats = []
107         for fnode in format_nodes:
108             video_url = fnode.find('url').text
109             is_available = 'http://www.metafilegenerator' not in video_url
110             if not is_available:
111                 continue
112             format_id = fnode.attrib['basetype']
113             quality = xpath_text(fnode, './quality', 'quality')
114             format_m = re.match(r'''(?x)
115                 (?P<vcodec>[^_]+)_(?P<acodec>[^_]+)_(?P<container>[^_]+)_
116                 (?P<proto>[^_]+)_(?P<index>[^_]+)_(?P<indexproto>[^_]+)
117             ''', format_id)
118
119             ext = determine_ext(video_url, None) or format_m.group('container')
120             if ext not in ('smil', 'f4m', 'm3u8'):
121                 format_id = format_id + '-' + quality
122             if format_id in format_ids:
123                 continue
124
125             if ext == 'meta':
126                 continue
127             elif ext == 'smil':
128                 formats.extend(self._extract_smil_formats(
129                     video_url, video_id, fatal=False))
130             elif ext == 'm3u8':
131                 formats.extend(self._extract_m3u8_formats(
132                     video_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
133             elif ext == 'f4m':
134                 formats.extend(self._extract_f4m_formats(
135                     video_url, video_id, f4m_id='hds', fatal=False))
136             else:
137                 proto = format_m.group('proto').lower()
138
139                 abr = int_or_none(xpath_text(fnode, './audioBitrate', 'abr'), 1000)
140                 vbr = int_or_none(xpath_text(fnode, './videoBitrate', 'vbr'), 1000)
141
142                 width = int_or_none(xpath_text(fnode, './width', 'width'))
143                 height = int_or_none(xpath_text(fnode, './height', 'height'))
144
145                 filesize = int_or_none(xpath_text(fnode, './filesize', 'filesize'))
146
147                 format_note = ''
148                 if not format_note:
149                     format_note = None
150
151                 formats.append({
152                     'format_id': format_id,
153                     'url': video_url,
154                     'ext': ext,
155                     'acodec': format_m.group('acodec'),
156                     'vcodec': format_m.group('vcodec'),
157                     'abr': abr,
158                     'vbr': vbr,
159                     'width': width,
160                     'height': height,
161                     'filesize': filesize,
162                     'format_note': format_note,
163                     'protocol': proto,
164                     '_available': is_available,
165                 })
166             format_ids.append(format_id)
167
168         self._sort_formats(formats)
169
170         return {
171             'id': video_id,
172             'title': title,
173             'description': description,
174             'duration': duration,
175             'thumbnails': thumbnails,
176             'uploader': uploader,
177             'uploader_id': uploader_id,
178             'upload_date': upload_date,
179             'formats': formats,
180         }
181
182     def _real_extract(self, url):
183         video_id = self._match_id(url)
184         xml_url = 'http://www.zdf.de/ZDFmediathek/xmlservice/web/beitragsDetails?ak=web&id=%s' % video_id
185         return self.extract_from_xml_url(video_id, xml_url)
186
187
188 class ZDFChannelIE(InfoExtractor):
189     _VALID_URL = r'(?:zdf:topic:|https?://www\.zdf\.de/ZDFmediathek(?:#)?/.*kanaluebersicht/(?:[^/]+/)?)(?P<id>[0-9]+)'
190     _TESTS = [{
191         'url': 'http://www.zdf.de/ZDFmediathek#/kanaluebersicht/1586442/sendung/Titanic',
192         'info_dict': {
193             'id': '1586442',
194         },
195         'playlist_count': 3,
196     }, {
197         'url': 'http://www.zdf.de/ZDFmediathek/kanaluebersicht/aktuellste/332',
198         'only_matching': True,
199     }, {
200         'url': 'http://www.zdf.de/ZDFmediathek/kanaluebersicht/meist-gesehen/332',
201         'only_matching': True,
202     }, {
203         'url': 'http://www.zdf.de/ZDFmediathek/kanaluebersicht/_/1798716?bc=nrt;nrm?flash=off',
204         'only_matching': True,
205     }]
206     _PAGE_SIZE = 50
207
208     def _fetch_page(self, channel_id, page):
209         offset = page * self._PAGE_SIZE
210         xml_url = (
211             'http://www.zdf.de/ZDFmediathek/xmlservice/web/aktuellste?ak=web&offset=%d&maxLength=%d&id=%s'
212             % (offset, self._PAGE_SIZE, channel_id))
213         doc = self._download_xml(
214             xml_url, channel_id,
215             note='Downloading channel info',
216             errnote='Failed to download channel info')
217
218         title = doc.find('.//information/title').text
219         description = doc.find('.//information/detail').text
220         for asset in doc.findall('.//teasers/teaser'):
221             a_type = asset.find('./type').text
222             a_id = asset.find('./details/assetId').text
223             if a_type not in ('video', 'topic'):
224                 continue
225             yield {
226                 '_type': 'url',
227                 'playlist_title': title,
228                 'playlist_description': description,
229                 'url': 'zdf:%s:%s' % (a_type, a_id),
230             }
231
232     def _real_extract(self, url):
233         channel_id = self._match_id(url)
234         entries = OnDemandPagedList(
235             functools.partial(self._fetch_page, channel_id), self._PAGE_SIZE)
236
237         return {
238             '_type': 'playlist',
239             'id': channel_id,
240             'entries': entries,
241         }