downloader.py 24 KB

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