downloader.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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
  16. from .logger import seperator
  17. def main(instagram_api_arg, download_arg, settings_arg):
  18. global instagram_api
  19. global user_to_download
  20. global broadcast
  21. global settings
  22. settings = settings_arg
  23. instagram_api = instagram_api_arg
  24. user_to_download = download_arg
  25. get_user_info(user_to_download)
  26. def run_command(command):
  27. try:
  28. FNULL = open(os.devnull, 'w')
  29. subprocess.Popen(shlex.split(command), stdout=FNULL, stderr=subprocess.STDOUT)
  30. except Exception as e:
  31. pass
  32. def get_stream_duration(compare_time, broadcast=None):
  33. try:
  34. had_wrong_time = False
  35. if broadcast:
  36. if (int(time.time()) < int(compare_time)):
  37. had_wrong_time = True
  38. corrected_compare_time = int(compare_time) - 5
  39. download_time = int(time.time()) - int(corrected_compare_time)
  40. else:
  41. download_time = int(time.time()) - int(compare_time)
  42. stream_time = int(time.time()) - int(broadcast.get('published_time'))
  43. stream_started_mins, stream_started_secs = divmod(stream_time - download_time, 60)
  44. else:
  45. if (int(time.time()) < int(compare_time)):
  46. had_wrong_time = True
  47. corrected_compare_time = int(compare_time) - 5
  48. stream_started_mins, stream_started_secs = divmod((int(time.time()) - int(corrected_compare_time)), 60)
  49. else:
  50. stream_started_mins, stream_started_secs = divmod((int(time.time()) - int(compare_time)), 60)
  51. stream_duration_str = '%d minutes' % stream_started_mins
  52. if stream_started_secs:
  53. stream_duration_str += ' and %d seconds' % stream_started_secs
  54. if had_wrong_time:
  55. return "{:s} (corrected)".format(stream_duration_str)
  56. else:
  57. return stream_duration_str
  58. except Exception as 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 = '{}{}_{}_{}_{}_live_downloads'.format(settings.save_path, settings.current_date, user_to_download, 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_download):
  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 current guest is "{}".'.format(broadcast_guest), "BLUE")
  100. seperator("GREEN")
  101. log('[I] Username : {:s}'.format(user_to_download), "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_download, 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 downloading comments: {:s}'.format(str(e)), "RED")
  123. broadcast_downloader.run()
  124. seperator("GREEN")
  125. log('[I] The livestream has ended.\n[I] Download duration : {}\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] Download duration : {}\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 Exception:
  140. pass
  141. def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
  142. try:
  143. live_mp4_file = '{}{}_{}_{}_{}_live.mp4'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  144. live_folder_path = "{:s}_downloads".format(live_mp4_file.split('.mp4')[0])
  145. if comment_thread_worker and comment_thread_worker.is_alive():
  146. log("[I] Waiting for comment downloader to end cycle...", "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 Exception:
  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 Exception:
  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 Exception:
  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 Exception:
  196. pass
  197. sys.exit(0)
  198. def get_user_info(user_to_download):
  199. try:
  200. user_res = instagram_api.username_info(user_to_download)
  201. user_id = user_res.get('user', {}).get('pk')
  202. except ClientConnectionError as cce:
  203. log('[E] Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, cce.code, str(cce)), "RED")
  204. if "getaddrinfo failed" in str(cce):
  205. log('[E] Could not resolve host, check your internet connection.', "RED")
  206. if "timed out" in str(cce):
  207. log('[E] The connection timed out, check your internet connection.', "RED")
  208. seperator("GREEN")
  209. sys.exit(1)
  210. except ClientThrottledError as cte:
  211. log('[E] Could not get user info for "{:s}": {:d} {:s}\n[E] You are making too many requests at this time.'.format(user_to_download, cte.code, str(cte)), "RED")
  212. seperator("GREEN")
  213. sys.exit(1)
  214. except ClientError as ce:
  215. log('[E] Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, ce.code, str(ce)), "RED")
  216. if ("Not Found") in str(ce):
  217. log('[E] The specified user does not exist.', "RED")
  218. seperator("GREEN")
  219. sys.exit(1)
  220. except Exception as e:
  221. log('[E] Could not get user info for "{:s}": {:s}'.format(user_to_download, str(e)), "RED")
  222. seperator("GREEN")
  223. sys.exit(1)
  224. except KeyboardInterrupt:
  225. log('[W] Aborted getting user info for "{:s}", exiting...'.format(user_to_download), "YELLOW")
  226. seperator("GREEN")
  227. sys.exit(0)
  228. log('[I] Getting info for "{:s}" successful.'.format(user_to_download), "GREEN")
  229. get_broadcasts_info(user_id)
  230. def get_broadcasts_info(user_id):
  231. seperator("GREEN")
  232. try:
  233. log('[I] Checking for livestreams and replays...', "GREEN")
  234. seperator("GREEN")
  235. broadcasts = instagram_api.user_story_feed(user_id)
  236. livestream = broadcasts.get('broadcast')
  237. replays = broadcasts.get('post_live_item', {}).get('broadcasts', [])
  238. if settings.save_lives.title() == "True":
  239. if livestream:
  240. download_livestream(livestream)
  241. else:
  242. log('[I] There are no available livestreams.', "YELLOW")
  243. else:
  244. log("[I] Livestream saving is disabled either with an argument or in the config file.", "BLUE")
  245. if settings.save_replays.title() == "True":
  246. if replays:
  247. seperator("GREEN")
  248. log('[I] Replays found, beginning download...', "GREEN")
  249. seperator("GREEN")
  250. download_replays(replays)
  251. else:
  252. log('[I] There are no available replays.', "YELLOW")
  253. else:
  254. seperator("GREEN")
  255. log("[I] Replay saving is disabled either with an argument or in the config file.", "BLUE")
  256. seperator("GREEN")
  257. except Exception as e:
  258. log('[E] Could not finish checking: {:s}'.format(str(e)), "RED")
  259. if "timed out" in str(e):
  260. log('[E] The connection timed out, check your internet connection.', "RED")
  261. seperator("GREEN")
  262. exit(1)
  263. except KeyboardInterrupt:
  264. log('[W] Aborted checking for livestreams and replays, exiting...'.format(user_to_download), "YELLOW")
  265. seperator("GREEN")
  266. sys.exit(1)
  267. except ClientThrottledError as cte:
  268. log('[E] Could not check because you are making too many requests at this time.', "RED")
  269. seperator("GREEN")
  270. exit(1)
  271. def download_replays(broadcasts):
  272. try:
  273. try:
  274. log('[I] Amount of replays : {:s}'.format(str(len(broadcasts))), "GREEN")
  275. for replay_index, broadcast in enumerate(broadcasts):
  276. bc_dash_manifest = parseString(broadcast.get('dash_manifest')).getElementsByTagName('Period')
  277. bc_duration_raw = bc_dash_manifest[0].getAttribute("duration")
  278. bc_hours = (bc_duration_raw.split("PT"))[1].split("H")[0]
  279. bc_minutes = (bc_duration_raw.split("H"))[1].split("M")[0]
  280. bc_seconds = ((bc_duration_raw.split("M"))[1].split("S")[0]).split('.')[0]
  281. log('[I] Replay {:s} duration : {:s} minutes and {:s} seconds'.format(str(replay_index + 1), bc_minutes, bc_seconds), "GREEN")
  282. except Exception as e:
  283. log("[W] An error occurred while getting replay duration information: {:s}".format(str(e)))
  284. seperator("GREEN")
  285. log("[I] Downloading replays... press [CTRL+C] to abort.", "GREEN")
  286. seperator("GREEN")
  287. for replay_index, broadcast in enumerate(broadcasts):
  288. exists = False
  289. if sys.version.split(' ')[0].startswith('2'):
  290. directories = (os.walk(settings.save_path).next()[1])
  291. else:
  292. directories = (os.walk(settings.save_path).__next__()[1])
  293. for directory in directories:
  294. if (str(broadcast.get('id')) in directory) and ("_live_" not in directory):
  295. log("[W] Already downloaded a replay with ID '{:s}'.".format(str(broadcast.get('id'))), "YELLOW")
  296. exists = True
  297. if not exists:
  298. current = replay_index + 1
  299. log("[I] Downloading replay {:s} of {:s} with ID '{:s}'...".format(str(current), str(len(broadcasts)), str(broadcast.get('id'))), "GREEN")
  300. current_time = str(int(time.time()))
  301. output_dir = '{}{}_{}_{}_{}_replay_downloads'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  302. broadcast_downloader = replay.Downloader(
  303. mpd=broadcast.get('dash_manifest'),
  304. output_dir=output_dir,
  305. user_agent=instagram_api.user_agent)
  306. open(os.path.join(output_dir, 'folder.lock'), 'a').close()
  307. replay_mp4_file = '{}{}_{}_{}_{}_replay.mp4'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  308. replay_json_file = os.path.join(output_dir, '{}_{}_{}_{}_replay_comments.json'.format(settings.current_date, user_to_download, broadcast.get('id'), settings.current_time))
  309. if settings.clear_temp_files.title() == "True":
  310. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=True)
  311. else:
  312. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=False)
  313. if settings.save_comments.title() == "True":
  314. log("[I] Downloading replay comments...", "GREEN")
  315. try:
  316. get_replay_comments(instagram_api, broadcast, replay_json_file, broadcast_downloader)
  317. except Exception as e:
  318. log('[E] An error occurred while downloading comments: {:s}'.format(str(e)), "RED")
  319. if (len(replay_saved) == 1):
  320. log("[I] Finished downloading replay {:s} of {:s}.".format(str(current), str(len(broadcasts))), "GREEN")
  321. try:
  322. os.remove(os.path.join(output_dir, 'folder.lock'))
  323. except Exception:
  324. pass
  325. if (current != len(broadcasts)):
  326. seperator("GREEN")
  327. else:
  328. log("[W] No output video file was made, please merge the files manually if possible.", "YELLOW")
  329. log("[W] Check if ffmpeg is available by running ffmpeg in your terminal/cmd prompt.", "YELLOW")
  330. log("", "GREEN")
  331. seperator("GREEN")
  332. log("[I] Finished downloading all available replays.", "GREEN")
  333. seperator("GREEN")
  334. sys.exit(0)
  335. except Exception as e:
  336. log('[E] Could not save replay: {:s}'.format(str(e)), "RED")
  337. seperator("GREEN")
  338. try:
  339. os.remove(os.path.join(output_dir, 'folder.lock'))
  340. except Exception:
  341. pass
  342. sys.exit(1)
  343. except KeyboardInterrupt:
  344. seperator("GREEN")
  345. log('[I] The download has been aborted by the user, exiting...', "YELLOW")
  346. seperator("GREEN")
  347. try:
  348. shutil.rmtree(output_dir)
  349. except Exception as e:
  350. log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
  351. sys.exit(1)
  352. sys.exit(0)
  353. def get_replay_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  354. try:
  355. comments_downloader = CommentsDownloader(
  356. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  357. comments_downloader.get_replay()
  358. try:
  359. if comments_downloader.comments:
  360. comments_log_file = comments_json_file.replace('.json', '.log')
  361. comment_errors, total_comments = CommentsDownloader.generate_log(
  362. comments_downloader.comments, broadcast.get('published_time'), comments_log_file,
  363. comments_delay=0)
  364. if total_comments == 1:
  365. log("[I] Successfully saved 1 comment to logfile.", "GREEN")
  366. seperator("GREEN")
  367. return True
  368. else:
  369. if comment_errors:
  370. log("[W] Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)), "YELLOW")
  371. else:
  372. log("[I] Successfully saved {:s} comments to logfile.".format(str(total_comments)), "GREEN")
  373. seperator("GREEN")
  374. return True
  375. else:
  376. log("[I] There are no available comments to save.", "GREEN")
  377. return False
  378. except Exception as e:
  379. log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")
  380. return False
  381. except KeyboardInterrupt as e:
  382. log("[W] Downloading replay comments has been aborted.", "YELLOW")
  383. return False
  384. def get_live_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  385. try:
  386. comments_downloader = CommentsDownloader(
  387. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  388. first_comment_created_at = 0
  389. try:
  390. while not broadcast_downloader.is_aborted:
  391. if 'initial_buffered_duration' not in broadcast and broadcast_downloader.initial_buffered_duration:
  392. broadcast['initial_buffered_duration'] = broadcast_downloader.initial_buffered_duration
  393. comments_downloader.broadcast = broadcast
  394. first_comment_created_at = comments_downloader.get_live(first_comment_created_at)
  395. except ClientError as e:
  396. if not 'media has been deleted' in e.error_response:
  397. log("[W] Comment collection ClientError: %d %s" % (e.code, e.error_response), "YELLOW")
  398. try:
  399. if comments_downloader.comments:
  400. comments_downloader.save()
  401. comments_log_file = comments_json_file.replace('.json', '.log')
  402. comment_errors, total_comments = CommentsDownloader.generate_log(
  403. comments_downloader.comments, settings.current_time, comments_log_file,
  404. comments_delay=broadcast_downloader.initial_buffered_duration)
  405. if len(comments_downloader.comments) == 1:
  406. log("[I] Successfully saved 1 comment to logfile.", "GREEN")
  407. seperator("GREEN")
  408. return True
  409. else:
  410. if comment_errors:
  411. log("[W] Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)), "YELLOW")
  412. else:
  413. log("[I] Successfully saved {:s} comments to logfile.".format(str(total_comments)), "GREEN")
  414. seperator("GREEN")
  415. return True
  416. else:
  417. log("[I] There are no available comments to save.", "GREEN")
  418. return False
  419. seperator("GREEN")
  420. except Exception as e:
  421. log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")
  422. return False
  423. except KeyboardInterrupt as e:
  424. log("[W] Downloading livestream comments has been aborted.", "YELLOW")
  425. return False