This repository has been archived on 2021-11-25. You can view files and clone it, but cannot push or open issues or pull requests.
CodePaste/doPaste.cpp

114 lines
2.4 KiB
C++
Raw Normal View History

2017-11-21 15:38:03 +08:00
#include "Request.h"
#include "Response.h"
#include "Util.h"
#include "json.hpp"
#include <fstream>
#include <cstdio>
#include "windows.h"
using namespace std;
using json = nlohmann::json;
const string docroot = "D:\\Bitnami\\wampstack-5.6.31-0\\apache2\\htdocs\\";
int main()
{
Request req;
Response res;
json j;
auto jsonfail=[&](int errcode,const std::string& errmsg)
{
j["success"]=0;
j["errcode"]=errcode;
j["errmsg"]=errmsg;
};
do
{
if(req.requestMethod!="POST")
{
jsonfail(1,"Request Method Not Supported");
break;
}
if(req.post.find("code")==req.post.end() ||
req.post.find("title")==req.post.end() )
{
jsonfail(2,"Missing Parameters");
break;
}
string code=req.post["code"];
string title=req.post["title"];
string html;
ifstream ifs("paste_template.txt");
if(!ifs)
{
jsonfail(3,"Failed to read template.");
break;
}
string temp;
while(getline(ifs,temp))
{
html.append(temp);
}
int len=code.size();
ostringstream ostr;
for(int i=0;i<len;i++)
{
if(code[i]=='<')
{
ostr<<"&lt";
}
else if(code[i]=='>')
{
ostr<<"&gt";
}
else
{
ostr<<code[i];
}
}
string purecode=ostr.str();
string tag="{{Title}}";
html.replace(html.find(tag),tag.size(),title);
tag="{{Codetag}}";
html.replace(html.find(tag),tag.size(),"cpp");
tag="{{Code}}";
html.replace(html.find(tag),tag.size(),purecode);
int id,rd;
srand(time(NULL));
while(true)
{
id=time(NULL);
rd=rand()%100;
ifstream ifsx(make_str(docroot,"paste\\",id,"_",rd,".html"));
if(ifsx) continue;
else break;
}
string fname=make_str(docroot,"paste\\",id,"_",rd,".html");
ofstream ofs(fname);
if(!ofs)
{
jsonfail(4,"File cannot be created.");
break;
}
ofs<<html<<endl;
j["success"]=1;
j["next_url"]=make_str("/paste/",id,"_",rd,".html");
}while(0);
res.content.append(j.dump());
res.show();
return 0;
}