[discovery] fix free videos extraction(#14157)(#14954)
[youtube-dl] / youtube_dl / extractor / discoverygo.py
1 from __future__ import unicode_literals
2
3 import re
4
5 from .common import InfoExtractor
6 from ..compat import compat_str
7 from ..utils import (
8     extract_attributes,
9     ExtractorError,
10     int_or_none,
11     parse_age_limit,
12     remove_end,
13     unescapeHTML,
14 )
15
16
17 class DiscoveryGoBaseIE(InfoExtractor):
18     _VALID_URL_TEMPLATE = r'''(?x)https?://(?:www\.)?(?:
19             discovery|
20             investigationdiscovery|
21             discoverylife|
22             animalplanet|
23             ahctv|
24             destinationamerica|
25             sciencechannel|
26             tlc|
27             velocitychannel
28         )go\.com/%s(?P<id>[^/?#&]+)'''
29
30     def _extract_video_info(self, video, stream, display_id):
31         title = video['name']
32
33         if not stream:
34             if video.get('authenticated') is True:
35                 raise ExtractorError(
36                     'This video is only available via cable service provider subscription that'
37                     ' is not currently supported. You may want to use --cookies.', expected=True)
38             else:
39                 raise ExtractorError('Unable to find stream')
40         STREAM_URL_SUFFIX = 'streamUrl'
41         formats = []
42         for stream_kind in ('', 'hds'):
43             suffix = STREAM_URL_SUFFIX.capitalize() if stream_kind else STREAM_URL_SUFFIX
44             stream_url = stream.get('%s%s' % (stream_kind, suffix))
45             if not stream_url:
46                 continue
47             if stream_kind == '':
48                 formats.extend(self._extract_m3u8_formats(
49                     stream_url, display_id, 'mp4', entry_protocol='m3u8_native',
50                     m3u8_id='hls', fatal=False))
51             elif stream_kind == 'hds':
52                 formats.extend(self._extract_f4m_formats(
53                     stream_url, display_id, f4m_id=stream_kind, fatal=False))
54         self._sort_formats(formats)
55
56         video_id = video.get('id') or display_id
57         description = video.get('description', {}).get('detailed')
58         duration = int_or_none(video.get('duration'))
59
60         series = video.get('show', {}).get('name')
61         season_number = int_or_none(video.get('season', {}).get('number'))
62         episode_number = int_or_none(video.get('episodeNumber'))
63
64         tags = video.get('tags')
65         age_limit = parse_age_limit(video.get('parental', {}).get('rating'))
66
67         subtitles = {}
68         captions = stream.get('captions')
69         if isinstance(captions, list):
70             for caption in captions:
71                 subtitle_url = caption.get('fileUrl')
72                 if (not subtitle_url or not isinstance(subtitle_url, compat_str) or
73                         not subtitle_url.startswith('http')):
74                     continue
75                 lang = caption.get('fileLang', 'en')
76                 subtitles.setdefault(lang, []).append({'url': subtitle_url})
77
78         return {
79             'id': video_id,
80             'display_id': display_id,
81             'title': title,
82             'description': description,
83             'duration': duration,
84             'series': series,
85             'season_number': season_number,
86             'episode_number': episode_number,
87             'tags': tags,
88             'age_limit': age_limit,
89             'formats': formats,
90             'subtitles': subtitles,
91         }
92
93
94 class DiscoveryGoIE(DiscoveryGoBaseIE):
95     _VALID_URL = DiscoveryGoBaseIE._VALID_URL_TEMPLATE % r'(?:[^/]+/)+'
96     _GEO_COUNTRIES = ['US']
97     _TEST = {
98         'url': 'https://www.discoverygo.com/bering-sea-gold/reaper-madness/',
99         'info_dict': {
100             'id': '58c167d86b66d12f2addeb01',
101             'ext': 'mp4',
102             'title': 'Reaper Madness',
103             'description': 'md5:09f2c625c99afb8946ed4fb7865f6e78',
104             'duration': 2519,
105             'series': 'Bering Sea Gold',
106             'season_number': 8,
107             'episode_number': 6,
108             'age_limit': 14,
109         },
110     }
111
112     def _real_extract(self, url):
113         display_id = self._match_id(url)
114
115         webpage = self._download_webpage(url, display_id)
116
117         container = extract_attributes(
118             self._search_regex(
119                 r'(<div[^>]+class=["\']video-player-container[^>]+>)',
120                 webpage, 'video container'))
121
122         video = self._parse_json(
123             container.get('data-video') or container.get('data-json'),
124             display_id)
125
126         stream = video.get('stream')
127
128         return self._extract_video_info(video, stream, display_id)
129
130
131 class DiscoveryGoPlaylistIE(DiscoveryGoBaseIE):
132     _VALID_URL = DiscoveryGoBaseIE._VALID_URL_TEMPLATE % ''
133     _TEST = {
134         'url': 'https://www.discoverygo.com/bering-sea-gold/',
135         'info_dict': {
136             'id': 'bering-sea-gold',
137             'title': 'Bering Sea Gold',
138             'description': 'md5:cc5c6489835949043c0cc3ad66c2fa0e',
139         },
140         'playlist_mincount': 6,
141     }
142
143     @classmethod
144     def suitable(cls, url):
145         return False if DiscoveryGoIE.suitable(url) else super(
146             DiscoveryGoPlaylistIE, cls).suitable(url)
147
148     def _real_extract(self, url):
149         display_id = self._match_id(url)
150
151         webpage = self._download_webpage(url, display_id)
152
153         entries = []
154         for mobj in re.finditer(r'data-json=(["\'])(?P<json>{.+?})\1', webpage):
155             data = self._parse_json(
156                 mobj.group('json'), display_id,
157                 transform_source=unescapeHTML, fatal=False)
158             if not isinstance(data, dict) or data.get('type') != 'episode':
159                 continue
160             episode_url = data.get('socialUrl')
161             if not episode_url:
162                 continue
163             entries.append(self.url_result(
164                 episode_url, ie=DiscoveryGoIE.ie_key(),
165                 video_id=data.get('id')))
166
167         return self.playlist_result(
168             entries, display_id,
169             remove_end(self._og_search_title(
170                 webpage, fatal=False), ' | Discovery GO'),
171             self._og_search_description(webpage))