diff --git a/autotests/core/createjobtest.cpp b/autotests/core/createjobtest.cpp index 5c84b8d..b89e189 100644 --- a/autotests/core/createjobtest.cpp +++ b/autotests/core/createjobtest.cpp @@ -1,121 +1,120 @@ /* * Copyright (C) 2018 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include #include #include "fakenetworkaccessmanagerfactory.h" #include "testutils.h" #include "createjob.h" #include "account.h" Q_DECLARE_METATYPE(QList) using Scenarios = QList; using namespace KGAPI2; class TestCreateJob : public CreateJob { Q_OBJECT public: TestCreateJob(const QUrl &url, const QByteArray &data, QObject *parent = nullptr) : CreateJob(AccountPtr::create(QStringLiteral("MockAccount"), QStringLiteral("MockToken")), parent) , mUrl(url) , mData(data) { } void start() override { QNetworkRequest request(mUrl); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); enqueueRequest(request, mData); } QByteArray response() { return mResponse; } void handleReply(const QNetworkReply *, const QByteArray &rawData) override { mResponse = rawData; emitFinished(); } private: QUrl mUrl; QByteArray mData; QByteArray mResponse; }; class CreateJobTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase() { NetworkAccessManagerFactory::setFactory(new FakeNetworkAccessManagerFactory); } void testCreate_data() { QTest::addColumn>("scenarios"); QTest::newRow("success") << Scenarios{ { QUrl(QStringLiteral("https://example.test/request/data")), QNetworkAccessManager::PostOperation, "New data", 200, "Data created" } }; QTest::newRow("creation failed") << Scenarios{ { QUrl(QStringLiteral("https://example.test/request/data")), QNetworkAccessManager::PostOperation, "New data", KGAPI2::Forbidden, {} } }; QTest::newRow("redirect") << Scenarios{ { QUrl(QStringLiteral("https://example.test/request/data")), QNetworkAccessManager::PostOperation, "New data", KGAPI2::TemporarilyMoved, "https://example.test/moved/data" }, { QUrl(QStringLiteral("https://example.test/moved/data")), QNetworkAccessManager::PostOperation, "New data", KGAPI2::OK, "Data created" } }; } void testCreate() { QFETCH(QList, scenarios); FakeNetworkAccessManagerFactory::get()->setScenarios(scenarios); auto job = new TestCreateJob(scenarios.first().requestUrl, scenarios.first().requestData); QVERIFY(execJob(job)); QCOMPARE(static_cast(job->error()), scenarios.last().responseCode == 200 ? KGAPI2::NoError : scenarios.last().responseCode); QCOMPARE(job->response(), scenarios.last().responseData); QVERIFY(!FakeNetworkAccessManagerFactory::get()->hasScenario()); } }; QTEST_GUILESS_MAIN(CreateJobTest) #include "createjobtest.moc" diff --git a/autotests/core/fetchjobtest.cpp b/autotests/core/fetchjobtest.cpp index 98edb98..a098c55 100644 --- a/autotests/core/fetchjobtest.cpp +++ b/autotests/core/fetchjobtest.cpp @@ -1,157 +1,154 @@ /* * Copyright (C) 2018 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include #include #include "fakenetworkaccessmanagerfactory.h" #include "testutils.h" #include "fetchjob.h" #include "account.h" Q_DECLARE_METATYPE(QList) using Scenarios = QList; using namespace KGAPI2; class TestFetchJob : public FetchJob { Q_OBJECT public: explicit TestFetchJob(const QUrl &url, QObject *parent = nullptr) : FetchJob(parent) , mUrl(url) { } TestFetchJob(const AccountPtr &account, const QUrl &url, QObject *parent = nullptr) : FetchJob(account, parent) , mUrl(url) { } void start() override { QNetworkRequest request(mUrl); - if (account()) { - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - } enqueueRequest(request); } QByteArray response() { return mResponse; } void handleReply(const QNetworkReply *, const QByteArray &rawData) override { mResponse = rawData; emitFinished(); } private: QUrl mUrl; QByteArray mResponse; }; class FetchJobTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase() { NetworkAccessManagerFactory::setFactory(new FakeNetworkAccessManagerFactory); } void testUnauthenticatedFetch_data() { QTest::addColumn>("scenarios"); QTest::newRow("success") << Scenarios{ { QUrl(QStringLiteral("https://example.test/request/data")), QNetworkAccessManager::GetOperation, {}, 200, "Test Response", false } }; QTest::newRow("not found") << Scenarios{ { QUrl(QStringLiteral("https://example.test/does/not/exist")), QNetworkAccessManager::GetOperation, {}, KGAPI2::NotFound, {}, false } }; QTest::newRow("redirect") << Scenarios{ { QUrl(QStringLiteral("https://example.test/request/data")), QNetworkAccessManager::GetOperation, {}, KGAPI2::TemporarilyMoved, "https://example.test/moved/data", false }, { QUrl(QStringLiteral("https://example.test/moved/data")), QNetworkAccessManager::GetOperation, {}, KGAPI2::OK, "Here's your data", false } }; } void testUnauthenticatedFetch() { QFETCH(QList, scenarios); FakeNetworkAccessManagerFactory::get()->setScenarios(scenarios); auto job = new TestFetchJob(scenarios.first().requestUrl); QVERIFY(execJob(job)); QCOMPARE(static_cast(job->error()), scenarios.last().responseCode == 200 ? KGAPI2::NoError : scenarios.last().responseCode); QCOMPARE(job->response(), scenarios.last().responseData); QVERIFY(!FakeNetworkAccessManagerFactory::get()->hasScenario()); } void testAuthenticatedFetch_data() { QTest::addColumn>("scenarios"); QTest::newRow("success") << Scenarios{ { QUrl(QStringLiteral("https://example.test/request/data")), QNetworkAccessManager::GetOperation, {}, 200, "Response" } }; QTest::newRow("token expired") << Scenarios{ { QUrl(QStringLiteral("https://example.test/request/data")), QNetworkAccessManager::GetOperation, {}, KGAPI2::Unauthorized, {} } }; } void testAuthenticatedFetch() { QFETCH(QList, scenarios); FakeNetworkAccessManagerFactory::get()->setScenarios(scenarios); auto account = AccountPtr::create(QStringLiteral("MockAccount"), QStringLiteral("MockToken")); auto job = new TestFetchJob(account, scenarios.first().requestUrl); QVERIFY(execJob(job)); QCOMPARE(static_cast(job->error()), scenarios.last().responseCode == 200 ? KGAPI2::NoError : scenarios.last().responseCode); QCOMPARE(job->response(), scenarios.last().responseData); QVERIFY(!FakeNetworkAccessManagerFactory::get()->hasScenario()); } }; QTEST_GUILESS_MAIN(FetchJobTest) #include "fetchjobtest.moc" diff --git a/src/blogger/blogfetchjob.cpp b/src/blogger/blogfetchjob.cpp index eb7890e..33c487d 100644 --- a/src/blogger/blogfetchjob.cpp +++ b/src/blogger/blogfetchjob.cpp @@ -1,110 +1,107 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "blogfetchjob.h" #include "blog.h" #include "bloggerservice.h" #include "account.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN BlogFetchJob::Private { public: Private(const QString &id, FetchBy fetchBy); ~Private(); QString id; FetchBy fetchBy; }; BlogFetchJob::Private::Private(const QString &id_, FetchBy fetchBy_) : id(id_) , fetchBy(fetchBy_) { } BlogFetchJob::Private::~Private() { } BlogFetchJob::BlogFetchJob(const QString &id, FetchBy fetchBy, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new Private(id, fetchBy)) { } BlogFetchJob::~BlogFetchJob() { delete d; } void BlogFetchJob::start() { QNetworkRequest request; switch (d->fetchBy) { case FetchByBlogId: request.setUrl(BloggerService::fetchBlogByBlogIdUrl(d->id)); break; case FetchByBlogUrl: request.setUrl(BloggerService::fetchBlogByBlogUrlUrl(d->id)); break; case FetchByUserId: request.setUrl(BloggerService::fetchBlogsByUserIdUrl(d->id)); break; } - if (account()) { - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - } enqueueRequest(request); } ObjectsList BlogFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->fetchBy == FetchByUserId) { items << Blog::fromJSONFeed(rawData); } else { items << Blog::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); } emitFinished(); return items; } diff --git a/src/blogger/commentdeletejob.cpp b/src/blogger/commentdeletejob.cpp index efbfccc..8e77415 100644 --- a/src/blogger/commentdeletejob.cpp +++ b/src/blogger/commentdeletejob.cpp @@ -1,97 +1,96 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "commentdeletejob.h" #include "bloggerservice.h" #include "comment.h" #include "utils.h" #include "account.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN CommentDeleteJob::Private { public: Private(const QString &blogId, const QString &postId, const QString &commentId); QString blogId; QString postId; QString commentId; }; CommentDeleteJob::Private::Private(const QString &blogId_, const QString &postId_, const QString &commentId_) : blogId(blogId_) , postId(postId_) , commentId(commentId_) { } CommentDeleteJob::CommentDeleteJob(const CommentPtr &comment, const AccountPtr &account, QObject *parent) : DeleteJob(account, parent) , d(new Private(comment->blogId(), comment->postId(), comment->id())) { } CommentDeleteJob::CommentDeleteJob(const QString &blogId, const QString &postId, const QString &commentId, const AccountPtr &account, QObject *parent) : DeleteJob(account, parent) , d(new Private(blogId, postId, commentId)) { } CommentDeleteJob::~CommentDeleteJob() { delete d; } void CommentDeleteJob::start() { QNetworkRequest request(BloggerService::deleteCommentUrl(d->blogId, d->postId, d->commentId)); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); enqueueRequest(request); } void CommentDeleteJob::handleReply(const QNetworkReply *reply, const QByteArray &rawData) { Q_UNUSED(reply); Q_UNUSED(rawData); emitFinished(); } diff --git a/src/blogger/commentfetchjob.cpp b/src/blogger/commentfetchjob.cpp index 9ae9d4a..5add6e7 100644 --- a/src/blogger/commentfetchjob.cpp +++ b/src/blogger/commentfetchjob.cpp @@ -1,217 +1,204 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "commentfetchjob.h" #include "comment.h" #include "bloggerservice.h" #include "utils.h" #include "account.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN CommentFetchJob::Private { public: Private(const QString &blogId, const QString &postId, const QString &commentId, CommentFetchJob *parent); ~Private(); - QNetworkRequest createRequest(const QUrl &url); - QString blogId; QString postId; QString commentId; uint maxResults; QDateTime startDate; QDateTime endDate; bool fetchBodies; private: CommentFetchJob *q; }; CommentFetchJob::Private::Private(const QString &blogId_, const QString &postId_, const QString &commentId_, CommentFetchJob *parent) : blogId(blogId_) , postId(postId_) , commentId(commentId_) , maxResults(0) , fetchBodies(true) , q(parent) { } CommentFetchJob::Private::~Private() { } -QNetworkRequest CommentFetchJob::Private::createRequest(const QUrl &url) -{ - QNetworkRequest request; - if (q->account()) { - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - } - request.setUrl(url); - - return request; -} - CommentFetchJob::CommentFetchJob(const QString &blogId, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new Private(blogId, QString(), QString(), this)) { } CommentFetchJob::CommentFetchJob(const QString &blogId, const QString &postId, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new Private(blogId, postId, QString(), this)) { } CommentFetchJob::CommentFetchJob(const QString &blogId, const QString &postId, const QString &commentId, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new Private(blogId, postId, commentId, this)) { } CommentFetchJob::~CommentFetchJob() { delete d; } QDateTime CommentFetchJob::endDate() const { return d->endDate; } void CommentFetchJob::setEndDate(const QDateTime &endDate) { d->endDate = endDate; } QDateTime CommentFetchJob::startDate() const { return d->startDate; } void CommentFetchJob::setStartDate(const QDateTime &startDate) { d->startDate = startDate; } uint CommentFetchJob::maxResults() const { return d->maxResults; } void CommentFetchJob::setMaxResults(uint maxResults) { d->maxResults = maxResults; } bool CommentFetchJob::fetchBodies() const { return d->fetchBodies; } void CommentFetchJob::setFetchBodies(bool fetchBodies) { d->fetchBodies = fetchBodies; } void CommentFetchJob::start() { QUrl url = BloggerService::fetchCommentsUrl(d->blogId, d->postId, d->commentId); QUrlQuery query(url); if (d->startDate.isValid()) { query.addQueryItem(QStringLiteral("startDate"), d->startDate.toString(Qt::ISODate)); } if (d->endDate.isValid()) { query.addQueryItem(QStringLiteral("endDate"), d->endDate.toString(Qt::ISODate)); } if (d->maxResults > 0) { query.addQueryItem(QStringLiteral("maxResults"), QString::number(d->maxResults)); } query.addQueryItem(QStringLiteral("fetchBodies"), Utils::bool2Str(d->fetchBodies)); if (account()) { query.addQueryItem(QStringLiteral("view"), QStringLiteral("ADMIN")); } url.setQuery(query); - const QNetworkRequest request = d->createRequest(url); + const QNetworkRequest request(url); enqueueRequest(request); } ObjectsList CommentFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { FeedData feedData; feedData.requestUrl = reply->request().url(); ObjectsList items; QString itemId; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->commentId.isEmpty()) { items = Comment::fromJSONFeed(rawData, feedData); } else { items << Comment::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { - const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); + const QNetworkRequest request(feedData.nextPageUrl); enqueueRequest(request); } else { emitFinished(); } return items; } diff --git a/src/blogger/pagecreatejob.cpp b/src/blogger/pagecreatejob.cpp index bc9c1e5..1f7babf 100644 --- a/src/blogger/pagecreatejob.cpp +++ b/src/blogger/pagecreatejob.cpp @@ -1,89 +1,87 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "pagecreatejob.h" #include "page.h" #include "bloggerservice.h" #include "utils.h" #include "account.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN PageCreateJob::Private { public: Private(const PagePtr &page); PagePtr page; }; PageCreateJob::Private::Private(const PagePtr &page_) : page(page_) { } PageCreateJob::PageCreateJob(const PagePtr &page, const AccountPtr &account, QObject *parent) : CreateJob(account, parent) , d(new Private(page)) { } PageCreateJob::~PageCreateJob() { delete d; } void PageCreateJob::start() { const QUrl url = BloggerService::createPageUrl(d->page->blogId()); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = Page::toJSON(d->page); enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList PageCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << Page::fromJSON(rawData); emitFinished(); return items; } diff --git a/src/blogger/pagedeletejob.cpp b/src/blogger/pagedeletejob.cpp index 551de15..f29ad37 100644 --- a/src/blogger/pagedeletejob.cpp +++ b/src/blogger/pagedeletejob.cpp @@ -1,90 +1,89 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "pagedeletejob.h" #include "page.h" #include "bloggerservice.h" #include "account.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN PageDeleteJob::Private { public: Private(const QString &blogId, const QString &pageId); QString blogId; QString pageId; }; PageDeleteJob::Private::Private(const QString &blogId_, const QString &pageId_) : blogId(blogId_) , pageId(pageId_) { } PageDeleteJob::PageDeleteJob(const QString &blogId, const QString &pageId, const AccountPtr &account, QObject *parent) : DeleteJob(account, parent) , d(new Private(blogId, pageId)) { } PageDeleteJob::PageDeleteJob(const PagePtr &page, const AccountPtr &account, QObject *parent) : DeleteJob(account, parent) , d(new Private(page->blogId(), page->id())) { } PageDeleteJob::~PageDeleteJob() { delete d; } void PageDeleteJob::start() { QNetworkRequest request(BloggerService::deletePageUrl(d->blogId, d->pageId)); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); enqueueRequest(request); } void PageDeleteJob::handleReply(const QNetworkReply *reply, const QByteArray &rawData) { Q_UNUSED(reply); Q_UNUSED(rawData); emitFinished(); } diff --git a/src/blogger/pagefetchjob.cpp b/src/blogger/pagefetchjob.cpp index aa3c7eb..0887f3d 100644 --- a/src/blogger/pagefetchjob.cpp +++ b/src/blogger/pagefetchjob.cpp @@ -1,146 +1,143 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "pagefetchjob.h" #include "bloggerservice.h" #include "page.h" #include "utils.h" #include "account.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN PageFetchJob::Private { public: Private(const QString &blogId, const QString &pageId); QString blogId; QString pageId; bool fetchContent; StatusFilters statusFilter; }; PageFetchJob::Private::Private(const QString &blogId_, const QString &pageId_) : blogId(blogId_) , pageId(pageId_) , fetchContent(true) , statusFilter(All) { } PageFetchJob::PageFetchJob(const QString &blogId, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new Private(blogId, QString())) { } PageFetchJob::PageFetchJob(const QString &blogId, const QString &pageId, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new Private(blogId, pageId)) { } PageFetchJob::~PageFetchJob() { delete d; } bool PageFetchJob::fetchContent() const { return d->fetchContent; } void PageFetchJob::setFetchContent(bool fetchContent) { d->fetchContent = fetchContent; } PageFetchJob::StatusFilters PageFetchJob::statusFilter() const { return d->statusFilter; } void PageFetchJob::setStatusFilter(StatusFilters status) { d->statusFilter = status; } void PageFetchJob::start() { QUrl url = BloggerService::fetchPageUrl(d->blogId, d->pageId); QUrlQuery query(url); query.addQueryItem(QStringLiteral("fetchBodies"), Utils::bool2Str(d->fetchContent)); if (d->statusFilter & Draft) { query.addQueryItem(QStringLiteral("status"), QStringLiteral("draft")); } if (d->statusFilter & Imported) { query.addQueryItem(QStringLiteral("status"), QStringLiteral("imported")); } if (d->statusFilter & Live) { query.addQueryItem(QStringLiteral("status"), QStringLiteral("live")); } if (account()) { query.addQueryItem(QStringLiteral("view"), QStringLiteral("ADMIN")); } url.setQuery(query); QNetworkRequest request(url); - if (account()) { - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - } enqueueRequest(request); } ObjectsList PageFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->pageId.isEmpty()) { items = Page::fromJSONFeed(rawData); } else { items << Page::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } emitFinished(); return items; } diff --git a/src/blogger/pagemodifyjob.cpp b/src/blogger/pagemodifyjob.cpp index 9583b62..44d6a77 100644 --- a/src/blogger/pagemodifyjob.cpp +++ b/src/blogger/pagemodifyjob.cpp @@ -1,88 +1,86 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "pagemodifyjob.h" #include "page.h" #include "bloggerservice.h" #include "utils.h" #include "account.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN PageModifyJob::Private { public: Private(const PagePtr &page); PagePtr page; }; PageModifyJob::Private::Private(const PagePtr &page_) : page(page_) { } PageModifyJob::PageModifyJob(const PagePtr &page, const AccountPtr &account, QObject *parent) : ModifyJob(account, parent) , d(new Private(page)) { } PageModifyJob::~PageModifyJob() { delete d; } void PageModifyJob::start() { const QUrl url = BloggerService::modifyPageUrl(d->page->blogId(), d->page->id()); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = Page::toJSON(d->page); enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList PageModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << Page::fromJSON(rawData); emitFinished(); return items; } diff --git a/src/blogger/postcreatejob.cpp b/src/blogger/postcreatejob.cpp index 89f09dd..eb531ea 100644 --- a/src/blogger/postcreatejob.cpp +++ b/src/blogger/postcreatejob.cpp @@ -1,98 +1,96 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "postcreatejob.h" #include "post.h" #include "bloggerservice.h" #include "account.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN PostCreateJob::Private { public: Private(const PostPtr &post, bool isDraft); PostPtr post; bool isDraft; }; PostCreateJob::Private::Private(const PostPtr &post_, bool isDraft_) : post(post_) , isDraft(isDraft_) { } PostCreateJob::PostCreateJob(const PostPtr &post, bool isDraft, const AccountPtr &account, QObject *parent) : CreateJob(account, parent) , d(new Private(post, isDraft)) { } PostCreateJob::~PostCreateJob() { delete d; } void PostCreateJob::start() { QUrl url = BloggerService::createPostUrl(d->post->blogId()); if (d->isDraft) { QUrlQuery query(url); query.addQueryItem(QStringLiteral("isDraft"), Utils::bool2Str(d->isDraft)); url.setQuery(query); } - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = Post::toJSON(d->post); enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList PostCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << Post::fromJSON(rawData); emitFinished(); return items; } diff --git a/src/blogger/postdeletejob.cpp b/src/blogger/postdeletejob.cpp index c32adfc..f01c586 100644 --- a/src/blogger/postdeletejob.cpp +++ b/src/blogger/postdeletejob.cpp @@ -1,85 +1,85 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "postdeletejob.h" #include "post.h" #include "bloggerservice.h" #include "account.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN PostDeleteJob::Private { public: Private(const QString &blogId, const QString &postId); QString blogId; QString postId; }; PostDeleteJob::Private::Private(const QString &blogId_, const QString &postId_) : blogId(blogId_) , postId(postId_) { } PostDeleteJob::PostDeleteJob(const QString &blogId, const QString &postId, const AccountPtr &account, QObject *parent) : DeleteJob(account, parent) , d(new Private(blogId, postId)) { } PostDeleteJob::PostDeleteJob(const PostPtr &post, const AccountPtr &account, QObject *parent) : DeleteJob(account, parent) , d(new Private(post->blogId(), post->id())) { } PostDeleteJob::~PostDeleteJob() { delete d; } void PostDeleteJob::start() { - QNetworkRequest request(BloggerService::deletePostUrl(d->blogId, d->postId)); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + const QUrl url = BloggerService::deletePostUrl(d->blogId, d->postId); + QNetworkRequest request(url); enqueueRequest(request); } void PostDeleteJob::handleReply(const QNetworkReply *reply, const QByteArray &rawData) { Q_UNUSED(reply); Q_UNUSED(rawData); emitFinished(); } diff --git a/src/blogger/postfetchjob.cpp b/src/blogger/postfetchjob.cpp index 3ef2b79..a370aa2 100644 --- a/src/blogger/postfetchjob.cpp +++ b/src/blogger/postfetchjob.cpp @@ -1,240 +1,227 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "postfetchjob.h" #include "post.h" #include "bloggerservice.h" #include "account.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN PostFetchJob::Private { public: Private(const QString &blogId, const QString &postId, PostFetchJob *parent); - QNetworkRequest createRequest(const QUrl &url); - QString blogId; QString postId; bool fetchBodies; bool fetchImages; uint maxResults; QStringList filterLabels; QDateTime startDate; QDateTime endDate; StatusFilters statusFilter; private: PostFetchJob *q; }; PostFetchJob::Private::Private(const QString &blogId_, const QString &postId_, PostFetchJob *parent) : blogId(blogId_) , postId(postId_) , fetchBodies(true) , fetchImages(true) , maxResults(0) , statusFilter(All) , q(parent) { } -QNetworkRequest PostFetchJob::Private::createRequest(const QUrl &url) -{ - QNetworkRequest request; - if (q->account()) { - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - } - request.setUrl(url); - - return request; -} - PostFetchJob::PostFetchJob(const QString &blogId, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new Private(blogId, QString(), this)) { } PostFetchJob::PostFetchJob(const QString &blogId, const QString &postId, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new Private(blogId, postId, this)) { } PostFetchJob::~PostFetchJob() { delete d; } bool PostFetchJob::fetchBodies() const { return d->fetchBodies; } void PostFetchJob::setFetchBodies(bool fetchBodies) { d->fetchBodies = fetchBodies; } bool PostFetchJob::fetchImages() const { return d->fetchImages; } void PostFetchJob::setFetchImages(bool fetchImages) { d->fetchImages = fetchImages; } uint PostFetchJob::maxResults() const { return d->maxResults; } void PostFetchJob::setMaxResults(uint maxResults) { d->maxResults = maxResults; } QStringList PostFetchJob::filterLabels() const { return d->filterLabels; } void PostFetchJob::setFilterLabels(const QStringList &labels) { d->filterLabels = labels; } QDateTime PostFetchJob::startDate() const { return d->startDate; } void PostFetchJob::setStartDate(const QDateTime &startDate) { d->startDate = startDate; } QDateTime PostFetchJob::endDate() const { return d->endDate; } void PostFetchJob::setEndDate(const QDateTime &endDate) { d->endDate = endDate; } void PostFetchJob::setStatusFilter(PostFetchJob::StatusFilters filter) { d->statusFilter = filter; } PostFetchJob::StatusFilters PostFetchJob::statusFilter() const { return d->statusFilter; } void PostFetchJob::start() { QUrl url = BloggerService::fetchPostUrl(d->blogId, d->postId); QUrlQuery query(url); if (d->postId.isEmpty()) { if (d->startDate.isValid()) { query.addQueryItem(QStringLiteral("startDate"), d->startDate.toString(Qt::ISODate)); } if (d->endDate.isValid()) { query.addQueryItem(QStringLiteral("endDate"), d->endDate.toString(Qt::ISODate)); } if (d->maxResults > 0) { query.addQueryItem(QStringLiteral("maxResults"), QString::number(d->maxResults)); } if (!d->filterLabels.isEmpty()) query.addQueryItem(QStringLiteral("labels"), d->filterLabels.join(QStringLiteral(","))); query.addQueryItem(QStringLiteral("fetchBodies"), Utils::bool2Str(d->fetchBodies)); query.addQueryItem(QStringLiteral("fetchImages"), Utils::bool2Str(d->fetchImages)); } if (account()) { query.addQueryItem(QStringLiteral("view"), QStringLiteral("ADMIN")); } if (d->statusFilter & Draft) { query.addQueryItem(QStringLiteral("status"), QStringLiteral("draft")); } if (d->statusFilter & Live) { query.addQueryItem(QStringLiteral("status"), QStringLiteral("live")); } if (d->statusFilter & Scheduled) { query.addQueryItem(QStringLiteral("status"), QStringLiteral("scheduled")); } url.setQuery(query); - const QNetworkRequest request = d->createRequest(url); + const QNetworkRequest request(url); enqueueRequest(request); } ObjectsList PostFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { FeedData feedData; feedData.requestUrl = reply->request().url(); ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->postId.isEmpty()) { items = Post::fromJSONFeed(rawData, feedData); } else { items << Post::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { - const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); + const QNetworkRequest request(feedData.nextPageUrl); enqueueRequest(request); } else { emitFinished(); } return items; } diff --git a/src/blogger/postmodifyjob.cpp b/src/blogger/postmodifyjob.cpp index f007e9b..402453c 100644 --- a/src/blogger/postmodifyjob.cpp +++ b/src/blogger/postmodifyjob.cpp @@ -1,85 +1,83 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "postmodifyjob.h" #include "post.h" #include "bloggerservice.h" #include "account.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN PostModifyJob::Private { public: Private(const PostPtr &post); PostPtr post; }; PostModifyJob::Private::Private(const PostPtr &post_) : post(post_) { } PostModifyJob::PostModifyJob(const PostPtr &post, const AccountPtr &account, QObject *parent) : ModifyJob(account, parent) , d(new Private(post)) { } PostModifyJob::~PostModifyJob() { delete d; } void PostModifyJob::start() { const QUrl url = BloggerService::modifyPostUrl(d->post->blogId(), d->post->id()); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = Post::toJSON(d->post); enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList PostModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << Post::fromJSON(rawData); emitFinished(); return items; } diff --git a/src/blogger/postsearchjob.cpp b/src/blogger/postsearchjob.cpp index 23a6071..968be52 100644 --- a/src/blogger/postsearchjob.cpp +++ b/src/blogger/postsearchjob.cpp @@ -1,135 +1,122 @@ /* * Copyright (C) 2014 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "postsearchjob.h" #include "post.h" #include "bloggerservice.h" #include "account.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Blogger; class Q_DECL_HIDDEN PostSearchJob::Private { public: Private(const QString &blogId, const QString &query, PostSearchJob *parent); - QNetworkRequest createRequest(const QUrl &url); - QString blogId; QString query; bool fetchBodies; private: PostSearchJob *q; }; PostSearchJob::Private::Private(const QString &blogId_, const QString &query_, PostSearchJob *parent) : blogId(blogId_) , query(query_) , fetchBodies(true) , q(parent) { } -QNetworkRequest PostSearchJob::Private::createRequest(const QUrl &url) -{ - QNetworkRequest request; - if (q->account()) { - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - } - request.setUrl(url); - - return request; -} - PostSearchJob::PostSearchJob(const QString &blogId, const QString &query, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new Private(blogId, query, this)) { } PostSearchJob::~PostSearchJob() { delete d; } bool PostSearchJob::fetchBodies() const { return d->fetchBodies; } void PostSearchJob::setFetchBodies(bool fetchBodies) { d->fetchBodies = fetchBodies; } void PostSearchJob::start() { QUrl url = BloggerService::searchPostUrl(d->blogId); QUrlQuery query(url); query.addQueryItem(QStringLiteral("q"), d->query); query.addQueryItem(QStringLiteral("fetchBodies"), Utils::bool2Str(d->fetchBodies)); url.setQuery(query); - const QNetworkRequest request = d->createRequest(url); + const QNetworkRequest request(url); enqueueRequest(request); } ObjectsList PostSearchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { FeedData feedData; feedData.requestUrl = reply->request().url(); ObjectsList items; QString itemId; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { items = Post::fromJSONFeed(rawData, feedData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { - const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); + const QNetworkRequest request(feedData.nextPageUrl); enqueueRequest(request); } else { emitFinished(); } return items; } diff --git a/src/calendar/calendarcreatejob.cpp b/src/calendar/calendarcreatejob.cpp index 43e98f6..7ab4f25 100644 --- a/src/calendar/calendarcreatejob.cpp +++ b/src/calendar/calendarcreatejob.cpp @@ -1,109 +1,107 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "calendarcreatejob.h" #include "calendarservice.h" #include "object.h" #include "account.h" #include "calendar.h" #include "../debug.h" #include "utils.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN CalendarCreateJob::Private { public: QueueHelper calendars; }; CalendarCreateJob::CalendarCreateJob(const CalendarPtr& calendar, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->calendars << calendar; } CalendarCreateJob::CalendarCreateJob(const CalendarsList& calendars, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->calendars = calendars; } CalendarCreateJob::~CalendarCreateJob() { delete d; } void CalendarCreateJob::start() { if (d->calendars.atEnd()) { emitFinished(); return; } CalendarPtr calendar = d->calendars.current(); const QUrl url = CalendarService::createCalendarUrl(); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); - request.setUrl(url); const QByteArray rawData = CalendarService::calendarToJSON(calendar); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList CalendarCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << CalendarService::JSONToCalendar(rawData).dynamicCast(); d->calendars.currentProcessed(); start(); return items; } diff --git a/src/calendar/calendardeletejob.cpp b/src/calendar/calendardeletejob.cpp index 6b66973..2450969 100644 --- a/src/calendar/calendardeletejob.cpp +++ b/src/calendar/calendardeletejob.cpp @@ -1,107 +1,106 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "calendardeletejob.h" #include "calendarservice.h" #include "account.h" #include "calendar.h" #include "../debug.h" #include "private/queuehelper_p.h" #include using namespace KGAPI2; class Q_DECL_HIDDEN CalendarDeleteJob::Private { public: QueueHelper calendarsIds; }; CalendarDeleteJob::CalendarDeleteJob(const CalendarPtr& calendar, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private) { d->calendarsIds << calendar->uid(); } CalendarDeleteJob::CalendarDeleteJob(const CalendarsList& calendars, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private) { for (const CalendarPtr &calendar : calendars) { d->calendarsIds << calendar->uid(); } } CalendarDeleteJob::CalendarDeleteJob(const QString &calendarId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->calendarsIds << calendarId; } CalendarDeleteJob::CalendarDeleteJob(const QStringList &calendarsIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->calendarsIds = calendarsIds; } CalendarDeleteJob::~CalendarDeleteJob() { delete d; } void CalendarDeleteJob::start() { if (d->calendarsIds.atEnd()) { emitFinished(); return; } const QString calendarId = d->calendarsIds.current(); const QUrl url = CalendarService::removeCalendarUrl(calendarId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request); } void CalendarDeleteJob::handleReply(const QNetworkReply* reply, const QByteArray& rawData) { d->calendarsIds.currentProcessed(); KGAPI2::DeleteJob::handleReply(reply, rawData); } diff --git a/src/calendar/calendarfetchjob.cpp b/src/calendar/calendarfetchjob.cpp index add4cfc..6f2ef7d 100644 --- a/src/calendar/calendarfetchjob.cpp +++ b/src/calendar/calendarfetchjob.cpp @@ -1,131 +1,129 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "calendarfetchjob.h" #include "calendarservice.h" #include "account.h" #include "calendar.h" #include "../debug.h" #include "utils.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN CalendarFetchJob::Private { public: Private(CalendarFetchJob *parent); QNetworkRequest createRequest(const QUrl &url); QString calendarId; private: CalendarFetchJob * const q; }; CalendarFetchJob::Private::Private(CalendarFetchJob* parent): q(parent) { } QNetworkRequest CalendarFetchJob::Private::createRequest(const QUrl& url) { - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); - request.setUrl(url); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } return request; } CalendarFetchJob::CalendarFetchJob(const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { } CalendarFetchJob::CalendarFetchJob(const QString& calendarId, const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { d->calendarId = calendarId; } CalendarFetchJob::~CalendarFetchJob() { delete d; } void CalendarFetchJob::start() { QUrl url; if (d->calendarId.isEmpty()) { url = CalendarService::fetchCalendarsUrl(); } else { url = CalendarService::fetchCalendarUrl(d->calendarId); } const QNetworkRequest request = d->createRequest(url); enqueueRequest(request); } ObjectsList CalendarFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { FeedData feedData; feedData.requestUrl = reply->request().url(); ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->calendarId.isEmpty()) { items = CalendarService::parseCalendarJSONFeed(rawData, feedData); } else { items << CalendarService::JSONToCalendar(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); enqueueRequest(request); } return items; } diff --git a/src/calendar/calendarmodifyjob.cpp b/src/calendar/calendarmodifyjob.cpp index 95747ff..0e77a08 100644 --- a/src/calendar/calendarmodifyjob.cpp +++ b/src/calendar/calendarmodifyjob.cpp @@ -1,109 +1,107 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "calendarmodifyjob.h" #include "calendarservice.h" #include "account.h" #include "calendar.h" #include "../debug.h" #include "utils.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN CalendarModifyJob::Private { public: QueueHelper calendars; }; CalendarModifyJob::CalendarModifyJob(const CalendarPtr& calendar, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->calendars << calendar; } CalendarModifyJob::CalendarModifyJob(const CalendarsList& calendars, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->calendars = calendars; } CalendarModifyJob::~CalendarModifyJob() { delete d; } void CalendarModifyJob::start() { if (d->calendars.atEnd()) { emitFinished(); return; } const CalendarPtr calendar = d->calendars.current(); const QUrl url = CalendarService::updateCalendarUrl(calendar->uid()); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); - request.setUrl(url); const QByteArray rawData = CalendarService::calendarToJSON(calendar); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList CalendarModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << CalendarService::JSONToCalendar(rawData).dynamicCast(); d->calendars.currentProcessed(); // Enqueue next item or finish start(); return items; } diff --git a/src/calendar/eventcreatejob.cpp b/src/calendar/eventcreatejob.cpp index 77dc159..59ef9fe 100644 --- a/src/calendar/eventcreatejob.cpp +++ b/src/calendar/eventcreatejob.cpp @@ -1,126 +1,124 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "eventcreatejob.h" #include "calendarservice.h" #include "account.h" #include "../debug.h" #include "event.h" #include "utils.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN EventCreateJob::Private { public: QueueHelper events; QString calendarId; SendUpdatesPolicy updatesPolicy = SendUpdatesPolicy::All; }; EventCreateJob::EventCreateJob(const EventPtr& event, const QString &calendarId, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->events << event; d->calendarId = calendarId; } EventCreateJob::EventCreateJob(const EventsList& events, const QString& calendarId, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->events = events; d->calendarId = calendarId; } EventCreateJob::~EventCreateJob() { delete d; } void EventCreateJob::setSendUpdates(SendUpdatesPolicy policy) { if (d->updatesPolicy != policy) { d->updatesPolicy = policy; Q_EMIT sendUpdatesChanged(d->updatesPolicy); } } SendUpdatesPolicy EventCreateJob::sendUpdates() const { return d->updatesPolicy; } void EventCreateJob::start() { if (d->events.atEnd()) { emitFinished(); return; } const EventPtr event = d->events.current(); const QUrl url = CalendarService::createEventUrl(d->calendarId, d->updatesPolicy); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); - request.setUrl(url); const QByteArray rawData = CalendarService::eventToJSON(event, CalendarService::EventSerializeFlag::NoID); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList EventCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << CalendarService::JSONToEvent(rawData).dynamicCast(); d->events.currentProcessed(); // Enqueue next item or finish start(); return items; } diff --git a/src/calendar/eventdeletejob.cpp b/src/calendar/eventdeletejob.cpp index 49fbc67..5173dfb 100644 --- a/src/calendar/eventdeletejob.cpp +++ b/src/calendar/eventdeletejob.cpp @@ -1,112 +1,111 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "eventdeletejob.h" #include "calendarservice.h" #include "account.h" #include "../debug.h" #include "event.h" #include "private/queuehelper_p.h" #include using namespace KGAPI2; class Q_DECL_HIDDEN EventDeleteJob::Private { public: QueueHelper eventsIds; QString calendarId; }; EventDeleteJob::EventDeleteJob(const EventPtr& event, const QString &calendarId, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private) { d->eventsIds << event->id(); d->calendarId = calendarId; } EventDeleteJob::EventDeleteJob(const EventsList& events, const QString& calendarId, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private) { for (const EventPtr &event : events) { d->eventsIds << event->id(); } d->calendarId = calendarId; } EventDeleteJob::EventDeleteJob(const QString &eventId, const QString &calendarId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->eventsIds << eventId; d->calendarId = calendarId; } EventDeleteJob::EventDeleteJob(const QStringList &eventIds, const QString &calendarId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->eventsIds = eventIds; d->calendarId = calendarId; } EventDeleteJob::~EventDeleteJob() { delete d; } void EventDeleteJob::start() { if (d->eventsIds.atEnd()) { emitFinished(); return; } const QString eventId = d->eventsIds.current(); const QUrl url = CalendarService::removeEventUrl(d->calendarId, eventId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request); } void EventDeleteJob::handleReply(const QNetworkReply* reply, const QByteArray& rawData) { d->eventsIds.currentProcessed(); KGAPI2::DeleteJob::handleReply(reply, rawData); } diff --git a/src/calendar/eventfetchjob.cpp b/src/calendar/eventfetchjob.cpp index ea3c395..41889b5 100644 --- a/src/calendar/eventfetchjob.cpp +++ b/src/calendar/eventfetchjob.cpp @@ -1,230 +1,228 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "eventfetchjob.h" #include "calendarservice.h" #include "account.h" #include "../debug.h" #include "event.h" #include "utils.h" #include #include #include using namespace KGAPI2; class Q_DECL_HIDDEN EventFetchJob::Private { public: Private(EventFetchJob *parent); QNetworkRequest createRequest(const QUrl &url); QString calendarId; QString eventId; QString filter; bool fetchDeleted; quint64 updatedTimestamp; quint64 timeMin; quint64 timeMax; private: EventFetchJob * const q; }; EventFetchJob::Private::Private(EventFetchJob* parent): fetchDeleted(true), updatedTimestamp(0), timeMin(0), timeMax(0), q(parent) { } QNetworkRequest EventFetchJob::Private::createRequest(const QUrl& url) { - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); - request.setUrl(url); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } return request; } EventFetchJob::EventFetchJob(const QString& calendarId, const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { d->calendarId = calendarId; } EventFetchJob::EventFetchJob(const QString& eventId, const QString& calendarId, const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { d->calendarId = calendarId; d->eventId = eventId; } EventFetchJob::~EventFetchJob() { delete d; } void EventFetchJob::setFetchDeleted(bool fetchDeleted) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify fetchDeleted property when job is running"; return; } d->fetchDeleted = fetchDeleted; } bool EventFetchJob::fetchDeleted() { return d->fetchDeleted; } void EventFetchJob::setFetchOnlyUpdated(quint64 timestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify setFetchOnlyUpdated property when job is running"; return; } d->updatedTimestamp = timestamp; } quint64 EventFetchJob::fetchOnlyUpdated() { return d->updatedTimestamp; } void EventFetchJob::setTimeMax(quint64 timestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify timeMax property when job is running"; return; } d->timeMax = timestamp; } quint64 EventFetchJob::timeMax() const { return d->timeMax; } void EventFetchJob::setTimeMin(quint64 timestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify timeMin property when job is running"; return; } d->timeMin = timestamp; } quint64 EventFetchJob::timeMin() const { return d->timeMin; } void EventFetchJob::setFilter(const QString &query) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify filter property when job is running"; return; } d->filter = query; } QString EventFetchJob::filter() const { return d->filter; } void EventFetchJob::start() { QUrl url; if (d->eventId.isEmpty()) { url = CalendarService::fetchEventsUrl(d->calendarId); QUrlQuery query(url); query.addQueryItem(QStringLiteral("showDeleted"), Utils::bool2Str(d->fetchDeleted)); if (!d->filter.isEmpty()) { query.addQueryItem(QStringLiteral("q"), d->filter); } if (d->updatedTimestamp > 0) { query.addQueryItem(QStringLiteral("updatedMin"), Utils::ts2Str(d->updatedTimestamp)); } if (d->timeMin > 0) { query.addQueryItem(QStringLiteral("timeMin"), Utils::ts2Str(d->timeMin)); } if (d->timeMax > 0) { query.addQueryItem(QStringLiteral("timeMax"), Utils::ts2Str(d->timeMax)); } url.setQuery(query); } else { url = CalendarService::fetchEventUrl(d->calendarId, d->eventId); } const QNetworkRequest request = d->createRequest(url); enqueueRequest(request); } ObjectsList EventFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { FeedData feedData; feedData.requestUrl = reply->url(); ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->eventId.isEmpty()) { items = CalendarService::parseEventJSONFeed(rawData, feedData); } else { items << CalendarService::JSONToEvent(rawData).dynamicCast(); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); enqueueRequest(request); } return items; } diff --git a/src/calendar/eventmodifyjob.cpp b/src/calendar/eventmodifyjob.cpp index 71db8e1..7d36144 100644 --- a/src/calendar/eventmodifyjob.cpp +++ b/src/calendar/eventmodifyjob.cpp @@ -1,125 +1,123 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "eventmodifyjob.h" #include "calendarservice.h" #include "account.h" #include "../debug.h" #include "event.h" #include "utils.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN EventModifyJob::Private { public: QueueHelper events; QString calendarId; SendUpdatesPolicy updatesPolicy = SendUpdatesPolicy::All; }; EventModifyJob::EventModifyJob(const EventPtr& event, const QString& calendarId, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->events << event; d->calendarId = calendarId; } EventModifyJob::EventModifyJob(const EventsList& events, const QString& calendarId, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->events = events; d->calendarId = calendarId; } EventModifyJob::~EventModifyJob() { delete d; } void EventModifyJob::setSendUpdates(KGAPI2::SendUpdatesPolicy updatesPolicy) { if (d->updatesPolicy != updatesPolicy) { d->updatesPolicy = updatesPolicy; Q_EMIT sendUpdatesChanged(d->updatesPolicy); } } SendUpdatesPolicy EventModifyJob::sendUpdates() const { return d->updatesPolicy; } void EventModifyJob::start() { if (d->events.atEnd()) { emitFinished(); return; } const EventPtr event = d->events.current(); const QUrl url = CalendarService::updateEventUrl(d->calendarId, event->id(), d->updatesPolicy); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); - request.setUrl(url); const QByteArray rawData = CalendarService::eventToJSON(event); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList EventModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << CalendarService::JSONToEvent(rawData).dynamicCast(); d->events.currentProcessed(); // Enqueue next item or finish start(); return items; } diff --git a/src/calendar/eventmovejob.cpp b/src/calendar/eventmovejob.cpp index 4459c92..f0915c9 100644 --- a/src/calendar/eventmovejob.cpp +++ b/src/calendar/eventmovejob.cpp @@ -1,165 +1,163 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "eventmovejob.h" #include "account.h" #include "calendarservice.h" #include "../debug.h" #include "event.h" #include "utils.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN EventMoveJob::Private { public: explicit Private(EventMoveJob *parent); void processNextEvent(); QueueHelper eventsIds; QString source; QString destination; private: EventMoveJob * const q; }; EventMoveJob::Private::Private(EventMoveJob *parent): q(parent) { } void EventMoveJob::Private::processNextEvent() { if (eventsIds.atEnd()) { q->emitFinished(); return; } const QString eventId = eventsIds.current(); const QUrl url = CalendarService::moveEventUrl(source, destination, eventId); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); - request.setUrl(url); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } q->enqueueRequest(request); } EventMoveJob::EventMoveJob(const EventPtr &event, const QString &sourceCalendarId, const QString &destinationCalendarId, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->eventsIds << event->id(); d->source = sourceCalendarId; d->destination = destinationCalendarId; } EventMoveJob::EventMoveJob(const EventsList &events, const QString &sourceCalendarId, const QString &destinationCalendarId, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { for (const EventPtr &event : events) { d->eventsIds << event->id(); } d->source = sourceCalendarId; d->destination = destinationCalendarId; } EventMoveJob::EventMoveJob(const QString &eventId, const QString &sourceCalendarId, const QString &destinationCalendarId, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->eventsIds << eventId; d->source = sourceCalendarId; d->destination = destinationCalendarId; } EventMoveJob::EventMoveJob(const QStringList &eventsIds, const QString &sourceCalendarId, const QString &destinationCalendarId, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->eventsIds = eventsIds; d->source = sourceCalendarId; d->destination = destinationCalendarId; } EventMoveJob::~EventMoveJob() { delete d; } void EventMoveJob::start() { d->processNextEvent(); } void EventMoveJob::dispatchRequest(QNetworkAccessManager *accessManager, const QNetworkRequest &request, const QByteArray &data, const QString &contentType) { Q_UNUSED(data) Q_UNUSED(contentType) accessManager->post(request, QByteArray()); } KGAPI2::ObjectsList EventMoveJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << CalendarService::JSONToEvent(rawData).dynamicCast(); d->eventsIds.currentProcessed(); // Enqueue next item or finish d->processNextEvent(); return items; } diff --git a/src/calendar/freebusyqueryjob.cpp b/src/calendar/freebusyqueryjob.cpp index 03eed39..b884ec0 100644 --- a/src/calendar/freebusyqueryjob.cpp +++ b/src/calendar/freebusyqueryjob.cpp @@ -1,142 +1,141 @@ /* * Copyright 2015 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "freebusyqueryjob.h" #include "calendarservice.h" #include "utils.h" #include "account.h" #include #include #include #include #include using namespace KGAPI2; class Q_DECL_HIDDEN FreeBusyQueryJob::Private { public: Private(const QString &id, const QDateTime &timeMin, const QDateTime &timeMax) : id(id) , timeMin(timeMin) , timeMax(timeMax) {} QString id; QDateTime timeMin; QDateTime timeMax; FreeBusyQueryJob::BusyRangeList busy; }; FreeBusyQueryJob::FreeBusyQueryJob(const QString &id, const QDateTime &timeMin, const QDateTime &timeMax, const AccountPtr &account, QObject *parent) : FetchJob(account, parent) , d(new FreeBusyQueryJob::Private(id, timeMin, timeMax)) { } FreeBusyQueryJob::~FreeBusyQueryJob() { delete d; } FreeBusyQueryJob::BusyRangeList FreeBusyQueryJob::busy() const { return d->busy; } QString FreeBusyQueryJob::id() const { return d->id; } QDateTime FreeBusyQueryJob::timeMin() const { return d->timeMin; } QDateTime FreeBusyQueryJob::timeMax() const { return d->timeMax; } void FreeBusyQueryJob::start() { QVariantMap requestData({ { QStringLiteral("timeMin"), Utils::rfc3339DateToString(d->timeMin) }, { QStringLiteral("timeMax"), Utils::rfc3339DateToString(d->timeMax) }, { QStringLiteral("items"), QVariantList({ QVariantMap({ { QStringLiteral("id"), d->id } }) }) }}); QJsonDocument document = QJsonDocument::fromVariant(requestData); const QByteArray json = document.toJson(QJsonDocument::Compact); QNetworkRequest request(CalendarService::freeBusyQueryUrl()); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); request.setRawHeader("GData-Version", CalendarService::APIVersion().toLatin1()); enqueueRequest(request, json, QStringLiteral("application/json")); } void FreeBusyQueryJob::dispatchRequest(QNetworkAccessManager *accessManager, const QNetworkRequest &request, const QByteArray &data, const QString &contentType) { QNetworkRequest r = request; if (!r.hasRawHeader("Content-Type")) { r.setHeader(QNetworkRequest::ContentTypeHeader, contentType); } accessManager->post(r, data); } void FreeBusyQueryJob::handleReply(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { const QJsonDocument document = QJsonDocument::fromJson(rawData); const QVariantMap data = document.toVariant().toMap(); const QVariantMap cals = data[QStringLiteral("calendars")].toMap(); const QVariantMap cal = cals[d->id].toMap(); if (cal.contains(QStringLiteral("errors"))) { setError(KGAPI2::NotFound); setErrorString(tr("FreeBusy information is not available")); } else { const QVariantList busyList = cal[QStringLiteral("busy")].toList(); for (const QVariant &busyV : busyList) { const QVariantMap busy = busyV.toMap(); d->busy << BusyRange{ Utils::rfc3339DateFromString(busy[QStringLiteral("start")].toString()), Utils::rfc3339DateFromString(busy[QStringLiteral("end")].toString()) }; } } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); } emitFinished(); } diff --git a/src/contacts/contactcreatejob.cpp b/src/contacts/contactcreatejob.cpp index 75f1269..c6b28ce 100644 --- a/src/contacts/contactcreatejob.cpp +++ b/src/contacts/contactcreatejob.cpp @@ -1,172 +1,169 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "contactcreatejob.h" #include "contact.h" #include "contactsservice.h" #include "utils.h" #include "../debug.h" #include "account.h" #include "private/queuehelper_p.h" #include #include #include #include using namespace KGAPI2; class Q_DECL_HIDDEN ContactCreateJob::Private { public: Private(ContactCreateJob *parent); void processNextContact(); QueueHelper contacts; ContactPtr lastContact; QPair pendingPhoto; private: ContactCreateJob * const q; }; ContactCreateJob::Private::Private(ContactCreateJob *parent): q(parent) { } void ContactCreateJob::Private::processNextContact() { if (contacts.atEnd()) { if (pendingPhoto.first.isEmpty()) { q->emitFinished(); } return; } const ContactPtr contact = contacts.current(); const QUrl url = ContactsService::createContactUrl(q->account()->accountName()); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", ContactsService::APIVersion().toLatin1()); - request.setUrl(url); QByteArray rawData = ContactsService::contactToXML(contact); rawData.prepend("" ""); rawData.append(""); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } q->enqueueRequest(request, rawData, QStringLiteral("application/atom+xml")); if (!contact->photo().isEmpty()) { - QNetworkRequest photoRequest; - photoRequest.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + const QUrl url = ContactsService::photoUrl(q->account()->accountName(), contact->uid()); + QNetworkRequest photoRequest(url); photoRequest.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("image/*")); - photoRequest.setUrl(ContactsService::photoUrl(q->account()->accountName(), contact->uid())); pendingPhoto.first = contact->photo().rawData(); pendingPhoto.second = contact->photo().type(); q->enqueueRequest(photoRequest, pendingPhoto.first, QStringLiteral("modifyImage")); } } ContactCreateJob::ContactCreateJob(const ContactsList& contacts, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private(this)) { d->contacts = contacts; } ContactCreateJob::ContactCreateJob(const ContactPtr& contact, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private(this)) { d->contacts << contact; } ContactCreateJob::~ContactCreateJob() { delete d; } void ContactCreateJob::start() { d->processNextContact(); } void ContactCreateJob::dispatchRequest(QNetworkAccessManager *accessManager, const QNetworkRequest &request, const QByteArray &data, const QString &contentType) { QNetworkRequest r = request; if (contentType == QLatin1String("modifyImage")) { accessManager->put(r, data); } else { r.setHeader(QNetworkRequest::ContentTypeHeader, contentType); accessManager->post(r, data); } } ObjectsList ContactCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { ObjectsList items; if (!reply->url().path().contains(QLatin1String("/photos/media/"))) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { d->lastContact = ContactsService::JSONToContact(rawData); items << d->lastContact.dynamicCast(); d->contacts.currentProcessed(); } else if (ct == KGAPI2::XML) { d->lastContact = ContactsService::XMLToContact(rawData); items << d->lastContact.dynamicCast(); d->contacts.currentProcessed(); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } } else { if (d->lastContact) { KContacts::Picture picture; picture.setRawData(d->pendingPhoto.first, d->pendingPhoto.second); d->lastContact->setPhoto(picture); d->pendingPhoto.first.clear(); d->pendingPhoto.second.clear(); } } // Enqueue next item or finish d->processNextContact(); return items; } diff --git a/src/contacts/contactdeletejob.cpp b/src/contacts/contactdeletejob.cpp index 2b373bf..8b18788 100644 --- a/src/contacts/contactdeletejob.cpp +++ b/src/contacts/contactdeletejob.cpp @@ -1,126 +1,125 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "contactdeletejob.h" #include "contact.h" #include "contactsservice.h" #include "../debug.h" #include "utils.h" #include "account.h" #include "private/queuehelper_p.h" #include using namespace KGAPI2; class Q_DECL_HIDDEN ContactDeleteJob::Private { public: Private(ContactDeleteJob *parent); void processNextContact(); QueueHelper contactIds; private: ContactDeleteJob * const q; }; ContactDeleteJob::Private::Private(ContactDeleteJob* parent): q(parent) { } void ContactDeleteJob::Private::processNextContact() { if (contactIds.atEnd()) { q->emitFinished(); return; } const QString contactId = contactIds.current(); const QUrl url = ContactsService::removeContactUrl(q->account()->accountName(), contactId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); request.setRawHeader("GData-Version", ContactsService::APIVersion().toLatin1()); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } q->enqueueRequest(request); } ContactDeleteJob::ContactDeleteJob(const ContactsList& contacts, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private(this)) { d->contactIds.reserve(contacts.size()); for (const ContactPtr &contact : contacts) { d->contactIds << contact->uid(); } } ContactDeleteJob::ContactDeleteJob(const ContactPtr& contact, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private(this)) { d->contactIds << contact->uid(); } ContactDeleteJob::ContactDeleteJob(const QStringList &contactIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private(this)) { d->contactIds = contactIds; } ContactDeleteJob::ContactDeleteJob(const QString &contactId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private(this)) { d->contactIds << contactId; } ContactDeleteJob::~ContactDeleteJob() { delete d; } void ContactDeleteJob::start() { d->processNextContact(); } void ContactDeleteJob::handleReply(const QNetworkReply *reply, const QByteArray &rawData) { Q_UNUSED(reply) Q_UNUSED(rawData) d->contactIds.currentProcessed(); d->processNextContact(); } diff --git a/src/contacts/contactfetchjob.cpp b/src/contacts/contactfetchjob.cpp index fdbe2fc..217fd2c 100644 --- a/src/contacts/contactfetchjob.cpp +++ b/src/contacts/contactfetchjob.cpp @@ -1,190 +1,188 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "contactfetchjob.h" #include "contact.h" #include "contactsservice.h" #include "../debug.h" #include "utils.h" #include "account.h" #include #include #include using namespace KGAPI2; class Q_DECL_HIDDEN ContactFetchJob::Private { public: Private(ContactFetchJob *parent); QNetworkRequest createRequest(const QUrl &url); bool fetchDeleted; QString contactId; quint64 timestamp; QString filter; private: ContactFetchJob * const q; }; ContactFetchJob::Private::Private(ContactFetchJob *parent): fetchDeleted(true), timestamp(0), q(parent) { } QNetworkRequest ContactFetchJob::Private::createRequest(const QUrl& url) { - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", ContactsService::APIVersion().toLatin1()); - request.setUrl(url); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } return request; } ContactFetchJob::ContactFetchJob(const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { } ContactFetchJob::ContactFetchJob(const QString& contactId, const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { d->contactId = contactId; } ContactFetchJob::~ContactFetchJob() { delete d; } bool ContactFetchJob::fetchDeleted() const { return d->fetchDeleted; } void ContactFetchJob::setFetchDeleted(bool fetchDeleted) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify fetchDeleted property when job is running"; return; } d->fetchDeleted = fetchDeleted; } quint64 ContactFetchJob::fetchOnlyUpdated() { return d->timestamp; } void ContactFetchJob::setFetchOnlyUpdated(quint64 timestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify fetchOnlyUpdated property when job is running"; return; } d->timestamp = timestamp; } QString ContactFetchJob::filter() const { return d->filter; } void ContactFetchJob::setFilter(const QString &query) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify filter property when job is running"; return; } d->filter = query; } void ContactFetchJob::start() { QUrl url; if (d->contactId.isEmpty()) { url = ContactsService::fetchAllContactsUrl(account()->accountName(), d->fetchDeleted); QUrlQuery query(url); if (d->timestamp > 0) { query.addQueryItem(QStringLiteral("updated-min"), Utils::ts2Str(d->timestamp)); } if (!d->filter.isEmpty()) { query.addQueryItem(QStringLiteral("q"), d->filter); } url.setQuery(query); } else { url = ContactsService::fetchContactUrl(account()->accountName(), d->contactId); } const QNetworkRequest request = d->createRequest(url); enqueueRequest(request); } ObjectsList ContactFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { FeedData feedData; ObjectsList items; QString itemId; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->contactId.isEmpty()) { items = ContactsService::parseJSONFeed(rawData, feedData); } else { items << ContactsService::JSONToContact(rawData); } if (feedData.nextPageUrl.isValid()) { emitProgress(feedData.startIndex, feedData.totalResults); const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); enqueueRequest(request); } else { emitFinished(); } return items; } return ObjectsList(); } diff --git a/src/contacts/contactfetchphotojob.cpp b/src/contacts/contactfetchphotojob.cpp index b182e51..18aab4d 100644 --- a/src/contacts/contactfetchphotojob.cpp +++ b/src/contacts/contactfetchphotojob.cpp @@ -1,117 +1,115 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "contactfetchphotojob.h" #include "account.h" #include "contact.h" #include "contactsservice.h" #include "private/queuehelper_p.h" #include #include #include Q_DECLARE_METATYPE(KGAPI2::ContactPtr) using namespace KGAPI2; class Q_DECL_HIDDEN ContactFetchPhotoJob::Private { public: Private(ContactFetchPhotoJob *parent); void processNextContact(); QueueHelper contacts; private: ContactFetchPhotoJob * const q; }; ContactFetchPhotoJob::Private::Private(ContactFetchPhotoJob *parent): q(parent) { } void ContactFetchPhotoJob::Private::processNextContact() { if (contacts.atEnd()) { q->emitFinished(); return; } const ContactPtr contact = contacts.current(); const QUrl url = ContactsService::photoUrl(q->account()->accountName(), contact->uid()); - QNetworkRequest request; - request.setUrl(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", ContactsService::APIVersion().toLatin1()); q->enqueueRequest(request); } ContactFetchPhotoJob::ContactFetchPhotoJob(const ContactsList &contacts, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->contacts = contacts; } ContactFetchPhotoJob::ContactFetchPhotoJob(const ContactPtr &contact, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->contacts << contact; } ContactFetchPhotoJob::~ContactFetchPhotoJob() { delete d; } void ContactFetchPhotoJob::start() { d->processNextContact(); } void ContactFetchPhotoJob::handleReply(const QNetworkReply *reply, const QByteArray &rawData) { if (reply->error() == QNetworkReply::ContentNotFoundError || reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == NotFound) { d->contacts.currentProcessed(); d->processNextContact(); // If the last photo failed, make sure we don't fail the whole job! setError(KGAPI2::NoError); setErrorString(QString()); return; } ContactPtr contact = d->contacts.current(); KContacts::Picture picture; picture.setRawData(rawData, reply->header(QNetworkRequest::ContentTypeHeader).toString()); contact->setPhoto(picture); Q_EMIT photoFetched(this, contact); d->contacts.currentProcessed(); d->processNextContact(); } diff --git a/src/contacts/contactmodifyjob.cpp b/src/contacts/contactmodifyjob.cpp index e582edf..2f74adc 100644 --- a/src/contacts/contactmodifyjob.cpp +++ b/src/contacts/contactmodifyjob.cpp @@ -1,180 +1,176 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "contactmodifyjob.h" #include "contactsservice.h" #include "contact.h" #include "../debug.h" #include "utils.h" #include "account.h" #include "private/queuehelper_p.h" #include #include #include #include using namespace KGAPI2; class Q_DECL_HIDDEN ContactModifyJob::Private { public: Private(ContactModifyJob *parent); void processNextContact(); QueueHelper contacts; ContactPtr lastContact; QPair pendingPhoto; private: ContactModifyJob *q; }; ContactModifyJob::Private::Private(ContactModifyJob *parent): q(parent) { } void ContactModifyJob::Private::processNextContact() { if (contacts.atEnd()) { if (pendingPhoto.first.isEmpty()) { q->emitFinished(); } return; } const ContactPtr contact = contacts.current(); const QUrl url = ContactsService::updateContactUrl(q->account()->accountName(), contact->uid()); - QNetworkRequest request; - request.setUrl(url); + QNetworkRequest request(url); QByteArray rawData = ContactsService::contactToXML(contact); rawData.prepend("" ""); rawData.append(""); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } q->enqueueRequest(request, rawData, QStringLiteral("application/atom+xml")); - QNetworkRequest photoRequest; - photoRequest.setUrl(ContactsService::photoUrl(q->account()->accountName(), contact->uid())); + const QUrl photoUrl = ContactsService::photoUrl(q->account()->accountName(), contact->uid()); + QNetworkRequest photoRequest(photoUrl); if (!contact->photo().isEmpty()) { - QNetworkRequest photoRequest; photoRequest.setHeader(QNetworkRequest::ContentTypeHeader, QLatin1String("image/*")); - photoRequest.setUrl(ContactsService::photoUrl(q->account()->accountName(), contact->uid())); pendingPhoto.first = contact->photo().rawData(); pendingPhoto.second = contact->photo().type(); q->enqueueRequest(photoRequest, pendingPhoto.first, QStringLiteral("modifyImage")); } else { q->enqueueRequest(photoRequest, QByteArray(), QStringLiteral("deleteImage")); } } ContactModifyJob::ContactModifyJob(const ContactsList& contacts, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private(this)) { d->contacts = contacts; } ContactModifyJob::ContactModifyJob(const ContactPtr& contact, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private(this)) { d->contacts << contact; } ContactModifyJob::~ContactModifyJob() { delete d; } void ContactModifyJob::start() { d->processNextContact(); } void ContactModifyJob::dispatchRequest(QNetworkAccessManager *accessManager, const QNetworkRequest &request, const QByteArray &data, const QString &contentType) { QNetworkRequest r = request; r.setRawHeader("If-Match", "*"); - r.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); r.setRawHeader("GData-Version", ContactsService::APIVersion().toLatin1()); if (contentType == QLatin1String("modifyImage")) { accessManager->put(r, data); } else if (contentType == QLatin1String("deleteImage")) { accessManager->deleteResource(r); } else { r.setHeader(QNetworkRequest::ContentTypeHeader, contentType); accessManager->put(r, data); } } ObjectsList ContactModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { ObjectsList items; if (!reply->url().path().contains(QLatin1String("/photos/media/"))) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { d->lastContact = ContactsService::JSONToContact(rawData); items << d->lastContact; d->contacts.currentProcessed(); } else if (ct == KGAPI2::XML) { d->lastContact = ContactsService::XMLToContact(rawData); items << d->lastContact; d->contacts.currentProcessed(); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } } else { if (d->lastContact && !d->pendingPhoto.first.isEmpty()) { KContacts::Picture picture; picture.setRawData(d->pendingPhoto.first, d->pendingPhoto.second); d->lastContact->setPhoto(picture); d->pendingPhoto.first.clear(); d->pendingPhoto.second.clear(); } // Enqueue next item and picture or finish d->processNextContact(); } return items; } diff --git a/src/contacts/contactsgroupcreatejob.cpp b/src/contacts/contactsgroupcreatejob.cpp index da6a8ff..37cfb08 100644 --- a/src/contacts/contactsgroupcreatejob.cpp +++ b/src/contacts/contactsgroupcreatejob.cpp @@ -1,117 +1,115 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "contactsgroupcreatejob.h" #include "contactsgroup.h" #include "contactsservice.h" #include "../debug.h" #include "utils.h" #include "account.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN ContactsGroupCreateJob::Private { public: QueueHelper groups; }; ContactsGroupCreateJob::ContactsGroupCreateJob(const ContactsGroupsList& groups, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->groups = groups; } ContactsGroupCreateJob::ContactsGroupCreateJob(const ContactsGroupPtr& contactsGroup, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->groups << contactsGroup; } ContactsGroupCreateJob::~ContactsGroupCreateJob() { delete d; } void ContactsGroupCreateJob::start() { if (d->groups.atEnd()) { emitFinished(); return; } const ContactsGroupPtr contact = d->groups.current(); const QUrl url = ContactsService::createGroupUrl(account()->accountName()); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", ContactsService::APIVersion().toLatin1()); - request.setUrl(url); QByteArray rawData = ContactsService::contactsGroupToXML(contact); rawData.prepend("" ""); rawData.append(""); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/atom+xml")); } ObjectsList ContactsGroupCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << ContactsService::JSONToContactsGroup(rawData); d->groups.currentProcessed(); } else if (ct == KGAPI2::XML) { items << ContactsService::XMLToContactsGroup(rawData); d->groups.currentProcessed(); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } // Enqueue next item or finish start(); return items; } diff --git a/src/contacts/contactsgroupdeletejob.cpp b/src/contacts/contactsgroupdeletejob.cpp index 67e1932..b6bce83 100644 --- a/src/contacts/contactsgroupdeletejob.cpp +++ b/src/contacts/contactsgroupdeletejob.cpp @@ -1,128 +1,126 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "contactsgroupdeletejob.h" #include "contactsgroup.h" #include "contactsservice.h" #include "../debug.h" #include "utils.h" #include "account.h" #include "private/queuehelper_p.h" #include using namespace KGAPI2; class Q_DECL_HIDDEN ContactsGroupDeleteJob::Private { public: Private(ContactsGroupDeleteJob *parent); QNetworkRequest createRequest(const QUrl &url) const; QueueHelper groupsIds; private: ContactsGroupDeleteJob * const q; }; ContactsGroupDeleteJob::Private::Private(ContactsGroupDeleteJob* parent): q(parent) { } QNetworkRequest ContactsGroupDeleteJob::Private::createRequest(const QUrl& url) const { - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", ContactsService::APIVersion().toLatin1()); - request.setUrl(url); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } return request; } ContactsGroupDeleteJob::ContactsGroupDeleteJob(const ContactsGroupsList& groups, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private(this)) { d->groupsIds.reserve(groups.size()); for(const ContactsGroupPtr &group : groups) { d->groupsIds << group->id(); } } ContactsGroupDeleteJob::ContactsGroupDeleteJob(const ContactsGroupPtr& group, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private(this)) { d->groupsIds << group->id(); } ContactsGroupDeleteJob::ContactsGroupDeleteJob(const QStringList &groupsIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private(this)) { d->groupsIds = groupsIds; } ContactsGroupDeleteJob::ContactsGroupDeleteJob(const QString &groupId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private(this)) { d->groupsIds << groupId; } ContactsGroupDeleteJob::~ContactsGroupDeleteJob() { delete d; } void ContactsGroupDeleteJob::start() { if (d->groupsIds.atEnd()) { emitFinished(); return; } const QString groupId = d->groupsIds.current(); const QUrl url = ContactsService::removeGroupUrl(account()->accountName(), groupId); const QNetworkRequest request = d->createRequest(url); enqueueRequest(request); } void ContactsGroupDeleteJob::handleReply(const QNetworkReply* reply, const QByteArray& rawData) { d->groupsIds.currentProcessed(); KGAPI2::DeleteJob::handleReply(reply, rawData); } diff --git a/src/contacts/contactsgroupfetchjob.cpp b/src/contacts/contactsgroupfetchjob.cpp index 907fbe4..cdad79b 100644 --- a/src/contacts/contactsgroupfetchjob.cpp +++ b/src/contacts/contactsgroupfetchjob.cpp @@ -1,131 +1,129 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "contactsgroupfetchjob.h" #include "contactsgroup.h" #include "contactsservice.h" #include "../debug.h" #include "utils.h" #include "account.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN ContactsGroupFetchJob::Private { public: Private(ContactsGroupFetchJob *parent); QNetworkRequest createRequest(const QUrl &url); QString groupId; private: ContactsGroupFetchJob * const q; }; ContactsGroupFetchJob::Private::Private(ContactsGroupFetchJob* parent): q(parent) { } QNetworkRequest ContactsGroupFetchJob::Private::createRequest(const QUrl& url) { - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", ContactsService::APIVersion().toLatin1()); - request.setUrl(url); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } return request; } ContactsGroupFetchJob::ContactsGroupFetchJob(const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { } ContactsGroupFetchJob::ContactsGroupFetchJob(const QString& groupId, const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { d->groupId = groupId; } ContactsGroupFetchJob::~ContactsGroupFetchJob() { delete d; } void ContactsGroupFetchJob::start() { QUrl url; if (d->groupId.isEmpty()) { url = ContactsService::fetchAllGroupsUrl(account()->accountName()); } else { url = ContactsService::fetchGroupUrl(account()->accountName(), d->groupId); } const QNetworkRequest request = d->createRequest(url); enqueueRequest(request); } ObjectsList ContactsGroupFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { FeedData feedData; ObjectsList items; QString itemId; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->groupId.isEmpty()) { items = ContactsService::parseJSONFeed(rawData, feedData); } else { items << ContactsService::JSONToContactsGroup(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { emitProgress(feedData.itemsPerPage * feedData.startIndex, feedData.totalResults); const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); enqueueRequest(request); } return items; } diff --git a/src/contacts/contactsgroupmodifyjob.cpp b/src/contacts/contactsgroupmodifyjob.cpp index cf0f751..90913ba 100644 --- a/src/contacts/contactsgroupmodifyjob.cpp +++ b/src/contacts/contactsgroupmodifyjob.cpp @@ -1,120 +1,118 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "contactsgroupmodifyjob.h" #include "contactsgroup.h" #include "contactsservice.h" #include "../debug.h" #include "utils.h" #include "account.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN ContactsGroupModifyJob::Private { public: QueueHelper groups; }; ContactsGroupModifyJob::ContactsGroupModifyJob(const ContactsGroupsList& groups, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->groups = groups; } ContactsGroupModifyJob::ContactsGroupModifyJob(const ContactsGroupPtr& group, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->groups << group; } ContactsGroupModifyJob::~ContactsGroupModifyJob() { delete d; } void ContactsGroupModifyJob::start() { if (d->groups.atEnd()) { emitFinished(); return; } const ContactsGroupPtr group = d->groups.current(); const QUrl url = ContactsService::updateGroupUrl(account()->accountName(), group->id()); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", ContactsService::APIVersion().toLatin1()); - request.setUrl(url); QByteArray rawData = ContactsService::contactsGroupToXML(group); rawData.prepend("" ""); rawData.append(""); QStringList headers; auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/atom+xml")); } ObjectsList ContactsGroupModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << ContactsService::JSONToContactsGroup(rawData); d->groups.currentProcessed(); } else if (ct == KGAPI2::XML) { items << ContactsService::XMLToContactsGroup(rawData); d->groups.currentProcessed(); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } // Enqueue next item or finish start(); return items; } diff --git a/src/core/accountinfo/accountinfofetchjob.cpp b/src/core/accountinfo/accountinfofetchjob.cpp index f5e31cb..b88ecd1 100644 --- a/src/core/accountinfo/accountinfofetchjob.cpp +++ b/src/core/accountinfo/accountinfofetchjob.cpp @@ -1,82 +1,82 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "accountinfofetchjob.h" #include "account.h" #include "accountinfo.h" #include "../debug.h" #include "utils.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN AccountInfoFetchJob::Private { }; AccountInfoFetchJob::AccountInfoFetchJob(const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private) { } AccountInfoFetchJob::~AccountInfoFetchJob() { delete d; } void AccountInfoFetchJob::start() { - QNetworkRequest request(QUrl(QStringLiteral("https://www.googleapis.com/oauth2/v1/userinfo"))); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + const QUrl url = QUrl(QStringLiteral("https://www.googleapis.com/oauth2/v1/userinfo")); + QNetworkRequest request(url); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request); } ObjectsList AccountInfoFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { items << AccountInfo::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } return items; } #include "moc_accountinfofetchjob.cpp" diff --git a/src/core/job.cpp b/src/core/job.cpp index 1123f46..3fb37e6 100644 --- a/src/core/job.cpp +++ b/src/core/job.cpp @@ -1,489 +1,492 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "job.h" #include "job_p.h" #include "account.h" #include "networkaccessmanagerfactory_p.h" #include "../debug.h" #include "authjob.h" #include #include #include #include using namespace KGAPI2; FileLogger *FileLogger::sInstance = nullptr; FileLogger::FileLogger() { if (!qEnvironmentVariableIsSet("KGAPI_SESSION_LOGFILE")) { return; } QString filename = QString::fromLocal8Bit(qgetenv("KGAPI_SESSION_LOGFILE")) + QLatin1Char('.') + QString::number(QCoreApplication::applicationPid()); mFile.reset(new QFile(filename)); if (!mFile->open(QIODevice::WriteOnly | QIODevice::Truncate)) { qCWarning(KGAPIDebug) << "Failed to open logging file" << filename << ":" << mFile->errorString(); mFile.reset(); } } FileLogger::~FileLogger() {} FileLogger *FileLogger::self() { if (!sInstance) { sInstance = new FileLogger(); } return sInstance; } -void FileLogger::logRequest(const KGAPI2::Request &request) +void FileLogger::logRequest(const QNetworkRequest &request, const QByteArray &rawData) { if (!mFile) { return; } QTextStream stream(mFile.data()); - stream << "C: " << request.request.url().toDisplayString() << "\n"; - stream << " Content-type: " << request.contentType << "\n"; - const auto headers = request.request.rawHeaderList(); + stream << "C: " << request.url().toDisplayString() << "\n"; + const auto headers = request.rawHeaderList(); for (const auto &header : headers) { - stream << " " << header << ": " << request.request.rawHeader(header) << "\n\n"; + stream << " " << header << ": " << request.rawHeader(header) << "\n"; } - stream << " " << request.rawData << "\n\n"; + stream << " " << rawData << "\n\n"; mFile->flush(); } void FileLogger::logReply(const QNetworkReply *reply, const QByteArray &rawData) { if (!mFile) { return; } QTextStream stream(mFile.data()); stream << "S: " << reply->url().toDisplayString() << "\n"; const auto headers = reply->rawHeaderList(); for (const auto &header : headers) { - stream << " " << header << ": " << reply->rawHeader(header) << "\n\n"; + stream << " " << header << ": " << reply->rawHeader(header) << "\n"; } - stream << " " << rawData; + stream << " " << rawData << "\n\n"; mFile->flush(); } Job::Private::Private(Job *parent): isRunning(false), error(KGAPI2::NoError), accessManager(nullptr), maxTimeout(0), q(parent) { } void Job::Private::init() { QTimer::singleShot(0, q, [this]() { _k_doStart(); }); accessManager = NetworkAccessManagerFactory::instance()->networkAccessManager(q); connect(accessManager, &QNetworkAccessManager::finished, q, [this](QNetworkReply *reply) { _k_replyReceived(reply); }); dispatchTimer = new QTimer(q); connect(dispatchTimer, &QTimer::timeout, q, [this]() { _k_dispatchTimeout(); }); } QString Job::Private::parseErrorMessage(const QByteArray &json) { QJsonDocument document = QJsonDocument::fromJson(json); if (!document.isNull()) { QVariantMap map = document.toVariant().toMap(); QString message; if (map.contains(QStringLiteral("error"))) { map = map.value(QStringLiteral("error")).toMap(); } if (map.contains(QStringLiteral("message"))) { message.append(map.value(QStringLiteral("message")).toString()); } else { message = QLatin1String(json); } return message; } else { return QLatin1String(json); } } void Job::Private::_k_doStart() { isRunning = true; q->aboutToStart(); q->start(); } void Job::Private::_k_doEmitFinished() { Q_EMIT q->finished(q); } void Job::Private::_k_replyReceived(QNetworkReply* reply) { int replyCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (replyCode == 0) { /* Workaround for a bug (??), when QNetworkReply does not report HTTP/1.1 401 Unauthorized * as an error. */ if (!reply->rawHeaderList().isEmpty()) { QString status = QLatin1String(reply->rawHeaderList().first()); if (status.startsWith(QLatin1String("HTTP/1.1 401"))) replyCode = KGAPI2::Unauthorized; } } const QByteArray rawData = reply->readAll(); qCDebug(KGAPIDebug) << "Received reply from" << reply->url(); qCDebug(KGAPIDebug) << "Status code: " << replyCode; FileLogger::self()->logReply(reply, rawData); switch (replyCode) { case KGAPI2::NoError: case KGAPI2::OK: /** << OK status (fetched, updated, removed) */ case KGAPI2::Created: /** << OK status (created) */ case KGAPI2::NoContent: /** << OK status (removed task using Tasks API) */ break; case KGAPI2::TemporarilyMoved: { /** << Temporarily moved - Google provides a new URL where to send the request */ qCDebug(KGAPIDebug) << "Google says: Temporarily moved to " << reply->header(QNetworkRequest::LocationHeader).toUrl(); QNetworkRequest request = currentRequest.request; request.setUrl(reply->header(QNetworkRequest::LocationHeader).toUrl()); q->enqueueRequest(request, currentRequest.rawData, currentRequest.contentType); return; } case KGAPI2::BadRequest: /** << Bad request - malformed data, API changed, something went wrong... */ qCWarning(KGAPIDebug) << "Bad request, Google replied '" << rawData << "'"; q->setError(KGAPI2::BadRequest); q->setErrorString(tr("Bad request.")); q->emitFinished(); return; case KGAPI2::Unauthorized: /** << Unauthorized - Access token has expired, request a new token */ qCWarning(KGAPIDebug) << "Unauthorized. Access token has expired or is invalid."; q->setError(KGAPI2::Unauthorized); q->setErrorString(tr("Invalid authentication.")); q->emitFinished(); return; case KGAPI2::Forbidden: { qCWarning(KGAPIDebug) << "Requested resource is forbidden."; const QString msg = parseErrorMessage(rawData); q->setError(KGAPI2::Forbidden); q->setErrorString(tr("Requested resource is forbidden.\n\nGoogle replied '%1'").arg(msg)); q->emitFinished(); return; } case KGAPI2::NotFound: { qCWarning(KGAPIDebug) << "Requested resource does not exist"; const QString msg = parseErrorMessage(rawData); q->setError(KGAPI2::NotFound); q->setErrorString(tr("Requested resource does not exist.\n\nGoogle replied '%1'").arg(msg)); // don't emit finished() here, we can get 404 when fetching contact photos or so, // in that case 404 is not fatal. Let subclass decide whether to terminate or not. q->handleReply(reply, rawData); if (requestQueue.isEmpty()) { q->emitFinished(); } return; } case KGAPI2::Conflict: { qCWarning(KGAPIDebug) << "Conflict. Remote resource is newer then local."; const QString msg = parseErrorMessage(rawData); q->setError(KGAPI2::Conflict); q->setErrorString(tr("Conflict. Remote resource is newer than local.\n\nGoogle replied '%1'").arg(msg)); q->emitFinished(); return; } case KGAPI2::Gone: { qCWarning(KGAPIDebug) << "Requested resource does not exist anymore."; const QString msg = parseErrorMessage(rawData); q->setError(KGAPI2::Gone); q->setErrorString(tr("Requested resource does not exist anymore.\n\nGoogle replied '%1'").arg(msg)); q->emitFinished(); return; } case KGAPI2::InternalError: { qCWarning(KGAPIDebug) << "Internal server error."; const QString msg = parseErrorMessage(rawData); q->setError(KGAPI2::InternalError); q->setErrorString(tr("Internal server error. Try again later.\n\nGoogle replied '%1'").arg(msg)); q->emitFinished(); return; } case KGAPI2::QuotaExceeded: { qCWarning(KGAPIDebug) << "User quota exceeded."; // Extend the interval (if possible) and enqueue the request again int interval = dispatchTimer->interval() / 1000; if (interval == 0) { interval = 1; } else if (interval == 1) { interval = 2; } else if ((interval > maxTimeout) && (maxTimeout > 0)) { const QString msg = parseErrorMessage(rawData); q->setError(KGAPI2::QuotaExceeded); q->setErrorString(tr("Maximum quota exceeded. Try again later.\n\nGoogle replied '%1'").arg(msg)); q->emitFinished(); return; } else { interval = interval ^ 2; } qCDebug(KGAPIDebug) << "Increasing dispatch interval to" << interval * 1000 << "msecs"; dispatchTimer->setInterval(interval * 1000); const QNetworkRequest request = reply->request(); q->enqueueRequest(request); if (!dispatchTimer->isActive()) { dispatchTimer->start(); } return; } default:{ /** Something went wrong, there's nothing we can do about it */ qCWarning(KGAPIDebug) << "Unknown error" << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); const QString msg = parseErrorMessage(rawData); q->setError(KGAPI2::UnknownError); q->setErrorString(tr("Unknown error.\n\nGoogle replied '%1'").arg(msg)); q->emitFinished(); return; } } q->handleReply(reply, rawData); // handleReply has terminated the job, don't continue if (!q->isRunning()) { return; } qCDebug(KGAPIDebug) << requestQueue.length() << "requests in requestQueue."; if (requestQueue.isEmpty()) { q->emitFinished(); return; } if (!dispatchTimer->isActive()) { dispatchTimer->start(); } } void Job::Private::_k_dispatchTimeout() { if (requestQueue.isEmpty()) { dispatchTimer->stop(); return; } const Request r = requestQueue.dequeue(); currentRequest = r; + QNetworkRequest authorizedRequest = r.request; + if (account) { + authorizedRequest.setRawHeader("Authorization", "Bearer " + account->accessToken().toLatin1()); + } qCDebug(KGAPIDebug) << q << "Dispatching request to" << r.request.url(); - FileLogger::self()->logRequest(r); + FileLogger::self()->logRequest(authorizedRequest, r.rawData); - q->dispatchRequest(accessManager, r.request, r.rawData, r.contentType); + q->dispatchRequest(accessManager, authorizedRequest, r.rawData, r.contentType); if (requestQueue.isEmpty()) { dispatchTimer->stop(); } } /************************* PUBLIC **********************/ Job::Job(QObject* parent): QObject(parent), d(new Private(this)) { d->init(); } Job::Job(const AccountPtr& account, QObject* parent): QObject(parent), d(new Private(this)) { d->account = account; d->init(); } Job::~Job() { delete d; } void Job::setError(Error error) { d->error = error; } Error Job::error() const { if (isRunning()) { qCWarning(KGAPIDebug) << "Called error() on running job, returning nothing"; return KGAPI2::NoError; } return d->error; } void Job::setErrorString(const QString& errorString) { d->errorString = errorString; } QString Job::errorString() const { if (isRunning()) { qCWarning(KGAPIDebug) << "Called errorString() on running job, returning nothing"; return QString(); } return d->errorString; } bool Job::isRunning() const { return d->isRunning; } int Job::maxTimeout() const { return d->maxTimeout; } void Job::setMaxTimeout(int maxTimeout) { if (isRunning()) { qCWarning(KGAPIDebug) << "Called setMaxTimeout() on running job. Ignoring."; return; } d->maxTimeout = maxTimeout; } AccountPtr Job::account() const { return d->account; } void Job::setAccount(const AccountPtr& account) { if (d->isRunning) { qCWarning(KGAPIDebug) << "Called setAccount() on running job. Ignoring."; return; } d->account = account; } void Job::restart() { if (d->isRunning) { qCWarning(KGAPIDebug) << "Running job cannot be restarted."; return; } QTimer::singleShot(0, this, [this]() { d->_k_doStart();}); } void Job::emitFinished() { qCDebug(KGAPIDebug); aboutToFinish(); d->isRunning = false; d->dispatchTimer->stop(); d->requestQueue.clear(); // Emit in next event loop iteration so that the method caller can finish // before user is notified QTimer::singleShot(0, this, [this]() { d->_k_doEmitFinished(); }); } void Job::emitProgress(int processed, int total) { Q_EMIT progress(this, processed, total); } void Job::enqueueRequest(const QNetworkRequest& request, const QByteArray& data, const QString& contentType) { if (!isRunning()) { qCDebug(KGAPIDebug) << "Can't enqueue requests when job is not running."; qCDebug(KGAPIDebug) << "Not enqueueing" << request.url(); return; } qCDebug(KGAPIDebug) << "Queued" << request.url(); Request r_; r_.request = request; r_.rawData = data; r_.contentType = contentType; d->requestQueue.enqueue(r_); if (!d->dispatchTimer->isActive()) { d->dispatchTimer->start(); } } void Job::aboutToFinish() { } void Job::aboutToStart() { d->error = KGAPI2::NoError; d->errorString.clear(); d->currentRequest.contentType.clear(); d->currentRequest.rawData.clear(); d->currentRequest.request = QNetworkRequest(); d->dispatchTimer->setInterval(0); } #include "moc_job.cpp" diff --git a/src/core/job.h b/src/core/job.h index 8d64619..9912f18 100644 --- a/src/core/job.h +++ b/src/core/job.h @@ -1,334 +1,336 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #ifndef LIBKGAPI2_JOB_H #define LIBKGAPI2_JOB_H #include "types.h" #include "kgapicore_export.h" #include class QNetworkAccessManager; class QNetworkReply; class QNetworkRequest; namespace KGAPI2 { /** * @headerfile job.h * @brief Abstract base class for all jobs in LibKGAPI * * Usual workflow of Job subclasses is to reimplement Job::start, * Job::dispatchRequest and Job::handleReply, then enqueue a QNetworkRequest using - * Job::enqueueRequest. The request will automatically be scheduled in a queue - * and dispatched by calling Job::dispatchRequest implementation. When a reply - * is received, the Job will automatically perform error handling and if there - * is no error, the reply is passed to implementation of Job::handleReply. + * Job::enqueueRequest. Authorization headers and standard query parameters will be + * set by Job class. The request will automatically be scheduled in a queue and + * dispatched by calling Job::dispatchRequest implementation. When a reply is received, + * the Job will automatically perform error handling and if there is no error, the + * reply is passed to implementation of Job::handleReply. * - * Job is automatically when program enters an event loop. + * Job is automatically started when program enters an event loop. * * @author Daniel Vrátil * @since 2.0 */ class KGAPICORE_EXPORT Job : public QObject { Q_OBJECT /** * @brief Maximum interval between requests. * * Some Google APIs have a quota on maximum amount of requests per account * per second. When this quota is exceeded, the Job will automatically increase * the interval between dispatching requests, wait for a while and then try * again. If however the interval is increased over @p maxTimeout, the job * will fail and finish immediately. By default @p maxTimeout is @p -1, which * allows the interval to be increased indefinitely. * * @see Job::maxTimeout, Job::setMaxTimeout */ Q_PROPERTY(int maxTimeout READ maxTimeout WRITE setMaxTimeout) /** * @brief Whether the job is running * * This property indicates whether the job is running or not. The value is - * set to @p true when the job is started (see Job::start) and back to + * set to @p true when the job is started (see Job::start) and back to * @p false right before Job::finished is emitted. * * @see Job::isRunning, Job::finished */ Q_PROPERTY(bool isRunning READ isRunning NOTIFY finished) public: /** * @brief Constructor for jobs that don't require authentication * * @param parent */ explicit Job(QObject* parent = nullptr); /** * @brief Constructor for jobs that require authentication * * @param account Account to use to authenticate the requests send by this job * @param parent * @see Job::Account, Job::setAccount */ explicit Job(const AccountPtr &account, QObject* parent = nullptr); /** * @brief Destructor */ ~Job() override; /** * @brief Error code * * This method can only be called after the job has emitted Job::finished * signal. Calling this method on a running job will always return * KGAPI2::NoError. * * @return Returns code of occurred error or KGAPI2::NoError when no error * has occurred. */ KGAPI2::Error error() const; /** * @brief Error string * * This method can only be called after the job has emitted Job::finished * signal. Calling this method on a running job will always return an empty * string. * * @return Returns localized description of error or an empty string if no * error has occurred. */ QString errorString() const; /** * @brief Set maximum quota timeout * * Sets maximum interval for which the job should wait before trying to submit * a request that has previously failed due to exceeded quota. * * Default timeout is 1 seconds, then after every failed request the timeout * is increased exponentially until reaching @p maxTimeout. * * @param maxTimeout Maximum timeout (in seconds), or @p -1 for no timeout */ void setMaxTimeout(int maxTimeout); /** * @brief Maximum quota limit. * * @return Returns maximum timeout in seconds or -1 if there is no timeout set. * @see Job::setMaxTimeout */ int maxTimeout() const; /** * @brief Whether job is running * * A job is considered running from the moment it's started until * until Job::finished is emitted. Some methods should not be * called when a job is running. * * @return Returns whether this job is currently running. * @sa start() */ bool isRunning() const; /** * @brief Set account to be used to authenticate requests * * By default, no account is set and all request are sent without any * authentication. * * @param account Account to use */ void setAccount(const AccountPtr &account); /** * @brief Returns account used to authenticate requests * * For jobs that don't require authentication, this method returns a null * pointer. * * @return Am Account or a null pointer when no account was set. */ AccountPtr account() const; /** * @brief Restarts this job * * When a job finishes, it's possible to run it again, without having * to create a new job. * * The job will throw away all results retrieved in previous run and retrieve * everything again. * * @see Job::aboutToStart */ void restart(); Q_SIGNALS: /** * @brief Emitted when @p job has finished * * The signal is emitted every time, no matter whether the job is successful * or an error has occurred. * * Subclasses should never ever emit this signal directly. * Use Job::emitFinished instead. * * @param job The job that has finished * @sa emitFinished() */ void finished(KGAPI2::Job *job); /** * @brief Emitted when a job progress changes. * * Note that some jobs might not provide progress information, thus this * signal will never be emitted. * * @param job The job that the information relates to * @param processed Amount of already processed items * @param total Total amount of items to process */ void progress(KGAPI2::Job *job, int processed, int total); protected: /** * @brief Set job error to @p error * * @param error Error code to set * @see Job::error */ void setError(KGAPI2::Error error); /** * @brief Set job error description to @p errorString * * @param errorString Error description to set * @see Job::errorString */ void setErrorString(const QString &errorString); /** * @brief Emits Job::finished() signal * * Subclasses should always use this method instead of directly emitting * Job::finished(). */ virtual void emitFinished(); /** * @brief This method is invoked right before finished() is emitted * * Subclasses can reimplement this method to do a final cleanup before * the Job::finished() signal is emitted. * * @note Note that after Job::finished() the job is not running anymore and * therefore the job should not modify any data accessible by user. */ virtual void aboutToFinish(); /** * @brief Emit progress() signal * * Subclasses should always use this method instead of directly emitting * Job::progress(). * * @param processed Amount of already processed items * @param total Total amount of items to process */ virtual void emitProgress(int processed, int total); /** * @brief This method is invoked right before Job::start() is called. * * Subclasses should reset their internal state and call parent implementation. */ virtual void aboutToStart(); /** * @brief This method is invoked when job is started. * * Job is automatically started when application enters event loop. */ virtual void start() = 0; /** * @brief Dispatches @p request via @p accessManager * * Because different types of request require different HTTP method to be * used, subclasses must reimplement this method and use respective HTTP * method to send the @p request via @p accessManager. * * @param accessManager QNetworkAccessManager used to dispatch the request * @param request Request to dispatch * @param data Data to sent in the body of the request * @param contentType Content-Type of @p data */ virtual void dispatchRequest(QNetworkAccessManager *accessManager, const QNetworkRequest &request, const QByteArray &data, const QString &contentType) = 0; /** * @brief Called when a reply is received. * * Sublcasses must reimplement this method to handle reply content. * * @param reply A reply received from server * @param rawData Raw content of the reply. Don't use QNetworkReply::readAll, * because this method has already been called by Job and thus it would * return nothing. */ virtual void handleReply(const QNetworkReply *reply, const QByteArray &rawData) = 0; /** * @brief Enqueues @p request in dispatcher queue * * Subclasses should call this method to enqueue the @p request in main job * queue. The request is automatically dispatched, and reply is handled. + * Authorization headers and standars query parameters will be applied. * * @param request Request to enqueue * @param data Data to be send in body of the request * @param contentType Content type of @p data */ virtual void enqueueRequest(const QNetworkRequest &request, const QByteArray &data = QByteArray(), const QString &contentType = QString()); private: class Private; Private * const d; friend class Private; friend class AuthJob; }; } // namespace KGAPI2 #endif // LIBKGAPI2_JOB_H diff --git a/src/core/job_p.h b/src/core/job_p.h index b6f767b..c418938 100644 --- a/src/core/job_p.h +++ b/src/core/job_p.h @@ -1,93 +1,93 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #ifndef KGAPI_JOB_P_H #define KGAPI_JOB_P_H #include "job.h" #include #include #include #include class QFile; namespace KGAPI2 { struct Request { QNetworkRequest request; QByteArray rawData; QString contentType; }; class Q_DECL_HIDDEN FileLogger { public: ~FileLogger(); static FileLogger *self(); - void logRequest(const Request &request); + void logRequest(const QNetworkRequest &request, const QByteArray &rawData); void logReply(const QNetworkReply *reply, const QByteArray &rawData); private: FileLogger(); QScopedPointer mFile; static FileLogger *sInstance; }; class Q_DECL_HIDDEN Job::Private { public: Private(Job *parent); void init(); QString parseErrorMessage(const QByteArray &json); void _k_doStart(); void _k_doEmitFinished(); void _k_replyReceived(QNetworkReply *reply); void _k_dispatchTimeout(); bool isRunning; Error error; QString errorString; AccountPtr account; QNetworkAccessManager *accessManager; QQueue requestQueue; QTimer *dispatchTimer; int maxTimeout; Request currentRequest; private: Job * const q; }; } #endif // KGAPI_JOB_P_H diff --git a/src/drive/aboutfetchjob.cpp b/src/drive/aboutfetchjob.cpp index 3a37fd8..0048972 100644 --- a/src/drive/aboutfetchjob.cpp +++ b/src/drive/aboutfetchjob.cpp @@ -1,147 +1,146 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "aboutfetchjob.h" #include "about.h" #include "account.h" #include "../debug.h" #include "driveservice.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN AboutFetchJob::Private { public: Private(); bool includeSubscribed; qlonglong maxChangeIdCount; qlonglong startChangeId; }; AboutFetchJob::Private::Private(): includeSubscribed(true), maxChangeIdCount(0), startChangeId(0) { } AboutFetchJob::AboutFetchJob(const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { } AboutFetchJob::~AboutFetchJob() { delete d; } void AboutFetchJob::setIncludeSubscribed(bool includeSubscribed) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify includeSubscribed property when job is running"; return; } d->includeSubscribed = includeSubscribed; } bool AboutFetchJob::includeSubscribed() const { return d->includeSubscribed; } void AboutFetchJob::setMaxChangeIdCount(qlonglong maxChangeIdCount) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify maxChangeIdCount property when job is running"; return; } d->maxChangeIdCount = maxChangeIdCount; } qlonglong AboutFetchJob::maxChangeIdCount() const { return d->maxChangeIdCount; } void AboutFetchJob::setStartChangeId(qlonglong startChangeId) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify startChangeId property when job is running"; return; } d->startChangeId = startChangeId; } qlonglong AboutFetchJob::startChangeId() const { return d->startChangeId; } AboutPtr AboutFetchJob::aboutData() const { if (isRunning() || items().count() == 0) { return AboutPtr(); } return items().at(0).dynamicCast(); } void AboutFetchJob::start() { - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - request.setUrl(DriveService::fetchAboutUrl(d->includeSubscribed, d->maxChangeIdCount, d->startChangeId)); + QUrl url = DriveService::fetchAboutUrl(d->includeSubscribed, d->maxChangeIdCount, d->startChangeId); + QNetworkRequest request(url); enqueueRequest(request); } KGAPI2::ObjectsList AboutFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { AboutPtr about = About::fromJSON(rawData); items << about; } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); } emitFinished(); return items; } diff --git a/src/drive/appfetchjob.cpp b/src/drive/appfetchjob.cpp index e49c8ff..a3b8357 100644 --- a/src/drive/appfetchjob.cpp +++ b/src/drive/appfetchjob.cpp @@ -1,97 +1,97 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "appfetchjob.h" #include "account.h" #include "app.h" #include "driveservice.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN AppFetchJob::Private { public: QString appId; }; AppFetchJob::AppFetchJob(const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { } AppFetchJob::AppFetchJob(const QString &appId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { d->appId = appId; } AppFetchJob::~AppFetchJob() { delete d; } void AppFetchJob::start() { - QNetworkRequest request; + QUrl url; if (d->appId.isEmpty()) { - request.setUrl(DriveService::fetchAppsUrl()); + url = DriveService::fetchAppsUrl(); } else { - request.setUrl(DriveService::fetchAppUrl(d->appId)); + url = DriveService::fetchAppUrl(d->appId); } - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); enqueueRequest(request); } ObjectsList AppFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->appId.isEmpty()) { items << App::fromJSONFeed(rawData); } else { items << App::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); } emitFinished(); return items; } diff --git a/src/drive/changefetchjob.cpp b/src/drive/changefetchjob.cpp index 9862e21..8c2bf2a 100644 --- a/src/drive/changefetchjob.cpp +++ b/src/drive/changefetchjob.cpp @@ -1,237 +1,226 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "changefetchjob.h" #include "account.h" #include "change.h" #include "../debug.h" #include "driveservice.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN ChangeFetchJob::Private { public: Private(ChangeFetchJob *parent); - QNetworkRequest createRequest(const QUrl &url); QString changeId; bool includeDeleted; bool includeSubscribed; int maxResults; qlonglong startChangeId; bool includeItemsFromAllDrives; bool supportsAllDrives; private: ChangeFetchJob *q; }; ChangeFetchJob::Private::Private(ChangeFetchJob *parent): includeDeleted(true), includeSubscribed(true), maxResults(0), startChangeId(0), includeItemsFromAllDrives(true), supportsAllDrives(true), q(parent) { } -QNetworkRequest ChangeFetchJob::Private::createRequest(const QUrl &url) -{ - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - request.setUrl(url); - - return request; -} - - ChangeFetchJob::ChangeFetchJob(const QString &changeId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->changeId = changeId; } ChangeFetchJob::ChangeFetchJob(const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { } ChangeFetchJob::~ChangeFetchJob() { delete d; } void ChangeFetchJob::setIncludeDeleted(bool includeDeleted) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify includeDeleted property when job is running"; return; } d->includeDeleted = includeDeleted; } bool ChangeFetchJob::includeDeleted() const { return d->includeDeleted; } void ChangeFetchJob::setIncludeSubscribed(bool includeSubscribed) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify includeSubscribed property when job is running"; return; } d->includeSubscribed = includeSubscribed; } bool ChangeFetchJob::includeSubscribed() const { return d->includeSubscribed; } void ChangeFetchJob::setMaxResults(int maxResults) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify maxResults property when job is running"; return; } d->maxResults = maxResults; } int ChangeFetchJob::maxResults() const { return d->maxResults; } void ChangeFetchJob::setStartChangeId(qlonglong startChangeId) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify startChangeId property when job is running"; } d->startChangeId = startChangeId; } qlonglong ChangeFetchJob::startChangeId() const { return d->startChangeId; } bool ChangeFetchJob::includeItemsFromAllDrives() const { return d->includeItemsFromAllDrives; } void ChangeFetchJob::setIncludeItemsFromAllDrives(bool includeItemsFromAllDrives) { d->includeItemsFromAllDrives = includeItemsFromAllDrives; } bool ChangeFetchJob::supportsAllDrives() const { return d->supportsAllDrives; } void ChangeFetchJob::setSupportsAllDrives(bool supportsAllDrives) { d->supportsAllDrives = supportsAllDrives; } void ChangeFetchJob::start() { QUrl url; if (d->changeId.isEmpty()) { url = DriveService::fetchChangesUrl(); QUrlQuery query(url); query.addQueryItem(QStringLiteral("includeDeleted"), Utils::bool2Str(d->includeDeleted)); query.addQueryItem(QStringLiteral("includeSubscribed"), Utils::bool2Str(d->includeSubscribed)); if (d->maxResults > 0) { query.addQueryItem(QStringLiteral("maxResults"), QString::number(d->maxResults)); } if (d->startChangeId > 0) { query.addQueryItem(QStringLiteral("startChangeId"), QString::number(d->startChangeId)); } query.addQueryItem(QStringLiteral("includeItemsFromAllDrives"), d->includeItemsFromAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(query); } else { url = DriveService::fetchChangeUrl(d->changeId); } QUrlQuery query(url); query.addQueryItem(QStringLiteral("supportsAllDrives"), d->supportsAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(query); - const QNetworkRequest request = d->createRequest(url); + QNetworkRequest request(url); enqueueRequest(request); } ObjectsList ChangeFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { FeedData feedData; feedData.requestUrl = reply->url(); ObjectsList items; QString itemId; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->changeId.isEmpty()) { items << Change::fromJSONFeed(rawData, feedData); } else { items << Change::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { - const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); + QNetworkRequest request(feedData.nextPageUrl); enqueueRequest(request); } return items; } diff --git a/src/drive/childreferencecreatejob.cpp b/src/drive/childreferencecreatejob.cpp index 7dba704..b3cd3ea 100644 --- a/src/drive/childreferencecreatejob.cpp +++ b/src/drive/childreferencecreatejob.cpp @@ -1,165 +1,163 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "childreferencecreatejob.h" #include "account.h" #include "childreference.h" #include "driveservice.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN ChildReferenceCreateJob::Private { public: Private(ChildReferenceCreateJob *parent); void processNext(); QString folderId; ChildReferencesList references; bool supportsAllDrives; private: ChildReferenceCreateJob *q; }; ChildReferenceCreateJob::Private::Private(ChildReferenceCreateJob *parent): supportsAllDrives(true), q(parent) { } void ChildReferenceCreateJob::Private::processNext() { if (references.isEmpty()) { q->emitFinished(); return; } const ChildReferencePtr reference = references.takeFirst(); QUrl url = DriveService::createChildReference(folderId); QUrlQuery withDriveSupportQuery(url); withDriveSupportQuery.addQueryItem(QStringLiteral("supportsAllDrives"), supportsAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(withDriveSupportQuery); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = ChildReference::toJSON(reference); q->enqueueRequest(request, rawData, QStringLiteral("application/json")); } ChildReferenceCreateJob::ChildReferenceCreateJob(const QString &folderId, const QString &childId, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->folderId = folderId; d->references << ChildReferencePtr(new ChildReference(childId)); } ChildReferenceCreateJob::ChildReferenceCreateJob(const QString &folderId, const QStringList &childrenIds, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->folderId = folderId; for (const QString & childId : qAsConst(childrenIds)) { d->references << ChildReferencePtr(new ChildReference(childId)); } } ChildReferenceCreateJob::ChildReferenceCreateJob(const QString &folderId, const ChildReferencePtr &reference, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->folderId = folderId; d->references << reference; } ChildReferenceCreateJob::ChildReferenceCreateJob(const QString &folderId, const ChildReferencesList &references, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->folderId = folderId; d->references << references; } ChildReferenceCreateJob::~ChildReferenceCreateJob() { delete d; } bool ChildReferenceCreateJob::supportsAllDrives() const { return d->supportsAllDrives; } void ChildReferenceCreateJob::setSupportsAllDrives(bool supportsAllDrives) { d->supportsAllDrives = supportsAllDrives; } void ChildReferenceCreateJob::start() { d->processNext(); } ObjectsList ChildReferenceCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << ChildReference::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } // Enqueue next item or finish d->processNext(); return items; } diff --git a/src/drive/childreferencedeletejob.cpp b/src/drive/childreferencedeletejob.cpp index 5799445..1ed0685 100644 --- a/src/drive/childreferencedeletejob.cpp +++ b/src/drive/childreferencedeletejob.cpp @@ -1,107 +1,106 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "childreferencedeletejob.h" #include "account.h" #include "childreference.h" #include "driveservice.h" #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN ChildReferenceDeleteJob::Private { public: QString folderId; QStringList childrenIds; }; ChildReferenceDeleteJob::ChildReferenceDeleteJob(const QString &folderId, const QString &childId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->folderId = folderId; d->childrenIds << childId; } ChildReferenceDeleteJob::ChildReferenceDeleteJob(const QString &folderId, const QStringList &childrenIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->folderId = folderId; d->childrenIds << childrenIds; } ChildReferenceDeleteJob::ChildReferenceDeleteJob(const QString &folderId, const ChildReferencePtr &reference, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->folderId = folderId; d->childrenIds << reference->id(); } ChildReferenceDeleteJob::ChildReferenceDeleteJob(const QString &folderId, const ChildReferencesList &references, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->folderId = folderId; for (const ChildReferencePtr & reference : references) { d->childrenIds << reference->id(); } } ChildReferenceDeleteJob::~ChildReferenceDeleteJob() { delete d; } void ChildReferenceDeleteJob::start() { if (d->childrenIds.isEmpty()) { emitFinished(); return; } const QString childId = d->childrenIds.takeFirst(); const QUrl url = DriveService::deleteChildReference(d->folderId, childId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); enqueueRequest(request); } diff --git a/src/drive/childreferencefetchjob.cpp b/src/drive/childreferencefetchjob.cpp index 297f0f7..4a1528a 100644 --- a/src/drive/childreferencefetchjob.cpp +++ b/src/drive/childreferencefetchjob.cpp @@ -1,131 +1,121 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "childreferencefetchjob.h" #include "account.h" #include "childreference.h" #include "driveservice.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN ChildReferenceFetchJob::Private { public: Private(ChildReferenceFetchJob *parent); - QNetworkRequest createRequest(const QUrl &url); QString folderId; QString childId; private: ChildReferenceFetchJob *q; }; ChildReferenceFetchJob::Private::Private(ChildReferenceFetchJob *parent): q(parent) { } -QNetworkRequest ChildReferenceFetchJob::Private::createRequest(const QUrl &url) -{ - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - request.setUrl(url); - - return request; -} - ChildReferenceFetchJob::ChildReferenceFetchJob(const QString &folderId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->folderId = folderId; } ChildReferenceFetchJob::ChildReferenceFetchJob(const QString &folderId, const QString &childId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->folderId = folderId; d->childId = childId; } ChildReferenceFetchJob::~ChildReferenceFetchJob() { delete d; } void ChildReferenceFetchJob::start() { QUrl url; if (d->childId.isEmpty()) { url = DriveService::fetchChildReferences(d->folderId); } else { url = DriveService::fetchParentReferenceUrl(d->folderId, d->childId); } - const QNetworkRequest request = d->createRequest(url); + QNetworkRequest request(url); enqueueRequest(request); } ObjectsList ChildReferenceFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { ObjectsList items; FeedData feedData; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->childId.isEmpty()) { items << ChildReference::fromJSONFeed(rawData, feedData); } else { items << ChildReference::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { - const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); + QNetworkRequest request(feedData.nextPageUrl); enqueueRequest(request); } return items; } diff --git a/src/drive/fileabstractmodifyjob.cpp b/src/drive/fileabstractmodifyjob.cpp index 224c1fa..e966642 100644 --- a/src/drive/fileabstractmodifyjob.cpp +++ b/src/drive/fileabstractmodifyjob.cpp @@ -1,138 +1,136 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "fileabstractmodifyjob.h" #include "account.h" #include "driveservice.h" #include "file.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN FileAbstractModifyJob::Private { public: Private(FileAbstractModifyJob *parent); void processNext(); QStringList filesIds; private: FileAbstractModifyJob *q; }; FileAbstractModifyJob::Private::Private(FileAbstractModifyJob *parent): q(parent) { } void FileAbstractModifyJob::Private::processNext() { if (filesIds.isEmpty()) { q->emitFinished(); return; } const QString fileId = filesIds.takeFirst(); const QUrl url = q->url(fileId); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentLengthHeader, 0); - request.setUrl(url); q->enqueueRequest(request); } FileAbstractModifyJob::FileAbstractModifyJob(const QString &fileId, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->filesIds << fileId; } FileAbstractModifyJob::FileAbstractModifyJob(const QStringList &filesIds, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->filesIds << filesIds; } FileAbstractModifyJob::FileAbstractModifyJob(const FilePtr &file, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->filesIds << file->id(); } FileAbstractModifyJob::FileAbstractModifyJob(const FilesList &files, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { for (const FilePtr & file : qAsConst(files)) { d->filesIds << file->id(); } } FileAbstractModifyJob::~FileAbstractModifyJob() { delete d; } void FileAbstractModifyJob::start() { d->processNext(); } ObjectsList FileAbstractModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << File::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } d->processNext(); return items; } #include "moc_fileabstractmodifyjob.cpp" diff --git a/src/drive/fileabstractuploadjob.cpp b/src/drive/fileabstractuploadjob.cpp index a3c0c9c..b74497d 100644 --- a/src/drive/fileabstractuploadjob.cpp +++ b/src/drive/fileabstractuploadjob.cpp @@ -1,368 +1,366 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "fileabstractuploadjob.h" #include "account.h" #include "../debug.h" #include "driveservice.h" #include "file.h" #include "utils.h" #include #include #include #include #include #include #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN FileAbstractUploadJob::Private { public: Private(FileAbstractUploadJob *parent); void processNext(); QByteArray buildMultipart(const QString &filePath, const FilePtr &metaData, QString &boundary); QByteArray readFile(const QString &filePath, QString &contentType); void _k_uploadProgress(qint64 bytesSent, qint64 totalBytes); int originalFilesCount; QMap files; QMap uploadedFiles; bool supportsAllDrives; bool useContentAsIndexableText; File::SerializationOptions serializationOptions = File::NoOptions; private: FileAbstractUploadJob *const q; }; FileAbstractUploadJob::Private::Private(FileAbstractUploadJob *parent): originalFilesCount(0), supportsAllDrives(true), useContentAsIndexableText(false), q(parent) { } QByteArray FileAbstractUploadJob::Private::readFile(const QString &filePath, QString &contentType) { QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) { qCWarning(KGAPIDebug) << "Failed to access" << filePath; return QByteArray(); } const QMimeDatabase db; const QMimeType mime = db.mimeTypeForFileNameAndData(filePath, &file); contentType = mime.name(); file.reset(); QByteArray output = file.readAll(); file.close(); return output; } QByteArray FileAbstractUploadJob::Private::buildMultipart(const QString &filePath, const FilePtr &metaData, QString &boundary) { QString fileContentType; QByteArray fileContent; fileContent = readFile(filePath, fileContentType); if (fileContent.isEmpty()) { return QByteArray(); } // Wannabe implementation of RFC2387, i.e. multipart/related QByteArray body; QFileInfo finfo(filePath); const QByteArray md5 = QCryptographicHash::hash(finfo.fileName().toLatin1(), QCryptographicHash::Md5); boundary = QString::fromLatin1(md5.toHex()); body += "--" + boundary.toLatin1() + '\n'; body += "Content-Type: application/json; charset=UTF-8\n"; body += '\n'; body += File::toJSON(metaData); body += '\n'; body += '\n'; body += "--" + boundary.toLatin1() + '\n'; body += "Content-Type: " + fileContentType.toLatin1() + '\n'; body += '\n'; body += fileContent; body += '\n'; body += "--" + boundary.toLatin1() + "--"; return body; } void FileAbstractUploadJob::Private::processNext() { if (files.isEmpty()) { q->emitFinished(); return; } const QString filePath = files.cbegin().key(); if (!filePath.startsWith(QLatin1String("?=")) && !QFile::exists(filePath)) { qCWarning(KGAPIDebug) << filePath << "is not a valid file path"; processNext(); return; } const FilePtr metaData = files.take(filePath); QUrl url; if (filePath.startsWith(QLatin1String("?="))) { url = q->createUrl(QString(), metaData); } else { url = q->createUrl(filePath, metaData); } q->updateUrl(url); QUrlQuery query(url); query.addQueryItem(QStringLiteral("useContentAsIndexableText"), Utils::bool2Str(useContentAsIndexableText)); - QNetworkRequest request; QByteArray rawData; QString contentType; // just to be sure query.removeQueryItem(QStringLiteral("uploadType")); if (metaData.isNull()) { query.addQueryItem(QStringLiteral("uploadType"), QStringLiteral("media")); rawData = readFile(filePath, contentType); if (rawData.isEmpty()) { processNext(); return; } } else if (!filePath.startsWith(QLatin1String("?="))) { query.addQueryItem(QStringLiteral("uploadType"), QStringLiteral("multipart")); QString boundary; rawData = buildMultipart(filePath, metaData, boundary); contentType = QStringLiteral("multipart/related; boundary=%1").arg(boundary); if (rawData.isEmpty()) { processNext(); return; } } else { rawData = File::toJSON(metaData, q->serializationOptions()); contentType = QStringLiteral("application/json"); } query.addQueryItem(QStringLiteral("supportsAllDrives"), supportsAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(query); - request.setUrl(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentLengthHeader, rawData.length()); request.setHeader(QNetworkRequest::ContentTypeHeader, contentType); request.setAttribute(QNetworkRequest::User, filePath); q->enqueueRequest(request, rawData, contentType); } void FileAbstractUploadJob::Private::_k_uploadProgress(qint64 bytesSent, qint64 totalBytes) { // Each file consists of 100 units, so if we have two files, one already // uploaded and the other one uploaded from 50%, the values are (150, 200) int processedParts = (originalFilesCount - files.count()) * 100; int currentFileParts = 100.0 * ((qreal) bytesSent / (qreal) totalBytes); q->emitProgress(processedParts + currentFileParts, originalFilesCount * 100); } FileAbstractUploadJob::FileAbstractUploadJob(const FilePtr &metadata, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { d->files.insert(QStringLiteral("?=0"), metadata); d->originalFilesCount = 1; } FileAbstractUploadJob::FileAbstractUploadJob(const FilesList &metadata, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { int i = 0; for (const FilePtr &file : metadata) { d->files.insert(QStringLiteral("?=%1").arg(i), file); ++i; } d->originalFilesCount = d->files.count(); } FileAbstractUploadJob::FileAbstractUploadJob(const QString &filePath, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { d->files.insert(filePath, FilePtr()); d->originalFilesCount = 1; } FileAbstractUploadJob::FileAbstractUploadJob(const QString &filePath, const FilePtr &metaData, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { d->files.insert(filePath, metaData); d->originalFilesCount = 1; } FileAbstractUploadJob::FileAbstractUploadJob(const QStringList &filePaths, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { for (const QString & filePath : filePaths) { d->files.insert(filePath, FilePtr()); } d->originalFilesCount = d->files.count(); } FileAbstractUploadJob::FileAbstractUploadJob(const QMap< QString, FilePtr > &files, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { d->files = files; d->originalFilesCount = d->files.count(); } FileAbstractUploadJob::~FileAbstractUploadJob() { delete d; } void FileAbstractUploadJob::setUseContentAsIndexableText(bool useContentAsIndexableText) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify useContentAsIndexableText property when job is running"; return; } d->useContentAsIndexableText = useContentAsIndexableText; } bool FileAbstractUploadJob::useContentAsIndexableText() const { return d->useContentAsIndexableText; } void FileAbstractUploadJob::start() { d->processNext(); } QMap FileAbstractUploadJob::files() const { return d->uploadedFiles; } bool FileAbstractUploadJob::supportsAllDrives() const { return d->supportsAllDrives; } void FileAbstractUploadJob::setSupportsAllDrives(bool supportsAllDrives) { d->supportsAllDrives = supportsAllDrives; } void FileAbstractUploadJob::dispatchRequest(QNetworkAccessManager *accessManager, const QNetworkRequest &request, const QByteArray &data, const QString &contentType) { Q_UNUSED(contentType) QNetworkReply *reply = dispatch(accessManager, request, data); connect(reply, &QNetworkReply::uploadProgress, this, [this](qint64 bytesSent, qint64 totalBytes) {d->_k_uploadProgress(bytesSent, totalBytes); }); } void FileAbstractUploadJob::handleReply(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { const QNetworkRequest request = reply->request(); const QString filePath = request.attribute(QNetworkRequest::User).toString(); FilePtr file = File::fromJSON(rawData); d->uploadedFiles.insert(filePath, file); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return; } d->processNext(); } void FileAbstractUploadJob::setSerializationOptions(File::SerializationOptions options) { d->serializationOptions = options; } File::SerializationOptions FileAbstractUploadJob::serializationOptions() const { return d->serializationOptions; } #include "moc_fileabstractuploadjob.cpp" diff --git a/src/drive/filecopyjob.cpp b/src/drive/filecopyjob.cpp index d00802d..6ce0be6 100644 --- a/src/drive/filecopyjob.cpp +++ b/src/drive/filecopyjob.cpp @@ -1,162 +1,161 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "filecopyjob.h" #include "account.h" #include "driveservice.h" #include "file.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN FileCopyJob::Private { public: Private(FileCopyJob *parent); void processNext(); QMap files; QList copies; private: FileCopyJob *const q; }; FileCopyJob::Private::Private(FileCopyJob *parent): q(parent) { } void FileCopyJob::Private::processNext() { if (files.isEmpty()) { q->emitFinished(); return; } const QString fileId = files.cbegin().key(); const FilePtr file = files.take(fileId); QUrl url = DriveService::copyFileUrl(fileId); q->updateUrl(url); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); const QByteArray rawData = File::toJSON(file); q->enqueueRequest(request, rawData, QStringLiteral("application/json")); } FileCopyJob::FileCopyJob(const QString &sourceFileId, const FilePtr &destinationFile, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { d->files.insert(sourceFileId, destinationFile); } FileCopyJob::FileCopyJob(const FilePtr &sourceFile, const FilePtr &destinationFile, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { d->files.insert(sourceFile->id(), destinationFile); } FileCopyJob::FileCopyJob(const QMap< QString, FilePtr > &files, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { d->files = files; } FileCopyJob::FileCopyJob(const QMap< FilePtr, FilePtr > &files, const AccountPtr &account, QObject *parent): FileAbstractDataJob(account, parent), d(new Private(this)) { QMap::ConstIterator iter = files.constBegin(); QMap::ConstIterator iterEnd = files.constEnd(); for (; iter != iterEnd; ++iter) { d->files.insert(iter.key()->id(), iter.value()); } } FileCopyJob::~FileCopyJob() { delete d; } FilesList FileCopyJob::files() const { return d->copies; } void FileCopyJob::start() { d->processNext(); } void FileCopyJob::dispatchRequest(QNetworkAccessManager *accessManager, const QNetworkRequest &request, const QByteArray &data, const QString &contentType) { QNetworkRequest r = request; r.setHeader(QNetworkRequest::ContentTypeHeader, contentType); accessManager->post(r, data); } void FileCopyJob::handleReply(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { d->copies << File::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return; } // Enqueue next item or finish d->processNext(); } diff --git a/src/drive/filedeletejob.cpp b/src/drive/filedeletejob.cpp index 68a6cc2..971d4fd 100644 --- a/src/drive/filedeletejob.cpp +++ b/src/drive/filedeletejob.cpp @@ -1,98 +1,96 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "filedeletejob.h" #include "account.h" #include "driveservice.h" #include "file.h" #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN FileDeleteJob::Private { public: QStringList filesIDs; }; FileDeleteJob::FileDeleteJob(const QString &fileId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->filesIDs << fileId; } FileDeleteJob::FileDeleteJob(const QStringList &filesIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->filesIDs << filesIds; } FileDeleteJob::FileDeleteJob(const FilePtr &file, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->filesIDs << file->id(); } FileDeleteJob::FileDeleteJob(const FilesList &files, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { for (const FilePtr & file : qAsConst(files)) { d->filesIDs << file->id(); } } FileDeleteJob::~FileDeleteJob() { delete d; } void FileDeleteJob::start() { if (d->filesIDs.isEmpty()) { emitFinished(); return; } const QString fileId = d->filesIDs.takeFirst(); const QUrl url = DriveService::deleteFileUrl(fileId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - enqueueRequest(request); } diff --git a/src/drive/filefetchcontentjob.cpp b/src/drive/filefetchcontentjob.cpp index 6b38e6b..6f57653 100644 --- a/src/drive/filefetchcontentjob.cpp +++ b/src/drive/filefetchcontentjob.cpp @@ -1,124 +1,122 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "filefetchcontentjob.h" #include "account.h" #include "file.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN FileFetchContentJob::Private { public: Private(FileFetchContentJob *parent); void _k_downloadProgress(qint64 downloaded, qint64 total); QUrl url; QByteArray fileData; private: FileFetchContentJob * const q; }; FileFetchContentJob::Private::Private(FileFetchContentJob *parent): q(parent) { } void FileFetchContentJob::Private::_k_downloadProgress(qint64 downloaded, qint64 total) { q->emitProgress(downloaded, total); } FileFetchContentJob::FileFetchContentJob(const FilePtr &file, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->url = file->downloadUrl(); } FileFetchContentJob::FileFetchContentJob(const QUrl &url, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->url = url; } FileFetchContentJob::~FileFetchContentJob() { delete d; } QByteArray FileFetchContentJob::data() const { return d->fileData; } void FileFetchContentJob::start() { QNetworkRequest request(d->url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - enqueueRequest(request); } void FileFetchContentJob::dispatchRequest(QNetworkAccessManager *accessManager, const QNetworkRequest &request, const QByteArray &data, const QString &contentType) { Q_UNUSED(data) Q_UNUSED(contentType) QNetworkReply *reply = accessManager->get(request); connect(reply, &QNetworkReply::downloadProgress, this, [this](qint64 downloaded, qint64 total) { d->_k_downloadProgress(downloaded, total); }); } void FileFetchContentJob::handleReply(const QNetworkReply *reply, const QByteArray &rawData) { Q_UNUSED(reply) d->fileData = rawData; } ObjectsList FileFetchContentJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { Q_UNUSED(reply) Q_UNUSED(rawData) return ObjectsList(); } #include "moc_filefetchcontentjob.cpp" diff --git a/src/drive/filefetchjob.cpp b/src/drive/filefetchjob.cpp index 3142f44..ea11e2e 100644 --- a/src/drive/filefetchjob.cpp +++ b/src/drive/filefetchjob.cpp @@ -1,394 +1,386 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "filefetchjob.h" #include "filesearchquery.h" #include "account.h" #include "../debug.h" #include "driveservice.h" #include "file.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN FileFetchJob::Private { public: Private(FileFetchJob *parent); void processNext(); - QNetworkRequest createRequest(const QUrl &url); QStringList fieldsToStrings(qulonglong fields); FileSearchQuery searchQuery; QStringList filesIDs; bool isFeed; bool includeItemsFromAllDrives; bool supportsAllDrives; bool updateViewedDate; qulonglong fields; private: FileFetchJob *const q; }; FileFetchJob::Private::Private(FileFetchJob *parent): isFeed(false), includeItemsFromAllDrives(true), supportsAllDrives(true), updateViewedDate(false), fields(FileFetchJob::AllFields), q(parent) { } -QNetworkRequest FileFetchJob::Private::createRequest(const QUrl &url) -{ - QNetworkRequest request; - request.setUrl(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - - return request; -} QStringList FileFetchJob::Private::fieldsToStrings(qulonglong fields) { if (fields & AllFields) { return QStringList(); } QStringList fieldsStrings; // Always fetch kind fieldsStrings << QStringLiteral("kind"); // FIXME: Use QMetaEnum once it supports enums larger than int if (fields & Id) { fieldsStrings << QStringLiteral("id"); } if (fields & Title) { fieldsStrings << QStringLiteral("title"); } if (fields & MimeType) { fieldsStrings << QStringLiteral("mimeType"); } if (fields & Description) { fieldsStrings << QStringLiteral("description"); } if (fields & Labels) { fieldsStrings << QStringLiteral("labels"); } if (fields & CreatedDate) { fieldsStrings << QStringLiteral("createdDate"); } if (fields & ModifiedDate) { fieldsStrings << QStringLiteral("modifiedDate"); } if (fields & ModifiedByMeDate) { fieldsStrings << QStringLiteral("modifiedByMeDate"); } if (fields & DownloadUrl) { fieldsStrings << QStringLiteral("downloadUrl"); } if (fields & IndexableText) { fieldsStrings << QStringLiteral("indexableText"); } if (fields & UserPermission) { fieldsStrings << QStringLiteral("userPermission"); } if (fields & FileExtension) { fieldsStrings << QStringLiteral("fileExtension"); } if (fields & MD5Checksum) { fieldsStrings << QStringLiteral("md5Checksum"); } if (fields & FileSize) { fieldsStrings << QStringLiteral("fileSize"); } if (fields & AlternateLink) { fieldsStrings << QStringLiteral("alternateLink"); } if (fields & EmbedLink) { fieldsStrings << QStringLiteral("embedLink"); } if (fields & SharedWithMeDate) { fieldsStrings << QStringLiteral("sharedWithMeDate"); } if (fields & Parents) { fieldsStrings << QStringLiteral("parents"); } if (fields & ExportLinks) { fieldsStrings << QStringLiteral("exportLinks"); } if (fields & OriginalFilename) { fieldsStrings << QStringLiteral("originalFilename"); } if (fields & OwnerNames) { fieldsStrings << QStringLiteral("ownerNames"); } if (fields & LastModifiedByMeDate) { fieldsStrings << QStringLiteral("lastModifiedByMeDate"); } if (fields & Editable) { fieldsStrings << QStringLiteral("editable"); } if (fields & WritersCanShare) { fieldsStrings << QStringLiteral("writersCanShare"); } if (fields & ThumbnailLink) { fieldsStrings << QStringLiteral("thumbnailLink"); } if (fields & LastViewedByMeDate) { fieldsStrings << QStringLiteral("lastViewedByMeDate"); } if (fields & WebContentLink) { fieldsStrings << QStringLiteral("webContentLink"); } if (fields & ExplicitlyTrashed) { fieldsStrings << QStringLiteral("explicitlyTrashed"); } if (fields & ImageMediaMetadata) { fieldsStrings << QStringLiteral("imageMediaMetadata"); } if (fields & Thumbnail) { fieldsStrings << QStringLiteral("thumbnail"); } if (fields & WebViewLink) { fieldsStrings << QStringLiteral("webViewLink"); } if (fields & IconLink) { fieldsStrings << QStringLiteral("iconLink"); } if (fields & Shared) { fieldsStrings << QStringLiteral("shared"); } if (fields & Owners) { fieldsStrings << QStringLiteral("owners"); } if (fields & LastModifyingUser) { fieldsStrings << QStringLiteral("lastModifyingUser"); } if (fields & AppDataContents) { fieldsStrings << QStringLiteral("appDataContents"); } if (fields & OpenWithLinks) { fieldsStrings << QStringLiteral("openWithLinks"); } if (fields & DefaultOpenWithLink) { fieldsStrings << QStringLiteral("defaultOpenWithLink"); } if (fields & HeadRevisionId) { fieldsStrings << QStringLiteral("headRevisionId"); } if (fields & Copyable) { fieldsStrings << QStringLiteral("copyable"); } if (fields & Properties) { fieldsStrings << QStringLiteral("properties"); } if (fields & MarkedViewedByMeDate) { fieldsStrings << QStringLiteral("markedViewedByMeDate"); } if (fields & Version) { fieldsStrings << QStringLiteral("version"); } if (fields & SharingUser) { fieldsStrings << QStringLiteral("sharingUser"); } if (fields & Permissions) { fieldsStrings << QStringLiteral("permissions"); } return fieldsStrings; } void FileFetchJob::Private::processNext() { QUrl url; if (isFeed) { url = DriveService::fetchFilesUrl(); QUrlQuery query(url); if (!searchQuery.isEmpty()) { query.addQueryItem(QStringLiteral("q"), searchQuery.serialize()); } if (fields != FileFetchJob::AllFields) { const QStringList fieldsStrings = fieldsToStrings(fields); query.addQueryItem(QStringLiteral("fields"), QStringLiteral("etag,kind,nextLink,nextPageToken,selfLink,items(%1)").arg(fieldsStrings.join(QStringLiteral(",")))); } query.addQueryItem(QStringLiteral("includeItemsFromAllDrives"), includeItemsFromAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(query); } else { if (filesIDs.isEmpty()) { q->emitFinished(); return; } const QString fileId = filesIDs.takeFirst(); url = DriveService::fetchFileUrl(fileId); if (fields != FileFetchJob::AllFields) { const QStringList fieldsStrings = fieldsToStrings(fields); QUrlQuery query(url); query.addQueryItem(QStringLiteral("fields"), fieldsStrings.join(QStringLiteral(","))); url.setQuery(query); } } QUrlQuery withDriveSupportQuery(url); withDriveSupportQuery.addQueryItem(QStringLiteral("supportsAllDrives"), supportsAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(withDriveSupportQuery); - q->enqueueRequest(createRequest(url)); + QNetworkRequest request(url); + q->enqueueRequest(request); } FileFetchJob::FileFetchJob(const QString &fileId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->filesIDs << fileId; } FileFetchJob::FileFetchJob(const QStringList &filesIds, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->filesIDs << filesIds; } FileFetchJob::FileFetchJob(const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->isFeed = true; } FileFetchJob::FileFetchJob(const FileSearchQuery &query, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->isFeed = true; d->searchQuery = query; } FileFetchJob::~FileFetchJob() { delete d; } bool FileFetchJob::updateViewedDate() const { return d->updateViewedDate; } void FileFetchJob::setUpdateViewedDate(bool updateViewedDate) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify updateViewedDate property when job is running."; return; } d->updateViewedDate = updateViewedDate; } void FileFetchJob::start() { d->processNext(); } void FileFetchJob::setFields(qulonglong fields) { d->fields = fields; } qulonglong FileFetchJob::fields() const { return d->fields; } bool FileFetchJob::includeItemsFromAllDrives() const { return d->includeItemsFromAllDrives; } void FileFetchJob::setIncludeItemsFromAllDrives(bool includeItemsFromAllDrives) { d->includeItemsFromAllDrives = includeItemsFromAllDrives; } bool FileFetchJob::supportsAllDrives() const { return d->supportsAllDrives; } void FileFetchJob::setSupportsAllDrives(bool supportsAllDrives) { d->supportsAllDrives = supportsAllDrives; } ObjectsList FileFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->isFeed) { FeedData feedData; items << File::fromJSONFeed(rawData, feedData); if (feedData.nextPageUrl.isValid()) { - const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); + QNetworkRequest request(feedData.nextPageUrl); enqueueRequest(request); } } else { items << File::fromJSON(rawData); d->processNext(); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } return items; } diff --git a/src/drive/parentreferencecreatejob.cpp b/src/drive/parentreferencecreatejob.cpp index 0341fe4..425b01b 100644 --- a/src/drive/parentreferencecreatejob.cpp +++ b/src/drive/parentreferencecreatejob.cpp @@ -1,165 +1,163 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "parentreferencecreatejob.h" #include "account.h" #include "driveservice.h" #include "parentreference.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN ParentReferenceCreateJob::Private { public: Private(ParentReferenceCreateJob *parent); void processNext(); bool supportsAllDrives; QString fileId; ParentReferencesList references; private: ParentReferenceCreateJob *q; }; ParentReferenceCreateJob::Private::Private(ParentReferenceCreateJob *parent): supportsAllDrives(true), q(parent) { } void ParentReferenceCreateJob::Private::processNext() { if (references.isEmpty()) { q->emitFinished(); return; } const ParentReferencePtr reference = references.takeFirst(); QUrl url = DriveService::createParentReferenceUrl(fileId); QUrlQuery withDriveSupportQuery(url); withDriveSupportQuery.addQueryItem(QStringLiteral("supportsAllDrives"), supportsAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(withDriveSupportQuery); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = ParentReference::toJSON(reference); q->enqueueRequest(request, rawData, QStringLiteral("application/json")); } ParentReferenceCreateJob::ParentReferenceCreateJob(const QString &fileId, const QString &parentId, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->fileId = fileId; d->references << ParentReferencePtr(new ParentReference(parentId)); } ParentReferenceCreateJob::ParentReferenceCreateJob(const QString &fileId, const QStringList &parentsIds, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->fileId = fileId; for (const QString & parentId : qAsConst(parentsIds)) { d->references << ParentReferencePtr(new ParentReference(parentId)); } } ParentReferenceCreateJob::ParentReferenceCreateJob(const QString &fileId, const ParentReferencePtr &reference, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->fileId = fileId; d->references << reference; } ParentReferenceCreateJob::ParentReferenceCreateJob(const QString &fileId, const ParentReferencesList &references, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->fileId = fileId; d->references << references; } ParentReferenceCreateJob::~ParentReferenceCreateJob() { delete d; } bool ParentReferenceCreateJob::supportsAllDrives() const { return d->supportsAllDrives; } void ParentReferenceCreateJob::setSupportsAllDrives(bool supportsAllDrives) { d->supportsAllDrives = supportsAllDrives; } void ParentReferenceCreateJob::start() { d->processNext(); } ObjectsList ParentReferenceCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << ParentReference::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } // Enqueue next item or finish d->processNext(); return items; } diff --git a/src/drive/parentreferencedeletejob.cpp b/src/drive/parentreferencedeletejob.cpp index 36b6714..679d064 100644 --- a/src/drive/parentreferencedeletejob.cpp +++ b/src/drive/parentreferencedeletejob.cpp @@ -1,109 +1,108 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "parentreferencedeletejob.h" #include "account.h" #include "parentreference.h" #include "driveservice.h" #include "utils.h" #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN ParentReferenceDeleteJob::Private { public: QString fileId; QStringList referencesIds; }; ParentReferenceDeleteJob::ParentReferenceDeleteJob(const QString &fileId, const QString &referenceId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->fileId = fileId; d->referencesIds << referenceId; } ParentReferenceDeleteJob::ParentReferenceDeleteJob(const QString &fileId, const QStringList &referencesIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->fileId = fileId; d->referencesIds << referencesIds; } ParentReferenceDeleteJob::ParentReferenceDeleteJob(const QString &fileId, const ParentReferencePtr &reference, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->fileId = fileId; d->referencesIds << reference->id(); } ParentReferenceDeleteJob::ParentReferenceDeleteJob(const QString &fileId, const ParentReferencesList &references, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->fileId = fileId; for (const ParentReferencePtr & reference : references) { d->referencesIds << reference->id(); } } ParentReferenceDeleteJob::~ParentReferenceDeleteJob() { delete d; } void ParentReferenceDeleteJob::start() { if (d->referencesIds.isEmpty()) { emitFinished(); return; } const QString referenceId = d->referencesIds.takeFirst(); const QUrl url = DriveService::deleteParentReferenceUrl(d->fileId, referenceId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); enqueueRequest(request); } diff --git a/src/drive/parentreferencefetchjob.cpp b/src/drive/parentreferencefetchjob.cpp index fa3ced5..a927714 100644 --- a/src/drive/parentreferencefetchjob.cpp +++ b/src/drive/parentreferencefetchjob.cpp @@ -1,103 +1,103 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "parentreferencefetchjob.h" #include "account.h" #include "driveservice.h" #include "parentreference.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN ParentReferenceFetchJob::Private { public: QString fileId; QString referenceId; }; ParentReferenceFetchJob::ParentReferenceFetchJob(const QString &fileId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { d->fileId = fileId; } ParentReferenceFetchJob::ParentReferenceFetchJob(const QString &fileId, const QString &referenceId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { d->fileId = fileId; d->referenceId = referenceId; } ParentReferenceFetchJob::~ParentReferenceFetchJob() { delete d; } void ParentReferenceFetchJob::start() { - QNetworkRequest request; + QUrl url; if (d->referenceId.isEmpty()) { - request.setUrl(DriveService::fetchParentReferencesUrl(d->fileId)); + url = DriveService::fetchParentReferencesUrl(d->fileId); } else { - request.setUrl(DriveService::fetchParentReferenceUrl(d->fileId, d->referenceId)); + url = DriveService::fetchParentReferenceUrl(d->fileId, d->referenceId); } - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); enqueueRequest(request); } ObjectsList ParentReferenceFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->referenceId.isEmpty()) { items << ParentReference::fromJSONFeed(rawData); } else { items << ParentReference::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); } emitFinished(); return items; } diff --git a/src/drive/permissioncreatejob.cpp b/src/drive/permissioncreatejob.cpp index ac29369..d63b8f7 100644 --- a/src/drive/permissioncreatejob.cpp +++ b/src/drive/permissioncreatejob.cpp @@ -1,142 +1,140 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "permissioncreatejob.h" #include "account.h" #include "driveservice.h" #include "permission.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN PermissionCreateJob::Private { public: Private(PermissionCreateJob *parent); void processNext(); PermissionsList permissions; QString fileId; bool supportsAllDrives; private: PermissionCreateJob *const q; }; PermissionCreateJob::Private::Private(PermissionCreateJob *parent): supportsAllDrives(true), q(parent) { } void PermissionCreateJob::Private::processNext() { if (permissions.isEmpty()) { q->emitFinished(); return; } const PermissionPtr permission = permissions.takeFirst(); QUrl url = DriveService::createPermissionUrl(fileId); QUrlQuery withDriveSupportQuery(url); withDriveSupportQuery.addQueryItem(QStringLiteral("supportsAllDrives"), supportsAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(withDriveSupportQuery); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = Permission::toJSON(permission); q->enqueueRequest(request, rawData, QStringLiteral("application/json")); } PermissionCreateJob::PermissionCreateJob(const QString &fileId, const PermissionPtr &permission, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->fileId = fileId; d->permissions << permission; } PermissionCreateJob::PermissionCreateJob(const QString &fileId, const PermissionsList &permissions, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->fileId = fileId; d->permissions = permissions; } PermissionCreateJob::~PermissionCreateJob() { delete d; } bool PermissionCreateJob::supportsAllDrives() const { return d->supportsAllDrives; } void PermissionCreateJob::setSupportsAllDrives(bool supportsAllDrives) { d->supportsAllDrives = supportsAllDrives; } void PermissionCreateJob::start() { d->processNext(); } ObjectsList PermissionCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << Permission::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } // Enqueue next item or finish d->processNext(); return items; } diff --git a/src/drive/permissiondeletejob.cpp b/src/drive/permissiondeletejob.cpp index c0e43aa..34baeca 100644 --- a/src/drive/permissiondeletejob.cpp +++ b/src/drive/permissiondeletejob.cpp @@ -1,126 +1,125 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "permissiondeletejob.h" #include "permission.h" #include "account.h" #include "driveservice.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN PermissionDeleteJob::Private { public: QString fileId; QStringList permissionsIds; bool supportsAllDrives; }; PermissionDeleteJob::PermissionDeleteJob(const QString &fileId, const PermissionPtr &permission, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->supportsAllDrives = true; d->fileId = fileId; d->permissionsIds << permission->id(); } PermissionDeleteJob::PermissionDeleteJob(const QString &fileId, const QString &permissionId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->supportsAllDrives = true; d->fileId = fileId; d->permissionsIds << permissionId; } PermissionDeleteJob::PermissionDeleteJob(const QString &fileId, const PermissionsList &permissions, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->supportsAllDrives = true; d->fileId = fileId; for (const PermissionPtr & permission : qAsConst(permissions)) { d->permissionsIds << permission->id(); } } PermissionDeleteJob::PermissionDeleteJob(const QString &fileId, const QStringList &permissionsIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->supportsAllDrives = true; d->fileId = fileId; d->permissionsIds << permissionsIds; } PermissionDeleteJob::~PermissionDeleteJob() { delete d; } bool PermissionDeleteJob::supportsAllDrives() const { return d->supportsAllDrives; } void PermissionDeleteJob::setSupportsAllDrives(bool supportsAllDrives) { d->supportsAllDrives = supportsAllDrives; } void PermissionDeleteJob::start() { if (d->permissionsIds.isEmpty()) { emitFinished(); return; } const QString permissionId = d->permissionsIds.takeFirst(); QUrl url = DriveService::deletePermissionUrl(d->fileId, permissionId); QUrlQuery withDriveSupportQuery(url); withDriveSupportQuery.addQueryItem(QStringLiteral("supportsAllDrives"), d->supportsAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(withDriveSupportQuery); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); enqueueRequest(request); } diff --git a/src/drive/permissionfetchjob.cpp b/src/drive/permissionfetchjob.cpp index b45987b..4176153 100644 --- a/src/drive/permissionfetchjob.cpp +++ b/src/drive/permissionfetchjob.cpp @@ -1,147 +1,144 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "permissionfetchjob.h" #include "driveservice.h" #include "account.h" #include "file.h" #include "permission.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN PermissionFetchJob::Private { public: QString fileId; QString permissionId; bool supportsAllDrives; }; PermissionFetchJob::PermissionFetchJob(const QString &fileId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { d->supportsAllDrives = true; d->fileId = fileId; } PermissionFetchJob::PermissionFetchJob(const FilePtr &file, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { d->supportsAllDrives = true; d->fileId = file->id(); } PermissionFetchJob::PermissionFetchJob(const QString &fileId, const QString &permissionId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { d->supportsAllDrives = true; d->fileId = fileId; d->permissionId = permissionId; } PermissionFetchJob::PermissionFetchJob(const FilePtr &file, const QString &permissionId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { d->supportsAllDrives = true; d->fileId = file->id(); d->permissionId = permissionId; } PermissionFetchJob::~PermissionFetchJob() { delete d; } bool PermissionFetchJob::supportsAllDrives() const { return d->supportsAllDrives; } void PermissionFetchJob::setSupportsAllDrives(bool supportsAllDrives) { d->supportsAllDrives = supportsAllDrives; } void PermissionFetchJob::start() { QUrl url; if (d->permissionId.isEmpty()) { url = DriveService::fetchPermissionsUrl(d->fileId); } else { url = DriveService::fetchPermissionUrl(d->fileId, d->permissionId); } QUrlQuery withDriveSupportQuery(url); withDriveSupportQuery.addQueryItem(QStringLiteral("supportsAllDrives"), d->supportsAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(withDriveSupportQuery); - QNetworkRequest request; - request.setUrl(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - + QNetworkRequest request(url); enqueueRequest(request); } ObjectsList PermissionFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->permissionId.isEmpty()) { items << Permission::fromJSONFeed(rawData); } else { items << Permission::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); } emitFinished(); return items; } diff --git a/src/drive/permissionmodifyjob.cpp b/src/drive/permissionmodifyjob.cpp index fbb74bd..0c84e8d 100644 --- a/src/drive/permissionmodifyjob.cpp +++ b/src/drive/permissionmodifyjob.cpp @@ -1,141 +1,140 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "permissionmodifyjob.h" #include "account.h" #include "driveservice.h" #include "permission.h" #include "utils.h" #include #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN PermissionModifyJob::Private { public: Private(PermissionModifyJob *parent); void processNext(); QString fileId; PermissionsList permissions; bool supportsAllDrives; private: PermissionModifyJob *q; }; PermissionModifyJob::Private::Private(PermissionModifyJob *parent): supportsAllDrives(true), q(parent) { } void PermissionModifyJob::Private::processNext() { if (permissions.isEmpty()) { q->emitFinished(); return; } const PermissionPtr permission = permissions.takeFirst(); QUrl url = DriveService::modifyPermissionUrl(fileId, permission->id()); QUrlQuery withDriveSupportQuery(url); withDriveSupportQuery.addQueryItem(QStringLiteral("supportsAllDrives"), supportsAllDrives ? QStringLiteral("true") : QStringLiteral("false")); url.setQuery(withDriveSupportQuery); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); const QByteArray rawData = Permission::toJSON(permission); q->enqueueRequest(request, rawData, QStringLiteral("application/json")); } PermissionModifyJob::PermissionModifyJob(const QString &fileId, const PermissionPtr &permission, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->fileId = fileId; d->permissions << permission; } PermissionModifyJob::PermissionModifyJob(const QString &fileId, const PermissionsList &permissions, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->fileId = fileId; d->permissions << permissions; } PermissionModifyJob::~PermissionModifyJob() { delete d; } bool PermissionModifyJob::supportsAllDrives() const { return d->supportsAllDrives; } void PermissionModifyJob::setSupportsAllDrives(bool supportsAllDrives) { d->supportsAllDrives = supportsAllDrives; } void PermissionModifyJob::start() { d->processNext(); } ObjectsList PermissionModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << Permission::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } // Enqueue next item or finish d->processNext(); return items; } diff --git a/src/drive/revisiondeletejob.cpp b/src/drive/revisiondeletejob.cpp index 0a75795..a63dfd8 100644 --- a/src/drive/revisiondeletejob.cpp +++ b/src/drive/revisiondeletejob.cpp @@ -1,107 +1,105 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "revisiondeletejob.h" #include "account.h" #include "driveservice.h" #include "revision.h" #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN RevisionDeleteJob::Private { public: QString fileId; QStringList revisionsIds; }; RevisionDeleteJob::RevisionDeleteJob(const QString &fileId, const QString &revisionId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->fileId = fileId; d->revisionsIds << revisionId; } RevisionDeleteJob::RevisionDeleteJob(const QString &fileId, const QStringList &revisionsIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->fileId = fileId; d->revisionsIds << revisionsIds; } RevisionDeleteJob::RevisionDeleteJob(const QString &fileId, const RevisionPtr &revision, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->fileId = fileId; d->revisionsIds << revision->id(); } RevisionDeleteJob::RevisionDeleteJob(const QString &fileId, const RevisionsList &revisions, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->fileId = fileId; for (const RevisionPtr &revision : qAsConst(revisions)) { d->revisionsIds << revision->id(); } } RevisionDeleteJob::~RevisionDeleteJob() { delete d; } void RevisionDeleteJob::start() { if (d->revisionsIds.isEmpty()) { emitFinished(); return; } const QString revisionId = d->revisionsIds.takeFirst(); const QUrl url = DriveService::deleteRevisionUrl(d->fileId, revisionId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - enqueueRequest(request); } diff --git a/src/drive/revisionfetchjob.cpp b/src/drive/revisionfetchjob.cpp index 77aa25d..5426141 100644 --- a/src/drive/revisionfetchjob.cpp +++ b/src/drive/revisionfetchjob.cpp @@ -1,102 +1,102 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "revisionfetchjob.h" #include "account.h" #include "driveservice.h" #include "revision.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN RevisionFetchJob::Private { public: QString fileId; QString revisionId; }; RevisionFetchJob::RevisionFetchJob(const QString &fileId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { d->fileId = fileId; } RevisionFetchJob::RevisionFetchJob(const QString &fileId, const QString &revisionId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private) { d->fileId = fileId; d->revisionId = revisionId; } RevisionFetchJob::~RevisionFetchJob() { delete d; } void RevisionFetchJob::start() { - QNetworkRequest request; + QUrl url; if (d->revisionId.isEmpty()) { - request.setUrl(DriveService::fetchRevisionsUrl(d->fileId)); + url = DriveService::fetchRevisionsUrl(d->fileId); } else { - request.setUrl(DriveService::fetchRevisionUrl(d->fileId, d->revisionId)); + url = DriveService::fetchRevisionUrl(d->fileId, d->revisionId); } - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); enqueueRequest(request); } ObjectsList RevisionFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { ObjectsList items; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->revisionId.isEmpty()) { items << Revision::fromJSONFeed(rawData); } else { items << Revision::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); } emitFinished(); return items; } diff --git a/src/drive/revisionmodifyjob.cpp b/src/drive/revisionmodifyjob.cpp index fa9bd7b..66a3fd4 100644 --- a/src/drive/revisionmodifyjob.cpp +++ b/src/drive/revisionmodifyjob.cpp @@ -1,123 +1,122 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "revisionmodifyjob.h" #include "account.h" #include "driveservice.h" #include "revision.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN RevisionModifyJob::Private { public: Private(RevisionModifyJob *parent); void processNext(); QString fileId; RevisionsList revisions; private: RevisionModifyJob *q; }; RevisionModifyJob::Private::Private(RevisionModifyJob *parent): q(parent) { } void RevisionModifyJob::Private::processNext() { if (revisions.isEmpty()) { q->emitFinished(); return; } const RevisionPtr revision = revisions.takeFirst(); const QUrl url = DriveService::modifyRevisionUrl(fileId, revision->id()); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); const QByteArray rawData = Revision::toJSON(revision); q->enqueueRequest(request, rawData, QStringLiteral("application/json")); } RevisionModifyJob::RevisionModifyJob(const QString &fileId, const RevisionPtr &revision, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->fileId = fileId; d->revisions << revision; } RevisionModifyJob::RevisionModifyJob(const QString &fileId, const RevisionsList &revisions, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->fileId = fileId; d->revisions << revisions; } RevisionModifyJob::~RevisionModifyJob() { delete d; } void RevisionModifyJob::start() { d->processNext(); } ObjectsList RevisionModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << Revision::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } // Enqueue next item or finish d->processNext(); return items; } diff --git a/src/drive/teamdrivecreatejob.cpp b/src/drive/teamdrivecreatejob.cpp index 120a68d..dec9aab 100644 --- a/src/drive/teamdrivecreatejob.cpp +++ b/src/drive/teamdrivecreatejob.cpp @@ -1,137 +1,136 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2019 David Barchiesi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "teamdrivecreatejob.h" #include "account.h" #include "driveservice.h" #include "teamdrive.h" #include "utils.h" #include #include #include namespace { static const QString RequestIdParam = QStringLiteral("requestId"); } using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN TeamdriveCreateJob::Private { public: Private(TeamdriveCreateJob *parent); void processNext(); TeamdrivesList teamdrives; QString requestId; private: TeamdriveCreateJob *const q; }; TeamdriveCreateJob::Private::Private(TeamdriveCreateJob *parent): q(parent) { } void TeamdriveCreateJob::Private::processNext() { if (teamdrives.isEmpty()) { q->emitFinished(); return; } const TeamdrivePtr teamdrive = teamdrives.takeFirst(); QUrl url = DriveService::fetchTeamdrivesUrl(); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); QUrlQuery query(url); if (!requestId.isEmpty()) { query.addQueryItem(RequestIdParam, requestId); } url.setQuery(query); - request.setUrl(url); + + QNetworkRequest request(url); const QByteArray rawData = Teamdrive::toJSON(teamdrive); q->enqueueRequest(request, rawData, QStringLiteral("application/json")); } TeamdriveCreateJob::TeamdriveCreateJob(const QString &requestId, const TeamdrivePtr &teamdrive, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->requestId = requestId; d->teamdrives << teamdrive; } TeamdriveCreateJob::TeamdriveCreateJob(const QString &requestId, const TeamdrivesList &teamdrives, const AccountPtr &account, QObject *parent): CreateJob(account, parent), d(new Private(this)) { d->requestId = requestId; d->teamdrives = teamdrives; } TeamdriveCreateJob::~TeamdriveCreateJob() = default; QString TeamdriveCreateJob::requestId() const { return d->requestId; } void TeamdriveCreateJob::start() { d->processNext(); } ObjectsList TeamdriveCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << Teamdrive::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } // Enqueue next item or finish d->processNext(); return items; } diff --git a/src/drive/teamdrivedeletejob.cpp b/src/drive/teamdrivedeletejob.cpp index fc8cd59..a193e1e 100644 --- a/src/drive/teamdrivedeletejob.cpp +++ b/src/drive/teamdrivedeletejob.cpp @@ -1,91 +1,90 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2019 David Barchiesi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "teamdrivedeletejob.h" #include "teamdrive.h" #include "account.h" #include "driveservice.h" #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN TeamdriveDeleteJob::Private { public: QStringList teamdrivesIds; }; TeamdriveDeleteJob::TeamdriveDeleteJob(const QString &teamdriveId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->teamdrivesIds << teamdriveId; } TeamdriveDeleteJob::TeamdriveDeleteJob(const QStringList &teamdrivesIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->teamdrivesIds << teamdrivesIds; } TeamdriveDeleteJob::TeamdriveDeleteJob(const TeamdrivePtr &teamdrive, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->teamdrivesIds << teamdrive->id(); } TeamdriveDeleteJob::TeamdriveDeleteJob(const TeamdrivesList &teamdrives, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { for (const TeamdrivePtr & teamdrive : qAsConst(teamdrives)) { d->teamdrivesIds << teamdrive->id(); } } TeamdriveDeleteJob::~TeamdriveDeleteJob() = default; void TeamdriveDeleteJob::start() { if (d->teamdrivesIds.isEmpty()) { emitFinished(); return; } const QString teamdriveId = d->teamdrivesIds.takeFirst(); const QUrl url = DriveService::fetchTeamdriveUrl(teamdriveId); - QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); enqueueRequest(request); } diff --git a/src/drive/teamdrivefetchjob.cpp b/src/drive/teamdrivefetchjob.cpp index ea59b67..38c9748 100644 --- a/src/drive/teamdrivefetchjob.cpp +++ b/src/drive/teamdrivefetchjob.cpp @@ -1,192 +1,181 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2019 David Barchiesi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "teamdrivefetchjob.h" #include "account.h" #include "teamdrive.h" #include "../debug.h" #include "driveservice.h" #include "utils.h" #include #include #include namespace { static const QString MaxResultsAttr = QStringLiteral("maxResults"); static const QString UseDomainAdminAccessAttr = QStringLiteral("useDomainAdminAccess"); static const QString True = QStringLiteral("true"); static const QString False = QStringLiteral("false"); } using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN TeamdriveFetchJob::Private { public: Private(TeamdriveFetchJob *parent); - QNetworkRequest createRequest(const QUrl &url); TeamdriveSearchQuery searchQuery; QString teamdriveId; int maxResults = 0; bool useDomainAdminAccess = false; private: TeamdriveFetchJob *const q; }; TeamdriveFetchJob::Private::Private(TeamdriveFetchJob *parent): q(parent) { } -QNetworkRequest TeamdriveFetchJob::Private::createRequest(const QUrl &url) -{ - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - request.setUrl(url); - - return request; -} - - TeamdriveFetchJob::TeamdriveFetchJob(const QString &teamdriveId, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->teamdriveId = teamdriveId; } TeamdriveFetchJob::TeamdriveFetchJob(const TeamdriveSearchQuery &query, const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { d->useDomainAdminAccess = true; d->searchQuery = query; } TeamdriveFetchJob::TeamdriveFetchJob(const AccountPtr &account, QObject *parent): FetchJob(account, parent), d(new Private(this)) { } TeamdriveFetchJob::~TeamdriveFetchJob() = default; void TeamdriveFetchJob::setMaxResults(int maxResults) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify maxResults property when job is running"; return; } d->maxResults = maxResults; } int TeamdriveFetchJob::maxResults() const { return d->maxResults; } void TeamdriveFetchJob::setUseDomainAdminAccess(bool useDomainAdminAccess) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify useDomainAdminAccess property when job is running"; return; } d->useDomainAdminAccess = useDomainAdminAccess; } bool TeamdriveFetchJob::useDomainAdminAccess() const { return d->useDomainAdminAccess; } void TeamdriveFetchJob::start() { QUrl url; if (d->teamdriveId.isEmpty()) { url = DriveService::fetchTeamdrivesUrl(); applyRequestParameters(url); } else { url = DriveService::fetchTeamdriveUrl(d->teamdriveId); } - const QNetworkRequest request = d->createRequest(url); + QNetworkRequest request(url); enqueueRequest(request); } ObjectsList TeamdriveFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { FeedData feedData; feedData.requestUrl = reply->url(); ObjectsList items; QString itemId; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->teamdriveId.isEmpty()) { items << Teamdrive::fromJSONFeed(rawData, feedData); } else { items << Teamdrive::fromJSON(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { // Reapply query options applyRequestParameters(feedData.nextPageUrl); - const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); + QNetworkRequest request(feedData.nextPageUrl); enqueueRequest(request); } return items; } void TeamdriveFetchJob::applyRequestParameters(QUrl &url) { QUrlQuery query(url); if (d->maxResults != 0) { query.addQueryItem(MaxResultsAttr, QString::number(d->maxResults)); } if (d->useDomainAdminAccess != false) { query.addQueryItem(UseDomainAdminAccessAttr, d->useDomainAdminAccess ? True : False); } if (!d->searchQuery.isEmpty()) { query.addQueryItem(QStringLiteral("q"), d->searchQuery.serialize()); } url.setQuery(query); } diff --git a/src/drive/teamdrivemodifyjob.cpp b/src/drive/teamdrivemodifyjob.cpp index f99f601..03dd323 100644 --- a/src/drive/teamdrivemodifyjob.cpp +++ b/src/drive/teamdrivemodifyjob.cpp @@ -1,117 +1,116 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2019 David Barchiesi * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "teamdrivemodifyjob.h" #include "account.h" #include "driveservice.h" #include "teamdrive.h" #include "utils.h" #include #include using namespace KGAPI2; using namespace KGAPI2::Drive; class Q_DECL_HIDDEN TeamdriveModifyJob::Private { public: Private(TeamdriveModifyJob *parent); void processNext(); TeamdrivesList teamdrives; private: TeamdriveModifyJob *const q; }; TeamdriveModifyJob::Private::Private(TeamdriveModifyJob *parent): q(parent) { } void TeamdriveModifyJob::Private::processNext() { if (teamdrives.isEmpty()) { q->emitFinished(); return; } const TeamdrivePtr teamdrive = teamdrives.takeFirst(); const QUrl url = DriveService::fetchTeamdriveUrl(teamdrive->id()); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); const QByteArray rawData = Teamdrive::toJSON(teamdrive); q->enqueueRequest(request, rawData, QStringLiteral("application/json")); } TeamdriveModifyJob::TeamdriveModifyJob(const TeamdrivePtr &teamdrive, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->teamdrives << teamdrive; } TeamdriveModifyJob::TeamdriveModifyJob(const TeamdrivesList &teamdrives, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->teamdrives << teamdrives; } TeamdriveModifyJob::~TeamdriveModifyJob() = default; void TeamdriveModifyJob::start() { d->processNext(); } ObjectsList TeamdriveModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray &rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << Teamdrive::fromJSON(rawData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } // Enqueue next item or finish d->processNext(); return items; } diff --git a/src/latitude/locationcreatejob.cpp b/src/latitude/locationcreatejob.cpp index 434c2fc..88c217f 100644 --- a/src/latitude/locationcreatejob.cpp +++ b/src/latitude/locationcreatejob.cpp @@ -1,105 +1,103 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "locationcreatejob.h" #include "latitudeservice.h" #include "account.h" #include "../debug.h" #include "location.h" #include "utils.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN LocationCreateJob::Private { public: Private(); LocationPtr location; bool isCurrent; }; LocationCreateJob::Private::Private(): isCurrent(true) { } LocationCreateJob::LocationCreateJob(const LocationPtr& location, bool isCurrent, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->location = location; d->isCurrent = isCurrent; } LocationCreateJob::~LocationCreateJob() { delete d; } void LocationCreateJob::start() { QUrl url; if (d->isCurrent) { url = LatitudeService::insertCurrentLocationUrl(); } else { url = LatitudeService::insertLocationUrl(); } - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", LatitudeService::APIVersion().toLatin1()); - request.setUrl(url); const QByteArray rawData = LatitudeService::locationToJSON(d->location); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList LocationCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << LatitudeService::JSONToLocation(rawData).dynamicCast(); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } return items; } diff --git a/src/latitude/locationdeletejob.cpp b/src/latitude/locationdeletejob.cpp index 3ae36cf..7872245 100644 --- a/src/latitude/locationdeletejob.cpp +++ b/src/latitude/locationdeletejob.cpp @@ -1,106 +1,105 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "locationdeletejob.h" #include "latitudeservice.h" #include "account.h" #include "../debug.h" #include "location.h" #include "utils.h" #include using namespace KGAPI2; class Q_DECL_HIDDEN LocationDeleteJob::Private { public: Private(); qulonglong locationId; bool finished; }; LocationDeleteJob::Private::Private(): locationId(0), finished(false) { } LocationDeleteJob::LocationDeleteJob(const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private) { } LocationDeleteJob::LocationDeleteJob(const LocationPtr& location, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private) { d->locationId = location->timestamp(); } LocationDeleteJob::LocationDeleteJob(qulonglong timestamp, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private) { d->locationId = timestamp; } LocationDeleteJob::~LocationDeleteJob() { delete d; } void LocationDeleteJob::start() { if (d->finished) { emitFinished(); return; } QUrl url; if (d->locationId > 0) { url = LatitudeService::deleteLocationUrl(d->locationId); } else { url = LatitudeService::deleteCurrentLocationUrl(); } QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); request.setRawHeader("GData-Version", LatitudeService::APIVersion().toLatin1()); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request); d->finished = true; } diff --git a/src/latitude/locationfetchhistoryjob.cpp b/src/latitude/locationfetchhistoryjob.cpp index 7b0a6ed..0dacab4 100644 --- a/src/latitude/locationfetchhistoryjob.cpp +++ b/src/latitude/locationfetchhistoryjob.cpp @@ -1,164 +1,162 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "locationfetchhistoryjob.h" #include "account.h" #include "../debug.h" #include "location.h" #include "utils.h" #include "latitudeservice.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN LocationFetchHistoryJob::Private { public: Private(LocationFetchHistoryJob *parent); QNetworkRequest createRequest(const QUrl &url); Latitude::Granularity granularity; int maxResults; qlonglong minTimestamp; qlonglong maxTimestamp; private: LocationFetchHistoryJob * const q; }; LocationFetchHistoryJob::Private::Private(LocationFetchHistoryJob *parent): granularity(Latitude::City), maxResults(0), minTimestamp(0), maxTimestamp(0), q(parent) { } QNetworkRequest LocationFetchHistoryJob::Private::createRequest(const QUrl& url) { - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", LatitudeService::APIVersion().toLatin1()); - request.setUrl(url); return request; } LocationFetchHistoryJob::LocationFetchHistoryJob(const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { } LocationFetchHistoryJob::~LocationFetchHistoryJob() { delete d; } int LocationFetchHistoryJob::maxResults() const { return d->maxResults; } void LocationFetchHistoryJob::setMaxResults(int results) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify maxResults property while job is running"; } d->maxResults = results; } Latitude::Granularity LocationFetchHistoryJob::granularity() const { return d->granularity; } void LocationFetchHistoryJob::setGranularity(Latitude::Granularity granularity) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify maxResults property while job is running"; } d->granularity = granularity; } qlonglong LocationFetchHistoryJob::minTimestamp() const { return d->minTimestamp; } void LocationFetchHistoryJob::setMinTimestamp(qlonglong minTimestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify maxResults property while job is running"; } d->minTimestamp = minTimestamp; } qlonglong LocationFetchHistoryJob::maxTimestamp() const { return d->maxTimestamp; } void LocationFetchHistoryJob::setMaxTimestamp(qlonglong maxTimestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify maxResults property while job is running"; } d->maxTimestamp = maxTimestamp; } void LocationFetchHistoryJob::start() { const QUrl url = LatitudeService::locationHistoryUrl(d->granularity, d->maxResults, d->maxTimestamp, d->minTimestamp); const QNetworkRequest request = d->createRequest(url); enqueueRequest(request); } ObjectsList LocationFetchHistoryJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { FeedData feedData; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << LatitudeService::parseLocationJSONFeed(rawData, feedData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } if (feedData.nextPageUrl.isValid()) { const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); enqueueRequest(request); } return items; } #include "moc_locationfetchhistoryjob.cpp" diff --git a/src/latitude/locationfetchjob.cpp b/src/latitude/locationfetchjob.cpp index 081684b..40539ce 100644 --- a/src/latitude/locationfetchjob.cpp +++ b/src/latitude/locationfetchjob.cpp @@ -1,114 +1,112 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "locationfetchjob.h" #include "latitudeservice.h" #include "account.h" #include "../debug.h" #include "location.h" #include "utils.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN LocationFetchJob::Private { public: Private(); qlonglong timestamp; Latitude::Granularity granularity; }; LocationFetchJob::Private::Private(): timestamp(-1), granularity(Latitude::City) { } LocationFetchJob::LocationFetchJob(const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private) { } LocationFetchJob::LocationFetchJob(qlonglong timestamp, const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private) { d->timestamp = timestamp; } LocationFetchJob::~LocationFetchJob() { delete d; } Latitude::Granularity LocationFetchJob::granularity() const { return d->granularity; } void LocationFetchJob::setGranularity(Latitude::Granularity granularity) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify granularity property when the job is running"; } d->granularity = granularity; } void LocationFetchJob::start() { QUrl url; if (d->timestamp == -1) { url = LatitudeService::retrieveCurrentLocationUrl(d->granularity); } else { url = LatitudeService::retrieveLocationUrl(d->timestamp, d->granularity); } - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); + QNetworkRequest request(url); request.setRawHeader("GData-Version", LatitudeService::APIVersion().toLatin1()); - request.setUrl(url); enqueueRequest(request); } ObjectsList LocationFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct == KGAPI2::JSON) { items << LatitudeService::JSONToLocation(rawData).dynamicCast(); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); } return items; } #include "moc_locationfetchjob.cpp" diff --git a/src/tasks/taskcreatejob.cpp b/src/tasks/taskcreatejob.cpp index 8f09491..b048bb9 100644 --- a/src/tasks/taskcreatejob.cpp +++ b/src/tasks/taskcreatejob.cpp @@ -1,135 +1,133 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "taskcreatejob.h" #include "tasksservice.h" #include "account.h" #include "../debug.h" #include "utils.h" #include "task.h" #include "private/queuehelper_p.h" #include #include #include using namespace KGAPI2; class Q_DECL_HIDDEN TaskCreateJob::Private { public: QueueHelper tasks; QString taskListId; QString parentId; }; TaskCreateJob::TaskCreateJob(const TaskPtr& task, const QString& taskListId, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->tasks << task; d->taskListId = taskListId; } TaskCreateJob::TaskCreateJob(const TasksList& tasks, const QString& taskListId, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->tasks = tasks; d->taskListId = taskListId; } TaskCreateJob::~TaskCreateJob() { delete d; } QString TaskCreateJob::parentItem() const { return d->parentId; } void TaskCreateJob::setParentItem(const QString &parentId) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify parentItem property when job is running!"; return; } d->parentId = parentId; } void TaskCreateJob::start() { if (d->tasks.atEnd()) { emitFinished(); return; } const TaskPtr task = d->tasks.current(); QUrl url = TasksService::createTaskUrl(d->taskListId); QUrlQuery query(url); if (!d->parentId.isEmpty()) { query.addQueryItem(QStringLiteral("parent"), d->parentId); } url.setQuery(query); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = TasksService::taskToJSON(task); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList TaskCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << TasksService::JSONToTask(rawData).dynamicCast(); d->tasks.currentProcessed(); // Enqueue next item or finish start(); return items; } diff --git a/src/tasks/taskdeletejob.cpp b/src/tasks/taskdeletejob.cpp index ba99b81..fe81b87 100644 --- a/src/tasks/taskdeletejob.cpp +++ b/src/tasks/taskdeletejob.cpp @@ -1,132 +1,131 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "taskdeletejob.h" #include "tasksservice.h" #include "account.h" #include "../debug.h" #include "task.h" #include "utils.h" #include "private/queuehelper_p.h" #include using namespace KGAPI2; class Q_DECL_HIDDEN TaskDeleteJob::Private { public: Private(TaskDeleteJob *parent); void processNextTask(); QueueHelper tasksIds; QString taskListId; private: TaskDeleteJob * const q; }; TaskDeleteJob::Private::Private(TaskDeleteJob *parent): q(parent) { } void TaskDeleteJob::Private::processNextTask() { if (tasksIds.atEnd()) { q->emitFinished(); return; } const QString taskId = tasksIds.current(); const QUrl url = TasksService::removeTaskUrl(taskListId, taskId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } q->enqueueRequest(request); } TaskDeleteJob::TaskDeleteJob(const TaskPtr& task, const QString& taskListId, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private(this)) { d->tasksIds << task->uid(); d->taskListId = taskListId; } TaskDeleteJob::TaskDeleteJob(const TasksList& tasks, const QString& tasklistId, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private(this)) { d->tasksIds.reserve(tasks.size()); for (const TaskPtr &task : qAsConst(tasks)) { d->tasksIds << task->uid(); } d->taskListId = tasklistId; } TaskDeleteJob::TaskDeleteJob(const QString &taskId, const QString &taskListId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private(this)) { d->tasksIds << taskId; d->taskListId = taskListId; } TaskDeleteJob::TaskDeleteJob(const QStringList &tasksIds, const QString &taskListId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private(this)) { d->tasksIds = tasksIds; d->taskListId = taskListId; } TaskDeleteJob::~TaskDeleteJob() { delete d; } void TaskDeleteJob::start() { d->processNextTask(); } void TaskDeleteJob::handleReply(const QNetworkReply* reply, const QByteArray& rawData) { d->tasksIds.currentProcessed(); KGAPI2::DeleteJob::handleReply(reply, rawData); } diff --git a/src/tasks/taskfetchjob.cpp b/src/tasks/taskfetchjob.cpp index 09da970..cfb859c 100644 --- a/src/tasks/taskfetchjob.cpp +++ b/src/tasks/taskfetchjob.cpp @@ -1,266 +1,264 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "taskfetchjob.h" #include "tasksservice.h" #include "account.h" #include "../debug.h" #include "task.h" #include "utils.h" #include #include #include using namespace KGAPI2; class Q_DECL_HIDDEN TaskFetchJob::Private { public: Private(TaskFetchJob *parent); QNetworkRequest createRequest(const QUrl &url); QString taskId; QString taskListId; bool fetchDeleted; bool fetchCompleted; quint64 updatedTimestamp; quint64 completedMin; quint64 completedMax; quint64 dueMin; quint64 dueMax; private: TaskFetchJob * const q; }; TaskFetchJob::Private::Private(TaskFetchJob* parent): fetchDeleted(true), fetchCompleted(true), updatedTimestamp(0), completedMin(0), completedMax(0), dueMin(0), dueMax(0), q(parent) { } QNetworkRequest TaskFetchJob::Private::createRequest(const QUrl& url) { - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } return request; } TaskFetchJob::TaskFetchJob(const QString& taskListId, const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { d->taskListId = taskListId; } TaskFetchJob::TaskFetchJob(const QString& taskId, const QString& taskListId, const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { d->taskId = taskId; d->taskListId = taskListId; } TaskFetchJob::~TaskFetchJob() { delete d; } void TaskFetchJob::setFetchOnlyUpdated(quint64 timestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify fetchOnlyUpdated property when job is running"; return; } d->updatedTimestamp = timestamp; } quint64 TaskFetchJob::fetchOnlyUpdated() { return d->updatedTimestamp; } void TaskFetchJob::setFetchCompleted(bool fetchCompleted) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify fetchCompleted property when job is running"; return; } d->fetchCompleted = fetchCompleted; } bool TaskFetchJob::fetchCompleted() const { return d->fetchCompleted; } void TaskFetchJob::setFetchDeleted(bool fetchDeleted) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify fetchDeleted property when job is running"; return; } d->fetchDeleted = fetchDeleted; } bool TaskFetchJob::fetchDeleted() const { return d->fetchDeleted; } void TaskFetchJob::setCompletedMin(quint64 timestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify completedMin property when job is running"; return; } d->completedMin = timestamp; } quint64 TaskFetchJob::completedMin() const { return d->completedMin; } void TaskFetchJob::setCompletedMax(quint64 timestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify completedMax property when job is running"; return; } d->completedMax = timestamp; } quint64 TaskFetchJob::completedMax() const { return d->completedMax; } void TaskFetchJob::setDueMin(quint64 timestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify dueMin property when job is running"; return; } d->dueMin = timestamp; } quint64 TaskFetchJob::dueMin() const { return d->dueMin; } void TaskFetchJob::setDueMax(quint64 timestamp) { if (isRunning()) { qCWarning(KGAPIDebug) << "Can't modify dueMax property when job is running"; return; } d->dueMax = timestamp; } quint64 TaskFetchJob::dueMax() const { return d->dueMax; } void TaskFetchJob::start() { QUrl url; if (d->taskId.isEmpty()) { url = TasksService::fetchAllTasksUrl(d->taskListId); QUrlQuery query(url); query.addQueryItem(QStringLiteral("showDeleted"), Utils::bool2Str(d->fetchDeleted)); query.addQueryItem(QStringLiteral("showCompleted"), Utils::bool2Str(d->fetchCompleted)); if (d->updatedTimestamp > 0) { query.addQueryItem(QStringLiteral("updatedMin"), Utils::ts2Str(d->updatedTimestamp)); } if (d->completedMin > 0) { query.addQueryItem(QStringLiteral("completedMin"), Utils::ts2Str(d->completedMin)); } if (d->completedMax > 0) { query.addQueryItem(QStringLiteral("completedMax"), Utils::ts2Str(d->completedMax)); } if (d->dueMin > 0) { query.addQueryItem(QStringLiteral("dueMin"), Utils::ts2Str(d->dueMin)); } if (d->dueMax > 0) { query.addQueryItem(QStringLiteral("dueMax"), Utils::ts2Str(d->dueMax)); } url.setQuery(query); } else { url = TasksService::fetchTaskUrl(d->taskListId, d->taskId); } const QNetworkRequest request = d->createRequest(url); enqueueRequest(request); } ObjectsList TaskFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { FeedData feedData; feedData.requestUrl = reply->url(); ObjectsList items; QString itemId; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { if (d->taskId.isEmpty()) { items = TasksService::parseJSONFeed(rawData, feedData); } else { items << TasksService::JSONToTask(rawData); } } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); enqueueRequest(request); } return items; } diff --git a/src/tasks/tasklistcreatejob.cpp b/src/tasks/tasklistcreatejob.cpp index 309de11..c46d70a 100644 --- a/src/tasks/tasklistcreatejob.cpp +++ b/src/tasks/tasklistcreatejob.cpp @@ -1,109 +1,107 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "tasklistcreatejob.h" #include "tasksservice.h" #include "account.h" #include "../debug.h" #include "tasklist.h" #include "utils.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN TaskListCreateJob::Private { public: QueueHelper taskLists; }; TaskListCreateJob::TaskListCreateJob(const TaskListPtr& taskList, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->taskLists << taskList; } TaskListCreateJob::TaskListCreateJob(const TaskListsList& taskLists, const AccountPtr& account, QObject* parent): CreateJob(account, parent), d(new Private) { d->taskLists = taskLists; } TaskListCreateJob::~TaskListCreateJob() { delete d; } void TaskListCreateJob::start() { if (d->taskLists.atEnd()) { emitFinished(); return; } const TaskListPtr taskList = d->taskLists.current(); const QUrl url = TasksService::createTaskListUrl(); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = TasksService::taskListToJSON(taskList); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList TaskListCreateJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << TasksService::JSONToTaskList(rawData).dynamicCast(); d->taskLists.currentProcessed(); // Enqueue next item or finish start(); return items; } diff --git a/src/tasks/tasklistdeletejob.cpp b/src/tasks/tasklistdeletejob.cpp index 4d99743..fe973e2 100644 --- a/src/tasks/tasklistdeletejob.cpp +++ b/src/tasks/tasklistdeletejob.cpp @@ -1,126 +1,125 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "tasklistdeletejob.h" #include "tasksservice.h" #include "account.h" #include "../debug.h" #include "tasklist.h" #include "private/queuehelper_p.h" #include using namespace KGAPI2; class Q_DECL_HIDDEN TaskListDeleteJob::Private { public: Private(TaskListDeleteJob *parent); void processNextTaskList(); QueueHelper taskListsIds; private: TaskListDeleteJob * const q; }; TaskListDeleteJob::Private::Private(TaskListDeleteJob *parent): q(parent) { } void TaskListDeleteJob::Private::processNextTaskList() { if (taskListsIds.atEnd()) { q->emitFinished(); return; } const QString taskListId = taskListsIds.current(); const QUrl url = TasksService::removeTaskListUrl(taskListId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } q->enqueueRequest(request); } TaskListDeleteJob::TaskListDeleteJob(const TaskListPtr& taskList, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private(this)) { d->taskListsIds << taskList->uid(); } TaskListDeleteJob::TaskListDeleteJob(const TaskListsList& taskLists, const AccountPtr& account, QObject* parent): DeleteJob(account, parent), d(new Private(this)) { d->taskListsIds.reserve(taskLists.size()); for (const TaskListPtr &taskList : taskLists) { d->taskListsIds << taskList->uid(); } } TaskListDeleteJob::TaskListDeleteJob(const QStringList &taskListsIds, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private(this)) { d->taskListsIds = taskListsIds; } TaskListDeleteJob::TaskListDeleteJob(const QString &taskListsId, const AccountPtr &account, QObject *parent): DeleteJob(account, parent), d(new Private(this)) { d->taskListsIds << taskListsId; } TaskListDeleteJob::~TaskListDeleteJob() { delete d; } void TaskListDeleteJob::start() { d->processNextTaskList(); } void TaskListDeleteJob::handleReply(const QNetworkReply* reply, const QByteArray& rawData) { d->taskListsIds.currentProcessed(); KGAPI2::DeleteJob::handleReply(reply, rawData); } diff --git a/src/tasks/tasklistfetchjob.cpp b/src/tasks/tasklistfetchjob.cpp index d427e7e..c571934 100644 --- a/src/tasks/tasklistfetchjob.cpp +++ b/src/tasks/tasklistfetchjob.cpp @@ -1,109 +1,107 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "tasklistfetchjob.h" #include "tasksservice.h" #include "account.h" #include "../debug.h" #include "tasklist.h" #include "utils.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN TaskListFetchJob::Private { public: Private(TaskListFetchJob *parent); QNetworkRequest createRequest(const QUrl &url); private: TaskListFetchJob * const q; }; TaskListFetchJob::Private::Private(TaskListFetchJob* parent): q(parent) { } QNetworkRequest TaskListFetchJob::Private::createRequest(const QUrl& url) { - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } return request; } TaskListFetchJob::TaskListFetchJob(const AccountPtr& account, QObject* parent): FetchJob(account, parent), d(new Private(this)) { } TaskListFetchJob::~TaskListFetchJob() { delete d; } void TaskListFetchJob::start() { const QUrl url = TasksService::fetchTaskListsUrl(); const QNetworkRequest request = d->createRequest(url); enqueueRequest(request); } ObjectsList TaskListFetchJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { FeedData feedData; ObjectsList items; QString itemId; const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); if (ct == KGAPI2::JSON) { items = TasksService::parseJSONFeed(rawData, feedData); } else { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } if (feedData.nextPageUrl.isValid()) { const QNetworkRequest request = d->createRequest(feedData.nextPageUrl); enqueueRequest(request); } return items; } diff --git a/src/tasks/tasklistmodifyjob.cpp b/src/tasks/tasklistmodifyjob.cpp index 69bdb8e..95ffe89 100644 --- a/src/tasks/tasklistmodifyjob.cpp +++ b/src/tasks/tasklistmodifyjob.cpp @@ -1,111 +1,109 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "tasklistmodifyjob.h" #include "tasksservice.h" #include "account.h" #include "../debug.h" #include "tasklist.h" #include "utils.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN TaskListModifyJob::Private { public: QueueHelper taskLists; }; TaskListModifyJob::TaskListModifyJob(const TaskListPtr& taskList, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->taskLists << taskList; } TaskListModifyJob::TaskListModifyJob(const TaskListsList& taskLists, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->taskLists = taskLists; } TaskListModifyJob::~TaskListModifyJob() { delete d; } void TaskListModifyJob::start() { if (d->taskLists.atEnd()) { emitFinished(); return; } const TaskListPtr taskList = d->taskLists.current(); const QUrl url = TasksService::updateTaskListUrl(taskList->uid()); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = TasksService::taskListToJSON(taskList); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList TaskListModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << TasksService::JSONToTaskList(rawData).dynamicCast(); d->taskLists.currentProcessed(); // Enqueue next item or finish start(); return items; } diff --git a/src/tasks/taskmodifyjob.cpp b/src/tasks/taskmodifyjob.cpp index b81b676..87ee325 100644 --- a/src/tasks/taskmodifyjob.cpp +++ b/src/tasks/taskmodifyjob.cpp @@ -1,112 +1,110 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "taskmodifyjob.h" #include "tasksservice.h" #include "account.h" #include "../debug.h" #include "task.h" #include "utils.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN TaskModifyJob::Private { public: QueueHelper tasks; QString taskListId; }; TaskModifyJob::TaskModifyJob(const TaskPtr& task, const QString& taskListId, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->tasks << task; d->taskListId = taskListId; } TaskModifyJob::TaskModifyJob(const TasksList& tasks, const QString& taskListId, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private) { d->tasks = tasks; d->taskListId = taskListId; } TaskModifyJob::~TaskModifyJob() { delete d; } void TaskModifyJob::start() { if (d->tasks.atEnd()) { emitFinished(); return; } const TaskPtr task = d->tasks.current(); const QUrl url = TasksService::updateTaskUrl(d->taskListId, task->uid()); - QNetworkRequest request; - request.setRawHeader("Authorization", "Bearer " + account()->accessToken().toLatin1()); - request.setUrl(url); + QNetworkRequest request(url); const QByteArray rawData = TasksService::taskToJSON(task); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } enqueueRequest(request, rawData, QStringLiteral("application/json")); } ObjectsList TaskModifyJob::handleReplyWithItems(const QNetworkReply *reply, const QByteArray& rawData) { const QString contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString(); ContentType ct = Utils::stringToContentType(contentType); ObjectsList items; if (ct != KGAPI2::JSON) { setError(KGAPI2::InvalidResponse); setErrorString(tr("Invalid response content type")); emitFinished(); return items; } items << TasksService::JSONToTask(rawData).dynamicCast(); d->tasks.currentProcessed(); // Enqueue next item or finish start(); return items; } diff --git a/src/tasks/taskmovejob.cpp b/src/tasks/taskmovejob.cpp index 77ab378..5acaaf0 100644 --- a/src/tasks/taskmovejob.cpp +++ b/src/tasks/taskmovejob.cpp @@ -1,151 +1,150 @@ /* * This file is part of LibKGAPI library * * Copyright (C) 2013 Daniel Vrátil * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) version 3, or any * later version accepted by the membership of KDE e.V. (or its * successor approved by the membership of KDE e.V.), which shall * act as a proxy defined in Section 6 of version 3 of the license. * * This library 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see . */ #include "taskmovejob.h" #include "tasksservice.h" #include "account.h" #include "../debug.h" #include "task.h" #include "utils.h" #include "private/queuehelper_p.h" #include #include using namespace KGAPI2; class Q_DECL_HIDDEN TaskMoveJob::Private { public: Private(TaskMoveJob *parent); void processNextTask(); QueueHelper tasksIds; QString taskListId; QString newParentId; private: TaskMoveJob * const q; }; TaskMoveJob::Private::Private(TaskMoveJob *parent): q(parent) { } void TaskMoveJob::Private::processNextTask() { if (tasksIds.atEnd()) { q->emitFinished(); return; } const QString taskId = tasksIds.current(); const QUrl url = TasksService::moveTaskUrl(taskListId, taskId, newParentId); QNetworkRequest request(url); - request.setRawHeader("Authorization", "Bearer " + q->account()->accessToken().toLatin1()); QStringList headers; const auto rawHeaderList = request.rawHeaderList(); headers.reserve(rawHeaderList.size()); for (const QByteArray &str : qAsConst(rawHeaderList)) { headers << QLatin1String(str) + QLatin1String(": ") + QLatin1String(request.rawHeader(str)); } q->enqueueRequest(request); } TaskMoveJob::TaskMoveJob(const TaskPtr& task, const QString& taskListId, const QString& newParentId, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private(this)) { d->tasksIds << task->uid(); d->taskListId = taskListId; d->newParentId = newParentId; } TaskMoveJob::TaskMoveJob(const TasksList& tasks, const QString& taskListId, const QString& newParentId, const AccountPtr& account, QObject* parent): ModifyJob(account, parent), d(new Private(this)) { d->tasksIds.reserve(tasks.size()); for (const TaskPtr &task : tasks) { d->tasksIds << task->uid(); } d->taskListId = taskListId; d->newParentId = newParentId; } TaskMoveJob::TaskMoveJob(const QString &taskId, const QString &taskListId, const QString &newParentId, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->tasksIds << taskId; d->taskListId = taskListId; d->newParentId = newParentId; } TaskMoveJob::TaskMoveJob(const QStringList &tasksIds, const QString &taskListId, const QString &newParentId, const AccountPtr &account, QObject *parent): ModifyJob(account, parent), d(new Private(this)) { d->tasksIds = tasksIds; d->taskListId = taskListId; d->newParentId = newParentId; } TaskMoveJob::~TaskMoveJob() { delete d; } void TaskMoveJob::start() { d->processNextTask(); } void TaskMoveJob::dispatchRequest(QNetworkAccessManager *accessManager, const QNetworkRequest &request, const QByteArray &data, const QString &contentType) { Q_UNUSED(data) Q_UNUSED(contentType) accessManager->post(request, QByteArray()); } void TaskMoveJob::handleReply(const QNetworkReply *reply, const QByteArray& rawData) { Q_UNUSED(reply) Q_UNUSED(rawData) d->tasksIds.currentProcessed(); d->processNextTask(); }