radiko.py 9.6 KB

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