[abc:iview] Fix extraction (closes #14711)
[youtube-dl] / youtube_dl / extractor / abc.py
1 from __future__ import unicode_literals
2
3 import hashlib
4 import hmac
5 import re
6 import time
7
8 from .common import InfoExtractor
9 from ..compat import compat_str
10 from ..utils import (
11     ExtractorError,
12     js_to_json,
13     int_or_none,
14     parse_iso8601,
15     try_get,
16 )
17
18
19 class ABCIE(InfoExtractor):
20     IE_NAME = 'abc.net.au'
21     _VALID_URL = r'https?://(?:www\.)?abc\.net\.au/news/(?:[^/]+/){1,2}(?P<id>\d+)'
22
23     _TESTS = [{
24         'url': 'http://www.abc.net.au/news/2014-11-05/australia-to-staff-ebola-treatment-centre-in-sierra-leone/5868334',
25         'md5': 'cb3dd03b18455a661071ee1e28344d9f',
26         'info_dict': {
27             'id': '5868334',
28             'ext': 'mp4',
29             'title': 'Australia to help staff Ebola treatment centre in Sierra Leone',
30             'description': 'md5:809ad29c67a05f54eb41f2a105693a67',
31         },
32         'skip': 'this video has expired',
33     }, {
34         'url': 'http://www.abc.net.au/news/2015-08-17/warren-entsch-introduces-same-sex-marriage-bill/6702326',
35         'md5': 'db2a5369238b51f9811ad815b69dc086',
36         'info_dict': {
37             'id': 'NvqvPeNZsHU',
38             'ext': 'mp4',
39             'upload_date': '20150816',
40             'uploader': 'ABC News (Australia)',
41             'description': 'Government backbencher Warren Entsch introduces a cross-party sponsored bill to legalise same-sex marriage, saying the bill is designed to promote "an inclusive Australia, not a divided one.". Read more here: http://ab.co/1Mwc6ef',
42             'uploader_id': 'NewsOnABC',
43             'title': 'Marriage Equality: Warren Entsch introduces same sex marriage bill',
44         },
45         'add_ie': ['Youtube'],
46         'skip': 'Not accessible from Travis CI server',
47     }, {
48         'url': 'http://www.abc.net.au/news/2015-10-23/nab-lifts-interest-rates-following-westpac-and-cba/6880080',
49         'md5': 'b96eee7c9edf4fc5a358a0252881cc1f',
50         'info_dict': {
51             'id': '6880080',
52             'ext': 'mp3',
53             'title': 'NAB lifts interest rates, following Westpac and CBA',
54             'description': 'md5:f13d8edc81e462fce4a0437c7dc04728',
55         },
56     }, {
57         'url': 'http://www.abc.net.au/news/2015-10-19/6866214',
58         'only_matching': True,
59     }]
60
61     def _real_extract(self, url):
62         video_id = self._match_id(url)
63         webpage = self._download_webpage(url, video_id)
64
65         mobj = re.search(
66             r'inline(?P<type>Video|Audio|YouTube)Data\.push\((?P<json_data>[^)]+)\);',
67             webpage)
68         if mobj is None:
69             expired = self._html_search_regex(r'(?s)class="expired-(?:video|audio)".+?<span>(.+?)</span>', webpage, 'expired', None)
70             if expired:
71                 raise ExtractorError('%s said: %s' % (self.IE_NAME, expired), expected=True)
72             raise ExtractorError('Unable to extract video urls')
73
74         urls_info = self._parse_json(
75             mobj.group('json_data'), video_id, transform_source=js_to_json)
76
77         if not isinstance(urls_info, list):
78             urls_info = [urls_info]
79
80         if mobj.group('type') == 'YouTube':
81             return self.playlist_result([
82                 self.url_result(url_info['url']) for url_info in urls_info])
83
84         formats = [{
85             'url': url_info['url'],
86             'vcodec': url_info.get('codec') if mobj.group('type') == 'Video' else 'none',
87             'width': int_or_none(url_info.get('width')),
88             'height': int_or_none(url_info.get('height')),
89             'tbr': int_or_none(url_info.get('bitrate')),
90             'filesize': int_or_none(url_info.get('filesize')),
91         } for url_info in urls_info]
92
93         self._sort_formats(formats)
94
95         return {
96             'id': video_id,
97             'title': self._og_search_title(webpage),
98             'formats': formats,
99             'description': self._og_search_description(webpage),
100             'thumbnail': self._og_search_thumbnail(webpage),
101         }
102
103
104 class ABCIViewIE(InfoExtractor):
105     IE_NAME = 'abc.net.au:iview'
106     _VALID_URL = r'https?://iview\.abc\.net\.au/programs/[^/]+/(?P<id>[^/?#]+)'
107
108     # ABC iview programs are normally available for 14 days only.
109     _TESTS = [{
110         'url': 'http://iview.abc.net.au/programs/diaries-of-a-broken-mind/ZX9735A001S00',
111         'md5': 'cde42d728b3b7c2b32b1b94b4a548afc',
112         'info_dict': {
113             'id': 'ZX9735A001S00',
114             'ext': 'mp4',
115             'title': 'Diaries Of A Broken Mind',
116             'description': 'md5:7de3903874b7a1be279fe6b68718fc9e',
117             'upload_date': '20161010',
118             'uploader_id': 'abc2',
119             'timestamp': 1476064920,
120         },
121         'skip': 'Video gone',
122     }]
123
124     def _real_extract(self, url):
125         video_id = self._match_id(url)
126         webpage = self._download_webpage(url, video_id)
127         video_params = self._parse_json(self._search_regex(
128             r'videoParams\s*=\s*({.+?});', webpage, 'video params'), video_id)
129         title = video_params.get('title') or video_params['seriesTitle']
130         stream = next(s for s in video_params['playlist'] if s.get('type') == 'program')
131
132         key = 'android.content.res.Resources'.encode('utf-8')
133         time_str = str(int(time.time()))
134         house_number = video_params.get('episodeHouseNumber')
135         path = '/auth/hls/sign?ts={0}&hn={1}&d=android-mobile'.format(
136             time_str, house_number)
137         sig = hmac.new(key, path.encode('utf-8'), hashlib.sha256).hexdigest()
138         auth_url = 'http://iview.abc.net.au{0}&sig={1}'.format(path, sig)
139         token = self._download_webpage(auth_url, video_id)
140
141         format_urls = []
142
143         def tokenize_url(url, token):
144             return ''.join([url, '?hdnea=', token])
145
146         # May have higher quality video
147         sd_url = try_get(
148             stream, lambda x: x['streams']['hls']['sd'], compat_str)
149         if sd_url:
150             format_urls.append(tokenize_url(sd_url, token))
151         else:
152             sd_low_url = try_get(
153                 stream, lambda x: x['streams']['hls']['sd-low'], compat_str)
154             format_urls.append(tokenize_url(sd_low_url, token))
155
156         formats = []
157         for format_url in format_urls:
158             if format_url:
159                 formats.extend(
160                     self._extract_m3u8_formats(format_url, video_id, 'mp4'))
161         self._sort_formats(formats)
162
163         subtitles = {}
164         src_vtt = stream.get('captions', {}).get('src-vtt')
165         if src_vtt:
166             subtitles['en'] = [{
167                 'url': src_vtt,
168                 'ext': 'vtt',
169             }]
170
171         return {
172             'id': video_id,
173             'title': title,
174             'description': self._html_search_meta(['og:description', 'twitter:description'], webpage),
175             'thumbnail': self._html_search_meta(['og:image', 'twitter:image:src'], webpage),
176             'duration': int_or_none(video_params.get('eventDuration')),
177             'timestamp': parse_iso8601(video_params.get('pubDate'), ' '),
178             'series': video_params.get('seriesTitle'),
179             'series_id': video_params.get('seriesHouseNumber') or video_id[:7],
180             'episode_number': int_or_none(self._html_search_meta('episodeNumber', webpage, default=None)),
181             'episode': self._html_search_meta('episode_title', webpage, default=None),
182             'uploader_id': video_params.get('channel'),
183             'formats': formats,
184             'subtitles': subtitles,
185         }