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