initialize.py 17 KB

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