blob: a6baba0e9ae2521ad5e92d27f7309bcf743125a2 (
plain) (
tree)
|
|
#include <QHash>
#include <QtDebug>
#include <QFile>
#include <QDir>
#include <QIcon>
#include <QResource>
#include <QFileInfo>
#include <QCryptographicHash>
#include "globals.h"
#include "sessionsiconholder.h"
#include "sessiontreemodel.h"
#include "filedownloader.h"
SessionsIconHolder* SessionsIconHolder::instance = nullptr;
static inline QString url2filename(const QString& url) {
return TEMP_PATH_ICONS + QString(QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5).toHex());
}
SessionsIconHolder::SessionsIconHolder() {
QDir().mkpath(TEMP_PATH_ICONS);
}
QIcon SessionsIconHolder::getIcon(const QString& name) {
// check if icon was loaded before
if (icons.contains(name)) {
return icons[name];
}
// else load icon from resource
QIcon icon;
QString resName(":" + name.toLower());
if (QResource(resName).isValid()) {
icon = QIcon(resName);
} else if (QFileInfo(name).isAbsolute() && QFile::exists(name)) {
// absolute icon path and file exists
icon = QIcon(name);
} else {
icon = QIcon();
}
// insert icon to hash table
icons.insert(name, icon);
return icon;
}
QIcon SessionsIconHolder::getIcon(const QUrl& url) {
// check if icon was loaded before
if (icons.contains(url.toString())) {
return icons[url.toString()];
}
// search the icon in the tmp folder
QString strUrl(url.toString());
QString file_path(url2filename(strUrl));
if (QFile::exists(file_path)) {
QIcon icon(file_path);
icons.insert(strUrl, icon);
return icon;
}
// Put empty icon in map while we're downloading, so successive calls won't trigger
// more downloads before the running download finishes
icons.insert(strUrl, QIcon());
// else load icon from url
// TODO add '--url-icon' command line option we want to reintroduce this feature (currently not used).
FileDownloader::download(url, [this, url](QNetworkReply::NetworkError, const QByteArray &downloadedData) {
// save the data to disk
QString strUrl(url.toString());
QString file_path(url2filename(strUrl));
QFile file(file_path);
if (!file.open(QFile::WriteOnly)) {
if (g_debugMode) {
qDebug() << "Could not write file: " << file_path;
}
return;
}
file.write(downloadedData);
if (file.write(downloadedData) != downloadedData.length()) {
if (g_debugMode) {
qDebug() << "Could not write file: " << file_path;
}
return;
}
file.close();
QIcon icon(file_path);
icons.insert(strUrl, icon);
emit iconDownloaded(url, icon);
});
return QIcon();
}
|