initialize.py 21 KB

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