downloader.py 13 KB

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