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

110 lines
5.1 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):
sock.send(self.HTTPHead['200'].encode("utf-8"))
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)
API.Log(addr[0],addr[1],"RECV","Received a request.")
#print(data.decode("utf-8"))
if("HTTP/" in data.decode("utf-8")):
#HTTP Request.
HTTPRequestHead=data.decode("utf-8").split("\r\n")[0].split(" ")[1].split("/")
del HTTPRequestHead[0]
for i in range(0,len(HTTPRequestHead)):
HTTPRequestHead[i]=urllib.parse.unquote(HTTPRequestHead[i])
API.Log(addr[0],addr[1],"RECV",HTTPRequestHead)
if(" / " in data.decode("utf-8")):
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")):
try:
HTTPRequestHead[1]
if(API.IsJson(HTTPRequestHead[1])):
API.SunAzEl(sock,addr)
else:
API.Error400(sock,addr)
except:
API.SunAzEl(sock,addr)
elif("POST " in data.decode("utf-8")):
try:
HTTPRequestHead[1]
API.Error400(sock,addr)
except:
API.SunAzEl(sock,addr)
break
else:
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:
#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")=="?"):
Result=json.dumps({"wikis":"https://gitee.com/ghink/api/wikis"})
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(str(Result).encode("utf8"))
elif(data.decode("utf-8")=="SunAzEl"):
Result=json.dumps(Astronomy().calcSunAzEl())
API.Log(addr[0],addr[1],"SEND",Result)
sock.send(str(Result).encode("utf-8"))
else:
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()