]> jfr.im git - yt-dlp.git/blame - yt_dlp/extractor/nhk.py
[ie/NhkRadiru] Extract extended description (#9162)
[yt-dlp.git] / yt_dlp / extractor / nhk.py
CommitLineData
77cc7c6e 1import re
061d1cd9 2
298a120a 3from .common import InfoExtractor
77cc7c6e 4from ..utils import (
81c8b9bd 5 ExtractorError,
54579be4 6 clean_html,
7 get_element_by_class,
81c8b9bd 8 int_or_none,
9 join_nonempty,
77cc7c6e
LNO
10 parse_duration,
11 traverse_obj,
4392447d 12 try_call,
77cc7c6e
LNO
13 unescapeHTML,
14 unified_timestamp,
81c8b9bd 15 url_or_none,
8f0be90e 16 urljoin,
77cc7c6e 17)
298a120a
AN
18
19
29f7c58a 20class NhkBaseIE(InfoExtractor):
6d1b3489 21 _API_URL_TEMPLATE = 'https://nwapi.nhk.jp/nhkworld/%sod%slist/v7b/%s/%s/%s/all%s.json'
29f7c58a 22 _BASE_URL_REGEX = r'https?://www3\.nhk\.or\.jp/nhkworld/(?P<lang>[a-z]{2})/ondemand'
23 _TYPE_REGEX = r'/(?P<type>video|audio)/'
298a120a 24
29f7c58a 25 def _call_api(self, m_id, lang, is_video, is_episode, is_clip):
26 return self._download_json(
27 self._API_URL_TEMPLATE % (
28 'v' if is_video else 'r',
29 'clip' if is_clip else 'esd',
30 'episode' if is_episode else 'program',
31 m_id, lang, '/all' if is_video else ''),
32 m_id, query={'apikey': 'EJfK8jdS57GqlupFgAfAAwr573q01y6k'})['data']['episodes'] or []
33
e831c80e 34 def _get_api_info(self, refresh=True):
35 if not refresh:
36 return self.cache.load('nhk', 'api_info')
37
38 self.cache.store('nhk', 'api_info', {})
39 movie_player_js = self._download_webpage(
40 'https://movie-a.nhk.or.jp/world/player/js/movie-player.js', None,
41 note='Downloading stream API information')
42 api_info = {
43 'url': self._search_regex(
44 r'prod:[^;]+\bapiUrl:\s*[\'"]([^\'"]+)[\'"]', movie_player_js, None, 'stream API url'),
45 'token': self._search_regex(
46 r'prod:[^;]+\btoken:\s*[\'"]([^\'"]+)[\'"]', movie_player_js, None, 'stream API token'),
47 }
48 self.cache.store('nhk', 'api_info', api_info)
49 return api_info
50
54579be4 51 def _extract_stream_info(self, vod_id):
e831c80e 52 for refresh in (False, True):
53 api_info = self._get_api_info(refresh)
54 if not api_info:
55 continue
56
57 api_url = api_info.pop('url')
54579be4 58 meta = traverse_obj(
e831c80e 59 self._download_json(
60 api_url, vod_id, 'Downloading stream url info', fatal=False, query={
61 **api_info,
62 'type': 'json',
63 'optional_id': vod_id,
64 'active_flg': 1,
54579be4 65 }), ('meta', 0))
66 stream_url = traverse_obj(
67 meta, ('movie_url', ('mb_auto', 'auto_sp', 'auto_pc'), {url_or_none}), get_all=False)
e831c80e 68
54579be4 69 if stream_url:
70 formats, subtitles = self._extract_m3u8_formats_and_subtitles(stream_url, vod_id)
71 return {
72 **traverse_obj(meta, {
73 'duration': ('duration', {int_or_none}),
74 'timestamp': ('publication_date', {unified_timestamp}),
75 'release_timestamp': ('insert_date', {unified_timestamp}),
76 'modified_timestamp': ('update_date', {unified_timestamp}),
77 }),
78 'formats': formats,
79 'subtitles': subtitles,
80 }
e831c80e 81 raise ExtractorError('Unable to extract stream url')
82
29f7c58a 83 def _extract_episode_info(self, url, episode=None):
84 fetch_episode = episode is None
4de94b9e 85 lang, m_type, episode_id = NhkVodIE._match_valid_url(url).group('lang', 'type', 'id')
86 is_video = m_type == 'video'
87
88 if is_video:
061d1cd9 89 episode_id = episode_id[:4] + '-' + episode_id[4:]
f9b373af 90
29f7c58a 91 if fetch_episode:
92 episode = self._call_api(
93 episode_id, lang, is_video, True, episode_id[:4] == '9999')[0]
45396dd2 94
061d1cd9 95 def get_clean_field(key):
54579be4 96 return clean_html(episode.get(key + '_clean') or episode.get(key))
45396dd2 97
54579be4 98 title = get_clean_field('sub_title')
061d1cd9 99 series = get_clean_field('title')
45396dd2 100
061d1cd9
RA
101 thumbnails = []
102 for s, w, h in [('', 640, 360), ('_l', 1280, 720)]:
103 img_path = episode.get('image' + s)
104 if not img_path:
105 continue
106 thumbnails.append({
107 'id': '%dp' % h,
108 'height': h,
109 'width': w,
110 'url': 'https://www3.nhk.or.jp' + img_path,
111 })
298a120a 112
54579be4 113 episode_name = title
114 if series and title:
115 title = f'{series} - {title}'
116 elif series and not title:
117 title = series
118 series = None
119 episode_name = None
120 else: # title, no series
121 episode_name = None
122
061d1cd9
RA
123 info = {
124 'id': episode_id + '-' + lang,
54579be4 125 'title': title,
061d1cd9
RA
126 'description': get_clean_field('description'),
127 'thumbnails': thumbnails,
f9b373af 128 'series': series,
54579be4 129 'episode': episode_name,
f9b373af 130 }
54579be4 131
061d1cd9 132 if is_video:
29f7c58a 133 vod_id = episode['vod_id']
061d1cd9 134 info.update({
54579be4 135 **self._extract_stream_info(vod_id),
29f7c58a 136 'id': vod_id,
061d1cd9 137 })
e831c80e 138
061d1cd9 139 else:
29f7c58a 140 if fetch_episode:
141 audio_path = episode['audio']['audio']
142 info['formats'] = self._extract_m3u8_formats(
143 'https://nhkworld-vh.akamaihd.net/i%s/master.m3u8' % audio_path,
144 episode_id, 'm4a', entry_protocol='m3u8_native',
145 m3u8_id='hls', fatal=False)
146 for f in info['formats']:
147 f['language'] = lang
148 else:
149 info.update({
150 '_type': 'url_transparent',
151 'ie_key': NhkVodIE.ie_key(),
152 'url': url,
153 })
061d1cd9 154 return info
29f7c58a 155
156
157class NhkVodIE(NhkBaseIE):
6d1b3489 158 # the 7-character IDs can have alphabetic chars too: assume [a-z] rather than just [a-f], eg
4de94b9e 159 _VALID_URL = [rf'{NhkBaseIE._BASE_URL_REGEX}/(?P<type>video)/(?P<id>[0-9a-z]+)',
160 rf'{NhkBaseIE._BASE_URL_REGEX}/(?P<type>audio)/(?P<id>[^/?#]+?-\d{{8}}-[0-9a-z]+)']
29f7c58a 161 # Content available only for a limited period of time. Visit
162 # https://www3.nhk.or.jp/nhkworld/en/ondemand/ for working samples.
163 _TESTS = [{
4de94b9e 164 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/2049126/',
f41b949a 165 'info_dict': {
4de94b9e 166 'id': 'nw_vod_v_en_2049_126_20230413233000_01_1681398302',
f41b949a 167 'ext': 'mp4',
4de94b9e 168 'title': 'Japan Railway Journal - The Tohoku Shinkansen: Full Speed Ahead',
169 'description': 'md5:49f7c5b206e03868a2fdf0d0814b92f6',
170 'thumbnail': 'md5:51bcef4a21936e7fea1ff4e06353f463',
171 'episode': 'The Tohoku Shinkansen: Full Speed Ahead',
172 'series': 'Japan Railway Journal',
54579be4 173 'modified_timestamp': 1694243656,
174 'timestamp': 1681428600,
175 'release_timestamp': 1693883728,
176 'duration': 1679,
177 'upload_date': '20230413',
178 'modified_date': '20230909',
179 'release_date': '20230905',
180
f41b949a
DR
181 },
182 }, {
29f7c58a 183 # video clip
184 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/9999011/',
4de94b9e 185 'md5': '153c3016dfd252ba09726588149cf0e7',
29f7c58a 186 'info_dict': {
4de94b9e 187 'id': 'lpZXIwaDE6_Z-976CPsFdxyICyWUzlT5',
29f7c58a 188 'ext': 'mp4',
4de94b9e 189 'title': 'Dining with the Chef - Chef Saito\'s Family recipe: MENCHI-KATSU',
29f7c58a 190 'description': 'md5:5aee4a9f9d81c26281862382103b0ea5',
4de94b9e 191 'thumbnail': 'md5:d6a4d9b6e9be90aaadda0bcce89631ed',
f41b949a
DR
192 'series': 'Dining with the Chef',
193 'episode': 'Chef Saito\'s Family recipe: MENCHI-KATSU',
54579be4 194 'duration': 148,
195 'upload_date': '20190816',
196 'release_date': '20230902',
197 'release_timestamp': 1693619292,
198 'modified_timestamp': 1694168033,
199 'modified_date': '20230908',
200 'timestamp': 1565997540,
29f7c58a 201 },
202 }, {
4de94b9e 203 # radio
204 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/livinginjapan-20231001-1/',
29f7c58a 205 'info_dict': {
4de94b9e 206 'id': 'livinginjapan-20231001-1-en',
29f7c58a 207 'ext': 'm4a',
4de94b9e 208 'title': 'Living in Japan - Tips for Travelers to Japan / Ramen Vending Machines',
209 'series': 'Living in Japan',
54579be4 210 'description': 'md5:0a0e2077d8f07a03071e990a6f51bfab',
4de94b9e 211 'thumbnail': 'md5:960622fb6e06054a4a1a0c97ea752545',
212 'episode': 'Tips for Travelers to Japan / Ramen Vending Machines'
29f7c58a 213 },
29f7c58a 214 }, {
215 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/2015173/',
216 'only_matching': True,
217 }, {
218 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/plugin-20190404-1/',
219 'only_matching': True,
220 }, {
221 'url': 'https://www3.nhk.or.jp/nhkworld/fr/ondemand/audio/plugin-20190404-1/',
222 'only_matching': True,
223 }, {
224 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/j_art-20150903-1/',
225 'only_matching': True,
6d1b3489 226 }, {
227 # video, alphabetic character in ID #29670
228 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/9999a34/',
6d1b3489 229 'info_dict': {
230 'id': 'qfjay6cg',
231 'ext': 'mp4',
232 'title': 'DESIGN TALKS plus - Fishermen’s Finery',
233 'description': 'md5:8a8f958aaafb0d7cb59d38de53f1e448',
234 'thumbnail': r're:^https?:/(/[a-z0-9.-]+)+\.jpg\?w=1920&h=1080$',
235 'upload_date': '20210615',
236 'timestamp': 1623722008,
f41b949a
DR
237 },
238 'skip': '404 Not Found',
4de94b9e 239 }, {
240 # japanese-language, longer id than english
241 'url': 'https://www3.nhk.or.jp/nhkworld/ja/ondemand/video/0020271111/',
242 'info_dict': {
243 'id': 'nw_ja_v_jvod_ohayou_20231008',
244 'ext': 'mp4',
245 'title': 'おはよう日本(7時台) - 10月8日放送',
246 'series': 'おはよう日本(7時台)',
247 'episode': '10月8日放送',
248 'thumbnail': 'md5:d733b1c8e965ab68fb02b2d347d0e9b4',
249 'description': 'md5:9c1d6cbeadb827b955b20e99ab920ff0',
250 },
251 'skip': 'expires 2023-10-15',
54579be4 252 }, {
253 # a one-off (single-episode series). title from the api is just '<p></p>'
254 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/3004952/',
255 'info_dict': {
256 'id': 'nw_vod_v_en_3004_952_20230723091000_01_1690074552',
257 'ext': 'mp4',
258 'title': 'Barakan Discovers AMAMI OSHIMA: Isson\'s Treasure Island',
259 'description': 'md5:5db620c46a0698451cc59add8816b797',
260 'thumbnail': 'md5:67d9ff28009ba379bfa85ad1aaa0e2bd',
261 'release_date': '20230905',
262 'timestamp': 1690103400,
263 'duration': 2939,
264 'release_timestamp': 1693898699,
265 'modified_timestamp': 1698057495,
266 'modified_date': '20231023',
267 'upload_date': '20230723',
268 },
29f7c58a 269 }]
270
271 def _real_extract(self, url):
272 return self._extract_episode_info(url)
273
274
275class NhkVodProgramIE(NhkBaseIE):
4de94b9e 276 _VALID_URL = rf'{NhkBaseIE._BASE_URL_REGEX}/program{NhkBaseIE._TYPE_REGEX}(?P<id>\w+)(?:.+?\btype=(?P<episode_type>clip|(?:radio|tv)Episode))?'
29f7c58a 277 _TESTS = [{
278 # video program episodes
f41b949a
DR
279 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/program/video/sumo',
280 'info_dict': {
281 'id': 'sumo',
282 'title': 'GRAND SUMO Highlights',
54579be4 283 'description': 'md5:fc20d02dc6ce85e4b72e0273aa52fdbf',
f41b949a 284 },
54579be4 285 'playlist_mincount': 0,
f41b949a 286 }, {
29f7c58a 287 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/program/video/japanrailway',
288 'info_dict': {
289 'id': 'japanrailway',
290 'title': 'Japan Railway Journal',
54579be4 291 'description': 'md5:ea39d93af7d05835baadf10d1aae0e3f',
29f7c58a 292 },
f41b949a 293 'playlist_mincount': 12,
29f7c58a 294 }, {
295 # video program clips
296 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/program/video/japanrailway/?type=clip',
297 'info_dict': {
298 'id': 'japanrailway',
299 'title': 'Japan Railway Journal',
54579be4 300 'description': 'md5:ea39d93af7d05835baadf10d1aae0e3f',
29f7c58a 301 },
302 'playlist_mincount': 5,
303 }, {
304 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/program/video/10yearshayaomiyazaki/',
305 'only_matching': True,
306 }, {
307 # audio program
308 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/program/audio/listener/',
309 'only_matching': True,
310 }]
311
312 def _real_extract(self, url):
4de94b9e 313 lang, m_type, program_id, episode_type = self._match_valid_url(url).group('lang', 'type', 'id', 'episode_type')
29f7c58a 314 episodes = self._call_api(
315 program_id, lang, m_type == 'video', False, episode_type == 'clip')
316
317 entries = []
318 for episode in episodes:
319 episode_path = episode.get('url')
320 if not episode_path:
321 continue
322 entries.append(self._extract_episode_info(
323 urljoin(url, episode_path), episode))
324
54579be4 325 html = self._download_webpage(url, program_id)
326 program_title = clean_html(get_element_by_class('p-programDetail__title', html))
327 program_description = clean_html(get_element_by_class('p-programDetail__text', html))
29f7c58a 328
54579be4 329 return self.playlist_result(entries, program_id, program_title, program_description)
77cc7c6e
LNO
330
331
332class NhkForSchoolBangumiIE(InfoExtractor):
333 _VALID_URL = r'https?://www2\.nhk\.or\.jp/school/movie/(?P<type>bangumi|clip)\.cgi\?das_id=(?P<id>[a-zA-Z0-9_-]+)'
334 _TESTS = [{
335 'url': 'https://www2.nhk.or.jp/school/movie/bangumi.cgi?das_id=D0005150191_00000',
336 'info_dict': {
337 'id': 'D0005150191_00003',
338 'title': 'にている かな',
339 'duration': 599.999,
340 'timestamp': 1396414800,
341
342 'upload_date': '20140402',
343 'ext': 'mp4',
344
345 'chapters': 'count:12'
346 },
347 'params': {
348 # m3u8 download
349 'skip_download': True,
350 },
351 }]
352
353 def _real_extract(self, url):
354 program_type, video_id = self._match_valid_url(url).groups()
355
356 webpage = self._download_webpage(
357 f'https://www2.nhk.or.jp/school/movie/{program_type}.cgi?das_id={video_id}', video_id)
358
359 # searches all variables
360 base_values = {g.group(1): g.group(2) for g in re.finditer(r'var\s+([a-zA-Z_]+)\s*=\s*"([^"]+?)";', webpage)}
361 # and programObj values too
362 program_values = {g.group(1): g.group(3) for g in re.finditer(r'(?:program|clip)Obj\.([a-zA-Z_]+)\s*=\s*(["\'])([^"]+?)\2;', webpage)}
363 # extract all chapters
364 chapter_durations = [parse_duration(g.group(1)) for g in re.finditer(r'chapterTime\.push\(\'([0-9:]+?)\'\);', webpage)]
365 chapter_titles = [' '.join([g.group(1) or '', unescapeHTML(g.group(2))]).strip() for g in re.finditer(r'<div class="cpTitle"><span>(scene\s*\d+)?</span>([^<]+?)</div>', webpage)]
366
367 # this is how player_core.js is actually doing (!)
368 version = base_values.get('r_version') or program_values.get('version')
369 if version:
370 video_id = f'{video_id.split("_")[0]}_{version}'
371
372 formats = self._extract_m3u8_formats(
373 f'https://nhks-vh.akamaihd.net/i/das/{video_id[0:8]}/{video_id}_V_000.f4v/master.m3u8',
374 video_id, ext='mp4', m3u8_id='hls')
77cc7c6e
LNO
375
376 duration = parse_duration(base_values.get('r_duration'))
377
378 chapters = None
379 if chapter_durations and chapter_titles and len(chapter_durations) == len(chapter_titles):
380 start_time = chapter_durations
381 end_time = chapter_durations[1:] + [duration]
382 chapters = [{
383 'start_time': s,
384 'end_time': e,
385 'title': t,
386 } for s, e, t in zip(start_time, end_time, chapter_titles)]
387
388 return {
389 'id': video_id,
390 'title': program_values.get('name'),
391 'duration': parse_duration(base_values.get('r_duration')),
392 'timestamp': unified_timestamp(base_values['r_upload']),
393 'formats': formats,
394 'chapters': chapters,
395 }
396
397
398class NhkForSchoolSubjectIE(InfoExtractor):
399 IE_DESC = 'Portal page for each school subjects, like Japanese (kokugo, 国語) or math (sansuu/suugaku or 算数・数学)'
400 KNOWN_SUBJECTS = (
401 'rika', 'syakai', 'kokugo',
402 'sansuu', 'seikatsu', 'doutoku',
403 'ongaku', 'taiiku', 'zukou',
404 'gijutsu', 'katei', 'sougou',
405 'eigo', 'tokkatsu',
406 'tokushi', 'sonota',
407 )
408 _VALID_URL = r'https?://www\.nhk\.or\.jp/school/(?P<id>%s)/?(?:[\?#].*)?$' % '|'.join(re.escape(s) for s in KNOWN_SUBJECTS)
409
410 _TESTS = [{
411 'url': 'https://www.nhk.or.jp/school/sougou/',
412 'info_dict': {
413 'id': 'sougou',
414 'title': '総合的な学習の時間',
415 },
416 'playlist_mincount': 16,
417 }, {
418 'url': 'https://www.nhk.or.jp/school/rika/',
419 'info_dict': {
420 'id': 'rika',
421 'title': '理科',
422 },
423 'playlist_mincount': 15,
424 }]
425
426 def _real_extract(self, url):
427 subject_id = self._match_id(url)
428 webpage = self._download_webpage(url, subject_id)
429
430 return self.playlist_from_matches(
431 re.finditer(rf'href="((?:https?://www\.nhk\.or\.jp)?/school/{re.escape(subject_id)}/[^/]+/)"', webpage),
432 subject_id,
433 self._html_search_regex(r'(?s)<span\s+class="subjectName">\s*<img\s*[^<]+>\s*([^<]+?)</span>', webpage, 'title', fatal=False),
434 lambda g: urljoin(url, g.group(1)))
435
436
437class NhkForSchoolProgramListIE(InfoExtractor):
438 _VALID_URL = r'https?://www\.nhk\.or\.jp/school/(?P<id>(?:%s)/[a-zA-Z0-9_-]+)' % (
439 '|'.join(re.escape(s) for s in NhkForSchoolSubjectIE.KNOWN_SUBJECTS)
440 )
441 _TESTS = [{
442 'url': 'https://www.nhk.or.jp/school/sougou/q/',
443 'info_dict': {
444 'id': 'sougou/q',
445 'title': 'Q~こどものための哲学',
446 },
447 'playlist_mincount': 20,
448 }]
449
450 def _real_extract(self, url):
451 program_id = self._match_id(url)
452
453 webpage = self._download_webpage(f'https://www.nhk.or.jp/school/{program_id}/', program_id)
454
62b8dac4 455 title = (self._generic_title('', webpage)
04f3fd2c 456 or self._html_search_regex(r'<h3>([^<]+?)とは?\s*</h3>', webpage, 'title', fatal=False))
77cc7c6e
LNO
457 title = re.sub(r'\s*\|\s*NHK\s+for\s+School\s*$', '', title) if title else None
458 description = self._html_search_regex(
459 r'(?s)<div\s+class="programDetail\s*">\s*<p>[^<]+</p>',
460 webpage, 'description', fatal=False, group=0)
461
462 bangumi_list = self._download_json(
463 f'https://www.nhk.or.jp/school/{program_id}/meta/program.json', program_id)
464 # they're always bangumi
465 bangumis = [
466 self.url_result(f'https://www2.nhk.or.jp/school/movie/bangumi.cgi?das_id={x}')
467 for x in traverse_obj(bangumi_list, ('part', ..., 'part-video-dasid')) or []]
468
469 return self.playlist_result(bangumis, program_id, title, description)
8f0be90e 470
471
472class NhkRadiruIE(InfoExtractor):
473 _GEO_COUNTRIES = ['JP']
474 IE_DESC = 'NHK らじる (Radiru/Rajiru)'
475 _VALID_URL = r'https?://www\.nhk\.or\.jp/radio/(?:player/ondemand|ondemand/detail)\.html\?p=(?P<site>[\da-zA-Z]+)_(?P<corner>[\da-zA-Z]+)(?:_(?P<headline>[\da-zA-Z]+))?'
476 _TESTS = [{
4392447d 477 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=0449_01_3926210',
478 'skip': 'Episode expired on 2024-02-24',
8f0be90e 479 'info_dict': {
4392447d 480 'title': 'ジャズ・トゥナイト シリーズJAZZジャイアンツ 56 ジョニー・ホッジス',
481 'id': '0449_01_3926210',
8f0be90e 482 'ext': 'm4a',
8f0be90e 483 'series': 'ジャズ・トゥナイト',
4392447d 484 'uploader': 'NHK-FM',
485 'channel': 'NHK-FM',
8f0be90e 486 'thumbnail': 'https://www.nhk.or.jp/prog/img/449/g449.jpg',
4392447d 487 'release_date': '20240217',
488 'description': 'md5:a456ee8e5e59e6dd2a7d32e62386e811',
489 'timestamp': 1708185600,
490 'release_timestamp': 1708178400,
491 'upload_date': '20240217',
8f0be90e 492 },
493 }, {
494 # playlist, airs every weekday so it should _hopefully_ be okay forever
495 'url': 'https://www.nhk.or.jp/radio/ondemand/detail.html?p=0458_01',
496 'info_dict': {
497 'id': '0458_01',
498 'title': 'ベストオブクラシック',
499 'description': '世界中の上質な演奏会をじっくり堪能する本格派クラシック番組。',
500 'channel': 'NHK-FM',
54579be4 501 'uploader': 'NHK-FM',
8f0be90e 502 'thumbnail': 'https://www.nhk.or.jp/prog/img/458/g458.jpg',
503 },
504 'playlist_mincount': 3,
505 }, {
506 # one with letters in the id
507 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=F300_06_3738470',
508 'note': 'Expires on 2024-03-31',
509 'info_dict': {
510 'id': 'F300_06_3738470',
511 'ext': 'm4a',
512 'title': '有島武郎「一房のぶどう」',
513 'description': '朗読:川野一宇(ラジオ深夜便アンカー)\r\n\r\n(2016年12月8日放送「ラジオ深夜便『アンカー朗読シリーズ』」より)',
514 'channel': 'NHKラジオ第1、NHK-FM',
54579be4 515 'uploader': 'NHKラジオ第1、NHK-FM',
8f0be90e 516 'timestamp': 1635757200,
517 'thumbnail': 'https://www.nhk.or.jp/radioondemand/json/F300/img/corner/box_109_thumbnail.jpg',
518 'release_date': '20161207',
519 'series': 'らじる文庫 by ラジオ深夜便 ',
520 'release_timestamp': 1481126700,
521 'upload_date': '20211101',
4392447d 522 },
523 'expected_warnings': ['Unable to download JSON metadata', 'Failed to get extended description'],
8f0be90e 524 }, {
525 # news
526 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=F261_01_3855109',
527 'skip': 'Expires on 2023-04-17',
528 'info_dict': {
529 'id': 'F261_01_3855109',
530 'ext': 'm4a',
531 'channel': 'NHKラジオ第1',
54579be4 532 'uploader': 'NHKラジオ第1',
8f0be90e 533 'timestamp': 1681635900,
534 'release_date': '20230416',
535 'series': 'NHKラジオニュース',
536 'title': '午後6時のNHKニュース',
537 'thumbnail': 'https://www.nhk.or.jp/radioondemand/json/F261/img/RADIONEWS_640.jpg',
538 'upload_date': '20230416',
539 'release_timestamp': 1681635600,
540 },
541 }]
542
4392447d 543 _API_URL_TMPL = None
544
545 def _extract_extended_description(self, episode_id, episode):
546 service, _, area = traverse_obj(episode, ('aa_vinfo2', {str}, {lambda x: (x or '').partition(',')}))
547 aa_vinfo3 = traverse_obj(episode, ('aa_vinfo3', {str}))
548 detail_url = try_call(
549 lambda: self._API_URL_TMPL.format(service=service, area=area, dateid=aa_vinfo3))
550 if not detail_url:
551 return
552
553 full_meta = traverse_obj(
554 self._download_json(detail_url, episode_id, 'Downloading extended metadata', fatal=False),
555 ('list', service, 0, {dict})) or {}
556 return join_nonempty('subtitle', 'content', 'act', 'music', delim='\n\n', from_dict=full_meta)
557
8f0be90e 558 def _extract_episode_info(self, headline, programme_id, series_meta):
559 episode_id = f'{programme_id}_{headline["headline_id"]}'
560 episode = traverse_obj(headline, ('file_list', 0, {dict}))
4392447d 561 description = self._extract_extended_description(episode_id, episode)
562 if not description:
563 self.report_warning('Failed to get extended description, falling back to summary')
564 description = traverse_obj(episode, ('file_title_sub', {str}))
8f0be90e 565
566 return {
567 **series_meta,
568 'id': episode_id,
569 'formats': self._extract_m3u8_formats(episode.get('file_name'), episode_id, fatal=False),
570 'container': 'm4a_dash', # force fixup, AAC-only HLS
571 'was_live': True,
572 'series': series_meta.get('title'),
573 'thumbnail': url_or_none(headline.get('headline_image')) or series_meta.get('thumbnail'),
4392447d 574 'description': description,
8f0be90e 575 **traverse_obj(episode, {
576 'title': 'file_title',
8f0be90e 577 'timestamp': ('open_time', {unified_timestamp}),
578 'release_timestamp': ('aa_vinfo4', {lambda x: x.split('_')[0]}, {unified_timestamp}),
579 }),
580 }
581
4392447d 582 def _real_initialize(self):
583 if self._API_URL_TMPL:
584 return
585 api_config = self._download_xml(
586 'https://www.nhk.or.jp/radio/config/config_web.xml', None, 'Downloading API config', fatal=False)
587 NhkRadiruIE._API_URL_TMPL = try_call(lambda: f'https:{api_config.find(".//url_program_detail").text}')
588
8f0be90e 589 def _real_extract(self, url):
590 site_id, corner_id, headline_id = self._match_valid_url(url).group('site', 'corner', 'headline')
591 programme_id = f'{site_id}_{corner_id}'
592
593 if site_id == 'F261':
594 json_url = 'https://www.nhk.or.jp/s-media/news/news-site/list/v1/all.json'
595 else:
596 json_url = f'https://www.nhk.or.jp/radioondemand/json/{site_id}/bangumi_{programme_id}.json'
597
598 meta = self._download_json(json_url, programme_id)['main']
599
600 series_meta = traverse_obj(meta, {
601 'title': 'program_name',
602 'channel': 'media_name',
54579be4 603 'uploader': 'media_name',
8f0be90e 604 'thumbnail': (('thumbnail_c', 'thumbnail_p'), {url_or_none}),
605 }, get_all=False)
606
607 if headline_id:
608 return self._extract_episode_info(
609 traverse_obj(meta, (
610 'detail_list', lambda _, v: v['headline_id'] == headline_id), get_all=False),
611 programme_id, series_meta)
612
613 def entries():
614 for headline in traverse_obj(meta, ('detail_list', ..., {dict})):
615 yield self._extract_episode_info(headline, programme_id, series_meta)
616
617 return self.playlist_result(
618 entries(), programme_id, playlist_description=meta.get('site_detail'), **series_meta)
619
620
621class NhkRadioNewsPageIE(InfoExtractor):
622 _VALID_URL = r'https?://www\.nhk\.or\.jp/radionews/?(?:$|[?#])'
623 _TESTS = [{
624 # airs daily, on-the-hour most hours
625 'url': 'https://www.nhk.or.jp/radionews/',
626 'playlist_mincount': 5,
627 'info_dict': {
628 'id': 'F261_01',
629 'thumbnail': 'https://www.nhk.or.jp/radioondemand/json/F261/img/RADIONEWS_640.jpg',
630 'description': 'md5:bf2c5b397e44bc7eb26de98d8f15d79d',
631 'channel': 'NHKラジオ第1',
54579be4 632 'uploader': 'NHKラジオ第1',
8f0be90e 633 'title': 'NHKラジオニュース',
634 }
635 }]
636
637 def _real_extract(self, url):
638 return self.url_result('https://www.nhk.or.jp/radio/ondemand/detail.html?p=F261_01', NhkRadiruIE)
81c8b9bd 639
640
641class NhkRadiruLiveIE(InfoExtractor):
642 _GEO_COUNTRIES = ['JP']
643 _VALID_URL = r'https?://www\.nhk\.or\.jp/radio/player/\?ch=(?P<id>r[12]|fm)'
644 _TESTS = [{
645 # radio 1, no area specified
646 'url': 'https://www.nhk.or.jp/radio/player/?ch=r1',
647 'info_dict': {
648 'id': 'r1-tokyo',
649 'title': 're:^NHKネットラジオ第1 東京.+$',
650 'ext': 'm4a',
651 'thumbnail': 'https://www.nhk.or.jp/common/img/media/r1-200x200.png',
652 'live_status': 'is_live',
653 },
654 }, {
655 # radio 2, area specified
656 # (the area doesnt actually matter, r2 is national)
657 'url': 'https://www.nhk.or.jp/radio/player/?ch=r2',
658 'params': {'extractor_args': {'nhkradirulive': {'area': ['fukuoka']}}},
659 'info_dict': {
660 'id': 'r2-fukuoka',
661 'title': 're:^NHKネットラジオ第2 福岡.+$',
662 'ext': 'm4a',
663 'thumbnail': 'https://www.nhk.or.jp/common/img/media/r2-200x200.png',
664 'live_status': 'is_live',
665 },
666 }, {
667 # fm, area specified
668 'url': 'https://www.nhk.or.jp/radio/player/?ch=fm',
669 'params': {'extractor_args': {'nhkradirulive': {'area': ['sapporo']}}},
670 'info_dict': {
671 'id': 'fm-sapporo',
672 'title': 're:^NHKネットラジオFM 札幌.+$',
673 'ext': 'm4a',
674 'thumbnail': 'https://www.nhk.or.jp/common/img/media/fm-200x200.png',
675 'live_status': 'is_live',
676 }
677 }]
678
679 _NOA_STATION_IDS = {'r1': 'n1', 'r2': 'n2', 'fm': 'n3'}
680
681 def _real_extract(self, url):
682 station = self._match_id(url)
683 area = self._configuration_arg('area', ['tokyo'])[0]
684
685 config = self._download_xml(
686 'https://www.nhk.or.jp/radio/config/config_web.xml', station, 'Downloading area information')
687 data = config.find(f'.//data//area[.="{area}"]/..')
688
689 if not data:
690 raise ExtractorError('Invalid area. Valid areas are: %s' % ', '.join(
691 [i.text for i in config.findall('.//data//area')]), expected=True)
692
693 noa_info = self._download_json(
694 f'https:{config.find(".//url_program_noa").text}'.format(area=data.find('areakey').text),
5af1f197 695 station, note=f'Downloading {area} station metadata', fatal=False)
81c8b9bd 696 present_info = traverse_obj(noa_info, ('nowonair_list', self._NOA_STATION_IDS.get(station), 'present'))
697
698 return {
699 'title': ' '.join(traverse_obj(present_info, (('service', 'area',), 'name', {str}))),
700 'id': join_nonempty(station, area),
701 'thumbnails': traverse_obj(present_info, ('service', 'images', ..., {
702 'url': 'url',
703 'width': ('width', {int_or_none}),
704 'height': ('height', {int_or_none}),
705 })),
706 'formats': self._extract_m3u8_formats(data.find(f'{station}hls').text, station),
707 'is_live': True,
708 }