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.

322 lines
6.8 KiB

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