files.cpp 26.4 KB
Newer Older
1
/*
2
 * Copyright (C) 2014-2018 CZ.NIC
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include <QDebug>
#include <QDesktopServices>
26
#include <QFileInfo>
Martin Straka's avatar
Martin Straka committed
27
#include <QQmlEngine>
28

29
#include "ios/src/url_opener.h"
30
#include "src/auxiliaries/attachment_helper.h"
31
#include "src/auxiliaries/email_helper.h"
32
#include "src/common.h"
33
#include "src/crypto/crypto.h"
34
#include "src/dialogues/dialogues.h"
35
#include "src/files.h"
36
#include "src/global.h"
37 38
#include "src/io/filesystem.h"
#include "src/models/accountmodel.h"
39
#include "src/net/xml_layer.h"
40
#include "src/qml_interaction/attachment_data.h"
41
#include "src/qml_interaction/message_envelope.h"
42
#include "src/settings.h"
43
#include "src/sqlite/dbs.h"
44 45
#include "src/sqlite/file_db_container.h"
#include "src/sqlite/message_db_container.h"
46
#include "src/sqlite/zfo_db.h"
47

Martin Straka's avatar
Martin Straka committed
48 49 50
void Files::declareQML(void)
{
	qmlRegisterType<Files>("cz.nic.mobileDatovka.files", 1, 0, "FileIdType");
51
	qmlRegisterType<Files>("cz.nic.mobileDatovka.files", 1, 0, "EmailAttachType");
Martin Straka's avatar
Martin Straka committed
52
	qRegisterMetaType<Files::FileIdType>();
53
	qRegisterMetaType<Files::EmailAttachType>();
Martin Straka's avatar
Martin Straka committed
54 55
}

56 57
Files::Files(QObject *parent)
    : QObject(parent)
58 59 60
{
}

61
void Files::attachmentSavingNotification(const QString &destPath)
62
{
63 64 65 66
	QFileInfo fi(destPath);

	Dialogues::errorMessage(
	    !destPath.isEmpty() ? Dialogues::INFORMATION : Dialogues::CRITICAL,
67 68 69 70 71
	    tr("Attachment saving"),
	    !destPath.isEmpty() ? tr("Attachments have been saved.") :
	        tr("Attachments have not been saved!"),
	    !destPath.isEmpty() ?
	        tr("Path: '%1'").arg(fi.absolutePath()) : QString());
72 73 74 75 76 77
}

void Files::deleteExpiredFilesFromDbs(int days)
{
	qDebug("%s()", __func__);

78 79
	if (Q_UNLIKELY((GlobInstcs::setPtr == Q_NULLPTR) ||
	        (GlobInstcs::messageDbsPtr == Q_NULLPTR) ||
80 81
	        (GlobInstcs::fileDbsPtr == Q_NULLPTR) ||
	        (GlobInstcs::acntMapPtr == Q_NULLPTR))) {
82 83 84 85
		Q_ASSERT(0);
		return;
	}

86
	QStringList msgIDList;
87
	QStringList userNameList(GlobInstcs::acntMapPtr->keys());
88
	foreach (const QString &userName, userNameList) {
89 90
		FileDb *fDb = GlobInstcs::fileDbsPtr->accessFileDb(
		    GlobInstcs::setPtr->dbsLocation, userName,
91
		    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
Martin Straka's avatar
Martin Straka committed
92 93 94
		if (fDb == Q_NULLPTR) {
			qCritical() << "ERROR: File database cannot open!"
			    << userName;
95 96 97 98 99 100 101
			return;
		}
		msgIDList = fDb->cleanFilesInDb(days);
		if (msgIDList.isEmpty()) {
			continue;
		}

102 103
		MessageDb *msgDb = GlobInstcs::messageDbsPtr->accessMessageDb(
		    GlobInstcs::setPtr->dbsLocation, userName,
104
		    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
Martin Straka's avatar
Martin Straka committed
105
		if (msgDb == Q_NULLPTR) {
106
			qCritical() << "ERROR: Message database cannot open!";
107 108
			return;
		}
109
		msgDb->beginTransaction();
110 111 112 113
		foreach (const QString &msgId, msgIDList) {
			msgDb->setAttachmentDownloaded(msgId.toLongLong(),
			    false);
		}
114
		msgDb->commitTransaction();
115 116 117
	}
}

118 119 120 121 122 123 124 125 126 127 128
QString Files::getAttachmentFileIcon(const QString &fileName)
{
	return getAttachmentFileIconFromFileExtension(fileName);
}

qint64 Files::getAttachmentSizeInBytes(const QString &filePath)
{
	QFileInfo fileInfo(filePath);
	return fileInfo.size();
}

129
QByteArray Files::getFileRawContentFromDb(const QString &userName, int fileId)
130 131 132
{
	qDebug("%s()", __func__);

133
	if (Q_UNLIKELY((GlobInstcs::setPtr == Q_NULLPTR) ||
134 135
	        (GlobInstcs::fileDbsPtr == Q_NULLPTR) ||
	        (GlobInstcs::acntMapPtr == Q_NULLPTR))) {
136 137 138 139
		Q_ASSERT(0);
		return QByteArray();
	}

140 141
	FileDb *fDb = GlobInstcs::fileDbsPtr->accessFileDb(
	    GlobInstcs::setPtr->dbsLocation, userName,
142
	    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
143

144 145 146 147 148
	if (fDb == Q_NULLPTR) {
		qCritical() << "Cannot open file database!";
		return QByteArray();
	}

149
	return base64ToRaw(fDb->getFileContentFromDb(fileId).content.toUtf8());
150 151
}

152
void Files::openAttachmentFromDb(const QString &userName, int fileId)
153 154 155
{
	qDebug("%s()", __func__);

156
	if (Q_UNLIKELY((GlobInstcs::setPtr == Q_NULLPTR) ||
157 158
	        (GlobInstcs::fileDbsPtr == Q_NULLPTR) ||
	        (GlobInstcs::acntMapPtr == Q_NULLPTR))) {
159 160 161 162
		Q_ASSERT(0);
		return;
	}

163 164
	FileDb *fDb = GlobInstcs::fileDbsPtr->accessFileDb(
	    GlobInstcs::setPtr->dbsLocation, userName,
165
	    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
166

167 168
	if (fDb == Q_NULLPTR) {
		qCritical() << "Cannot open file database!";
169 170 171
		return;
	}

172 173
	FileDb::FileData file = fDb->getFileContentFromDb(fileId);

174
	openAttachment(file.filename, file.content.toUtf8());
175 176
}

177 178
void Files::openAttachment(const QString &fileName,
    const QByteArray &base64Data)
179 180
{
	Q_ASSERT(!fileName.isEmpty());
181
	Q_ASSERT(!base64Data.isEmpty());
182

183 184
	if (fileName.isEmpty() || base64Data.isEmpty()) {
		qCritical() << "File name or its content is empty!";
185 186 187
		return;
	}

188 189 190
	if (isZfoFile(fileName)) {
		/* Don't open zfo files from here. */
		qCritical() << "This should open ZFO files by itself.";
191
		Q_ASSERT(0);
192 193 194
		return;
	}

195
	QString filePath(writeFile(appTmpDirPath(), fileName,
196
	    base64ToRaw(base64Data)));
197 198

	if (!filePath.isEmpty()) {
199
		qInfo() << "Creating temporary file" << filePath;
200 201 202 203 204 205 206 207 208 209 210 211 212 213
		openAttachmentFromPath(filePath);
	} else {
		qCritical() << "Cannot create temporary file for" << fileName;
		Dialogues::errorMessage(Dialogues::CRITICAL,
		    tr("Open attachment error"),
		    tr("Cannot save selected file to disk for opening."),
		    QString());
	}
}

void Files::openAttachmentFromPath(const QString &filePath)
{
	if (filePath.isEmpty()) {
		qCritical() << "File path is empty!";
214
		Q_ASSERT(0);
215 216 217 218 219 220
		return;
	}

	if (isZfoFile(filePath)) {
		/* Don't open zfo files from here. */
		qCritical() << "This should open ZFO files by itself.";
221
		Q_ASSERT(0);
222 223
		return;
	}
224

225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
#ifdef Q_OS_IOS

	UrlOpener urlOpener;
	urlOpener.openFile(filePath);

#else

	if (!QDesktopServices::openUrl(QUrl::fromLocalFile(filePath))) {
		Dialogues::errorMessage(Dialogues::CRITICAL,
		    tr("Open attachment error"),
		    tr("There is no application to open this file format."),
		    tr("File: '%1'").arg(filePath));
	}

#endif
240 241
}

242 243
void Files::sendMsgFilesWithEmail(const QString &userName, qint64 msgId,
    enum Files::EmailAttachType attachType)
244 245 246
{
	qDebug("%s()", __func__);

247 248
	if (Q_UNLIKELY((GlobInstcs::setPtr == Q_NULLPTR) ||
	        (GlobInstcs::messageDbsPtr == Q_NULLPTR) ||
249
	        (GlobInstcs::fileDbsPtr == Q_NULLPTR) ||
250
	        (GlobInstcs::zfoDbPtr == Q_NULLPTR) ||
251
	        (GlobInstcs::acntMapPtr == Q_NULLPTR))) {
252 253 254 255
		Q_ASSERT(0);
		return;
	}

256 257 258 259 260 261 262
	if (userName.isEmpty() || msgId <= 0) {
		return;
	}

	QString body;
	QString subject;

263
	/* Fill email subject and email body */
264 265
	MessageDb *msgDb = GlobInstcs::messageDbsPtr->accessMessageDb(
	    GlobInstcs::setPtr->dbsLocation, userName,
266
	    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
Martin Straka's avatar
Martin Straka committed
267
	if (msgDb == Q_NULLPTR) {
268
		qCritical() << "ERROR: Message database cannot open!";
269 270 271
		return;
	}
	if (!msgDb->getMessageDataForEmail(msgId, body, subject)) {
272
		qCritical() << "ERROR: Message data mssing!";
273 274 275 276
		return;
	}

	QList<FileDb::FileData> filelist;
277 278 279

	/* Get attachment files from database if needed */
	if (Files::SEND_EMAIL_ZFO_ATTACHMENT == attachType
280
	        || Files::SEND_EMAIL_ATTACHMENT_ONLY == attachType ) {
281 282 283 284 285 286 287 288 289 290 291 292 293
		FileDb *fDb = GlobInstcs::fileDbsPtr->accessFileDb(
		    GlobInstcs::setPtr->dbsLocation, userName,
		    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
		if (fDb == Q_NULLPTR) {
			qCritical() << "ERROR: File database cannot open!";
			return;
		}

		filelist = fDb->getFilesFromDb(msgId);
		if (filelist.isEmpty()) {
			qCritical() << "ERROR: File list is empty!";
			return;
		}
294 295
	}

296 297
	/* Get zfo file from database if needed */
	if (Files::SEND_EMAIL_ZFO_ATTACHMENT == attachType
298
	        || Files::SEND_EMAIL_ZFO_ONLY == attachType ) {
299 300 301 302 303
		FileDb::FileData msgData;
		msgData.content = GlobInstcs::zfoDbPtr->getZfoContentFromDb(msgId,
		    (*GlobInstcs::acntMapPtr)[userName].isTestAccount());
		if (msgData.content.isEmpty()) {
			qCritical() << "ERROR: ZFO message data missing!";
304 305 306 307
			Dialogues::errorMessage(Dialogues::CRITICAL,
			    tr("ZFO missing"),
			    tr("ZFO message is not present in local database."),
			    tr("Download complete message again to obtain it."));
308 309 310 311 312 313
			Q_ASSERT(0);
			return;
		}
		msgData.filename = QString("DZ_%1.zfo").arg(msgId);
		filelist.append(msgData);
	}
314

315
	/* Create email content, email attachment path, email eml content */
316 317
	removeDirFromDocLoc(DATOVKA_MAIL_DIR_NAME);
	QString targetPath(appEmailDirPath(QString::number(msgId)));
318 319
	const QString boundary = generateBoundaryString();
	QString emailMessage = createEmailMessage(body, subject,  boundary);
320
	QStringList filePathList;
321

322
	/* Write attachment files to email directory */
323
	foreach (const FileDb::FileData &file, filelist) {
324
		QString fileName = file.filename;
325
		if (fileName.isEmpty()) {
326
			qCritical() << "ERROR: File name is empty!";
327 328
			return;
		}
329
		fileName = writeFile(targetPath, fileName,
330
		    base64ToRaw(file.content.toUtf8()));
331
		filePathList.append(fileName);
332 333 334 335 336 337
		addAttachmentToEmailMessage(emailMessage, file.filename,
		    file.content.toUtf8(), boundary);
	}

	finishEmailMessage(emailMessage, boundary);

338 339
	/* Send email */
	sendEmail(emailMessage, filePathList, subject, body, msgId);
340
}
341 342 343 344 345

void Files::deleteFileDb(const QString &userName)
{
	qDebug("%s()", __func__);

346 347
	if (Q_UNLIKELY((GlobInstcs::setPtr == Q_NULLPTR) ||
	        (GlobInstcs::messageDbsPtr == Q_NULLPTR) ||
348 349
	        (GlobInstcs::fileDbsPtr == Q_NULLPTR) ||
	        (GlobInstcs::acntMapPtr == Q_NULLPTR))) {
350 351 352 353
		Q_ASSERT(0);
		return;
	}

354
	int msgResponse = Dialogues::message(Dialogues::QUESTION,
355 356 357
	    tr("Delete files: %1").arg(userName),
	    tr("Do you want to clean up the file database of account '%1'?").arg(userName),
	    tr("Note: All attachment files of messages will be removed from the database."),
358 359
	    Dialogues::NO | Dialogues::YES, Dialogues::NO);
	if (msgResponse == Dialogues::NO) {
360 361 362
		return;
	}

363 364
	FileDb *fDb = GlobInstcs::fileDbsPtr->accessFileDb(
	    GlobInstcs::setPtr->dbsLocation, userName,
365
	    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
Martin Straka's avatar
Martin Straka committed
366
	if (fDb == Q_NULLPTR) {
367
		qCritical() << "ERROR: File database open error!";
368 369
		return;
	}
370
	if (!GlobInstcs::fileDbsPtr->deleteDb(fDb)) {
371
		qCritical() << "ERROR: File database could not delete!";
372 373 374
		return;
	}

375 376
	MessageDb *msgDb = GlobInstcs::messageDbsPtr->accessMessageDb(
	    GlobInstcs::setPtr->dbsLocation, userName,
377
	    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
Martin Straka's avatar
Martin Straka committed
378
	if (msgDb == Q_NULLPTR) {
379
		qCritical() << "ERROR: Message database cannot open!";
380 381 382
		return;
	}
	if (!msgDb->setAttachmentsDownloaded(false)) {
383
		qCritical() << "ERROR: Message data mssing!";
384 385 386
		return;
	}
}
387

Karel Slaný's avatar
Karel Slaný committed
388
void Files::vacuumFileDbs(void)
389 390 391
{
	qDebug("%s()", __func__);

392
	if (Q_UNLIKELY((GlobInstcs::setPtr == Q_NULLPTR) ||
393 394
	        (GlobInstcs::fileDbsPtr == Q_NULLPTR) ||
	        (GlobInstcs::acntMapPtr == Q_NULLPTR))) {
395 396 397 398
		Q_ASSERT(0);
		return;
	}

Karel Slaný's avatar
Karel Slaný committed
399
	emit statusBarTextChanged(tr("Vacuum databases"), true);
400

401
	QStringList userNameList(GlobInstcs::acntMapPtr->keys());
402
	foreach (const QString &userName, userNameList) {
403 404
		FileDb *fDb = GlobInstcs::fileDbsPtr->accessFileDb(
		    GlobInstcs::setPtr->dbsLocation, userName,
405
		    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
Martin Straka's avatar
Martin Straka committed
406
		if (fDb == Q_NULLPTR) {
407 408
			qCritical() << "ERROR: File database cannot open!"
			    << userName;
409 410
			return;
		}
Karel Slaný's avatar
Karel Slaný committed
411
		fDb->vacuumFileDb();
412 413
	}

Karel Slaný's avatar
Karel Slaný committed
414
	emit statusBarTextChanged(tr("Operation Vacuum has finished"), false);
415
}
416 417 418 419 420

bool Files::deleteAttachmentsFromDb(const QString &userName, qint64 msgId)
{
	qDebug("%s()", __func__);

421 422
	if (Q_UNLIKELY((GlobInstcs::setPtr == Q_NULLPTR) ||
	        (GlobInstcs::messageDbsPtr == Q_NULLPTR) ||
423 424
	        (GlobInstcs::fileDbsPtr == Q_NULLPTR) ||
	        (GlobInstcs::acntMapPtr == Q_NULLPTR))) {
425 426 427 428
		Q_ASSERT(0);
		return false;
	}

429 430
	FileDb *fDb = GlobInstcs::fileDbsPtr->accessFileDb(
	    GlobInstcs::setPtr->dbsLocation, userName,
431
	    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
Martin Straka's avatar
Martin Straka committed
432
	if (fDb == Q_NULLPTR) {
433
		qCritical() << "ERROR: File database cannot open!" << userName;
434 435 436 437
		return false;
	}

	if (fDb->deleteFilesFromDb(msgId)) {
438 439
		MessageDb *msgDb = GlobInstcs::messageDbsPtr->accessMessageDb(
		    GlobInstcs::setPtr->dbsLocation, userName,
440
		    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
Martin Straka's avatar
Martin Straka committed
441
		if (msgDb == Q_NULLPTR) {
442
			qCritical() << "ERROR: Message database cannot open!";
443 444 445 446 447 448 449
			return false;
		}
		return msgDb->setAttachmentDownloaded(msgId, false);
	}

	return false;
}
450

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
bool Files::fileReadable(const QString &filePath)
{
	if (filePath.isEmpty()) {
		Q_ASSERT(0);
		qCritical() << "Target ZFO path is empty!";
		return false;
	}

	{
		QFileInfo fileInfo(filePath);
		if (!fileInfo.isFile() || !fileInfo.isReadable()) {
			qCritical() << "Cannot open ZFO file from" << filePath;
			return false;
		}
	}

	return true;
}

bool Files::isZfoFile(const QString &fileName)
{
	return QFileInfo(fileName).suffix().toLower() == QStringLiteral("zfo");
}

QByteArray Files::rawFileContent(const QString &filePath)
{
	if (!fileReadable(filePath)) {
		return QByteArray();
	}

	QFile file(filePath);
	if (!file.open(QIODevice::ReadOnly)) {
		Q_ASSERT(0);
		qCritical() << "Cannot open file" << filePath;
		return QByteArray();
	}

	QByteArray rawData(file.readAll());
	file.close();
	return rawData;
}

QByteArray Files::base64ToRaw(const QByteArray &base64Data)
{
	return QByteArray::fromBase64(base64Data);
}

498 499
MsgInfo *Files::zfoData(const QVariant &attachModelVariant,
    const QByteArray &rawZfoData)
500
{
501
	enum MsgInfo::ZfoType type = MsgInfo::TYPE_UNKNOWN;
502
	QString idStr, annot, htmlDescr, emailBody;
503

504
	bool ret = parseXmlData(&type, &idStr, &annot, &htmlDescr,
505
	    FileListModel::fromVariant(attachModelVariant),
506
	    &emailBody, getXmlFromCms(rawZfoData));
507

508
	return ret ?
509
	    new (std::nothrow) MsgInfo(type, idStr, annot, htmlDescr,
510
	        emailBody) :
511
	    new (std::nothrow) MsgInfo();
512 513 514 515 516 517 518
}

bool Files::setAttachmentModel(FileListModel &attachModel,
    const QString &userName, qint64 msgId)
{
	qDebug("%s()", __func__);

519
	if (Q_UNLIKELY((GlobInstcs::setPtr == Q_NULLPTR) ||
520 521
	        (GlobInstcs::fileDbsPtr == Q_NULLPTR) ||
	        (GlobInstcs::acntMapPtr == Q_NULLPTR))) {
522 523 524 525
		Q_ASSERT(0);
		return false;
	}

526 527
	FileDb *fDb = GlobInstcs::fileDbsPtr->accessFileDb(
	    GlobInstcs::setPtr->dbsLocation, userName,
528
	    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544

	if (fDb == Q_NULLPTR) {
		qCritical() << "Cannot open file database!";
		return false;
	}
	attachModel.clearAll();
	fDb->getFileListFromDb(attachModel, msgId);
	return true;
}

void Files::sendAttachmentEmailZfo(const QVariant &attachModelVariant,
    const QString &msgIdStr, QString subject, QString body)
{
	qDebug("%s()", __func__);

	/* Obtain pointer to attachment model. */
545
	const FileListModel *attachModel =
546
	    FileListModel::fromVariant(attachModelVariant);
547 548 549 550 551 552 553 554 555 556 557 558 559 560
	if (attachModel == Q_NULLPTR) {
		Q_ASSERT(0);
		return;
	}

	/* Obtain message identifier. */
	bool ok = false;
	qint64 msgId = msgIdStr.toLongLong(&ok);
	if (!ok || (msgId < 0)) {
		return;
	}

	QStringList fileList;

561 562
	const QString boundary = generateBoundaryString();
	QString emailMessage = createEmailMessage(body, subject,  boundary);
563

564 565
	removeDirFromDocLoc(DATOVKA_MAIL_DIR_NAME);
	QString targetPath(appEmailDirPath(msgIdStr));
566 567 568 569 570 571 572 573 574 575 576

	for (int row = 0; row < attachModel->rowCount(); ++row) {
		QModelIndex idx(attachModel->index(row));
		/*
		 * On Android the attachment must be saved and the explicitly
		 * add into the email message.
		 */
		QByteArray base64Data(attachModel->data(idx,
		    FileListModel::ROLE_FILE_DATA).toByteArray());
		QString attachName(attachModel->data(idx,
		    FileListModel::ROLE_FILE_NAME).toString());
577 578
		QString filePath(writeFile(targetPath, attachName,
		    base64ToRaw(base64Data)));
579 580 581 582 583 584 585 586 587 588
		fileList.append(filePath);
		addAttachmentToEmailMessage(emailMessage, attachName,
		    base64Data, boundary);
	}

	finishEmailMessage(emailMessage, boundary);

	sendEmail(emailMessage, fileList, subject, body, msgId);
}

589 590 591 592 593
void Files::saveAttachmentsToDiskDb(const QString &userName,
    const QString &msgIdStr)
{
	qDebug("%s()", __func__);

594
	if (Q_UNLIKELY((GlobInstcs::setPtr == Q_NULLPTR) ||
595 596
	        (GlobInstcs::fileDbsPtr == Q_NULLPTR) ||
	        (GlobInstcs::acntMapPtr == Q_NULLPTR))) {
597 598 599 600
		Q_ASSERT(0);
		return;
	}

601 602 603 604 605 606 607 608 609 610 611 612 613
	/* User name must be supplied. */
	if (userName.isEmpty()) {
		Q_ASSERT(0);
		return;
	}

	/* Obtain message identifier. */
	bool ok = false;
	qint64 msgId = msgIdStr.toLongLong(&ok);
	if (!ok || (msgId < 0)) {
		return;
	}

614 615
	FileDb *fDb = GlobInstcs::fileDbsPtr->accessFileDb(
	    GlobInstcs::setPtr->dbsLocation, userName,
616
	    (*GlobInstcs::acntMapPtr)[userName].storeToDisk());
617

Martin Straka's avatar
Martin Straka committed
618 619 620 621
	if (fDb == Q_NULLPTR) {
		qCritical() << "Cannot open file database!";
		return;
	}
622

Martin Straka's avatar
Martin Straka committed
623 624 625 626
	QList<FileDb::FileData> filelist = fDb->getFilesFromDb(msgId);
	if (filelist.isEmpty()) {
		qCritical() << "File list is empty!";
		return;
627 628
	}

629
	QString filePath(appMsgAttachDirPath(msgIdStr));
630

631 632
	QString destPath;
	foreach (const FileDb::FileData &file, filelist) {
633
		destPath = writeFile(filePath, file.filename,
634
		    base64ToRaw(file.content.toUtf8()));
635 636 637 638 639 640 641 642 643 644 645 646
	}

	attachmentSavingNotification(destPath);
}

void Files::saveAttachmentsToDiskZfo(const QVariant &attachModelVariant,
    const QString &msgIdStr)
{
	qDebug("%s()", __func__);

	/* Obtain pointer to attachment model. */
	const FileListModel *attachModel =
647
	    FileListModel::fromVariant(attachModelVariant);
648 649 650 651 652
	if (attachModel == Q_NULLPTR) {
		Q_ASSERT(0);
		return;
	}

653
	QString targetPath(appMsgAttachDirPath(msgIdStr));
654 655 656 657

	QString destPath;
	for (int row = 0; row < attachModel->rowCount(); ++row) {
		QModelIndex idx(attachModel->index(row));
658 659
		destPath = writeFile(targetPath, attachModel->data(idx,
		    FileListModel::ROLE_FILE_NAME).toString(),
660
		    base64ToRaw(attachModel->data(idx,
661
		    FileListModel::ROLE_FILE_DATA).toByteArray()));
662 663 664 665 666
	}

	attachmentSavingNotification(destPath);
}

667 668 669 670 671 672 673
void Files::deleteTmpFileFromStorage(const QString &filePath)
{
#if defined Q_OS_IOS
	QFile file(filePath);
	file.remove();
#else
	Q_UNUSED(filePath);
674
#endif
675 676
}

677 678 679
void Files::sendEmail(const QString &emailMessage, const QStringList &fileList,
    const QString &subject, const QString &body, qint64 msgId)
{
680 681 682 683
	Q_UNUSED(subject);
	Q_UNUSED(body);
	Q_UNUSED(emailMessage);
	Q_UNUSED(msgId);
684
	Q_UNUSED(fileList);
685 686

#if defined Q_OS_IOS
687 688 689 690

	UrlOpener urlOpener;
	urlOpener.createEmail(body, subject, fileList);

691
#elif defined Q_OS_ANDROID
692 693 694 695

	QDesktopServices::openUrl(QUrl("mailto:?subject=" + subject +
	    "&body=" + body));

696 697
#else

698
	QString tmpEmailFile = writeFile(
699
	    appEmailDirPath(QString::number(msgId)),
700 701 702 703
	    QString::number(msgId) + "_mail.eml", emailMessage.toUtf8());
	QDesktopServices::openUrl(QUrl::fromLocalFile(tmpEmailFile));

#endif
704 705
}

706
QByteArray Files::getXmlFromCms(const QByteArray &rawData)
707 708 709
{
	qDebug("%s()", __func__);

710 711 712
	if (rawData.isEmpty()) {
		Q_ASSERT(0);
		qCritical() << "File content is empty!";
713 714 715
		return QByteArray();
	}

716
	/* Decode CMS and obtain message XML data - uses OpenSSL. */
Martin Straka's avatar
Martin Straka committed
717
	void *xmlContent = Q_NULLPTR;
718
	size_t xmlContentLen = 0;
719
	if (extract_cms_data(rawData.data(), rawData.length(), &xmlContent,
Martin Straka's avatar
Martin Straka committed
720
	        &xmlContentLen) != 0) {
721 722 723
		return QByteArray();
	}
	if (xmlContentLen == 0) {
Martin Straka's avatar
Martin Straka committed
724
		free(xmlContent); xmlContent = Q_NULLPTR;
725 726 727
		return QByteArray();
	}

728
	QByteArray soap((char *)xmlContent, xmlContentLen);
Martin Straka's avatar
Martin Straka committed
729
	free(xmlContent); xmlContent = Q_NULLPTR;
730 731 732 733

	return soap;
}

734
QByteArray Files::decodeZfoFile(const QByteArray &base64ZfoData)
Martin Straka's avatar
Martin Straka committed
735 736 737
{
	qDebug("%s()", __func__);

738 739 740
	if (base64ZfoData.isEmpty()) {
		Q_ASSERT(0);
		qCritical() << "File content is empty.";
Martin Straka's avatar
Martin Straka committed
741 742 743
		return QByteArray();
	}

744
	/* decode signature from base64 and obtain something CMS message */
745
	return getXmlFromCms(base64ToRaw(base64ZfoData));
Martin Straka's avatar
Martin Straka committed
746 747
}

748
bool Files::parseXmlData(enum MsgInfo::ZfoType *type, QString *idStr,
749 750
    QString *annotation, QString *msgDescrHtml, FileListModel *attachModel,
    QString *emailBody, QByteArray xmlData)
751 752 753
{
	qDebug("%s()", __func__);

754 755
	if (xmlData.isEmpty()) {
		qCritical() << "XML content is empty!";
756
		return false;
757 758
	}

759
	xmlData.prepend("<?xml version='1.0' encoding='utf-8'?>"
760 761 762 763
	      "<SOAP-ENV:Envelope "
	      "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" "
	      "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">"
	      "<SOAP-ENV:Body>");
764
	xmlData.append("</SOAP-ENV:Body></SOAP-ENV:Envelope>");
765

766
	/* Test if zfo is message, delivery info or unknown format */
767
	if (xmlData.contains(QByteArray("MessageDownloadResponse"))) {
768 769
		if (type != Q_NULLPTR) {
			*type = MsgInfo::TYPE_MESSAGE;
770
		}
771 772
		return parseAndShowXmlData(MsgInfo::TYPE_MESSAGE, idStr,
		    annotation, msgDescrHtml, attachModel, emailBody, xmlData);
773
	} else if (xmlData.contains(QByteArray("GetDeliveryInfoResponse"))) {
774 775
		if (type != Q_NULLPTR) {
			*type = MsgInfo::TYPE_DELIVERY_INFO;
776
		}
777 778
		return parseAndShowXmlData(MsgInfo::TYPE_DELIVERY_INFO, idStr,
		    annotation, msgDescrHtml, attachModel, emailBody, xmlData);
779
	} else {
780 781 782 783
		if (type != Q_NULLPTR) {
			*type = MsgInfo::TYPE_UNKNOWN;
		}
		qCritical() << "Unknown ZFO format";
784 785
	}

786
	return false;
787 788
}

789
bool Files::parseAndShowXmlData(enum MsgInfo::ZfoType type, QString *idStr,
790 791
    QString *annotation, QString *msgDescrHtml, FileListModel *attachModel,
    QString *emailBody, QByteArray &xmlData)
792 793 794
{
	qDebug("%s()", __func__);

795
	QXmlStreamReader xml;
796
	MsgEnvelope msg;
797
	QList<AttachmentData> fileList;
798
	QList<Messages::Event> eventList;
799

800 801 802 803 804
	if (type == MsgInfo::TYPE_UNKNOWN) {
		Q_ASSERT(0);
		return false;
	}

805 806
	/* parse message envelope and files */
	xml.addData(xmlData);
807 808 809
	while(!xml.atEnd() && !xml.hasError()) {
		QXmlStreamReader::TokenType token = xml.readNext();
		if (xml.error() != QXmlStreamReader::NoError) {
810
			return false;
811 812 813 814 815 816
		}
		if (token == QXmlStreamReader::StartDocument) {
			continue;
		}
		if (token == QXmlStreamReader::StartElement) {
			if (xml.name() == "dmDm") {
817
				XmlLayer::completeMessageParse(xml, msg, fileList);
818 819 820 821
			}
		}
	}

822
	if (type == MsgInfo::TYPE_DELIVERY_INFO) {
823 824 825 826 827 828 829 830 831 832
		/* parse delivery info */
		xml.clear();
		xml.addData(xmlData);
		while(!xml.atEnd() && !xml.hasError()){
			QXmlStreamReader::TokenType token = xml.readNext();
			if (token == QXmlStreamReader::StartDocument) {
				continue;
			}
			if (token == QXmlStreamReader::StartElement) {
				if (xml.name() == "dmEvent") {
833
					eventList.append(XmlLayer::parseEvent(xml));
834 835 836
				}
			}
		}
837 838 839 840
	}

	QString html = divStart;

841 842
	html += "<h3>" + tr("General") + "</h3>";
	html += strongInfoLine(tr("Subject"), msg.dmAnnotation());
843
	QString size = QString::number(msg.dmAttachmentSize());
844
	html += strongInfoLine(tr("Attachment size"),
845
	    (size == "0") ? "&lt;1 kB" : "~" + size + " kB");
846 847 848 849 850 851 852 853 854 855 856 857 858 859
	html += strongInfoLine(tr("Personal delivery"),
	    (msg.dmPersonalDelivery()) ? tr("Yes") : tr("No"));
	html += strongInfoLine(tr("Delivery by fiction"),
	    (msg.dmAllowSubstDelivery()) ? tr("Yes") : tr("No"));

	html += "<h3>" + tr("Sender") + "</h3>";
	html += strongInfoLine(tr("Databox ID"), msg.dbIDSender());
	html += strongInfoLine(tr("Name"), msg.dmSender());
	html += strongInfoLine(tr("Address"),msg.dmSenderAddress());

	html += "<h3>" + tr("Recipient") + "</h3>";
	html += strongInfoLine(tr("Databox ID"), msg.dbIDRecipient());
	html += strongInfoLine(tr("Name"), msg.dmRecipient());
	html += strongInfoLine(tr("Address"),msg.dmRecipientAddress());
860
	if (!msg.dmToHands().isEmpty()) {
861
		html += strongInfoLine(tr("To hands"), msg.dmToHands());
862
	}
863

864
	QString tmpHtml;
865
	if (!msg.dmSenderIdent().isEmpty()) {
866
		tmpHtml += strongInfoLine(tr("Our file mark"),
867
		    msg.dmSenderIdent());
868
	}
869
	if (!msg.dmSenderRefNumber().isEmpty()) {
870
		tmpHtml += strongInfoLine(tr("Our reference number"),
871
		    msg.dmSenderRefNumber());
872
	}
873
	if (!msg.dmRecipientIdent().isEmpty()) {
874
		tmpHtml += strongInfoLine(tr("Your file mark"),
875
		    msg.dmRecipientIdent());
876
	}
877
	if (!msg.dmRecipientRefNumber().isEmpty()) {
878
		tmpHtml += strongInfoLine(tr("Your reference number"),
879
		    msg.dmRecipientRefNumber());
880
	}
881
	if (!msg.dmLegalTitleLaw().isEmpty()) {
882
		tmpHtml += strongInfoLine(tr("Law"), msg.dmLegalTitleLaw());
883
	}
884
	if (!msg.dmLegalTitleYear().isEmpty()) {
885
		tmpHtml += strongInfoLine(tr("Year"), msg.dmLegalTitleYear());
886
	}
887
	if (!msg.dmLegalTitleSect().isEmpty()) {
888
		tmpHtml += strongInfoLine(tr("Section"), msg.dmLegalTitleSect());
889
	}
890
	if (!msg.dmLegalTitlePar().isEmpty()) {
891
		tmpHtml += strongInfoLine(tr("Paragraph"),
892
		    msg.dmLegalTitlePar());
893
	}
894
	if (!msg.dmLegalTitlePoint().isEmpty()) {
895
		tmpHtml += strongInfoLine(tr("Letter"), msg.dmLegalTitlePoint());
896 897
	}
	if (!tmpHtml.isEmpty()) {
898
		html += "<h3>" + tr("Additional info") + "</h3>";
899 900
		html += tmpHtml;
	}
901

902 903
	html += "<h3>" + tr("Message state") + "</h3>";
	html += strongInfoLine(tr("Delivery time"),
904
	    dateTimeStrFromDbFormat(
905
	        dateTimeStrToUTCDbFormat(msg.dmDeliveryTime()),
906
	        DATETIME_QML_FORMAT));
907
	html += strongInfoLine(tr("Accetance time"),
908
	    dateTimeStrFromDbFormat(
909
	        dateTimeStrToUTCDbFormat(msg.dmAcceptanceTime()),
910
	        DATETIME_QML_FORMAT));
911
	html += strongInfoLine(tr("Status"),
912
	    QString::number(msg.dmMessageStatus()));
913

914
	if (type == MsgInfo::TYPE_DELIVERY_INFO) {
915
		html += "<h3>" + tr("Events") + "</h3>";
916 917 918 919 920 921 922 923 924
		foreach (const Messages::Event &event, eventList) {
			html += divStart +
			    strongInfoLine(dateTimeStrFromDbFormat(
			        dateTimeStrToUTCDbFormat(event.dmEventTime),
			        DATETIME_QML_FORMAT), event.dmEventDescr)
			    + divEnd;
		}
	}

925 926
	html += divEnd;

927
	// Create body for email
928 929 930 931
	QString body = generateEmailBodyText(msg.dmID(), msg.dmSender(),
	    msg.dmRecipient(), dateTimeStrFromDbFormat(
	    dateTimeStrToUTCDbFormat(msg.dmAcceptanceTime()),
	    DATETIME_QML_FORMAT));
932

933
	if (idStr != Q_NULLPTR) {
934
		*idStr = QString::number(msg.dmID());
935
	}
936
	if (annotation != Q_NULLPTR) {
937
		*annotation = msg.dmAnnotation();
938 939 940 941 942
	}
	if (msgDescrHtml != Q_NULLPTR) {
		*msgDescrHtml = html;
	}
	if (attachModel != Q_NULLPTR) {
943 944
		attachModel->clearAll();
		foreach (const AttachmentData &file, fileList) {
Martin Straka's avatar
Martin Straka committed
945 946 947 948
			attachModel->appendFileEntry(
			    FileListModel::Entry(-1, file.dmFileDescr(),
			    file._dmFileSize(), file._icon(),
			    file.dmEncodedContent(), QString()));
949
		}
950 951 952 953
	}
	if (emailBody != Q_NULLPTR) {
		*emailBody = body;
	}
954

955 956
	return true;
}