downloader.py 16 KB

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