annotate server/file_sender.cpp @ 0:a4671277546c tip

created the repository for the thymian project
author ferencd
date Tue, 17 Aug 2021 11:19:54 +0200
parents
children
rev   line source
ferencd@0 1 #include "file_sender.h"
ferencd@0 2 #include <templater.h>
ferencd@0 3 #include <log.h>
ferencd@0 4 #include <unistd.h>
ferencd@0 5 #include <fstream>
ferencd@0 6 #include <boost/algorithm/string.hpp>
ferencd@0 7
ferencd@0 8 file_sender::file_sender(tnt::HttpRequest& request, tnt::HttpReply& reply, const std::string& file)
ferencd@0 9 : web_component(request, reply, ""), mfile(file)
ferencd@0 10 {}
ferencd@0 11
ferencd@0 12 file_sender &file_sender::templatize()
ferencd@0 13 {
ferencd@0 14 mneeds_templates = true;
ferencd@0 15 return *this;
ferencd@0 16 }
ferencd@0 17
ferencd@0 18 static std::string fn = "";
ferencd@0 19
ferencd@0 20 unsigned file_sender::send()
ferencd@0 21 {
ferencd@0 22
ferencd@0 23 char cCurrentPath[FILENAME_MAX] = {0};
ferencd@0 24
ferencd@0 25 if (!getcwd(cCurrentPath, sizeof(cCurrentPath)))
ferencd@0 26 {
ferencd@0 27 return internalServerError();
ferencd@0 28 }
ferencd@0 29
ferencd@0 30 std::string filename(cCurrentPath);
ferencd@0 31 if(mfile[0] != '/' && filename[filename.length() - 1] != '/')
ferencd@0 32 {
ferencd@0 33 filename += '/';
ferencd@0 34 }
ferencd@0 35 filename += mfile;
ferencd@0 36
ferencd@0 37 std::ifstream fin(filename.c_str(), std::ios::in | std::ios::binary);
ferencd@0 38
ferencd@0 39 if(fin)
ferencd@0 40 {
ferencd@0 41 if(mneeds_templates)
ferencd@0 42 {
ferencd@0 43 //TODO mutex!
ferencd@0 44 fn = filename;
ferencd@0 45 GENERIC_FILE_TEMPLATE(FileSender, fn);
ferencd@0 46 std::string res = templater<FileSender>().templatize().get();
ferencd@0 47 mreply.out() << res;
ferencd@0 48 }
ferencd@0 49 else
ferencd@0 50 {
ferencd@0 51 mreply.setContentType(mimeDb.getMimetype(mfile));
ferencd@0 52 std::ostringstream oss;
ferencd@0 53 oss << fin.rdbuf();
ferencd@0 54 std::string fileData(oss.str());
ferencd@0 55 mreply.out() << fileData; // send the file
ferencd@0 56 }
ferencd@0 57
ferencd@0 58 return HTTP_OK;
ferencd@0 59 }
ferencd@0 60 else
ferencd@0 61 {
ferencd@0 62 if(boost::starts_with(mfile, theme_path))
ferencd@0 63 {
ferencd@0 64 return HTTP_NOT_FOUND;
ferencd@0 65 }
ferencd@0 66
ferencd@0 67 // see if the file is actually from the current theme
ferencd@0 68 unsigned current_theme_file_send = file_sender(mrequest, mreply, theme_path + mfile).send();
ferencd@0 69 return current_theme_file_send;
ferencd@0 70 }
ferencd@0 71 }