Pārlūkot izejas kodu

Add option to log to console, bugfixes

Cammy 7 gadi atpakaļ
vecāks
revīzija
417a324ff8
4 mainītis faili ar 76 papildinājumiem un 27 dzēšanām
  1. 3 4
      pyinstalive/downloader.py
  2. 39 8
      pyinstalive/initialize.py
  3. 31 14
      pyinstalive/logger.py
  4. 3 1
      pyinstalive/settings.py

+ 3 - 4
pyinstalive/downloader.py

@@ -112,7 +112,7 @@ def download_livestream(broadcast):
 			log('[I] This livestream is a dual-live, the owner is "{}".'.format(broadcast_owner), "BLUE")
 			broadcast_guest = None
 		if broadcast_guest:
-			log('[I] This livestream is a dual-live, the guest is "{}".'.format(broadcast_guest), "BLUE")
+			log('[I] This livestream is a dual-live, the current guest is "{}".'.format(broadcast_guest), "BLUE")
 		seperator("GREEN")
 		log('[I] Username    : {:s}'.format(user_to_record), "GREEN")
 		print_status(False)
@@ -141,12 +141,12 @@ def download_livestream(broadcast):
 				log('[E] An error occurred while checking comments: {:s}'.format(str(e)), "RED")
 		broadcast_downloader.run()
 		seperator("GREEN")
-		log('[I] The livestream has ended.\n[I] Time recorded     : {}\n[I] Stream duration   : {}\n[I] Missing (approx.) : {}'.format(get_stream_duration(int(settings.current_time)), get_stream_duration(broadcast.get('published_time')), get_stream_duration(int(settings.current_time), broadcast)), "YELLOW")
+		log('[I] The livestream has ended.\n[I] Download duration : {}\n[I] Stream duration   : {}\n[I] Missing (approx.) : {}'.format(get_stream_duration(int(settings.current_time)), get_stream_duration(broadcast.get('published_time')), get_stream_duration(int(settings.current_time), broadcast)), "YELLOW")
 		seperator("GREEN")
 		stitch_video(broadcast_downloader, broadcast, comment_thread_worker)
 	except KeyboardInterrupt:
 		seperator("GREEN")
-		log('[I] The download has been aborted by the user.\n[I] Time recorded     : {}\n[I] Stream duration   : {}\n[I] Missing (approx.) : {}'.format(get_stream_duration(int(settings.current_time)), get_stream_duration(broadcast.get('published_time')), get_stream_duration(int(settings.current_time), broadcast)), "YELLOW")
+		log('[I] The download has been aborted by the user.\n[I] Download duration : {}\n[I] Stream duration   : {}\n[I] Missing (approx.) : {}'.format(get_stream_duration(int(settings.current_time)), get_stream_duration(broadcast.get('published_time')), get_stream_duration(int(settings.current_time), broadcast)), "YELLOW")
 		seperator("GREEN")
 		if not broadcast_downloader.is_aborted:
 			broadcast_downloader.stop()
@@ -256,7 +256,6 @@ def get_broadcasts_info(user_id):
 		replays = broadcasts.get('post_live_item', {}).get('broadcasts', [])
 
 		if livestream:
-			seperator("GREEN")
 			download_livestream(livestream)
 		else:
 			log('[I] There are no available livestreams.', "YELLOW")

+ 39 - 8
pyinstalive/initialize.py

@@ -72,6 +72,19 @@ def check_config_validity(config):
 
 
 
+		try:
+			settings.log_to_file = config.get('pyinstalive', 'log_to_file').title()
+			if not settings.log_to_file in bool_values:
+				log("[W] Invalid or missing setting detected for 'log_to_file', using default value (True)", "YELLOW")
+				settings.log_to_file = 'true'
+				has_thrown_errors = True
+		except:
+			log("[W] Invalid or missing setting detected for 'log_to_file', using default value (True)", "YELLOW")
+			settings.log_to_file = 'true'
+			has_thrown_errors = True
+
+
+
 		try:
 			settings.run_at_start = config.get('pyinstalive', 'run_at_start').replace("\\", "\\\\")
 			if not settings.run_at_start:
@@ -173,9 +186,9 @@ def show_info(config):
 		log("[I] FFmpeg framework:       	Available", "GREEN")
 
 	if (len(cookie_from_config) > 0):
-		log("[I] Cookie files:            	{} ({} matches config user)".format(str(len(cookie_files)), cookie_from_config), "GREEN")
+		log("[I] Cookie files:            	{:d} ({:s} matches config user)".format(str(len(cookie_files)), cookie_from_config), "GREEN")
 	elif len(cookie_files) > 0:
-		log("[I] Cookie files:            	{}".format(str(len(cookie_files))), "GREEN")
+		log("[I] Cookie files:            	{:d}".format(str(len(cookie_files))), "GREEN")
 	else:
 		log("[W] Cookie files:            	None found", "YELLOW")
 
@@ -214,7 +227,7 @@ def new_config():
 		else:
 			try:
 				log("[W] Could not find configuration file, creating a default one...", "YELLOW")
-				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"
+				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\nlog_to_file = false\n"
 				config_file = open("pyinstalive.ini", "w")
 				config_file.write(config_template)
 				config_file.close()
@@ -289,12 +302,7 @@ def clean_download_dir():
 		seperator("GREEN")
 
 def run():
-	seperator("GREEN")
-	log('PYINSTALIVE (SCRIPT V{} - PYTHON V{}) - {}'.format(script_version, python_version, time.strftime('%I:%M:%S %p')), "GREEN")
-	seperator("GREEN")
-
 	logging.disable(logging.CRITICAL)
-
 	config = configparser.ConfigParser()
 	parser = argparse.ArgumentParser(description='You are running PyInstaLive ' + script_version + " using Python " + python_version)
 	parser.add_argument('-u', '--username', dest='username', type=str, required=False, help="Instagram username to login with.")
@@ -317,6 +325,29 @@ def run():
 
 
 	args, unknown = parser.parse_known_args()
+
+	if args.record:
+		settings.user_to_record = args.record
+		try:
+			config.read('pyinstalive.ini')
+			settings.log_to_file = config.get('pyinstalive', 'log_to_file').title()
+			if not settings.log_to_file in bool_values:
+				settings.log_to_file = 'false'
+			elif settings.log_to_file == "True":
+				try:
+					with open("pyinstalive_{:s}.log".format(args.record),"a+") as f:
+						f.write("\n")
+						f.close()
+				except:
+					pass
+		except Exception as e:
+			settings.log_to_file = 'false'
+			print(str(e))
+			pass # Pretend nothing happened
+
+	seperator("GREEN")
+	log('PYINSTALIVE (SCRIPT V{:s} - PYTHON V{:s}) - {:s}'.format(script_version, python_version, time.strftime('%I:%M:%S %p')), "GREEN")
+	seperator("GREEN")
 	
 	if unknown:
 		log("[E] The following invalid argument(s) were provided: ", "RED") 

+ 31 - 14
pyinstalive/logger.py

@@ -1,5 +1,8 @@
 import os
 import sys
+from .settings import settings
+
+sep = "-" * 70
 
 def colors(state):
 	color = ''
@@ -25,29 +28,43 @@ def colors(state):
 	return color
 
 def supports_color():
-    """
-    from https://github.com/django/django/blob/master/django/core/management/color.py
-    Return True if the running system's terminal supports color,
-    and False otherwise.
-    """
+	"""
+	from https://github.com/django/django/blob/master/django/core/management/color.py
+	Return True if the running system's terminal supports color,
+	and False otherwise.
+	"""
 
-    plat = sys.platform
-    supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
+	plat = sys.platform
+	supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ)
 
-    # isatty is not always implemented, #6223.
-    is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
-    if not supported_platform or not is_a_tty:
-        return False
-    return True
+	# isatty is not always implemented, #6223.
+	is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
+	if not supported_platform or not is_a_tty:
+		return False
+	return True
 
 def log(string, color):
 	if not supports_color():
 		print(string)
 	else:
 		print('\033[1m' + colors(color) + string + colors("ENDC"))
+	if settings.log_to_file == 'True':
+		try:
+			with open("pyinstalive_{:s}.log".format(settings.user_to_record),"a+") as f:
+				f.write(string + "\n")
+				f.close()
+		except:
+			pass
 
 def seperator(color):
 	if not supports_color():
-		print("-" * 70)
+		print(sep)
 	else:
-		print('\033[1m' + colors(color) + ("-" * 70) + colors("ENDC"))
+		print('\033[1m' + colors(color) + (sep) + colors("ENDC"))
+	if settings.log_to_file == 'True':
+		try:
+			with open("pyinstalive_{:s}.log".format(settings.user_to_record),"a+") as f:
+				f.write(sep + "\n")
+				f.close()
+		except:
+			pass

+ 3 - 1
pyinstalive/settings.py

@@ -1,6 +1,7 @@
 import time
 
 class settings:
+	user_to_record = ""
 	username = ""
 	password = ""
 	save_path = "/"
@@ -11,4 +12,5 @@ class settings:
 	save_replays = "true"
 	run_at_start = "None"
 	run_at_finish = "None"
-	save_comments = "true"
+	save_comments = "true"
+	log_to_file = "false"