auth.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  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, settings_file):
  28. cache_settings = api.settings
  29. with open(settings_file, 'w') as outfile:
  30. json.dump(cache_settings, outfile, default=to_json)
  31. log('[I] New auth cookie file was made: {0!s}'.format(settings_file), "GREEN")
  32. def login(username, password, show_cookie_expiry, ignore_existing_cookie):
  33. device_id = None
  34. try:
  35. if ignore_existing_cookie:
  36. api = Client(
  37. username, password)
  38. else:
  39. settings_file = username + ".json"
  40. if not os.path.isfile(settings_file):
  41. # settings file does not exist
  42. log('[W] Unable to find auth cookie file: {0!s}'.format(settings_file), "YELLOW")
  43. # login new
  44. api = Client(
  45. username, password,
  46. on_login=lambda x: onlogin_callback(x, settings_file))
  47. else:
  48. with open(settings_file) as file_data:
  49. cached_settings = json.load(file_data, object_hook=from_json)
  50. # log('[I] Using settings file: {0!s}'.format(settings_file), "GREEN")
  51. device_id = cached_settings.get('device_id')
  52. # reuse auth settings
  53. api = Client(
  54. username, password,
  55. settings=cached_settings)
  56. except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
  57. log('[E] ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(e), "RED")
  58. # Login expired
  59. # Do relogin but use default ua, keys and such
  60. api = Client(
  61. username, password,
  62. device_id=device_id,
  63. on_login=lambda x: onlogin_callback(x, settings_file))
  64. except ClientLoginError as e:
  65. log('[E] ClientLoginError: {0!s}\n\n(Code: {1:d}, Response: {2!s})\n'.format(e.msg, e.code, e.error_response), "RED")
  66. seperator("GREEN")
  67. sys.exit(9)
  68. except ClientError as e:
  69. log('[E] ClientError: {0!s}\n\n(Code: {1:d}, Response: {2!s})\n'.format(e.msg, e.code, e.error_response), "RED")
  70. seperator("GREEN")
  71. sys.exit(9)
  72. except Exception as e:
  73. if (str(e).startswith("unsupported pickle protocol")):
  74. log("[W] This cookie file is not compatible with Python {}.".format(sys.version.split(' ')[0][0]), "YELLOW")
  75. log("[W] Please delete your cookie file '" + username + ".json' and try again.", "YELLOW")
  76. else:
  77. log('[E] Unexpected Exception: {0!s}'.format(e), "RED")
  78. seperator("GREEN")
  79. sys.exit(99)
  80. log('[I] Using cached login cookie for "' + api.authenticated_user_name + '".', "GREEN")
  81. if show_cookie_expiry.title() == 'True' and ignore_existing_cookie == False:
  82. cookie_expiry = api.cookie_jar.expires_earliest
  83. log('[I] Login cookie expiry date: {0!s}'.format(datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%d at %I:%M:%S %p')), "GREEN")
  84. return api