initialize.py 19 KB

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