David 10 лет назад
Родитель
Сommit
4bb1719f0e
1 измененных файлов с 119 добавлено и 0 удалено
  1. 119 0
      wsread.py

+ 119 - 0
wsread.py

@@ -0,0 +1,119 @@
+#!/usr/bin/env python3
+import json
+import os
+import signal
+import socket
+import subprocess
+import sys
+import websocket
+
+ws = websocket.WebSocket()
+p_list = {}
+
+ptable = {}
+ptable["audio"] = [ "/home/nginx/scripts-snowmix/working-udp-audio.sh"]
+ptable["video"] = [ "/home/nginx/scripts-snowmix/working-udp-video.sh", "1", "0" ]
+ptable["rtmp"] =  [ "/home/nginx/scripts-snowmix/stream.sh"]
+
+log_list = {}
+
+def conn(target):
+	global ws
+	if ws is None:
+		ws = websocket.WebSocket()
+	try:
+		ws.connect(target)
+	except Exception as e:
+		time.sleep(2)
+		conn(target) #keep trying you basterd
+
+
+def close():
+	if ws is None:
+		return
+	ws.close()
+
+def sighandler(signal,frame):
+	print("Exiting!")
+	close()
+	print("Bye!")
+	sys.exit(0)
+
+def stop(key):
+	if key not in p_list:
+		print("key %s doesn't exist! not killing!" % (key))
+		return
+	os.killpg(os.getpgid(p_list[key].pid), signal.SIGTERM)
+
+	try:
+		log_list[key].close()
+	except Exception as e:
+		print("ex file: %s" % e)
+
+	if key in log_list:
+		del log_list[key]
+
+	del p_list[key]
+		
+def launch(key,options=None):
+	if key in p_list:
+		print("key %s exist! not running!" % (key))
+		return
+	
+	tolaunch = ptable[j["key"]]
+	if options is not None:
+		tolaunch = tolaunch + options
+
+	log_list[key]=open("/tmp/%s" % key, "w")
+	proc=subprocess.Popen(tolaunch, preexec_fn=os.setsid, stdout=log_list[key])
+	#Le doy su propio grupo al subproceso
+	p_list[key]=proc
+	return proc.pid
+
+def sendmsg(msg):
+	s = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
+	ret = None
+	try:
+		s.connect(('localhost',9999))
+		tosend = msg + "\r\n"
+		s.sendall(tosend.encode("ascii"))
+		ret=s.recv(4096)
+		s.close()
+	except Exception as e:
+		print(e)
+		return None
+	print(ret)
+	return ret
+
+ip="ws://192.168.1.208:9001"
+conn(ip)
+signal.signal(signal.SIGINT, sighandler)
+signal.signal(signal.SIGCHLD, signal.SIG_IGN) #To kill zombies
+
+while True:
+	try:
+		data = ws.recv()
+	except Exception as e:
+		print(e)
+		conn(ip)
+		continue
+
+	try:
+		j = json.loads(data)
+	except Exception as e:
+		print(e)
+		print("Invalid json?")
+		continue
+	
+	if ("type" not in j or "command" not in j or
+		"key" not in j or j["type"] != "snowmix"):
+		continue
+
+	if j["command"] == "launch":
+		launch(j["key"]) 
+
+	if j["command"] == "kill":
+		stop(j["key"])
+	
+	if j["command"] == "netcat":
+		sendmsg(j["key"])