downloader.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import sys
  2. import time
  3. import os
  4. import shutil
  5. import subprocess
  6. import threading
  7. from instagram_private_api_extensions import live, replay
  8. from .logger import log, seperator
  9. class NoLivestreamException(Exception):
  10. pass
  11. class NoReplayException(Exception):
  12. pass
  13. def main(api_arg, record_arg, settings_arg):
  14. global api
  15. global record
  16. global broadcast
  17. global mpd_url
  18. global settings
  19. settings = settings_arg
  20. api = api_arg
  21. record = record_arg
  22. get_user_info(record)
  23. def run_script(file):
  24. try:
  25. FNULL = open(os.devnull, 'w')
  26. if sys.version.split(' ')[0].startswith('2'):
  27. subprocess.call(["python", file], stdout=FNULL, stderr=subprocess.STDOUT)
  28. else:
  29. subprocess.call(["python3", file], stdout=FNULL, stderr=subprocess.STDOUT)
  30. except OSError as e:
  31. pass
  32. def get_stream_duration(broadcast):
  33. try:
  34. started_mins, started_secs = divmod((int(time.time()) - broadcast['published_time']), 60)
  35. started_label = '%d minutes' % started_mins
  36. if started_secs:
  37. started_label += ' and %d seconds' % started_secs
  38. return started_label
  39. except:
  40. return "not available"
  41. def record_stream(broadcast):
  42. try:
  43. def print_status():
  44. heartbeat_info = api.broadcast_heartbeat_and_viewercount(broadcast['id'])
  45. viewers = broadcast.get('viewer_count', 0)
  46. log('[I] Viewers : ' + str(int(viewers)) + " watching", "GREEN")
  47. log('[I] Airing time : ' + get_stream_duration(broadcast).title(), "GREEN")
  48. log('[I] Status : ' + heartbeat_info['broadcast_status'].title(), "GREEN")
  49. seperator("GREEN")
  50. return heartbeat_info['broadcast_status'] not in ['active', 'interrupted']
  51. mpd_url = (broadcast.get('dash_manifest')
  52. or broadcast.get('dash_abr_playback_url')
  53. or broadcast['dash_playback_url'])
  54. output_dir = settings.save_path + '{}_{}_{}_{}_live_downloads'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  55. dl = live.Downloader(
  56. mpd=mpd_url,
  57. output_dir=output_dir,
  58. user_agent=api.user_agent,
  59. max_connection_error_retry=3,
  60. duplicate_etag_retry=30,
  61. callback_check=print_status,
  62. mpd_download_timeout=5,
  63. download_timeout=10)
  64. except Exception as e:
  65. log('[E] Could not start recording livestream: ' + str(e), "RED")
  66. seperator("GREEN")
  67. sys.exit(1)
  68. try:
  69. log('[I] Starting livestream recording:', "GREEN")
  70. log('[I] Username : ' + record, "GREEN")
  71. log('[I] MPD URL : ' + mpd_url, "GREEN")
  72. print_status()
  73. log('[I] Recording livestream... press [CTRL+C] to abort.', "GREEN")
  74. if (settings.run_at_start is not "None"):
  75. try:
  76. thread = threading.Thread(target=run_script, args=(settings.run_at_start,))
  77. thread.daemon = True
  78. thread.start()
  79. log("[I] Executed file to run at start.", "GREEN")
  80. except Exception as e:
  81. log('[W] Could not run file: ' + str(e), "YELLOW")
  82. dl.run()
  83. log('[I] The livestream has ended. (Duration: ' + get_stream_duration(broadcast) + ")", "GREEN")
  84. stitch_video(dl, broadcast)
  85. except KeyboardInterrupt:
  86. log("", "GREEN")
  87. log('[W] Download has been aborted.', "YELLOW")
  88. log("", "GREEN")
  89. if not dl.is_aborted:
  90. dl.stop()
  91. stitch_video(dl, broadcast)
  92. def stitch_video(dl, broadcast):
  93. if (settings.run_at_finish is not "None"):
  94. try:
  95. thread = threading.Thread(target=run_script, args=(settings.run_at_finish,))
  96. thread.daemon = True
  97. thread.start()
  98. log("[I] Executed file to run at finish.", "GREEN")
  99. except Exception as e:
  100. log('[W] Could not run file: ' + str(e), "YELLOW")
  101. log('[I] Stitching downloaded files into video...', "GREEN")
  102. output_file = settings.save_path + '{}_{}_{}_{}_live.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  103. try:
  104. if settings.clear_temp_files.title() == "True":
  105. dl.stitch(output_file, cleartempfiles=True)
  106. else:
  107. dl.stitch(output_file, cleartempfiles=False)
  108. log('[I] Successfully stitched downloaded files.', "GREEN")
  109. seperator("GREEN")
  110. sys.exit(0)
  111. except Exception as e:
  112. log('[E] Could not stitch downloaded files: ' + str(e), "RED")
  113. seperator("GREEN")
  114. sys.exit(1)
  115. def get_user_info(record):
  116. try:
  117. log("[I] Checking user: '"+ record + "'", "GREEN")
  118. user_res = api.username_info(record)
  119. user_id = user_res['user']['pk']
  120. except Exception as e:
  121. log('[E] Could not get user info: ' + str(e), "RED")
  122. seperator("GREEN")
  123. sys.exit(1)
  124. get_livestreams(user_id)
  125. if settings.save_replays.title() == "True":
  126. get_replays(user_id)
  127. else:
  128. log("", "BLUE")
  129. log("[I] Replay saving is disabled either with a flag or in the config file.", "BLUE")
  130. seperator("GREEN")
  131. sys.exit(0)
  132. def get_livestreams(user_id):
  133. try:
  134. log('[I] Checking for ongoing livestreams...', "GREEN")
  135. broadcast = api.user_broadcast(user_id)
  136. if (broadcast is None):
  137. raise NoLivestreamException('There are no livestreams available.')
  138. else:
  139. record_stream(broadcast)
  140. except NoLivestreamException as e:
  141. log('[W] ' + str(e), "YELLOW")
  142. except Exception as e:
  143. if (e.__class__.__name__ is not NoLivestreamException):
  144. log('[E] Could not get livestreams info: ' + str(e), "RED")
  145. seperator("GREEN")
  146. sys.exit(1)
  147. def get_replays(user_id):
  148. try:
  149. log('[I] Checking for available replays...', "GREEN")
  150. user_story_feed = api.user_story_feed(user_id)
  151. broadcasts = user_story_feed.get('post_live_item', {}).get('broadcasts', [])
  152. except Exception as e:
  153. log('[E] Could not get replay info: ' + str(e), "RED")
  154. seperator("GREEN")
  155. sys.exit(1)
  156. try:
  157. if (len(broadcasts) == 0):
  158. raise NoReplayException('There are no replays available.')
  159. else:
  160. log("[I] Available replays have been found to download, press [CTRL+C] to abort.", "GREEN")
  161. log("", "GREEN")
  162. for index, broadcast in enumerate(broadcasts):
  163. exists = False
  164. if sys.version.split(' ')[0].startswith('2'):
  165. directories = (os.walk(settings.save_path).next()[1])
  166. else:
  167. directories = (os.walk(settings.save_path).__next__()[1])
  168. for directory in directories:
  169. if (str(broadcast['id']) in directory) and ("_live_" not in directory):
  170. log("[W] Already downloaded a replay with ID '" + str(broadcast['id']) + "', skipping...", "GREEN")
  171. exists = True
  172. if exists is False:
  173. current = index + 1
  174. log("[I] Downloading replay " + str(current) + " of " + str(len(broadcasts)) + " with ID '" + str(broadcast['id']) + "'...", "GREEN")
  175. current_time = str(int(time.time()))
  176. output_dir = settings.save_path + '{}_{}_{}_{}_replay_downloads'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  177. dl = replay.Downloader(
  178. mpd=broadcast['dash_manifest'],
  179. output_dir=output_dir,
  180. user_agent=api.user_agent)
  181. if settings.clear_temp_files.title() == "True":
  182. replay_saved = dl.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time), cleartempfiles=True)
  183. else:
  184. replay_saved = dl.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time), cleartempfiles=False)
  185. if (len(replay_saved) == 1):
  186. log("[I] Finished downloading replay " + str(current) + " of " + str(len(broadcasts)) + ".", "GREEN")
  187. log("", "GREEN")
  188. else:
  189. log("[W] No output video file was made, please merge the files manually.", "RED")
  190. log("[W] Check if ffmpeg is available by running ffmpeg in your terminal.", "RED")
  191. log("", "GREEN")
  192. log("[I] Finished downloading available replays.", "GREEN")
  193. seperator("GREEN")
  194. sys.exit(0)
  195. except NoReplayException as e:
  196. log('[W] ' + str(e), "YELLOW")
  197. seperator("GREEN")
  198. sys.exit(0)
  199. except Exception as e:
  200. log('[E] Could not save replay: ' + str(e), "RED")
  201. seperator("GREEN")
  202. sys.exit(1)
  203. except KeyboardInterrupt:
  204. log("", "GREEN")
  205. log('[W] Download has been aborted.', "YELLOW")
  206. try:
  207. shutil.rmtree(output_dir)
  208. except Exception as e:
  209. log("[E] Could not remove temp folder: " + str(e), "RED")
  210. sys.exit(1)
  211. sys.exit(0)