]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/fox.py
[panopto] Add extractors (#2908)
[yt-dlp.git] / yt_dlp / extractor / fox.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import json
5 import uuid
6
7 from .common import InfoExtractor
8 from ..compat import (
9 compat_HTTPError,
10 compat_str,
11 compat_urllib_parse_unquote,
12 )
13 from ..utils import (
14 ExtractorError,
15 int_or_none,
16 parse_age_limit,
17 parse_duration,
18 try_get,
19 unified_timestamp,
20 )
21
22
23 class FOXIE(InfoExtractor):
24 _VALID_URL = r'https?://(?:www\.)?fox\.com/watch/(?P<id>[\da-fA-F]+)'
25 _TESTS = [{
26 # clip
27 'url': 'https://www.fox.com/watch/4b765a60490325103ea69888fb2bd4e8/',
28 'md5': 'ebd296fcc41dd4b19f8115d8461a3165',
29 'info_dict': {
30 'id': '4b765a60490325103ea69888fb2bd4e8',
31 'ext': 'mp4',
32 'title': 'Aftermath: Bruce Wayne Develops Into The Dark Knight',
33 'description': 'md5:549cd9c70d413adb32ce2a779b53b486',
34 'duration': 102,
35 'timestamp': 1504291893,
36 'upload_date': '20170901',
37 'creator': 'FOX',
38 'series': 'Gotham',
39 'age_limit': 14,
40 'episode': 'Aftermath: Bruce Wayne Develops Into The Dark Knight'
41 },
42 'params': {
43 'skip_download': True,
44 },
45 }, {
46 # episode, geo-restricted
47 'url': 'https://www.fox.com/watch/087036ca7f33c8eb79b08152b4dd75c1/',
48 'only_matching': True,
49 }, {
50 # sports event, geo-restricted
51 'url': 'https://www.fox.com/watch/b057484dade738d1f373b3e46216fa2c/',
52 'only_matching': True,
53 }]
54 _GEO_BYPASS = False
55 _HOME_PAGE_URL = 'https://www.fox.com/'
56 _API_KEY = '6E9S4bmcoNnZwVLOHywOv8PJEdu76cM9'
57 _access_token = None
58 _device_id = compat_str(uuid.uuid4())
59
60 def _call_api(self, path, video_id, data=None):
61 headers = {
62 'X-Api-Key': self._API_KEY,
63 }
64 if self._access_token:
65 headers['Authorization'] = 'Bearer ' + self._access_token
66 try:
67 return self._download_json(
68 'https://api3.fox.com/v2.0/' + path,
69 video_id, data=data, headers=headers)
70 except ExtractorError as e:
71 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
72 entitlement_issues = self._parse_json(
73 e.cause.read().decode(), video_id)['entitlementIssues']
74 for e in entitlement_issues:
75 if e.get('errorCode') == 1005:
76 raise ExtractorError(
77 'This video is only available via cable service provider '
78 'subscription. You may want to use --cookies.', expected=True)
79 messages = ', '.join([e['message'] for e in entitlement_issues])
80 raise ExtractorError(messages, expected=True)
81 raise
82
83 def _real_initialize(self):
84 if not self._access_token:
85 mvpd_auth = self._get_cookies(self._HOME_PAGE_URL).get('mvpd-auth')
86 if mvpd_auth:
87 self._access_token = (self._parse_json(compat_urllib_parse_unquote(
88 mvpd_auth.value), None, fatal=False) or {}).get('accessToken')
89 if not self._access_token:
90 self._access_token = self._call_api(
91 'login', None, json.dumps({
92 'deviceId': self._device_id,
93 }).encode())['accessToken']
94
95 def _real_extract(self, url):
96 video_id = self._match_id(url)
97
98 self._access_token = self._call_api(
99 'previewpassmvpd?device_id=%s&mvpd_id=TempPass_fbcfox_60min' % self._device_id,
100 video_id)['accessToken']
101
102 video = self._call_api('watch', video_id, data=json.dumps({
103 'capabilities': ['drm/widevine', 'fsdk/yo'],
104 'deviceWidth': 1280,
105 'deviceHeight': 720,
106 'maxRes': '720p',
107 'os': 'macos',
108 'osv': '',
109 'provider': {
110 'freewheel': {'did': self._device_id},
111 'vdms': {'rays': ''},
112 'dmp': {'kuid': '', 'seg': ''}
113 },
114 'playlist': '',
115 'privacy': {'us': '1---'},
116 'siteSection': '',
117 'streamType': 'vod',
118 'streamId': video_id}).encode('utf-8'))
119
120 title = video['name']
121 release_url = video['url']
122
123 try:
124 m3u8_url = self._download_json(release_url, video_id)['playURL']
125 except ExtractorError as e:
126 if isinstance(e.cause, compat_HTTPError) and e.cause.code == 403:
127 error = self._parse_json(e.cause.read().decode(), video_id)
128 if error.get('exception') == 'GeoLocationBlocked':
129 self.raise_geo_restricted(countries=['US'])
130 raise ExtractorError(error['description'], expected=True)
131 raise
132 formats = self._extract_m3u8_formats(
133 m3u8_url, video_id, 'mp4',
134 entry_protocol='m3u8_native', m3u8_id='hls')
135 self._sort_formats(formats)
136
137 data = try_get(
138 video, lambda x: x['trackingData']['properties'], dict) or {}
139
140 duration = int_or_none(video.get('durationInSeconds')) or int_or_none(
141 video.get('duration')) or parse_duration(video.get('duration'))
142 timestamp = unified_timestamp(video.get('datePublished'))
143 creator = data.get('brand') or data.get('network') or video.get('network')
144 series = video.get('seriesName') or data.get(
145 'seriesName') or data.get('show')
146
147 subtitles = {}
148 for doc_rel in video.get('documentReleases', []):
149 rel_url = doc_rel.get('url')
150 if not url or doc_rel.get('format') != 'SCC':
151 continue
152 subtitles['en'] = [{
153 'url': rel_url,
154 'ext': 'scc',
155 }]
156 break
157
158 return {
159 'id': video_id,
160 'title': title,
161 'formats': formats,
162 'description': video.get('description'),
163 'duration': duration,
164 'timestamp': timestamp,
165 'age_limit': parse_age_limit(video.get('contentRating')),
166 'creator': creator,
167 'series': series,
168 'season_number': int_or_none(video.get('seasonNumber')),
169 'episode': video.get('name'),
170 'episode_number': int_or_none(video.get('episodeNumber')),
171 'release_year': int_or_none(video.get('releaseYear')),
172 'subtitles': subtitles,
173 }