defaultNames) {
this->vfs = fs;
this->allowListing = allowListing;
this->defaultNames = defaultNames;
this->spa = spa;
}
bool FileServer::SendFile(ServerContext &ctx, VFSPath path) {
TF_LOG("File: " + path.ToString());
auto strm = this->vfs->OpenFile(path, "rb");
bool retVal = false;
if (strm != nullptr) {
Date::DateTime lw, la;
this->vfs->GetDate(path, lw, la);
ctx.WithLastModified(lw)
.WithMimeType(HttpUtils::GetMimeTypePath(path))
.SendStream(strm);
retVal = true;
}
return retVal;
}
bool FileServer::Handle(ServerContext &ctx) {
auto path =
((VFSPath)HttpUtils::UrlPathDecode(ctx.path)).CollapseRelativeParents();
if (this->vfs->DirectoryExists(path)) {
TF_LOG("Directory exists");
for (auto f : defaultNames) {
VFSPath p = path;
p = p / f;
TF_LOG("Trying " + p.ToString());
TF_LOG("Before file exists");
TF_LOG(this->vfs->FileExists(p) ? "File Exists"
: "File Does Not Exist");
TF_LOG("After file exists");
if (this->vfs->FileExists(p))
return SendFile(ctx, p);
}
if (this->allowListing) {
std::string p = HttpUtils::HtmlEncode(ctx.originalPath);
std::string html = "Index of ";
html.append(p);
html.append("Index of ");
html.append(p);
html.append("
../\r\n");
for (auto item : vfs->EnumeratePaths(path)) {
if (vfs->DirectoryExists(item)) {
// is dir
std::string path = item.GetFileName();
html.append("");
html.append(HttpUtils::HtmlEncode(path) + "/");
html.append("\r\n");
} else {
// is file
std::string path = item.GetFileName();
html.append("");
html.append(HttpUtils::HtmlEncode(path));
html.append("\r\n");
}
}
html.append("
");
ctx.WithMimeType("text/html").SendText(html);
return true;
}
} else if (this->vfs->FileExists(path)) {
return SendFile(ctx, path);
} else if (this->spa) {
for (auto f : defaultNames) {
VFSPath p(f);
p.relative = false;
if (this->vfs->FileExists(p))
return SendFile(ctx, p);
}
}
return false;
}
FileServer::~FileServer() {}
} // namespace Tesses::Framework::Http