Просмотр исходного кода

Testing for Python>=3.5 support

Cammy 7 лет назад
Родитель
Сommit
a9e3920f8b
4 измененных файлов с 89 добавлено и 85 удалено
  1. 10 10
      pyinstalive/auth.py
  2. 47 47
      pyinstalive/downloader.py
  3. 30 28
      pyinstalive/initialize.py
  4. 2 0
      setup.py

+ 10 - 10
pyinstalive/auth.py

@@ -3,7 +3,7 @@ import datetime
 import json
 import os.path
 import sys
-import logger
+from .logger import log, seperator
 
 
 
@@ -36,7 +36,7 @@ def onlogin_callback(api, settings_file):
 	cache_settings = api.settings
 	with open(settings_file, 'w') as outfile:
 		json.dump(cache_settings, outfile, default=to_json)
-		logger.log('[I] New auth cookie file was made: {0!s}'.format(settings_file), "GREEN")
+		log('[I] New auth cookie file was made: {0!s}'.format(settings_file), "GREEN")
 
 
 def login(username, password, show_cookie_expiry):
@@ -46,7 +46,7 @@ def login(username, password, show_cookie_expiry):
 		settings_file = "credentials.json"
 		if not os.path.isfile(settings_file):
 			# settings file does not exist
-			logger.log('[W] Unable to find auth cookie file: {0!s}'.format(settings_file), "YELLOW")
+			log('[W] Unable to find auth cookie file: {0!s}'.format(settings_file), "YELLOW")
 
 			# login new
 			api = Client(
@@ -55,7 +55,7 @@ def login(username, password, show_cookie_expiry):
 		else:
 			with open(settings_file) as file_data:
 				cached_settings = json.load(file_data, object_hook=from_json)
-			# logger.log('[I] Using settings file: {0!s}'.format(settings_file), "GREEN")
+			# log('[I] Using settings file: {0!s}'.format(settings_file), "GREEN")
 
 			device_id = cached_settings.get('device_id')
 			# reuse auth settings
@@ -64,7 +64,7 @@ def login(username, password, show_cookie_expiry):
 				settings=cached_settings)
 
 	except (ClientCookieExpiredError, ClientLoginRequiredError) as e:
-		logger.log('[E] ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(e), "RED")
+		log('[E] ClientCookieExpiredError/ClientLoginRequiredError: {0!s}'.format(e), "RED")
 
 		# Login expired
 		# Do relogin but use default ua, keys and such
@@ -74,18 +74,18 @@ def login(username, password, show_cookie_expiry):
 			on_login=lambda x: onlogin_callback(x, settings_file))
 
 	except ClientLoginError as e:
-		logger.log('[E] ClientLoginError: {0!s}'.format(e), "RED")
+		log('[E] ClientLoginError: {0!s}'.format(e), "RED")
 		sys.exit(9)
 	except ClientError as e:
-		logger.log('[E] ClientError: {0!s}'.format(e), "RED")
+		log('[E] ClientError: {0!s}'.format(e), "RED")
 		sys.exit(9)
 	except Exception as e:
-		logger.log('[E] Unexpected Exception: {0!s}'.format(e), "RED")
+		log('[E] Unexpected Exception: {0!s}'.format(e), "RED")
 		sys.exit(99)
 
-	logger.log('[I] Login to "' + api.authenticated_user_name + '" OK!', "GREEN")
+	log('[I] Login to "' + api.authenticated_user_name + '" OK!', "GREEN")
 	if show_cookie_expiry == 'True':
 		cookie_expiry = api.cookie_jar.expires_earliest
-		logger.log('[I] Login cookie expiry date: {0!s}'.format(datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%d at %H:%M:%S')), "GREEN")
+		log('[I] Login cookie expiry date: {0!s}'.format(datetime.datetime.fromtimestamp(cookie_expiry).strftime('%Y-%m-%d at %H:%M:%S')), "GREEN")
 
 	return api

+ 47 - 47
pyinstalive/downloader.py

@@ -5,7 +5,7 @@ import shutil
 
 from instagram_private_api_extensions import live, replay
 
-import logger
+from .logger import log, seperator
 
 
 class NoLivestreamException(Exception):
@@ -38,10 +38,10 @@ def record_stream(broadcast):
 			started_label = '%d minutes' % started_mins
 			if started_secs:
 				started_label += ' and %d seconds' % started_secs
-			logger.log('[I] Viewers     : ' + str(int(viewers)) + " watching", "GREEN")
-			logger.log('[I] Airing time : ' + started_label, "GREEN")
-			logger.log('[I] Status      : ' + heartbeat_info['broadcast_status'].title(), "GREEN")
-			logger.seperator("GREEN")
+			log('[I] Viewers     : ' + str(int(viewers)) + " watching", "GREEN")
+			log('[I] Airing time : ' + started_label, "GREEN")
+			log('[I] Status      : ' + heartbeat_info['broadcast_status'].title(), "GREEN")
+			seperator("GREEN")
 			return heartbeat_info['broadcast_status'] not in ['active', 'interrupted'] 
 
 		mpd_url = (broadcast.get('dash_manifest')
@@ -60,91 +60,91 @@ def record_stream(broadcast):
 			mpd_download_timeout=5,
 			download_timeout=10)
 	except Exception as e:
-		logger.log('[E] Could not start recording livestream: ' + str(e), "RED")
-		logger.seperator("GREEN")
+		log('[E] Could not start recording livestream: ' + str(e), "RED")
+		seperator("GREEN")
 		sys.exit(1)
 	try:
-		logger.log('[I] Starting livestream recording:', "GREEN")
-		logger.log('[I] Username    : ' + record, "GREEN")
-		logger.log('[I] MPD URL     : ' + mpd_url, "GREEN")
+		log('[I] Starting livestream recording:', "GREEN")
+		log('[I] Username    : ' + record, "GREEN")
+		log('[I] MPD URL     : ' + mpd_url, "GREEN")
 		print_status()
-		logger.log('[I] Recording livestream... press [CTRL+C] to abort.', "GREEN")
+		log('[I] Recording livestream... press [CTRL+C] to abort.', "GREEN")
 		dl.run()
 		stitch_video(dl, broadcast)
 	except KeyboardInterrupt:
-		logger.log("", "GREEN")
-		logger.log('[W] Download has been aborted.', "YELLOW")
-		logger.log("", "GREEN")
+		log("", "GREEN")
+		log('[W] Download has been aborted.', "YELLOW")
+		log("", "GREEN")
 		if not dl.is_aborted:
 			dl.stop()
 			stitch_video(dl, broadcast)
 
 def stitch_video(dl, broadcast):
-		logger.log('[I] Stitching downloaded files into video...', "GREEN")
+		log('[I] Stitching downloaded files into video...', "GREEN")
 		output_file = save_path + '{}_{}_{}_{}_live.mp4'.format(current_date, record, broadcast['id'], current_time)
 		try:
 			dl.stitch(output_file, cleartempfiles=False)
-			logger.log('[I] Successfully stitched downloaded files.', "GREEN")
-			logger.seperator("GREEN")
+			log('[I] Successfully stitched downloaded files.', "GREEN")
+			seperator("GREEN")
 			sys.exit(0)
 		except Exception as e:
-			logger.log('[E] Could not stitch downloaded files: ' + str(e), "RED")
-			logger.seperator("GREEN")
+			log('[E] Could not stitch downloaded files: ' + str(e), "RED")
+			seperator("GREEN")
 			sys.exit(1)
 
 def get_user_info(record):
 	try:
-		logger.log('[I] Getting required user info for user "' + record + '"...', "GREEN")
+		log('[I] Getting required user info for user "' + record + '"...', "GREEN")
 		user_res = api.username_info(record)
 		user_id = user_res['user']['pk']
 	except Exception as e:
-		logger.log('[E] Could not get user info: ' + str(e), "RED")
-		logger.seperator("GREEN")
+		log('[E] Could not get user info: ' + str(e), "RED")
+		seperator("GREEN")
 		sys.exit(1)
 	get_livestreams(user_id)
 	get_replays(user_id)
 
 def get_livestreams(user_id):
 	try:
-		logger.log('[I] Checking for ongoing livestreams...', "GREEN")
+		log('[I] Checking for ongoing livestreams...', "GREEN")
 		broadcast = api.user_broadcast(user_id)
 		if (broadcast is None):
 			raise NoLivestreamException('There are no livestreams available.')
 		else:
 			record_stream(broadcast)
 	except NoLivestreamException as e:
-		logger.log('[W] ' + str(e), "YELLOW")
+		log('[W] ' + str(e), "YELLOW")
 	except Exception as e:
 		if (e.__class__.__name__ is not NoLivestreamException):
-			logger.log('[E] Could not get livestreams info: ' + str(e), "RED")
-			logger.seperator("GREEN")
+			log('[E] Could not get livestreams info: ' + str(e), "RED")
+			seperator("GREEN")
 			sys.exit(1)
 
 
 def get_replays(user_id):
 	try:
-		logger.log('[I] Checking for available replays...', "GREEN")
+		log('[I] Checking for available replays...', "GREEN")
 		user_story_feed = api.user_story_feed(user_id)
 		broadcasts = user_story_feed.get('post_live_item', {}).get('broadcasts', [])
 	except Exception as e:
-		logger.log('[E] Could not get replay info: ' + str(e), "RED")
-		logger.seperator("GREEN")
+		log('[E] Could not get replay info: ' + str(e), "RED")
+		seperator("GREEN")
 		sys.exit(1)
 	try:
 		if (len(broadcasts) == 0):
 			raise NoReplayException('There are no replays available.')
 		else:
-			logger.log("[I] Available replays have been found to download, press [CTRL+C] to abort.", "GREEN")
-			logger.log("", "GREEN")
+			log("[I] Available replays have been found to download, press [CTRL+C] to abort.", "GREEN")
+			log("", "GREEN")
 			for index, broadcast in enumerate(broadcasts):
 				exists = False
 				for directory in (os.walk(save_path).next()[1]):
 					if (str(broadcast['id']) in directory) and ("_live_" not in directory):
-						logger.log("[W] Already downloaded a replay with ID '" + str(broadcast['id']) + "', skipping...", "GREEN")
+						log("[W] Already downloaded a replay with ID '" + str(broadcast['id']) + "', skipping...", "GREEN")
 						exists = True
 				if exists is False:
 					current = index + 1
-					logger.log("[I] Downloading replay " + str(current) + " of "  + str(len(broadcasts)) + " with ID '" + str(broadcast['id']) + "'...", "GREEN")
+					log("[I] Downloading replay " + str(current) + " of "  + str(len(broadcasts)) + " with ID '" + str(broadcast['id']) + "'...", "GREEN")
 					current_time = str(int(time.time()))
 					output_dir = save_path + '{}_{}_{}_{}_replay_downloads'.format(current_date, record, broadcast['id'], current_time)
 					dl = replay.Downloader(
@@ -153,29 +153,29 @@ def get_replays(user_id):
 						user_agent=api.user_agent)
 					replay_saved = dl.download(save_path + '{}_{}_{}_{}_replay.mp4'.format(current_date, record, broadcast['id'], current_time), cleartempfiles=False)
 					if (len(replay_saved) == 1):
-						logger.log("[I] Finished downloading replay " + str(current) + " of "  + str(len(broadcasts)) + ".", "GREEN")
-						logger.log("", "GREEN")
+						log("[I] Finished downloading replay " + str(current) + " of "  + str(len(broadcasts)) + ".", "GREEN")
+						log("", "GREEN")
 					else:
-						logger.log("[W] No output video file was made, please merge the files manually.", "RED")
-						logger.log("[W] Check if ffmpeg is available by running ffmpeg in your terminal.", "RED")
-						logger.log("", "GREEN")
-		logger.log("[I] Finished downloading available replays.", "GREEN")
-		logger.seperator("GREEN")
+						log("[W] No output video file was made, please merge the files manually.", "RED")
+						log("[W] Check if ffmpeg is available by running ffmpeg in your terminal.", "RED")
+						log("", "GREEN")
+		log("[I] Finished downloading available replays.", "GREEN")
+		seperator("GREEN")
 		sys.exit(0)
 	except NoReplayException as e:
-		logger.log('[W] ' + str(e), "YELLOW")
-		logger.seperator("GREEN")
+		log('[W] ' + str(e), "YELLOW")
+		seperator("GREEN")
 		sys.exit(0)
 	except Exception as e:
-		logger.log('[E] Could not save replay: ' + str(e), "RED")
-		logger.seperator("GREEN")
+		log('[E] Could not save replay: ' + str(e), "RED")
+		seperator("GREEN")
 		sys.exit(1)
 	except KeyboardInterrupt:
-		logger.log("", "GREEN")
-		logger.log('[W] Download has been aborted.', "YELLOW")
+		log("", "GREEN")
+		log('[W] Download has been aborted.', "YELLOW")
 		try:
 			shutil.rmtree(output_dir)
 		except Exception as e:
-			logger.log("[E] Could not remove temp folder: " + str(e), "RED")
+			log("[E] Could not remove temp folder: " + str(e), "RED")
 			sys.exit(1)
 		sys.exit(0)

+ 30 - 28
pyinstalive/initialize.py

@@ -5,7 +5,9 @@ import os.path
 import sys
 import subprocess
 
-import auth, downloader, logger
+from .auth import login
+from .logger import log, seperator
+from .downloader import main
 
 def check_ffmpeg():
 	try:
@@ -22,11 +24,11 @@ def check_config_validity(config):
 		password = config['pyinstalive']['password']
 
 		if not (len(username) > 0):
-			logger.log("[E] Invalid setting detected for 'username'.", "RED")
+			log("[E] Invalid setting detected for 'username'.", "RED")
 			return False
 
 		if not (len(password) > 0):
-			logger.log("[E] Invalid setting detected for 'password'.", "RED")
+			log("[E] Invalid setting detected for 'password'.", "RED")
 			return False
 
 		return True
@@ -39,8 +41,8 @@ def run():
 	script_version = "2.2.2"
 	bool_values = {'True', 'False'}
 
-	logger.log('PYINSTALIVE DOWNLOADER (SCRIPT v{0!s})'.format(script_version), "GREEN")
-	logger.seperator("GREEN")
+	log('PYINSTALIVE DOWNLOADER (SCRIPT v{0!s})'.format(script_version), "GREEN")
+	seperator("GREEN")
 
 	logging.disable(logging.CRITICAL)
 	config = configparser.ConfigParser()
@@ -49,26 +51,26 @@ def run():
 		try:
 			config.read('pyinstalive.ini')
 		except Exception:
-			logger.log("[E] Could not read configuration file. Try passing the required arguments manually.", "RED")
-			logger.seperator("GREEN")
+			log("[E] Could not read configuration file. Try passing the required arguments manually.", "RED")
+			seperator("GREEN")
 	else:
-		logger.log("[W] Could not find configuration file, creating a default one ...", "YELLOW")
+		log("[W] Could not find configuration file, creating a default one ...", "YELLOW")
 		try:
 			config_template = "[pyinstalive]\nusername = johndoe\npassword = grapefruits\nsave_path = /\nshow_cookie_expiry = true"
 			config_file = open("pyinstalive.ini", "w")
 			config_file.write(config_template)
 			config_file.close()
-			logger.log("[W] Edit the created 'pyinstalive.ini' file and run this script again.", "YELLOW")
-			logger.seperator("GREEN")
+			log("[W] Edit the created 'pyinstalive.ini' file and run this script again.", "YELLOW")
+			seperator("GREEN")
 			sys.exit(0)
 		except Exception as e:
-			logger.log("[E] Could not create default config file: " + str(e), "RED")
-			logger.log("[W] You must manually create and edit it with the following template: ", "YELLOW")
-			logger.log("", "GREEN")
-			logger.log(config_template, "BLUE")
-			logger.log("", "GREEN")
-			logger.log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
-			logger.log("", "GREEN")
+			log("[E] Could not create default config file: " + str(e), "RED")
+			log("[W] You must manually create and edit it with the following template: ", "YELLOW")
+			log("", "GREEN")
+			log(config_template, "BLUE")
+			log("", "GREEN")
+			log("[W] Save it as 'pyinstalive.ini' and run this script again.", "YELLOW")
+			log("", "GREEN")
 			sys.exit(1)
 
 
@@ -85,17 +87,17 @@ def run():
 		password = config['pyinstalive']['password']
 
 		if check_ffmpeg() == False:
-			logger.log("[E] Could not find ffmpeg, the script will now exit. ", "RED")
-			logger.seperator("GREEN")
+			log("[E] Could not find ffmpeg, the script will now exit. ", "RED")
+			seperator("GREEN")
 			sys.exit(1)
 
 		try:
 			show_cookie_expiry = config['pyinstalive']['show_cookie_expiry']
 			if not config['pyinstalive']['show_cookie_expiry'].title() in bool_values:
-				logger.log("[W] Invalid setting detected for 'show_cookie_expiry', falling back to default value (True)", "YELLOW")
+				log("[W] Invalid setting detected for 'show_cookie_expiry', falling back to default value (True)", "YELLOW")
 				show_cookie_expiry = 'True'
 		except:
-			logger.log("[W] Invalid setting detected for 'show_cookie_expiry', falling back to default value (True)", "YELLOW")
+			log("[W] Invalid setting detected for 'show_cookie_expiry', falling back to default value (True)", "YELLOW")
 			show_cookie_expiry = 'True'
 
 		try:
@@ -104,22 +106,22 @@ def run():
 			if (os.path.exists(save_path)):
 				pass
 			else:
-				logger.log("[W] Invalid setting detected for 'save_path', falling back to location: " + os.getcwd(), "YELLOW")
+				log("[W] Invalid setting detected for 'save_path', falling back to location: " + os.getcwd(), "YELLOW")
 				save_path = os.getcwd()
 
 			if not save_path.endswith('/'):
 				save_path = save_path + '/'
 		except:
-			logger.log("[W] Invalid setting detected for 'save_path', falling back to location: " + os.getcwd(), "YELLOW")
+			log("[W] Invalid setting detected for 'save_path', falling back to location: " + os.getcwd(), "YELLOW")
 			save_path = os.getcwd()
 
 		if (args.username is not None) and (args.password is not None):
-			api = auth.login(args.username, args.password, show_cookie_expiry)
+			api = login(args.username, args.password, show_cookie_expiry)
 		else:
-			api = auth.login(username, password, show_cookie_expiry)
+			api = login(username, password, show_cookie_expiry)
 		
-		downloader.main(api, args.record, save_path)
+		main(api, args.record, save_path)
 	else:
-		logger.log("[E] The configuration file is not valid. Please check your configuration settings and try again.", "RED")
-		logger.seperator("GREEN")
+		log("[E] The configuration file is not valid. Please check your configuration settings and try again.", "RED")
+		seperator("GREEN")
 		sys.exit(0)

+ 2 - 0
setup.py

@@ -41,5 +41,7 @@ setup(
 	classifiers=[
 		'Environment :: Console',
 		'Programming Language :: Python :: 2.7',
+		'Programming Language :: Python :: 3.5',
+		'Programming Language :: Python :: 3.6',
 	]
 )