initialize.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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. from .auth import login
  10. from .downloader import main
  11. from .logger import log
  12. from .logger import seperator
  13. from .logger import supports_color
  14. from .settings import settings
  15. script_version = "2.4.9"
  16. python_version = sys.version.split(' ')[0]
  17. bool_values = {'True', 'False'}
  18. def check_ffmpeg():
  19. try:
  20. FNULL = open(os.devnull, 'w')
  21. subprocess.call(["ffmpeg"], stdout=FNULL, stderr=subprocess.STDOUT)
  22. return True
  23. except OSError as e:
  24. return False
  25. def check_config_validity(config):
  26. try:
  27. has_thrown_errors = False
  28. settings.username = config.get('pyinstalive', 'username')
  29. settings.password = config.get('pyinstalive', 'password')
  30. try:
  31. settings.show_cookie_expiry = config.get('pyinstalive', 'show_cookie_expiry').title()
  32. if not settings.show_cookie_expiry in bool_values:
  33. log("[W] Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)", "YELLOW")
  34. settings.show_cookie_expiry = 'true'
  35. has_thrown_errors = True
  36. except:
  37. log("[W] Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)", "YELLOW")
  38. settings.show_cookie_expiry = 'true'
  39. has_thrown_errors = True
  40. try:
  41. settings.clear_temp_files = config.get('pyinstalive', 'clear_temp_files').title()
  42. if not settings.clear_temp_files in bool_values:
  43. log("[W] Invalid or missing setting detected for 'clear_temp_files', using default value (True)", "YELLOW")
  44. settings.clear_temp_files = 'true'
  45. has_thrown_errors = True
  46. except:
  47. log("[W] Invalid or missing setting detected for 'clear_temp_files', using default value (True)", "YELLOW")
  48. settings.clear_temp_files = 'true'
  49. has_thrown_errors = True
  50. try:
  51. settings.save_replays = config.get('pyinstalive', 'save_replays').title()
  52. if not settings.save_replays in bool_values:
  53. log("[W] Invalid or missing setting detected for 'save_replays', using default value (True)", "YELLOW")
  54. settings.save_replays = 'true'
  55. has_thrown_errors = True
  56. except:
  57. log("[W] Invalid or missing setting detected for 'save_replays', using default value (True)", "YELLOW")
  58. settings.save_replays = 'true'
  59. has_thrown_errors = True
  60. try:
  61. settings.run_at_start = config.get('pyinstalive', 'run_at_start').replace("\\", "\\\\")
  62. if not settings.run_at_start:
  63. settings.run_at_start = "None"
  64. except:
  65. log("[W] Invalid or missing settings detected for 'run_at_start', using default value (None)", "YELLOW")
  66. settings.run_at_start = "None"
  67. has_thrown_errors = True
  68. try:
  69. settings.run_at_finish = config.get('pyinstalive', 'run_at_finish').replace("\\", "\\\\")
  70. if not settings.run_at_finish:
  71. settings.run_at_finish = "None"
  72. except:
  73. log("[W] Invalid or missing settings detected for 'run_at_finish', using default value (None)", "YELLOW")
  74. settings.run_at_finish = "None"
  75. has_thrown_errors = True
  76. try:
  77. settings.save_comments = config.get('pyinstalive', 'save_comments').title()
  78. wide_build = sys.maxunicode > 65536
  79. if sys.version.split(' ')[0].startswith('2') and settings.save_comments == "True" and not wide_build:
  80. log("[W] Your Python 2 build does not support wide unicode characters.\n[W] This means characters such as mojis will not be saved.", "YELLOW")
  81. has_thrown_errors = True
  82. else:
  83. if not settings.show_cookie_expiry in bool_values:
  84. log("[W] Invalid or missing setting detected for 'save_comments', using default value (False)", "YELLOW")
  85. settings.save_comments = 'false'
  86. has_thrown_errors = True
  87. except:
  88. log("[W] Invalid or missing setting detected for 'save_comments', using default value (False)", "YELLOW")
  89. settings.save_comments = 'false'
  90. has_thrown_errors = True
  91. try:
  92. settings.save_path = config.get('pyinstalive', 'save_path')
  93. if (os.path.exists(settings.save_path)):
  94. pass
  95. else:
  96. log("[W] Invalid or missing setting detected for 'save_path', falling back to path: " + os.getcwd(), "YELLOW")
  97. settings.save_path = os.getcwd()
  98. has_thrown_errors = True
  99. if not settings.save_path.endswith('/'):
  100. settings.save_path = settings.save_path + '/'
  101. except:
  102. log("[W] Invalid or missing setting detected for 'save_path', falling back to path: " + os.getcwd(), "YELLOW")
  103. settings.save_path = os.getcwd()
  104. has_thrown_errors = True
  105. try:
  106. if config.get('ftp', 'ftp_enabled').title() == "True":
  107. settings.ftp_host = config.get('ftp', 'ftp_host')
  108. settings.ftp_save_path = config.get('ftp', 'ftp_save_path')
  109. settings.ftp_username = config.get('ftp', 'ftp_username')
  110. settings.ftp_password = config.get('ftp', 'ftp_password')
  111. if len(settings.ftp_host) > 0 and len(settings.ftp_save_path) > 0 and len(settings.ftp_username) > 0 and len(settings.ftp_password) > 0:
  112. settings.ftp_enabled = True
  113. else:
  114. log("[W] Missing settings detected for the FTP settings, FTP will be ignored.", "YELLOW")
  115. has_thrown_errors = True
  116. except:
  117. log("[W] Missing or invalid settings detected for the FTP settings, FTP will be ignored.", "YELLOW")
  118. has_thrown_errors = True
  119. if has_thrown_errors:
  120. seperator("GREEN")
  121. return True
  122. except Exception as e:
  123. print(str(e))
  124. return False
  125. def show_info(config):
  126. if os.path.exists('pyinstalive.ini'):
  127. try:
  128. config.read('pyinstalive.ini')
  129. except Exception:
  130. log("[E] Could not read configuration file.", "RED")
  131. seperator("GREEN")
  132. else:
  133. new_config()
  134. sys.exit(1)
  135. if not check_config_validity(config):
  136. log("[W] Config file is not valid, some information may be inaccurate.", "YELLOW")
  137. log("", "GREEN")
  138. cookie_files = []
  139. cookie_from_config = ''
  140. try:
  141. for file in os.listdir(os.getcwd()):
  142. if file.endswith(".json"):
  143. cookie_files.append(file)
  144. if settings.username == file.replace(".json", ''):
  145. cookie_from_config = file
  146. except Exception as e:
  147. log("[W] Could not check for cookie files: " + str(e), "YELLOW")
  148. log("", "ENDC")
  149. log("[I] To see all the available flags, use the -h flag.", "BLUE")
  150. log("", "GREEN")
  151. log("[I] PyInstaLive version: " + script_version, "GREEN")
  152. log("[I] Python version: " + python_version, "GREEN")
  153. if check_ffmpeg() == False:
  154. log("[E] FFmpeg framework: Not found", "RED")
  155. else:
  156. log("[I] FFmpeg framework: Available", "GREEN")
  157. if (len(cookie_from_config) > 0):
  158. log("[I] Cookie files: {} ({} matches config user)".format(str(len(cookie_files)), cookie_from_config), "GREEN")
  159. elif len(cookie_files) > 0:
  160. log("[I] Cookie files: {}".format(str(len(cookie_files))), "GREEN")
  161. else:
  162. log("[W] Cookie files: None found", "YELLOW")
  163. log("[I] CLI supports color: " + str(supports_color()), "GREEN")
  164. log("[I] File to run at start: " + settings.run_at_start, "GREEN")
  165. log("[I] File to run at finish: " + settings.run_at_finish, "GREEN")
  166. log("", "GREEN")
  167. if os.path.exists('pyinstalive.ini'):
  168. log("[I] Config file:", "GREEN")
  169. log("", "GREEN")
  170. with open('pyinstalive.ini') as f:
  171. for line in f:
  172. log(" " + line.rstrip(), "YELLOW")
  173. else:
  174. log("[E] Config file: Not found", "RED")
  175. log("", "GREEN")
  176. log("[I] End of PyInstaLive information screen.", "GREEN")
  177. seperator("GREEN")
  178. def new_config():
  179. try:
  180. if os.path.exists('pyinstalive.ini'):
  181. log("[I] A configuration file is already present:", "GREEN")
  182. log("", "GREEN")
  183. with open('pyinstalive.ini') as f:
  184. for line in f:
  185. log(" " + line.rstrip(), "YELLOW")
  186. log("", "GREEN")
  187. log("[I] To create a default config file, delete 'pyinstalive.ini' and ", "GREEN")
  188. log(" run this script again.", "GREEN")
  189. seperator("GREEN")
  190. else:
  191. try:
  192. log("[W] Could not find configuration file, creating a default one...", "YELLOW")
  193. config_template = "[pyinstalive]\nusername = johndoe\npassword = grapefruits\nsave_path = " + os.getcwd() + "\nshow_cookie_expiry = true\nclear_temp_files = false\nsave_replays = true\nrun_at_start = \nrun_at_finish = \nsave_comments = false\n\n[ftp]\nftp_enabled = false\nftp_host = \nftp_save_path = \nftp_username = \nftp_password = \n"
  194. config_file = open("pyinstalive.ini", "w")
  195. config_file.write(config_template)
  196. config_file.close()
  197. log("[W] Edit the created 'pyinstalive.ini' file and run this script again.", "YELLOW")
  198. seperator("GREEN")
  199. sys.exit(0)
  200. except Exception as e:
  201. log("[E] Could not create default config file: " + str(e), "RED")
  202. log("[W] You must manually create and edit it with the following template: ", "YELLOW")
  203. log("", "GREEN")
  204. log(config_template, "YELLOW")
  205. log("", "GREEN")
  206. log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
  207. seperator("GREEN")
  208. except Exception as e:
  209. log("[E] An error occurred: " + str(e), "RED")
  210. log("[W] If you don't have a configuration file, you must", "YELLOW")
  211. log(" manually create and edit it with the following template: ", "YELLOW")
  212. log("", "GREEN")
  213. log(config_template, "YELLOW")
  214. log("", "GREEN")
  215. log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
  216. seperator("GREEN")
  217. def clean_download_dir():
  218. dir_delcount = 0
  219. file_delcount = 0
  220. error_count = 0
  221. log('[I] Cleaning up temporary files and folders...', "GREEN")
  222. try:
  223. if sys.version.split(' ')[0].startswith('2'):
  224. directories = (os.walk(settings.save_path).next()[1])
  225. files = (os.walk(settings.save_path).next()[2])
  226. else:
  227. directories = (os.walk(settings.save_path).__next__()[1])
  228. files = (os.walk(settings.save_path).__next__()[2])
  229. for directory in directories:
  230. if directory.endswith('_downloads'):
  231. try:
  232. shutil.rmtree(settings.save_path + directory)
  233. dir_delcount += 1
  234. except Exception as e:
  235. log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
  236. error_count += 1
  237. for file in files:
  238. if file.endswith('_comments.json'):
  239. try:
  240. os.remove(settings.save_path + file)
  241. file_delcount += 1
  242. except Exception as e:
  243. log("[E] Could not remove temp file: {:s}".format(str(e)), "RED")
  244. error_count += 1
  245. seperator("GREEN")
  246. log('[I] The cleanup has finished.', "YELLOW")
  247. if dir_delcount == 0 and file_delcount == 0 and error_count == 0:
  248. log('[I] No files or folders were removed.', "YELLOW")
  249. seperator("GREEN")
  250. return
  251. log('[I] Folders removed: {:d}'.format(dir_delcount), "YELLOW")
  252. log('[I] Files removed: {:d}'.format(file_delcount), "YELLOW")
  253. log('[I] Errors: {:d}'.format(error_count), "YELLOW")
  254. seperator("GREEN")
  255. except KeyboardInterrupt as e:
  256. seperator("GREEN")
  257. log("[W] The cleanup has been aborted.", "YELLOW")
  258. if dir_delcount == 0 and file_delcount == 0 and error_count == 0:
  259. log('[I] No files or folders were removed.', "YELLOW")
  260. seperator("GREEN")
  261. return
  262. log('[I] Folders removed: {:d}'.format(dir_delcount), "YELLOW")
  263. log('[I] Files removed: {:d}'.format(file_delcount), "YELLOW")
  264. log('[I] Errors: {:d}'.format(error_count), "YELLOW")
  265. seperator("GREEN")
  266. def run():
  267. seperator("GREEN")
  268. log('PYINSTALIVE (SCRIPT V{} - PYTHON V{}) - {}'.format(script_version, python_version, time.strftime('%I:%M:%S %p')), "GREEN")
  269. seperator("GREEN")
  270. logging.disable(logging.CRITICAL)
  271. config = configparser.ConfigParser()
  272. parser = argparse.ArgumentParser(description='You are running PyInstaLive ' + script_version + " using Python " + python_version)
  273. parser.add_argument('-u', '--username', dest='username', type=str, required=False, help="Instagram username to login with.")
  274. parser.add_argument('-p', '--password', dest='password', type=str, required=False, help="Instagram password to login with.")
  275. parser.add_argument('-r', '--record', dest='record', type=str, required=False, help="The username of the user whose livestream or replay you want to save.")
  276. parser.add_argument('-i', '--info', dest='info', action='store_true', help="View information about PyInstaLive.")
  277. parser.add_argument('-c', '--config', dest='config', action='store_true', help="Create a default configuration file if it doesn't exist.")
  278. parser.add_argument('-nr', '--noreplays', dest='noreplays', action='store_true', help="When used, do not check for any available replays.")
  279. parser.add_argument('-cl', '--clean', dest='clean', action='store_true', help="PyInstaLive will clean the current download folder of all leftover files.")
  280. # Workaround to 'disable' argument abbreviations
  281. parser.add_argument('--usernamx', help=argparse.SUPPRESS, metavar='IGNORE')
  282. parser.add_argument('--passworx', help=argparse.SUPPRESS, metavar='IGNORE')
  283. parser.add_argument('--recorx', help=argparse.SUPPRESS, metavar='IGNORE')
  284. parser.add_argument('--infx', help=argparse.SUPPRESS, metavar='IGNORE')
  285. parser.add_argument('--confix', help=argparse.SUPPRESS, metavar='IGNORE')
  286. parser.add_argument('--noreplayx', help=argparse.SUPPRESS, metavar='IGNORE')
  287. parser.add_argument('--cleax', help=argparse.SUPPRESS, metavar='IGNORE')
  288. parser.add_argument('-cx', help=argparse.SUPPRESS, metavar='IGNORE')
  289. args, unknown = parser.parse_known_args()
  290. if unknown:
  291. log("[E] The following invalid argument(s) were provided: ", "RED")
  292. log('', "GREEN")
  293. log(' '.join(unknown), "YELLOW")
  294. log('', "GREEN")
  295. log("[I] \033[94mpyinstalive -h\033[92m can be used to display command help.", "GREEN")
  296. exit(1)
  297. if (args.info) or (not
  298. args.username and not
  299. args.password and not
  300. args.record and not
  301. args.info and not
  302. args.config and not
  303. args.noreplays and not
  304. args.clean):
  305. show_info(config)
  306. sys.exit(0)
  307. if (args.config == True):
  308. new_config()
  309. sys.exit(0)
  310. if os.path.exists('pyinstalive.ini'):
  311. try:
  312. config.read('pyinstalive.ini')
  313. except Exception:
  314. log("[E] Could not read configuration file. Try passing the required arguments manually.", "RED")
  315. seperator("GREEN")
  316. else:
  317. new_config()
  318. sys.exit(1)
  319. if check_config_validity(config):
  320. if (args.clean == True):
  321. clean_download_dir()
  322. sys.exit(0)
  323. if check_ffmpeg() == False:
  324. log("[E] Could not find ffmpeg, the script will now exit. ", "RED")
  325. seperator("GREEN")
  326. sys.exit(1)
  327. if (args.record == None):
  328. log("[E] Missing --record argument. Please specify an Instagram username.", "RED")
  329. seperator("GREEN")
  330. sys.exit(1)
  331. if (args.noreplays == True):
  332. settings.save_replays = "false"
  333. if (args.username is not None) and (args.password is not None):
  334. api = login(args.username, args.password, settings.show_cookie_expiry, True)
  335. elif (args.username is not None) or (args.password is not None):
  336. log("[W] Missing -u or -p arguments, falling back to config file...", "YELLOW")
  337. if (not len(settings.username) > 0) or (not len(settings.password) > 0):
  338. log("[E] Username or password are missing. Please check your configuration settings and try again.", "RED")
  339. seperator("GREEN")
  340. sys.exit(1)
  341. else:
  342. api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
  343. else:
  344. if (not len(settings.username) > 0) or (not len(settings.password) > 0):
  345. log("[E] Username or password are missing. Please check your configuration settings and try again.", "RED")
  346. seperator("GREEN")
  347. sys.exit(1)
  348. else:
  349. api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
  350. main(api, args.record, settings)
  351. else:
  352. log("[E] The configuration file is not valid. Please check your configuration settings and try again.", "RED")
  353. seperator("GREEN")
  354. sys.exit(1)