Debian Codegraph @

gallery_dl/extractor/seiga.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2016-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://seiga.nicovideo.jp/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13
14
15 class SeigaExtractor(Extractor):
16 """Base class for seiga extractors"""
17 category = "seiga"
18 archive_fmt = "{image_id}"
19 cookies_domain = ".nicovideo.jp"
20 cookies_names = ("user_session",)
21 root = "https://seiga.nicovideo.jp"
22
23 def __init__(self, match):
24 Extractor.__init__(self, match)
25 self.start_image = 0
26
27 def items(self):
28 self.login()
29
30 images = iter(self.get_images())
31 data = next(images)
32
33 yield Message.Directory, "", data
34 for image in util.advance(images, self.start_image):
35 data.update(image)
36 data["extension"] = None
37 yield Message.Url, self.get_image_url(data["image_id"]), data
38
39 def get_images(self):
40 """Return iterable containing metadata and images"""
41
42 def get_image_url(self, image_id):
43 """Get url for an image with id 'image_id'"""
44 url = f"{self.root}/image/source/{image_id}"
45 location = self.request_location(url, notfound="image")
46 if "nicovideo.jp/login" in location:
47 raise self.exc.AbortExtraction(
48 f"HTTP redirect to login page ({location.partition('?')[0]})")
49 return location.replace("/o/", "/priv/", 1)
50
51 def login(self):
52 if self.cookies_check(self.cookies_names):
53 return
54
55 username, password = self._get_auth_info()
56 if username:
57 return self.cookies_update(self.cache(
58 self._login_impl, username, password,
59 _exp=365*86400, _mem=False))
60
61 raise self.exc.AuthorizationError(
62 "username & password or 'user_session' cookie required")
63
64 def _login_impl(self, username, password):
65 self.log.info("Logging in as %s", username)
66
67 root = "https://account.nicovideo.jp"
68 response = self.request(root + "/login?site=seiga")
69 page = response.text
70
71 data = {
72 "mail_tel": username,
73 "password": password,
74 }
75 url = root + text.unescape(text.extr(page, '<form action="', '"'))
76 response = self.request(url, method="POST", data=data)
77
78 if "message=cant_login" in response.url:
79 raise self.exc.AuthenticationError()
80
81 if "/mfa" in response.url:
82 page = response.text
83 email = text.extr(page, 'class="userAccount">', "<")
84 code = self.input(f"Email Confirmation Code ({email}): ")
85
86 data = {
87 "otp": code,
88 "loginBtn": "Login",
89 "device_name": "gdl",
90 }
91 url = root + text.unescape(text.extr(page, '<form action="', '"'))
92 response = self.request(url, method="POST", data=data)
93
94 if not response.history and \
95 b"Confirmation code is incorrect" in response.content:
96 raise self.exc.AuthenticationError(
97 "Incorrect Confirmation Code")
98
99 return {
100 cookie.name: cookie.value
101 for cookie in self.cookies
102 if cookie.expires and cookie.domain == self.cookies_domain
103 }
104
105
106 class SeigaUserExtractor(SeigaExtractor):
107 """Extractor for images of a user from seiga.nicovideo.jp"""
108 subcategory = "user"
109 directory_fmt = ("{category}", "{user[id]}")
110 filename_fmt = "{category}_{user[id]}_{image_id}.{extension}"
111 pattern = (r"(?:https?://)?(?:www\.|(?:sp\.)?seiga\.)?nicovideo\.jp/"
112 r"user/illust/(\d+)(?:\?(?:[^&]+&)*sort=([^&#]+))?")
113 example = "https://seiga.nicovideo.jp/user/illust/12345"
114
115 def __init__(self, match):
116 SeigaExtractor.__init__(self, match)
117 self.user_id, self.order = match.groups()
118 self.start_page = 1
119
120 def skip_files(self, num):
121 pages, images = divmod(num, 40)
122 self.start_page += pages
123 self.start_image += images
124 return num
125
126 def get_metadata(self, page):
127 """Collect metadata from 'page'"""
128 data = text.extract_all(page, (
129 ("name" , '<img alt="', '"'),
130 ("msg" , '<li class="user_message">', '</li>'),
131 (None , '<span class="target_name">すべて</span>', ''),
132 ("count", '<span class="count ">', '</span>'),
133 ))[0]
134
135 if not data["name"] and "ユーザー情報が取得出来ませんでした" in page:
136 raise self.exc.NotFoundError("user")
137
138 return {
139 "user": {
140 "id": text.parse_int(self.user_id),
141 "name": data["name"],
142 "message": (data["msg"] or "").strip(),
143 },
144 "count": text.parse_int(data["count"]),
145 }
146
147 def get_images(self):
148 url = f"{self.root}/user/illust/{self.user_id}"
149 params = {"sort": self.order, "page": self.start_page,
150 "target": "illust_all"}
151
152 while True:
153 cnt = 0
154 page = self.request(url, params=params).text
155
156 if params["page"] == self.start_page:
157 yield self.get_metadata(page)
158
159 for info in text.extract_iter(
160 page, '<li class="list_item', '</a></li> '):
161 data = text.extract_all(info, (
162 ("image_id", '/seiga/im', '"'),
163 ("title" , '<li class="title">', '</li>'),
164 ("views" , '</span>', '</li>'),
165 ("comments", '</span>', '</li>'),
166 ("clips" , '</span>', '</li>'),
167 ))[0]
168 for key in ("image_id", "views", "comments", "clips"):
169 data[key] = text.parse_int(data[key])
170 yield data
171 cnt += 1
172
173 if cnt < 40:
174 return
175 params["page"] += 1
176
177
178 class SeigaImageExtractor(SeigaExtractor):
179 """Extractor for single images from seiga.nicovideo.jp"""
180 subcategory = "image"
181 filename_fmt = "{category}_{image_id}.{extension}"
182 pattern = (r"(?:https?://)?(?:"
183 r"(?:seiga\.|www\.)?nicovideo\.jp/(?:seiga/im|image/source/)"
184 r"|sp\.seiga\.nicovideo\.jp/seiga/#!/im"
185 r"|lohas\.nicoseiga\.jp/(?:thumb|(?:priv|o)/[^/]+/\d+)/)(\d+)")
186 example = "https://seiga.nicovideo.jp/seiga/im12345"
187
188 def __init__(self, match):
189 SeigaExtractor.__init__(self, match)
190 self.image_id = match[1]
191
192 def skip_files(self, num):
193 self.start_image += num
194 return num
195
196 def get_images(self):
197 self.cookies.set(
198 "skip_fetish_warning", "1", domain="seiga.nicovideo.jp")
199
200 url = f"{self.root}/seiga/im{self.image_id}"
201 page = self.request(url, notfound=True).text
202
203 data = text.extract_all(page, (
204 ("date" , '<li class="date"><span class="created">', '<'),
205 ("title" , '<h1 class="title">', '</h1>'),
206 ("description" , '<p class="discription">', '</p>'),
207 ))[0]
208
209 data["user"] = text.extract_all(page, (
210 ("id" , '<a href="/user/illust/' , '"'),
211 ("name", '<span itemprop="title">', '<'),
212 ))[0]
213
214 data["description"] = text.remove_html(data["description"])
215 data["image_id"] = text.parse_int(self.image_id)
216 data["date"] = self.parse_datetime(
217 data["date"] + ":00+0900", "%Y年%m月%d日 %H:%M:%S%z")
218
219 return (data, data)