Browse Source

Revamp logging system

Cammy 7 years ago
parent
commit
2fbea8d67d
5 changed files with 356 additions and 313 deletions
  1. 37 37
      pyinstalive/auth.py
  2. 5 5
      pyinstalive/comments.py
  3. 118 114
      pyinstalive/downloader.py
  4. 121 124
      pyinstalive/initialize.py
  5. 75 33
      pyinstalive/logger.py

+ 37 - 37
pyinstalive/auth.py

@@ -4,8 +4,8 @@ import json
 import os.path
 import sys
 
-from .logger import log
-from .logger import seperator
+from .logger import log_seperator, supports_color, log_info_blue, log_info_green, log_warn, log_error, log_whiteline, log_plain
+
 
 
 
@@ -38,23 +38,23 @@ def onlogin_callback(api, cookie_file):
 	cache_settings = api.settings
 	with open(cookie_file, 'w') as outfile:
 		json.dump(cache_settings, outfile, default=to_json)
-		log('[I] New cookie file was made: {0!s}'.format(cookie_file), "GREEN")
-		seperator("GREEN")
+		log_info_green('New cookie file was made: {0!s}'.format(cookie_file))
+		log_seperator()
 
 
 def login(username, password, show_cookie_expiry, force_use_login_args):
 	device_id = None
 	try:
 		if force_use_login_args:
-			log("[I] Overriding standard login with -u and -p arguments...", "GREEN")
+			log_info_green("Overriding standard login with -u and -p arguments...")
 			api = Client(
 				username, password)
 		else:
 			cookie_file = "{}.json".format(username)
 			if not os.path.isfile(cookie_file):
 				# settings file does not exist
-				log('[W] Unable to find cookie file: {0!s}'.format(cookie_file), "YELLOW")
-				log('[I] Creating a new cookie file...', "YELLOW")
+				log_warn('Unable to find cookie file: {0!s}'.format(cookie_file))
+				log_info_green('Creating a new cookie file...')
 
 				# login new
 				api = Client(
@@ -63,7 +63,7 @@ def login(username, password, show_cookie_expiry, force_use_login_args):
 			else:
 				with open(cookie_file) as file_data:
 					cached_settings = json.load(file_data, object_hook=from_json)
-				# log('[I] Using settings file: {0!s}'.format(cookie_file), "GREEN")
+				# log_info_green('Using settings file: {0!s}'.format(cookie_file))
 
 				device_id = cached_settings.get('device_id')
 				# reuse auth cached_settings
@@ -72,7 +72,7 @@ def login(username, password, show_cookie_expiry, force_use_login_args):
 					settings=cached_settings)
 
 	except (ClientCookieExpiredError) as e:
-		log('[W] The current cookie file for "{:s}" has expired, creating a new one...'.format(username), "YELLOW")
+		log_warn('The current cookie file for "{:s}" has expired, creating a new one...'.format(username))
 
 		# Login expired
 		# Do relogin but use default ua, keys and such
@@ -82,58 +82,58 @@ def login(username, password, show_cookie_expiry, force_use_login_args):
 				device_id=device_id,
 				on_login=lambda x: onlogin_callback(x, cookie_file))
 		except Exception as ee:
-			seperator("GREEN")
-			log('[E] An error occurred while trying to create a new cookie file: {:s}'.format(str(ee)), "RED")
+			log_seperator()
+			log_error('An error occurred while trying to create a new cookie file: {:s}'.format(str(ee)))
 			if "getaddrinfo failed" in str(ee):
-				log('[E] Could not resolve host, check your internet connection.', "RED")
+				log_error('Could not resolve host, check your internet connection.')
 			elif "timed out" in str(ee):
-				log('[E] The connection timed out, check your internet connection.', "RED")
+				log_error('The connection timed out, check your internet connection.')
 			elif "bad_password" in str(ee):
-				log('[E] The password you entered is incorrect. Please try again.', "RED")
+				log_error('The password you entered is incorrect. Please try again.')
 			else:
-				log('[E] {:s}'.format(ee.message), "RED")
-			seperator("GREEN")
+				log_error('{:s}'.format(ee.message))
+			log_seperator()
 			exit(1)
 
 	except ClientLoginError as e:
-		seperator("GREEN")
-		log('[E] Could not login: {:s}.\n[E] {:s}\n\n{:s}'.format(json.loads(e.error_response).get("error_title", "Error title not available."), json.loads(e.error_response).get("message", "Not available"), e.error_response), "RED")
-		seperator("GREEN")
+		log_seperator()
+		log_error('Could not login: {:s}.\n[E] {:s}\n\n{:s}'.format(json.loads(e.error_response).get("error_title", "Error title not available."), json.loads(e.error_response).get("message", "Not available"), e.error_response))
+		log_seperator()
 		sys.exit(9)
 	except ClientError as e:
-		seperator("GREEN")
+		log_seperator()
 		try:
-			log('[E] Unexpected exception: {0!s}\n[E] Message: {1!s}\n[E] Code: {2:d}\n\n[E] Full response:\n{3!s}\n'.format(e.msg, json.loads(e.error_response).get("message", "Additional error information not available."), e.code, e.error_response), "RED")
+			log_error('Unexpected exception: {0!s}\n[E] Message: {1!s}\n[E] Code: {2:d}\n\n[E] Full response:\n{3!s}\n'.format(e.msg, json.loads(e.error_response).get("message", "Additional error information not available."), e.code, e.error_response))
 		except Exception as ee:
-			log('[E] An error occurred while trying to handle a previous exception.\n[E] 1: {:s}\n[E] 2: {:s}'.format(str(e), str(ee)), "RED")
+			log_error('An error occurred while trying to handle a previous exception.\n[E] 1: {:s}\n[E] 2: {:s}'.format(str(e), str(ee)))
 			if "getaddrinfo failed" in str(ee):
-				log('[E] Could not resolve host, check your internet connection.', "RED")
+				log_error('Could not resolve host, check your internet connection.')
 			if "timed out" in str(ee):
-				log('[E] The connection timed out, check your internet connection.', "RED")
-		seperator("GREEN")
+				log_error('The connection timed out, check your internet connection.')
+		log_seperator()
 		sys.exit(9)
 	except Exception as e:
 		if (str(e).startswith("unsupported pickle protocol")):
-			log("[W] This cookie file is not compatible with Python {}.".format(sys.version.split(' ')[0][0]), "YELLOW")
-			log("[W] Please delete your cookie file '{}.json' and try again.".format(username), "YELLOW")
+			log_warn("This cookie file is not compatible with Python {}.".format(sys.version.split(' ')[0][0]))
+			log_warn("Please delete your cookie file '{}.json' and try again.".format(username))
 		else:
-			seperator("GREEN")
-			log('[E] Unexpected exception: {0!s}'.format(e), "RED")
-		seperator("GREEN")
+			log_seperator()
+			log_error('Unexpected exception: {0!s}'.format(e))
+		log_seperator()
 		sys.exit(99)
 	except KeyboardInterrupt as e:
-		seperator("GREEN")
-		log("[W] The user authentication has been aborted.", "YELLOW")
-		seperator("GREEN")
+		log_seperator()
+		log_warn("The user authentication has been aborted.")
+		log_seperator()
 		sys.exit(0)
 
-	log('[I] Successfully logged into user "{:s}".'.format(str(api.authenticated_user_name)), "GREEN")
+	log_info_green('Successfully logged into user "{:s}".'.format(str(api.authenticated_user_name)))
 	if show_cookie_expiry.title() == 'True' and not force_use_login_args:
 		try:
 			cookie_expiry = api.cookie_jar.auth_expires
-			log('[I] Cookie file expiry date: {0!s}'.format(datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%d at %I:%M:%S %p')), "GREEN")
+			log_info_green('Cookie file expiry date: {0!s}'.format(datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%d at %I:%M:%S %p')))
 		except AttributeError as e:
-			log('[W] An error occurred while getting the cookie file expiry date: {0!s}'.format(e), "YELLOW")
+			log_warn('An error occurred while getting the cookie file expiry date: {0!s}'.format(e))
 
-	seperator("GREEN")		
+	log_seperator()		
 	return api

+ 5 - 5
pyinstalive/comments.py

@@ -18,8 +18,8 @@ except ImportError:
 	from urllib.error import URLError
 	from http.client import HTTPException
 
-from .logger import log
-from .logger import seperator
+from .logger import log_seperator, supports_color, log_info_blue, log_info_green, log_warn, log_error, log_whiteline, log_plain
+
 from instagram_private_api import ClientError
 
 """
@@ -58,12 +58,12 @@ class CommentsDownloader(object):
 			self.comments = comments_collected
 
 		except (SSLError, timeout, URLError, HTTPException, SocketError) as e:
-			log('[W] Comment downloading error: %s' % e, "YELLOW")
+			log_warn('Comment downloading error: %s' % e)
 		except ClientError as e:
 			if e.code == 500:
-				log('[W] Comment downloading ClientError: %d %s' % (e.code, e.error_response), "YELLOW")
+				log_warn('Comment downloading ClientError: %d %s' % (e.code, e.error_response))
 			elif e.code == 400 and not e.msg:
-				log('[W] Comment downloading ClientError: %d %s' % (e.code, e.error_response), "YELLOW")
+				log_warn('Comment downloading ClientError: %d %s' % (e.code, e.error_response))
 			else:
 				raise e
 		finally:

+ 118 - 114
pyinstalive/downloader.py

@@ -15,8 +15,8 @@ from instagram_private_api_extensions import live
 from instagram_private_api_extensions import replay
 
 from .comments import CommentsDownloader
-from .logger import log
-from .logger import seperator
+from .logger import log_seperator, supports_color, log_info_blue, log_info_green, log_warn, log_error, log_whiteline, log_plain
+
 
 
 def main(instagram_api_arg, download_arg, settings_arg):
@@ -77,10 +77,10 @@ def download_livestream(broadcast):
 			heartbeat_info = instagram_api.broadcast_heartbeat_and_viewercount(broadcast.get('id'))
 			viewers = broadcast.get('viewer_count', 0)
 			if sep:
-				seperator("GREEN")
-			log('[I] Viewers     : {:s} watching'.format(str(int(viewers))), "GREEN")
-			log('[I] Airing time : {:s}'.format(get_stream_duration(broadcast.get('published_time'))), "GREEN")
-			log('[I] Status      : {:s}'.format(heartbeat_info.get('broadcast_status').title()), "GREEN")
+				log_seperator()
+			log_info_green('Viewers     : {:s} watching'.format(str(int(viewers))))
+			log_info_green('Airing time : {:s}'.format(get_stream_duration(broadcast.get('published_time'))))
+			log_info_green('Status      : {:s}'.format(heartbeat_info.get('broadcast_status').title()))
 			return heartbeat_info.get('broadcast_status') not in ['active', 'interrupted']
 
 		mpd_url = (broadcast.get('dash_manifest')
@@ -99,37 +99,37 @@ def download_livestream(broadcast):
 			mpd_download_timeout=3,
 			download_timeout=3)
 	except Exception as e:
-		log('[E] Could not start downloading livestream: {:s}'.format(str(e)), "RED")
-		seperator("GREEN")
+		log_error('Could not start downloading livestream: {:s}'.format(str(e)))
+		log_seperator()
 		sys.exit(1)
 	try:
-		log('[I] Livestream found, beginning download...', "GREEN")
+		log_info_green('Livestream found, beginning download...')
 		broadcast_owner = broadcast.get('broadcast_owner', {}).get('username')
 		try:
 			broadcast_guest = broadcast.get('cobroadcasters', {})[0].get('username')
 		except:
 			broadcast_guest = None
 		if (broadcast_owner != user_to_download):
-			log('[I] This livestream is a dual-live, the owner is "{}".'.format(broadcast_owner), "BLUE")
+			log_info_blue('This livestream is a dual-live, the owner is "{}".'.format(broadcast_owner))
 			broadcast_guest = None
 		if broadcast_guest:
-			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_download), "GREEN")
+			log_info_blue('This livestream is a dual-live, the current guest is "{}".'.format(broadcast_guest))
+		log_seperator()
+		log_info_green('Username    : {:s}'.format(user_to_download))
 		print_status(False)
-		log('[I] MPD URL     : {:s}'.format(mpd_url), "GREEN")
-		seperator("GREEN")
+		log_info_green('MPD URL     : {:s}'.format(mpd_url))
+		log_seperator()
 		open(os.path.join(output_dir, 'folder.lock'), 'a').close()
-		log('[I] Downloading livestream... press [CTRL+C] to abort.', "GREEN")
+		log_info_green('Downloading livestream... press [CTRL+C] to abort.')
 
 		if (settings.run_at_start is not "None"):
 			try:
 				thread = threading.Thread(target=run_command, args=(settings.run_at_start,))
 				thread.daemon = True
 				thread.start()
-				log("[I] Command executed: \033[94m{:s}".format(settings.run_at_start), "GREEN")
+				log_info_green("Command executed: \033[94m{:s}".format(settings.run_at_start))
 			except Exception as e:
-				log('[W] Could not execute command: {:s}'.format(str(e)), "YELLOW")
+				log_warn('Could not execute command: {:s}'.format(str(e)))
 
 
 		comment_thread_worker = None
@@ -139,21 +139,25 @@ def download_livestream(broadcast):
 				comment_thread_worker = threading.Thread(target=get_live_comments, args=(instagram_api, broadcast, comments_json_file, broadcast_downloader,))
 				comment_thread_worker.start()
 			except Exception as e:
-				log('[E] An error occurred while downloading comments: {:s}'.format(str(e)), "RED")
+				log_error('An error occurred while downloading comments: {:s}'.format(str(e)))
 		broadcast_downloader.run()
-		seperator("GREEN")
-		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")
+		log_seperator()
+		log_info_green('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)))
+		log_seperator()
 		stitch_video(broadcast_downloader, broadcast, comment_thread_worker)
 	except KeyboardInterrupt:
-		seperator("GREEN")
-		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")
+		log_seperator()
+		log_info_blue('The download has been aborted by the user.')
+		log_seperator()
+		log_info_green('Download duration : {}'.format(get_stream_duration(int(settings.current_time))))
+		log_info_green('Stream duration   : {}'.format(get_stream_duration(broadcast.get('published_time'))))
+		log_info_green('Missing (approx.) : {}'.format(get_stream_duration(int(settings.current_time), broadcast)))
+		log_seperator()
 		if not broadcast_downloader.is_aborted:
 			broadcast_downloader.stop()
 			stitch_video(broadcast_downloader, broadcast, comment_thread_worker)
 	except Exception as e:
-		log("[E] Could not download livestream: {:s}".format(str(e)), "RED")
+		log_error("Could not download livestream: {:s}".format(str(e)))
 		try:
 		    os.remove(os.path.join(output_dir, 'folder.lock'))
 		except Exception:
@@ -166,7 +170,7 @@ def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
 		live_folder_path = "{:s}_downloads".format(live_mp4_file.split('.mp4')[0])
 
 		if comment_thread_worker and comment_thread_worker.is_alive():
-			log("[I] Waiting for comment downloader to end cycle...", "GREEN")
+			log_info_green("Waiting for comment downloader to end cycle...")
 			comment_thread_worker.join()
 
 		if (settings.run_at_finish is not "None"):
@@ -174,17 +178,17 @@ def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
 				thread = threading.Thread(target=run_command, args=(settings.run_at_finish,))
 				thread.daemon = True
 				thread.start()
-				log("[I] Command executed: \033[94m{:s}".format(settings.run_at_finish), "GREEN")
+				log_info_green("Command executed: \033[94m{:s}".format(settings.run_at_finish))
 			except Exception as e:
-				log('[W] Could not execute command: {:s}'.format(str(e)), "YELLOW")
+				log_warn('Could not execute command: {:s}'.format(str(e)))
 
-		log('[I] Stitching downloaded files into video...', "GREEN")		
+		log_info_green('Stitching downloaded files into video...')		
 		try:
 			if settings.clear_temp_files.title() == "True":
 				broadcast_downloader.stitch(live_mp4_file, cleartempfiles=True)
 			else:
 				broadcast_downloader.stitch(live_mp4_file, cleartempfiles=False)
-			log('[I] Successfully stitched downloaded files into video.', "GREEN")
+			log_info_green('Successfully stitched downloaded files into video.')
 			try:
 			    os.remove(os.path.join(live_folder_path, 'folder.lock'))
 			except Exception:
@@ -193,28 +197,28 @@ def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
 				try:
 					shutil.rmtree(live_folder_path)
 				except Exception as e:
-					log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
-			seperator("GREEN")
+					log_error("Could not remove temp folder: {:s}".format(str(e)))
+			log_seperator()
 			sys.exit(0)
 		except ValueError as e:
-			log('[E] Could not stitch downloaded files: {:s}\n[E] Likely the download duration was too short and no temp files were saved.'.format(str(e)), "RED")
-			seperator("GREEN")
+			log_error('Could not stitch downloaded files: {:s}\n[E] Likely the download duration was too short and no temp files were saved.'.format(str(e)))
+			log_seperator()
 			try:
 			    os.remove(os.path.join(live_folder_path, 'folder.lock'))
 			except Exception:
 			    pass
 			sys.exit(1)
 		except Exception as e:
-			log('[E] Could not stitch downloaded files: {:s}'.format(str(e)), "RED")
-			seperator("GREEN")
+			log_error('Could not stitch downloaded files: {:s}'.format(str(e)))
+			log_seperator()
 			try:
 			    os.remove(os.path.join(live_folder_path, 'folder.lock'))
 			except Exception:
 			    pass
 			sys.exit(1)
 	except KeyboardInterrupt:
-			log('[I] Aborted stitching process, no video was created.', "YELLOW")
-			seperator("GREEN")
+			log_info_blue('Aborted stitching process, no video was created.')
+			log_seperator()
 			try:
 			    os.remove(os.path.join(live_folder_path, 'folder.lock'))
 			except Exception:
@@ -228,42 +232,42 @@ def get_user_info(user_to_download):
 		user_res = instagram_api.username_info(user_to_download)
 		user_id = user_res.get('user', {}).get('pk')
 	except ClientConnectionError as cce:
-		log('[E] Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, cce.code, str(cce)), "RED")
+		log_error('Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, cce.code, str(cce)))
 		if "getaddrinfo failed" in str(cce):
-			log('[E] Could not resolve host, check your internet connection.', "RED")
+			log_error('Could not resolve host, check your internet connection.')
 		if "timed out" in str(cce):
-			log('[E] The connection timed out, check your internet connection.', "RED")
-		seperator("GREEN")
+			log_error('The connection timed out, check your internet connection.')
+		log_seperator()
 		sys.exit(1)
 	except ClientThrottledError as cte:
-		log('[E] Could not get user info for "{:s}": {:d} {:s}\n[E] You are making too many requests at this time.'.format(user_to_download, cte.code, str(cte)), "RED")
-		seperator("GREEN")
+		log_error('Could not get user info for "{:s}": {:d} {:s}\n[E] You are making too many requests at this time.'.format(user_to_download, cte.code, str(cte)))
+		log_seperator()
 		sys.exit(1)
 	except ClientError as ce:
-		log('[E] Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, ce.code, str(ce)), "RED")
+		log_error('Could not get user info for "{:s}": {:d} {:s}'.format(user_to_download, ce.code, str(ce)))
 		if ("Not Found") in str(ce):
-			log('[E] The specified user does not exist.', "RED")
-		seperator("GREEN")
+			log_error('The specified user does not exist.')
+		log_seperator()
 		sys.exit(1)
 	except Exception as e:
-		log('[E] Could not get user info for "{:s}": {:s}'.format(user_to_download, str(e)), "RED")
+		log_error('Could not get user info for "{:s}": {:s}'.format(user_to_download, str(e)))
 
-		seperator("GREEN")
+		log_seperator()
 		sys.exit(1)
 	except KeyboardInterrupt:
-		log('[W] Aborted getting user info for "{:s}", exiting...'.format(user_to_download), "YELLOW")
-		seperator("GREEN")
+		log_info_blue('Aborted getting user info for "{:s}", exiting...'.format(user_to_download))
+		log_seperator()
 		sys.exit(0)
-	log('[I] Getting info for "{:s}" successful.'.format(user_to_download), "GREEN")
+	log_info_green('Getting info for "{:s}" successful.'.format(user_to_download))
 	get_broadcasts_info(user_id)
 
 
 
 def get_broadcasts_info(user_id):
 	try:
-		seperator("GREEN")
-		log('[I] Checking for livestreams and replays...', "GREEN")
-		seperator("GREEN")
+		log_seperator()
+		log_info_green('Checking for livestreams and replays...')
+		log_seperator()
 		broadcasts = instagram_api.user_story_feed(user_id)
 
 		livestream = broadcasts.get('broadcast')
@@ -273,55 +277,55 @@ def get_broadcasts_info(user_id):
 			if livestream:
 				download_livestream(livestream)
 			else:
-				log('[I] There are no available livestreams.', "YELLOW")
+				log_info_green('There are no available livestreams.')
 		else:
-			log("[I] Livestream saving is disabled either with an argument or in the config file.", "BLUE")
+			log_info_blue("Livestream saving is disabled either with an argument or in the config file.")
 			
 
 		if settings.save_replays.title() == "True":
 			if replays:
-				seperator("GREEN")
-				log('[I] Replays found, beginning download...', "GREEN")
-				seperator("GREEN")
+				log_seperator()
+				log_info_green('Replays found, beginning download...')
+				log_seperator()
 				download_replays(replays)
 			else:
-				log('[I] There are no available replays.', "YELLOW")
+				log_info_green('There are no available replays.')
 		else:
-			seperator("GREEN")
-			log("[I] Replay saving is disabled either with an argument or in the config file.", "BLUE")
+			log_seperator()
+			log_info_blue("Replay saving is disabled either with an argument or in the config file.")
 
-		seperator("GREEN")
+		log_seperator()
 	except Exception as e:
-		log('[E] Could not finish checking: {:s}'.format(str(e)), "RED")
+		log_error('Could not finish checking: {:s}'.format(str(e)))
 		if "timed out" in str(e):
-			log('[E] The connection timed out, check your internet connection.', "RED")
-		seperator("GREEN")
+			log_error('The connection timed out, check your internet connection.')
+		log_seperator()
 		exit(1)
 	except KeyboardInterrupt:
-		log('[W] Aborted checking for livestreams and replays, exiting...'.format(user_to_download), "YELLOW")
-		seperator("GREEN")
+		log_info_blue('Aborted checking for livestreams and replays, exiting...'.format(user_to_download))
+		log_seperator()
 		sys.exit(1)
 	except ClientThrottledError as cte:
-		log('[E] Could not check because you are making too many requests at this time.', "RED")
-		seperator("GREEN")
+		log_error('Could not check because you are making too many requests at this time.')
+		log_seperator()
 		exit(1)
 
 def download_replays(broadcasts):
 	try:
 		try:
-			log('[I] Amount of replays    : {:s}'.format(str(len(broadcasts))), "GREEN")
+			log_info_green('Amount of replays    : {:s}'.format(str(len(broadcasts))))
 			for replay_index, broadcast in enumerate(broadcasts):
 				bc_dash_manifest = parseString(broadcast.get('dash_manifest')).getElementsByTagName('Period')
 				bc_duration_raw = bc_dash_manifest[0].getAttribute("duration")	
 				bc_hours = (bc_duration_raw.split("PT"))[1].split("H")[0]
 				bc_minutes = (bc_duration_raw.split("H"))[1].split("M")[0]
 				bc_seconds = ((bc_duration_raw.split("M"))[1].split("S")[0]).split('.')[0]
-				log('[I] Replay {:s} duration    : {:s} minutes and {:s} seconds'.format(str(replay_index + 1), bc_minutes, bc_seconds), "GREEN")
+				log_info_green('Replay {:s} duration    : {:s} minutes and {:s} seconds'.format(str(replay_index + 1), bc_minutes, bc_seconds))
 		except Exception as e:
-			log("[W] An error occurred while getting replay duration information: {:s}".format(str(e)))
-		seperator("GREEN")
-		log("[I] Downloading replays... press [CTRL+C] to abort.", "GREEN")
-		seperator("GREEN")
+			log_warn("An error occurred while getting replay duration information: {:s}".format(str(e)))
+		log_seperator()
+		log_info_green("Downloading replays... press [CTRL+C] to abort.")
+		log_seperator()
 		for replay_index, broadcast in enumerate(broadcasts):
 			exists = False
 
@@ -332,11 +336,11 @@ def download_replays(broadcasts):
 
 			for directory in directories:
 				if (str(broadcast.get('id')) in directory) and ("_live_" not in directory):
-					log("[W] Already downloaded a replay with ID '{:s}'.".format(str(broadcast.get('id'))), "YELLOW")
+					log_info_blue("Already downloaded a replay with ID '{:s}'.".format(str(broadcast.get('id'))))
 					exists = True
 			if not exists:
 				current = replay_index + 1
-				log("[I] Downloading replay {:s} of {:s} with ID '{:s}'...".format(str(current), str(len(broadcasts)), str(broadcast.get('id'))), "GREEN")
+				log_info_green("Downloading replay {:s} of {:s} with ID '{:s}'...".format(str(current), str(len(broadcasts)), str(broadcast.get('id'))))
 				current_time = str(int(time.time()))
 				output_dir = '{}{}_{}_{}_{}_replay_downloads'.format(settings.save_path, settings.current_date, user_to_download, broadcast.get('id'), settings.current_time)
 				broadcast_downloader = replay.Downloader(
@@ -353,47 +357,47 @@ def download_replays(broadcasts):
 					replay_saved = broadcast_downloader.download(replay_mp4_file, cleartempfiles=False)
 
 				if settings.save_comments.title() == "True":
-					log("[I] Downloading replay comments...", "GREEN")
+					log_info_green("Downloading replay comments...")
 					try:
 						get_replay_comments(instagram_api, broadcast, replay_json_file, broadcast_downloader)
 					except Exception as e:
-						log('[E] An error occurred while downloading comments: {:s}'.format(str(e)), "RED")
+						log_error('An error occurred while downloading comments: {:s}'.format(str(e)))
 
 				if (len(replay_saved) == 1):
-					log("[I] Finished downloading replay {:s} of {:s}.".format(str(current), str(len(broadcasts))), "GREEN")
+					log_info_green("Finished downloading replay {:s} of {:s}.".format(str(current), str(len(broadcasts))))
 					try:
 					    os.remove(os.path.join(output_dir, 'folder.lock'))
 					except Exception:
 					    pass
 
 					if (current != len(broadcasts)):
-						seperator("GREEN")
+						log_seperator()
 
 				else:
-					log("[W] No output video file was made, please merge the files manually if possible.", "YELLOW")
-					log("[W] Check if ffmpeg is available by running ffmpeg in your terminal/cmd prompt.", "YELLOW")
-					log("", "GREEN")
+					log_warn("No output video file was made, please merge the files manually if possible.")
+					log_warn("Check if ffmpeg is available by running ffmpeg in your terminal/cmd prompt.")
+					log_whiteline()
 
-		seperator("GREEN")
-		log("[I] Finished downloading all available replays.", "GREEN")
-		seperator("GREEN")
+		log_seperator()
+		log_info_green("Finished downloading all available replays.")
+		log_seperator()
 		sys.exit(0)
 	except Exception as e:
-		log('[E] Could not save replay: {:s}'.format(str(e)), "RED")
-		seperator("GREEN")
+		log_error('Could not save replay: {:s}'.format(str(e)))
+		log_seperator()
 		try:
 		    os.remove(os.path.join(output_dir, 'folder.lock'))
 		except Exception:
 		    pass
 		sys.exit(1)
 	except KeyboardInterrupt:
-		seperator("GREEN")
-		log('[I] The download has been aborted by the user, exiting...', "YELLOW")
-		seperator("GREEN")
+		log_seperator()
+		log_info_blue('The download has been aborted by the user, exiting...')
+		log_seperator()
 		try:
 			shutil.rmtree(output_dir)
 		except Exception as e:
-			log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
+			log_error("Could not remove temp folder: {:s}".format(str(e)))
 			sys.exit(1)
 		sys.exit(0)
 
@@ -412,24 +416,24 @@ def get_replay_comments(instagram_api, broadcast, comments_json_file, broadcast_
 					comments_downloader.comments, broadcast.get('published_time'), comments_log_file,
 					comments_delay=0)
 				if total_comments == 1:
-					log("[I] Successfully saved 1 comment to logfile.", "GREEN")
-					seperator("GREEN")
+					log_info_green("Successfully saved 1 comment to logfile.")
+					log_seperator()
 					return True
 				else:
 					if comment_errors:
-						log("[W] Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)), "YELLOW")
+						log_warn("Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)))
 					else:
-						log("[I] Successfully saved {:s} comments to logfile.".format(str(total_comments)), "GREEN")
-					seperator("GREEN")
+						log_info_green("Successfully saved {:s} comments to logfile.".format(str(total_comments)))
+					log_seperator()
 					return True
 			else:
-				log("[I] There are no available comments to save.", "GREEN")
+				log_info_green("There are no available comments to save.")
 				return False
 		except Exception as e:
-			log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")
+			log_error('Could not save comments to logfile: {:s}'.format(str(e)))
 			return False
 	except KeyboardInterrupt as e:
-		log("[W] Downloading replay comments has been aborted.", "YELLOW")
+		log_info_blue("Downloading replay comments has been aborted.")
 		return False
 
 
@@ -448,7 +452,7 @@ def get_live_comments(instagram_api, broadcast, comments_json_file, broadcast_do
 				first_comment_created_at = comments_downloader.get_live(first_comment_created_at)
 		except ClientError as e:
 			if not 'media has been deleted' in e.error_response:
-				log("[W] Comment collection ClientError: %d %s" % (e.code, e.error_response), "YELLOW")
+				log_warn("Comment collection ClientError: %d %s" % (e.code, e.error_response))
 
 		try:
 			if comments_downloader.comments:
@@ -458,23 +462,23 @@ def get_live_comments(instagram_api, broadcast, comments_json_file, broadcast_do
 					comments_downloader.comments, settings.current_time, comments_log_file,
 					comments_delay=broadcast_downloader.initial_buffered_duration)
 				if len(comments_downloader.comments) == 1:
-					log("[I] Successfully saved 1 comment to logfile.", "GREEN")
-					seperator("GREEN")
+					log_info_green("Successfully saved 1 comment to logfile.")
+					log_seperator()
 					return True
 				else:
 					if comment_errors:
-						log("[W] Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)), "YELLOW")
+						log_warn("Successfully saved {:s} comments to logfile but {:s} comments are (partially) missing.".format(str(total_comments), str(comment_errors)))
 					else:
-						log("[I] Successfully saved {:s} comments to logfile.".format(str(total_comments)), "GREEN")
-					seperator("GREEN")
+						log_info_green("Successfully saved {:s} comments to logfile.".format(str(total_comments)))
+					log_seperator()
 					return True
 			else:
-				log("[I] There are no available comments to save.", "GREEN")
+				log_info_green("There are no available comments to save.")
 				return False
-				seperator("GREEN")
+				log_seperator()
 		except Exception as e:
-			log('[E] Could not save comments to logfile: {:s}'.format(str(e)), "RED")
+			log_error('Could not save comments to logfile: {:s}'.format(str(e)))
 			return False
 	except KeyboardInterrupt as e:
-		log("[W] Downloading livestream comments has been aborted.", "YELLOW")
+		log_info_blue("Downloading livestream comments has been aborted.")
 		return False

+ 121 - 124
pyinstalive/initialize.py

@@ -10,9 +10,7 @@ import json
 
 from .auth import login
 from .downloader import main
-from .logger import log
-from .logger import seperator
-from .logger import supports_color
+from .logger import log_seperator, supports_color, log_info_blue, log_info_green, log_warn, log_error, log_whiteline, log_plain
 from .settings import settings
 
 script_version = "2.5.6"
@@ -37,11 +35,11 @@ def check_config_validity(config):
 		try:
 			settings.show_cookie_expiry = config.get('pyinstalive', 'show_cookie_expiry').title()
 			if not settings.show_cookie_expiry in bool_values:
-				log("[W] Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)", "YELLOW")
+				log_warn("Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)")
 				settings.show_cookie_expiry = 'true'
 				has_thrown_errors = True
 		except:
-			log("[W] Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)", "YELLOW")
+			log_warn("Invalid or missing setting detected for 'show_cookie_expiry', using default value (True)")
 			settings.show_cookie_expiry = 'true'
 			has_thrown_errors = True
 
@@ -50,11 +48,11 @@ def check_config_validity(config):
 		try:
 			settings.clear_temp_files = config.get('pyinstalive', 'clear_temp_files').title()
 			if not settings.clear_temp_files in bool_values:
-				log("[W] Invalid or missing setting detected for 'clear_temp_files', using default value (True)", "YELLOW")
+				log_warn("Invalid or missing setting detected for 'clear_temp_files', using default value (True)")
 				settings.clear_temp_files = 'true'
 				has_thrown_errors = True
 		except:
-			log("[W] Invalid or missing setting detected for 'clear_temp_files', using default value (True)", "YELLOW")
+			log_warn("Invalid or missing setting detected for 'clear_temp_files', using default value (True)")
 			settings.clear_temp_files = 'true'
 			has_thrown_errors = True
 
@@ -63,22 +61,22 @@ def check_config_validity(config):
 		try:
 			settings.save_replays = config.get('pyinstalive', 'save_replays').title()
 			if not settings.save_replays in bool_values:
-				log("[W] Invalid or missing setting detected for 'save_replays', using default value (True)", "YELLOW")
+				log_warn("Invalid or missing setting detected for 'save_replays', using default value (True)")
 				settings.save_replays = 'true'
 				has_thrown_errors = True
 		except:
-			log("[W] Invalid or missing setting detected for 'save_replays', using default value (True)", "YELLOW")
+			log_warn("Invalid or missing setting detected for 'save_replays', using default value (True)")
 			settings.save_replays = 'true'
 			has_thrown_errors = True
 
 		try:
 			settings.save_lives = config.get('pyinstalive', 'save_lives').title()
 			if not settings.save_lives in bool_values:
-				log("[W] Invalid or missing setting detected for 'save_lives', using default value (True)", "YELLOW")
+				log_warn("Invalid or missing setting detected for 'save_lives', using default value (True)")
 				settings.save_lives = 'true'
 				has_thrown_errors = True
 		except:
-			log("[W] Invalid or missing setting detected for 'save_lives', using default value (True)", "YELLOW")
+			log_warn("Invalid or missing setting detected for 'save_lives', using default value (True)")
 			settings.save_lives = 'true'
 			has_thrown_errors = True
 
@@ -87,11 +85,11 @@ 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 (False)", "YELLOW")
+				log_warn("Invalid or missing setting detected for 'log_to_file', using default value (False)")
 				settings.log_to_file = 'False'
 				has_thrown_errors = True
 		except:
-			log("[W] Invalid or missing setting detected for 'log_to_file', using default value (False)", "YELLOW")
+			log_warn("Invalid or missing setting detected for 'log_to_file', using default value (False)")
 			settings.log_to_file = 'False'
 			has_thrown_errors = True
 
@@ -102,7 +100,7 @@ def check_config_validity(config):
 			if not settings.run_at_start:
 				settings.run_at_start = "None"
 		except:
-			log("[W] Invalid or missing settings detected for 'run_at_start', using default value (None)", "YELLOW")
+			log_warn("Invalid or missing settings detected for 'run_at_start', using default value (None)")
 			settings.run_at_start = "None"
 			has_thrown_errors = True
 
@@ -113,7 +111,7 @@ def check_config_validity(config):
 			if not settings.run_at_finish:
 				settings.run_at_finish = "None"
 		except:
-			log("[W] Invalid or missing settings detected for 'run_at_finish', using default value (None)", "YELLOW")
+			log_warn("Invalid or missing settings detected for 'run_at_finish', using default value (None)")
 			settings.run_at_finish = "None"
 			has_thrown_errors = True
 
@@ -122,15 +120,16 @@ def check_config_validity(config):
 			settings.save_comments = config.get('pyinstalive', 'save_comments').title()
 			wide_build = sys.maxunicode > 65536
 			if sys.version.split(' ')[0].startswith('2') and settings.save_comments == "True" and not wide_build:
-				log("[W] Your Python 2 build does not support wide unicode characters.\n[W] This means characters such as emojis will not be saved.", "YELLOW")
+				log_warn("Your Python 2 build does not support wide unicode characters.")
+				log_warn("This means characters such as emojis will not be saved.")
 				has_thrown_errors = True
 			else:
 				if not settings.show_cookie_expiry in bool_values:
-					log("[W] Invalid or missing setting detected for 'save_comments', using default value (False)", "YELLOW")
+					log_warn("Invalid or missing setting detected for 'save_comments', using default value (False)")
 					settings.save_comments = 'false'
 					has_thrown_errors = True
 		except:
-			log("[W] Invalid or missing setting detected for 'save_comments', using default value (False)", "YELLOW")
+			log_warn("Invalid or missing setting detected for 'save_comments', using default value (False)")
 			settings.save_comments = 'false'
 			has_thrown_errors = True
 
@@ -140,20 +139,20 @@ def check_config_validity(config):
 			if (os.path.exists(settings.save_path)):
 				pass
 			else:
-				log("[W] Invalid or missing setting detected for 'save_path', falling back to path: {:s}".format(os.getcwd()), "YELLOW")
+				log_warn("Invalid or missing setting detected for 'save_path', falling back to path: {:s}".format(os.getcwd()))
 				settings.save_path = os.getcwd()
 				has_thrown_errors = True
 
 			if not settings.save_path.endswith('/'):
 				settings.save_path = settings.save_path + '/'
 		except:
-			log("[W] Invalid or missing setting detected for 'save_path', falling back to path: {:s}".format(os.getcwd()), "YELLOW")
+			log_warn("Invalid or missing setting detected for 'save_path', falling back to path: {:s}".format(os.getcwd()))
 			settings.save_path = os.getcwd()
 			has_thrown_errors = True
 
 
 		if has_thrown_errors:
-			seperator("GREEN")
+			log_seperator()
 
 		return True
 	except Exception as e:
@@ -167,15 +166,15 @@ def show_info(config):
 		try:
 			config.read('pyinstalive.ini')
 		except Exception as e:
-			log("[E] Could not read configuration file: {:s}".format(str(e)), "RED")
-			seperator("GREEN")
+			log_error("Could not read configuration file: {:s}".format(str(e)))
+			log_seperator()
 	else:
 		new_config()
 		sys.exit(1)
 
 	if not check_config_validity(config):
-		log("[W] Config file is not valid, some information may be inaccurate.", "YELLOW")
-		log("", "GREEN")
+		log_warn("Config file is not valid, some information may be inaccurate.")
+		log_whiteline()
 
 	cookie_files = []
 	cookie_from_config = ''
@@ -192,59 +191,59 @@ def show_info(config):
 			if settings.username == file.replace(".json", ''):
 				cookie_from_config = file
 	except Exception as e:
-		log("[W] Could not check for cookie files: {:s}".format(str(e)), "YELLOW")
-		log("", "ENDC")
-	log("[I] To see all the available arguments, use the -h argument.", "BLUE")
-	log("", "GREEN")
-	log("[I] PyInstaLive version:    	{:s}".format(script_version), "GREEN")
-	log("[I] Python version:         	{:s}".format(python_version), "GREEN")
+		log_warn("Could not check for cookie files: {:s}".format(str(e)))
+		log_whiteline()
+	log_info_green("To see all the available arguments, use the -h argument.")
+	log_whiteline()
+	log_info_green("PyInstaLive version:    	{:s}".format(script_version))
+	log_info_green("Python version:         	{:s}".format(python_version))
 	if not check_ffmpeg():
-		log("[E] FFmpeg framework:       	Not found", "RED")
+		log_error("FFmpeg framework:       	Not found")
 	else:
-		log("[I] FFmpeg framework:       	Available", "GREEN")
+		log_info_green("FFmpeg framework:       	Available")
 
 	if (len(cookie_from_config) > 0):
-		log("[I] Cookie files:            	{:s} ({:s} matches config user)".format(str(len(cookie_files)), cookie_from_config), "GREEN")
+		log_info_green("Cookie files:            	{:s} ({:s} matches config user)".format(str(len(cookie_files)), cookie_from_config))
 	elif len(cookie_files) > 0:
-		log("[I] Cookie files:            	{:s}".format(str(len(cookie_files))), "GREEN")
+		log_info_green("Cookie files:            	{:s}".format(str(len(cookie_files))))
 	else:
-		log("[W] Cookie files:            	None found", "YELLOW")
+		log_warn("Cookie files:            	None found")
 
-	log("[I] CLI supports color:     	{:s}".format(str(supports_color()[0])), "GREEN")
-	log("[I] File to run at start:       {:s}".format(settings.run_at_start), "GREEN")
-	log("[I] File to run at finish:      {:s}".format(settings.run_at_finish), "GREEN")
-	log("", "GREEN")
+	log_info_green("CLI supports color:     	{:s}".format(str(supports_color()[0])))
+	log_info_green("File to run at start:       {:s}".format(settings.run_at_start))
+	log_info_green("File to run at finish:      {:s}".format(settings.run_at_finish))
+	log_whiteline()
 
 
 	if os.path.exists('pyinstalive.ini'):
-		log("[I] Config file:", "GREEN")
-		log("", "GREEN")
+		log_info_green("Config file:")
+		log_whiteline()
 		with open('pyinstalive.ini') as f:
 			for line in f:
-				log("    {:s}".format(line.rstrip()), "YELLOW")
+				log_plain("    {:s}".format(line.rstrip()))
 	else:
-		log("[E] Config file:	    	Not found", "RED")
-	log("", "GREEN")
-	log("[I] End of PyInstaLive information screen.", "GREEN")
-	seperator("GREEN")
+		log_error("Config file:	    	Not found")
+	log_whiteline()
+	log_info_green("End of PyInstaLive information screen.")
+	log_seperator()
 
 
 
 def new_config():
 	try:
 		if os.path.exists('pyinstalive.ini'):
-			log("[I] A configuration file is already present:", "GREEN")
-			log("", "GREEN")
+			log_info_green("A configuration file is already present:")
+			log_whiteline()
 			with open('pyinstalive.ini') as f:
 				for line in f:
-					log("    {:s}".format(line.rstrip()), "YELLOW")
-			log("", "GREEN")
-			log("[I] To create a default config file, delete 'pyinstalive.ini' and ", "GREEN")
-			log("    run this script again.", "GREEN")
-			seperator("GREEN")
+					log_plain("    {:s}".format(line.rstrip()))
+			log_whiteline()
+			log_info_green("To create a default config file, delete 'pyinstalive.ini' and ")
+			log_plain("    run this script again.")
+			log_seperator()
 		else:
 			try:
-				log("[W] Could not find configuration file, creating a default one...", "YELLOW")
+				log_warn("Could not find configuration file, creating a default one...")
 				config_template = """
 [pyinstalive]
 username = johndoe
@@ -262,27 +261,27 @@ log_to_file = false
 				config_file = open("pyinstalive.ini", "w")
 				config_file.write(config_template.strip())
 				config_file.close()
-				log("[W] Edit the created 'pyinstalive.ini' file and run this script again.", "YELLOW")
-				seperator("GREEN")
+				log_warn("Edit the created 'pyinstalive.ini' file and run this script again.")
+				log_seperator()
 				sys.exit(0)
 			except Exception as e:
-				log("[E] Could not create default config file: {:s}".format(str(e)), "RED")
-				log("[W] You must manually create and edit it with the following template: ", "YELLOW")
-				log("", "GREEN")
+				log_error("Could not create default config file: {:s}".format(str(e)))
+				log_warn("You must manually create and edit it with the following template: ")
+				log_whiteline()
 				for line in config_template.strip().splitlines():
-					log("    {:s}".format(line.rstrip()), "YELLOW")
-				log("", "GREEN")
-				log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
-				seperator("GREEN")
+					log_plain("    {:s}".format(line.rstrip()))
+				log_whiteline()
+				log_warn("Save it as 'pyinstalive.ini' and run this script again.")
+				log_seperator()
 	except Exception as e:
-		log("[E] An error occurred: {:s}".format(str(e)), "RED")
-		log("[W] If you don't have a configuration file, you must", "YELLOW")
-		log("    manually create and edit it with the following template: ", "YELLOW")
-		log("", "GREEN")
-		log(config_template, "YELLOW")
-		log("", "GREEN")
-		log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
-		seperator("GREEN")
+		log_error("An error occurred: {:s}".format(str(e)))
+		log_warn("If you don't have a configuration file, you must")
+		log_plain("    manually create and edit it with the following template: ")
+		log_whiteline()
+		log_plain(config_template)
+		log_whiteline()
+		log_warn("Save it as 'pyinstalive.ini' and run this script again.")
+		log_seperator()
 
 
 
@@ -291,7 +290,7 @@ def clean_download_dir():
 	error_count = 0
 	lock_count = 0
 
-	log('[I] Cleaning up temporary files and folders...', "GREEN")
+	log_info_green(' Cleaning up temporary files and folders...')
 	try:
 		if sys.version.split(' ')[0].startswith('2'):
 			directories = (os.walk(settings.save_path).next()[1])
@@ -307,31 +306,31 @@ def clean_download_dir():
 						shutil.rmtree(settings.save_path + directory)
 						dir_delcount += 1
 					except Exception as e:
-						log("[E] Could not remove temp folder: {:s}".format(str(e)), "RED")
+						log_error("Could not remove temp folder: {:s}".format(str(e)))
 						error_count += 1
 				else:
 					lock_count += 1
-		seperator("GREEN")
-		log('[I] The cleanup has finished.', "YELLOW")
+		log_seperator()
+		log_info_green(' The cleanup has finished.')
 		if dir_delcount == 0 and error_count == 0 and lock_count == 0:
-			log('[I] No folders were removed.', "YELLOW")
-			seperator("GREEN")
+			log_info_green(' No folders were removed.')
+			log_seperator()
 			return
-		log('[I] Folders removed:     {:d}'.format(dir_delcount), "YELLOW")
-		log('[I] Locked folders:      {:d}'.format(lock_count), "YELLOW")
-		log('[I] Errors:              {:d}'.format(error_count), "YELLOW")
-		seperator("GREEN")
+		log_info_green(' Folders removed:     {:d}'.format(dir_delcount))
+		log_info_green(' Locked folders:      {:d}'.format(lock_count))
+		log_info_green(' Errors:              {:d}'.format(error_count))
+		log_seperator()
 	except KeyboardInterrupt as e:
-		seperator("GREEN")
-		log("[W] The cleanup has been aborted.", "YELLOW")
+		log_seperator()
+		log_warn("The cleanup has been aborted.")
 		if dir_delcount == 0 and error_count == 0 and lock_count == 0:
-			log('[I] No folders were removed.', "YELLOW")
-			seperator("GREEN")
+			log_info_green(' No folders were removed.')
+			log_seperator()
 			return
-		log('[I] Folders removed:     {:d}'.format(dir_delcount), "YELLOW")
-		log('[I] Locked folders:      {:d}'.format(lock_count), "YELLOW")
-		log('[I] Errors:              {:d}'.format(error_count), "YELLOW")
-		seperator("GREEN")
+		log_info_green(' Folders removed:     {:d}'.format(dir_delcount))
+		log_info_green(' Locked folders:      {:d}'.format(lock_count))
+		log_info_green(' Errors:              {:d}'.format(error_count))
+		log_seperator()
 
 def run():
 	logging.disable(logging.CRITICAL)
@@ -359,7 +358,7 @@ def run():
 	parser.add_argument('-nx', help=argparse.SUPPRESS, metavar='IGNORE')
 
 
-	args, unknown = parser.parse_known_args()
+	args, unknown_args = parser.parse_known_args()
 
 
 	try:
@@ -370,10 +369,8 @@ def run():
 		elif settings.log_to_file == "True":
 			if args.download:
 				settings.user_to_download = args.download
-			else:
-				settings.user_to_download = "log"
 			try:
-				with open("pyinstalive_{:s}.log".format(settings.user_to_download),"a+") as f:
+				with open("pyinstalive{:s}.log".format("_" + settings.user_to_download if len(settings.user_to_download) > 0 else ".default"),"a+") as f:
 					f.write("\n")
 					f.close()
 			except:
@@ -382,20 +379,20 @@ def run():
 		settings.log_to_file = 'False'
 		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")
+	log_seperator()
+	log_info_blue('PYINSTALIVE (SCRIPT V{:s} - PYTHON V{:s}) - {:s}'.format(script_version, python_version, time.strftime('%I:%M:%S %p')))
+	log_seperator()
 
-	if unknown:
-		log("[E] The following invalid argument(s) were provided: ", "RED") 
-		log('', "GREEN") 
-		log('    ' + ' '.join(unknown), "YELLOW") 
-		log('', "GREEN")
+	if unknown_args:
+		log_error("The following invalid argument(s) were provided: ") 
+		log_whiteline() 
+		log_info_blue('    ' + ' '.join(unknown_args)) 
+		log_whiteline()
 		if (supports_color()[1] == True):
-			log("[I] \033[94mpyinstalive -h\033[92m can be used to display command help.", "GREEN")
+			log_info_green("'pyinstalive -h' can be used to display command help.")
 		else:
-			log("[I] pyinstalive -h can be used to display command help.", "GREEN")
-		seperator("GREEN")
+			log_plain("pyinstalive -h can be used to display command help.")
+		log_seperator()
 		exit(1)
 
 	if (args.info) or (not
@@ -419,8 +416,8 @@ def run():
 		try:
 			config.read('pyinstalive.ini')
 		except Exception:
-			log("[E] Could not read configuration file.", "RED")
-			seperator("GREEN")
+			log_error("Could not read configuration file.")
+			log_seperator()
 	else:
 		new_config()
 		sys.exit(1)
@@ -433,8 +430,8 @@ def run():
 				sys.exit(0)
 
 			if not check_ffmpeg():
-				log("[E] Could not find ffmpeg, the script will now exit. ", "RED")
-				seperator("GREEN")
+				log_error("Could not find ffmpeg, the script will now exit. ")
+				log_seperator()
 				sys.exit(1)
 
 			if (args.noreplays):
@@ -444,43 +441,43 @@ def run():
 				settings.save_lives = "False"
 
 			if settings.save_lives == "False" and settings.save_replays == "False":
-				log("[W] Script will not run because both live and replay saving is disabled.", "YELLOW")
-				seperator("GREEN")
+				log_warn("Script will not run because both live and replay saving is disabled.")
+				log_seperator()
 				sys.exit(1)
 
 			if not args.download:
-				log("[W] Missing --download argument. Please specify an Instagram username.", "YELLOW")
-				seperator("GREEN")
+				log_warn("Missing --download argument. Please specify an Instagram username.")
+				log_seperator()
 				sys.exit(1)
 
 
 			if (args.username is not None) and (args.password is not None):
 				api = login(args.username, args.password, settings.show_cookie_expiry, True)
 			elif (args.username is not None) or (args.password is not None):
-				log("[W] Missing --username or --password argument, falling back to config file...", "YELLOW")
+				log_warn("Missing --username or --password argument, falling back to config file...")
 				if (not len(settings.username) > 0) or (not len(settings.password) > 0):
-					log("[E] Username or password are missing. Please check your configuration settings and try again.", "RED")
-					seperator("GREEN")
+					log_error("Username or password are missing. Please check your configuration settings and try again.")
+					log_seperator()
 					sys.exit(1)
 				else:
 					api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
 			else:
 				if (not len(settings.username) > 0) or (not len(settings.password) > 0):
-					log("[E] Username or password are missing. Please check your configuration settings and try again.", "RED")
-					seperator("GREEN")
+					log_error("Username or password are missing. Please check your configuration settings and try again.")
+					log_seperator()
 					sys.exit(1)
 				else:
 					api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
 
 			main(api, args.download, settings)
 		except Exception as e:
-			log("[E] Could not finish pre-download checks:  {:s}".format(str(e)), "RED")
-			seperator("GREEN")
+			log_error("Could not finish pre-download checks:  {:s}".format(str(e)))
+			log_seperator()
 		except KeyboardInterrupt as ee:
-			log("[W] Pre-download checks have been aborted, exiting...", "YELLOW")
-			seperator("GREEN")
+			log_warn("Pre-download checks have been aborted, exiting...")
+			log_seperator()
 
 	else:
-		log("[E] The configuration file is not valid. Please check your configuration settings and try again.", "RED")
-		seperator("GREEN")
+		log_error("The configuration file is not valid. Please check your configuration settings and try again.")
+		log_seperator()
 		sys.exit(1)

+ 75 - 33
pyinstalive/logger.py

@@ -5,29 +5,6 @@ from .settings import settings
 
 sep = "-" * 70
 
-def colors(state):
-	color = ''
-
-	if (state == 'BLUE'):
-		color = '\033[94m'
-
-	if (state == 'GREEN'):
-		color = '\033[92m'
-
-	if (state == 'YELLOW'):
-		color = '\033[93m'
-
-	if (state == 'RED'):
-		color = '\033[91m'
-
-	if (state == 'ENDC'):
-		color = '\033[0m'
-
-	if (state == 'WHITE'):
-		color = '\033[0m'
-
-	return color
-
 def supports_color():
 	"""
 	from https://github.com/django/django/blob/master/django/core/management/color.py
@@ -44,30 +21,95 @@ def supports_color():
 		return "No", False
 	return "Yes", True
 
-def log(string, color):
+
+def log_seperator():
+	print(sep + "\033[0m")
+	if settings.log_to_file == 'True':
+		try:
+			with open("pyinstalive{:s}.log".format("_" + settings.user_to_download if len(settings.user_to_download) > 0 else ".default"),"a+") as f:
+				f.write(sep + '\n')
+				f.close()
+		except:
+			pass
+	sys.stdout.flush()
+
+
+
+
+
+def log_info_green(string):
 	if supports_color()[1] == False:
 		print(string)
 	else:
-		print('\033[1m{}{}{}'.format(colors(color), string, colors("ENDC")))
+		print('[\033[92mI\033[0m] {:s}\033[0m'.format(string))
 	if settings.log_to_file == 'True':
 		try:
-			with open("pyinstalive_{:s}.log".format(settings.user_to_download),"a+") as f:
-				no_ansi = re.compile(r'\x1B\[[0-?]*[ -/]*[@-~]')
-				f.write("{:s}\n".format(no_ansi.sub('', string)))
+			with open("pyinstalive{:s}.log".format("_" + settings.user_to_download if len(settings.user_to_download) > 0 else ".default"),"a+") as f:
+				f.write("[I] {:s}\n".format(string))
 				f.close()
 		except:
 			pass
 	sys.stdout.flush()
 
-def seperator(color):
+def log_info_blue(string):
 	if supports_color()[1] == False:
-		print(sep)
+		print(string)
 	else:
-		print('\033[1m{}{}{}'.format(colors(color), sep, colors("ENDC")))
+		print('[\033[94mI\033[0m] {:s}\033[0m'.format(string))
+	if settings.log_to_file == 'True':
+		try:
+			with open("pyinstalive{:s}.log".format("_" + settings.user_to_download if len(settings.user_to_download) > 0 else ".default"),"a+") as f:
+				f.write("[I] {:s}\n".format(string))
+				f.close()
+		except:
+			pass
+	sys.stdout.flush()
+
+def log_warn(string):
+	if supports_color()[1] == False:
+		print(string)
+	else:
+		print('[\033[93mW\033[0m] {:s}\033[0m'.format(string))
+	if settings.log_to_file == 'True':
+		try:
+			with open("pyinstalive{:s}.log".format("_" + settings.user_to_download if len(settings.user_to_download) > 0 else ".default"),"a+") as f:
+				f.write("[I] {:s}\n".format(string))
+				f.close()
+		except:
+			pass
+	sys.stdout.flush()
+
+def log_error(string):
+	if supports_color()[1] == False:
+		print(string)
+	else:
+		print('[\033[91mE\033[0m] {:s}\033[0m'.format(string))
+	if settings.log_to_file == 'True':
+		try:
+			with open("pyinstalive{:s}.log".format("_" + settings.user_to_download if len(settings.user_to_download) > 0 else ".default"),"a+") as f:
+				f.write("[I] {:s}\n".format(string))
+				f.close()
+		except:
+			pass
+	sys.stdout.flush()
+
+def log_whiteline():
+	print("")
+	if settings.log_to_file == 'True':
+		try:
+			with open("pyinstalive{:s}.log".format("_" + settings.user_to_download if len(settings.user_to_download) > 0 else ".default"),"a+") as f:
+				f.write("\n")
+				f.close()
+		except:
+			pass
+	sys.stdout.flush()
+
+def log_plain(string):
+	print(string)
 	if settings.log_to_file == 'True':
 		try:
-			with open("pyinstalive_{:s}.log".format(settings.user_to_download),"a+") as f:
-				f.write("{:s}\n".format(sep))
+			with open("pyinstalive{:s}.log".format("_" + settings.user_to_download if len(settings.user_to_download) > 0 else ".default"),"a+") as f:
+				f.write("    {:s}\n".format(string))
 				f.close()
 		except:
 			pass