main-db.cpp 29.1 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

Ronan's avatar
Ronan committed
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"
Ronan's avatar
Ronan committed
32
#include "content/content.h"
33
#include "db/session/db-session-provider.h"
Ronan's avatar
Ronan committed
34
#include "event-log/call-event.h"
Ronan's avatar
Ronan committed
35
#include "event-log/chat-message-event.h"
36 37
#include "event-log/conference-participant-device-event.h"
#include "event-log/conference-subject-event.h"
Ronan's avatar
Ronan committed
38
#include "event-log/event-log-p.h"
Ronan's avatar
Ronan committed
39
#include "logger/logger.h"
Ronan's avatar
Ronan committed
40
#include "main-db-p.h"
Ronan's avatar
Ronan committed
41 42 43

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

Ronan's avatar
Ronan committed
44 45
using namespace std;

Ronan's avatar
Ronan committed
46 47 48 49
LINPHONE_BEGIN_NAMESPACE

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

50
MainDb::MainDb () : AbstractDb(*new MainDbPrivate) {}
Ronan's avatar
Ronan committed
51

52 53
#ifdef SOCI_ENABLED

Ronan's avatar
Ronan committed
54
// -----------------------------------------------------------------------------
55
// Soci backend.
Ronan's avatar
Ronan committed
56 57
// -----------------------------------------------------------------------------

58 59 60 61 62
	template<typename T>
	struct EnumToSql {
		T first;
		const char *second;
	};
63

64 65 66 67 68 69 70
	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)
		);
	}

71 72 73 74
	static constexpr EnumToSql<MainDb::Filter> eventFilterToSql[] = {
		{ MainDb::MessageFilter, "1" },
		{ MainDb::CallFilter, "2" },
		{ MainDb::ConferenceFilter, "3" }
75
	};
76

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

Ronan's avatar
Ronan committed
83 84
// -----------------------------------------------------------------------------

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

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

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

			if (isStart) {
				isStart = false;
				sql += " WHERE ";
			} else
				sql += " OR ";
106
			sql += " type = ";
107 108 109 110 111 112
			sql += mapEventFilterToSql(filter);
		}

		return sql;
	}

113 114
// -----------------------------------------------------------------------------

115
	long MainDbPrivate::insertSipAddress (const string &sipAddress) {
116 117 118
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

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

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

128
	void MainDbPrivate::insertContent (long messageEventId, const Content &content) {
129 130
		L_Q();

131 132
		soci::session *session = dbSession.getBackendSession<soci::session>();

133 134 135 136
		long contentTypeId = insertContentType(content.getContentType().asString());
		*session << "INSERT INTO message_content (message_event_id, content_type_id, body) VALUES"
			"  (:messageEventId, :contentTypeId, :body)", soci::use(messageEventId), soci::use(contentTypeId),
			soci::use(content.getBodyAsString());
137 138 139 140 141 142

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

145
	long MainDbPrivate::insertContentType (const string &contentType) {
146 147 148
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

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

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

158
	long MainDbPrivate::insertEvent (EventLog::Type type, const tm &date) {
159 160 161 162
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

		*session << "INSERT INTO event (type, date) VALUES (:type, :date)",
163
			soci::use(static_cast<int>(type)), soci::use(date);
164
		return q->getLastInsertId();
165 166
	}

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

170
		long id;
171
		*session << "SELECT peer_sip_address_id FROM chat_room WHERE peer_sip_address_id = :sipAddressId",
172
			soci::use(sipAddressId), soci::into(id);
173
		if (!session->got_data())
174 175 176
			*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);
177
		else
178
			*session << "UPDATE chat_room SET last_update_date = :lastUpdateDate WHERE peer_sip_address_id = :sipAddressId",
179
				soci::use(date), soci::use(sipAddressId);
180

181 182 183
		return sipAddressId;
	}

184
	void MainDbPrivate::insertChatRoomParticipant (long chatRoomId, long sipAddressId, bool isAdmin) {
185
		soci::session *session = dbSession.getBackendSession<soci::session>();
186 187 188 189 190 191 192 193 194 195
		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));
196 197
	}

198
	long MainDbPrivate::insertMessageEvent (
199
		const MessageEventReferences &references,
200 201
		int state,
		int direction,
202 203
		const string &imdnMessageId,
		bool isSecured,
204
		const list<Content> &contents
205
	) {
206 207
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();
208

209 210
		*session << "INSERT INTO message_event ("
			"  event_id, chat_room_id, local_sip_address_id, remote_sip_address_id,"
211
			"  state, direction, imdn_message_id, is_secured"
212
			") VALUES ("
213
			"  :eventId, :chatRoomId, :localSipaddressId, :remoteSipaddressId,"
214
			"  :state, :direction, :imdnMessageId, :isSecured"
215
			")", soci::use(references.eventId), soci::use(references.chatRoomId), soci::use(references.localSipAddressId),
216 217
			soci::use(references.remoteSipAddressId), soci::use(state), soci::use(direction),
			soci::use(imdnMessageId), soci::use(isSecured ? 1 : 0);
218 219 220 221

		long messageEventId = q->getLastInsertId();

		for (const auto &content : contents)
222
			insertContent(messageEventId, content);
223 224

		return messageEventId;
225 226
	}

227
	void MainDbPrivate::insertMessageParticipant (long messageEventId, long sipAddressId, int state) {
228 229 230 231
		soci::session *session = dbSession.getBackendSession<soci::session>();
		soci::statement statement = (
			session->prepare << "UPDATE message_participant SET state = :state"
				"  WHERE message_event_id = :messageEventId AND sip_address_id = :sipAddressId",
232
				soci::use(state), soci::use(messageEventId), soci::use(sipAddressId)
233 234
		);
		statement.execute(true);
235
		if (statement.get_affected_rows() == 0 && state != static_cast<int>(ChatMessage::State::Displayed))
236 237
			*session << "INSERT INTO message_participant (message_event_id, sip_address_id, state)"
				"  VALUES (:messageEventId, :sipAddressId, :state)",
238
				soci::use(messageEventId), soci::use(sipAddressId), soci::use(state);
239 240
	}

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
// -----------------------------------------------------------------------------

	long MainDbPrivate::insertEvent (const EventLog &eventLog) {
		return insertEvent(eventLog.getType(), Utils::getLongAsTm(eventLog.getTime()));
	}

	long MainDbPrivate::insertMessageEvent (const EventLog &eventLog) {
		// TODO.
		return 0;
	}

	long MainDbPrivate::insertConferenceEvent (const EventLog &eventLog) {
		long eventId = insertEvent(eventLog);
		soci::session *session = dbSession.getBackendSession<soci::session>();
		*session << "INSERT INTO conference_event (event_id, chat_room_id)"
			"  VALUES (:eventId, (SELECT id FROM sip_address WHERE value = :conferenceAddress))",
			soci::use(eventId), soci::use(static_cast<const ConferenceEvent &>(eventLog).getConferenceAddress().asString());
		return eventId;
	}

	long MainDbPrivate::insertConferenceParticipantEvent (const EventLog &eventLog) {
		long eventId = insertConferenceEvent(eventLog);
263
		soci::session *session = dbSession.getBackendSession<soci::session>();
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
		*session << "INSERT INTO conference_participant_event (conference_event_id, chat_room_id)"
			"  VALUES (:eventId, (SELECT id FROM sip_address WHERE value = :participantAddress))",
			soci::use(eventId),
			soci::use(static_cast<const ConferenceParticipantEvent &>(eventLog).getParticipantAddress().asStringUriOnly());
		return eventId;
	}

	long MainDbPrivate::insertConferenceParticipantDeviceEvent (const EventLog &eventLog) {
		// TODO.
		return 0;
	}

	long MainDbPrivate::insertConferenceSubjectEvent (const EventLog &eventLog) {
		// TODO.
		return 0;
279 280
	}

281 282
// -----------------------------------------------------------------------------

283 284 285 286 287 288 289 290 291 292 293 294 295
	#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

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

		try {
301
			return message.get<T>(static_cast<size_t>(index));
302 303 304 305 306 307 308
		} catch (const exception &) {
			isNull = true;
		}

		return T();
	}

309
// -----------------------------------------------------------------------------
Ronan's avatar
Ronan committed
310

311
	void MainDb::init () {
312
		L_D();
Ronan's avatar
Ronan committed
313
		soci::session *session = d->dbSession.getBackendSession<soci::session>();
314

Ronan's avatar
Ronan committed
315
		*session <<
316 317
			"CREATE TABLE IF NOT EXISTS sip_address ("
			"  id" + primaryKeyAutoIncrementStr() + ","
Ronan's avatar
Ronan committed
318
			"  value VARCHAR(255) UNIQUE NOT NULL"
319 320
			")";

321
		*session <<
322 323
			"CREATE TABLE IF NOT EXISTS content_type ("
			"  id" + primaryKeyAutoIncrementStr() + ","
Ronan's avatar
Ronan committed
324
			"  value VARCHAR(255) UNIQUE NOT NULL"
325 326
			")";

Ronan's avatar
Ronan committed
327
		*session <<
328 329
			"CREATE TABLE IF NOT EXISTS event ("
			"  id" + primaryKeyAutoIncrementStr() + ","
330
			"  type TINYINT UNSIGNED NOT NULL,"
331
			"  date DATE NOT NULL"
332 333
			")";

Ronan's avatar
Ronan committed
334
		*session <<
335
			"CREATE TABLE IF NOT EXISTS chat_room ("
336
			// Server (for conference) or user sip address.
337
			"  peer_sip_address_id INT UNSIGNED PRIMARY KEY,"
338 339

			// Dialog creation date.
340 341 342 343
			"  creation_date DATE NOT NULL,"

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

345 346 347
			// ConferenceChatRoom, BasicChatRoom, RTT...
			"capabilities TINYINT UNSIGNED,"

348 349 350
			// Chatroom subject.
			"  subject VARCHAR(255),"

351 352
			"  last_notify INT UNSIGNED,"

353
			"  FOREIGN KEY (peer_sip_address_id)"
354 355 356 357
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
			")";

358 359 360 361 362 363
		*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,"

364
			"  PRIMARY KEY (chat_room_id, sip_address_id),"
365 366 367 368 369 370
			"  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"
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
			")";

		*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"
			")";

		*session <<
			"CREATE TABLE IF NOT EXISTS conference_participant_event ("
			"  conference_event_id INT UNSIGNED PRIMARY KEY,"
			"  participant_address_id INT UNSIGNED NOT NULL,"

			"  FOREIGN KEY (conference_event_id)"
			"    REFERENCES event(event_id)"
			"    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 ("
			"  conference_participant_event_id INT UNSIGNED PRIMARY KEY,"
			"  gruu_address_id INT UNSIGNED NOT NULL,"

			"  FOREIGN KEY (conference_participant_event_id)"
			"    REFERENCES conference_participant_event(conference_event_id)"
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (gruu_address_id)"
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
			")";

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

			"  FOREIGN KEY (conference_event_id)"
			"    REFERENCES event(event_id)"
			"    ON DELETE CASCADE"
420 421
			")";

Ronan's avatar
Ronan committed
422
		*session <<
423
			"CREATE TABLE IF NOT EXISTS message_event ("
424
			"  event_id INT UNSIGNED PRIMARY KEY,"
425 426 427
			"  chat_room_id INT UNSIGNED NOT NULL,"
			"  local_sip_address_id INT UNSIGNED NOT NULL,"
			"  remote_sip_address_id INT UNSIGNED NOT NULL,"
428 429 430 431

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

432 433
			"  state TINYINT UNSIGNED NOT NULL,"
			"  direction TINYINT UNSIGNED NOT NULL,"
434
			"  is_secured BOOLEAN NOT NULL,"
435

436 437 438
			"  FOREIGN KEY (event_id)"
			"    REFERENCES event(id)"
			"    ON DELETE CASCADE,"
439 440
			"  FOREIGN KEY (chat_room_id)"
			"    REFERENCES chat_room(peer_sip_address_id)"
441
			"    ON DELETE CASCADE,"
442 443
			"  FOREIGN KEY (local_sip_address_id)"
			"    REFERENCES sip_address(id)"
444
			"    ON DELETE CASCADE,"
445
			"  FOREIGN KEY (remote_sip_address_id)"
446
			"    REFERENCES sip_address(id)"
447 448 449
			"    ON DELETE CASCADE"
			")";

450 451 452 453 454 455 456 457
		*session <<
			"CREATE TABLE IF NOT EXISTS message_participant ("
			"  message_event_id INT UNSIGNED NOT NULL,"
			"  sip_address_id INT UNSIGNED NOT NULL,"
			"  state TINYINT UNSIGNED NOT NULL,"

			"  PRIMARY KEY (message_event_id, sip_address_id),"
			"  FOREIGN KEY (message_event_id)"
458
			"    REFERENCES message_event(event_id)"
459 460 461
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (sip_address_id)"
			"    REFERENCES sip_address(id)"
462
			"    ON DELETE CASCADE"
463 464
			")";

465
		*session <<
466
			"CREATE TABLE IF NOT EXISTS message_content ("
467 468
			"  id" + primaryKeyAutoIncrementStr() + ","
			"  message_event_id INT UNSIGNED NOT NULL,"
469
			"  content_type_id INT UNSIGNED NOT NULL,"
470
			"  body TEXT NOT NULL,"
471

472
			"  FOREIGN KEY (message_event_id)"
473
			"    REFERENCES message_event(event_id)"
474 475 476
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (content_type_id)"
			"    REFERENCES content_type(id)"
477 478
			"    ON DELETE CASCADE"
			")";
479

480 481 482 483 484 485 486 487 488 489 490 491
		*session <<
			"CREATE TABLE IF NOT EXISTS message_content_app_data ("
			"  message_content_id INT UNSIGNED NOT NULL,"
			"  key VARCHAR(255),"
			"  data BLOB,"

			"  PRIMARY KEY (message_content_id, key),"
			"  FOREIGN KEY (message_content_id)"
			"    REFERENCES message_content(id)"
			"    ON DELETE CASCADE"
			")";

492 493 494
		*session <<
			"CREATE TABLE IF NOT EXISTS message_crypto_data ("
			"  message_event_id INT UNSIGNED NOT NULL,"
495
			"  key VARCHAR(255),"
496 497
			"  data BLOB,"

498
			"  PRIMARY KEY (message_event_id, key),"
499
			"  FOREIGN KEY (message_event_id)"
500
			"    REFERENCES message_event(event_id)"
501
			"    ON DELETE CASCADE"
502
			")";
503 504 505 506

		// Trigger to delete participant_message cache entries.
		string displayedId = Utils::toString(static_cast<int>(ChatMessage::State::Displayed));
		string participantMessageDeleter =
507
			"CREATE TRIGGER IF NOT EXISTS message_participant_deleter"
508 509 510
			"  AFTER UPDATE OF state ON message_participant FOR EACH ROW"
			"  WHEN NEW.state = ";
		participantMessageDeleter += displayedId;
511
		participantMessageDeleter += " AND (SELECT COUNT(*) FROM ("
512 513 514 515 516 517 518 519
			"    SELECT state FROM message_participant WHERE"
			"    NEW.message_event_id = message_participant.message_event_id"
			"    AND state <> ";
		participantMessageDeleter += displayedId;
		participantMessageDeleter += "    LIMIT 1"
			"  )) = 0"
			"  BEGIN"
			"  DELETE FROM message_participant WHERE NEW.message_event_id = message_participant.message_event_id;"
520 521 522
			"  UPDATE message_event SET state = ";
		participantMessageDeleter += displayedId;
		participantMessageDeleter += " WHERE event_id = NEW.message_event_id;"
523 524 525
			"  END";

		*session << participantMessageDeleter;
Ronan's avatar
Ronan committed
526
	}
527

528
	bool MainDb::addEvent (const EventLog &eventLog) {
529 530
		L_D();

Ronan's avatar
Ronan committed
531 532
		if (!isConnected()) {
			lWarning() << "Unable to add event. Not connected.";
533
			return false;
Ronan's avatar
Ronan committed
534 535
		}

Ronan's avatar
Ronan committed
536
		// TODO.
Ronan's avatar
Ronan committed
537
		switch (eventLog.getType()) {
538
			case EventLog::Type::None:
Ronan's avatar
Ronan committed
539
				return false;
540

Ronan's avatar
Ronan committed
541
			case EventLog::Type::ChatMessage:
542 543 544
				d->insertMessageEvent(eventLog);
				break;

545 546
			case EventLog::Type::CallStart:
			case EventLog::Type::CallEnd:
547 548
				return false; // TODO.

549 550
			case EventLog::Type::ConferenceCreated:
			case EventLog::Type::ConferenceDestroyed:
551 552 553
				d->insertConferenceEvent(eventLog);
				break;

554 555 556 557
			case EventLog::Type::ConferenceParticipantAdded:
			case EventLog::Type::ConferenceParticipantRemoved:
			case EventLog::Type::ConferenceParticipantSetAdmin:
			case EventLog::Type::ConferenceParticipantUnsetAdmin:
558 559 560
				d->insertConferenceParticipantEvent(eventLog);
				break;

561 562
			case EventLog::Type::ConferenceParticipantDeviceAdded:
			case EventLog::Type::ConferenceParticipantDeviceRemoved:
563 564 565
				d->insertConferenceParticipantDeviceEvent(eventLog);
				break;

566
			case EventLog::Type::ConferenceSubjectChanged:
567
				d->insertConferenceSubjectEvent(eventLog);
Ronan's avatar
Ronan committed
568 569 570 571 572 573
				break;
		}

		return true;
	}

574
	bool MainDb::deleteEvent (const EventLog &eventLog) {
Ronan's avatar
Ronan committed
575 576
		L_D();

Ronan's avatar
Ronan committed
577 578 579 580 581
		if (!isConnected()) {
			lWarning() << "Unable to delete event. Not connected.";
			return false;
		}

Ronan's avatar
Ronan committed
582 583
		long &storageId = const_cast<EventLog &>(eventLog).getPrivate()->storageId;
		if (storageId < 0)
Ronan's avatar
Ronan committed
584 585 586 587 588
			return false;

		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
Ronan's avatar
Ronan committed
589 590
		*session << "DELETE FROM event WHERE id = :id", soci::use(storageId);
		storageId = -1;
Ronan's avatar
Ronan committed
591 592 593

		L_END_LOG_EXCEPTION

Ronan's avatar
Ronan committed
594
		return storageId == -1;
Ronan's avatar
Ronan committed
595 596
	}

597
	void MainDb::cleanEvents (FilterMask mask) {
Ronan's avatar
Ronan committed
598 599
		L_D();

Ronan's avatar
Ronan committed
600 601 602 603 604
		if (!isConnected()) {
			lWarning() << "Unable to clean events. Not connected.";
			return;
		}

Ronan's avatar
Ronan committed
605 606 607 608 609 610 611 612 613
		string query = "DELETE FROM event" +
			buildSqlEventFilter({ MessageFilter, CallFilter, ConferenceFilter }, mask);

		L_BEGIN_LOG_EXCEPTION

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

		L_END_LOG_EXCEPTION
Ronan's avatar
Ronan committed
614 615
	}

616
	int MainDb::getEventsCount (FilterMask mask) const {
617
		L_D();
Ronan's avatar
Ronan committed
618

Ronan's avatar
Ronan committed
619 620 621 622 623
		if (!isConnected()) {
			lWarning() << "Unable to get events count. Not connected.";
			return 0;
		}

Ronan's avatar
Ronan committed
624 625 626 627 628 629 630 631 632 633 634 635 636 637
		string query = "SELECT COUNT(*) FROM event" +
			buildSqlEventFilter({ MessageFilter, CallFilter, ConferenceFilter }, mask);
		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;
	}

638
	int MainDb::getMessagesCount (const string &peerAddress) const {
639
		L_D();
640

Ronan's avatar
Ronan committed
641 642 643 644
		if (!isConnected()) {
			lWarning() << "Unable to get messages count. Not connected.";
			return 0;
		}
645

646 647 648 649 650
		int count = 0;

		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
Ronan's avatar
Ronan committed
651 652 653 654 655 656

		string query = "SELECT COUNT(*) FROM message_event";
		if (peerAddress.empty())
			*session << query, soci::into(count);
		else {
			query += "  WHERE chat_room_id = ("
657
				"  SELECT id FROM sip_address WHERE value = :peerAddress"
Ronan's avatar
Ronan committed
658 659 660 661
				")";

			*session << query, soci::use(peerAddress), soci::into(count);
		}
662 663 664 665

		L_END_LOG_EXCEPTION

		return count;
Ronan's avatar
Ronan committed
666 667
	}

668
	int MainDb::getUnreadMessagesCount (const string &peerAddress) const {
669
		L_D();
670

Ronan's avatar
Ronan committed
671 672 673 674 675
		if (!isConnected()) {
			lWarning() << "Unable to get unread messages count. Not connected.";
			return 0;
		}

676 677
		int count = 0;

678 679 680 681 682 683 684
		string query = "SELECT COUNT(*) FROM message_event WHERE";
		if (!peerAddress.empty())
			query += " chat_room_id = ("
				"  SELECT id FROM sip_address WHERE value = :peerAddress"
				") AND ";

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

687 688 689
		L_BEGIN_LOG_EXCEPTION

		soci::session *session = d->dbSession.getBackendSession<soci::session>();
690 691 692 693 694

		if (peerAddress.empty())
			*session << query, soci::into(count);
		else
			*session << query, soci::use(peerAddress), soci::into(count);
695 696 697 698

		L_END_LOG_EXCEPTION

		return count;
Ronan's avatar
Ronan committed
699 700
	}

701
	list<shared_ptr<EventLog>> MainDb::getHistory (const string &peerAddress, int nLast, FilterMask mask) const {
Ronan's avatar
Ronan committed
702 703 704 705 706
		if (!isConnected()) {
			lWarning() << "Unable to get history. Not connected.";
			return list<shared_ptr<EventLog>>();
		}

Ronan's avatar
Ronan committed
707
		// TODO.
Ronan's avatar
Ronan committed
708
		(void)peerAddress;
Ronan's avatar
Ronan committed
709 710
		(void)nLast;
		(void)mask;
Ronan's avatar
Ronan committed
711
		return list<shared_ptr<EventLog>>();
Ronan's avatar
Ronan committed
712 713
	}

714
	list<shared_ptr<EventLog>> MainDb::getHistory (
Ronan's avatar
Ronan committed
715
		const string &peerAddress,
716 717 718 719
		int begin,
		int end,
		FilterMask mask
	) const {
Ronan's avatar
Ronan committed
720 721 722 723 724
		if (!isConnected()) {
			lWarning() << "Unable to get history. Not connected.";
			return list<shared_ptr<EventLog>>();
		}

Ronan's avatar
Ronan committed
725
		// TODO.
Ronan's avatar
Ronan committed
726
		(void)peerAddress;
Ronan's avatar
Ronan committed
727 728 729
		(void)begin;
		(void)end;
		(void)mask;
Ronan's avatar
Ronan committed
730
		return list<shared_ptr<EventLog>>();
Ronan's avatar
Ronan committed
731 732
	}

733
	void MainDb::cleanHistory (const string &peerAddress, FilterMask mask) {
734 735
		L_D();

Ronan's avatar
Ronan committed
736 737 738 739 740
		if (!isConnected()) {
			lWarning() << "Unable to clean history. Not connected.";
			return;
		}

741
		string query;
742
		if (mask == MainDb::NoFilter || mask & MessageFilter)
743 744 745 746 747 748 749 750 751
			query += "SELECT event_id FROM message_event WHERE chat_room_id = ("
				"  SELECT peer_sip_address_id FROM chat_room WHERE peer_sip_address_id = ("
				"    SELECT id FROM sip_address WHERE value = :peerAddress"
				"  )"
				")";

		if (query.empty())
			return;

752 753 754
		L_BEGIN_LOG_EXCEPTION

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

		L_END_LOG_EXCEPTION
Ronan's avatar
Ronan committed
758
	}
Ronan's avatar
Ronan committed
759

760 761
// -----------------------------------------------------------------------------

762 763 764
shared_ptr<ChatRoom> MainDb::findChatRoom (const string &peerAddress) const {
	L_D();

765
	// TODO: Use core cache.
766

Ronan's avatar
Ronan committed
767
	L_BEGIN_LOG_EXCEPTION
768

Ronan's avatar
Ronan committed
769
	soci::session *session = d->dbSession.getBackendSession<soci::session>();
770

Ronan's avatar
Ronan committed
771 772 773 774
	tm creationDate;
	tm lastUpdateDate;
	int capabilities;
	string subject;
775

Ronan's avatar
Ronan committed
776 777 778 779 780 781 782 783
	*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);

	L_END_LOG_EXCEPTION
784 785 786 787 788 789 790

	return shared_ptr<ChatRoom>();
}

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

	bool MainDb::import (Backend, const string &parameters) {
791 792
		L_D();

793 794 795 796 797
		if (!isConnected()) {
			lWarning() << "Unable to import data. Not connected.";
			return 0;
		}

798 799 800 801 802 803 804 805 806 807 808 809 810
		// 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 {
811
			soci::rowset<soci::row> messages = (inSession->prepare << "SELECT * FROM history");
812
			try {
Ronan's avatar
Ronan committed
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
				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);
					}

					struct MessageEventReferences references;
					references.eventId = d->insertEvent(EventLog::Type::ChatMessage, date);
					references.localSipAddressId = d->insertSipAddress(message.get<string>(LEGACY_MESSAGE_COL_LOCAL_ADDRESS));
					references.remoteSipAddressId = d->insertSipAddress(message.get<string>(LEGACY_MESSAGE_COL_REMOTE_ADDRESS));
					references.chatRoomId = d->insertChatRoom(
						references.remoteSipAddressId,
						static_cast<int>(ChatRoom::Capabilities::Basic),
						date
					);

					d->insertChatRoomParticipant(references.chatRoomId, references.remoteSipAddressId, false);

					long messageEventId = d->insertMessageEvent (
						references,
885 886
						state,
						direction,
Ronan's avatar
Ronan committed
887 888 889 890 891 892 893 894 895
						message.get<string>(LEGACY_MESSAGE_COL_IMDN_MESSAGE_ID, ""),
						!!message.get<int>(LEGACY_MESSAGE_COL_IS_SECURED, 0),
						{ move(content) }
					);

					if (state != static_cast<int>(ChatMessage::State::Displayed))
						d->insertMessageParticipant(
							messageEventId,
							references.remoteSipAddressId,
896
							state
Ronan's avatar
Ronan committed
897 898 899 900
						);
				}

				tr.commit();
901 902 903 904 905 906 907 908 909 910 911 912 913
			} 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;
	}

Ronan's avatar
Ronan committed
914
// -----------------------------------------------------------------------------
Ronan's avatar
Ronan committed
915 916
// No backend.
// -----------------------------------------------------------------------------
Ronan's avatar
Ronan committed
917

Ronan's avatar
Ronan committed
918 919
#else

920
	void MainDb::init () {}
Ronan's avatar
Ronan committed
921

922
	bool MainDb::addEvent (const EventLog &) {
Ronan's avatar
Ronan committed
923
		return false;
Ronan's avatar
Ronan committed
924 925
	}

926
	bool MainDb::deleteEvent (const EventLog &) {
Ronan's avatar
Ronan committed
927 928
		return false;
	}
Ronan's avatar
Ronan committed
929

930
	void MainDb::cleanEvents (FilterMask) {}
Ronan's avatar
Ronan committed
931

932
	int MainDb::getEventsCount (FilterMask) const {
Ronan's avatar
Ronan committed
933 934
		return 0;
	}
Ronan's avatar
Ronan committed
935

936
	int MainDb::getMessagesCount (const string &) const {
Ronan's avatar
Ronan committed
937 938
		return 0;
	}
Ronan's avatar
Ronan committed
939

940
	int MainDb::getUnreadMessagesCount (const string &) const {
Ronan's avatar
Ronan committed
941 942
		return 0;
	}
Ronan's avatar
Ronan committed
943

944
	list<shared_ptr<EventLog>> MainDb::getHistory (const string &, int, FilterMask) const {
Ronan's avatar
Ronan committed
945
		return list<shared_ptr<EventLog>>();
Ronan's avatar
Ronan committed
946
	}
Ronan's avatar
Ronan committed
947

948
	list<shared_ptr<EventLog>> MainDb::getHistory (const string &, int, int, FilterMask) const {
Ronan's avatar
Ronan committed
949
		return list<shared_ptr<EventLog>>();
Ronan's avatar
Ronan committed
950
	}
Ronan's avatar
Ronan committed
951

952 953
	void MainDb::cleanHistory (const string &, FilterMask) {}

954 955 956
	shared_ptr<ChatRoom> MainDb::findChatRoom (const string &) const {
		return nullptr;
	}
Ronan's avatar
Ronan committed
957

958
	bool MainDb::import (Backend, const string &) {
Ghislain MARY's avatar
Ghislain MARY committed
959 960 961
		return false;
	}

Ronan's avatar
Ronan committed
962
#endif // ifdef SOCI_ENABLED
Ronan's avatar
Ronan committed
963 964

LINPHONE_END_NAMESPACE