| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# This program is free software; you can redistribute it and/or modify |
| 4 |
# it under the terms of the GNU General Public License version 2 as |
| 5 |
# published by the Free Software Foundation. |
| 6 |
|
| 7 |
"""Extractors for https://www.iwara.tv/""" |
| 8 |
|
| 9 |
from .common import Extractor, Message, Dispatch |
| 10 |
from .. import text, util |
| 11 |
import hashlib |
| 12 |
|
| 13 |
BASE_PATTERN = r"(?:https?://)?(?:www\.)?iwara\.(tv|ai)" |
| 14 |
USER_PATTERN = BASE_PATTERN + r"/profile/([^/?#]+)" |
| 15 |
|
| 16 |
|
| 17 |
class IwaraExtractor(Extractor): |
| 18 |
"""Base class for iwara.tv extractors""" |
| 19 |
category = "iwara" |
| 20 |
root = "https://www.iwara.tv" |
| 21 |
directory_fmt = ("{category}", "{user[name]}") |
| 22 |
filename_fmt = "{date} {id} {title[:200]} {filename}.{extension}" |
| 23 |
archive_fmt = "{type} {user[name]} {id} {file_id}" |
| 24 |
|
| 25 |
def _init(self): |
| 26 |
self.root = "https://www.iwara." + self.groups[0] |
| 27 |
self.api = IwaraAPI(self) |
| 28 |
|
| 29 |
self.embeds = self.config("embeds", False) |
| 30 |
if fmts := self.config("format"): |
| 31 |
if isinstance(fmts, str): |
| 32 |
fmts = fmts.replace(" ", "").lower().split(",") |
| 33 |
elif not isinstance(fmts, (list, tuple)): |
| 34 |
fmts = (str(fmts),) |
| 35 |
self.formats = fmts |
| 36 |
self.extract_video_source = self.extract_video_source_custom |
| 37 |
|
| 38 |
def items_image(self, images, user=None): |
| 39 |
for image in images: |
| 40 |
try: |
| 41 |
if "image" in image: |
| 42 |
# could extract 'date_favorited' here |
| 43 |
image = image["image"] |
| 44 |
if not (files := image.get("files")): |
| 45 |
image = self.api.image(image["id"]) |
| 46 |
files = image["files"] |
| 47 |
|
| 48 |
group_info = self.extract_media_info(image, "file", False) |
| 49 |
group_info["user"] = (self.extract_user_info(image) |
| 50 |
if user is None else user) |
| 51 |
except Exception as exc: |
| 52 |
self.status |= 1 |
| 53 |
self.log.error("Failed to process image %s (%s: %s)", |
| 54 |
image["id"], exc.__class__.__name__, exc) |
| 55 |
continue |
| 56 |
|
| 57 |
group_info["type"] = "image" |
| 58 |
group_info["count"] = len(files) |
| 59 |
yield Message.Directory, "", group_info |
| 60 |
for num, file in enumerate(files, 1): |
| 61 |
file_info = self.extract_media_info(file) |
| 62 |
file_id = file_info["file_id"] |
| 63 |
url = (f"https://i.iwara.tv/image/original/" |
| 64 |
f"{file_id}/{file_id}.{file_info['extension']}") |
| 65 |
yield Message.Url, url, {**file_info, **group_info, "num": num} |
| 66 |
|
| 67 |
def items_video(self, videos, user=None): |
| 68 |
for video in videos: |
| 69 |
try: |
| 70 |
if "video" in video: |
| 71 |
video = video["video"] |
| 72 |
|
| 73 |
if embed := video.get("embedUrl"): |
| 74 |
if not self.embeds: |
| 75 |
self.log.warning("%s: Skipping embed", video["id"]) |
| 76 |
continue |
| 77 |
download_url = "ytdl:" + embed |
| 78 |
info = self.extract_media_info(video) |
| 79 |
info["format"] = "embed" |
| 80 |
else: |
| 81 |
if "fileUrl" not in video: |
| 82 |
video = self.api.video(video["id"]) |
| 83 |
|
| 84 |
source = self.extract_video_source(self.api.source( |
| 85 |
video["fileUrl"])) |
| 86 |
download_url = "https:" + source["src"].get("download") |
| 87 |
|
| 88 |
info = self.extract_media_info(video, "file") |
| 89 |
info["format"] = source.get("name") |
| 90 |
info["_fallback"] = self._fallback_video(download_url) |
| 91 |
info["count"] = info["num"] = 1 |
| 92 |
info["user"] = (self.extract_user_info(video) |
| 93 |
if user is None else user) |
| 94 |
except Exception as exc: |
| 95 |
self.status |= 1 |
| 96 |
self.log.traceback(exc) |
| 97 |
self.log.error("Failed to process video %s (%s: %s)", |
| 98 |
video["id"], exc.__class__.__name__, exc) |
| 99 |
continue |
| 100 |
|
| 101 |
yield Message.Directory, "", info |
| 102 |
yield Message.Url, download_url, info |
| 103 |
|
| 104 |
def _fallback_video(self, url): |
| 105 |
sub, sep, url = url[5:].partition(".") |
| 106 |
sub = sub.lstrip("//") |
| 107 |
for server in ("mikoto", "hime", "himeko", "yuko"): |
| 108 |
if server != sub: |
| 109 |
yield f"https://{server}.{url}" |
| 110 |
|
| 111 |
def items_user(self, users, key=None): |
| 112 |
base = self.root + "/profile/" |
| 113 |
for user in users: |
| 114 |
if key is not None: |
| 115 |
user = user[key] |
| 116 |
if (username := user["username"]) is None: |
| 117 |
continue |
| 118 |
user["type"] = "user" |
| 119 |
user["_extractor"] = IwaraUserExtractor |
| 120 |
yield Message.Queue, base + username, user |
| 121 |
|
| 122 |
def items_by_type(self, type, results): |
| 123 |
if type == "image": |
| 124 |
return self.items_image(results) |
| 125 |
if type == "video": |
| 126 |
return self.items_video(results) |
| 127 |
if type == "user": |
| 128 |
return self.items_user(results) |
| 129 |
|
| 130 |
raise self.exc.AbortExtraction(f"Unsupported result type '{type}'") |
| 131 |
|
| 132 |
def extract_media_info(self, item, key=None, include_file_info=True): |
| 133 |
info = { |
| 134 |
"id" : item["id"], |
| 135 |
"slug" : item.get("slug"), |
| 136 |
"rating" : item.get("rating"), |
| 137 |
"likes" : item.get("numLikes"), |
| 138 |
"views" : item.get("numViews"), |
| 139 |
"comments": item.get("numComments"), |
| 140 |
"tags" : [t["id"] for t in item.get("tags") or ()], |
| 141 |
"title" : t.strip() if (t := item.get("title")) else "", |
| 142 |
"description": t.strip() if (t := item.get("body")) else "", |
| 143 |
} |
| 144 |
|
| 145 |
if include_file_info: |
| 146 |
file_info = item if key is None else item.get(key) or {} |
| 147 |
filename, _, extension = file_info.get("name", "").rpartition(".") |
| 148 |
|
| 149 |
info["file_id"] = file_info.get("id") |
| 150 |
info["filename"] = filename |
| 151 |
info["extension"] = extension |
| 152 |
info["date"] = self.parse_datetime_iso( |
| 153 |
file_info.get("createdAt")) |
| 154 |
info["date_updated"] = self.parse_datetime_iso( |
| 155 |
file_info.get("updatedAt")) |
| 156 |
info["mime"] = file_info.get("mime") |
| 157 |
info["size"] = file_info.get("size") |
| 158 |
info["width"] = file_info.get("width") |
| 159 |
info["height"] = file_info.get("height") |
| 160 |
info["duration"] = file_info.get("duration") |
| 161 |
info["type"] = file_info.get("type") |
| 162 |
|
| 163 |
return info |
| 164 |
|
| 165 |
def extract_user_info(self, profile): |
| 166 |
user = profile.get("user") or {} |
| 167 |
return { |
| 168 |
"id" : user.get("id"), |
| 169 |
"name" : user.get("username"), |
| 170 |
"nick" : user.get("name").strip(), |
| 171 |
"status" : user.get("status"), |
| 172 |
"role" : user.get("role"), |
| 173 |
"premium": user.get("premium"), |
| 174 |
"date" : self.parse_datetime_iso(user.get("createdAt")), |
| 175 |
"description": profile.get("body"), |
| 176 |
} |
| 177 |
|
| 178 |
def extract_video_source(self, sources): |
| 179 |
sources.sort(key=self._sort_formats, reverse=True) |
| 180 |
return sources[0] |
| 181 |
|
| 182 |
def extract_video_source_custom(self, sources): |
| 183 |
fmts = { |
| 184 |
name.lower(): source |
| 185 |
for source in sources |
| 186 |
if source.get("src") and (name := source.get("name")) |
| 187 |
} |
| 188 |
|
| 189 |
for fmt in self.formats: |
| 190 |
if fmt in fmts: |
| 191 |
return fmts[fmt] |
| 192 |
self.log.warning("Requested format(s) not available") |
| 193 |
|
| 194 |
def _user_params(self): |
| 195 |
_, user, qs = self.groups |
| 196 |
params = text.parse_query(qs) |
| 197 |
profile = self.cache(self.api.profile, user) |
| 198 |
params["user"] = profile["user"]["id"] |
| 199 |
return self.extract_user_info(profile), params |
| 200 |
|
| 201 |
def _sort_formats(self, fmt): |
| 202 |
return (0 if not fmt.get("src") else |
| 203 |
99999 if (name := fmt.get("name")) == "Source" else |
| 204 |
text.parse_int(name)) |
| 205 |
|
| 206 |
|
| 207 |
class IwaraUserExtractor(Dispatch, IwaraExtractor): |
| 208 |
"""Extractor for iwara.tv profile pages""" |
| 209 |
pattern = USER_PATTERN + r"/?$" |
| 210 |
example = "https://www.iwara.tv/profile/USERNAME" |
| 211 |
|
| 212 |
def items(self): |
| 213 |
tld, user = self.groups |
| 214 |
base = f"{self.root[:-2]}{tld}/profile/{user}/" |
| 215 |
return self._dispatch_extractors(( |
| 216 |
(IwaraUserImagesExtractor , base + "images"), |
| 217 |
(IwaraUserVideosExtractor , base + "videos"), |
| 218 |
(IwaraUserPlaylistsExtractor, base + "playlists"), |
| 219 |
), ("user-images", "user-videos")) |
| 220 |
|
| 221 |
|
| 222 |
class IwaraUserImagesExtractor(IwaraExtractor): |
| 223 |
subcategory = "user-images" |
| 224 |
pattern = USER_PATTERN + r"/images(?:\?([^#]+))?" |
| 225 |
example = "https://www.iwara.tv/profile/USERNAME/images" |
| 226 |
|
| 227 |
def items(self): |
| 228 |
user, params = self._user_params() |
| 229 |
return self.items_image(self.api.images(params), user) |
| 230 |
|
| 231 |
|
| 232 |
class IwaraUserVideosExtractor(IwaraExtractor): |
| 233 |
subcategory = "user-videos" |
| 234 |
pattern = USER_PATTERN + r"/videos(?:\?([^#]+))?" |
| 235 |
example = "https://www.iwara.tv/profile/USERNAME/videos" |
| 236 |
|
| 237 |
def items(self): |
| 238 |
user, params = self._user_params() |
| 239 |
return self.items_video(self.api.videos(params), user) |
| 240 |
|
| 241 |
|
| 242 |
class IwaraUserPlaylistsExtractor(IwaraExtractor): |
| 243 |
subcategory = "user-playlists" |
| 244 |
pattern = USER_PATTERN + r"/playlists(?:\?([^#]+))?" |
| 245 |
example = "https://www.iwara.tv/profile/USERNAME/playlists" |
| 246 |
|
| 247 |
def items(self): |
| 248 |
base = self.root + "/playlist/" |
| 249 |
|
| 250 |
for playlist in self.api.playlists(self._user_params()[1]): |
| 251 |
playlist["type"] = "playlist" |
| 252 |
playlist["_extractor"] = IwaraPlaylistExtractor |
| 253 |
url = base + playlist["id"] |
| 254 |
yield Message.Queue, url, playlist |
| 255 |
|
| 256 |
|
| 257 |
class IwaraFollowingExtractor(IwaraExtractor): |
| 258 |
subcategory = "following" |
| 259 |
pattern = USER_PATTERN + r"/following" |
| 260 |
example = "https://www.iwara.tv/profile/USERNAME/following" |
| 261 |
|
| 262 |
def items(self): |
| 263 |
uid = self.cache(self.api.profile, self.groups[1])["user"]["id"] |
| 264 |
return self.items_user(self.api.user_following(uid), "user") |
| 265 |
|
| 266 |
|
| 267 |
class IwaraFollowersExtractor(IwaraExtractor): |
| 268 |
subcategory = "followers" |
| 269 |
pattern = USER_PATTERN + r"/followers" |
| 270 |
example = "https://www.iwara.tv/profile/USERNAME/followers" |
| 271 |
|
| 272 |
def items(self): |
| 273 |
uid = self.cache(self.api.profile, self.groups[1])["user"]["id"] |
| 274 |
return self.items_user(self.api.user_followers(uid), "follower") |
| 275 |
|
| 276 |
|
| 277 |
class IwaraImageExtractor(IwaraExtractor): |
| 278 |
"""Extractor for individual iwara.tv image pages""" |
| 279 |
subcategory = "image" |
| 280 |
pattern = BASE_PATTERN + r"/image/([^/?#]+)" |
| 281 |
example = "https://www.iwara.tv/image/ID" |
| 282 |
|
| 283 |
def items(self): |
| 284 |
return self.items_image((self.api.image(self.groups[1]),)) |
| 285 |
|
| 286 |
|
| 287 |
class IwaraVideoExtractor(IwaraExtractor): |
| 288 |
"""Extractor for individual iwara.tv videos""" |
| 289 |
subcategory = "video" |
| 290 |
pattern = BASE_PATTERN + r"/video/([^/?#]+)" |
| 291 |
example = "https://www.iwara.tv/video/ID" |
| 292 |
|
| 293 |
def items(self): |
| 294 |
return self.items_video((self.api.video(self.groups[1]),)) |
| 295 |
|
| 296 |
|
| 297 |
class IwaraPlaylistExtractor(IwaraExtractor): |
| 298 |
"""Extractor for individual iwara.tv playlist pages""" |
| 299 |
subcategory = "playlist" |
| 300 |
pattern = BASE_PATTERN + r"/playlist/([^/?#]+)" |
| 301 |
example = "https://www.iwara.tv/playlist/ID" |
| 302 |
|
| 303 |
def items(self): |
| 304 |
return self.items_video(self.api.playlist(self.groups[1])) |
| 305 |
|
| 306 |
|
| 307 |
class IwaraFavoriteExtractor(IwaraExtractor): |
| 308 |
subcategory = "favorite" |
| 309 |
pattern = BASE_PATTERN + r"/favorites(?:/(image|video)s)?" |
| 310 |
example = "https://www.iwara.tv/favorites/videos" |
| 311 |
|
| 312 |
def items(self): |
| 313 |
type = self.groups[1] or "vidoo" |
| 314 |
return self.items_by_type(type, self.api.favorites(type)) |
| 315 |
|
| 316 |
|
| 317 |
class IwaraSearchExtractor(IwaraExtractor): |
| 318 |
"""Extractor for iwara.tv search pages""" |
| 319 |
subcategory = "search" |
| 320 |
pattern = BASE_PATTERN + r"/search\?([^#]+)" |
| 321 |
example = "https://www.iwara.tv/search?query=QUERY&type=TYPE" |
| 322 |
|
| 323 |
def items(self): |
| 324 |
params = text.parse_query(self.groups[1]) |
| 325 |
type = params.get("type") or "videos" |
| 326 |
if type[-1] != "s": |
| 327 |
type += "s" |
| 328 |
self.kwdict["search_tags"] = query = params.get("query") |
| 329 |
return self.items_by_type(type[:-1], self.api.search(type, query)) |
| 330 |
|
| 331 |
|
| 332 |
class IwaraTagExtractor(IwaraExtractor): |
| 333 |
"""Extractor for iwara.tv tag search""" |
| 334 |
subcategory = "tag" |
| 335 |
pattern = BASE_PATTERN + r"/(image|video)s(?:\?([^#]+))?" |
| 336 |
example = "https://www.iwara.tv/videos?tags=TAGS" |
| 337 |
|
| 338 |
def items(self): |
| 339 |
_, type, qs = self.groups |
| 340 |
params = text.parse_query(qs) |
| 341 |
self.kwdict["search_tags"] = params.get("tags") |
| 342 |
return self.items_by_type(type, self.api.media(type, params)) |
| 343 |
|
| 344 |
|
| 345 |
class IwaraAPI(): |
| 346 |
"""Interface for the Iwara API""" |
| 347 |
root = "https://apiq.iwara.tv" |
| 348 |
|
| 349 |
def __init__(self, extractor): |
| 350 |
self.extractor = extractor |
| 351 |
self.exc = extractor.exc |
| 352 |
self.headers = { |
| 353 |
"Content-Type": "application/json", |
| 354 |
"X-Site" : extractor.root[8:], |
| 355 |
} |
| 356 |
|
| 357 |
self.username, self.password = extractor._get_auth_info() |
| 358 |
if not self.username: |
| 359 |
self.authenticate = util.noop |
| 360 |
|
| 361 |
def image(self, image_id): |
| 362 |
endpoint = "/image/" + image_id |
| 363 |
return self._call(endpoint) |
| 364 |
|
| 365 |
def video(self, video_id): |
| 366 |
endpoint = "/video/" + video_id |
| 367 |
return self._call(endpoint) |
| 368 |
|
| 369 |
def playlist(self, playlist_id): |
| 370 |
endpoint = "/playlist/" + playlist_id |
| 371 |
return self._pagination(endpoint) |
| 372 |
|
| 373 |
def detail(self, media): |
| 374 |
endpoint = f"/{media['type']}/{media['id']}" |
| 375 |
return self._call(endpoint) |
| 376 |
|
| 377 |
def images(self, params): |
| 378 |
endpoint = "/images" |
| 379 |
params.setdefault("rating", "all") |
| 380 |
return self._pagination(endpoint, params) |
| 381 |
|
| 382 |
def videos(self, params): |
| 383 |
endpoint = "/videos" |
| 384 |
params.setdefault("rating", "all") |
| 385 |
return self._pagination(endpoint, params) |
| 386 |
|
| 387 |
def playlists(self, params): |
| 388 |
endpoint = "/playlists" |
| 389 |
return self._pagination(endpoint, params) |
| 390 |
|
| 391 |
def media(self, type, params): |
| 392 |
endpoint = f"/{type}s" |
| 393 |
params.setdefault("rating", "all") |
| 394 |
return self._pagination(endpoint, params) |
| 395 |
|
| 396 |
def favorites(self, type): |
| 397 |
if not self.username: |
| 398 |
raise self.exc.AuthRequired( |
| 399 |
"username & password", "your favorites") |
| 400 |
endpoint = f"/favorites/{type}s" |
| 401 |
return self._pagination(endpoint) |
| 402 |
|
| 403 |
def search(self, type, query): |
| 404 |
endpoint = "/search" |
| 405 |
params = {"type": type, "query": query} |
| 406 |
return self._pagination(endpoint, params) |
| 407 |
|
| 408 |
def profile(self, username): |
| 409 |
endpoint = "/profile/" + username |
| 410 |
return self._call(endpoint) |
| 411 |
|
| 412 |
def user_following(self, user_id): |
| 413 |
endpoint = f"/user/{user_id}/following" |
| 414 |
return self._pagination(endpoint) |
| 415 |
|
| 416 |
def user_followers(self, user_id): |
| 417 |
endpoint = f"/user/{user_id}/followers" |
| 418 |
return self._pagination(endpoint) |
| 419 |
|
| 420 |
def source(self, file_url): |
| 421 |
base, _, query = file_url.partition("?") |
| 422 |
if not (expires := text.extr(query, "expires=", "&")): |
| 423 |
return () |
| 424 |
file_id = base.rpartition("/")[2] |
| 425 |
sha_postfix = "mSvL05GfEmeEmsEYfGCnVpEjYgTJraJN" |
| 426 |
sha_key = f"{file_id}_{expires}_{sha_postfix}" |
| 427 |
hash = hashlib.sha1(sha_key.encode()).hexdigest() |
| 428 |
headers = {"X-Version": hash, **self.headers} |
| 429 |
return self.extractor.request_json(file_url, headers=headers) |
| 430 |
|
| 431 |
def authenticate(self): |
| 432 |
self.headers["Authorization"] = self.extractor.cache( |
| 433 |
self._authenticate_impl, self.username, _exp=3600, _mem=False) |
| 434 |
|
| 435 |
def _authenticate_impl(self, username): |
| 436 |
refresh_token = self.extractor.cache( |
| 437 |
_refresh_token_cache, username, _exp=28*86400, _mem=False) |
| 438 |
if refresh_token is None: |
| 439 |
self.extractor.log.info("Logging in as %s", username) |
| 440 |
|
| 441 |
url = self.root + "/user/login" |
| 442 |
json = { |
| 443 |
"email" : username, |
| 444 |
"password": self.password |
| 445 |
} |
| 446 |
data = self.extractor.request_json( |
| 447 |
url, method="POST", headers=self.headers, json=json, |
| 448 |
fatal=False) |
| 449 |
|
| 450 |
if not (refresh_token := data.get("token")): |
| 451 |
self.extractor.log.debug(data) |
| 452 |
raise self.exc.AuthenticationError(data.get("message")) |
| 453 |
self.extractor.cache_update( |
| 454 |
_refresh_token_cache, username, refresh_token, _exp=28*86400) |
| 455 |
|
| 456 |
self.extractor.log.info("Refreshing access token for %s", username) |
| 457 |
|
| 458 |
url = self.root + "/user/token" |
| 459 |
headers = {"Authorization": "Bearer " + refresh_token, **self.headers} |
| 460 |
data = self.extractor.request_json( |
| 461 |
url, method="POST", headers=headers, fatal=False) |
| 462 |
|
| 463 |
if not (access_token := data.get("accessToken")): |
| 464 |
self.extractor.log.debug(data) |
| 465 |
raise self.exc.AuthenticationError(data.get("message")) |
| 466 |
return "Bearer " + access_token |
| 467 |
|
| 468 |
def _call(self, endpoint, params=None, headers=None): |
| 469 |
if headers is None: |
| 470 |
headers = self.headers |
| 471 |
|
| 472 |
url = self.root + endpoint |
| 473 |
self.authenticate() |
| 474 |
return self.extractor.request_json(url, params=params, headers=headers) |
| 475 |
|
| 476 |
def _pagination(self, endpoint, params=None): |
| 477 |
if params is None: |
| 478 |
params = {} |
| 479 |
params["page"] = 0 |
| 480 |
params["limit"] = 50 |
| 481 |
|
| 482 |
while True: |
| 483 |
data = self._call(endpoint, params) |
| 484 |
|
| 485 |
if not (results := data.get("results")): |
| 486 |
break |
| 487 |
yield from results |
| 488 |
|
| 489 |
if len(results) < params["limit"]: |
| 490 |
break |
| 491 |
params["page"] += 1 |
| 492 |
|
| 493 |
|
| 494 |
def _refresh_token_cache(username): |
| 495 |
return None |