File indexing completed on 2024-06-23 05:07:00

0001 /*
0002     SPDX-FileCopyrightText: 2009 Volker Krause <vkrause@kde.org>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "collectionmovehandler.h"
0008 
0009 #include "akonadi.h"
0010 #include "cachecleaner.h"
0011 #include "connection.h"
0012 #include "handlerhelper.h"
0013 #include "storage/collectionqueryhelper.h"
0014 #include "storage/datastore.h"
0015 #include "storage/itemretriever.h"
0016 #include "storage/transaction.h"
0017 
0018 using namespace Akonadi;
0019 using namespace Akonadi::Server;
0020 
0021 CollectionMoveHandler::CollectionMoveHandler(AkonadiServer &akonadi)
0022     : Handler(akonadi)
0023 {
0024 }
0025 
0026 bool CollectionMoveHandler::parseStream()
0027 {
0028     const auto &cmd = Protocol::cmdCast<Protocol::MoveCollectionCommand>(m_command);
0029 
0030     Collection source = HandlerHelper::collectionFromScope(cmd.collection(), connection()->context());
0031     if (!source.isValid()) {
0032         return failureResponse(QStringLiteral("Invalid collection to move"));
0033     }
0034 
0035     Collection target;
0036     if (cmd.destination().isEmpty()) {
0037         target.setId(0);
0038     } else {
0039         target = HandlerHelper::collectionFromScope(cmd.destination(), connection()->context());
0040         if (!target.isValid()) {
0041             return failureResponse(QStringLiteral("Invalid destination collection"));
0042         }
0043     }
0044 
0045     if (source.parentId() == target.id()) {
0046         return successResponse<Protocol::MoveCollectionResponse>();
0047     }
0048 
0049     CacheCleanerInhibitor inhibitor(akonadi());
0050 
0051     // retrieve all not yet cached items of the source
0052     ItemRetriever retriever(akonadi().itemRetrievalManager(), connection(), connection()->context());
0053     retriever.setCollection(source, true);
0054     retriever.setRetrieveFullPayload(true);
0055     if (!retriever.exec()) {
0056         return failureResponse(retriever.lastError());
0057     }
0058 
0059     DataStore *store = connection()->storageBackend();
0060     Transaction transaction(store, QStringLiteral("CollectionMoveHandler"));
0061 
0062     if (!store->moveCollection(source, target)) {
0063         return failureResponse(QStringLiteral("Unable to reparent collection"));
0064     }
0065 
0066     if (!transaction.commit()) {
0067         return failureResponse(QStringLiteral("Cannot commit transaction."));
0068     }
0069 
0070     return successResponse<Protocol::MoveCollectionResponse>();
0071 }