Commit eef6d7e1 authored by Volker Krause's avatar Volker Krause

Implement cache expiry

parent b49195d4
......@@ -66,6 +66,8 @@ private slots:
QCOMPARE(entry.data[0].identifiers().size(), 1);
QCOMPARE(entry.data[0].identifier(QLatin1String("uic")), QLatin1String("85xxxxx"));
QCOMPARE(entry.data[0].timeZone().isValid(), false);
Cache::expire();
}
void testLocationCacheKey()
......
......@@ -16,11 +16,14 @@
*/
#include "cache.h"
#include "logging.h"
#include <KPublicTransport/Location>
#include <QDateTime>
#include <QDebug>
#include <QDir>
#include <QDirIterator>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
......@@ -29,11 +32,14 @@
using namespace KPublicTransport;
static QString cacheBasePath()
{
return QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) + QLatin1String("/org.kde.kpublictransport/backends/");
}
static QString cachePath(const QString &backendId, const QString &contentType)
{
return QStandardPaths::writableLocation(QStandardPaths::GenericCacheLocation) +
QLatin1String("/org.kde.kpublictransport/") + backendId + QLatin1Char('/') +
contentType + QLatin1Char('/');
return cacheBasePath() + backendId + QLatin1Char('/') + contentType + QLatin1Char('/');
}
void Cache::addLocationCacheEntry(const QString &backendId, const QString &cacheKey, const std::vector<Location> &data)
......@@ -74,3 +80,30 @@ CacheEntry<Location> Cache::lookupLocation(const QString &backendId, const QStri
entry.data = Location::fromJson(QJsonDocument::fromJson(f.readAll()).array());
return entry;
}
static void expireRecursive(const QString &path)
{
const auto now = QDateTime::currentDateTime();
QDirIterator it(path, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
while (it.hasNext()) {
it.next();
if (it.fileInfo().isDir()) {
expireRecursive(it.filePath());
if (QDir(it.filePath()).isEmpty()) {
qCDebug(Log) << "removing empty cache directory" << it.fileName();
QDir(path).rmdir(it.filePath());
}
}
if (it.fileInfo().lastModified().addDays(30) < now) {
qCDebug(Log) << "removing expired cache entry" << it.fileName();
QDir(path).remove(it.filePath());
}
}
}
void Cache::expire()
{
expireRecursive(cacheBasePath());
}
......@@ -54,6 +54,9 @@ namespace Cache
void addNegativeLocationCacheEntry(const QString &backendId, const QString &cacheKey);
/** Perform cache lookuip for location results. */
CacheEntry<Location> lookupLocation(const QString &backendId, const QString &cacheKey);
/** Expire old cache entries. */
void expire();
}
}
......
......@@ -145,6 +145,8 @@ Manager::Manager() :
{
initResources();
d->loadNetworks();
Cache::expire();
}
Manager::Manager(Manager&&) noexcept = default;
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment