Debian Codegraph @

gallery_dl/extractor/cosmos.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright 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://www.cosmos.so/"""
10
11 from .common import Extractor, Message
12 from .. import text, util
13
14 BASE_PATTERN = r"(?:https?://)?(?:www\.)?cosmos\.so"
15
16
17 class CosmosExtractor(Extractor):
18 """Base class for cosmos extractors"""
19 category = "cosmos"
20 root = "https://www.cosmos.so"
21 root_graphql = "https://api.cosmos.so/graphql"
22 filename_fmt = "{id}{num:?_//}_{filename}.{extension}"
23 archive_fmt = "{id}_{filename}"
24
25 def _init(self):
26 self.fmt = self.config("format", "jpeg")
27
28 def request_graphql(self, opname, variables):
29 headers = {
30 "Accept" : "application/graphql-response+json,"
31 "application/json;q=0.9",
32 "content-type" : "application/json",
33 "x-client-name": "cosmos-web",
34 }
35 data = {
36 "operationName": opname,
37 "variables" : variables,
38 "extensions" : {
39 "clientLibrary": {
40 "name" : "@apollo/client",
41 "version": "4.1.4",
42 },
43 },
44 "query" : self.utils("graphql", opname),
45 }
46 return self.request_json(
47 f"{self.root_graphql}?q={opname}", method="POST",
48 headers=headers, json=data)["data"].popitem()[1]
49
50 def items(self):
51 for element in self.elements():
52 element["date"] = self.parse_datetime_iso(element.get("createdAt"))
53
54 if caption := element.pop("generatedCaption", None):
55 element["description"] = caption.get("text", "")
56 else:
57 element["description"] = ""
58
59 files = self._extract_files(element)
60 element["count"] = len(files)
61
62 yield Message.Directory, "", element
63 for file in files:
64 file.update(element)
65 yield Message.Url, file["url"], file
66
67 def _extract_files(self, ele):
68 try:
69 media = ele.pop("media")
70 except Exception as exc:
71 self.log.traceback(exc)
72 return ()
73
74 if medias := ele.pop("multipleMedia", None):
75 files = []
76 for num, media in enumerate(medias, 1):
77 media["num"] = num
78 files.append(self._extract_media(media))
79 return files
80
81 return (self._extract_media(media),)
82
83 def _extract_media(self, media):
84 url = media["url"].rstrip(".")
85 if "mux" in media:
86 if mux := media["mux"]:
87 media["url"] = "ytdl:" + mux["playbackUrl"]
88 media["_fallback"] = (mux.get("downloadableUrl") or
89 mux.get("mp4Url"),)
90 else:
91 media["url"] = "ytdl:" + url
92 media["_ytdl_manifest"] = "hls"
93 media["filename"] = url[url.rfind("/")+1:-4]
94 media["extension"] = "mp4"
95 else:
96 media["filename"] = url[url.rfind("/")+1:]
97 if self.fmt is None:
98 media["extension"] = "avif"
99 else:
100 media["url"] = f"{url}?format={self.fmt}"
101 media["extension"] = self.fmt
102
103 return media
104
105 def _extract_user(self, username):
106 try:
107 page = self.request(f"{self.root}/{username}").text
108 data = text.iextr(
109 page, ',"username":"', '"data":{"user":{', '},"networkStatus"')
110 return util.json_loads(f'{{"user":{{{data}}}')["user"]
111 except Exception:
112 raise self.exc.NotFoundError("user")
113
114 def _pagination(self, opname, variables, unpack=False):
115 while True:
116 data = self.request_graphql(opname, variables)
117
118 if unpack:
119 for item in data["items"]:
120 yield item["element"]
121 else:
122 yield from data["items"]
123
124 try:
125 variables["pageCursor"] = cursor = data["meta"].get(
126 "nextPageCursor")
127 if not cursor:
128 break
129 except Exception as exc:
130 self.traceback(exc)
131 break
132
133
134 class CosmosElementExtractor(CosmosExtractor):
135 subcategory = "element"
136 pattern = BASE_PATTERN + r"/e/(\d+)"
137 example = "https://cosmos.so/e/1234567890"
138
139 def elements(self):
140 return (self.request_graphql("GetElementDetails", {
141 "elementId" : int(self.groups[0]),
142 "userId" : 0,
143 "isLoggedIn": False,
144 })["element"],)
145
146
147 class CosmosSearchExtractor(CosmosExtractor):
148 subcategory = "search"
149 directory_fmt = ("{category}", "Search", "{search_tags}")
150 pattern = BASE_PATTERN + r"/search/elements/([^/?#]+)"
151 example = "https://www.cosmos.so/search/elements/QUERY"
152
153 def elements(self):
154 self.kwdict["search_tags"] = tag = text.unquote(self.groups[0])
155 return self._pagination("SearchGlobalElements", {
156 "searchTerm" : tag,
157 "origin" : "SEARCH_BOX",
158 "contentType": None,
159 "order" : None,
160 "color" : None,
161 })
162
163
164 class CosmosCollectionsExtractor(CosmosExtractor):
165 subcategory = "collections"
166 pattern = BASE_PATTERN + r"/([^/?#]+)/collections(?:$|\?|#)"
167 example = "https://cosmos.so/USER/collections"
168
169 def items(self):
170 user = self.kwdict["user"] = self._extract_user(self.groups[0])
171 variables = {
172 "pageSize" : 20,
173 "ownerId" : user["id"],
174 "userId" : 0,
175 "isLoggedIn": False,
176 "order" : "PUBLIC",
177 "filters" : {"isPrivate": False},
178 }
179 collections = self._pagination("GetUserClusters", variables)
180
181 base = f"{self.root}/{user['username']}/"
182 for collection in collections:
183 collection["_extractor"] = CosmosCollectionExtractor
184 yield Message.Queue, base + collection["slug"], collection
185
186
187 class CosmosCollectionExtractor(CosmosExtractor):
188 subcategory = "collection"
189 directory_fmt = ("{category}", "{user[username]} ({user[id]})",
190 "{collection[name]} ({collection[id]})")
191 pattern = BASE_PATTERN + r"/([^/?#]+)/([^/?#]+)"
192 example = "https://cosmos.so/USER/COLLECTION"
193
194 def elements(self):
195 username, collection = self.groups
196 variables = {
197 "slug" : text.unquote(collection),
198 "ownerUsername" : text.unquote(username),
199 "userId" : 0,
200 "fetchSubCluster": False,
201 "isLoggedIn" : False,
202 }
203 self.kwdict["collection"] = cluster = self.request_graphql(
204 "GetClusterBasic", variables)
205 self.kwdict["user"] = cluster.pop("owner", None)
206
207 variables = {
208 "clusterId" : cluster["id"],
209 "userId" : 0,
210 "isLoggedIn" : False,
211 "showCollaborator": False,
212 }
213 return self._pagination("GetClusterElements", variables, True)
214
215
216 class CosmosUserExtractor(CosmosExtractor):
217 subcategory = "user"
218 directory_fmt = ("{category}", "{user[username]} ({user[id]})")
219 pattern = BASE_PATTERN + r"/([^/?#]+)"
220 example = "https://cosmos.so/USER"
221
222 def elements(self):
223 username = self.groups[0]
224 if username.startswith("id:"):
225 uid = int(username[3:])
226 else:
227 user = self.kwdict["user"] = self._extract_user(username)
228 uid = user["id"]
229
230 variables = {
231 "userId" : uid,
232 "callingUserId": 0,
233 "isLoggedIn" : False,
234 }
235 return self._pagination("GetUserPublicElementsV2", variables)