You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
3.2 KiB
90 lines
3.2 KiB
from fastapi import FastAPI, Response
|
|
from fastapi.responses import StreamingResponse
|
|
import uvicorn
|
|
import traceback
|
|
|
|
from config_parser import Config as ConfigParser
|
|
from nvr_core import NVR
|
|
from nvr_types import File
|
|
|
|
class Server:
|
|
app: FastAPI = FastAPI()
|
|
config: ConfigParser = ConfigParser()
|
|
|
|
def __init__(self):
|
|
self.setup_events()
|
|
self.setup_routers()
|
|
|
|
def setup_events(self):
|
|
@self.app.on_event('startup')
|
|
def on_startup():
|
|
print("i am alive")
|
|
|
|
def setup_routers(self):
|
|
@self.app.get("/api/recorders", status_code=200)
|
|
async def getRecorders(response: Response):
|
|
try:
|
|
return {"ok":True, "data":self.config.getRecorders()}
|
|
except Exception as e:
|
|
traceback.print_exc()
|
|
response.status_code = 400
|
|
return {"ok":False, "error":e}
|
|
|
|
#@self.app.get("/{recorder_index}")
|
|
#async def getRecorder(recorder_index:int):
|
|
# return self.config.getRecorder(recorder_index).nvr
|
|
|
|
@self.app.get("/api/recorders/{recorder_index}/channels", status_code=200)
|
|
async def getRecorder(response: Response, recorder_index:int):
|
|
try:
|
|
nvr:NVR = self.config.getRecorder(recorder_index).nvr
|
|
nvr.login()
|
|
return {"ok":True, "data":nvr.channels}
|
|
except Exception as e:
|
|
traceback.print_exc()
|
|
response.status_code = 400
|
|
return {"ok":False, "error":e}
|
|
finally:
|
|
nvr.logout()
|
|
|
|
@self.app.get("/api/recorders/{recorder_index}/{channel}/{stream}")
|
|
async def getHistory(response: Response, recorder_index:int, channel: int, stream: int, start_date:str = None, end_date:str = None):
|
|
try:
|
|
nvr:NVR = self.config.getRecorder(recorder_index).nvr
|
|
nvr.login()
|
|
return {"ok":True, "data":list(nvr.files(channel, start_date, end_date, stype=stream, json=False))}
|
|
except Exception as e:
|
|
traceback.print_exc()
|
|
response.status_code = 400
|
|
return {"ok":False, "error":e}
|
|
finally:
|
|
nvr.logout()
|
|
|
|
@self.app.get("/api/recorders/{recorder_index}/file")
|
|
async def getFile(response: Response, recorder_index:int, b64:str):
|
|
try:
|
|
if len(b64) == 0:
|
|
response.status_code = 404
|
|
return ""
|
|
nvr:NVR = self.config.getRecorder(recorder_index).nvr
|
|
nvr.login()
|
|
|
|
file: File = File.from_b64(b64 + "==")
|
|
print("open")
|
|
return StreamingResponse(file.generate_bytes(nvr.client))
|
|
except Exception as e:
|
|
traceback.print_exc()
|
|
response.status_code = 400
|
|
return {"ok":False, "error":e}
|
|
finally:
|
|
nvr.logout()
|
|
|
|
def run(self):
|
|
uvicorn.run(
|
|
self.app,
|
|
host=self.config.listen_address,
|
|
port=self.config.listen_port,
|
|
)
|
|
|
|
if __name__ == "__main__":
|
|
Server().run()
|