mvc.hpp 87 KB

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