downloader.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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. log('[I] Viewers : ' + str(int(viewers)) + " watching", "GREEN")
  49. log('[I] Airing time : ' + get_stream_duration(broadcast).title(), "GREEN")
  50. log('[I] Status : ' + heartbeat_info['broadcast_status'].title(), "GREEN")
  51. if sep:
  52. seperator("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. seperator("GREEN")
  73. log('[I] Livestream downloading started...', "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. if settings.save_comments.title() == "True":
  88. try:
  89. comments_json_file = settings.save_path + '{}_{}_{}_{}_live_comments.json'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  90. comment_thread_worker = None
  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. log('[I] The livestream has ended. (Duration: ' + get_stream_duration(broadcast) + ")", "GREEN")
  97. stitch_video(dl, broadcast, comment_thread_worker)
  98. except KeyboardInterrupt:
  99. seperator("GREEN")
  100. log('[W] Download has been aborted.', "YELLOW")
  101. seperator("GREEN")
  102. if not dl.is_aborted:
  103. dl.stop()
  104. stitch_video(dl, broadcast, comment_thread_worker)
  105. def stitch_video(dl, broadcast, comment_thread_worker):
  106. if comment_thread_worker and comment_thread_worker.is_alive():
  107. log("[I] Ending comment saving process...", "GREEN")
  108. comment_thread_worker.join()
  109. if (settings.run_at_finish is not "None"):
  110. try:
  111. thread = threading.Thread(target=run_script, args=(settings.run_at_finish,))
  112. thread.daemon = True
  113. thread.start()
  114. log("[I] Executed file to run at finish.", "GREEN")
  115. except Exception as e:
  116. log('[W] Could not run file: ' + e, "YELLOW")
  117. log('[I] Stitching downloaded files into video...', "GREEN")
  118. output_file = settings.save_path + '{}_{}_{}_{}_live.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  119. try:
  120. if settings.clear_temp_files.title() == "True":
  121. dl.stitch(output_file, cleartempfiles=True)
  122. else:
  123. dl.stitch(output_file, cleartempfiles=False)
  124. log('[I] Successfully stitched downloaded files into video.', "GREEN")
  125. seperator("GREEN")
  126. sys.exit(0)
  127. except Exception as e:
  128. log('[E] Could not stitch downloaded files: ' + str(e), "RED")
  129. seperator("GREEN")
  130. sys.exit(1)
  131. def get_user_info(record):
  132. try:
  133. log('[I] Checking user "' + record + '"...', "GREEN")
  134. user_res = api.username_info(record)
  135. user_id = user_res['user']['pk']
  136. except Exception as e:
  137. log('[E] Could not get user info: ' + str(e), "RED")
  138. seperator("GREEN")
  139. sys.exit(1)
  140. get_livestreams(user_id)
  141. if settings.save_replays.title() == "True":
  142. get_replays(user_id)
  143. else:
  144. log("", "BLUE")
  145. log("[I] Replay saving is disabled either with a flag or in the config file.", "BLUE")
  146. seperator("GREEN")
  147. sys.exit(0)
  148. def get_livestreams(user_id):
  149. try:
  150. seperator("GREEN")
  151. log('[I] Checking for ongoing livestreams...', "GREEN")
  152. broadcast = api.user_broadcast(user_id)
  153. if (broadcast is None):
  154. raise NoLivestreamException('There are no livestreams available.')
  155. else:
  156. record_stream(broadcast)
  157. except NoLivestreamException as e:
  158. log('[I] ' + str(e), "BLUE")
  159. except Exception as e:
  160. if (e.__class__.__name__ is not NoLivestreamException):
  161. log('[E] Could not get livestreams info: ' + str(e), "RED")
  162. seperator("GREEN")
  163. sys.exit(1)
  164. def get_replays(user_id):
  165. try:
  166. seperator("GREEN")
  167. log('[I] Checking for available replays...', "GREEN")
  168. user_story_feed = api.user_story_feed(user_id)
  169. broadcasts = user_story_feed.get('post_live_item', {}).get('broadcasts', [])
  170. except Exception as e:
  171. log('[E] Could not get replay info: ' + str(e), "RED")
  172. seperator("GREEN")
  173. sys.exit(1)
  174. try:
  175. if (len(broadcasts) == 0):
  176. raise NoReplayException('There are no replays available.')
  177. else:
  178. log("[I] Available replays have been found to download, press [CTRL+C] to abort.", "GREEN")
  179. log("", "GREEN")
  180. for index, broadcast in enumerate(broadcasts):
  181. exists = False
  182. if sys.version.split(' ')[0].startswith('2'):
  183. directories = (os.walk(settings.save_path).next()[1])
  184. else:
  185. directories = (os.walk(settings.save_path).__next__()[1])
  186. for directory in directories:
  187. if (str(broadcast['id']) in directory) and ("_live_" not in directory):
  188. log("[W] Already downloaded a replay with ID '" + str(broadcast['id']) + "', skipping...", "GREEN")
  189. exists = True
  190. if exists is False:
  191. current = index + 1
  192. log("[I] Downloading replay " + str(current) + " of " + str(len(broadcasts)) + " with ID '" + str(broadcast['id']) + "'...", "GREEN")
  193. current_time = str(int(time.time()))
  194. output_dir = settings.save_path + '{}_{}_{}_{}_replay_downloads'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  195. dl = replay.Downloader(
  196. mpd=broadcast['dash_manifest'],
  197. output_dir=output_dir,
  198. user_agent=api.user_agent)
  199. if settings.clear_temp_files.title() == "True":
  200. replay_saved = dl.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time), cleartempfiles=True)
  201. else:
  202. replay_saved = dl.download(settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, record, broadcast['id'], settings.current_time), cleartempfiles=False)
  203. if (len(replay_saved) == 1):
  204. log("[I] Finished downloading replay " + str(current) + " of " + str(len(broadcasts)) + ".", "GREEN")
  205. seperator("GREEN")
  206. if settings.save_comments.title() == "True":
  207. log("[I] Checking for available comments to save...", "GREEN")
  208. comments_json_file = settings.save_path + '{}_{}_{}_{}_replay_comments.json'.format(settings.current_date, record, broadcast['id'], settings.current_time)
  209. get_replay_comments(api, broadcast, comments_json_file, dl)
  210. else:
  211. log("[W] No output video file was made, please merge the files manually.", "RED")
  212. log("[W] Check if ffmpeg is available by running ffmpeg in your terminal.", "RED")
  213. log("", "GREEN")
  214. log("[I] Finished downloading available replays.", "GREEN")
  215. seperator("GREEN")
  216. sys.exit(0)
  217. except NoReplayException as e:
  218. log('[I] ' + str(e), "BLUE")
  219. seperator("GREEN")
  220. sys.exit(0)
  221. except Exception as e:
  222. log('[E] Could not save replay: ' + str(e), "RED")
  223. seperator("GREEN")
  224. sys.exit(1)
  225. except KeyboardInterrupt:
  226. log("", "GREEN")
  227. log('[W] Download has been aborted by the user.', "YELLOW")
  228. try:
  229. shutil.rmtree(output_dir)
  230. except Exception as e:
  231. log("[E] Could not remove temp folder: " + str(e), "RED")
  232. sys.exit(1)
  233. sys.exit(0)
  234. def get_replay_comments(api, broadcast, comments_json_file, dl):
  235. cdl = CommentsDownloader(
  236. api=api, broadcast=broadcast, destination_file=comments_json_file)
  237. cdl.get_replay()
  238. if cdl.comments:
  239. comments_log_file = comments_json_file.replace('.json', '.log')
  240. CommentsDownloader.generate_log(
  241. cdl.comments, broadcast['published_time'], comments_log_file,
  242. comments_delay=0)
  243. log("[I] Successfully saved comments to logfile.", "GREEN")
  244. seperator("GREEN")
  245. else:
  246. log("[I] There are no available comments to save.", "GREEN")
  247. seperator("GREEN")
  248. def get_live_comments(api, broadcast, comments_json_file, dl):
  249. cdl = CommentsDownloader(
  250. api=api, broadcast=broadcast, destination_file=comments_json_file)
  251. first_comment_created_at = 0
  252. try:
  253. while not dl.is_aborted:
  254. if 'initial_buffered_duration' not in broadcast and dl.initial_buffered_duration:
  255. broadcast['initial_buffered_duration'] = dl.initial_buffered_duration
  256. cdl.broadcast = broadcast
  257. first_comment_created_at = cdl.get_live(first_comment_created_at)
  258. except ClientError as e:
  259. if not 'media has been deleted' in e.error_response:
  260. log("[W] Comment collection ClientError: %d %s" % (e.code, e.error_response), "YELLOW")
  261. try:
  262. if cdl.comments:
  263. log("[I] Checking for available comments to save...", "GREEN")
  264. cdl.save()
  265. comments_log_file = comments_json_file.replace('.json', '.log')
  266. CommentsDownloader.generate_log(
  267. cdl.comments, settings.current_time, comments_log_file,
  268. comments_delay=dl.initial_buffered_duration)
  269. log("[I] Successfully saved comments to logfile.", "GREEN")
  270. seperator("GREEN")
  271. else:
  272. log("[I] There are no available comments to save.", "GREEN")
  273. seperator("GREEN")
  274. except Exception as e:
  275. log('[E] Could not save comments to logfile: ' + str(e), "RED")