/*
 * This file is part of smolbote. It's copyrighted by the contributors recorded
 * in the version control history of the file, available from its original
 * location: https://neueland.iserlohn-fortress.net/gitea/aqua/smolbote
 *
 * SPDX-License-Identifier: GPL-3.0
 */

#include "urlinterceptor.h"
#include "webprofile.h"
#include "urlfilter.h"

// test DNT on https://browserleaks.com/donottrack

UrlRequestInterceptor::UrlRequestInterceptor(WebProfile* profile, QObject* parent)
    : QWebEngineUrlRequestInterceptor(parent)
{
    Q_CHECK_PTR(profile);
    m_profile = profile;
}

void UrlRequestInterceptor::addHttpHeader(const QByteArray &key, const QByteArray &value)
{
    headers.append(qMakePair(key, value));
}

void UrlRequestInterceptor::addFilter(UrlFilter *filter)
{
    if(filter != nullptr)
        filters.append(filter);
}
void UrlRequestInterceptor::removeFilter(UrlFilter *filter)
{
    if(filter != nullptr)
        filters.removeOne(filter);
}

void UrlRequestInterceptor::interceptRequest(QWebEngineUrlRequestInfo &info)
{
    for(const auto *filter : filters) {
        const auto match = filter->match(info.firstPartyUrl(), info.requestUrl(), info.resourceType());

        // skip if no match
        if(match.first == UrlFilter::NotMatched)
            continue;

        else {
            if(match.first == UrlFilter::Allow)
                info.block(false);
            else if(match.first == UrlFilter::Block)
                info.block(true);
            else if(match.first == UrlFilter::Redirect)
                info.redirect(QUrl::fromUserInput(match.second));
            // we found a match, skip the rest
            break;
        }
    }

    // set headers
    for(const auto &header : headers) {
        info.setHttpHeader(header.first, header.second);
    }
    for(auto i = m_profile->headers().constBegin(); i != m_profile->headers().constEnd(); ++i) {
        info.setHttpHeader(i.key(), i.value());
    }
}