#include "api.h" #include #include namespace mtx { using json = nlohmann::json; namespace { std::string isoTime(int64_t us) { if (us <= 0) { return std::string(); } time_t tSec = (time_t) (us / 1000000); struct tm tTm; gmtime_r(&tSec, &tTm); char tB[40]; strftime(tB, sizeof(tB), "%Y-%m-%dT%H:%M:%SZ", &tTm); return tB; } json pathConfJson(const PathConf & p) { return json{{"name", p.name}, {"source", p.source}, {"record", p.record}, {"rtspTransport", p.transport == RtspTransport::Udp ? "udp" : "tcp"}}; } json pathInfoJson(const PathInfo & i) { json j = {{"name", i.name}, {"confName", i.name}, {"source", {{"type", "rtspSource"}, {"id", ""}}}, {"ready", i.ready}, {"readyTime", i.ready ? json(isoTime(i.readySinceUs)) : json(nullptr)}, {"tracks", i.ready ? json::array({"H264"}) : json::array()}, {"bytesReceived", i.bytesReceived}, {"record", i.record}, {"readers", i.readers}}; if (i.ready) { j["width"] = i.desc.width; j["height"] = i.desc.height; } return j; } void error(HttpResponse & res, int status, const std::string & msg) { res.status = status; res.setHeader("Content-Type", "application/json"); res.body = json{{"error", msg}}.dump(); } void ok(HttpResponse & res, const json & body) { res.status = 200; res.setHeader("Content-Type", "application/json"); res.body = body.dump(); } // fields of a path configuration from JSON into pc bool applyFields(const json & j, PathConf & pc, std::string & err) { if (! j.is_object()) { err = "body must be a JSON object"; return false; } for (auto it = j.begin(); it != j.end(); ++it) { if (it.key() == "source" && it->is_string()) { pc.source = it->get(); } else if (it.key() == "record" && it->is_boolean()) { pc.record = it->get(); } else if (it.key() == "rtspTransport" && it->is_string()) { std::string v = it->get(); if (v == "tcp" || v == "automatic") { pc.transport = RtspTransport::Tcp; } else if (v == "udp") { pc.transport = RtspTransport::Udp; } else { err = "rtspTransport must be tcp or udp"; return false; } } else if (it.key() == "name") { continue; } else { err = "unsupported field '" + it.key() + "'"; return false; } } if (pc.source.compare(0, 7, "rtsp://") != 0) { err = "source must be an rtsp:// URL"; return false; } return true; } } // namespace Api::Api(const Conf & global, PathManager * paths, ApplyFn apply) : LogParent("[API] "), m_global(global), m_pPaths(paths), m_apply(std::move(apply)), m_http(this) {} Api::~Api() { stop(); } bool Api::start(std::string & err) { if (! m_http.start(m_global.apiAddress, [this](const HttpRequest & q, HttpResponse & r) { handle(q, r); }, err)) { return false; } log(LogLevel::Info, "listener opened on %s", m_global.apiAddress.c_str()); return true; } void Api::stop() { m_http.stop(); } void Api::handle(const HttpRequest & req, HttpResponse & res) { const std::string & p = req.path; auto starts = [&p](const char * prefix) { return p.compare(0, strlen(prefix), prefix) == 0; }; if (req.method == "GET" && p == "/v3/paths/list") { json tItems = json::array(); for (const PathInfo & i : m_pPaths->list()) { tItems.push_back(pathInfoJson(i)); } ok(res, json{{"itemCount", tItems.size()}, {"pageCount", 1}, {"items", tItems}}); return; } if (req.method == "GET" && starts("/v3/paths/get/")) { auto tPath = m_pPaths->find(p.substr(strlen("/v3/paths/get/"))); if (! tPath) { error(res, 404, "path not found"); return; } ok(res, pathInfoJson(tPath->info())); return; } if (req.method == "GET" && p == "/v3/config/paths/list") { json tItems = json::array(); for (const PathConf & c : m_pPaths->confs()) { tItems.push_back(pathConfJson(c)); } ok(res, json{{"itemCount", tItems.size()}, {"pageCount", 1}, {"items", tItems}}); return; } if (req.method == "GET" && starts("/v3/config/paths/get/")) { auto tPath = m_pPaths->find(p.substr(strlen("/v3/config/paths/get/"))); if (! tPath) { error(res, 404, "path not found"); return; } ok(res, pathConfJson(tPath->conf())); return; } // changes std::string tName; enum { NONE, ADD, PATCH, REPLACE, DEL } tOp = NONE; if (req.method == "POST" && starts("/v3/config/paths/add/")) { tOp = ADD; tName = p.substr(strlen("/v3/config/paths/add/")); } else if (req.method == "PATCH" && starts("/v3/config/paths/patch/")) { tOp = PATCH; tName = p.substr(strlen("/v3/config/paths/patch/")); } else if (req.method == "POST" && starts("/v3/config/paths/replace/")) { tOp = REPLACE; tName = p.substr(strlen("/v3/config/paths/replace/")); } else if (req.method == "DELETE" && starts("/v3/config/paths/delete/")) { tOp = DEL; tName = p.substr(strlen("/v3/config/paths/delete/")); } if (tOp == NONE) { error(res, 404, "not found"); return; } if (! validPathName(tName)) { error(res, 400, "invalid path name"); return; } std::vector tConfs = m_pPaths->confs(); auto tIt = std::find_if(tConfs.begin(), tConfs.end(), [&tName](const PathConf & c) { return c.name == tName; }); json tBody; if (tOp != DEL) { try { tBody = json::parse(req.body.empty() ? std::string("{}") : req.body); } catch (const std::exception & e) { error(res, 400, std::string("invalid JSON: ") + e.what()); return; } } std::string tErr; if (tOp == ADD) { if (tIt != tConfs.end()) { error(res, 400, "path already exists"); return; } PathConf tPc; tPc.name = tName; if (! applyFields(tBody, tPc, tErr)) { error(res, 400, tErr); return; } tConfs.push_back(tPc); } else { if (tIt == tConfs.end()) { error(res, 404, "path not found"); return; } if (tOp == DEL) { tConfs.erase(tIt); } else { PathConf tPc; if (tOp == PATCH) { tPc = *tIt; } tPc.name = tName; if (! applyFields(tBody, tPc, tErr)) { error(res, 400, tErr); return; } *tIt = tPc; } } if (! m_apply(tConfs, tErr)) { error(res, 500, tErr); return; } res.status = 200; } } // namespace mtx