downloader.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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, ClientThrottledError
  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}".\n[E] Error message: {:s}\n[E] Code: {:d}\n[E] Response: {:s}'.format(user_to_record, str(e), e.code, e.error_response), "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. try:
  159. broadcasts = instagram_api.user_story_feed(user_id)
  160. livestream = broadcasts.get('broadcast')
  161. replays = broadcasts.get('post_live_item', {}).get('broadcasts', [])
  162. if livestream:
  163. seperator("GREEN")
  164. download_livestream(livestream)
  165. else:
  166. log('[I] There are no available livestreams.', "YELLOW")
  167. if settings.save_replays.title() == "True":
  168. if replays:
  169. seperator("GREEN")
  170. download_replays(replays)
  171. else:
  172. log('[I] There are no available replays.', "YELLOW")
  173. else:
  174. log("[I] Replay saving is disabled either with a flag or in the config file.", "BLUE")
  175. seperator("GREEN")
  176. except Exception as e:
  177. log('[E] Could not finish checking: {:s}'.format(str(e)), "RED")
  178. except ClientThrottledError as cte:
  179. log('[E] Could not check because you are making too many requests at this time.', "RED")
  180. log('[E] Error response: {:s}'.format(str(cte)), "RED")
  181. def download_replays(broadcasts):
  182. try:
  183. log("[I] Downloading replays... press [CTRL+C] to abort.", "GREEN")
  184. seperator("GREEN")
  185. for replay_index, broadcast in enumerate(broadcasts):
  186. exists = False
  187. if sys.version.split(' ')[0].startswith('2'):
  188. directories = (os.walk(settings.save_path).next()[1])
  189. else:
  190. directories = (os.walk(settings.save_path).__next__()[1])
  191. for directory in directories:
  192. if (str(broadcast['id']) in directory) and ("_live_" not in directory):
  193. log("[W] Already downloaded a replay with ID '{:s}'.".format(str(broadcast['id'])), "YELLOW")
  194. exists = True
  195. if not exists:
  196. current = replay_index + 1
  197. log("[I] Downloading replay {:s} of {:s} with ID '{:s}'...".format(str(current), str(len(broadcasts)), str(broadcast['id'])), "GREEN")
  198. current_time = str(int(time.time()))
  199. output_dir = settings.save_path + '{}_{}_{}_{}_replay_downloads'.format(settings.current_date, user_to_record, broadcast['id'], settings.current_time)
  200. broadcast_downloader = replay.Downloader(
  201. mpd=broadcast['dash_manifest'],
  202. output_dir=output_dir,
  203. user_agent=instagram_api.user_agent)
  204. if settings.clear_temp_files.title() == "True":
  205. replay_saved = broadcast_downloader.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, user_to_record, broadcast['id'], settings.current_time), cleartempfiles=True)
  206. else:
  207. replay_saved = broadcast_downloader.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, user_to_record, broadcast['id'], settings.current_time), cleartempfiles=False)
  208. if settings.save_comments.title() == "True":
  209. log("[I] Checking for available comments to save...", "GREEN")
  210. comments_json_file = settings.save_path + '{}_{}_{}_{}_replay_comments.json'.format(settings.current_date, user_to_record, broadcast['id'], settings.current_time)
  211. get_replay_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader)
  212. if (len(replay_saved) == 1):
  213. log("[I] Finished downloading replay {:s} of {:s}.".format(str(current), str(len(broadcasts))), "GREEN")
  214. if (current != len(broadcasts)):
  215. seperator("GREEN")
  216. else:
  217. log("[W] No output video file was made, please merge the files manually if possible.", "YELLOW")
  218. log("[W] Check if ffmpeg is available by running ffmpeg in your terminal/cmd prompt.", "YELLOW")
  219. log("", "GREEN")
  220. seperator("GREEN")
  221. log("[I] Finished downloading all available replays.", "GREEN")
  222. seperator("GREEN")
  223. sys.exit(0)
  224. except Exception as e:
  225. log('[E] Could not save replay: {:s}'.format(str(e)), "RED")
  226. seperator("GREEN")
  227. sys.exit(1)
  228. except KeyboardInterrupt:
  229. seperator("GREEN")
  230. log('[I] The download has been aborted by the user.', "YELLOW")
  231. seperator("GREEN")
  232. try:
  233. shutil.rmtree(output_dir)
  234. except Exception as e:
  235. log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
  236. sys.exit(1)
  237. sys.exit(0)
  238. def get_replay_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  239. comments_downloader = CommentsDownloader(
  240. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  241. comments_downloader.get_replay()
  242. try:
  243. if comments_downloader.comments:
  244. comments_log_file = comments_json_file.replace('.json', '.log')
  245. CommentsDownloader.generate_log(
  246. comments_downloader.comments, broadcast['published_time'], comments_log_file,
  247. comments_delay=0)
  248. if len(comments_downloader.comments) == 1:
  249. log("[I] Successfully saved 1 comment to logfile.", "GREEN")
  250. else:
  251. log("[I] Successfully saved {} comments to logfile.".format(len(comments_downloader.comments)), "GREEN")
  252. else:
  253. log("[I] There are no available comments to save.", "GREEN")
  254. except Exception as e:
  255. log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")
  256. def get_live_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  257. comments_downloader = CommentsDownloader(
  258. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  259. first_comment_created_at = 0
  260. try:
  261. while not broadcast_downloader.is_aborted:
  262. if 'initial_buffered_duration' not in broadcast and broadcast_downloader.initial_buffered_duration:
  263. broadcast['initial_buffered_duration'] = broadcast_downloader.initial_buffered_duration
  264. comments_downloader.broadcast = broadcast
  265. first_comment_created_at = comments_downloader.get_live(first_comment_created_at)
  266. except ClientError as e:
  267. if not 'media has been deleted' in e.error_response:
  268. log("[W] Comment collection ClientError: %d %s" % (e.code, e.error_response), "YELLOW")
  269. try:
  270. if comments_downloader.comments:
  271. comments_downloader.save()
  272. comments_log_file = comments_json_file.replace('.json', '.log')
  273. CommentsDownloader.generate_log(
  274. comments_downloader.comments, settings.current_time, comments_log_file,
  275. comments_delay=broadcast_downloader.initial_buffered_duration)
  276. if len(comments_downloader.comments) == 1:
  277. log("[I] Successfully saved 1 comment to logfile.", "GREEN")
  278. else:
  279. log("[I] Successfully saved {} comments to logfile.".format(len(comments_downloader.comments)), "GREEN")
  280. seperator("GREEN")
  281. else:
  282. log("[I] There are no available comments to save.", "GREEN")
  283. seperator("GREEN")
  284. except Exception as e:
  285. log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")