Debian Codegraph @

gallery_dl/extractor/fansly.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2025-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://fansly.com/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13 import time
14
15 BASE_PATTERN = r"(?:https?://)?(?:www\.)?fansly\.com"
16
17
18 class FanslyExtractor(Extractor):
19 """Base class for fansly extractors"""
20 category = "fansly"
21 root = "https://fansly.com"
22 directory_fmt = ("{category}", "{account[username]} ({account[id]})")
23 filename_fmt = "{id}_{num}_{file[id]}.{extension}"
24 archive_fmt = "{file[id]}"
25
26 def _init(self):
27 self.api = FanslyAPI(self)
28 self.previews = self.config("previews", True)
29
30 if fmts := self.config("formats"):
31 self.formats = set(fmts)
32 else:
33 self.formats = None
34
35 def items(self):
36 for post in self.posts():
37 files = self._extract_files(post)
38 post["count"] = len(files)
39 post["date"] = self.parse_timestamp(post["createdAt"])
40
41 yield Message.Directory, "", post
42 for post["num"], file in enumerate(files, 1):
43 post.update(file)
44 url = file["url"]
45 yield Message.Url, url, text.nameext_from_url(url, post)
46
47 def posts(self):
48 creator, wall_id = self.groups
49 account = self.api.account(creator)
50 walls = account["walls"]
51
52 if wall_id:
53 for wall in walls:
54 if wall["id"] == wall_id:
55 break
56 else:
57 raise self.exc.NotFoundError("wall")
58 walls = (wall,)
59
60 for wall in walls:
61 self.kwdict["wall"] = wall
62 yield from self.posts_wall(account, wall)
63
64 def _extract_files(self, post):
65 if "attachments" not in post:
66 return ()
67
68 if "_extra" in post:
69 extra = post.pop("_extra", ())
70 media = {
71 media["id"]: media
72 for media in self.api.account_media(extra)
73 }
74 post["attachments"].extend(
75 media[mid]
76 for mid in extra
77 if mid in media
78 )
79
80 files = []
81 for attachment in post.pop("attachments"):
82 try:
83 self._extract_attachment(files, post, attachment)
84 except Exception as exc:
85 self.log.traceback(exc)
86 self.log.error(
87 "%s/%s, Failed to extract media (%s: %s)",
88 post["id"], attachment.get("id"),
89 exc.__class__.__name__, exc)
90 return files
91
92 def _extract_attachment(self, files, post, attachment, preview=False):
93 media = attachment["preview" if preview else "media"]
94
95 variants = media.pop("variants") or []
96 if media.get("locations"):
97 variants.append(media)
98
99 fmts = self.formats
100 formats = [
101 (variant["width"], (type-500 if type > 256 else type), variant)
102 for variant in variants
103 if variant.get("locations") and
104 (type := variant["type"]) and
105 (fmts is None or type in fmts)
106 ]
107
108 try:
109 variant = max(formats)[-1]
110 except Exception:
111 if self.previews and "preview" in attachment and not preview:
112 self.log.info("%s/%s: Downloading Preview",
113 post["id"], attachment["id"])
114 return self._extract_attachment(files, post, attachment, True)
115 return self.log.warning("%s/%s: No format available",
116 post["id"], attachment["id"])
117
118 mime = variant["mimetype"]
119 location = variant.pop("locations")[0]
120 if "metadata" in variant:
121 try:
122 variant.update(util.json_loads(variant.pop("metadata")))
123 except Exception:
124 pass
125
126 file = {
127 **variant,
128 "preview": preview,
129 "format": variant["type"],
130 "date": self.parse_timestamp(media["createdAt"]),
131 "date_updated": self.parse_timestamp(media["updatedAt"]),
132 }
133
134 if "metadata" in location:
135 # manifest
136 meta = location["metadata"]
137 file["type"] = "video"
138
139 try:
140 fallback = (media["locations"][0]["location"],)
141 except Exception:
142 fallback = ()
143
144 files.append({
145 "file": file,
146 "url": "ytdl:" + location["location"],
147 "_fallback": fallback,
148 "_ytdl_manifest":
149 "dash" if mime == "application/dash+xml" else "hls",
150 "_ytdl_manifest_cookies": (
151 ("CloudFront-Key-Pair-Id", meta["Key-Pair-Id"]),
152 ("CloudFront-Signature" , meta["Signature"]),
153 ("CloudFront-Policy" , meta["Policy"]),
154 ),
155 })
156 else:
157 file["type"] = "image" if mime.startswith("image/") else "video"
158 files.append({
159 "file": file,
160 "url" : location["location"],
161 })
162
163
164 class FanslyPostExtractor(FanslyExtractor):
165 subcategory = "post"
166 pattern = BASE_PATTERN + r"/post/(\d+)"
167 example = "https://fansly.com/post/1234567890"
168
169 def posts(self):
170 return self.api.post(self.groups[0])
171
172
173 class FanslyHomeExtractor(FanslyExtractor):
174 subcategory = "home"
175 pattern = BASE_PATTERN + r"/home(?:/(?:subscribed()|list/(\d+)))?"
176 example = "https://fansly.com/home"
177
178 def posts(self):
179 subscribed, list_id = self.groups
180 if subscribed is not None:
181 mode = "1"
182 elif list_id is not None:
183 mode = None
184 else:
185 mode = "0"
186 return self.api.timeline_home(mode, list_id)
187
188
189 class FanslyListExtractor(FanslyExtractor):
190 subcategory = "list"
191 pattern = BASE_PATTERN + r"/lists/(\d+)"
192 example = "https://fansly.com/lists/1234567890"
193
194 def items(self):
195 base = self.root + "/"
196 for account in self.api.lists_itemsnew(self.groups[0]):
197 account["_extractor"] = FanslyCreatorPostsExtractor
198 url = f"{base}{account['username']}/posts"
199 yield Message.Queue, url, account
200
201
202 class FanslyListsExtractor(FanslyExtractor):
203 subcategory = "lists"
204 pattern = BASE_PATTERN + r"/lists"
205 example = "https://fansly.com/lists"
206
207 def items(self):
208 base = self.root + "/lists/"
209 for list in self.api.lists_account():
210 list["_extractor"] = FanslyListExtractor
211 url = f"{base}{list['id']}#{list['label']}"
212 yield Message.Queue, url, list
213
214
215 class FanslyCreatorPostsExtractor(FanslyExtractor):
216 subcategory = "creator-posts"
217 pattern = BASE_PATTERN + r"/([^/?#]+)/posts(?:/wall/(\d+))?"
218 example = "https://fansly.com/CREATOR/posts"
219
220 def posts_wall(self, account, wall):
221 return self.api.timeline_new(account["id"], wall["id"])
222
223
224 class FanslyCreatorMediaExtractor(FanslyExtractor):
225 subcategory = "creator-media"
226 pattern = BASE_PATTERN + r"/([^/?#]+)/media(?:/wall/(\d+))?"
227 example = "https://fansly.com/CREATOR/media"
228
229 def posts_wall(self, account, wall):
230 return self.api.mediaoffers_location(account["id"], wall["id"])
231
232
233 class FanslyAPI():
234 ROOT = "https://apiv3.fansly.com"
235
236 def __init__(self, extractor):
237 self.extractor = extractor
238 self.headers = {}
239
240 if token := extractor.config("token"):
241 self.headers["authorization"] = token
242 self.extractor.log.debug(
243 "Using authorization 'token' %.5s...", token)
244 else:
245 self.extractor.log.warning("No 'token' provided")
246
247 def account(self, creator):
248 if creator.startswith("id:"):
249 return self.account_by_id(creator[3:])
250 return self.account_by_username(creator)
251
252 def account_by_username(self, username):
253 endpoint = "/v1/account"
254 params = {"usernames": username}
255 return self._call(endpoint, params)[0]
256
257 def account_by_id(self, account_id):
258 endpoint = "/v1/account"
259 params = {"ids": account_id}
260 return self._call(endpoint, params)[0]
261
262 def accounts_by_id(self, account_ids):
263 endpoint = "/v1/account"
264 params = {"ids": ",".join(map(str, account_ids))}
265 return self._call(endpoint, params)
266
267 def account_media(self, media_ids):
268 endpoint = "/v1/account/media"
269 params = {"ids": ",".join(map(str, media_ids))}
270 return self._call(endpoint, params)
271
272 def lists_account(self):
273 endpoint = "/v1/lists/account"
274 params = {"itemId": ""}
275 return self._call(endpoint, params)
276
277 def lists_itemsnew(self, list_id, sort="3"):
278 endpoint = "/v1/lists/itemsnew"
279 params = {
280 "listId" : list_id,
281 "limit" : 50,
282 "after" : None,
283 "sortMode": sort,
284 }
285 return self._pagination_list(endpoint, params)
286
287 def mediaoffers_location(self, account_id, wall_id):
288 endpoint = "/v1/mediaoffers/location"
289 params = {
290 "locationId": wall_id,
291 "locationType": "1002",
292 "accountId": account_id,
293 "mediaType": "",
294 "before": "",
295 "after" : "0",
296 "limit" : "30",
297 "offset": "0",
298 }
299 return self._pagination_media(endpoint, params)
300
301 def post(self, post_id):
302 endpoint = "/v1/post"
303 params = {"ids": post_id}
304 return self._update_posts(self._call(endpoint, params))
305
306 def timeline_home(self, mode="0", list_id=None):
307 endpoint = "/v1/timeline/home"
308 params = {"before": "0", "after": "0"}
309 if list_id is None:
310 params["mode"] = mode
311 else:
312 params["listId"] = list_id
313 return self._pagination(endpoint, params)
314
315 def timeline_new(self, account_id, wall_id):
316 endpoint = "/v1/timelinenew/" + str(account_id)
317 params = {
318 "before" : "0",
319 "after" : "0",
320 "wallId" : wall_id,
321 "contentSearch": "",
322 }
323 return self._pagination(endpoint, params)
324
325 def _update_posts(self, response):
326 accounts = {
327 account["id"]: account
328 for account in response["accounts"]
329 }
330 media = {
331 media["id"]: media
332 for media in response["accountMedia"]
333 }
334 bundles = {
335 bundle["id"]: bundle
336 for bundle in response["accountMediaBundles"]
337 }
338
339 posts = response["posts"]
340 for post in posts:
341 try:
342 post["account"] = accounts[post.pop("accountId")]
343 except KeyError:
344 pass
345
346 extra = None
347 attachments = []
348 for attachment in post["attachments"]:
349 try:
350 cid = attachment["contentId"]
351 except KeyError:
352 attachments.append(attachment)
353 continue
354
355 if cid in media:
356 attachments.append(media[cid])
357 elif cid in bundles:
358 bundle = bundles[cid]["bundleContent"]
359 bundle.sort(key=lambda c: c["pos"])
360 for c in bundle:
361 mid = c["accountMediaId"]
362 if mid in media:
363 attachments.append(media[mid])
364 else:
365 if extra is None:
366 post["_extra"] = extra = []
367 extra.append(mid)
368 else:
369 self.extractor.log.warning(
370 "%s: Unhandled 'contentId' %s",
371 post["id"], cid)
372 post["attachments"] = attachments
373
374 return posts
375
376 def _update_media(self, items, response):
377 posts = {
378 post["id"]: post
379 for post in response["posts"]
380 }
381
382 response["posts"] = [
383 posts[item["correlationId"]]
384 for item in items
385 ]
386
387 return self._update_posts(response)
388
389 def _update_items(self, items):
390 ids = [item["id"] for item in items]
391 accounts = {
392 account["id"]: account
393 for account in self.accounts_by_id(ids)
394 }
395 return [accounts[id] for id in ids]
396
397 def _call(self, endpoint, params):
398 url = f"{self.ROOT}/api{endpoint}"
399 params["ngsw-bypass"] = "true"
400 self.headers["fansly-client-ts"] = str(int(time.time() * 1000))
401
402 return self.extractor.request_json(
403 url, params=params, headers=self.headers)["response"]
404
405 def _pagination(self, endpoint, params):
406 while True:
407 response = self._call(endpoint, params)
408
409 if not response.get("posts"):
410 return
411 posts = self._update_posts(response)
412 yield from posts
413 params["before"] = min(p["id"] for p in posts)
414
415 def _pagination_list(self, endpoint, params):
416 while True:
417 response = self._call(endpoint, params)
418
419 if not response:
420 return
421 yield from self._update_items(response)
422 params["after"] = response[-1]["sortId"]
423
424 def _pagination_media(self, endpoint, params):
425 while True:
426 response = self._call(endpoint, params)
427
428 if not (data := response.get("data")):
429 return
430 yield from self._update_media(data, response["aggregationData"])
431 params["before"] = data[-1]["id"]