summaryrefslogblamecommitdiffstats
path: root/src/webview.cpp
blob: e0b47f398d29ea55f4c5897a098c0ca1ae46df41 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11










                             

                             
                                
 


                                                                     










                                                                        












                                                                                      
                                            




                                               
                               

                                              
         
                                     


                                                                                            
                                                       
                                                   

                                                                                       



                                                                                                                  

                                                          
                                                            



















                                                                                                                  
























                                              























                                                                                                                
                                     


                                          
                              


                                                                                             











                                                                                                                         
                                   

                                                          
                                                     


                                          




                                                 














                                                                                         
                           
                                                                              
                      
                      

                               


                                       
 
#include "webview.h"
#include <QWebFrame>
#include <QNetworkReply>
#include <QMessageBox>
#include <QTimer>
#include <QUrlQuery>
#include <QCryptographicHash>
#include <QCursor>
#include <QWebHistory>
#include <QNetworkCookieJar>
#include <QWebElement>
#include <QRegularExpression>
#include <QWebPage>
#include <QNetworkAccessManager>

static QRegularExpression R_USER("^[a-z_A-Z][a-zA-Z0-9_@.-]{1,32}$");
static QRegularExpression R_PASS("^[a-z0-9]{1,32}$");

// Override user-agent to make it appear mobile
class UaWebPage : public QWebPage
{
public:
    static QRegularExpression re;

    QString userAgentForUrl(const QUrl &url) const override {
        return QWebPage::userAgentForUrl(url).replace(re, "Mobile \\1");
    }
};

class Nam : public QNetworkAccessManager
{
public:
    explicit Nam(QObject *parent = nullptr) : QNetworkAccessManager(parent) {}
protected:
    virtual QNetworkReply *createRequest(Operation op, const QNetworkRequest &request,
                                         QIODevice *outgoingData = nullptr) override {
        auto cp(request);
        cp.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, QVariant(false));
        return QNetworkAccessManager::createRequest(op, cp, outgoingData);
    }
};

QRegularExpression UaWebPage::re("(\\S+)$");

WebView::WebView(QWidget* parent)
	: QWebView(parent),
	  _timerAbortMessage(new QTimer(this)),
	  _abortedDownload(false),
	  _inErrorState(false),
		_timerReset(new QTimer(this)),
		_firstLoad(false)
	{
	this->setPage(new UaWebPage);
	_timerAbortMessage->setSingleShot(true);
	_timerReset->setSingleShot(true);
	connect(page(), SIGNAL(windowCloseRequested()), this, SLOT(windowCloseRequested()));
	page()->setNetworkAccessManager(new Nam(this));
	page()->setForwardUnsupportedContent(true);
	page()->settings()->setAttribute(QWebSettings::LocalStorageEnabled, true);
	//page()->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
	connect(page(), SIGNAL(unsupportedContent(QNetworkReply*)),this,SLOT(unsupportedContent(QNetworkReply*)));
	connect(page(), SIGNAL(downloadRequested(QNetworkRequest)),this,SLOT(downloadRequest(QNetworkRequest)));
	connect(_timerAbortMessage, &QTimer::timeout, this, &WebView::downloadDeniedMessage);
	connect(_timerReset, &QTimer::timeout, this, [this]() {
		this->stop();
		this->page()->mainFrame()->setContent("");
		emit triggerReset(tr("Inactivity Timeout"));
	});
	connect(this, &QWebView::loadFinished, this, &WebView::onLoadFinished);
}

void WebView::windowCloseRequested()
{
	// If we have an old URL stored on the stack, navigate back to it, otherwise we return and nothing happens
	if (_urls.empty())
		return;
	QUrl url = _urls.pop();
	page()->mainFrame()->load(url);
}

QWebView* WebView::createWindow(QWebPage::WebWindowType)
{
	// Remember current URL, then return the current Web View so no new window opens
	_urls.push(this->url());
	return this;
}

void WebView::mousePressEvent(QMouseEvent* ev)
{
	QWebView::mousePressEvent(ev);
	resetTimeout();
}

void WebView::keyPressEvent(QKeyEvent* ev)
{
	QWebView::keyPressEvent(ev);
	resetTimeout();
}

void WebView::wheelEvent(QWheelEvent* ev)
{
	QWebView::wheelEvent(ev);
	resetTimeout();
}

void WebView::resetTimeout()
{
	if (!_inErrorState) {
		_timerReset->start(60000);
	}
}

void WebView::unsupportedContent(QNetworkReply* rep)
{
	_abortedDownload = true;
	rep->abort();
	rep->deleteLater();
	_timerAbortMessage->start(1);
}

void WebView::downloadRequest(QNetworkRequest)
{
	_timerAbortMessage->start(1);
}

void WebView::downloadDeniedMessage()
{
	QMessageBox::warning(this->parentWidget(), QString::fromUtf8("Denied"),
			QString::fromUtf8("The requested action triggered a download, which is not allowed.\n\n"
					"Diese Aktion löst einen Download aus, was nicht erlaubt ist."));
}

void WebView::onLoadFinished(bool ok)
{
	if (_abortedDownload || !ok) {
		_abortedDownload = false;
		_inErrorState = true;
		_timerReset->start(10000);
		return;
	}
	_inErrorState = false;
	auto user = this->page()->mainFrame()->documentElement().findFirst("#bwlp-username");
	auto pass = this->page()->mainFrame()->documentElement().findFirst("#bwlp-password");
	auto err = this->page()->mainFrame()->documentElement().findFirst("#bwlp-error");
	auto hash = this->page()->mainFrame()->documentElement().findFirst("#bwlp-hash");
	if (!user.isNull() && !pass.isNull() && !hash.isNull()) {
		if (hash.toPlainText() != QCryptographicHash::hash(_token.toLatin1(), QCryptographicHash::Md5).toHex()) {
			qDebug() << " *** Invalid security hash ***";
			emit triggerReset("Invalid Hash");
			return;
		}
		auto ustr = user.toPlainText();
		auto upass = pass.toPlainText();
		if (ustr.contains('@') && R_USER.match(ustr).hasMatch() && R_PASS.match(upass).hasMatch()) {
			emit startAuthentication(ustr, "shib=" + _token + upass);
		}
	} else if (!err.isNull()) {
		this->stop();
		this->page()->mainFrame()->setContent("");
		emit triggerReset(err.toPlainText());
	} else {
		_timerReset->start(60000);
	}
	if (_firstLoad) {
		_firstLoad = false;
		this->page()->history()->clear();
		this->history()->clear();
	}
}

void WebView::reset(const QString baseUrl)
{
    QUrl url(baseUrl);
    QUrlQuery q(url.query());
    q.addQueryItem("action", "browser");
    QByteArray input;
    input.append((const char*)this, sizeof(*this));
    input.append(QString().sprintf("%d %d", QCursor::pos().x(), QCursor::pos().y()));
    input.append(QString::number(QDateTime::currentMSecsSinceEpoch()));
    _token = QCryptographicHash::hash(input, QCryptographicHash::Md5).chopped(8).toHex();
    q.addQueryItem("token", _token);
    url.setQuery(q);
    _urls.clear();
    qDebug() << "Bahnahne";
    this->page()->networkAccessManager()->setCookieJar(new QNetworkCookieJar);
    this->setUrl(url);
    _firstLoad = true;
    _timerAbortMessage->stop();
    _timerReset->stop();
    QTimer::singleShot(5000, [this]() {
        _timerReset->stop();
    });
}