This repository has been archived on 2022-12-28. You can view files and clone it, but cannot push or open issues or pull requests.
apiOld/Server.py

173 lines
8.6 KiB
Python
Raw Normal View History

2020-12-26 17:11:26 +00:00
import socket,threading,os,time,math,json,sys,urllib,requests
sys.path.append('libraries\\')
from Astronomy import *
#-------------------------------------#
#Define Area
class APICore(object):
HTTPHead={
'200':'HTTP/1.1 200 OK\r\nServer: SparkE/Alpha1.0\r\nContent-Type: application/json; charset=utf-8\r\n\r\n',
'400':'HTTP/1.1 400 BAD REQUEST\r\nServer: SparkE/Alpha1.0\r\nContent-Type: application/json; charset=utf-8\r\n\r\n',
'404':'HTTP/1.1 404 NOT FOUND\r\nServer: SparkE/Alpha1.0\r\nContent-Type: application/json; charset=utf-8\r\n\r\n'
}
def __init__(self):
self.__Log=[]
def Log(self,IP,Port,Type,Text):
Time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
self.__Log.append((Time,IP,Port,Type,Text))
print("["+Type+"]["+Time+"]["+IP+"]["+str(Port)+"]"+str(Text))
def IsJson(self,text):
try:
json.loads(text)
return True
except:
return False
def Error400(self,sock,addr):
sock.send(self.HTTPHead['400'].encode("utf-8"))
Result=json.dumps({"info":"bad request","code":400})
self.Log(addr[0],addr[1],"SEND",Result)
sock.send(str(Result).encode("utf-8"))
def SunAzEl(self,sock,addr):
Result=json.dumps(Astronomy().calcSunAzEl())
self.Log(addr[0],addr[1],"SEND",Result)
sock.send(str(Result).encode("utf-8"))
#-------------------------------------#
API=APICore()
#-------------------------------------#
RequestRecord={}
server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server.bind(("0.0.0.0",8000))
server.listen()
def socket(sock,addr):
while True:
try:
data = sock.recv(1024)
#print(data.decode("utf-8"))
if("HTTP/" in data.decode("utf-8")):
2020-12-27 06:17:58 +00:00
API.Log(addr[0],addr[1],"RECV","Received a HTTP request.")
2020-12-26 17:11:26 +00:00
#HTTP Request.
2020-12-27 06:17:58 +00:00
try:
Heada=data.decode("utf-8").split("\r\n")[0].split(" ")[1].split("/")
del Heada[0]
except:
API.Error400(sock,addr)
break
try:
Headb=data.decode("utf-8").split("\r\n\r\n")[1]
except:
Headb=""
HTTPRequestHead=(Heada,Headb)
for i in range(0,len(HTTPRequestHead[0])):
HTTPRequestHead[0][i]=urllib.parse.unquote(HTTPRequestHead[0][i])
2020-12-26 17:11:26 +00:00
API.Log(addr[0],addr[1],"RECV",HTTPRequestHead)
if(" / " in data.decode("utf-8")):
2020-12-27 06:17:58 +00:00
#Help Command
2020-12-26 17:11:26 +00:00
sock.send(API.HTTPHead['200'].encode("utf-8"))
Result=json.dumps({"wikis":"https://gitee.com/ghink/api/wikis"})
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(str(Result).encode("utf8"))
break
elif(" /SunAzEl" in data.decode("utf-8")):
if("GET " in data.decode("utf-8")):
2020-12-27 06:17:58 +00:00
#GET Request
2020-12-26 17:11:26 +00:00
try:
2020-12-27 06:17:58 +00:00
#Exist Parameter
HTTPRequestHead[0][1]
if(API.IsJson(HTTPRequestHead[0][1])):
#Is Json,Return Result
try:
Para=json.loads(HTTPRequestHead[0][1])
Result=json.dumps(Astronomy().calcSunAzEl(Para['Stamp'],Para['Lon'],Para['Lat'],Para['TimeZone'],Para['ZeroAzimuth']))
sock.send(API.HTTPHead['200'].encode("utf-8"))
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(str(Result).encode("utf-8"))
except:
API.Error400(sock,addr)
2020-12-26 17:11:26 +00:00
else:
2020-12-27 06:17:58 +00:00
#Not Json,Return Bad Request
2020-12-26 17:11:26 +00:00
API.Error400(sock,addr)
except:
2020-12-27 06:17:58 +00:00
#No Parameter
sock.send(API.HTTPHead['200'].encode("utf-8"))
2020-12-26 17:11:26 +00:00
API.SunAzEl(sock,addr)
elif("POST " in data.decode("utf-8")):
2020-12-27 06:17:58 +00:00
#POST Request
2020-12-26 17:11:26 +00:00
try:
2020-12-27 06:17:58 +00:00
#Exist GET Parameter,Return Bad Request
HTTPRequestHead[0][1]
2020-12-26 17:11:26 +00:00
API.Error400(sock,addr)
except:
2020-12-27 06:17:58 +00:00
#No GET Parameter,Continue
if(API.IsJson(HTTPRequestHead[1])):
#If POST Parameter is Json
try:
Para=json.loads(HTTPRequestHead[1])
Result=json.dumps(Astronomy().calcSunAzEl(Para['Stamp'],Para['Lon'],Para['Lat'],Para['TimeZone'],Para['ZeroAzimuth']))
sock.send(API.HTTPHead['200'].encode("utf-8"))
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(str(Result).encode("utf-8"))
except:
API.Error400(sock,addr)
elif(HTTPRequestHead[1]==""):
#If No POST Parameter
sock.send(API.HTTPHead['200'].encode("utf-8"))
API.SunAzEl(sock,addr)
else:
#Wrong POST Parameter,Return Bad Request
API.Error400(sock,addr)
2020-12-26 17:11:26 +00:00
break
else:
2020-12-27 06:17:58 +00:00
#No Such Command
2020-12-26 17:11:26 +00:00
sock.send(API.HTTPHead['404'].encode("utf8"))
Result=json.dumps({"info":"not found","code":404})
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(Result.encode("utf-8"))
break
else:
2020-12-27 06:17:58 +00:00
API.Log(addr[0],addr[1],"RECV","Received a TCP request.")
2020-12-26 17:11:26 +00:00
#TCP Request.
if(data.decode("utf-8")=="Help" or data.decode("utf-8")=="HELP" or data.decode("utf-8")=="help" or data.decode("utf-8")=="WIKI" or data.decode("utf-8")=="wiki" or data.decode("utf-8")=="wikis" or data.decode("utf-8")=="WIKIS" or data.decode("utf-8")=="?"):
2020-12-27 06:17:58 +00:00
#Help Command
2020-12-26 17:11:26 +00:00
Result=json.dumps({"wikis":"https://gitee.com/ghink/api/wikis"})
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(str(Result).encode("utf8"))
2020-12-27 06:17:58 +00:00
elif("SunAzEl" in data.decode("utf-8")):
if(API.IsJson(data.decode("utf-8"))):
#Is Json
try:
#Check whether is right json
Para=json.loads(data.decode("utf-8"))['Parameter']
Result=json.dumps(Astronomy().calcSunAzEl(Para['Stamp'],Para['Lon'],Para['Lat'],Para['TimeZone'],Para['ZeroAzimuth']))
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(str(Result).encode("utf-8"))
except:
#Not right json
Result=json.dumps({"info":"bad request","code":400})
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(Result.encode("utf-8"))
elif(data.decode("utf-8")=="SunAzEl"):
#Not Json
API.SunAzEl(sock,addr)
else:
#Wrong Command
Result=json.dumps({"info":"bad request","code":400})
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(Result.encode("utf-8"))
2020-12-26 17:11:26 +00:00
else:
2020-12-27 06:17:58 +00:00
#No Such Command
2020-12-26 17:11:26 +00:00
Result=json.dumps({"info":"not found","code":404})
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(Result.encode("utf-8"))
except (ConnectionResetError,ConnectionAbortedError):
API.Log(addr[0],addr[1],"STATUS","Lost connection.")
break
except UnicodeDecodeError:
API.Log(addr[0],addr[1],"STATUS","Wrong code mode,must be utf-8.")
API.Log(addr[0],addr[1],"STATUS","Lost connection.")
break
def main():
sock,addr=server.accept()
client_thread=threading.Thread(target=socket,args=(sock,addr))
client_thread.start()
while True:
main()