Forráskód Böngészése

Support basic multi-user check with following list and daemon processes

Cammy 6 éve
szülő
commit
999a1c4954
3 módosított fájl, 105 hozzáadás és 21 törlés
  1. 2 0
      MOREHELP.md
  2. 67 16
      pyinstalive/downloader.py
  3. 36 5
      pyinstalive/initialize.py

+ 2 - 0
MOREHELP.md

@@ -19,6 +19,8 @@
 
 - ```-cl``` or ```--clean```  **—**  When this argument is passed, PyInstaLive clean the current download folder by deleting folders ending in `_downloads`. Any folders that contain a `folder.lock` file (e.g. folders for ongoing downloads) will be skipped.
 
+- ```-df``` or ```--downloadfollowing```  **—**  When this argument is passed, PyInstaLive will check if any users from your following list have any available livestreams or replays and start a daemon process running PyInstaLive in the background for those that do. You cannot cancel the launched processes or start them with any extra arguments. It's recommended to enable ```log_to_file``` when using this argument. (Exeprimental, use at own risk.)
+
 
 # Default configuration file
 

+ 67 - 16
pyinstalive/downloader.py

@@ -5,6 +5,7 @@ import sys
 import threading
 import time
 import shlex
+import json
 
 from xml.dom.minidom import parse, parseString
 
@@ -19,7 +20,7 @@ from .logger import log_seperator, supports_color, log_info_blue, log_info_green
 
 
 
-def main(instagram_api_arg, download_arg, settings_arg):
+def start_single(instagram_api_arg, download_arg, settings_arg):
 	global instagram_api
 	global user_to_download
 	global broadcast
@@ -29,14 +30,64 @@ def main(instagram_api_arg, download_arg, settings_arg):
 	user_to_download = download_arg
 	get_user_info(user_to_download)
 
+def start_multiple(instagram_api_arg, settings_arg, proc_arg):
+	try:
+		log_info_green("Checking following users for any livestreams or replays...")
+		broadcast_f_list = instagram_api_arg.reels_tray()
+		usernames_available = []
+		if broadcast_f_list['broadcasts']:
+			for broadcast_f in broadcast_f_list['broadcasts']:
+				username = broadcast_f['broadcast_owner']['username']
+				if username not in usernames_available:
+					usernames_available.append(username)
+
+		if broadcast_f_list.get('post_live', {}).get('post_live_items', []):
+			for broadcast_r in broadcast_f_list.get('post_live', {}).get('post_live_items', []):
+				for broadcast_f in broadcast_r.get("broadcasts", []):
+					username = broadcast_f['broadcast_owner']['username']
+					if username not in usernames_available:
+						usernames_available.append(username)
+		log_seperator()
+		if usernames_available:
+			log_info_green("The following users have available livestreams or replays:")
+			log_info_green(', '.join(usernames_available))
+			log_seperator()
+			for index, user in enumerate(usernames_available):
+				try:
+					log_info_green("Launching daemon process for '{:s}'...".format(user))
+					start_result = run_command("{:s} -d {:s}".format(proc_arg, user))
+					if start_result:
+						log_info_green("Could not start processs: {:s}".format(str(start_result)))
+					else:
+						log_info_green("Process started successfully.")
+
+					log_seperator()
+					time.sleep(2)
+				except Exception as e:
+					log_error("Could not start processs: {:s}".format(str(e)))
+				except KeyboardInterrupt:
+					log_info_blue('The process launching has been aborted by the user.')
+					log_seperator()				
+					exit(0)
+	except Exception as e:
+		log_error("Could not finish checking following users: {:s}".format(str(e)))
+		exit(1)
+	except KeyboardInterrupt:
+		log_seperator()
+		log_info_blue('The checking process has been aborted by the user.')
+		log_seperator()
+		exit(0)
+	#open("reels.json", "w").write(json.dumps(following_broadcasts))
+
 
 
 def run_command(command):
 	try:
 		FNULL = open(os.devnull, 'w')
 		subprocess.Popen(shlex.split(command), stdout=FNULL, stderr=subprocess.STDOUT)
+		return False
 	except Exception as e:
-		pass
+		return str(e)
 
 
 
@@ -161,9 +212,9 @@ def download_livestream(broadcast):
 	except Exception as e:
 		log_error("Could not download livestream: {:s}".format(str(e)))
 		try:
-		    os.remove(os.path.join(output_dir, 'folder.lock'))
+			os.remove(os.path.join(output_dir, 'folder.lock'))
 		except Exception:
-		    pass
+			pass
 
 
 def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
@@ -192,9 +243,9 @@ def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
 				broadcast_downloader.stitch(live_mp4_file, cleartempfiles=False)
 			log_info_green('Successfully stitched downloaded files into video.')
 			try:
-			    os.remove(os.path.join(live_folder_path, 'folder.lock'))
+				os.remove(os.path.join(live_folder_path, 'folder.lock'))
 			except Exception:
-			    pass
+				pass
 			if settings.clear_temp_files.title() == "True":
 				try:
 					shutil.rmtree(live_folder_path)
@@ -207,25 +258,25 @@ def stitch_video(broadcast_downloader, broadcast, comment_thread_worker):
 			log_error('Likely the download duration was too short and no temp files were saved.')
 			log_seperator()
 			try:
-			    os.remove(os.path.join(live_folder_path, 'folder.lock'))
+				os.remove(os.path.join(live_folder_path, 'folder.lock'))
 			except Exception:
-			    pass
+				pass
 			sys.exit(1)
 		except Exception as e:
 			log_error('Could not stitch downloaded files: {:s}'.format(str(e)))
 			log_seperator()
 			try:
-			    os.remove(os.path.join(live_folder_path, 'folder.lock'))
+				os.remove(os.path.join(live_folder_path, 'folder.lock'))
 			except Exception:
-			    pass
+				pass
 			sys.exit(1)
 	except KeyboardInterrupt:
 			log_info_blue('Aborted stitching process, no video was created.')
 			log_seperator()
 			try:
-			    os.remove(os.path.join(live_folder_path, 'folder.lock'))
+				os.remove(os.path.join(live_folder_path, 'folder.lock'))
 			except Exception:
-			    pass
+				pass
 			sys.exit(0)
 
 
@@ -370,9 +421,9 @@ def download_replays(broadcasts):
 				if (len(replay_saved) == 1):
 					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'))
+						os.remove(os.path.join(output_dir, 'folder.lock'))
 					except Exception:
-					    pass
+						pass
 
 					if (current != len(broadcasts)):
 						log_seperator()
@@ -390,9 +441,9 @@ def download_replays(broadcasts):
 		log_error('Could not save replay: {:s}'.format(str(e)))
 		log_seperator()
 		try:
-		    os.remove(os.path.join(output_dir, 'folder.lock'))
+			os.remove(os.path.join(output_dir, 'folder.lock'))
 		except Exception:
-		    pass
+			pass
 		sys.exit(1)
 	except KeyboardInterrupt:
 		log_seperator()

+ 36 - 5
pyinstalive/initialize.py

@@ -9,7 +9,7 @@ import shutil
 import json
 
 from .auth import login
-from .downloader import main
+from .downloader import start_single, start_multiple
 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
 
@@ -25,6 +25,14 @@ def check_ffmpeg():
 	except OSError as e:
 		return False
 
+def check_pyinstalive():
+	try:
+		FNULL = open(os.devnull, 'w')
+		subprocess.call(["pyinstalive"], stdout=FNULL, stderr=subprocess.STDOUT)
+		return True
+	except OSError as e:
+		return False
+
 
 def check_config_validity(config):
 	try:
@@ -343,6 +351,8 @@ def run():
 	parser.add_argument('-nr', '--noreplays', dest='noreplays', action='store_true', help="When used, do not check for any available replays.")
 	parser.add_argument('-nl', '--nolives', dest='nolives', action='store_true', help="When used, do not check for any available livestreams.")
 	parser.add_argument('-cl', '--clean', dest='clean', action='store_true', help="PyInstaLive will clean the current download folder of all leftover files.")
+	parser.add_argument('-df', '--downloadfollowing', dest='downloadfollowing', action='store_true', help="PyInstaLive will check for available livestreams and replays from users the account used to login follows.")
+
 
 	# Workaround to 'disable' argument abbreviations
 	parser.add_argument('--usernamx', help=argparse.SUPPRESS, metavar='IGNORE')
@@ -352,8 +362,12 @@ def run():
 	parser.add_argument('--confix', help=argparse.SUPPRESS, metavar='IGNORE')
 	parser.add_argument('--noreplayx', help=argparse.SUPPRESS, metavar='IGNORE') 
 	parser.add_argument('--cleax', help=argparse.SUPPRESS, metavar='IGNORE')
+	parser.add_argument('--downloadfollowinx', help=argparse.SUPPRESS, metavar='IGNORE')
+
 	parser.add_argument('-cx', help=argparse.SUPPRESS, metavar='IGNORE')
 	parser.add_argument('-nx', help=argparse.SUPPRESS, metavar='IGNORE')
+	parser.add_argument('-dx', help=argparse.SUPPRESS, metavar='IGNORE')
+
 
 
 	args, unknown_args = parser.parse_known_args()
@@ -397,6 +411,7 @@ def run():
 	args.username and not
 	args.password and not
 	args.download and not
+	args.downloadfollowing and not
 	args.info and not
 	args.config and not
 	args.noreplays and not
@@ -443,8 +458,13 @@ def run():
 				log_seperator()
 				sys.exit(1)
 
-			if not args.download:
-				log_warn("Missing --download argument. Please specify an Instagram username.")
+			if not args.download and not args.downloadfollowing:
+				log_warn("Neither argument -d or -df was passed. Please use one of the two and try again.")
+				log_seperator()
+				sys.exit(1)
+
+			if args.download and args.downloadfollowing:
+				log_warn("You can't pass both the -d and -df arguments. Please use one of the two and try again.")
 				log_seperator()
 				sys.exit(1)
 
@@ -466,8 +486,19 @@ def run():
 					sys.exit(1)
 				else:
 					api = login(settings.username, settings.password, settings.show_cookie_expiry, False)
-
-			main(api, args.download, settings)
+			if args.download and not args.downloadfollowing:
+				start_single(api, args.download, settings)
+			if not args.download and args.downloadfollowing:
+				if check_pyinstalive():
+					start_multiple(api, settings, "pyinstalive")
+				else:
+					log_warn("You probably ran PyInstaLive as a script module with the -m argument.")
+					log_warn("PyInstaLive should be properly installed when using the -df argument.")
+					log_seperator()
+					if python_version[0] == 3:
+						start_multiple(api, settings, "python3 -m pyinstalive")
+					else:
+						start_multiple(api, settings, "python -m pyinstalive")
 		except Exception as e:
 			log_error("Could not finish pre-download checks:  {:s}".format(str(e)))
 			log_seperator()