Debian Codegraph @

gallery_dl/extractor/fantia.py

raw
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://fantia.jp/"""
8
9 from .common import Extractor, Message
10 from .. import text, util
11
12
13 class FantiaExtractor(Extractor):
14 """Base class for Fantia extractors"""
15 category = "fantia"
16 root = "https://fantia.jp"
17 directory_fmt = ("{category}", "{fanclub_id}")
18 filename_fmt = "{post_id}_{file_id}.{extension}"
19 archive_fmt = "{post_id}_{file_id}"
20 _warning = True
21
22 def _init(self):
23 self.blog_text = self.config("text", True)
24 self.headers = {
25 "Accept" : "application/json, text/plain, */*",
26 "X-Requested-With": "XMLHttpRequest",
27 }
28 self._empty_plan = {
29 "id" : 0,
30 "price": 0,
31 "limit": 0,
32 "name" : "",
33 "description": "",
34 "thumb": self.root + "/images/fallback/plan/thumb_default.png",
35 }
36 if self._warning:
37 if not self.cookies_check(("_session_id",)):
38 self.log.warning("no '_session_id' cookie set")
39 FantiaExtractor._warning = False
40
41 def items(self):
42 for post_id in self.posts():
43 post = self._get_post_data(post_id)
44 post["num"] = 0
45
46 contents = self._get_post_contents(post)
47 post["content_count"] = len(contents)
48 post["content_num"] = 0
49
50 for content in contents:
51 files = self._process_content(post, content)
52 yield Message.Directory, "", post
53
54 if content["visible_status"] != "visible":
55 self.log.warning(
56 "Unable to download '%s' files from "
57 "%s#post-content-id-%s", content["visible_status"],
58 post["post_url"], content["id"])
59
60 for file in files:
61 post.update(file)
62 post["num"] += 1
63 text.nameext_from_url(
64 post["content_filename"] or file["file_url"], post)
65 yield Message.Url, file["file_url"], post
66
67 post["content_num"] += 1
68
69 def posts(self):
70 """Return post IDs"""
71
72 def _pagination(self, url, params, needle=""):
73 params["page"] = 1
74
75 while True:
76 page = self.request(url, params=params).text
77 self._csrf_token(page)
78
79 target_id = None
80 for target_id in text.extract_iter(page, needle, '"'):
81 yield target_id
82
83 if not target_id:
84 return
85 params["page"] += 1
86
87 def _csrf_token(self, page=None):
88 if not page:
89 page = self.request(self.root + "/").text
90 self.headers["X-CSRF-Token"] = text.extr(
91 page, 'name="csrf-token" content="', '"')
92
93 def _get_post_data(self, post_id):
94 """Fetch and process post data"""
95 url = self.root+"/api/v1/posts/"+post_id
96 resp = self.request_json(url, headers=self.headers)["post"]
97 return {
98 "post_id": resp["id"],
99 "post_url": self.root + "/posts/" + str(resp["id"]),
100 "post_title": resp["title"],
101 "comment": resp["comment"],
102 "rating": resp["rating"],
103 "posted_at": resp["posted_at"],
104 "date": self.parse_datetime(
105 resp["posted_at"], "%a, %d %b %Y %H:%M:%S %z"),
106 "fanclub_id": resp["fanclub"]["id"],
107 "fanclub_user_id": resp["fanclub"]["user"]["id"],
108 "fanclub_user_name": resp["fanclub"]["user"]["name"],
109 "fanclub_name": resp["fanclub"]["name"],
110 "fanclub_url": self.root+"/fanclubs/"+str(resp["fanclub"]["id"]),
111 "tags": [t["name"] for t in resp["tags"]],
112 "_data": resp,
113 }
114
115 def _get_post_contents(self, post):
116 contents = post["_data"]["post_contents"]
117
118 try:
119 url = post["_data"]["thumb"]["original"]
120 except Exception:
121 pass
122 else:
123 contents.insert(0, {
124 "id": "thumb",
125 "title": "thumb",
126 "category": "thumb",
127 "download_uri": url,
128 "visible_status": "visible",
129 "plan": None,
130 })
131
132 return contents
133
134 def _process_content(self, post, content):
135 post["content_category"] = content["category"]
136 post["content_title"] = content["title"]
137 post["content_filename"] = content.get("filename") or ""
138 post["content_id"] = content["id"]
139 post["content_comment"] = content.get("comment") or ""
140 post["content_num"] += 1
141 post["plan"] = content["plan"] or self._empty_plan
142
143 files = []
144
145 if "post_content_photos" in content:
146 for photo in content["post_content_photos"]:
147 files.append({"file_id" : photo["id"],
148 "file_url": photo["url"]["original"]})
149
150 if "download_uri" in content:
151 url = content["download_uri"]
152 if url[0] == "/":
153 url = self.root + url
154 files.append({"file_id" : content["id"],
155 "file_url": url})
156
157 if content["category"] == "blog" and "comment" in content:
158 comment_json = util.json_loads(content["comment"])
159
160 blog_text = ""
161 for op in comment_json.get("ops") or ():
162 insert = op.get("insert")
163 if isinstance(insert, str):
164 blog_text += insert
165 elif isinstance(insert, dict) and "fantiaImage" in insert:
166 img = insert["fantiaImage"]
167 files.append({"file_id" : img["id"],
168 "file_url": self.root + img["original_url"]})
169 post["blogpost_text"] = blog_text
170
171 if not files and blog_text and self.blog_text:
172 files.append({
173 "file_id" : content["id"],
174 "file_url": "text:" + blog_text,
175 "content_filename": (content["title"] or
176 post["post_title"]) + ".txt",
177 })
178 else:
179 post["blogpost_text"] = ""
180
181 return files
182
183
184 class FantiaCreatorExtractor(FantiaExtractor):
185 """Extractor for a Fantia creator's works"""
186 subcategory = "creator"
187 pattern = r"(?:https?://)?(?:www\.)?fantia\.jp/fanclubs/(\d+)"
188 example = "https://fantia.jp/fanclubs/12345"
189
190 def posts(self):
191 url = f"{self.root}/fanclubs/{self.groups[0]}/posts"
192 return self._pagination(url, {}, 'class="link-block" href="/posts/')
193
194
195 class FantiaPostExtractor(FantiaExtractor):
196 """Extractor for media from a single Fantia post"""
197 subcategory = "post"
198 pattern = r"(?:https?://)?(?:www\.)?fantia\.jp/posts/(\d+)"
199 example = "https://fantia.jp/posts/12345"
200
201 def posts(self):
202 self._csrf_token()
203 return (self.groups[0],)
204
205
206 class FantiaSupportingExtractor(FantiaExtractor):
207 """Extractor for free and paid supporting fanclubs for the current user"""
208 subcategory = "supporting"
209 pattern = (r"(?:https?://)?(?:www\.)?fantia\.jp/mypage/users/plans"
210 r"(?:\?type=((?:not_)?free))?")
211 example = "https://fantia.jp/mypage/users/plans"
212
213 def items(self):
214 url = self.root + "/mypage/users/plans"
215 base = self.root + "/fanclubs/"
216 data = {"_extractor": FantiaCreatorExtractor}
217
218 type = self.groups[0]
219 for plan_type in ("not_free", "free") if type is None else (type,):
220 params = {"type": plan_type}
221 for fanclub_id in self._pagination(
222 url, params, 'class="user-avatar" href="/fanclubs/'):
223 yield Message.Queue, base + fanclub_id, data