downloader.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. from .comments import CommentsDownloader
  11. class NoLivestreamException(Exception):
  12. pass
  13. class NoReplayException(Exception):
  14. pass
  15. def main(api_arg, record_arg, settings_arg):
  16. global api
  17. global record
  18. global broadcast
  19. global mpd_url
  20. global settings
  21. settings = settings_arg
  22. api = api_arg
  23. record = record_arg
  24. get_user_info(record)
  25. def run_script(file):
  26. try:
  27. FNULL = open(os.devnull, 'w')
  28. if sys.version.split(' ')[0].startswith('2'):
  29. subprocess.call(["python", file], stdout=FNULL, stderr=subprocess.STDOUT)
  30. else:
  31. subprocess.call(["python3", file], stdout=FNULL, stderr=subprocess.STDOUT)
  32. except OSError as e:
  33. pass
  34. def get_stream_duration(compare_time):
  35. try:
  36. stream_started_mins, stream_started_secs = divmod((int(time.time()) - int(compare_time)), 60)
  37. stream_duration_str = '%d minutes' % stream_started_mins
  38. if stream_started_secs:
  39. stream_duration_str += ' and %d seconds' % stream_started_secs
  40. return stream_duration_str
  41. except:
  42. return "not available"
  43. def record_stream(broadcast):
  44. try:
  45. def print_status(sep=True):
  46. heartbeat_info = api.broadcast_heartbeat_and_viewercount(broadcast['id'])
  47. viewers = broadcast.get('viewer_count', 0)
  48. if sep:
  49. seperator("GREEN")
  50. log('[I] Viewers : ' + str(int(viewers)) + " watching", "GREEN")
  51. log('[I] Airing time : ' + get_stream_duration(broadcast['published_time']).title(), "GREEN")
  52. log('[I] Status : ' + heartbeat_info['broadcast_status'].title(), "GREEN")
  53. return heartbeat_info['broadcast_status'] not in ['active', 'interrupted']
  54. mpd_url = (broadcast.get('dash_manifest')
  55. or broadcast.get('dash_abr_playback_url')
  56. or broadcast['dash_playback_url'])
  57. output_dir = settings.save_path + '{}_{}_{}_{}_live_downloads'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  58. dl = live.Downloader(
  59. mpd=mpd_url,
  60. output_dir=output_dir,
  61. user_agent=api.user_agent,
  62. max_connection_error_retry=3,
  63. duplicate_etag_retry=30,
  64. callback_check=print_status,
  65. mpd_download_timeout=5,
  66. download_timeout=10)
  67. except Exception as e:
  68. log('[E] Could not start downloading livestream: ' + str(e), "RED")
  69. seperator("GREEN")
  70. sys.exit(1)
  71. try:
  72. log('[I] Livestream downloading started...', "GREEN")
  73. seperator("GREEN")
  74. log('[I] Username : ' + record, "GREEN")
  75. print_status(False)
  76. log('[I] MPD URL : ' + mpd_url, "GREEN")
  77. seperator("GREEN")
  78. log('[I] Downloading livestream... press [CTRL+C] to abort.', "GREEN")
  79. if (settings.run_at_start is not "None"):
  80. try:
  81. thread = threading.Thread(target=run_script, args=(settings.run_at_start,))
  82. thread.daemon = True
  83. thread.start()
  84. log("[I] Executed file to run at start.", "GREEN")
  85. except Exception as e:
  86. log('[W] Could not run file: ' + str(e), "YELLOW")
  87. comment_thread_worker = None
  88. if settings.save_comments.title() == "True":
  89. try:
  90. comments_json_file = settings.save_path + '{}_{}_{}_{}_live_comments.json'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  91. comment_thread_worker = threading.Thread(target=get_live_comments, args=(api, broadcast, comments_json_file, dl,))
  92. comment_thread_worker.start()
  93. except Exception as e:
  94. log('[E] An error occurred while checking comments: ' + e, "RED")
  95. dl.run()
  96. seperator("GREEN")
  97. log('[I] The livestream has ended.\n[I] Time recorded : {}\n[I] Stream duration : {}'.format(get_stream_duration(int(settings.current_time)), get_stream_duration(broadcast['published_time'])), "YELLOW")
  98. seperator("GREEN")
  99. stitch_video(dl, broadcast, comment_thread_worker)
  100. except KeyboardInterrupt:
  101. seperator("GREEN")
  102. log('[I] Download has been aborted by the user.\n[I] Time recorded : {}\n[I] Stream duration : {}'.format(get_stream_duration(int(settings.current_time)), get_stream_duration(broadcast['published_time'])), "YELLOW")
  103. seperator("GREEN")
  104. if not dl.is_aborted:
  105. dl.stop()
  106. stitch_video(dl, broadcast, comment_thread_worker)
  107. def stitch_video(dl, broadcast, comment_thread_worker):
  108. if comment_thread_worker and comment_thread_worker.is_alive():
  109. log("[I] Ending comment saving process...", "GREEN")
  110. comment_thread_worker.join()
  111. if (settings.run_at_finish is not "None"):
  112. try:
  113. thread = threading.Thread(target=run_script, args=(settings.run_at_finish,))
  114. thread.daemon = True
  115. thread.start()
  116. log("[I] Executed file to run at finish.", "GREEN")
  117. except Exception as e:
  118. log('[W] Could not run file: ' + e, "YELLOW")
  119. log('[I] Stitching downloaded files into video...', "GREEN")
  120. output_file = settings.save_path + '{}_{}_{}_{}_live.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  121. try:
  122. if settings.clear_temp_files.title() == "True":
  123. dl.stitch(output_file, cleartempfiles=True)
  124. else:
  125. dl.stitch(output_file, cleartempfiles=False)
  126. log('[I] Successfully stitched downloaded files into video.', "GREEN")
  127. seperator("GREEN")
  128. sys.exit(0)
  129. except Exception as e:
  130. log('[E] Could not stitch downloaded files: ' + str(e), "RED")
  131. seperator("GREEN")
  132. sys.exit(1)
  133. def get_user_info(record):
  134. try:
  135. log('[I] Checking user "' + record + '"...', "GREEN")
  136. user_res = api.username_info(record)
  137. user_id = user_res['user']['pk']
  138. except Exception as e:
  139. log('[E] Could not get user info: ' + str(e), "RED")
  140. seperator("GREEN")
  141. sys.exit(1)
  142. except KeyboardInterrupt:
  143. log('[W] Aborted checking for user.', "YELLOW")
  144. seperator("GREEN")
  145. sys.exit(1)
  146. get_livestreams(user_id)
  147. if settings.save_replays.title() == "True":
  148. get_replays(user_id)
  149. else:
  150. seperator("GREEN")
  151. log("[I] Replay saving is disabled either with a flag or in the config file.", "BLUE")
  152. seperator("GREEN")
  153. sys.exit(0)
  154. def get_livestreams(user_id):
  155. try:
  156. seperator("GREEN")
  157. log('[I] Checking for ongoing livestreams...', "GREEN")
  158. broadcast = api.user_broadcast(user_id)
  159. if (broadcast is None):
  160. raise NoLivestreamException('There are no livestreams available.')
  161. else:
  162. try:
  163. record_stream(broadcast)
  164. except Exception as e:
  165. log('[E] An error occurred while trying to record livestream: ' + str(e), "RED")
  166. seperator("GREEN")
  167. sys.exit(1)
  168. except NoLivestreamException as e:
  169. log('[I] ' + str(e), "YELLOW")
  170. except Exception as e:
  171. if (e.__class__.__name__ is not NoLivestreamException):
  172. log('[E] Could not get livestreams info: ' + str(e), "RED")
  173. seperator("GREEN")
  174. sys.exit(1)
  175. def get_replays(user_id):
  176. try:
  177. seperator("GREEN")
  178. log('[I] Checking for available replays...', "GREEN")
  179. user_story_feed = api.user_story_feed(user_id)
  180. broadcasts = user_story_feed.get('post_live_item', {}).get('broadcasts', [])
  181. except Exception as e:
  182. log('[E] Could not get replay info: ' + str(e), "RED")
  183. seperator("GREEN")
  184. sys.exit(1)
  185. try:
  186. if (len(broadcasts) == 0):
  187. raise NoReplayException('There are no replays available.')
  188. else:
  189. log("[I] Available replays have been found to download, press [CTRL+C] to abort.", "GREEN")
  190. seperator("GREEN")
  191. for index, broadcast in enumerate(broadcasts):
  192. exists = False
  193. if sys.version.split(' ')[0].startswith('2'):
  194. directories = (os.walk(settings.save_path).next()[1])
  195. else:
  196. directories = (os.walk(settings.save_path).__next__()[1])
  197. for directory in directories:
  198. if (str(broadcast['id']) in directory) and ("_live_" not in directory):
  199. log("[W] Already downloaded a replay with ID '" + str(broadcast['id']) + "', skipping...", "GREEN")
  200. exists = True
  201. if not exists:
  202. current = index + 1
  203. log("[I] Downloading replay " + str(current) + " of " + str(len(broadcasts)) + " with ID '" + str(broadcast['id']) + "'...", "GREEN")
  204. current_time = str(int(time.time()))
  205. output_dir = settings.save_path + '{}_{}_{}_{}_replay_downloads'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  206. dl = replay.Downloader(
  207. mpd=broadcast['dash_manifest'],
  208. output_dir=output_dir,
  209. user_agent=api.user_agent)
  210. if settings.clear_temp_files.title() == "True":
  211. replay_saved = dl.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time), cleartempfiles=True)
  212. else:
  213. replay_saved = dl.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time), cleartempfiles=False)
  214. if (len(replay_saved) == 1):
  215. log("[I] Finished downloading replay " + str(current) + " of " + str(len(broadcasts)) + ".", "GREEN")
  216. seperator("GREEN")
  217. else:
  218. log("[W] No output video file was made, please merge the files manually.", "YELLOW")
  219. log("[W] Check if ffmpeg is available by running ffmpeg in your terminal.", "YELLOW")
  220. log("", "GREEN")
  221. if settings.save_comments.title() == "True":
  222. log("[I] Checking for available comments to save...", "GREEN")
  223. comments_json_file = settings.save_path + '{}_{}_{}_{}_replay_comments.json'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  224. get_replay_comments(api, broadcast, comments_json_file, dl)
  225. log("[I] Finished downloading available replays.", "GREEN")
  226. seperator("GREEN")
  227. sys.exit(0)
  228. except NoReplayException as e:
  229. log('[I] ' + str(e), "YELLOW")
  230. seperator("GREEN")
  231. sys.exit(0)
  232. except Exception as e:
  233. log('[E] Could not save replay: ' + str(e), "RED")
  234. seperator("GREEN")
  235. sys.exit(1)
  236. except KeyboardInterrupt:
  237. seperator("GREEN")
  238. log('[I] Download has been aborted by the user.', "YELLOW")
  239. seperator("GREEN")
  240. try:
  241. shutil.rmtree(output_dir)
  242. except Exception as e:
  243. log("[E] Could not remove temp folder: " + str(e), "RED")
  244. sys.exit(1)
  245. sys.exit(0)
  246. def get_replay_comments(api, broadcast, comments_json_file, dl):
  247. cdl = CommentsDownloader(
  248. api=api, broadcast=broadcast, destination_file=comments_json_file)
  249. cdl.get_replay()
  250. if cdl.comments:
  251. comments_log_file = comments_json_file.replace('.json', '.log')
  252. CommentsDownloader.generate_log(
  253. cdl.comments, broadcast['published_time'], comments_log_file,
  254. comments_delay=0)
  255. log("[I] Successfully saved comments to logfile.", "GREEN")
  256. seperator("GREEN")
  257. else:
  258. log("[I] There are no available comments to save.", "GREEN")
  259. seperator("GREEN")
  260. def get_live_comments(api, broadcast, comments_json_file, dl):
  261. cdl = CommentsDownloader(
  262. api=api, broadcast=broadcast, destination_file=comments_json_file)
  263. first_comment_created_at = 0
  264. try:
  265. while not dl.is_aborted:
  266. if 'initial_buffered_duration' not in broadcast and dl.initial_buffered_duration:
  267. broadcast['initial_buffered_duration'] = dl.initial_buffered_duration
  268. cdl.broadcast = broadcast
  269. first_comment_created_at = cdl.get_live(first_comment_created_at)
  270. except ClientError as e:
  271. if not 'media has been deleted' in e.error_response:
  272. log("[W] Comment collection ClientError: %d %s" % (e.code, e.error_response), "YELLOW")
  273. try:
  274. if cdl.comments:
  275. log("[I] Checking for available comments to save...", "GREEN")
  276. cdl.save()
  277. comments_log_file = comments_json_file.replace('.json', '.log')
  278. CommentsDownloader.generate_log(
  279. cdl.comments, settings.current_time, comments_log_file,
  280. comments_delay=dl.initial_buffered_duration)
  281. log("[I] Successfully saved comments to logfile.", "GREEN")
  282. seperator("GREEN")
  283. else:
  284. log("[I] There are no available comments to save.", "GREEN")
  285. seperator("GREEN")
  286. except Exception as e:
  287. log('[E] Could not save comments to logfile: ' + str(e), "RED")