startup.py 12 KB

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