Skip to content

Commit

Permalink
Update login method to restore sessions
Browse files Browse the repository at this point in the history
Update login method to try to restore saved sessions before logging in. Just a way to avoid frequent/unnecessary logins.
  • Loading branch information
iSarabjitDhiman committed Jul 29, 2023
1 parent 4dae2da commit 4354bf0
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 32 deletions.
71 changes: 40 additions & 31 deletions instagpy/instagpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def me(self):
dict: Currently logged in User Data.
"""
response = self._get_meta_data()
return response['config']['viewer']
return response.get('config', {}).get('viewer', None)

def _get_meta_data(self):
"""Returns Browser's and User's Meta Data.
Expand Down Expand Up @@ -178,37 +178,46 @@ def login(self, username=None, password=None, show_saved_sessions=False, save_se
return
if username is None:
username = str(input("Enter Your Username or Email : ")).strip()
if password is None:
password = getpass.getpass()
timestamp = int(datetime.datetime.now().timestamp())
# login to generate cookies
payload = {
'username': username,
'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{timestamp}:{password}',
'queryParams': {},
'optIntoOneTap': 'false',
'trustedDeviceRecords': {}
}
user = self.session.post(path.LOGIN_URL, data=payload).json()

try:
if user["authenticated"]:
user_id = user["userId"]
# test if the account is working
user = self.session.get(
path.USER_DATA_ENDPOINT.format(user_id)).json()
if user['status'] != 'ok':
raise Exception(
f"Not Working! Check if the given account is working.")
user_fullname = user['user']['full_name']
print(f"{user_fullname} : Successfully Logged In....")
if save_session:
session_util.save_session(
session=self.session, filename=username)
return
raise Exception("Couldn't LogIn, Try again...")
except Exception as error:
print('\n', error)
utils.check_for_errors(user)
session_util.load_session(filename=username, session=self.session)
user = self.me
if not user:
print("Restored Session has been Expired. Trying to Login...")
raise Exception("Session Expired.")
print(f"{user.get('full_name','')} : Session Restored.")
except:
if password is None:
password = getpass.getpass()
timestamp = int(datetime.datetime.now().timestamp())
# login to generate cookies
payload = {
'username': username,
'enc_password': f'#PWD_INSTAGRAM_BROWSER:0:{timestamp}:{password}',
'queryParams': {},
'optIntoOneTap': 'false',
'trustedDeviceRecords': {}
}
user = self.session.post(path.LOGIN_URL, data=payload).json()
try:
if user["authenticated"]:
user_id = user["userId"]
# test if the account is working
user = self.session.get(
path.USER_DATA_ENDPOINT.format(user_id)).json()
if user['status'] != 'ok':
raise Exception(
f"Not Working! Check if the given account is working.")
user_fullname = user['user']['full_name']
print(f"{user_fullname} : Successfully Logged In....")
if save_session:
session_util.save_session(
session=self.session, filename=username)
return
raise Exception("Couldn't Login, Try again...")
except Exception as error:
print('\n', error)
utils.check_for_errors(user)

def logged_in(self):
"""Check if user is logged in.
Expand Down
8 changes: 7 additions & 1 deletion instagpy/session_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,9 +66,15 @@ def save_session(session=None, filename=None, path=None):


def load_session(filename=None, path=None, session=None):
if filename is None or path is None:
if filename is None:
path, filename = show_saved_sessions()
if path is None:
path = create_session_directory()
if not filename.endswith("pkl"):
filename = f"{filename}.pkl"
filename = os.path.join(path, filename)
if not os.path.exists(filename):
raise Exception("Couldn't find any session file for this user.")

with open(filename, "rb") as file:
sessionid = pickle.load(file)
Expand Down

0 comments on commit 4354bf0

Please sign in to comment.