startup.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import argparse
  2. import configparser
  3. import os
  4. import logging
  5. import platform
  6. import subprocess
  7. try:
  8. import pil
  9. import auth
  10. import logger
  11. import helpers
  12. import downloader
  13. import assembler
  14. import dlfuncs
  15. from constants import Constants
  16. except ImportError:
  17. from . import pil
  18. from . import auth
  19. from . import logger
  20. from . import helpers
  21. from . import downloader
  22. from . import assembler
  23. from . import dlfuncs
  24. from .constants import Constants
  25. def validate_inputs(config, args, unknown_args):
  26. error_arr = []
  27. try:
  28. config.read(pil.config_path)
  29. if args.download:
  30. pil.dl_user = args.download
  31. if args.downloadfollowing or args.batchfile:
  32. logger.banner()
  33. logger.warn("Please use only one download method. Use -h for more information.")
  34. logger.separator()
  35. return False
  36. elif not args.clean and not args.info and not args.assemble and not args.downloadfollowing and not args.batchfile:
  37. logger.banner()
  38. logger.error("Please use a download method. Use -h for more information.")
  39. logger.separator()
  40. return False
  41. if helpers.bool_str_parse(config.get('pyinstalive', 'log_to_file')) == "Invalid":
  42. pil.log_to_file = True
  43. error_arr.append(['log_to_file', 'True'])
  44. elif helpers.bool_str_parse(config.get('pyinstalive', 'log_to_file')):
  45. pil.log_to_file = True
  46. else:
  47. pil.log_to_file = False
  48. logger.banner()
  49. if args.batchfile:
  50. if os.path.isfile(args.batchfile):
  51. pil.dl_batchusers = [user.rstrip('\n') for user in open(args.batchfile)]
  52. if not pil.dl_batchusers:
  53. logger.error("The specified file is empty.")
  54. logger.separator()
  55. return False
  56. else:
  57. logger.info("Downloading {:d} users from batch file.".format(len(pil.dl_batchusers)))
  58. logger.separator()
  59. else:
  60. logger.error('The specified file does not exist.')
  61. logger.separator()
  62. return False
  63. if unknown_args:
  64. pil.uargs = unknown_args
  65. logger.warn("The following unknown argument(s) were provided and will be ignored: ")
  66. logger.warn(' ' + ' '.join(unknown_args))
  67. logger.separator()
  68. pil.ig_user = config.get('pyinstalive', 'username')
  69. pil.ig_pass = config.get('pyinstalive', 'password')
  70. pil.dl_path = config.get('pyinstalive', 'download_path')
  71. pil.run_at_start = config.get('pyinstalive', 'run_at_start')
  72. pil.run_at_finish = config.get('pyinstalive', 'run_at_finish')
  73. pil.ffmpeg_path = config.get('pyinstalive', 'ffmpeg_path')
  74. pil.args = args
  75. pil.config = config
  76. pil.proxy = config.get('pyinstalive', 'proxy')
  77. if args.configpath:
  78. pil.config_path = args.configpath
  79. if not os.path.isfile(pil.config_path):
  80. pil.config_path = os.path.join(os.getcwd(), "pyinstalive.ini")
  81. logger.warn("Custom config path is invalid, falling back to default path: {:s}".format(pil.config_path))
  82. logger.separator()
  83. if args.dlpath:
  84. pil.dl_path = args.dlpath
  85. if helpers.bool_str_parse(config.get('pyinstalive', 'show_cookie_expiry')) == "Invalid":
  86. pil.show_cookie_expiry = False
  87. error_arr.append(['show_cookie_expiry', 'False'])
  88. elif helpers.bool_str_parse(config.get('pyinstalive', 'show_cookie_expiry')):
  89. pil.show_cookie_expiry = True
  90. else:
  91. pil.show_cookie_expiry = False
  92. if helpers.bool_str_parse(config.get('pyinstalive', 'use_locks')) == "Invalid":
  93. pil.use_locks = False
  94. error_arr.append(['use_locks', 'False'])
  95. elif helpers.bool_str_parse(config.get('pyinstalive', 'use_locks')):
  96. pil.use_locks = True
  97. else:
  98. pil.use_locks = False
  99. if helpers.bool_str_parse(config.get('pyinstalive', 'clear_temp_files')) == "Invalid":
  100. pil.clear_temp_files = False
  101. error_arr.append(['clear_temp_files', 'False'])
  102. elif helpers.bool_str_parse(config.get('pyinstalive', 'clear_temp_files')):
  103. pil.clear_temp_files = True
  104. else:
  105. pil.clear_temp_files = False
  106. if helpers.bool_str_parse(config.get('pyinstalive', 'do_heartbeat')) == "Invalid":
  107. pil.do_heartbeat = True
  108. error_arr.append(['do_heartbeat', 'True'])
  109. elif helpers.bool_str_parse(config.get('pyinstalive', 'do_heartbeat')):
  110. pil.do_heartbeat = True
  111. else:
  112. pil.do_heartbeat = False
  113. logger.warn("Getting livestream heartbeat disabled, this may cause degraded performance.")
  114. logger.separator()
  115. if not args.nolives and helpers.bool_str_parse(config.get('pyinstalive', 'download_lives')) == "Invalid":
  116. pil.dl_lives = True
  117. error_arr.append(['download_lives', 'True'])
  118. elif helpers.bool_str_parse(config.get('pyinstalive', 'download_lives')):
  119. pil.dl_lives = True
  120. else:
  121. pil.dl_lives = False
  122. if not args.noreplays and helpers.bool_str_parse(config.get('pyinstalive', 'download_replays')) == "Invalid":
  123. pil.dl_replays = True
  124. error_arr.append(['download_replays', 'True'])
  125. elif helpers.bool_str_parse(config.get('pyinstalive', 'download_replays')):
  126. pil.dl_replays = True
  127. else:
  128. pil.dl_replays = False
  129. if helpers.bool_str_parse(config.get('pyinstalive', 'download_comments')) == "Invalid":
  130. pil.dl_comments = True
  131. error_arr.append(['download_comments', 'True'])
  132. elif helpers.bool_str_parse(config.get('pyinstalive', 'download_comments')):
  133. pil.dl_comments = True
  134. else:
  135. pil.dl_comments = False
  136. if args.nolives:
  137. pil.dl_lives = False
  138. if args.noreplays:
  139. pil.dl_replays = False
  140. if not pil.dl_lives and not pil.dl_replays:
  141. logger.error("You have disabled both livestream and replay downloading.")
  142. logger.error("Please enable at least one of them and try again.")
  143. logger.separator()
  144. return False
  145. if pil.ffmpeg_path:
  146. if not os.path.isfile(pil.ffmpeg_path):
  147. pil.ffmpeg_path = None
  148. cmd = "where" if platform.system() == "Windows" else "which"
  149. logger.warn("Custom ffmpeg binary path is invalid, falling back to default path: {:s}".format(
  150. subprocess.check_output([cmd, 'ffmpeg']).decode('UTF-8').rstrip()))
  151. else:
  152. logger.binfo("Overriding ffmpeg binary path: {:s}".format(pil.ffmpeg_path))
  153. if not pil.ig_user or not len(pil.ig_user):
  154. raise Exception("Invalid value for 'username'. This value is required.")
  155. if not pil.ig_pass or not len(pil.ig_pass):
  156. raise Exception("Invalid value for 'password'. This value is required.")
  157. if not pil.dl_path.endswith('/'):
  158. pil.dl_path = pil.dl_path + '/'
  159. if not pil.dl_path or not os.path.exists(pil.dl_path):
  160. pil.dl_path = os.getcwd()
  161. if not args.dlpath:
  162. error_arr.append(['download_path', os.getcwd()])
  163. else:
  164. logger.warn("Custom config path is invalid, falling back to default path: {:s}".format(pil.dl_path))
  165. logger.separator()
  166. if error_arr:
  167. for error in error_arr:
  168. logger.warn("Invalid value for '{:s}'. Using default value: {:s}".format(error[0], error[1]))
  169. logger.separator()
  170. if args.info:
  171. helpers.show_info()
  172. return False
  173. elif args.clean:
  174. helpers.clean_download_dir()
  175. return False
  176. elif args.assemble:
  177. pil.assemble_arg = args.assemble
  178. assembler.assemble()
  179. return False
  180. return True
  181. except Exception as e:
  182. logger.error("An error occurred: {:s}".format(str(e)))
  183. logger.error("Make sure the config file and given arguments are valid and try again.")
  184. logger.separator()
  185. return False
  186. def run():
  187. pil.initialize()
  188. logging.disable(logging.CRITICAL)
  189. config = configparser.ConfigParser()
  190. parser = argparse.ArgumentParser(
  191. description="You are running PyInstaLive {:s} using Python {:s}".format(Constants.SCRIPT_VER,
  192. Constants.PYTHON_VER))
  193. parser.add_argument('-u', '--username', dest='username', type=str, required=False,
  194. help="Instagram username to login with.")
  195. parser.add_argument('-p', '--password', dest='password', type=str, required=False,
  196. help="Instagram password to login with.")
  197. parser.add_argument('-d', '--download', dest='download', type=str, required=False,
  198. help="The username of the user whose livestream or replay you want to save.")
  199. parser.add_argument('-b,', '--batch-file', dest='batchfile', type=str, required=False,
  200. help="Read a text file of usernames to download livestreams or replays from.")
  201. parser.add_argument('-i', '--info', dest='info', action='store_true', help="View information about PyInstaLive.")
  202. parser.add_argument('-nr', '--no-replays', dest='noreplays', action='store_true',
  203. help="When used, do not check for any available replays.")
  204. parser.add_argument('-nl', '--no-lives', dest='nolives', action='store_true',
  205. help="When used, do not check for any available livestreams.")
  206. parser.add_argument('-cl', '--clean', dest='clean', action='store_true',
  207. help="PyInstaLive will clean the current download folder of all leftover files.")
  208. parser.add_argument('-cp', '--config-path', dest='configpath', type=str, required=False,
  209. help="Path to a PyInstaLive configuration file.")
  210. parser.add_argument('-dp', '--download-path', dest='dlpath', type=str, required=False,
  211. help="Path to folder where PyInstaLive should save livestreams and replays.")
  212. parser.add_argument('-as', '--assemble', dest='assemble', type=str, required=False,
  213. help="Path to json file required by the assembler to generate a video file from the segments.")
  214. parser.add_argument('-df', '--download-following', dest='downloadfollowing', action='store_true',
  215. help="PyInstaLive will check for available livestreams and replays from users the account "
  216. "used to login follows.")
  217. # Workaround to 'disable' argument abbreviations
  218. parser.add_argument('--usernamx', help=argparse.SUPPRESS, metavar='IGNORE')
  219. parser.add_argument('--passworx', help=argparse.SUPPRESS, metavar='IGNORE')
  220. parser.add_argument('--infx', help=argparse.SUPPRESS, metavar='IGNORE')
  221. parser.add_argument('--noreplayx', help=argparse.SUPPRESS, metavar='IGNORE')
  222. parser.add_argument('--cleax', help=argparse.SUPPRESS, metavar='IGNORE')
  223. parser.add_argument('--downloadfollowinx', help=argparse.SUPPRESS, metavar='IGNORE')
  224. parser.add_argument('--configpatx', help=argparse.SUPPRESS, metavar='IGNORE')
  225. parser.add_argument('--confix', help=argparse.SUPPRESS, metavar='IGNORE')
  226. parser.add_argument('-cx', help=argparse.SUPPRESS, metavar='IGNORE')
  227. parser.add_argument('-nx', help=argparse.SUPPRESS, metavar='IGNORE')
  228. parser.add_argument('-dx', help=argparse.SUPPRESS, metavar='IGNORE')
  229. args, unknown_args = parser.parse_known_args() # Parse arguments
  230. if not os.path.exists(pil.config_path): # Create new config if it doesn't exist
  231. logger.banner()
  232. helpers.new_config()
  233. return
  234. if validate_inputs(config, args, unknown_args):
  235. if not args.username and not args.password:
  236. pil.ig_api = auth.authenticate(username=pil.ig_user, password=pil.ig_pass, proxy=pil.proxy)
  237. elif (args.username and not args.password) or (args.password and not args.username):
  238. logger.warn("Missing --username or --password argument. Falling back to config file.")
  239. logger.separator()
  240. pil.ig_api = auth.authenticate(username=pil.ig_user, password=pil.ig_pass, proxy=pil.proxy)
  241. elif args.username and args.password:
  242. pil.ig_api = auth.authenticate(username=args.username, password=args.password, force_use_login_args=True, proxy=pil.proxy)
  243. if pil.ig_api:
  244. if pil.dl_user or pil.args.downloadfollowing:
  245. downloader.start()
  246. elif pil.dl_batchusers:
  247. if not helpers.command_exists("pyinstalive"):
  248. logger.error("PyInstaLive must be properly installed when using the -b argument.")
  249. logger.separator()
  250. else:
  251. dlfuncs.iterate_users(pil.dl_batchusers)