Newer
Older
saori / saoricache.cpp
/***

The MIT License

Copyright (c) 2018 Teppei Tamra (TAM)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

***/

#include "saoricache.h"
#include "saoriapplication.h"
#include <QCryptographicHash>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QFile>
#include <QDir>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlResult>
#include <QDateTime>

/*
 * table file_cache
 *  url(text unique)
 *  filename(text)
 *  size(integer)
 *  timestamp(integer)
 *
 */

QList<QUrl> SaoriCache::m_nowloading;

SaoriCache::SaoriCache(QObject *parent) : QObject(parent)
{
    migration();
}

void SaoriCache::removeFileCache(const QUrl url)
{
    QSqlQuery query(*SaoriApplication::saori()->database());
    query.prepare("DELETE from file_cache WHERE url=?;");
    query.addBindValue(url.toString());
    query.exec();
    QFile localfile(urlToFilename(url));
    if (localfile.exists()) localfile.remove();
}

void SaoriCache::reloadFileCache(const QUrl url)
{
    removeFileCache(url);
    download(url);
}

const QString SaoriCache::fileCache(const QUrl url)
{
    if (isCached(url)) return urlToFilename(url);
    else download(url);
    return QString(":/icons/ionicons/load-a.svg");
}

bool SaoriCache::migration()
{
    if (SaoriApplication::saori()->database()->tables().contains("file_cache")) return true;
    QSqlQuery query(*SaoriApplication::saori()->database());
    return query.exec("CREATE TABLE file_cache(url TEXT UNIQUE,filename TEXT,size INTEGER,timestamp INTEGER);");
}

void SaoriCache::download(const QUrl url)
{
    if (m_nowloading.contains(url)) return;
    if (isCached(url)) return;
    m_nowloading.append(url);
    QNetworkRequest request;
    request.setUrl(url);
    auto *reply = SaoriApplication::saori()->manager->get(request);
    connect(reply,&QNetworkReply::finished,this,[=](){
        if (reply->error() == QNetworkReply::NoError) {
            QFile localfile(urlToFilename(url));
            if (localfile.exists()) localfile.remove();
            localfile.open(QIODevice::WriteOnly);
            localfile.write(reply->readAll());
            // TODO 100MBのファイルに100MBのメモリを使うのは如何なものか。
            qint64 size = localfile.size();
            localfile.close();
            QSqlQuery query(*SaoriApplication::saori()->database());
            query.prepare("INSERT INTO file_cache(url,filename,size,timestamp) values(?,?,?,?);");
            query.addBindValue(url.toString());
            query.addBindValue(urlToFilename(url));
            query.addBindValue(size);
            query.addBindValue(QDateTime::currentSecsSinceEpoch());
            query.exec();
            emit downloaded(url);
        } else {
            QSqlQuery query(*SaoriApplication::saori()->database());
            query.prepare("INSERT INTO file_cache(url,filename,size,timestamp) values(?,?,?,?);");
            query.addBindValue(url.toString());
            query.addBindValue(":/icons/ionicons/alert-circled.svg");
            query.addBindValue("-1");
            query.addBindValue(QDateTime::currentSecsSinceEpoch());
            query.exec();
            emit downloaded(url);
        }
        m_nowloading.removeAll(url);
        reply->deleteLater();
    });
}

bool SaoriCache::isCached(const QUrl url)
{
    QSqlQuery query(*SaoriApplication::saori()->database());
    query.prepare("SELECT size from file_cache WHERE url=?;");
    query.addBindValue(url.toString());
    query.exec();
    if (query.next()) {
        if (query.value(0).toInt() >= 0) return true;
    }
    return false;
}

const QString SaoriCache::urlToFilename(QUrl url)
{
    QString dir = QString::fromUtf8(QCryptographicHash::hash(url.adjusted(QUrl::RemovePath).toString().toLatin1(),QCryptographicHash::Md5).toHex());
    QString file = QString::fromUtf8(QCryptographicHash::hash(url.path().toLatin1(),QCryptographicHash::Md5).toHex());
    QDir d;
    d.mkpath(SaoriApplication::saori()->cacheDirectory().absolutePath() + "/" + dir);
    return QString(SaoriApplication::saori()->cacheDirectory().absolutePath() + "/" + dir + "/" + file);
}