2
* Copyright (C) 2019 KeePassXC Team <team@keepassxc.org>
4
* This program is free software: you can redistribute it and/or modify
5
* it under the terms of the GNU General Public License as published by
6
* the Free Software Foundation, either version 2 or (at your option)
7
* version 3 of the License.
9
* This program is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
* GNU General Public License for more details.
14
* You should have received a copy of the GNU General Public License
15
* along with this program. If not, see <http://www.gnu.org/licenses/>.
18
#include "AttachmentImport.h"
21
#include "core/Group.h"
23
#include <QCommandLineParser>
26
const QCommandLineOption AttachmentImport::ForceOption =
27
QCommandLineOption(QStringList() << "f"
29
QObject::tr("Overwrite existing attachments."));
31
AttachmentImport::AttachmentImport()
33
name = QString("attachment-import");
34
description = QObject::tr("Imports an attachment to an entry.");
35
options.append(AttachmentImport::ForceOption);
36
positionalArguments.append({QString("entry"), QObject::tr("Path of the entry."), QString("")});
37
positionalArguments.append(
38
{QString("attachment-name"), QObject::tr("Name of the attachment to be added."), QString("")});
39
positionalArguments.append(
40
{QString("import-file"), QObject::tr("Path of the attachment to be imported."), QString("")});
43
int AttachmentImport::executeWithDatabase(QSharedPointer<Database> database, QSharedPointer<QCommandLineParser> parser)
45
auto& out = parser->isSet(Command::QuietOption) ? Utils::DEVNULL : Utils::STDOUT;
46
auto& err = Utils::STDERR;
48
auto args = parser->positionalArguments();
49
auto entryPath = args.at(1);
51
auto entry = database->rootGroup()->findEntryByPath(entryPath);
53
err << QObject::tr("Could not find entry with path %1.").arg(entryPath) << endl;
57
auto attachmentName = args.at(2);
59
auto attachments = entry->attachments();
60
if (attachments->hasKey(attachmentName) && !parser->isSet(AttachmentImport::ForceOption)) {
61
err << QObject::tr("Attachment %1 already exists for entry %2.").arg(attachmentName, entryPath) << endl;
65
auto importFileName = args.at(3);
67
QFile importFile(importFileName);
68
if (!importFile.open(QIODevice::ReadOnly)) {
69
err << QObject::tr("Could not open attachment file %1.").arg(importFileName) << endl;
74
attachments->set(attachmentName, importFile.readAll());
78
if (!database->save(Database::Atomic, {}, &errorMessage)) {
79
err << QObject::tr("Writing the database failed %1.").arg(errorMessage) << endl;
83
out << QObject::tr("Successfully imported attachment %1 as %2 to entry %3.")
84
.arg(importFileName, attachmentName, entryPath)