[ie/dplay] Fix extractors (#10471)
[yt-dlp3.git] / yt_dlp / extractor / ruutu.py
blob2dddb39f95d411e0e17c68ac314827fe35785281
1 import json
2 import re
3 import urllib.parse
5 from .common import InfoExtractor
6 from ..utils import (
7 ExtractorError,
8 determine_ext,
9 find_xpath_attr,
10 int_or_none,
11 traverse_obj,
12 try_call,
13 unified_strdate,
14 url_or_none,
15 xpath_attr,
16 xpath_text,
20 class RuutuIE(InfoExtractor):
21 _VALID_URL = r'''(?x)
22 https?://
23 (?:
24 (?:www\.)?(?:ruutu|supla)\.fi/(?:video|supla|audio)/|
25 static\.nelonenmedia\.fi/player/misc/embed_player\.html\?.*?\bnid=
27 (?P<id>\d+)
28 '''
29 _TESTS = [
31 'url': 'http://www.ruutu.fi/video/2058907',
32 'md5': 'ab2093f39be1ca8581963451b3c0234f',
33 'info_dict': {
34 'id': '2058907',
35 'ext': 'mp4',
36 'title': 'Oletko aina halunnut tietää mitä tapahtuu vain hetki ennen lähetystä? - Nyt se selvisi!',
37 'description': 'md5:cfc6ccf0e57a814360df464a91ff67d6',
38 'thumbnail': r're:^https?://.*\.jpg$',
39 'duration': 114,
40 'age_limit': 0,
41 'upload_date': '20150508',
45 'url': 'http://www.ruutu.fi/video/2057306',
46 'md5': '065a10ae4d5b8cfd9d0c3d332465e3d9',
47 'info_dict': {
48 'id': '2057306',
49 'ext': 'mp4',
50 'title': 'Superpesis: katso koko kausi Ruudussa',
51 'description': 'md5:bfb7336df2a12dc21d18fa696c9f8f23',
52 'thumbnail': r're:^https?://.*\.jpg$',
53 'duration': 40,
54 'age_limit': 0,
55 'upload_date': '20150507',
56 'series': 'Superpesis',
57 'categories': ['Urheilu'],
61 'url': 'http://www.supla.fi/supla/2231370',
62 'md5': 'df14e782d49a2c0df03d3be2a54ef949',
63 'info_dict': {
64 'id': '2231370',
65 'ext': 'mp4',
66 'title': 'Osa 1: Mikael Jungner',
67 'description': 'md5:7d90f358c47542e3072ff65d7b1bcffe',
68 'thumbnail': r're:^https?://.*\.jpg$',
69 'age_limit': 0,
70 'upload_date': '20151012',
71 'series': 'Läpivalaisu',
74 # Episode where <SourceFile> is "NOT-USED", but has other
75 # downloadable sources available.
77 'url': 'http://www.ruutu.fi/video/3193728',
78 'only_matching': True,
81 # audio podcast
82 'url': 'https://www.supla.fi/supla/3382410',
83 'md5': 'b9d7155fed37b2ebf6021d74c4b8e908',
84 'info_dict': {
85 'id': '3382410',
86 'ext': 'mp3',
87 'title': 'Mikä ihmeen poltergeist?',
88 'description': 'md5:bbb6963df17dfd0ecd9eb9a61bf14b52',
89 'thumbnail': r're:^https?://.*\.jpg$',
90 'age_limit': 0,
91 'upload_date': '20190320',
92 'series': 'Mysteeritarinat',
93 'duration': 1324,
95 'expected_warnings': [
96 'HTTP Error 502: Bad Gateway',
97 'Failed to download m3u8 information',
101 'url': 'http://www.supla.fi/audio/2231370',
102 'only_matching': True,
105 'url': 'https://static.nelonenmedia.fi/player/misc/embed_player.html?nid=3618790',
106 'only_matching': True,
109 # episode
110 'url': 'https://www.ruutu.fi/video/3401964',
111 'info_dict': {
112 'id': '3401964',
113 'ext': 'mp4',
114 'title': 'Temptation Island Suomi - Kausi 5 - Jakso 17',
115 'description': 'md5:87cf01d5e1e88adf0c8a2937d2bd42ba',
116 'thumbnail': r're:^https?://.*\.jpg$',
117 'duration': 2582,
118 'age_limit': 12,
119 'upload_date': '20190508',
120 'series': 'Temptation Island Suomi',
121 'season_number': 5,
122 'episode_number': 17,
123 'categories': ['Reality ja tositapahtumat', 'Kotimaiset suosikit', 'Romantiikka ja parisuhde'],
125 'params': {
126 'skip_download': True,
130 # premium
131 'url': 'https://www.ruutu.fi/video/3618715',
132 'only_matching': True,
135 _API_BASE = 'https://gatling.nelonenmedia.fi'
137 @classmethod
138 def _extract_embed_urls(cls, url, webpage):
139 # nelonen.fi
140 settings = try_call(
141 lambda: json.loads(re.search(
142 r'jQuery\.extend\(Drupal\.settings, ({.+?})\);', webpage).group(1), strict=False))
143 if settings:
144 video_id = traverse_obj(settings, (
145 'mediaCrossbowSettings', 'file', 'field_crossbow_video_id', 'und', 0, 'value'))
146 if video_id:
147 return [f'http://www.ruutu.fi/video/{video_id}']
148 # hs.fi and is.fi
149 settings = try_call(
150 lambda: json.loads(re.search(
151 '(?s)<script[^>]+id=[\'"]__NEXT_DATA__[\'"][^>]*>([^<]+)</script>',
152 webpage).group(1), strict=False))
153 if settings:
154 video_ids = set(traverse_obj(settings, (
155 'props', 'pageProps', 'page', 'assetData', 'splitBody', ..., 'video', 'sourceId')) or [])
156 if video_ids:
157 return [f'http://www.ruutu.fi/video/{v}' for v in video_ids]
158 video_id = traverse_obj(settings, (
159 'props', 'pageProps', 'page', 'assetData', 'mainVideo', 'sourceId'))
160 if video_id:
161 return [f'http://www.ruutu.fi/video/{video_id}']
163 def _real_extract(self, url):
164 video_id = self._match_id(url)
166 video_xml = self._download_xml(
167 f'{self._API_BASE}/media-xml-cache', video_id,
168 query={'id': video_id})
170 formats = []
171 processed_urls = []
173 def extract_formats(node):
174 for child in node:
175 if child.tag.endswith('Files'):
176 extract_formats(child)
177 elif child.tag.endswith('File'):
178 video_url = child.text
179 if (not video_url or video_url in processed_urls
180 or any(p in video_url for p in ('NOT_USED', 'NOT-USED'))):
181 continue
182 processed_urls.append(video_url)
183 ext = determine_ext(video_url)
184 auth_video_url = url_or_none(self._download_webpage(
185 f'{self._API_BASE}/auth/access/v2', video_id,
186 note=f'Downloading authenticated {ext} stream URL',
187 fatal=False, query={'stream': video_url}))
188 if auth_video_url:
189 processed_urls.append(auth_video_url)
190 video_url = auth_video_url
191 if ext == 'm3u8':
192 formats.extend(self._extract_m3u8_formats(
193 video_url, video_id, 'mp4',
194 entry_protocol='m3u8_native', m3u8_id='hls',
195 fatal=False))
196 elif ext == 'f4m':
197 formats.extend(self._extract_f4m_formats(
198 video_url, video_id, f4m_id='hds', fatal=False))
199 elif ext == 'mpd':
200 # video-only and audio-only streams are of different
201 # duration resulting in out of sync issue
202 continue
203 formats.extend(self._extract_mpd_formats(
204 video_url, video_id, mpd_id='dash', fatal=False))
205 elif ext == 'mp3' or child.tag == 'AudioMediaFile':
206 formats.append({
207 'format_id': 'audio',
208 'url': video_url,
209 'vcodec': 'none',
211 else:
212 proto = urllib.parse.urlparse(video_url).scheme
213 if not child.tag.startswith('HTTP') and proto != 'rtmp':
214 continue
215 preference = -1 if proto == 'rtmp' else 1
216 label = child.get('label')
217 tbr = int_or_none(child.get('bitrate'))
218 format_id = f'{proto}-{label if label else tbr}' if label or tbr else proto
219 if not self._is_valid_url(video_url, video_id, format_id):
220 continue
221 width, height = (int_or_none(x) for x in child.get('resolution', 'x').split('x')[:2])
222 formats.append({
223 'format_id': format_id,
224 'url': video_url,
225 'width': width,
226 'height': height,
227 'tbr': tbr,
228 'preference': preference,
231 extract_formats(video_xml.find('./Clip'))
233 def pv(name):
234 value = try_call(lambda: find_xpath_attr(
235 video_xml, './Clip/PassthroughVariables/variable', 'name', name).get('value'))
236 if value != 'NA':
237 return value or None
239 if not formats:
240 if (not self.get_param('allow_unplayable_formats')
241 and xpath_text(video_xml, './Clip/DRM', default=None)):
242 self.report_drm(video_id)
243 ns_st_cds = pv('ns_st_cds')
244 if ns_st_cds != 'free':
245 raise ExtractorError(f'This video is {ns_st_cds}.', expected=True)
247 themes = pv('themes')
249 return {
250 'id': video_id,
251 'title': xpath_attr(video_xml, './/Behavior/Program', 'program_name', 'title', fatal=True),
252 'description': xpath_attr(video_xml, './/Behavior/Program', 'description', 'description'),
253 'thumbnail': xpath_attr(video_xml, './/Behavior/Startpicture', 'href', 'thumbnail'),
254 'duration': int_or_none(xpath_text(video_xml, './/Runtime', 'duration')) or int_or_none(pv('runtime')),
255 'age_limit': int_or_none(xpath_text(video_xml, './/AgeLimit', 'age limit')),
256 'upload_date': unified_strdate(pv('date_start')),
257 'series': pv('series_name'),
258 'season_number': int_or_none(pv('season_number')),
259 'episode_number': int_or_none(pv('episode_number')),
260 'categories': themes.split(',') if themes else None,
261 'formats': formats,