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 text, 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}", "{uploader[username]}")
21 filename_fmt = "{date:%Y-%m-%d} {title} ({id}).{extension}"
22 archive_fmt = "{id}"
23 root = "https://500px.com"
24 cookies_domain = ".500px.com"
25
26 def _init(self):
27 self.headers = {"x-500px-platform": "Web"}
28
29 name = "x-500px-device-id-prod"
30 if value := self.cookies.get(name, domain=self.cookies_domain):
31 self.headers[name] = value
32 else:
33 self.headers[name] = value = util.generate_uuid()
34 self.cookies.set(name, value, domain=self.cookies_domain)
35
36 name = "x-500px-csrf-token-prod"
37 if value := self.cookies.get(name, domain=self.cookies_domain):
38 self.headers[name] = value
39 else:
40 self.headers[name] = value = util.generate_token(43)
41 self.cookies.set(name, value, domain=self.cookies_domain)
42
43 def items(self):
44 for photo in self.photos():
45 if "videoUrl" in photo:
46 url = photo["videoUrl"]
47 photo["type"] = "video"
48 else:
49 url = photo["urls"]["size_4k"]
50 photo["type"] = "photo"
51 photo["date_taken"] = self.parse_datetime_iso(
52 photo["takenAt"])
53 photo["id_num"] = url.rsplit("/", 2)[1]
54 photo["date"] = self.parse_datetime_iso(photo["uploadedAt"])
55 text.nameext_from_url(url, photo)
56 yield Message.Directory, "", photo
57 yield Message.Url, url, photo
58
59 def request_graphql(self, opname, variables):
60 url = "https://api-neo.500px.com/graphql"
61 headers = {
62 **self.headers,
63 "Accept": "application/graphql-response+json,"
64 "application/json;q=0.9",
65 "content-type": "application/json",
66 }
67 body = {
68 "operationName": opname,
69 "variables" : variables,
70 "extensions" : {"clientLibrary": {
71 "name" : "@apollo/client",
72 "version" : "4.1.6",
73 }},
74 "query" : self.utils("graphql", opname),
75 }
76 return self.request_json(
77 url, method="POST", headers=headers, json=body,
78 )["data"].popitem()[1]
79
80 def _pagination(self, opname, variables):
81 while True:
82 data = self.request_graphql(opname, variables)
83
84 if isinstance(data, list):
85 yield from data
86 else:
87 for edge in data["edges"]:
88 yield edge["node"]
89
90 info = data.get("pageInfo")
91 if not info or not info.get("hasNextPage"):
92 break
93 variables["after"] = info["endCursor"]
94
95
96 class _500pxUserExtractor(_500pxExtractor):
97 """Extractor for photos from a user's photostream on 500px.com"""
98 subcategory = "user"
99 pattern = BASE_PATTERN + r"/(?!photo/|liked)(?:p/)?([^/?#]+)/?(?:$|[?#])"
100 example = "https://500px.com/USER"
101
102 def photos(self):
103 self.kwdict["user"] = user = self.request_graphql(
104 "getUserProfile", {"username": self.groups[0]})
105
106 variables = {
107 "sort" : "CREATED_AT_DESC",
108 "first" : 20,
109 "resourceTypes": ("PHOTO", "PHOTO_GROUP", "VIDEO"),
110 "excludeNsfw" : False,
111 "userId" : user["id"],
112 }
113
114 return self._pagination("pageResources", variables)
115
116
117 class _500pxGalleryExtractor(_500pxExtractor):
118 """Extractor for photo galleries on 500px.com"""
119 subcategory = "gallery"
120 directory_fmt = ("{category}", "{user[username]}",
121 "Galleries", "{gallery[name]} ({gallery[id]})")
122 pattern = BASE_PATTERN + r"/gallery/([^/?#]+)"
123 example = "https://500px.com/gallery/ID"
124
125 def photos(self):
126 self.kwdict["gallery"] = gallery = self.request_graphql(
127 "GetGalleryById", {"id": self.groups[0]})
128 self.kwdict["user"] = self.request_graphql(
129 "getUserProfile", {"username": gallery["creator"]["username"]})
130
131 variables = {
132 "first" : 20,
133 "galleryId": gallery["id"]
134 }
135
136 return self._pagination("PageGalleryItems", variables)
137
138
139 class _500pxGroupExtractor(_500pxExtractor):
140 """Extractor for photo groups"""
141 subcategory = "group"
142 directory_fmt = ("{category}", "{user[username]}",
143 "{group[title]} ({group[id]})")
144 filename_fmt = "{num:>02} {date:%Y-%m-%d} {title} ({id}).{extension}"
145 pattern = BASE_PATTERN + r"/photo-group/([^/?#]+)"
146 example = "https://500px.com/photo-group/1a2B3"
147
148 def photos(self):
149 self.kwdict["group"] = group = self.request_graphql(
150 "getPhotoGroupById", {"id": self.groups[0]})
151 self.kwdict["user"] = group.pop("uploader")
152
153 variables = {
154 "excludeNsfw": False,
155 "groupId" : group["id"],
156 }
157
158 photos = self.request_graphql("getPhotosByGroupId", variables)
159 self.kwdict["count"] = len(photos)
160 for num, photo in enumerate(photos, 1):
161 photo["num"] = num
162 return photos
163
164
165 class _500pxPostExtractor(_500pxExtractor):
166 """Extractor for individual posts from 500px.com"""
167 subcategory = "post"
168 pattern = BASE_PATTERN + r"/(photo|video)/([^/?#]+)"
169 example = "https://500px.com/photo/1a2B3"
170
171 def __init__(self, match):
172 self.subcategory = match[1]
173 _500pxExtractor.__init__(self, match)
174
175 def photos(self):
176 type, id = self.groups
177 opname = "getPhotoById" if type == "photo" else "getVideoById"
178 return (self.request_graphql(opname, {"id": id}),)