downloader.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. import os
  2. import shutil
  3. import subprocess
  4. import sys
  5. import threading
  6. import time
  7. import shlex
  8. import json
  9. from xml.dom.minidom import parse, parseString
  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_seperator, supports_color, log_info_blue, log_info_green, log_warn, log_error, log_whiteline, log_plain
  17. def start_single(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. try:
  26. if not os.path.isfile(os.path.join(settings.save_path, user_to_download + '.lock')):
  27. open(os.path.join(settings.save_path, user_to_download + '.lock'), 'a').close()
  28. else:
  29. log_warn("Lock file is already present for this user, there is probably another download ongoing!")
  30. log_warn("If this is not the case, manually delete the file '{:s}' and try again.".format(user_to_download + '.lock'))
  31. log_seperator()
  32. sys.exit(1)
  33. except Exception:
  34. log_warn("Lock file could not be created. Downloads started from -df might cause problems!")
  35. get_user_info(user_to_download)
  36. def start_multiple(instagram_api_arg, settings_arg, proc_arg):
  37. try:
  38. log_info_green("Checking following users for any livestreams or replays...")
  39. broadcast_f_list = instagram_api_arg.reels_tray()
  40. usernames_available = []
  41. if broadcast_f_list['broadcasts']:
  42. for broadcast_f in broadcast_f_list['broadcasts']:
  43. username = broadcast_f['broadcast_owner']['username']
  44. if username not in usernames_available:
  45. usernames_available.append(username)
  46. if broadcast_f_list.get('post_live', {}).get('post_live_items', []):
  47. for broadcast_r in broadcast_f_list.get('post_live', {}).get('post_live_items', []):
  48. for broadcast_f in broadcast_r.get("broadcasts", []):
  49. username = broadcast_f['broadcast_owner']['username']
  50. if username not in usernames_available:
  51. usernames_available.append(username)
  52. log_seperator()
  53. if usernames_available:
  54. log_info_green("The following users have available livestreams or replays:")
  55. log_info_green(', '.join(usernames_available))
  56. log_seperator()
  57. for user in usernames_available:
  58. try:
  59. log_info_green("Launching daemon process for '{:s}'...".format(user))
  60. start_result = run_command("{:s} -d {:s}".format(proc_arg, user))
  61. if start_result:
  62. log_info_green("Could not start processs: {:s}".format(str(start_result)))
  63. else:
  64. log_info_green("Process started successfully.")
  65. log_seperator()
  66. time.sleep(2)
  67. except Exception as e:
  68. log_error("Could not start processs: {:s}".format(str(e)))
  69. except KeyboardInterrupt:
  70. log_info_blue('The process launching has been aborted by the user.')
  71. log_seperator()
  72. sys.exit(0)
  73. else:
  74. log_info_green("There are currently no available livestreams or replays.")
  75. log_seperator()
  76. sys.exit(0)
  77. except Exception as e:
  78. log_error("Could not finish checking following users: {:s}".format(str(e)))
  79. sys.exit(1)
  80. except KeyboardInterrupt:
  81. log_seperator()
  82. log_info_blue('The checking process has been aborted by the user.')
  83. log_seperator()
  84. sys.exit(0)
  85. def run_command(command):
  86. try:
  87. FNULL = open(os.devnull, 'w')
  88. subprocess.Popen(shlex.split(command), stdout=FNULL, stderr=subprocess.STDOUT)
  89. return False
  90. except Exception as e:
  91. return str(e)
  92. def get_stream_duration(compare_time, broadcast=None):
  93. try:
  94. had_wrong_time = False
  95. if broadcast:
  96. if (int(time.time()) < int(compare_time)):
  97. had_wrong_time = True
  98. corrected_compare_time = int(compare_time) - 5
  99. download_time = int(time.time()) - int(corrected_compare_time)
  100. else:
  101. download_time = int(time.time()) - int(compare_time)
  102. stream_time = int(time.time()) - int(broadcast.get('published_time'))
  103. stream_started_mins, stream_started_secs = divmod(stream_time - download_time, 60)
  104. else:
  105. if (int(time.time()) < int(compare_time)):
  106. had_wrong_time = True
  107. corrected_compare_time = int(compare_time) - 5
  108. stream_started_mins, stream_started_secs = divmod((int(time.time()) - int(corrected_compare_time)), 60)
  109. else:
  110. stream_started_mins, stream_started_secs = divmod((int(time.time()) - int(compare_time)), 60)
  111. stream_duration_str = '%d minutes' % stream_started_mins
  112. if stream_started_secs:
  113. stream_duration_str += ' and %d seconds' % stream_started_secs
  114. if had_wrong_time:
  115. return "{:s} (corrected)".format(stream_duration_str)
  116. else:
  117. return stream_duration_str
  118. except Exception as e:
  119. return "Not available"
  120. def download_livestream(broadcast):
  121. try:
  122. def print_status(sep=True):
  123. heartbeat_info = instagram_api.broadcast_heartbeat_and_viewercount(broadcast.get('id'))
  124. viewers = broadcast.get('viewer_count', 0)
  125. if sep:
  126. log_seperator()
  127. log_info_green('Viewers : {:s} watching'.format(str(int(viewers))))
  128. log_info_green('Airing time : {:s}'.format(get_stream_duration(broadcast.get('published_time'))))
  129. log_info_green('Status : {:s}'.format(heartbeat_info.get('broadcast_status').title()))
  130. return heartbeat_info.get('broadcast_status') not in ['active', 'interrupted']
  131. mpd_url = (broadcast.get('dash_manifest')
  132. or broadcast.get('dash_abr_playback_url')
  133. or broadcast.get('dash_playback_url'))
  134. output_dir = '{}{}_{}_{}_{}_live_downloads'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  135. broadcast_downloader = live.Downloader(
  136. mpd=mpd_url,
  137. output_dir=output_dir,
  138. user_agent=instagram_api.user_agent,
  139. max_connection_error_retry=3,
  140. duplicate_etag_retry=30,
  141. callback_check=print_status,
  142. mpd_download_timeout=3,
  143. download_timeout=3)
  144. except Exception as e:
  145. log_error('Could not start downloading livestream: {:s}'.format(str(e)))
  146. log_seperator()
  147. try:
  148. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  149. except Exception:
  150. pass
  151. sys.exit(1)
  152. try:
  153. log_info_green('Livestream found, beginning download...')
  154. broadcast_owner = broadcast.get('broadcast_owner', {}).get('username')
  155. try:
  156. broadcast_guest = broadcast.get('cobroadcasters', {})[0].get('username')
  157. except Exception:
  158. broadcast_guest = None
  159. if (broadcast_owner != user_to_download):
  160. log_info_blue('This livestream is a dual-live, the owner is "{}".'.format(broadcast_owner))
  161. broadcast_guest = None
  162. if broadcast_guest:
  163. log_info_blue('This livestream is a dual-live, the current guest is "{}".'.format(broadcast_guest))
  164. log_seperator()
  165. log_info_green('Username : {:s}'.format(user_to_download))
  166. print_status(False)
  167. log_info_green('MPD URL : {:s}'.format(mpd_url))
  168. log_seperator()
  169. open(os.path.join(output_dir, 'folder.lock'), 'a').close()
  170. log_info_green('Downloading livestream... press [CTRL+C] to abort.')
  171. if (settings.run_at_start is not "None"):
  172. try:
  173. thread = threading.Thread(target=run_command, args=(settings.run_at_start,))
  174. thread.daemon = True
  175. thread.start()
  176. log_info_green("Command executed: \033[94m{:s}".format(settings.run_at_start))
  177. except Exception as e:
  178. log_warn('Could not execute command: {:s}'.format(str(e)))
  179. comment_thread_worker = None
  180. if settings.save_comments.title() == "True":
  181. try:
  182. comments_json_file = os.path.join(output_dir, '{}_{}_{}_{}_live_comments.json'.format(settings.current_date, user_to_download, broadcast.get('id'), settings.current_time))
  183. comment_thread_worker = threading.Thread(target=get_live_comments, args=(instagram_api, broadcast, comments_json_file, broadcast_downloader,))
  184. comment_thread_worker.start()
  185. except Exception as e:
  186. log_error('An error occurred while downloading comments: {:s}'.format(str(e)))
  187. broadcast_downloader.run()
  188. log_seperator()
  189. log_info_green('Download duration : {}'.format(get_stream_duration(int(settings.current_time))))
  190. log_info_green('Stream duration : {}'.format(get_stream_duration(broadcast.get('published_time'))))
  191. log_info_green('Missing (approx.) : {}'.format(get_stream_duration(int(settings.current_time), broadcast)))
  192. log_seperator()
  193. stitch_video(broadcast_downloader, broadcast, comment_thread_worker)
  194. except KeyboardInterrupt:
  195. log_seperator()
  196. log_info_blue('The download has been aborted by the user.')
  197. log_seperator()
  198. log_info_green('Download duration : {}'.format(get_stream_duration(int(settings.current_time))))
  199. log_info_green('Stream duration : {}'.format(get_stream_duration(broadcast.get('published_time'))))
  200. log_info_green('Missing (approx.) : {}'.format(get_stream_duration(int(settings.current_time), broadcast)))
  201. log_seperator()
  202. if not broadcast_downloader.is_aborted:
  203. broadcast_downloader.stop()
  204. stitch_video(broadcast_downloader, broadcast, comment_thread_worker)
  205. except Exception as e:
  206. log_error("Could not download livestream: {:s}".format(str(e)))
  207. try:
  208. os.remove(os.path.join(output_dir, 'folder.lock'))
  209. except Exception:
  210. pass
  211. try:
  212. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  213. except Exception:
  214. pass
  215. def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
  216. try:
  217. live_mp4_file = '{}{}_{}_{}_{}_live.mp4'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  218. live_folder_path = "{:s}_downloads".format(live_mp4_file.split('.mp4')[0])
  219. if comment_thread_worker and comment_thread_worker.is_alive():
  220. log_info_green("Waiting for comment downloader to end cycle...")
  221. comment_thread_worker.join()
  222. if (settings.run_at_finish is not "None"):
  223. try:
  224. thread = threading.Thread(target=run_command, args=(settings.run_at_finish,))
  225. thread.daemon = True
  226. thread.start()
  227. log_info_green("Command executed: \033[94m{:s}".format(settings.run_at_finish))
  228. except Exception as e:
  229. log_warn('Could not execute command: {:s}'.format(str(e)))
  230. log_info_green('Stitching downloaded files into video...')
  231. try:
  232. if settings.clear_temp_files.title() == "True":
  233. broadcast_downloader.stitch(live_mp4_file, cleartempfiles=True)
  234. else:
  235. broadcast_downloader.stitch(live_mp4_file, cleartempfiles=False)
  236. log_info_green('Successfully stitched downloaded files into video.')
  237. try:
  238. os.remove(os.path.join(live_folder_path, 'folder.lock'))
  239. except Exception:
  240. pass
  241. try:
  242. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  243. except Exception:
  244. pass
  245. if settings.clear_temp_files.title() == "True":
  246. try:
  247. shutil.rmtree(live_folder_path)
  248. except Exception as e:
  249. log_error("Could not remove temp folder: {:s}".format(str(e)))
  250. log_seperator()
  251. sys.exit(0)
  252. except ValueError as e:
  253. log_error('Could not stitch downloaded files: {:s}'.format(str(e)))
  254. log_error('Likely the download duration was too short and no temp files were saved.')
  255. log_seperator()
  256. try:
  257. os.remove(os.path.join(live_folder_path, 'folder.lock'))
  258. except Exception:
  259. pass
  260. try:
  261. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  262. except Exception:
  263. pass
  264. sys.exit(1)
  265. except Exception as e:
  266. log_error('Could not stitch downloaded files: {:s}'.format(str(e)))
  267. log_seperator()
  268. try:
  269. os.remove(os.path.join(live_folder_path, 'folder.lock'))
  270. except Exception:
  271. pass
  272. try:
  273. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  274. except Exception:
  275. pass
  276. sys.exit(1)
  277. except KeyboardInterrupt:
  278. log_info_blue('Aborted stitching process, no video was created.')
  279. log_seperator()
  280. try:
  281. os.remove(os.path.join(live_folder_path, 'folder.lock'))
  282. except Exception:
  283. pass
  284. try:
  285. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  286. except Exception:
  287. pass
  288. sys.exit(0)
  289. def get_user_info(user_to_download):
  290. try:
  291. user_res = instagram_api.username_info(user_to_download)
  292. user_id = user_res.get('user', {}).get('pk')
  293. except ClientConnectionError as cce:
  294. log_error('Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, cce.code, str(cce)))
  295. if "getaddrinfo failed" in str(cce):
  296. log_error('Could not resolve host, check your internet connection.')
  297. if "timed out" in str(cce):
  298. log_error('The connection timed out, check your internet connection.')
  299. log_seperator()
  300. try:
  301. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  302. except Exception:
  303. pass
  304. sys.exit(1)
  305. except ClientThrottledError as cte:
  306. log_error('Could not get user info for "{:s}": {:d} {:s}.'.format(user_to_download, cte.code, str(cte)))
  307. log_error('You are making too many requests at this time.')
  308. log_seperator()
  309. try:
  310. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  311. except Exception:
  312. pass
  313. sys.exit(1)
  314. except ClientError as ce:
  315. log_error('Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, ce.code, str(ce)))
  316. if ("Not Found") in str(ce):
  317. log_error('The specified user does not exist.')
  318. log_seperator()
  319. try:
  320. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  321. except Exception:
  322. pass
  323. sys.exit(1)
  324. except Exception as e:
  325. log_error('Could not get user info for "{:s}": {:s}'.format(user_to_download, str(e)))
  326. log_seperator()
  327. try:
  328. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  329. except Exception:
  330. pass
  331. sys.exit(1)
  332. except KeyboardInterrupt:
  333. log_info_blue('Aborted getting user info for "{:s}", exiting...'.format(user_to_download))
  334. log_seperator()
  335. try:
  336. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  337. except Exception:
  338. pass
  339. sys.exit(0)
  340. log_info_green('Getting info for "{:s}" successful.'.format(user_to_download))
  341. get_broadcasts_info(user_id)
  342. def get_broadcasts_info(user_id):
  343. try:
  344. log_seperator()
  345. log_info_green('Checking for livestreams and replays...')
  346. log_seperator()
  347. broadcasts = instagram_api.user_story_feed(user_id)
  348. livestream = broadcasts.get('broadcast')
  349. replays = broadcasts.get('post_live_item', {}).get('broadcasts', [])
  350. if settings.save_lives.title() == "True":
  351. if livestream:
  352. download_livestream(livestream)
  353. else:
  354. log_info_green('There are no available livestreams.')
  355. else:
  356. log_info_blue("Livestream saving is disabled either with an argument or in the config file.")
  357. if settings.save_replays.title() == "True":
  358. if replays:
  359. log_seperator()
  360. log_info_green('Replays found, beginning download...')
  361. log_seperator()
  362. download_replays(replays)
  363. else:
  364. log_info_green('There are no available replays.')
  365. else:
  366. log_seperator()
  367. log_info_blue("Replay saving is disabled either with an argument or in the config file.")
  368. log_seperator()
  369. try:
  370. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  371. except Exception:
  372. pass
  373. except Exception as e:
  374. log_error('Could not finish checking: {:s}'.format(str(e)))
  375. if "timed out" in str(e):
  376. log_error('The connection timed out, check your internet connection.')
  377. log_seperator()
  378. try:
  379. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  380. except Exception:
  381. pass
  382. sys.exit(1)
  383. except KeyboardInterrupt:
  384. log_info_blue('Aborted checking for livestreams and replays, exiting...'.format(user_to_download))
  385. log_seperator()
  386. try:
  387. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  388. except Exception:
  389. pass
  390. sys.exit(1)
  391. except ClientThrottledError as cte:
  392. log_error('Could not check because you are making too many requests at this time.')
  393. log_seperator()
  394. try:
  395. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  396. except Exception:
  397. pass
  398. sys.exit(1)
  399. def download_replays(broadcasts):
  400. try:
  401. try:
  402. log_info_green('Amount of replays : {:s}'.format(str(len(broadcasts))))
  403. for replay_index, broadcast in enumerate(broadcasts):
  404. bc_dash_manifest = parseString(broadcast.get('dash_manifest')).getElementsByTagName('Period')
  405. bc_duration_raw = bc_dash_manifest[0].getAttribute("duration")
  406. bc_hours = (bc_duration_raw.split("PT"))[1].split("H")[0]
  407. bc_minutes = (bc_duration_raw.split("H"))[1].split("M")[0]
  408. bc_seconds = ((bc_duration_raw.split("M"))[1].split("S")[0]).split('.')[0]
  409. log_info_green('Replay {:s} duration : {:s} minutes and {:s} seconds'.format(str(replay_index + 1), bc_minutes, bc_seconds))
  410. except Exception as e:
  411. log_warn("An error occurred while getting replay duration information: {:s}".format(str(e)))
  412. log_seperator()
  413. log_info_green("Downloading replays... press [CTRL+C] to abort.")
  414. log_seperator()
  415. for replay_index, broadcast in enumerate(broadcasts):
  416. exists = False
  417. if sys.version.split(' ')[0].startswith('2'):
  418. directories = (os.walk(settings.save_path).next()[1])
  419. else:
  420. directories = (os.walk(settings.save_path).__next__()[1])
  421. for directory in directories:
  422. if (str(broadcast.get('id')) in directory) and ("_live_" not in directory):
  423. log_info_blue("Already downloaded a replay with ID '{:s}'.".format(str(broadcast.get('id'))))
  424. exists = True
  425. if not exists:
  426. current = replay_index + 1
  427. log_info_green("Downloading replay {:s} of {:s} with ID '{:s}'...".format(str(current), str(len(broadcasts)), str(broadcast.get('id'))))
  428. current_time = str(int(time.time()))
  429. output_dir = '{}{}_{}_{}_{}_replay_downloads'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  430. broadcast_downloader = replay.Downloader(
  431. mpd=broadcast.get('dash_manifest'),
  432. output_dir=output_dir,
  433. user_agent=instagram_api.user_agent)
  434. open(os.path.join(output_dir, 'folder.lock'), 'a').close()
  435. replay_mp4_file = '{}{}_{}_{}_{}_replay.mp4'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
  436. replay_json_file = os.path.join(output_dir, '{}_{}_{}_{}_replay_comments.json'.format(settings.current_date, user_to_download, broadcast.get('id'), settings.current_time))
  437. if settings.clear_temp_files.title() == "True":
  438. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=True)
  439. else:
  440. replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=False)
  441. if settings.save_comments.title() == "True":
  442. log_info_green("Downloading replay comments...")
  443. try:
  444. get_replay_comments(instagram_api, broadcast, replay_json_file, broadcast_downloader)
  445. except Exception as e:
  446. log_error('An error occurred while downloading comments: {:s}'.format(str(e)))
  447. if (len(replay_saved) == 1):
  448. log_info_green("Finished downloading replay {:s} of {:s}.".format(str(current), str(len(broadcasts))))
  449. try:
  450. os.remove(os.path.join(output_dir, 'folder.lock'))
  451. except Exception:
  452. pass
  453. if (current != len(broadcasts)):
  454. log_seperator()
  455. else:
  456. log_warn("No output video file was made, please merge the files manually if possible.")
  457. log_warn("Check if ffmpeg is available by running ffmpeg in your terminal/cmd prompt.")
  458. log_whiteline()
  459. log_seperator()
  460. log_info_green("Finished downloading all available replays.")
  461. log_seperator()
  462. try:
  463. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  464. except Exception:
  465. pass
  466. sys.exit(0)
  467. except Exception as e:
  468. log_error('Could not save replay: {:s}'.format(str(e)))
  469. log_seperator()
  470. try:
  471. os.remove(os.path.join(output_dir, 'folder.lock'))
  472. except Exception:
  473. pass
  474. try:
  475. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  476. except Exception:
  477. pass
  478. sys.exit(1)
  479. except KeyboardInterrupt:
  480. log_seperator()
  481. log_info_blue('The download has been aborted by the user, exiting...')
  482. log_seperator()
  483. try:
  484. shutil.rmtree(output_dir)
  485. except Exception as e:
  486. log_error("Could not remove temp folder: {:s}".format(str(e)))
  487. sys.exit(1)
  488. try:
  489. os.remove(os.path.join(settings.save_path, user_to_download + '.lock'))
  490. except Exception:
  491. pass
  492. sys.exit(0)
  493. def get_replay_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  494. try:
  495. comments_downloader = CommentsDownloader(
  496. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  497. comments_downloader.get_replay()
  498. try:
  499. if comments_downloader.comments:
  500. comments_log_file = comments_json_file.replace('.json', '.log')
  501. comment_errors, total_comments = CommentsDownloader.generate_log(
  502. comments_downloader.comments, broadcast.get('published_time'), comments_log_file,
  503. comments_delay=0)
  504. if total_comments == 1:
  505. log_info_green("Successfully saved 1 comment to logfile.")
  506. log_seperator()
  507. return True
  508. else:
  509. if comment_errors:
  510. log_warn("Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)))
  511. else:
  512. log_info_green("Successfully saved {:s} comments to logfile.".format(str(total_comments)))
  513. log_seperator()
  514. return True
  515. else:
  516. log_info_green("There are no available comments to save.")
  517. return False
  518. except Exception as e:
  519. log_error('Could not save comments to logfile: {:s}'.format(str(e)))
  520. return False
  521. except KeyboardInterrupt as e:
  522. log_info_blue("Downloading replay comments has been aborted.")
  523. return False
  524. def get_live_comments(instagram_api, broadcast, comments_json_file, broadcast_downloader):
  525. try:
  526. comments_downloader = CommentsDownloader(
  527. api=instagram_api, broadcast=broadcast, destination_file=comments_json_file)
  528. first_comment_created_at = 0
  529. try:
  530. while not broadcast_downloader.is_aborted:
  531. if 'initial_buffered_duration' not in broadcast and broadcast_downloader.initial_buffered_duration:
  532. broadcast['initial_buffered_duration'] = broadcast_downloader.initial_buffered_duration
  533. comments_downloader.broadcast = broadcast
  534. first_comment_created_at = comments_downloader.get_live(first_comment_created_at)
  535. except ClientError as e:
  536. if not 'media has been deleted' in e.error_response:
  537. log_warn("Comment collection ClientError: %d %s" % (e.code, e.error_response))
  538. try:
  539. if comments_downloader.comments:
  540. comments_downloader.save()
  541. comments_log_file = comments_json_file.replace('.json', '.log')
  542. comment_errors, total_comments = CommentsDownloader.generate_log(
  543. comments_downloader.comments, settings.current_time, comments_log_file,
  544. comments_delay=broadcast_downloader.initial_buffered_duration)
  545. if len(comments_downloader.comments) == 1:
  546. log_info_green("Successfully saved 1 comment to logfile.")
  547. log_seperator()
  548. return True
  549. else:
  550. if comment_errors:
  551. log_warn("Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)))
  552. else:
  553. log_info_green("Successfully saved {:s} comments to logfile.".format(str(total_comments)))
  554. log_seperator()
  555. return True
  556. else:
  557. log_info_green("There are no available comments to save.")
  558. return False
  559. log_seperator()
  560. except Exception as e:
  561. log_error('Could not save comments to logfile: {:s}'.format(str(e)))
  562. return False
  563. except KeyboardInterrupt as e:
  564. log_info_blue("Downloading livestream comments has been aborted.")
  565. return False