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