[radiocanada] Relax DRM check
[youtube-dl] / youtube_dl / extractor / radiocanada.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     xpath_text,
9     find_xpath_attr,
10     determine_ext,
11     int_or_none,
12     unified_strdate,
13     xpath_element,
14     ExtractorError,
15     determine_protocol,
16     unsmuggle_url,
17 )
18
19
20 class RadioCanadaIE(InfoExtractor):
21     IE_NAME = 'radiocanada'
22     _VALID_URL = r'(?:radiocanada:|https?://ici\.radio-canada\.ca/widgets/mediaconsole/)(?P<app_code>[^:/]+)[:/](?P<id>[0-9]+)'
23     _TESTS = [
24         {
25             'url': 'http://ici.radio-canada.ca/widgets/mediaconsole/medianet/7184272',
26             'info_dict': {
27                 'id': '7184272',
28                 'ext': 'mp4',
29                 'title': 'Le parcours du tireur capté sur vidéo',
30                 'description': 'Images des caméras de surveillance fournies par la GRC montrant le parcours du tireur d\'Ottawa',
31                 'upload_date': '20141023',
32             },
33             'params': {
34                 # m3u8 download
35                 'skip_download': True,
36             }
37         },
38         {
39             # empty Title
40             'url': 'http://ici.radio-canada.ca/widgets/mediaconsole/medianet/7754998/',
41             'info_dict': {
42                 'id': '7754998',
43                 'ext': 'mp4',
44                 'title': 'letelejournal22h',
45                 'description': 'INTEGRALE WEB 22H-TJ',
46                 'upload_date': '20170720',
47             },
48             'params': {
49                 # m3u8 download
50                 'skip_download': True,
51             },
52         },
53         {
54             # with protectionType but not actually DRM protected
55             'url': 'radiocanada:toutv:140872',
56             'info_dict': {
57                 'id': '140872',
58                 'title': 'Épisode 1',
59                 'series': 'District 31',
60             },
61             'only_matching': True,
62         }
63     ]
64
65     def _real_extract(self, url):
66         url, smuggled_data = unsmuggle_url(url, {})
67         app_code, video_id = re.match(self._VALID_URL, url).groups()
68
69         metadata = self._download_xml(
70             'http://api.radio-canada.ca/metaMedia/v1/index.ashx',
71             video_id, note='Downloading metadata XML', query={
72                 'appCode': app_code,
73                 'idMedia': video_id,
74             })
75
76         def get_meta(name):
77             el = find_xpath_attr(metadata, './/Meta', 'name', name)
78             return el.text if el is not None else None
79
80         # protectionType does not necessarily mean the video is DRM protected (see
81         # https://github.com/rg3/youtube-dl/pull/18609).
82         if get_meta('protectionType'):
83             self.report_warning('This video is probably DRM protected.')
84
85         device_types = ['ipad']
86         if not smuggled_data:
87             device_types.append('flash')
88             device_types.append('android')
89
90         formats = []
91         error = None
92         # TODO: extract f4m formats
93         # f4m formats can be extracted using flashhd device_type but they produce unplayable file
94         for device_type in device_types:
95             validation_url = 'http://api.radio-canada.ca/validationMedia/v1/Validation.ashx'
96             query = {
97                 'appCode': app_code,
98                 'idMedia': video_id,
99                 'connectionType': 'broadband',
100                 'multibitrate': 'true',
101                 'deviceType': device_type,
102             }
103             if smuggled_data:
104                 validation_url = 'https://services.radio-canada.ca/media/validation/v2/'
105                 query.update(smuggled_data)
106             else:
107                 query.update({
108                     # paysJ391wsHjbOJwvCs26toz and bypasslock are used to bypass geo-restriction
109                     'paysJ391wsHjbOJwvCs26toz': 'CA',
110                     'bypasslock': 'NZt5K62gRqfc',
111                 })
112             v_data = self._download_xml(validation_url, video_id, note='Downloading %s XML' % device_type, query=query, fatal=False)
113             v_url = xpath_text(v_data, 'url')
114             if not v_url:
115                 continue
116             if v_url == 'null':
117                 error = xpath_text(v_data, 'message')
118                 continue
119             ext = determine_ext(v_url)
120             if ext == 'm3u8':
121                 formats.extend(self._extract_m3u8_formats(
122                     v_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
123             elif ext == 'f4m':
124                 formats.extend(self._extract_f4m_formats(
125                     v_url, video_id, f4m_id='hds', fatal=False))
126             else:
127                 ext = determine_ext(v_url)
128                 bitrates = xpath_element(v_data, 'bitrates')
129                 for url_e in bitrates.findall('url'):
130                     tbr = int_or_none(url_e.get('bitrate'))
131                     if not tbr:
132                         continue
133                     f_url = re.sub(r'\d+\.%s' % ext, '%d.%s' % (tbr, ext), v_url)
134                     protocol = determine_protocol({'url': f_url})
135                     f = {
136                         'format_id': '%s-%d' % (protocol, tbr),
137                         'url': f_url,
138                         'ext': 'flv' if protocol == 'rtmp' else ext,
139                         'protocol': protocol,
140                         'width': int_or_none(url_e.get('width')),
141                         'height': int_or_none(url_e.get('height')),
142                         'tbr': tbr,
143                     }
144                     mobj = re.match(r'(?P<url>rtmp://[^/]+/[^/]+)/(?P<playpath>[^?]+)(?P<auth>\?.+)', f_url)
145                     if mobj:
146                         f.update({
147                             'url': mobj.group('url') + mobj.group('auth'),
148                             'play_path': mobj.group('playpath'),
149                         })
150                     formats.append(f)
151                     if protocol == 'rtsp':
152                         base_url = self._search_regex(
153                             r'rtsp://([^?]+)', f_url, 'base url', default=None)
154                         if base_url:
155                             base_url = 'http://' + base_url
156                             formats.extend(self._extract_m3u8_formats(
157                                 base_url + '/playlist.m3u8', video_id, 'mp4',
158                                 'm3u8_native', m3u8_id='hls', fatal=False))
159                             formats.extend(self._extract_f4m_formats(
160                                 base_url + '/manifest.f4m', video_id,
161                                 f4m_id='hds', fatal=False))
162         if not formats and error:
163             raise ExtractorError(
164                 '%s said: %s' % (self.IE_NAME, error), expected=True)
165         self._sort_formats(formats)
166
167         subtitles = {}
168         closed_caption_url = get_meta('closedCaption') or get_meta('closedCaptionHTML5')
169         if closed_caption_url:
170             subtitles['fr'] = [{
171                 'url': closed_caption_url,
172                 'ext': determine_ext(closed_caption_url, 'vtt'),
173             }]
174
175         return {
176             'id': video_id,
177             'title': get_meta('Title') or get_meta('AV-nomEmission'),
178             'description': get_meta('Description') or get_meta('ShortDescription'),
179             'thumbnail': get_meta('imageHR') or get_meta('imageMR') or get_meta('imageBR'),
180             'duration': int_or_none(get_meta('length')),
181             'series': get_meta('Emission'),
182             'season_number': int_or_none('SrcSaison'),
183             'episode_number': int_or_none('SrcEpisode'),
184             'upload_date': unified_strdate(get_meta('Date')),
185             'subtitles': subtitles,
186             'formats': formats,
187         }
188
189
190 class RadioCanadaAudioVideoIE(InfoExtractor):
191     'radiocanada:audiovideo'
192     _VALID_URL = r'https?://ici\.radio-canada\.ca/audio-video/media-(?P<id>[0-9]+)'
193     _TEST = {
194         'url': 'http://ici.radio-canada.ca/audio-video/media-7527184/barack-obama-au-vietnam',
195         'info_dict': {
196             'id': '7527184',
197             'ext': 'mp4',
198             'title': 'Barack Obama au Vietnam',
199             'description': 'Les États-Unis lèvent l\'embargo sur la vente d\'armes qui datait de la guerre du Vietnam',
200             'upload_date': '20160523',
201         },
202         'params': {
203             # m3u8 download
204             'skip_download': True,
205         },
206     }
207
208     def _real_extract(self, url):
209         return self.url_result('radiocanada:medianet:%s' % self._match_id(url))