downloader.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. import os
  2. import shutil
  3. import subprocess
  4. import sys
  5. import threading
  6. import time
  7. import shlex
  8. from xml.dom.minidom import parse, parseString
  9. from instagram_private_api import ClientConnectionError
  10. from instagram_private_api import ClientError
  11. from instagram_private_api import ClientThrottledError
  12. from instagram_private_api_extensions import live
  13. from instagram_private_api_extensions import replay
  14. from .comments import CommentsDownloader
  15. from .logger import log_seperator, supports_color, log_info_blue, log_info_green, log_warn, log_error, log_whiteline, log_plain
  16. def main(instagram_api_arg, download_arg, settings_arg):
  17. global instagram_api
  18. global user_to_download
  19. global broadcast
  20. global settings
  21. settings = settings_arg
  22. instagram_api = instagram_api_arg
  23. user_to_download = download_arg
  24. get_user_info(user_to_download)
  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 Exception 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. download_time = int(time.time()) - int(corrected_compare_time)
  39. else:
  40. download_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 - download_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 "{:s} (corrected)".format(stream_duration_str)
  55. else:
  56. return stream_duration_str
  57. except Exception as e:
  58. return "Not available"
  59. def download_livestream(broadcast):
  60. try:
  61. def print_status(sep=True):
  62. heartbeat_info = instagram_api.broadcast_heartbeat_and_viewercount(broadcast.get('id'))
  63. viewers = broadcast.get('viewer_count', 0)
  64. if sep:
  65. log_seperator()
  66. log_info_green('Viewers : {:s} watching'.format(str(int(viewers))))
  67. log_info_green('Airing time : {:s}'.format(get_stream_duration(broadcast.get('published_time'))))
  68. log_info_green('Status : {:s}'.format(heartbeat_info.get('broadcast_status').title()))
  69. return heartbeat_info.get('broadcast_status') not in ['active', 'interrupted']
  70. mpd_url = (broadcast.get('dash_manifest')
  71. or broadcast.get('dash_abr_playback_url')
  72. or broadcast.get('dash_playback_url'))
  73. output_dir = '{}{}_{}_{}_{}_live_downloads'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  74. broadcast_downloader = live.Downloader(
  75. mpd=mpd_url,
  76. output_dir=output_dir,
  77. user_agent=instagram_api.user_agent,
  78. max_connection_error_retry=3,
  79. duplicate_etag_retry=30,
  80. callback_check=print_status,
  81. mpd_download_timeout=3,
  82. download_timeout=3)
  83. except Exception as e:
  84. log_error('Could not start downloading livestream: {:s}'.format(str(e)))
  85. log_seperator()
  86. sys.exit(1)
  87. try:
  88. log_info_green('Livestream found, beginning download...')
  89. broadcast_owner = broadcast.get('broadcast_owner', {}).get('username')
  90. try:
  91. broadcast_guest = broadcast.get('cobroadcasters', {})[0].get('username')
  92. except:
  93. broadcast_guest = None
  94. if (broadcast_owner != user_to_download):
  95. log_info_blue('This livestream is a dual-live, the owner is "{}".'.format(broadcast_owner))
  96. broadcast_guest = None
  97. if broadcast_guest:
  98. log_info_blue('This livestream is a dual-live, the current guest is "{}".'.format(broadcast_guest))
  99. log_seperator()
  100. log_info_green('Username : {:s}'.format(user_to_download))
  101. print_status(False)
  102. log_info_green('MPD URL : {:s}'.format(mpd_url))
  103. log_seperator()
  104. open(os.path.join(output_dir, 'folder.lock'), 'a').close()
  105. log_info_green('Downloading livestream... press [CTRL+C] to abort.')
  106. if (settings.run_at_start is not "None"):
  107. try:
  108. thread = threading.Thread(target=run_command, args=(settings.run_at_start,))
  109. thread.daemon = True
  110. thread.start()
  111. log_info_green("Command executed: \033[94m{:s}".format(settings.run_at_start))
  112. except Exception as e:
  113. log_warn('Could not execute command: {:s}'.format(str(e)))
  114. comment_thread_worker = None
  115. if settings.save_comments.title() == "True":
  116. try:
  117. comments_json_file = os.path.join(output_dir, '{}_{}_{}_{}_live_comments.json'.format(settings.current_date, user_to_download, broadcast.get('id'), settings.current_time))
  118. comment_thread_worker = threading.Thread(target=get_live_comments, args=(instagram_api, broadcast, comments_json_file, broadcast_downloader,))
  119. comment_thread_worker.start()
  120. except Exception as e:
  121. log_error('An error occurred while downloading comments: {:s}'.format(str(e)))
  122. broadcast_downloader.run()
  123. log_seperator()
  124. log_info_green('Download duration : {}'.format(get_stream_duration(int(settings.current_time))))
  125. log_info_green('Stream duration : {}'.format(get_stream_duration(broadcast.get('published_time'))))
  126. log_info_green('Missing (approx.) : {}'.format(get_stream_duration(int(settings.current_time), broadcast)))
  127. log_seperator()
  128. stitch_video(broadcast_downloader, broadcast, comment_thread_worker)
  129. except KeyboardInterrupt:
  130. log_seperator()
  131. log_info_blue('The download has been aborted by the user.')
  132. log_seperator()
  133. log_info_green('Download duration : {}'.format(get_stream_duration(int(settings.current_time))))
  134. log_info_green('Stream duration : {}'.format(get_stream_duration(broadcast.get('published_time'))))
  135. log_info_green('Missing (approx.) : {}'.format(get_stream_duration(int(settings.current_time), broadcast)))
  136. log_seperator()
  137. if not broadcast_downloader.is_aborted:
  138. broadcast_downloader.stop()
  139. stitch_video(broadcast_downloader, broadcast, comment_thread_worker)
  140. except Exception as e:
  141. log_error("Could not download livestream: {:s}".format(str(e)))
  142. try:
  143. os.remove(os.path.join(output_dir, 'folder.lock'))
  144. except Exception:
  145. pass
  146. def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
  147. try:
  148. live_mp4_file = '{}{}_{}_{}_{}_live.mp4'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  149. live_folder_path = "{:s}_downloads".format(live_mp4_file.split('.mp4')[0])
  150. if comment_thread_worker and comment_thread_worker.is_alive():
  151. log_info_green("Waiting for comment downloader to end cycle...")
  152. comment_thread_worker.join()
  153. if (settings.run_at_finish is not "None"):
  154. try:
  155. thread = threading.Thread(target=run_command, args=(settings.run_at_finish,))
  156. thread.daemon = True
  157. thread.start()
  158. log_info_green("Command executed: \033[94m{:s}".format(settings.run_at_finish))
  159. except Exception as e:
  160. log_warn('Could not execute command: {:s}'.format(str(e)))
  161. log_info_green('Stitching downloaded files into video...')
  162. try:
  163. if settings.clear_temp_files.title() == "True":
  164. broadcast_downloader.stitch(live_mp4_file, cleartempfiles=True)
  165. else:
  166. broadcast_downloader.stitch(live_mp4_file, cleartempfiles=False)
  167. log_info_green('Successfully stitched downloaded files into video.')
  168. try:
  169. os.remove(os.path.join(live_folder_path, 'folder.lock'))
  170. except Exception:
  171. pass
  172. if settings.clear_temp_files.title() == "True":
  173. try:
  174. shutil.rmtree(live_folder_path)
  175. except Exception as e:
  176. log_error("Could not remove temp folder: {:s}".format(str(e)))
  177. log_seperator()
  178. sys.exit(0)
  179. except ValueError as e:
  180. log_error('Could not stitch downloaded files: {:s}'.format(str(e)))
  181. log_error('Likely the download duration was too short and no temp files were saved.')
  182. log_seperator()
  183. try:
  184. os.remove(os.path.join(live_folder_path, 'folder.lock'))
  185. except Exception:
  186. pass
  187. sys.exit(1)
  188. except Exception as e:
  189. log_error('Could not stitch downloaded files: {:s}'.format(str(e)))
  190. log_seperator()
  191. try:
  192. os.remove(os.path.join(live_folder_path, 'folder.lock'))
  193. except Exception:
  194. pass
  195. sys.exit(1)
  196. except KeyboardInterrupt:
  197. log_info_blue('Aborted stitching process, no video was created.')
  198. log_seperator()
  199. try:
  200. os.remove(os.path.join(live_folder_path, 'folder.lock'))
  201. except Exception:
  202. pass
  203. sys.exit(0)
  204. def get_user_info(user_to_download):
  205. try:
  206. user_res = instagram_api.username_info(user_to_download)
  207. user_id = user_res.get('user', {}).get('pk')
  208. except ClientConnectionError as cce:
  209. log_error('Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, cce.code, str(cce)))
  210. if "getaddrinfo failed" in str(cce):
  211. log_error('Could not resolve host, check your internet connection.')
  212. if "timed out" in str(cce):
  213. log_error('The connection timed out, check your internet connection.')
  214. log_seperator()
  215. sys.exit(1)
  216. except ClientThrottledError as cte:
  217. log_error('Could not get user info for "{:s}": {:d} {:s}.'.format(user_to_download, cte.code, str(cte)))
  218. log_error('You are making too many requests at this time.')
  219. log_seperator()
  220. sys.exit(1)
  221. except ClientError as ce:
  222. log_error('Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, ce.code, str(ce)))
  223. if ("Not Found") in str(ce):
  224. log_error('The specified user does not exist.')
  225. log_seperator()
  226. sys.exit(1)
  227. except Exception as e:
  228. log_error('Could not get user info for "{:s}": {:s}'.format(user_to_download, str(e)))
  229. log_seperator()
  230. sys.exit(1)
  231. except KeyboardInterrupt:
  232. log_info_blue('Aborted getting user info for "{:s}", exiting...'.format(user_to_download))
  233. log_seperator()
  234. sys.exit(0)
  235. log_info_green('Getting info for "{:s}" successful.'.format(user_to_download))
  236. get_broadcasts_info(user_id)
  237. def get_broadcasts_info(user_id):
  238. try:
  239. log_seperator()
  240. log_info_green('Checking for livestreams and replays...')
  241. log_seperator()
  242. broadcasts = instagram_api.user_story_feed(user_id)
  243. livestream = broadcasts.get('broadcast')
  244. replays = broadcasts.get('post_live_item', {}).get('broadcasts', [])
  245. if settings.save_lives.title() == "True":
  246. if livestream:
  247. download_livestream(livestream)
  248. else:
  249. log_info_green('There are no available livestreams.')
  250. else:
  251. log_info_blue("Livestream saving is disabled either with an argument or in the config file.")
  252. if settings.save_replays.title() == "True":
  253. if replays:
  254. log_seperator()
  255. log_info_green('Replays found, beginning download...')
  256. log_seperator()
  257. download_replays(replays)
  258. else:
  259. log_info_green('There are no available replays.')
  260. else:
  261. log_seperator()
  262. log_info_blue("Replay saving is disabled either with an argument or in the config file.")
  263. log_seperator()
  264. except Exception as e:
  265. log_error('Could not finish checking: {:s}'.format(str(e)))
  266. if "timed out" in str(e):
  267. log_error('The connection timed out, check your internet connection.')
  268. log_seperator()
  269. exit(1)
  270. except KeyboardInterrupt:
  271. log_info_blue('Aborted checking for livestreams and replays, exiting...'.format(user_to_download))
  272. log_seperator()
  273. sys.exit(1)
  274. except ClientThrottledError as cte:
  275. log_error('Could not check because you are making too many requests at this time.')
  276. log_seperator()
  277. exit(1)
  278. def download_replays(broadcasts):
  279. try:
  280. try:
  281. log_info_green('Amount of replays : {:s}'.format(str(len(broadcasts))))
  282. for replay_index, broadcast in enumerate(broadcasts):
  283. bc_dash_manifest = parseString(broadcast.get('dash_manifest')).getElementsByTagName('Period')
  284. bc_duration_raw = bc_dash_manifest[0].getAttribute("duration")
  285. bc_hours = (bc_duration_raw.split("PT"))[1].split("H")[0]
  286. bc_minutes = (bc_duration_raw.split("H"))[1].split("M")[0]
  287. bc_seconds = ((bc_duration_raw.split("M"))[1].split("S")[0]).split('.')[0]
  288. log_info_green('Replay {:s} duration : {:s} minutes and {:s} seconds'.format(str(replay_index + 1), bc_minutes, bc_seconds))
  289. except Exception as e:
  290. log_warn("An error occurred while getting replay duration information: {:s}".format(str(e)))
  291. log_seperator()
  292. log_info_green("Downloading replays... press [CTRL+C] to abort.")
  293. log_seperator()
  294. for replay_index, broadcast in enumerate(broadcasts):
  295. exists = False
  296. if sys.version.split(' ')[0].startswith('2'):
  297. directories = (os.walk(settings.save_path).next()[1])
  298. else:
  299. directories = (os.walk(settings.save_path).__next__()[1])
  300. for directory in directories:
  301. if (str(broadcast.get('id')) in directory) and ("_live_" not in directory):
  302. log_info_blue("Already downloaded a replay with ID '{:s}'.".format(str(broadcast.get('id'))))
  303. exists = True
  304. if not exists:
  305. current = replay_index + 1
  306. log_info_green("Downloading replay {:s} of {:s} with ID '{:s}'...".format(str(current), str(len(broadcasts)), str(broadcast.get('id'))))
  307. current_time = str(int(time.time()))
  308. output_dir = '{}{}_{}_{}_{}_replay_downloads'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  309. broadcast_downloader = replay.Downloader(
  310. mpd=broadcast.get('dash_manifest'),
  311. output_dir=output_dir,
  312. user_agent=instagram_api.user_agent)
  313. open(os.path.join(output_dir, 'folder.lock'), 'a').close()
  314. replay_mp4_file = '{}{}_{}_{}_{}_replay.mp4'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  315. replay_json_file = os.path.join(output_dir, '{}_{}_{}_{}_replay_comments.json'.format(settings.current_date, user_to_download, broadcast.get('id'), settings.current_time))
  316. if settings.clear_temp_files.title() == "True":
  317. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=True)
  318. else:
  319. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=False)
  320. if settings.save_comments.title() == "True":
  321. log_info_green("Downloading replay comments...")
  322. try:
  323. get_replay_comments(instagram_api, broadcast, replay_json_file, broadcast_downloader)
  324. except Exception as e:
  325. log_error('An error occurred while downloading comments: {:s}'.format(str(e)))
  326. if (len(replay_saved) == 1):
  327. log_info_green("Finished downloading replay {:s} of {:s}.".format(str(current), str(len(broadcasts))))
  328. try:
  329. os.remove(os.path.join(output_dir, 'folder.lock'))
  330. except Exception:
  331. pass
  332. if (current != len(broadcasts)):
  333. log_seperator()
  334. else:
  335. log_warn("No output video file was made, please merge the files manually if possible.")
  336. log_warn("Check if ffmpeg is available by running ffmpeg in your terminal/cmd prompt.")
  337. log_whiteline()
  338. log_seperator()
  339. log_info_green("Finished downloading all available replays.")
  340. log_seperator()
  341. sys.exit(0)
  342. except Exception as e:
  343. log_error('Could not save replay: {:s}'.format(str(e)))
  344. log_seperator()
  345. try:
  346. os.remove(os.path.join(output_dir, 'folder.lock'))
  347. except Exception:
  348. pass
  349. sys.exit(1)
  350. except KeyboardInterrupt:
  351. log_seperator()
  352. log_info_blue('The download has been aborted by the user, exiting...')
  353. log_seperator()
  354. try:
  355. shutil.rmtree(output_dir)
  356. except Exception as e:
  357. log_error("Could not remove temp folder: {:s}".format(str(e)))
  358. sys.exit(1)
  359. sys.exit(0)
  360. def get_replay_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  361. try:
  362. comments_downloader = CommentsDownloader(
  363. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  364. comments_downloader.get_replay()
  365. try:
  366. if comments_downloader.comments:
  367. comments_log_file = comments_json_file.replace('.json', '.log')
  368. comment_errors, total_comments = CommentsDownloader.generate_log(
  369. comments_downloader.comments, broadcast.get('published_time'), comments_log_file,
  370. comments_delay=0)
  371. if total_comments == 1:
  372. log_info_green("Successfully saved 1 comment to logfile.")
  373. log_seperator()
  374. return True
  375. else:
  376. if comment_errors:
  377. log_warn("Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)))
  378. else:
  379. log_info_green("Successfully saved {:s} comments to logfile.".format(str(total_comments)))
  380. log_seperator()
  381. return True
  382. else:
  383. log_info_green("There are no available comments to save.")
  384. return False
  385. except Exception as e:
  386. log_error('Could not save comments to logfile: {:s}'.format(str(e)))
  387. return False
  388. except KeyboardInterrupt as e:
  389. log_info_blue("Downloading replay comments has been aborted.")
  390. return False
  391. def get_live_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  392. try:
  393. comments_downloader = CommentsDownloader(
  394. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  395. first_comment_created_at = 0
  396. try:
  397. while not broadcast_downloader.is_aborted:
  398. if 'initial_buffered_duration' not in broadcast and broadcast_downloader.initial_buffered_duration:
  399. broadcast['initial_buffered_duration'] = broadcast_downloader.initial_buffered_duration
  400. comments_downloader.broadcast = broadcast
  401. first_comment_created_at = comments_downloader.get_live(first_comment_created_at)
  402. except ClientError as e:
  403. if not 'media has been deleted' in e.error_response:
  404. log_warn("Comment collection ClientError: %d %s" % (e.code, e.error_response))
  405. try:
  406. if comments_downloader.comments:
  407. comments_downloader.save()
  408. comments_log_file = comments_json_file.replace('.json', '.log')
  409. comment_errors, total_comments = CommentsDownloader.generate_log(
  410. comments_downloader.comments, settings.current_time, comments_log_file,
  411. comments_delay=broadcast_downloader.initial_buffered_duration)
  412. if len(comments_downloader.comments) == 1:
  413. log_info_green("Successfully saved 1 comment to logfile.")
  414. log_seperator()
  415. return True
  416. else:
  417. if comment_errors:
  418. log_warn("Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)))
  419. else:
  420. log_info_green("Successfully saved {:s} comments to logfile.".format(str(total_comments)))
  421. log_seperator()
  422. return True
  423. else:
  424. log_info_green("There are no available comments to save.")
  425. return False
  426. log_seperator()
  427. except Exception as e:
  428. log_error('Could not save comments to logfile: {:s}'.format(str(e)))
  429. return False
  430. except KeyboardInterrupt as e:
  431. log_info_blue("Downloading livestream comments has been aborted.")
  432. return False