Debian Codegraph @

gallery_dl/extractor/snapchat.py

raw
1 # -*- coding: utf-8 -*-
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License version 2 as
5 # published by the Free Software Foundation.
6
7 """Extractors for https://www.snapchat.com/"""
8
9 from .common import Extractor, Message
10 from .. import text
11
12 BASE_PATTERN = r"(?:https?://)?(?:www\.)?snapchat\.com"
13 USER = r"(?:@|add/)([^/\?#]+)"
14 USER_PATTERN = f"{BASE_PATTERN}/{USER}"
15
16
17 class SnapchatExtractor(Extractor):
18 """Base class for Snapchat extractors"""
19 category = "snapchat"
20 directory_fmt = ("{category}", "{user}")
21 filename_fmt = (
22 "{date} {id}{num:?_//>02} {title[b:150]}{file_id:? [/]/}.{extension}")
23 archive_fmt = "{date}_{id}_{num}_{file_id}"
24 root = "https://www.snapchat.com"
25 cookies_domain = ".snapchat.com"
26
27 def _request_next_data(self, url):
28 html = self.request(url).text
29 data = self._extract_nextdata(html)
30 return data["props"]["pageProps"]
31
32 def _extract_avatar(self, next_data):
33 metadata = next_data["userProfile"]["publicProfileInfo"].copy()
34
35 url = metadata["profilePictureUrl"]
36 text.nameext_from_url(url, metadata)
37 try:
38 timestamp = metadata["lastUpdateTimestampMs"]["value"]
39 except (KeyError, TypeError):
40 timestamp = metadata["creationTimestampMs"]["value"]
41 # Ignore the milliseconds from the timestamp.
42 timestamp = timestamp[:-3]
43
44 metadata.update({
45 "type" : "avatar",
46 # Unfortunately, the file extension is non-standard.
47 # We'll need to overwrite it.
48 "extension": "jpg",
49 "date" : self.parse_timestamp(timestamp),
50 "id" : metadata["username"],
51 "file_id" : url.rpartition("/")[2].rpartition(".")[0],
52 "num" : 0,
53 "url" : url,
54 "user" : next_data["user"],
55 })
56
57 return [url, metadata]
58
59 def _extract_story_list(self, next_data):
60 return next_data["curatedHighlights"].copy()
61
62 def _extract_story(self, next_data):
63 if "highlight" in next_data:
64 return next_data["highlight"].copy()
65 return next_data["story"].copy()
66
67 def _extract_spotlight_list(self, next_data):
68 return next_data["spotlightHighlights"].copy()
69
70 def _extract_spotlight_feed(self, next_data):
71 return next_data["spotlightFeed"]["spotlightStories"].copy()
72
73 def _extract_post(self, data, item, default_title):
74 url = item["snapUrls"]["mediaUrl"]
75 text.nameext_from_url(url, data)
76 timestamp = item["timestampInSec"]["value"]
77 # 0: image, 1: video.
78 media_type = item["snapMediaType"]
79 try:
80 title = data["storyTitle"]["value"]
81 except (KeyError, TypeError):
82 title = default_title
83 id = item["snapId"]["value"]
84 if not id:
85 if "highlightId" in data:
86 id = data["highlightId"]["value"]
87 else:
88 id = data["storyId"]["value"]
89
90 data.update({
91 **item,
92 "type" : "image" if media_type == 0 else "video",
93 # Unfortunately, the file extension is non-standard.
94 # We'll need to overwrite it.
95 "extension": "jpg" if media_type == 0 else "mp4",
96 "date" : self.parse_timestamp(timestamp),
97 "id" : id,
98 "num" : item["snapIndex"] + 1,
99 "title" : title,
100 "file_id" : url.partition("?")[0].rpartition("/")[2],
101 "url" : url,
102 })
103
104 return [url, data]
105
106 def _extract_story_item(self, story_data, snap_item):
107 return self._extract_post(story_data, snap_item,
108 "Snapchat Story")
109
110 def _extract_spotlight_item(self, spotlight_data, snap_item):
111 return self._extract_post(spotlight_data, snap_item,
112 "Snapchat Spotlight")
113
114
115 class SnapchatAvatarExtractor(SnapchatExtractor):
116 """Extracts a Snapchat user's avatar"""
117 subcategory = "avatar"
118 pattern = USER_PATTERN + r"/avatar"
119 example = "https://www.snapchat.com/@username/avatar"
120
121 def items(self):
122 user = self.groups[0]
123 profile_url = f"{self.root}/@{user}"
124 next_data = self._request_next_data(profile_url)
125 next_data["user"] = user
126
127 [avatar_url, next_data] = self._extract_avatar(next_data)
128 yield Message.Directory, "", next_data
129 yield Message.Url, avatar_url, next_data
130
131
132 class SnapchatStoryExtractor(SnapchatExtractor):
133 """Extracts an individual or timed story"""
134 subcategory = "story"
135 # The {20,} stops /stories and /spotlights URLs from matching with this
136 # one. It is used to match against "timed" stories such as this one:
137 # https://www.snapchat.com/@snackattackshow/
138 # PnJFM8uuTRWo90OsrEH5pwAAgeGZvd2RrZGxxAZ1I2NonAZ1I2NmfAAAAAA.
139 pattern = USER_PATTERN + r"/(?:highlight/)?[^/\?#]{20,}"
140 example = ("https://www.snapchat.com/@username/highlight"
141 "/c3050cba-2f43-4e06-8ac4-d79069bac22f")
142
143 def items(self):
144 next_data = self._request_next_data(self.url)
145 story_data = self._extract_story(next_data)
146 if "publicUserProfile" in next_data:
147 story_data["user"] = next_data["publicUserProfile"]["username"]
148 else:
149 public_profile_info = next_data["userProfile"]["publicProfileInfo"]
150 story_data["user"] = public_profile_info["username"]
151
152 yield Message.Directory, "", story_data
153 for num, snap in enumerate(story_data["snapList"]):
154 try:
155 [url, story_item_data] = self._extract_story_item(
156 story_data.copy(), snap)
157 yield Message.Url, url, story_item_data
158 except Exception as exc:
159 self.log.traceback(exc)
160 self.log.error("%s: Failed to extract story item %d (%s: %s)",
161 self.url, num + 1, exc.__class__.__name__, exc)
162
163
164 class SnapchatSpotlightExtractor(SnapchatExtractor):
165 """Extracts an individual spotlight post"""
166 subcategory = "spotlight"
167 pattern = rf"{BASE_PATTERN}/(?:{USER}/)?spotlight/[^/\?#]+"
168 example = ("https://www.snapchat.com/spotlight"
169 "/W7_EDlXWTBiXAEEniNoMPwAAYdGFzb3FpYXVuAZqDMm6sAZqDMm6VAAAAAQ")
170
171 def items(self):
172 next_data = self._request_next_data(self.url)
173 next_data = self._extract_spotlight_feed(next_data)
174 spotlight_data = next_data[0]["story"].copy()
175 spotlight_data["metadata"] = next_data[0]["metadata"].copy()
176 creator = spotlight_data["metadata"]["videoMetadata"]["creator"]
177 spotlight_data["user"] = creator["personCreator"]["username"]
178
179 yield Message.Directory, "", spotlight_data
180 for num, snap in enumerate(spotlight_data["snapList"]):
181 try:
182 [url, spotlight_item_data] = self._extract_spotlight_item(
183 spotlight_data.copy(), snap)
184 yield Message.Url, url, spotlight_item_data
185 except Exception as exc:
186 self.log.traceback(exc)
187 self.log.error("%s: Failed to extract spotlight item %d (%s: "
188 "%s)", self.url, num + 1,
189 exc.__class__.__name__, exc)
190
191
192 class SnapchatLimitedSupportExtractor(SnapchatExtractor):
193 """Notifies the user that this subcategory is only partially supported"""
194 _user_has_been_alerted = False
195
196 def _init(self):
197 if not SnapchatLimitedSupportExtractor._user_has_been_alerted:
198 subcategory = self.subcategory
199 if subcategory == "user":
200 subcategory += "s"
201 self.log.warning("Be aware that support for Snapchat %s is "
202 "limited, you may not be able to download every "
203 "post!", subcategory)
204 SnapchatLimitedSupportExtractor._user_has_been_alerted = True
205
206
207 class SnapchatStoriesExtractor(SnapchatLimitedSupportExtractor):
208 """Extracts every [known] story belonging to a single Snapchat user"""
209 subcategory = "stories"
210 pattern = USER_PATTERN + r"/(?:stories|highlights)"
211 example = "https://www.snapchat.com/@username/stories"
212
213 def items(self):
214 user = self.groups[0]
215 profile_url = f"{self.root}/@{user}"
216 next_data = self._request_next_data(profile_url)
217 next_data["user"] = user
218
219 yield Message.Directory, "", next_data
220 story_list = self._extract_story_list(next_data)
221 for num, story in enumerate(story_list):
222 for item_num, snap in enumerate(story["snapList"]):
223 try:
224 [url, story_data] = self._extract_story_item(story.copy(),
225 snap)
226 story_data["user"] = user
227 yield Message.Url, url, story_data
228 except Exception as exc:
229 self.log.traceback(exc)
230 self.log.error("%s: Failed to extract item %d of story %d "
231 "(%s: %s)", self.url, item_num + 1, num + 1,
232 exc.__class__.__name__, exc)
233
234
235 class SnapchatSpotlightsExtractor(SnapchatLimitedSupportExtractor):
236 """Extracts every [known] spotlight belonging to a single Snapchat user"""
237 subcategory = "spotlights"
238 pattern = USER_PATTERN + r"/spotlights"
239 example = "https://www.snapchat.com/@username/spotlights"
240
241 def items(self):
242 user = self.groups[0]
243 profile_url = f"{self.root}/@{user}"
244 next_data = self._request_next_data(profile_url)
245 next_data["user"] = user
246
247 yield Message.Directory, "", next_data
248 spotlight_list = self._extract_spotlight_list(next_data)
249 for num, spotlight in enumerate(spotlight_list):
250 for item_num, snap in enumerate(spotlight["snapList"]):
251 try:
252 [url, spotlight_data] = self._extract_spotlight_item(
253 spotlight.copy(), snap)
254 spotlight_data["user"] = user
255 yield Message.Url, url, spotlight_data
256 except Exception as exc:
257 self.log.traceback(exc)
258 self.log.error("%s: Failed to extract item %d of "
259 "spotlight %d (%s: %s)", self.url,
260 item_num + 1, num + 1,
261 exc.__class__.__name__, exc)
262
263
264 class SnapchatUserExtractor(SnapchatLimitedSupportExtractor):
265 """Extractor for a Snapchat user profile"""
266 subcategory = "user"
267 pattern = USER_PATTERN + r"$"
268 example = "https://www.snapchat.com/@username"
269
270 def items(self):
271 user = self.groups[0]
272 profile_url = f"{self.root}/@{user}"
273 next_data = self._request_next_data(profile_url)
274 next_data["user"] = user
275
276 yield Message.Directory, "", next_data
277
278 # Avatar.
279 try:
280 [avatar_url, avatar_data] = self._extract_avatar(next_data)
281 yield Message.Url, avatar_url, avatar_data
282 except Exception as exc:
283 self.log.traceback(exc)
284 self.log.error("%s: Failed to extract avatar (%s: %s)",
285 self.url, exc.__class__.__name__, exc)
286
287 # Stories.
288 story_list = self._extract_story_list(next_data)
289 for num, story in enumerate(story_list):
290 for item_num, snap in enumerate(story["snapList"]):
291 try:
292 [url, story_data] = self._extract_story_item(story.copy(),
293 snap)
294 story_data["user"] = user
295 yield Message.Url, url, story_data
296 except Exception as exc:
297 self.log.traceback(exc)
298 self.log.error("%s: Failed to extract item %d of story "
299 "%d (%s: %s)", self.url, item_num + 1,
300 num + 1, exc.__class__.__name__, exc)
301
302 # Spotlight.
303 spotlight_list = self._extract_spotlight_list(next_data)
304 for num, spotlight in enumerate(spotlight_list):
305 for item_num, snap in enumerate(spotlight["snapList"]):
306 try:
307 [url, spotlight_data] = self._extract_spotlight_item(
308 spotlight.copy(), snap)
309 spotlight_data["user"] = user
310 yield Message.Url, url, spotlight_data
311 except Exception as exc:
312 self.log.traceback(exc)
313 self.log.error("%s: Failed to extract item %d of "
314 "spotlight %d (%s: %s)", self.url,
315 item_num + 1, num + 1,
316 exc.__class__.__name__, exc)