startup.py 13 KB

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