]> jfr.im git - yt-dlp.git/blob - yt_dlp/extractor/iwara.py
fix motherless
[yt-dlp.git] / yt_dlp / extractor / iwara.py
1 import functools
2 import hashlib
3 import json
4 import time
5 import urllib.parse
6
7 from .common import InfoExtractor
8 from ..utils import (
9 ExtractorError,
10 OnDemandPagedList,
11 int_or_none,
12 jwt_decode_hs256,
13 mimetype2ext,
14 qualities,
15 traverse_obj,
16 try_call,
17 unified_timestamp,
18 )
19
20
21 class IwaraBaseIE(InfoExtractor):
22 _NETRC_MACHINE = 'iwara'
23 _USERTOKEN = None
24 _MEDIATOKEN = None
25
26 def _is_token_expired(self, token, token_type):
27 # User token TTL == ~3 weeks, Media token TTL == ~1 hour
28 if (try_call(lambda: jwt_decode_hs256(token)['exp']) or 0) <= int(time.time() - 120):
29 self.to_screen(f'{token_type} token has expired')
30 return True
31
32 def _get_user_token(self):
33 username, password = self._get_login_info()
34 if not username or not password:
35 return
36
37 user_token = IwaraBaseIE._USERTOKEN or self.cache.load(self._NETRC_MACHINE, username)
38 if not user_token or self._is_token_expired(user_token, 'User'):
39 response = self._download_json(
40 'https://api.iwara.tv/user/login', None, note='Logging in',
41 headers={'Content-Type': 'application/json'}, data=json.dumps({
42 'email': username,
43 'password': password,
44 }).encode(), expected_status=lambda x: True)
45 user_token = traverse_obj(response, ('token', {str}))
46 if not user_token:
47 error = traverse_obj(response, ('message', {str}))
48 if 'invalidLogin' in error:
49 raise ExtractorError('Invalid login credentials', expected=True)
50 else:
51 raise ExtractorError(f'Iwara API said: {error or "nothing"}')
52
53 self.cache.store(self._NETRC_MACHINE, username, user_token)
54
55 IwaraBaseIE._USERTOKEN = user_token
56
57 def _get_media_token(self):
58 self._get_user_token()
59 if not IwaraBaseIE._USERTOKEN:
60 return # user has not passed credentials
61
62 if not IwaraBaseIE._MEDIATOKEN or self._is_token_expired(IwaraBaseIE._MEDIATOKEN, 'Media'):
63 IwaraBaseIE._MEDIATOKEN = self._download_json(
64 'https://api.iwara.tv/user/token', None, note='Fetching media token',
65 data=b'', headers={
66 'Authorization': f'Bearer {IwaraBaseIE._USERTOKEN}',
67 'Content-Type': 'application/json',
68 })['accessToken']
69
70 return {'Authorization': f'Bearer {IwaraBaseIE._MEDIATOKEN}'}
71
72 def _perform_login(self, username, password):
73 self._get_media_token()
74
75
76 class IwaraIE(IwaraBaseIE):
77 IE_NAME = 'iwara'
78 _VALID_URL = r'https?://(?:www\.|ecchi\.)?iwara\.tv/videos?/(?P<id>[a-zA-Z0-9]+)'
79 _TESTS = [{
80 'url': 'https://www.iwara.tv/video/k2ayoueezfkx6gvq',
81 'info_dict': {
82 'id': 'k2ayoueezfkx6gvq',
83 'ext': 'mp4',
84 'age_limit': 18,
85 'title': 'Defeat of Irybelda - アイリベルダの敗北',
86 'description': 'md5:70278abebe706647a8b4cb04cf23e0d3',
87 'uploader': 'Inwerwm',
88 'uploader_id': 'inwerwm',
89 'tags': 'count:1',
90 'like_count': 6133,
91 'view_count': 1050343,
92 'comment_count': 1,
93 'timestamp': 1677843869,
94 'modified_timestamp': 1679056362,
95 },
96 'skip': 'this video cannot be played because of migration',
97 }, {
98 'url': 'https://iwara.tv/video/1ywe1sbkqwumpdxz5/',
99 'md5': '7645f966f069b8ec9210efd9130c9aad',
100 'info_dict': {
101 'id': '1ywe1sbkqwumpdxz5',
102 'ext': 'mp4',
103 'age_limit': 18,
104 'title': 'Aponia アポニア SEX Party Tonight 手の脱衣 巨乳 ',
105 'description': 'md5:3f60016fff22060eef1ef26d430b1f67',
106 'uploader': 'Lyu ya',
107 'uploader_id': 'user792540',
108 'tags': [
109 'uncategorized',
110 ],
111 'like_count': int,
112 'view_count': int,
113 'comment_count': int,
114 'timestamp': 1678732213,
115 'modified_timestamp': int,
116 'thumbnail': 'https://files.iwara.tv/image/thumbnail/581d12b5-46f4-4f15-beb2-cfe2cde5d13d/thumbnail-00.jpg',
117 'modified_date': '20230614',
118 'upload_date': '20230313',
119 },
120 }, {
121 'url': 'https://iwara.tv/video/blggmfno8ghl725bg',
122 'info_dict': {
123 'id': 'blggmfno8ghl725bg',
124 'ext': 'mp4',
125 'age_limit': 18,
126 'title': 'お外でおしっこしちゃう猫耳ロリメイド',
127 'description': 'md5:0342ba9bf6db09edbbb28729657c3611',
128 'uploader': 'Fe_Kurosabi',
129 'uploader_id': 'fekurosabi',
130 'tags': [
131 'pee',
132 ],
133 'like_count': int,
134 'view_count': int,
135 'comment_count': int,
136 'timestamp': 1598880567,
137 'modified_timestamp': int,
138 'upload_date': '20200831',
139 'modified_date': '20230605',
140 'thumbnail': 'https://files.iwara.tv/image/thumbnail/7693e881-d302-42a4-a780-f16d66b5dadd/thumbnail-00.jpg',
141 # 'availability': 'needs_auth',
142 },
143 }]
144
145 def _extract_formats(self, video_id, fileurl):
146 up = urllib.parse.urlparse(fileurl)
147 q = urllib.parse.parse_qs(up.query)
148 paths = up.path.rstrip('/').split('/')
149 # https://github.com/yt-dlp/yt-dlp/issues/6549#issuecomment-1473771047
150 x_version = hashlib.sha1('_'.join((paths[-1], q['expires'][0], '5nFp9kmbNnHdAFhaqMvt')).encode()).hexdigest()
151
152 preference = qualities(['preview', '360', '540', 'Source'])
153
154 files = self._download_json(fileurl, video_id, headers={'X-Version': x_version})
155 for fmt in files:
156 yield traverse_obj(fmt, {
157 'format_id': 'name',
158 'url': ('src', ('view', 'download'), {self._proto_relative_url}),
159 'ext': ('type', {mimetype2ext}),
160 'quality': ('name', {preference}),
161 'height': ('name', {int_or_none}),
162 }, get_all=False)
163
164 def _real_extract(self, url):
165 video_id = self._match_id(url)
166 username, _ = self._get_login_info()
167 video_data = self._download_json(
168 f'https://api.iwara.tv/video/{video_id}', video_id,
169 expected_status=lambda x: True, headers=self._get_media_token())
170 errmsg = video_data.get('message')
171 # at this point we can actually get uploaded user info, but do we need it?
172 if errmsg == 'errors.privateVideo':
173 self.raise_login_required('Private video. Login if you have permissions to watch', method='password')
174 elif errmsg == 'errors.notFound' and not username:
175 self.raise_login_required('Video may need login to view', method='password')
176 elif errmsg: # None if success
177 raise ExtractorError(f'Iwara says: {errmsg}')
178
179 if not video_data.get('fileUrl'):
180 if video_data.get('embedUrl'):
181 return self.url_result(video_data.get('embedUrl'))
182 raise ExtractorError('This video is unplayable', expected=True)
183
184 return {
185 'id': video_id,
186 'age_limit': 18 if video_data.get('rating') == 'ecchi' else 0, # ecchi is 'sexy' in Japanese
187 **traverse_obj(video_data, {
188 'title': 'title',
189 'description': 'body',
190 'uploader': ('user', 'name'),
191 'uploader_id': ('user', 'username'),
192 'tags': ('tags', ..., 'id'),
193 'like_count': 'numLikes',
194 'view_count': 'numViews',
195 'comment_count': 'numComments',
196 'timestamp': ('createdAt', {unified_timestamp}),
197 'modified_timestamp': ('updatedAt', {unified_timestamp}),
198 'thumbnail': ('file', 'id', {str}, {
199 lambda x: f'https://files.iwara.tv/image/thumbnail/{x}/thumbnail-00.jpg'}),
200 }),
201 'formats': list(self._extract_formats(video_id, video_data.get('fileUrl'))),
202 }
203
204
205 class IwaraUserIE(IwaraBaseIE):
206 _VALID_URL = r'https?://(?:www\.)?iwara\.tv/profile/(?P<id>[^/?#&]+)'
207 IE_NAME = 'iwara:user'
208 _PER_PAGE = 32
209
210 _TESTS = [{
211 'url': 'https://iwara.tv/profile/user792540/videos',
212 'info_dict': {
213 'id': 'user792540',
214 'title': 'Lyu ya',
215 },
216 'playlist_mincount': 70,
217 }, {
218 'url': 'https://iwara.tv/profile/theblackbirdcalls/videos',
219 'info_dict': {
220 'id': 'theblackbirdcalls',
221 'title': 'TheBlackbirdCalls',
222 },
223 'playlist_mincount': 723,
224 }, {
225 'url': 'https://iwara.tv/profile/user792540',
226 'only_matching': True,
227 }, {
228 'url': 'https://iwara.tv/profile/theblackbirdcalls',
229 'only_matching': True,
230 }, {
231 'url': 'https://www.iwara.tv/profile/lumymmd',
232 'info_dict': {
233 'id': 'lumymmd',
234 'title': 'Lumy MMD',
235 },
236 'playlist_mincount': 1,
237 }]
238
239 def _entries(self, playlist_id, user_id, page):
240 videos = self._download_json(
241 'https://api.iwara.tv/videos', playlist_id,
242 note=f'Downloading page {page}',
243 query={
244 'page': page,
245 'sort': 'date',
246 'user': user_id,
247 'limit': self._PER_PAGE,
248 }, headers=self._get_media_token())
249 for x in traverse_obj(videos, ('results', ..., 'id')):
250 yield self.url_result(f'https://iwara.tv/video/{x}')
251
252 def _real_extract(self, url):
253 playlist_id = self._match_id(url)
254 user_info = self._download_json(
255 f'https://api.iwara.tv/profile/{playlist_id}', playlist_id,
256 note='Requesting user info')
257 user_id = traverse_obj(user_info, ('user', 'id'))
258
259 return self.playlist_result(
260 OnDemandPagedList(
261 functools.partial(self._entries, playlist_id, user_id),
262 self._PER_PAGE),
263 playlist_id, traverse_obj(user_info, ('user', 'name')))
264
265
266 class IwaraPlaylistIE(IwaraBaseIE):
267 _VALID_URL = r'https?://(?:www\.)?iwara\.tv/playlist/(?P<id>[0-9a-f-]+)'
268 IE_NAME = 'iwara:playlist'
269 _PER_PAGE = 32
270
271 _TESTS = [{
272 'url': 'https://iwara.tv/playlist/458e5486-36a4-4ac0-b233-7e9eef01025f',
273 'info_dict': {
274 'id': '458e5486-36a4-4ac0-b233-7e9eef01025f',
275 },
276 'playlist_mincount': 3,
277 }]
278
279 def _entries(self, playlist_id, first_page, page):
280 videos = self._download_json(
281 'https://api.iwara.tv/videos', playlist_id, f'Downloading page {page}',
282 query={'page': page, 'limit': self._PER_PAGE},
283 headers=self._get_media_token()) if page else first_page
284 for x in traverse_obj(videos, ('results', ..., 'id')):
285 yield self.url_result(f'https://iwara.tv/video/{x}')
286
287 def _real_extract(self, url):
288 playlist_id = self._match_id(url)
289 page_0 = self._download_json(
290 f'https://api.iwara.tv/playlist/{playlist_id}?page=0&limit={self._PER_PAGE}', playlist_id,
291 note='Requesting playlist info', headers=self._get_media_token())
292
293 return self.playlist_result(
294 OnDemandPagedList(
295 functools.partial(self._entries, playlist_id, page_0),
296 self._PER_PAGE),
297 playlist_id, traverse_obj(page_0, ('title', 'name')))