| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
n |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
"""Extractors for https://www.instagram.com/""" |
| 11 |
|
| 12 |
from .common import Extractor, Message, Dispatch |
| 13 |
from .. import text, util |
| 14 |
import itertools |
| 15 |
|
| 16 |
BASE_PATTERN = r"(?:https?://)?(?:www\.)?instagram\.com" |
| 17 |
USER_PATTERN = BASE_PATTERN + r"/(?!(?:p|tv|reel|explore|stories)/)([^/?#]+)" |
| 18 |
|
| 19 |
|
| 20 |
class InstagramExtractor(Extractor): |
| 21 |
"""Base class for instagram extractors""" |
| 22 |
category = "instagram" |
| 23 |
directory_fmt = ("{category}", "{username}") |
| 24 |
filename_fmt = "{sidecar_media_id:?/_/}{media_id}.{extension}" |
| 25 |
archive_fmt = "{media_id}" |
| 26 |
root = "https://www.instagram.com" |
| 27 |
cookies_domain = ".instagram.com" |
| 28 |
cookies_names = ("sessionid",) |
| 29 |
useragent = util.USERAGENT_CHROME |
| 30 |
request_interval = (6.0, 12.0) |
| 31 |
|
| 32 |
def __init__(self, match): |
| 33 |
Extractor.__init__(self, match) |
| 34 |
self.item = match[1] |
| 35 |
|
| 36 |
def _init(self): |
| 37 |
self.www_claim = "0" |
| 38 |
self.csrf_token = util.generate_token() |
| 39 |
self._find_tags = text.re(r"#\w+").findall |
| 40 |
self._logged_in = True |
| 41 |
self._cursor = None |
| 42 |
self._user = None |
| 43 |
|
| 44 |
self.cookies.set( |
| 45 |
"csrftoken", self.csrf_token, domain=self.cookies_domain) |
| 46 |
|
| 47 |
if not (wd := self.config("wd", False)): |
| 48 |
self.cookies.set("wd", None, domain=self.cookies_domain) |
| 49 |
elif isinstance(wd, str): |
| 50 |
self.cookies.set("wd", wd, domain=self.cookies_domain) |
| 51 |
|
| 52 |
if self.config("api") == "graphql": |
| 53 |
self.api = InstagramGraphqlAPI(self) |
| 54 |
else: |
| 55 |
self.api = InstagramRestAPI(self) |
| 56 |
|
| 57 |
self._static_video = \ |
| 58 |
True if self.config("static-videos", True) else False |
| 59 |
self._warn_video = \ |
| 60 |
True if self.config("warn-videos", True) else False |
| 61 |
self._warn_image = ( |
| 62 |
9 if not (wi := self.config("warn-images", True)) else |
| 63 |
1 if wi in {"all", "both"} else |
| 64 |
0) |
| 65 |
|
| 66 |
def items(self): |
| 67 |
self.login() |
| 68 |
|
| 69 |
data = self.metadata() |
| 70 |
|
| 71 |
if videos := self.config("videos", True): |
| 72 |
self.videos_dash = videos_dash = (videos != "merged") |
| 73 |
else: |
| 74 |
self.videos_dash = False |
| 75 |
|
| 76 |
if audio := self.config("audio", False): |
| 77 |
audio_dash = (audio != "merged") |
| 78 |
else: |
| 79 |
audio_dash = False |
| 80 |
|
| 81 |
if previews := self.config("previews", False): |
| 82 |
if isinstance(previews, str): |
| 83 |
previews = previews.split(",") |
| 84 |
elif not isinstance(previews, (list, tuple)): |
| 85 |
previews = {"video", "audio"} |
| 86 |
previews_video = ("video" in previews) |
| 87 |
previews_audio = ("audio" in previews) |
| 88 |
else: |
| 89 |
previews_video = previews_audio = False |
| 90 |
del previews |
| 91 |
|
| 92 |
pinned = self.config("pinned", True) |
| 93 |
max_posts = self.config("max-posts") |
| 94 |
order = self.config("order-files") |
| 95 |
reverse = order[0] in {"r", "d"} if order else False |
| 96 |
videos_headers = {"User-Agent": "Mozilla/5.0"} |
| 97 |
|
| 98 |
posts = self.posts() |
| 99 |
if max_posts: |
| 100 |
posts = itertools.islice(posts, max_posts) |
| 101 |
|
| 102 |
for post in posts: |
| 103 |
if "__typename" in post: |
| 104 |
post = self._parse_post_graphql(post) |
| 105 |
else: |
| 106 |
post = self._parse_post_rest(post) |
| 107 |
|
| 108 |
if not pinned and post.get("pinned"): |
| 109 |
self.log.debug("%s: Skipping pinned post", post.get("post_id")) |
| 110 |
continue |
| 111 |
|
| 112 |
if self._user: |
| 113 |
post["user"] = self._user |
| 114 |
post.update(data) |
| 115 |
files = post.pop("_files") |
| 116 |
|
| 117 |
post["count"] = len(files) |
| 118 |
yield Message.Directory, "", post |
| 119 |
|
| 120 |
if reverse: |
| 121 |
files.reverse() |
| 122 |
|
| 123 |
for file in files: |
| 124 |
file = {**post, **file} |
| 125 |
|
| 126 |
if url := file.get("audio_url"): |
| 127 |
if audio: |
| 128 |
file["_http_headers"] = videos_headers |
| 129 |
text.nameext_from_url(url, file) |
| 130 |
if audio_dash and "_ytdl_manifest_data" in file: |
| 131 |
file["_fallback"] = (url,) |
| 132 |
file["_ytdl_manifest"] = "dash" |
| 133 |
url = f"ytdl:{post['post_url']}{file['num']}.m4a" |
| 134 |
yield Message.Url, url, file |
| 135 |
if previews_audio and file.get("display_url"): |
| 136 |
file["media_id"] += "p" |
| 137 |
else: |
| 138 |
continue |
| 139 |
elif url := file.get("video_url"): |
| 140 |
if videos: |
| 141 |
file["_http_headers"] = videos_headers |
| 142 |
text.nameext_from_url(url, file) |
| 143 |
if videos_dash and "_ytdl_manifest_data" in file: |
| 144 |
file["_fallback"] = (url,) |
| 145 |
file["_ytdl_manifest"] = "dash" |
| 146 |
url = f"ytdl:{post['post_url']}{file['num']}.mp4" |
| 147 |
yield Message.Url, url, file |
| 148 |
if previews_video: |
| 149 |
file["media_id"] += "p" |
| 150 |
else: |
| 151 |
continue |
| 152 |
|
| 153 |
url = file["display_url"] |
| 154 |
text.nameext_from_url(url, file) |
| 155 |
if file["extension"] == "webp" and "stp=dst-jpg" in url: |
| 156 |
file["extension"] = "jpg" |
| 157 |
yield Message.Url, url, file |
| 158 |
|
| 159 |
def metadata(self): |
| 160 |
return () |
| 161 |
|
| 162 |
def posts(self): |
| 163 |
return () |
| 164 |
|
| 165 |
def finalize(self, status): |
| 166 |
if status and self._cursor: |
| 167 |
self.log.info("Use '-o cursor=%s' to continue downloading " |
| 168 |
"from the current position", self._cursor) |
| 169 |
|
| 170 |
def request(self, url, **kwargs): |
| 171 |
response = Extractor.request(self, url, **kwargs) |
| 172 |
|
| 173 |
if response.history: |
| 174 |
|
| 175 |
url = response.url |
| 176 |
if "/accounts/login/" in url: |
| 177 |
page = "login" |
| 178 |
elif "/challenge/" in url: |
| 179 |
page = "challenge" |
| 180 |
elif 24 < len(url) < 28 and url[-1] == "/": |
| 181 |
page = "home" |
| 182 |
else: |
| 183 |
page = None |
| 184 |
|
| 185 |
if page is not None: |
| 186 |
raise self.exc.AbortExtraction( |
| 187 |
f"HTTP redirect to {page} page ({url.partition('?')[0]})") |
| 188 |
|
| 189 |
www_claim = response.headers.get("x-ig-set-www-claim") |
| 190 |
if www_claim is not None: |
| 191 |
self.www_claim = www_claim |
| 192 |
|
| 193 |
if csrf_token := response.cookies.get("csrftoken"): |
| 194 |
self.csrf_token = csrf_token |
| 195 |
|
| 196 |
return response |
| 197 |
|
| 198 |
def login(self): |
| 199 |
if self.cookies_check(self.cookies_names): |
| 200 |
return |
| 201 |
|
| 202 |
username, password = self._get_auth_info() |
| 203 |
if username: |
| 204 |
return self.cookies_update(self.cache( |
| 205 |
self._login_impl, username, password, |
| 206 |
_exp=90*86400, _mem=False)) |
| 207 |
|
| 208 |
self._logged_in = False |
| 209 |
|
| 210 |
def _login_impl(self, username, password): |
| 211 |
self.log.error("Login with username & password is no longer " |
| 212 |
"supported. Use browser cookies instead.") |
| 213 |
return {} |
| 214 |
|
| 215 |
def _parse_post_rest(self, post): |
| 216 |
if "items" in post: |
| 217 |
items = post["items"] |
| 218 |
reel_id = str(post["id"]).rpartition(":")[2] |
| 219 |
if expires := post.get("expiring_at"): |
| 220 |
post_url = f"{self.root}/stories/{post['user']['username']}/" |
| 221 |
else: |
| 222 |
post_url = f"{self.root}/stories/highlights/{reel_id}/" |
| 223 |
data = { |
| 224 |
"user" : post.get("user"), |
| 225 |
"expires": self.parse_timestamp(expires), |
| 226 |
"post_id": reel_id, |
| 227 |
"post_shortcode": shortcode_from_id(reel_id), |
| 228 |
"post_url": post_url, |
| 229 |
"type": "story" if expires else "highlight", |
| 230 |
} |
| 231 |
if "title" in post: |
| 232 |
data["highlight_title"] = post["title"] |
| 233 |
if expires and not post.get("seen"): |
| 234 |
post["seen"] = expires - 86400 |
| 235 |
|
| 236 |
else: |
| 237 |
data = { |
| 238 |
"post_id" : post["pk"], |
| 239 |
"post_shortcode": post["code"], |
| 240 |
"likes": post.get("like_count", 0), |
| 241 |
"liked": post.get("has_liked", False), |
| 242 |
"pinned": self._extract_pinned(post), |
| 243 |
} |
| 244 |
|
| 245 |
caption = post["caption"] |
| 246 |
data["description"] = caption["text"] if caption else "" |
| 247 |
|
| 248 |
if tags := self._find_tags(data["description"]): |
| 249 |
data["tags"] = sorted(set(tags)) |
| 250 |
|
| 251 |
if location := post.get("location"): |
| 252 |
slug = location["short_name"].replace(" ", "-").lower() |
| 253 |
data["location_id"] = location["pk"] |
| 254 |
data["location_slug"] = slug |
| 255 |
data["location_url"] = \ |
| 256 |
f"{self.root}/explore/locations/{location['pk']}/{slug}/" |
| 257 |
|
| 258 |
if coauthors := post.get("coauthor_producers"): |
| 259 |
data["coauthors"] = [ |
| 260 |
{"id" : user["pk"], |
| 261 |
"username" : user["username"], |
| 262 |
"full_name": user["full_name"]} |
| 263 |
for user in coauthors |
| 264 |
] |
| 265 |
|
| 266 |
if items := post.get("carousel_media"): |
| 267 |
data["sidecar_media_id"] = data["post_id"] |
| 268 |
data["sidecar_shortcode"] = data["post_shortcode"] |
| 269 |
else: |
| 270 |
items = (post,) |
| 271 |
|
| 272 |
owner = post["user"] |
| 273 |
data["owner_id"] = owner["pk"] |
| 274 |
data["username"] = owner.get("username") |
| 275 |
data["fullname"] = owner.get("full_name") |
| 276 |
data["post_date"] = data["date"] = self.parse_timestamp( |
| 277 |
post.get("taken_at") or post.get("created_at") or post.get("seen")) |
| 278 |
data["_files"] = files = [] |
| 279 |
for num, item in enumerate(items, 1): |
| 280 |
|
| 281 |
try: |
| 282 |
image = item["image_versions2"]["candidates"][0] |
| 283 |
except Exception: |
| 284 |
self.log.warning("Missing media in post %s", |
| 285 |
data["post_shortcode"]) |
| 286 |
continue |
| 287 |
|
| 288 |
if not self._static_video and \ |
| 289 |
(type_orig := item.get("original_media_type")) and \ |
| 290 |
type_orig == 1 and type_orig != item.get("media_type"): |
| 291 |
if item.pop("video_versions", None): |
| 292 |
item["original_width"] = image["width"] |
| 293 |
item["original_height"] = image["height"] |
| 294 |
|
| 295 |
width_orig = item.get("original_width", 0) |
| 296 |
height_orig = item.get("original_height", 0) |
| 297 |
|
| 298 |
if video_versions := item.get("video_versions"): |
| 299 |
video = max( |
| 300 |
video_versions, |
| 301 |
key=lambda x: (x["width"], x["height"], x["type"]), |
| 302 |
) |
| 303 |
|
| 304 |
media = video |
| 305 |
if (manifest := item.get("video_dash_manifest")) and \ |
| 306 |
self.videos_dash: |
| 307 |
width = width_orig |
| 308 |
height = height_orig |
| 309 |
else: |
| 310 |
width = video["width"] |
| 311 |
height = video["height"] |
| 312 |
|
| 313 |
if self._warn_video: |
| 314 |
self._warn_video = False |
| 315 |
pattern = text.re( |
| 316 |
r"Chrome/\d{3,}\.\d+\.\d+\.\d+(?!\d* Mobile)") |
| 317 |
if not pattern.search(self.session.headers["User-Agent"]): |
| 318 |
self.log.warning("Potentially lowered video quality " |
| 319 |
"due to non-Chrome User-Agent") |
| 320 |
else: |
| 321 |
video = manifest = None |
| 322 |
media = image |
| 323 |
width = image["width"] |
| 324 |
height = image["height"] |
| 325 |
|
| 326 |
if self._warn_image < ((width * 1.1 < width_orig) + |
| 327 |
(height * 1.1 < height_orig)): |
| 328 |
self.log.warning( |
| 329 |
"%s: Available image resolutions lower than the " |
| 330 |
"original (%sx%s < %sx%s). " |
| 331 |
"Consider refreshing your cookies.", |
| 332 |
data["post_shortcode"], |
| 333 |
width, height, width_orig, height_orig) |
| 334 |
|
| 335 |
media = { |
| 336 |
"num" : num, |
| 337 |
"date" : self.parse_timestamp(item.get("taken_at") or |
| 338 |
media.get("taken_at") or |
| 339 |
post.get("taken_at")), |
| 340 |
"media_id" : item["pk"], |
| 341 |
"shortcode" : (item.get("code") or |
| 342 |
shortcode_from_id(item["pk"])), |
| 343 |
"display_url": image["url"], |
| 344 |
"video_url" : video["url"] if video else None, |
| 345 |
"width" : width, |
| 346 |
"width_original" : width_orig, |
| 347 |
"height" : height, |
| 348 |
"height_original": height_orig, |
| 349 |
} |
| 350 |
|
| 351 |
if manifest is not None: |
| 352 |
media["_ytdl_manifest_data"] = manifest |
| 353 |
if "owner" in item: |
| 354 |
media["owner"] = item["owner"] |
| 355 |
if "reshared_story_media_author" in item: |
| 356 |
media["author"] = item["reshared_story_media_author"] |
| 357 |
if "expiring_at" in item: |
| 358 |
media["expires"] = self.parse_timestamp(item["expiring_at"]) |
| 359 |
if "subscription_media_visibility" in item: |
| 360 |
media["subscription"] = item["subscription_media_visibility"] |
| 361 |
if "audience" in item: |
| 362 |
media["audience"] = item["audience"] |
| 363 |
|
| 364 |
self._extract_tagged_users(item, media) |
| 365 |
files.append(media) |
| 366 |
|
| 367 |
if stickers := item.get("story_music_stickers"): |
| 368 |
try: |
| 369 |
if audio := self._extract_audio(item, media, stickers[0]): |
| 370 |
audio["num"] = num |
| 371 |
files.append(audio) |
| 372 |
except Exception as exc: |
| 373 |
self.log.traceback(exc) |
| 374 |
|
| 375 |
if metadata := post.get("music_metadata"): |
| 376 |
try: |
| 377 |
if audio := self._extract_audio( |
| 378 |
post, data, metadata.get("music_info")): |
| 379 |
num += 1 |
| 380 |
audio["num"] = num |
| 381 |
files.append(audio) |
| 382 |
except Exception as exc: |
| 383 |
self.log.traceback(exc) |
| 384 |
|
| 385 |
if clips := post.get("clips_metadata"): |
| 386 |
try: |
| 387 |
if audio := self._extract_audio(post, data, clips): |
| 388 |
num += 1 |
| 389 |
audio["num"] = num |
| 390 |
files.append(audio) |
| 391 |
except Exception as exc: |
| 392 |
self.log.traceback(exc) |
| 393 |
|
| 394 |
if "subscription_media_visibility" in post: |
| 395 |
data["subscription"] = post["subscription_media_visibility"] |
| 396 |
if "type" not in data: |
| 397 |
if len(files) == 1 and files[0]["video_url"]: |
| 398 |
data["type"] = "reel" |
| 399 |
data["post_url"] = f"{self.root}/reel/{post['code']}/" |
| 400 |
else: |
| 401 |
data["type"] = "post" |
| 402 |
data["post_url"] = f"{self.root}/p/{post['code']}/" |
| 403 |
|
| 404 |
return data |
| 405 |
|
| 406 |
def _parse_post_graphql(self, post): |
| 407 |
typename = post["__typename"] |
| 408 |
|
| 409 |
if self._logged_in: |
| 410 |
if post.get("is_video") and "video_url" not in post: |
| 411 |
post = self.api.media(post["id"])[0] |
| 412 |
elif typename == "GraphSidecar" and \ |
| 413 |
"edge_sidecar_to_children" not in post: |
| 414 |
post = self.api.media(post["id"])[0] |
| 415 |
|
| 416 |
if pinned := post.get("pinned_for_users", ()): |
| 417 |
for index, user in enumerate(pinned): |
| 418 |
pinned[index] = int(user["id"]) |
| 419 |
|
| 420 |
owner = post["owner"] |
| 421 |
data = { |
| 422 |
"typename" : typename, |
| 423 |
"likes" : post["edge_media_preview_like"]["count"], |
| 424 |
"liked" : post.get("viewer_has_liked", False), |
| 425 |
"pinned" : pinned, |
| 426 |
"owner_id" : owner["id"], |
| 427 |
"username" : owner.get("username"), |
| 428 |
"fullname" : owner.get("full_name"), |
| 429 |
"post_id" : post["id"], |
| 430 |
"post_shortcode": post["shortcode"], |
| 431 |
"post_url" : f"{self.root}/p/{post['shortcode']}/", |
| 432 |
"post_date" : self.parse_timestamp(post["taken_at_timestamp"]), |
| 433 |
"description": text.parse_unicode_escapes("\n".join( |
| 434 |
edge["node"]["text"] |
| 435 |
for edge in post["edge_media_to_caption"]["edges"] |
| 436 |
)), |
| 437 |
} |
| 438 |
data["date"] = data["post_date"] |
| 439 |
|
| 440 |
if tags := self._find_tags(data["description"]): |
| 441 |
data["tags"] = sorted(set(tags)) |
| 442 |
|
| 443 |
if location := post.get("location"): |
| 444 |
data["location_id"] = location["id"] |
| 445 |
data["location_slug"] = location["slug"] |
| 446 |
data["location_url"] = (f"{self.root}/explore/locations/" |
| 447 |
f"{location['id']}/{location['slug']}/") |
| 448 |
|
| 449 |
if coauthors := post.get("coauthor_producers"): |
| 450 |
data["coauthors"] = [ |
| 451 |
{"id" : user["id"], |
| 452 |
"username": user["username"]} |
| 453 |
for user in coauthors |
| 454 |
] |
| 455 |
|
| 456 |
data["_files"] = files = [] |
| 457 |
if "edge_sidecar_to_children" in post: |
| 458 |
for num, edge in enumerate( |
| 459 |
post["edge_sidecar_to_children"]["edges"], 1): |
| 460 |
node = edge["node"] |
| 461 |
dimensions = node["dimensions"] |
| 462 |
media = { |
| 463 |
"num": num, |
| 464 |
"media_id" : node["id"], |
| 465 |
"date" : data["date"], |
| 466 |
"shortcode" : (node.get("shortcode") or |
| 467 |
shortcode_from_id(node["id"])), |
| 468 |
"display_url": node["display_url"], |
| 469 |
"video_url" : node.get("video_url"), |
| 470 |
"width" : dimensions["width"], |
| 471 |
"height" : dimensions["height"], |
| 472 |
"sidecar_media_id" : post["id"], |
| 473 |
"sidecar_shortcode": post["shortcode"], |
| 474 |
} |
| 475 |
self._extract_tagged_users(node, media) |
| 476 |
files.append(media) |
| 477 |
else: |
| 478 |
dimensions = post["dimensions"] |
| 479 |
media = { |
| 480 |
"media_id" : post["id"], |
| 481 |
"date" : data["date"], |
| 482 |
"shortcode" : post["shortcode"], |
| 483 |
"display_url": post["display_url"], |
| 484 |
"video_url" : post.get("video_url"), |
| 485 |
"width" : dimensions["width"], |
| 486 |
"height" : dimensions["height"], |
| 487 |
} |
| 488 |
self._extract_tagged_users(post, media) |
| 489 |
files.append(media) |
| 490 |
|
| 491 |
return data |
| 492 |
|
| 493 |
def _extract_tagged_users(self, src, dest): |
| 494 |
dest["tagged_users"] = tagged_users = [] |
| 495 |
|
| 496 |
if edges := src.get("edge_media_to_tagged_user"): |
| 497 |
for edge in edges["edges"]: |
| 498 |
user = edge["node"]["user"] |
| 499 |
tagged_users.append({"id" : user["id"], |
| 500 |
"username" : user["username"], |
| 501 |
"full_name": user["full_name"]}) |
| 502 |
|
| 503 |
if usertags := src.get("usertags"): |
| 504 |
for tag in usertags["in"]: |
| 505 |
user = tag["user"] |
| 506 |
tagged_users.append({"id" : user["pk"], |
| 507 |
"username" : user["username"], |
| 508 |
"full_name": user["full_name"]}) |
| 509 |
|
| 510 |
if mentions := src.get("reel_mentions"): |
| 511 |
for mention in mentions: |
| 512 |
user = mention["user"] |
| 513 |
tagged_users.append({"id" : user.get("pk"), |
| 514 |
"username" : user["username"], |
| 515 |
"full_name": user["full_name"]}) |
| 516 |
|
| 517 |
if stickers := src.get("story_bloks_stickers"): |
| 518 |
for sticker in stickers: |
| 519 |
sticker = sticker["bloks_sticker"] |
| 520 |
if sticker["bloks_sticker_type"] == "mention": |
| 521 |
user = sticker["sticker_data"]["ig_mention"] |
| 522 |
tagged_users.append({"id" : user["account_id"], |
| 523 |
"username" : user["username"], |
| 524 |
"full_name": user["full_name"]}) |
| 525 |
|
| 526 |
def _is_reel(self, post): |
| 527 |
product_type = post.get("product_type") or post.get( |
| 528 |
"media_product_type") |
| 529 |
return ( |
| 530 |
product_type == "clips" or |
| 531 |
post.get("subtype_name_for_REST__") == "XDTClipsMedia" or |
| 532 |
"clips_metadata" in post |
| 533 |
) |
| 534 |
|
| 535 |
def _extract_pinned(self, post): |
| 536 |
return (post.get("timeline_pinned_user_ids") or |
| 537 |
post.get("clips_tab_pinned_user_ids") or ()) |
| 538 |
|
| 539 |
def _extract_audio(self, src, dest, info): |
| 540 |
if not info or not (audio := info.get("music_asset_info") or |
| 541 |
info.get("original_sound_info")): |
| 542 |
return None |
| 543 |
cinfo = info.get("music_consumption_info") or audio |
| 544 |
|
| 545 |
dest["audio_title"] = title = audio.get("title") or audio.get( |
| 546 |
"original_audio_title") |
| 547 |
dest["audio_duration"] = duration = audio.get( |
| 548 |
"duration_in_ms", 0) / 1000 |
| 549 |
dest["audio_user"] = user = audio.get( |
| 550 |
"ig_artist") or cinfo.get("ig_artist") |
| 551 |
|
| 552 |
if parts := audio.get("audio_parts"): |
| 553 |
artist = [a for p in parts if (a := p.get("display_artist"))] |
| 554 |
timestamps = [p.get("parent_start_time_in_ms") for p in parts] |
| 555 |
else: |
| 556 |
artist = audio.get("display_artist") or cinfo.get("display_artist") |
| 557 |
timestamps = audio.get("highlight_start_times_in_ms") |
| 558 |
dest["audio_artist"] = artist |
| 559 |
dest["audio_timestamps"] = timestamps |
| 560 |
|
| 561 |
if not (url := audio["progressive_download_url"]): |
| 562 |
return None |
| 563 |
audio_id = audio.get("id") or audio.get("audio_asset_id") or 0 |
| 564 |
|
| 565 |
file = { |
| 566 |
"date" : self.parse_timestamp(src.get("taken_at")), |
| 567 |
"media_id" : audio_id, |
| 568 |
"shortcode" : shortcode_from_id(audio_id), |
| 569 |
"display_url": audio.get("cover_artwork_uri"), |
| 570 |
"audio_url" : url, |
| 571 |
"width" : 0, |
| 572 |
"width_original" : 0, |
| 573 |
"height" : 0, |
| 574 |
"height_original" : 0, |
| 575 |
"audio_user" : user, |
| 576 |
"audio_title" : title, |
| 577 |
"audio_artist" : artist, |
| 578 |
"audio_duration" : duration, |
| 579 |
"audio_timestamps": timestamps, |
| 580 |
} |
| 581 |
|
| 582 |
if manifest := audio.get("dash_manifest"): |
| 583 |
file["_ytdl_manifest_data"] = manifest |
| 584 |
return file |
| 585 |
|
| 586 |
def _init_cursor(self): |
| 587 |
cursor = self.config("cursor", True) |
| 588 |
if cursor is True: |
| 589 |
return None |
| 590 |
elif not cursor: |
| 591 |
self._update_cursor = util.identity |
| 592 |
return cursor |
| 593 |
|
| 594 |
def _update_cursor(self, cursor): |
| 595 |
if cursor: |
| 596 |
self.log.debug("Cursor: %s", cursor) |
| 597 |
self._cursor = cursor |
| 598 |
return cursor |
| 599 |
|
| 600 |
def _assign_user(self, user): |
| 601 |
self._user = user |
| 602 |
|
| 603 |
for key, old in ( |
| 604 |
("count_media" , "edge_owner_to_timeline_media"), |
| 605 |
("count_video" , "edge_felix_video_timeline"), |
| 606 |
("count_saved" , "edge_saved_media"), |
| 607 |
("count_mutual" , "edge_mutual_followed_by"), |
| 608 |
("count_follow" , "edge_follow"), |
| 609 |
("count_followed" , "edge_followed_by"), |
| 610 |
("count_collection", "edge_media_collections")): |
| 611 |
try: |
| 612 |
user[key] = user.pop(old)["count"] |
| 613 |
except Exception: |
| 614 |
user[key] = 0 |
| 615 |
|
| 616 |
|
| 617 |
class InstagramPostExtractor(InstagramExtractor): |
| 618 |
"""Extractor for an Instagram post""" |
| 619 |
subcategory = "post" |
| 620 |
pattern = (r"(?:https?://)?(?:www\.)?instagram\.com" |
| 621 |
r"/(?:share()(?:/(?:p|tv|reels?()))?" |
| 622 |
r"|(?:[^/?#]+/)?(?:p|tv|reels?()))" |
| 623 |
r"/([^/?#]+)") |
| 624 |
example = "https://www.instagram.com/p/abcdefg/" |
| 625 |
|
| 626 |
def __init__(self, match): |
| 627 |
if match[2] is not None or match[3] is not None: |
| 628 |
self.subcategory = "reel" |
| 629 |
InstagramExtractor.__init__(self, match) |
| 630 |
|
| 631 |
def posts(self): |
| 632 |
share, _, _, shortcode = self.groups |
| 633 |
if share is not None: |
| 634 |
url = text.ensure_http_scheme(self.url) |
| 635 |
headers = { |
| 636 |
"Sec-Fetch-Dest": "empty", |
| 637 |
"Sec-Fetch-Mode": "navigate", |
| 638 |
"Sec-Fetch-Site": "same-origin", |
| 639 |
} |
| 640 |
location = self.request_location(url, headers=headers) |
| 641 |
shortcode = location.split("/")[-2] |
| 642 |
return self.api.media(shortcode) |
| 643 |
|
| 644 |
|
| 645 |
class InstagramUserExtractor(Dispatch, InstagramExtractor): |
| 646 |
"""Extractor for an Instagram user profile""" |
| 647 |
pattern = USER_PATTERN + r"/?(?:$|[?#])" |
| 648 |
example = "https://www.instagram.com/USER/" |
| 649 |
|
| 650 |
def items(self): |
| 651 |
base = f"{self.root}/{self.item}/" |
| 652 |
stories = f"{self.root}/stories/{self.item}/" |
| 653 |
return self._dispatch_extractors(( |
| 654 |
(InstagramInfoExtractor , base + "info/"), |
| 655 |
(InstagramAvatarExtractor , base + "avatar/"), |
| 656 |
(InstagramStoriesExtractor , stories), |
| 657 |
(InstagramHighlightsExtractor, base + "highlights/"), |
| 658 |
(InstagramPostsExtractor , base + "posts/"), |
| 659 |
(InstagramPhotosExtractor , base + "photos/"), |
| 660 |
(InstagramReelsExtractor , base + "reels/"), |
| 661 |
(InstagramTaggedExtractor , base + "tagged/"), |
| 662 |
), ("posts",)) |
| 663 |
|
| 664 |
|
| 665 |
class InstagramPostsExtractor(InstagramExtractor): |
| 666 |
"""Extractor for an Instagram user's posts""" |
| 667 |
subcategory = "posts" |
| 668 |
pattern = USER_PATTERN + r"/posts" |
| 669 |
example = "https://www.instagram.com/USER/posts/" |
| 670 |
|
| 671 |
def posts(self): |
| 672 |
uid = self.api.user_id(self.item) |
| 673 |
return self.api.user_feed(uid) |
| 674 |
|
| 675 |
def _extract_pinned(self, post): |
| 676 |
try: |
| 677 |
return post["timeline_pinned_user_ids"] |
| 678 |
except KeyError: |
| 679 |
return () |
| 680 |
|
| 681 |
|
| 682 |
class InstagramPhotosExtractor(InstagramExtractor): |
| 683 |
"""Extractor for an Instagram user's photos""" |
| 684 |
subcategory = "photos" |
| 685 |
pattern = USER_PATTERN + r"/photos" |
| 686 |
example = "https://www.instagram.com/USER/photos/" |
| 687 |
|
| 688 |
def posts(self): |
| 689 |
uid = self.api.user_id(self.item) |
| 690 |
for post in self.api.user_feed(uid): |
| 691 |
if not self._is_reel(post): |
| 692 |
yield post |
| 693 |
|
| 694 |
|
| 695 |
class InstagramReelsExtractor(InstagramExtractor): |
| 696 |
"""Extractor for an Instagram user's reels""" |
| 697 |
subcategory = "reels" |
| 698 |
pattern = USER_PATTERN + r"/reels" |
| 699 |
example = "https://www.instagram.com/USER/reels/" |
| 700 |
|
| 701 |
def posts(self): |
| 702 |
uid = self.api.user_id(self.item) |
| 703 |
return self.api.user_clips(uid) |
| 704 |
|
| 705 |
def _extract_pinned(self, post): |
| 706 |
try: |
| 707 |
return post["clips_tab_pinned_user_ids"] |
| 708 |
except KeyError: |
| 709 |
return () |
| 710 |
|
| 711 |
|
| 712 |
class InstagramTaggedExtractor(InstagramExtractor): |
| 713 |
"""Extractor for an Instagram user's tagged posts""" |
| 714 |
subcategory = "tagged" |
| 715 |
pattern = USER_PATTERN + r"/tagged" |
| 716 |
example = "https://www.instagram.com/USER/tagged/" |
| 717 |
|
| 718 |
def metadata(self): |
| 719 |
if self.item.startswith("id:"): |
| 720 |
self.user_id = self.item[3:] |
| 721 |
if not self.config("metadata"): |
| 722 |
return {"tagged_owner_id": self.user_id} |
| 723 |
user = self.api.user_by_id(self.user_id) |
| 724 |
else: |
| 725 |
self.user_id = self.api.user_id(self.item) |
| 726 |
user = self.api.user_by_screen_name(self.item) |
| 727 |
|
| 728 |
return { |
| 729 |
"tagged_owner_id" : user["id"], |
| 730 |
"tagged_username" : user["username"], |
| 731 |
"tagged_full_name": user["full_name"], |
| 732 |
} |
| 733 |
|
| 734 |
def posts(self): |
| 735 |
return self.api.user_tagged(self.user_id) |
| 736 |
|
| 737 |
|
| 738 |
class InstagramGuideExtractor(InstagramExtractor): |
| 739 |
"""Extractor for an Instagram guide""" |
| 740 |
subcategory = "guide" |
| 741 |
pattern = USER_PATTERN + r"/guide/[^/?#]+/(\d+)" |
| 742 |
example = "https://www.instagram.com/USER/guide/NAME/12345" |
| 743 |
|
| 744 |
def __init__(self, match): |
| 745 |
InstagramExtractor.__init__(self, match) |
| 746 |
self.guide_id = match[2] |
| 747 |
|
| 748 |
def metadata(self): |
| 749 |
return {"guide": self.api.guide(self.guide_id)} |
| 750 |
|
| 751 |
def posts(self): |
| 752 |
return self.api.guide_media(self.guide_id) |
| 753 |
|
| 754 |
|
| 755 |
class InstagramSavedExtractor(InstagramExtractor): |
| 756 |
"""Extractor for an Instagram user's saved media""" |
| 757 |
subcategory = "saved" |
| 758 |
pattern = USER_PATTERN + r"/saved(?:/all-posts)?/?$" |
| 759 |
example = "https://www.instagram.com/USER/saved/" |
| 760 |
|
| 761 |
def posts(self): |
| 762 |
return self.api.user_saved() |
| 763 |
|
| 764 |
|
| 765 |
class InstagramCollectionExtractor(InstagramExtractor): |
| 766 |
"""Extractor for Instagram collection""" |
| 767 |
subcategory = "collection" |
| 768 |
pattern = USER_PATTERN + r"/saved/([^/?#]+)/([^/?#]+)" |
| 769 |
example = "https://www.instagram.com/USER/saved/COLLECTION/12345" |
| 770 |
|
| 771 |
def __init__(self, match): |
| 772 |
InstagramExtractor.__init__(self, match) |
| 773 |
self.user, self.collection_name, self.collection_id = match.groups() |
| 774 |
|
| 775 |
def metadata(self): |
| 776 |
return { |
| 777 |
"collection_id" : self.collection_id, |
| 778 |
"collection_name": text.unescape(self.collection_name), |
| 779 |
} |
| 780 |
|
| 781 |
def posts(self): |
| 782 |
return self.api.user_collection(self.collection_id) |
| 783 |
|
| 784 |
|
| 785 |
class InstagramStoriesTrayExtractor(InstagramExtractor): |
| 786 |
"""Extractor for your Instagram account's stories tray""" |
| 787 |
subcategory = "stories-tray" |
| 788 |
pattern = BASE_PATTERN + r"/stories/me/?$()" |
| 789 |
example = "https://www.instagram.com/stories/me/" |
| 790 |
|
| 791 |
def items(self): |
| 792 |
base = self.root + "/stories/id:" |
| 793 |
for story in self.api.reels_tray(): |
| 794 |
story["date"] = self.parse_timestamp(story["latest_reel_media"]) |
| 795 |
story["_extractor"] = InstagramStoriesExtractor |
| 796 |
yield Message.Queue, f"{base}{story['id']}/", story |
| 797 |
|
| 798 |
|
| 799 |
class InstagramStoriesExtractor(InstagramExtractor): |
| 800 |
"""Extractor for Instagram stories""" |
| 801 |
subcategory = "stories" |
| 802 |
pattern = (r"(?:https?://)?(?:www\.)?instagram\.com" |
| 803 |
r"/s(?:tories/(?:highlights/(\d+)|([^/?#]+)(?:/(\d+))?)" |
| 804 |
r"|/(aGlnaGxpZ2h0[^?#]+)(?:\?story_media_id=(\d+))?)") |
| 805 |
example = "https://www.instagram.com/stories/USER/" |
| 806 |
|
| 807 |
def __init__(self, match): |
| 808 |
h1, self.user, m1, h2, m2 = match.groups() |
| 809 |
|
| 810 |
if self.user: |
| 811 |
self.highlight_id = None |
| 812 |
else: |
| 813 |
self.subcategory = InstagramHighlightsExtractor.subcategory |
| 814 |
self.highlight_id = "highlight:" + h1 if h1 else util.b64decode(h2) |
| 815 |
|
| 816 |
self.media_id = m1 or m2 |
| 817 |
InstagramExtractor.__init__(self, match) |
| 818 |
|
| 819 |
def posts(self): |
| 820 |
reel_id = self.highlight_id or self.api.user_id(self.user) |
| 821 |
reels = self.api.reels_media(reel_id) |
| 822 |
|
| 823 |
if not reels: |
| 824 |
return () |
| 825 |
|
| 826 |
if self.media_id: |
| 827 |
reel = reels[0] |
| 828 |
for item in reel["items"]: |
| 829 |
if item["pk"] == self.media_id: |
| 830 |
reel["items"] = (item,) |
| 831 |
break |
| 832 |
else: |
| 833 |
raise self.exc.NotFoundError("story") |
| 834 |
|
| 835 |
elif self.config("split"): |
| 836 |
reel = reels[0] |
| 837 |
reels = [] |
| 838 |
for item in reel["items"]: |
| 839 |
item.pop("user", None) |
| 840 |
copy = reel.copy() |
| 841 |
copy.update(item) |
| 842 |
copy["items"] = (item,) |
| 843 |
reels.append(copy) |
| 844 |
|
| 845 |
return reels |
| 846 |
|
| 847 |
|
| 848 |
class InstagramHighlightsExtractor(InstagramExtractor): |
| 849 |
"""Extractor for an Instagram user's story highlights""" |
| 850 |
subcategory = "highlights" |
| 851 |
pattern = USER_PATTERN + r"/highlights" |
| 852 |
example = "https://www.instagram.com/USER/highlights/" |
| 853 |
|
| 854 |
def posts(self): |
| 855 |
uid = self.api.user_id(self.item) |
| 856 |
return self.api.highlights_media(uid) |
| 857 |
|
| 858 |
|
| 859 |
class InstagramFollowersExtractor(InstagramExtractor): |
| 860 |
"""Extractor for an Instagram user's followers""" |
| 861 |
subcategory = "followers" |
| 862 |
pattern = USER_PATTERN + r"/followers" |
| 863 |
example = "https://www.instagram.com/USER/followers/" |
| 864 |
|
| 865 |
def items(self): |
| 866 |
uid = self.api.user_id(self.item) |
| 867 |
for user in self.api.user_followers(uid): |
| 868 |
user["_extractor"] = InstagramUserExtractor |
| 869 |
url = f"{self.root}/{user['username']}" |
| 870 |
yield Message.Queue, url, user |
| 871 |
|
| 872 |
|
| 873 |
class InstagramFollowingExtractor(InstagramExtractor): |
| 874 |
"""Extractor for an Instagram user's followed users""" |
| 875 |
subcategory = "following" |
| 876 |
pattern = USER_PATTERN + r"/following" |
| 877 |
example = "https://www.instagram.com/USER/following/" |
| 878 |
|
| 879 |
def items(self): |
| 880 |
uid = self.api.user_id(self.item) |
| 881 |
for user in self.api.user_following(uid): |
| 882 |
user["_extractor"] = InstagramUserExtractor |
| 883 |
url = f"{self.root}/{user['username']}" |
| 884 |
yield Message.Queue, url, user |
| 885 |
|
| 886 |
|
| 887 |
class InstagramTagExtractor(InstagramExtractor): |
| 888 |
"""Extractor for Instagram tags""" |
| 889 |
subcategory = "tag" |
| 890 |
directory_fmt = ("{category}", "{subcategory}", "{tag}") |
| 891 |
pattern = BASE_PATTERN + r"/explore/tags/([^/?#]+)" |
| 892 |
example = "https://www.instagram.com/explore/tags/TAG/" |
| 893 |
|
| 894 |
def metadata(self): |
| 895 |
return {"tag": text.unquote(self.item)} |
| 896 |
|
| 897 |
def posts(self): |
| 898 |
return self.api.tags_media(self.item) |
| 899 |
|
| 900 |
|
| 901 |
class InstagramInfoExtractor(InstagramExtractor): |
| 902 |
"""Extractor for an Instagram user's profile data""" |
| 903 |
subcategory = "info" |
| 904 |
pattern = USER_PATTERN + r"/info" |
| 905 |
example = "https://www.instagram.com/USER/info/" |
| 906 |
|
| 907 |
def items(self): |
| 908 |
screen_name = self.item |
| 909 |
if screen_name.startswith("id:"): |
| 910 |
user = self.api.user_by_id(screen_name[3:]) |
| 911 |
else: |
| 912 |
user = self.api.user_by_screen_name(screen_name) |
| 913 |
|
| 914 |
return iter(((Message.Directory, "", user.copy()),)) |
| 915 |
|
| 916 |
|
| 917 |
class InstagramAvatarExtractor(InstagramExtractor): |
| 918 |
"""Extractor for an Instagram user's avatar""" |
| 919 |
subcategory = "avatar" |
| 920 |
pattern = USER_PATTERN + r"/avatar" |
| 921 |
example = "https://www.instagram.com/USER/avatar/" |
| 922 |
|
| 923 |
def posts(self): |
| 924 |
if self._logged_in: |
| 925 |
user_id = self.api.user_id(self.item, check_private=False) |
| 926 |
user = self.api.user_by_id(user_id) |
| 927 |
avatar = (user.get("hd_profile_pic_url_info") or |
| 928 |
user["hd_profile_pic_versions"][-1]) |
| 929 |
else: |
| 930 |
user = self.item |
| 931 |
if user.startswith("id:"): |
| 932 |
user = self.api.user_by_id(user[3:]) |
| 933 |
else: |
| 934 |
user = self.api.user_by_screen_name(user) |
| 935 |
user["pk"] = user["id"] |
| 936 |
url = user.get("profile_pic_url_hd") or user["profile_pic_url"] |
| 937 |
avatar = {"url": url, "width": 0, "height": 0} |
| 938 |
|
| 939 |
if pk := user.get("profile_pic_id"): |
| 940 |
pk = pk.partition("_")[0] |
| 941 |
code = shortcode_from_id(pk) |
| 942 |
else: |
| 943 |
pk = code = "avatar:" + str(user["pk"]) |
| 944 |
|
| 945 |
return ({ |
| 946 |
"pk" : pk, |
| 947 |
"code" : code, |
| 948 |
"user" : user, |
| 949 |
"caption" : None, |
| 950 |
"like_count": 0, |
| 951 |
"image_versions2": {"candidates": (avatar,)}, |
| 952 |
},) |
| 953 |
|
| 954 |
|
| 955 |
class InstagramRestAPI(): |
| 956 |
|
| 957 |
def __init__(self, extractor): |
| 958 |
self.extractor = extractor |
| 959 |
self.exc = extractor.exc |
| 960 |
|
| 961 |
_cache = self.extractor.config("user-cache", True) |
| 962 |
self._user_cache = True if not _cache or _cache == "memory" else False |
| 963 |
|
| 964 |
if strategy := self.extractor.config("user-strategy"): |
| 965 |
if isinstance(strategy, str): |
| 966 |
strategy = strategy.split(",") |
| 967 |
self._strategy_uid = strategy |
| 968 |
else: |
| 969 |
self._strategy_uid = ("search", "web") |
| 970 |
|
| 971 |
def guide(self, guide_id): |
| 972 |
endpoint = "/v1/guides/web_info/" |
| 973 |
params = {"guide_id": guide_id} |
| 974 |
return self._call(endpoint, params=params) |
| 975 |
|
| 976 |
def guide_media(self, guide_id): |
| 977 |
endpoint = f"/v1/guides/guide/{guide_id}/" |
| 978 |
return self._pagination_guides(endpoint) |
| 979 |
|
| 980 |
def highlights_media(self, user_id, chunk_size=5): |
| 981 |
reel_ids = [hl["id"] for hl in self.highlights_tray(user_id)] |
| 982 |
|
| 983 |
if order := self.extractor.config("order-posts"): |
| 984 |
if order in {"desc", "reverse"}: |
| 985 |
reel_ids.reverse() |
| 986 |
elif order in {"id", "id_asc"}: |
| 987 |
reel_ids.sort(key=lambda r: int(r[10:])) |
| 988 |
elif order == "id_desc": |
| 989 |
reel_ids.sort(key=lambda r: int(r[10:]), reverse=True) |
| 990 |
elif order != "asc": |
| 991 |
self.extractor.log.warning("Unknown posts order '%s'", order) |
| 992 |
|
| 993 |
for offset in range(0, len(reel_ids), chunk_size): |
| 994 |
yield from self.reels_media( |
| 995 |
reel_ids[offset : offset+chunk_size]) |
| 996 |
|
| 997 |
def highlights_tray(self, user_id): |
| 998 |
endpoint = f"/v1/highlights/{user_id}/highlights_tray/" |
| 999 |
return self._call(endpoint)["tray"] |
| 1000 |
|
| 1001 |
def media(self, shortcode): |
| 1002 |
if len(shortcode) > 28: |
| 1003 |
shortcode = shortcode[:-28] |
| 1004 |
endpoint = f"/v1/media/{id_from_shortcode(shortcode)}/info/" |
| 1005 |
return self._pagination(endpoint) |
| 1006 |
|
| 1007 |
def reels_media(self, reel_ids): |
| 1008 |
endpoint = "/v1/feed/reels_media/" |
| 1009 |
params = {"reel_ids": reel_ids} |
| 1010 |
try: |
| 1011 |
return self._call(endpoint, params=params)["reels_media"] |
| 1012 |
except KeyError: |
| 1013 |
raise self.exc.AuthRequired("authenticated cookies") |
| 1014 |
|
| 1015 |
def reels_tray(self): |
| 1016 |
endpoint = "/v1/feed/reels_tray/" |
| 1017 |
return self._call(endpoint)["tray"] |
| 1018 |
|
| 1019 |
def tags_media(self, tag): |
| 1020 |
for section in self.tags_sections(tag): |
| 1021 |
for media in section["layout_content"]["medias"]: |
| 1022 |
yield media["media"] |
| 1023 |
|
| 1024 |
def tags_sections(self, tag): |
| 1025 |
endpoint = f"/v1/tags/{tag}/sections/" |
| 1026 |
data = { |
| 1027 |
"include_persistent": "0", |
| 1028 |
"max_id" : None, |
| 1029 |
"page" : None, |
| 1030 |
"surface": "grid", |
| 1031 |
"tab" : "recent", |
| 1032 |
} |
| 1033 |
return self._pagination_sections(endpoint, data) |
| 1034 |
|
| 1035 |
def user_by_id(self, user_id): |
| 1036 |
return self.extractor.cache( |
| 1037 |
self._user_by_id_impl, user_id, _mem=self._user_cache) |
| 1038 |
|
| 1039 |
def _user_by_id_impl(self, user_id): |
| 1040 |
endpoint = f"/v1/users/{user_id}/info/" |
| 1041 |
try: |
| 1042 |
return self._call(endpoint, notfound="user")["user"] |
| 1043 |
except Exception: |
| 1044 |
raise self.exc.NotFoundError("user") |
| 1045 |
|
| 1046 |
def user_by_name(self, username): |
| 1047 |
return self.extractor.cache( |
| 1048 |
self._user_by_name_impl, username, _mem=self._user_cache) |
| 1049 |
|
| 1050 |
def _user_by_name_impl(self, username): |
| 1051 |
endpoint = "/v1/users/web_profile_info/" |
| 1052 |
params = {"username": username} |
| 1053 |
try: |
| 1054 |
return self._call( |
| 1055 |
endpoint, params=params, notfound="user")["data"]["user"] |
| 1056 |
except Exception: |
| 1057 |
raise self.exc.NotFoundError("user") |
| 1058 |
|
| 1059 |
def user_by_search(self, username): |
| 1060 |
return self.extractor.cache( |
| 1061 |
self._user_by_search_impl, username, _mem=self._user_cache) |
| 1062 |
|
| 1063 |
def _user_by_search_impl(self, username): |
| 1064 |
url = "https://www.instagram.com/web/search/topsearch/" |
| 1065 |
params = {"query": username} |
| 1066 |
|
| 1067 |
name = username.lower() |
| 1068 |
try: |
| 1069 |
for result in self._call(url, params=params)["users"]: |
| 1070 |
user = result["user"] |
| 1071 |
if user["username"].lower() == name: |
| 1072 |
return user |
| 1073 |
except Exception: |
| 1074 |
pass |
| 1075 |
raise self.exc.NotFoundError("user") |
| 1076 |
|
| 1077 |
def user_by_web(self, username): |
| 1078 |
return self.extractor.cache( |
| 1079 |
self._user_by_web_impl, username, _mem=self._user_cache) |
| 1080 |
|
| 1081 |
def _user_by_web_impl(self, username): |
| 1082 |
url = "https://www.instagram.com/" + username |
| 1083 |
|
| 1084 |
try: |
| 1085 |
headers = { |
| 1086 |
"Accept": "text/html,application/xhtml+xml," |
| 1087 |
"application/xml;q=0.9,*/*;q=0.8", |
| 1088 |
"Accept-Language": "en-US,en;q=0.5", |
| 1089 |
"Accept-Encoding": "gzip, deflate, br, zstd", |
| 1090 |
"Alt-Used": "www.instagram.com", |
| 1091 |
"Connection": "keep-alive", |
| 1092 |
"Sec-Fetch-Dest": "document", |
| 1093 |
"Sec-Fetch-Mode": "navigate", |
| 1094 |
"Sec-Fetch-Site": "none", |
| 1095 |
"Priority": "u=0, i", |
| 1096 |
} |
| 1097 |
page = self.extractor.request(url, headers=headers).text |
| 1098 |
if uid := text.extr(page, '"profile_id":"', '"'): |
| 1099 |
return {"id": uid} |
| 1100 |
except Exception: |
| 1101 |
pass |
| 1102 |
raise self.exc.NotFoundError("user") |
| 1103 |
|
| 1104 |
def user_by_screen_name(self, screen_name): |
| 1105 |
for strategy in self._strategy_uid: |
| 1106 |
try: |
| 1107 |
if strategy in {"search", "topsearch"}: |
| 1108 |
return self.user_by_search(screen_name) |
| 1109 |
elif strategy in {"info", "web_profile_info", "api"}: |
| 1110 |
return self.user_by_name(screen_name) |
| 1111 |
elif strategy in {"web", "webpage"}: |
| 1112 |
return self.user_by_web(screen_name) |
| 1113 |
else: |
| 1114 |
self.extractor.log.warning("Invalid strategy %r", strategy) |
| 1115 |
except Exception: |
| 1116 |
self.extractor.log.debug("Failed to get user via %r", strategy) |
| 1117 |
raise self.exc.NotFoundError("user") |
| 1118 |
|
| 1119 |
def user_id(self, screen_name, check_private=True): |
| 1120 |
if screen_name.startswith("id:"): |
| 1121 |
if self.extractor.config("metadata"): |
| 1122 |
self.extractor._user = self.user_by_id(screen_name[3:]) |
| 1123 |
return screen_name[3:] |
| 1124 |
|
| 1125 |
user = self.user_by_screen_name(screen_name) |
| 1126 |
if check_private and user.get("is_private") and ( |
| 1127 |
not user.get("followed_by_viewer", True) or |
| 1128 |
not user.get("friendship_status", {}).get("following", True)): |
| 1129 |
name = user["username"] |
| 1130 |
s = "" if name.endswith("s") else "s" |
| 1131 |
self.extractor.log.warning("%s'%s posts are private", name, s) |
| 1132 |
|
| 1133 |
self.extractor._assign_user(user) |
| 1134 |
return user["id"] |
| 1135 |
|
| 1136 |
def user_clips(self, user_id): |
| 1137 |
endpoint = "/v1/clips/user/" |
| 1138 |
data = { |
| 1139 |
"target_user_id": user_id, |
| 1140 |
"page_size": "50", |
| 1141 |
"max_id": None, |
| 1142 |
"include_feed_video": "true", |
| 1143 |
} |
| 1144 |
return self._pagination_post(endpoint, data) |
| 1145 |
|
| 1146 |
def user_collection(self, collection_id): |
| 1147 |
endpoint = f"/v1/feed/collection/{collection_id}/posts/" |
| 1148 |
params = {"count": 50} |
| 1149 |
return self._pagination(endpoint, params, media=True) |
| 1150 |
|
| 1151 |
def user_feed(self, user_id): |
| 1152 |
endpoint = f"/v1/feed/user/{user_id}/" |
| 1153 |
params = {"count": 30} |
| 1154 |
return self._pagination(endpoint, params) |
| 1155 |
|
| 1156 |
def user_followers(self, user_id): |
| 1157 |
endpoint = f"/v1/friendships/{user_id}/followers/" |
| 1158 |
params = {"count": 12} |
| 1159 |
return self._pagination_following(endpoint, params) |
| 1160 |
|
| 1161 |
def user_following(self, user_id): |
| 1162 |
endpoint = f"/v1/friendships/{user_id}/following/" |
| 1163 |
params = {"count": 12} |
| 1164 |
return self._pagination_following(endpoint, params) |
| 1165 |
|
| 1166 |
def user_saved(self): |
| 1167 |
endpoint = "/v1/feed/saved/posts/" |
| 1168 |
params = {"count": 50} |
| 1169 |
return self._pagination(endpoint, params, media=True) |
| 1170 |
|
| 1171 |
def user_tagged(self, user_id): |
| 1172 |
endpoint = f"/v1/usertags/{user_id}/feed/" |
| 1173 |
params = {"count": 20} |
| 1174 |
return self._pagination(endpoint, params) |
| 1175 |
|
| 1176 |
def _call(self, endpoint, **kwargs): |
| 1177 |
extr = self.extractor |
| 1178 |
|
| 1179 |
if endpoint[0] == "/": |
| 1180 |
url = "https://www.instagram.com/api" + endpoint |
| 1181 |
else: |
| 1182 |
url = endpoint |
| 1183 |
kwargs["headers"] = { |
| 1184 |
"Accept" : "*/*", |
| 1185 |
"X-CSRFToken" : extr.csrf_token, |
| 1186 |
"X-IG-App-ID" : "936619743392459", |
| 1187 |
"X-ASBD-ID" : "129477", |
| 1188 |
"X-IG-WWW-Claim" : extr.www_claim, |
| 1189 |
"X-Requested-With": "XMLHttpRequest", |
| 1190 |
"Connection" : "keep-alive", |
| 1191 |
} |
| 1192 |
return extr.request_json(url, **kwargs) |
| 1193 |
|
| 1194 |
def _pagination(self, endpoint, params=None, media=False): |
| 1195 |
if params is None: |
| 1196 |
params = {} |
| 1197 |
extr = self.extractor |
| 1198 |
params["max_id"] = extr._init_cursor() |
| 1199 |
|
| 1200 |
while True: |
| 1201 |
data = self._call(endpoint, params=params) |
| 1202 |
|
| 1203 |
if media: |
| 1204 |
for item in data["items"]: |
| 1205 |
yield item["media"] |
| 1206 |
else: |
| 1207 |
yield from data["items"] |
| 1208 |
|
| 1209 |
if not data.get("more_available"): |
| 1210 |
return extr._update_cursor(None) |
| 1211 |
params["max_id"] = extr._update_cursor(data["next_max_id"]) |
| 1212 |
|
| 1213 |
def _pagination_post(self, endpoint, params): |
| 1214 |
extr = self.extractor |
| 1215 |
params["max_id"] = extr._init_cursor() |
| 1216 |
|
| 1217 |
while True: |
| 1218 |
data = self._call(endpoint, method="POST", data=params) |
| 1219 |
|
| 1220 |
for item in data["items"]: |
| 1221 |
yield item["media"] |
| 1222 |
|
| 1223 |
info = data["paging_info"] |
| 1224 |
if not info.get("more_available"): |
| 1225 |
return extr._update_cursor(None) |
| 1226 |
params["max_id"] = extr._update_cursor(info["max_id"]) |
| 1227 |
|
| 1228 |
def _pagination_sections(self, endpoint, params): |
| 1229 |
extr = self.extractor |
| 1230 |
params["max_id"] = extr._init_cursor() |
| 1231 |
|
| 1232 |
while True: |
| 1233 |
info = self._call(endpoint, method="POST", data=params) |
| 1234 |
|
| 1235 |
yield from info["sections"] |
| 1236 |
|
| 1237 |
if not info.get("more_available"): |
| 1238 |
return extr._update_cursor(None) |
| 1239 |
params["page"] = info["next_page"] |
| 1240 |
params["max_id"] = extr._update_cursor(info["next_max_id"]) |
| 1241 |
|
| 1242 |
def _pagination_guides(self, endpoint): |
| 1243 |
extr = self.extractor |
| 1244 |
params = {"max_id": extr._init_cursor()} |
| 1245 |
|
| 1246 |
while True: |
| 1247 |
data = self._call(endpoint, params=params) |
| 1248 |
|
| 1249 |
for item in data["items"]: |
| 1250 |
yield from item["media_items"] |
| 1251 |
|
| 1252 |
next_max_id = data.get("next_max_id") |
| 1253 |
if not next_max_id: |
| 1254 |
return extr._update_cursor(None) |
| 1255 |
params["max_id"] = extr._update_cursor(next_max_id) |
| 1256 |
|
| 1257 |
def _pagination_following(self, endpoint, params): |
| 1258 |
extr = self.extractor |
| 1259 |
params["max_id"] = text.parse_int(extr._init_cursor()) |
| 1260 |
|
| 1261 |
while True: |
| 1262 |
data = self._call(endpoint, params=params) |
| 1263 |
|
| 1264 |
yield from data["users"] |
| 1265 |
|
| 1266 |
next_max_id = data.get("next_max_id") |
| 1267 |
if not next_max_id: |
| 1268 |
return extr._update_cursor(None) |
| 1269 |
params["max_id"] = extr._update_cursor(next_max_id) |
| 1270 |
|
| 1271 |
|
| 1272 |
class InstagramGraphqlAPI(): |
| 1273 |
|
| 1274 |
def __init__(self, extractor): |
| 1275 |
self.extractor = extractor |
| 1276 |
self.user_collection = self.user_saved = self.reels_media = \ |
| 1277 |
self.highlights_media = self.guide = self.guide_media = \ |
| 1278 |
self._unsupported |
| 1279 |
self._json_dumps = util.json_dumps |
| 1280 |
|
| 1281 |
api = InstagramRestAPI(extractor) |
| 1282 |
self.user_by_screen_name = api.user_by_screen_name |
| 1283 |
self.user_by_id = api.user_by_id |
| 1284 |
self.user_id = api.user_id |
| 1285 |
|
| 1286 |
def _unsupported(self, _=None): |
| 1287 |
raise self.extractor.exc.AbortExtraction( |
| 1288 |
"Unsupported with GraphQL API") |
| 1289 |
|
| 1290 |
def highlights_tray(self, user_id): |
| 1291 |
query_hash = "d4d88dc1500312af6f937f7b804c68c3" |
| 1292 |
variables = { |
| 1293 |
"user_id": user_id, |
| 1294 |
"include_chaining": False, |
| 1295 |
"include_reel": False, |
| 1296 |
"include_suggested_users": False, |
| 1297 |
"include_logged_out_extras": True, |
| 1298 |
"include_highlight_reels": True, |
| 1299 |
"include_live_status": False, |
| 1300 |
} |
| 1301 |
edges = (self._call(query_hash, variables)["user"] |
| 1302 |
["edge_highlight_reels"]["edges"]) |
| 1303 |
return [edge["node"] for edge in edges] |
| 1304 |
|
| 1305 |
def media(self, shortcode): |
| 1306 |
query_hash = "9f8827793ef34641b2fb195d4d41151c" |
| 1307 |
variables = { |
| 1308 |
"shortcode": shortcode, |
| 1309 |
"child_comment_count": 3, |
| 1310 |
"fetch_comment_count": 40, |
| 1311 |
"parent_comment_count": 24, |
| 1312 |
"has_threaded_comments": True, |
| 1313 |
} |
| 1314 |
media = self._call(query_hash, variables).get("shortcode_media") |
| 1315 |
return (media,) if media else () |
| 1316 |
|
| 1317 |
def tags_media(self, tag): |
| 1318 |
query_hash = "9b498c08113f1e09617a1703c22b2f32" |
| 1319 |
variables = {"tag_name": text.unescape(tag), "first": 24} |
| 1320 |
return self._pagination(query_hash, variables, |
| 1321 |
"hashtag", "edge_hashtag_to_media") |
| 1322 |
|
| 1323 |
def user_clips(self, user_id): |
| 1324 |
query_hash = "bc78b344a68ed16dd5d7f264681c4c76" |
| 1325 |
variables = {"id": user_id, "first": 24} |
| 1326 |
return self._pagination(query_hash, variables) |
| 1327 |
|
| 1328 |
def user_feed(self, user_id): |
| 1329 |
query_hash = "69cba40317214236af40e7efa697781d" |
| 1330 |
variables = {"id": user_id, "first": 24} |
| 1331 |
return self._pagination(query_hash, variables) |
| 1332 |
|
| 1333 |
def user_tagged(self, user_id): |
| 1334 |
query_hash = "be13233562af2d229b008d2976b998b5" |
| 1335 |
variables = {"id": user_id, "first": 24} |
| 1336 |
return self._pagination(query_hash, variables) |
| 1337 |
|
| 1338 |
def _call(self, query_hash, variables): |
| 1339 |
extr = self.extractor |
| 1340 |
|
| 1341 |
url = "https://www.instagram.com/graphql/query/" |
| 1342 |
params = { |
| 1343 |
"query_hash": query_hash, |
| 1344 |
"variables" : self._json_dumps(variables), |
| 1345 |
} |
| 1346 |
headers = { |
| 1347 |
"Accept" : "*/*", |
| 1348 |
"X-CSRFToken" : extr.csrf_token, |
| 1349 |
"X-Instagram-AJAX": "1006267176", |
| 1350 |
"X-IG-App-ID" : "936619743392459", |
| 1351 |
"X-ASBD-ID" : "198387", |
| 1352 |
"X-IG-WWW-Claim" : extr.www_claim, |
| 1353 |
"X-Requested-With": "XMLHttpRequest", |
| 1354 |
} |
| 1355 |
return extr.request_json(url, params=params, headers=headers)["data"] |
| 1356 |
|
| 1357 |
def _pagination(self, query_hash, variables, |
| 1358 |
key_data="user", key_edge=None): |
| 1359 |
extr = self.extractor |
| 1360 |
variables["after"] = extr._init_cursor() |
| 1361 |
|
| 1362 |
while True: |
| 1363 |
data = self._call(query_hash, variables)[key_data] |
| 1364 |
data = data[key_edge] if key_edge else next(iter(data.values())) |
| 1365 |
|
| 1366 |
for edge in data["edges"]: |
| 1367 |
yield edge["node"] |
| 1368 |
|
| 1369 |
info = data["page_info"] |
| 1370 |
if not info["has_next_page"]: |
| 1371 |
return extr._update_cursor(None) |
| 1372 |
elif not data["edges"]: |
| 1373 |
user = self.extractor.item |
| 1374 |
s = "" if user.endswith("s") else "s" |
| 1375 |
raise self.exc.AbortExtraction( |
| 1376 |
f"{user}'{s} posts are private") |
| 1377 |
|
| 1378 |
variables["after"] = extr._update_cursor(info["end_cursor"]) |
| 1379 |
|
| 1380 |
|
| 1381 |
def id_from_shortcode(shortcode): |
| 1382 |
return util.bdecode(shortcode, _ALPHABET) |
| 1383 |
|
| 1384 |
|
| 1385 |
def shortcode_from_id(post_id): |
| 1386 |
return util.bencode(int(post_id), _ALPHABET) |
| 1387 |
|
| 1388 |
|
| 1389 |
_ALPHABET = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ" |
| 1390 |
"abcdefghijklmnopqrstuvwxyz" |
| 1391 |
"0123456789-_") |