downloader.py 17 KB

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