aboutsummaryrefslogtreecommitdiffstats
path: root/gallery_dl/extractor/redbust.py
blob: d00ed526b118a39766df30969ccdeded170de6c2 (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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# -*- 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://redbust.com/"""

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

BASE_PATTERN = r"(?:https?://)?redbust\.com"


class RedbustExtractor(Extractor):
    """Base class for RedBust extractors"""
    category = "redbust"
    root = "https://redbust.com"
    filename_fmt = "{filename}.{extension}"

    def items(self):
        data = {"_extractor": RedbustGalleryExtractor}
        for url in self.galleries():
            yield Message.Queue, url, data

    def _pagination(self, path, page=None):
        if page is None:
            url = f"{self.root}{path}/"
            base = url + "page/"
            page = self.request(url).text
        else:
            base = f"{self.root}{path}/page/"

        pnum = 1
        while True:
            for post in text.extract_iter(
                    page, '<h2 class="post-title">', "rel="):
                yield text.extr(post, 'href="', '"')

            pnum += 1
            url = f"{base}{pnum}/"
            if url not in page:
                return
            page = self.request(url).text


class RedbustGalleryExtractor(GalleryExtractor, RedbustExtractor):
    """Extractor for RedBust galleries"""
    pattern = BASE_PATTERN + r"/([\w-]+)/?$"
    example = "https://redbust.com/TITLE/"

    def items(self):
        url = f"{self.root}/{self.groups[0]}/"
        self.page = page = self.request(url).text

        self.gallery_id = gid = text.extr(
            page, "<link rel='shortlink' href='https://redbust.com/?p=", "'")

        if gid:
            self.page_url = False
            return GalleryExtractor.items(self)
        else:
            self.subcategory = "category"
            return self._items_category(page)

    def _items_category(self, _):
        page = self.page
        data = {"_extractor": RedbustGalleryExtractor}
        base = f"{self.root}/{self.groups[0]}/page/"
        pnum = 1

        while True:
            for post in text.extract_iter(
                    page, '<h2 class="post-title">', "rel="):
                url = text.extr(post, 'href="', '"')
                yield Message.Queue, url, data

            pnum += 1
            url = f"{base}{pnum}/"
            if url not in page:
                return
            page = self.request(url).text

    def metadata(self, _):
        extr = text.extract_from(self.page)

        return {
            "gallery_id"  : self.gallery_id,
            "gallery_slug": self.groups[0],
            "categories"  : text.split_html(extr(
                '<li class="category">', "</li>"))[::2],
            "title"       : text.unescape(extr('class="post-title">', "<")),
            "date"        : text.parse_datetime(
                extr('class="post-byline">', "<").strip(), "%B %d, %Y"),
            "views"       : text.parse_int(extr("</b>", "v").replace(",", "")),
            "tags"        : text.split_html(extr(
                'class="post-tags">', "</p"))[1:],
        }

    def images(self, _):
        results = []

        for img in text.extract_iter(self.page, "'><img ", ">"):
            if src := text.extr(img, 'src="', '"'):
                path, _, end = src.rpartition("-")
                if "x" in end:
                    url = f"{path}.{end.rpartition('.')[2]}"
                    data = None if src == url else {"_fallback": (src,)}
                else:
                    url = src
                    data = None
                results.append((url, data))

        if not results:
            # fallback for older galleries
            for path in text.extract_iter(
                    self.page, '<img src="/wp-content/uploads/', '"'):
                results.append(
                    (f"{self.root}/wp-content/uploads/{path}", None))

        return results


class RedbustTagExtractor(RedbustExtractor):
    """Extractor for RedBust tag searches"""
    subcategory = "tag"
    pattern = BASE_PATTERN + r"/tag/([\w-]+)"
    example = "https://redbust.com/tag/TAG/"

    def galleries(self):
        return self._pagination("/tag/" + self.groups[0])


class RedbustArchiveExtractor(RedbustExtractor):
    """Extractor for RedBust monthly archive collections"""
    subcategory = "archive"
    pattern = BASE_PATTERN + r"(/\d{4}/\d{2})"
    example = "https://redbust.com/2010/01/"

    def galleries(self):
        return self._pagination(self.groups[0])


class RedbustImageExtractor(RedbustExtractor):
    """Extractor for RedBust images"""
    subcategory = "image"
    directory_fmt = ("{category}", "{title}")
    pattern = BASE_PATTERN + r"/(?!tag/|\d{4}/)([\w-]+)/([\w-]+)/?$"
    example = "https://redbust.com/TITLE/SLUG/"

    def items(self):
        gallery_slug, image_slug = self.groups
        url = f"{self.root}/{gallery_slug}/{image_slug}/"
        page = self.request(url).text

        img_url = None

        # Look for the largest image in srcset first
        if srcset := text.extr(page, 'srcset="', '"'):
            # Extract the largest image from srcset (typically last one)
            urls = srcset.split(", ")
            img_url = urls[-1].partition(" ")[0] if urls else None

        # Fallback to original extraction method
        if not img_url:
            if entry := text.extr(page, "entry-inner ", "alt="):
                img_url = text.extr(entry, "img src=", " ").strip("\"'")

        if not img_url:
            return

        end = img_url.rpartition("-")[2]
        data = text.nameext_from_url(img_url, {
            "title"       : text.unescape(text.extr(
                page, 'title="Return to ', '"')),
            "image_id"    : text.extr(
                page, "rel='shortlink' href='https://redbust.com/?p=", "'"),
            "gallery_slug": gallery_slug,
            "image_slug"  : image_slug,
            "num"         : text.parse_int(end.partition(".")[0]),
            "count"       : 1,
            "url"         : img_url,
        })

        yield Message.Directory, data
        yield Message.Url, img_url, data