radiko.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import base64
  2. import re
  3. import urllib.parse
  4. from .common import InfoExtractor
  5. from ..utils import (
  6. ExtractorError,
  7. clean_html,
  8. time_seconds,
  9. try_call,
  10. unified_timestamp,
  11. update_url_query,
  12. )
  13. class RadikoBaseIE(InfoExtractor):
  14. _FULL_KEY = None
  15. def _auth_client(self):
  16. _, auth1_handle = self._download_webpage_handle(
  17. 'https://radiko.jp/v2/api/auth1', None, 'Downloading authentication page',
  18. headers={
  19. 'x-radiko-app': 'pc_html5',
  20. 'x-radiko-app-version': '0.0.1',
  21. 'x-radiko-device': 'pc',
  22. 'x-radiko-user': 'dummy_user',
  23. })
  24. auth1_header = auth1_handle.info()
  25. auth_token = auth1_header['X-Radiko-AuthToken']
  26. kl = int(auth1_header['X-Radiko-KeyLength'])
  27. ko = int(auth1_header['X-Radiko-KeyOffset'])
  28. raw_partial_key = self._extract_full_key()[ko:ko + kl]
  29. partial_key = base64.b64encode(raw_partial_key).decode()
  30. area_id = self._download_webpage(
  31. 'https://radiko.jp/v2/api/auth2', None, 'Authenticating',
  32. headers={
  33. 'x-radiko-device': 'pc',
  34. 'x-radiko-user': 'dummy_user',
  35. 'x-radiko-authtoken': auth_token,
  36. 'x-radiko-partialkey': partial_key,
  37. }).split(',')[0]
  38. auth_data = (auth_token, area_id)
  39. self.cache.store('radiko', 'auth_data', auth_data)
  40. return auth_data
  41. def _extract_full_key(self):
  42. if self._FULL_KEY:
  43. return self._FULL_KEY
  44. jscode = self._download_webpage(
  45. 'https://radiko.jp/apps/js/playerCommon.js', None,
  46. note='Downloading player js code')
  47. full_key = self._search_regex(
  48. (r"RadikoJSPlayer\([^,]*,\s*(['\"])pc_html5\1,\s*(['\"])(?P<fullkey>[0-9a-f]+)\2,\s*{"),
  49. jscode, 'full key', fatal=False, group='fullkey')
  50. if full_key:
  51. full_key = full_key.encode()
  52. else: # use full key ever known
  53. full_key = b'bcd151073c03b352e1ef2fd66c32209da9ca0afa'
  54. self._FULL_KEY = full_key
  55. return full_key
  56. def _find_program(self, video_id, station, cursor):
  57. station_program = self._download_xml(
  58. 'https://radiko.jp/v3/program/station/weekly/%s.xml' % station, video_id,
  59. note='Downloading radio program for %s station' % station)
  60. prog = None
  61. for p in station_program.findall('.//prog'):
  62. ft_str, to_str = p.attrib['ft'], p.attrib['to']
  63. ft = unified_timestamp(ft_str, False)
  64. to = unified_timestamp(to_str, False)
  65. if ft <= cursor and cursor < to:
  66. prog = p
  67. break
  68. if not prog:
  69. raise ExtractorError('Cannot identify radio program to download!')
  70. assert ft, to
  71. return prog, station_program, ft, ft_str, to_str
  72. def _extract_formats(self, video_id, station, is_onair, ft, cursor, auth_token, area_id, query):
  73. m3u8_playlist_data = self._download_xml(
  74. f'https://radiko.jp/v3/station/stream/pc_html5/{station}.xml', video_id,
  75. note='Downloading stream information')
  76. m3u8_urls = m3u8_playlist_data.findall('.//url')
  77. formats = []
  78. found = set()
  79. for url_tag in m3u8_urls:
  80. pcu = url_tag.find('playlist_create_url')
  81. url_attrib = url_tag.attrib
  82. playlist_url = update_url_query(pcu.text, {
  83. 'station_id': station,
  84. **query,
  85. 'l': '15',
  86. 'lsid': '88ecea37e968c1f17d5413312d9f8003',
  87. 'type': 'b',
  88. })
  89. if playlist_url in found:
  90. continue
  91. else:
  92. found.add(playlist_url)
  93. time_to_skip = None if is_onair else cursor - ft
  94. domain = urllib.parse.urlparse(playlist_url).netloc
  95. subformats = self._extract_m3u8_formats(
  96. playlist_url, video_id, ext='m4a',
  97. live=True, fatal=False, m3u8_id=domain,
  98. note=f'Downloading m3u8 information from {domain}',
  99. headers={
  100. 'X-Radiko-AreaId': area_id,
  101. 'X-Radiko-AuthToken': auth_token,
  102. })
  103. for sf in subformats:
  104. if re.fullmatch(r'[cf]-radiko\.smartstream\.ne\.jp', domain):
  105. # Prioritize live radio vs playback based on extractor
  106. sf['preference'] = 100 if is_onair else -100
  107. if not is_onair and url_attrib['timefree'] == '1' and time_to_skip:
  108. sf['downloader_options'] = {'ffmpeg_args': ['-ss', time_to_skip]}
  109. formats.extend(subformats)
  110. return formats
  111. class RadikoIE(RadikoBaseIE):
  112. _VALID_URL = r'https?://(?:www\.)?radiko\.jp/#!/ts/(?P<station>[A-Z0-9-]+)/(?P<id>\d+)'
  113. _TESTS = [{
  114. # QRR (文化放送) station provides <desc>
  115. 'url': 'https://radiko.jp/#!/ts/QRR/20210425101300',
  116. 'only_matching': True,
  117. }, {
  118. # FMT (TOKYO FM) station does not provide <desc>
  119. 'url': 'https://radiko.jp/#!/ts/FMT/20210810150000',
  120. 'only_matching': True,
  121. }, {
  122. 'url': 'https://radiko.jp/#!/ts/JOAK-FM/20210509090000',
  123. 'only_matching': True,
  124. }]
  125. def _real_extract(self, url):
  126. station, video_id = self._match_valid_url(url).groups()
  127. vid_int = unified_timestamp(video_id, False)
  128. prog, station_program, ft, radio_begin, radio_end = self._find_program(video_id, station, vid_int)
  129. auth_cache = self.cache.load('radiko', 'auth_data')
  130. for attempt in range(2):
  131. auth_token, area_id = (not attempt and auth_cache) or self._auth_client()
  132. formats = self._extract_formats(
  133. video_id=video_id, station=station, is_onair=False,
  134. ft=ft, cursor=vid_int, auth_token=auth_token, area_id=area_id,
  135. query={
  136. 'start_at': radio_begin,
  137. 'ft': radio_begin,
  138. 'end_at': radio_end,
  139. 'to': radio_end,
  140. 'seek': video_id,
  141. })
  142. if formats:
  143. break
  144. return {
  145. 'id': video_id,
  146. 'title': try_call(lambda: prog.find('title').text),
  147. 'description': clean_html(try_call(lambda: prog.find('info').text)),
  148. 'uploader': try_call(lambda: station_program.find('.//name').text),
  149. 'uploader_id': station,
  150. 'timestamp': vid_int,
  151. 'formats': formats,
  152. 'is_live': True,
  153. }
  154. class RadikoRadioIE(RadikoBaseIE):
  155. _VALID_URL = r'https?://(?:www\.)?radiko\.jp/#!/live/(?P<id>[A-Z0-9-]+)'
  156. _TESTS = [{
  157. # QRR (文化放送) station provides <desc>
  158. 'url': 'https://radiko.jp/#!/live/QRR',
  159. 'only_matching': True,
  160. }, {
  161. # FMT (TOKYO FM) station does not provide <desc>
  162. 'url': 'https://radiko.jp/#!/live/FMT',
  163. 'only_matching': True,
  164. }, {
  165. 'url': 'https://radiko.jp/#!/live/JOAK-FM',
  166. 'only_matching': True,
  167. }]
  168. def _real_extract(self, url):
  169. station = self._match_id(url)
  170. self.report_warning('Downloader will not stop at the end of the program! Press Ctrl+C to stop')
  171. auth_token, area_id = self._auth_client()
  172. # get current time in JST (GMT+9:00 w/o DST)
  173. vid_now = time_seconds(hours=9)
  174. prog, station_program, ft, _, _ = self._find_program(station, station, vid_now)
  175. title = prog.find('title').text
  176. description = clean_html(prog.find('info').text)
  177. station_name = station_program.find('.//name').text
  178. formats = self._extract_formats(
  179. video_id=station, station=station, is_onair=True,
  180. ft=ft, cursor=vid_now, auth_token=auth_token, area_id=area_id,
  181. query={})
  182. return {
  183. 'id': station,
  184. 'title': title,
  185. 'description': description,
  186. 'uploader': station_name,
  187. 'uploader_id': station,
  188. 'timestamp': ft,
  189. 'formats': formats,
  190. 'is_live': True,
  191. }