CNetWork.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #include "stdafx.h"
  2. #include "CNetWork.h"
  3. #include <nlohmann/json.hpp>
  4. #include <fmt/format.h>
  5. CNetWork::CNetWork() : m_http_ret(http_f)
  6. {
  7. }
  8. CNetWork::~CNetWork(void)
  9. {
  10. }
  11. HTTPRET CNetWork::PostLogin(LPCSTR username, LPCSTR password, std::string& data)
  12. {
  13. std::vector<cpr::Pair> p;
  14. p.push_back({ "email",username });
  15. p.push_back({ "password",password });
  16. std::string text = PostUrl("/api/client/v3/login", p);
  17. if (text.empty()) {
  18. return http_f;
  19. }
  20. data = text.c_str();
  21. return http_yes;
  22. }
  23. void CNetWork::SetUrl(LPCSTR url)
  24. {
  25. m_url = url;
  26. }
  27. SStringA CNetWork::GetLastErrorA()
  28. {
  29. return SStringA().Format("%s", m_error_msg.c_str()).GetBuffer(0);
  30. }
  31. SStringW CNetWork::GetLastErrorW()
  32. {
  33. return S_CA2W(m_error_msg.c_str(),CP_UTF8).GetBuffer(0);
  34. }
  35. std::string CNetWork::GetUrl(std::string path, std::vector<cpr::Parameter> parame)
  36. {
  37. return std::string();
  38. }
  39. std::string CNetWork::PostUrl(std::string path, std::vector<cpr::Pair> parame)
  40. {
  41. auto s = fmt::format("{0}{1}", m_url, path.c_str());
  42. cpr::Response r;
  43. if (parame.empty())
  44. {
  45. r = cpr::Get(cpr::Url{ s.c_str() });
  46. }
  47. else {
  48. r = cpr::Post(cpr::Url{ s.c_str() }, cpr::Payload{ parame.begin(),parame.end() }, cpr::Header{ {"accept", "application/json"} });
  49. }
  50. if (r.status_code == 200 || r.status_code == 201)
  51. {
  52. return std::move(r.text);
  53. }
  54. else {
  55. m_http_status = r.status_code;
  56. if (m_http_status == 0)
  57. {
  58. //m_http_status = r.error.code;
  59. m_error_msg = r.error.message;
  60. }
  61. return "";
  62. }
  63. return std::string("");
  64. }
  65. bool write_data(std::string /*data*/, intptr_t /*userdata*/)
  66. {
  67. return true;
  68. }
  69. bool CNetWork::Download(std::string path)
  70. {
  71. std::string configdir = std::filesystem::current_path().string() + "\\" + CLASHCONFIGDIR;
  72. std::filesystem::path p(configdir);
  73. if (!std::filesystem::exists(p)) {
  74. std::filesystem::create_directory(p);
  75. }
  76. std::string configname = configdir + "\\" CLASHCONFIGNAME;
  77. std::ofstream ofs(configname);
  78. cpr::Url url{ path };
  79. cpr::Session session;
  80. session.SetUrl(url);
  81. cpr::Response response = session.Download(ofs);
  82. return response.status_code == 200;
  83. }
  84. void CNetWork::Init()
  85. {
  86. }
  87. void CNetWork::UnInit()
  88. {
  89. }