Merge remote-tracking branch 'jaimeMF/yt-playlists'
[youtube-dl] / youtube_dl / extractor / zdf.py
1 import re
2
3 from .common import InfoExtractor
4 from ..utils import (
5     determine_ext,
6     ExtractorError,
7 )
8
9
10 class ZDFIE(InfoExtractor):
11     _VALID_URL = r'^http://www\.zdf\.de\/ZDFmediathek(?P<hash>#)?\/(.*beitrag\/video\/)(?P<video_id>[^/\?]+)(?:\?.*)?'
12     _MEDIA_STREAM = r'<a href="(?P<video_url>.+(?P<media_type>.streaming).+/zdf/(?P<quality>[^\/]+)/[^"]*)".+class="play".+>'
13
14     def _real_extract(self, url):
15         mobj = re.match(self._VALID_URL, url)
16         if mobj is None:
17             raise ExtractorError(u'Invalid URL: %s' % url)
18         video_id = mobj.group('video_id')
19
20         if mobj.group('hash'):
21             url = url.replace(u'#', u'', 1)
22
23         html = self._download_webpage(url, video_id)
24         streams = [m.groupdict() for m in re.finditer(self._MEDIA_STREAM, html)]
25         if streams is None:
26             raise ExtractorError(u'No media url found.')
27
28         # s['media_type'] == 'wstreaming' -> use 'Windows Media Player' and mms url
29         # s['media_type'] == 'hstreaming' -> use 'Quicktime' and rtsp url
30         # choose first/default media type and highest quality for now
31         def stream_pref(s):
32             TYPE_ORDER = ['ostreaming', 'hstreaming', 'wstreaming']
33             try:
34                 type_pref = TYPE_ORDER.index(s['media_type'])
35             except ValueError:
36                 type_pref = 999
37
38             QUALITY_ORDER = ['veryhigh', '300']
39             try:
40                 quality_pref = QUALITY_ORDER.index(s['quality'])
41             except ValueError:
42                 quality_pref = 999
43
44             return (type_pref, quality_pref)
45
46         sorted_streams = sorted(streams, key=stream_pref)
47         if not sorted_streams:
48             raise ExtractorError(u'No stream found.')
49         stream = sorted_streams[0]
50
51         media_link = self._download_webpage(
52             stream['video_url'],
53             video_id,
54             u'Get stream URL')
55
56         #MMS_STREAM = r'href="(?P<video_url>mms://[^"]*)"'
57         RTSP_STREAM = r'(?P<video_url>rtsp://[^"]*.mp4)'
58
59         mobj = re.search(self._MEDIA_STREAM, media_link)
60         if mobj is None:
61             mobj = re.search(RTSP_STREAM, media_link)
62             if mobj is None:
63                 raise ExtractorError(u'Cannot extract mms:// or rtsp:// URL')
64         video_url = mobj.group('video_url')
65
66         title = self._html_search_regex(
67             r'<h1(?: class="beitragHeadline")?>(.*?)</h1>',
68             html, u'title')
69
70         return {
71             'id': video_id,
72             'url': video_url,
73             'title': title,
74             'ext': determine_ext(video_url)
75         }