// // Created by Shell on 2026/6/17. // #ifndef SEADISK_SEAFILE_API_HPP #define SEADISK_SEAFILE_API_HPP #include #include #include #include "exception.hpp" #include #include #include #include "auth_token.hpp" #include "server_info.hpp" namespace seafile { class SeaFileApi final { //base url of the seafile api server std::string base_url; /** * make a url string from given path * @param path url path * @return the whole url string */ std::string makeUrl(const std::string &path) { auto url = ada::parse(this->base_url); url->set_pathname(path); return std::string(url->get_href()); } template tl::expected parseResponse(const cpr::Response &response) { if (response.error) { return tl::make_unexpected( SeafileException( response.error.message)); } if (response.status_code != 200) { return tl::make_unexpected( SeafileException( std::format("Http Error: {}", response.status_code))); } try { return nlohmann::json::parse(response.text) .get(); } catch (const std::exception &e) { return tl::make_unexpected( SeafileException(e.what())); } } /** * post body and fetch result * @tparam T return type * @param path target url path * @param body post body data * @return T if success else SeafileException */ template tl::expected post(const std::string &path, const nlohmann::json &body) { const auto url = makeUrl(path); auto response = cpr::Post( cpr::Url{url}, cpr::Header{ {"accept", "application/json"}, {"content-type", "application/json"} }, cpr::Body{body.dump()}); return parseResponse(response); } public: /** * primary constructor * @param base_url base url of seafile server */ explicit SeaFileApi(std::string base_url) : base_url(std::move(base_url)) { } /** * * @param username username * @param password password * @return token when success else SeafileException */ tl::expected authToken(const std::string &username, const std::string &password) { const nlohmann::json body = { {"username", username}, {"password", password} }; return this->post("/api2/auth-token/", body); } tl::expected serverInfo() { auto response = cpr::Get( cpr::Url{makeUrl("/api2/server-info/")}, cpr::Header{ {"accept", "application/json"} }); return parseResponse(response); } }; } #endif //SEADISK_SEAFILE_API_HPP