Debian Codegraph @

gallery_dl/extractor/500px.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 2019-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://500px.com/"""
10
11 from .common import Extractor, Message
12 from .. import util
13
14 BASE_PATTERN = r"(?:https?://)?(?:web\.)?500px\.com"
15
16
17 class _500pxExtractor(Extractor):
18 """Base class for 500px extractors"""
19 category = "500px"
20 directory_fmt = ("{category}", "{user[username]}")
21 filename_fmt = "{id}_{name}.{extension}"
22 archive_fmt = "{id}"
23 root = "https://500px.com"
24 cookies_domain = ".500px.com"
25
26 def items(self):
27 data = self.metadata()
28
29 for photo in self.photos():
30 url = photo["images"][-1]["url"]
31 photo["extension"] = photo["image_format"]
32 if data:
33 photo.update(data)
34 yield Message.Directory, "", photo
35 yield Message.Url, url, photo
36
37 def metadata(self):
38 """Returns general metadata"""
39
40 def photos(self):
41 """Returns an iterable containing all relevant photo IDs"""
42
43 def _extend(self, edges):
44 """Extend photos with additional metadata and higher resolution URLs"""
45 ids = [str(edge["node"]["legacyId"]) for edge in edges]
46
47 url = "https://api.500px.com/v1/photos"
48 params = {
49 "expanded_user_info" : "true",
50 "include_tags" : "true",
51 "include_geo" : "true",
52 "include_equipment_info": "true",
53 "vendor_photos" : "true",
54 "include_licensing" : "true",
55 "include_releases" : "true",
56 "liked_by" : "1",
57 "following_sample" : "100",
58 "image_size" : "4096",
59 "ids" : ",".join(ids),
60 }
61
62 photos = self._request_api(url, params)["photos"]
63 return [
64 photos[pid] for pid in ids
65 if pid in photos or
66 self.log.warning("Unable to fetch photo %s", pid)
67 ]
68
69 def _request_api(self, url, params):
70 headers = {
71 "x-csrf-token": self.cookies.get(
72 "x-csrf-token", domain=".500px.com"),
73 }
74 return self.request_json(url, headers=headers, params=params)
75
76 def _request_graphql(self, opname, variables):
77 url = "https://api.500px.com/graphql"
78 headers = {
79 "x-csrf-token": self.cookies.get(
80 "x-csrf-token", domain=".500px.com"),
81 }
82 data = {
83 "operationName": opname,
84 "variables" : util.json_dumps(variables),
85 "query" : self.utils("graphql", opname),
86 }
87 return self.request_json(
88 url, method="POST", headers=headers, json=data)["data"]
89
90
91 class _500pxUserExtractor(_500pxExtractor):
92 """Extractor for photos from a user's photostream on 500px.com"""
93 subcategory = "user"
94 pattern = BASE_PATTERN + r"/(?!photo/|liked)(?:p/)?([^/?#]+)/?(?:$|[?#])"
95 example = "https://500px.com/USER"
96
97 def __init__(self, match):
98 _500pxExtractor.__init__(self, match)
99 self.user = match[1]
100
101 def photos(self):
102 variables = {"username": self.user, "pageSize": 20}
103 photos = self._request_graphql(
104 "OtherPhotosQuery", variables,
105 )["user"]["photos"]
106
107 while True:
108 yield from self._extend(photos["edges"])
109
110 if not photos["pageInfo"]["hasNextPage"]:
111 return
112
113 variables["cursor"] = photos["pageInfo"]["endCursor"]
114 photos = self._request_graphql(
115 "OtherPhotosPaginationContainerQuery", variables,
116 )["userByUsername"]["photos"]
117
118
119 class _500pxGalleryExtractor(_500pxExtractor):
120 """Extractor for photo galleries on 500px.com"""
121 subcategory = "gallery"
122 directory_fmt = ("{category}", "{user[username]}", "{gallery[name]}")
123 pattern = (BASE_PATTERN + r"/(?!photo/)(?:p/)?"
124 r"([^/?#]+)/galleries/([^/?#]+)")
125 example = "https://500px.com/USER/galleries/GALLERY"
126
127 def __init__(self, match):
128 _500pxExtractor.__init__(self, match)
129 self.user_name, self.gallery_name = match.groups()
130 self.user_id = self._photos = None
131
132 def metadata(self):
133 user = self._request_graphql(
134 "ProfileRendererQuery", {"username": self.user_name},
135 )["profile"]
136 self.user_id = str(user["legacyId"])
137
138 variables = {
139 "galleryOwnerLegacyId": self.user_id,
140 "ownerLegacyId" : self.user_id,
141 "slug" : self.gallery_name,
142 "token" : None,
143 "pageSize" : 20,
144 }
145 gallery = self._request_graphql(
146 "GalleriesDetailQueryRendererQuery", variables,
147 )["gallery"]
148
149 self._photos = gallery["photos"]
150 del gallery["photos"]
151 return {
152 "gallery": gallery,
153 "user" : user,
154 }
155
156 def photos(self):
157 photos = self._photos
158 variables = {
159 "ownerLegacyId": self.user_id,
160 "slug" : self.gallery_name,
161 "token" : None,
162 "pageSize" : 20,
163 }
164
165 while True:
166 yield from self._extend(photos["edges"])
167
168 if not photos["pageInfo"]["hasNextPage"]:
169 return
170
171 variables["cursor"] = photos["pageInfo"]["endCursor"]
172 photos = self._request_graphql(
173 "GalleriesDetailPaginationContainerQuery", variables,
174 )["galleryByOwnerIdAndSlugOrToken"]["photos"]
175
176
177 class _500pxFavoriteExtractor(_500pxExtractor):
178 """Extractor for favorite 500px photos"""
179 subcategory = "favorite"
180 pattern = BASE_PATTERN + r"/liked/?$"
181 example = "https://500px.com/liked"
182
183 def photos(self):
184 variables = {"pageSize": 20}
185 photos = self._request_graphql(
186 "LikedPhotosQueryRendererQuery", variables,
187 )["likedPhotos"]
188
189 while True:
190 yield from self._extend(photos["edges"])
191
192 if not photos["pageInfo"]["hasNextPage"]:
193 return
194
195 variables["cursor"] = photos["pageInfo"]["endCursor"]
196 photos = self._request_graphql(
197 "LikedPhotosPaginationContainerQuery", variables,
198 )["likedPhotos"]
199
200
201 class _500pxImageExtractor(_500pxExtractor):
202 """Extractor for individual images from 500px.com"""
203 subcategory = "image"
204 pattern = BASE_PATTERN + r"/photo/(\d+)"
205 example = "https://500px.com/photo/12345/TITLE"
206
207 def __init__(self, match):
208 _500pxExtractor.__init__(self, match)
209 self.photo_id = match[1]
210
211 def photos(self):
212 edges = ({"node": {"legacyId": self.photo_id}},)
213 return self._extend(edges)