Merge remote-tracking branch 'drags/yt-feed-loadmore'
[youtube-dl] / youtube_dl / extractor / orf.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import re
6 import calendar
7 import datetime
8
9 from .common import InfoExtractor
10 from ..utils import (
11     HEADRequest,
12     unified_strdate,
13     ExtractorError,
14 )
15
16
17 class ORFTVthekIE(InfoExtractor):
18     IE_NAME = 'orf:tvthek'
19     IE_DESC = 'ORF TVthek'
20     _VALID_URL = r'https?://tvthek\.orf\.at/(?:programs/.+?/episodes|topics/.+?|program/[^/]+)/(?P<id>\d+)'
21
22     _TEST = {
23         'url': 'http://tvthek.orf.at/program/matinee-Was-Sie-schon-immer-ueber-Klassik-wissen-wollten/7317210/Was-Sie-schon-immer-ueber-Klassik-wissen-wollten/7319746/Was-Sie-schon-immer-ueber-Klassik-wissen-wollten/7319747',
24         'file': '7319747.mp4',
25         'md5': 'bd803c5d8c32d3c64a0ea4b4eeddf375',
26         'info_dict': {
27             'title': 'Was Sie schon immer über Klassik wissen wollten',
28             'description': 'md5:0ddf0d5f0060bd53f744edaa5c2e04a4',
29             'duration': 3508,
30             'upload_date': '20140105',
31         },
32         'skip': 'Blocked outside of Austria',
33     }
34
35     def _real_extract(self, url):
36         mobj = re.match(self._VALID_URL, url)
37         playlist_id = mobj.group('id')
38         webpage = self._download_webpage(url, playlist_id)
39
40         data_json = self._search_regex(
41             r'initializeAdworx\((.+?)\);\n', webpage, 'video info')
42         all_data = json.loads(data_json)
43
44         def get_segments(all_data):
45             for data in all_data:
46                 if data['name'] == 'Tracker::EPISODE_DETAIL_PAGE_OVER_PROGRAM':
47                     return data['values']['segments']
48
49         sdata = get_segments(all_data)
50         if not sdata:
51             raise ExtractorError('Unable to extract segments')
52
53         def quality_to_int(s):
54             m = re.search('([0-9]+)', s)
55             if m is None:
56                 return -1
57             return int(m.group(1))
58
59         entries = []
60         for sd in sdata:
61             video_id = sd['id']
62             formats = [{
63                 'preference': -10 if fd['delivery'] == 'hls' else None,
64                 'format_id': '%s-%s-%s' % (
65                     fd['delivery'], fd['quality'], fd['quality_string']),
66                 'url': fd['src'],
67                 'protocol': fd['protocol'],
68                 'quality': quality_to_int(fd['quality']),
69             } for fd in sd['playlist_item_array']['sources']]
70
71             # Check for geoblocking.
72             # There is a property is_geoprotection, but that's always false
73             geo_str = sd.get('geoprotection_string')
74             if geo_str:
75                 try:
76                     http_url = next(
77                         f['url']
78                         for f in formats
79                         if re.match(r'^https?://.*\.mp4$', f['url']))
80                 except StopIteration:
81                     pass
82                 else:
83                     req = HEADRequest(http_url)
84                     self._request_webpage(
85                         req, video_id,
86                         note='Testing for geoblocking',
87                         errnote=((
88                             'This video seems to be blocked outside of %s. '
89                             'You may want to try the streaming-* formats.')
90                             % geo_str),
91                         fatal=False)
92
93             self._sort_formats(formats)
94
95             upload_date = unified_strdate(sd['created_date'])
96             entries.append({
97                 '_type': 'video',
98                 'id': video_id,
99                 'title': sd['header'],
100                 'formats': formats,
101                 'description': sd.get('description'),
102                 'duration': int(sd['duration_in_seconds']),
103                 'upload_date': upload_date,
104                 'thumbnail': sd.get('image_full_url'),
105             })
106
107         return {
108             '_type': 'playlist',
109             'entries': entries,
110             'id': playlist_id,
111         }
112
113
114 # Audios on ORF radio are only available for 7 days, so we can't add tests.
115
116
117 class ORFOE1IE(InfoExtractor):
118     IE_NAME = 'orf:oe1'
119     IE_DESC = 'Radio Österreich 1'
120     _VALID_URL = r'http://oe1\.orf\.at/programm/(?P<id>[0-9]+)'
121
122     def _real_extract(self, url):
123         mobj = re.match(self._VALID_URL, url)
124         show_id = mobj.group('id')
125
126         data = self._download_json(
127             'http://oe1.orf.at/programm/%s/konsole' % show_id,
128             show_id
129         )
130
131         timestamp = datetime.datetime.strptime('%s %s' % (
132             data['item']['day_label'],
133             data['item']['time']
134         ), '%d.%m.%Y %H:%M')
135         unix_timestamp = calendar.timegm(timestamp.utctimetuple())
136
137         return {
138             'id': show_id,
139             'title': data['item']['title'],
140             'url': data['item']['url_stream'],
141             'ext': 'mp3',
142             'description': data['item'].get('info'),
143             'timestamp': unix_timestamp
144         }
145
146
147 class ORFFM4IE(InfoExtractor):
148     IE_DESC = 'orf:fm4'
149     IE_DESC = 'radio FM4'
150     _VALID_URL = r'http://fm4\.orf\.at/7tage/?#(?P<date>[0-9]+)/(?P<show>\w+)'
151
152     def _real_extract(self, url):
153         mobj = re.match(self._VALID_URL, url)
154         show_date = mobj.group('date')
155         show_id = mobj.group('show')
156
157         data = self._download_json(
158             'http://audioapi.orf.at/fm4/json/2.0/broadcasts/%s/4%s' % (show_date, show_id),
159             show_id
160         )
161
162         def extract_entry_dict(info, title, subtitle):
163             return {
164                 'id': info['loopStreamId'].replace('.mp3', ''),
165                 'url': 'http://loopstream01.apa.at/?channel=fm4&id=%s' % info['loopStreamId'],
166                 'title': title,
167                 'description': subtitle,
168                 'duration': (info['end'] - info['start']) / 1000,
169                 'timestamp': info['start'] / 1000,
170                 'ext': 'mp3'
171             }
172
173         entries = [extract_entry_dict(t, data['title'], data['subtitle']) for t in data['streams']]
174
175         return {
176             '_type': 'playlist',
177             'id': show_id,
178             'title': data['title'],
179             'description': data['subtitle'],
180             'entries': entries
181         }