main-db.cpp 37.9 KB
Newer Older
Ronan's avatar
Ronan committed
1
/*
2
 * main-db.cpp
Ghislain MARY's avatar
Ghislain MARY committed
3
 * Copyright (C) 2010-2017 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 <algorithm>
21
#include <ctime>
22

23 24 25 26
#ifdef SOCI_ENABLED
	#include <soci/soci.h>
#endif // ifdef SOCI_ENABLED

27 28
#include "linphone/utils/utils.h"

29
#include "chat/chat-room/chat-room.h"
30
#include "conference/participant.h"
31
#include "content/content-type.h"
32
#include "content/content.h"
33
#include "db/session/db-session-provider.h"
34
#include "event-log/events.h"
35
#include "event-log/event-log-p.h"
36
#include "logger/logger.h"
37
#include "main-db-p.h"
Ronan's avatar
Ronan committed
38 39 40

// =============================================================================

41 42
using namespace std;

Ronan's avatar
Ronan committed
43 44 45 46
LINPHONE_BEGIN_NAMESPACE

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

47
MainDb::MainDb () : AbstractDb(*new MainDbPrivate) {}
Ronan's avatar
Ronan committed
48

49 50
#ifdef SOCI_ENABLED

51
// -----------------------------------------------------------------------------
52
// Soci backend.
53 54
// -----------------------------------------------------------------------------

55 56 57 58 59
	template<typename T>
	struct EnumToSql {
		T first;
		const char *second;
	};
60

61 62 63 64 65 66 67
	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)
		);
	}

68
	static constexpr EnumToSql<MainDb::Filter> eventFilterToSql[] = {
69 70 71
		{ MainDb::ConferenceCallFilter, "1, 2" },
		{ MainDb::ConferenceChatMessageFilter, "5" },
		{ MainDb::ConferenceInfoFilter, "3, 4, 6, 7, 8, 9, 10, 11, 12" }
72
	};
73

74
	static constexpr const char *mapEventFilterToSql (MainDb::Filter filter) {
75 76 77
		return mapEnumToSql(
			eventFilterToSql, sizeof eventFilterToSql / sizeof eventFilterToSql[0], filter
		);
78 79
	}

80 81
// -----------------------------------------------------------------------------

82 83 84 85 86
	static string buildSqlEventFilter (
		const list<MainDb::Filter> &filters,
		MainDb::FilterMask mask,
		const string &condKeyWord = "WHERE"
	) {
87
		L_ASSERT(
88 89
			find_if(filters.cbegin(), filters.cend(), [](const MainDb::Filter &filter) {
					return filter == MainDb::NoFilter;
90 91 92
				}) == filters.cend()
		);

93
		if (mask == MainDb::NoFilter)
94 95 96 97 98 99 100 101 102 103
			return "";

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

			if (isStart) {
				isStart = false;
104
				sql += " " + condKeyWord + " type IN (";
105
			} else
106
				sql += ", ";
107 108 109
			sql += mapEventFilterToSql(filter);
		}

110 111 112
		if (!isStart)
			sql += ") ";

113 114 115
		return sql;
	}

116 117
// -----------------------------------------------------------------------------

118
	long MainDbPrivate::insertSipAddress (const string &sipAddress) {
119 120 121
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

122
		long id;
123 124
		*session << "SELECT id FROM sip_address WHERE value = :sipAddress", soci::use(sipAddress), soci::into(id);
		if (session->got_data())
125 126
			return id;

127 128
		*session << "INSERT INTO sip_address (value) VALUES (:sipAddress)", soci::use(sipAddress);
		return q->getLastInsertId();
129 130
	}

Ronan's avatar
Ronan committed
131
	void MainDbPrivate::insertContent (long eventId, const Content &content) {
132 133
		L_Q();

134 135
		soci::session *session = dbSession.getBackendSession<soci::session>();

136
		long contentTypeId = insertContentType(content.getContentType().asString());
137
		*session << "INSERT INTO chat_message_content (event_id, content_type_id, body) VALUES"
Ronan's avatar
Ronan committed
138
			"  (:eventId, :contentTypeId, :body)", soci::use(eventId), soci::use(contentTypeId),
139
			soci::use(content.getBodyAsString());
140 141 142

		long messageContentId = q->getLastInsertId();
		for (const auto &appData : content.getAppDataMap())
143
			*session << "INSERT INTO chat_message_content_app_data (chat_message_content_id, key, data) VALUES"
144 145
				"  (:messageContentId, :key, :data)",
				soci::use(messageContentId), soci::use(appData.first), soci::use(appData.second);
146 147
	}

148
	long MainDbPrivate::insertContentType (const string &contentType) {
149 150 151
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

152
		long id;
153 154
		*session << "SELECT id FROM content_type WHERE value = :contentType", soci::use(contentType), soci::into(id);
		if (session->got_data())
155 156
			return id;

157 158
		*session << "INSERT INTO content_type (value) VALUES (:contentType)", soci::use(contentType);
		return q->getLastInsertId();
159 160
	}

161
	long MainDbPrivate::insertChatRoom (long sipAddressId, int capabilities, const tm &date) {
162 163
		soci::session *session = dbSession.getBackendSession<soci::session>();

164
		long id;
165
		*session << "SELECT peer_sip_address_id FROM chat_room WHERE peer_sip_address_id = :sipAddressId",
166
			soci::use(sipAddressId), soci::into(id);
167
		if (!session->got_data())
168 169 170
			*session << "INSERT INTO chat_room (peer_sip_address_id, creation_date, last_update_date, capabilities, subject) VALUES"
				"  (:sipAddressId, :creationDate, :lastUpdateDate, :capabilities, '')",
				soci::use(sipAddressId), soci::use(date), soci::use(date), soci::use(capabilities);
171
		else
172
			*session << "UPDATE chat_room SET last_update_date = :lastUpdateDate WHERE peer_sip_address_id = :sipAddressId",
173
				soci::use(date), soci::use(sipAddressId);
174

175 176 177
		return sipAddressId;
	}

178
	void MainDbPrivate::insertChatRoomParticipant (long chatRoomId, long sipAddressId, bool isAdmin) {
179
		soci::session *session = dbSession.getBackendSession<soci::session>();
180 181 182 183 184 185 186 187 188 189
		soci::statement statement = (
			session->prepare << "UPDATE chat_room_participant SET is_admin = :isAdmin"
				"  WHERE chat_room_id = :chatRoomId AND sip_address_id = :sipAddressId",
				soci::use(static_cast<int>(isAdmin)), soci::use(chatRoomId), soci::use(sipAddressId)
		);
		statement.execute(true);
		if (statement.get_affected_rows() == 0)
			*session << "INSERT INTO chat_room_participant (chat_room_id, sip_address_id, is_admin)"
				"  VALUES (:chatRoomId, :sipAddressId, :isAdmin)",
				soci::use(chatRoomId), soci::use(sipAddressId), soci::use(static_cast<int>(isAdmin));
190 191
	}

192
	void MainDbPrivate::insertChatMessageParticipant (long eventId, long sipAddressId, int state) {
193 194
		soci::session *session = dbSession.getBackendSession<soci::session>();
		soci::statement statement = (
195
			session->prepare << "UPDATE chat_message_participant SET state = :state"
Ronan's avatar
Ronan committed
196 197
				"  WHERE event_id = :eventId AND sip_address_id = :sipAddressId",
				soci::use(state), soci::use(eventId), soci::use(sipAddressId)
198 199
		);
		statement.execute(true);
200
		if (statement.get_affected_rows() == 0 && state != static_cast<int>(ChatMessage::State::Displayed))
201
			*session << "INSERT INTO chat_message_participant (event_id, sip_address_id, state)"
Ronan's avatar
Ronan committed
202 203
				"  VALUES (:eventId, :sipAddressId, :state)",
				soci::use(eventId), soci::use(sipAddressId), soci::use(state);
204 205
	}

Ronan's avatar
Ronan committed
206 207
// -----------------------------------------------------------------------------

208
	shared_ptr<EventLog> MainDbPrivate::selectGenericConferenceEvent (
209 210 211 212 213
		long eventId,
		EventLog::Type type,
		time_t date,
		const string &peerAddress
	) const {
Ronan's avatar
Ronan committed
214 215 216 217 218 219
		switch (type) {
			case EventLog::Type::None:
				return nullptr;

			case EventLog::Type::ConferenceCreated:
			case EventLog::Type::ConferenceDestroyed:
220
				return selectConferenceEvent(eventId, type, date, peerAddress);
Ronan's avatar
Ronan committed
221 222 223

			case EventLog::Type::CallStart:
			case EventLog::Type::CallEnd:
224
				return selectConferenceCallEvent(eventId, type, date, peerAddress);
Ronan's avatar
Ronan committed
225 226

			case EventLog::Type::ConferenceChatMessage:
227
				return selectConferenceChatMessageEvent(eventId, type, date, peerAddress);
Ronan's avatar
Ronan committed
228 229 230 231 232

			case EventLog::Type::ConferenceParticipantAdded:
			case EventLog::Type::ConferenceParticipantRemoved:
			case EventLog::Type::ConferenceParticipantSetAdmin:
			case EventLog::Type::ConferenceParticipantUnsetAdmin:
233
				return selectConferenceParticipantEvent(eventId, type, date, peerAddress);
Ronan's avatar
Ronan committed
234 235 236

			case EventLog::Type::ConferenceParticipantDeviceAdded:
			case EventLog::Type::ConferenceParticipantDeviceRemoved:
237
				return selectConferenceParticipantDeviceEvent(eventId, type, date, peerAddress);
Ronan's avatar
Ronan committed
238 239

			case EventLog::Type::ConferenceSubjectChanged:
240
				return selectConferenceSubjectEvent(eventId, type, date, peerAddress);
Ronan's avatar
Ronan committed
241 242 243 244 245
		}

		return nullptr;
	}

246 247 248 249 250 251
	shared_ptr<EventLog> MainDbPrivate::selectConferenceEvent (
		long eventId,
		EventLog::Type type,
		time_t date,
		const string &peerAddress
	) const {
252 253 254 255 256 257 258 259 260
		// Useless here.
		(void)eventId;

		// TODO: Use cache.
		return make_shared<ConferenceEvent>(
			type,
			date,
			Address(peerAddress)
		);
Ronan's avatar
Ronan committed
261 262
	}

263 264 265 266 267 268
	shared_ptr<EventLog> MainDbPrivate::selectConferenceCallEvent (
		long eventId,
		EventLog::Type type,
		time_t date,
		const string &peerAddress
	) const {
Ronan's avatar
Ronan committed
269 270 271 272
		// TODO.
		return nullptr;
	}

273 274 275 276 277 278
	shared_ptr<EventLog> MainDbPrivate::selectConferenceChatMessageEvent (
		long eventId,
		EventLog::Type type,
		time_t date,
		const string &peerAddress
	) const {
Ronan's avatar
Ronan committed
279 280 281 282
		// TODO.
		return nullptr;
	}

283 284 285 286 287 288
	shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantEvent (
		long eventId,
		EventLog::Type type,
		time_t date,
		const string &peerAddress
	) const {
289 290 291 292
		unsigned int notifyId;
		string participantAddress;

		soci::session *session = dbSession.getBackendSession<soci::session>();
293 294
		*session << "SELECT notify_id, participant_address.value"
			"  FROM conference_notified_event, conference_participant_event, sip_address as participant_address"
295
			"  WHERE conference_participant_event.event_id = :eventId"
Ronan's avatar
Ronan committed
296 297
			"    AND conference_notified_event.event_id = conference_participant_event.event_id"
			"    AND participant_address.id = participant_address_id",
298 299 300 301 302 303 304 305 306 307
			soci::into(notifyId), soci::into(participantAddress), soci::use(eventId);

		// TODO: Use cache.
		return make_shared<ConferenceParticipantEvent>(
			type,
			date,
			Address(peerAddress),
			notifyId,
			Address(participantAddress)
		);
Ronan's avatar
Ronan committed
308 309
	}

310 311 312 313 314 315
	shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantDeviceEvent (
		long eventId,
		EventLog::Type type,
		time_t date,
		const string &peerAddress
	) const {
316 317 318 319 320
		unsigned int notifyId;
		string participantAddress;
		string gruuAddress;

		soci::session *session = dbSession.getBackendSession<soci::session>();
321 322 323
		*session << "SELECT notify_id, participant_address.value, gruu_address.value"
			"  FROM conference_notified_event, conference_participant_event, conference_participant_device_event,"
			"    sip_address AS participant_address, sip_address AS gruu_address"
324 325
			"  WHERE conference_participant_device_event.event_id = :eventId"
			"    AND conference_participant_event.event_id = conference_participant_device_event.event_id"
326 327 328
			"    AND conference_notified_event.event_id = conference_participant_event.event_id"
			"    AND participant_address.id = participant_address_id"
			"    AND gruu_address.id = gruu_address_id",
329 330 331 332 333 334 335 336 337 338 339
			soci::into(notifyId), soci::into(participantAddress), soci::into(gruuAddress), soci::use(eventId);

		// TODO: Use cache.
		return make_shared<ConferenceParticipantDeviceEvent>(
			type,
			date,
			Address(peerAddress),
			notifyId,
			Address(participantAddress),
			Address(gruuAddress)
		);
Ronan's avatar
Ronan committed
340 341
	}

342 343 344 345 346 347 348 349 350
	shared_ptr<EventLog> MainDbPrivate::selectConferenceSubjectEvent (
		long eventId,
		EventLog::Type type,
		time_t date,
		const string &peerAddress
	) const {
		unsigned int notifyId;
		string subject;

351 352 353 354 355 356
		soci::session *session = dbSession.getBackendSession<soci::session>();
		*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);
357 358 359 360 361 362 363 364

		// TODO: Use cache.
		return make_shared<ConferenceSubjectEvent>(
			date,
			Address(peerAddress),
			notifyId,
			subject
		);
Ronan's avatar
Ronan committed
365 366
	}

367 368 369
// -----------------------------------------------------------------------------

	long MainDbPrivate::insertEvent (const EventLog &eventLog) {
370 371 372 373 374 375
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

		*session << "INSERT INTO event (type, date) VALUES (:type, :date)",
		soci::use(static_cast<int>(eventLog.getType())), soci::use(Utils::getLongAsTm(eventLog.getTime()));
		return q->getLastInsertId();
376 377
	}

378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
	long MainDbPrivate::insertConferenceEvent (const EventLog &eventLog, long *chatRoomId) {
		long eventId = insertEvent(eventLog);
		long curChatRoomId = insertSipAddress(
			static_cast<const ConferenceEvent &>(eventLog).getConferenceAddress().asString()
		);

		soci::session *session = dbSession.getBackendSession<soci::session>();
		*session << "INSERT INTO conference_event (event_id, chat_room_id)"
			"  VALUES (:eventId, :chatRoomId)", soci::use(eventId), soci::use(curChatRoomId);

		if (chatRoomId)
			*chatRoomId = curChatRoomId;

		return eventId;
	}

	long MainDbPrivate::insertConferenceCallEvent (const EventLog &eventLog) {
395 396 397 398
		// TODO.
		return 0;
	}

399 400
	long MainDbPrivate::insertConferenceChatMessageEvent (const EventLog &eventLog) {
		shared_ptr<ChatMessage> chatMessage = static_cast<const ConferenceChatMessageEvent &>(eventLog).getChatMessage();
401 402 403 404 405 406 407 408
		shared_ptr<ChatRoom> chatRoom = chatMessage->getChatRoom();
		if (!chatRoom) {
			lError() << "Unable to get a valid chat room. It was removed from database.";
			return -1;
		}

		tm eventTime = Utils::getLongAsTm(static_cast<long>(eventLog.getTime()));

409 410 411 412
		long localSipAddressId = insertSipAddress(chatMessage->getLocalAddress().asString());
		long remoteSipAddressId = insertSipAddress(chatMessage->getRemoteAddress().asString());
		insertChatRoom(remoteSipAddressId, chatRoom->getCapabilities(), eventTime);
		long eventId = insertConferenceEvent(eventLog);
413

414
		soci::session *session = dbSession.getBackendSession<soci::session>();
415

416 417 418 419 420 421 422 423 424 425 426 427
		*session << "INSERT INTO conference_chat_message_event ("
			"  event_id, local_sip_address_id, remote_sip_address_id,"
			"  state, direction, imdn_message_id, is_secured"
			") VALUES ("
			"  :eventId, :localSipaddressId, :remoteSipaddressId,"
			"  :state, :direction, :imdnMessageId, :isSecured"
			")", soci::use(eventId), soci::use(localSipAddressId), soci::use(remoteSipAddressId),
			soci::use(static_cast<int>(chatMessage->getState())), soci::use(static_cast<int>(chatMessage->getDirection())),
			soci::use(chatMessage->getImdnMessageId()), soci::use(chatMessage->isSecured() ? 1 : 0);

		for (const auto &content : chatMessage->getContents())
			insertContent(eventId, content);
428

429 430 431
		return eventId;
	}

432
	long MainDbPrivate::insertConferenceNotifiedEvent (const EventLog &eventLog) {
433 434 435
		long chatRoomId;
		long eventId = insertConferenceEvent(eventLog, &chatRoomId);
		unsigned int lastNotifyId = static_cast<const ConferenceNotifiedEvent &>(eventLog).getNotifyId();
436 437 438

		soci::session *session = dbSession.getBackendSession<soci::session>();
		*session << "INSERT INTO conference_notified_event (event_id, notify_id)"
439 440 441
			"  VALUES (:eventId, :notifyId)", soci::use(eventId), soci::use(lastNotifyId);
		*session << "UPDATE chat_room SET last_notify_id = :lastNotifyId WHERE peer_sip_address_id = :chatRoomId",
			soci::use(lastNotifyId), soci::use(chatRoomId);
442

443 444 445 446 447
		return eventId;
	}

	long MainDbPrivate::insertConferenceParticipantEvent (const EventLog &eventLog) {
		long eventId = insertConferenceNotifiedEvent(eventLog);
448 449 450 451
		long participantAddressId = insertSipAddress(
			static_cast<const ConferenceParticipantEvent &>(eventLog).getParticipantAddress().asString()
		);

452
		soci::session *session = dbSession.getBackendSession<soci::session>();
453
		*session << "INSERT INTO conference_participant_event (event_id, participant_address_id)"
454
			"  VALUES (:eventId, :participantAddressId)", soci::use(eventId), soci::use(participantAddressId);
455

456 457 458 459
		return eventId;
	}

	long MainDbPrivate::insertConferenceParticipantDeviceEvent (const EventLog &eventLog) {
460 461 462 463 464 465
		long eventId = insertConferenceParticipantEvent(eventLog);
		long gruuAddressId = insertSipAddress(
			static_cast<const ConferenceParticipantDeviceEvent &>(eventLog).getGruuAddress().asString()
		);

		soci::session *session = dbSession.getBackendSession<soci::session>();
466
		*session << "INSERT INTO conference_participant_device_event (event_id, gruu_address_id)"
467
			"  VALUES (:eventId, :gruuAddressId)", soci::use(eventId), soci::use(gruuAddressId);
468

469
		return eventId;
470 471 472
	}

	long MainDbPrivate::insertConferenceSubjectEvent (const EventLog &eventLog) {
473
		long eventId = insertConferenceNotifiedEvent(eventLog);
474 475

		soci::session *session = dbSession.getBackendSession<soci::session>();
476
		*session << "INSERT INTO conference_subject_event (event_id, subject)"
477 478 479
			"  VALUES (:eventId, :subject)", soci::use(eventId), soci::use(
				static_cast<const ConferenceSubjectEvent &>(eventLog).getSubject()
			);
480

481
		return eventId;
482 483
	}

484
// -----------------------------------------------------------------------------
485

486
	void MainDb::init () {
487
		L_D();
488
		soci::session *session = d->dbSession.getBackendSession<soci::session>();
489

490
		*session <<
491 492
			"CREATE TABLE IF NOT EXISTS sip_address ("
			"  id" + primaryKeyAutoIncrementStr() + ","
493
			"  value VARCHAR(255) UNIQUE NOT NULL"
494 495
			")";

496
		*session <<
497 498
			"CREATE TABLE IF NOT EXISTS content_type ("
			"  id" + primaryKeyAutoIncrementStr() + ","
499
			"  value VARCHAR(255) UNIQUE NOT NULL"
500 501
			")";

502
		*session <<
503 504
			"CREATE TABLE IF NOT EXISTS event ("
			"  id" + primaryKeyAutoIncrementStr() + ","
505
			"  type TINYINT UNSIGNED NOT NULL,"
506
			"  date DATE NOT NULL"
507 508
			")";

509
		*session <<
510
			"CREATE TABLE IF NOT EXISTS chat_room ("
511
			// Server (for conference) or user sip address.
512
			"  peer_sip_address_id INT UNSIGNED PRIMARY KEY,"
513 514

			// Dialog creation date.
515 516 517 518
			"  creation_date DATE NOT NULL,"

			// Last event date (call, message...).
			"  last_update_date DATE NOT NULL,"
519

520 521 522
			// ConferenceChatRoom, BasicChatRoom, RTT...
			"capabilities TINYINT UNSIGNED,"

523 524 525
			// Chatroom subject.
			"  subject VARCHAR(255),"

526
			"  last_notify_id INT UNSIGNED,"
527

528
			"  FOREIGN KEY (peer_sip_address_id)"
529 530 531 532
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
			")";

533 534 535 536 537 538
		*session <<
			"CREATE TABLE IF NOT EXISTS chat_room_participant ("
			"  chat_room_id INT UNSIGNED NOT NULL,"
			"  sip_address_id INT UNSIGNED NOT NULL,"
			"  is_admin BOOLEAN NOT NULL,"

539
			"  PRIMARY KEY (chat_room_id, sip_address_id),"
540 541 542 543 544 545
			"  FOREIGN KEY (chat_room_id)"
			"    REFERENCES chat_room(peer_sip_address_id)"
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (sip_address_id)"
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
			")";

		*session <<
			"CREATE TABLE IF NOT EXISTS conference_event ("
			"  event_id INT UNSIGNED PRIMARY KEY,"
			"  chat_room_id INT UNSIGNED NOT NULL,"

			"  FOREIGN KEY (event_id)"
			"    REFERENCES event(id)"
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (chat_room_id)"
			"    REFERENCES chat_room(peer_sip_address_id)"
			"    ON DELETE CASCADE"
			")";

561 562 563 564 565 566 567 568 569 570
		*session <<
			"CREATE TABLE IF NOT EXISTS conference_notified_event ("
			"  event_id INT UNSIGNED PRIMARY KEY,"
			"  notify_id INT UNSIGNED NOT NULL,"

			"  FOREIGN KEY (event_id)"
			"    REFERENCES conference_event(event_id)"
			"    ON DELETE CASCADE"
			")";

571 572
		*session <<
			"CREATE TABLE IF NOT EXISTS conference_participant_event ("
573
			"  event_id INT UNSIGNED PRIMARY KEY,"
574 575
			"  participant_address_id INT UNSIGNED NOT NULL,"

576 577
			"  FOREIGN KEY (event_id)"
			"    REFERENCES conference_notified_event(event_id)"
578 579 580 581 582 583 584 585
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (participant_address_id)"
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
			")";

		*session <<
			"CREATE TABLE IF NOT EXISTS conference_participant_device_event ("
586
			"  event_id INT UNSIGNED PRIMARY KEY,"
587 588
			"  gruu_address_id INT UNSIGNED NOT NULL,"

589 590
			"  FOREIGN KEY (event_id)"
			"    REFERENCES conference_participant_event(event_id)"
591 592 593 594 595 596 597 598
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (gruu_address_id)"
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
			")";

		*session <<
			"CREATE TABLE IF NOT EXISTS conference_subject_event ("
599
			"  event_id INT UNSIGNED PRIMARY KEY,"
600 601
			"  subject VARCHAR(255),"

602 603
			"  FOREIGN KEY (event_id)"
			"    REFERENCES conference_notified_event(event_id)"
604
			"    ON DELETE CASCADE"
605 606
			")";

607
		*session <<
608
			"CREATE TABLE IF NOT EXISTS conference_chat_message_event ("
609
			"  event_id INT UNSIGNED PRIMARY KEY,"
610 611
			"  local_sip_address_id INT UNSIGNED NOT NULL,"
			"  remote_sip_address_id INT UNSIGNED NOT NULL,"
612 613 614 615

			// See: https://tools.ietf.org/html/rfc5438#section-6.3
			"  imdn_message_id VARCHAR(255) NOT NULL,"

616 617
			"  state TINYINT UNSIGNED NOT NULL,"
			"  direction TINYINT UNSIGNED NOT NULL,"
618
			"  is_secured BOOLEAN NOT NULL,"
619

620
			"  FOREIGN KEY (event_id)"
621
			"    REFERENCES conference_event(id)"
622
			"    ON DELETE CASCADE,"
623 624
			"  FOREIGN KEY (local_sip_address_id)"
			"    REFERENCES sip_address(id)"
625
			"    ON DELETE CASCADE,"
626
			"  FOREIGN KEY (remote_sip_address_id)"
627
			"    REFERENCES sip_address(id)"
628 629 630
			"    ON DELETE CASCADE"
			")";

631
		*session <<
632
			"CREATE TABLE IF NOT EXISTS chat_message_participant ("
Ronan's avatar
Ronan committed
633
			"  event_id INT UNSIGNED NOT NULL,"
634 635 636
			"  sip_address_id INT UNSIGNED NOT NULL,"
			"  state TINYINT UNSIGNED NOT NULL,"

Ronan's avatar
Ronan committed
637 638
			"  PRIMARY KEY (event_id, sip_address_id),"
			"  FOREIGN KEY (event_id)"
639
			"    REFERENCES conference_chat_message_event(event_id)"
640 641 642
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (sip_address_id)"
			"    REFERENCES sip_address(id)"
643
			"    ON DELETE CASCADE"
644 645
			")";

646
		*session <<
647
			"CREATE TABLE IF NOT EXISTS chat_message_content ("
648
			"  id" + primaryKeyAutoIncrementStr() + ","
Ronan's avatar
Ronan committed
649
			"  event_id INT UNSIGNED NOT NULL,"
650
			"  content_type_id INT UNSIGNED NOT NULL,"
651
			"  body TEXT NOT NULL,"
652

Ronan's avatar
Ronan committed
653
			"  FOREIGN KEY (event_id)"
654
			"    REFERENCES conference_chat_message_event(event_id)"
655 656 657
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (content_type_id)"
			"    REFERENCES content_type(id)"
658 659
			"    ON DELETE CASCADE"
			")";
660

661
		*session <<
662 663
			"CREATE TABLE IF NOT EXISTS chat_message_content_app_data ("
			"  chat_message_content_id INT UNSIGNED NOT NULL,"
664 665 666
			"  key VARCHAR(255),"
			"  data BLOB,"

667 668 669
			"  PRIMARY KEY (chat_message_content_id, key),"
			"  FOREIGN KEY (chat_message_content_id)"
			"    REFERENCES chat_message_content(id)"
670 671 672
			"    ON DELETE CASCADE"
			")";

673
		*session <<
674
			"CREATE TABLE IF NOT EXISTS conference_message_crypto_data ("
Ronan's avatar
Ronan committed
675
			"  event_id INT UNSIGNED NOT NULL,"
676
			"  key VARCHAR(255),"
677 678
			"  data BLOB,"

Ronan's avatar
Ronan committed
679 680
			"  PRIMARY KEY (event_id, key),"
			"  FOREIGN KEY (event_id)"
681
			"    REFERENCES conference_chat_message_event(event_id)"
682
			"    ON DELETE CASCADE"
683
			")";
684 685 686 687

		// Trigger to delete participant_message cache entries.
		string displayedId = Utils::toString(static_cast<int>(ChatMessage::State::Displayed));
		string participantMessageDeleter =
688 689
			"CREATE TRIGGER IF NOT EXISTS chat_message_participant_deleter"
			"  AFTER UPDATE OF state ON chat_message_participant FOR EACH ROW"
690 691
			"  WHEN NEW.state = ";
		participantMessageDeleter += displayedId;
692
		participantMessageDeleter += " AND (SELECT COUNT(*) FROM ("
693 694
			"    SELECT state FROM chat_message_participant WHERE"
			"    NEW.event_id = chat_message_participant.event_id"
695 696 697 698 699
			"    AND state <> ";
		participantMessageDeleter += displayedId;
		participantMessageDeleter += "    LIMIT 1"
			"  )) = 0"
			"  BEGIN"
700 701
			"  DELETE FROM chat_message_participant WHERE NEW.event_id = chat_message_participant.event_id;"
			"  UPDATE conference_chat_message_event SET state = ";
702
		participantMessageDeleter += displayedId;
Ronan's avatar
Ronan committed
703
		participantMessageDeleter += " WHERE event_id = NEW.event_id;"
704 705 706
			"  END";

		*session << participantMessageDeleter;
707
	}
708

709
	bool MainDb::addEvent (const EventLog &eventLog) {
710 711
		L_D();

Ronan's avatar
Ronan committed
712 713
		if (!isConnected()) {
			lWarning() << "Unable to add event. Not connected.";
714
			return false;
Ronan's avatar
Ronan committed
715 716
		}

717 718 719 720 721 722
		bool soFarSoGood = false;

		L_BEGIN_LOG_EXCEPTION

		soci::transaction tr(*d->dbSession.getBackendSession<soci::session>());

Ronan's avatar
Ronan committed
723
		switch (eventLog.getType()) {
724
			case EventLog::Type::None:
725
				return false;
726

727 728
			case EventLog::Type::ConferenceChatMessage:
				d->insertConferenceChatMessageEvent(eventLog);
729 730
				break;

731 732
			case EventLog::Type::CallStart:
			case EventLog::Type::CallEnd:
733
				d->insertConferenceCallEvent(eventLog);
734
				break;
735

736 737
			case EventLog::Type::ConferenceCreated:
			case EventLog::Type::ConferenceDestroyed:
738 739 740
				d->insertConferenceEvent(eventLog);
				break;

741 742 743 744
			case EventLog::Type::ConferenceParticipantAdded:
			case EventLog::Type::ConferenceParticipantRemoved:
			case EventLog::Type::ConferenceParticipantSetAdmin:
			case EventLog::Type::ConferenceParticipantUnsetAdmin:
745 746 747
				d->insertConferenceParticipantEvent(eventLog);
				break;

748 749
			case EventLog::Type::ConferenceParticipantDeviceAdded:
			case EventLog::Type::ConferenceParticipantDeviceRemoved:
750 751 752
				d->insertConferenceParticipantDeviceEvent(eventLog);
				break;

753
			case EventLog::Type::ConferenceSubjectChanged:
754
				d->insertConferenceSubjectEvent(eventLog);
755 756 757
				break;
		}

758 759 760 761 762 763 764
		tr.commit();

		soFarSoGood = true;

		L_END_LOG_EXCEPTION

		return soFarSoGood;
765 766
	}

767
	bool MainDb::deleteEvent (const EventLog &eventLog) {
768 769
		L_D();

Ronan's avatar
Ronan committed
770 771 772 773 774
		if (!isConnected()) {
			lWarning() << "Unable to delete event. Not connected.";
			return false;
		}

Ronan's avatar
Ronan committed
775 776
		long &storageId = const_cast<EventLog &>(eventLog).getPrivate()->storageId;
		if (storageId < 0)
777 778 779 780 781
			return false;

		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
Ronan's avatar
Ronan committed
782 783
		*session << "DELETE FROM event WHERE id = :id", soci::use(storageId);
		storageId = -1;
784 785 786

		L_END_LOG_EXCEPTION

Ronan's avatar
Ronan committed
787
		return storageId == -1;
788 789
	}

790
	void MainDb::cleanEvents (FilterMask mask) {
791 792
		L_D();

Ronan's avatar
Ronan committed
793 794 795 796 797
		if (!isConnected()) {
			lWarning() << "Unable to clean events. Not connected.";
			return;
		}

798
		string query = "DELETE FROM event" +
799
			buildSqlEventFilter({ ConferenceCallFilter, ConferenceChatMessageFilter, ConferenceInfoFilter }, mask);
800 801 802 803 804 805 806

		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
		*session << query;

		L_END_LOG_EXCEPTION
807 808
	}

809
	int MainDb::getEventsCount (FilterMask mask) const {
810
		L_D();
811

Ronan's avatar
Ronan committed
812 813 814 815 816
		if (!isConnected()) {
			lWarning() << "Unable to get events count. Not connected.";
			return 0;
		}

817
		string query = "SELECT COUNT(*) FROM event" +
818
			buildSqlEventFilter({ ConferenceCallFilter, ConferenceChatMessageFilter, ConferenceInfoFilter }, mask);
819 820 821 822 823 824 825 826 827 828 829 830
		int count = 0;

		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
		*session << query, soci::into(count);

		L_END_LOG_EXCEPTION

		return count;
	}

831
	int MainDb::getMessagesCount (const string &peerAddress) const {
832
		L_D();
833

Ronan's avatar
Ronan committed
834 835 836 837
		if (!isConnected()) {
			lWarning() << "Unable to get messages count. Not connected.";
			return 0;
		}
838

839 840 841 842 843
		int count = 0;

		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
844

845
		string query = "SELECT COUNT(*) FROM conference_chat_message_event";
846 847 848
		if (peerAddress.empty())
			*session << query, soci::into(count);
		else {
849 850 851 852
			query += "  WHERE event_id IN ("
				"  SELECT event_id FROM conference_event WHERE chat_room_id = ("
				"    SELECT id FROM sip_address WHERE value = :peerAddress"
				"  )"
853 854 855 856
				")";

			*session << query, soci::use(peerAddress), soci::into(count);
		}
857 858 859 860

		L_END_LOG_EXCEPTION

		return count;
861 862
	}

863
	int MainDb::getUnreadMessagesCount (const string &peerAddress) const {
864
		L_D();
865

Ronan's avatar
Ronan committed
866 867 868 869 870
		if (!isConnected()) {
			lWarning() << "Unable to get unread messages count. Not connected.";
			return 0;
		}

871 872
		int count = 0;

873
		string query = "SELECT COUNT(*) FROM conference_chat_message_event WHERE";
874
		if (!peerAddress.empty())
875 876 877 878 879
			query += " event_id IN ("
				"  SELECT event_id FROM conference_event WHERE chat_room_id = ("
				"    SELECT id FROM sip_address WHERE value = :peerAddress"
				"  )"
				") AND";
880 881

		query += " direction = " + Utils::toString(static_cast<int>(ChatMessage::Direction::Incoming)) +
882
			+ " AND state <> " + Utils::toString(static_cast<int>(ChatMessage::State::Displayed));
883

884 885 886
		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
887 888 889 890 891

		if (peerAddress.empty())
			*session << query, soci::into(count);
		else
			*session << query, soci::use(peerAddress), soci::into(count);
892 893 894 895

		L_END_LOG_EXCEPTION

		return count;
896 897
	}

898
	list<shared_ptr<EventLog>> MainDb::getHistory (const string &peerAddress, int nLast, FilterMask mask) const {
Ronan's avatar
Ronan committed
899 900 901 902 903
		if (!isConnected()) {
			lWarning() << "Unable to get history. Not connected.";
			return list<shared_ptr<EventLog>>();
		}

904
		// TODO.
Ronan's avatar
Ronan committed
905
		return list<shared_ptr<EventLog>>();
906 907
	}

908
	list<shared_ptr<EventLog>> MainDb::getHistory (
909
		const string &peerAddress,
910 911 912 913
		int begin,
		int end,
		FilterMask mask
	) const {
914 915 916 917
		L_D();

		list<shared_ptr<EventLog>> events;

Ronan's avatar
Ronan committed
918 919
		if (!isConnected()) {
			lWarning() << "Unable to get history. Not connected.";
920
			return events;
Ronan's avatar
Ronan committed
921 922
		}

923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
		if (begin < 0)
			begin = 0;

		if (end > 0 && begin > end) {
			lWarning() << "Unable to get history. Invalid range.";
			return events;
		}

		string query = "SELECT id, type, date FROM event"
			"  WHERE id IN ("
			"    SELECT event_id FROM conference_event WHERE chat_room_id = ("
			"      SELECT id FROM sip_address WHERE value = :peerAddress"
			"    )"
			"  )";
		query += buildSqlEventFilter({
			ConferenceCallFilter, ConferenceChatMessageFilter, ConferenceInfoFilter
		}, mask, "AND");
		query += "  ORDER BY id DESC";

		if (end >= 0)
			query += "  LIMIT " + Utils::toString(end + 1 - begin);
		else
			query += "  LIMIT -1";

		if (begin > 0)
			query += "  OFFSET " + Utils::toString(begin);

		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
		soci::transaction tr(*session);

		soci::rowset<soci::row> rows = (session->prepare << query, soci::use(peerAddress));
		for (const auto &row : rows) {
Ronan's avatar
Ronan committed
957
			tm date = row.get<tm>(2);
958
			events.push_back(d->selectGenericConferenceEvent(
959 960 961 962 963
				row.get<long>(0),
				static_cast<EventLog::Type>(row.get<int>(1)),
				mktime(&date),
				peerAddress
			));
964 965 966 967 968
		}

		L_END_LOG_EXCEPTION

		return events;
969 970
	}

971
	void MainDb::cleanHistory (const string &peerAddress, FilterMask mask) {
972 973
		L_D();

Ronan's avatar
Ronan committed
974 975 976 977 978
		if (!isConnected()) {
			lWarning() << "Unable to clean history. Not connected.";
			return;
		}

979 980
		// TODO: Deal with mask.

981
		string query;
982 983 984
		if (mask == MainDb::NoFilter || mask & ConferenceChatMessageFilter)
			query += "SELECT event_id FROM conference_event WHERE chat_room_id = ("
				"  SELECT id FROM sip_address WHERE value = :peerAddress"
985 986 987 988 989
				")";

		if (query.empty())
			return;

990 991 992
		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
993
		*session << "DELETE FROM event WHERE id IN (" + query + ")", soci::use(peerAddress);
994 995

		L_END_LOG_EXCEPTION
996
	}
997

998 999
// -----------------------------------------------------------------------------

1000 1001 1002 1003 1004 1005
list<shared_ptr<ChatRoom>> MainDb::getChatRooms () const {
	list<shared_ptr<ChatRoom>> chatRooms;
	// TODO.
	return chatRooms;
}

1006 1007 1008
shared_ptr<ChatRoom> MainDb::findChatRoom (const string &peerAddress) const {
	L_D();

1009
	// TODO: Use core cache.
1010

1011
	L_BEGIN_LOG_EXCEPTION
1012

1013
	soci::session *session = d->dbSession.getBackendSession<soci::session>();
1014

1015 1016 1017 1018
	tm creationDate;
	tm lastUpdateDate;
	int capabilities;
	string subject;
1019

1020 1021 1022 1023 1024 1025 1026
	*session << "SELECT creation_date, last_update_date, capabilities, subject "
		"  FROM chat_room"
		"  WHERE peer_sip_address_id = ("
		"    SELECT id from sip_address WHERE value = :peerAddress"
		"  )", soci::use(peerAddress), soci::into(creationDate), soci::into(lastUpdateDate),
		soci::use(capabilities), soci::use(subject);

1027 1028
	// TODO.

1029
	L_END_LOG_EXCEPTION
1030 1031 1032 1033 1034 1035

	return shared_ptr<ChatRoom>();
}

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

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
	#define LEGACY_MESSAGE_COL_LOCAL_ADDRESS 1
	#define LEGACY_MESSAGE_COL_REMOTE_ADDRESS 2
	#define LEGACY_MESSAGE_COL_DIRECTION 3
	#define LEGACY_MESSAGE_COL_TEXT 4
	#define LEGACY_MESSAGE_COL_STATE 7
	#define LEGACY_MESSAGE_COL_URL 8
	#define LEGACY_MESSAGE_COL_DATE 9
	#define LEGACY_MESSAGE_COL_APP_DATA 10
	#define LEGACY_MESSAGE_COL_CONTENT_ID 11
	#define LEGACY_MESSAGE_COL_IMDN_MESSAGE_ID 12
	#define LEGACY_MESSAGE_COL_CONTENT_TYPE 13
	#define LEGACY_MESSAGE_COL_IS_SECURED 14

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

		try {
			return message.get<T>(static_cast<size_t>(index));
		} catch (const exception &) {
			isNull = true;
		}

		return T();
	}

1062
	bool MainDb::import (Backend, const string &parameters) {
1063 1064
		L_D();

1065 1066 1067 1068 1069
		if (!isConnected()) {
			lWarning() << "Unable to import data. Not connected.";
			return 0;
		}

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
		// Backend is useless, it's sqlite3. (Only available legacy backend.)
		const string uri = "sqlite3://" + parameters;
		DbSession inDbSession = DbSessionProvider::getInstance()->getSession(uri);

		if (!inDbSession) {
			lWarning() << "Unable to connect to: `" << uri << "`.";
			return false;
		}

		soci::session *inSession = inDbSession.getBackendSession<soci::session>();

		// Import messages.
		try {
1083
			soci::rowset<soci::row> messages = (inSession->prepare << "SELECT * FROM history");
1084
			try {
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
				soci::transaction tr(*d->dbSession.getBackendSession<soci::session>());

				for (const auto &message : messages) {
					const int direction = message.get<int>(LEGACY_MESSAGE_COL_DIRECTION);
					if (direction != 0 && direction != 1) {
						lWarning() << "Unable to import legacy message with invalid direction.";
						continue;
					}

					const int state = message.get<int>(
						LEGACY_MESSAGE_COL_STATE, static_cast<int>(ChatMessage::State::Displayed)
					);
					if (state < 0 || state > static_cast<int>(ChatMessage::State::Displayed)) {
						lWarning() << "Unable to import legacy message with invalid state.";
						continue;
					}

					const tm date = Utils::getLongAsTm(message.get<int>(LEGACY_MESSAGE_COL_DATE, 0));

					bool isNull;
					const string url = getValueFromLegacyMessage<string>(message, LEGACY_MESSAGE_COL_URL, isNull);

					const int contentId = message.get<int>(LEGACY_MESSAGE_COL_CONTENT_ID, -1);
					ContentType contentType(message.get<string>(LEGACY_MESSAGE_COL_CONTENT_TYPE, ""));
					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;
					}

					const string text = getValueFromLegacyMessage<string>(message, LEGACY_MESSAGE_COL_TEXT, isNull);

					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;
						}

						const string appData = getValueFromLegacyMessage<string>(message, LEGACY_MESSAGE_COL_APP_DATA, isNull);
						if (isNull) {
							lWarning() << "Unable to import legacy file message without app data.";
							continue;
						}

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

1143 1144 1145
					soci::session *session = d->dbSession.getBackendSession<soci::session>();
					*session << "INSERT INTO event (type, date) VALUES (:type, :date)",
					soci::use(static_cast<int>(EventLog::Type::ConferenceChatMessage)), soci::use(date);
1146

1147 1148 1149 1150
					long eventId = getLastInsertId();
					long localSipAddressId = d->insertSipAddress(message.get<string>(LEGACY_MESSAGE_COL_LOCAL_ADDRESS));
					long remoteSipAddressId = d->insertSipAddress(message.get<string>(LEGACY_MESSAGE_COL_REMOTE_ADDRESS));
					long chatRoomId = d->insertChatRoom(remoteSipAddressId, static_cast<int>(ChatRoom::Capabilities::Basic), date);
1151

1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
					*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, local_sip_address_id, remote_sip_address_id,"
						"  state, direction, imdn_message_id, is_secured"
						") VALUES ("
						"  :eventId, :localSipaddressId, :remoteSipaddressId,"
						"  :state, :direction, '', :isSecured"
						")", soci::use(eventId), soci::use(localSipAddressId), soci::use(remoteSipAddressId),
						soci::use(state), soci::use(direction), soci::use(message.get<int>(LEGACY_MESSAGE_COL_IS_SECURED, 0));

					d->insertContent(eventId, content);
					d->insertChatRoomParticipant(chatRoomId, remoteSipAddressId, false);
1166 1167

					if (state != static_cast<int>(ChatMessage::State::Displayed))
1168
						d->insertChatMessageParticipant(eventId, remoteSipAddressId, state);
1169 1170 1171
				}

				tr.commit();
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
			} catch (const exception &e) {
				lInfo() << "Failed to import legacy messages from: `" << uri << "`. (" << e.what() << ")";
				return false;
			}
			lInfo() << "Successful import of legacy messages from: `" << uri << "`.";
		} catch (const exception &) {
			// Table doesn't exist.
			return false;
		}

		return true;
	}

1185
// -----------------------------------------------------------------------------
1186 1187
// No backend.
// -----------------------------------------------------------------------------
1188

1189 1190
#else

1191
	void MainDb::init () {}
1192

1193
	bool MainDb::addEvent (const EventLog &) {
1194
		return false;
1195 1196
	}

1197
	bool MainDb::deleteEvent (const EventLog &) {
1198 1199
		return false;
	}
1200

1201
	void MainDb::cleanEvents (FilterMask) {}
1202

1203
	int MainDb::getEventsCount (FilterMask) const {
1204 1205
		return 0;
	}
1206

1207
	int MainDb::getMessagesCount (const string &) const {
1208 1209
		return 0;
	}
1210

1211
	int MainDb::getUnreadMessagesCount (const string &) const {
1212 1213
		return 0;
	}
1214

1215
	list<shared_ptr<EventLog>> MainDb::getHistory (const string &, int, FilterMask) const {
Ronan's avatar
Ronan committed
1216
		return list<shared_ptr<EventLog>>();
1217
	}
1218

1219
	list<shared_ptr<EventLog>> MainDb::getHistory (const string &, int, int, FilterMask) const {
Ronan's avatar
Ronan committed
1220
		return list<shared_ptr<EventLog>>();
1221
	}
1222

1223 1224
	void MainDb::cleanHistory (const string &, FilterMask) {}

1225 1226 1227
	shared_ptr<ChatRoom> MainDb::findChatRoom (const string &) const {
		return nullptr;
	}
1228

1229
	bool MainDb::import (Backend, const string &) {
Ghislain MARY's avatar
Ghislain MARY committed
1230 1231 1232
		return false;
	}

1233
#endif // ifdef SOCI_ENABLED
Ronan's avatar
Ronan committed
1234 1235

LINPHONE_END_NAMESPACE