From ddeb862395d5d2d7163182c87fdbe2cb2b9dba35 Mon Sep 17 00:00:00 2001 From: Matthieu Gautier Date: Thu, 8 Aug 2019 12:33:44 +0200 Subject: [PATCH] Add getMimeTypeForFile in pathTool. --- include/tools/pathTools.h | 1 + src/tools/pathTools.cpp | 48 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/include/tools/pathTools.h b/include/tools/pathTools.h index 1ea7ae4e0..a820c959f 100644 --- a/include/tools/pathTools.h +++ b/include/tools/pathTools.h @@ -61,4 +61,5 @@ string getExecutablePath(); string getCurrentDirectory(); string getDataDirectory(); bool writeTextFile(const string& path, const string& content); +std::string getMimeTypeForFile(const std::string& filename); #endif diff --git a/src/tools/pathTools.cpp b/src/tools/pathTools.cpp index 83db6f90c..8b3ae5afa 100644 --- a/src/tools/pathTools.cpp +++ b/src/tools/pathTools.cpp @@ -29,6 +29,8 @@ #define getcwd _getcwd // stupid MSFT "deprecation" warning #endif +#include + #ifdef _WIN32 const std::string SEPARATOR("\\"); #else @@ -323,3 +325,49 @@ string getDataDirectory() #endif return appendToDirectory(dataDir, "kiwix"); } + +static std::map extMimeTypes = { + { "html", "text/html"}, + { "htm", "text/html"}, + { "png", "image/png"}, + { "tiff", "image/tiff"}, + { "tif", "image/tiff"}, + { "jpeg", "image/jpeg"}, + { "jpg", "image/jpeg"}, + { "gif", "image/gif"}, + { "svg", "image/svg+xml"}, + { "txt", "text/plain"}, + { "xml", "text/xml"}, + { "pdf", "application/pdf"}, + { "ogg", "application/ogg"}, + { "js", "application/javascript"}, + { "css", "text/css"}, + { "otf", "application/vnd.ms-opentype"}, + { "ttf", "application/font-ttf"}, + { "woff", "application/font-woff"}, + { "vtt", "text/vtt"} +}; + +/* Try to get the mimeType from the file extension */ +std::string getMimeTypeForFile(const std::string& filename) +{ + std::string mimeType = "text/plain"; + auto pos = filename.find_last_of("."); + + if (pos != std::string::npos) { + std::string extension = filename.substr(pos + 1); + + auto it = extMimeTypes.find(extension); + if (it != extMimeTypes.end()) { + mimeType = it->second; + } else { + it = extMimeTypes.find(kiwix::lcAll(extension)); + if (it != extMimeTypes.end()) { + mimeType = it->second; + } + } + } + + return mimeType; +} +