mvc_impl.h 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748
  1. #pragma once
  2. #ifdef WINDOWS_BUILD
  3. #ifdef MVC_EXPORTS
  4. #define MVC_API _declspec(dllexport)
  5. #else
  6. #define MVC_API _declspec(dllimport)
  7. #endif
  8. #elif LINUX_BUILD
  9. #define MVC_API
  10. #endif
  11. //asio2
  12. #include <asio2/asio2.hpp>
  13. //robotics
  14. #include "../robot/robotics/utils.hpp"
  15. #include "../robot/robotics/json.hpp"
  16. #include "../robot/robotics/CImg.h"
  17. namespace robotics {
  18. namespace v3 {
  19. namespace mvc {
  20. class web_reflect {
  21. public:
  22. /**
  23. * @brief
  24. * @param obj
  25. */
  26. static std::map<std::string, std::string> get_object_value(rttr::instance obj) {
  27. std::map<std::string, std::string> result;
  28. auto propertys = obj.get_type().get_properties();
  29. for (auto& property : propertys) {
  30. std::string propName(property.get_name());
  31. rttr::variant propValue = property.get_value(obj);
  32. rttr::type propType = property.get_type();
  33. if (propType == rttr::type::get<int>()) {
  34. result[propName] = std::to_string(propValue.get_value<int>());
  35. }
  36. else if (propType == rttr::type::get<std::int64_t>()) {
  37. result[propName] = std::to_string(propValue.get_value<std::int64_t>());
  38. }
  39. else if (propType == rttr::type::get<float>()) {
  40. result[propName] = v3::utils::format("{:.2f}", propValue.get_value<float>());
  41. }
  42. else if (propType == rttr::type::get<double>()) {
  43. result[propName] = v3::utils::format("{:.2f}", propValue.get_value<double>());
  44. }
  45. else if (propType == rttr::type::get<long>()) {
  46. result[propName] = std::to_string(propValue.get_value<long>());
  47. }
  48. else if (propType == rttr::type::get<bool>()) {
  49. result[propName] = propValue.get_value<bool>() ? "true" : "false";
  50. }
  51. else if (propType == rttr::type::get<std::string>()) {
  52. result[propName] = propValue.get_value<std::string>();
  53. }
  54. else if (propType == rttr::type::get<v3::datetime>()) {
  55. result[propName] = propValue.get_value<v3::datetime>().to_string();
  56. }
  57. else if (propType == rttr::type::get<std::vector<int>>()) {
  58. auto vecValue = propValue.get_value<std::vector<int>>();
  59. result[propName] = v3::utils::join(vecValue, ",");
  60. }
  61. else if (propType == rttr::type::get<std::vector<std::int64_t>>()) {
  62. auto vecValue = propValue.get_value<std::vector<std::int64_t>>();
  63. result[propName] = v3::utils::join(vecValue, ",");
  64. }
  65. else if (propType == rttr::type::get<std::vector<float>>()) {
  66. auto vecValue = propValue.get_value<std::vector<float>>();
  67. result[propName] = v3::utils::join(vecValue, ",");
  68. }
  69. else if (propType == rttr::type::get<std::vector<double>>()) {
  70. auto vecValue = propValue.get_value<std::vector<double>>();
  71. result[propName] = v3::utils::join(vecValue, ",");
  72. }
  73. else if (propType == rttr::type::get<std::vector<long>>()) {
  74. auto vecValue = propValue.get_value<std::vector<long>>();
  75. result[propName] = v3::utils::join(vecValue, ",");
  76. }
  77. else if (propType == rttr::type::get<std::vector<bool>>()) {
  78. auto vecValue = propValue.get_value<std::vector<bool>>();
  79. result[propName] = v3::utils::join(vecValue, ",");
  80. }
  81. else if (propType == rttr::type::get<std::vector<std::string>>()) {
  82. auto vecValue = propValue.get_value<std::vector<std::string>>();
  83. result[propName] = v3::utils::join(vecValue, ",");
  84. }
  85. else if (propType == rttr::type::get<std::vector<v3::datetime>>()) {
  86. auto vecValue = propValue.get_value<std::vector<v3::datetime>>();
  87. result[propName] = v3::utils::join(vecValue, ",");
  88. }
  89. }
  90. return result;
  91. }
  92. /**
  93. * @brief
  94. * @param obj
  95. * @param values
  96. */
  97. static void set_object_value(rttr::instance obj, std::map<std::string, std::string>const& values) {
  98. rttr::instance obj1 = obj.get_type().get_raw_type().is_wrapper() ? obj.get_wrapped_instance() : obj;
  99. const auto propertys = obj1.get_derived_type().get_properties();
  100. for (auto& property : propertys) {
  101. auto name = std::string(property.get_name());
  102. auto type = property.get_type();
  103. if (!values.contains(name))
  104. continue;
  105. std::string value = values.find(name)->second;
  106. if (type == rttr::type::get<int>()) {
  107. property.set_value(obj1, atoi(value.c_str()));
  108. }
  109. else if (type == rttr::type::get<std::int64_t>()) {
  110. property.set_value(obj, std::int64_t(std::atoll(value.c_str())));
  111. }
  112. else if (type == rttr::type::get<float>()) {
  113. property.set_value(obj, float(std::atof(value.c_str())));
  114. }
  115. else if (type == rttr::type::get<double>()) {
  116. property.set_value(obj, double(std::atof(value.c_str())));
  117. }
  118. else if (type == rttr::type::get<long>()) {
  119. property.set_value(obj, long(std::atol(value.c_str())));
  120. }
  121. else if (type == rttr::type::get<bool>()) {
  122. if (value == "1" || value == "true" || value == "TRUE" || value == "True") {
  123. property.set_value(obj, true);
  124. }
  125. else {
  126. property.set_value(obj, false);
  127. }
  128. }
  129. else if (type == rttr::type::get<std::string>()) {
  130. property.set_value(obj, value);
  131. }
  132. else if (type == rttr::type::get<v3::datetime>()) {
  133. property.set_value(obj, v3::datetime(value));
  134. }
  135. else if (type == rttr::type::get<std::vector<int>>()) {
  136. std::vector<std::string> vec = v3::utils::split(value, ",");
  137. std::vector<int> vecValue;
  138. for (auto vecIt : vec) {
  139. vecValue.push_back(std::atoi(vecIt.c_str()));
  140. }
  141. property.set_value(obj, vecValue);
  142. }
  143. else if (type == rttr::type::get<std::vector<std::int64_t>>()) {
  144. std::vector<std::string> vec = v3::utils::split(value, ",");
  145. std::vector<std::int64_t> vecValue;
  146. for (auto vecIt : vec) {
  147. vecValue.push_back(std::atoll(vecIt.c_str()));
  148. }
  149. property.set_value(obj, vecValue);
  150. }
  151. else if (type == rttr::type::get<std::vector<float>>()) {
  152. std::vector<std::string> vec = v3::utils::split(value, ",");
  153. std::vector<float> vecValue;
  154. for (auto vecIt : vec) {
  155. vecValue.push_back(std::atof(vecIt.c_str()));
  156. }
  157. property.set_value(obj, vecValue);
  158. }
  159. else if (type == rttr::type::get<std::vector<double>>()) {
  160. std::vector<std::string> vec = v3::utils::split(value, ",");
  161. std::vector<double> vecValue;
  162. for (auto vecIt : vec) {
  163. vecValue.push_back(std::atof(vecIt.c_str()));
  164. }
  165. property.set_value(obj, vecValue);
  166. }
  167. else if (type == rttr::type::get<std::vector<long>>()) {
  168. std::vector<std::string> vec = v3::utils::split(value, ",");
  169. std::vector<long> vecValue;
  170. for (auto vecIt : vec) {
  171. vecValue.push_back(std::atol(vecIt.c_str()));
  172. }
  173. property.set_value(obj, vecValue);
  174. }
  175. else if (type == rttr::type::get<std::vector<bool>>()) {
  176. std::vector<std::string> vec = v3::utils::split(value, ",");
  177. std::vector<bool> vecValue;
  178. for (auto vecIt : vec) {
  179. vecValue.push_back(vecIt == "1" || vecIt == "true" || vecIt == "TRUE" || vecIt == "True");
  180. }
  181. property.set_value(obj, vecValue);
  182. }
  183. else if (type == rttr::type::get<std::vector<std::string>>()) {
  184. std::vector<std::string> vecValue = v3::utils::split(value, ",");
  185. property.set_value(obj, vecValue);
  186. }
  187. else if (type == rttr::type::get<std::vector<v3::datetime>>()) {
  188. std::vector<std::string> vec = v3::utils::split(value, ",");
  189. std::vector<v3::datetime> vecValue;
  190. for (auto vecIt : vec) {
  191. vecValue.push_back(v3::datetime(vecIt));
  192. }
  193. property.set_value(obj, vecValue);
  194. }
  195. }
  196. }
  197. };
  198. class cookie_id {
  199. public:
  200. static std::string get_id() {
  201. static std::string g_cookie_id;
  202. if (g_cookie_id.empty()) {
  203. g_cookie_id = v3::utils::uuid();
  204. }
  205. return g_cookie_id;
  206. }
  207. };
  208. class cookie {
  209. public:
  210. cookie() {
  211. //name = "SessionId";
  212. name = cookie_id::get_id();
  213. value = v3::utils::base64_encode(v3::utils::uuid());
  214. path = "path=/";
  215. time = 30 * 60 * 1000;
  216. last_expire_time = v3::datetime::current_time_stamp() + time;
  217. }
  218. /**
  219. * @brief cookie名称
  220. */
  221. std::string name;
  222. /**
  223. * @brief cookie值
  224. */
  225. std::string value;
  226. /**
  227. * @brief cookie路径
  228. */
  229. std::string path;
  230. /**
  231. * @brief cookie时间
  232. */
  233. time_t time = 0;
  234. /**
  235. * @brief 上次刷新时间
  236. */
  237. time_t last_expire_time = 0;
  238. /**
  239. * @brief 对比
  240. * @param cookie
  241. * @param remove
  242. * @return
  243. */
  244. bool compare(std::shared_ptr<cookie> cookie, bool& remove) {
  245. bool result = false;
  246. remove = false;
  247. if (cookie) {
  248. result = (name == cookie->name && value == cookie->value);
  249. if (result) {
  250. time_t current_time = v3::datetime::current_time_stamp();
  251. if (last_expire_time < current_time) {
  252. remove = true;
  253. result = false;
  254. }
  255. else {
  256. last_expire_time = v3::datetime::current_time_stamp() + time;
  257. }
  258. }
  259. }
  260. return result;
  261. }
  262. };
  263. class cookies {
  264. public:
  265. /**
  266. * @brief 解析
  267. * @param cookie_str
  268. * @return
  269. */
  270. static std::shared_ptr<cookies> analysis(std::string const& cookie_str) {
  271. std::shared_ptr<cookies> result;
  272. std::vector<std::string> cookies_tmp = v3::utils::split(cookie_str, ";");
  273. for (auto& item : cookies_tmp) {
  274. int index = item.find('=');
  275. if (index == std::string::npos)
  276. continue;
  277. std::shared_ptr<cookie> add(new cookie);
  278. add->name = item.substr(0, index);
  279. add->value = item.substr(index + 1);
  280. add->name = v3::utils::trim(add->name);
  281. add->value = v3::utils::trim(add->value);
  282. if (add->name != "path") {
  283. if (!result) {
  284. result.reset(new cookies);
  285. }
  286. result->cookies_.push_back(add);
  287. }
  288. }
  289. return result;
  290. }
  291. /**
  292. * @brief 对比
  293. * @param value
  294. * @return
  295. */
  296. bool compare(std::shared_ptr<cookies> value) {
  297. bool result = false;
  298. if (!value)
  299. return result;
  300. for (auto& value_elem : value->cookies_) {
  301. for (int i = 0; i < cookies_.size(); ++i) {
  302. bool is_remove = false;
  303. bool exist = cookies_[i]->compare(value_elem, is_remove);
  304. if (is_remove) {
  305. cookies_.erase(cookies_.begin() + i);
  306. --i;
  307. continue;
  308. }
  309. if (exist) {
  310. result = true;
  311. }
  312. }
  313. }
  314. return result;
  315. }
  316. /**
  317. * @brief 数量
  318. * @return
  319. */
  320. int count() {
  321. return int(cookies_.size());
  322. }
  323. /**
  324. * @brief 添加
  325. * @param cookie
  326. */
  327. void add(std::shared_ptr<cookie> cookie) {
  328. cookies_.push_back(cookie);
  329. }
  330. private:
  331. std::vector<std::shared_ptr<cookie>> cookies_;
  332. };
  333. struct session {
  334. /**
  335. * @brief 关闭
  336. */
  337. bool close = false;
  338. /**
  339. * @brief
  340. */
  341. bool authen = false;
  342. /**
  343. * @brief
  344. */
  345. std::shared_ptr<cookies> cookies_;
  346. /**
  347. * @brief
  348. */
  349. std::map<std::string, std::any> user_data;
  350. };
  351. class MVC_API sessions {
  352. public:
  353. /**
  354. * @brief
  355. */
  356. static void add_session(std::shared_ptr<session> session) {
  357. std::lock_guard<std::mutex> locker(mutex_);
  358. sessions_.push_back(session);
  359. }
  360. /**
  361. * @brief
  362. */
  363. static std::shared_ptr<session> get_session(std::string const& cookie_str) {
  364. std::shared_ptr<session> result;
  365. std::shared_ptr<cookies> cookies = cookies::analysis(cookie_str);
  366. {
  367. std::lock_guard<std::mutex> locker(mutex_);
  368. for (int i = 0; i < sessions_.size(); ++i) {
  369. if (sessions_[i]->cookies_->compare(cookies) && !sessions_[i]->close) {
  370. result = sessions_[i];
  371. }
  372. else if (sessions_[i]->cookies_->count() <= 0 || sessions_[i]->close) {
  373. sessions_.erase(sessions_.begin() + i);
  374. i--;
  375. }
  376. }
  377. }
  378. return result;
  379. }
  380. private:
  381. static std::vector<std::shared_ptr<session>> sessions_;
  382. static std::mutex mutex_;
  383. };
  384. enum class captcha_type {
  385. /**
  386. * @brief 成功
  387. */
  388. success,
  389. /**
  390. * @brief 失败
  391. */
  392. fail,
  393. /**
  394. * @brief 没有验证码
  395. */
  396. no
  397. };
  398. struct controller_action;
  399. class MVC_API http_context {
  400. public:
  401. class curr {
  402. public:
  403. /**
  404. * @brief 当前context
  405. * @return
  406. */
  407. static std::shared_ptr<http_context> current() {
  408. return http_context::current();
  409. }
  410. /**
  411. * @brief 是否有权限
  412. * @return
  413. */
  414. static bool authen() {
  415. return current()->authen();
  416. }
  417. /**
  418. * @brief 设置权限
  419. * @param value
  420. */
  421. static void set_authen(bool value = true) {
  422. current()->set_authen(value);
  423. }
  424. /**
  425. * @brief 设置session
  426. * @param key
  427. * @param value
  428. */
  429. static void add_session(std::string const& key, std::any const& value) {
  430. current()->add_session(key, value);
  431. }
  432. /**
  433. * @brief 添加session并设置权限
  434. * @param key
  435. * @param value
  436. */
  437. static void add_authen_session(std::string const& key, std::any const& value) {
  438. add_session(key, value);
  439. set_authen();
  440. }
  441. /**
  442. * @brief 获取session
  443. * @param key
  444. * @return
  445. */
  446. static std::any& session(std::string const& key) {
  447. return current()->session(key);
  448. }
  449. /**
  450. * @brief 获取session
  451. * @tparam _Ret
  452. * @param key
  453. * @param succ
  454. * @return
  455. */
  456. template<typename _Ret>
  457. static bool get_session(std::string const& key, _Ret& result) {
  458. std::any any_value = current()->session(key);
  459. if (any_value.type() != typeid(_Ret)) {
  460. return false;
  461. }
  462. result = std::any_cast<_Ret>(any_value);
  463. return true;
  464. }
  465. /**
  466. * @brief 添加cookie
  467. * @param timeout
  468. */
  469. static void add_cookie(int timeout = 30) {
  470. current()->add_cookie(timeout);
  471. }
  472. /**
  473. * @brief 删除cookie
  474. */
  475. static void remove_cookie() {
  476. current()->remove_cookie();
  477. }
  478. /**
  479. * @brief 重置cookie
  480. * @param timeout
  481. */
  482. static void reset_cookie(int timeout = 30) {
  483. remove_cookie();
  484. add_cookie(timeout);
  485. }
  486. /**
  487. * @brief 验证码比较
  488. * @param key
  489. * @param captcha_code
  490. * @return
  491. */
  492. static captcha_type captcha_compare(std::string const& key, std::string const& captcha_code) {
  493. std::string value;
  494. if (!get_session<std::string>(key, value))
  495. return mvc::captcha_type::no;
  496. else if (v3::utils::case_insensitive_compare(value, captcha_code))
  497. return mvc::captcha_type::success;
  498. else
  499. return mvc::captcha_type::fail;
  500. }
  501. /**
  502. * @brief 验证码比较
  503. * @param key
  504. * @param captcha_code
  505. * @param success
  506. * @param message
  507. * @return
  508. */
  509. static bool captcha_compare(std::string const& key, std::string const& captcha_code, bool& success, std::string& message) {
  510. auto result = captcha_compare(key, captcha_code);
  511. if (mvc::captcha_type::no == result) {
  512. success = false;
  513. message = "验证码不存在!";
  514. return false;
  515. }
  516. else if (mvc::captcha_type::fail == result) {
  517. success = false;
  518. message = "验证码错误!";
  519. return false;
  520. }
  521. else {
  522. success = true;
  523. message = "成功!";
  524. return true;
  525. }
  526. }
  527. };
  528. /**
  529. * @brief
  530. */
  531. static void new_curr_http_context(http::web_request& req, http::web_response& rep) {
  532. rep.clear();
  533. new http_context(req, rep);
  534. }
  535. /**
  536. * @brief
  537. */
  538. static void remove_curr_http_context() {
  539. std::lock_guard<std::mutex> locker(mutex_);
  540. http_context_list_.erase(std::this_thread::get_id());
  541. }
  542. /**
  543. * @brief
  544. * @param route
  545. * @return
  546. */
  547. static std::shared_ptr<http_context> current() {
  548. std::lock_guard<std::mutex> locker(mutex_);
  549. return http_context_list_[std::this_thread::get_id()];
  550. }
  551. /**
  552. * @brief
  553. */
  554. bool authen() {
  555. if (current_session_)
  556. return current_session_->authen;
  557. return false;
  558. }
  559. /**
  560. * @brief
  561. */
  562. void set_authen(bool value = true) {
  563. if (current_session_)
  564. current_session_->authen = value;
  565. }
  566. /**
  567. * @brief
  568. */
  569. void add_session(std::string const& key, std::any const& value) {
  570. if (!current_session_)
  571. throw std::runtime_error("not cookie!");
  572. current_session_->user_data[key] = value;
  573. }
  574. /**
  575. * @brief
  576. */
  577. std::any& session(std::string const& key) {
  578. static std::any g_any;
  579. if (current_session_) {
  580. if (current_session_->user_data.find(key) != current_session_->user_data.end()) {
  581. return current_session_->user_data[key];
  582. }
  583. }
  584. g_any = std::any();
  585. return g_any;
  586. }
  587. /**
  588. * @brief
  589. */
  590. void add_cookie(int timeout = 30) {
  591. std::shared_ptr<cookie> item(new cookie);
  592. item->time = timeout * (1000 * 60);
  593. item->last_expire_time = v3::datetime::current_time_stamp() + item->time;
  594. if (current_session_ && !current_session_->close) {
  595. if (!current_session_->cookies_)
  596. current_session_->cookies_.reset(new cookies);
  597. current_session_->cookies_->add(item);
  598. }
  599. else {
  600. current_session_.reset(new mvc::session);
  601. current_session_->cookies_.reset(new cookies);
  602. current_session_->cookies_->add(item);
  603. mvc::sessions::add_session(current_session_);
  604. }
  605. std::string set_cookie_str;
  606. set_cookie_str += item->name;
  607. set_cookie_str += "=";
  608. set_cookie_str += item->value;
  609. set_cookie_str += ";";
  610. set_cookie_str += item->path;
  611. response.set(http::field::set_cookie, set_cookie_str);
  612. }
  613. /**
  614. * @brief
  615. */
  616. void remove_cookie() {
  617. if (current_session_) {
  618. current_session_->close = true;
  619. }
  620. response.set(http::field::set_cookie, "SessionId=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT");
  621. }
  622. /**
  623. * @brief
  624. */
  625. void set_controller_action(std::shared_ptr<controller_action> value) {
  626. controller_action_ = value;
  627. }
  628. /**
  629. * @brief
  630. */
  631. std::shared_ptr<controller_action> get_controller_action() {
  632. return controller_action_;
  633. }
  634. /**
  635. * @brief
  636. */
  637. http::web_request& request;
  638. /**
  639. * @brief
  640. */
  641. http::web_response& response;
  642. /**
  643. * @brief
  644. */
  645. std::filesystem::path root_directory;
  646. private:
  647. http_context(http::web_request& req, http::web_response& rep) :
  648. request(req),
  649. response(rep),
  650. root_directory(rep.get_root_directory()) {
  651. if (req.find(http::field::cookie) != req.end()) {
  652. current_session_ = sessions::get_session(std::string(req.find(http::field::cookie)->value().begin(), req.find(http::field::cookie)->value().end()));
  653. }
  654. std::lock_guard<std::mutex> locker(mutex_);
  655. http_context_list_[std::this_thread::get_id()].reset(this);
  656. }
  657. private:
  658. std::shared_ptr<mvc::session> current_session_;
  659. std::shared_ptr<controller_action> controller_action_;
  660. private:
  661. static std::mutex mutex_;
  662. static std::map<std::thread::id, std::shared_ptr<http_context>> http_context_list_;
  663. };
  664. class http_context_gc {
  665. public:
  666. http_context_gc(http::web_request& req, http::web_response& rep) {
  667. http_context::new_curr_http_context(req, rep);
  668. }
  669. virtual ~http_context_gc() {
  670. http_context::remove_curr_http_context();
  671. }
  672. };
  673. enum class pseudo_type {
  674. NON = 0,
  675. MASK,
  676. MODEL,
  677. FOR,
  678. IF,
  679. SWITCH,
  680. FILE
  681. };
  682. struct class_value {
  683. bool is_list = false;
  684. std::string class_name;
  685. std::vector<std::map<std::string, std::string>> class_value;
  686. };
  687. struct ipseudo_label {
  688. ipseudo_label(std::pair<pseudo_type, std::pair<std::string, std::string>> const& value_type) :
  689. type(value_type.first),
  690. label(value_type.second) {
  691. }
  692. /**
  693. * @brief 类型
  694. */
  695. pseudo_type type;
  696. /**
  697. * @brief 原始代码
  698. */
  699. std::string html_code;
  700. /**
  701. * @brief 临时原始代码
  702. */
  703. std::string html_code_tmp;
  704. /**
  705. * @brief 类名
  706. */
  707. std::string class_name;
  708. /**
  709. * @brief 标签
  710. */
  711. std::pair<std::string, std::string> label;
  712. /**
  713. * @brief 实体类数据列表
  714. */
  715. std::vector<std::map<std::string, std::string>> class_value_list;
  716. /**
  717. * @brief 子标签
  718. */
  719. std::vector<std::shared_ptr<ipseudo_label>> childs;
  720. /**
  721. * @brief 解析返回html
  722. */
  723. virtual std::string analysis() = 0;
  724. /**
  725. * @brief 设置属性值
  726. */
  727. void set_class_value(std::vector<std::shared_ptr<class_value>>const& value) {
  728. for (auto it : childs) {
  729. it->set_class_value(value);
  730. }
  731. for (auto it : value) {
  732. if (class_name != it->class_name)
  733. continue;
  734. if (it->is_list && type == pseudo_type::FOR) {
  735. class_value_list = it->class_value;
  736. break;
  737. }
  738. else if (!it->is_list) {
  739. class_value_list = it->class_value;
  740. break;
  741. }
  742. }
  743. }
  744. /**
  745. * @brief 解析基础信息
  746. */
  747. virtual void analysis_baseinfo() = 0;
  748. protected:
  749. std::string extract(std::string const& value, std::pair<std::string, std::string> const& pair, int& index) {
  750. std::string result;
  751. bool ok = false;
  752. int count = 0;
  753. for (size_t i = 0; i < value.size(); ++i) {
  754. if (i + 1 >= pair.first.size() &&
  755. value[i] == pair.first[pair.first.size() - 1] &&
  756. value.substr(i - pair.first.size() + 1, pair.first.size()) == pair.first) {
  757. count++;
  758. if (count == 1) {
  759. ok = true;
  760. continue;
  761. }
  762. }
  763. if (ok &&
  764. value.size() >= i + pair.second.size() &&
  765. value[i] == pair.second[0] &&
  766. value.substr(i, pair.second.size()) == pair.second) {
  767. count--;
  768. if (count == 0) {
  769. index = i + 1;
  770. return result;
  771. }
  772. }
  773. if (ok) {
  774. result += value[i];
  775. }
  776. }
  777. index = -1;
  778. return result;
  779. }
  780. std::vector<std::string> extractList(std::string const& value, std::pair<std::string, std::string> const& pair) {
  781. std::vector<std::string> result;
  782. int index = 0;
  783. int pos = 0;
  784. while (index > -1) {
  785. pos += index;
  786. std::string ret = extract(value.substr(pos, value.size() - pos), pair, index);
  787. if (index != -1)
  788. result.push_back(ret);
  789. }
  790. return result;
  791. }
  792. };
  793. struct pseudo_mask_label : public ipseudo_label {
  794. pseudo_mask_label(std::pair<pseudo_type, std::pair<std::string, std::string>>const& value_type) :
  795. ipseudo_label(value_type) {
  796. }
  797. std::string mask_name;
  798. virtual std::string analysis()override {
  799. for (auto child : childs) {
  800. std::string childValue = child->analysis();
  801. html_code_tmp = v3::utils::replace(html_code_tmp, child->html_code, childValue);
  802. }
  803. int index = 0;
  804. std::string header = extract(html_code_tmp, { "${mask","}" }, index);
  805. header = "${mask" + header + "}";
  806. std::string tmp = extract(html_code_tmp, { header,"{/mask}" }, index);
  807. return tmp;
  808. }
  809. virtual void analysis_baseinfo() override {
  810. html_code_tmp = html_code;
  811. for (auto child : childs) {
  812. child->analysis_baseinfo();
  813. }
  814. //获取mask名称
  815. int index = 0;
  816. mask_name = extract(html_code, { "name='","'" }, index);
  817. }
  818. };
  819. struct pseudo_model_label : public ipseudo_label {
  820. pseudo_model_label(std::pair<pseudo_type, std::pair<std::string, std::string>>const& value_type) :
  821. ipseudo_label(value_type) {
  822. }
  823. virtual std::string analysis()override {
  824. for (auto child : childs) {
  825. std::string childValue = child->analysis();
  826. html_code_tmp = v3::utils::replace(html_code_tmp, child->html_code, childValue);
  827. }
  828. std::string propName;
  829. std::string propValue;
  830. std::map<std::string, std::string> mapPropValue;
  831. {
  832. int index = 0;
  833. std::string tmp = extract(html_code_tmp, { "name='","'" }, index);
  834. std::string::size_type pos = tmp.find('.');
  835. if (pos != std::string::npos) {
  836. propName = tmp.substr(pos + 1, tmp.size() - pos - 1);
  837. }
  838. }
  839. //获取值
  840. {
  841. int index = 0;
  842. std::string tmp = extract(html_code_tmp.substr(index, html_code_tmp.size() - index), { "value='[","]'" }, index);
  843. //属性值
  844. if (tmp == "#value") {
  845. propValue = tmp;
  846. }
  847. else {
  848. auto values = v3::utils::split(tmp, ",");
  849. for (auto value : values) {
  850. auto valueItem = v3::utils::split(value, ":");
  851. if (valueItem.size() == 2) {
  852. if (valueItem[0].size() >= 2 && valueItem[1].size() >= 2 &&
  853. valueItem[0][0] == '\'' && valueItem[0][valueItem[0].size() - 1] == '\'' &&
  854. valueItem[1][0] == '\'' && valueItem[1][valueItem[1].size() - 1] == '\'') {
  855. valueItem[0].erase(valueItem[0].begin());
  856. valueItem[0].erase(valueItem[0].begin() + valueItem[0].size() - 1);
  857. valueItem[1].erase(valueItem[1].begin());
  858. valueItem[1].erase(valueItem[1].begin() + valueItem[1].size() - 1);
  859. mapPropValue[valueItem[0]] = valueItem[1];
  860. }
  861. }
  862. }
  863. }
  864. }
  865. if (propName.empty()) {
  866. return "";
  867. }
  868. //属性值
  869. if (!propValue.empty() && !class_value_list.empty()) {
  870. if (class_value_list[0].find(propName) != class_value_list[0].end()) {
  871. return class_value_list[0][propName];
  872. }
  873. }
  874. else if (!mapPropValue.empty() && !class_value_list.empty()) {
  875. if (class_value_list[0].find(propName) != class_value_list[0].end()) {
  876. std::string value = class_value_list[0][propName];
  877. //选择值
  878. if (mapPropValue.find(value) != mapPropValue.end()) {
  879. return mapPropValue[value];
  880. }
  881. //默认值
  882. else if (mapPropValue.find("default") != mapPropValue.end()) {
  883. if (mapPropValue["default"] == "#value") {
  884. return class_value_list[0][propName];
  885. }
  886. else {
  887. return mapPropValue["default"];
  888. }
  889. }
  890. }
  891. }
  892. return "";
  893. }
  894. virtual void analysis_baseinfo() override {
  895. html_code_tmp = html_code;
  896. for (auto child : childs) {
  897. child->analysis_baseinfo();
  898. }
  899. //获取类名属性名
  900. int index = 0;
  901. std::string tmp = extract(html_code, { "name='","'" }, index);
  902. std::string::size_type pos = tmp.find('.');
  903. if (pos != std::string::npos) {
  904. class_name = tmp.substr(0, pos);
  905. }
  906. }
  907. };
  908. struct pseudo_for_label : public ipseudo_label {
  909. pseudo_for_label(std::pair<pseudo_type, std::pair<std::string, std::string>> const& value_type) :
  910. ipseudo_label(value_type) {
  911. }
  912. virtual std::string analysis()override {
  913. for (auto child : childs) {
  914. std::string childValue = child->analysis();
  915. html_code_tmp = v3::utils::replace(html_code_tmp, child->html_code, childValue);
  916. }
  917. std::string resultValue;
  918. std::string itemName;
  919. std::string forLabel;
  920. std::vector<std::string> forItemLabelList;
  921. std::map<std::string, std::map<std::string, std::map<std::string, std::string>>> forItemLabelValueList;
  922. //获取ITEM名称
  923. {
  924. int index = 0;
  925. itemName = extract(html_code_tmp, { "item='","'" }, index);
  926. if (itemName.empty())
  927. return "";
  928. }
  929. //提取for标签值
  930. {
  931. int index = 0;
  932. std::string header = extract(html_code_tmp, { "${for","}" }, index);
  933. header = "${for" + header + "}";
  934. forLabel = extract(html_code_tmp, { header,"{/for}" }, index);
  935. }
  936. //提取foritem标签
  937. {
  938. forItemLabelList = extractList(forLabel, { "{item","/}" });
  939. for (auto& it : forItemLabelList) {
  940. it = "{item" + it + "/}";
  941. }
  942. if (forItemLabelList.empty())
  943. return forLabel;
  944. }
  945. //提取foritem参数
  946. {
  947. int index = 0;
  948. std::string header = "name='" + itemName + ".";
  949. for (auto it : forItemLabelList) {
  950. std::string propName = extract(it, { header,"'" }, index);
  951. if (propName.empty())
  952. continue;
  953. std::string value = extract(it, { "value='[","]'" }, index);
  954. if (value.empty())
  955. continue;
  956. if (value == "#value") {
  957. forItemLabelValueList[it][propName][value] = value;
  958. }
  959. else {
  960. auto values = v3::utils::split(value, ",");
  961. for (auto valueIt : values) {
  962. auto valueItem = v3::utils::split(valueIt, "':'");
  963. if (valueItem.size() == 2) {
  964. valueItem[0] += "'";
  965. valueItem[1] = "'" + valueItem[1];
  966. if (valueItem[0].size() >= 2 && valueItem[1].size() >= 2 &&
  967. valueItem[0][0] == '\'' && valueItem[0][valueItem[0].size() - 1] == '\'' &&
  968. valueItem[1][0] == '\'' && valueItem[1][valueItem[1].size() - 1] == '\'') {
  969. valueItem[0].erase(valueItem[0].begin());
  970. valueItem[0].erase(valueItem[0].begin() + valueItem[0].size() - 1);
  971. valueItem[1].erase(valueItem[1].begin());
  972. valueItem[1].erase(valueItem[1].begin() + valueItem[1].size() - 1);
  973. forItemLabelValueList[it][propName][valueItem[0]] = valueItem[1];
  974. }
  975. }
  976. }
  977. }
  978. }
  979. }
  980. //遍历值
  981. {
  982. int index = 0;
  983. for (auto item : class_value_list) {
  984. index++;
  985. std::string itemValue = forLabel;
  986. for (auto forItem : forItemLabelList) {
  987. //没有查找到值赋值为空
  988. if (forItemLabelValueList.find(forItem) == forItemLabelValueList.end()) {
  989. itemValue = v3::utils::replace(itemValue, forItem, "");
  990. continue;
  991. }
  992. //查找属性
  993. if (forItemLabelValueList[forItem].find("for-index") != forItemLabelValueList[forItem].end()) {
  994. //默认值
  995. if (forItemLabelValueList[forItem]["for-index"].find("#value") != forItemLabelValueList[forItem]["for-index"].end()) {
  996. itemValue = v3::utils::replace(itemValue, forItem, std::to_string(index));
  997. }
  998. else {
  999. if (forItemLabelValueList[forItem]["for-index"].find(std::to_string(index)) != forItemLabelValueList[forItem]["for-index"].end()) {
  1000. itemValue = v3::utils::replace(itemValue, forItem, forItemLabelValueList[forItem]["for-index"][std::to_string(index)]);
  1001. }
  1002. else if (forItemLabelValueList[forItem]["for-index"].find("default") != forItemLabelValueList[forItem]["for-index"].end()) {
  1003. itemValue = v3::utils::replace(itemValue, forItem, forItemLabelValueList[forItem]["for-index"]["default"]);
  1004. }
  1005. else {
  1006. itemValue = v3::utils::replace(itemValue, forItem, "");
  1007. }
  1008. }
  1009. continue;
  1010. }
  1011. else {
  1012. std::string propNameItem;
  1013. std::map<std::string, std::string> propValueItem;
  1014. auto childItem = forItemLabelValueList[forItem];
  1015. for (auto childItemIt : childItem) {
  1016. propNameItem = childItemIt.first;
  1017. propValueItem = childItemIt.second;
  1018. }
  1019. if (propNameItem.empty()) {
  1020. itemValue = v3::utils::replace(itemValue, forItem, "");
  1021. continue;
  1022. }
  1023. if (item.find(propNameItem) != item.end()) {
  1024. if (item.find(propNameItem) != item.end()) {
  1025. if (propValueItem.find("#value") != propValueItem.end()) {
  1026. itemValue = v3::utils::replace(itemValue, forItem, item[propNameItem]);
  1027. }
  1028. else if (propValueItem.find(item[propNameItem]) != propValueItem.end()) {
  1029. itemValue = v3::utils::replace(itemValue, forItem, propValueItem[item[propNameItem]]);
  1030. }
  1031. else if (propValueItem.find("default") != propValueItem.end()) {
  1032. if (propValueItem["default"] == "#value") {
  1033. itemValue = v3::utils::replace(itemValue, forItem, item[propNameItem]);
  1034. }
  1035. else {
  1036. itemValue = v3::utils::replace(itemValue, forItem, propValueItem["default"]);
  1037. }
  1038. }
  1039. else {
  1040. itemValue = v3::utils::replace(itemValue, forItem, "");
  1041. }
  1042. }
  1043. else {
  1044. itemValue = v3::utils::replace(itemValue, forItem, "");
  1045. }
  1046. }
  1047. else {
  1048. itemValue = v3::utils::replace(itemValue, forItem, "");
  1049. }
  1050. }
  1051. }
  1052. resultValue += itemValue;
  1053. }
  1054. }
  1055. return resultValue;
  1056. }
  1057. virtual void analysis_baseinfo() override {
  1058. html_code_tmp = html_code;
  1059. for (auto child : childs) {
  1060. child->analysis_baseinfo();
  1061. }
  1062. //获取类名属性名
  1063. int index = 0;
  1064. class_name = extract(html_code, { "list='","'" }, index);
  1065. }
  1066. };
  1067. struct pseudo_if_label : public ipseudo_label {
  1068. pseudo_if_label(std::pair<pseudo_type, std::pair<std::string, std::string>> const& value_type) :
  1069. ipseudo_label(value_type) {
  1070. }
  1071. virtual std::string analysis()override {
  1072. for (auto child : childs) {
  1073. std::string childValue = child->analysis();
  1074. html_code_tmp = v3::utils::replace(html_code_tmp, child->html_code, childValue);
  1075. }
  1076. std::string propName;
  1077. std::string propValue;
  1078. std::string symbol;
  1079. std::vector<std::string> labelValue;
  1080. //提取标签内容
  1081. {
  1082. labelValue = extractList(html_code_tmp, { "}","{" });
  1083. if (labelValue.empty())
  1084. return "";
  1085. }
  1086. //判断结构体是否有值
  1087. {
  1088. if (class_value_list.empty()) {
  1089. if (labelValue.size() == 2) {
  1090. return labelValue[1];
  1091. }
  1092. return "";
  1093. }
  1094. }
  1095. //获取类名属性名
  1096. {
  1097. int index = 0;
  1098. std::string tmp = extract(html_code_tmp, { "name='","'" }, index);
  1099. std::string::size_type pos = tmp.find('.');
  1100. if (pos != std::string::npos) {
  1101. propName = tmp.substr(pos + 1, tmp.size() - pos - 1);
  1102. }
  1103. }
  1104. //判断类名
  1105. {
  1106. if (propName.empty()) {
  1107. if (labelValue.size() == 2) {
  1108. return labelValue[1];
  1109. }
  1110. return "";
  1111. }
  1112. }
  1113. //判断属性名称是否存在
  1114. {
  1115. if (class_value_list[0].find(propName) == class_value_list[0].end()) {
  1116. if (labelValue.size() == 2) {
  1117. return labelValue[1];
  1118. }
  1119. return "";
  1120. }
  1121. }
  1122. //提取操作符 逻辑对比值
  1123. {
  1124. int index = 0;
  1125. propValue = extract(html_code_tmp, { "value=='","'" }, index);
  1126. //==
  1127. if (propValue.empty()) {
  1128. propValue = extract(html_code_tmp, { "value!='","'" }, index);
  1129. //!=
  1130. if (propValue.empty()) {
  1131. propValue = extract(html_code_tmp, { "value>='","'" }, index);
  1132. //>=
  1133. if (propValue.empty()) {
  1134. propValue = extract(html_code_tmp, { "value<='","'" }, index);
  1135. //<=
  1136. if (propValue.empty()) {
  1137. if (labelValue.size() == 2) {
  1138. return labelValue[1];
  1139. }
  1140. return "";
  1141. }
  1142. else
  1143. symbol = "<=";
  1144. }
  1145. else
  1146. symbol = ">=";
  1147. }
  1148. else
  1149. symbol = "!=";
  1150. }
  1151. else
  1152. symbol = "==";
  1153. }
  1154. //判断
  1155. {
  1156. if (symbol == "==" && propValue.compare(class_value_list[0][propName]) == 0) {
  1157. return labelValue[0];
  1158. }
  1159. else if (symbol == "!=" && propValue.compare(class_value_list[0][propName]) != 0) {
  1160. return labelValue[0];
  1161. }
  1162. else if (symbol == ">=" && propValue.compare(class_value_list[0][propName]) >= 0) {
  1163. return labelValue[0];
  1164. }
  1165. else if (symbol == "<=" && propValue.compare(class_value_list[0][propName]) <= 0) {
  1166. return labelValue[0];
  1167. }
  1168. else {
  1169. if (labelValue.size() == 2)
  1170. return labelValue[1];
  1171. }
  1172. }
  1173. return "";
  1174. }
  1175. virtual void analysis_baseinfo() override {
  1176. html_code_tmp = html_code;
  1177. for (auto child : childs) {
  1178. child->analysis_baseinfo();
  1179. }
  1180. //获取类名属性名
  1181. int index = 0;
  1182. std::string tmp = extract(html_code, { "name='","'" }, index);
  1183. std::string::size_type pos = tmp.find('.');
  1184. if (pos != std::string::npos) {
  1185. class_name = tmp.substr(0, pos);
  1186. }
  1187. }
  1188. };
  1189. struct pseudo_switch_label : public ipseudo_label {
  1190. pseudo_switch_label(std::pair<pseudo_type, std::pair<std::string, std::string>> const& value_type) :
  1191. ipseudo_label(value_type) {
  1192. }
  1193. virtual std::string analysis()override {
  1194. for (auto child : childs) {
  1195. std::string childValue = child->analysis();
  1196. html_code_tmp = v3::utils::replace(html_code_tmp, child->html_code, childValue);
  1197. }
  1198. std::string propName;
  1199. std::string labelValueDefault;
  1200. std::vector<std::string> labelValue;
  1201. //获取类名属性名
  1202. {
  1203. int index = 0;
  1204. std::string tmp = extract(html_code_tmp, { "name='","'" }, index);
  1205. std::string::size_type pos = tmp.find('.');
  1206. if (pos != std::string::npos) {
  1207. propName = tmp.substr(pos + 1, tmp.size() - pos - 1);
  1208. }
  1209. }
  1210. //提取标签内容
  1211. {
  1212. int index = 0;
  1213. labelValue = extractList(html_code_tmp, { "{case","/case}" });
  1214. labelValueDefault = extract(html_code_tmp, { "{default}","{/default}" }, index);
  1215. if (labelValue.empty() && labelValueDefault.empty()) {
  1216. return "";
  1217. }
  1218. else if (labelValue.empty() && !labelValueDefault.empty()) {
  1219. if (labelValueDefault.find("#value") != std::string::npos) {
  1220. if (class_value_list.empty())
  1221. return "";
  1222. if (propName.empty())
  1223. return "";
  1224. if (class_value_list[0].find(propName) == class_value_list[0].end())
  1225. return "";
  1226. return class_value_list[0][propName];
  1227. }
  1228. return labelValueDefault;
  1229. }
  1230. }
  1231. //判断属性值
  1232. {
  1233. if (class_value_list.empty()) {
  1234. if (labelValueDefault.empty())
  1235. return "";
  1236. if (labelValueDefault.find("#value") != std::string::npos)
  1237. return "";
  1238. return labelValueDefault;
  1239. }
  1240. if (propName.empty()) {
  1241. if (labelValueDefault.empty())
  1242. return "";
  1243. if (labelValueDefault.find("#value") != std::string::npos)
  1244. return "";
  1245. return labelValueDefault;
  1246. }
  1247. if (class_value_list[0].find(propName) == class_value_list[0].end()) {
  1248. if (labelValueDefault.empty())
  1249. return "";
  1250. if (labelValueDefault.find("#value") != std::string::npos)
  1251. return "";
  1252. return labelValueDefault;
  1253. }
  1254. }
  1255. //遍历值
  1256. {
  1257. for (auto it : labelValue) {
  1258. int index = 0;
  1259. std::string propValue = extract(it, { "value='","'" }, index);
  1260. if (class_value_list[0][propName] == propValue) {
  1261. return extract(it, { "}","{" }, index);
  1262. }
  1263. }
  1264. }
  1265. //判断默认值
  1266. {
  1267. if (labelValueDefault.empty())
  1268. return "";
  1269. if (labelValueDefault.find("#value") != std::string::npos) {
  1270. return v3::utils::replace(labelValueDefault, "#value", class_value_list[0][propName]);
  1271. }
  1272. return labelValueDefault;
  1273. }
  1274. }
  1275. virtual void analysis_baseinfo() override {
  1276. html_code_tmp = html_code;
  1277. for (auto child : childs) {
  1278. child->analysis_baseinfo();
  1279. }
  1280. //获取类名属性名
  1281. int index = 0;
  1282. std::string tmp = extract(html_code, { "name='","'" }, index);
  1283. std::string::size_type pos = tmp.find('.');
  1284. if (pos != std::string::npos) {
  1285. class_name = tmp.substr(0, pos);
  1286. }
  1287. }
  1288. };
  1289. struct pseudo_file_label : public ipseudo_label {
  1290. pseudo_file_label(std::pair<pseudo_type, std::pair<std::string, std::string>> const& value_type) :
  1291. ipseudo_label(value_type) {
  1292. }
  1293. virtual std::string analysis()override {
  1294. for (auto child : childs) {
  1295. std::string childValue = child->analysis();
  1296. html_code_tmp = v3::utils::replace(html_code_tmp, child->html_code, childValue);
  1297. }
  1298. int index = 0;
  1299. std::string path_tmp = extract(html_code_tmp, { "path='","'" }, index);
  1300. std::filesystem::path path = path_tmp;
  1301. std::filesystem::path filepath;
  1302. filepath = http_context::current()->response.get_root_directory();
  1303. filepath.make_preferred();
  1304. filepath /= path.make_preferred().relative_path();
  1305. if (filepath.empty())
  1306. return "";
  1307. if (std::filesystem::exists(filepath)) {
  1308. std::ifstream file(filepath, std::ios::in);
  1309. if (file.is_open()) {
  1310. return std::string((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  1311. }
  1312. }
  1313. return "";
  1314. }
  1315. virtual void analysis_baseinfo() override {
  1316. html_code_tmp = html_code;
  1317. for (auto child : childs) {
  1318. child->analysis_baseinfo();
  1319. }
  1320. }
  1321. };
  1322. struct pseudo_extract_class_value {
  1323. template<typename ..._Args>
  1324. static std::vector<std::shared_ptr<class_value>> get_class_value(_Args&&...args) {
  1325. std::vector<std::shared_ptr<class_value>> result;
  1326. auto tuple = std::forward_as_tuple(std::forward<_Args>(args)...);
  1327. v3::utils::for_each(tuple, [&](auto& it) {
  1328. auto value = serialize(it);
  1329. result.push_back(value); });
  1330. return result;
  1331. }
  1332. private:
  1333. static std::string get_prop_value(rttr::variant const& value) {
  1334. std::string result;
  1335. if (value.get_type() == rttr::type::get<int>()) {
  1336. result = std::to_string(value.get_value<int>());
  1337. }
  1338. else if (value.get_type() == rttr::type::get<std::int64_t>()) {
  1339. result = std::to_string(value.get_value<std::int64_t>());
  1340. }
  1341. else if (value.get_type() == rttr::type::get<float>()) {
  1342. result = v3::utils::format("{:.2f}", value.get_value<float>());
  1343. }
  1344. else if (value.get_type() == rttr::type::get<double>()) {
  1345. result = v3::utils::format("{:.2f}", value.get_value<double>());
  1346. }
  1347. else if (value.get_type() == rttr::type::get<long>()) {
  1348. result = std::to_string(value.get_value<long>());
  1349. }
  1350. else if (value.get_type() == rttr::type::get<bool>()) {
  1351. if (value.get_value<bool>())
  1352. result = "true";
  1353. else
  1354. result = "false";
  1355. }
  1356. else if (value.get_type() == rttr::type::get<std::string>()) {
  1357. result = value.get_value<std::string>();
  1358. }
  1359. else if (value.get_type() == rttr::type::get<v3::datetime>()) {
  1360. auto t = value.get_value<v3::datetime>();
  1361. result = t.to_string();
  1362. }
  1363. else if (value.get_type() == rttr::type::get<std::vector<int>>()) {
  1364. auto values = value.get_value<std::vector<int>>();
  1365. for (int i = 0; i < values.size(); ++i) {
  1366. if (i + 1 == values.size()) {
  1367. result += std::to_string(values[i]);
  1368. }
  1369. else {
  1370. result += std::to_string(values[i]) + ",";
  1371. }
  1372. }
  1373. }
  1374. else if (value.get_type() == rttr::type::get<std::vector<std::int64_t>>()) {
  1375. auto values = value.get_value<std::vector<std::int64_t>>();
  1376. for (int i = 0; i < values.size(); ++i) {
  1377. if (i + 1 == values.size()) {
  1378. result += std::to_string(values[i]);
  1379. }
  1380. else {
  1381. result += std::to_string(values[i]) + ",";
  1382. }
  1383. }
  1384. }
  1385. else if (value.get_type() == rttr::type::get<std::vector<float>>()) {
  1386. auto values = value.get_value<std::vector<float>>();
  1387. for (int i = 0; i < values.size(); ++i) {
  1388. if (i + 1 == values.size()) {
  1389. result += v3::utils::format("{:.2f}", values[i]);
  1390. }
  1391. else {
  1392. result += v3::utils::format("{:.2f}", values[i]) + ",";
  1393. }
  1394. }
  1395. }
  1396. else if (value.get_type() == rttr::type::get<std::vector<double>>()) {
  1397. auto values = value.get_value<std::vector<double>>();
  1398. for (int i = 0; i < values.size(); ++i) {
  1399. if (i + 1 == values.size()) {
  1400. result += v3::utils::format("{:.2f}", values[i]);
  1401. }
  1402. else {
  1403. result += v3::utils::format("{:.2f}", values[i]) + ",";
  1404. }
  1405. }
  1406. }
  1407. else if (value.get_type() == rttr::type::get<std::vector<long>>()) {
  1408. auto values = value.get_value<std::vector<long>>();
  1409. for (int i = 0; i < values.size(); ++i) {
  1410. if (i + 1 == values.size()) {
  1411. result += std::to_string(values[i]);
  1412. }
  1413. else {
  1414. result += std::to_string(values[i]) + ",";
  1415. }
  1416. }
  1417. }
  1418. else if (value.get_type() == rttr::type::get<std::vector<bool>>()) {
  1419. auto values = value.get_value<std::vector<bool>>();
  1420. for (int i = 0; i < values.size(); ++i) {
  1421. if (i + 1 == values.size()) {
  1422. result += values[i] ? "true" : "false";
  1423. }
  1424. else {
  1425. result += values[i] ? "true," : "false,";
  1426. }
  1427. }
  1428. }
  1429. else if (value.get_type() == rttr::type::get<std::vector<std::string>>()) {
  1430. auto values = value.get_value<std::vector<std::string>>();
  1431. for (int i = 0; i < values.size(); ++i) {
  1432. if (i + 1 == values.size()) {
  1433. result += values[i];
  1434. }
  1435. else {
  1436. result += values[i] + ",";
  1437. }
  1438. }
  1439. }
  1440. else if (value.get_type() == rttr::type::get<std::vector<v3::datetime>>()) {
  1441. auto values = value.get_value<std::vector<v3::datetime>>();
  1442. for (int i = 0; i < values.size(); ++i) {
  1443. if (i + 1 == values.size()) {
  1444. result += values[i].to_string();
  1445. }
  1446. else {
  1447. result += values[i].to_string() + ",";
  1448. }
  1449. }
  1450. }
  1451. return result;
  1452. }
  1453. template<typename _Type>
  1454. static std::shared_ptr<class_value> serialize(std::vector<std::shared_ptr<_Type>> const& values) {
  1455. std::vector<_Type> valueTmp;
  1456. for (auto it : values) {
  1457. valueTmp.push_back(*it);
  1458. }
  1459. return serialize(valueTmp);
  1460. }
  1461. template<typename _Type>
  1462. static std::shared_ptr<class_value> serialize(std::vector<_Type*> values) {
  1463. std::vector<_Type> valueTmp;
  1464. for (auto it : values) {
  1465. valueTmp.push_back(*it);
  1466. }
  1467. return serialize(valueTmp);
  1468. }
  1469. template<typename _Type>
  1470. static std::shared_ptr<class_value> serialize(std::vector<_Type> values) {
  1471. std::shared_ptr<class_value> result(new class_value);
  1472. rttr::type type = rttr::type::get<_Type>();
  1473. std::string className(type.get_name());
  1474. result->class_name = className;
  1475. result->is_list = true;
  1476. for (auto it : values) {
  1477. std::map<std::string, std::string> elem = web_reflect::get_object_value(it);
  1478. result->class_value.push_back(elem);
  1479. }
  1480. return result;
  1481. }
  1482. template<typename _Type>
  1483. static std::shared_ptr<class_value> serialize(std::shared_ptr<_Type> value) {
  1484. return serialize(*value);
  1485. }
  1486. template<typename _Type>
  1487. static std::shared_ptr<class_value> serialize(_Type* value) {
  1488. return serialize(*value);
  1489. }
  1490. template<typename _Type>
  1491. static std::shared_ptr<class_value> serialize(_Type value) {
  1492. std::shared_ptr<class_value> result(new class_value);
  1493. rttr::type type = rttr::type::get<_Type>();
  1494. std::string className(type.get_name());
  1495. result->class_name = className;
  1496. result->is_list = false;
  1497. std::map<std::string, std::string> elem = web_reflect::get_object_value(value);
  1498. result->class_value.push_back(elem);
  1499. return result;
  1500. }
  1501. };
  1502. struct pseudo_extract_label_value {
  1503. /*
  1504. * 伪代码结构
  1505. * 可嵌套 避开关键字 [' }]
  1506. * ${model name='test_info.userName' value='['${model name='test_info.id' value='[#value]'/}':'启用','false':'禁用'/}
  1507. *
  1508. * switch case 中不能存在 #value 属性值 default可以有默认值 可以有固定值
  1509. * ${switch name='test_info.id'}{case value='1'}<h1>值1</h1>{/case}...{default}<h1>#value</h1>{/default}{/switch}
  1510. *
  1511. * if 运算符 == != >= <=
  1512. * ${if name='test_info.id' value=='100'}<p>判断正确</p>{else}<p>判断错误</p>{/if}
  1513. *
  1514. * for for-index 从1开始
  1515. * ${for item='item' list='test_info'} <td>{item name='item.for-index' value='[#value]'/}</td><td>{item name='item.enable' value='['true':'启用','default':'#value']'/}</td>{/for}
  1516. *
  1517. * file path 可以固定 可以嵌套 model设置html路径
  1518. * ${file path='C:/Users/86158/Desktop/404.html'/}
  1519. */
  1520. static std::vector<std::shared_ptr<ipseudo_label>> analysis(std::string const& html) {
  1521. std::vector<std::shared_ptr<ipseudo_label>> result;
  1522. std::pair<std::string, std::string> type = { "${mask","{/mask}" };
  1523. for (size_t i = 0; i < html.size(); ++i) {
  1524. if (html.size() > i + type.first.size() &&
  1525. html[i] == type.first[0] &&
  1526. html.substr(i, type.first.size()) == type.first) {
  1527. std::string retHtml = nounanalysis(html.substr(i, html.size() - i), result);
  1528. result[result.size() - 1]->html_code;
  1529. i += retHtml.size();
  1530. }
  1531. }
  1532. for (auto it : result) {
  1533. it->analysis_baseinfo();
  1534. }
  1535. return result;
  1536. }
  1537. private:
  1538. static std::string nounanalysis(std::string const& html, std::vector<std::shared_ptr<ipseudo_label>>& childs, pseudo_type type = pseudo_type::MASK) {
  1539. static std::map<pseudo_type, std::pair<std::string, std::string>> g_pseudoLabel = {
  1540. {
  1541. pseudo_type::MASK,
  1542. {"${mask","{/mask}"}
  1543. },
  1544. {
  1545. pseudo_type::MODEL,
  1546. {"${model","/}"}
  1547. },
  1548. {
  1549. pseudo_type::SWITCH,
  1550. {"${switch","{/switch}"}
  1551. },
  1552. {
  1553. pseudo_type::IF,
  1554. {"${if","{/if}"}
  1555. },
  1556. {
  1557. pseudo_type::FOR,
  1558. {"${for","{/for}"}
  1559. },
  1560. {
  1561. pseudo_type::FILE,
  1562. {"${file","/}"}
  1563. }
  1564. };
  1565. if (!(html.size() > g_pseudoLabel[type].first.size() &&
  1566. html.substr(0, g_pseudoLabel[type].first.size()) == g_pseudoLabel[type].first)) {
  1567. return "";
  1568. }
  1569. if (type == pseudo_type::MASK)
  1570. childs.push_back(std::make_shared<pseudo_mask_label>(*g_pseudoLabel.find(type)));
  1571. else if (type == pseudo_type::MODEL)
  1572. childs.push_back(std::make_shared<pseudo_model_label>(*g_pseudoLabel.find(type)));
  1573. else if (type == pseudo_type::FOR)
  1574. childs.push_back(std::make_shared<pseudo_for_label>(*g_pseudoLabel.find(type)));
  1575. else if (type == pseudo_type::IF)
  1576. childs.push_back(std::make_shared<pseudo_if_label>(*g_pseudoLabel.find(type)));
  1577. else if (type == pseudo_type::SWITCH)
  1578. childs.push_back(std::make_shared<pseudo_switch_label>(*g_pseudoLabel.find(type)));
  1579. else if (type == pseudo_type::FILE)
  1580. childs.push_back(std::make_shared<pseudo_file_label>(*g_pseudoLabel.find(type)));
  1581. for (std::string::size_type i = 0; i < html.size(); ++i) {
  1582. for (auto pseudo : g_pseudoLabel) {
  1583. if (html.size() > i + pseudo.second.first.size() &&
  1584. html[i] == pseudo.second.first[0] &&
  1585. html.substr(i, pseudo.second.first.size()) == pseudo.second.first) {
  1586. if (i == 0) {
  1587. break;
  1588. }
  1589. else {
  1590. std::string retHtml = nounanalysis(html.substr(i, html.size() - i), childs[childs.size() - 1]->childs, pseudo.first);
  1591. childs[childs.size() - 1]->html_code += retHtml;
  1592. i += retHtml.size();
  1593. }
  1594. }
  1595. }
  1596. if (type != pseudo_type::NON) {
  1597. childs[childs.size() - 1]->html_code += html[i];
  1598. }
  1599. if (childs[childs.size() - 1]->html_code.size() > g_pseudoLabel[type].second.size() &&
  1600. childs[childs.size() - 1]->html_code.substr(childs[childs.size() - 1]->html_code.size() - g_pseudoLabel[type].second.size(), g_pseudoLabel[type].second.size()) == g_pseudoLabel[type].second) {
  1601. return childs[childs.size() - 1]->html_code;
  1602. }
  1603. }
  1604. return "";
  1605. }
  1606. };
  1607. enum class from_storage_type {
  1608. /**
  1609. * @brief body
  1610. */
  1611. BODY = 0,
  1612. /**
  1613. * @brief url
  1614. */
  1615. QUERY,
  1616. /**
  1617. * @brief header
  1618. */
  1619. HEADER,
  1620. /**
  1621. * @brief url
  1622. */
  1623. URL
  1624. };
  1625. enum class argument_type {
  1626. Json = 0,
  1627. Multipart,
  1628. Int,
  1629. Int64,
  1630. Float,
  1631. Double,
  1632. Long,
  1633. Bool_,
  1634. String,
  1635. DateTime,
  1636. Binary,
  1637. VecJson,
  1638. VecInt,
  1639. VecInt64,
  1640. VecFloat,
  1641. VecDouble,
  1642. VecLong,
  1643. VecBool,
  1644. VecString,
  1645. VecDateTime
  1646. };
  1647. enum class http_method {
  1648. /**
  1649. * @brief get
  1650. */
  1651. GET = 0,
  1652. /**
  1653. * @brief post
  1654. */
  1655. POST = 1
  1656. };
  1657. struct multipart {
  1658. std::string content_disposition;
  1659. std::string name;
  1660. std::vector<std::uint8_t> data;
  1661. std::string value;
  1662. std::string content_type;
  1663. std::string filename;
  1664. std::string content_transfer_encoding;
  1665. };
  1666. struct multipart_value {
  1667. std::vector<multipart> data;
  1668. template<typename _Type>
  1669. _Type value() {
  1670. _Type result;
  1671. std::map<std::string, std::string> elem;
  1672. for (auto value : data) {
  1673. elem[value.name] = value.value;
  1674. }
  1675. web_reflect::set_object_value(result, elem);
  1676. return result;
  1677. }
  1678. };
  1679. struct action_argument {
  1680. void parameter(http::web_request& request, const rttr::parameter_info& type) {
  1681. parameter_value_.clear();
  1682. switch (from_storage_type_) {
  1683. case from_storage_type::HEADER: analysis_header(request, type); return;
  1684. case from_storage_type::QUERY: analysis_query(request, type); return;
  1685. case from_storage_type::BODY: analysis_body(request, type); return;
  1686. case from_storage_type::URL: analysis_url(request, type); return;
  1687. }
  1688. throw std::runtime_error("FormStorageType:错误!");
  1689. }
  1690. /**
  1691. * @brief 参数名称
  1692. */
  1693. std::string parameter_name_;
  1694. /**
  1695. * @brief 参数
  1696. */
  1697. rttr::variant parameter_value_;
  1698. /**
  1699. * @brief 数据类型
  1700. */
  1701. argument_type argument_type_ = argument_type::Binary;
  1702. /**
  1703. * @brief 表单存储类型
  1704. */
  1705. from_storage_type from_storage_type_ = from_storage_type::QUERY;
  1706. private:
  1707. /**
  1708. * @brief 解析协议头
  1709. * @param request
  1710. * @param type
  1711. */
  1712. void analysis_header(http::web_request& request, const rttr::parameter_info& type) {
  1713. std::map<std::string, std::string> headers;
  1714. for (auto& it : request) {
  1715. std::string name(it.name_string().begin(), it.name_string().end());
  1716. std::string value(it.value().begin(), it.value().end());
  1717. headers[name] = value;
  1718. }
  1719. if (headers.find(parameter_name_) == headers.end())
  1720. throw std::runtime_error("解析协议头参数错误!");
  1721. convert(headers[parameter_name_], type);
  1722. }
  1723. /**
  1724. * @brief 解析url参数
  1725. * @param request
  1726. * @param type
  1727. */
  1728. void analysis_query(http::web_request& request, const rttr::parameter_info& type) {
  1729. std::string query(request.query().begin(), request.query().end());
  1730. std::map<std::string, std::string> querys = v3::utils::split_http_form(query);
  1731. if (querys.find(parameter_name_) == querys.end())
  1732. throw std::runtime_error("解析Query参数错误!");
  1733. convert(querys[parameter_name_], type);
  1734. }
  1735. /**
  1736. * @brief 解析BODY
  1737. * @param request
  1738. * @param type
  1739. */
  1740. void analysis_body(http::web_request& request, const rttr::parameter_info& type) {
  1741. if (type.get_type() == rttr::type::get<multipart_value>()) {
  1742. multipart_value parameter;
  1743. auto multipartValue = request.get_multipart();
  1744. for (auto it = multipartValue.begin(); it != multipartValue.end(); ++it) {
  1745. multipart item;
  1746. item.content_disposition = it->content_disposition();
  1747. item.name = it->name();
  1748. auto valueTmp = it->value();
  1749. item.data.insert(item.data.end(), valueTmp.begin(), valueTmp.end());
  1750. if (it->filename().empty()) {
  1751. try {
  1752. item.value = it->value();
  1753. }
  1754. catch (...) {}
  1755. }
  1756. item.content_type = it->content_type();
  1757. item.filename = it->filename();
  1758. item.content_transfer_encoding = it->content_transfer_encoding();
  1759. parameter.data.push_back(item);
  1760. }
  1761. parameter_value_ = parameter;
  1762. }
  1763. else if (parameter_name_.empty()) {
  1764. convert(std::string(request.body().begin(), request.body().end()), type);
  1765. }
  1766. else {
  1767. std::string body(request.body().begin(), request.body().end());
  1768. std::map<std::string, std::string> bodys = v3::utils::split_http_form(body);
  1769. if (bodys.find(parameter_name_) == bodys.end())
  1770. throw std::runtime_error("解析Body参数错误!");
  1771. convert(bodys[parameter_name_], type);
  1772. }
  1773. }
  1774. /**
  1775. * @brief url
  1776. * @param request
  1777. * @param type
  1778. */
  1779. void analysis_url(http::web_request& request, const rttr::parameter_info& type) {
  1780. std::string query(request.find("http_route_parameter")->value());
  1781. std::map<std::string, std::string> querys = v3::utils::split_http_form(query);
  1782. if (querys.find(parameter_name_) == querys.end())
  1783. throw std::runtime_error("解析Query参数错误!");
  1784. convert(querys[parameter_name_], type);
  1785. }
  1786. /**
  1787. * @brief 数据转换
  1788. * @param data
  1789. * @param type
  1790. */
  1791. void convert(std::string_view data, const rttr::parameter_info& type) {
  1792. try {
  1793. switch (argument_type_) {
  1794. case argument_type::Json: {
  1795. parameter_value_ = type.get_type().create();
  1796. v3::json_convert::deserialize(std::string(data.begin(), data.end()), parameter_value_);
  1797. return;
  1798. }
  1799. case argument_type::Multipart: {
  1800. return;
  1801. }
  1802. case argument_type::Int: {
  1803. parameter_value_ = std::atoi(std::string(data.begin(), data.end()).c_str());
  1804. return;
  1805. }
  1806. case argument_type::Int64: {
  1807. parameter_value_ = std::atoll(std::string(data.begin(), data.end()).c_str());
  1808. return;
  1809. }
  1810. case argument_type::Float: {
  1811. parameter_value_ = std::atof(std::string(data.begin(), data.end()).c_str());
  1812. return;
  1813. }
  1814. case argument_type::Double: {
  1815. parameter_value_ = std::atof(std::string(data.begin(), data.end()).c_str());
  1816. return;
  1817. }
  1818. case argument_type::Long: {
  1819. parameter_value_ = std::atol(std::string(data.begin(), data.end()).c_str());
  1820. return;
  1821. }
  1822. case argument_type::Bool_: {
  1823. std::string tmpValue(data.begin(), data.end());
  1824. parameter_value_ = tmpValue == "1" || tmpValue == "true" || tmpValue == "TRUE" || tmpValue == "True";
  1825. return;
  1826. }
  1827. case argument_type::String: {
  1828. parameter_value_ = std::string(data.begin(), data.end());
  1829. return;
  1830. }
  1831. case argument_type::DateTime: {
  1832. parameter_value_ = datetime(std::string(data.begin(), data.end()));
  1833. return;
  1834. }
  1835. case argument_type::Binary: {
  1836. parameter_value_ = std::vector<std::uint8_t>(data.begin(), data.end());
  1837. return;
  1838. }
  1839. case argument_type::VecInt: {
  1840. std::vector<std::string> vec = v3::utils::split(std::string(data.begin(), data.end()), ",");
  1841. std::vector<int> vecValue;
  1842. for (auto vecIt : vec) {
  1843. vecValue.push_back(std::atoi(vecIt.c_str()));
  1844. }
  1845. parameter_value_ = vecValue;
  1846. return;
  1847. }
  1848. case argument_type::VecInt64: {
  1849. std::vector<std::string> vec = v3::utils::split(std::string(data.begin(), data.end()), ",");
  1850. std::vector<std::int64_t> vecValue;
  1851. for (auto vecIt : vec) {
  1852. vecValue.push_back(std::atoll(vecIt.c_str()));
  1853. }
  1854. parameter_value_ = vecValue;
  1855. return;
  1856. }
  1857. case argument_type::VecFloat: {
  1858. std::vector<std::string> vec = v3::utils::split(std::string(data.begin(), data.end()), ",");
  1859. std::vector<float> vecValue;
  1860. for (auto vecIt : vec) {
  1861. vecValue.push_back(std::atof(vecIt.c_str()));
  1862. }
  1863. parameter_value_ = vecValue;
  1864. return;
  1865. }
  1866. case argument_type::VecDouble: {
  1867. std::vector<std::string> vec = v3::utils::split(std::string(data.begin(), data.end()), ",");
  1868. std::vector<double> vecValue;
  1869. for (auto vecIt : vec) {
  1870. vecValue.push_back(std::atof(vecIt.c_str()));
  1871. }
  1872. parameter_value_ = vecValue;
  1873. return;
  1874. }
  1875. case argument_type::VecLong: {
  1876. std::vector<std::string> vec = v3::utils::split(std::string(data.begin(), data.end()), ",");
  1877. std::vector<long> vecValue;
  1878. for (auto vecIt : vec) {
  1879. vecValue.push_back(std::atol(vecIt.c_str()));
  1880. }
  1881. parameter_value_ = vecValue;
  1882. return;
  1883. }
  1884. case argument_type::VecBool: {
  1885. std::vector<std::string> vec = v3::utils::split(std::string(data.begin(), data.end()), ",");
  1886. std::vector<bool> vecValue;
  1887. for (auto vecIt : vec) {
  1888. vecValue.push_back(vecIt == "1" || vecIt == "true" || vecIt == "TRUE" || vecIt == "True");
  1889. }
  1890. parameter_value_ = vecValue;
  1891. return;
  1892. }
  1893. case argument_type::VecString: {
  1894. std::vector<std::string> vecValue = v3::utils::split(std::string(data.begin(), data.end()), ",");
  1895. parameter_value_ = vecValue;
  1896. return;
  1897. }
  1898. case argument_type::VecDateTime: {
  1899. std::vector<std::string> vec = v3::utils::split(std::string(data.begin(), data.end()), ",");
  1900. std::vector<datetime> vecValue;
  1901. for (auto vecIt : vec) {
  1902. vecValue.push_back(datetime(vecIt));
  1903. }
  1904. parameter_value_ = vecValue;
  1905. return;
  1906. }
  1907. }
  1908. }
  1909. catch (...) {
  1910. throw std::runtime_error("解析参数错误");
  1911. }
  1912. }
  1913. };
  1914. struct controller;
  1915. struct controller_action {
  1916. /**
  1917. * @brief 执行动作
  1918. * @param request
  1919. */
  1920. rttr::variant invoke(http::web_request& request, rttr::variant& variant, rttr::type const& controller_type) {
  1921. auto http_current_ptr = http_context::current();
  1922. //判断contentType
  1923. std::string content_type = "application/x-www-form-urlencoded";
  1924. if (request.find(http::field::content_type) != request.end()) {
  1925. content_type = std::string(request.find(http::field::content_type)->value().begin(), request.find(http::field::content_type)->value().end());
  1926. }
  1927. if (content_type.find(content_type) == std::string::npos) {
  1928. throw std::runtime_error("Content-Type:错误!");
  1929. }
  1930. //判断method
  1931. if (!((method == http_method::GET && request.method() == http::verb::get) || (method == http_method::POST && request.method() == http::verb::post))) {
  1932. throw std::runtime_error("Method:错误!");
  1933. }
  1934. std::vector<rttr::method> find_method;
  1935. for (auto& it : controller_type.get_methods()) {
  1936. if (it.get_name() == action_name && it.get_parameter_infos().size() == arguments.size()) {
  1937. find_method.push_back(it);
  1938. break;
  1939. }
  1940. }
  1941. if (find_method.empty())
  1942. throw std::runtime_error("Action:错误!");
  1943. std::vector<rttr::argument> parameters;
  1944. std::vector<rttr::variant> variantParameters;
  1945. {
  1946. std::lock_guard<std::mutex> locker(mux);
  1947. for (auto& it : find_method[0].get_parameter_infos()) {
  1948. arguments[it.get_index()]->parameter(request, it);
  1949. }
  1950. for (auto& it : arguments) {
  1951. variantParameters.push_back(it->parameter_value_);
  1952. }
  1953. }
  1954. for (auto& it : variantParameters) {
  1955. parameters.push_back(it);
  1956. }
  1957. return controller_type.invoke(action_name, variant, parameters);
  1958. }
  1959. /**
  1960. * @brief 身份验证
  1961. */
  1962. bool authen = true;
  1963. /**
  1964. * @brief 未登录跳转
  1965. */
  1966. std::string authen_jump;
  1967. /**
  1968. * @brief 方法名称
  1969. */
  1970. std::string action_name;
  1971. /**
  1972. * @brief 方式
  1973. */
  1974. http_method method = http_method::GET;
  1975. /**
  1976. * @brief 数据类型
  1977. */
  1978. std::string content_type = "application/x-www-form-urlencoded";
  1979. /**
  1980. * @brief 动作类型
  1981. */
  1982. std::string action_type;
  1983. /**
  1984. * @brief 文件映射
  1985. */
  1986. std::string file_mapping;
  1987. /**
  1988. * @brief 参数
  1989. */
  1990. std::vector<std::shared_ptr<action_argument>> arguments;
  1991. /**
  1992. * @brief 控制器
  1993. */
  1994. std::shared_ptr<controller> parent;
  1995. private:
  1996. /**
  1997. * @brief 锁
  1998. */
  1999. std::mutex mux;
  2000. };
  2001. struct controller {
  2002. rttr::variant invoke(http::web_request& request) {
  2003. std::string key(request.find("http_route_key")->value());
  2004. if (!actions.contains(key))
  2005. throw std::runtime_error("Action:不存在!");
  2006. rttr::type type = rttr::type::get_by_name(controller_name);
  2007. if (!variant.is_valid())
  2008. variant = type.create();
  2009. return actions[key]->invoke(request, variant, type);
  2010. }
  2011. /**
  2012. * @brief 控制器名称
  2013. */
  2014. std::string controller_name;
  2015. /**
  2016. * @brief 动作列表 路由 动作
  2017. */
  2018. std::map<std::string, std::shared_ptr<controller_action>> actions;
  2019. private:
  2020. /**
  2021. * @brief 对象
  2022. */
  2023. rttr::variant variant;
  2024. };
  2025. struct mvc_route {
  2026. bool contains(http::web_request& req) {
  2027. std::string key;
  2028. std::string route(req.find("http_route")->value());
  2029. if (contains(route, key)) {
  2030. std::size_t index = key.find('<');
  2031. std::vector<std::string> params;
  2032. if (std::string::npos != index) {
  2033. auto keys = v3::utils::split(key.substr(index), "/");
  2034. auto values = v3::utils::split(route.substr(index), "/");
  2035. for (int i = 0; i < keys.size() && i < values.size(); ++i) {
  2036. params.push_back(keys[i].substr(1, keys[i].size() - 2) + "=" + values[i]);
  2037. }
  2038. }
  2039. req.insert("http_route_key", key);
  2040. req.insert("http_route_parameter", v3::utils::join(params, "&"));
  2041. return true;
  2042. }
  2043. return false;
  2044. }
  2045. bool contains(std::string const& route) {
  2046. std::string key;
  2047. return contains(route, key);
  2048. }
  2049. void add(std::string const& route, std::shared_ptr<controller> value) {
  2050. routes_[route] = value;
  2051. }
  2052. std::shared_ptr<controller>& find(std::string const& route) {
  2053. std::string key;
  2054. if (contains(route, key)) {
  2055. return routes_[key];
  2056. }
  2057. throw std::runtime_error("key does not exist");
  2058. }
  2059. std::shared_ptr<controller>& operator[](std::string const& route) {
  2060. return find(route);
  2061. }
  2062. std::shared_ptr<controller>& operator[](http::web_request& req) {
  2063. return find(std::string(req.find("http_route_key")->value()));
  2064. }
  2065. private:
  2066. bool contains(std::string const& route, std::string& result) {
  2067. if (routes_.contains(route)) {
  2068. result = route;
  2069. return true;
  2070. }
  2071. else {
  2072. int slash_count = std::count(route.begin(), route.end(), '/');
  2073. for (auto& [first, second] : routes_) {
  2074. std::size_t index = first.find('<');
  2075. if (std::count(first.begin(), first.end(), '/') == slash_count && index != std::string::npos) {
  2076. if (first.substr(0, index) == route.substr(0, index)) {
  2077. result = first;
  2078. return true;
  2079. }
  2080. }
  2081. }
  2082. return false;
  2083. }
  2084. }
  2085. private:
  2086. std::map<std::string, std::shared_ptr<controller>> routes_;
  2087. };
  2088. struct MVC_API ico_controller {
  2089. /**
  2090. * @brief 注册
  2091. */
  2092. static void attach(std::shared_ptr<controller> controller) {
  2093. for (auto& [first, second] : controller->actions) {
  2094. controllers_.add(first, controller);
  2095. }
  2096. }
  2097. /**
  2098. * @brief
  2099. * @param url
  2100. * @return
  2101. */
  2102. static std::shared_ptr<controller> resolve(http::web_request& req) {
  2103. if (controllers_.contains(req)) {
  2104. return controllers_[req];
  2105. }
  2106. return nullptr;
  2107. }
  2108. private:
  2109. /**
  2110. * @brief
  2111. */
  2112. static mvc_route controllers_;
  2113. };
  2114. struct web_base_response {
  2115. void set_header(std::string_view name, std::string_view value) {
  2116. auto& response = http_context::current()->response;
  2117. response.set(name, value);
  2118. }
  2119. void set_header(http::field field, std::string_view value) {
  2120. auto& response = http_context::current()->response;
  2121. response.set(field, value);
  2122. }
  2123. void set_value(std::string_view value) {
  2124. auto& response = http_context::current()->response;
  2125. response.body().file().close();
  2126. response.body().text() = std::move(value);
  2127. auto const size = response.body().size();
  2128. response.content_length(size);
  2129. }
  2130. void set_value(std::vector<std::uint8_t> const& value) {
  2131. auto& response = http_context::current()->response;
  2132. response.body().file().close();
  2133. response.body().text() = std::string((char*)&value[0], value.size());
  2134. auto const size = response.body().size();
  2135. response.content_length(size);
  2136. }
  2137. void set_status(http::status status = http::status::ok) {
  2138. auto& response = http_context::current()->response;
  2139. response.result(status);
  2140. }
  2141. std::filesystem::path get_root_directory() {
  2142. auto& response = http_context::current()->response;
  2143. return response.get_root_directory();
  2144. }
  2145. http::status get_status() {
  2146. auto& response = http_context::current()->response;
  2147. return response.result();
  2148. }
  2149. std::string get_value() {
  2150. auto& response = http_context::current()->response;
  2151. return response.body().text();
  2152. }
  2153. void prepare_payload() {
  2154. auto& response = http_context::current()->response;
  2155. response.prepare_payload();
  2156. }
  2157. void chunked(bool value) {
  2158. auto& response = http_context::current()->response;
  2159. response.chunked(value);
  2160. }
  2161. void set_server(std::string_view value = BEAST_VERSION_STRING) {
  2162. auto& response = http_context::current()->response;
  2163. response.set(http::field::server, value);
  2164. }
  2165. void set_version(int ver = 11) {
  2166. auto& response = http_context::current()->response;
  2167. response.version(ver);
  2168. }
  2169. void fill_file(std::filesystem::path const& path, http::status status = http::status::ok) {
  2170. auto& response = http_context::current()->response;
  2171. if (path.c_str()[0] == '/' || path.c_str()[0] == '\\') {
  2172. response.fill_file(path, status);
  2173. }
  2174. else {
  2175. response.fill_file("/" + path.string(), status);
  2176. }
  2177. }
  2178. void fill_html(std::string const& html, http::status status = http::status::ok) {
  2179. auto& response = http_context::current()->response;
  2180. response.fill_html(html, status);
  2181. }
  2182. void fill_json(std::string const& json, http::status status = http::status::ok) {
  2183. auto& response = http_context::current()->response;
  2184. response.fill_json(json, status);
  2185. }
  2186. void fill_page(std::string const& value, http::status status = http::status::ok) {
  2187. auto& response = http_context::current()->response;
  2188. response.fill_page(status, value);
  2189. }
  2190. void fill_text(std::string const& text, http::status status = http::status::ok) {
  2191. auto& response = http_context::current()->response;
  2192. response.fill_text(text, status);
  2193. }
  2194. void fill_jump(std::string const& url) {
  2195. set_header(http::field::content_type, http::extension_to_mimetype("html"));
  2196. set_header(http::field::location, url);
  2197. set_status(http::status::found);
  2198. }
  2199. void fill_stream(std::vector<std::uint8_t> const& data, std::string const& extension, http::status status = http::status::ok) {
  2200. set_header("Content-Type", http::extension_to_mimetype(extension));
  2201. set_value(data);
  2202. set_status(status);
  2203. }
  2204. void fill_download(std::filesystem::path const& path, http::status status = http::status::ok) {
  2205. set_header(http::field::content_type, "application/octet-stream");
  2206. set_header(http::field::content_disposition, v3::utils::format("attachment; filename={}", path.filename().string()));
  2207. }
  2208. void fill_download(std::filesystem::path const& path, std::string const& filename, http::status status = http::status::ok) {
  2209. set_header(http::field::content_type, "application/octet-stream");
  2210. set_header(http::field::content_disposition, v3::utils::format("attachment; filename={}", filename));
  2211. }
  2212. void fill_view(http::status status = http::status::ok) {
  2213. fill_file(get_filename(), status);
  2214. }
  2215. std::filesystem::path get_filename() {
  2216. return mvc::http_context::current()->get_controller_action()->file_mapping;
  2217. }
  2218. };
  2219. struct web_result_response : public web_base_response {};
  2220. struct unknown_response : public web_base_response {
  2221. unknown_response(std::string const& text) {
  2222. set_value(text);
  2223. set_status(http::status::unknown);
  2224. }
  2225. virtual ~unknown_response() {
  2226. }
  2227. operator web_result_response() {
  2228. return {};
  2229. }
  2230. };
  2231. struct jump_response : public web_base_response {
  2232. jump_response(std::string const& url) {
  2233. if (!url.empty()) {
  2234. if (url[0] != '/')
  2235. fill_jump("/" + url);
  2236. }
  2237. else {
  2238. fill_jump(url);
  2239. }
  2240. }
  2241. virtual ~jump_response() {
  2242. }
  2243. operator web_result_response() {
  2244. return {};
  2245. }
  2246. };
  2247. struct text_response : public web_base_response {
  2248. text_response(std::string const& text, http::status status = http::status::ok) {
  2249. fill_text(text, status);
  2250. }
  2251. virtual ~text_response() {
  2252. }
  2253. operator web_result_response() {
  2254. return {};
  2255. }
  2256. };
  2257. struct html_response : public web_base_response {
  2258. html_response(std::string const& html, http::status status = http::status::ok) {
  2259. fill_html(html, status);
  2260. }
  2261. virtual ~html_response() {
  2262. }
  2263. operator web_result_response() {
  2264. return {};
  2265. }
  2266. };
  2267. struct file_response : public web_base_response {
  2268. file_response() {
  2269. fill_file(get_filename());
  2270. }
  2271. file_response(http::status status = http::status::ok) {
  2272. fill_file(get_filename(), status);
  2273. }
  2274. file_response(std::filesystem::path const& path, http::status status = http::status::ok) {
  2275. fill_file(path, status);
  2276. }
  2277. virtual ~file_response() {
  2278. }
  2279. operator web_result_response() {
  2280. return {};
  2281. }
  2282. };
  2283. struct json_response : public web_base_response {
  2284. json_response(std::string const& json) {
  2285. fill_json(json);
  2286. }
  2287. json_response(char* json) :
  2288. json_response(std::string(json)) {
  2289. }
  2290. json_response(const char* json) :
  2291. json_response(std::string(json)) {
  2292. }
  2293. template<typename _Type>
  2294. json_response(_Type const& value) {
  2295. fill_json(v3::json_convert::serialize(value));
  2296. }
  2297. virtual~json_response() {
  2298. }
  2299. operator web_result_response() {
  2300. return {};
  2301. }
  2302. };
  2303. struct stream_response : public web_base_response {
  2304. stream_response(std::vector<std::uint8_t> const& data, std::string const& extension, http::status status = http::status::ok) {
  2305. fill_stream(data, extension, status);
  2306. }
  2307. virtual~stream_response() {
  2308. }
  2309. operator web_result_response() {
  2310. return {};
  2311. }
  2312. };
  2313. struct download_response : public web_base_response {
  2314. download_response(std::filesystem::path const& path, http::status status = http::status::ok) {
  2315. fill_download(path, status);
  2316. }
  2317. download_response(std::filesystem::path const& path, std::string const& filename, http::status status = http::status::ok) {
  2318. fill_download(path, filename, status);
  2319. }
  2320. virtual~download_response() {
  2321. }
  2322. operator web_result_response() {
  2323. return {};
  2324. }
  2325. };
  2326. struct view : public web_base_response {
  2327. virtual ~view() {
  2328. }
  2329. view() :
  2330. web_base_response() {
  2331. fill_view();
  2332. }
  2333. view(std::string const& path) :
  2334. web_base_response() {
  2335. fill_file(path);
  2336. }
  2337. template<typename ..._Args>
  2338. view(_Args&& ...args) {
  2339. std::filesystem::path path = get_filename();
  2340. std::filesystem::path filepath;
  2341. filepath = http_context::current()->response.get_root_directory();
  2342. filepath.make_preferred();
  2343. filepath /= path.make_preferred().relative_path();
  2344. std::vector<std::uint8_t> value;
  2345. std::ifstream file(filepath, std::ios::in | std::ios::binary);
  2346. if (file.is_open()) {
  2347. file.seekg(0, std::ios::end);
  2348. int file_size = file.tellg();
  2349. file.seekg(0, std::ios::beg);
  2350. value.resize(file_size);
  2351. file.read((char*)&value[0], file_size);
  2352. file.close();
  2353. }
  2354. std::string html(value.begin(), value.end());
  2355. auto label_value_list = pseudo_extract_label_value::analysis(html);
  2356. if (!label_value_list.empty()) {
  2357. auto classValueList = pseudo_extract_class_value::get_class_value(std::forward<_Args>(args)...);
  2358. label_value_list[0]->set_class_value(classValueList);
  2359. html = label_value_list[0]->analysis();
  2360. fill_html(html);
  2361. }
  2362. }
  2363. operator web_result_response() {
  2364. return {};
  2365. }
  2366. };
  2367. template<int _Width = 100, int _Height = 38, int _Length = 4, int _Line = 2, int _Spot = 200>
  2368. struct captcha_response : public v3::mvc::web_base_response {
  2369. captcha_response(std::string const& session_key = "code") :
  2370. session_key_(session_key) {
  2371. }
  2372. virtual ~captcha_response() {
  2373. }
  2374. operator v3::mvc::web_result_response() {
  2375. //验证码
  2376. std::string captcha_code = generate_captcha_digits();
  2377. http_context::current()->add_session(session_key_, captcha_code);
  2378. std::vector<std::uint8_t> img_vec = generate_captcha_image(captcha_code);
  2379. return v3::mvc::stream_response(img_vec, "bmp");
  2380. }
  2381. private:
  2382. class CImage : public cimg_library::CImg<unsigned char> {
  2383. public:
  2384. CImage(const cimg_library::CImg<unsigned char>& img) :
  2385. cimg_library::CImg<unsigned char>(img) {}
  2386. cimg_library::CImg<unsigned char>& save_memory_bmp(std::vector<std::uint8_t>& result) {
  2387. cimg_library::CImg<ucharT> header(54, 1, 1, 1, 0);
  2388. unsigned char align_buf[4] = {};
  2389. const unsigned int
  2390. align = (4 - (3 * _width) % 4) % 4,
  2391. buf_size = (3 * _width + align) * height(),
  2392. file_size = 54 + buf_size;
  2393. header[0] = 'B'; header[1] = 'M';
  2394. header[0x02] = file_size & 0xFF;
  2395. header[0x03] = (file_size >> 8) & 0xFF;
  2396. header[0x04] = (file_size >> 16) & 0xFF;
  2397. header[0x05] = (file_size >> 24) & 0xFF;
  2398. header[0x0A] = 0x36;
  2399. header[0x0E] = 0x28;
  2400. header[0x12] = _width & 0xFF;
  2401. header[0x13] = (_width >> 8) & 0xFF;
  2402. header[0x14] = (_width >> 16) & 0xFF;
  2403. header[0x15] = (_width >> 24) & 0xFF;
  2404. header[0x16] = _height & 0xFF;
  2405. header[0x17] = (_height >> 8) & 0xFF;
  2406. header[0x18] = (_height >> 16) & 0xFF;
  2407. header[0x19] = (_height >> 24) & 0xFF;
  2408. header[0x1A] = 1;
  2409. header[0x1B] = 0;
  2410. header[0x1C] = 24;
  2411. header[0x1D] = 0;
  2412. header[0x22] = buf_size & 0xFF;
  2413. header[0x23] = (buf_size >> 8) & 0xFF;
  2414. header[0x24] = (buf_size >> 16) & 0xFF;
  2415. header[0x25] = (buf_size >> 24) & 0xFF;
  2416. header[0x27] = 0x1;
  2417. header[0x2B] = 0x1;
  2418. result.insert(result.end(), reinterpret_cast<std::uint8_t*>(header._data), reinterpret_cast<std::uint8_t*>(header._data) + 64);
  2419. const unsigned char
  2420. * ptr_r = data(0, _height - 1, 0, 0),
  2421. * ptr_g = (_spectrum >= 2) ? data(0, _height - 1, 0, 1) : 0,
  2422. * ptr_b = (_spectrum >= 3) ? data(0, _height - 1, 0, 2) : 0;
  2423. switch (_spectrum) {
  2424. case 1: {
  2425. cimg_forY(*this, y) {
  2426. cimg_forX(*this, x) {
  2427. const unsigned char val = (unsigned char)*(ptr_r++);
  2428. result.push_back(val); result.push_back(val); result.push_back(val);
  2429. }
  2430. result.insert(result.end(), reinterpret_cast<std::uint8_t*>(align_buf), reinterpret_cast<std::uint8_t*>(align_buf) + align);
  2431. ptr_r -= 2 * _width;
  2432. }
  2433. } break;
  2434. case 2: {
  2435. cimg_forY(*this, y) {
  2436. cimg_forX(*this, x) {
  2437. result.push_back(0);
  2438. result.push_back((unsigned char)(*(ptr_g++)));
  2439. result.push_back((unsigned char)(*(ptr_r++)));
  2440. }
  2441. result.insert(result.end(), reinterpret_cast<std::uint8_t*>(align_buf), reinterpret_cast<std::uint8_t*>(align_buf) + align);
  2442. ptr_r -= 2 * _width; ptr_g -= 2 * _width;
  2443. }
  2444. } break;
  2445. default: {
  2446. cimg_forY(*this, y) {
  2447. cimg_forX(*this, x) {
  2448. result.push_back((unsigned char)(*(ptr_b++)));
  2449. result.push_back((unsigned char)(*(ptr_g++)));
  2450. result.push_back((unsigned char)(*(ptr_r++)));
  2451. }
  2452. result.insert(result.end(), reinterpret_cast<std::uint8_t*>(align_buf), reinterpret_cast<std::uint8_t*>(align_buf) + align);
  2453. ptr_r -= 2 * _width; ptr_g -= 2 * _width; ptr_b -= 2 * _width;
  2454. }
  2455. }
  2456. }
  2457. return *this;
  2458. }
  2459. };
  2460. private:
  2461. //获取验证码
  2462. std::string generate_captcha_digits() {
  2463. static const char data_character[] = "23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ\0";
  2464. int min = 0;
  2465. int max = std::strlen(data_character) - 1;
  2466. std::string result;
  2467. for (int i = 0; i < _Length; ++i) {
  2468. result += data_character[v3::utils::random(min, max)];
  2469. }
  2470. return result;
  2471. }
  2472. //生成随机颜色
  2473. unsigned char* generate_random_color() {
  2474. static unsigned char colors[][3] = {
  2475. {47,79,79 },
  2476. {105,105,105 },
  2477. {0,0,128 },
  2478. {100,149,237 },
  2479. {72,61,139 },
  2480. {106,90,205 },
  2481. {123,104,238 },
  2482. {132,112,255 },
  2483. {65,105,225 },
  2484. {85,107,47 },
  2485. {107,142,35 },
  2486. {205,92,92 },
  2487. {160,82,45 },
  2488. {178,34,34 },
  2489. {255,69,0 },
  2490. {176,48,96 },
  2491. {160,32,240 },
  2492. {139,137,137 },
  2493. {0,139,139 },
  2494. {139,0,0 },
  2495. {139,0,139 },
  2496. {154,50,205 },
  2497. {238,64,0 },
  2498. {0,139,69 } };
  2499. return colors[v3::utils::random(0, sizeof(colors) / sizeof(colors[0]) - 1)];
  2500. }
  2501. //生成字体大小,位置
  2502. std::vector<std::tuple<int, int, int>> generate_font_size() {
  2503. std::vector<std::tuple<int, int, int>> result;
  2504. int s_width = _Width / _Length;
  2505. int s_height = _Height;
  2506. for (int i = 0; i < _Length; ++i) {
  2507. int x = 0, y = 0, s = 0;
  2508. double font_centre_pos = 0.0;
  2509. if (s_width > s_height) {
  2510. s = v3::utils::random(double(s_height) - double(s_height) * 0.2, double(s_height) * 1.2);
  2511. }
  2512. else {
  2513. s = v3::utils::random(double(s_width) - double(s_width) * 0.2, double(s_width) * 1.2);
  2514. }
  2515. font_centre_pos = double(s) * 0.8;
  2516. x = v3::utils::random(0, double(s_width) - font_centre_pos);
  2517. y = v3::utils::random(0, double(s_height) - font_centre_pos);
  2518. result.push_back(std::make_tuple(s, x, y));
  2519. }
  2520. return result;
  2521. }
  2522. //验证码图片
  2523. std::vector<std::uint8_t> generate_captcha_image(std::string const& code) {
  2524. std::vector<std::uint8_t> result;
  2525. cimg_library::CImg<unsigned char> image(_Width, _Height, 1, 3, 255); // 创建一个白色背景的图像
  2526. int s_width = _Width / _Length;
  2527. int s_height = _Height;
  2528. std::vector<std::tuple<int, int, int>> font_info = generate_font_size();
  2529. char c[2] = { 0 };
  2530. //绘制验证码
  2531. for (int i = 0; i < _Length; ++i) {
  2532. c[0] = code[i];
  2533. image.draw_text(i * s_width + std::get<1>(font_info[i]), std::get<2>(font_info[i]), c, generate_random_color(), 0, 1, std::get<0>(font_info[i])).width();
  2534. }
  2535. //绘制干扰线
  2536. for (int i = 0; i < _Line; ++i) {
  2537. int x1 = std::rand() % _Width;
  2538. int y1 = std::rand() % _Height;
  2539. int x2 = std::rand() % _Width;
  2540. int y2 = std::rand() % _Height;
  2541. // 生成随机颜色
  2542. image.draw_line(x1, y1, x2, y2, generate_random_color());
  2543. }
  2544. //绘制干扰点
  2545. for (int i = 0; i < _Spot; ++i) {
  2546. int x = std::rand() % _Width;
  2547. int y = std::rand() % _Height;
  2548. // 生成随机颜色
  2549. image.draw_point(x, y, generate_random_color());
  2550. }
  2551. //扭曲图像
  2552. cimg_library::CImg<unsigned char> distorted_image(_Width, _Height, 1, 3, 255);
  2553. cimg_forXY(image, xx, yy) {
  2554. int new_xx = xx + static_cast<int>(1.32 * sin(2 * 3.14 * yy * 0.045));
  2555. int new_yy = yy + static_cast<int>(1.42 * sin(2 * 3.14 * xx * 0.062));
  2556. if (new_xx >= 0 && new_xx < _Width && new_yy >= 0 && new_yy < _Height) {
  2557. distorted_image(xx, yy, 0, 0) = image(new_xx, new_yy, 0, 0);
  2558. distorted_image(xx, yy, 0, 1) = image(new_xx, new_yy, 0, 1);
  2559. distorted_image(xx, yy, 0, 2) = image(new_xx, new_yy, 0, 2);
  2560. }
  2561. }
  2562. CImage(distorted_image).save_memory_bmp(result);
  2563. return result;
  2564. }
  2565. private:
  2566. std::string session_key_;
  2567. };
  2568. class http_server_t {
  2569. public:
  2570. http_server_t() {
  2571. server_.bind<http::verb::post, http::verb::get>(std::string("/*"), &http_server_t::on_base_request, this);
  2572. }
  2573. bool start(std::string const& ip, int port) {
  2574. return server_.start(ip, port);
  2575. }
  2576. void stop() {
  2577. server_.stop();
  2578. }
  2579. void set_root_directory(std::filesystem::path const& path) {
  2580. server_.set_root_directory(path);
  2581. }
  2582. protected:
  2583. virtual void on_request(http::web_request& req, http::web_response& rep) = 0;
  2584. private:
  2585. void on_base_request(std::shared_ptr<asio2::http_session>& session_ptr, http::web_request& req, http::web_response& rep) {
  2586. on_request(req, rep);
  2587. }
  2588. private:
  2589. asio2::http_server server_;
  2590. };
  2591. class https_server_t {
  2592. public:
  2593. https_server_t() {
  2594. server_.bind<http::verb::post, http::verb::get>("/*", &https_server_t::on_base_request, this);
  2595. }
  2596. bool start(std::string const& ip, int port) {
  2597. return server_.start(ip, port);
  2598. }
  2599. void stop() {
  2600. server_.stop();
  2601. }
  2602. void set_root_directory(std::filesystem::path const& path) {
  2603. server_.set_root_directory(path);
  2604. }
  2605. void set_cert_file(std::string const& ca_cert_file, std::string const& private_cert_file, std::string const& private_key_file, std::string const& private_password) {
  2606. server_.set_cert_file(ca_cert_file, private_cert_file, private_key_file, private_password);
  2607. }
  2608. protected:
  2609. virtual void on_request(http::web_request& req, http::web_response& rep) = 0;
  2610. private:
  2611. void on_base_request(std::shared_ptr<asio2::https_session>& session_ptr, http::web_request& req, http::web_response& rep) {
  2612. on_request(req, rep);
  2613. }
  2614. private:
  2615. asio2::https_server server_;
  2616. };
  2617. template<typename _Before, typename _Err, typename _After, typename _TypeBase>
  2618. class http_server_base : public _TypeBase {
  2619. public:
  2620. http_server_base() :
  2621. _TypeBase() {
  2622. }
  2623. private:
  2624. virtual void on_request(http::web_request& req, http::web_response& rep)override {
  2625. http_context_gc http_context(req, rep);
  2626. try {
  2627. req.insert("http_route", std::string(req.path()).substr(1));
  2628. std::shared_ptr<controller> controller = v3::mvc::ico_controller::resolve(req);
  2629. std::string key(req.find("http_route_key")->value());
  2630. http_context::current()->set_controller_action((bool)controller ? controller->actions[key] : nullptr);
  2631. if (before_.before((bool)controller ? controller->actions[key] : nullptr, req, rep)) {
  2632. rttr::variant variant = controller->invoke(req);
  2633. if (variant.is_valid()) {
  2634. auto response = variant.get_value<web_base_response>();
  2635. response.set_version();
  2636. response.set_server();
  2637. response.chunked(true);
  2638. response.prepare_payload();
  2639. }
  2640. }
  2641. //文件
  2642. else {
  2643. rep.fill_file(req.path());
  2644. rep.set(http::field::cache_control, "max-age=31536000");
  2645. rep.chunked(true);
  2646. }
  2647. }
  2648. catch (unknown_response const&) {
  2649. }
  2650. catch (jump_response const&) {
  2651. }
  2652. catch (text_response const&) {
  2653. }
  2654. catch (html_response const&) {
  2655. }
  2656. catch (file_response const&) {
  2657. }
  2658. catch (json_response const&) {
  2659. }
  2660. catch (std::exception const& ec) {
  2661. err_.error(ec.what(), req, rep);
  2662. }
  2663. catch (...) {
  2664. err_.error("未知异常", req, rep);
  2665. }
  2666. after_.after(req, rep);
  2667. }
  2668. private:
  2669. _Before before_;
  2670. _Err err_;
  2671. _After after_;
  2672. };
  2673. template<typename _Before, typename _Err, typename _After>
  2674. using http_server = http_server_base<_Before, _Err, _After, http_server_t>;
  2675. template<typename _Before, typename _Err, typename _After>
  2676. using https_server = http_server_base<_Before, _Err, _After, https_server_t>;
  2677. }
  2678. }
  2679. }