Compare commits

...
9 Commits
Author SHA1 Message Date
Alexander Graf e97fd8a27c Release of Version 4.9.3 2022-08-11 20:00:42 +02:00
fireattack 7f9d1618ad Use api/v1/feed/reels_media endpoint to get story info (#1675) 2022-08-11 19:59:02 +02:00
fireattack 6a42906697 don't try to call iPhone api when comparing profile_pic URL (#1681) 2022-08-11 19:56:52 +02:00
fireattack 4bb32e3c5a write caption in text mode (#1632) 2022-07-14 21:00:24 +02:00
Alexander Graf 5e232fd4f5 Release of Version 4.9.2 2022-07-04 20:18:22 +02:00
Eduardo Kalinowski da0dcb106c Handle pinned posts with --fast-update and --latest-stamps (#1586)
Instead of hard-coding a check for pinned items when storing the first
item, allows the creater of NodeIterator to specify how the comparison
should be made.

This also allows storing the newest post (whatever it's status is),
instead of simply storing the newst non-pinned post, which prevents
redownloads in case a user adds only a pinned post between runs.
2022-07-04 20:02:41 +02:00
Alexander Graf 8649a10113 docs: fix link to requests intersphinx inventory 2022-06-23 20:50:05 +02:00
Ziemowit Zabawa 2d37e1dca2 Make docs explicit about importing multiple argument files (#1548) 2022-06-16 10:25:43 +02:00
fireattack 37cbc5d72d Handle StoryImage in StoryItem.url (#1558) 2022-06-16 10:18:59 +02:00
6 changed files with 104 additions and 23 deletions
+2 -1
View File
@@ -329,12 +329,13 @@ Miscellaneous Options
Read arguments from file `args.txt`, a shortcut to provide arguments from Read arguments from file `args.txt`, a shortcut to provide arguments from
file rather than command-line. This provides a convenient way to hide login file rather than command-line. This provides a convenient way to hide login
info from CLI, and can also be used to simplify management of long arguments. info from CLI, and can also be used to simplify management of long arguments.
You can provide more than one file at once, e.g.: ``+args1.txt +args2.txt``.
.. note:: .. note::
Text file should separate arguments with line breaks. Text file should separate arguments with line breaks.
args.txt example:: `args.txt` example::
--login=MYUSERNAME --login=MYUSERNAME
--password=MYPASSWORD --password=MYPASSWORD
+1 -1
View File
@@ -48,7 +48,7 @@ autodoc_default_flags = ['show-inheritance', 'members', 'undoc-members']
autodoc_member_order = 'bysource' autodoc_member_order = 'bysource'
intersphinx_mapping = {'python': ('https://docs.python.org/3', None), intersphinx_mapping = {'python': ('https://docs.python.org/3', None),
'requests': ('https://requests.kennethreitz.org/en/master/', None)} 'requests': ('https://requests.readthedocs.io/en/latest/', None)}
nitpick_ignore = [('py:class', 'typing.Tuple')] nitpick_ignore = [('py:class', 'typing.Tuple')]
+1 -1
View File
@@ -1,7 +1,7 @@
"""Download pictures (or videos) along with their captions and other metadata from Instagram.""" """Download pictures (or videos) along with their captions and other metadata from Instagram."""
__version__ = '4.9.1' __version__ = '4.9.3'
try: try:
+8 -6
View File
@@ -478,9 +478,8 @@ class Instaloader:
self.context.log(pcaption, end=' ', flush=True) self.context.log(pcaption, end=' ', flush=True)
except UnicodeEncodeError: except UnicodeEncodeError:
self.context.log('txt', end=' ', flush=True) self.context.log('txt', end=' ', flush=True)
with open(filename, 'wb') as text_file: with open(filename, 'w', encoding='UTF-8') as fio:
with BytesIO(bcaption) as bio: fio.write(caption)
shutil.copyfileobj(cast(IO, bio), text_file)
os.utime(filename, (datetime.now().timestamp(), mtime.timestamp())) os.utime(filename, (datetime.now().timestamp(), mtime.timestamp()))
def save_location(self, filename: str, location: PostLocation, mtime: datetime) -> None: def save_location(self, filename: str, location: PostLocation, mtime: datetime) -> None:
@@ -563,7 +562,7 @@ class Instaloader:
if latest_stamps is None: if latest_stamps is None:
self.download_profilepic(profile) self.download_profilepic(profile)
return return
profile_pic_basename = profile.profile_pic_url.split('/')[-1].split('?')[0] profile_pic_basename = profile.profile_pic_url_no_iphone.split('/')[-1].split('?')[0]
saved_basename = latest_stamps.get_profile_pic(profile.username) saved_basename = latest_stamps.get_profile_pic(profile.username)
if saved_basename == profile_pic_basename: if saved_basename == profile_pic_basename:
return return
@@ -1010,7 +1009,10 @@ class Instaloader:
enabled=self.resume_prefix is not None enabled=self.resume_prefix is not None
) as (is_resuming, start_index): ) as (is_resuming, start_index):
for number, post in enumerate(posts, start=start_index + 1): for number, post in enumerate(posts, start=start_index + 1):
if (max_count is not None and number > max_count) or not takewhile(post): should_stop = not takewhile(post)
if should_stop and post.is_pinned:
continue
if (max_count is not None and number > max_count) or should_stop:
break break
if displayed_count is not None: if displayed_count is not None:
self.context.log("[{0:{w}d}/{1:{w}d}] ".format(number, displayed_count, self.context.log("[{0:{w}d}/{1:{w}d}] ".format(number, displayed_count,
@@ -1042,7 +1044,7 @@ class Instaloader:
except PostChangedException: except PostChangedException:
post_changed = True post_changed = True
continue continue
if fast_update and not downloaded and not post_changed: if fast_update and not downloaded and not post_changed and not post.is_pinned:
# disengage fast_update for first post when resuming # disengage fast_update for first post when resuming
if not is_resuming or number > 0: if not is_resuming or number > 0:
break break
+15 -3
View File
@@ -76,7 +76,8 @@ class NodeIterator(Iterator[T]):
node_wrapper: Callable[[Dict], T], node_wrapper: Callable[[Dict], T],
query_variables: Optional[Dict[str, Any]] = None, query_variables: Optional[Dict[str, Any]] = None,
query_referer: Optional[str] = None, query_referer: Optional[str] = None,
first_data: Optional[Dict[str, Any]] = None): first_data: Optional[Dict[str, Any]] = None,
is_first: Optional[Callable[[T], bool]] = None):
self._context = context self._context = context
self._query_hash = query_hash self._query_hash = query_hash
self._edge_extractor = edge_extractor self._edge_extractor = edge_extractor
@@ -91,6 +92,7 @@ class NodeIterator(Iterator[T]):
else: else:
self._data = self._query() self._data = self._query()
self._first_node: Optional[Dict] = None self._first_node: Optional[Dict] = None
self._is_first = is_first
def _query(self, after: Optional[str] = None) -> Dict: def _query(self, after: Optional[str] = None) -> Dict:
pagination_variables = {'first': NodeIterator._graphql_page_length} # type: Dict[str, Any] pagination_variables = {'first': NodeIterator._graphql_page_length} # type: Dict[str, Any]
@@ -128,8 +130,12 @@ class NodeIterator(Iterator[T]):
self._page_index, self._total_index = page_index, total_index self._page_index, self._total_index = page_index, total_index
raise raise
item = self._node_wrapper(node) item = self._node_wrapper(node)
if self._first_node is None: if self._is_first is not None:
self._first_node = node if self._is_first(item):
self._first_node = node
else:
if self._first_node is None:
self._first_node = node
return item return item
if self._data['page_info']['has_next_page']: if self._data['page_info']['has_next_page']:
query_response = self._query(self._data['page_info']['end_cursor']) query_response = self._query(self._data['page_info']['end_cursor'])
@@ -168,7 +174,13 @@ class NodeIterator(Iterator[T]):
""" """
If this iterator has produced any items, returns the first item produced. If this iterator has produced any items, returns the first item produced.
It is possible to override what is considered the first item (for example, to consider the
newest item in case items are not in strict chronological order) by passing a callback
function as the `is_first` parameter when creating the class.
.. versionadded:: 4.8 .. versionadded:: 4.8
.. versionchanged:: 4.9.2
What is considered the first item can be overridden.
""" """
return self._node_wrapper(self._first_node) if self._first_node is not None else None return self._node_wrapper(self._first_node) if self._first_node is not None else None
+77 -11
View File
@@ -7,7 +7,7 @@ from contextlib import suppress
from datetime import datetime from datetime import datetime
from itertools import islice from itertools import islice
from pathlib import Path from pathlib import Path
from typing import Any, Dict, Iterable, Iterator, List, Optional, Tuple, Union from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union
from unicodedata import normalize from unicodedata import normalize
from . import __version__ from . import __version__
@@ -293,7 +293,7 @@ class Post:
url = re.sub(r'([?&])se=\d+&?', r'\1', orig_url).rstrip('&') url = re.sub(r'([?&])se=\d+&?', r'\1', orig_url).rstrip('&')
return url return url
except (InstaloaderException, KeyError, IndexError) as err: except (InstaloaderException, KeyError, IndexError) as err:
self._context.error('{} Unable to fetch high quality image version of {}.'.format(err, self)) self._context.error(f"Unable to fetch high quality image version of {self}: {err}")
return self._node["display_url"] if "display_url" in self._node else self._node["display_src"] return self._node["display_url"] if "display_url" in self._node else self._node["display_src"]
@property @property
@@ -357,8 +357,7 @@ class Post:
orig_url = carousel_media[idx]['image_versions2']['candidates'][0]['url'] orig_url = carousel_media[idx]['image_versions2']['candidates'][0]['url']
display_url = re.sub(r'([?&])se=\d+&?', r'\1', orig_url).rstrip('&') display_url = re.sub(r'([?&])se=\d+&?', r'\1', orig_url).rstrip('&')
except (InstaloaderException, KeyError, IndexError) as err: except (InstaloaderException, KeyError, IndexError) as err:
self._context.error('{} Unable to fetch high quality image version of {}.'.format( self._context.error(f"Unable to fetch high quality image version of {self}: {err}")
err, self))
yield PostSidecarNode(is_video=is_video, display_url=display_url, yield PostSidecarNode(is_video=is_video, display_url=display_url,
video_url=node['video_url'] if is_video else None) video_url=node['video_url'] if is_video else None)
@@ -644,6 +643,13 @@ class Post:
loc.get('lat'), loc.get('lng')) loc.get('lat'), loc.get('lng'))
return self._location return self._location
@property
def is_pinned(self) -> bool:
"""True if this Post has been pinned by at least one user.
.. versionadded: 4.9.2"""
return 'pinned_for_users' in self._node and bool(self._node['pinned_for_users'])
class Profile: class Profile:
""" """
@@ -946,11 +952,18 @@ class Profile:
try: try:
return self._iphone_struct['hd_profile_pic_url_info']['url'] return self._iphone_struct['hd_profile_pic_url_info']['url']
except (InstaloaderException, KeyError) as err: except (InstaloaderException, KeyError) as err:
self._context.error('{} Unable to fetch high quality profile pic.'.format(err)) self._context.error(f"Unable to fetch high quality profile pic: {err}")
return self._metadata("profile_pic_url_hd") return self._metadata("profile_pic_url_hd")
else: else:
return self._metadata("profile_pic_url_hd") return self._metadata("profile_pic_url_hd")
@property
def profile_pic_url_no_iphone(self) -> str:
"""Return URL of lower-quality profile picture.
.. versionadded:: 4.9.3"""
return self._metadata("profile_pic_url_hd")
def get_profile_pic_url(self) -> str: def get_profile_pic_url(self) -> str:
""".. deprecated:: 4.0.3 """.. deprecated:: 4.0.3
@@ -970,6 +983,7 @@ class Profile:
{'id': self.userid}, {'id': self.userid},
'https://www.instagram.com/{0}/'.format(self.username), 'https://www.instagram.com/{0}/'.format(self.username),
self._metadata('edge_owner_to_timeline_media'), self._metadata('edge_owner_to_timeline_media'),
Profile._make_is_newest_checker()
) )
def get_saved_posts(self) -> NodeIterator[Post]: def get_saved_posts(self) -> NodeIterator[Post]:
@@ -1003,6 +1017,7 @@ class Profile:
lambda n: Post(self._context, n, self if int(n['owner']['id']) == self.userid else None), lambda n: Post(self._context, n, self if int(n['owner']['id']) == self.userid else None),
{'id': self.userid}, {'id': self.userid},
'https://www.instagram.com/{0}/'.format(self.username), 'https://www.instagram.com/{0}/'.format(self.username),
is_first=Profile._make_is_newest_checker()
) )
def get_igtv_posts(self) -> NodeIterator[Post]: def get_igtv_posts(self) -> NodeIterator[Post]:
@@ -1020,8 +1035,22 @@ class Profile:
{'id': self.userid}, {'id': self.userid},
'https://www.instagram.com/{0}/channel/'.format(self.username), 'https://www.instagram.com/{0}/channel/'.format(self.username),
self._metadata('edge_felix_video_timeline'), self._metadata('edge_felix_video_timeline'),
Profile._make_is_newest_checker()
) )
@staticmethod
def _make_is_newest_checker() -> Callable[[Post], bool]:
newest_date: Optional[datetime] = None
def is_newest(p: Post) -> bool:
nonlocal newest_date
post_date = p.date_local
if newest_date is None or post_date > newest_date:
newest_date = post_date
return True
else:
return False
return is_newest
def get_followers(self) -> NodeIterator['Profile']: def get_followers(self) -> NodeIterator['Profile']:
""" """
Retrieve list of followers of given profile. Retrieve list of followers of given profile.
@@ -1149,8 +1178,14 @@ class StoryItem:
if not self._context.is_logged_in: if not self._context.is_logged_in:
raise LoginRequiredException("--login required to access iPhone media info endpoint.") raise LoginRequiredException("--login required to access iPhone media info endpoint.")
if not self._iphone_struct_: if not self._iphone_struct_:
data = self._context.get_iphone_json(path='api/v1/media/{}/info/'.format(self.mediaid), params={}) data = self._context.get_iphone_json(
self._iphone_struct_ = data['items'][0] path='api/v1/feed/reels_media/?reel_ids={}'.format(self.owner_id), params={}
)
self._iphone_struct_ = {}
for item in data['reels'][str(self.owner_id)]['items']:
if item['pk'] == self.mediaid:
self._iphone_struct_ = item
break
return self._iphone_struct_ return self._iphone_struct_
@property @property
@@ -1207,13 +1242,14 @@ class StoryItem:
@property @property
def url(self) -> str: def url(self) -> str:
"""URL of the picture / video thumbnail of the StoryItem""" """URL of the picture / video thumbnail of the StoryItem"""
if self.typename == "GraphStoryImage" and self._context.iphone_support and self._context.is_logged_in: if self.typename in ["GraphStoryImage", "StoryImage"] and \
self._context.iphone_support and self._context.is_logged_in:
try: try:
orig_url = self._iphone_struct['image_versions2']['candidates'][0]['url'] orig_url = self._iphone_struct['image_versions2']['candidates'][0]['url']
url = re.sub(r'([?&])se=\d+&?', r'\1', orig_url).rstrip('&') url = re.sub(r'([?&])se=\d+&?', r'\1', orig_url).rstrip('&')
return url return url
except (InstaloaderException, KeyError, IndexError) as err: except (InstaloaderException, KeyError, IndexError) as err:
self._context.error('{} Unable to fetch high quality image version of {}.'.format(err, self)) self._context.error(f"Unable to fetch high quality image version of {self}: {err}")
return self._node['display_resources'][-1]['src'] return self._node['display_resources'][-1]['src']
@property @property
@@ -1288,6 +1324,7 @@ class Story:
self._node = node self._node = node
self._unique_id = None # type: Optional[str] self._unique_id = None # type: Optional[str]
self._owner_profile = None # type: Optional[Profile] self._owner_profile = None # type: Optional[Profile]
self._iphone_struct_ = None # type: Optional[Dict[str, Any]]
def __repr__(self): def __repr__(self):
return '<Story by {} changed {:%Y-%m-%d_%H-%M-%S_UTC}>'.format(self.owner_username, self.latest_media_utc) return '<Story by {} changed {:%Y-%m-%d_%H-%M-%S_UTC}>'.format(self.owner_username, self.latest_media_utc)
@@ -1358,9 +1395,23 @@ class Story:
"""The story owner's ID.""" """The story owner's ID."""
return self.owner_profile.userid return self.owner_profile.userid
def _fetch_iphone_struct(self) -> None:
if self._context.iphone_support and self._context.is_logged_in and not self._iphone_struct_:
data = self._context.get_iphone_json(
path='api/v1/feed/reels_media/?reel_ids={}'.format(self.owner_id), params={}
)
self._iphone_struct_ = data['reels'][str(self.owner_id)]
def get_items(self) -> Iterator[StoryItem]: def get_items(self) -> Iterator[StoryItem]:
"""Retrieve all items from a story.""" """Retrieve all items from a story."""
yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node['items'])) self._fetch_iphone_struct()
for item in reversed(self._node['items']):
if self._iphone_struct_ is not None:
for iphone_struct_item in self._iphone_struct_['items']:
if iphone_struct_item['pk'] == int(item['id']):
item['iphone_struct'] = iphone_struct_item
break
yield StoryItem(self._context, item, self.owner_profile)
class Highlight(Story): class Highlight(Story):
@@ -1390,6 +1441,7 @@ class Highlight(Story):
super().__init__(context, node) super().__init__(context, node)
self._owner_profile = owner self._owner_profile = owner
self._items = None # type: Optional[List[Dict[str, Any]]] self._items = None # type: Optional[List[Dict[str, Any]]]
self._iphone_struct_ = None # type: Optional[Dict[str, Any]]
def __repr__(self): def __repr__(self):
return '<Highlight by {}: {}>'.format(self.owner_username, self.title) return '<Highlight by {}: {}>'.format(self.owner_username, self.title)
@@ -1428,6 +1480,13 @@ class Highlight(Story):
"highlight_reel_ids": [str(self.unique_id)], "highlight_reel_ids": [str(self.unique_id)],
"precomposed_overlay": False})['data']['reels_media'][0]['items'] "precomposed_overlay": False})['data']['reels_media'][0]['items']
def _fetch_iphone_struct(self) -> None:
if self._context.iphone_support and self._context.is_logged_in and not self._iphone_struct_:
data = self._context.get_iphone_json(
path='api/v1/feed/reels_media/?reel_ids=highlight:{}'.format(self.unique_id), params={}
)
self._iphone_struct_ = data['reels']['highlight:{}'.format(self.unique_id)]
@property @property
def itemcount(self) -> int: def itemcount(self) -> int:
"""Count of items associated with the :class:`Highlight` instance.""" """Count of items associated with the :class:`Highlight` instance."""
@@ -1438,8 +1497,15 @@ class Highlight(Story):
def get_items(self) -> Iterator[StoryItem]: def get_items(self) -> Iterator[StoryItem]:
"""Retrieve all associated highlight items.""" """Retrieve all associated highlight items."""
self._fetch_items() self._fetch_items()
self._fetch_iphone_struct()
assert self._items is not None assert self._items is not None
yield from (StoryItem(self._context, item, self.owner_profile) for item in self._items) for item in self._items:
if self._iphone_struct_ is not None:
for iphone_struct_item in self._iphone_struct_['items']:
if iphone_struct_item['pk'] == int(item['id']):
item['iphone_struct'] = iphone_struct_item
break
yield StoryItem(self._context, item, self.owner_profile)
class Hashtag: class Hashtag: