cutelyst 5.1.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 "engine.h"
8#include "request.h"
9#include "response.h"
10#include "staticsimple_p.h"
11
12#include <QDateTime>
13#include <QDir>
14#include <QFile>
15#include <QLoggingCategory>
16#include <QMimeDatabase>
17
18using namespace Cutelyst;
19using namespace Qt::Literals::StringLiterals;
20
21Q_LOGGING_CATEGORY(C_STATICSIMPLE, "cutelyst.plugin.staticsimple", QtWarningMsg)
22
24 : Plugin(parent)
25 , d_ptr(new StaticSimplePrivate)
26{
27 Q_D(StaticSimple);
28 d->includePaths.append(parent->config(u"root"_s).toString());
29}
30
31StaticSimple::StaticSimple(Application *parent, const QVariantMap &defaultConfig)
32 : Plugin(parent)
33 , d_ptr(new StaticSimplePrivate)
34{
35 Q_D(StaticSimple);
36 d->includePaths.append(parent->config(u"root"_s).toString());
37 d->defaultConfig = defaultConfig;
38}
39
41{
42 delete d_ptr;
43}
44
46{
47 Q_D(StaticSimple);
48 d->includePaths.clear();
49 for (const QString &path : paths) {
50 d->includePaths.append(QDir(path));
51 }
52}
53
55{
56 Q_D(StaticSimple);
57 d->dirs = dirs;
58}
59
61{
62 Q_D(StaticSimple);
63 d->serveDirsOnly = dirsOnly;
64}
65
67{
68 Q_D(StaticSimple);
69
70 const QVariantMap config = app->engine()->config(u"Cutelyst_StaticSimple_Plugin"_s);
71
72 d->logFailedIp =
73 config.value(u"log_failed_ip"_s, d->defaultConfig.value(u"log_failed_ip"_s, false))
74 .toBool();
75
76 connect(app, &Application::beforePrepareAction, this, &StaticSimple::beforePrepareAction);
77 return true;
78}
79
80void StaticSimple::beforePrepareAction(Context *c, bool *skipMethod) const
81{
82 Q_D(const StaticSimple);
83
84 if (*skipMethod) {
85 return;
86 }
87
88 const QString path = c->req()->path().mid(1);
89 const QRegularExpression re = d->re; // Thread-safe
90
91 bool found = std::ranges::any_of(d->dirs, [&](const QString &dir) {
92 if (path.startsWith(dir)) {
93 if (!locateStaticFile(c, path)) {
94 Response *res = c->response();
95 res->setStatus(Response::NotFound);
96 res->setContentType("text/html"_ba);
97 res->setBody("File not found: " + path.toUtf8());
98 }
99 return true;
100 }
101 return false;
102 });
103
104 if (found) {
105 *skipMethod = true;
106 return;
107 }
108
109 if (d->serveDirsOnly) {
110 return;
111 }
112
113 QRegularExpressionMatch match = re.match(path);
114 if (match.hasMatch() && locateStaticFile(c, path)) {
115 *skipMethod = true;
116 }
117}
118
119bool StaticSimple::locateStaticFile(Context *c, const QString &relPath) const
120{
121 Q_D(const StaticSimple);
122
123 for (const QDir &includePath : d->includePaths) {
124 QString path = includePath.absoluteFilePath(relPath);
125 QFileInfo fileInfo(path);
126 if (fileInfo.exists()) {
127 Response *res = c->res();
128 const QDateTime currentDateTime = fileInfo.lastModified();
129 if (!c->req()->headers().ifModifiedSince(currentDateTime)) {
130 res->setStatus(Response::NotModified);
131 return true;
132 }
133
134 // Response::setBody() will take the ownership
135 // NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
136 auto file = new QFile(path);
137 if (file->open(QFile::ReadOnly)) {
138 qCDebug(C_STATICSIMPLE) << "Serving" << path;
139 Headers &headers = res->headers();
140
141 // set our open file
142 res->setBody(file);
143
144 static QMimeDatabase db;
145 // use the extension to match to be faster
146 QMimeType mimeType = db.mimeTypeForFile(path, QMimeDatabase::MatchExtension);
147 if (mimeType.isValid()) {
148 headers.setContentType(mimeType.name().toLatin1());
149 }
150
151 headers.setLastModified(currentDateTime);
152 // Tell Firefox & friends its OK to cache, even over SSL
153 headers.setHeader("Cache-Control"_ba, "public"_ba);
154
155 return true;
156 }
157
158 qCWarning(C_STATICSIMPLE) << "Could not serve" << path << file->errorString();
159 return false;
160 }
161 }
162
163 if (C_STATICSIMPLE().isWarningEnabled()) {
164 if (d->logFailedIp) {
165 qCWarning(C_STATICSIMPLE).nospace().noquote()
166 << "File not found: \"" << relPath << '"' << " [client "
167 << c->req()->addressString() << "]";
168 } else {
169 qCWarning(C_STATICSIMPLE).nospace().noquote() << "File not found: \"" << relPath << '"';
170 }
171 }
172
173 return false;
174}
175
176#include "moc_staticsimple.cpp"
The Cutelyst application.
Definition application.h:66
Engine * engine() const noexcept
void beforePrepareAction(Cutelyst::Context *c, bool *skipMethod)
The Cutelyst Context.
Definition context.h:42
Response * res() const noexcept
Definition context.cpp:104
Request * req
Definition context.h:66
QVariantMap config(const QString &entity) const
Definition engine.cpp:122
QByteArray ifModifiedSince() const noexcept
Definition headers.cpp:229
void setLastModified(const QByteArray &value)
Definition headers.cpp:295
void setContentType(const QByteArray &contentType)
Definition headers.cpp:100
void setHeader(const QByteArray &key, const QByteArray &value)
Definition headers.cpp:463
Plugin(Application *parent)
Definition plugin.cpp:12
QString addressString() const
Definition request.cpp:40
Headers headers() const noexcept
Definition request.cpp:312
Headers & headers() noexcept
Definition response.cpp:283
void setStatus(quint16 status) noexcept
Definition response.cpp:74
void setBody(QIODevice *body)
Definition response.cpp:105
Serve static files directly from your application.
void setServeDirsOnly(bool dirsOnly)
void setDirs(const QStringList &dirs)
virtual bool setup(Application *app) override
StaticSimple(Application *parent)
void setIncludePaths(const QStringList &paths)
virtual ~StaticSimple() override
The Cutelyst namespace holds all public Cutelyst API.
QString absoluteFilePath(const QString &fileName) 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)
QObject * parent() const const
QRegularExpressionMatch match(QStringView subjectView, qsizetype offset, QRegularExpression::MatchType matchType, QRegularExpression::MatchOptions matchOptions) const const
bool hasMatch() const const
QString mid(qsizetype position, qsizetype n) &&