File: mediawiki_upload.cpp

package info (click to toggle)
digikam 4%3A7.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 511,244 kB
  • sloc: cpp: 754,438; ansic: 41,776; xml: 18,008; sh: 5,484; sql: 3,076; perl: 2,386; python: 2,310; javascript: 1,828; yacc: 958; objc: 340; lex: 315; ruby: 165; java: 54; makefile: 46
file content (305 lines) | stat: -rw-r--r-- 7,976 bytes parent folder | download
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/* ============================================================
 *
 * This file is a part of digiKam project
 * https://www.digikam.org
 *
 * Date        : 2011-03-22
 * Description : a Iface C++ interface
 *
 * Copyright (C) 2011-2022 by Gilles Caulier <caulier dot gilles at gmail dot com>
 * Copyright (C) 2011      by Alexandre Mendes <alex dot mendes1988 at gmail dot 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 2, 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.
 *
 * ============================================================ */

#include "mediawiki_upload.h"

// Qt includes

#include <QFile>
#include <QStringList>
#include <QTimer>
#include <QUrl>
#include <QUrlQuery>
#include <QXmlStreamReader>
#include <QNetworkAccessManager>
#include <QNetworkCookie>
#include <QNetworkReply>
#include <QNetworkRequest>

// Local includes

#include "mediawiki_job_p.h"
#include "mediawiki_iface.h"
#include "mediawiki_queryinfo.h"

namespace MediaWiki
{

class Q_DECL_HIDDEN UploadPrivate : public JobPrivate
{
public:

    explicit UploadPrivate(Iface& MediaWiki)
        : JobPrivate(MediaWiki),
          file(nullptr)
    {
    }

    static int error(const QString& error)
    {
        QString temp = error;
        int ret      = 0;
        QStringList list;
        list    << QStringLiteral("internalerror")
                << QStringLiteral("uploaddisabled")
                << QStringLiteral("invalidsessionkey")
                << QStringLiteral("badaccessgroups")
                << QStringLiteral("missingparam")
                << QStringLiteral("mustbeloggedin")
                << QStringLiteral("fetchfileerror")
                << QStringLiteral("nomodule")
                << QStringLiteral("emptyfile")
                << QStringLiteral("filetypemissing")
                << QStringLiteral("filenametooshort")
                << QStringLiteral("overwrite")
                << QStringLiteral("stashfailed");

        ret = list.indexOf(temp.remove(QChar::fromLatin1('-')));

        if (ret == -1)
        {
            ret = 0;
        }

        return  ret + (int)Upload::InternalError ;
    }

    QIODevice* file;
    QString    filename;
    QString    comment;
    QString    text;
    QString    token;
};

Upload::Upload(Iface& MediaWiki, QObject* const parent)
    : Job(*new UploadPrivate(MediaWiki), parent)
{
}

Upload::~Upload()
{
}

void Upload::setFilename(const QString& param)
{
    Q_D(Upload);
    d->filename = param;
}

void Upload::setFile(QIODevice* const file)
{
    Q_D(Upload);
    d->file = file;
}

void Upload::setComment(const QString& param)
{
    Q_D(Upload);
    d->comment = param;
}

void Upload::setText(const QString& text)
{
    Q_D(Upload);
    d->text = text;
}

void Upload::start()
{
    Q_D(Upload);

    QueryInfo* const info = new QueryInfo(d->MediaWiki, this);
    info->setPageName(QStringLiteral("File:") + d->filename);
    info->setToken(QStringLiteral("tokens"));

    connect(info, SIGNAL(page(Page)),
            this, SLOT(doWorkSendRequest(Page)));

    info->start();
}

void Upload::doWorkSendRequest(const Page& page)
{
    Q_D(Upload);

    QString token        = page.pageEditToken();
    d->token             = token;

    // Get the extension

    QStringList filename = d->filename.split(QChar::fromLatin1('.'));
    QString extension    = filename.at(filename.size()-1);

    if      (extension == QLatin1String("jpg"))
    {
        extension = QStringLiteral("jpeg");
    }
    else if (extension == QLatin1String("svg"))
    {
        extension += QStringLiteral("+xml");
    }

    QUrl url = d->MediaWiki.url();
    QUrlQuery query;
    query.addQueryItem(QStringLiteral("action"), QStringLiteral("upload"));
    query.addQueryItem(QStringLiteral("format"), QStringLiteral("xml"));
    url.setQuery(query);

    // Add the cookies

    QByteArray cookie = "";
    QList<QNetworkCookie> MediaWikiCookies = d->manager->cookieJar()->cookiesForUrl(d->MediaWiki.url());

    for (int i = 0 ; i < MediaWikiCookies.size() ; ++i)
    {
        cookie += MediaWikiCookies.at(i).toRawForm(QNetworkCookie::NameAndValueOnly);
        cookie += ';';
    }

    // Set the request

    QNetworkRequest request(url);
    request.setRawHeader("User-Agent", d->MediaWiki.userAgent().toUtf8());
    request.setRawHeader("Accept-Charset", "utf-8");

    QByteArray boundary = "-----------------------------15827188141577679942014851228";
    request.setRawHeader("Content-Type", "multipart/form-data; boundary="  + boundary);
    request.setRawHeader("Cookie", cookie);

    // send data

    boundary = "--" + boundary + "\r\n";
    QByteArray out = boundary;

    // ignore warnings

    out += "Content-Disposition: form-data; name=\"ignorewarnings\"\r\n\r\n";
    out += "true\r\n";
    out += boundary;

    // filename

    out += "Content-Disposition: form-data; name=\"filename\"\r\n\r\n";
    out += d->filename.toUtf8();
    out += "\r\n";
    out += boundary;

    // comment

    if (!d->comment.isEmpty())
    {
        out += "Content-Disposition: form-data; name=\"comment\"\r\n\r\n";
        out += d->comment.toUtf8();
        out += "\r\n";
        out += boundary;
    }

    // token

    out += "Content-Disposition: form-data; name=\"token\"\r\n\r\n";
    out += d->token.toUtf8();
    out += "\r\n";
    out += boundary;

    // the actual file

    out += "Content-Disposition: form-data; name=\"file\"; filename=\"";
    out += d->filename.toUtf8();
    out += "\"\r\n";
    out += "Content-Type: image/";
    out += extension.toUtf8();
    out += "\r\n\r\n";
    out += d->file->readAll();
    out += "\r\n";
    out += boundary;

    // description page

    out += "Content-Disposition: form-data; name=\"text\"\r\n";
    out += "Content-Type: text/plain\r\n\r\n";
    out += d->text.toUtf8();
    out += "\r\n";
    out += boundary.mid(0, boundary.length() - 2);
    out += "--\r\n";

    d->reply = d->manager->post(request, out);
    connectReply();

    connect(d->reply, SIGNAL(finished()),
            this, SLOT(doWorkProcessReply()));
}

void Upload::doWorkProcessReply()
{
    Q_D(Upload);

    disconnect(d->reply, SIGNAL(finished()),
               this, SLOT(doWorkProcessReply()));

    if (d->reply->error() != QNetworkReply::NoError)
    {
        this->setError(this->NetworkError);
        d->reply->close();
        d->reply->deleteLater();

        emitResult();
        return;
    }

    QXmlStreamReader reader(d->reply);

    while (!reader.atEnd() && !reader.hasError())
    {
        QXmlStreamReader::TokenType token = reader.readNext();

        if      (token == QXmlStreamReader::StartElement)
        {
            QXmlStreamAttributes attrs = reader.attributes();

            if      (reader.name() == QLatin1String("upload"))
            {
                if (attrs.value(QStringLiteral("result")).toString() == QLatin1String("Success"))
                {
                    this->setError(KJob::NoError);
                }
            }
            else if (reader.name() == QLatin1String("error"))
            {
                this->setErrorText(attrs.value( QStringLiteral("info")).toString());
                this->setError(UploadPrivate::error(attrs.value(QStringLiteral("code")).toString()));
            }
        }
        else if ((token          == QXmlStreamReader::Invalid) &&
                 (reader.error() != QXmlStreamReader::PrematureEndOfDocumentError))
        {
            this->setError(this->XmlError);
        }
    }

    d->reply->close();
    d->reply->deleteLater();

    emitResult();
}

} // namespace MediaWiki