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