Debian Codegraph @

gallery_dl/extractor/hatenablog.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://hatenablog.com"""
8
9 from .common import Extractor, Message
10 from .. import text
11
12
13 BASE_PATTERN = (
14 r"(?:hatenablog:https?://([^/?#]+)|(?:https?://)?"
15 r"([\w-]+\.(?:hatenablog\.(?:com|jp)"
16 r"|hatenadiary\.com|hateblo\.jp)))"
17 )
18 QUERY_RE = r"(?:\?([^#]*))?(?:#.*)?$"
19
20
21 class HatenablogExtractor(Extractor):
22 """Base class for HatenaBlog extractors"""
23 category = "hatenablog"
24 directory_fmt = ("{category}", "{domain}")
25 filename_fmt = "{category}_{domain}_{entry}_{num:>02}.{extension}"
26 archive_fmt = "{filename}"
27
28 def __init__(self, match):
29 Extractor.__init__(self, match)
30 self.domain = match[1] or match[2]
31
32 def _init(self):
33 self._find_img = text.re(r'<img +([^>]+)').finditer
34
35 def _handle_article(self, article: str):
36 extr = text.extract_from(article)
37 date = self.parse_datetime_iso(extr('<time datetime="', '"'))
38 entry_link = text.unescape(extr('<a href="', '"'))
39 entry = entry_link.partition("/entry/")[2]
40 title = text.unescape(extr('>', '<'))
41 content = extr(
42 '<div class="entry-content hatenablog-entry">', '</div>')
43
44 images = []
45 for match in self._find_img(content):
46 attributes = match[1]
47 if 'class="hatena-fotolife"' not in attributes:
48 continue
49 image = text.unescape(text.extr(attributes, 'src="', '"'))
50 images.append(image)
51
52 data = {
53 "domain": self.domain,
54 "date": date,
55 "entry": entry,
56 "title": title,
57 "count": len(images),
58 }
59 yield Message.Directory, "", data
60 for data["num"], url in enumerate(images, 1):
61 yield Message.Url, url, text.nameext_from_url(url, data)
62
63
64 class HatenablogEntriesExtractor(HatenablogExtractor):
65 """Base class for a list of entries"""
66 allowed_parameters = ()
67
68 def __init__(self, match):
69 HatenablogExtractor.__init__(self, match)
70 self.path = match[3]
71 self.query = {key: value for key, value in text.parse_query(
72 match[4]).items() if self._acceptable_query(key)}
73
74 def _init(self):
75 HatenablogExtractor._init(self)
76 self._find_pager_url = text.re(
77 r' class="pager-next">\s*<a href="([^"]+)').search
78
79 def items(self):
80 url = "https://" + self.domain + self.path
81 query = self.query
82
83 while url:
84 page = self.request(url, params=query).text
85
86 extr = text.extract_from(page)
87 attributes = extr('<body ', '>')
88 if "page-archive" in attributes:
89 yield from self._handle_partial_articles(extr)
90 else:
91 yield from self._handle_full_articles(extr)
92
93 match = self._find_pager_url(page)
94 url = text.unescape(match[1]) if match else None
95 query = None
96
97 def _handle_partial_articles(self, extr):
98 while True:
99 section = extr('<section class="archive-entry', '</section>')
100 if not section:
101 break
102
103 url = "hatenablog:" + text.unescape(text.extr(
104 section, '<a class="entry-title-link" href="', '"'))
105 data = {"_extractor": HatenablogEntryExtractor}
106 yield Message.Queue, url, data
107
108 def _handle_full_articles(self, extr):
109 while True:
110 attributes = extr('<article ', '>')
111 if not attributes:
112 break
113 if "no-entry" in attributes:
114 continue
115
116 article = extr('', '</article>')
117 yield from self._handle_article(article)
118
119 def _acceptable_query(self, key):
120 return key == "page" or key in self.allowed_parameters
121
122
123 class HatenablogEntryExtractor(HatenablogExtractor):
124 """Extractor for a single entry URL"""
125 subcategory = "entry"
126 pattern = BASE_PATTERN + r"/entry/([^?#]+)" + QUERY_RE
127 example = "https://BLOG.hatenablog.com/entry/PATH"
128
129 def __init__(self, match):
130 HatenablogExtractor.__init__(self, match)
131 self.path = match[3]
132
133 def items(self):
134 url = "https://" + self.domain + "/entry/" + self.path
135 page = self.request(url).text
136
137 extr = text.extract_from(page)
138 while True:
139 attributes = extr('<article ', '>')
140 if "no-entry" in attributes:
141 continue
142 article = extr('', '</article>')
143 return self._handle_article(article)
144
145
146 class HatenablogHomeExtractor(HatenablogEntriesExtractor):
147 """Extractor for a blog's home page"""
148 subcategory = "home"
149 pattern = BASE_PATTERN + r"(/?)" + QUERY_RE
150 example = "https://BLOG.hatenablog.com"
151
152
153 class HatenablogArchiveExtractor(HatenablogEntriesExtractor):
154 """Extractor for a blog's archive page"""
155 subcategory = "archive"
156 pattern = (BASE_PATTERN + r"(/archive(?:/\d+(?:/\d+(?:/\d+)?)?"
157 r"|/category/[^?#]+)?)" + QUERY_RE)
158 example = "https://BLOG.hatenablog.com/archive/2024"
159
160
161 class HatenablogSearchExtractor(HatenablogEntriesExtractor):
162 """Extractor for a blog's search results"""
163 subcategory = "search"
164 pattern = BASE_PATTERN + r"(/search)" + QUERY_RE
165 example = "https://BLOG.hatenablog.com/search?q=QUERY"
166 allowed_parameters = ("q",)