pyinstalive.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. import json
  2. import codecs
  3. import datetime
  4. import os.path
  5. import logging
  6. import argparse
  7. import json
  8. import codecs
  9. from socket import timeout, error as SocketError
  10. from ssl import SSLError
  11. from urllib2 import URLError
  12. from httplib import HTTPException
  13. try:
  14. from instagram_private_api import (
  15. Client, ClientError, ClientLoginError,
  16. ClientCookieExpiredError, ClientLoginRequiredError,
  17. __version__ as client_version)
  18. except ImportError:
  19. import sys
  20. sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
  21. from instagram_private_api import (
  22. Client, ClientError, ClientLoginError,
  23. ClientCookieExpiredError, ClientLoginRequiredError,
  24. __version__ as client_version)
  25. from instagram_private_api_extensions import live
  26. import sys, os, time, json
  27. def download():
  28. try:
  29. user_res = api.username_info(args.record)
  30. user_id = user_res['user']['pk']
  31. except Exception as e:
  32. print('[E] Could not get user information, exiting . . .')
  33. print('[E] ' + str(e))
  34. print(seperator)
  35. exit()
  36. try:
  37. print('[I] Checking broadcast for ' + args.record + ' . . .')
  38. broadcast = api.user_broadcast(user_id)
  39. if (broadcast is None):
  40. raise Exception('No broadcast available')
  41. except Exception as e:
  42. print('[E] Could not get broadcast information, exiting . . .')
  43. print('[E] ' + str(e))
  44. print(seperator)
  45. exit()
  46. try:
  47. dl = live.Downloader(
  48. mpd=broadcast['dash_playback_url'],
  49. output_dir='{}_output_{}/'.format(args.record, broadcast['id']),
  50. user_agent=api.user_agent)
  51. except Exception as e:
  52. print('[E] Could not start broadcast recording, exiting . . .')
  53. print('[E] ' + str(e))
  54. print(seperator)
  55. exit()
  56. try:
  57. print('[I] Starting broadcast recording . . .')
  58. dl.run()
  59. except KeyboardInterrupt:
  60. print('')
  61. print('[I] Aborting broadcast recording . . .')
  62. if not dl.is_aborted:
  63. dl.stop()
  64. finally:
  65. t = time.time()
  66. print('[I] Stitching downloaded files into video . . .')
  67. dl.stitch(args.record + "_" + str(broadcast['id']) + "_" + str(int(t)) + '.mp4')
  68. print('[I] Successfully stitched downloaded files, exiting . . .')
  69. print(seperator)
  70. exit()
  71. def to_json(python_object):
  72. if isinstance(python_object, bytes):
  73. return {'__class__': 'bytes',
  74. '__value__': codecs.encode(python_object, 'base64').decode()}
  75. raise TypeError(repr(python_object) + ' is not JSON serializable')
  76. def from_json(json_object):
  77. if '__class__' in json_object and json_object['__class__'] == 'bytes':
  78. return codecs.decode(json_object['__value__'].encode(), 'base64')
  79. return json_object
  80. def onlogin_callback(api, new_settings_file):
  81. cache_settings = api.settings
  82. with open(new_settings_file, 'w') as outfile:
  83. json.dump(cache_settings, outfile, default=to_json)
  84. print('SAVED: {0!s}'.format(new_settings_file))
  85. if __name__ == '__main__':
  86. logging.basicConfig()
  87. logger = logging.getLogger('instagram_private_api')
  88. logger.setLevel(logging.WARNING)
  89. # Example command:
  90. # python examples/savesettings_logincallback.py -u "yyy" -p "zzz" -settings "test_credentials.json"
  91. parser = argparse.ArgumentParser(description='login callback and save settings demo')
  92. parser.add_argument('-settings', '--settings', dest='settings_file_path', type=str, required=True)
  93. parser.add_argument('-u', '--username', dest='username', type=str, required=True)
  94. parser.add_argument('-p', '--password', dest='password', type=str, required=True)
  95. parser.add_argument('-r', '--record', dest='record', type=str, required=True)
  96. global args
  97. global clear
  98. global seperator
  99. seperator = '=-' * 35
  100. clear = lambda: os.system('clear')
  101. args = parser.parse_args()
  102. #clear()
  103. print('PYINSTALIVE DOWNLOADER (API v{0!s})'.format(client_version))
  104. print(seperator)
  105. device_id = None
  106. try:
  107. settings_file = args.settings_file_path
  108. if not os.path.isfile(settings_file):
  109. # settings file does not exist
  110. print('[E] Unable to find file: {0!s}'.format(settings_file))
  111. # login new
  112. api = Client(
  113. args.username, args.password,
  114. on_login=lambda x: onlogin_callback(x, args.settings_file_path))
  115. else:
  116. with open(settings_file) as file_data:
  117. cached_settings = json.load(file_data, object_hook=from_json)
  118. print('[I] Reusing settings: {0!s}'.format(settings_file))
  119. device_id = cached_settings.get('device_id')
  120. # reuse auth settings
  121. api = Client(
  122. args.username, args.password,
  123. settings=cached_settings)
  124. except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
  125. print('[E] ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(e))
  126. # Login expired
  127. # Do relogin but use default ua, keys and such
  128. api = Client(
  129. args.username, args.password,
  130. device_id=device_id,
  131. on_login=lambda x: onlogin_callback(x, args.settings_file_path))
  132. except ClientLoginError as e:
  133. print('[E] ClientLoginError {0!s}'.format(e))
  134. print(seperator)
  135. exit(9)
  136. except ClientError as e:
  137. print('[E] ClientError {0!s} (Code: {1:d}, Response: {2!s})'.format(e.msg, e.code, e.error_response))
  138. print(seperator)
  139. exit(9)
  140. except Exception as e:
  141. print('[E] Unexpected Exception: {0!s}'.format(e))
  142. print(seperator)
  143. exit(99)
  144. # Show when login expires
  145. cookie_expiry = api.cookie_jar.expires_earliest
  146. print('[I] Cookie Expiry: {0!s}'.format(datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%dT%H:%M:%SZ')))
  147. print('[I] Successfully logged in, starting recorder . . .')
  148. download()