nhk.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. import re
  2. from .common import InfoExtractor
  3. from ..utils import (
  4. ExtractorError,
  5. clean_html,
  6. filter_dict,
  7. get_element_by_class,
  8. int_or_none,
  9. join_nonempty,
  10. parse_duration,
  11. remove_end,
  12. traverse_obj,
  13. try_call,
  14. unescapeHTML,
  15. unified_timestamp,
  16. url_or_none,
  17. urljoin,
  18. )
  19. class NhkBaseIE(InfoExtractor):
  20. _API_URL_TEMPLATE = 'https://nwapi.nhk.jp/nhkworld/%sod%slist/v7b/%s/%s/%s/all%s.json'
  21. _BASE_URL_REGEX = r'https?://www3\.nhk\.or\.jp/nhkworld/(?P<lang>[a-z]{2})/'
  22. def _call_api(self, m_id, lang, is_video, is_episode, is_clip):
  23. return self._download_json(
  24. self._API_URL_TEMPLATE % (
  25. 'v' if is_video else 'r',
  26. 'clip' if is_clip else 'esd',
  27. 'episode' if is_episode else 'program',
  28. m_id, lang, '/all' if is_video else ''),
  29. m_id, query={'apikey': 'EJfK8jdS57GqlupFgAfAAwr573q01y6k'})['data']['episodes'] or []
  30. def _get_api_info(self, refresh=True):
  31. if not refresh:
  32. return self.cache.load('nhk', 'api_info')
  33. self.cache.store('nhk', 'api_info', {})
  34. movie_player_js = self._download_webpage(
  35. 'https://movie-a.nhk.or.jp/world/player/js/movie-player.js', None,
  36. note='Downloading stream API information')
  37. api_info = {
  38. 'url': self._search_regex(
  39. r'prod:[^;]+\bapiUrl:\s*[\'"]([^\'"]+)[\'"]', movie_player_js, None, 'stream API url'),
  40. 'token': self._search_regex(
  41. r'prod:[^;]+\btoken:\s*[\'"]([^\'"]+)[\'"]', movie_player_js, None, 'stream API token'),
  42. }
  43. self.cache.store('nhk', 'api_info', api_info)
  44. return api_info
  45. def _extract_stream_info(self, vod_id):
  46. for refresh in (False, True):
  47. api_info = self._get_api_info(refresh)
  48. if not api_info:
  49. continue
  50. api_url = api_info.pop('url')
  51. meta = traverse_obj(
  52. self._download_json(
  53. api_url, vod_id, 'Downloading stream url info', fatal=False, query={
  54. **api_info,
  55. 'type': 'json',
  56. 'optional_id': vod_id,
  57. 'active_flg': 1,
  58. }), ('meta', 0))
  59. stream_url = traverse_obj(
  60. meta, ('movie_url', ('mb_auto', 'auto_sp', 'auto_pc'), {url_or_none}), get_all=False)
  61. if stream_url:
  62. formats, subtitles = self._extract_m3u8_formats_and_subtitles(stream_url, vod_id)
  63. return {
  64. **traverse_obj(meta, {
  65. 'duration': ('duration', {int_or_none}),
  66. 'timestamp': ('publication_date', {unified_timestamp}),
  67. 'release_timestamp': ('insert_date', {unified_timestamp}),
  68. 'modified_timestamp': ('update_date', {unified_timestamp}),
  69. }),
  70. 'formats': formats,
  71. 'subtitles': subtitles,
  72. }
  73. raise ExtractorError('Unable to extract stream url')
  74. def _extract_episode_info(self, url, episode=None):
  75. fetch_episode = episode is None
  76. lang, m_type, episode_id = NhkVodIE._match_valid_url(url).group('lang', 'type', 'id')
  77. is_video = m_type != 'audio'
  78. if is_video:
  79. episode_id = episode_id[:4] + '-' + episode_id[4:]
  80. if fetch_episode:
  81. episode = self._call_api(
  82. episode_id, lang, is_video, True, episode_id[:4] == '9999')[0]
  83. def get_clean_field(key):
  84. return clean_html(episode.get(key + '_clean') or episode.get(key))
  85. title = get_clean_field('sub_title')
  86. series = get_clean_field('title')
  87. thumbnails = []
  88. for s, w, h in [('', 640, 360), ('_l', 1280, 720)]:
  89. img_path = episode.get('image' + s)
  90. if not img_path:
  91. continue
  92. thumbnails.append({
  93. 'id': f'{h}p',
  94. 'height': h,
  95. 'width': w,
  96. 'url': 'https://www3.nhk.or.jp' + img_path,
  97. })
  98. episode_name = title
  99. if series and title:
  100. title = f'{series} - {title}'
  101. elif series and not title:
  102. title = series
  103. series = None
  104. episode_name = None
  105. else: # title, no series
  106. episode_name = None
  107. info = {
  108. 'id': episode_id + '-' + lang,
  109. 'title': title,
  110. 'description': get_clean_field('description'),
  111. 'thumbnails': thumbnails,
  112. 'series': series,
  113. 'episode': episode_name,
  114. }
  115. if is_video:
  116. vod_id = episode['vod_id']
  117. info.update({
  118. **self._extract_stream_info(vod_id),
  119. 'id': vod_id,
  120. })
  121. else:
  122. if fetch_episode:
  123. # From https://www3.nhk.or.jp/nhkworld/common/player/radio/inline/rod.html
  124. audio_path = remove_end(episode['audio']['audio'], '.m4a')
  125. info['formats'] = self._extract_m3u8_formats(
  126. f'{urljoin("https://vod-stream.nhk.jp", audio_path)}/index.m3u8',
  127. episode_id, 'm4a', entry_protocol='m3u8_native',
  128. m3u8_id='hls', fatal=False)
  129. for f in info['formats']:
  130. f['language'] = lang
  131. else:
  132. info.update({
  133. '_type': 'url_transparent',
  134. 'ie_key': NhkVodIE.ie_key(),
  135. 'url': url,
  136. })
  137. return info
  138. class NhkVodIE(NhkBaseIE):
  139. _VALID_URL = [
  140. rf'{NhkBaseIE._BASE_URL_REGEX}shows/(?:(?P<type>video)/)?(?P<id>\d{{4}}[\da-z]\d+)/?(?:$|[?#])',
  141. rf'{NhkBaseIE._BASE_URL_REGEX}(?:ondemand|shows)/(?P<type>audio)/(?P<id>[^/?#]+?-\d{{8}}-[\da-z]+)',
  142. rf'{NhkBaseIE._BASE_URL_REGEX}ondemand/(?P<type>video)/(?P<id>\d{{4}}[\da-z]\d+)', # deprecated
  143. ]
  144. # Content available only for a limited period of time. Visit
  145. # https://www3.nhk.or.jp/nhkworld/en/ondemand/ for working samples.
  146. _TESTS = [{
  147. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/2049126/',
  148. 'info_dict': {
  149. 'id': 'nw_vod_v_en_2049_126_20230413233000_01_1681398302',
  150. 'ext': 'mp4',
  151. 'title': 'Japan Railway Journal - The Tohoku Shinkansen: Full Speed Ahead',
  152. 'description': 'md5:49f7c5b206e03868a2fdf0d0814b92f6',
  153. 'thumbnail': r're:https://.+/.+\.jpg',
  154. 'episode': 'The Tohoku Shinkansen: Full Speed Ahead',
  155. 'series': 'Japan Railway Journal',
  156. 'modified_timestamp': 1707217907,
  157. 'timestamp': 1681428600,
  158. 'release_timestamp': 1693883728,
  159. 'duration': 1679,
  160. 'upload_date': '20230413',
  161. 'modified_date': '20240206',
  162. 'release_date': '20230905',
  163. },
  164. }, {
  165. # video clip
  166. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/9999011/',
  167. 'md5': '153c3016dfd252ba09726588149cf0e7',
  168. 'info_dict': {
  169. 'id': 'lpZXIwaDE6_Z-976CPsFdxyICyWUzlT5',
  170. 'ext': 'mp4',
  171. 'title': 'Dining with the Chef - Chef Saito\'s Family recipe: MENCHI-KATSU',
  172. 'description': 'md5:5aee4a9f9d81c26281862382103b0ea5',
  173. 'thumbnail': r're:https://.+/.+\.jpg',
  174. 'series': 'Dining with the Chef',
  175. 'episode': 'Chef Saito\'s Family recipe: MENCHI-KATSU',
  176. 'duration': 148,
  177. 'upload_date': '20190816',
  178. 'release_date': '20230902',
  179. 'release_timestamp': 1693619292,
  180. 'modified_timestamp': 1707217907,
  181. 'modified_date': '20240206',
  182. 'timestamp': 1565997540,
  183. },
  184. }, {
  185. # radio
  186. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/livinginjapan-20231001-1/',
  187. 'info_dict': {
  188. 'id': 'livinginjapan-20231001-1-en',
  189. 'ext': 'm4a',
  190. 'title': 'Living in Japan - Tips for Travelers to Japan / Ramen Vending Machines',
  191. 'series': 'Living in Japan',
  192. 'description': 'md5:0a0e2077d8f07a03071e990a6f51bfab',
  193. 'thumbnail': r're:https://.+/.+\.jpg',
  194. 'episode': 'Tips for Travelers to Japan / Ramen Vending Machines',
  195. },
  196. }, {
  197. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/2015173/',
  198. 'only_matching': True,
  199. }, {
  200. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/plugin-20190404-1/',
  201. 'only_matching': True,
  202. }, {
  203. 'url': 'https://www3.nhk.or.jp/nhkworld/fr/ondemand/audio/plugin-20190404-1/',
  204. 'only_matching': True,
  205. }, {
  206. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/audio/j_art-20150903-1/',
  207. 'only_matching': True,
  208. }, {
  209. # video, alphabetic character in ID #29670
  210. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/9999a34/',
  211. 'info_dict': {
  212. 'id': 'qfjay6cg',
  213. 'ext': 'mp4',
  214. 'title': 'DESIGN TALKS plus - Fishermen’s Finery',
  215. 'description': 'md5:8a8f958aaafb0d7cb59d38de53f1e448',
  216. 'thumbnail': r're:^https?:/(/[a-z0-9.-]+)+\.jpg\?w=1920&h=1080$',
  217. 'upload_date': '20210615',
  218. 'timestamp': 1623722008,
  219. },
  220. 'skip': '404 Not Found',
  221. }, {
  222. # japanese-language, longer id than english
  223. 'url': 'https://www3.nhk.or.jp/nhkworld/ja/ondemand/video/0020271111/',
  224. 'info_dict': {
  225. 'id': 'nw_ja_v_jvod_ohayou_20231008',
  226. 'ext': 'mp4',
  227. 'title': 'おはよう日本(7時台) - 10月8日放送',
  228. 'series': 'おはよう日本(7時台)',
  229. 'episode': '10月8日放送',
  230. 'thumbnail': r're:https://.+/.+\.jpg',
  231. 'description': 'md5:9c1d6cbeadb827b955b20e99ab920ff0',
  232. },
  233. 'skip': 'expires 2023-10-15',
  234. }, {
  235. # a one-off (single-episode series). title from the api is just '<p></p>'
  236. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/3004952/',
  237. 'info_dict': {
  238. 'id': 'nw_vod_v_en_3004_952_20230723091000_01_1690074552',
  239. 'ext': 'mp4',
  240. 'title': 'Barakan Discovers - AMAMI OSHIMA: Isson\'s Treasure Isla',
  241. 'description': 'md5:5db620c46a0698451cc59add8816b797',
  242. 'thumbnail': r're:https://.+/.+\.jpg',
  243. 'release_date': '20230905',
  244. 'timestamp': 1690103400,
  245. 'duration': 2939,
  246. 'release_timestamp': 1693898699,
  247. 'upload_date': '20230723',
  248. 'modified_timestamp': 1707217907,
  249. 'modified_date': '20240206',
  250. 'episode': 'AMAMI OSHIMA: Isson\'s Treasure Isla',
  251. 'series': 'Barakan Discovers',
  252. },
  253. }, {
  254. # /ondemand/video/ url with alphabetical character in 5th position of id
  255. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/9999a07/',
  256. 'info_dict': {
  257. 'id': 'nw_c_en_9999-a07',
  258. 'ext': 'mp4',
  259. 'episode': 'Mini-Dramas on SDGs: Ep 1 Close the Gender Gap [Director\'s Cut]',
  260. 'series': 'Mini-Dramas on SDGs',
  261. 'modified_date': '20240206',
  262. 'title': 'Mini-Dramas on SDGs - Mini-Dramas on SDGs: Ep 1 Close the Gender Gap [Director\'s Cut]',
  263. 'description': 'md5:3f9dcb4db22fceb675d90448a040d3f6',
  264. 'timestamp': 1621962360,
  265. 'duration': 189,
  266. 'release_date': '20230903',
  267. 'modified_timestamp': 1707217907,
  268. 'upload_date': '20210525',
  269. 'thumbnail': r're:https://.+/.+\.jpg',
  270. 'release_timestamp': 1693713487,
  271. },
  272. }, {
  273. 'url': 'https://www3.nhk.or.jp/nhkworld/en/ondemand/video/9999d17/',
  274. 'info_dict': {
  275. 'id': 'nw_c_en_9999-d17',
  276. 'ext': 'mp4',
  277. 'title': 'Flowers of snow blossom - The 72 Pentads of Yamato',
  278. 'description': 'Today’s focus: Snow',
  279. 'release_timestamp': 1693792402,
  280. 'release_date': '20230904',
  281. 'upload_date': '20220128',
  282. 'timestamp': 1643370960,
  283. 'thumbnail': r're:https://.+/.+\.jpg',
  284. 'duration': 136,
  285. 'series': '',
  286. 'modified_date': '20240206',
  287. 'modified_timestamp': 1707217907,
  288. },
  289. }, {
  290. # new /shows/ url format
  291. 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/2032307/',
  292. 'info_dict': {
  293. 'id': 'nw_vod_v_en_2032_307_20240321113000_01_1710990282',
  294. 'ext': 'mp4',
  295. 'title': 'Japanology Plus - 20th Anniversary Special Part 1',
  296. 'description': 'md5:817d41fc8e54339ad2a916161ea24faf',
  297. 'episode': '20th Anniversary Special Part 1',
  298. 'series': 'Japanology Plus',
  299. 'thumbnail': r're:https://.+/.+\.jpg',
  300. 'duration': 1680,
  301. 'timestamp': 1711020600,
  302. 'upload_date': '20240321',
  303. 'release_timestamp': 1711022683,
  304. 'release_date': '20240321',
  305. 'modified_timestamp': 1711031012,
  306. 'modified_date': '20240321',
  307. },
  308. }, {
  309. 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/3020025/',
  310. 'info_dict': {
  311. 'id': 'nw_vod_v_en_3020_025_20230325144000_01_1679723944',
  312. 'ext': 'mp4',
  313. 'title': '100 Ideas to Save the World - Working Styles Evolve',
  314. 'description': 'md5:9e6c7778eaaf4f7b4af83569649f84d9',
  315. 'episode': 'Working Styles Evolve',
  316. 'series': '100 Ideas to Save the World',
  317. 'thumbnail': r're:https://.+/.+\.jpg',
  318. 'duration': 899,
  319. 'upload_date': '20230325',
  320. 'timestamp': 1679755200,
  321. 'release_date': '20230905',
  322. 'release_timestamp': 1693880540,
  323. 'modified_date': '20240206',
  324. 'modified_timestamp': 1707217907,
  325. },
  326. }, {
  327. # new /shows/audio/ url format
  328. 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/audio/livinginjapan-20231001-1/',
  329. 'only_matching': True,
  330. }, {
  331. # valid url even if can't be found in wild; support needed for clip entries extraction
  332. 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/9999o80/',
  333. 'only_matching': True,
  334. }]
  335. def _real_extract(self, url):
  336. return self._extract_episode_info(url)
  337. class NhkVodProgramIE(NhkBaseIE):
  338. _VALID_URL = rf'''(?x)
  339. {NhkBaseIE._BASE_URL_REGEX}(?:shows|tv)/
  340. (?:(?P<type>audio)/programs/)?(?P<id>\w+)/?
  341. (?:\?(?:[^#]+&)?type=(?P<episode_type>clip|(?:radio|tv)Episode))?'''
  342. _TESTS = [{
  343. # video program episodes
  344. 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/sumo/',
  345. 'info_dict': {
  346. 'id': 'sumo',
  347. 'title': 'GRAND SUMO Highlights',
  348. 'description': 'md5:fc20d02dc6ce85e4b72e0273aa52fdbf',
  349. },
  350. 'playlist_mincount': 1,
  351. }, {
  352. 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/japanrailway/',
  353. 'info_dict': {
  354. 'id': 'japanrailway',
  355. 'title': 'Japan Railway Journal',
  356. 'description': 'md5:ea39d93af7d05835baadf10d1aae0e3f',
  357. },
  358. 'playlist_mincount': 12,
  359. }, {
  360. # video program clips
  361. 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/japanrailway/?type=clip',
  362. 'info_dict': {
  363. 'id': 'japanrailway',
  364. 'title': 'Japan Railway Journal',
  365. 'description': 'md5:ea39d93af7d05835baadf10d1aae0e3f',
  366. },
  367. 'playlist_mincount': 12,
  368. }, {
  369. # audio program
  370. 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/audio/programs/livinginjapan/',
  371. 'info_dict': {
  372. 'id': 'livinginjapan',
  373. 'title': 'Living in Japan',
  374. 'description': 'md5:665bb36ec2a12c5a7f598ee713fc2b54',
  375. },
  376. 'playlist_mincount': 12,
  377. }, {
  378. # /tv/ program url
  379. 'url': 'https://www3.nhk.or.jp/nhkworld/en/tv/designtalksplus/',
  380. 'info_dict': {
  381. 'id': 'designtalksplus',
  382. 'title': 'DESIGN TALKS plus',
  383. 'description': 'md5:47b3b3a9f10d4ac7b33b53b70a7d2837',
  384. },
  385. 'playlist_mincount': 20,
  386. }, {
  387. 'url': 'https://www3.nhk.or.jp/nhkworld/en/shows/10yearshayaomiyazaki/',
  388. 'only_matching': True,
  389. }]
  390. @classmethod
  391. def suitable(cls, url):
  392. return False if NhkVodIE.suitable(url) else super().suitable(url)
  393. def _extract_meta_from_class_elements(self, class_values, html):
  394. for class_value in class_values:
  395. if value := clean_html(get_element_by_class(class_value, html)):
  396. return value
  397. def _real_extract(self, url):
  398. lang, m_type, program_id, episode_type = self._match_valid_url(url).group('lang', 'type', 'id', 'episode_type')
  399. episodes = self._call_api(
  400. program_id, lang, m_type != 'audio', False, episode_type == 'clip')
  401. def entries():
  402. for episode in episodes:
  403. if episode_path := episode.get('url'):
  404. yield self._extract_episode_info(urljoin(url, episode_path), episode)
  405. html = self._download_webpage(url, program_id)
  406. program_title = self._extract_meta_from_class_elements([
  407. 'p-programDetail__title', # /ondemand/program/
  408. 'pProgramHero__logoText', # /shows/
  409. 'tAudioProgramMain__title', # /shows/audio/programs/
  410. 'p-program-name'], html) # /tv/
  411. program_description = self._extract_meta_from_class_elements([
  412. 'p-programDetail__text', # /ondemand/program/
  413. 'pProgramHero__description', # /shows/
  414. 'tAudioProgramMain__info', # /shows/audio/programs/
  415. 'p-program-description'], html) # /tv/
  416. return self.playlist_result(entries(), program_id, program_title, program_description)
  417. class NhkForSchoolBangumiIE(InfoExtractor):
  418. _VALID_URL = r'https?://www2\.nhk\.or\.jp/school/movie/(?P<type>bangumi|clip)\.cgi\?das_id=(?P<id>[a-zA-Z0-9_-]+)'
  419. _TESTS = [{
  420. 'url': 'https://www2.nhk.or.jp/school/movie/bangumi.cgi?das_id=D0005150191_00000',
  421. 'info_dict': {
  422. 'id': 'D0005150191_00003',
  423. 'title': 'にている かな',
  424. 'duration': 599.999,
  425. 'timestamp': 1396414800,
  426. 'upload_date': '20140402',
  427. 'ext': 'mp4',
  428. 'chapters': 'count:12',
  429. },
  430. 'params': {
  431. # m3u8 download
  432. 'skip_download': True,
  433. },
  434. }]
  435. def _real_extract(self, url):
  436. program_type, video_id = self._match_valid_url(url).groups()
  437. webpage = self._download_webpage(
  438. f'https://www2.nhk.or.jp/school/movie/{program_type}.cgi?das_id={video_id}', video_id)
  439. # searches all variables
  440. base_values = {g.group(1): g.group(2) for g in re.finditer(r'var\s+([a-zA-Z_]+)\s*=\s*"([^"]+?)";', webpage)}
  441. # and programObj values too
  442. program_values = {g.group(1): g.group(3) for g in re.finditer(r'(?:program|clip)Obj\.([a-zA-Z_]+)\s*=\s*(["\'])([^"]+?)\2;', webpage)}
  443. # extract all chapters
  444. chapter_durations = [parse_duration(g.group(1)) for g in re.finditer(r'chapterTime\.push\(\'([0-9:]+?)\'\);', webpage)]
  445. 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)]
  446. # this is how player_core.js is actually doing (!)
  447. version = base_values.get('r_version') or program_values.get('version')
  448. if version:
  449. video_id = f'{video_id.split("_")[0]}_{version}'
  450. formats = self._extract_m3u8_formats(
  451. f'https://nhks-vh.akamaihd.net/i/das/{video_id[0:8]}/{video_id}_V_000.f4v/master.m3u8',
  452. video_id, ext='mp4', m3u8_id='hls')
  453. duration = parse_duration(base_values.get('r_duration'))
  454. chapters = None
  455. if chapter_durations and chapter_titles and len(chapter_durations) == len(chapter_titles):
  456. start_time = chapter_durations
  457. end_time = chapter_durations[1:] + [duration]
  458. chapters = [{
  459. 'start_time': s,
  460. 'end_time': e,
  461. 'title': t,
  462. } for s, e, t in zip(start_time, end_time, chapter_titles)]
  463. return {
  464. 'id': video_id,
  465. 'title': program_values.get('name'),
  466. 'duration': parse_duration(base_values.get('r_duration')),
  467. 'timestamp': unified_timestamp(base_values['r_upload']),
  468. 'formats': formats,
  469. 'chapters': chapters,
  470. }
  471. class NhkForSchoolSubjectIE(InfoExtractor):
  472. IE_DESC = 'Portal page for each school subjects, like Japanese (kokugo, 国語) or math (sansuu/suugaku or 算数・数学)'
  473. KNOWN_SUBJECTS = (
  474. 'rika', 'syakai', 'kokugo',
  475. 'sansuu', 'seikatsu', 'doutoku',
  476. 'ongaku', 'taiiku', 'zukou',
  477. 'gijutsu', 'katei', 'sougou',
  478. 'eigo', 'tokkatsu',
  479. 'tokushi', 'sonota',
  480. )
  481. _VALID_URL = r'https?://www\.nhk\.or\.jp/school/(?P<id>{})/?(?:[\?#].*)?$'.format(
  482. '|'.join(re.escape(s) for s in KNOWN_SUBJECTS))
  483. _TESTS = [{
  484. 'url': 'https://www.nhk.or.jp/school/sougou/',
  485. 'info_dict': {
  486. 'id': 'sougou',
  487. 'title': '総合的な学習の時間',
  488. },
  489. 'playlist_mincount': 16,
  490. }, {
  491. 'url': 'https://www.nhk.or.jp/school/rika/',
  492. 'info_dict': {
  493. 'id': 'rika',
  494. 'title': '理科',
  495. },
  496. 'playlist_mincount': 15,
  497. }]
  498. def _real_extract(self, url):
  499. subject_id = self._match_id(url)
  500. webpage = self._download_webpage(url, subject_id)
  501. return self.playlist_from_matches(
  502. re.finditer(rf'href="((?:https?://www\.nhk\.or\.jp)?/school/{re.escape(subject_id)}/[^/]+/)"', webpage),
  503. subject_id,
  504. self._html_search_regex(r'(?s)<span\s+class="subjectName">\s*<img\s*[^<]+>\s*([^<]+?)</span>', webpage, 'title', fatal=False),
  505. lambda g: urljoin(url, g.group(1)))
  506. class NhkForSchoolProgramListIE(InfoExtractor):
  507. _VALID_URL = r'https?://www\.nhk\.or\.jp/school/(?P<id>(?:{})/[a-zA-Z0-9_-]+)'.format(
  508. '|'.join(re.escape(s) for s in NhkForSchoolSubjectIE.KNOWN_SUBJECTS))
  509. _TESTS = [{
  510. 'url': 'https://www.nhk.or.jp/school/sougou/q/',
  511. 'info_dict': {
  512. 'id': 'sougou/q',
  513. 'title': 'Q~こどものための哲学',
  514. },
  515. 'playlist_mincount': 20,
  516. }]
  517. def _real_extract(self, url):
  518. program_id = self._match_id(url)
  519. webpage = self._download_webpage(f'https://www.nhk.or.jp/school/{program_id}/', program_id)
  520. title = (self._generic_title('', webpage)
  521. or self._html_search_regex(r'<h3>([^<]+?)とは?\s*</h3>', webpage, 'title', fatal=False))
  522. title = re.sub(r'\s*\|\s*NHK\s+for\s+School\s*$', '', title) if title else None
  523. description = self._html_search_regex(
  524. r'(?s)<div\s+class="programDetail\s*">\s*<p>[^<]+</p>',
  525. webpage, 'description', fatal=False, group=0)
  526. bangumi_list = self._download_json(
  527. f'https://www.nhk.or.jp/school/{program_id}/meta/program.json', program_id)
  528. # they're always bangumi
  529. bangumis = [
  530. self.url_result(f'https://www2.nhk.or.jp/school/movie/bangumi.cgi?das_id={x}')
  531. for x in traverse_obj(bangumi_list, ('part', ..., 'part-video-dasid')) or []]
  532. return self.playlist_result(bangumis, program_id, title, description)
  533. class NhkRadiruIE(InfoExtractor):
  534. _GEO_COUNTRIES = ['JP']
  535. IE_DESC = 'NHK らじる (Radiru/Rajiru)'
  536. _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]+))?'
  537. _TESTS = [{
  538. 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=0449_01_4003239',
  539. 'skip': 'Episode expired on 2024-06-09',
  540. 'info_dict': {
  541. 'title': 'ジャズ・トゥナイト ジャズ「Night and Day」特集',
  542. 'id': '0449_01_4003239',
  543. 'ext': 'm4a',
  544. 'uploader': 'NHK FM 東京',
  545. 'description': 'md5:ad05f3c3f3f6e99b2e69f9b5e49551dc',
  546. 'series': 'ジャズ・トゥナイト',
  547. 'channel': 'NHK FM 東京',
  548. 'thumbnail': 'https://www.nhk.or.jp/prog/img/449/g449.jpg',
  549. 'upload_date': '20240601',
  550. 'series_id': '0449_01',
  551. 'release_date': '20240601',
  552. 'timestamp': 1717257600,
  553. 'release_timestamp': 1717250400,
  554. },
  555. }, {
  556. # playlist, airs every weekday so it should _hopefully_ be okay forever
  557. 'url': 'https://www.nhk.or.jp/radio/ondemand/detail.html?p=0458_01',
  558. 'info_dict': {
  559. 'id': '0458_01',
  560. 'title': 'ベストオブクラシック',
  561. 'description': '世界中の上質な演奏会をじっくり堪能する本格派クラシック番組。',
  562. 'thumbnail': 'https://www.nhk.or.jp/prog/img/458/g458.jpg',
  563. 'series_id': '0458_01',
  564. 'uploader': 'NHK FM',
  565. 'channel': 'NHK FM',
  566. 'series': 'ベストオブクラシック',
  567. },
  568. 'playlist_mincount': 3,
  569. }, {
  570. # one with letters in the id
  571. 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=F683_01_3910688',
  572. 'note': 'Expires on 2025-03-31',
  573. 'info_dict': {
  574. 'id': 'F683_01_3910688',
  575. 'ext': 'm4a',
  576. 'title': '夏目漱石「文鳥」第1回',
  577. 'series': '【らじる文庫】夏目漱石「文鳥」(全4回)',
  578. 'series_id': 'F683_01',
  579. 'description': '朗読:浅井理アナウンサー',
  580. 'thumbnail': 'https://www.nhk.or.jp/radioondemand/json/F683/img/roudoku_05_rod_640.jpg',
  581. 'upload_date': '20240106',
  582. 'release_date': '20240106',
  583. 'uploader': 'NHK R1',
  584. 'release_timestamp': 1704511800,
  585. 'channel': 'NHK R1',
  586. 'timestamp': 1704512700,
  587. },
  588. 'expected_warnings': ['Unable to download JSON metadata',
  589. 'Failed to get extended metadata. API returned Error 1: Invalid parameters'],
  590. }, {
  591. # news
  592. 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=F261_01_4012173',
  593. 'info_dict': {
  594. 'id': 'F261_01_4012173',
  595. 'ext': 'm4a',
  596. 'channel': 'NHKラジオ第1',
  597. 'uploader': 'NHKラジオ第1',
  598. 'series': 'NHKラジオニュース',
  599. 'title': '午前0時のNHKニュース',
  600. 'thumbnail': 'https://www.nhk.or.jp/radioondemand/json/F261/img/RADIONEWS_640.jpg',
  601. 'release_timestamp': 1718290800,
  602. 'release_date': '20240613',
  603. 'timestamp': 1718291400,
  604. 'upload_date': '20240613',
  605. },
  606. }, {
  607. # fallback when extended metadata fails
  608. 'url': 'https://www.nhk.or.jp/radio/player/ondemand.html?p=2834_01_4009298',
  609. 'skip': 'Expires on 2024-06-07',
  610. 'info_dict': {
  611. 'id': '2834_01_4009298',
  612. 'title': 'まち☆キラ!開成町特集',
  613. 'ext': 'm4a',
  614. 'release_date': '20240531',
  615. 'upload_date': '20240531',
  616. 'series': 'はま☆キラ!',
  617. 'thumbnail': 'https://www.nhk.or.jp/prog/img/2834/g2834.jpg',
  618. 'channel': 'NHK R1,FM',
  619. 'description': '',
  620. 'timestamp': 1717123800,
  621. 'uploader': 'NHK R1,FM',
  622. 'release_timestamp': 1717120800,
  623. 'series_id': '2834_01',
  624. },
  625. 'expected_warnings': ['Failed to get extended metadata. API returned empty list.'],
  626. }]
  627. _API_URL_TMPL = None
  628. def _extract_extended_metadata(self, episode_id, aa_vinfo):
  629. service, _, area = traverse_obj(aa_vinfo, (2, {str}, {lambda x: (x or '').partition(',')}))
  630. detail_url = try_call(
  631. lambda: self._API_URL_TMPL.format(area=area, service=service, dateid=aa_vinfo[3]))
  632. if not detail_url:
  633. return {}
  634. response = self._download_json(
  635. detail_url, episode_id, 'Downloading extended metadata',
  636. 'Failed to download extended metadata', fatal=False, expected_status=400)
  637. if not response:
  638. return {}
  639. if error := traverse_obj(response, ('error', {dict})):
  640. self.report_warning(
  641. 'Failed to get extended metadata. API returned '
  642. f'Error {join_nonempty("code", "message", from_dict=error, delim=": ")}')
  643. return {}
  644. full_meta = traverse_obj(response, ('list', service, 0, {dict}))
  645. if not full_meta:
  646. self.report_warning('Failed to get extended metadata. API returned empty list.')
  647. return {}
  648. station = ' '.join(traverse_obj(full_meta, (('service', 'area'), 'name', {str}))) or None
  649. thumbnails = [{
  650. 'id': str(id_),
  651. 'preference': 1 if id_.startswith('thumbnail') else -2 if id_.startswith('logo') else -1,
  652. **traverse_obj(thumb, {
  653. 'url': 'url',
  654. 'width': ('width', {int_or_none}),
  655. 'height': ('height', {int_or_none}),
  656. }),
  657. } for id_, thumb in traverse_obj(full_meta, ('images', {dict.items}, lambda _, v: v[1]['url']))]
  658. return filter_dict({
  659. 'channel': station,
  660. 'uploader': station,
  661. 'description': join_nonempty(
  662. 'subtitle', 'content', 'act', 'music', delim='\n\n', from_dict=full_meta),
  663. 'thumbnails': thumbnails,
  664. **traverse_obj(full_meta, {
  665. 'title': ('title', {str}),
  666. 'timestamp': ('end_time', {unified_timestamp}),
  667. 'release_timestamp': ('start_time', {unified_timestamp}),
  668. }),
  669. })
  670. def _extract_episode_info(self, episode, programme_id, series_meta):
  671. episode_id = f'{programme_id}_{episode["id"]}'
  672. aa_vinfo = traverse_obj(episode, ('aa_contents_id', {lambda x: x.split(';')}))
  673. extended_metadata = self._extract_extended_metadata(episode_id, aa_vinfo)
  674. fallback_start_time, _, fallback_end_time = traverse_obj(
  675. aa_vinfo, (4, {str}, {lambda x: (x or '').partition('_')}))
  676. return {
  677. **series_meta,
  678. 'id': episode_id,
  679. 'formats': self._extract_m3u8_formats(episode.get('stream_url'), episode_id, fatal=False),
  680. 'container': 'm4a_dash', # force fixup, AAC-only HLS
  681. 'was_live': True,
  682. 'title': episode.get('program_title'),
  683. 'description': episode.get('program_sub_title'), # fallback
  684. 'timestamp': unified_timestamp(fallback_end_time),
  685. 'release_timestamp': unified_timestamp(fallback_start_time),
  686. **extended_metadata,
  687. }
  688. def _extract_news_info(self, headline, programme_id, series_meta):
  689. episode_id = f'{programme_id}_{headline["headline_id"]}'
  690. episode = traverse_obj(headline, ('file_list', 0, {dict}))
  691. return {
  692. **series_meta,
  693. 'id': episode_id,
  694. 'formats': self._extract_m3u8_formats(episode.get('file_name'), episode_id, fatal=False),
  695. 'container': 'm4a_dash', # force fixup, AAC-only HLS
  696. 'was_live': True,
  697. 'series': series_meta.get('title'),
  698. 'thumbnail': url_or_none(headline.get('headline_image')) or series_meta.get('thumbnail'),
  699. **traverse_obj(episode, {
  700. 'title': ('file_title', {str}),
  701. 'description': ('file_title_sub', {str}),
  702. 'timestamp': ('open_time', {unified_timestamp}),
  703. 'release_timestamp': ('aa_vinfo4', {lambda x: x.split('_')[0]}, {unified_timestamp}),
  704. }),
  705. }
  706. def _real_initialize(self):
  707. if self._API_URL_TMPL:
  708. return
  709. api_config = self._download_xml(
  710. 'https://www.nhk.or.jp/radio/config/config_web.xml', None, 'Downloading API config', fatal=False)
  711. NhkRadiruIE._API_URL_TMPL = try_call(lambda: f'https:{api_config.find(".//url_program_detail").text}')
  712. def _real_extract(self, url):
  713. site_id, corner_id, headline_id = self._match_valid_url(url).group('site', 'corner', 'headline')
  714. programme_id = f'{site_id}_{corner_id}'
  715. if site_id == 'F261': # XXX: News programmes use old API (for now?)
  716. meta = self._download_json(
  717. 'https://www.nhk.or.jp/s-media/news/news-site/list/v1/all.json', programme_id)['main']
  718. series_meta = traverse_obj(meta, {
  719. 'title': ('program_name', {str}),
  720. 'channel': ('media_name', {str}),
  721. 'uploader': ('media_name', {str}),
  722. 'thumbnail': (('thumbnail_c', 'thumbnail_p'), {url_or_none}),
  723. }, get_all=False)
  724. if headline_id:
  725. headline = traverse_obj(
  726. meta, ('detail_list', lambda _, v: v['headline_id'] == headline_id, any))
  727. if not headline:
  728. raise ExtractorError('Content not found; it has most likely expired', expected=True)
  729. return self._extract_news_info(headline, programme_id, series_meta)
  730. def news_entries():
  731. for headline in traverse_obj(meta, ('detail_list', ..., {dict})):
  732. yield self._extract_news_info(headline, programme_id, series_meta)
  733. return self.playlist_result(
  734. news_entries(), programme_id, description=meta.get('site_detail'), **series_meta)
  735. meta = self._download_json(
  736. 'https://www.nhk.or.jp/radio-api/app/v1/web/ondemand/series', programme_id, query={
  737. 'site_id': site_id,
  738. 'corner_site_id': corner_id,
  739. })
  740. fallback_station = join_nonempty('NHK', traverse_obj(meta, ('radio_broadcast', {str})), delim=' ')
  741. series_meta = {
  742. 'series': join_nonempty('title', 'corner_name', delim=' ', from_dict=meta),
  743. 'series_id': programme_id,
  744. 'thumbnail': traverse_obj(meta, ('thumbnail_url', {url_or_none})),
  745. 'channel': fallback_station,
  746. 'uploader': fallback_station,
  747. }
  748. if headline_id:
  749. episode = traverse_obj(meta, ('episodes', lambda _, v: v['id'] == int(headline_id), any))
  750. if not episode:
  751. raise ExtractorError('Content not found; it has most likely expired', expected=True)
  752. return self._extract_episode_info(episode, programme_id, series_meta)
  753. def entries():
  754. for episode in traverse_obj(meta, ('episodes', ..., {dict})):
  755. yield self._extract_episode_info(episode, programme_id, series_meta)
  756. return self.playlist_result(
  757. entries(), programme_id, title=series_meta.get('series'),
  758. description=meta.get('series_description'), **series_meta)
  759. class NhkRadioNewsPageIE(InfoExtractor):
  760. _VALID_URL = r'https?://www\.nhk\.or\.jp/radionews/?(?:$|[?#])'
  761. _TESTS = [{
  762. # airs daily, on-the-hour most hours
  763. 'url': 'https://www.nhk.or.jp/radionews/',
  764. 'playlist_mincount': 5,
  765. 'info_dict': {
  766. 'id': 'F261_01',
  767. 'thumbnail': 'https://www.nhk.or.jp/radioondemand/json/F261/img/RADIONEWS_640.jpg',
  768. 'description': 'md5:bf2c5b397e44bc7eb26de98d8f15d79d',
  769. 'channel': 'NHKラジオ第1',
  770. 'uploader': 'NHKラジオ第1',
  771. 'title': 'NHKラジオニュース',
  772. },
  773. }]
  774. def _real_extract(self, url):
  775. return self.url_result('https://www.nhk.or.jp/radio/ondemand/detail.html?p=F261_01', NhkRadiruIE)
  776. class NhkRadiruLiveIE(InfoExtractor):
  777. _GEO_COUNTRIES = ['JP']
  778. _VALID_URL = r'https?://www\.nhk\.or\.jp/radio/player/\?ch=(?P<id>r[12]|fm)'
  779. _TESTS = [{
  780. # radio 1, no area specified
  781. 'url': 'https://www.nhk.or.jp/radio/player/?ch=r1',
  782. 'info_dict': {
  783. 'id': 'r1-tokyo',
  784. 'title': 're:^NHKネットラジオ第1 東京.+$',
  785. 'ext': 'm4a',
  786. 'thumbnail': 'https://www.nhk.or.jp/common/img/media/r1-200x200.png',
  787. 'live_status': 'is_live',
  788. },
  789. }, {
  790. # radio 2, area specified
  791. # (the area doesnt actually matter, r2 is national)
  792. 'url': 'https://www.nhk.or.jp/radio/player/?ch=r2',
  793. 'params': {'extractor_args': {'nhkradirulive': {'area': ['fukuoka']}}},
  794. 'info_dict': {
  795. 'id': 'r2-fukuoka',
  796. 'title': 're:^NHKネットラジオ第2 福岡.+$',
  797. 'ext': 'm4a',
  798. 'thumbnail': 'https://www.nhk.or.jp/common/img/media/r2-200x200.png',
  799. 'live_status': 'is_live',
  800. },
  801. }, {
  802. # fm, area specified
  803. 'url': 'https://www.nhk.or.jp/radio/player/?ch=fm',
  804. 'params': {'extractor_args': {'nhkradirulive': {'area': ['sapporo']}}},
  805. 'info_dict': {
  806. 'id': 'fm-sapporo',
  807. 'title': 're:^NHKネットラジオFM 札幌.+$',
  808. 'ext': 'm4a',
  809. 'thumbnail': 'https://www.nhk.or.jp/common/img/media/fm-200x200.png',
  810. 'live_status': 'is_live',
  811. },
  812. }]
  813. _NOA_STATION_IDS = {'r1': 'n1', 'r2': 'n2', 'fm': 'n3'}
  814. def _real_extract(self, url):
  815. station = self._match_id(url)
  816. area = self._configuration_arg('area', ['tokyo'])[0]
  817. config = self._download_xml(
  818. 'https://www.nhk.or.jp/radio/config/config_web.xml', station, 'Downloading area information')
  819. data = config.find(f'.//data//area[.="{area}"]/..')
  820. if not data:
  821. raise ExtractorError('Invalid area. Valid areas are: {}'.format(', '.join(
  822. [i.text for i in config.findall('.//data//area')])), expected=True)
  823. noa_info = self._download_json(
  824. f'https:{config.find(".//url_program_noa").text}'.format(area=data.find('areakey').text),
  825. station, note=f'Downloading {area} station metadata', fatal=False)
  826. present_info = traverse_obj(noa_info, ('nowonair_list', self._NOA_STATION_IDS.get(station), 'present'))
  827. return {
  828. 'title': ' '.join(traverse_obj(present_info, (('service', 'area'), 'name', {str}))),
  829. 'id': join_nonempty(station, area),
  830. 'thumbnails': traverse_obj(present_info, ('service', 'images', ..., {
  831. 'url': 'url',
  832. 'width': ('width', {int_or_none}),
  833. 'height': ('height', {int_or_none}),
  834. })),
  835. 'formats': self._extract_m3u8_formats(data.find(f'{station}hls').text, station),
  836. 'is_live': True,
  837. }