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.

290 lines
6.1 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "api.h"
  2. #include <ctime>
  3. #include <nlohmann/json.hpp>
  4. namespace mtx {
  5. using json = nlohmann::json;
  6. namespace {
  7. std::string isoTime(int64_t us)
  8. {
  9. if (us <= 0)
  10. {
  11. return std::string();
  12. }
  13. time_t tSec = (time_t) (us / 1000000);
  14. struct tm tTm;
  15. gmtime_r(&tSec, &tTm);
  16. char tB[40];
  17. strftime(tB, sizeof(tB), "%Y-%m-%dT%H:%M:%SZ", &tTm);
  18. return tB;
  19. }
  20. json pathConfJson(const PathConf & p)
  21. {
  22. return json{{"name", p.name}, {"source", p.source}, {"record", p.record}, {"rtspTransport", p.transport == RtspTransport::Udp ? "udp" : "tcp"}};
  23. }
  24. json pathInfoJson(const PathInfo & i)
  25. {
  26. json j = {{"name", i.name},
  27. {"confName", i.name},
  28. {"source", {{"type", "rtspSource"}, {"id", ""}}},
  29. {"ready", i.ready},
  30. {"readyTime", i.ready ? json(isoTime(i.readySinceUs)) : json(nullptr)},
  31. {"tracks", i.ready ? json::array({"H264"}) : json::array()},
  32. {"bytesReceived", i.bytesReceived},
  33. {"record", i.record},
  34. {"readers", i.readers}};
  35. if (i.ready)
  36. {
  37. j["width"] = i.desc.width;
  38. j["height"] = i.desc.height;
  39. }
  40. return j;
  41. }
  42. void error(HttpResponse & res, int status, const std::string & msg)
  43. {
  44. res.status = status;
  45. res.setHeader("Content-Type", "application/json");
  46. res.body = json{{"error", msg}}.dump();
  47. }
  48. void ok(HttpResponse & res, const json & body)
  49. {
  50. res.status = 200;
  51. res.setHeader("Content-Type", "application/json");
  52. res.body = body.dump();
  53. }
  54. // fields of a path configuration from JSON into pc
  55. bool applyFields(const json & j, PathConf & pc, std::string & err)
  56. {
  57. if (! j.is_object())
  58. {
  59. err = "body must be a JSON object";
  60. return false;
  61. }
  62. for (auto it = j.begin(); it != j.end(); ++it)
  63. {
  64. if (it.key() == "source" && it->is_string())
  65. {
  66. pc.source = it->get<std::string>();
  67. }
  68. else if (it.key() == "record" && it->is_boolean())
  69. {
  70. pc.record = it->get<bool>();
  71. }
  72. else if (it.key() == "rtspTransport" && it->is_string())
  73. {
  74. std::string v = it->get<std::string>();
  75. if (v == "tcp" || v == "automatic")
  76. {
  77. pc.transport = RtspTransport::Tcp;
  78. }
  79. else if (v == "udp")
  80. {
  81. pc.transport = RtspTransport::Udp;
  82. }
  83. else
  84. {
  85. err = "rtspTransport must be tcp or udp";
  86. return false;
  87. }
  88. }
  89. else if (it.key() == "name")
  90. {
  91. continue;
  92. }
  93. else
  94. {
  95. err = "unsupported field '" + it.key() + "'";
  96. return false;
  97. }
  98. }
  99. if (pc.source.compare(0, 7, "rtsp://") != 0)
  100. {
  101. err = "source must be an rtsp:// URL";
  102. return false;
  103. }
  104. return true;
  105. }
  106. } // namespace
  107. 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) {}
  108. Api::~Api()
  109. {
  110. stop();
  111. }
  112. bool Api::start(std::string & err)
  113. {
  114. if (! m_http.start(m_global.apiAddress, [this](const HttpRequest & q, HttpResponse & r) { handle(q, r); }, err))
  115. {
  116. return false;
  117. }
  118. log(LogLevel::Info, "listener opened on %s", m_global.apiAddress.c_str());
  119. return true;
  120. }
  121. void Api::stop()
  122. {
  123. m_http.stop();
  124. }
  125. void Api::handle(const HttpRequest & req, HttpResponse & res)
  126. {
  127. const std::string & p = req.path;
  128. auto starts = [&p](const char * prefix) { return p.compare(0, strlen(prefix), prefix) == 0; };
  129. if (req.method == "GET" && p == "/v3/paths/list")
  130. {
  131. json tItems = json::array();
  132. for (const PathInfo & i : m_pPaths->list())
  133. {
  134. tItems.push_back(pathInfoJson(i));
  135. }
  136. ok(res, json{{"itemCount", tItems.size()}, {"pageCount", 1}, {"items", tItems}});
  137. return;
  138. }
  139. if (req.method == "GET" && starts("/v3/paths/get/"))
  140. {
  141. auto tPath = m_pPaths->find(p.substr(strlen("/v3/paths/get/")));
  142. if (! tPath)
  143. {
  144. error(res, 404, "path not found");
  145. return;
  146. }
  147. ok(res, pathInfoJson(tPath->info()));
  148. return;
  149. }
  150. if (req.method == "GET" && p == "/v3/config/paths/list")
  151. {
  152. json tItems = json::array();
  153. for (const PathConf & c : m_pPaths->confs())
  154. {
  155. tItems.push_back(pathConfJson(c));
  156. }
  157. ok(res, json{{"itemCount", tItems.size()}, {"pageCount", 1}, {"items", tItems}});
  158. return;
  159. }
  160. if (req.method == "GET" && starts("/v3/config/paths/get/"))
  161. {
  162. auto tPath = m_pPaths->find(p.substr(strlen("/v3/config/paths/get/")));
  163. if (! tPath)
  164. {
  165. error(res, 404, "path not found");
  166. return;
  167. }
  168. ok(res, pathConfJson(tPath->conf()));
  169. return;
  170. }
  171. // changes
  172. std::string tName;
  173. enum { NONE, ADD, PATCH, REPLACE, DEL } tOp = NONE;
  174. if (req.method == "POST" && starts("/v3/config/paths/add/"))
  175. {
  176. tOp = ADD;
  177. tName = p.substr(strlen("/v3/config/paths/add/"));
  178. }
  179. else if (req.method == "PATCH" && starts("/v3/config/paths/patch/"))
  180. {
  181. tOp = PATCH;
  182. tName = p.substr(strlen("/v3/config/paths/patch/"));
  183. }
  184. else if (req.method == "POST" && starts("/v3/config/paths/replace/"))
  185. {
  186. tOp = REPLACE;
  187. tName = p.substr(strlen("/v3/config/paths/replace/"));
  188. }
  189. else if (req.method == "DELETE" && starts("/v3/config/paths/delete/"))
  190. {
  191. tOp = DEL;
  192. tName = p.substr(strlen("/v3/config/paths/delete/"));
  193. }
  194. if (tOp == NONE)
  195. {
  196. error(res, 404, "not found");
  197. return;
  198. }
  199. if (! validPathName(tName))
  200. {
  201. error(res, 400, "invalid path name");
  202. return;
  203. }
  204. std::vector<PathConf> tConfs = m_pPaths->confs();
  205. auto tIt = std::find_if(tConfs.begin(), tConfs.end(), [&tName](const PathConf & c) { return c.name == tName; });
  206. json tBody;
  207. if (tOp != DEL)
  208. {
  209. try
  210. {
  211. tBody = json::parse(req.body.empty() ? std::string("{}") : req.body);
  212. }
  213. catch (const std::exception & e)
  214. {
  215. error(res, 400, std::string("invalid JSON: ") + e.what());
  216. return;
  217. }
  218. }
  219. std::string tErr;
  220. if (tOp == ADD)
  221. {
  222. if (tIt != tConfs.end())
  223. {
  224. error(res, 400, "path already exists");
  225. return;
  226. }
  227. PathConf tPc;
  228. tPc.name = tName;
  229. if (! applyFields(tBody, tPc, tErr))
  230. {
  231. error(res, 400, tErr);
  232. return;
  233. }
  234. tConfs.push_back(tPc);
  235. }
  236. else
  237. {
  238. if (tIt == tConfs.end())
  239. {
  240. error(res, 404, "path not found");
  241. return;
  242. }
  243. if (tOp == DEL)
  244. {
  245. tConfs.erase(tIt);
  246. }
  247. else
  248. {
  249. PathConf tPc;
  250. if (tOp == PATCH)
  251. {
  252. tPc = *tIt;
  253. }
  254. tPc.name = tName;
  255. if (! applyFields(tBody, tPc, tErr))
  256. {
  257. error(res, 400, tErr);
  258. return;
  259. }
  260. *tIt = tPc;
  261. }
  262. }
  263. if (! m_apply(tConfs, tErr))
  264. {
  265. error(res, 500, tErr);
  266. return;
  267. }
  268. res.status = 200;
  269. }
  270. } // namespace mtx