downloader.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 livestream:
  239. download_livestream(livestream)
  240. else:
  241. log('[I] There are no available livestreams.', "YELLOW")
  242. if settings.save_replays.title() == "True":
  243. if replays:
  244. seperator("GREEN")
  245. log('[I] Replays found, beginning download...', "GREEN")
  246. seperator("GREEN")
  247. download_replays(replays)
  248. else:
  249. log('[I] There are no available replays.', "YELLOW")
  250. else:
  251. log("[I] Replay saving is disabled either with an argument or in the config file.", "BLUE")
  252. seperator("GREEN")
  253. except Exception as e:
  254. log('[E] Could not finish checking: {:s}'.format(str(e)), "RED")
  255. if "timed out" in str(e):
  256. log('[E] The connection timed out, check your internet connection.', "RED")
  257. seperator("GREEN")
  258. exit(1)
  259. except KeyboardInterrupt:
  260. log('[W] Aborted checking for livestreams and replays, exiting...'.format(user_to_download), "YELLOW")
  261. seperator("GREEN")
  262. sys.exit(1)
  263. except ClientThrottledError as cte:
  264. log('[E] Could not check because you are making too many requests at this time.', "RED")
  265. seperator("GREEN")
  266. exit(1)
  267. def download_replays(broadcasts):
  268. try:
  269. try:
  270. log('[I] Amount of replays : {:s}'.format(str(len(broadcasts))), "GREEN")
  271. for replay_index, broadcast in enumerate(broadcasts):
  272. bc_dash_manifest = parseString(broadcast.get('dash_manifest')).getElementsByTagName('Period')
  273. bc_duration_raw = bc_dash_manifest[0].getAttribute("duration")
  274. bc_hours = (bc_duration_raw.split("PT"))[1].split("H")[0]
  275. bc_minutes = (bc_duration_raw.split("H"))[1].split("M")[0]
  276. bc_seconds = ((bc_duration_raw.split("M"))[1].split("S")[0]).split('.')[0]
  277. log('[I] Replay {:s} duration : {:s} minutes and {:s} seconds'.format(str(replay_index + 1), bc_minutes, bc_seconds), "GREEN")
  278. except Exception as e:
  279. log("[W] An error occurred while getting replay duration information: {:s}".format(str(e)))
  280. seperator("GREEN")
  281. log("[I] Downloading replays... press [CTRL+C] to abort.", "GREEN")
  282. seperator("GREEN")
  283. for replay_index, broadcast in enumerate(broadcasts):
  284. exists = False
  285. if sys.version.split(' ')[0].startswith('2'):
  286. directories = (os.walk(settings.save_path).next()[1])
  287. else:
  288. directories = (os.walk(settings.save_path).__next__()[1])
  289. for directory in directories:
  290. if (str(broadcast.get('id')) in directory) and ("_live_" not in directory):
  291. log("[W] Already downloaded a replay with ID '{:s}'.".format(str(broadcast.get('id'))), "YELLOW")
  292. exists = True
  293. if not exists:
  294. current = replay_index + 1
  295. log("[I] Downloading replay {:s} of {:s} with ID '{:s}'...".format(str(current), str(len(broadcasts)), str(broadcast.get('id'))), "GREEN")
  296. current_time = str(int(time.time()))
  297. output_dir = '{}{}_{}_{}_{}_replay_downloads'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  298. broadcast_downloader = replay.Downloader(
  299. mpd=broadcast.get('dash_manifest'),
  300. output_dir=output_dir,
  301. user_agent=instagram_api.user_agent)
  302. open(os.path.join(output_dir, 'folder.lock'), 'a').close()
  303. replay_mp4_file = '{}{}_{}_{}_{}_replay.mp4'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  304. replay_json_file = os.path.join(output_dir, '{}_{}_{}_{}_replay_comments.json'.format(settings.current_date, user_to_download, broadcast.get('id'), settings.current_time))
  305. if settings.clear_temp_files.title() == "True":
  306. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=True)
  307. else:
  308. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=False)
  309. if settings.save_comments.title() == "True":
  310. log("[I] Downloading replay comments...", "GREEN")
  311. try:
  312. get_replay_comments(instagram_api, broadcast, replay_json_file, broadcast_downloader)
  313. except Exception as e:
  314. log('[E] An error occurred while downloading comments: {:s}'.format(str(e)), "RED")
  315. if (len(replay_saved) == 1):
  316. log("[I] Finished downloading replay {:s} of {:s}.".format(str(current), str(len(broadcasts))), "GREEN")
  317. try:
  318. os.remove(os.path.join(output_dir, 'folder.lock'))
  319. except Exception:
  320. pass
  321. if (current != len(broadcasts)):
  322. seperator("GREEN")
  323. else:
  324. log("[W] No output video file was made, please merge the files manually if possible.", "YELLOW")
  325. log("[W] Check if ffmpeg is available by running ffmpeg in your terminal/cmd prompt.", "YELLOW")
  326. log("", "GREEN")
  327. seperator("GREEN")
  328. log("[I] Finished downloading all available replays.", "GREEN")
  329. seperator("GREEN")
  330. sys.exit(0)
  331. except Exception as e:
  332. log('[E] Could not save replay: {:s}'.format(str(e)), "RED")
  333. seperator("GREEN")
  334. try:
  335. os.remove(os.path.join(output_dir, 'folder.lock'))
  336. except Exception:
  337. pass
  338. sys.exit(1)
  339. except KeyboardInterrupt:
  340. seperator("GREEN")
  341. log('[I] The download has been aborted by the user.', "YELLOW")
  342. seperator("GREEN")
  343. try:
  344. shutil.rmtree(output_dir)
  345. except Exception as e:
  346. log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
  347. sys.exit(1)
  348. sys.exit(0)
  349. def get_replay_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  350. try:
  351. comments_downloader = CommentsDownloader(
  352. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  353. comments_downloader.get_replay()
  354. try:
  355. if comments_downloader.comments:
  356. comments_log_file = comments_json_file.replace('.json', '.log')
  357. comment_errors, total_comments = CommentsDownloader.generate_log(
  358. comments_downloader.comments, broadcast.get('published_time'), comments_log_file,
  359. comments_delay=0)
  360. if total_comments == 1:
  361. log("[I] Successfully saved 1 comment to logfile.", "GREEN")
  362. seperator("GREEN")
  363. return True
  364. else:
  365. if comment_errors:
  366. log("[W] Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)), "YELLOW")
  367. else:
  368. log("[I] Successfully saved {:s} comments to logfile.".format(str(total_comments)), "GREEN")
  369. seperator("GREEN")
  370. return True
  371. else:
  372. log("[I] There are no available comments to save.", "GREEN")
  373. return False
  374. except Exception as e:
  375. log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")
  376. return False
  377. except KeyboardInterrupt as e:
  378. log("[W] Downloading replay comments has been aborted.", "YELLOW")
  379. return False
  380. def get_live_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  381. try:
  382. comments_downloader = CommentsDownloader(
  383. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  384. first_comment_created_at = 0
  385. try:
  386. while not broadcast_downloader.is_aborted:
  387. if 'initial_buffered_duration' not in broadcast and broadcast_downloader.initial_buffered_duration:
  388. broadcast['initial_buffered_duration'] = broadcast_downloader.initial_buffered_duration
  389. comments_downloader.broadcast = broadcast
  390. first_comment_created_at = comments_downloader.get_live(first_comment_created_at)
  391. except ClientError as e:
  392. if not 'media has been deleted' in e.error_response:
  393. log("[W] Comment collection ClientError: %d %s" % (e.code, e.error_response), "YELLOW")
  394. try:
  395. if comments_downloader.comments:
  396. comments_downloader.save()
  397. comments_log_file = comments_json_file.replace('.json', '.log')
  398. comment_errors, total_comments = CommentsDownloader.generate_log(
  399. comments_downloader.comments, settings.current_time, comments_log_file,
  400. comments_delay=broadcast_downloader.initial_buffered_duration)
  401. if len(comments_downloader.comments) == 1:
  402. log("[I] Successfully saved 1 comment to logfile.", "GREEN")
  403. seperator("GREEN")
  404. return True
  405. else:
  406. if comment_errors:
  407. log("[W] Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)), "YELLOW")
  408. else:
  409. log("[I] Successfully saved {:s} comments to logfile.".format(str(total_comments)), "GREEN")
  410. seperator("GREEN")
  411. return True
  412. else:
  413. log("[I] There are no available comments to save.", "GREEN")
  414. return False
  415. seperator("GREEN")
  416. except Exception as e:
  417. log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")
  418. return False
  419. except KeyboardInterrupt as e:
  420. log("[W] Downloading livestream comments has been aborted.", "YELLOW")
  421. return False