summaryrefslogtreecommitdiff
path: root/src/persistentcookiejar.cpp
blob: 0e17d5b749c59ea621ff3b347336895fabf302f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include "persistentcookiejar.h"
#include <QDataStream>
#include <QNetworkCookie>
#include <QTemporaryFile>

PersistentCookieJar::PersistentCookieJar(const QString& fileName, QObject* parent)
    : QNetworkCookieJar(parent), m_FileName(fileName) {
    restore();
}

PersistentCookieJar::~PersistentCookieJar() {
    qDebug("save %s", qPrintable(m_FileName));
    save();
}

void PersistentCookieJar::clear() {
    for (const QNetworkCookie& cookie : allCookies()) {
        deleteCookie(cookie);
    }
}

void PersistentCookieJar::save() {
    QTemporaryFile file;
    if (!file.open()) {
        qCritical("failed to save cookies: couldn't create temporary file");
        return;
    }
    QDataStream data(&file);

    QList<QNetworkCookie> cookies = allCookies();
    data << static_cast<quint32>(cookies.size());

    for (const QNetworkCookie& cookie : allCookies()) {
        data << cookie.toRawForm();
    }

    {
        QFile oldCookies(m_FileName);
        if (oldCookies.exists()) {
            if (!oldCookies.remove()) {
                qCritical("failed to save cookies: failed to remove %s", qPrintable(m_FileName));
                return;
            }
        } // if it doesn't exists that's fine
    }

    if (!file.copy(m_FileName)) {
        qCritical("failed to save cookies: failed to write %s", qPrintable(m_FileName));
    }
}

void PersistentCookieJar::restore() {
    QFile file(m_FileName);
    if (!file.open(QIODevice::ReadOnly)) {
        // not necessarily a problem, the file may just not exist (yet)
        return;
    }

    QList<QNetworkCookie> allCookies;

    QDataStream data(&file);
    quint32 count;
    data >> count;
    for (quint32 i = 0; i < count; ++i) {
        QByteArray cookieRaw;
        data >> cookieRaw;
        allCookies.append(QNetworkCookie::parseCookies(cookieRaw));
    }
    setAllCookies(allCookies);
}