aboutsummaryrefslogtreecommitdiffstats
path: root/gallery_dl/extractor/hatenablog.py
blob: 7740eda72b35ea7faca78e5fb4233ca2b3b35f75 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# -*- coding: utf-8 -*-

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

"""Extractors for https://hatenablog.com"""

from .common import Extractor, Message
from .. import text


BASE_PATTERN = (
    r"(?:hatenablog:https?://([^/?#]+)|(?:https?://)?"
    r"([\w-]+\.(?:hatenablog\.(?:com|jp)"
    r"|hatenadiary\.com|hateblo\.jp)))"
)
QUERY_RE = r"(?:\?([^#]*))?(?:#.*)?$"


class HatenablogExtractor(Extractor):
    """Base class for HatenaBlog extractors"""
    category = "hatenablog"
    directory_fmt = ("{category}", "{domain}")
    filename_fmt = "{category}_{domain}_{entry}_{num:>02}.{extension}"
    archive_fmt = "{filename}"

    def __init__(self, match):
        Extractor.__init__(self, match)
        self.domain = match[1] or match[2]

    def _init(self):
        self._find_img = text.re(r'<img +([^>]+)').finditer

    def _handle_article(self, article: str):
        extr = text.extract_from(article)
        date = self.parse_datetime_iso(extr('<time datetime="', '"'))
        entry_link = text.unescape(extr('<a href="', '"'))
        entry = entry_link.partition("/entry/")[2]
        title = text.unescape(extr('>', '<'))
        content = extr(
            '<div class="entry-content hatenablog-entry">', '</div>')

        images = []
        for match in self._find_img(content):
            attributes = match[1]
            if 'class="hatena-fotolife"' not in attributes:
                continue
            image = text.unescape(text.extr(attributes, 'src="', '"'))
            images.append(image)

        data = {
            "domain": self.domain,
            "date": date,
            "entry": entry,
            "title": title,
            "count": len(images),
        }
        yield Message.Directory, "", data
        for data["num"], url in enumerate(images, 1):
            yield Message.Url, url, text.nameext_from_url(url, data)


class HatenablogEntriesExtractor(HatenablogExtractor):
    """Base class for a list of entries"""
    allowed_parameters = ()

    def __init__(self, match):
        HatenablogExtractor.__init__(self, match)
        self.path = match[3]
        self.query = {key: value for key, value in text.parse_query(
            match[4]).items() if self._acceptable_query(key)}

    def _init(self):
        HatenablogExtractor._init(self)
        self._find_pager_url = text.re(
            r' class="pager-next">\s*<a href="([^"]+)').search

    def items(self):
        url = "https://" + self.domain + self.path
        query = self.query

        while url:
            page = self.request(url, params=query).text

            extr = text.extract_from(page)
            attributes = extr('<body ', '>')
            if "page-archive" in attributes:
                yield from self._handle_partial_articles(extr)
            else:
                yield from self._handle_full_articles(extr)

            match = self._find_pager_url(page)
            url = text.unescape(match[1]) if match else None
            query = None

    def _handle_partial_articles(self, extr):
        while True:
            section = extr('<section class="archive-entry', '</section>')
            if not section:
                break

            url = "hatenablog:" + text.unescape(text.extr(
                section, '<a class="entry-title-link" href="', '"'))
            data = {"_extractor": HatenablogEntryExtractor}
            yield Message.Queue, url, data

    def _handle_full_articles(self, extr):
        while True:
            attributes = extr('<article ', '>')
            if not attributes:
                break
            if "no-entry" in attributes:
                continue

            article = extr('', '</article>')
            yield from self._handle_article(article)

    def _acceptable_query(self, key):
        return key == "page" or key in self.allowed_parameters


class HatenablogEntryExtractor(HatenablogExtractor):
    """Extractor for a single entry URL"""
    subcategory = "entry"
    pattern = BASE_PATTERN + r"/entry/([^?#]+)" + QUERY_RE
    example = "https://BLOG.hatenablog.com/entry/PATH"

    def __init__(self, match):
        HatenablogExtractor.__init__(self, match)
        self.path = match[3]

    def items(self):
        url = "https://" + self.domain + "/entry/" + self.path
        page = self.request(url).text

        extr = text.extract_from(page)
        while True:
            attributes = extr('<article ', '>')
            if "no-entry" in attributes:
                continue
            article = extr('', '</article>')
            return self._handle_article(article)


class HatenablogHomeExtractor(HatenablogEntriesExtractor):
    """Extractor for a blog's home page"""
    subcategory = "home"
    pattern = BASE_PATTERN + r"(/?)" + QUERY_RE
    example = "https://BLOG.hatenablog.com"


class HatenablogArchiveExtractor(HatenablogEntriesExtractor):
    """Extractor for a blog's archive page"""
    subcategory = "archive"
    pattern = (BASE_PATTERN + r"(/archive(?:/\d+(?:/\d+(?:/\d+)?)?"
               r"|/category/[^?#]+)?)" + QUERY_RE)
    example = "https://BLOG.hatenablog.com/archive/2024"


class HatenablogSearchExtractor(HatenablogEntriesExtractor):
    """Extractor for a blog's search results"""
    subcategory = "search"
    pattern = BASE_PATTERN + r"(/search)" + QUERY_RE
    example = "https://BLOG.hatenablog.com/search?q=QUERY"
    allowed_parameters = ("q",)