downloader.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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(broadcast):
  35. try:
  36. started_mins, started_secs = divmod((int(time.time()) - broadcast['published_time']), 60)
  37. started_label = '%d minutes' % started_mins
  38. if started_secs:
  39. started_label += ' and %d seconds' % started_secs
  40. return started_label
  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).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. (Duration: ' + get_stream_duration(broadcast) + ")", "GREEN")
  98. seperator("GREEN")
  99. stitch_video(dl, broadcast, comment_thread_worker)
  100. except KeyboardInterrupt:
  101. seperator("GREEN")
  102. log('[W] Download has been aborted.', "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. get_livestreams(user_id)
  143. if settings.save_replays.title() == "True":
  144. get_replays(user_id)
  145. else:
  146. log("", "BLUE")
  147. log("[I] Replay saving is disabled either with a flag or in the config file.", "BLUE")
  148. seperator("GREEN")
  149. sys.exit(0)
  150. def get_livestreams(user_id):
  151. try:
  152. seperator("GREEN")
  153. log('[I] Checking for ongoing livestreams...', "GREEN")
  154. broadcast = api.user_broadcast(user_id)
  155. if (broadcast is None):
  156. raise NoLivestreamException('There are no livestreams available.')
  157. else:
  158. record_stream(broadcast)
  159. except NoLivestreamException as e:
  160. log('[I] ' + str(e), "YELLOW")
  161. except Exception as e:
  162. if (e.__class__.__name__ is not NoLivestreamException):
  163. log('[E] Could not get livestreams info: ' + str(e), "RED")
  164. seperator("GREEN")
  165. sys.exit(1)
  166. def get_replays(user_id):
  167. try:
  168. seperator("GREEN")
  169. log('[I] Checking for available replays...', "GREEN")
  170. user_story_feed = api.user_story_feed(user_id)
  171. broadcasts = user_story_feed.get('post_live_item', {}).get('broadcasts', [])
  172. except Exception as e:
  173. log('[E] Could not get replay info: ' + str(e), "RED")
  174. seperator("GREEN")
  175. sys.exit(1)
  176. try:
  177. if (len(broadcasts) == 0):
  178. raise NoReplayException('There are no replays available.')
  179. else:
  180. log("[I] Available replays have been found to download, press [CTRL+C] to abort.", "GREEN")
  181. seperator("GREEN")
  182. for index, broadcast in enumerate(broadcasts):
  183. exists = False
  184. if sys.version.split(' ')[0].startswith('2'):
  185. directories = (os.walk(settings.save_path).next()[1])
  186. else:
  187. directories = (os.walk(settings.save_path).__next__()[1])
  188. for directory in directories:
  189. if (str(broadcast['id']) in directory) and ("_live_" not in directory):
  190. log("[W] Already downloaded a replay with ID '" + str(broadcast['id']) + "', skipping...", "GREEN")
  191. exists = True
  192. if exists is False:
  193. current = index + 1
  194. log("[I] Downloading replay " + str(current) + " of " + str(len(broadcasts)) + " with ID '" + str(broadcast['id']) + "'...", "GREEN")
  195. current_time = str(int(time.time()))
  196. output_dir = settings.save_path + '{}_{}_{}_{}_replay_downloads'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  197. dl = replay.Downloader(
  198. mpd=broadcast['dash_manifest'],
  199. output_dir=output_dir,
  200. user_agent=api.user_agent)
  201. if settings.clear_temp_files.title() == "True":
  202. replay_saved = dl.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time), cleartempfiles=True)
  203. else:
  204. replay_saved = dl.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time), cleartempfiles=False)
  205. if (len(replay_saved) == 1):
  206. log("[I] Finished downloading replay " + str(current) + " of " + str(len(broadcasts)) + ".", "GREEN")
  207. seperator("GREEN")
  208. else:
  209. log("[W] No output video file was made, please merge the files manually.", "YELLOW")
  210. log("[W] Check if ffmpeg is available by running ffmpeg in your terminal.", "YELLOW")
  211. log("", "GREEN")
  212. if settings.save_comments.title() == "True":
  213. log("[I] Checking for available comments to save...", "GREEN")
  214. comments_json_file = settings.save_path + '{}_{}_{}_{}_replay_comments.json'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  215. get_replay_comments(api, broadcast, comments_json_file, dl)
  216. log("[I] Finished downloading available replays.", "GREEN")
  217. seperator("GREEN")
  218. sys.exit(0)
  219. except NoReplayException as e:
  220. log('[I] ' + str(e), "YELLOW")
  221. seperator("GREEN")
  222. sys.exit(0)
  223. except Exception as e:
  224. log('[E] Could not save replay: ' + str(e), "RED")
  225. seperator("GREEN")
  226. sys.exit(1)
  227. except KeyboardInterrupt:
  228. log("", "GREEN")
  229. log('[W] Download has been aborted by the user.', "YELLOW")
  230. try:
  231. shutil.rmtree(output_dir)
  232. except Exception as e:
  233. log("[E] Could not remove temp folder: " + str(e), "RED")
  234. sys.exit(1)
  235. sys.exit(0)
  236. def get_replay_comments(api, broadcast, comments_json_file, dl):
  237. cdl = CommentsDownloader(
  238. api=api, broadcast=broadcast, destination_file=comments_json_file)
  239. cdl.get_replay()
  240. if cdl.comments:
  241. comments_log_file = comments_json_file.replace('.json', '.log')
  242. CommentsDownloader.generate_log(
  243. cdl.comments, broadcast['published_time'], comments_log_file,
  244. comments_delay=0)
  245. log("[I] Successfully saved comments to logfile.", "GREEN")
  246. seperator("GREEN")
  247. else:
  248. log("[I] There are no available comments to save.", "GREEN")
  249. seperator("GREEN")
  250. def get_live_comments(api, broadcast, comments_json_file, dl):
  251. cdl = CommentsDownloader(
  252. api=api, broadcast=broadcast, destination_file=comments_json_file)
  253. first_comment_created_at = 0
  254. try:
  255. while not dl.is_aborted:
  256. if 'initial_buffered_duration' not in broadcast and dl.initial_buffered_duration:
  257. broadcast['initial_buffered_duration'] = dl.initial_buffered_duration
  258. cdl.broadcast = broadcast
  259. first_comment_created_at = cdl.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 cdl.comments:
  265. log("[I] Checking for available comments to save...", "GREEN")
  266. cdl.save()
  267. comments_log_file = comments_json_file.replace('.json', '.log')
  268. CommentsDownloader.generate_log(
  269. cdl.comments, settings.current_time, comments_log_file,
  270. comments_delay=dl.initial_buffered_duration)
  271. log("[I] Successfully saved comments to logfile.", "GREEN")
  272. seperator("GREEN")
  273. else:
  274. log("[I] There are no available comments to save.", "GREEN")
  275. seperator("GREEN")
  276. except Exception as e:
  277. log('[E] Could not save comments to logfile: ' + str(e), "RED")