downloader.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import os
  2. import shutil
  3. import subprocess
  4. import sys
  5. import threading
  6. import time
  7. import shlex
  8. from instagram_private_api import ClientConnectionError
  9. from instagram_private_api import ClientError
  10. from instagram_private_api import ClientThrottledError
  11. from instagram_private_api_extensions import live
  12. from instagram_private_api_extensions import replay
  13. from .comments import CommentsDownloader
  14. from .logger import log
  15. from .logger import seperator
  16. def main(instagram_api_arg, record_arg, settings_arg):
  17. global instagram_api
  18. global user_to_record
  19. global broadcast
  20. global settings
  21. settings = settings_arg
  22. instagram_api = instagram_api_arg
  23. user_to_record = record_arg
  24. get_user_info(user_to_record)
  25. def run_command(command):
  26. try:
  27. FNULL = open(os.devnull, 'w')
  28. subprocess.Popen(shlex.split(command), stdout=FNULL, stderr=subprocess.STDOUT)
  29. except OSError as e:
  30. pass
  31. def get_stream_duration(compare_time, broadcast=None):
  32. try:
  33. had_wrong_time = False
  34. if broadcast:
  35. if (int(time.time()) < int(compare_time)):
  36. had_wrong_time = True
  37. corrected_compare_time = int(compare_time) - 5
  38. record_time = int(time.time()) - int(corrected_compare_time)
  39. else:
  40. record_time = int(time.time()) - int(compare_time)
  41. stream_time = int(time.time()) - int(broadcast.get('published_time'))
  42. stream_started_mins, stream_started_secs = divmod(stream_time - record_time, 60)
  43. else:
  44. if (int(time.time()) < int(compare_time)):
  45. had_wrong_time = True
  46. corrected_compare_time = int(compare_time) - 5
  47. stream_started_mins, stream_started_secs = divmod((int(time.time()) - int(corrected_compare_time)), 60)
  48. else:
  49. stream_started_mins, stream_started_secs = divmod((int(time.time()) - int(compare_time)), 60)
  50. stream_duration_str = '%d minutes' % stream_started_mins
  51. if stream_started_secs:
  52. stream_duration_str += ' and %d seconds' % stream_started_secs
  53. if had_wrong_time:
  54. return stream_duration_str + " (corrected)"
  55. else:
  56. return stream_duration_str
  57. except Exception as e:
  58. print(str(e))
  59. return "Not available"
  60. def download_livestream(broadcast):
  61. try:
  62. def print_status(sep=True):
  63. heartbeat_info = instagram_api.broadcast_heartbeat_and_viewercount(broadcast.get('id'))
  64. viewers = broadcast.get('viewer_count', 0)
  65. if sep:
  66. seperator("GREEN")
  67. log('[I] Viewers : {:s} watching'.format(str(int(viewers))), "GREEN")
  68. log('[I] Airing time : {:s}'.format(get_stream_duration(broadcast.get('published_time'))), "GREEN")
  69. log('[I] Status : {:s}'.format(heartbeat_info.get('broadcast_status').title()), "GREEN")
  70. return heartbeat_info.get('broadcast_status') not in ['active', 'interrupted']
  71. mpd_url = (broadcast.get('dash_manifest')
  72. or broadcast.get('dash_abr_playback_url')
  73. or broadcast.get('dash_playback_url'))
  74. output_dir = settings.save_path + '{}_{}_{}_{}_live_downloads'.format(settings.current_date, user_to_record, broadcast.get('id'), settings.current_time)
  75. broadcast_downloader = live.Downloader(
  76. mpd=mpd_url,
  77. output_dir=output_dir,
  78. user_agent=instagram_api.user_agent,
  79. max_connection_error_retry=3,
  80. duplicate_etag_retry=30,
  81. callback_check=print_status,
  82. mpd_download_timeout=3,
  83. download_timeout=3)
  84. except Exception as e:
  85. log('[E] Could not start downloading livestream: {:s}'.format(str(e)), "RED")
  86. seperator("GREEN")
  87. sys.exit(1)
  88. try:
  89. log('[I] Livestream found, beginning download...', "GREEN")
  90. broadcast_owner = broadcast.get('broadcast_owner', {}).get('username')
  91. try:
  92. broadcast_guest = broadcast.get('cobroadcasters', {})[0].get('username')
  93. except:
  94. broadcast_guest = None
  95. if (broadcast_owner != user_to_record):
  96. log('[I] This livestream is a dual-live, the owner is "{}".'.format(broadcast_owner), "BLUE")
  97. broadcast_guest = None
  98. if broadcast_guest:
  99. log('[I] This livestream is a dual-live, the guest is "{}".'.format(broadcast_guest), "BLUE")
  100. seperator("GREEN")
  101. log('[I] Username : {:s}'.format(user_to_record), "GREEN")
  102. print_status(False)
  103. log('[I] MPD URL : {:s}'.format(mpd_url), "GREEN")
  104. seperator("GREEN")
  105. open(os.path.join(output_dir,'folder.lock'), 'a').close()
  106. log('[I] Downloading livestream... press [CTRL+C] to abort.', "GREEN")
  107. if (settings.run_at_start is not "None"):
  108. try:
  109. thread = threading.Thread(target=run_command, args=(settings.run_at_start,))
  110. thread.daemon = True
  111. thread.start()
  112. log("[I] Command executed: \033[94m{:s}".format(settings.run_at_start), "GREEN")
  113. except Exception as e:
  114. log('[W] Could not execute command: {:s}'.format(str(e)), "YELLOW")
  115. comment_thread_worker = None
  116. if settings.save_comments.title() == "True":
  117. try:
  118. comments_json_file = os.path.join(output_dir, '{}_{}_{}_{}_live_comments.json'.format(settings.current_date, user_to_record, broadcast.get('id'), settings.current_time))
  119. comment_thread_worker = threading.Thread(target=get_live_comments, args=(instagram_api, broadcast, comments_json_file, broadcast_downloader,))
  120. comment_thread_worker.start()
  121. except Exception as e:
  122. log('[E] An error occurred while checking comments: {:s}'.format(str(e)), "RED")
  123. broadcast_downloader.run()
  124. seperator("GREEN")
  125. 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.get('published_time')), get_stream_duration(int(settings.current_time), broadcast)), "YELLOW")
  126. seperator("GREEN")
  127. stitch_video(broadcast_downloader, broadcast, comment_thread_worker)
  128. except KeyboardInterrupt:
  129. seperator("GREEN")
  130. 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.get('published_time')), get_stream_duration(int(settings.current_time), broadcast)), "YELLOW")
  131. seperator("GREEN")
  132. if not broadcast_downloader.is_aborted:
  133. broadcast_downloader.stop()
  134. stitch_video(broadcast_downloader, broadcast, comment_thread_worker)
  135. except Exception as e:
  136. log("[E] Could not download livestream: {:s}".format(str(e)), "RED")
  137. try:
  138. os.remove(os.path.join(output_dir,'folder.lock'))
  139. except OSError:
  140. pass
  141. def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
  142. try:
  143. live_mp4_file = settings.save_path + '{}_{}_{}_{}_live.mp4'.format(settings.current_date, user_to_record, broadcast.get('id'), settings.current_time)
  144. live_folder_path = live_mp4_file.split('.mp4')[0] + "_downloads"
  145. if comment_thread_worker and comment_thread_worker.is_alive():
  146. log("[I] Stopping comment downloading and saving comments (if any)...", "GREEN")
  147. comment_thread_worker.join()
  148. if (settings.run_at_finish is not "None"):
  149. try:
  150. thread = threading.Thread(target=run_command, args=(settings.run_at_finish,))
  151. thread.daemon = True
  152. thread.start()
  153. log("[I] Command executed: \033[94m{:s}".format(settings.run_at_finish), "GREEN")
  154. except Exception as e:
  155. log('[W] Could not execute command: {:s}'.format(str(e)), "YELLOW")
  156. log('[I] Stitching downloaded files into video...', "GREEN")
  157. try:
  158. if settings.clear_temp_files.title() == "True":
  159. broadcast_downloader.stitch(live_mp4_file, cleartempfiles=True)
  160. else:
  161. broadcast_downloader.stitch(live_mp4_file, cleartempfiles=False)
  162. log('[I] Successfully stitched downloaded files into video.', "GREEN")
  163. try:
  164. os.remove(os.path.join(live_folder_path,'folder.lock'))
  165. except OSError:
  166. pass
  167. if settings.clear_temp_files.title() == "True":
  168. try:
  169. shutil.rmtree(live_folder_path)
  170. except Exception as e:
  171. log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
  172. seperator("GREEN")
  173. sys.exit(0)
  174. except ValueError as e:
  175. log('[E] Could not stitch downloaded files: {:s}\n[E] Likely the download duration was too short and no temp files were saved.'.format(str(e)), "RED")
  176. seperator("GREEN")
  177. try:
  178. os.remove(os.path.join(live_folder_path,'folder.lock'))
  179. except OSError:
  180. pass
  181. sys.exit(1)
  182. except Exception as e:
  183. log('[E] Could not stitch downloaded files: {:s}'.format(str(e)), "RED")
  184. seperator("GREEN")
  185. try:
  186. os.remove(os.path.join(live_folder_path,'folder.lock'))
  187. except OSError:
  188. pass
  189. sys.exit(1)
  190. except KeyboardInterrupt:
  191. log('[I] Aborted stitching process, no video was created.', "YELLOW")
  192. seperator("GREEN")
  193. try:
  194. os.remove(os.path.join(live_folder_path,'folder.lock'))
  195. except OSError:
  196. pass
  197. sys.exit(0)
  198. def get_user_info(user_to_record):
  199. try:
  200. user_res = instagram_api.username_info(user_to_record)
  201. user_id = user_res.get('user', {}).get('pk')
  202. except ClientConnectionError as e:
  203. if "timed out" in str(e):
  204. log('[E] Could not get information for "{:s}": The connection has timed out.'.format(user_to_record), "RED")
  205. else:
  206. 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")
  207. seperator("GREEN")
  208. sys.exit(1)
  209. except Exception as e:
  210. 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")
  211. seperator("GREEN")
  212. sys.exit(1)
  213. except KeyboardInterrupt:
  214. log('[W] Aborted getting information for "{:s}", exiting...'.format(user_to_record), "YELLOW")
  215. seperator("GREEN")
  216. sys.exit(1)
  217. log('[I] Getting info for "{:s}" successful.'.format(user_to_record), "GREEN")
  218. get_broadcasts_info(user_id)
  219. def get_broadcasts_info(user_id):
  220. try:
  221. log('[I] Checking for livestreams and replays...', "GREEN")
  222. seperator("GREEN")
  223. broadcasts = instagram_api.user_story_feed(user_id)
  224. livestream = broadcasts.get('broadcast')
  225. replays = broadcasts.get('post_live_item', {}).get('broadcasts', [])
  226. if livestream:
  227. seperator("GREEN")
  228. download_livestream(livestream)
  229. else:
  230. log('[I] There are no available livestreams.', "YELLOW")
  231. if settings.save_replays.title() == "True":
  232. if replays:
  233. seperator("GREEN")
  234. download_replays(replays)
  235. else:
  236. log('[I] There are no available replays.', "YELLOW")
  237. else:
  238. log("[I] Replay saving is disabled either with a flag or in the config file.", "BLUE")
  239. seperator("GREEN")
  240. except Exception as e:
  241. log('[E] Could not finish checking: {:s}'.format(str(e)), "RED")
  242. except ClientThrottledError as cte:
  243. log('[E] Could not check because you are making too many requests at this time.', "RED")
  244. log('[E] Error response: {:s}'.format(str(cte)), "RED")
  245. def download_replays(broadcasts):
  246. try:
  247. log("[I] Downloading replays... press [CTRL+C] to abort.", "GREEN")
  248. seperator("GREEN")
  249. for replay_index, broadcast in enumerate(broadcasts):
  250. exists = False
  251. if sys.version.split(' ')[0].startswith('2'):
  252. directories = (os.walk(settings.save_path).next()[1])
  253. else:
  254. directories = (os.walk(settings.save_path).__next__()[1])
  255. for directory in directories:
  256. if (str(broadcast.get('id')) in directory) and ("_live_" not in directory):
  257. log("[W] Already downloaded a replay with ID '{:s}'.".format(str(broadcast.get('id'))), "YELLOW")
  258. exists = True
  259. if not exists:
  260. current = replay_index + 1
  261. log("[I] Downloading replay {:s} of {:s} with ID '{:s}'...".format(str(current), str(len(broadcasts)), str(broadcast.get('id'))), "GREEN")
  262. current_time = str(int(time.time()))
  263. output_dir = settings.save_path + '{}_{}_{}_{}_replay_downloads'.format(settings.current_date, user_to_record, broadcast.get('id'), settings.current_time)
  264. broadcast_downloader = replay.Downloader(
  265. mpd=broadcast.get('dash_manifest'),
  266. output_dir=output_dir,
  267. user_agent=instagram_api.user_agent)
  268. open(os.path.join(output_dir,'folder.lock'), 'a').close()
  269. replay_mp4_file = settings.save_path + '{}_{}_{}_{}_replay.mp4'.format(settings.current_date, user_to_record, broadcast.get('id'), settings.current_time)
  270. replay_json_file = os.path.join(output_dir, '{}_{}_{}_{}_replay_comments.json'.format(settings.current_date, user_to_record, broadcast.get('id'), settings.current_time))
  271. if settings.clear_temp_files.title() == "True":
  272. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=True)
  273. else:
  274. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=False)
  275. if settings.save_comments.title() == "True":
  276. log("[I] Checking for available comments to save...", "GREEN")
  277. try:
  278. get_replay_comments(instagram_api, broadcast, replay_json_file, broadcast_downloader)
  279. except Exception as e:
  280. log('[E] An error occurred while checking comments: {:s}'.format(str(e)), "RED")
  281. if (len(replay_saved) == 1):
  282. log("[I] Finished downloading replay {:s} of {:s}.".format(str(current), str(len(broadcasts))), "GREEN")
  283. try:
  284. os.remove(os.path.join(output_dir,'folder.lock'))
  285. except OSError:
  286. pass
  287. if (current != len(broadcasts)):
  288. seperator("GREEN")
  289. else:
  290. log("[W] No output video file was made, please merge the files manually if possible.", "YELLOW")
  291. log("[W] Check if ffmpeg is available by running ffmpeg in your terminal/cmd prompt.", "YELLOW")
  292. log("", "GREEN")
  293. seperator("GREEN")
  294. log("[I] Finished downloading all available replays.", "GREEN")
  295. seperator("GREEN")
  296. sys.exit(0)
  297. except Exception as e:
  298. log('[E] Could not save replay: {:s}'.format(str(e)), "RED")
  299. seperator("GREEN")
  300. try:
  301. os.remove(os.path.join(output_dir,'folder.lock'))
  302. except OSError:
  303. pass
  304. sys.exit(1)
  305. except KeyboardInterrupt:
  306. seperator("GREEN")
  307. log('[I] The download has been aborted by the user.', "YELLOW")
  308. seperator("GREEN")
  309. try:
  310. shutil.rmtree(output_dir)
  311. except Exception as e:
  312. log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
  313. sys.exit(1)
  314. sys.exit(0)
  315. def get_replay_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  316. try:
  317. comments_downloader = CommentsDownloader(
  318. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  319. comments_downloader.get_replay()
  320. try:
  321. if comments_downloader.comments:
  322. comments_log_file = comments_json_file.replace('.json', '.log')
  323. CommentsDownloader.generate_log(
  324. comments_downloader.comments, broadcast.get('published_time'), comments_log_file,
  325. comments_delay=0)
  326. if len(comments_downloader.comments) == 1:
  327. log("[I] Successfully saved 1 comment to logfile.", "GREEN")
  328. seperator("GREEN")
  329. return True
  330. else:
  331. log("[I] Successfully saved {} comments to logfile.".format(len(comments_downloader.comments)), "GREEN")
  332. seperator("GREEN")
  333. return True
  334. else:
  335. log("[I] There are no available comments to save.", "GREEN")
  336. return False
  337. except Exception as e:
  338. log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")
  339. return False
  340. except KeyboardInterrupt as e:
  341. log("[W] Downloading replay comments has been aborted.", "YELLOW")
  342. return False
  343. def get_live_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  344. try:
  345. comments_downloader = CommentsDownloader(
  346. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  347. first_comment_created_at = 0
  348. try:
  349. while not broadcast_downloader.is_aborted:
  350. if 'initial_buffered_duration' not in broadcast and broadcast_downloader.initial_buffered_duration:
  351. broadcast['initial_buffered_duration'] = broadcast_downloader.initial_buffered_duration
  352. comments_downloader.broadcast = broadcast
  353. first_comment_created_at = comments_downloader.get_live(first_comment_created_at)
  354. except ClientError as e:
  355. if not 'media has been deleted' in e.error_response:
  356. log("[W] Comment collection ClientError: %d %s" % (e.code, e.error_response), "YELLOW")
  357. try:
  358. if comments_downloader.comments:
  359. comments_downloader.save()
  360. comments_log_file = comments_json_file.replace('.json', '.log')
  361. CommentsDownloader.generate_log(
  362. comments_downloader.comments, settings.current_time, comments_log_file,
  363. comments_delay=broadcast_downloader.initial_buffered_duration)
  364. if len(comments_downloader.comments) == 1:
  365. log("[I] Successfully saved 1 comment to logfile.", "GREEN")
  366. seperator("GREEN")
  367. return True
  368. else:
  369. log("[I] Successfully saved {} comments to logfile.".format(len(comments_downloader.comments)), "GREEN")
  370. seperator("GREEN")
  371. return True
  372. else:
  373. log("[I] There are no available comments to save.", "GREEN")
  374. return False
  375. seperator("GREEN")
  376. except Exception as e:
  377. log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")
  378. return False
  379. except KeyboardInterrupt as e:
  380. log("[W] Downloading livestream comments has been aborted.", "YELLOW")
  381. return False