cutelyst  4.8.0
A C++ Web Framework built on top of Qt, using the simple approach of Catalyst (Perl) framework.
staticsimple.cpp
1 /*
2  * SPDX-FileCopyrightText: (C) 2014-2022 Daniel Nicoletti <dantti12@gmail.com>
3  * SPDX-License-Identifier: BSD-3-Clause
4  */
5 #include "application.h"
6 #include "context.h"
7 #include "request.h"
8 #include "response.h"
9 #include "staticsimple_p.h"
10 
11 #include <QDateTime>
12 #include <QDir>
13 #include <QFile>
14 #include <QLoggingCategory>
15 #include <QMimeDatabase>
16 
17 using namespace Cutelyst;
18 using namespace Qt::Literals::StringLiterals;
19 
20 Q_LOGGING_CATEGORY(C_STATICSIMPLE, "cutelyst.plugin.staticsimple", QtWarningMsg)
21 
23  : Plugin(parent)
24  , d_ptr(new StaticSimplePrivate)
25 {
26  Q_D(StaticSimple);
27  d->includePaths.append(parent->config(QLatin1String("root")).toString());
28 }
29 
31 {
32  delete d_ptr;
33 }
34 
36 {
37  Q_D(StaticSimple);
38  d->includePaths.clear();
39  for (const QString &path : paths) {
40  d->includePaths.append(QDir(path));
41  }
42 }
43 
45 {
46  Q_D(StaticSimple);
47  d->dirs = dirs;
48 }
49 
50 void StaticSimple::setServeDirsOnly(bool dirsOnly)
51 {
52  Q_D(StaticSimple);
53  d->serveDirsOnly = dirsOnly;
54 }
55 
57 {
58  connect(app, &Application::beforePrepareAction, this, &StaticSimple::beforePrepareAction);
59  return true;
60 }
61 
62 void StaticSimple::beforePrepareAction(Context *c, bool *skipMethod)
63 {
64  Q_D(StaticSimple);
65 
66  if (*skipMethod) {
67  return;
68  }
69 
70  // TODO mid(1) quick fix for path now having leading slash
71  const QString path = c->req()->path().mid(1);
72  const QRegularExpression re = d->re; // Thread-safe
73 
74  for (const QString &dir : d->dirs) {
75  if (path.startsWith(dir)) {
76  if (!locateStaticFile(c, path)) {
77  Response *res = c->response();
78  res->setStatus(Response::NotFound);
79  res->setContentType("text/html"_ba);
80  res->setBody("File not found: " + path.toUtf8());
81  }
82 
83  *skipMethod = true;
84  return;
85  }
86  }
87 
88  if (d->serveDirsOnly) {
89  return;
90  }
91 
92  QRegularExpressionMatch match = re.match(path);
93  if (match.hasMatch() && locateStaticFile(c, path)) {
94  *skipMethod = true;
95  }
96 }
97 
98 bool StaticSimple::locateStaticFile(Context *c, const QString &relPath)
99 {
100  Q_D(const StaticSimple);
101 
102  for (const QDir &includePath : d->includePaths) {
103  QString path = includePath.absoluteFilePath(relPath);
104  QFileInfo fileInfo(path);
105  if (fileInfo.exists()) {
106  Response *res = c->res();
107  const QDateTime currentDateTime = fileInfo.lastModified();
108  if (!c->req()->headers().ifModifiedSince(currentDateTime)) {
109  res->setStatus(Response::NotModified);
110  return true;
111  }
112 
113  // Response::setBody() will take the ownership
114  // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
115  QFile *file = new QFile(path);
116  if (file->open(QFile::ReadOnly)) {
117  qCDebug(C_STATICSIMPLE) << "Serving" << path;
118  Headers &headers = res->headers();
119 
120  // set our open file
121  res->setBody(file);
122 
123  static QMimeDatabase db;
124  // use the extension to match to be faster
126  if (mimeType.isValid()) {
127  headers.setContentType(mimeType.name().toLatin1());
128  }
129 
130  headers.setLastModified(currentDateTime);
131  // Tell Firefox & friends its OK to cache, even over SSL
132  headers.setHeader("Cache-Control"_ba, "public"_ba);
133 
134  return true;
135  }
136 
137  qCWarning(C_STATICSIMPLE) << "Could not serve" << path << file->errorString();
138  return false;
139  }
140  }
141 
142  qCWarning(C_STATICSIMPLE) << "File not found" << relPath;
143  return false;
144 }
145 
146 #include "moc_staticsimple.cpp"
void setDirs(const QStringList &dirs)
Headers & headers() noexcept
QString errorString() const const
Response * res() const noexcept
Definition: context.cpp:104
Container for HTTP headers.
Definition: headers.h:23
void setLastModified(const QByteArray &value)
Definition: headers.cpp:272
Request req
Definition: context.h:67
virtual ~StaticSimple() override
void setContentType(const QByteArray &type)
Definition: response.h:238
A Cutelyst response.
Definition: response.h:28
The Cutelyst Context.
Definition: context.h:42
void setContentType(const QByteArray &contentType)
Definition: headers.cpp:77
Headers headers() const noexcept
Definition: request.cpp:313
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
void beforePrepareAction(Cutelyst::Context *c, bool *skipMethod)
Serve static files directly from your application.
Definition: staticsimple.h:61
virtual bool setup(Application *app) override
bool hasMatch() const const
The Cutelyst namespace holds all public Cutelyst API.
QMimeType mimeTypeForFile(const QFileInfo &fileInfo, MatchMode mode) const const
bool isValid() const const
QByteArray ifModifiedSince() const noexcept
Definition: headers.cpp:206
void setIncludePaths(const QStringList &paths)
QString mid(qsizetype position, qsizetype n) const const
QRegularExpressionMatch match(QStringView subjectView, qsizetype offset, MatchType matchType, MatchOptions matchOptions) const const
QString absoluteFilePath(const QString &fileName) const const
bool open(FILE *fh, OpenMode mode, FileHandleFlags handleFlags)
void setServeDirsOnly(bool dirsOnly)
Base class for Cutelyst Plugins.
Definition: plugin.h:24
The Cutelyst application.
Definition: application.h:72
void setBody(QIODevice *body)
Definition: response.cpp:104
Response * response() const noexcept
Definition: context.cpp:98
void setStatus(quint16 status) noexcept
Definition: response.cpp:73
void setHeader(const QByteArray &key, const QByteArray &value)
Definition: headers.cpp:437
QByteArray toUtf8() const const