StaticWebPageController.cpp 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // Created by xcbosa on 2023/1/28.
  3. //
  4. #include "../processor/processor.h"
  5. #include "../webuiconf.h"
  6. #include "../processor/templates/framework7/Framework7Document.hpp"
  7. #include <sys/stat.h>
  8. using namespace std;
  9. using namespace xc::processor;
  10. using namespace xc::processor::templates;
  11. using namespace configor;
  12. namespace xc::controller {
  13. ContentGeneratorDefine({
  14. if (!conf::enableStaticAssetsController) { return false; }
  15. if (request.getMethod() != "GET") { return false; }
  16. if (request.getURL().length() == 0) { return false; }
  17. struct stat buffer;
  18. string filePath = "html";
  19. if (request.getURL()[0] == '/') {
  20. filePath += request.getURL();
  21. } else {
  22. filePath += "/" + request.getURL();
  23. }
  24. if (stat(filePath.c_str(), &buffer) == 0) {
  25. if (S_ISREG(buffer.st_mode)) {
  26. return true;
  27. } else {
  28. for (auto file: conf::defaultFiles) {
  29. string newFilePath = filePath;
  30. if (filePath[filePath.length() - 1] == '/') {
  31. newFilePath += file;
  32. } else {
  33. newFilePath += "/" + file;
  34. }
  35. if (stat(newFilePath.c_str(), &buffer) == 0) {
  36. return S_ISREG(buffer.st_mode);
  37. }
  38. }
  39. }
  40. }
  41. return false;
  42. }, {
  43. struct stat buffer;
  44. string filePath = "html";
  45. if (request.getURL()[0] == '/') {
  46. filePath += request.getURL();
  47. } else {
  48. filePath += "/" + request.getURL();
  49. }
  50. if (stat(filePath.c_str(), &buffer) == 0) {
  51. if (S_ISREG(buffer.st_mode)) {
  52. return (ResponseData *) new BinaryResponseData(200, filePath,
  53. mimeTypeOfFile(filePath));
  54. } else {
  55. for (auto file: conf::defaultFiles) {
  56. string newFilePath = filePath;
  57. if (filePath[filePath.length() - 1] == '/') {
  58. newFilePath += file;
  59. } else {
  60. newFilePath += "/" + file;
  61. }
  62. if (stat(newFilePath.c_str(), &buffer) == 0) {
  63. if (S_ISREG(buffer.st_mode)) {
  64. return (ResponseData *) new BinaryResponseData(200, newFilePath,
  65. mimeTypeOfFile(
  66. newFilePath));
  67. }
  68. }
  69. }
  70. }
  71. }
  72. return (ResponseData *) new FileResponseData(conf::errorPage404);
  73. })
  74. ResponseData *test1(RequestData request) {
  75. return new TemplateResponseData({
  76. framework7::Framework7Document()
  77. });
  78. }
  79. ContentGeneratorDefineS(request.getURL() == "/test1",
  80. test1(request))
  81. ContentGeneratorDefineS(request.getURL() == "/test2",
  82. new TextResponseData(200, "test2 controller response"))
  83. }