2024-03-02 23:10:37 +01:00
|
|
|
"""Main api runner."""
|
|
|
|
|
|
|
|
import copy
|
|
|
|
import json
|
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
import traceback
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
from functools import reduce
|
2024-09-26 00:22:11 +02:00
|
|
|
from typing import Any, Optional
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
import requests
|
2024-09-26 00:22:11 +02:00
|
|
|
from fastapi import APIRouter, Body, Path, Request, Response
|
2024-09-24 15:05:30 +02:00
|
|
|
from fastapi.encoders import jsonable_encoder
|
|
|
|
from fastapi.params import Depends
|
2024-09-25 20:35:30 +02:00
|
|
|
from fastapi.responses import JSONResponse, PlainTextResponse
|
2024-03-02 23:10:37 +01:00
|
|
|
from markupsafe import escape
|
|
|
|
from peewee import operator
|
2024-09-24 15:05:30 +02:00
|
|
|
|
|
|
|
from frigate.api.defs.app_body import AppConfigSetBody
|
|
|
|
from frigate.api.defs.app_query_parameters import AppTimelineHourlyQueryParameters
|
|
|
|
from frigate.api.defs.tags import Tags
|
2024-06-15 01:02:13 +02:00
|
|
|
from frigate.config import FrigateConfig
|
2024-03-02 23:10:37 +01:00
|
|
|
from frigate.const import CONFIG_DIR
|
2024-03-05 20:55:44 +01:00
|
|
|
from frigate.models import Event, Timeline
|
2024-03-02 23:10:37 +01:00
|
|
|
from frigate.util.builtin import (
|
|
|
|
clean_camera_user_pass,
|
|
|
|
get_tz_modifiers,
|
|
|
|
update_yaml_from_url,
|
|
|
|
)
|
2024-10-08 04:15:31 +02:00
|
|
|
from frigate.util.services import (
|
|
|
|
ffprobe_stream,
|
|
|
|
get_nvidia_driver_info,
|
|
|
|
restart_frigate,
|
|
|
|
vainfo_hwaccel,
|
|
|
|
)
|
2024-03-02 23:10:37 +01:00
|
|
|
from frigate.version import VERSION
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
router = APIRouter(tags=[Tags.app])
|
|
|
|
|
|
|
|
|
2024-09-25 20:35:30 +02:00
|
|
|
@router.get("/", response_class=PlainTextResponse)
|
2024-03-02 23:10:37 +01:00
|
|
|
def is_healthy():
|
|
|
|
return "Frigate is running. Alive and healthy!"
|
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/config/schema.json")
|
|
|
|
def config_schema(request: Request):
|
|
|
|
return Response(
|
|
|
|
content=request.app.frigate_config.schema_json(), media_type="application/json"
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/go2rtc/streams")
|
2024-03-02 23:10:37 +01:00
|
|
|
def go2rtc_streams():
|
|
|
|
r = requests.get("http://127.0.0.1:1984/api/streams")
|
|
|
|
if not r.ok:
|
|
|
|
logger.error("Failed to fetch streams from go2rtc")
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=({"success": False, "message": "Error fetching stream data"}),
|
|
|
|
status_code=500,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
stream_data = r.json()
|
|
|
|
for data in stream_data.values():
|
|
|
|
for producer in data.get("producers", []):
|
|
|
|
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(content=stream_data)
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/go2rtc/streams/{camera_name}")
|
2024-05-17 15:30:22 +02:00
|
|
|
def go2rtc_camera_stream(camera_name: str):
|
|
|
|
r = requests.get(
|
|
|
|
f"http://127.0.0.1:1984/api/streams?src={camera_name}&video=all&audio=allµphone"
|
|
|
|
)
|
|
|
|
if not r.ok:
|
|
|
|
logger.error("Failed to fetch streams from go2rtc")
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=({"success": False, "message": "Error fetching stream data"}),
|
|
|
|
status_code=500,
|
2024-05-17 15:30:22 +02:00
|
|
|
)
|
|
|
|
stream_data = r.json()
|
|
|
|
for producer in stream_data.get("producers", []):
|
|
|
|
producer["url"] = clean_camera_user_pass(producer.get("url", ""))
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(content=stream_data)
|
2024-05-17 15:30:22 +02:00
|
|
|
|
|
|
|
|
2024-09-25 20:35:30 +02:00
|
|
|
@router.get("/version", response_class=PlainTextResponse)
|
2024-03-02 23:10:37 +01:00
|
|
|
def version():
|
2024-09-25 20:35:30 +02:00
|
|
|
return VERSION
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/stats")
|
|
|
|
def stats(request: Request):
|
|
|
|
return JSONResponse(content=request.app.stats_emitter.get_latest_stats())
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/stats/history")
|
|
|
|
def stats_history(request: Request, keys: str = None):
|
2024-04-04 05:22:11 +02:00
|
|
|
if keys:
|
|
|
|
keys = keys.split(",")
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(content=request.app.stats_emitter.get_stats_history(keys))
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/config")
|
|
|
|
def config(request: Request):
|
|
|
|
config_obj: FrigateConfig = request.app.frigate_config
|
2024-04-10 00:51:38 +02:00
|
|
|
config: dict[str, dict[str, any]] = config_obj.model_dump(
|
2024-04-16 22:55:24 +02:00
|
|
|
mode="json", warnings="none", exclude_none=True
|
2024-04-10 00:51:38 +02:00
|
|
|
)
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
# remove the mqtt password
|
|
|
|
config["mqtt"].pop("password", None)
|
|
|
|
|
2024-06-15 01:02:13 +02:00
|
|
|
# remove the proxy secret
|
|
|
|
config["proxy"].pop("auth_secret", None)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
for camera_name, camera in request.app.frigate_config.cameras.items():
|
2024-03-02 23:10:37 +01:00
|
|
|
camera_dict = config["cameras"][camera_name]
|
|
|
|
|
|
|
|
# clean paths
|
|
|
|
for input in camera_dict.get("ffmpeg", {}).get("inputs", []):
|
|
|
|
input["path"] = clean_camera_user_pass(input["path"])
|
|
|
|
|
|
|
|
# add clean ffmpeg_cmds
|
|
|
|
camera_dict["ffmpeg_cmds"] = copy.deepcopy(camera.ffmpeg_cmds)
|
|
|
|
for cmd in camera_dict["ffmpeg_cmds"]:
|
|
|
|
cmd["cmd"] = clean_camera_user_pass(" ".join(cmd["cmd"]))
|
|
|
|
|
2024-04-10 00:51:38 +02:00
|
|
|
# ensure that zones are relative
|
|
|
|
for zone_name, zone in config_obj.cameras[camera_name].zones.items():
|
|
|
|
camera_dict["zones"][zone_name]["color"] = zone.color
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
config["plus"] = {"enabled": request.app.frigate_config.plus_api.is_active()}
|
2024-05-01 16:07:56 +02:00
|
|
|
config["model"]["colormap"] = config_obj.model.colormap
|
2024-03-02 23:10:37 +01:00
|
|
|
|
2024-04-10 00:51:38 +02:00
|
|
|
for detector_config in config["detectors"].values():
|
2024-03-02 23:10:37 +01:00
|
|
|
detector_config["model"]["labelmap"] = (
|
2024-09-24 15:05:30 +02:00
|
|
|
request.app.frigate_config.model.merged_labelmap
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(content=config)
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/config/raw")
|
2024-03-02 23:10:37 +01:00
|
|
|
def config_raw():
|
|
|
|
config_file = os.environ.get("CONFIG_FILE", "/config/config.yml")
|
|
|
|
|
|
|
|
# Check if we can use .yaml instead of .yml
|
|
|
|
config_file_yaml = config_file.replace(".yml", ".yaml")
|
|
|
|
|
|
|
|
if os.path.isfile(config_file_yaml):
|
|
|
|
config_file = config_file_yaml
|
|
|
|
|
|
|
|
if not os.path.isfile(config_file):
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=({"success": False, "message": "Could not find file"}),
|
|
|
|
status_code=404,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
with open(config_file, "r") as f:
|
|
|
|
raw_config = f.read()
|
|
|
|
f.close()
|
|
|
|
|
2024-09-24 17:54:03 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=raw_config, media_type="text/plain", status_code=200
|
|
|
|
)
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.post("/config/save")
|
2024-09-26 18:19:37 +02:00
|
|
|
def config_save(save_option: str, body: Any = Body(media_type="text/plain")):
|
|
|
|
new_config = body.decode()
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
if not new_config:
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{"success": False, "message": "Config with body param is required"}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=400,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
# Validate the config schema
|
|
|
|
try:
|
2024-09-22 17:56:57 +02:00
|
|
|
FrigateConfig.parse_yaml(new_config)
|
2024-03-02 23:10:37 +01:00
|
|
|
except Exception:
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{
|
|
|
|
"success": False,
|
|
|
|
"message": f"\nConfig Error:\n\n{escape(str(traceback.format_exc()))}",
|
|
|
|
}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=400,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
# Save the config to file
|
|
|
|
try:
|
|
|
|
config_file = os.environ.get("CONFIG_FILE", "/config/config.yml")
|
|
|
|
|
|
|
|
# Check if we can use .yaml instead of .yml
|
|
|
|
config_file_yaml = config_file.replace(".yml", ".yaml")
|
|
|
|
|
|
|
|
if os.path.isfile(config_file_yaml):
|
|
|
|
config_file = config_file_yaml
|
|
|
|
|
|
|
|
with open(config_file, "w") as f:
|
|
|
|
f.write(new_config)
|
|
|
|
f.close()
|
|
|
|
except Exception:
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{
|
|
|
|
"success": False,
|
|
|
|
"message": "Could not write config file, be sure that Frigate has write permission on the config file.",
|
|
|
|
}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=400,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
if save_option == "restart":
|
|
|
|
try:
|
|
|
|
restart_frigate()
|
|
|
|
except Exception as e:
|
|
|
|
logging.error(f"Error restarting Frigate: {e}")
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{
|
|
|
|
"success": True,
|
|
|
|
"message": "Config successfully saved, unable to restart Frigate",
|
|
|
|
}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=200,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{
|
|
|
|
"success": True,
|
|
|
|
"message": "Config successfully saved, restarting (this can take up to one minute)...",
|
|
|
|
}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=200,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
else:
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=({"success": True, "message": "Config successfully saved."}),
|
|
|
|
status_code=200,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.put("/config/set")
|
|
|
|
def config_set(request: Request, body: AppConfigSetBody):
|
2024-03-02 23:10:37 +01:00
|
|
|
config_file = os.environ.get("CONFIG_FILE", f"{CONFIG_DIR}/config.yml")
|
|
|
|
|
|
|
|
# Check if we can use .yaml instead of .yml
|
|
|
|
config_file_yaml = config_file.replace(".yml", ".yaml")
|
|
|
|
|
|
|
|
if os.path.isfile(config_file_yaml):
|
|
|
|
config_file = config_file_yaml
|
|
|
|
|
|
|
|
with open(config_file, "r") as f:
|
|
|
|
old_raw_config = f.read()
|
|
|
|
f.close()
|
|
|
|
|
|
|
|
try:
|
2024-09-24 17:54:03 +02:00
|
|
|
update_yaml_from_url(config_file, str(request.url))
|
2024-03-02 23:10:37 +01:00
|
|
|
with open(config_file, "r") as f:
|
|
|
|
new_raw_config = f.read()
|
|
|
|
f.close()
|
|
|
|
# Validate the config schema
|
|
|
|
try:
|
2024-09-24 17:54:03 +02:00
|
|
|
config = FrigateConfig.parse(new_raw_config)
|
2024-03-02 23:10:37 +01:00
|
|
|
except Exception:
|
|
|
|
with open(config_file, "w") as f:
|
|
|
|
f.write(old_raw_config)
|
|
|
|
f.close()
|
|
|
|
logger.error(f"\nConfig Error:\n\n{str(traceback.format_exc())}")
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{
|
|
|
|
"success": False,
|
|
|
|
"message": "Error parsing config. Check logs for error message.",
|
|
|
|
}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=400,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
except Exception as e:
|
|
|
|
logging.error(f"Error updating config: {e}")
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=({"success": False, "message": "Error updating config"}),
|
|
|
|
status_code=500,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
if body.requires_restart == 0:
|
2024-09-24 17:54:03 +02:00
|
|
|
request.app.frigate_config = config
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{
|
|
|
|
"success": True,
|
|
|
|
"message": "Config successfully updated, restart to apply",
|
|
|
|
}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=200,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/ffprobe")
|
|
|
|
def ffprobe(request: Request, paths: str = ""):
|
|
|
|
path_param = paths
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
if not path_param:
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=({"success": False, "message": "Path needs to be provided."}),
|
|
|
|
status_code=404,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
if path_param.startswith("camera"):
|
|
|
|
camera = path_param[7:]
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
if camera not in request.app.frigate_config.cameras.keys():
|
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{"success": False, "message": f"{camera} is not a valid camera."}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=404,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
if not request.app.frigate_config.cameras[camera].enabled:
|
|
|
|
return JSONResponse(
|
|
|
|
content=({"success": False, "message": f"{camera} is not enabled."}),
|
|
|
|
status_code=404,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
paths = map(
|
|
|
|
lambda input: input.path,
|
2024-09-24 15:05:30 +02:00
|
|
|
request.app.frigate_config.cameras[camera].ffmpeg.inputs,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
elif "," in clean_camera_user_pass(path_param):
|
|
|
|
paths = path_param.split(",")
|
|
|
|
else:
|
|
|
|
paths = [path_param]
|
|
|
|
|
|
|
|
# user has multiple streams
|
|
|
|
output = []
|
|
|
|
|
|
|
|
for path in paths:
|
2024-09-24 15:05:30 +02:00
|
|
|
ffprobe = ffprobe_stream(request.app.frigate_config.ffmpeg, path.strip())
|
2024-03-02 23:10:37 +01:00
|
|
|
output.append(
|
|
|
|
{
|
|
|
|
"return_code": ffprobe.returncode,
|
|
|
|
"stderr": (
|
|
|
|
ffprobe.stderr.decode("unicode_escape").strip()
|
|
|
|
if ffprobe.returncode != 0
|
|
|
|
else ""
|
|
|
|
),
|
|
|
|
"stdout": (
|
|
|
|
json.loads(ffprobe.stdout.decode("unicode_escape").strip())
|
|
|
|
if ffprobe.returncode == 0
|
|
|
|
else ""
|
|
|
|
),
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(content=output)
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/vainfo")
|
2024-03-02 23:10:37 +01:00
|
|
|
def vainfo():
|
|
|
|
vainfo = vainfo_hwaccel()
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content={
|
2024-03-02 23:10:37 +01:00
|
|
|
"return_code": vainfo.returncode,
|
|
|
|
"stderr": (
|
|
|
|
vainfo.stderr.decode("unicode_escape").strip()
|
|
|
|
if vainfo.returncode != 0
|
|
|
|
else ""
|
|
|
|
),
|
|
|
|
"stdout": (
|
|
|
|
vainfo.stdout.decode("unicode_escape").strip()
|
|
|
|
if vainfo.returncode == 0
|
|
|
|
else ""
|
|
|
|
),
|
|
|
|
}
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-10-08 04:15:31 +02:00
|
|
|
@router.get("/nvinfo")
|
|
|
|
def nvinfo():
|
|
|
|
return JSONResponse(content=get_nvidia_driver_info())
|
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/logs/{service}", tags=[Tags.logs])
|
|
|
|
def logs(
|
2024-10-07 22:30:45 +02:00
|
|
|
service: str = Path(enum=["frigate", "nginx", "go2rtc"]),
|
2024-09-24 15:05:30 +02:00
|
|
|
download: Optional[str] = None,
|
|
|
|
start: Optional[int] = 0,
|
|
|
|
end: Optional[int] = None,
|
|
|
|
):
|
2024-10-07 22:30:45 +02:00
|
|
|
"""Get logs for the requested service (frigate/nginx/go2rtc)"""
|
2024-09-24 15:05:30 +02:00
|
|
|
|
2024-08-19 16:53:33 +02:00
|
|
|
def download_logs(service_location: str):
|
|
|
|
try:
|
|
|
|
file = open(service_location, "r")
|
|
|
|
contents = file.read()
|
|
|
|
file.close()
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(jsonable_encoder(contents))
|
2024-08-19 16:53:33 +02:00
|
|
|
except FileNotFoundError as e:
|
|
|
|
logger.error(e)
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content={"success": False, "message": "Could not find log file"},
|
|
|
|
status_code=500,
|
2024-08-19 16:53:33 +02:00
|
|
|
)
|
|
|
|
|
2024-03-02 23:10:37 +01:00
|
|
|
log_locations = {
|
|
|
|
"frigate": "/dev/shm/logs/frigate/current",
|
|
|
|
"go2rtc": "/dev/shm/logs/go2rtc/current",
|
|
|
|
"nginx": "/dev/shm/logs/nginx/current",
|
|
|
|
}
|
|
|
|
service_location = log_locations.get(service)
|
|
|
|
|
|
|
|
if not service_location:
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content={"success": False, "message": "Not a valid service"},
|
|
|
|
status_code=404,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
if download:
|
2024-08-19 16:53:33 +02:00
|
|
|
return download_logs(service_location)
|
|
|
|
|
2024-03-02 23:10:37 +01:00
|
|
|
try:
|
|
|
|
file = open(service_location, "r")
|
|
|
|
contents = file.read()
|
|
|
|
file.close()
|
2024-04-03 18:55:13 +02:00
|
|
|
|
|
|
|
# use the start timestamp to group logs together``
|
|
|
|
logLines = []
|
|
|
|
keyLength = 0
|
|
|
|
dateEnd = 0
|
|
|
|
currentKey = ""
|
|
|
|
currentLine = ""
|
|
|
|
|
|
|
|
for rawLine in contents.splitlines():
|
|
|
|
cleanLine = rawLine.strip()
|
|
|
|
|
2024-06-18 15:07:28 +02:00
|
|
|
if len(cleanLine) < 10:
|
2024-04-03 18:55:13 +02:00
|
|
|
continue
|
|
|
|
|
2024-06-18 15:07:28 +02:00
|
|
|
# handle cases where S6 does not include date in log line
|
|
|
|
if " " not in cleanLine:
|
|
|
|
cleanLine = f"{datetime.now()} {cleanLine}"
|
|
|
|
|
2024-04-03 18:55:13 +02:00
|
|
|
if dateEnd == 0:
|
|
|
|
dateEnd = cleanLine.index(" ")
|
|
|
|
keyLength = dateEnd - (6 if service_location == "frigate" else 0)
|
|
|
|
|
|
|
|
newKey = cleanLine[0:keyLength]
|
|
|
|
|
|
|
|
if newKey == currentKey:
|
|
|
|
currentLine += f"\n{cleanLine[dateEnd:].strip()}"
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
if len(currentLine) > 0:
|
|
|
|
logLines.append(currentLine)
|
|
|
|
|
|
|
|
currentKey = newKey
|
|
|
|
currentLine = cleanLine
|
|
|
|
|
|
|
|
logLines.append(currentLine)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content={"totalLines": len(logLines), "lines": logLines[start:end]},
|
|
|
|
status_code=200,
|
2024-04-03 18:55:13 +02:00
|
|
|
)
|
2024-03-02 23:10:37 +01:00
|
|
|
except FileNotFoundError as e:
|
|
|
|
logger.error(e)
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content={"success": False, "message": "Could not find log file"},
|
|
|
|
status_code=500,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.post("/restart")
|
2024-03-02 23:10:37 +01:00
|
|
|
def restart():
|
|
|
|
try:
|
|
|
|
restart_frigate()
|
|
|
|
except Exception as e:
|
|
|
|
logging.error(f"Error restarting Frigate: {e}")
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{
|
|
|
|
"success": False,
|
|
|
|
"message": "Unable to restart Frigate.",
|
|
|
|
}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=500,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=(
|
2024-03-02 23:10:37 +01:00
|
|
|
{
|
|
|
|
"success": True,
|
|
|
|
"message": "Restarting (this can take up to one minute)...",
|
|
|
|
}
|
|
|
|
),
|
2024-09-24 15:05:30 +02:00
|
|
|
status_code=200,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/labels")
|
|
|
|
def get_labels(camera: str = ""):
|
2024-03-02 23:10:37 +01:00
|
|
|
try:
|
|
|
|
if camera:
|
|
|
|
events = Event.select(Event.label).where(Event.camera == camera).distinct()
|
|
|
|
else:
|
|
|
|
events = Event.select(Event.label).distinct()
|
|
|
|
except Exception as e:
|
|
|
|
logger.error(e)
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=({"success": False, "message": "Failed to get labels"}),
|
|
|
|
status_code=404,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
labels = sorted([e.label for e in events])
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(content=labels)
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/sub_labels")
|
|
|
|
def get_sub_labels(split_joined: Optional[int] = None):
|
2024-03-02 23:10:37 +01:00
|
|
|
try:
|
|
|
|
events = Event.select(Event.sub_label).distinct()
|
|
|
|
except Exception:
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content=({"success": False, "message": "Failed to get sub_labels"}),
|
|
|
|
status_code=404,
|
2024-03-02 23:10:37 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
sub_labels = [e.sub_label for e in events]
|
|
|
|
|
|
|
|
if None in sub_labels:
|
|
|
|
sub_labels.remove(None)
|
|
|
|
|
|
|
|
if split_joined:
|
|
|
|
original_labels = sub_labels.copy()
|
|
|
|
|
|
|
|
for label in original_labels:
|
|
|
|
if "," in label:
|
|
|
|
sub_labels.remove(label)
|
|
|
|
parts = label.split(",")
|
|
|
|
|
|
|
|
for part in parts:
|
|
|
|
if part.strip() not in sub_labels:
|
|
|
|
sub_labels.append(part.strip())
|
|
|
|
|
|
|
|
sub_labels.sort()
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(content=sub_labels)
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/timeline")
|
|
|
|
def timeline(camera: str = "all", limit: int = 100, source_id: Optional[str] = None):
|
2024-03-02 23:10:37 +01:00
|
|
|
clauses = []
|
|
|
|
|
|
|
|
selected_columns = [
|
|
|
|
Timeline.timestamp,
|
|
|
|
Timeline.camera,
|
|
|
|
Timeline.source,
|
|
|
|
Timeline.source_id,
|
|
|
|
Timeline.class_type,
|
|
|
|
Timeline.data,
|
|
|
|
]
|
|
|
|
|
|
|
|
if camera != "all":
|
|
|
|
clauses.append((Timeline.camera == camera))
|
|
|
|
|
|
|
|
if source_id:
|
|
|
|
clauses.append((Timeline.source_id == source_id))
|
|
|
|
|
|
|
|
if len(clauses) == 0:
|
|
|
|
clauses.append((True))
|
|
|
|
|
|
|
|
timeline = (
|
|
|
|
Timeline.select(*selected_columns)
|
|
|
|
.where(reduce(operator.and_, clauses))
|
|
|
|
.order_by(Timeline.timestamp.asc())
|
|
|
|
.limit(limit)
|
|
|
|
.dicts()
|
|
|
|
)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(content=[t for t in timeline])
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
@router.get("/timeline/hourly")
|
|
|
|
def hourly_timeline(params: AppTimelineHourlyQueryParameters = Depends()):
|
2024-03-02 23:10:37 +01:00
|
|
|
"""Get hourly summary for timeline."""
|
2024-09-24 15:05:30 +02:00
|
|
|
cameras = params.cameras
|
|
|
|
labels = params.labels
|
|
|
|
before = params.before
|
|
|
|
after = params.after
|
|
|
|
limit = params.limit
|
|
|
|
tz_name = params.timezone
|
2024-03-02 23:10:37 +01:00
|
|
|
|
|
|
|
_, minute_modifier, _ = get_tz_modifiers(tz_name)
|
|
|
|
minute_offset = int(minute_modifier.split(" ")[0])
|
|
|
|
|
|
|
|
clauses = []
|
|
|
|
|
|
|
|
if cameras != "all":
|
|
|
|
camera_list = cameras.split(",")
|
|
|
|
clauses.append((Timeline.camera << camera_list))
|
|
|
|
|
|
|
|
if labels != "all":
|
|
|
|
label_list = labels.split(",")
|
|
|
|
clauses.append((Timeline.data["label"] << label_list))
|
|
|
|
|
|
|
|
if before:
|
|
|
|
clauses.append((Timeline.timestamp < before))
|
|
|
|
|
|
|
|
if after:
|
|
|
|
clauses.append((Timeline.timestamp > after))
|
|
|
|
|
|
|
|
if len(clauses) == 0:
|
|
|
|
clauses.append((True))
|
|
|
|
|
|
|
|
timeline = (
|
|
|
|
Timeline.select(
|
|
|
|
Timeline.camera,
|
|
|
|
Timeline.timestamp,
|
|
|
|
Timeline.data,
|
|
|
|
Timeline.class_type,
|
|
|
|
Timeline.source_id,
|
|
|
|
Timeline.source,
|
|
|
|
)
|
|
|
|
.where(reduce(operator.and_, clauses))
|
|
|
|
.order_by(Timeline.timestamp.desc())
|
|
|
|
.limit(limit)
|
|
|
|
.dicts()
|
|
|
|
.iterator()
|
|
|
|
)
|
|
|
|
|
|
|
|
count = 0
|
|
|
|
start = 0
|
|
|
|
end = 0
|
|
|
|
hours: dict[str, list[dict[str, any]]] = {}
|
|
|
|
|
|
|
|
for t in timeline:
|
|
|
|
if count == 0:
|
|
|
|
start = t["timestamp"]
|
|
|
|
else:
|
|
|
|
end = t["timestamp"]
|
|
|
|
|
|
|
|
count += 1
|
|
|
|
|
|
|
|
hour = (
|
|
|
|
datetime.fromtimestamp(t["timestamp"]).replace(
|
|
|
|
minute=0, second=0, microsecond=0
|
|
|
|
)
|
|
|
|
+ timedelta(
|
|
|
|
minutes=minute_offset,
|
|
|
|
)
|
|
|
|
).timestamp()
|
|
|
|
if hour not in hours:
|
|
|
|
hours[hour] = [t]
|
|
|
|
else:
|
|
|
|
hours[hour].insert(0, t)
|
|
|
|
|
2024-09-24 15:05:30 +02:00
|
|
|
return JSONResponse(
|
|
|
|
content={
|
2024-03-02 23:10:37 +01:00
|
|
|
"start": start,
|
|
|
|
"end": end,
|
|
|
|
"count": count,
|
|
|
|
"hours": hours,
|
|
|
|
}
|
|
|
|
)
|