logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

radiko.py (9906B)


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