downloader.py 23 KB

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