initialize.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import argparse
  2. import configparser
  3. import logging
  4. import os.path
  5. import sys
  6. import subprocess
  7. import time
  8. from .auth import login
  9. from .logger import log, seperator, supports_color
  10. from .downloader import main
  11. from .settings import settings
  12. script_version = "2.3.6"
  13. python_version = sys.version.split(' ')[0]
  14. bool_values = {'True', 'False'}
  15. def check_ffmpeg():
  16. try:
  17. FNULL = open(os.devnull, 'w')
  18. subprocess.call(["ffmpeg"], stdout=FNULL, stderr=subprocess.STDOUT)
  19. return True
  20. except OSError as e:
  21. return False
  22. def check_config_validity(config):
  23. try:
  24. settings.username = config.get('pyinstalive', 'username')
  25. settings.password = config.get('pyinstalive', 'password')
  26. try:
  27. settings.show_cookie_expiry = config.get('pyinstalive', 'show_cookie_expiry').title()
  28. if not settings.show_cookie_expiry in bool_values:
  29. log("[W] Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)", "YELLOW")
  30. settings.show_cookie_expiry = 'true'
  31. except:
  32. log("[W] Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)", "YELLOW")
  33. settings.show_cookie_expiry = 'true'
  34. try:
  35. settings.clear_temp_files = config.get('pyinstalive', 'clear_temp_files').title()
  36. if not settings.clear_temp_files in bool_values:
  37. log("[W] Invalid or missing setting detected for 'clear_temp_files', using default value (True)", "YELLOW")
  38. settings.clear_temp_files = 'true'
  39. except:
  40. log("[W] Invalid or missing setting detected for 'clear_temp_files', using default value (True)", "YELLOW")
  41. settings.clear_temp_files = 'true'
  42. try:
  43. settings.save_replays = config.get('pyinstalive', 'save_replays').title()
  44. if not settings.save_replays in bool_values:
  45. log("[W] Invalid or missing setting detected for 'save_replays', using default value (True)", "YELLOW")
  46. settings.save_replays = 'true'
  47. except:
  48. log("[W] Invalid or missing setting detected for 'save_replays', using default value (True)", "YELLOW")
  49. settings.save_replays = 'true'
  50. try:
  51. settings.run_at_start = config.get('pyinstalive', 'run_at_start')
  52. if (settings.run_at_start):
  53. if not os.path.isfile(settings.run_at_start):
  54. log("[W] Path to file given for 'run_at_start' does not exist, using default value (None)", "YELLOW")
  55. settings.run_at_start = "None"
  56. else:
  57. if not settings.run_at_start.split('.')[-1] == 'py':
  58. log("[W] File given for 'run_at_start' is not a Python script, using default value (None)", "YELLOW")
  59. settings.run_at_start = "None"
  60. else:
  61. settings.run_at_start = "None"
  62. except:
  63. log("[W] Invalid or missing settings detected for 'run_at_start', using default value (None)", "YELLOW")
  64. settings.run_at_start = "None"
  65. try:
  66. settings.run_at_finish = config.get('pyinstalive', 'run_at_finish')
  67. if (settings.run_at_finish):
  68. if not os.path.isfile(settings.run_at_finish):
  69. log("[W] Path to file given for 'run_at_finish' does not exist, using default value (None)", "YELLOW")
  70. settings.run_at_finish = "None"
  71. else:
  72. if not settings.run_at_finish.split('.')[-1] == 'py':
  73. log("[W] File given for 'run_at_finish' is not a Python script, using default value (None)", "YELLOW")
  74. settings.run_at_finish = "None"
  75. else:
  76. settings.run_at_finish = "None"
  77. except:
  78. log("[W] Invalid or missing settings detected for 'run_at_finish', using default value (None)", "YELLOW")
  79. settings.run_at_finish = "None"
  80. try:
  81. settings.save_path = config.get('pyinstalive', 'save_path')
  82. if (os.path.exists(settings.save_path)):
  83. pass
  84. else:
  85. log("[W] Invalid or missing setting detected for 'save_path', falling back to path: " + os.getcwd(), "YELLOW")
  86. settings.save_path = os.getcwd()
  87. if not settings.save_path.endswith('/'):
  88. settings.save_path = settings.save_path + '/'
  89. except:
  90. log("[W] Invalid or missing setting detected for 'save_path', falling back to path: " + os.getcwd(), "YELLOW")
  91. settings.save_path = os.getcwd()
  92. if not (len(settings.username) > 0):
  93. log("[E] Invalid or missing setting detected for 'username'.", "RED")
  94. return False
  95. if not (len(settings.password) > 0):
  96. log("[E] Invalid or missing setting detected for 'password'.", "RED")
  97. return False
  98. return True
  99. except Exception as e:
  100. return False
  101. def show_info(config):
  102. if os.path.exists('pyinstalive.ini'):
  103. try:
  104. config.read('pyinstalive.ini')
  105. except Exception:
  106. log("[E] Could not read configuration file.", "RED")
  107. seperator("GREEN")
  108. else:
  109. new_config()
  110. sys.exit(1)
  111. if not check_config_validity(config):
  112. log("[W] Config file is not valid, some information may be inaccurate.", "YELLOW")
  113. log("", "GREEN")
  114. cookie_files = []
  115. cookie_from_config = ''
  116. try:
  117. for file in os.listdir(os.getcwd()):
  118. if file.endswith(".json"):
  119. cookie_files.append(file)
  120. if settings.username == file.replace(".json", ''):
  121. cookie_from_config = file
  122. except Exception as e:
  123. log("[W] Could not check for cookie files: " + str(e), "YELLOW")
  124. log("", "ENDC")
  125. log("[I] To see all the available flags, use the -h flag.", "BLUE")
  126. log("", "GREEN")
  127. log("[I] PyInstaLive version: " + script_version, "GREEN")
  128. log("[I] Python version: " + python_version, "GREEN")
  129. if check_ffmpeg() == False:
  130. log("[E] FFmpeg framework: Not found", "RED")
  131. else:
  132. log("[I] FFmpeg framework: Available", "GREEN")
  133. if (len(cookie_from_config) > 0):
  134. log("[I] Cookie files: {} ({} matches config user)".format(str(len(cookie_files)), cookie_from_config), "GREEN")
  135. elif len(cookie_files) > 0:
  136. log("[I] Cookie files: {}".format(str(len(cookie_files))), "GREEN")
  137. else:
  138. log("[W] Cookie files: None found", "YELLOW")
  139. log("[I] CLI supports color: " + str(supports_color()), "GREEN")
  140. log("[I] File to run at start: " + settings.run_at_start, "GREEN")
  141. log("[I] File to run at finish: " + settings.run_at_finish, "GREEN")
  142. log("", "GREEN")
  143. if os.path.exists('pyinstalive.ini'):
  144. log("[I] Config file:", "GREEN")
  145. log("", "GREEN")
  146. with open('pyinstalive.ini') as f:
  147. for line in f:
  148. log(" " + line.rstrip(), "YELLOW")
  149. else:
  150. log("[E] Config file: Not found", "RED")
  151. log("", "GREEN")
  152. log("[I] End of PyInstaLive information screen.", "GREEN")
  153. seperator("GREEN")
  154. def new_config():
  155. try:
  156. if os.path.exists('pyinstalive.ini'):
  157. log("[I] A configuration file is already present:", "GREEN")
  158. log("", "GREEN")
  159. with open('pyinstalive.ini') as f:
  160. for line in f:
  161. log(" " + line.rstrip(), "YELLOW")
  162. log("", "GREEN")
  163. log("[W] To create a default config file, delete 'pyinstalive.ini' and ", "YELLOW")
  164. log(" run this script again.", "YELLOW")
  165. seperator("GREEN")
  166. else:
  167. try:
  168. log("[W] Could not find configuration file, creating a default one...", "YELLOW")
  169. config_template = "[pyinstalive]\nusername = johndoe\npassword = grapefruits\nsave_path = " + os.getcwd() + "\nshow_cookie_expiry = true\nclear_temp_files = false\nsave_replays = true\nrun_at_start = \nrun_at_finish = \n"
  170. config_file = open("pyinstalive.ini", "w")
  171. config_file.write(config_template)
  172. config_file.close()
  173. log("[W] Edit the created 'pyinstalive.ini' file and run this script again.", "YELLOW")
  174. seperator("GREEN")
  175. sys.exit(0)
  176. except Exception as e:
  177. log("[E] Could not create default config file: " + str(e), "RED")
  178. log("[W] You must manually create and edit it with the following template: ", "YELLOW")
  179. log("", "GREEN")
  180. log(config_template, "YELLOW")
  181. log("", "GREEN")
  182. log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
  183. seperator("GREEN")
  184. except Exception as e:
  185. log("[E] An error occurred: " + str(e), "RED")
  186. log("[W] If you don't have a configuration file, you must", "YELLOW")
  187. log(" manually create and edit it with the following template: ", "YELLOW")
  188. log("", "GREEN")
  189. log(config_template, "YELLOW")
  190. log("", "GREEN")
  191. log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
  192. seperator("GREEN")
  193. def run():
  194. seperator("GREEN")
  195. log('PYINSTALIVE (SCRIPT V{} - PYTHON V{}) - {}'.format(script_version, python_version, time.strftime('%I:%M:%S %p')), "GREEN")
  196. seperator("GREEN")
  197. logging.disable(logging.CRITICAL)
  198. config = configparser.ConfigParser()
  199. parser = argparse.ArgumentParser(description='You are running PyInstaLive ' + script_version + " using Python " + python_version)
  200. parser.add_argument('-u', '--username', dest='username', type=str, required=False, help="Instagram username to login with.")
  201. parser.add_argument('-p', '--password', dest='password', type=str, required=False, help="Instagram password to login with.")
  202. parser.add_argument('-r', '--record', dest='record', type=str, required=False, help="The username of the user whose livestream or replay you want to save.")
  203. parser.add_argument('-i', '--info', dest='info', action='store_true', help="View information about PyInstaLive.")
  204. parser.add_argument('-c', '--config', dest='config', action='store_true', help="Create a default configuration file if it doesn't exist.")
  205. parser.add_argument('-nr', '--noreplays', dest='noreplays', action='store_true', help="When used, do not check for any available replays.")
  206. # Workaround to 'disable' argument abbreviations
  207. parser.add_argument('--usernamx', help=argparse.SUPPRESS, metavar='IGNORE')
  208. parser.add_argument('--passworx', help=argparse.SUPPRESS, metavar='IGNORE')
  209. parser.add_argument('--recorx', help=argparse.SUPPRESS, metavar='IGNORE')
  210. parser.add_argument('--infx', help=argparse.SUPPRESS, metavar='IGNORE')
  211. parser.add_argument('--confix', help=argparse.SUPPRESS, metavar='IGNORE')
  212. parser.add_argument('--noreplayx', help=argparse.SUPPRESS, metavar='IGNORE')
  213. # Erase line that tells the user the error has to do with ambiguous arguments
  214. try:
  215. args = parser.parse_args()
  216. except SystemExit as e:
  217. args_raw = sys.argv[1:]
  218. if "-h" not in args_raw and "--help" not in args_raw:
  219. CURSOR_UP_ONE = '\x1b[1A'
  220. ERASE_LINE = '\x1b[2K'
  221. log(CURSOR_UP_ONE + ERASE_LINE + CURSOR_UP_ONE + "[E] Invalid argument(s) were provided in command: " + ' ' * 50, "RED")
  222. log(" pyinstalive " + ' '.join(args_raw), "YELLOW")
  223. log("\n[I] Usage for PyInstaLive is printed below.\n", "GREEN")
  224. parser.print_help()
  225. sys.exit(1)
  226. else:
  227. sys.exit(0)
  228. if (args.username == None
  229. and args.password == None
  230. and args.record == None
  231. and args.info == False
  232. and args.config == False) or (args.info != False):
  233. show_info(config)
  234. sys.exit(0)
  235. if (args.config == True):
  236. new_config()
  237. sys.exit(0)
  238. if os.path.exists('pyinstalive.ini'):
  239. try:
  240. config.read('pyinstalive.ini')
  241. except Exception:
  242. log("[E] Could not read configuration file. Try passing the required arguments manually.", "RED")
  243. seperator("GREEN")
  244. else:
  245. new_config()
  246. sys.exit(1)
  247. if check_config_validity(config):
  248. if check_ffmpeg() == False:
  249. log("[E] Could not find ffmpeg, the script will now exit. ", "RED")
  250. seperator("GREEN")
  251. sys.exit(1)
  252. if (args.record == None):
  253. log("[E] Missing --record argument. Please specify an Instagram username.", "RED")
  254. seperator("GREEN")
  255. sys.exit(1)
  256. if (args.noreplays == True):
  257. settings.save_replays = "false"
  258. if (args.username is not None) and (args.password is not None):
  259. api = login(args.username, args.password, settings.show_cookie_expiry, True)
  260. else:
  261. if (args.username is not None) or (args.password is not None):
  262. log("[W] Missing -u or -p arguments, falling back to config login...", "YELLOW")
  263. api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
  264. main(api, args.record, settings)
  265. else:
  266. log("[E] The configuration file is not valid. Please check your configuration settings and try again.", "RED")
  267. seperator("GREEN")
  268. sys.exit(0)