Debian Codegraph @

gallery_dl/extractor/pillowfort.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2021-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.pillowfort.social/"""
10
11 from .common import Extractor, Message
12 from .. import text
13
14 BASE_PATTERN = r"(?:https?://)?www\.pillowfort\.social"
15
16
17 class PillowfortExtractor(Extractor):
18 """Base class for pillowfort extractors"""
19 category = "pillowfort"
20 root = "https://www.pillowfort.social"
21 directory_fmt = ("{category}", "{username}")
22 filename_fmt = ("{post_id} {title|original_post[title]:?/ /}"
23 "{num:>02}.{extension}")
24 archive_fmt = "{id}"
25 cookies_domain = "www.pillowfort.social"
26
27 def __init__(self, match):
28 Extractor.__init__(self, match)
29 self.item = match[1]
30
31 def items(self):
32 self.login()
33 inline = self.config("inline", True)
34 reblogs = self.config("reblogs", False)
35 external = self.config("external", False)
36
37 if inline:
38 inline = text.re(r'src="(https://img\d+\.pillowfort\.social'
39 r'/posts/[^"]+)').findall
40
41 for post in self.posts():
42 if "original_post" in post and not reblogs:
43 continue
44
45 files = post.pop("media")
46 if inline:
47 for url in inline(post["content"]):
48 files.append({"url": url})
49
50 post["date"] = self.parse_datetime_iso(post["created_at"])
51 post["post_id"] = post.pop("id")
52 post["count"] = len(files)
53 yield Message.Directory, "", post
54
55 post["num"] = 0
56 for file in files:
57 url = file["url"] or file.get("b2_lg_url")
58 if not url:
59 continue
60
61 if file.get("embed_code"):
62 if not external:
63 continue
64 msgtype = Message.Queue
65 else:
66 post["num"] += 1
67 msgtype = Message.Url
68
69 post.update(file)
70 text.nameext_from_url(url, post)
71 post["hash"], _, post["filename"] = \
72 post["filename"].partition("_")
73
74 if "id" not in file:
75 post["id"] = post["hash"]
76 if "created_at" in file:
77 post["date"] = self.parse_datetime_iso(file["created_at"])
78
79 yield msgtype, url, post
80
81 def login(self):
82 if self.cookies.get("_Pf_new_session", domain=self.cookies_domain):
83 return
84 if self.cookies.get("remember_user_token", domain=self.cookies_domain):
85 return
86
87 username, password = self._get_auth_info()
88 if username:
89 return self.cookies_update(self.cache(
90 self._login_impl, username, password,
91 _exp=14*86400, _mem=False))
92
93 def _login_impl(self, username, password):
94 self.log.info("Logging in as %s", username)
95
96 url = "https://www.pillowfort.social/users/sign_in"
97 page = self.request(url).text
98 auth = text.extr(page, 'name="authenticity_token" value="', '"')
99
100 headers = {"Origin": self.root, "Referer": url}
101 data = {
102 "utf8" : "✓",
103 "authenticity_token": auth,
104 "user[email]" : username,
105 "user[password]" : password,
106 "user[remember_me]" : "1",
107 }
108 response = self.request(url, method="POST", headers=headers, data=data)
109
110 if not response.history:
111 raise self.exc.AuthenticationError()
112
113 return {
114 cookie.name: cookie.value
115 for cookie in response.history[0].cookies
116 }
117
118
119 class PillowfortPostExtractor(PillowfortExtractor):
120 """Extractor for a single pillowfort post"""
121 subcategory = "post"
122 pattern = BASE_PATTERN + r"/posts/(\d+)"
123 example = "https://www.pillowfort.social/posts/12345"
124
125 def posts(self):
126 url = f"{self.root}/posts/{self.item}/json/"
127 return (self.request_json(url),)
128
129
130 class PillowfortUserExtractor(PillowfortExtractor):
131 """Extractor for all posts of a pillowfort user"""
132 subcategory = "user"
133 pattern = BASE_PATTERN + r"/(?!posts/)([^/?#]+(?:/tagged/[^/?#]+)?)"
134 example = "https://www.pillowfort.social/USER"
135
136 def posts(self):
137 url = f"{self.root}/{self.item}/json/"
138 params = {"p": 1}
139
140 while True:
141 posts = self.request_json(url, params=params)["posts"]
142 yield from posts
143
144 if len(posts) < 20:
145 return
146 params["p"] += 1