downloader.py 12 KB

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