Merge remote-tracking branch 'akretz/master'
[youtube-dl] / youtube_dl / extractor / zdf.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5
6 from .common import InfoExtractor
7 from ..utils import (
8     int_or_none,
9     unified_strdate,
10 )
11
12
13 def extract_from_xml_url(ie, video_id, xml_url):
14     doc = ie._download_xml(
15         xml_url, video_id,
16         note='Downloading video info',
17         errnote='Failed to download video info')
18
19     title = doc.find('.//information/title').text
20     description = doc.find('.//information/detail').text
21     duration = int(doc.find('.//details/lengthSec').text)
22     uploader_node = doc.find('.//details/originChannelTitle')
23     uploader = None if uploader_node is None else uploader_node.text
24     uploader_id_node = doc.find('.//details/originChannelId')
25     uploader_id = None if uploader_id_node is None else uploader_id_node.text
26     upload_date = unified_strdate(doc.find('.//details/airtime').text)
27
28     def xml_to_format(fnode):
29         video_url = fnode.find('url').text
30         is_available = 'http://www.metafilegenerator' not in video_url
31
32         format_id = fnode.attrib['basetype']
33         format_m = re.match(r'''(?x)
34             (?P<vcodec>[^_]+)_(?P<acodec>[^_]+)_(?P<container>[^_]+)_
35             (?P<proto>[^_]+)_(?P<index>[^_]+)_(?P<indexproto>[^_]+)
36         ''', format_id)
37
38         ext = format_m.group('container')
39         proto = format_m.group('proto').lower()
40
41         quality = fnode.find('./quality').text
42         abr = int(fnode.find('./audioBitrate').text) // 1000
43         vbr_node = fnode.find('./videoBitrate')
44         vbr = None if vbr_node is None else int(vbr_node.text) // 1000
45
46         width_node = fnode.find('./width')
47         width = None if width_node is None else int_or_none(width_node.text)
48         height_node = fnode.find('./height')
49         height = None if height_node is None else int_or_none(height_node.text)
50
51         format_note = ''
52         if not format_note:
53             format_note = None
54
55         return {
56             'format_id': format_id + '-' + quality,
57             'url': video_url,
58             'ext': ext,
59             'acodec': format_m.group('acodec'),
60             'vcodec': format_m.group('vcodec'),
61             'abr': abr,
62             'vbr': vbr,
63             'width': width,
64             'height': height,
65             'filesize': int_or_none(fnode.find('./filesize').text),
66             'format_note': format_note,
67             'protocol': proto,
68             '_available': is_available,
69         }
70
71     format_nodes = doc.findall('.//formitaeten/formitaet')
72     formats = list(filter(
73         lambda f: f['_available'],
74         map(xml_to_format, format_nodes)))
75     ie._sort_formats(formats)
76
77     return {
78         'id': video_id,
79         'title': title,
80         'description': description,
81         'duration': duration,
82         'uploader': uploader,
83         'uploader_id': uploader_id,
84         'upload_date': upload_date,
85         'formats': formats,
86     }
87
88
89 def extract_channel_from_xml_url(ie, channel_id, xml_url):
90     doc = ie._download_xml(
91         xml_url, channel_id,
92         note='Downloading channel info',
93         errnote='Failed to download channel info')
94
95     title = doc.find('.//information/title').text
96     description = doc.find('.//information/detail').text
97     assets = [{'id': asset.find('./details/assetId').text,
98                'type': asset.find('./type').text,
99                } for asset in doc.findall('.//teasers/teaser')]
100
101     return {
102         'id': channel_id,
103         'title': title,
104         'description': description,
105         'assets': assets,
106     }
107
108
109 class ZDFIE(InfoExtractor):
110     _VALID_URL = r'^https?://www\.zdf\.de/ZDFmediathek(?P<hash>#)?/(.*beitrag/(?:video/)?)(?P<id>[0-9]+)(?:/[^/?]+)?(?:\?.*)?'
111
112     _TEST = {
113         'url': 'http://www.zdf.de/ZDFmediathek/beitrag/video/2037704/ZDFspezial---Ende-des-Machtpokers--?bc=sts;stt',
114         'info_dict': {
115             'id': '2037704',
116             'ext': 'webm',
117             'title': 'ZDFspezial - Ende des Machtpokers',
118             '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".',
119             'duration': 1022,
120             'uploader': 'spezial',
121             'uploader_id': '225948',
122             'upload_date': '20131127',
123         },
124         'skip': 'Videos on ZDF.de are depublicised in short order',
125     }
126
127     def _extract_video(self, video_id):
128         xml_url = 'http://www.zdf.de/ZDFmediathek/xmlservice/web/beitragsDetails?ak=web&id=%s' % video_id
129         return extract_from_xml_url(self, video_id, xml_url)
130
131     def _real_extract(self, url):
132         return self._extract_video(self._match_id(url))
133
134
135 class ZDFChannelIE(ZDFIE):
136     _VALID_URL = r'^https?://www\.zdf\.de/ZDFmediathek(?P<hash>#)?/(.*kanaluebersicht/)(?P<id>[0-9]+)'
137
138     _TEST = {
139         'url': 'http://www.zdf.de/ZDFmediathek#/kanaluebersicht/1586442/sendung/Titanic',
140         'info_dict': {
141             'id': '1586442',
142             'title': 'Titanic',
143             'description': 'md5:444c048cfe3fdc2561be7de4bcbf1d04',
144         },
145         'playlist_count': 3,
146     }
147
148     def _extract_channel(self, channel_id):
149         def load_chunks(channel_id, chunk_length):
150             offset = 0
151             while True:
152                 url = ('http://www.zdf.de/ZDFmediathek/xmlservice/web/aktuellste?ak=web&offset=%d&maxLength=%d&id=%s'
153                        % (offset, chunk_length, channel_id))
154                 result = extract_channel_from_xml_url(self, channel_id, url)
155                 yield result
156                 if len(result['assets']) < chunk_length:
157                     return
158                 offset += chunk_length
159
160         def load_channel(channel_id):
161             chunks = list(load_chunks(channel_id, 50))  # The server rejects higher values
162             assets = [asset for chunk in chunks for asset in chunk['assets']]
163             video_ids = [asset['id'] for asset in
164                          filter(lambda asset: asset['type'] == 'video',
165                                 assets)]
166             topic_ids = [asset['id'] for asset in
167                          filter(lambda asset: asset['type'] == 'thema',
168                                 assets)]
169             if topic_ids:
170                 video_ids = reduce(list.__add__,
171                                    [load_channel(topic_id)['video_ids']
172                                     for topic_id in topic_ids],
173                                    video_ids)
174
175             result = chunks[0]
176             result['video_ids'] = video_ids
177             return result
178
179         channel = load_channel(channel_id)
180         return {
181             '_type': 'playlist',
182             'id': channel['id'],
183             'title': channel['title'],
184             'description': channel['description'],
185             'entries': [self._extract_video(video_id)
186                         for video_id in channel['video_ids']],
187         }
188
189     def _real_extract(self, url):
190         return self._extract_channel(self._match_id(url))