downloader.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import sys
  2. import time
  3. import os
  4. from instagram_private_api_extensions import live, replay
  5. import logger
  6. class NoLivestreamException(Exception):
  7. pass
  8. class NoReplayException(Exception):
  9. pass
  10. def main(api_arg, record_arg, save_path_arg):
  11. global api
  12. global record
  13. global save_path
  14. global current_date
  15. global current_time
  16. global broadcast
  17. global mpd_url
  18. current_time = str(int(time.time()))
  19. current_date = time.strftime("%Y%m%d")
  20. api = api_arg
  21. record = record_arg
  22. save_path = save_path_arg
  23. get_user_info(record)
  24. def record_stream(broadcast):
  25. try:
  26. def check_status():
  27. print_status()
  28. mpd_url = (broadcast.get('dash_manifest')
  29. or broadcast.get('dash_abr_playback_url')
  30. or broadcast['dash_playback_url'])
  31. output_dir = save_path + '{}_{}_{}_{}_live_downloads'.format(current_date, record, broadcast['id'], current_time)
  32. dl = live.Downloader(
  33. mpd=mpd_url,
  34. output_dir=output_dir,
  35. user_agent=api.user_agent,
  36. max_connection_error_retry=2,
  37. duplicate_etag_retry=60,
  38. callback_check=check_status,
  39. mpd_download_timeout=10,
  40. download_timeout=10)
  41. except Exception as e:
  42. logger.log('[E] Could not start recording livestream: ' + str(e), "RED")
  43. logger.seperator("GREEN")
  44. sys.exit(1)
  45. try:
  46. logger.log('[I] Starting livestream recording:', "GREEN")
  47. logger.log('[I] Username : ' + record, "GREEN")
  48. logger.log('[I] MPD URL : ' + mpd_url, "GREEN")
  49. print_status(api, broadcast)
  50. logger.log('[I] Recording livestream... press [CTRL+C] to abort.', "GREEN")
  51. dl.run()
  52. stitch_video(dl, broadcast)
  53. except KeyboardInterrupt:
  54. logger.log('', "GREEN")
  55. logger.log('[I] Aborting livestream recording...', "GREEN")
  56. if not dl.is_aborted:
  57. dl.stop()
  58. stitch_video(dl, broadcast)
  59. def stitch_video(dl, broadcast):
  60. logger.log('[I] Stitching downloaded files into video...', "GREEN")
  61. output_file = save_path + '{}_{}_{}_{}_live.mp4'.format(current_date, record, broadcast['id'], current_time)
  62. try:
  63. dl.stitch(output_file, cleartempfiles=False)
  64. logger.log('[I] Successfully stitched downloaded files!', "GREEN")
  65. logger.seperator("GREEN")
  66. sys.exit(0)
  67. except Exception as e:
  68. logger.log('[E] Could not stitch downloaded files: ' + str(e), "RED")
  69. logger.seperator("GREEN")
  70. sys.exit(1)
  71. def get_user_info(record):
  72. try:
  73. logger.log('[I] Getting required user info for user "' + record + '"...', "GREEN")
  74. user_res = api.username_info(record)
  75. user_id = user_res['user']['pk']
  76. except Exception as e:
  77. logger.log('[E] Could not get user info: ' + str(e), "RED")
  78. logger.seperator("GREEN")
  79. sys.exit(1)
  80. get_livestreams(user_id)
  81. get_replays(user_id)
  82. def get_livestreams(user_id):
  83. try:
  84. logger.log('[I] Checking for ongoing livestreams...', "GREEN")
  85. broadcast = api.user_broadcast(user_id)
  86. if (broadcast is None):
  87. raise NoLivestreamException('There are no livestreams available.')
  88. else:
  89. record_stream(broadcast)
  90. except NoLivestreamException as e:
  91. logger.log('[W] ' + str(e), "YELLOW")
  92. except Exception as e:
  93. if (e.__class__.__name__ is not NoLivestreamException):
  94. logger.log('[E] Could not get livestreams info: ' + str(e), "RED")
  95. logger.seperator("GREEN")
  96. sys.exit(1)
  97. def get_replays(user_id):
  98. try:
  99. logger.log('[I] Checking for available replays...', "GREEN")
  100. user_story_feed = api.user_story_feed(user_id)
  101. broadcasts = user_story_feed.get('post_live_item', {}).get('broadcasts', [])
  102. except Exception as e:
  103. logger.log('[E] Could not get replay: ' + str(e), "RED")
  104. logger.seperator("GREEN")
  105. sys.exit(1)
  106. try:
  107. if (len(broadcasts) == 0):
  108. raise NoReplayException('There are no replays available.')
  109. else:
  110. for index, broadcast in enumerate(broadcasts):
  111. exists = False
  112. for directory in (os.walk(save_path).next()[1]):
  113. if (str(broadcast['id']) in directory) and ("_live_" not in directory):
  114. logger.log("[W] Already downloaded a replay with ID '" + str(broadcast['id']) + "', skipping...", "GREEN")
  115. exists = True
  116. return
  117. if exists is False:
  118. current = index + 1
  119. logger.log("[I] Starting replay download " + str(current) + " of " + str(len(broadcasts)) + "...", "GREEN")
  120. current_time = str(int(time.time()))
  121. output_dir = save_path + '{}_{}_{}_{}_replay_downloads'.format(current_date, record, broadcast['id'], current_time)
  122. dl = replay.Downloader(
  123. mpd=broadcast['dash_manifest'],
  124. output_dir=output_dir,
  125. user_agent=api.user_agent)
  126. dl.download(save_path + '{}_{}_{}_{}_replay.mp4'.format(current_date, record, broadcast['id'], current_time), cleartempfiles=False)
  127. logger.log("[I] Finished downloading available replays.", "GREEN")
  128. logger.seperator("GREEN")
  129. sys.exit(0)
  130. except NoReplayException as e:
  131. logger.log('[W] ' + str(e), "YELLOW")
  132. logger.seperator("GREEN")
  133. sys.exit(1)
  134. except Exception as e:
  135. if (e.__class__.__name__ is not NoReplayException):
  136. logger.log('[E] Could not get replay: ' + str(e), "RED")
  137. logger.seperator("GREEN")
  138. sys.exit(1)
  139. def print_status(api, broadcast):
  140. heartbeat_info = api.broadcast_heartbeat_and_viewercount(broadcast['id'])
  141. viewers = broadcast.get('viewer_count', 0)
  142. started_mins, started_secs = divmod((int(time.time()) - broadcast['published_time']), 60)
  143. started_label = '%d minutes' % started_mins
  144. if started_secs:
  145. started_label += ' and %d seconds' % started_secs
  146. logger.log('[I] Viewers : ' + str(int(viewers)) + " watching", "GREEN")
  147. logger.log('[I] Airing time : ' + started_label, "GREEN")
  148. logger.log('[I] Status : ' + heartbeat_info['broadcast_status'].title(), "GREEN")
  149. logger.log('', "GREEN")