Newer
Older
saori / saoricache.cpp
@TAM (Teppei Tamra) TAM (Teppei Tamra) on 23 May 2018 5 KB アイコン名をdefine。
/***

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 "saoridef.h"
#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();
    m_thread = new QThread;
    m_downloader = new SaoriDownloader;
    m_downloader->moveToThread(m_thread);
    connect(this,&SaoriCache::initDownloader,m_downloader,&SaoriDownloader::initialize,Qt::QueuedConnection);
    connect(this,&SaoriCache::get,m_downloader,&SaoriDownloader::get,Qt::QueuedConnection);
    connect(m_downloader,&SaoriDownloader::downloaded,this,&SaoriCache::downloadFinished,Qt::QueuedConnection);
    connect(m_downloader,&SaoriDownloader::error,this,&SaoriCache::networkError,Qt::QueuedConnection);
    m_thread->start();
    emit initDownloader();
}

SaoriCache::~SaoriCache()
{
    m_thread->exit();
}

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(SAORI_ICONS_LOADING);
}

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);
    emit get(request);
}

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);
}

void SaoriCache::downloadFinished(QNetworkRequest req, QByteArray data)
{
    QFile localfile(urlToFilename(req.url()));
    if (localfile.exists()) localfile.remove();
    localfile.open(QIODevice::WriteOnly);
    localfile.write(data);
    // 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(req.url().toString());
    query.addBindValue(urlToFilename(req.url()));
    query.addBindValue(size);
    query.addBindValue(QDateTime::currentSecsSinceEpoch());
    query.exec();
    emit downloaded(req.url());
    m_nowloading.removeAll(req.url());
}

void SaoriCache::networkError(QNetworkRequest req, QNetworkReply::NetworkError error)
{
    if (error == QNetworkReply::NoError) return;
    QSqlQuery query(*SaoriApplication::saori()->database());
    query.prepare("INSERT INTO file_cache(url,filename,size,timestamp) values(?,?,?,?);");
    query.addBindValue(req.url().toString());
    query.addBindValue(SAORI_ICONS_ALERT);
    query.addBindValue("-1");
    query.addBindValue(QDateTime::currentSecsSinceEpoch());
    query.exec();
    emit downloaded(req.url());
}