~facundo/encuentro/trunk

« back to all changes in this revision

Viewing changes to external/youtube-dl/youtube_dl/extractor/ard.py

  • Committer: Facundo Batista
  • Date: 2015-12-27 11:27:15 UTC
  • mto: This revision was merged to the branch mainline in revision 274.
  • Revision ID: facundo@taniquetil.com.ar-20151227112715-ztuasdhqm26hycug
Able to download TEDx.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# coding: utf-8
 
2
from __future__ import unicode_literals
 
3
 
 
4
import re
 
5
 
 
6
from .common import InfoExtractor
 
7
from .generic import GenericIE
 
8
from ..utils import (
 
9
    determine_ext,
 
10
    ExtractorError,
 
11
    get_element_by_attribute,
 
12
    qualities,
 
13
    int_or_none,
 
14
    parse_duration,
 
15
    unified_strdate,
 
16
    xpath_text,
 
17
)
 
18
from ..compat import compat_etree_fromstring
 
19
 
 
20
 
 
21
class ARDMediathekIE(InfoExtractor):
 
22
    IE_NAME = 'ARD:mediathek'
 
23
    _VALID_URL = r'^https?://(?:(?:www\.)?ardmediathek\.de|mediathek\.daserste\.de)/(?:.*/)(?P<video_id>[0-9]+|[^0-9][^/\?]+)[^/\?]*(?:\?.*)?'
 
24
 
 
25
    _TESTS = [{
 
26
        'url': 'http://www.ardmediathek.de/tv/Dokumentation-und-Reportage/Ich-liebe-das-Leben-trotzdem/rbb-Fernsehen/Video?documentId=29582122&bcastId=3822114',
 
27
        'info_dict': {
 
28
            'id': '29582122',
 
29
            'ext': 'mp4',
 
30
            'title': 'Ich liebe das Leben trotzdem',
 
31
            'description': 'md5:45e4c225c72b27993314b31a84a5261c',
 
32
            'duration': 4557,
 
33
        },
 
34
        'params': {
 
35
            # m3u8 download
 
36
            'skip_download': True,
 
37
        },
 
38
    }, {
 
39
        'url': 'http://www.ardmediathek.de/tv/Tatort/Tatort-Scheinwelten-H%C3%B6rfassung-Video/Das-Erste/Video?documentId=29522730&bcastId=602916',
 
40
        'md5': 'f4d98b10759ac06c0072bbcd1f0b9e3e',
 
41
        'info_dict': {
 
42
            'id': '29522730',
 
43
            'ext': 'mp4',
 
44
            'title': 'Tatort: Scheinwelten - Hörfassung (Video tgl. ab 20 Uhr)',
 
45
            'description': 'md5:196392e79876d0ac94c94e8cdb2875f1',
 
46
            'duration': 5252,
 
47
        },
 
48
    }, {
 
49
        # audio
 
50
        'url': 'http://www.ardmediathek.de/tv/WDR-H%C3%B6rspiel-Speicher/Tod-eines-Fu%C3%9Fballers/WDR-3/Audio-Podcast?documentId=28488308&bcastId=23074086',
 
51
        'md5': '219d94d8980b4f538c7fcb0865eb7f2c',
 
52
        'info_dict': {
 
53
            'id': '28488308',
 
54
            'ext': 'mp3',
 
55
            'title': 'Tod eines Fußballers',
 
56
            'description': 'md5:f6e39f3461f0e1f54bfa48c8875c86ef',
 
57
            'duration': 3240,
 
58
        },
 
59
    }, {
 
60
        'url': 'http://mediathek.daserste.de/sendungen_a-z/328454_anne-will/22429276_vertrauen-ist-gut-spionieren-ist-besser-geht',
 
61
        'only_matching': True,
 
62
    }]
 
63
 
 
64
    def _extract_media_info(self, media_info_url, webpage, video_id):
 
65
        media_info = self._download_json(
 
66
            media_info_url, video_id, 'Downloading media JSON')
 
67
 
 
68
        formats = self._extract_formats(media_info, video_id)
 
69
 
 
70
        if not formats:
 
71
            if '"fsk"' in webpage:
 
72
                raise ExtractorError(
 
73
                    'This video is only available after 20:00', expected=True)
 
74
            elif media_info.get('_geoblocked'):
 
75
                raise ExtractorError('This video is not available due to geo restriction', expected=True)
 
76
 
 
77
        self._sort_formats(formats)
 
78
 
 
79
        duration = int_or_none(media_info.get('_duration'))
 
80
        thumbnail = media_info.get('_previewImage')
 
81
 
 
82
        subtitles = {}
 
83
        subtitle_url = media_info.get('_subtitleUrl')
 
84
        if subtitle_url:
 
85
            subtitles['de'] = [{
 
86
                'ext': 'srt',
 
87
                'url': subtitle_url,
 
88
            }]
 
89
 
 
90
        return {
 
91
            'id': video_id,
 
92
            'duration': duration,
 
93
            'thumbnail': thumbnail,
 
94
            'formats': formats,
 
95
            'subtitles': subtitles,
 
96
        }
 
97
 
 
98
    def _extract_formats(self, media_info, video_id):
 
99
        type_ = media_info.get('_type')
 
100
        media_array = media_info.get('_mediaArray', [])
 
101
        formats = []
 
102
        for num, media in enumerate(media_array):
 
103
            for stream in media.get('_mediaStreamArray', []):
 
104
                stream_urls = stream.get('_stream')
 
105
                if not stream_urls:
 
106
                    continue
 
107
                if not isinstance(stream_urls, list):
 
108
                    stream_urls = [stream_urls]
 
109
                quality = stream.get('_quality')
 
110
                server = stream.get('_server')
 
111
                for stream_url in stream_urls:
 
112
                    ext = determine_ext(stream_url)
 
113
                    if ext == 'f4m':
 
114
                        formats.extend(self._extract_f4m_formats(
 
115
                            stream_url + '?hdcore=3.1.1&plugin=aasp-3.1.1.69.124',
 
116
                            video_id, preference=-1, f4m_id='hds'))
 
117
                    elif ext == 'm3u8':
 
118
                        formats.extend(self._extract_m3u8_formats(
 
119
                            stream_url, video_id, 'mp4', preference=1, m3u8_id='hls'))
 
120
                    else:
 
121
                        if server and server.startswith('rtmp'):
 
122
                            f = {
 
123
                                'url': server,
 
124
                                'play_path': stream_url,
 
125
                                'format_id': 'a%s-rtmp-%s' % (num, quality),
 
126
                            }
 
127
                        elif stream_url.startswith('http'):
 
128
                            f = {
 
129
                                'url': stream_url,
 
130
                                'format_id': 'a%s-%s-%s' % (num, ext, quality)
 
131
                            }
 
132
                        else:
 
133
                            continue
 
134
                        m = re.search(r'_(?P<width>\d+)x(?P<height>\d+)\.mp4$', stream_url)
 
135
                        if m:
 
136
                            f.update({
 
137
                                'width': int(m.group('width')),
 
138
                                'height': int(m.group('height')),
 
139
                            })
 
140
                        if type_ == 'audio':
 
141
                            f['vcodec'] = 'none'
 
142
                        formats.append(f)
 
143
        return formats
 
144
 
 
145
    def _real_extract(self, url):
 
146
        # determine video id from url
 
147
        m = re.match(self._VALID_URL, url)
 
148
 
 
149
        numid = re.search(r'documentId=([0-9]+)', url)
 
150
        if numid:
 
151
            video_id = numid.group(1)
 
152
        else:
 
153
            video_id = m.group('video_id')
 
154
 
 
155
        webpage = self._download_webpage(url, video_id)
 
156
 
 
157
        if '>Der gewünschte Beitrag ist nicht mehr verfügbar.<' in webpage:
 
158
            raise ExtractorError('Video %s is no longer available' % video_id, expected=True)
 
159
 
 
160
        if 'Diese Sendung ist für Jugendliche unter 12 Jahren nicht geeignet. Der Clip ist deshalb nur von 20 bis 6 Uhr verfügbar.' in webpage:
 
161
            raise ExtractorError('This program is only suitable for those aged 12 and older. Video %s is therefore only available between 20 pm and 6 am.' % video_id, expected=True)
 
162
 
 
163
        if re.search(r'[\?&]rss($|[=&])', url):
 
164
            doc = compat_etree_fromstring(webpage.encode('utf-8'))
 
165
            if doc.tag == 'rss':
 
166
                return GenericIE()._extract_rss(url, video_id, doc)
 
167
 
 
168
        title = self._html_search_regex(
 
169
            [r'<h1(?:\s+class="boxTopHeadline")?>(.*?)</h1>',
 
170
             r'<meta name="dcterms.title" content="(.*?)"/>',
 
171
             r'<h4 class="headline">(.*?)</h4>'],
 
172
            webpage, 'title')
 
173
        description = self._html_search_meta(
 
174
            'dcterms.abstract', webpage, 'description', default=None)
 
175
        if description is None:
 
176
            description = self._html_search_meta(
 
177
                'description', webpage, 'meta description')
 
178
 
 
179
        # Thumbnail is sometimes not present.
 
180
        # It is in the mobile version, but that seems to use a different URL
 
181
        # structure altogether.
 
182
        thumbnail = self._og_search_thumbnail(webpage, default=None)
 
183
 
 
184
        media_streams = re.findall(r'''(?x)
 
185
            mediaCollection\.addMediaStream\([0-9]+,\s*[0-9]+,\s*"[^"]*",\s*
 
186
            "([^"]+)"''', webpage)
 
187
 
 
188
        if media_streams:
 
189
            QUALITIES = qualities(['lo', 'hi', 'hq'])
 
190
            formats = []
 
191
            for furl in set(media_streams):
 
192
                if furl.endswith('.f4m'):
 
193
                    fid = 'f4m'
 
194
                else:
 
195
                    fid_m = re.match(r'.*\.([^.]+)\.[^.]+$', furl)
 
196
                    fid = fid_m.group(1) if fid_m else None
 
197
                formats.append({
 
198
                    'quality': QUALITIES(fid),
 
199
                    'format_id': fid,
 
200
                    'url': furl,
 
201
                })
 
202
            self._sort_formats(formats)
 
203
            info = {
 
204
                'formats': formats,
 
205
            }
 
206
        else:  # request JSON file
 
207
            info = self._extract_media_info(
 
208
                'http://www.ardmediathek.de/play/media/%s' % video_id, webpage, video_id)
 
209
 
 
210
        info.update({
 
211
            'id': video_id,
 
212
            'title': title,
 
213
            'description': description,
 
214
            'thumbnail': thumbnail,
 
215
        })
 
216
 
 
217
        return info
 
218
 
 
219
 
 
220
class ARDIE(InfoExtractor):
 
221
    _VALID_URL = '(?P<mainurl>https?://(www\.)?daserste\.de/[^?#]+/videos/(?P<display_id>[^/?#]+)-(?P<id>[0-9]+))\.html'
 
222
    _TEST = {
 
223
        'url': 'http://www.daserste.de/information/reportage-dokumentation/dokus/videos/die-story-im-ersten-mission-unter-falscher-flagge-100.html',
 
224
        'md5': 'd216c3a86493f9322545e045ddc3eb35',
 
225
        'info_dict': {
 
226
            'display_id': 'die-story-im-ersten-mission-unter-falscher-flagge',
 
227
            'id': '100',
 
228
            'ext': 'mp4',
 
229
            'duration': 2600,
 
230
            'title': 'Die Story im Ersten: Mission unter falscher Flagge',
 
231
            'upload_date': '20140804',
 
232
            'thumbnail': 're:^https?://.*\.jpg$',
 
233
        }
 
234
    }
 
235
 
 
236
    def _real_extract(self, url):
 
237
        mobj = re.match(self._VALID_URL, url)
 
238
        display_id = mobj.group('display_id')
 
239
 
 
240
        player_url = mobj.group('mainurl') + '~playerXml.xml'
 
241
        doc = self._download_xml(player_url, display_id)
 
242
        video_node = doc.find('./video')
 
243
        upload_date = unified_strdate(xpath_text(
 
244
            video_node, './broadcastDate'))
 
245
        thumbnail = xpath_text(video_node, './/teaserImage//variant/url')
 
246
 
 
247
        formats = []
 
248
        for a in video_node.findall('.//asset'):
 
249
            f = {
 
250
                'format_id': a.attrib['type'],
 
251
                'width': int_or_none(a.find('./frameWidth').text),
 
252
                'height': int_or_none(a.find('./frameHeight').text),
 
253
                'vbr': int_or_none(a.find('./bitrateVideo').text),
 
254
                'abr': int_or_none(a.find('./bitrateAudio').text),
 
255
                'vcodec': a.find('./codecVideo').text,
 
256
                'tbr': int_or_none(a.find('./totalBitrate').text),
 
257
            }
 
258
            if a.find('./serverPrefix').text:
 
259
                f['url'] = a.find('./serverPrefix').text
 
260
                f['playpath'] = a.find('./fileName').text
 
261
            else:
 
262
                f['url'] = a.find('./fileName').text
 
263
            formats.append(f)
 
264
        self._sort_formats(formats)
 
265
 
 
266
        return {
 
267
            'id': mobj.group('id'),
 
268
            'formats': formats,
 
269
            'display_id': display_id,
 
270
            'title': video_node.find('./title').text,
 
271
            'duration': parse_duration(video_node.find('./duration').text),
 
272
            'upload_date': upload_date,
 
273
            'thumbnail': thumbnail,
 
274
        }
 
275
 
 
276
 
 
277
class SportschauIE(ARDMediathekIE):
 
278
    IE_NAME = 'Sportschau'
 
279
    _VALID_URL = r'(?P<baseurl>https?://(?:www\.)?sportschau\.de/(?:[^/]+/)+video(?P<id>[^/#?]+))\.html'
 
280
    _TESTS = [{
 
281
        'url': 'http://www.sportschau.de/tourdefrance/videoseppeltkokainhatnichtsmitklassischemdopingzutun100.html',
 
282
        'info_dict': {
 
283
            'id': 'seppeltkokainhatnichtsmitklassischemdopingzutun100',
 
284
            'ext': 'mp4',
 
285
            'title': 'Seppelt: "Kokain hat nichts mit klassischem Doping zu tun"',
 
286
            'thumbnail': 're:^https?://.*\.jpg$',
 
287
            'description': 'Der ARD-Doping Experte Hajo Seppelt gibt seine Einschätzung zum ersten Dopingfall der diesjährigen Tour de France um den Italiener Luca Paolini ab.',
 
288
        },
 
289
        'params': {
 
290
            # m3u8 download
 
291
            'skip_download': True,
 
292
        },
 
293
    }]
 
294
 
 
295
    def _real_extract(self, url):
 
296
        mobj = re.match(self._VALID_URL, url)
 
297
        video_id = mobj.group('id')
 
298
        base_url = mobj.group('baseurl')
 
299
 
 
300
        webpage = self._download_webpage(url, video_id)
 
301
        title = get_element_by_attribute('class', 'headline', webpage)
 
302
        description = self._html_search_meta('description', webpage, 'description')
 
303
 
 
304
        info = self._extract_media_info(
 
305
            base_url + '-mc_defaultQuality-h.json', webpage, video_id)
 
306
 
 
307
        info.update({
 
308
            'title': title,
 
309
            'description': description,
 
310
        })
 
311
 
 
312
        return info