]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/ertgr.py
[extractors] Use new framework for existing embeds (#4307)
[yt-dlp.git] / yt_dlp / extractor / ertgr.py
CommitLineData
2d49720f
ZM
1import json
2import re
3
4from .common import InfoExtractor
5from ..compat import compat_str
6from ..utils import (
7 clean_html,
8 determine_ext,
9 ExtractorError,
10 dict_get,
11 int_or_none,
12 merge_dicts,
13 parse_qs,
14 parse_age_limit,
15 parse_iso8601,
16 str_or_none,
17 try_get,
2d49720f
ZM
18 url_or_none,
19 variadic,
20)
21
22
23class ERTFlixBaseIE(InfoExtractor):
24 def _call_api(
25 self, video_id, method='Player/AcquireContent', api_version=1,
26 param_headers=None, data=None, headers=None, **params):
27 platform_codename = {'platformCodename': 'www'}
28 headers_as_param = {'X-Api-Date-Format': 'iso', 'X-Api-Camel-Case': False}
29 headers_as_param.update(param_headers or {})
30 headers = headers or {}
31 if data:
32 headers['Content-Type'] = headers_as_param['Content-Type'] = 'application/json;charset=utf-8'
33 data = json.dumps(merge_dicts(platform_codename, data)).encode('utf-8')
34 query = merge_dicts(
35 {} if data else platform_codename,
36 {'$headers': json.dumps(headers_as_param)},
37 params)
38 response = self._download_json(
39 'https://api.app.ertflix.gr/v%s/%s' % (str(api_version), method),
40 video_id, fatal=False, query=query, data=data, headers=headers)
41 if try_get(response, lambda x: x['Result']['Success']) is True:
42 return response
43
44 def _call_api_get_tiles(self, video_id, *tile_ids):
45 requested_tile_ids = [video_id] + list(tile_ids)
46 requested_tiles = [{'Id': tile_id} for tile_id in requested_tile_ids]
47 tiles_response = self._call_api(
48 video_id, method='Tile/GetTiles', api_version=2,
49 data={'RequestedTiles': requested_tiles})
50 tiles = try_get(tiles_response, lambda x: x['Tiles'], list) or []
51 if tile_ids:
52 if sorted([tile['Id'] for tile in tiles]) != sorted(requested_tile_ids):
53 raise ExtractorError('Requested tiles not found', video_id=video_id)
54 return tiles
55 try:
56 return next(tile for tile in tiles if tile['Id'] == video_id)
57 except StopIteration:
58 raise ExtractorError('No matching tile found', video_id=video_id)
59
60
61class ERTFlixCodenameIE(ERTFlixBaseIE):
62 IE_NAME = 'ertflix:codename'
63 IE_DESC = 'ERTFLIX videos by codename'
64 _VALID_URL = r'ertflix:(?P<id>[\w-]+)'
65 _TESTS = [{
66 'url': 'ertflix:monogramma-praxitelis-tzanoylinos',
67 'md5': '5b9c2cd171f09126167e4082fc1dd0ef',
68 'info_dict': {
69 'id': 'monogramma-praxitelis-tzanoylinos',
70 'ext': 'mp4',
71 'title': 'md5:ef0b439902963d56c43ac83c3f41dd0e',
72 },
73 },
74 ]
75
76 def _extract_formats_and_subs(self, video_id, allow_none=True):
77 media_info = self._call_api(video_id, codename=video_id)
78 formats, subs = [], {}
79 for media_file in try_get(media_info, lambda x: x['MediaFiles'], list) or []:
80 for media in try_get(media_file, lambda x: x['Formats'], list) or []:
81 fmt_url = url_or_none(try_get(media, lambda x: x['Url']))
82 if not fmt_url:
83 continue
84 ext = determine_ext(fmt_url)
85 if ext == 'm3u8':
86 formats_, subs_ = self._extract_m3u8_formats_and_subtitles(
87 fmt_url, video_id, m3u8_id='hls', ext='mp4', fatal=False)
88 elif ext == 'mpd':
89 formats_, subs_ = self._extract_mpd_formats_and_subtitles(
90 fmt_url, video_id, mpd_id='dash', fatal=False)
91 else:
92 formats.append({
93 'url': fmt_url,
94 'format_id': str_or_none(media.get('Id')),
95 })
96 continue
97 formats.extend(formats_)
98 self._merge_subtitles(subs_, target=subs)
99
100 if formats or not allow_none:
101 self._sort_formats(formats)
102 return formats, subs
103
104 def _real_extract(self, url):
105 video_id = self._match_id(url)
106
107 formats, subs = self._extract_formats_and_subs(video_id)
108
109 if formats:
110 return {
111 'id': video_id,
112 'formats': formats,
113 'subtitles': subs,
114 'title': self._generic_title(url),
115 }
116
117
118class ERTFlixIE(ERTFlixBaseIE):
119 IE_NAME = 'ertflix'
120 IE_DESC = 'ERTFLIX videos'
1685d460 121 _VALID_URL = r'https?://www\.ertflix\.gr/(?:[^/]+/)?(?:series|vod)/(?P<id>[a-z]{3}\.\d+)'
2d49720f
ZM
122 _TESTS = [{
123 'url': 'https://www.ertflix.gr/vod/vod.173258-aoratoi-ergates',
124 'md5': '6479d5e60fd7e520b07ba5411dcdd6e7',
125 'info_dict': {
126 'id': 'aoratoi-ergates',
127 'ext': 'mp4',
128 'title': 'md5:c1433d598fbba0211b0069021517f8b4',
129 'description': 'md5:01a64d113c31957eb7eb07719ab18ff4',
130 'thumbnail': r're:https?://.+\.jpg',
131 'episode_id': 'vod.173258',
132 'timestamp': 1639648800,
133 'upload_date': '20211216',
134 'duration': 3166,
135 'age_limit': 8,
136 },
137 }, {
138 'url': 'https://www.ertflix.gr/series/ser.3448-monogramma',
139 'info_dict': {
140 'id': 'ser.3448',
141 'age_limit': 8,
142 'description': 'Η εκπομπή σαράντα ετών που σημάδεψε τον πολιτισμό μας.',
143 'title': 'Μονόγραμμα',
144 },
145 'playlist_mincount': 64,
146 }, {
147 'url': 'https://www.ertflix.gr/series/ser.3448-monogramma?season=1',
148 'info_dict': {
149 'id': 'ser.3448',
150 'age_limit': 8,
151 'description': 'Η εκπομπή σαράντα ετών που σημάδεψε τον πολιτισμό μας.',
152 'title': 'Μονόγραμμα',
153 },
154 'playlist_count': 22,
155 }, {
156 'url': 'https://www.ertflix.gr/series/ser.3448-monogramma?season=1&season=2021%20-%202022',
157 'info_dict': {
158 'id': 'ser.3448',
159 'age_limit': 8,
160 'description': 'Η εκπομπή σαράντα ετών που σημάδεψε τον πολιτισμό μας.',
161 'title': 'Μονόγραμμα',
162 },
163 'playlist_mincount': 36,
164 }, {
165 'url': 'https://www.ertflix.gr/series/ser.164991-to-diktuo-1?season=1-9',
166 'info_dict': {
167 'id': 'ser.164991',
168 'age_limit': 8,
169 'description': 'Η πρώτη ελληνική εκπομπή με θεματολογία αποκλειστικά γύρω από το ίντερνετ.',
170 'title': 'Το δίκτυο',
171 },
172 'playlist_mincount': 9,
1685d460 173 }, {
174 'url': 'https://www.ertflix.gr/en/vod/vod.127652-ta-kalytera-mas-chronia-ep1-mia-volta-sto-feggari',
175 'only_matching': True,
2d49720f
ZM
176 }]
177
178 def _extract_episode(self, episode):
179 codename = try_get(episode, lambda x: x['Codename'], compat_str)
180 title = episode.get('Title')
181 description = clean_html(dict_get(episode, ('ShortDescription', 'TinyDescription', )))
182 if not codename or not title or not episode.get('HasPlayableStream', True):
183 return
184 thumbnail = next((
185 url_or_none(thumb.get('Url'))
186 for thumb in variadic(dict_get(episode, ('Images', 'Image')) or {})
187 if thumb.get('IsMain')),
188 None)
189 return {
190 '_type': 'url_transparent',
191 'thumbnail': thumbnail,
192 'id': codename,
193 'episode_id': episode.get('Id'),
194 'title': title,
195 'alt_title': episode.get('Subtitle'),
196 'description': description,
197 'timestamp': parse_iso8601(episode.get('PublishDate')),
198 'duration': episode.get('DurationSeconds'),
199 'age_limit': self._parse_age_rating(episode),
200 'url': 'ertflix:%s' % (codename, ),
201 }
202
203 @staticmethod
204 def _parse_age_rating(info_dict):
205 return parse_age_limit(
206 info_dict.get('AgeRating')
207 or (info_dict.get('IsAdultContent') and 18)
208 or (info_dict.get('IsKidsContent') and 0))
209
210 def _extract_series(self, video_id, season_titles=None, season_numbers=None):
211 media_info = self._call_api(video_id, method='Tile/GetSeriesDetails', id=video_id)
212
213 series = try_get(media_info, lambda x: x['Series'], dict) or {}
214 series_info = {
215 'age_limit': self._parse_age_rating(series),
216 'title': series.get('Title'),
217 'description': dict_get(series, ('ShortDescription', 'TinyDescription', )),
218 }
219 if season_numbers:
220 season_titles = season_titles or []
221 for season in try_get(series, lambda x: x['Seasons'], list) or []:
222 if season.get('SeasonNumber') in season_numbers and season.get('Title'):
223 season_titles.append(season['Title'])
224
225 def gen_episode(m_info, season_titles):
226 for episode_group in try_get(m_info, lambda x: x['EpisodeGroups'], list) or []:
227 if season_titles and episode_group.get('Title') not in season_titles:
228 continue
229 episodes = try_get(episode_group, lambda x: x['Episodes'], list)
230 if not episodes:
231 continue
232 season_info = {
233 'season': episode_group.get('Title'),
234 'season_number': int_or_none(episode_group.get('SeasonNumber')),
235 }
236 try:
237 episodes = [(int(ep['EpisodeNumber']), ep) for ep in episodes]
238 episodes.sort()
239 except (KeyError, ValueError):
240 episodes = enumerate(episodes, 1)
241 for n, episode in episodes:
242 info = self._extract_episode(episode)
243 if info is None:
244 continue
245 info['episode_number'] = n
246 info.update(season_info)
247 yield info
248
249 return self.playlist_result(
250 gen_episode(media_info, season_titles), playlist_id=video_id, **series_info)
251
252 def _real_extract(self, url):
253 video_id = self._match_id(url)
254 if video_id.startswith('ser.'):
255 param_season = parse_qs(url).get('season', [None])
256 param_season = [
257 (have_number, int_or_none(v) if have_number else str_or_none(v))
258 for have_number, v in
259 [(int_or_none(ps) is not None, ps) for ps in param_season]
260 if v is not None
261 ]
262 season_kwargs = {
263 k: [v for is_num, v in param_season if is_num is c] or None
264 for k, c in
265 [('season_titles', False), ('season_numbers', True)]
266 }
267 return self._extract_series(video_id, **season_kwargs)
268
269 return self._extract_episode(self._call_api_get_tiles(video_id))
270
271
272class ERTWebtvEmbedIE(InfoExtractor):
273 IE_NAME = 'ertwebtv:embed'
274 IE_DESC = 'ert.gr webtv embedded videos'
275 _BASE_PLAYER_URL_RE = re.escape('//www.ert.gr/webtv/live-uni/vod/dt-uni-vod.php')
276 _VALID_URL = rf'https?:{_BASE_PLAYER_URL_RE}\?([^#]+&)?f=(?P<id>[^#&]+)'
bfd973ec 277 _EMBED_REGEX = [rf'<iframe[^>]+?src=(?P<_q1>["\'])(?P<url>(?:https?:)?{_BASE_PLAYER_URL_RE}\?(?:(?!(?P=_q1)).)+)(?P=_q1)']
2d49720f
ZM
278
279 _TESTS = [{
280 'url': 'https://www.ert.gr/webtv/live-uni/vod/dt-uni-vod.php?f=trailers/E2251_TO_DIKTYO_E09_16-01_1900.mp4&bgimg=/photos/2022/1/to_diktio_ep09_i_istoria_tou_diadiktiou_stin_Ellada_1021x576.jpg',
281 'md5': 'f9e9900c25c26f4ecfbddbb4b6305854',
282 'info_dict': {
283 'id': 'trailers/E2251_TO_DIKTYO_E09_16-01_1900.mp4',
284 'title': 'md5:914f06a73cd8b62fbcd6fb90c636e497',
285 'ext': 'mp4',
286 'thumbnail': 'https://program.ert.gr/photos/2022/1/to_diktio_ep09_i_istoria_tou_diadiktiou_stin_Ellada_1021x576.jpg'
287 },
288 }]
289
2d49720f
ZM
290 def _real_extract(self, url):
291 video_id = self._match_id(url)
292 formats, subs = self._extract_m3u8_formats_and_subtitles(
293 f'https://mediastream.ert.gr/vodedge/_definst_/mp4:dvrorigin/{video_id}/playlist.m3u8',
294 video_id, 'mp4')
295 self._sort_formats(formats)
296 thumbnail_id = parse_qs(url).get('bgimg', [None])[0]
297 if thumbnail_id and not thumbnail_id.startswith('http'):
298 thumbnail_id = f'https://program.ert.gr{thumbnail_id}'
299 return {
300 'id': video_id,
301 'title': f'VOD - {video_id}',
302 'thumbnail': thumbnail_id,
303 'formats': formats,
304 'subtitles': subs,
305 }