initialize.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. from .auth import login
  10. from .downloader import main
  11. from .logger import log
  12. from .logger import seperator
  13. from .logger import supports_color
  14. from .settings import settings
  15. script_version = "2.5.2"
  16. python_version = sys.version.split(' ')[0]
  17. bool_values = {'True', 'False'}
  18. def check_ffmpeg():
  19. try:
  20. FNULL = open(os.devnull, 'w')
  21. subprocess.call(["ffmpeg"], stdout=FNULL, stderr=subprocess.STDOUT)
  22. return True
  23. except OSError as e:
  24. return False
  25. def check_config_validity(config):
  26. try:
  27. has_thrown_errors = False
  28. settings.username = config.get('pyinstalive', 'username')
  29. settings.password = config.get('pyinstalive', 'password')
  30. try:
  31. settings.show_cookie_expiry = config.get('pyinstalive', 'show_cookie_expiry').title()
  32. if not settings.show_cookie_expiry in bool_values:
  33. log("[W] Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)", "YELLOW")
  34. settings.show_cookie_expiry = 'true'
  35. has_thrown_errors = True
  36. except:
  37. log("[W] Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)", "YELLOW")
  38. settings.show_cookie_expiry = 'true'
  39. has_thrown_errors = True
  40. try:
  41. settings.clear_temp_files = config.get('pyinstalive', 'clear_temp_files').title()
  42. if not settings.clear_temp_files in bool_values:
  43. log("[W] Invalid or missing setting detected for 'clear_temp_files', using default value (True)", "YELLOW")
  44. settings.clear_temp_files = 'true'
  45. has_thrown_errors = True
  46. except:
  47. log("[W] Invalid or missing setting detected for 'clear_temp_files', using default value (True)", "YELLOW")
  48. settings.clear_temp_files = 'true'
  49. has_thrown_errors = True
  50. try:
  51. settings.save_replays = config.get('pyinstalive', 'save_replays').title()
  52. if not settings.save_replays in bool_values:
  53. log("[W] Invalid or missing setting detected for 'save_replays', using default value (True)", "YELLOW")
  54. settings.save_replays = 'true'
  55. has_thrown_errors = True
  56. except:
  57. log("[W] Invalid or missing setting detected for 'save_replays', using default value (True)", "YELLOW")
  58. settings.save_replays = 'true'
  59. has_thrown_errors = True
  60. try:
  61. settings.log_to_file = config.get('pyinstalive', 'log_to_file').title()
  62. if not settings.log_to_file in bool_values:
  63. log("[W] Invalid or missing setting detected for 'log_to_file', using default value (False)", "YELLOW")
  64. settings.log_to_file = 'False'
  65. has_thrown_errors = True
  66. except:
  67. log("[W] Invalid or missing setting detected for 'log_to_file', using default value (False)", "YELLOW")
  68. settings.log_to_file = 'False'
  69. has_thrown_errors = True
  70. try:
  71. settings.run_at_start = config.get('pyinstalive', 'run_at_start').replace("\\", "\\\\")
  72. if not settings.run_at_start:
  73. settings.run_at_start = "None"
  74. except:
  75. log("[W] Invalid or missing settings detected for 'run_at_start', using default value (None)", "YELLOW")
  76. settings.run_at_start = "None"
  77. has_thrown_errors = True
  78. try:
  79. settings.run_at_finish = config.get('pyinstalive', 'run_at_finish').replace("\\", "\\\\")
  80. if not settings.run_at_finish:
  81. settings.run_at_finish = "None"
  82. except:
  83. log("[W] Invalid or missing settings detected for 'run_at_finish', using default value (None)", "YELLOW")
  84. settings.run_at_finish = "None"
  85. has_thrown_errors = True
  86. try:
  87. settings.save_comments = config.get('pyinstalive', 'save_comments').title()
  88. wide_build = sys.maxunicode > 65536
  89. if sys.version.split(' ')[0].startswith('2') and settings.save_comments == "True" and not wide_build:
  90. log("[W] Your Python 2 build does not support wide unicode characters.\n[W] This means characters such as mojis will not be saved.", "YELLOW")
  91. has_thrown_errors = True
  92. else:
  93. if not settings.show_cookie_expiry in bool_values:
  94. log("[W] Invalid or missing setting detected for 'save_comments', using default value (False)", "YELLOW")
  95. settings.save_comments = 'false'
  96. has_thrown_errors = True
  97. except:
  98. log("[W] Invalid or missing setting detected for 'save_comments', using default value (False)", "YELLOW")
  99. settings.save_comments = 'false'
  100. has_thrown_errors = True
  101. try:
  102. settings.save_path = config.get('pyinstalive', 'save_path')
  103. if (os.path.exists(settings.save_path)):
  104. pass
  105. else:
  106. log("[W] Invalid or missing setting detected for 'save_path', falling back to path: " + os.getcwd(), "YELLOW")
  107. settings.save_path = os.getcwd()
  108. has_thrown_errors = True
  109. if not settings.save_path.endswith('/'):
  110. settings.save_path = settings.save_path + '/'
  111. except:
  112. log("[W] Invalid or missing setting detected for 'save_path', falling back to path: " + os.getcwd(), "YELLOW")
  113. settings.save_path = os.getcwd()
  114. has_thrown_errors = True
  115. if has_thrown_errors:
  116. seperator("GREEN")
  117. return True
  118. except Exception as e:
  119. print(str(e))
  120. return False
  121. def show_info(config):
  122. if os.path.exists('pyinstalive.ini'):
  123. try:
  124. config.read('pyinstalive.ini')
  125. except Exception:
  126. log("[E] Could not read configuration file.", "RED")
  127. seperator("GREEN")
  128. else:
  129. new_config()
  130. sys.exit(1)
  131. if not check_config_validity(config):
  132. log("[W] Config file is not valid, some information may be inaccurate.", "YELLOW")
  133. log("", "GREEN")
  134. cookie_files = []
  135. cookie_from_config = ''
  136. try:
  137. for file in os.listdir(os.getcwd()):
  138. if file.endswith(".json"):
  139. cookie_files.append(file)
  140. if settings.username == file.replace(".json", ''):
  141. cookie_from_config = file
  142. except Exception as e:
  143. log("[W] Could not check for cookie files: " + str(e), "YELLOW")
  144. log("", "ENDC")
  145. log("[I] To see all the available flags, use the -h flag.", "BLUE")
  146. log("", "GREEN")
  147. log("[I] PyInstaLive version: " + script_version, "GREEN")
  148. log("[I] Python version: " + python_version, "GREEN")
  149. if check_ffmpeg() == False:
  150. log("[E] FFmpeg framework: Not found", "RED")
  151. else:
  152. log("[I] FFmpeg framework: Available", "GREEN")
  153. if (len(cookie_from_config) > 0):
  154. log("[I] Cookie files: {:s} ({:s} matches config user)".format(str(len(cookie_files)), cookie_from_config), "GREEN")
  155. elif len(cookie_files) > 0:
  156. log("[I] Cookie files: {:s}".format(str(len(cookie_files))), "GREEN")
  157. else:
  158. log("[W] Cookie files: None found", "YELLOW")
  159. log("[I] CLI supports color: " + str(supports_color()), "GREEN")
  160. log("[I] File to run at start: " + settings.run_at_start, "GREEN")
  161. log("[I] File to run at finish: " + settings.run_at_finish, "GREEN")
  162. log("", "GREEN")
  163. if os.path.exists('pyinstalive.ini'):
  164. log("[I] Config file:", "GREEN")
  165. log("", "GREEN")
  166. with open('pyinstalive.ini') as f:
  167. for line in f:
  168. log(" " + line.rstrip(), "YELLOW")
  169. else:
  170. log("[E] Config file: Not found", "RED")
  171. log("", "GREEN")
  172. log("[I] End of PyInstaLive information screen.", "GREEN")
  173. seperator("GREEN")
  174. def new_config():
  175. try:
  176. if os.path.exists('pyinstalive.ini'):
  177. log("[I] A configuration file is already present:", "GREEN")
  178. log("", "GREEN")
  179. with open('pyinstalive.ini') as f:
  180. for line in f:
  181. log(" " + line.rstrip(), "YELLOW")
  182. log("", "GREEN")
  183. log("[I] To create a default config file, delete 'pyinstalive.ini' and ", "GREEN")
  184. log(" run this script again.", "GREEN")
  185. seperator("GREEN")
  186. else:
  187. try:
  188. log("[W] Could not find configuration file, creating a default one...", "YELLOW")
  189. 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 = \nsave_comments = false\nlog_to_file = false\n"
  190. config_file = open("pyinstalive.ini", "w")
  191. config_file.write(config_template)
  192. config_file.close()
  193. log("[W] Edit the created 'pyinstalive.ini' file and run this script again.", "YELLOW")
  194. seperator("GREEN")
  195. sys.exit(0)
  196. except Exception as e:
  197. log("[E] Could not create default config file: " + str(e), "RED")
  198. log("[W] You must manually create and edit it with the following template: ", "YELLOW")
  199. log("", "GREEN")
  200. log(config_template, "YELLOW")
  201. log("", "GREEN")
  202. log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
  203. seperator("GREEN")
  204. except Exception as e:
  205. log("[E] An error occurred: " + str(e), "RED")
  206. log("[W] If you don't have a configuration file, you must", "YELLOW")
  207. log(" manually create and edit it with the following template: ", "YELLOW")
  208. log("", "GREEN")
  209. log(config_template, "YELLOW")
  210. log("", "GREEN")
  211. log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
  212. seperator("GREEN")
  213. def clean_download_dir():
  214. dir_delcount = 0
  215. error_count = 0
  216. lock_count = 0
  217. log('[I] Cleaning up temporary files and folders...', "GREEN")
  218. try:
  219. if sys.version.split(' ')[0].startswith('2'):
  220. directories = (os.walk(settings.save_path).next()[1])
  221. files = (os.walk(settings.save_path).next()[2])
  222. else:
  223. directories = (os.walk(settings.save_path).__next__()[1])
  224. files = (os.walk(settings.save_path).__next__()[2])
  225. for directory in directories:
  226. if directory.endswith('_downloads'):
  227. if not any(filename.endswith('.lock') for filename in os.listdir(settings.save_path + directory)):
  228. try:
  229. shutil.rmtree(settings.save_path + directory)
  230. dir_delcount += 1
  231. except Exception as e:
  232. log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
  233. error_count += 1
  234. else:
  235. lock_count += 1
  236. seperator("GREEN")
  237. log('[I] The cleanup has finished.', "YELLOW")
  238. if dir_delcount == 0 and error_count == 0 and lock_count == 0:
  239. log('[I] No folders were removed.', "YELLOW")
  240. seperator("GREEN")
  241. return
  242. log('[I] Folders removed: {:d}'.format(dir_delcount), "YELLOW")
  243. log('[I] Locked folders: {:d}'.format(lock_count), "YELLOW")
  244. log('[I] Errors: {:d}'.format(error_count), "YELLOW")
  245. seperator("GREEN")
  246. except KeyboardInterrupt as e:
  247. seperator("GREEN")
  248. log("[W] The cleanup has been aborted.", "YELLOW")
  249. if dir_delcount == 0 and error_count == 0 and lock_count == 0:
  250. log('[I] No folders were removed.', "YELLOW")
  251. seperator("GREEN")
  252. return
  253. log('[I] Folders removed: {:d}'.format(dir_delcount), "YELLOW")
  254. log('[I] Locked folders: {:d}'.format(lock_count), "YELLOW")
  255. log('[I] Errors: {:d}'.format(error_count), "YELLOW")
  256. seperator("GREEN")
  257. def run():
  258. logging.disable(logging.CRITICAL)
  259. config = configparser.ConfigParser()
  260. parser = argparse.ArgumentParser(description='You are running PyInstaLive ' + script_version + " using Python " + python_version)
  261. parser.add_argument('-u', '--username', dest='username', type=str, required=False, help="Instagram username to login with.")
  262. parser.add_argument('-p', '--password', dest='password', type=str, required=False, help="Instagram password to login with.")
  263. 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.")
  264. parser.add_argument('-i', '--info', dest='info', action='store_true', help="View information about PyInstaLive.")
  265. parser.add_argument('-c', '--config', dest='config', action='store_true', help="Create a default configuration file if it doesn't exist.")
  266. parser.add_argument('-nr', '--noreplays', dest='noreplays', action='store_true', help="When used, do not check for any available replays.")
  267. parser.add_argument('-cl', '--clean', dest='clean', action='store_true', help="PyInstaLive will clean the current download folder of all leftover files.")
  268. # Workaround to 'disable' argument abbreviations
  269. parser.add_argument('--usernamx', help=argparse.SUPPRESS, metavar='IGNORE')
  270. parser.add_argument('--passworx', help=argparse.SUPPRESS, metavar='IGNORE')
  271. parser.add_argument('--recorx', help=argparse.SUPPRESS, metavar='IGNORE')
  272. parser.add_argument('--infx', help=argparse.SUPPRESS, metavar='IGNORE')
  273. parser.add_argument('--confix', help=argparse.SUPPRESS, metavar='IGNORE')
  274. parser.add_argument('--noreplayx', help=argparse.SUPPRESS, metavar='IGNORE')
  275. parser.add_argument('--cleax', help=argparse.SUPPRESS, metavar='IGNORE')
  276. parser.add_argument('-cx', help=argparse.SUPPRESS, metavar='IGNORE')
  277. args, unknown = parser.parse_known_args()
  278. try:
  279. config.read('pyinstalive.ini')
  280. settings.log_to_file = config.get('pyinstalive', 'log_to_file').title()
  281. if not settings.log_to_file in bool_values:
  282. settings.log_to_file = 'False'
  283. elif settings.log_to_file == "True":
  284. if args.record:
  285. settings.user_to_record = args.record
  286. else:
  287. settings.user_to_record = "log"
  288. try:
  289. with open("pyinstalive_{:s}.log".format(settings.user_to_record),"a+") as f:
  290. f.write("\n")
  291. f.close()
  292. except:
  293. pass
  294. except Exception as e:
  295. print(str(e))
  296. settings.log_to_file = 'False'
  297. pass # Pretend nothing happened
  298. seperator("GREEN")
  299. log('PYINSTALIVE (SCRIPT V{:s} - PYTHON V{:s}) - {:s}'.format(script_version, python_version, time.strftime('%I:%M:%S %p')), "GREEN")
  300. seperator("GREEN")
  301. if unknown:
  302. log("[E] The following invalid argument(s) were provided: ", "RED")
  303. log('', "GREEN")
  304. log(' '.join(unknown), "YELLOW")
  305. log('', "GREEN")
  306. log("[I] \033[94mpyinstalive -h\033[92m can be used to display command help.", "GREEN")
  307. exit(1)
  308. if (args.info) or (not
  309. args.username and not
  310. args.password and not
  311. args.record and not
  312. args.info and not
  313. args.config and not
  314. args.noreplays and not
  315. args.clean):
  316. show_info(config)
  317. sys.exit(0)
  318. if (args.config == True):
  319. new_config()
  320. sys.exit(0)
  321. if os.path.exists('pyinstalive.ini'):
  322. try:
  323. config.read('pyinstalive.ini')
  324. except Exception:
  325. log("[E] Could not read configuration file.", "RED")
  326. seperator("GREEN")
  327. else:
  328. new_config()
  329. sys.exit(1)
  330. if check_config_validity(config):
  331. if (args.clean == True):
  332. clean_download_dir()
  333. sys.exit(0)
  334. if check_ffmpeg() == False:
  335. log("[E] Could not find ffmpeg, the script will now exit. ", "RED")
  336. seperator("GREEN")
  337. sys.exit(1)
  338. if (args.record == None):
  339. log("[E] Missing --record argument. Please specify an Instagram username.", "RED")
  340. seperator("GREEN")
  341. sys.exit(1)
  342. if (args.noreplays == True):
  343. settings.save_replays = "false"
  344. if (args.username is not None) and (args.password is not None):
  345. api = login(args.username, args.password, settings.show_cookie_expiry, True)
  346. elif (args.username is not None) or (args.password is not None):
  347. log("[W] Missing -u or -p arguments, falling back to config file...", "YELLOW")
  348. if (not len(settings.username) > 0) or (not len(settings.password) > 0):
  349. log("[E] Username or password are missing. Please check your configuration settings and try again.", "RED")
  350. seperator("GREEN")
  351. sys.exit(1)
  352. else:
  353. api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
  354. else:
  355. if (not len(settings.username) > 0) or (not len(settings.password) > 0):
  356. log("[E] Username or password are missing. Please check your configuration settings and try again.", "RED")
  357. seperator("GREEN")
  358. sys.exit(1)
  359. else:
  360. api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
  361. main(api, args.record, settings)
  362. else:
  363. log("[E] The configuration file is not valid. Please check your configuration settings and try again.", "RED")
  364. seperator("GREEN")
  365. sys.exit(1)