|
| 1 | +#include "file_controller.h" |
| 2 | +#include <iostream> |
| 3 | +#include <stdexcept> |
| 4 | +#include <stdio.h> |
| 5 | +#include <string> |
| 6 | +#include <json/json.h> |
| 7 | + |
| 8 | + |
| 9 | +std::string shell_commons(const char* cmd) { |
| 10 | + char buffer[128]; |
| 11 | + std::string result = ""; |
| 12 | + FILE* pipe = popen(cmd, "r"); |
| 13 | + if (!pipe) throw std::runtime_error("popen() failed!"); |
| 14 | + try { |
| 15 | + while (fgets(buffer, sizeof buffer, pipe) != NULL) { |
| 16 | + result += buffer; |
| 17 | + } |
| 18 | + } catch (...) { |
| 19 | + pclose(pipe); |
| 20 | + throw; |
| 21 | + } |
| 22 | + pclose(pipe); |
| 23 | + return result; |
| 24 | +} |
| 25 | + |
| 26 | +void genTree(const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> &&callback) |
| 27 | +{ |
| 28 | + char *pathvar; |
| 29 | + pathvar = getenv("PWD"); |
| 30 | + std::string result = shell_commons(("cd "+std::string(pathvar)+"/.. " + "&&"+"tree -J root" ).c_str()) ; |
| 31 | + auto res = HttpResponse::newHttpResponse(); |
| 32 | + res->addHeader("Access-Control-Allow-Origin", "*"); |
| 33 | + res ->setBody(result); |
| 34 | + callback(res); |
| 35 | +} |
| 36 | +void catFile(const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> &&callback) |
| 37 | +{ |
| 38 | + char *pathvar; |
| 39 | + pathvar = getenv("PWD"); |
| 40 | + std::string path = req->getParameter("path"); |
| 41 | + std::string result = shell_commons(("cat "+std::string(pathvar)+"/../root/"+path).c_str()) ; |
| 42 | + auto res = HttpResponse::newHttpResponse(); |
| 43 | + res->addHeader("Access-Control-Allow-Origin", "*"); |
| 44 | + res ->setBody(result); |
| 45 | + callback(res); |
| 46 | +} |
| 47 | +void saveFile(const HttpRequestPtr &req, std::function<void(const HttpResponsePtr &)> &&callback) |
| 48 | +{ |
| 49 | + auto body = req->getBody(); |
| 50 | + Json::Value req_json; |
| 51 | + Json::Reader reader; |
| 52 | + std::string bodyStr(body); |
| 53 | + if (!reader.parse(bodyStr, req_json)) { |
| 54 | + std::cout<<"parse failed"<<std::endl; |
| 55 | + callback(HttpResponse::newHttpResponse()); |
| 56 | + return; |
| 57 | + } |
| 58 | + char *pathvar; |
| 59 | + pathvar = getenv("PWD"); |
| 60 | + std::string filename = req_json["filename"].asString(); |
| 61 | + std::string content = req_json["content"].asString(); |
| 62 | + std::string result = shell_commons(("echo '"+content+"'>"+std::string(pathvar)+"/../root/"+filename).c_str()) ; |
| 63 | + auto res = HttpResponse::newHttpResponse(); |
| 64 | + res->addHeader("Access-Control-Allow-Origin", "*"); |
| 65 | + res ->setBody("success"); |
| 66 | + callback(res); |
| 67 | +} |
0 commit comments