| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright 2019-2026 Mike Fährmann |
| 4 |
# |
| 5 |
# This program is free software; you can redistribute it and/or modify |
| 6 |
# it under the terms of the GNU General Public License version 2 as |
| 7 |
# published by the Free Software Foundation. |
| 8 |
|
| 9 |
"""Extractors for https://www.patreon.com/""" |
| 10 |
|
| 11 |
from .common import Extractor, Message |
| 12 |
from .. import text, util, dt |
| 13 |
import collections |
| 14 |
import itertools |
| 15 |
|
| 16 |
BASE_PATTERN = r"(?:https?://)?(?:www\.)?patreon\.com" |
| 17 |
|
| 18 |
|
| 19 |
class PatreonExtractor(Extractor): |
| 20 |
"""Base class for patreon extractors""" |
| 21 |
category = "patreon" |
| 22 |
root = "https://www.patreon.com" |
| 23 |
cookies_domain = ".patreon.com" |
| 24 |
directory_fmt = ("{category}", "{creator[full_name]}") |
| 25 |
filename_fmt = "{id}_{title}_{num:>02}.{extension}" |
| 26 |
archive_fmt = "{id}_{num}" |
| 27 |
useragent = "Patreon/126.24.0.9 (Android; Android 14; Scale/2.10)" |
| 28 |
_warning = True |
| 29 |
|
| 30 |
def _init(self): |
| 31 |
if self.cookies_check(("session_id",), subdomains=True): |
| 32 |
self._logged_in = True |
| 33 |
else: |
| 34 |
self._logged_in = False |
| 35 |
if self._warning: |
| 36 |
PatreonExtractor._warning = False |
| 37 |
self.log.warning("no 'session_id' cookie set") |
| 38 |
|
| 39 |
if format_images := self.config("format-images"): |
| 40 |
self._images_fmt = format_images |
| 41 |
self._images_url = self._images_url_fmt |
| 42 |
|
| 43 |
self._cursor = None |
| 44 |
|
| 45 |
def items(self): |
| 46 |
generators = self._build_file_generators(self.config("files")) |
| 47 |
|
| 48 |
for post in self.posts(): |
| 49 |
|
| 50 |
yield Message.Directory, "", post |
| 51 |
if not post.get("current_user_can_view", True): |
| 52 |
self.log.warning("Not allowed to view post %s", post["id"]) |
| 53 |
continue |
| 54 |
|
| 55 |
post["num"] = 0 |
| 56 |
hashes = set() |
| 57 |
for kind, file, url, name in itertools.chain.from_iterable( |
| 58 |
g(post) for g in generators): |
| 59 |
fhash = self._filehash(url) |
| 60 |
if fhash not in hashes or not fhash: |
| 61 |
hashes.add(fhash) |
| 62 |
post["hash"] = fhash |
| 63 |
post["type"] = kind |
| 64 |
post["file"] = file |
| 65 |
post["num"] += 1 |
| 66 |
text.nameext_from_url(name, post) |
| 67 |
if text.ext_from_url(url) == "m3u8": |
| 68 |
url = "ytdl:" + url |
| 69 |
headers = {"referer": self.root + "/"} |
| 70 |
post["_ytdl_manifest"] = "hls" |
| 71 |
post["_ytdl_manifest_headers"] = headers |
| 72 |
post["_ytdl_extra"] = {"http_headers": headers} |
| 73 |
post["extension"] = "mp4" |
| 74 |
yield Message.Url, url, post |
| 75 |
else: |
| 76 |
self.log.debug("skipping %s (%s %s)", url, fhash, kind) |
| 77 |
|
| 78 |
def finalize(self, status): |
| 79 |
if status and self._cursor: |
| 80 |
self.log.info("Use '-o cursor=%s' to continue downloading " |
| 81 |
"from the current position", self._cursor) |
| 82 |
|
| 83 |
def _postfile(self, post): |
| 84 |
if postfile := post.get("post_file"): |
| 85 |
url = postfile["url"] |
| 86 |
if not (name := postfile.get("name")): |
| 87 |
if url.startswith("https://stream.mux.com/"): |
| 88 |
name = url |
| 89 |
else: |
| 90 |
name = self._filename(url) or url |
| 91 |
return (("postfile", postfile, url, name),) |
| 92 |
return () |
| 93 |
|
| 94 |
def _images(self, post): |
| 95 |
if images := post.get("images"): |
| 96 |
for image in images: |
| 97 |
if url := self._images_url(image): |
| 98 |
name = image.get("file_name") or self._filename(url) or url |
| 99 |
yield "image", image, url, name |
| 100 |
|
| 101 |
def _images_url(self, image): |
| 102 |
return image.get("download_url") |
| 103 |
|
| 104 |
def _images_url_fmt(self, image): |
| 105 |
try: |
| 106 |
return image["image_urls"][self._images_fmt] |
| 107 |
except Exception: |
| 108 |
return image.get("download_url") |
| 109 |
|
| 110 |
def _image_large(self, post): |
| 111 |
if image := post.get("image"): |
| 112 |
if url := image.get("large_url"): |
| 113 |
name = image.get("file_name") or self._filename(url) or url |
| 114 |
return (("image_large", image, url, name),) |
| 115 |
return () |
| 116 |
|
| 117 |
def _attachments(self, post): |
| 118 |
for attachment in post.get("attachments") or (): |
| 119 |
if url := self.request_location(attachment["url"], fatal=False): |
| 120 |
yield "attachment", attachment, url, attachment["name"] |
| 121 |
|
| 122 |
for attachment in post.get("attachments_media") or (): |
| 123 |
if url := attachment.get("download_url"): |
| 124 |
yield "attachment", attachment, url, attachment["file_name"] |
| 125 |
|
| 126 |
def _content(self, post): |
| 127 |
if content := post.get("content"): |
| 128 |
pattern = text.re(r'><(?:figure><img|video) src="([^"]+)([^>]*)') |
| 129 |
for url, attrs in pattern.findall(content): |
| 130 |
url = text.unescape(url) |
| 131 |
data = {"media_id": text.extr(attrs, 'media_id="', '"')} |
| 132 |
yield "content", data, url, self._filename(url) or url |
| 133 |
|
| 134 |
def posts(self): |
| 135 |
"""Return all relevant post objects""" |
| 136 |
|
| 137 |
def _pagination(self, url): |
| 138 |
headers = { |
| 139 |
"Content-Type": "application/vnd.api+json", |
| 140 |
} |
| 141 |
|
| 142 |
while url: |
| 143 |
self._update_cursor(url) |
| 144 |
url = text.ensure_http_scheme(url) |
| 145 |
posts = self.request_json(url, headers=headers) |
| 146 |
|
| 147 |
if "included" in posts: |
| 148 |
included = self._transform(posts["included"]) |
| 149 |
for post in posts["data"]: |
| 150 |
yield self._process(post, included) |
| 151 |
|
| 152 |
if "links" not in posts: |
| 153 |
break |
| 154 |
url = posts["links"].get("next") |
| 155 |
|
| 156 |
self._update_cursor("") |
| 157 |
|
| 158 |
def _init_cursor(self): |
| 159 |
if cursor := self.config("cursor", True): |
| 160 |
return "" if cursor is True else cursor |
| 161 |
self._update_cursor = util.identity |
| 162 |
return "" |
| 163 |
|
| 164 |
def _update_cursor(self, url): |
| 165 |
params = text.parse_query(url.partition("?")[2]) |
| 166 |
self._cursor = cursor = params.get("page[cursor]") |
| 167 |
if cursor: |
| 168 |
self.log.debug("Cursor: %s", cursor) |
| 169 |
return cursor |
| 170 |
|
| 171 |
def _process(self, post, included): |
| 172 |
"""Process and extend a 'post' object""" |
| 173 |
attr = post["attributes"] |
| 174 |
attr["id"] = text.parse_int(post["id"]) |
| 175 |
|
| 176 |
relationships = post["relationships"] |
| 177 |
attr["images"] = self._files( |
| 178 |
post, included, "images") |
| 179 |
attr["attachments"] = self._files( |
| 180 |
post, included, "attachments") |
| 181 |
attr["attachments_media"] = self._files( |
| 182 |
post, included, "attachments_media") |
| 183 |
attr["date"] = self.parse_datetime_iso(attr["published_at"]) |
| 184 |
|
| 185 |
try: |
| 186 |
attr["campaign"] = (included["campaign"][ |
| 187 |
relationships["campaign"]["data"]["id"]]) |
| 188 |
except Exception: |
| 189 |
attr["campaign"] = None |
| 190 |
|
| 191 |
tags = relationships.get("user_defined_tags") |
| 192 |
attr["tags"] = [ |
| 193 |
tag["id"].replace("user_defined;", "") |
| 194 |
for tag in tags["data"] |
| 195 |
if tag["type"] == "post_tag" |
| 196 |
] if tags else [] |
| 197 |
|
| 198 |
user = relationships["user"] |
| 199 |
attr["creator"] = ( |
| 200 |
self.cache(self._user, user["links"]["related"]) or |
| 201 |
included["user"][user["data"]["id"]]) |
| 202 |
|
| 203 |
if not attr.get("content") and ( |
| 204 |
cjs := attr.pop("content_json_string", None)): |
| 205 |
try: |
| 206 |
attr["content"] = self.utils("tiptap").to_html(cjs) |
| 207 |
except Exception as exc: |
| 208 |
self.log.traceback(exc) |
| 209 |
self.log.warning( |
| 210 |
"%s: Failed to parse content_json_string (%s: %s)", |
| 211 |
attr["id"], exc.__class__.__name__, exc) |
| 212 |
|
| 213 |
return attr |
| 214 |
|
| 215 |
def _transform(self, included): |
| 216 |
"""Transform 'included' into an easier to handle format""" |
| 217 |
result = collections.defaultdict(dict) |
| 218 |
for inc in included: |
| 219 |
result[inc["type"]][inc["id"]] = inc["attributes"] |
| 220 |
return result |
| 221 |
|
| 222 |
def _files(self, post, included, key): |
| 223 |
"""Build a list of files""" |
| 224 |
files = post["relationships"].get(key) |
| 225 |
if files and files.get("data"): |
| 226 |
return [ |
| 227 |
included[file["type"]][file["id"]] |
| 228 |
for file in files["data"] |
| 229 |
] |
| 230 |
return [] |
| 231 |
|
| 232 |
def _user(self, url): |
| 233 |
"""Fetch user information""" |
| 234 |
response = self.request(url, fatal=False) |
| 235 |
if response.status_code >= 400: |
| 236 |
return None |
| 237 |
user = response.json()["data"] |
| 238 |
attr = user["attributes"] |
| 239 |
attr["id"] = user["id"] |
| 240 |
attr["date"] = self.parse_datetime_iso(attr["created"]) |
| 241 |
return attr |
| 242 |
|
| 243 |
def _collection(self, collection_id): |
| 244 |
url = f"{self.root}/api/collection/{collection_id}" |
| 245 |
data = self.request_json(url) |
| 246 |
coll = data["data"] |
| 247 |
attr = coll["attributes"] |
| 248 |
attr["id"] = coll["id"] |
| 249 |
attr["date"] = self.parse_datetime_iso(attr["created_at"]) |
| 250 |
return attr |
| 251 |
|
| 252 |
def _filename(self, url): |
| 253 |
"""Fetch filename from an URL's Content-Disposition header""" |
| 254 |
response = self.request(url, method="HEAD", fatal=False) |
| 255 |
return text.filename_from_contentdisposition( |
| 256 |
response.headers.get("content-disposition", "")) |
| 257 |
|
| 258 |
def _filehash(self, url): |
| 259 |
"""Extract MD5 hash from a download URL""" |
| 260 |
parts = url.partition("?")[0].split("/") |
| 261 |
parts.reverse() |
| 262 |
|
| 263 |
for part in parts: |
| 264 |
if len(part) == 32: |
| 265 |
return part |
| 266 |
return "" |
| 267 |
|
| 268 |
def _build_url(self, endpoint, sort, query): |
| 269 |
return ( |
| 270 |
f"https://www.patreon.com/api/{endpoint}" |
| 271 |
|
| 272 |
"?include=campaign,access_rules,attachments,attachments_media," |
| 273 |
"audio,images,media,native_video_insights,poll.choices," |
| 274 |
"poll.current_user_responses.user," |
| 275 |
"poll.current_user_responses.choice," |
| 276 |
"poll.current_user_responses.poll," |
| 277 |
"user,user_defined_tags,ti_checks" |
| 278 |
|
| 279 |
"&fields[campaign]=currency,show_audio_post_download_links," |
| 280 |
"avatar_photo_url,avatar_photo_image_urls,earnings_visibility," |
| 281 |
"is_nsfw,is_monthly,name,url" |
| 282 |
|
| 283 |
"&fields[post]=change_visibility_at,comment_count,commenter_count," |
| 284 |
"content,content_json_string,current_user_can_comment," |
| 285 |
"current_user_can_delete,current_user_can_view," |
| 286 |
"current_user_has_liked,embed,image,insights_last_updated_at," |
| 287 |
"is_paid,like_count,meta_image_url,min_cents_pledged_to_view," |
| 288 |
"post_file,post_metadata,published_at,patreon_url,post_type," |
| 289 |
"pledge_url,preview_asset_type,thumbnail,thumbnail_url," |
| 290 |
"teaser_text,title,upgrade_url,url,was_posted_by_campaign_owner," |
| 291 |
"has_ti_violation,moderation_status," |
| 292 |
"post_level_suspension_removal_date,pls_one_liners_by_category," |
| 293 |
"video_preview,view_count" |
| 294 |
|
| 295 |
"&fields[post_tag]=tag_type,value" |
| 296 |
"&fields[user]=image_url,full_name,url" |
| 297 |
"&fields[access_rule]=access_rule_type,amount_cents" |
| 298 |
"&fields[media]=id,image_urls,download_url,metadata,file_name" |
| 299 |
"&fields[native_video_insights]=average_view_duration," |
| 300 |
"average_view_pct,has_preview,id,last_updated_at,num_views," |
| 301 |
"preview_views,video_duration" |
| 302 |
|
| 303 |
f"&page[cursor]={self._init_cursor()}" |
| 304 |
f"{query}{self._order(sort)}" |
| 305 |
|
| 306 |
"&json-api-version=1.0" |
| 307 |
) |
| 308 |
|
| 309 |
def _order(self, sort): |
| 310 |
if order := self.config("order-posts"): |
| 311 |
if order in {"d", "desc"}: |
| 312 |
order = "-published_at" |
| 313 |
elif order in {"a", "asc", "r", "reverse"}: |
| 314 |
order = "published_at" |
| 315 |
return "&sort=" + order |
| 316 |
return "&sort=" + sort if sort else "" |
| 317 |
|
| 318 |
def _build_file_generators(self, filetypes): |
| 319 |
if filetypes is None: |
| 320 |
return (self._images, self._image_large, |
| 321 |
self._attachments, self._postfile, self._content) |
| 322 |
genmap = { |
| 323 |
"images" : self._images, |
| 324 |
"image_large": self._image_large, |
| 325 |
"attachments": self._attachments, |
| 326 |
"postfile" : self._postfile, |
| 327 |
"content" : self._content, |
| 328 |
} |
| 329 |
if isinstance(filetypes, str): |
| 330 |
filetypes = filetypes.split(",") |
| 331 |
return [genmap[ft] for ft in filetypes] |
| 332 |
|
| 333 |
def _extract_bootstrap(self, page): |
| 334 |
try: |
| 335 |
data = self._extract_nextdata(page) |
| 336 |
env = data["props"]["pageProps"]["bootstrapEnvelope"] |
| 337 |
return env.get("pageBootstrap") or env["bootstrap"] |
| 338 |
except Exception as exc: |
| 339 |
self.log.debug("%s: %s", exc.__class__.__name__, exc) |
| 340 |
|
| 341 |
bootstrap = text.extr( |
| 342 |
page, 'window.patreon = {"bootstrap":', '},"apiServer"') |
| 343 |
if bootstrap: |
| 344 |
return util.json_loads(bootstrap + "}") |
| 345 |
|
| 346 |
bootstrap = text.extr( |
| 347 |
page, |
| 348 |
'window.patreon = wrapInProxy({"bootstrap":', |
| 349 |
'},"apiServer"') |
| 350 |
if bootstrap: |
| 351 |
return util.json_loads(bootstrap + "}") |
| 352 |
|
| 353 |
if bootstrap := text.extr(page, "window.patreon.bootstrap,", "});"): |
| 354 |
return util.json_loads(bootstrap + "}") |
| 355 |
|
| 356 |
if data := text.extr(page, "window.patreon = {", "};\n"): |
| 357 |
try: |
| 358 |
return util.json_loads(f"{{{data}}}")["bootstrap"] |
| 359 |
except Exception: |
| 360 |
pass |
| 361 |
|
| 362 |
raise self.exc.AbortExtraction("Unable to extract bootstrap data") |
| 363 |
|
| 364 |
|
| 365 |
class PatreonCollectionExtractor(PatreonExtractor): |
| 366 |
"""Extractor for a patreon collection""" |
| 367 |
subcategory = "collection" |
| 368 |
directory_fmt = ("{category}", "{creator[full_name]}", |
| 369 |
"Collections", "{collection[title]} ({collection[id]})") |
| 370 |
pattern = BASE_PATTERN + r"/collection/(\d+)" |
| 371 |
example = "https://www.patreon.com/collection/12345" |
| 372 |
|
| 373 |
def posts(self): |
| 374 |
collection_id = self.groups[0] |
| 375 |
self.kwdict["collection"] = collection = \ |
| 376 |
self._collection(collection_id) |
| 377 |
campaign_id = text.extr( |
| 378 |
collection["thumbnail"]["url"], "/campaign/", "/") |
| 379 |
|
| 380 |
url = self._build_url("posts", "collection_order", ( |
| 381 |
# patreon returns '400 Bad Request' without campaign_id filter |
| 382 |
f"&filter[campaign_id]={campaign_id}" |
| 383 |
"&filter[contains_exclusive_posts]=true" |
| 384 |
"&filter[is_draft]=false" |
| 385 |
f"&filter[collection_id]={collection_id}" |
| 386 |
"&filter[include_drops]=true" |
| 387 |
)) |
| 388 |
return self._pagination(url) |
| 389 |
|
| 390 |
def _order(self, sort): |
| 391 |
if order := self.config("order-posts"): |
| 392 |
if order in {"a", "asc"}: |
| 393 |
order = "collection_order" |
| 394 |
elif order in {"d", "desc", "r", "reverse"}: |
| 395 |
# "-collection_order" results in a '400 Bad Request' error |
| 396 |
order = "-published_at" |
| 397 |
return "&sort=" + order |
| 398 |
return "&sort=" + sort if sort else "" |
| 399 |
|
| 400 |
|
| 401 |
class PatreonPostExtractor(PatreonExtractor): |
| 402 |
"""Extractor for media from a single post""" |
| 403 |
subcategory = "post" |
| 404 |
pattern = BASE_PATTERN + r"/(?:[^/?#]+/)?posts/(?:[^/?#]*-)?(\d+)" |
| 405 |
example = "https://www.patreon.com/posts/TITLE-12345" |
| 406 |
|
| 407 |
def posts(self): |
| 408 |
url = self._build_url("/posts/" + self.groups[0], "", "") |
| 409 |
post = self.request_json(url, notfound=True) |
| 410 |
included = self._transform(post["included"]) |
| 411 |
return (self._process(post["data"], included),) |
| 412 |
|
| 413 |
def _order(self, sort): |
| 414 |
return "" |
| 415 |
|
| 416 |
|
| 417 |
class PatreonCreatorExtractor(PatreonExtractor): |
| 418 |
"""Extractor for a creator's works""" |
| 419 |
subcategory = "creator" |
| 420 |
pattern = (BASE_PATTERN + |
| 421 |
r"/(?!(?:home|create|login|signup|search|posts|messages)" |
| 422 |
r"(?:$|[/?#]))" |
| 423 |
r"(?:profile/creators|(?:cw?/)?([^/?#]+)(?:/posts)?)" |
| 424 |
r"/?(?:\?([^#]+))?") |
| 425 |
example = "https://www.patreon.com/c/USER" |
| 426 |
|
| 427 |
def posts(self): |
| 428 |
creator, query = self.groups |
| 429 |
|
| 430 |
params = text.parse_query(query) |
| 431 |
campaign_id = self._get_campaign_id(creator, params) |
| 432 |
self.log.debug("campaign_id: %s", campaign_id) |
| 433 |
|
| 434 |
url = self._build_url("posts", params.get("sort", "-published_at"), ( |
| 435 |
f"&filter[campaign_id]={campaign_id}" |
| 436 |
"&filter[contains_exclusive_posts]=true" |
| 437 |
"&filter[is_draft]=false" |
| 438 |
f"{self._get_filters(params)}" |
| 439 |
)) |
| 440 |
return self._pagination(url) |
| 441 |
|
| 442 |
def _get_campaign_id(self, creator, params): |
| 443 |
if creator and creator.startswith("id:"): |
| 444 |
return creator[3:] |
| 445 |
|
| 446 |
if campaign_id := params.get("c") or params.get("campaign_id"): |
| 447 |
return campaign_id |
| 448 |
|
| 449 |
if user_id := params.get("u"): |
| 450 |
url = f"{self.root}/user?u={user_id}" |
| 451 |
else: |
| 452 |
url = f"{self.root}/{creator}" |
| 453 |
page = self.request(url, notfound=True).text |
| 454 |
|
| 455 |
try: |
| 456 |
data = None |
| 457 |
data = self._extract_bootstrap(page) |
| 458 |
return data["campaign"]["data"]["id"] |
| 459 |
except self.exc.ControlException: |
| 460 |
pass |
| 461 |
except Exception as exc: |
| 462 |
if data: |
| 463 |
self.log.debug(data) |
| 464 |
raise self.exc.AbortExtraction( |
| 465 |
f"Unable to extract campaign ID " |
| 466 |
f"({exc.__class__.__name__}: {exc})") |
| 467 |
|
| 468 |
# Next.js 13 |
| 469 |
if cid := text.extr( |
| 470 |
page, r'{\"value\":{\"campaign\":{\"data\":{\"id\":\"', '\\"'): |
| 471 |
return cid |
| 472 |
|
| 473 |
if (curl := text.extr(page, '"contentUrl":', ",")) and \ |
| 474 |
(cid := text.extr(curl, "/campaign/", "/")): |
| 475 |
return cid |
| 476 |
|
| 477 |
if cid := text.extr(page, r'\"id\":\"NavigationBar_', '\\"'): |
| 478 |
return cid |
| 479 |
|
| 480 |
raise self.exc.AbortExtraction("Failed to extract campaign ID") |
| 481 |
|
| 482 |
def _get_filters(self, params): |
| 483 |
return "".join( |
| 484 |
f"&filter[{key[8:]}={text.escape(value)}" |
| 485 |
for key, value in params.items() |
| 486 |
if key.startswith("filters[") |
| 487 |
) |
| 488 |
|
| 489 |
|
| 490 |
class PatreonUserExtractor(PatreonExtractor): |
| 491 |
"""Extractor for media from creators supported by you""" |
| 492 |
subcategory = "user" |
| 493 |
pattern = BASE_PATTERN + r"/home$" |
| 494 |
example = "https://www.patreon.com/home" |
| 495 |
|
| 496 |
def skip_date(self, date): |
| 497 |
self._cursor = cursor = dt.from_ts(date).isoformat() |
| 498 |
self._init_cursor = lambda: cursor |
| 499 |
return True |
| 500 |
|
| 501 |
def posts(self): |
| 502 |
if date_max := self._get_date_min_max(None, None)[1]: |
| 503 |
self._cursor = cursor = dt.from_ts(date_max).isoformat() |
| 504 |
self._init_cursor = lambda: cursor |
| 505 |
|
| 506 |
url = self._build_url("stream", None, ( |
| 507 |
"&filter[is_following]=true" |
| 508 |
"&json-api-use-default-includes=false" |
| 509 |
)) |
| 510 |
return self._pagination(url) |