File indexing completed on 2024-04-14 15:46:43
0001 /* This file is part of inqludeclient 0002 * Copyright 2014 David Faure <faure@kde.org> 0003 * 0004 * This library is free software; you can redistribute it and/or modify 0005 * it under the terms of the GNU Lesser General Public License as published by 0006 * the Free Software Foundation; either version 2 of the License or ( at 0007 * your option ) version 3 or, at the discretion of KDE e.V. ( which shall 0008 * act as a proxy as in section 14 of the GPLv3 ), any later version. 0009 * 0010 * This library is distributed in the hope that it will be useful, 0011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 0012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 0013 * Library General Public License for more details. 0014 * 0015 * You should have received a copy of the GNU Lesser General Public License 0016 * along with this library; see the file COPYING.LIB. If not, write to 0017 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, 0018 * Boston, MA 02110-1301, USA. 0019 */ 0020 0021 #include "httpdataprovider.h" 0022 #include <QFile> 0023 #include <QDir> 0024 #include <QJsonDocument> 0025 #include <QDebug> 0026 #include <QNetworkReply> 0027 #include <QNetworkAccessManager> 0028 0029 #include <iostream> 0030 0031 HttpDataProvider::HttpDataProvider(const QString &cacheFile) 0032 : m_qnam(new QNetworkAccessManager(this)), 0033 m_cacheFile(cacheFile) 0034 { 0035 } 0036 0037 HttpDataProvider::~HttpDataProvider() 0038 { 0039 } 0040 0041 void HttpDataProvider::ensureDataAvailable() 0042 { 0043 std::cerr << "Downloading library information, please wait..." << std::endl; 0044 QUrl url("https://inqlude.org/inqlude-all.json"); 0045 QNetworkRequest request(url); 0046 request.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true); 0047 QNetworkReply* reply = m_qnam->get(request); 0048 connect(m_qnam, &QNetworkAccessManager::finished, this, &HttpDataProvider::slotFinished); 0049 } 0050 0051 void HttpDataProvider::slotFinished(QNetworkReply *reply) 0052 { 0053 const QByteArray data = reply->readAll(); // QJsonDocument can't read from a QIODevice ! 0054 reply->deleteLater(); 0055 if (data.isEmpty()) { 0056 qWarning() << "Empty document downloaded"; 0057 emit error(); 0058 return; 0059 } 0060 QJsonParseError jsonError; 0061 const QJsonDocument doc = QJsonDocument::fromJson(data, &jsonError); 0062 if (doc.isNull()) { 0063 qWarning() << "Error parsing JSON document:" << jsonError.errorString() << "at offset" << jsonError.offset; 0064 emit error(); 0065 return; 0066 } 0067 // Write out cache 0068 QDir().mkpath(QFileInfo(m_cacheFile).absolutePath()); 0069 QFile file(m_cacheFile); 0070 if (file.open(QIODevice::WriteOnly)) { 0071 file.write(data); 0072 } 0073 emit dataAvailable(doc); 0074 }