aboutsummaryrefslogtreecommitdiffstats
path: root/gallery_dl/extractor/pexels.py
blob: 804623b891107e6e6180830edc880bde5ec0ccb5 (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
187
188
189
# -*- coding: utf-8 -*-

# Copyright 2025 Mike Fährmann
#
# 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://pexels.com/"""

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

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


class PexelsExtractor(Extractor):
    """Base class for pexels extractors"""
    category = "pexels"
    root = "https://www.pexels.com"
    archive_fmt = "{id}"
    request_interval = (1.0, 2.0)
    request_interval_min = 0.5

    def _init(self):
        self.api = PexelsAPI(self)

    def items(self):
        metadata = self.metadata()

        for post in self.posts():
            if "attributes" in post:
                attr = post
                post = post["attributes"]
                post["type"] = attr["type"]

            post.update(metadata)
            post["date"] = text.parse_datetime(
                post["created_at"][:-5], "%Y-%m-%dT%H:%M:%S")

            if "image" in post:
                url, _, query = post["image"]["download_link"].partition("?")
                name = text.extr(query, "&dl=", "&")
            elif "video" in post:
                video = post["video"]
                name = video["src"]
                url = video["download_link"]
            else:
                self.log.warning("%s: Unsupported post type", post.get("id"))
                continue

            yield Message.Directory, post
            yield Message.Url, url, text.nameext_from_url(name, post)

    def posts(self):
        return ()

    def metadata(self):
        return {}


class PexelsCollectionExtractor(PexelsExtractor):
    """Extractor for a pexels.com collection"""
    subcategory = "collection"
    directory_fmt = ("{category}", "Collections", "{collection}")
    pattern = BASE_PATTERN + r"/collections/((?:[^/?#]*-)?(\w+))"
    example = "https://www.pexels.com/collections/SLUG-a1b2c3/"

    def metadata(self):
        cname, cid = self.groups
        return {"collection": cname, "collection_id": cid}

    def posts(self):
        return self.api.collections_media(self.groups[1])


class PexelsSearchExtractor(PexelsExtractor):
    """Extractor for pexels.com search results"""
    subcategory = "search"
    directory_fmt = ("{category}", "Searches", "{search_tags}")
    pattern = BASE_PATTERN + r"/search/([^/?#]+)"
    example = "https://www.pexels.com/search/QUERY/"

    def metadata(self):
        return {"search_tags": self.groups[0]}

    def posts(self):
        return self.api.search_photos(self.groups[0])


class PexelsUserExtractor(PexelsExtractor):
    """Extractor for pexels.com user galleries"""
    subcategory = "user"
    directory_fmt = ("{category}", "@{user[slug]}")
    pattern = BASE_PATTERN + r"/(@(?:(?:[^/?#]*-)?(\d+)|[^/?#]+))"
    example = "https://www.pexels.com/@USER-12345/"

    def posts(self):
        return self.api.users_media_recent(self.groups[1] or self.groups[0])


class PexelsImageExtractor(PexelsExtractor):
    subcategory = "image"
    pattern = BASE_PATTERN + r"/photo/((?:[^/?#]*-)?\d+)"
    example = "https://www.pexels.com/photo/SLUG-12345/"

    def posts(self):
        url = "{}/photo/{}/".format(self.root, self.groups[0])
        page = self.request(url).text
        return (self._extract_nextdata(page)["props"]["pageProps"]["medium"],)


class PexelsAPI():
    """Interface for the Pexels Web API"""

    def __init__(self, extractor):
        self.extractor = extractor
        self.root = "https://www.pexels.com/en-us/api"
        self.headers = {
            "Accept"        : "*/*",
            "Content-Type"  : "application/json",
            "secret-key"    : "H2jk9uKnhRmL6WPwh89zBezWvr",
            "Authorization" : "",
            "X-Forwarded-CF-Connecting-IP" : "",
            "X-Forwarded-HTTP_CF_IPCOUNTRY": "",
            "X-Forwarded-CF-IPRegionCode"  : "",
            "X-Client-Type" : "react",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "same-origin",
            "Priority"      : "u=4",
        }

    def collections_media(self, collection_id):
        endpoint = "/v3/collections/{}/media".format(collection_id)
        params = {
            "page"    : "1",
            "per_page": "24",
        }
        return self._pagination(endpoint, params)

    def search_photos(self, query):
        endpoint = "/v3/search/photos"
        params = {
            "query"      : query,
            "page"       : "1",
            "per_page"   : "24",
            "orientation": "all",
            "size"       : "all",
            "color"      : "all",
            "sort"       : "popular",
        }
        return self._pagination(endpoint, params)

    def users_media_recent(self, user_id):
        endpoint = "/v3/users/{}/media/recent".format(user_id)
        params = {
            "page"    : "1",
            "per_page": "24",
        }
        return self._pagination(endpoint, params)

    def _call(self, endpoint, params):
        url = self.root + endpoint

        while True:
            response = self.extractor.request(
                url, params=params, headers=self.headers, fatal=None)

            if response.status_code < 300:
                return response.json()

            elif response.status_code == 429:
                self.extractor.wait(seconds=600)

            else:
                self.extractor.log.debug(response.text)
                raise exception.StopExtraction("API request failed")

    def _pagination(self, endpoint, params):
        while True:
            data = self._call(endpoint, params)

            yield from data["data"]

            pagination = data["pagination"]
            if pagination["current_page"] >= pagination["total_pages"]:
                return
            params["page"] = pagination["current_page"] + 1