initialize.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import argparse
  2. import configparser
  3. import logging
  4. import os.path
  5. import subprocess
  6. import sys
  7. import time
  8. import shutil
  9. import json
  10. from .auth import login
  11. from .downloader import start_single, start_multiple
  12. from .logger import log_seperator, supports_color, log_info_blue, log_info_green, log_warn, log_error, log_whiteline, log_plain
  13. from .settings import settings
  14. script_version = "2.5.8@master"
  15. python_version = sys.version.split(' ')[0]
  16. bool_values = {'True', 'False'}
  17. def check_ffmpeg():
  18. try:
  19. FNULL = open(os.devnull, 'w')
  20. if settings.ffmpeg_path == None:
  21. subprocess.call(["ffmpeg"], stdout=FNULL, stderr=subprocess.STDOUT)
  22. else:
  23. subprocess.call([settings.ffmpeg_path], stdout=FNULL, stderr=subprocess.STDOUT)
  24. return True
  25. except OSError as e:
  26. return False
  27. def check_pyinstalive():
  28. try:
  29. FNULL = open(os.devnull, 'w')
  30. subprocess.call(["pyinstalive"], stdout=FNULL, stderr=subprocess.STDOUT)
  31. return True
  32. except OSError as e:
  33. return False
  34. def check_config_validity(config, args=None):
  35. try:
  36. has_thrown_errors = False
  37. settings.username = config.get('pyinstalive', 'username')
  38. settings.password = config.get('pyinstalive', 'password')
  39. try:
  40. settings.show_cookie_expiry = config.get('pyinstalive', 'show_cookie_expiry').title()
  41. if not settings.show_cookie_expiry in bool_values:
  42. log_warn("Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)")
  43. settings.show_cookie_expiry = 'true'
  44. has_thrown_errors = True
  45. except:
  46. log_warn("Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)")
  47. settings.show_cookie_expiry = 'true'
  48. has_thrown_errors = True
  49. try:
  50. settings.clear_temp_files = config.get('pyinstalive', 'clear_temp_files').title()
  51. if not settings.clear_temp_files in bool_values:
  52. log_warn("Invalid or missing setting detected for 'clear_temp_files', using default value (True)")
  53. settings.clear_temp_files = 'true'
  54. has_thrown_errors = True
  55. except:
  56. log_warn("Invalid or missing setting detected for 'clear_temp_files', using default value (True)")
  57. settings.clear_temp_files = 'true'
  58. has_thrown_errors = True
  59. try:
  60. settings.save_replays = config.get('pyinstalive', 'save_replays').title()
  61. if not settings.save_replays in bool_values:
  62. log_warn("Invalid or missing setting detected for 'save_replays', using default value (True)")
  63. settings.save_replays = 'true'
  64. has_thrown_errors = True
  65. except:
  66. log_warn("Invalid or missing setting detected for 'save_replays', using default value (True)")
  67. settings.save_replays = 'true'
  68. has_thrown_errors = True
  69. try:
  70. settings.save_lives = config.get('pyinstalive', 'save_lives').title()
  71. if not settings.save_lives in bool_values:
  72. log_warn("Invalid or missing setting detected for 'save_lives', using default value (True)")
  73. settings.save_lives = 'true'
  74. has_thrown_errors = True
  75. except:
  76. log_warn("Invalid or missing setting detected for 'save_lives', using default value (True)")
  77. settings.save_lives = 'true'
  78. has_thrown_errors = True
  79. try:
  80. settings.log_to_file = config.get('pyinstalive', 'log_to_file').title()
  81. if not settings.log_to_file in bool_values:
  82. log_warn("Invalid or missing setting detected for 'log_to_file', using default value (False)")
  83. settings.log_to_file = 'False'
  84. has_thrown_errors = True
  85. except:
  86. log_warn("Invalid or missing setting detected for 'log_to_file', using default value (False)")
  87. settings.log_to_file = 'False'
  88. has_thrown_errors = True
  89. try:
  90. settings.run_at_start = config.get('pyinstalive', 'run_at_start').replace("\\", "\\\\")
  91. if not settings.run_at_start:
  92. settings.run_at_start = "None"
  93. except:
  94. log_warn("Invalid or missing settings detected for 'run_at_start', using default value (empty)")
  95. settings.run_at_start = "None"
  96. has_thrown_errors = True
  97. try:
  98. settings.run_at_finish = config.get('pyinstalive', 'run_at_finish').replace("\\", "\\\\")
  99. if not settings.run_at_finish:
  100. settings.run_at_finish = "None"
  101. except:
  102. log_warn("Invalid or missing settings detected for 'run_at_finish', using default value (empty)")
  103. settings.run_at_finish = "None"
  104. has_thrown_errors = True
  105. try:
  106. settings.save_comments = config.get('pyinstalive', 'save_comments').title()
  107. wide_build = sys.maxunicode > 65536
  108. if sys.version.split(' ')[0].startswith('2') and settings.save_comments == "True" and not wide_build:
  109. log_warn("Your Python 2 build does not support wide unicode characters.")
  110. log_warn("This means characters such as emojis will not be saved.")
  111. has_thrown_errors = True
  112. else:
  113. if not settings.show_cookie_expiry in bool_values:
  114. log_warn("Invalid or missing setting detected for 'save_comments', using default value (False)")
  115. settings.save_comments = 'false'
  116. has_thrown_errors = True
  117. except:
  118. log_warn("Invalid or missing setting detected for 'save_comments', using default value (False)")
  119. settings.save_comments = 'false'
  120. has_thrown_errors = True
  121. try:
  122. if args and args.savepath:
  123. args.savepath = args.savepath.replace("\"", "")
  124. print(args.savepath)
  125. if (os.path.exists(args.savepath)) and (args.savepath != config.get('pyinstalive', 'save_path')):
  126. settings.save_path = args.savepath
  127. log_info_blue("Overriding save path: {:s}".format(args.savepath))
  128. log_seperator()
  129. elif (args.savepath != config.get('pyinstalive', 'save_path')):
  130. log_warn("Custom save path does not exist, falling back to path specified in config.")
  131. settings.save_path = config.get('pyinstalive', 'save_path')
  132. log_seperator()
  133. else:
  134. settings.save_path = config.get('pyinstalive', 'save_path')
  135. else:
  136. settings.save_path = config.get('pyinstalive', 'save_path')
  137. if not settings.save_path.endswith('/'):
  138. settings.save_path = settings.save_path + '/'
  139. if (os.path.exists(settings.save_path)):
  140. pass
  141. else:
  142. log_warn("Invalid or missing setting detected for 'save_path', falling back to path: {:s}".format(os.getcwd()))
  143. settings.save_path = os.getcwd()
  144. has_thrown_errors = True
  145. except:
  146. log_warn("Invalid or missing setting detected for 'save_path', falling back to path: {:s}".format(os.getcwd()))
  147. settings.save_path = os.getcwd()
  148. has_thrown_errors = True
  149. try:
  150. settings.ffmpeg_path = config.get('pyinstalive', 'ffmpeg_path')
  151. if (len(settings.ffmpeg_path) > 1) and (os.path.exists(settings.ffmpeg_path)):
  152. log_info_blue("Overriding FFmpeg path: {:s}".format(settings.ffmpeg_path))
  153. log_seperator()
  154. else:
  155. if (len(settings.ffmpeg_path) > 1):
  156. log_warn("Invalid setting detected for 'ffmpeg_path', falling back to environment variable.")
  157. has_thrown_errors = True
  158. settings.ffmpeg_path = None
  159. except:
  160. log_warn("Invalid or missing setting detected for 'ffmpeg_path', falling back to environment variable.")
  161. settings.ffmpeg_path = None
  162. has_thrown_errors = True
  163. if has_thrown_errors:
  164. log_seperator()
  165. return True
  166. except Exception as e:
  167. print(str(e))
  168. return False
  169. def show_info(config):
  170. if os.path.exists(settings.custom_config_path):
  171. try:
  172. config.read(settings.custom_config_path)
  173. except Exception as e:
  174. log_error("Could not read configuration file: {:s}".format(str(e)))
  175. log_seperator()
  176. else:
  177. new_config()
  178. sys.exit(1)
  179. if not check_config_validity(config):
  180. log_warn("Config file is not valid, some information may be inaccurate.")
  181. log_whiteline()
  182. cookie_files = []
  183. cookie_from_config = ''
  184. try:
  185. for file in os.listdir(os.getcwd()):
  186. if file.endswith(".json"):
  187. with open(file) as data_file:
  188. try:
  189. json_data = json.load(data_file)
  190. if (json_data.get('created_ts')):
  191. cookie_files.append(file)
  192. except Exception as e:
  193. pass
  194. if settings.username == file.replace(".json", ''):
  195. cookie_from_config = file
  196. except Exception as e:
  197. log_warn("Could not check for cookie files: {:s}".format(str(e)))
  198. log_whiteline()
  199. log_info_green("To see all the available arguments, use the -h argument.")
  200. log_whiteline()
  201. log_info_green("PyInstaLive version: {:s}".format(script_version))
  202. log_info_green("Python version: {:s}".format(python_version))
  203. if not check_ffmpeg():
  204. log_error("FFmpeg framework: Not found")
  205. else:
  206. log_info_green("FFmpeg framework: Available")
  207. if (len(cookie_from_config) > 0):
  208. log_info_green("Cookie files: {:s} ({:s} matches config user)".format(str(len(cookie_files)), cookie_from_config))
  209. elif len(cookie_files) > 0:
  210. log_info_green("Cookie files: {:s}".format(str(len(cookie_files))))
  211. else:
  212. log_warn("Cookie files: None found")
  213. log_info_green("CLI supports color: {:s}".format(str(supports_color()[0])))
  214. log_info_green("File to run at start: {:s}".format(settings.run_at_start))
  215. log_info_green("File to run at finish: {:s}".format(settings.run_at_finish))
  216. log_whiteline()
  217. if os.path.exists(settings.custom_config_path):
  218. log_info_green("Config file:")
  219. log_whiteline()
  220. with open(settings.custom_config_path) as f:
  221. for line in f:
  222. log_plain(" {:s}".format(line.rstrip()))
  223. else:
  224. log_error("Config file: Not found")
  225. log_whiteline()
  226. log_info_green("End of PyInstaLive information screen.")
  227. log_seperator()
  228. def new_config():
  229. try:
  230. if os.path.exists(settings.custom_config_path):
  231. log_info_green("A configuration file is already present:")
  232. log_whiteline()
  233. with open(settings.custom_config_path) as f:
  234. for line in f:
  235. log_plain(" {:s}".format(line.rstrip()))
  236. log_whiteline()
  237. log_info_green("To create a default config file, delete 'pyinstalive.ini' and run this script again.")
  238. log_seperator()
  239. else:
  240. try:
  241. log_warn("Could not find configuration file, creating a default one...")
  242. config_template = """
  243. [pyinstalive]
  244. username = johndoe
  245. password = grapefruits
  246. save_path = {:s}
  247. ffmpeg_path =
  248. show_cookie_expiry = true
  249. clear_temp_files = false
  250. save_lives = true
  251. save_replays = true
  252. run_at_start =
  253. run_at_finish =
  254. save_comments = false
  255. log_to_file = false
  256. """.format(os.getcwd())
  257. config_file = open(settings.custom_config_path, "w")
  258. config_file.write(config_template.strip())
  259. config_file.close()
  260. log_warn("Edit the created 'pyinstalive.ini' file and run this script again.")
  261. log_seperator()
  262. sys.exit(0)
  263. except Exception as e:
  264. log_error("Could not create default config file: {:s}".format(str(e)))
  265. log_warn("You must manually create and edit it with the following template: ")
  266. log_whiteline()
  267. for line in config_template.strip().splitlines():
  268. log_plain(" {:s}".format(line.rstrip()))
  269. log_whiteline()
  270. log_warn("Save it as 'pyinstalive.ini' and run this script again.")
  271. log_seperator()
  272. except Exception as e:
  273. log_error("An error occurred: {:s}".format(str(e)))
  274. log_warn("If you don't have a configuration file, manually create and edit one with the following template:")
  275. log_whiteline()
  276. log_plain(config_template)
  277. log_whiteline()
  278. log_warn("Save it as 'pyinstalive.ini' and run this script again.")
  279. log_seperator()
  280. def clean_download_dir():
  281. dir_delcount = 0
  282. error_count = 0
  283. lock_count = 0
  284. log_info_green('Cleaning up temporary files and folders...')
  285. try:
  286. if sys.version.split(' ')[0].startswith('2'):
  287. directories = (os.walk(settings.save_path).next()[1])
  288. files = (os.walk(settings.save_path).next()[2])
  289. else:
  290. directories = (os.walk(settings.save_path).__next__()[1])
  291. files = (os.walk(settings.save_path).__next__()[2])
  292. for directory in directories:
  293. if directory.endswith('_downloads'):
  294. if not any(filename.endswith('.lock') for filename in os.listdir(settings.save_path + directory)):
  295. try:
  296. shutil.rmtree(settings.save_path + directory)
  297. dir_delcount += 1
  298. except Exception as e:
  299. log_error("Could not remove temp folder: {:s}".format(str(e)))
  300. error_count += 1
  301. else:
  302. lock_count += 1
  303. log_seperator()
  304. log_info_green('The cleanup has finished.')
  305. if dir_delcount == 0 and error_count == 0 and lock_count == 0:
  306. log_info_green('No folders were removed.')
  307. log_seperator()
  308. return
  309. log_info_green('Folders removed: {:d}'.format(dir_delcount))
  310. log_info_green('Locked folders: {:d}'.format(lock_count))
  311. log_info_green('Errors: {:d}'.format(error_count))
  312. log_seperator()
  313. except KeyboardInterrupt as e:
  314. log_seperator()
  315. log_warn("The cleanup has been aborted.")
  316. if dir_delcount == 0 and error_count == 0 and lock_count == 0:
  317. log_info_green('No folders were removed.')
  318. log_seperator()
  319. return
  320. log_info_green('Folders removed: {:d}'.format(dir_delcount))
  321. log_info_green('Locked folders: {:d}'.format(lock_count))
  322. log_info_green('Errors: {:d}'.format(error_count))
  323. log_seperator()
  324. def run():
  325. logging.disable(logging.CRITICAL)
  326. config = configparser.ConfigParser()
  327. parser = argparse.ArgumentParser(description="You are running PyInstaLive {:s} using Python {:s}".format(script_version, python_version))
  328. parser.add_argument('-u', '--username', dest='username', type=str, required=False, help="Instagram username to login with.")
  329. parser.add_argument('-p', '--password', dest='password', type=str, required=False, help="Instagram password to login with.")
  330. parser.add_argument('-r', '--record', dest='download', type=str, required=False, help="The username of the user whose livestream or replay you want to save.")
  331. parser.add_argument('-d', '--download', dest='download', type=str, required=False, help="The username of the user whose livestream or replay you want to save.")
  332. parser.add_argument('-i', '--info', dest='info', action='store_true', help="View information about PyInstaLive.")
  333. parser.add_argument('-c', '--config', dest='config', action='store_true', help="Create a default configuration file if it doesn't exist.")
  334. parser.add_argument('-nr', '--noreplays', dest='noreplays', action='store_true', help="When used, do not check for any available replays.")
  335. parser.add_argument('-nl', '--nolives', dest='nolives', action='store_true', help="When used, do not check for any available livestreams.")
  336. parser.add_argument('-cl', '--clean', dest='clean', action='store_true', help="PyInstaLive will clean the current download folder of all leftover files.")
  337. parser.add_argument('-df', '--downloadfollowing', dest='downloadfollowing', action='store_true', help="PyInstaLive will check for available livestreams and replays from users the account used to login follows.")
  338. parser.add_argument('-cp', '--configpath', dest='configpath', type=str, required=False, help="Path to a PyInstaLive configuration file.")
  339. parser.add_argument('-sp', '--savepath', dest='savepath', type=str, required=False, help="Path to folder where PyInstaLive should save livestreams and replays.")
  340. # Workaround to 'disable' argument abbreviations
  341. parser.add_argument('--usernamx', help=argparse.SUPPRESS, metavar='IGNORE')
  342. parser.add_argument('--passworx', help=argparse.SUPPRESS, metavar='IGNORE')
  343. parser.add_argument('--recorx', help=argparse.SUPPRESS, metavar='IGNORE')
  344. parser.add_argument('--infx', help=argparse.SUPPRESS, metavar='IGNORE')
  345. parser.add_argument('--confix', help=argparse.SUPPRESS, metavar='IGNORE')
  346. parser.add_argument('--noreplayx', help=argparse.SUPPRESS, metavar='IGNORE')
  347. parser.add_argument('--cleax', help=argparse.SUPPRESS, metavar='IGNORE')
  348. parser.add_argument('--downloadfollowinx', help=argparse.SUPPRESS, metavar='IGNORE')
  349. parser.add_argument('--configpatx', help=argparse.SUPPRESS, metavar='IGNORE')
  350. parser.add_argument('-cx', help=argparse.SUPPRESS, metavar='IGNORE')
  351. parser.add_argument('-nx', help=argparse.SUPPRESS, metavar='IGNORE')
  352. parser.add_argument('-dx', help=argparse.SUPPRESS, metavar='IGNORE')
  353. args, unknown_args = parser.parse_known_args()
  354. if args.configpath and os.path.exists(args.configpath):
  355. settings.custom_config_path = args.configpath
  356. try:
  357. config.read(settings.custom_config_path)
  358. settings.log_to_file = config.get('pyinstalive', 'log_to_file').title()
  359. if not settings.log_to_file in bool_values:
  360. settings.log_to_file = 'False'
  361. elif settings.log_to_file == "True":
  362. if args.download:
  363. settings.user_to_download = args.download
  364. try:
  365. with open("pyinstalive{:s}.log".format("_" + settings.user_to_download if len(settings.user_to_download) > 0 else ".default"),"a+") as f:
  366. f.write("\n")
  367. f.close()
  368. except:
  369. pass
  370. except Exception as e:
  371. settings.log_to_file = 'False'
  372. pass # Pretend nothing happened
  373. log_seperator()
  374. log_info_blue('PYINSTALIVE (SCRIPT V{:s} - PYTHON V{:s}) - {:s}'.format(script_version, python_version, time.strftime('%I:%M:%S %p')))
  375. log_seperator()
  376. if args.configpath and settings.custom_config_path != 'pyinstalive.ini':
  377. log_info_blue("Overriding config path: {:s}".format(args.configpath))
  378. log_seperator()
  379. elif args.configpath and settings.custom_config_path == 'pyinstalive.ini':
  380. log_warn("Custom config path does not exist, falling back to path: {:s}".format(os.getcwd()))
  381. log_seperator()
  382. if unknown_args:
  383. log_error("The following invalid argument(s) were provided: ")
  384. log_whiteline()
  385. log_info_blue(' ' + ' '.join(unknown_args))
  386. log_whiteline()
  387. if (supports_color()[1] == True):
  388. log_info_green("'pyinstalive -h' can be used to display command help.")
  389. else:
  390. log_plain("pyinstalive -h can be used to display command help.")
  391. log_seperator()
  392. exit(1)
  393. if (args.info) or (not
  394. args.username and not
  395. args.password and not
  396. args.download and not
  397. args.downloadfollowing and not
  398. args.info and not
  399. args.config and not
  400. args.noreplays and not
  401. args.nolives and not
  402. args.clean and not
  403. args.configpath and not
  404. args.savepath):
  405. show_info(config)
  406. sys.exit(0)
  407. if (args.config):
  408. new_config()
  409. sys.exit(0)
  410. if os.path.exists(settings.custom_config_path):
  411. try:
  412. config.read(settings.custom_config_path)
  413. except Exception:
  414. log_error("Could not read configuration file.")
  415. log_seperator()
  416. else:
  417. new_config()
  418. sys.exit(1)
  419. if check_config_validity(config, args):
  420. try:
  421. if (args.clean):
  422. clean_download_dir()
  423. sys.exit(0)
  424. if not check_ffmpeg():
  425. log_error("Could not find ffmpeg, the script will now exit. ")
  426. log_seperator()
  427. sys.exit(1)
  428. if (args.noreplays):
  429. settings.save_replays = "False"
  430. if (args.nolives):
  431. settings.save_lives = "False"
  432. if settings.save_lives == "False" and settings.save_replays == "False":
  433. log_warn("Script will not run because both live and replay saving is disabled.")
  434. log_seperator()
  435. sys.exit(1)
  436. if not args.download and not args.downloadfollowing:
  437. log_warn("Neither argument -d or -df was passed. Please use one of the two and try again.")
  438. log_seperator()
  439. sys.exit(1)
  440. if args.download and args.downloadfollowing:
  441. log_warn("You can't pass both the -d and -df arguments. Please use one of the two and try again.")
  442. log_seperator()
  443. sys.exit(1)
  444. if (args.username is not None) and (args.password is not None):
  445. api = login(args.username, args.password, settings.show_cookie_expiry, True)
  446. elif (args.username is not None) or (args.password is not None):
  447. log_warn("Missing --username or --password argument, falling back to configuration file...")
  448. if (not len(settings.username) > 0) or (not len(settings.password) > 0):
  449. log_error("Username or password are missing. Please check your configuration file and try again.")
  450. log_seperator()
  451. sys.exit(1)
  452. else:
  453. api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
  454. else:
  455. if (not len(settings.username) > 0) or (not len(settings.password) > 0):
  456. log_error("Username or password are missing. Please check your configuration file and try again.")
  457. log_seperator()
  458. sys.exit(1)
  459. else:
  460. api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
  461. if args.download and not args.downloadfollowing:
  462. start_single(api, args.download, settings)
  463. if not args.download and args.downloadfollowing:
  464. if check_pyinstalive():
  465. start_multiple(api, settings, "pyinstalive")
  466. else:
  467. log_warn("You probably ran PyInstaLive as a script module with the -m argument.")
  468. log_warn("PyInstaLive should be properly installed when using the -df argument.")
  469. log_seperator()
  470. if python_version[0] == "3":
  471. start_multiple(api, settings, "python3 -m pyinstalive")
  472. else:
  473. start_multiple(api, settings, "python -m pyinstalive")
  474. except KeyboardInterrupt as ee:
  475. log_warn("Pre-download checks have been aborted, exiting...")
  476. log_seperator()
  477. else:
  478. log_error("The configuration file is not valid. Please double-check and try again.")
  479. log_seperator()
  480. sys.exit(1)