main-db.cpp 97.9 KB
Newer Older
Ronan's avatar
Ronan committed
1
/*
2
 * main-db.cpp
3
 * Copyright (C) 2010-2018 Belledonne Communications SARL
Ronan's avatar
Ronan committed
4
 *
Ghislain MARY's avatar
Ghislain MARY committed
5 6 7 8
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
Ronan's avatar
Ronan committed
9 10 11 12 13 14 15
 *
 * 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
Ghislain MARY's avatar
Ghislain MARY committed
16 17
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Ronan's avatar
Ronan committed
18 19
 */

20
#include <ctime>
21

22
#include "linphone/utils/algorithm.h"
23 24
#include "linphone/utils/utils.h"

Ronan's avatar
Ronan committed
25
#include "chat/chat-message/chat-message-p.h"
26
#include "chat/chat-room/chat-room-p.h"
27
#include "chat/chat-room/client-group-chat-room.h"
28
#include "chat/chat-room/server-group-chat-room.h"
29
#include "conference/participant-p.h"
30
#include "content/content-type.h"
31
#include "content/content.h"
32
#include "core/core-p.h"
33
#include "event-log/event-log-p.h"
34
#include "event-log/events.h"
35
#include "logger/logger.h"
36
#include "main-db-key-p.h"
37
#include "main-db-p.h"
Ronan's avatar
Ronan committed
38

39 40 41 42 43
#ifdef SOCI_ENABLED
	#include "internal/safe-transaction.h"
	#include "internal/statements.h"
#endif // ifdef SOCI_ENABLED

Ronan's avatar
Ronan committed
44 45
// =============================================================================

46 47 48 49 50
// See: http://soci.sourceforge.net/doc/3.2/exchange.html
// Part: Object lifetime and immutability

// -----------------------------------------------------------------------------

51 52
using namespace std;

Ronan's avatar
Ronan committed
53 54
LINPHONE_BEGIN_NAMESPACE

55 56 57 58 59
namespace {
	constexpr unsigned int ModuleVersionEvents = makeVersion(1, 0, 1);
	constexpr unsigned int ModuleVersionFriends = makeVersion(1, 0, 0);
	constexpr unsigned int ModuleVersionLegacyFriendsImport = makeVersion(1, 0, 0);
	constexpr unsigned int ModuleVersionLegacyHistoryImport = makeVersion(1, 0, 0);
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

	constexpr int LegacyFriendListColId = 0;
	constexpr int LegacyFriendListColName = 1;
	constexpr int LegacyFriendListColRlsUri = 2;
	constexpr int LegacyFriendListColSyncUri = 3;
	constexpr int LegacyFriendListColRevision = 4;

	constexpr int LegacyFriendColFriendListId = 1;
	constexpr int LegacyFriendColSipAddress = 2;
	constexpr int LegacyFriendColSubscribePolicy = 3;
	constexpr int LegacyFriendColSendSubscribe = 4;
	constexpr int LegacyFriendColRefKey = 5;
	constexpr int LegacyFriendColVCard = 6;
	constexpr int LegacyFriendColVCardEtag = 7;
	constexpr int LegacyFriendColVCardSyncUri = 8;
	constexpr int LegacyFriendColPresenceReceived = 9;

	constexpr int LegacyMessageColLocalAddress = 1;
	constexpr int LegacyMessageColRemoteAddress = 2;
	constexpr int LegacyMessageColDirection = 3;
	constexpr int LegacyMessageColText = 4;
	constexpr int LegacyMessageColState = 7;
	constexpr int LegacyMessageColUrl = 8;
	constexpr int LegacyMessageColDate = 9;
	constexpr int LegacyMessageColAppData = 10;
	constexpr int LegacyMessageColContentId = 11;
	constexpr int LegacyMessageColContentType = 13;
	constexpr int LegacyMessageColIsSecured = 14;
88 89
}

Ronan's avatar
Ronan committed
90 91
// -----------------------------------------------------------------------------

92
MainDb::MainDb (const shared_ptr<Core> &core) : AbstractDb(*new MainDbPrivate), CoreAccessor(core) {}
Ronan's avatar
Ronan committed
93

94 95
#ifdef SOCI_ENABLED

96
// -----------------------------------------------------------------------------
97
// Soci backend.
98 99
// -----------------------------------------------------------------------------

100 101 102 103 104 105 106 107 108 109 110 111
template<typename T>
struct EnumToSql {
	T first;
	const char *second;
};

template<typename T>
static constexpr const char *mapEnumToSql (const EnumToSql<T> enumToSql[], size_t n, T key) {
	return n == 0 ? "" : (
		enumToSql[n - 1].first == key ? enumToSql[n - 1].second : mapEnumToSql(enumToSql, n - 1, key)
	);
}
112

113
// Update me event-log-enums values are changed!
114 115 116
static constexpr EnumToSql<MainDb::Filter> eventFilterToSql[] = {
	{ MainDb::ConferenceCallFilter, "3, 4" },
	{ MainDb::ConferenceChatMessageFilter, "5" },
117 118
	{ MainDb::ConferenceInfoFilter, "1, 2, 6, 7, 8, 9, 10, 11, 12" },
	{ MainDb::ConferenceInfoNoDeviceFilter, "1, 2, 6, 7, 8, 9, 12" }
119
};
120

121 122 123 124 125
static constexpr const char *mapEventFilterToSql (MainDb::Filter filter) {
	return mapEnumToSql(
		eventFilterToSql, sizeof eventFilterToSql / sizeof eventFilterToSql[0], filter
	);
}
126

127 128
// -----------------------------------------------------------------------------

129 130 131 132 133
static string buildSqlEventFilter (
	const list<MainDb::Filter> &filters,
	MainDb::FilterMask mask,
	const string &condKeyWord = "WHERE"
) {
134
	L_ASSERT(findIf(filters, [](const MainDb::Filter &filter) { return filter == MainDb::NoFilter; }) == filters.cend());
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

	if (mask == MainDb::NoFilter)
		return "";

	bool isStart = true;
	string sql;
	for (const auto &filter : filters) {
		if (!mask.isSet(filter))
			continue;

		if (isStart) {
			isStart = false;
			sql += " " + condKeyWord + " type IN (";
		} else
			sql += ", ";
		sql += mapEventFilterToSql(filter);
	}

	if (!isStart)
		sql += ") ";

	return sql;
}
158

159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
// -----------------------------------------------------------------------------

static inline vector<char> blobToVector (soci::blob &in) {
	size_t len = in.get_len();
	if (!len)
		return vector<char>();
	vector<char> out(len);
	in.read(0, &out[0], len);
	return out;
}

static inline string blobToString (soci::blob &in) {
	vector<char> out = blobToVector(in);
	return string(out.begin(), out.end());
}

175 176 177 178
static constexpr string &blobToString (string &in) {
	return in;
}

179 180 181 182 183 184 185 186 187 188 189 190 191
// -----------------------------------------------------------------------------
// Statements and helpers.
// -----------------------------------------------------------------------------

class StatementBind {
public:
	StatementBind (soci::statement &stmt) : mStmt(stmt) {}

	~StatementBind () {
		mStmt.bind_clean_up();
	}

	template<typename T>
192 193
	void bind (const T &var) {
		mStmt.exchange(soci::use(var));
194 195 196
	}

	template<typename T>
197
	void bindResult (T &var) {
198
		mStmt.exchange(soci::into(var));
199 200 201
	}

	bool exec () {
202
		mStmt.define_and_bind();
203 204 205 206 207 208 209 210 211 212 213
		return mStmt.execute(true);
	}

private:
	soci::statement &mStmt;
};

static inline unique_ptr<soci::statement> makeStatement (soci::session &session, const char *stmt) {
	return makeUnique<soci::statement>(session.prepare << stmt);
}

214
struct MainDbPrivate::PreparedStatements {
215 216
	typedef unique_ptr<soci::statement> Statement;

217
	Statement select[Statements::SelectCount];
218
	Statement insert[Statements::InsertCount];
219 220
};

221 222 223
void MainDbPrivate::initPreparedStatements () {
	L_Q();

224
	soci::session *session = dbSession.getBackendSession();
225
	AbstractDb::Backend backend = q->getBackend();
226

227 228 229
	preparedStatements = makeUnique<PreparedStatements>();
	for (int i = 0; i < int(Statements::SelectCount); ++i)
		preparedStatements->select[i] = makeStatement(*session, Statements::get(Statements::Select(i), backend));
230 231
	for (int i = 0; i < int(Statements::InsertCount); ++i)
		preparedStatements->insert[i] = makeStatement(*session, Statements::get(Statements::Insert(i), backend));
232 233
}

234 235
// -----------------------------------------------------------------------------

236
long long MainDbPrivate::insertSipAddress (const string &sipAddress) {
237
	soci::session *session = dbSession.getBackendSession();
238

239 240 241
	long long id = selectSipAddressId(sipAddress);
	if (id >= 0)
		return id;
242

243 244
	lInfo() << "Insert new sip address in database: `" << sipAddress << "`.";
	*session << "INSERT INTO sip_address (value) VALUES (:sipAddress)", soci::use(sipAddress);
245
	return dbSession.getLastInsertId();
246
}
247

248
void MainDbPrivate::insertContent (long long eventId, const Content &content) {
249
	soci::session *session = dbSession.getBackendSession();
250 251 252 253 254 255 256

	const long long &contentTypeId = insertContentType(content.getContentType().asString());
	const string &body = content.getBodyAsString();
	*session << "INSERT INTO chat_message_content (event_id, content_type_id, body) VALUES"
		" (:eventId, :contentTypeId, :body)", soci::use(eventId), soci::use(contentTypeId),
		soci::use(body);

257
	const long long &chatMessageContentId = dbSession.getLastInsertId();
258
	if (content.isFile()) {
259 260 261 262 263 264 265 266 267 268 269 270 271 272
		const FileContent &fileContent = static_cast<const FileContent &>(content);
		const string &name = fileContent.getFileName();
		const size_t &size = fileContent.getFileSize();
		const string &path = fileContent.getFilePath();
		*session << "INSERT INTO chat_message_file_content (chat_message_content_id, name, size, path) VALUES "
			" (:chatMessageContentId, :name, :size, :path)",
			soci::use(chatMessageContentId), soci::use(name), soci::use(size), soci::use(path);
	}

	for (const auto &appData : content.getAppDataMap())
		*session << "INSERT INTO chat_message_content_app_data (chat_message_content_id, name, data) VALUES"
			" (:chatMessageContentId, :name, :data)",
			soci::use(chatMessageContentId), soci::use(appData.first), soci::use(appData.second);
}
273

274
long long MainDbPrivate::insertContentType (const string &contentType) {
275
	soci::session *session = dbSession.getBackendSession();
276

277 278 279 280
	long long id;
	*session << "SELECT id FROM content_type WHERE value = :contentType", soci::use(contentType), soci::into(id);
	if (session->got_data())
		return id;
281

282 283
	lInfo() << "Insert new content type in database: `" << contentType << "`.";
	*session << "INSERT INTO content_type (value) VALUES (:contentType)", soci::use(contentType);
284
	return dbSession.getLastInsertId();
285 286 287 288 289 290 291
}

long long MainDbPrivate::insertOrUpdateImportedBasicChatRoom (
	long long peerSipAddressId,
	long long localSipAddressId,
	const tm &creationTime
) {
292
	soci::session *session = dbSession.getBackendSession();
293

294 295 296 297 298
	long long id = selectChatRoomId(peerSipAddressId, localSipAddressId);
	if (id >= 0) {
		*session << "UPDATE chat_room SET last_update_time = :lastUpdateTime WHERE id = :id",
			soci::use(creationTime), soci::use(id);
		return id;
299 300
	}

301 302 303 304 305 306 307 308 309 310
	static const int capabilities = ChatRoom::CapabilitiesMask(
		{ ChatRoom::Capabilities::Basic, ChatRoom::Capabilities::Migratable }
	);
	lInfo() << "Insert new chat room in database: (peer=" << peerSipAddressId <<
		", local=" << localSipAddressId << ", capabilities=" << capabilities << ").";
	*session << "INSERT INTO chat_room ("
		"  peer_sip_address_id, local_sip_address_id, creation_time, last_update_time, capabilities"
		") VALUES (:peerSipAddressId, :localSipAddressId, :creationTime, :lastUpdateTime, :capabilities)",
		soci::use(peerSipAddressId), soci::use(localSipAddressId), soci::use(creationTime), soci::use(creationTime),
		soci::use(capabilities);
311

312
	return dbSession.getLastInsertId();
313
}
314

315
long long MainDbPrivate::insertChatRoom (const shared_ptr<AbstractChatRoom> &chatRoom) {
316
	soci::session *session = dbSession.getBackendSession();
317

318 319 320
	const ChatRoomId &chatRoomId = chatRoom->getChatRoomId();
	const long long &peerSipAddressId = insertSipAddress(chatRoomId.getPeerAddress().asString());
	const long long &localSipAddressId = insertSipAddress(chatRoomId.getLocalAddress().asString());
321

322 323 324 325 326 327
	long long id = selectChatRoomId(peerSipAddressId, localSipAddressId);
	if (id >= 0) {
		lError() << "Unable to insert chat room (it already exists): (peer=" << peerSipAddressId <<
			", local=" << localSipAddressId << ").";
		return id;
	}
328

329 330
	lInfo() << "Insert new chat room in database: (peer=" << peerSipAddressId <<
		", local=" << localSipAddressId << ").";
331

332 333
	const tm &creationTime = Utils::getTimeTAsTm(chatRoom->getCreationTime());
	// Remove capabilities like `Proxy`.
334
	const int &capabilities = chatRoom->getCapabilities() & ~ChatRoom::CapabilitiesMask(ChatRoom::Capabilities::Proxy);
335

336 337 338 339 340 341 342
	const string &subject = chatRoom->getSubject();
	const int &flags = chatRoom->hasBeenLeft();
	*session << "INSERT INTO chat_room ("
		"  peer_sip_address_id, local_sip_address_id, creation_time, last_update_time, capabilities, subject, flags"
		") VALUES (:peerSipAddressId, :localSipAddressId, :creationTime, :lastUpdateTime, :capabilities, :subject, :flags)",
		soci::use(peerSipAddressId), soci::use(localSipAddressId), soci::use(creationTime), soci::use(creationTime),
		soci::use(capabilities), soci::use(subject), soci::use(flags);
343

344
	id = dbSession.getLastInsertId();
345 346
	if (!chatRoom->canHandleParticipants())
		return id;
347

348 349 350 351 352 353 354 355 356 357 358
	// Do not add 'me' when creating a server-group-chat-room.
	if (chatRoomId.getLocalAddress() != chatRoomId.getPeerAddress()) {
		shared_ptr<Participant> me = chatRoom->getMe();
		long long meId = insertChatRoomParticipant(
			id,
			insertSipAddress(me->getAddress().asString()),
			me->isAdmin()
		);
		for (const auto &device : me->getPrivate()->getDevices())
			insertChatRoomParticipantDevice(meId, insertSipAddress(device->getAddress().asString()));
	}
359

360 361 362 363 364 365 366 367
	for (const auto &participant : chatRoom->getParticipants()) {
		long long participantId = insertChatRoomParticipant(
			id,
			insertSipAddress(participant->getAddress().asString()),
			participant->isAdmin()
		);
		for (const auto &device : participant->getPrivate()->getDevices())
			insertChatRoomParticipantDevice(participantId, insertSipAddress(device->getAddress().asString()));
368 369
	}

370 371
	return id;
}
372

373 374 375 376 377
long long MainDbPrivate::insertChatRoomParticipant (
	long long chatRoomId,
	long long participantSipAddressId,
	bool isAdmin
) {
378
	soci::session *session = dbSession.getBackendSession();
379 380 381 382 383 384 385
	long long id = selectChatRoomParticipantId(chatRoomId, participantSipAddressId);
	if (id >= 0) {
		// See: https://stackoverflow.com/a/15299655 (cast to reference)
		*session << "UPDATE chat_room_participant SET is_admin = :isAdmin WHERE id = :id",
			soci::use(static_cast<const int &>(isAdmin)), soci::use(id);
		return id;
	}
386

387 388 389 390 391
	lInfo() << "Insert new chat room participant in database: `" << participantSipAddressId <<
		"` (isAdmin=" << isAdmin << ").";
	*session << "INSERT INTO chat_room_participant (chat_room_id, participant_sip_address_id, is_admin)"
		" VALUES (:chatRoomId, :participantSipAddressId, :isAdmin)",
		soci::use(chatRoomId), soci::use(participantSipAddressId), soci::use(static_cast<const int &>(isAdmin));
392

393
	return dbSession.getLastInsertId();
394
}
395

396 397 398 399
void MainDbPrivate::insertChatRoomParticipantDevice (
	long long participantId,
	long long participantDeviceSipAddressId
) {
400
	soci::session *session = dbSession.getBackendSession();
401 402 403 404 405 406 407 408 409 410 411 412 413
	long long count;
	*session << "SELECT COUNT(*) FROM chat_room_participant_device"
		" WHERE chat_room_participant_id = :participantId"
		" AND participant_device_sip_address_id = :participantDeviceSipAddressId",
		soci::into(count), soci::use(participantId), soci::use(participantDeviceSipAddressId);
	if (count)
		return;

	lInfo() << "Insert new chat room participant device in database: `" << participantDeviceSipAddressId << "`.";
	*session << "INSERT INTO chat_room_participant_device (chat_room_participant_id, participant_device_sip_address_id)"
		" VALUES (:participantId, :participantDeviceSipAddressId)",
		soci::use(participantId), soci::use(participantDeviceSipAddressId);
}
414

415
void MainDbPrivate::insertChatMessageParticipant (long long eventId, long long sipAddressId, int state) {
416 417
	if (state != static_cast<int>(ChatMessage::State::Displayed)) {
		soci::session *session = dbSession.getBackendSession();
418 419 420
		*session << "INSERT INTO chat_message_participant (event_id, participant_sip_address_id, state)"
			" VALUES (:eventId, :sipAddressId, :state)",
			soci::use(eventId), soci::use(sipAddressId), soci::use(state);
421
	}
422
}
423

424 425
// -----------------------------------------------------------------------------

426 427
long long MainDbPrivate::selectSipAddressId (const string &sipAddress) const {
	long long id;
428

429 430
	StatementBind stmt(*preparedStatements->select[Statements::SelectSipAddressId]);
	stmt.bind(sipAddress);
431 432 433
	stmt.bindResult(id);

	return stmt.exec() ? id : -1;
434
}
435

436 437
long long MainDbPrivate::selectChatRoomId (long long peerSipAddressId, long long localSipAddressId) const {
	long long id;
438

439 440 441
	StatementBind stmt(*preparedStatements->select[Statements::SelectChatRoomId]);
	stmt.bind(peerSipAddressId);
	stmt.bind(localSipAddressId);
442 443 444
	stmt.bindResult(id);

	return stmt.exec() ? id : -1;
445
}
446

447 448 449 450
long long MainDbPrivate::selectChatRoomId (const ChatRoomId &chatRoomId) const {
	long long peerSipAddressId = selectSipAddressId(chatRoomId.getPeerAddress().asString());
	if (peerSipAddressId < 0)
		return -1;
451

452 453 454
	long long localSipAddressId = selectSipAddressId(chatRoomId.getLocalAddress().asString());
	if (localSipAddressId < 0)
		return -1;
455

456 457
	return selectChatRoomId(peerSipAddressId, localSipAddressId);
}
458

459 460
long long MainDbPrivate::selectChatRoomParticipantId (long long chatRoomId, long long participantSipAddressId) const {
	long long id;
461 462 463 464 465 466 467

	StatementBind stmt(*preparedStatements->select[Statements::SelectChatRoomParticipantId]);
	stmt.bind(chatRoomId);
	stmt.bind(participantSipAddressId);
	stmt.bindResult(id);

	return stmt.exec() ? id : -1;
468
}
469

470 471
long long MainDbPrivate::selectOneToOneChatRoomId (long long sipAddressIdA, long long sipAddressIdB) const {
	long long id;
472 473 474 475 476 477 478 479 480

	StatementBind stmt(*preparedStatements->select[Statements::SelectOneToOneChatRoomId]);
	stmt.bind(sipAddressIdA);
	stmt.bind(sipAddressIdB);
	stmt.bind(sipAddressIdA);
	stmt.bind(sipAddressIdB);
	stmt.bindResult(id);

	return stmt.exec() ? id : -1;
481 482
}

483 484
// -----------------------------------------------------------------------------

485
void MainDbPrivate::deleteContents (long long messageEventId) {
486
	soci::session *session = dbSession.getBackendSession();
487 488
	*session << "DELETE FROM chat_message_content WHERE event_id = :messageEventId", soci::use(messageEventId);
}
489

490
void MainDbPrivate::deleteChatRoomParticipant (long long chatRoomId, long long participantSipAddressId) {
491
	soci::session *session = dbSession.getBackendSession();
492 493 494 495
	*session << "DELETE FROM chat_room_participant"
		"  WHERE chat_room_id = :chatRoomId AND participant_sip_address_id = :participantSipAddressId",
		soci::use(chatRoomId), soci::use(participantSipAddressId);
}
496

497 498 499 500
void MainDbPrivate::deleteChatRoomParticipantDevice (
	long long participantId,
	long long participantDeviceSipAddressId
) {
501
	soci::session *session = dbSession.getBackendSession();
502 503 504 505 506
	*session << "DELETE FROM chat_room_participant_device"
		"  WHERE chat_room_participant_id = :participantId"
		"  AND participant_device_sip_address_id = :participantDeviceSipAddressId",
		soci::use(participantId), soci::use(participantDeviceSipAddressId);
}
507

Ronan's avatar
Ronan committed
508 509
// -----------------------------------------------------------------------------

510 511 512 513 514 515 516 517 518 519 520
shared_ptr<EventLog> MainDbPrivate::selectGenericConferenceEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	shared_ptr<EventLog> eventLog;

	switch (type) {
		case EventLog::Type::None:
			return nullptr;
521

522 523 524 525
		case EventLog::Type::ConferenceCreated:
		case EventLog::Type::ConferenceTerminated:
			eventLog = selectConferenceEvent(eventId, type, creationTime, chatRoomId);
			break;
Ronan's avatar
Ronan committed
526

527 528 529 530
		case EventLog::Type::ConferenceCallStart:
		case EventLog::Type::ConferenceCallEnd:
			eventLog = selectConferenceCallEvent(eventId, type, creationTime, chatRoomId);
			break;
Ronan's avatar
Ronan committed
531

532 533 534
		case EventLog::Type::ConferenceChatMessage:
			eventLog = selectConferenceChatMessageEvent(eventId, type, creationTime, chatRoomId);
			break;
Ronan's avatar
Ronan committed
535

536 537 538 539 540 541
		case EventLog::Type::ConferenceParticipantAdded:
		case EventLog::Type::ConferenceParticipantRemoved:
		case EventLog::Type::ConferenceParticipantSetAdmin:
		case EventLog::Type::ConferenceParticipantUnsetAdmin:
			eventLog = selectConferenceParticipantEvent(eventId, type, creationTime, chatRoomId);
			break;
Ronan's avatar
Ronan committed
542

543 544 545 546
		case EventLog::Type::ConferenceParticipantDeviceAdded:
		case EventLog::Type::ConferenceParticipantDeviceRemoved:
			eventLog = selectConferenceParticipantDeviceEvent(eventId, type, creationTime, chatRoomId);
			break;
547

548 549 550
		case EventLog::Type::ConferenceSubjectChanged:
			eventLog = selectConferenceSubjectEvent(eventId, type, creationTime, chatRoomId);
			break;
551 552
	}

553 554
	if (eventLog)
		cache(eventLog, eventId);
Ronan's avatar
Ronan committed
555

556 557
	return eventLog;
}
Ronan's avatar
Ronan committed
558

559 560 561 562 563 564 565 566 567 568 569 570
shared_ptr<EventLog> MainDbPrivate::selectConferenceEvent (
	long long,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	return make_shared<ConferenceEvent>(
		type,
		creationTime,
		chatRoomId
	);
}
571

572 573 574 575 576 577 578 579 580
shared_ptr<EventLog> MainDbPrivate::selectConferenceCallEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	// TODO.
	return nullptr;
}
Ronan's avatar
Ronan committed
581

582 583 584 585
template<typename T>
static void fetchContentAppData (soci::session *session, Content &content, long long contentId, T &data) {
	static const string query = "SELECT name, data FROM chat_message_content_app_data"
		" WHERE chat_message_content_id = :contentId";
586

587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
	string name;
	soci::statement statement = (session->prepare << query, soci::use(contentId), soci::into(name), soci::into(data));
	statement.execute();
	while (statement.fetch())
		content.setAppData(name, blobToString(data));
}

shared_ptr<EventLog> MainDbPrivate::selectConferenceChatMessageEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	L_Q();

602 603 604 605 606 607
	shared_ptr<Core> core = q->getCore();
	shared_ptr<AbstractChatRoom> chatRoom = core->findChatRoom(chatRoomId);
	if (!chatRoom) {
		lError() << "Unable to find chat room storage id of (peer=" +
			chatRoomId.getPeerAddress().asString() +
			", local=" + chatRoomId.getLocalAddress().asString() + "`).";
608
		return nullptr;
609 610
	}

611
	shared_ptr<ChatMessage> chatMessage = getChatMessageFromCache(eventId);
612
	if (!chatMessage) {
613 614
		string fromSipAddress;
		string toSipAddress;
615

616 617 618
		tm messageTime;

		string imdnMessageId;
Ronan's avatar
Ronan committed
619

620 621 622
		int state;
		int direction;
		int isSecured;
623

624 625 626 627 628 629 630 631 632
		soci::session *session = dbSession.getBackendSession();
		*session << "SELECT from_sip_address.value, to_sip_address.value, time, imdn_message_id, state, direction, is_secured"
			" FROM event, conference_chat_message_event, sip_address AS from_sip_address, sip_address AS to_sip_address"
			" WHERE event_id = :eventId"
			" AND event_id = event.id"
			" AND from_sip_address_id = from_sip_address.id"
			" AND to_sip_address_id = to_sip_address.id", soci::into(fromSipAddress), soci::into(toSipAddress),
			soci::into(messageTime), soci::into(imdnMessageId), soci::into(state), soci::into(direction),
			soci::into(isSecured), soci::use(eventId);
633

634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
		return selectConferenceChatMessageEvent (
			eventId,
			type,
			creationTime,
			chatRoom,
			fromSipAddress,
			toSipAddress,
			messageTime,
			imdnMessageId,
			state,
			direction,
			isSecured
		);
	}

	return make_shared<ConferenceChatMessageEvent>(
		creationTime,
		chatMessage
	);
}

shared_ptr<EventLog> MainDbPrivate::selectConferenceChatMessageEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	shared_ptr<AbstractChatRoom> &chatRoom,
	const string &fromSipAddress,
	const string &toSipAddress,
	const tm &messageTime,
	const string &imdnMessageId,
	int state,
	int direction,
	int isSecured
) const {
	shared_ptr<ChatMessage> chatMessage = getChatMessageFromCache(eventId);
	if (!chatMessage) {
670 671
		chatMessage = shared_ptr<ChatMessage>(new ChatMessage(
			chatRoom,
672
			ChatMessage::Direction(direction)
673
		));
674
		chatMessage->setIsSecured(bool(isSecured));
Ronan's avatar
Ronan committed
675

676
		ChatMessagePrivate *dChatMessage = chatMessage->getPrivate();
677
		dChatMessage->setState(ChatMessage::State(state), true);
678

679 680
		dChatMessage->forceFromAddress(IdentityAddress(fromSipAddress));
		dChatMessage->forceToAddress(IdentityAddress(toSipAddress));
Ronan's avatar
Ronan committed
681

682 683 684
		dChatMessage->setTime(Utils::getTmAsTimeT(messageTime));
		dChatMessage->setImdnMessageId(imdnMessageId);

685 686
		dChatMessage->markContentsAsNotLoaded();
		dChatMessage->setIsReadOnly(true);
687

688
		cache(chatMessage, eventId);
Ronan's avatar
Ronan committed
689 690
	}

691 692 693 694 695
	return make_shared<ConferenceChatMessageEvent>(
		creationTime,
		chatMessage
	);
}
696

697 698 699 700 701 702 703 704 705
shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	unsigned int notifyId;
	string participantAddress;

706
	soci::session *session = dbSession.getBackendSession();
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
	*session << "SELECT notify_id, participant_address.value"
		"  FROM conference_notified_event, conference_participant_event, sip_address as participant_address"
		"  WHERE conference_participant_event.event_id = :eventId"
		"    AND conference_notified_event.event_id = conference_participant_event.event_id"
		"    AND participant_address.id = participant_sip_address_id",
		soci::into(notifyId), soci::into(participantAddress), soci::use(eventId);

	return make_shared<ConferenceParticipantEvent>(
		type,
		creationTime,
		chatRoomId,
		notifyId,
		IdentityAddress(participantAddress)
	);
}
722

723 724 725 726 727 728 729 730 731 732
shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantDeviceEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	unsigned int notifyId;
	string participantAddress;
	string deviceAddress;

733
	soci::session *session = dbSession.getBackendSession();
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
	*session << "SELECT notify_id, participant_address.value, device_address.value"
		"  FROM conference_notified_event, conference_participant_event, conference_participant_device_event,"
		"    sip_address AS participant_address, sip_address AS device_address"
		"  WHERE conference_participant_device_event.event_id = :eventId"
		"    AND conference_participant_event.event_id = conference_participant_device_event.event_id"
		"    AND conference_notified_event.event_id = conference_participant_event.event_id"
		"    AND participant_address.id = participant_sip_address_id"
		"    AND device_address.id = device_sip_address_id",
		soci::into(notifyId), soci::into(participantAddress), soci::into(deviceAddress), soci::use(eventId);

	return make_shared<ConferenceParticipantDeviceEvent>(
		type,
		creationTime,
		chatRoomId,
		notifyId,
		IdentityAddress(participantAddress),
		IdentityAddress(deviceAddress)
	);
}
753

754 755 756 757 758 759 760 761 762
shared_ptr<EventLog> MainDbPrivate::selectConferenceSubjectEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	unsigned int notifyId;
	string subject;

763
	soci::session *session = dbSession.getBackendSession();
764 765 766 767 768 769 770 771 772 773 774 775 776
	*session << "SELECT notify_id, subject"
		" FROM conference_notified_event, conference_subject_event"
		" WHERE conference_subject_event.event_id = :eventId"
		" AND conference_notified_event.event_id = conference_subject_event.event_id",
		soci::into(notifyId), soci::into(subject), soci::use(eventId);

	return make_shared<ConferenceSubjectEvent>(
		creationTime,
		chatRoomId,
		notifyId,
		subject
	);
}
777

778
// -----------------------------------------------------------------------------
779

780
long long MainDbPrivate::insertEvent (const shared_ptr<EventLog> &eventLog) {
781
	soci::session *session = dbSession.getBackendSession();
782

783
	const int &type = int(eventLog->getType());
784 785 786 787 788
	const tm &creationTime = Utils::getTimeTAsTm(eventLog->getCreationTime());
	*session << "INSERT INTO event (type, creation_time) VALUES (:type, :creationTime)",
		soci::use(type),
		soci::use(creationTime);

789
	return dbSession.getLastInsertId();
790
}
791

792 793 794 795 796 797 798 799 800 801 802 803 804 805
long long MainDbPrivate::insertConferenceEvent (const shared_ptr<EventLog> &eventLog, long long *chatRoomId) {
	shared_ptr<ConferenceEvent> conferenceEvent = static_pointer_cast<ConferenceEvent>(eventLog);

	long long eventId = -1;
	const long long &curChatRoomId = selectChatRoomId(conferenceEvent->getChatRoomId());
	if (curChatRoomId < 0) {
		// A conference event can be inserted in database only if chat room exists.
		// Otherwise it's an error.
		const ChatRoomId &chatRoomId = conferenceEvent->getChatRoomId();
		lError() << "Unable to find chat room storage id of (peer=" +
			chatRoomId.getPeerAddress().asString() +
			", local=" + chatRoomId.getLocalAddress().asString() + "`).";
	} else {
		eventId = insertEvent(eventLog);
806

807
		soci::session *session = dbSession.getBackendSession();
808 809 810 811 812 813 814
		*session << "INSERT INTO conference_event (event_id, chat_room_id)"
			" VALUES (:eventId, :chatRoomId)", soci::use(eventId), soci::use(curChatRoomId);

		const tm &lastUpdateTime = Utils::getTimeTAsTm(eventLog->getCreationTime());
		*session << "UPDATE chat_room SET last_update_time = :lastUpdateTime"
			" WHERE id = :chatRoomId", soci::use(lastUpdateTime),
			soci::use(curChatRoomId);
815

816 817
		if (eventLog->getType() == EventLog::Type::ConferenceTerminated)
			*session << "UPDATE chat_room SET flags = 1 WHERE id = :chatRoomId", soci::use(curChatRoomId);
818 819
	}

820 821 822 823 824
	if (chatRoomId)
		*chatRoomId = curChatRoomId;

	return eventId;
}
825

826 827 828 829
long long MainDbPrivate::insertConferenceCallEvent (const shared_ptr<EventLog> &eventLog) {
	// TODO.
	return 0;
}
830

831 832 833 834 835 836 837 838 839 840 841 842
long long MainDbPrivate::insertConferenceChatMessageEvent (const shared_ptr<EventLog> &eventLog) {
	shared_ptr<ChatMessage> chatMessage = static_pointer_cast<ConferenceChatMessageEvent>(eventLog)->getChatMessage();
	shared_ptr<AbstractChatRoom> chatRoom = chatMessage->getChatRoom();
	if (!chatRoom) {
		lError() << "Unable to get a valid chat room. It was removed from database.";
		return -1;
	}

	const long long &eventId = insertConferenceEvent(eventLog);
	if (eventId < 0)
		return -1;

843
	soci::session *session = dbSession.getBackendSession();
844 845 846 847

	const long long &fromSipAddressId = insertSipAddress(chatMessage->getFromAddress().asString());
	const long long &toSipAddressId = insertSipAddress(chatMessage->getToAddress().asString());
	const tm &messageTime = Utils::getTimeTAsTm(chatMessage->getTime());
848 849
	const int &state = int(chatMessage->getState());
	const int &direction = int(chatMessage->getDirection());
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
	const string &imdnMessageId = chatMessage->getImdnMessageId();
	const int &isSecured = chatMessage->isSecured() ? 1 : 0;

	*session << "INSERT INTO conference_chat_message_event ("
		"  event_id, from_sip_address_id, to_sip_address_id,"
		"  time, state, direction, imdn_message_id, is_secured"
		") VALUES ("
		"  :eventId, :localSipaddressId, :remoteSipaddressId,"
		"  :time, :state, :direction, :imdnMessageId, :isSecured"
		")", soci::use(eventId), soci::use(fromSipAddressId), soci::use(toSipAddressId),
		soci::use(messageTime), soci::use(state), soci::use(direction),
		soci::use(imdnMessageId), soci::use(isSecured);

	for (const Content *content : chatMessage->getContents())
		insertContent(eventId, *content);

866 867 868 869 870
	for (const auto &participant : chatRoom->getParticipants()) {
		const long long &participantSipAddressId = selectSipAddressId(participant->getAddress().asString());
		insertChatMessageParticipant(eventId, participantSipAddressId, state);
	}

871 872 873 874 875 876 877 878 879
	return eventId;
}

void MainDbPrivate::updateConferenceChatMessageEvent (const shared_ptr<EventLog> &eventLog) {
	shared_ptr<ChatMessage> chatMessage = static_pointer_cast<ConferenceChatMessageEvent>(eventLog)->getChatMessage();
	shared_ptr<AbstractChatRoom> chatRoom = chatMessage->getChatRoom();
	if (!chatRoom) {
		lError() << "Unable to get a valid chat room. It was removed from database.";
		return;
880 881
	}

882 883 884
	const EventLogPrivate *dEventLog = eventLog->getPrivate();
	MainDbKeyPrivate *dEventKey = static_cast<MainDbKey &>(dEventLog->dbKey).getPrivate();
	const long long &eventId = dEventKey->storageId;
885

886
	soci::session *session = dbSession.getBackendSession();
887
	const int &state = int(chatMessage->getState());
888 889 890 891
	const string &imdnMessageId = chatMessage->getImdnMessageId();
	*session << "UPDATE conference_chat_message_event SET state = :state, imdn_message_id = :imdnMessageId"
		" WHERE event_id = :eventId",
		soci::use(state), soci::use(imdnMessageId), soci::use(eventId);
892

893 894 895 896
	deleteContents(eventId);
	for (const auto &content : chatMessage->getContents())
		insertContent(eventId, *content);
}
897

898 899 900 901 902
long long MainDbPrivate::insertConferenceNotifiedEvent (const shared_ptr<EventLog> &eventLog, long long *chatRoomId) {
	long long curChatRoomId;
	const long long &eventId = insertConferenceEvent(eventLog, &curChatRoomId);
	if (eventId < 0)
		return -1;
903

904
	const unsigned int &lastNotifyId = static_pointer_cast<ConferenceNotifiedEvent>(eventLog)->getNotifyId();
905

906
	soci::session *session = dbSession.getBackendSession();
907 908 909 910
	*session << "INSERT INTO conference_notified_event (event_id, notify_id)"
		" VALUES (:eventId, :notifyId)", soci::use(eventId), soci::use(lastNotifyId);
	*session << "UPDATE chat_room SET last_notify_id = :lastNotifyId WHERE id = :chatRoomId",
		soci::use(lastNotifyId), soci::use(curChatRoomId);
911

912 913
	if (chatRoomId)
		*chatRoomId = curChatRoomId;
914

915 916
	return eventId;
}
917

918 919 920 921 922 923 924 925
long long MainDbPrivate::insertConferenceParticipantEvent (
	const shared_ptr<EventLog> &eventLog,
	long long *chatRoomId
) {
	long long curChatRoomId;
	const long long &eventId = insertConferenceNotifiedEvent(eventLog, &curChatRoomId);
	if (eventId < 0)
		return -1;
926

927 928
	shared_ptr<ConferenceParticipantEvent> participantEvent =
		static_pointer_cast<ConferenceParticipantEvent>(eventLog);
929

930 931 932 933
	const long long &participantAddressId = insertSipAddress(
		participantEvent->getParticipantAddress().asString()
	);

934
	soci::session *session = dbSession.getBackendSession();
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
	*session << "INSERT INTO conference_participant_event (event_id, participant_sip_address_id)"
		"  VALUES (:eventId, :participantAddressId)", soci::use(eventId), soci::use(participantAddressId);

	bool isAdmin = eventLog->getType() == EventLog::Type::ConferenceParticipantSetAdmin;
	switch (eventLog->getType()) {
		case EventLog::Type::ConferenceParticipantAdded:
		case EventLog::Type::ConferenceParticipantSetAdmin:
		case EventLog::Type::ConferenceParticipantUnsetAdmin:
			insertChatRoomParticipant(curChatRoomId, participantAddressId, isAdmin);
			break;

		case EventLog::Type::ConferenceParticipantRemoved:
			deleteChatRoomParticipant(curChatRoomId, participantAddressId);
			break;

		default:
			break;
952 953
	}

954 955
	if (chatRoomId)
		*chatRoomId = curChatRoomId;
956

957 958
	return eventId;
}
959

960 961 962 963 964
long long MainDbPrivate::insertConferenceParticipantDeviceEvent (const shared_ptr<EventLog> &eventLog) {
	long long chatRoomId;
	const long long &eventId = insertConferenceParticipantEvent(eventLog, &chatRoomId);
	if (eventId < 0)
		return -1;
965

966 967
	shared_ptr<ConferenceParticipantDeviceEvent> participantDeviceEvent =
		static_pointer_cast<ConferenceParticipantDeviceEvent>(eventLog);
968

969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
	const string participantAddress = participantDeviceEvent->getParticipantAddress().asString();
	const long long &participantAddressId = selectSipAddressId(participantAddress);
	if (participantAddressId < 0) {
		lError() << "Unable to find sip address id of: `" << participantAddress << "`.";
		return -1;
	}
	const long long &participantId = selectChatRoomParticipantId(chatRoomId, participantAddressId);
	if (participantId < 0) {
		lError() << "Unable to find valid participant id in database with chat room id = " << chatRoomId <<
		" and participant address id = " << participantId;
		return -1;
	}
	const long long &deviceAddressId = insertSipAddress(
		participantDeviceEvent->getDeviceAddress().asString()
	);
984

985
	soci::session *session = dbSession.getBackendSession();
986 987
	*session << "INSERT INTO conference_participant_device_event (event_id, device_sip_address_id)"
		" VALUES (:eventId, :deviceAddressId)", soci::use(eventId), soci::use(deviceAddressId);
988

989 990 991 992
	switch (eventLog->getType()) {
		case EventLog::Type::ConferenceParticipantDeviceAdded:
			insertChatRoomParticipantDevice(participantId, deviceAddressId);
			break;
993

994 995 996 997 998 999
		case EventLog::Type::ConferenceParticipantDeviceRemoved:
			deleteChatRoomParticipantDevice(participantId, deviceAddressId);
			break;

		default:
			break;
1000 1001
	}

1002 1003
	return eventId;
}
1004

1005 1006 1007 1008 1009
long long MainDbPrivate::insertConferenceSubjectEvent (const shared_ptr<EventLog> &eventLog) {
	long long chatRoomId;
	const long long &eventId = insertConferenceNotifiedEvent(eventLog, &chatRoomId);
	if (eventId < 0)
		return -1;
1010

1011
	const string &subject = static_pointer_cast<ConferenceSubjectEvent>(eventLog)->getSubject();
1012

1013
	soci::session *session = dbSession.getBackendSession();
1014 1015
	*session << "INSERT INTO conference_subject_event (event_id, subject)"
		" VALUES (:eventId, :subject)", soci::use(eventId), soci::use(subject);
1016

1017 1018 1019 1020 1021
	*session << "UPDATE chat_room SET subject = :subject"
		" WHERE id = :chatRoomId", soci::use(subject), soci::use(chatRoomId);

	return eventId;
}
1022

1023 1024
// -----------------------------------------------------------------------------

1025 1026 1027 1028
shared_ptr<EventLog> MainDbPrivate::getEventFromCache (long long storageId) const {
	auto it = storageIdToEvent.find(storageId);
	if (it == storageIdToEvent.cend())
		return nullptr;
1029

1030 1031 1032 1033 1034
	shared_ptr<EventLog> eventLog = it->second.lock();
	// Must exist. If not, implementation bug.
	L_ASSERT(eventLog);
	return eventLog;
}
1035

1036 1037 1038 1039
shared_ptr<ChatMessage> MainDbPrivate::getChatMessageFromCache (long long storageId) const {
	auto it = storageIdToChatMessage.find(storageId);
	if (it == storageIdToChatMessage.cend())
		return nullptr;
1040

1041 1042 1043 1044 1045
	shared_ptr<ChatMessage> chatMessage = it->second.lock();
	// Must exist. If not, implementation bug.
	L_ASSERT(chatMessage);
	return chatMessage;
}
1046

1047 1048
void MainDbPrivate::cache (const shared_ptr<EventLog> &eventLog, long long storageId) const {
	L_Q();
1049

1050 1051 1052 1053 1054 1055
	EventLogPrivate *dEventLog = eventLog->getPrivate();
	L_ASSERT(!dEventLog->dbKey.isValid());
	dEventLog->dbKey = MainDbEventKey(q->getCore(), storageId);
	storageIdToEvent[storageId] = eventLog;
	L_ASSERT(dEventLog->dbKey.isValid());
}
1056

1057 1058
void MainDbPrivate::cache (const shared_ptr<ChatMessage> &chatMessage, long long storageId) const {
	L_Q();
1059

1060 1061 1062 1063 1064 1065
	ChatMessagePrivate *dChatMessage = chatMessage->getPrivate();
	L_ASSERT(!dChatMessage->dbKey.isValid());
	dChatMessage->dbKey = MainDbChatMessageKey(q->getCore(), storageId);
	storageIdToChatMessage[storageId] = chatMessage;
	L_ASSERT(dChatMessage->dbKey.isValid());
}
1066

1067
void MainDbPrivate::invalidConferenceEventsFromQuery (const string &query, long long chatRoomId) {
1068
	soci::session *session = dbSession.getBackendSession();
1069 1070
	soci::rowset<soci::row> rows = (session->prepare << query, soci::use(chatRoomId));
	for (const auto &row : rows) {
1071
		long long eventId = dbSession.resolveId(row, 0);
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
		shared_ptr<EventLog> eventLog = getEventFromCache(eventId);
		if (eventLog) {
			const EventLogPrivate *dEventLog = eventLog->getPrivate();
			L_ASSERT(dEventLog->dbKey.isValid());
			dEventLog->dbKey = MainDbEventKey();
		}
		// TODO: Try to add a better code here...
		shared_ptr<ChatMessage> chatMessage = getChatMessageFromCache(eventId);
		if (chatMessage) {
			const ChatMessagePrivate *dChatMessage = chatMessage->getPrivate();
			L_ASSERT(dChatMessage->dbKey.isValid());
			dChatMessage->dbKey = MainDbChatMessageKey();
1084 1085
		}
	}
1086
}
1087

1088 1089
// -----------------------------------------------------------------------------

1090
unsigned int MainDbPrivate::getModuleVersion (const string &name) {
1091
	soci::session *session = dbSession.getBackendSession();
1092

1093 1094 1095 1096
	unsigned int version;
	*session << "SELECT version FROM db_module_version WHERE name = :name", soci::into(version), soci::use(name);
	return session->got_data() ? version : 0;
}
1097

1098 1099 1100 1101
void MainDbPrivate::updateModuleVersion (const string &name, unsigned int version) {
	unsigned int oldVersion = getModuleVersion(name);
	if (oldVersion == version)
		return;
1102

1103
	soci::session *session = dbSession.getBackendSession();
1104 1105 1106
	*session << "REPLACE INTO db_module_version (name, version) VALUES (:name, :version)",
		soci::use(name), soci::use(version);
}
1107

1108 1109 1110 1111
void MainDbPrivate::updateSchema () {
	soci::session *session = dbSession.getBackendSession();
	unsigned int version = getModuleVersion("events");

1112
	if (version < makeVersion(1, 0, 1)) {
1113 1114 1115 1116
		*session << "ALTER TABLE chat_room_participant_device ADD COLUMN state TINYINT UNSIGNED DEFAULT 0";
	}
}

1117
// -----------------------------------------------------------------------------
1118

1119 1120 1121 1122 1123
// NOTE: Legacy supports only sqlite.
static inline bool checkLegacyTableExists (soci::session &session, const string &name) {
	session << "SELECT name FROM sqlite_master WHERE type='table' AND name = :name", soci::use(name);
	return session.got_data() > 0;
}
1124 1125

static inline bool checkLegacyFriendsTableExists (soci::session &session) {
1126
	return checkLegacyTableExists(session, "friends");
1127 1128 1129
}

static inline bool checkLegacyHistoryTableExists (soci::session &session) {
1130
	return checkLegacyTableExists(session, "history");
1131 1132 1133 1134 1135 1136
}

template<typename T>
static T getValueFromRow (const soci::row &row, int index, bool &isNull) {
	isNull = false;

1137
	if (row.get_indicator(size_t(index)) == soci::i_null){
1138
		isNull = true;
1139
		return T();
1140
	}
1141
	return row.get<T>(size_t(index));
1142 1143 1144 1145 1146
}

// -----------------------------------------------------------------------------

void MainDbPrivate::importLegacyFriends (DbSession &inDbSession) {
1147 1148
	soci::session *inSession = inDbSession.getBackendSession();
	soci::transaction tr(*dbSession.getBackendSession());
1149

1150
	if (getModuleVersion("legacy-friends-import") >= makeVersion(1, 0, 0))
1151
		return;
1152
	updateModuleVersion("legacy-friends-import", ModuleVersionLegacyFriendsImport);
1153 1154 1155 1156 1157

	if (!checkLegacyFriendsTableExists(*inSession))
		return;

	unordered_map<int, long long> resolvedListsIds;
1158
	soci::session *session = dbSession.getBackendSession();
1159 1160 1161 1162 1163

	soci::rowset<soci::row> friendsLists = (inSession->prepare << "SELECT * FROM friends_lists");
	try {
		set<string> names;
		for (const auto &friendList : friendsLists) {
1164 1165 1166 1167
			const string &name = friendList.get<string>(LegacyFriendListColName, "");
			const string &rlsUri = friendList.get<string>(LegacyFriendListColRlsUri, "");
			const string &syncUri = friendList.get<string>(LegacyFriendListColSyncUri, "");
			const int &revision = friendList.get<int>(LegacyFriendListColRevision, 0);
1168 1169 1170 1171 1172 1173 1174 1175

			string uniqueName = name;
			for (int id = 0; names.find(uniqueName) != names.end(); uniqueName = name + "-" + Utils::toString(id++));
			names.insert(uniqueName);

			*session << "INSERT INTO friends_list (name, rls_uri, sync_uri, revision) VALUES ("
				"  :name, :rlsUri, :syncUri, :revision"
				")", soci::use(uniqueName), soci::use(rlsUri), soci::use(syncUri), soci::use(revision);
1176
			resolvedListsIds[friendList.get<int>(LegacyFriendListColId)] = dbSession.getLastInsertId();
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
		}
	} catch (const exception &e) {
		lWarning() << "Failed to import legacy friends list: " << e.what() << ".";
		return;
	}

	soci::rowset<soci::row> friends = (inSession->prepare << "SELECT * FROM friends");
	try {
		for (const auto &friendInfo : friends) {
			long long friendsListId;
			{
1188
				auto it = resolvedListsIds.find(friendInfo.get<int>(LegacyFriendColFriendListId, -1));
1189 1190 1191 1192 1193
				if (it == resolvedListsIds.end())
					continue;
				friendsListId = it->second;
			}

1194 1195 1196 1197 1198 1199 1200
			const long long &sipAddressId = insertSipAddress(friendInfo.get<string>(LegacyFriendColSipAddress, ""));
			const int &subscribePolicy = friendInfo.get<int>(LegacyFriendColSubscribePolicy, LinphoneSPAccept);
			const int &sendSubscribe = friendInfo.get<int>(LegacyFriendColSendSubscribe, 1);
			const string &vCard = friendInfo.get<string>(LegacyFriendColVCard, "");
			const string &vCardEtag = friendInfo.get<string>(LegacyFriendColVCardEtag, "");
			const string &vCardSyncUri = friendInfo.get<string>(LegacyFriendColVCardSyncUri, "");
			const int &presenceReveived = friendInfo.get<int>(LegacyFriendColPresenceReceived, 0);
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211

			*session << "INSERT INTO friend ("
				"  sip_address_id, friends_list_id, subscribe_policy, send_subscribe,"
				"  presence_received, v_card, v_card_etag, v_card_sync_uri"
				") VALUES ("
				"  :sipAddressId, :friendsListId, :subscribePolicy, :sendSubscribe,"
				"  :presenceReceived, :vCard, :vCardEtag, :vCardSyncUri"
				")", soci::use(sipAddressId), soci::use(friendsListId), soci::use(subscribePolicy), soci::use(sendSubscribe),
				soci::use(presenceReveived), soci::use(vCard), soci::use(vCardEtag), soci::use(vCardSyncUri);

			bool isNull;
1212
			const string &data = getValueFromRow<string>(friendInfo, LegacyFriendColRefKey, isNull);
1213 1214 1215
			if (!isNull)
				*session << "INSERT INTO friend_app_data (friend_id, name, data) VALUES"
					" (:friendId, 'legacy', :data)",
1216
					soci::use(dbSession.getLastInsertId()), soci::use(data);
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
		}
		tr.commit();
	} catch (const exception &e) {
		lWarning() << "Failed to import legacy friends: " << e.what() << ".";
		return;
	}

	lInfo() << "Successful import of legacy friends.";
}

void MainDbPrivate::importLegacyHistory (DbSession &inDbSession) {
1228 1229
	soci::session *inSession = inDbSession.getBackendSession();
	soci::transaction tr(*dbSession.getBackendSession());
1230 1231

	unsigned int version = getModuleVersion("legacy-history-import");
1232
	if (version >= makeVersion(1, 0, 0))
1233
		return;
1234
	updateModuleVersion("legacy-history-import", ModuleVersionLegacyHistoryImport);
1235 1236 1237 1238 1239 1240 1241

	if (!checkLegacyHistoryTableExists(*inSession))
		return;

	soci::rowset<soci::row> messages = (inSession->prepare << "SELECT * FROM history");
	try {
		for (const auto &message : messages) {
1242
			const int direction = message.get<int>(LegacyMessageColDirection);
1243 1244 1245 1246 1247 1248
			if (direction != 0 && direction != 1) {
				lWarning() << "Unable to import legacy message with invalid direction.";
				continue;
			}

			const int &state = message.get<int>(
1249
				LegacyMessageColState, int(ChatMessage::State::Displayed)
1250
			);
1251
			if (state < 0 || state > int(ChatMessage::State::Displayed)) {
1252 1253 1254 1255
				lWarning() << "Unable to import legacy message with invalid state.";
				continue;
			}

1256
			const tm &creationTime = Utils::getTimeTAsTm(message.get<int>(LegacyMessageColDate, 0));
1257 1258

			bool isNull;
1259
			getValueFromRow<string>(message, LegacyMessageColUrl, isNull);
1260

1261 1262
			const int &contentId = message.get<int>(LegacyMessageColContentId, -1);
			ContentType contentType(message.get<string>(LegacyMessageColContentType, ""));
1263 1264 1265 1266 1267 1268 1269 1270 1271
			if (!contentType.isValid())
				contentType = contentId != -1
					? ContentType::FileTransfer
					: (isNull ? ContentType::PlainText : ContentType::ExternalBody);
			if (contentType == ContentType::ExternalBody) {
				lInfo() << "Import of external body content is skipped.";
				continue;
			}

1272
			const string &text = getValueFromRow<string>(message, LegacyMessageColText, isNull);
1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287

			Content content;
			content.setContentType(contentType);
			if (contentType == ContentType::PlainText) {
				if (isNull) {
					lWarning() << "Unable to import legacy message with no text.";
					continue;
				}
				content.setBody(text);
			} else {
				if (contentType != ContentType::FileTransfer) {
					lWarning() << "Unable to import unsupported legacy content.";
					continue;
				}

1288
				const string appData = getValueFromRow<string>(message, LegacyMessageColAppData, isNull);
1289 1290 1291 1292 1293 1294 1295 1296
				if (isNull) {
					lWarning() << "Unable to import legacy file message without app data.";
					continue;
				}

				content.setAppData("legacy", appData);
			}

1297
			soci::session *session = dbSession.getBackendSession();
1298
			const int &eventType = int(EventLog::Type::ConferenceChatMessage);
1299 1300 1301
			*session << "INSERT INTO event (type, creation_time) VALUES (:type, :creationTime)",
				soci::use(eventType), soci::use(creationTime);

1302
			const long long &eventId = dbSession.getLastInsertId();
1303 1304 1305 1306 1307 1308
			const long long &localSipAddressId = insertSipAddress(
				IdentityAddress(message.get<string>(LegacyMessageColLocalAddress)).asString()
			);
			const long long &remoteSipAddressId = insertSipAddress(
				IdentityAddress(message.get<string>(LegacyMessageColRemoteAddress)).asString()
			);
1309 1310 1311 1312 1313
			const long long &chatRoomId = insertOrUpdateImportedBasicChatRoom(
				remoteSipAddressId,
				localSipAddressId,
				creationTime
			);
1314
			const int &isSecured = message.get<int>(LegacyMessageColIsSecured, 0);
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331

			*session << "INSERT INTO conference_event (event_id, chat_room_id)"
				"  VALUES (:eventId, :chatRoomId)", soci::use(eventId), soci::use(chatRoomId);

			*session << "INSERT INTO conference_chat_message_event ("
				"  event_id, from_sip_address_id, to_sip_address_id,"
				"  time, state, direction, imdn_message_id, is_secured"
				") VALUES ("
				"  :eventId, :localSipAddressId, :remoteSipAddressId,"
				"  :creationTime, :state, :direction, '', :isSecured"
				")", soci::use(eventId), soci::use(localSipAddressId), soci::use(remoteSipAddressId),
				soci::use(creationTime), soci::use(state), soci::use(direction),
				soci::use(isSecured);

			insertContent(eventId, content);
			insertChatRoomParticipant(chatRoomId, remoteSipAddressId, false);

1332
			if (state != int(ChatMessage::State::Displayed))
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
				insertChatMessageParticipant(eventId, remoteSipAddressId, state);
		}

		tr.commit();
	} catch (const exception &e) {
		lInfo() << "Failed to import legacy messages: " << e.what() << ".";
		return;
	}

	lInfo() << "Successful import of legacy messages.";
}

// -----------------------------------------------------------------------------

1347 1348
void MainDb::init () {
	L_D();
1349

1350 1351 1352
	Backend backend = getBackend();

	const string charset = backend == Mysql ? "DEFAULT CHARSET=utf8" : "";
1353 1354 1355 1356 1357 1358 1359
	soci::session *session = d->dbSession.getBackendSession();

	using namespace placeholders;
	auto primaryKeyRefStr = bind(&DbSession::primaryKeyRefStr, d->dbSession, _1);
	auto primaryKeyStr = bind(&DbSession::primaryKeyStr, d->dbSession, _1);
	auto timestampType = bind(&DbSession::timestampType, d->dbSession);
	auto varcharPrimaryKeyStr = bind(&DbSession::varcharPrimaryKeyStr, d->dbSession, _1);
1360

1361
	auto createTableSanitizer = [](const char *statement) {