downloader.py 8.1 KB

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