1
mirror of https://invent.kde.org/network/falkon.git synced 2024-12-20 18:56:34 +01:00

Remove dependency on deprecated QtScript

This commit is contained in:
David Rosca 2015-12-18 11:25:45 +01:00
parent e4b5a416b3
commit cbc83e81ba
14 changed files with 27 additions and 1020 deletions

View File

@ -23,9 +23,9 @@
#include "datapaths.h" #include "datapaths.h"
#include "settings.h" #include "settings.h"
#include "qztools.h" #include "qztools.h"
#include "json.h"
#include <QFile> #include <QFile>
#include <QJsonDocument>
Bookmarks::Bookmarks(QObject* parent) Bookmarks::Bookmarks(QObject* parent)
: QObject(parent) : QObject(parent)
@ -231,15 +231,11 @@ void Bookmarks::loadBookmarks()
const QString bookmarksFile = DataPaths::currentProfilePath() + QLatin1String("/bookmarks.json"); const QString bookmarksFile = DataPaths::currentProfilePath() + QLatin1String("/bookmarks.json");
const QString backupFile = bookmarksFile + QLatin1String(".old"); const QString backupFile = bookmarksFile + QLatin1String(".old");
QFile file(bookmarksFile); QJsonParseError err;
file.open(QFile::ReadOnly); QJsonDocument json = QJsonDocument::fromJson(QzTools::readAllFileByteContents(bookmarksFile), &err);
QByteArray data = file.readAll(); const QVariant res = json.toVariant();
file.close();
Json json; if (err.error != QJsonParseError::NoError || res.type() != QVariant::Map) {
const QVariant res = json.parse(QString::fromUtf8(data));
if (!json.ok() || res.type() != QVariant::Map) {
qWarning() << "Bookmarks::init() Error parsing bookmarks! Using default bookmarks!"; qWarning() << "Bookmarks::init() Error parsing bookmarks! Using default bookmarks!";
qWarning() << "Bookmarks::init() Your bookmarks have been backed up in" << backupFile; qWarning() << "Bookmarks::init() Your bookmarks have been backed up in" << backupFile;
@ -248,9 +244,10 @@ void Bookmarks::loadBookmarks()
QFile::copy(bookmarksFile, backupFile); QFile::copy(bookmarksFile, backupFile);
// Load default bookmarks // Load default bookmarks
const QVariant data = json.parse(QzTools::readAllFileContents(":data/bookmarks.json")); json = QJsonDocument::fromJson(QzTools::readAllFileByteContents(QSL(":data/bookmarks.json")), &err);
const QVariant data = json.toVariant();
Q_ASSERT(json.ok()); Q_ASSERT(err.error == QJsonParseError::NoError);
Q_ASSERT(data.type() == QVariant::Map); Q_ASSERT(data.type() == QVariant::Map);
loadBookmarksFromMap(data.toMap().value("roots").toMap()); loadBookmarksFromMap(data.toMap().value("roots").toMap());
@ -286,10 +283,10 @@ void Bookmarks::saveBookmarks()
map.insert("version", Qz::bookmarksVersion); map.insert("version", Qz::bookmarksVersion);
map.insert("roots", bookmarksMap); map.insert("roots", bookmarksMap);
Json json; const QJsonDocument json = QJsonDocument::fromVariant(map);
const QString data = json.serialize(map); const QByteArray data = json.toJson();
if (!json.ok() || data.isEmpty()) { if (data.isEmpty()) {
qWarning() << "Bookmarks::saveBookmarks() Error serializing bookmarks!"; qWarning() << "Bookmarks::saveBookmarks() Error serializing bookmarks!";
return; return;
} }
@ -300,7 +297,7 @@ void Bookmarks::saveBookmarks()
qWarning() << "Bookmarks::saveBookmarks() Error opening bookmarks file for writing!"; qWarning() << "Bookmarks::saveBookmarks() Error opening bookmarks file for writing!";
} }
file.write(data.toUtf8()); file.write(data);
file.close(); file.close();
} }

View File

@ -17,11 +17,11 @@
* ============================================================ */ * ============================================================ */
#include "chromeimporter.h" #include "chromeimporter.h"
#include "bookmarkitem.h" #include "bookmarkitem.h"
#include "json.h"
#include <QDir> #include <QDir>
#include <QFileDialog> #include <QFileDialog>
#include <QVariantList> #include <QVariantList>
#include <QJsonDocument>
ChromeImporter::ChromeImporter(QObject* parent) ChromeImporter::ChromeImporter(QObject* parent)
: BookmarksImporter(parent) : BookmarksImporter(parent)
@ -63,13 +63,14 @@ bool ChromeImporter::prepareImport()
BookmarkItem* ChromeImporter::importBookmarks() BookmarkItem* ChromeImporter::importBookmarks()
{ {
QString bookmarks = QString::fromUtf8(m_file.readAll()); const QByteArray data = m_file.readAll();
m_file.close(); m_file.close();
Json json; QJsonParseError err;
const QVariant res = json.parse(bookmarks); QJsonDocument json = QJsonDocument::fromJson(data);
const QVariant res = json.toVariant();
if (!json.ok() || res.type() != QVariant::Map) { if (err.error != QJsonParseError::NoError || res.type() != QVariant::Map) {
setError(BookmarksImporter::tr("Cannot parse JSON file!")); setError(BookmarksImporter::tr("Cannot parse JSON file!"));
return 0; return 0;
} }

View File

@ -1,4 +1,4 @@
QT += webenginecore webenginewidgets webchannel network widgets sql script quickwidgets QT += webenginecore webenginewidgets webchannel network widgets sql quickwidgets
TARGET = QupZilla TARGET = QupZilla
TEMPLATE = lib TEMPLATE = lib
@ -128,8 +128,6 @@ SOURCES += \
network/networkmanager.cpp \ network/networkmanager.cpp \
network/networkproxyfactory.cpp \ network/networkproxyfactory.cpp \
network/networkurlinterceptor.cpp \ network/networkurlinterceptor.cpp \
network/pac/pacmanager.cpp \
network/pac/proxyautoconfig.cpp \
#network/schemehandlers/fileschemehandler.cpp \ #network/schemehandlers/fileschemehandler.cpp \
network/schemehandlers/qupzillaschemehandler.cpp \ network/schemehandlers/qupzillaschemehandler.cpp \
network/sslerrordialog.cpp \ network/sslerrordialog.cpp \
@ -200,7 +198,6 @@ SOURCES += \
tools/html5permissions/html5permissionsnotification.cpp \ tools/html5permissions/html5permissionsnotification.cpp \
tools/iconfetcher.cpp \ tools/iconfetcher.cpp \
tools/iconprovider.cpp \ tools/iconprovider.cpp \
tools/json.cpp \
tools/listitemdelegate.cpp \ tools/listitemdelegate.cpp \
tools/mactoolbutton.cpp \ tools/mactoolbutton.cpp \
tools/menubar.cpp \ tools/menubar.cpp \
@ -313,9 +310,6 @@ HEADERS += \
network/networkmanager.h \ network/networkmanager.h \
network/networkproxyfactory.h \ network/networkproxyfactory.h \
network/networkurlinterceptor.h \ network/networkurlinterceptor.h \
network/pac/pacdatetime.h \
network/pac/pacmanager.h \
network/pac/proxyautoconfig.h \
#network/schemehandlers/fileschemehandler.h \ #network/schemehandlers/fileschemehandler.h \
network/schemehandlers/qupzillaschemehandler.h \ network/schemehandlers/qupzillaschemehandler.h \
network/urlinterceptor.h \ network/urlinterceptor.h \
@ -389,7 +383,6 @@ HEADERS += \
tools/html5permissions/html5permissionsnotification.h \ tools/html5permissions/html5permissionsnotification.h \
tools/iconfetcher.h \ tools/iconfetcher.h \
tools/iconprovider.h \ tools/iconprovider.h \
tools/json.h \
tools/listitemdelegate.h \ tools/listitemdelegate.h \
tools/mactoolbutton.h \ tools/mactoolbutton.h \
tools/menubar.h \ tools/menubar.h \

View File

@ -18,7 +18,6 @@
#include "networkproxyfactory.h" #include "networkproxyfactory.h"
#include "mainapplication.h" #include "mainapplication.h"
#include "settings.h" #include "settings.h"
#include "pac/pacmanager.h"
WildcardMatcher::WildcardMatcher(const QString &pattern) WildcardMatcher::WildcardMatcher(const QString &pattern)
: m_regExp(0) : m_regExp(0)
@ -62,7 +61,6 @@ bool WildcardMatcher::match(const QString &str) const
NetworkProxyFactory::NetworkProxyFactory() NetworkProxyFactory::NetworkProxyFactory()
: QNetworkProxyFactory() : QNetworkProxyFactory()
, m_pacManager(new PacManager)
, m_proxyPreference(SystemProxy) , m_proxyPreference(SystemProxy)
, m_proxyType(QNetworkProxy::HttpProxy) , m_proxyType(QNetworkProxy::HttpProxy)
, m_port(0) , m_port(0)
@ -98,13 +96,6 @@ void NetworkProxyFactory::loadSettings()
foreach (const QString &exception, exceptions) { foreach (const QString &exception, exceptions) {
m_proxyExceptions.append(new WildcardMatcher(exception.trimmed())); m_proxyExceptions.append(new WildcardMatcher(exception.trimmed()));
} }
m_pacManager->loadSettings();
}
PacManager* NetworkProxyFactory::pacManager() const
{
return m_pacManager;
} }
NetworkProxyFactory::ProxyPreference NetworkProxyFactory::proxyPreference() const NetworkProxyFactory::ProxyPreference NetworkProxyFactory::proxyPreference() const
@ -135,7 +126,7 @@ QList<QNetworkProxy> NetworkProxyFactory::queryProxy(const QNetworkProxyQuery &q
break; break;
case ProxyAutoConfig: case ProxyAutoConfig:
proxyList.append(m_pacManager->queryProxy(query.url())); qWarning() << "PAC Not Implemented!";
break; break;
case DefinedProxy: { case DefinedProxy: {

View File

@ -24,8 +24,6 @@
#include "qzcommon.h" #include "qzcommon.h"
#include "qzregexp.h" #include "qzregexp.h"
class PacManager;
class WildcardMatcher class WildcardMatcher
{ {
public: public:
@ -52,14 +50,11 @@ public:
void loadSettings(); void loadSettings();
PacManager* pacManager() const;
ProxyPreference proxyPreference() const; ProxyPreference proxyPreference() const;
QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery &query = QNetworkProxyQuery()); QList<QNetworkProxy> queryProxy(const QNetworkProxyQuery &query = QNetworkProxyQuery());
private: private:
PacManager* m_pacManager;
ProxyPreference m_proxyPreference; ProxyPreference m_proxyPreference;
QNetworkProxy::ProxyType m_proxyType; QNetworkProxy::ProxyType m_proxyType;

View File

@ -1,186 +0,0 @@
/*
* The following subset of Javascript code was taken from Mozilla (http://www.mozilla.org)
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: NPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Netscape Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Akhil Arora <akhil.arora@sun.com>
* Tomi Leppikangas <Tomi.Leppikangas@oulu.fi>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#define PAC_DATETIME_JAVASCRIPT \
"var wdays = {SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6};\n" \
"var months = {JAN: 0, FEB: 1, MAR: 2, APR: 3, MAY: 4, JUN: 5, JUL: 6, AUG: 7, SEP: 8, OCT: 9, NOV: 10, DEC: 11};\n"\
"function weekdayRange() {\n" \
" function getDay(weekday) {\n" \
" if (weekday in wdays) {\n" \
" return wdays[weekday];\n" \
" }\n" \
" return -1;\n" \
" }\n" \
" var date = new Date();\n" \
" var argc = arguments.length;\n" \
" var wday;\n" \
" if (argc < 1)\n" \
" return false;\n" \
" if (arguments[argc - 1] == 'GMT') {\n" \
" argc--;\n" \
" wday = date.getUTCDay();\n" \
" } else {\n" \
" wday = date.getDay();\n" \
" }\n" \
" var wd1 = getDay(arguments[0]);\n" \
" var wd2 = (argc == 2) ? getDay(arguments[1]) : wd1;\n" \
" return (wd1 == -1 || wd2 == -1) ? false\n" \
" : (wd1 <= wday && wday <= wd2);\n" \
"}\n" \
"function dateRange() {\n" \
" function getMonth(name) {\n" \
" if (name in months) {\n" \
" return months[name];\n" \
" }\n" \
" return -1;\n" \
" }\n" \
" var date = new Date();\n" \
" var argc = arguments.length;\n" \
" if (argc < 1) {\n" \
" return false;\n" \
" }\n" \
" var isGMT = (arguments[argc - 1] == 'GMT');\n" \
" if (isGMT) {\n" \
" argc--;\n" \
" }\n" \
" if (argc == 1) {\n" \
" var tmp = parseInt(arguments[0]);\n" \
" if (isNaN(tmp)) {\n" \
" return ((isGMT ? date.getUTCMonth() : date.getMonth()) == getMonth(arguments[0]));\n" \
" } else if (tmp < 32) {\n" \
" return ((isGMT ? date.getUTCDate() : date.getDate()) == tmp);\n" \
" } else {\n" \
" return ((isGMT ? date.getUTCFullYear() : date.getFullYear()) == tmp);\n" \
" }\n" \
" }\n" \
" var year = date.getFullYear();\n" \
" var date1, date2;\n" \
" date1 = new Date(year, 0, 1, 0, 0, 0);\n" \
" date2 = new Date(year, 11, 31, 23, 59, 59);\n" \
" var adjustMonth = false;\n" \
" for (var i = 0; i < (argc >> 1); i++) {\n" \
" var tmp = parseInt(arguments[i]);\n" \
" if (isNaN(tmp)) {\n" \
" var mon = getMonth(arguments[i]);\n" \
" date1.setMonth(mon);\n" \
" } else if (tmp < 32) {\n" \
" adjustMonth = (argc <= 2);\n" \
" date1.setDate(tmp);\n" \
" } else {\n" \
" date1.setFullYear(tmp);\n" \
" }\n" \
" }\n" \
" for (var i = (argc >> 1); i < argc; i++) {\n" \
" var tmp = parseInt(arguments[i]);\n" \
" if (isNaN(tmp)) {\n" \
" var mon = getMonth(arguments[i]);\n" \
" date2.setMonth(mon);\n" \
" } else if (tmp < 32) {\n" \
" date2.setDate(tmp);\n" \
" } else {\n" \
" date2.setFullYear(tmp);\n" \
" }\n" \
" }\n" \
" if (adjustMonth) {\n" \
" date1.setMonth(date.getMonth());\n" \
" date2.setMonth(date.getMonth());\n" \
" }\n" \
" if (isGMT) {\n" \
" var tmp = date;\n" \
" tmp.setFullYear(date.getUTCFullYear());\n" \
" tmp.setMonth(date.getUTCMonth());\n" \
" tmp.setDate(date.getUTCDate());\n" \
" tmp.setHours(date.getUTCHours());\n" \
" tmp.setMinutes(date.getUTCMinutes());\n" \
" tmp.setSeconds(date.getUTCSeconds());\n" \
" date = tmp;\n" \
" }\n" \
" return ((date1 <= date) && (date <= date2));\n" \
"}\n" \
"function timeRange() {\n" \
" var argc = arguments.length;\n" \
" var date = new Date();\n" \
" var isGMT= false;\n" \
" if (argc < 1) {\n" \
" return false;\n" \
" }\n" \
" if (arguments[argc - 1] == 'GMT') {\n" \
" isGMT = true;\n" \
" argc--;\n" \
" }\n" \
" var hour = isGMT ? date.getUTCHours() : date.getHours();\n" \
" var date1, date2;\n" \
" date1 = new Date();\n" \
" date2 = new Date();\n" \
" if (argc == 1) {\n" \
" return (hour == arguments[0]);\n" \
" } else if (argc == 2) {\n" \
" return ((arguments[0] <= hour) && (hour <= arguments[1]));\n" \
" } else {\n" \
" switch (argc) {\n" \
" case 6:\n" \
" date1.setSeconds(arguments[2]);\n" \
" date2.setSeconds(arguments[5]);\n" \
" case 4:\n" \
" var middle = argc >> 1;\n" \
" date1.setHours(arguments[0]);\n" \
" date1.setMinutes(arguments[1]);\n" \
" date2.setHours(arguments[middle]);\n" \
" date2.setMinutes(arguments[middle + 1]);\n" \
" if (middle == 2) {\n" \
" date2.setSeconds(59);\n" \
" }\n" \
" break;\n" \
" default:\n" \
" throw 'timeRange: bad number of arguments'\n" \
" }\n" \
" }\n" \
" if (isGMT) {\n" \
" date.setFullYear(date.getUTCFullYear());\n" \
" date.setMonth(date.getUTCMonth());\n" \
" date.setDate(date.getUTCDate());\n" \
" date.setHours(date.getUTCHours());\n" \
" date.setMinutes(date.getUTCMinutes());\n" \
" date.setSeconds(date.getUTCSeconds());\n" \
" }\n" \
" return ((date1 <= date) && (date <= date2));\n" \
"}\n" \
""

View File

@ -1,167 +0,0 @@
/* ============================================================
* QupZilla - WebKit based browser
* Copyright (C) 2013-2014 David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#include "pacmanager.h"
#include "proxyautoconfig.h"
#include "mainapplication.h"
#include "networkmanager.h"
#include "followredirectreply.h"
#include "settings.h"
#include "datapaths.h"
#include "qztools.h"
#include <QNetworkProxy>
#include <QStringList>
#include <QUrl>
#include <QFile>
PacManager::PacManager(QObject* parent)
: QObject(parent)
, m_pacrunner(0)
, m_reply(0)
, m_loaded(false)
{
}
void PacManager::loadSettings()
{
QUrl oldUrl = m_url;
Settings settings;
settings.beginGroup("Web-Proxy");
m_url = settings.value("PacUrl", QUrl()).toUrl();
settings.endGroup();
if (m_loaded && oldUrl != m_url) {
downloadPacFile();
}
m_loaded = true;
}
void PacManager::downloadPacFile()
{
if (m_reply) {
qWarning() << "PacManager: PAC file is already being downloaded!";
return;
}
if (m_url.scheme() == QLatin1String("file")) {
if (!QFile(m_url.path()).exists()) {
qWarning() << "PacManager: PAC file " << m_url.path() << "doesn't exists!";
}
else {
reloadScript();
}
return;
}
m_reply = new FollowRedirectReply(m_url, mApp->networkManager());
connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
}
QList<QNetworkProxy> PacManager::queryProxy(const QUrl &url)
{
if (!m_pacrunner) {
reloadScript();
}
QString proxyString = m_pacrunner->findProxyForUrl(url.toEncoded(), url.host());
return parseProxies(proxyString.trimmed());
}
void PacManager::replyFinished()
{
if (m_reply->error() != QNetworkReply::NoError) {
qWarning() << "PacManager: Cannot download PAC file from" << m_url;
m_reply->deleteLater();
m_reply = 0;
return;
}
QByteArray data = m_reply->readAll();
m_reply->deleteLater();
m_reply = 0;
QFile file(DataPaths::currentProfilePath() + "/proxy.pac");
if (!file.open(QFile::WriteOnly)) {
qWarning() << "PacManager: Cannot open PAC file for writing" << file.fileName();
return;
}
file.write(data);
file.close();
reloadScript();
}
void PacManager::reloadScript()
{
if (!m_pacrunner) {
m_pacrunner = new ProxyAutoConfig(this);
}
QFile file(m_url.scheme() == QLatin1String("file") ? m_url.path() : DataPaths::currentProfilePath() + "/proxy.pac");
if (!file.open(QFile::ReadOnly)) {
qWarning() << "PacManager: Cannot open PAC file for reading" << file.fileName();
return;
}
m_pacrunner->setConfig(file.readAll());
}
QList<QNetworkProxy> PacManager::parseProxies(const QString &string)
{
QString str = string.trimmed();
QList<QNetworkProxy> proxies;
if (str.isEmpty()) {
return proxies;
}
QStringList parts = str.split(QLatin1Char(';'), QString::SkipEmptyParts);
if (parts.isEmpty()) {
parts.append(str);
}
foreach (const QString &s, parts) {
QStringList l = s.split(QLatin1Char(' '), QString::SkipEmptyParts);
if (l.count() != 2) {
if (l.count() == 1 && l.at(0) == QLatin1String("DIRECT")) {
proxies.append(QNetworkProxy::NoProxy);
}
continue;
}
QString type = l.at(0);
QUrl url = QUrl::fromEncoded("proxy://" + l.at(1).toUtf8());
if (type == QLatin1String("PROXY")) {
QNetworkProxy proxy(QNetworkProxy::HttpProxy, url.host(), url.port(8080));
proxies.append(proxy);
}
else if (type == QLatin1String("SOCKS")) {
QNetworkProxy proxy(QNetworkProxy::Socks5Proxy, url.host(), url.port(1080));
proxies.append(proxy);
}
}
return proxies;
}

View File

@ -1,57 +0,0 @@
/* ============================================================
* QupZilla - WebKit based browser
* Copyright (C) 2013-2014 David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#ifndef PACMANAGER_H
#define PACMANAGER_H
#include <QObject>
#include <QList>
#include <QUrl>
#include "qzcommon.h"
class QNetworkProxy;
class FollowRedirectReply;
class ProxyAutoConfig;
class QUPZILLA_EXPORT PacManager : public QObject
{
Q_OBJECT
public:
explicit PacManager(QObject* parent = 0);
void loadSettings();
void downloadPacFile();
QList<QNetworkProxy> queryProxy(const QUrl &url);
private slots:
void replyFinished();
private:
void reloadScript();
QList<QNetworkProxy> parseProxies(const QString &string);
ProxyAutoConfig* m_pacrunner;
FollowRedirectReply* m_reply;
bool m_loaded;
QUrl m_url;
};
#endif // PACMANAGER_H

View File

@ -1,269 +0,0 @@
/* ============================================================
* QupZilla - WebKit based browser
* Copyright (C) 2013-2014 David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#include "proxyautoconfig.h"
#include "pacdatetime.h"
#include "qztools.h"
#include "qzregexp.h"
#include <QScriptEngine>
#include <QNetworkInterface>
#include <QHostAddress>
#include <QHostInfo>
#include <QRegExp>
/**
* Class implementing the proxy auto-configuration (PAC) JavaScript api.
*
* Based on qt-examples: https://gitorious.org/qt-examples/qt-examples/blobs/master/pac-files
*/
ProxyAutoConfig::ProxyAutoConfig(QObject* parent)
: QObject(parent)
, m_engine(new QScriptEngine(this))
{
install();
}
void ProxyAutoConfig::setConfig(const QString &config)
{
m_engine->evaluate(config);
}
// string findProxyForUrl url host
QString ProxyAutoConfig::findProxyForUrl(const QString &url, const QString &host)
{
QScriptValue global = m_engine->globalObject();
QScriptValue fun = global.property("FindProxyForURL");
if (!fun.isFunction()) {
return QString("DIRECT");
}
QScriptValueList args;
args << m_engine->toScriptValue(url) << m_engine->toScriptValue(host);
QScriptValue val = fun.call(global, args);
if (val.isError()) {
qWarning() << "PAC Error:" << val.toString();
return QString("DIRECT");
}
return val.toString();
}
QScriptValue ProxyAutoConfig::evaluate(const QString &source)
{
return m_engine->evaluate(source);
}
void ProxyAutoConfig::install()
{
QScriptValue globalObject = m_engine->globalObject();
QScriptValue fun;
fun = m_engine->newFunction(debug);
globalObject.setProperty("debug", fun);
fun = m_engine->newFunction(isPlainHostName);
globalObject.setProperty("isPlainHostName", fun);
fun = m_engine->newFunction(dnsDomainIs);
globalObject.setProperty("dnsDomainIs", fun);
fun = m_engine->newFunction(localHostOrDomainIs);
globalObject.setProperty("localHostOrDomainIs", fun);
fun = m_engine->newFunction(isResolvable);
globalObject.setProperty("isResolvable", fun);
fun = m_engine->newFunction(isInNet);
globalObject.setProperty("isInNet", fun);
fun = m_engine->newFunction(dnsResolve);
globalObject.setProperty("dnsResolve", fun);
fun = m_engine->newFunction(myIpAddress);
globalObject.setProperty("myIpAddress", fun);
fun = m_engine->newFunction(dnsDomainLevels);
globalObject.setProperty("dnsDomainLevels", fun);
fun = m_engine->newFunction(shExpMatch);
globalObject.setProperty("shExpMatch", fun);
m_engine->evaluate(PAC_DATETIME_JAVASCRIPT);
}
QScriptValue ProxyAutoConfig::debug(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 1) {
return context->throwError("Debug takes one argument");
}
qDebug() << context->argument(0).toString();
return engine->undefinedValue();
}
// bool isPlainHostName host
QScriptValue ProxyAutoConfig::isPlainHostName(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 1) {
return context->throwError("isPlainHostName takes one argument");
}
bool ret = !context->argument(0).toString().contains(QLatin1Char('.'));
return QScriptValue(engine, ret);
}
// bool dnsDomainIs host domain
QScriptValue ProxyAutoConfig::dnsDomainIs(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 2) {
return context->throwError("dnsDomainIs takes two arguments");
}
QString host = context->argument(0).toString();
QString domain = context->argument(1).toString();
if (host.startsWith(QLatin1Char('.'))) {
host = host.mid(1);
}
if (domain.startsWith(QLatin1Char('.'))) {
domain = domain.mid(1);
}
return QScriptValue(engine, QzTools::matchDomain(domain, host));
}
// bool localHostOrDomainIs host hostdom
QScriptValue ProxyAutoConfig::localHostOrDomainIs(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 2) {
return context->throwError("localHostOrDomainIs takes two arguments");
}
QString host = context->argument(0).toString();
QString hostdom = context->argument(1).toString();
bool ret = !host.contains(QLatin1Char('.')) ? hostdom.startsWith(host) : host == hostdom;
return QScriptValue(engine, ret);
}
static QList<QHostAddress> hostResolve(const QString &host)
{
QHostInfo info = QHostInfo::fromName(host);
return info.addresses();
}
// bool isResolvable host
QScriptValue ProxyAutoConfig::isResolvable(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 1) {
return context->throwError("isResolvable takes one arguments");
}
QString host = context->argument(0).toString();
return QScriptValue(engine, !hostResolve(host).isEmpty());
}
// bool isInNet host pattern mask
QScriptValue ProxyAutoConfig::isInNet(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 3) {
return context->throwError("isInNet takes three arguments");
}
QHostAddress host(context->argument(0).toString());
QHostAddress pattern(context->argument(1).toString());
QHostAddress mask(context->argument(2).toString());
if (host.isNull()) {
QList<QHostAddress> addresses = hostResolve(context->argument(0).toString());
host = addresses.isEmpty() ? QHostAddress() : addresses.at(0);
}
if ((pattern.toIPv4Address() & mask.toIPv4Address()) == (host.toIPv4Address() & mask.toIPv4Address())) {
return QScriptValue(engine, true);
}
return QScriptValue(engine, false);
}
// string dnsResolve hostname
QScriptValue ProxyAutoConfig::dnsResolve(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 1) {
return context->throwError("dnsResolve takes one arguments");
}
QString host = context->argument(0).toString();
QList<QHostAddress> addresses = hostResolve(host);
if (addresses.isEmpty()) {
return engine->nullValue();
}
return QScriptValue(engine, addresses.at(0).toString());
}
// string myIpAddress
QScriptValue ProxyAutoConfig::myIpAddress(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 0) {
return context->throwError("myIpAddress takes no arguments");
}
foreach (QHostAddress address, QNetworkInterface::allAddresses()) {
if (address != QHostAddress::LocalHost && address != QHostAddress::LocalHostIPv6)
return QScriptValue(engine, address.toString());
}
return engine->undefinedValue();
}
// int dnsDomainLevels host
QScriptValue ProxyAutoConfig::dnsDomainLevels(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 1) {
return context->throwError("dnsDomainLevels takes one argument");
}
QString host = context->argument(0).toString();
return QScriptValue(engine, host.count(QLatin1Char('.')));
}
// bool shExpMatch str shexp
QScriptValue ProxyAutoConfig::shExpMatch(QScriptContext* context, QScriptEngine* engine)
{
if (context->argumentCount() != 2) {
return context->throwError("shExpMatch takes two arguments");
}
QString str = context->argument(0).toString();
QString shexp = context->argument(1).toString();
shexp.replace(QLatin1Char('.'), QLatin1String("\\."))
.replace(QLatin1Char('*'), QLatin1String(".*"))
.replace(QLatin1Char('?'), QLatin1Char('.'));
shexp = QString("^%1$").arg(shexp);
QzRegExp re(shexp);
bool ret = re.indexIn(str) != -1;
return QScriptValue(engine, ret);
}

View File

@ -1,79 +0,0 @@
/* ============================================================
* QupZilla - WebKit based browser
* Copyright (C) 2013-2014 David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#ifndef PROXYAUTOCONFIG_H
#define PROXYAUTOCONFIG_H
#include <QObject>
#include <QScriptValue>
#include "qzcommon.h"
class QScriptContext;
class QScriptEngine;
/**
* Class implementing the proxy auto-configuration (PAC) JavaScript api.
*
* Based on qt-examples: https://gitorious.org/qt-examples/qt-examples/blobs/master/pac-files
*/
class QUPZILLA_EXPORT ProxyAutoConfig : public QObject
{
Q_OBJECT
public:
explicit ProxyAutoConfig(QObject* parent = 0);
// Call this to set the script to be executed. Note that the argument should be
// the content of the .pac file to be used, not the URL where it is located.
void setConfig(const QString &config);
// Returns the result
QString findProxyForUrl(const QString &url, const QString &host);
protected:
QScriptValue evaluate(const QString &source);
private:
void install();
// Debug
static QScriptValue debug(QScriptContext* context, QScriptEngine* engine);
// Hostname based conditions
static QScriptValue isPlainHostName(QScriptContext* context, QScriptEngine* engine);
static QScriptValue dnsDomainIs(QScriptContext* context, QScriptEngine* engine);
static QScriptValue localHostOrDomainIs(QScriptContext* context, QScriptEngine* engine);
static QScriptValue isResolvable(QScriptContext* context, QScriptEngine* engine);
static QScriptValue isInNet(QScriptContext* context, QScriptEngine* engine);
// Related utility functions
static QScriptValue dnsResolve(QScriptContext* context, QScriptEngine* engine);
static QScriptValue myIpAddress(QScriptContext* context, QScriptEngine* engine);
static QScriptValue dnsDomainLevels(QScriptContext* context, QScriptEngine* engine);
// URL/hostname based conditions
static QScriptValue shExpMatch(QScriptContext* context, QScriptEngine* engine);
// Time based conditions
// Implemented in JavaScript
private:
QScriptEngine* m_engine;
};
#endif // PROXYAUTOCONFIG_H

View File

@ -37,7 +37,6 @@
#include "opensearchengine.h" #include "opensearchengine.h"
#include "qzregexp.h" #include "qzregexp.h"
#include "opensearchenginedelegate.h" #include "opensearchenginedelegate.h"
#include "json.h"
#include <qbuffer.h> #include <qbuffer.h>
#include <qcoreapplication.h> #include <qcoreapplication.h>
@ -48,6 +47,7 @@
#include <qstringlist.h> #include <qstringlist.h>
#include <QUrlQuery> #include <QUrlQuery>
#include <QJsonDocument>
/*! /*!
@ -617,17 +617,17 @@ void OpenSearchEngine::requestSearchResults(const QString &searchTerm)
void OpenSearchEngine::suggestionsObtained() void OpenSearchEngine::suggestionsObtained()
{ {
QString response(QString::fromUtf8(m_suggestionsReply->readAll())); const QByteArray response = m_suggestionsReply->readAll();
response = response.trimmed();
m_suggestionsReply->close(); m_suggestionsReply->close();
m_suggestionsReply->deleteLater(); m_suggestionsReply->deleteLater();
m_suggestionsReply = 0; m_suggestionsReply = 0;
Json json; QJsonParseError err;
const QVariant res = json.parse(response); QJsonDocument json = QJsonDocument::fromJson(response);
const QVariant res = json.toVariant();
if (!json.ok() || res.type() != QVariant::Map) if (err.error != QJsonParseError::NoError || res.type() != QVariant::Map)
return; return;
const QVariantList list = res.toMap().value(QSL("1")).toList(); const QVariantList list = res.toMap().value(QSL("1")).toList();

View File

@ -1,163 +0,0 @@
/* ===========================================================
* QupZilla - WebKit based browser
* Copyright (C) 2014 David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#include "json.h"
#include <QScriptEngine>
#include <QScriptValueIterator>
// Class based on http://stackoverflow.com/a/15805783
Json::Json()
: m_engine(0)
, m_ok(true)
{
}
Json::~Json()
{
delete m_engine;
}
QVariant Json::parse(const QString &data)
{
delete m_engine;
m_engine = new QScriptEngine();
QString jsonData = QString("(%1)").arg(data);
QScriptValue obj = m_engine->evaluate(jsonData);
m_ok = !obj.isError() && obj.isObject();
return decodeInner(obj);
}
QString Json::serialize(const QVariant &variant)
{
delete m_engine;
m_engine = new QScriptEngine();
m_engine->evaluate("function toString() { return JSON.stringify(this, null, ' ') }");
QScriptValue toString = m_engine->globalObject().property("toString");
QScriptValue obj = encodeInner(variant.toMap());
QScriptValue result = toString.call(obj);
m_ok = !obj.isError() && obj.isObject();
return result.toString();
}
bool Json::ok() const
{
return m_ok;
}
QMap<QString, QVariant> Json::decodeInner(QScriptValue object)
{
QMap<QString, QVariant> map;
QScriptValueIterator it(object);
while (it.hasNext()) {
it.next();
if (it.value().isArray()) {
map.insert(it.name(), QVariant(decodeInnerToList(it.value())));
}
else if (it.value().isNumber()) {
map.insert(it.name(), QVariant(it.value().toNumber()));
}
else if (it.value().isString()) {
map.insert(it.name(), QVariant(it.value().toString()));
}
else if (it.value().isBool()) {
map.insert(it.name(), QVariant(it.value().toBool()));
}
else if (it.value().isNull()) {
map.insert(it.name(), QVariant());
}
else if (it.value().isObject()) {
map.insert(it.name(), QVariant(decodeInner(it.value())));
}
}
return map;
}
QList<QVariant> Json::decodeInnerToList(QScriptValue arrayValue)
{
QList<QVariant> list;
QScriptValueIterator it(arrayValue);
while (it.hasNext()) {
it.next();
if (it.name() == QLatin1String("length")) {
continue;
}
if (it.value().isArray()) {
list.append(QVariant(decodeInnerToList(it.value())));
}
else if (it.value().isNumber()) {
list.append(QVariant(it.value().toNumber()));
}
else if (it.value().isString()) {
list.append(QVariant(it.value().toString()));
}
else if (it.value().isBool()) {
list.append(QVariant(it.value().toBool()));
}
else if (it.value().isNull()) {
list.append(QVariant());
}
else if (it.value().isObject()) {
list.append(QVariant(decodeInner(it.value())));
}
}
return list;
}
QScriptValue Json::encodeInner(const QMap<QString, QVariant> &map)
{
QScriptValue obj = m_engine->newObject();
QMapIterator<QString, QVariant> i(map);
while (i.hasNext()) {
i.next();
if (i.value().type() == QVariant::String) {
obj.setProperty(i.key(), i.value().toString());
}
else if (i.value().type() == QVariant::Int) {
obj.setProperty(i.key(), i.value().toInt());
}
else if (i.value().type() == QVariant::Bool) {
obj.setProperty(i.key(), i.value().toBool());
}
else if (i.value().type() == QVariant::Double) {
obj.setProperty(i.key(), i.value().toDouble());
}
else if (i.value().type() == QVariant::List) {
obj.setProperty(i.key(), qScriptValueFromSequence(m_engine, i.value().toList()));
}
else if (i.value().type() == QVariant::Map) {
obj.setProperty(i.key(), encodeInner(i.value().toMap()));
}
}
return obj;
}

View File

@ -1,49 +0,0 @@
/* ============================================================
* QupZilla - WebKit based browser
* Copyright (C) 2014 David Rosca <nowrep@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ============================================================ */
#ifndef JSON_H
#define JSON_H
#include <QVariant>
#include <QString>
#include "qzcommon.h"
class QScriptValue;
class QScriptEngine;
class QUPZILLA_EXPORT Json
{
public:
explicit Json();
~Json();
QVariant parse(const QString &data);
QString serialize(const QVariant &variant);
bool ok() const;
private:
QMap<QString, QVariant> decodeInner(QScriptValue object);
QList<QVariant> decodeInnerToList(QScriptValue arrayValue);
QScriptValue encodeInner(const QMap<QString, QVariant> &map);
QScriptEngine* m_engine;
bool m_ok;
};
#endif // JSON_H

View File

@ -1,6 +1,6 @@
include(../defines.pri) include(../defines.pri)
QT += webenginecore webenginewidgets network widgets sql script QT += webenginecore webenginewidgets network widgets sql
TARGET = qupzilla TARGET = qupzilla
mac: TARGET = QupZilla mac: TARGET = QupZilla