Commit f9f9cde2 by xiongziliang

整理webapi、webhook框架代码

parent 781708f0
...@@ -12,10 +12,21 @@ ...@@ -12,10 +12,21 @@
#define ZLMEDIAKIT_WEBAPI_H #define ZLMEDIAKIT_WEBAPI_H
#include <string> #include <string>
#include <functional>
#include "jsoncpp/json.h"
#include "Common/Parser.h"
#include "Network/Socket.h"
#include "Http/HttpSession.h"
using namespace std; using namespace std;
using namespace Json;
using namespace toolkit;
using namespace mediakit;
namespace mediakit { //配置文件路径
extern string g_ini_file;
namespace mediakit {
////////////RTSP服务器配置/////////// ////////////RTSP服务器配置///////////
namespace Rtsp { namespace Rtsp {
extern const string kPort; extern const string kPort;
...@@ -25,13 +36,93 @@ extern const string kPort; ...@@ -25,13 +36,93 @@ extern const string kPort;
namespace Rtmp { namespace Rtmp {
extern const string kPort; extern const string kPort;
} //namespace RTMP } //namespace RTMP
} // namespace mediakit } // namespace mediakit
namespace API {
typedef enum {
NotFound = -500,//未找到
Exception = -400,//代码抛异常
InvalidArgs = -300,//参数不合法
SqlFailed = -200,//sql执行失败
AuthFailed = -100,//鉴权失败
OtherFailed = -1,//业务代码执行失败,
Success = 0//执行成功
} ApiErr;
}//namespace API
class ApiRetException: public std::runtime_error {
public:
ApiRetException(const char *str = "success" ,int code = API::Success):runtime_error(str){
_code = code;
}
~ApiRetException() = default;
int code(){ return _code; }
private:
int _code;
};
class AuthException : public ApiRetException {
public:
AuthException(const char *str):ApiRetException(str,API::AuthFailed){}
~AuthException() = default;
};
class InvalidArgsException: public ApiRetException {
public:
InvalidArgsException(const char *str):ApiRetException(str,API::InvalidArgs){}
~InvalidArgsException() = default;
};
class SuccessException: public ApiRetException {
public:
SuccessException():ApiRetException("success",API::Success){}
~SuccessException() = default;
};
using ApiArgsType = map<string, variant, StrCaseCompare>;
#define API_ARGS_MAP SockInfo &sender, HttpSession::KeyValue &headerIn, HttpSession::KeyValue &headerOut, ApiArgsType &allArgs, Json::Value &val
#define API_ARGS_MAP_ASYNC API_ARGS_MAP, const HttpSession::HttpResponseInvoker &invoker
#define API_ARGS_JSON SockInfo &sender, HttpSession::KeyValue &headerIn, HttpSession::KeyValue &headerOut, Json::Value &allArgs, Json::Value &val
#define API_ARGS_JSON_ASYNC API_ARGS_JSON, const HttpSession::HttpResponseInvoker &invoker
#define API_ARGS_VALUE sender, headerIn, headerOut, allArgs, val
//注册http请求参数是map<string, variant, StrCaseCompare>类型的http api
void api_regist(const string &api_path, const function<void(API_ARGS_MAP)> &func);
//注册http请求参数是map<string, variant, StrCaseCompare>类型,但是可以异步回复的的http api
void api_regist(const string &api_path, const function<void(API_ARGS_MAP_ASYNC)> &func);
//注册http请求参数是Json::Value类型的http api(可以支持多级嵌套的json参数对象)
void api_regist(const string &api_path, const function<void(API_ARGS_JSON)> &func);
//注册http请求参数是Json::Value类型,但是可以异步回复的的http api
void api_regist(const string &api_path, const function<void(API_ARGS_JSON_ASYNC)> &func);
template<typename Args, typename First>
bool checkArgs(Args &&args, First &&first) {
return !args[first].empty();
}
template<typename Args, typename First, typename ...KeyTypes>
bool checkArgs(Args &&args, First &&first, KeyTypes &&...keys) {
return !args[first].empty() && checkArgs(std::forward<Args>(args), std::forward<KeyTypes>(keys)...);
}
//检查http参数是否为空的宏
#define CHECK_ARGS(...) \
if(!checkArgs(allArgs,##__VA_ARGS__)){ \
throw InvalidArgsException("缺少必要参数:" #__VA_ARGS__); \
}
//检查http参数中是否附带secret密钥的宏,127.0.0.1的ip不检查密钥
#define CHECK_SECRET() \
if(sender.get_peer_ip() != "127.0.0.1"){ \
CHECK_ARGS("secret"); \
if(api_secret != allArgs["secret"]){ \
throw AuthException("secret错误"); \
} \
}
void installWebApi(); void installWebApi();
void unInstallWebApi(); void unInstallWebApi();
//配置文件路径
extern string g_ini_file;
#endif //ZLMEDIAKIT_WEBAPI_H #endif //ZLMEDIAKIT_WEBAPI_H
...@@ -9,9 +9,7 @@ ...@@ -9,9 +9,7 @@
*/ */
#include <sstream> #include <sstream>
#include "jsoncpp/json.h"
#include "Util/logger.h" #include "Util/logger.h"
#include "Util/util.h"
#include "Util/onceToken.h" #include "Util/onceToken.h"
#include "Util/NoticeCenter.h" #include "Util/NoticeCenter.h"
#include "Common/config.h" #include "Common/config.h"
...@@ -22,21 +20,9 @@ ...@@ -22,21 +20,9 @@
#include "Http/HttpSession.h" #include "Http/HttpSession.h"
#include "WebHook.h" #include "WebHook.h"
using namespace Json;
using namespace toolkit; using namespace toolkit;
using namespace mediakit; using namespace mediakit;
//支持json或urlencoded方式传输参数
#define JSON_ARGS
#ifdef JSON_ARGS
typedef Value ArgsType;
#else
typedef HttpArgs ArgsType;
#endif
namespace Hook { namespace Hook {
#define HOOK_FIELD "hook." #define HOOK_FIELD "hook."
...@@ -126,35 +112,35 @@ const char *getContentType(const HttpArgs &value){ ...@@ -126,35 +112,35 @@ const char *getContentType(const HttpArgs &value){
return "application/x-www-form-urlencoded"; return "application/x-www-form-urlencoded";
} }
static void do_http_hook(const string &url,const ArgsType &body,const function<void(const Value &,const string &)> &fun){ void do_http_hook(const string &url,const ArgsType &body,const function<void(const Value &,const string &)> &func){
GET_CONFIG(string,mediaServerId,General::kMediaServerId); GET_CONFIG(string, mediaServerId, General::kMediaServerId);
const_cast<ArgsType &>(body)["mediaServerId"] = mediaServerId; GET_CONFIG(float, hook_timeoutSec, Hook::kTimeoutSec);
GET_CONFIG(float,hook_timeoutSec,Hook::kTimeoutSec); const_cast<ArgsType &>(body)["mediaServerId"] = mediaServerId;
HttpRequester::Ptr requester(new HttpRequester); HttpRequester::Ptr requester(new HttpRequester);
requester->setMethod("POST"); requester->setMethod("POST");
auto bodyStr = to_string(body); auto bodyStr = to_string(body);
requester->setBody(bodyStr); requester->setBody(bodyStr);
requester->addHeader("Content-Type",getContentType(body)); requester->addHeader("Content-Type", getContentType(body));
std::shared_ptr<Ticker> pTicker(new Ticker); std::shared_ptr<Ticker> pTicker(new Ticker);
requester->startRequester(url,[url,fun,bodyStr,requester,pTicker](const SockException &ex, requester->startRequester(url, [url, func, bodyStr, requester, pTicker](const SockException &ex,
const string &status, const string &status,
const HttpClient::HttpHeader &header, const HttpClient::HttpHeader &header,
const string &strRecvBody){ const string &strRecvBody) {
onceToken token(nullptr,[&](){ onceToken token(nullptr, [&]() {
const_cast<HttpRequester::Ptr &>(requester).reset(); const_cast<HttpRequester::Ptr &>(requester).reset();
}); });
parse_http_response(ex,status,header,strRecvBody,[&](const Value &obj,const string &err){ parse_http_response(ex,status,header,strRecvBody,[&](const Value &obj,const string &err){
if(fun){ if (func) {
fun(obj,err); func(obj, err);
} }
if(!err.empty()) { if (!err.empty()) {
WarnL << "hook " << url << " " <<pTicker->elapsedTime() << "ms,failed" << err << ":" << bodyStr; WarnL << "hook " << url << " " << pTicker->elapsedTime() << "ms,failed" << err << ":" << bodyStr;
}else if(pTicker->elapsedTime() > 500){ } else if (pTicker->elapsedTime() > 500) {
DebugL << "hook " << url << " " <<pTicker->elapsedTime() << "ms,success:" << bodyStr; DebugL << "hook " << url << " " << pTicker->elapsedTime() << "ms,success:" << bodyStr;
} }
}); });
},hook_timeoutSec); }, hook_timeoutSec);
} }
static ArgsType make_json(const MediaInfo &args){ static ArgsType make_json(const MediaInfo &args){
......
...@@ -12,13 +12,32 @@ ...@@ -12,13 +12,32 @@
#define ZLMEDIAKIT_WEBHOOK_H #define ZLMEDIAKIT_WEBHOOK_H
#include <string> #include <string>
#include <functional>
#include "jsoncpp/json.h"
using namespace std; using namespace std;
using namespace Json;
//支持json或urlencoded方式传输参数
#define JSON_ARGS
#ifdef JSON_ARGS
typedef Value ArgsType;
#else
typedef HttpArgs ArgsType;
#endif
namespace Hook { namespace Hook {
//web hook回复最大超时时间
extern const string kTimeoutSec; extern const string kTimeoutSec;
}//namespace Hook }//namespace Hook
void installWebHook(); void installWebHook();
void unInstallWebHook(); void unInstallWebHook();
/**
* 触发http hook请求
* @param url 请求地址
* @param body 请求body
* @param func 回调
*/
void do_http_hook(const string &url, const ArgsType &body, const function<void(const Value &, const string &)> &func = nullptr);
#endif //ZLMEDIAKIT_WEBHOOK_H #endif //ZLMEDIAKIT_WEBHOOK_H
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论