Release 2024.12.03
[yt-dlp3.git] / yt_dlp / extractor / fox.py
blobe3cf22d4d6b56372ba7e35dedf784a4ad7ecfd02
1 import json
2 import urllib.parse
3 import uuid
5 from .common import InfoExtractor
6 from ..networking.exceptions import HTTPError
7 from ..utils import (
8 ExtractorError,
9 int_or_none,
10 parse_age_limit,
11 parse_duration,
12 traverse_obj,
13 try_get,
14 unified_timestamp,
15 url_or_none,
19 class FOXIE(InfoExtractor):
20 _VALID_URL = r'https?://(?:www\.)?fox(?:sports)?\.com/(?:watch|replay)/(?P<id>[\da-fA-F]+)'
21 _TESTS = [{
22 # clip
23 'url': 'https://www.fox.com/watch/4b765a60490325103ea69888fb2bd4e8/',
24 'md5': 'ebd296fcc41dd4b19f8115d8461a3165',
25 'info_dict': {
26 'id': '4b765a60490325103ea69888fb2bd4e8',
27 'ext': 'mp4',
28 'title': 'Aftermath: Bruce Wayne Develops Into The Dark Knight',
29 'description': 'md5:549cd9c70d413adb32ce2a779b53b486',
30 'duration': 102,
31 'timestamp': 1504291893,
32 'upload_date': '20170901',
33 'creator': 'FOX',
34 'series': 'Gotham',
35 'age_limit': 14,
36 'episode': 'Aftermath: Bruce Wayne Develops Into The Dark Knight',
37 'thumbnail': r're:^https?://.*\.jpg$',
39 'params': {
40 'skip_download': True,
42 }, {
43 # episode, geo-restricted
44 'url': 'https://www.fox.com/watch/087036ca7f33c8eb79b08152b4dd75c1/',
45 'only_matching': True,
46 }, {
47 # sports event, geo-restricted
48 'url': 'https://www.fox.com/watch/b057484dade738d1f373b3e46216fa2c/',
49 'only_matching': True,
50 }, {
51 # fox sports replay, geo-restricted
52 'url': 'https://www.foxsports.com/replay/561f3e071347a24e5e877abc56b22e89',
53 'only_matching': True,
55 _GEO_BYPASS = False
56 _HOME_PAGE_URL = 'https://www.fox.com/'
57 _API_KEY = '6E9S4bmcoNnZwVLOHywOv8PJEdu76cM9'
58 _access_token = None
59 _device_id = str(uuid.uuid4())
61 def _call_api(self, path, video_id, data=None):
62 headers = {
63 'X-Api-Key': self._API_KEY,
65 if self._access_token:
66 headers['Authorization'] = 'Bearer ' + self._access_token
67 try:
68 return self._download_json(
69 'https://api3.fox.com/v2.0/' + path,
70 video_id, data=data, headers=headers)
71 except ExtractorError as e:
72 if isinstance(e.cause, HTTPError) and e.cause.status == 403:
73 entitlement_issues = self._parse_json(
74 e.cause.response.read().decode(), video_id)['entitlementIssues']
75 for e in entitlement_issues:
76 if e.get('errorCode') == 1005:
77 raise ExtractorError(
78 'This video is only available via cable service provider '
79 'subscription. You may want to use --cookies.', expected=True)
80 messages = ', '.join([e['message'] for e in entitlement_issues])
81 raise ExtractorError(messages, expected=True)
82 raise
84 def _real_initialize(self):
85 if not self._access_token:
86 mvpd_auth = self._get_cookies(self._HOME_PAGE_URL).get('mvpd-auth')
87 if mvpd_auth:
88 self._access_token = (self._parse_json(urllib.parse.unquote(
89 mvpd_auth.value), None, fatal=False) or {}).get('accessToken')
90 if not self._access_token:
91 self._access_token = self._call_api(
92 'login', None, json.dumps({
93 'deviceId': self._device_id,
94 }).encode())['accessToken']
96 def _real_extract(self, url):
97 video_id = self._match_id(url)
99 self._access_token = self._call_api(
100 f'previewpassmvpd?device_id={self._device_id}&mvpd_id=TempPass_fbcfox_60min',
101 video_id)['accessToken']
103 video = self._call_api('watch', video_id, data=json.dumps({
104 'capabilities': ['drm/widevine', 'fsdk/yo'],
105 'deviceWidth': 1280,
106 'deviceHeight': 720,
107 'maxRes': '720p',
108 'os': 'macos',
109 'osv': '',
110 'provider': {
111 'freewheel': {'did': self._device_id},
112 'vdms': {'rays': ''},
113 'dmp': {'kuid': '', 'seg': ''},
115 'playlist': '',
116 'privacy': {'us': '1---'},
117 'siteSection': '',
118 'streamType': 'vod',
119 'streamId': video_id}).encode())
121 title = video['name']
122 release_url = video['url']
124 try:
125 m3u8_url = self._download_json(release_url, video_id)['playURL']
126 except ExtractorError as e:
127 if isinstance(e.cause, HTTPError) and e.cause.status == 403:
128 error = self._parse_json(e.cause.response.read().decode(), video_id)
129 if error.get('exception') == 'GeoLocationBlocked':
130 self.raise_geo_restricted(countries=['US'])
131 raise ExtractorError(error['description'], expected=True)
132 raise
133 formats = self._extract_m3u8_formats(
134 m3u8_url, video_id, 'mp4',
135 entry_protocol='m3u8_native', m3u8_id='hls')
137 data = try_get(
138 video, lambda x: x['trackingData']['properties'], dict) or {}
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')
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',
156 break
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 'thumbnail': traverse_obj(video, ('images', 'still', 'raw'), expected_type=url_or_none),
172 'release_year': int_or_none(video.get('releaseYear')),
173 'subtitles': subtitles,