[aenetworks] fix history topic extraction and extract more formats
[youtube-dl] / youtube_dl / extractor / aenetworks.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .theplatform import ThePlatformIE
6 from ..utils import (
7     extract_attributes,
8     ExtractorError,
9     int_or_none,
10     smuggle_url,
11     update_url_query,
12 )
13 from ..compat import (
14     compat_urlparse,
15 )
16
17
18 class AENetworksBaseIE(ThePlatformIE):
19     _THEPLATFORM_KEY = 'crazyjava'
20     _THEPLATFORM_SECRET = 's3cr3t'
21
22     def _extract_aen_smil(self, smil_url, video_id, auth=None):
23         query = {'mbr': 'true'}
24         if auth:
25             query['auth'] = auth
26         TP_SMIL_QUERY = [{
27             'assetTypes': 'high_video_ak',
28             'switch': 'hls_high_ak'
29         }, {
30             'assetTypes': 'high_video_s3'
31         }, {
32             'assetTypes': 'high_video_s3',
33             'switch': 'hls_ingest_fastly'
34         }]
35         formats = []
36         subtitles = {}
37         last_e = None
38         for q in TP_SMIL_QUERY:
39             q.update(query)
40             m_url = update_url_query(smil_url, q)
41             m_url = self._sign_url(m_url, self._THEPLATFORM_KEY, self._THEPLATFORM_SECRET)
42             try:
43                 tp_formats, tp_subtitles = self._extract_theplatform_smil(
44                     m_url, video_id, 'Downloading %s SMIL data' % (q.get('switch') or q['assetTypes']))
45             except ExtractorError as e:
46                 last_e = e
47                 continue
48             formats.extend(tp_formats)
49             subtitles = self._merge_subtitles(subtitles, tp_subtitles)
50         if last_e and not formats:
51             raise last_e
52         self._sort_formats(formats)
53         return {
54             'id': video_id,
55             'formats': formats,
56             'subtitles': subtitles,
57         }
58
59
60 class AENetworksIE(AENetworksBaseIE):
61     IE_NAME = 'aenetworks'
62     IE_DESC = 'A+E Networks: A&E, Lifetime, History.com, FYI Network and History Vault'
63     _VALID_URL = r'''(?x)
64                     https?://
65                         (?:www\.)?
66                         (?P<domain>
67                             (?:history(?:vault)?|aetv|mylifetime|lifetimemovieclub)\.com|
68                             fyi\.tv
69                         )/
70                         (?:
71                             shows/(?P<show_path>[^/]+(?:/[^/]+){0,2})|
72                             movies/(?P<movie_display_id>[^/]+)(?:/full-movie)?|
73                             specials/(?P<special_display_id>[^/]+)/(?:full-special|preview-)|
74                             collections/[^/]+/(?P<collection_display_id>[^/]+)
75                         )
76                     '''
77     _TESTS = [{
78         'url': 'http://www.history.com/shows/mountain-men/season-1/episode-1',
79         'info_dict': {
80             'id': '22253814',
81             'ext': 'mp4',
82             'title': 'Winter is Coming',
83             'description': 'md5:641f424b7a19d8e24f26dea22cf59d74',
84             'timestamp': 1338306241,
85             'upload_date': '20120529',
86             'uploader': 'AENE-NEW',
87         },
88         'params': {
89             # m3u8 download
90             'skip_download': True,
91         },
92         'add_ie': ['ThePlatform'],
93     }, {
94         'url': 'http://www.history.com/shows/ancient-aliens/season-1',
95         'info_dict': {
96             'id': '71889446852',
97         },
98         'playlist_mincount': 5,
99     }, {
100         'url': 'http://www.mylifetime.com/shows/atlanta-plastic',
101         'info_dict': {
102             'id': 'SERIES4317',
103             'title': 'Atlanta Plastic',
104         },
105         'playlist_mincount': 2,
106     }, {
107         'url': 'http://www.aetv.com/shows/duck-dynasty/season-9/episode-1',
108         'only_matching': True
109     }, {
110         'url': 'http://www.fyi.tv/shows/tiny-house-nation/season-1/episode-8',
111         'only_matching': True
112     }, {
113         'url': 'http://www.mylifetime.com/shows/project-runway-junior/season-1/episode-6',
114         'only_matching': True
115     }, {
116         'url': 'http://www.mylifetime.com/movies/center-stage-on-pointe/full-movie',
117         'only_matching': True
118     }, {
119         'url': 'https://www.lifetimemovieclub.com/movies/a-killer-among-us',
120         'only_matching': True
121     }, {
122         'url': 'http://www.history.com/specials/sniper-into-the-kill-zone/full-special',
123         'only_matching': True
124     }, {
125         'url': 'https://www.historyvault.com/collections/america-the-story-of-us/westward',
126         'only_matching': True
127     }, {
128         'url': 'https://www.aetv.com/specials/hunting-jonbenets-killer-the-untold-story/preview-hunting-jonbenets-killer-the-untold-story',
129         'only_matching': True
130     }]
131     _DOMAIN_TO_REQUESTOR_ID = {
132         'history.com': 'HISTORY',
133         'aetv.com': 'AETV',
134         'mylifetime.com': 'LIFETIME',
135         'lifetimemovieclub.com': 'LIFETIMEMOVIECLUB',
136         'fyi.tv': 'FYI',
137     }
138
139     def _real_extract(self, url):
140         domain, show_path, movie_display_id, special_display_id, collection_display_id = re.match(self._VALID_URL, url).groups()
141         display_id = show_path or movie_display_id or special_display_id or collection_display_id
142         webpage = self._download_webpage(url, display_id, headers=self.geo_verification_headers())
143         if show_path:
144             url_parts = show_path.split('/')
145             url_parts_len = len(url_parts)
146             if url_parts_len == 1:
147                 entries = []
148                 for season_url_path in re.findall(r'(?s)<li[^>]+data-href="(/shows/%s/season-\d+)"' % url_parts[0], webpage):
149                     entries.append(self.url_result(
150                         compat_urlparse.urljoin(url, season_url_path), 'AENetworks'))
151                 if entries:
152                     return self.playlist_result(
153                         entries, self._html_search_meta('aetn:SeriesId', webpage),
154                         self._html_search_meta('aetn:SeriesTitle', webpage))
155                 else:
156                     # single season
157                     url_parts_len = 2
158             if url_parts_len == 2:
159                 entries = []
160                 for episode_item in re.findall(r'(?s)<[^>]+class="[^"]*(?:episode|program)-item[^"]*"[^>]*>', webpage):
161                     episode_attributes = extract_attributes(episode_item)
162                     episode_url = compat_urlparse.urljoin(
163                         url, episode_attributes['data-canonical'])
164                     entries.append(self.url_result(
165                         episode_url, 'AENetworks',
166                         episode_attributes.get('data-videoid') or episode_attributes.get('data-video-id')))
167                 return self.playlist_result(
168                     entries, self._html_search_meta('aetn:SeasonId', webpage))
169
170         video_id = self._html_search_meta('aetn:VideoID', webpage)
171         media_url = self._search_regex(
172             [r"media_url\s*=\s*'(?P<url>[^']+)'",
173              r'data-media-url=(?P<url>(?:https?:)?//[^\s>]+)',
174              r'data-media-url=(["\'])(?P<url>(?:(?!\1).)+?)\1'],
175             webpage, 'video url', group='url')
176         theplatform_metadata = self._download_theplatform_metadata(self._search_regex(
177             r'https?://link\.theplatform\.com/s/([^?]+)', media_url, 'theplatform_path'), video_id)
178         info = self._parse_theplatform_metadata(theplatform_metadata)
179         auth = None
180         if theplatform_metadata.get('AETN$isBehindWall'):
181             requestor_id = self._DOMAIN_TO_REQUESTOR_ID[domain]
182             resource = self._get_mvpd_resource(
183                 requestor_id, theplatform_metadata['title'],
184                 theplatform_metadata.get('AETN$PPL_pplProgramId') or theplatform_metadata.get('AETN$PPL_pplProgramId_OLD'),
185                 theplatform_metadata['ratings'][0]['rating'])
186             auth = self._extract_mvpd_auth(
187                 url, video_id, requestor_id, resource)
188         info.update(self._search_json_ld(webpage, video_id, fatal=False))
189         info.update(self._extract_aen_smil(media_url, video_id, auth))
190         return info
191
192
193 class HistoryTopicIE(AENetworksBaseIE):
194     IE_NAME = 'history:topic'
195     IE_DESC = 'History.com Topic'
196     _VALID_URL = r'https?://(?:www\.)?history\.com/topics/[^/]+/(?P<id>[\w+-]+?)-video'
197     _TESTS = [{
198         'url': 'https://www.history.com/topics/valentines-day/history-of-valentines-day-video',
199         'info_dict': {
200             'id': '40700995724',
201             'ext': 'mp4',
202             'title': "History of Valentine’s Day",
203             'description': 'md5:7b57ea4829b391995b405fa60bd7b5f7',
204             'timestamp': 1375819729,
205             'upload_date': '20130806',
206         },
207         'params': {
208             # m3u8 download
209             'skip_download': True,
210         },
211         'add_ie': ['ThePlatform'],
212     }]
213
214     def theplatform_url_result(self, theplatform_url, video_id, query):
215         return {
216             '_type': 'url_transparent',
217             'id': video_id,
218             'url': smuggle_url(
219                 update_url_query(theplatform_url, query),
220                 {
221                     'sig': {
222                         'key': self._THEPLATFORM_KEY,
223                         'secret': self._THEPLATFORM_SECRET,
224                     },
225                     'force_smil_url': True
226                 }),
227             'ie_key': 'ThePlatform',
228         }
229
230     def _real_extract(self, url):
231         display_id = self._match_id(url)
232         webpage = self._download_webpage(url, display_id)
233         video_id = self._search_regex(
234             r'<phoenix-iframe[^>]+src="[^"]+\btpid=(\d+)', webpage, 'tpid')
235         result = self._download_json(
236             'https://feeds.video.aetnd.com/api/v2/history/videos',
237             video_id, query={'filter[id]': video_id})['results'][0]
238         title = result['title']
239         info = self._extract_aen_smil(result['publicUrl'], video_id)
240         info.update({
241             'title': title,
242             'description': result.get('description'),
243             'duration': int_or_none(result.get('duration')),
244             'timestamp': int_or_none(result.get('added'), 1000),
245         })
246         return info