startup.py 15 KB

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