auth.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. import codecs
  2. import datetime
  3. import json
  4. import os.path
  5. import sys
  6. from .logger import log
  7. from .logger import seperator
  8. try:
  9. from instagram_private_api import (
  10. Client, ClientError, ClientLoginError,
  11. ClientCookieExpiredError, ClientLoginRequiredError)
  12. except ImportError:
  13. import sys
  14. sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
  15. from instagram_private_api import (
  16. Client, ClientError, ClientLoginError,
  17. ClientCookieExpiredError, ClientLoginRequiredError)
  18. def to_json(python_object):
  19. if isinstance(python_object, bytes):
  20. return {'__class__': 'bytes',
  21. '__value__': codecs.encode(python_object, 'base64').decode()}
  22. raise TypeError(repr(python_object) + ' is not JSON serializable')
  23. def from_json(json_object):
  24. if '__class__' in json_object and json_object.get('__class__') == 'bytes':
  25. return codecs.decode(json_object.get('__value__').encode(), 'base64')
  26. return json_object
  27. def onlogin_callback(api, cookie_file):
  28. cache_settings = api.settings
  29. with open(cookie_file, 'w') as outfile:
  30. json.dump(cache_settings, outfile, default=to_json)
  31. log('[I] New cookie file was made: {0!s}'.format(cookie_file), "GREEN")
  32. def login(username, password, show_cookie_expiry, force_use_login_args):
  33. device_id = None
  34. try:
  35. if force_use_login_args:
  36. log("[I] Overriding standard login with -u and -p arguments...", "GREEN")
  37. api = Client(
  38. username, password)
  39. else:
  40. cookie_file = "{}.json".format(username)
  41. if not os.path.isfile(cookie_file):
  42. # settings file does not exist
  43. log('[W] Unable to find cookie file: {0!s}'.format(cookie_file), "YELLOW")
  44. log('[I] Creating a new cookie file...', "YELLOW")
  45. # login new
  46. api = Client(
  47. username, password,
  48. on_login=lambda x: onlogin_callback(x, cookie_file))
  49. else:
  50. with open(cookie_file) as file_data:
  51. cached_settings = json.load(file_data, object_hook=from_json)
  52. # log('[I] Using settings file: {0!s}'.format(cookie_file), "GREEN")
  53. device_id = cached_settings.get('device_id')
  54. # reuse auth cached_settings
  55. api = Client(
  56. username, password,
  57. settings=cached_settings)
  58. except (ClientCookieExpiredError) as e:
  59. log('[W] The current cookie file for "{:s}" has expired, creating a new one...'.format(username), "YELLOW")
  60. # Login expired
  61. # Do relogin but use default ua, keys and such
  62. try:
  63. api = Client(
  64. username, password,
  65. device_id=device_id,
  66. on_login=lambda x: onlogin_callback(x, cookie_file))
  67. except Exception as ee:
  68. seperator("GREEN")
  69. log('[E] An error occurred while trying to create a new cookie file: {:s}'.format(str(ee)), "RED")
  70. if "getaddrinfo failed" in str(ee):
  71. log('[E] Could not resolve host, check your internet connection.', "RED")
  72. if "timed out" in str(ee):
  73. log('[E] The connection timed out, check your internet connection.', "RED")
  74. exit(1)
  75. except ClientLoginError as e:
  76. seperator("GREEN")
  77. log('[E] Could not login: {:s}.\n[E] {:s}\n\n{:s}'.format(json.loads(e.error_response).get("error_title", "Error title not available."), json.loads(e.error_response).get("message", "Not available"), e.error_response), "RED")
  78. seperator("GREEN")
  79. sys.exit(9)
  80. except ClientError as e:
  81. seperator("GREEN")
  82. try:
  83. log('[E] Unexpected exception: {0!s}\n[E] Message: {1!s}\n[E] Code: {2:d}\n\n[E] Full response:\n{3!s}\n'.format(e.msg, json.loads(e.error_response).get("message", "Additional error information not available."), e.code, e.error_response), "RED")
  84. except Exception as ee:
  85. log('[E] An error occurred while trying to handle a previous exception.\n[E] 1: {:s}\n[E] 2: {:s}'.format(str(e), str(ee)), "RED")
  86. if "getaddrinfo failed" in str(ee):
  87. log('[E] Could not resolve host, check your internet connection.', "RED")
  88. if "timed out" in str(ee):
  89. log('[E] The connection timed out, check your internet connection.', "RED")
  90. seperator("GREEN")
  91. sys.exit(9)
  92. except Exception as e:
  93. if (str(e).startswith("unsupported pickle protocol")):
  94. log("[W] This cookie file is not compatible with Python {}.".format(sys.version.split(' ')[0][0]), "YELLOW")
  95. log("[W] Please delete your cookie file '{}.json' and try again.".format(username), "YELLOW")
  96. else:
  97. seperator("GREEN")
  98. log('[E] Unexpected exception: {0!s}'.format(e), "RED")
  99. seperator("GREEN")
  100. sys.exit(99)
  101. except KeyboardInterrupt as e:
  102. seperator("GREEN")
  103. log("[W] The user authentication has been aborted.", "YELLOW")
  104. seperator("GREEN")
  105. sys.exit(0)
  106. log('[I] Successfully logged into user "{:s}".'.format(str(api.authenticated_user_name)), "GREEN")
  107. if show_cookie_expiry.title() == 'True' and not force_use_login_args:
  108. try:
  109. cookie_expiry = api.cookie_jar.auth_expires
  110. log('[I] Cookie file expiry date: {0!s}'.format(datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%d at %I:%M:%S %p')), "GREEN")
  111. except AttributeError as e:
  112. log('[W] An error occurred while getting the cookie file expiry date: {0!s}'.format(e), "YELLOW")
  113. seperator("GREEN")
  114. return api