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

Ronan's avatar
Ronan committed
29
#include "chat/chat-message/chat-message-p.h"
30
#include "chat/chat-room/client-group-chat-room.h"
31
#include "conference/participant.h"
32
#include "content/content-type.h"
Ronan's avatar
Ronan committed
33
#include "content/content.h"
Ronan's avatar
Ronan committed
34
#include "core/core-p.h"
35
#include "db/session/db-session-provider.h"
Ronan's avatar
Ronan committed
36
#include "event-log/event-log-p.h"
37
#include "event-log/events.h"
Ronan's avatar
Ronan committed
38
#include "logger/logger.h"
39
#include "main-db-event-key-p.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 (const shared_ptr<Core> &core) : AbstractDb(*new MainDbPrivate), CoreAccessor(core) {}
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
	static constexpr EnumToSql<MainDb::Filter> eventFilterToSql[] = {
72
		{ MainDb::ConferenceCallFilter, "3, 4" },
Ronan's avatar
Ronan committed
73
		{ MainDb::ConferenceChatMessageFilter, "5" },
74
		{ MainDb::ConferenceInfoFilter, "1, 2, 6, 7, 8, 9, 10, 11, 12" }
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
// -----------------------------------------------------------------------------

Ronan's avatar
Ronan committed
85 86 87 88 89
	static string buildSqlEventFilter (
		const list<MainDb::Filter> &filters,
		MainDb::FilterMask mask,
		const string &condKeyWord = "WHERE"
	) {
90
		L_ASSERT(
91
			find_if(filters.cbegin(), filters.cend(), [](const MainDb::Filter &filter) {
92 93
				return filter == MainDb::NoFilter;
			}) == filters.cend()
94 95
		);

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

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

			if (isStart) {
				isStart = false;
Ronan's avatar
Ronan committed
107
				sql += " " + condKeyWord + " type IN (";
108
			} else
Ronan's avatar
Ronan committed
109
				sql += ", ";
110 111 112
			sql += mapEventFilterToSql(filter);
		}

Ronan's avatar
Ronan committed
113 114 115
		if (!isStart)
			sql += ") ";

116 117 118
		return sql;
	}

119 120
// -----------------------------------------------------------------------------

121
	long long MainDbPrivate::insertSipAddress (const string &sipAddress) {
122 123 124
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

125 126
		long long id = selectSipAddressId(sipAddress);
		if (id >= 0)
127 128
			return id;

Ronan's avatar
Ronan committed
129
		lInfo() << "Insert new sip address in database: `" << sipAddress << "`.";
130 131
		*session << "INSERT INTO sip_address (value) VALUES (:sipAddress)", soci::use(sipAddress);
		return q->getLastInsertId();
132 133
	}

134
	void MainDbPrivate::insertContent (long long eventId, const Content &content) {
135
		L_Q();
136 137
		soci::session *session = dbSession.getBackendSession<soci::session>();

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

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

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

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

Ronan's avatar
Ronan committed
159
		lInfo() << "Insert new content type in database: `" << contentType << "`.";
160 161
		*session << "INSERT INTO content_type (value) VALUES (:contentType)", soci::use(contentType);
		return q->getLastInsertId();
162 163
	}

164 165 166 167 168 169 170 171
	long long MainDbPrivate::insertChatRoom (
		long long peerSipAddressId,
		long long localSipAddressId,
		int capabilities,
		const tm &date
	) {
		L_Q();

172 173
		soci::session *session = dbSession.getBackendSession<soci::session>();

174 175 176 177 178 179 180 181 182 183 184
		long long id = selectChatRoomId(peerSipAddressId, localSipAddressId);
		if (id < 0) {
			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_date, last_update_date, capabilities, subject"
				") VALUES (:peerSipAddressId, :localSipAddressId, :creationDate, :lastUpdateDate, :capabilities, '')",
				soci::use(peerSipAddressId), soci::use(localSipAddressId), soci::use(date), soci::use(date),
				soci::use(capabilities);

			return q->getLastInsertId();
Ronan's avatar
Ronan committed
185
		}
186

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
		// Update date if chat room exists. Do not touch capabilities.
		*session << "UPDATE chat_room SET last_update_date = :lastUpdateDate"
			"  WHERE id = :chatRoomId",
			soci::use(date), soci::use(id);

		return id;
	}

	long long MainDbPrivate::insertChatRoom (const ChatRoomId &chatRoomId, int capabilities, const tm &date) {
		return insertChatRoom (
			insertSipAddress(chatRoomId.getPeerAddress().asString()),
			insertSipAddress(chatRoomId.getLocalAddress().asString()),
			capabilities,
			date
		);
202 203
	}

204
	void MainDbPrivate::insertChatRoomParticipant (long long chatRoomId, long long sipAddressId, bool isAdmin) {
205
		soci::session *session = dbSession.getBackendSession<soci::session>();
206 207
		soci::statement statement = (
			session->prepare << "UPDATE chat_room_participant SET is_admin = :isAdmin"
208
				"  WHERE chat_room_id = :chatRoomId AND participant_address_id = :sipAddressId",
209 210 211
				soci::use(static_cast<int>(isAdmin)), soci::use(chatRoomId), soci::use(sipAddressId)
		);
		statement.execute(true);
Ronan's avatar
Ronan committed
212 213
		if (statement.get_affected_rows() == 0) {
			lInfo() << "Insert new chat room participant in database: `" << sipAddressId << "` (isAdmin=" << isAdmin << ").";
214
			*session << "INSERT INTO chat_room_participant (chat_room_id, participant_address_id, is_admin)"
215 216
				"  VALUES (:chatRoomId, :sipAddressId, :isAdmin)",
				soci::use(chatRoomId), soci::use(sipAddressId), soci::use(static_cast<int>(isAdmin));
Ronan's avatar
Ronan committed
217
		}
218 219
	}

220
	void MainDbPrivate::insertChatMessageParticipant (long long eventId, long long sipAddressId, int state) {
221 222
		soci::session *session = dbSession.getBackendSession<soci::session>();
		soci::statement statement = (
223
			session->prepare << "UPDATE chat_message_participant SET state = :state"
224
				"  WHERE event_id = :eventId AND participant_address_id = :sipAddressId",
Ronan's avatar
Ronan committed
225
				soci::use(state), soci::use(eventId), soci::use(sipAddressId)
226 227
		);
		statement.execute(true);
228
		if (statement.get_affected_rows() == 0 && state != static_cast<int>(ChatMessage::State::Displayed))
229
			*session << "INSERT INTO chat_message_participant (event_id, participant_address_id, state)"
Ronan's avatar
Ronan committed
230 231
				"  VALUES (:eventId, :sipAddressId, :state)",
				soci::use(eventId), soci::use(sipAddressId), soci::use(state);
232 233
	}

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
	long long MainDbPrivate::selectSipAddressId (const std::string &sipAddress) const {
		soci::session *session = dbSession.getBackendSession<soci::session>();

		long long id;
		*session << "SELECT id FROM sip_address WHERE value = :sipAddress", soci::use(sipAddress), soci::into(id);
		return session->got_data() ? id : -1;
	}

	long long MainDbPrivate::selectChatRoomId (long long peerSipAddressId, long long localSipAddressId) const {
		soci::session *session = dbSession.getBackendSession<soci::session>();

		long long id;
		*session << "SELECT id FROM chat_room"
			"  WHERE peer_sip_address_id = :peerSipAddressId AND local_sip_address_id = :localSipAddressId",
			soci::use(peerSipAddressId), soci::use(localSipAddressId), soci::into(id);
		return session->got_data() ? id : -1;
	}

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

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

		return selectChatRoomId(peerSipAddressId, localSipAddressId);
	}

Ronan's avatar
Ronan committed
264 265
// -----------------------------------------------------------------------------

266
	shared_ptr<EventLog> MainDbPrivate::selectGenericConferenceEvent (
267
		long long eventId,
268 269
		EventLog::Type type,
		time_t date,
270
		const ChatRoomId &chatRoomId
271
	) const {
Ronan's avatar
Ronan committed
272 273 274 275 276 277
		switch (type) {
			case EventLog::Type::None:
				return nullptr;

			case EventLog::Type::ConferenceCreated:
			case EventLog::Type::ConferenceDestroyed:
278
				return selectConferenceEvent(eventId, type, date, chatRoomId);
Ronan's avatar
Ronan committed
279

280 281
			case EventLog::Type::ConferenceCallStart:
			case EventLog::Type::ConferenceCallEnd:
282
				return selectConferenceCallEvent(eventId, type, date, chatRoomId);
Ronan's avatar
Ronan committed
283 284

			case EventLog::Type::ConferenceChatMessage:
285
				return selectConferenceChatMessageEvent(eventId, type, date, chatRoomId);
Ronan's avatar
Ronan committed
286 287 288 289 290

			case EventLog::Type::ConferenceParticipantAdded:
			case EventLog::Type::ConferenceParticipantRemoved:
			case EventLog::Type::ConferenceParticipantSetAdmin:
			case EventLog::Type::ConferenceParticipantUnsetAdmin:
291
				return selectConferenceParticipantEvent(eventId, type, date, chatRoomId);
Ronan's avatar
Ronan committed
292 293 294

			case EventLog::Type::ConferenceParticipantDeviceAdded:
			case EventLog::Type::ConferenceParticipantDeviceRemoved:
295
				return selectConferenceParticipantDeviceEvent(eventId, type, date, chatRoomId);
Ronan's avatar
Ronan committed
296 297

			case EventLog::Type::ConferenceSubjectChanged:
298
				return selectConferenceSubjectEvent(eventId, type, date, chatRoomId);
Ronan's avatar
Ronan committed
299 300 301 302 303
		}

		return nullptr;
	}

304
	shared_ptr<EventLog> MainDbPrivate::selectConferenceEvent (
305
		long long,
306 307
		EventLog::Type type,
		time_t date,
308
		const ChatRoomId &chatRoomId
309
	) const {
310 311 312
		return make_shared<ConferenceEvent>(
			type,
			date,
313
			chatRoomId
314
		);
Ronan's avatar
Ronan committed
315 316
	}

317
	shared_ptr<EventLog> MainDbPrivate::selectConferenceCallEvent (
318
		long long eventId,
319 320
		EventLog::Type type,
		time_t date,
321
		const ChatRoomId &chatRoomId
322
	) const {
Ronan's avatar
Ronan committed
323 324 325 326
		// TODO.
		return nullptr;
	}

327
	shared_ptr<EventLog> MainDbPrivate::selectConferenceChatMessageEvent (
328
		long long eventId,
329 330
		EventLog::Type type,
		time_t date,
331
		const ChatRoomId &chatRoomId
332
	) const {
Ronan's avatar
Ronan committed
333 334 335 336
		L_Q();

		shared_ptr<Core> core = q->getCore();

337
		shared_ptr<ChatRoom> chatRoom = core->findChatRoom(chatRoomId);
Ronan's avatar
Ronan committed
338 339 340 341 342
		if (!chatRoom)
			return nullptr;

		// TODO: Use cache, do not fetch the same message twice.

343
		// 1 - Fetch chat message.
344
		shared_ptr<ChatMessage> chatMessage;
345
		{
346 347
			string fromSipAddress;
			string toSipAddress;
348 349 350 351 352 353
			string imdnMessageId;
			int state;
			int direction;
			int isSecured;

			soci::session *session = dbSession.getBackendSession<soci::session>();
354 355 356
			*session << "SELECT from_sip_address.value, to_sip_address.value, 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"
357 358
				"  WHERE event_id = :eventId"
				"  AND event_id = event.id"
359 360
				"  AND from_sip_address_id = from_sip_address.id"
				"  AND to_sip_address_id = to_sip_address.id", soci::into(fromSipAddress), soci::into(toSipAddress),
361 362
				soci::into(imdnMessageId), soci::into(state), soci::into(direction), soci::into(isSecured), soci::use(eventId);

363 364 365 366
			chatMessage = shared_ptr<ChatMessage>(new ChatMessage(
				chatRoom,
				static_cast<ChatMessage::Direction>(direction)
			));
367 368 369
			chatMessage->getPrivate()->setState(static_cast<ChatMessage::State>(state), true);
			chatMessage->setIsSecured(static_cast<bool>(isSecured));

370 371
			chatMessage->getPrivate()->forceFromAddress(IdentityAddress(fromSipAddress));
			chatMessage->getPrivate()->forceToAddress(IdentityAddress(toSipAddress));
372
		}
Ronan's avatar
Ronan committed
373

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
		// 2 - Fetch contents.
		{
			soci::session *session = dbSession.getBackendSession<soci::session>();
			const string query = "SELECT content_type.value, body FROM chat_message_content, content_type"
				"  WHERE event_id = :eventId AND content_type_id = content_type.id";
			soci::rowset<soci::row> rows = (session->prepare << query, soci::use(eventId));
			for (const auto &row : rows) {
				ContentType contentType(row.get<string>(1));
				Content *content;

				if (contentType == ContentType::FileTransfer)
					content = new FileTransferContent();
				else if (contentType.isFile()) {
					long long contentId = q->getBackend() == AbstractDb::Sqlite3
						? static_cast<long long>(row.get<int>(0))
						: row.get<long long>(0);

					string name;
					int size;
					string path;

					*session << "SELECT name, size, path FROM chat_message_file_content"
Ronan's avatar
Ronan committed
396
						"  WHERE chat_message_content_id = :contentId",
Ronan's avatar
Ronan committed
397
						soci::into(name), soci::into(size), soci::into(path), soci::use(contentId);
398 399 400 401 402 403 404 405

					FileContent *fileContent = new FileContent();
					fileContent->setFileName(name);
					fileContent->setFileSize(static_cast<size_t>(size));
					fileContent->setFilePath(path);

					content = fileContent;
				} else
Ronan's avatar
Ronan committed
406
					content = new Content();
407 408 409

				content->setContentType(contentType);
				content->setBody(row.get<string>(2));
410
				chatMessage->addContent(*content);
411
			}
Ronan's avatar
Ronan committed
412
		}
413 414 415 416 417 418

		// TODO: Use cache.
		return make_shared<ConferenceChatMessageEvent>(
			date,
			chatMessage
		);
Ronan's avatar
Ronan committed
419 420
	}

421
	shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantEvent (
422
		long long eventId,
423 424
		EventLog::Type type,
		time_t date,
425
		const ChatRoomId &chatRoomId
426
	) const {
427 428 429 430
		unsigned int notifyId;
		string participantAddress;

		soci::session *session = dbSession.getBackendSession<soci::session>();
431 432
		*session << "SELECT notify_id, participant_address.value"
			"  FROM conference_notified_event, conference_participant_event, sip_address as participant_address"
433
			"  WHERE conference_participant_event.event_id = :eventId"
Ronan's avatar
Ronan committed
434 435
			"    AND conference_notified_event.event_id = conference_participant_event.event_id"
			"    AND participant_address.id = participant_address_id",
436 437 438 439 440
			soci::into(notifyId), soci::into(participantAddress), soci::use(eventId);

		return make_shared<ConferenceParticipantEvent>(
			type,
			date,
441
			chatRoomId,
442
			notifyId,
443
			IdentityAddress(participantAddress)
444
		);
Ronan's avatar
Ronan committed
445 446
	}

447
	shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantDeviceEvent (
448
		long long eventId,
449 450
		EventLog::Type type,
		time_t date,
451
		const ChatRoomId &chatRoomId
452
	) const {
453 454
		unsigned int notifyId;
		string participantAddress;
455
		string deviceAddress;
456 457

		soci::session *session = dbSession.getBackendSession<soci::session>();
458
		*session << "SELECT notify_id, participant_address.value, device_address.value"
459
			"  FROM conference_notified_event, conference_participant_event, conference_participant_device_event,"
460
			"    sip_address AS participant_address, sip_address AS device_address"
461 462
			"  WHERE conference_participant_device_event.event_id = :eventId"
			"    AND conference_participant_event.event_id = conference_participant_device_event.event_id"
463 464
			"    AND conference_notified_event.event_id = conference_participant_event.event_id"
			"    AND participant_address.id = participant_address_id"
465 466
			"    AND device_address.id = device_address_id",
			soci::into(notifyId), soci::into(participantAddress), soci::into(deviceAddress), soci::use(eventId);
467 468 469 470

		return make_shared<ConferenceParticipantDeviceEvent>(
			type,
			date,
471
			chatRoomId,
472
			notifyId,
473 474
			IdentityAddress(participantAddress),
			IdentityAddress(deviceAddress)
475
		);
Ronan's avatar
Ronan committed
476 477
	}

478
	shared_ptr<EventLog> MainDbPrivate::selectConferenceSubjectEvent (
479
		long long eventId,
480 481
		EventLog::Type type,
		time_t date,
482
		const ChatRoomId &chatRoomId
483 484 485 486
	) const {
		unsigned int notifyId;
		string subject;

487 488 489 490 491 492
		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);
493 494 495

		return make_shared<ConferenceSubjectEvent>(
			date,
496
			chatRoomId,
497 498 499
			notifyId,
			subject
		);
Ronan's avatar
Ronan committed
500 501
	}

502 503
// -----------------------------------------------------------------------------

Ronan's avatar
Ronan committed
504
	long long MainDbPrivate::insertEvent (const shared_ptr<EventLog> &eventLog) {
505 506 507 508
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

		*session << "INSERT INTO event (type, date) VALUES (:type, :date)",
509 510
			soci::use(static_cast<int>(eventLog->getType())),
			soci::use(Utils::getTimeTAsTm(eventLog->getCreationTime()));
511
		return q->getLastInsertId();
512 513
	}

Ronan's avatar
Ronan committed
514
	long long MainDbPrivate::insertConferenceEvent (const shared_ptr<EventLog> &eventLog, long long *chatRoomId) {
515 516 517 518 519 520 521 522 523 524 525 526 527
		shared_ptr<ConferenceEvent> conferenceEvent = static_pointer_cast<ConferenceEvent>(eventLog);

		long long eventId = -1;
		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);
528

529 530 531 532 533 534 535 536
			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);

			*session << "UPDATE chat_room SET last_update_date = :lastUpdateDate"
				"  WHERE id = :chatRoomId", soci::use(Utils::getTimeTAsTm(eventLog->getCreationTime())),
				soci::use(curChatRoomId);
		}
537 538 539 540 541 542 543

		if (chatRoomId)
			*chatRoomId = curChatRoomId;

		return eventId;
	}

Ronan's avatar
Ronan committed
544
	long long MainDbPrivate::insertConferenceCallEvent (const shared_ptr<EventLog> &eventLog) {
545 546 547 548
		// TODO.
		return 0;
	}

Ronan's avatar
Ronan committed
549 550
	long long MainDbPrivate::insertConferenceChatMessageEvent (const shared_ptr<EventLog> &eventLog) {
		shared_ptr<ChatMessage> chatMessage = static_pointer_cast<ConferenceChatMessageEvent>(eventLog)->getChatMessage();
551 552 553 554 555 556
		shared_ptr<ChatRoom> chatRoom = chatMessage->getChatRoom();
		if (!chatRoom) {
			lError() << "Unable to get a valid chat room. It was removed from database.";
			return -1;
		}

557
		long long eventId = insertConferenceEvent(eventLog);
558 559
		if (eventId < 0)
			return -1;
560

561 562
		long long fromSipAddressId = insertSipAddress(chatMessage->getFromAddress().asString());
		long long toSipAddressId = insertSipAddress(chatMessage->getToAddress().asString());
Ronan's avatar
Ronan committed
563

564
		soci::session *session = dbSession.getBackendSession<soci::session>();
565
		*session << "INSERT INTO conference_chat_message_event ("
566
			"  event_id, from_sip_address_id, to_sip_address_id,"
567 568 569 570
			"  state, direction, imdn_message_id, is_secured"
			") VALUES ("
			"  :eventId, :localSipaddressId, :remoteSipaddressId,"
			"  :state, :direction, :imdnMessageId, :isSecured"
571
			")", soci::use(eventId), soci::use(fromSipAddressId), soci::use(toSipAddressId),
572 573 574
			soci::use(static_cast<int>(chatMessage->getState())), soci::use(static_cast<int>(chatMessage->getDirection())),
			soci::use(chatMessage->getImdnMessageId()), soci::use(chatMessage->isSecured() ? 1 : 0);

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

578 579 580
		return eventId;
	}

581 582 583 584 585 586
	long long MainDbPrivate::insertConferenceNotifiedEvent (const shared_ptr<EventLog> &eventLog, long long *chatRoomId) {
		long long curChatRoomId;
		long long eventId = insertConferenceEvent(eventLog, &curChatRoomId);
		if (eventId < 0)
			return -1;

Ronan's avatar
Ronan committed
587
		unsigned int lastNotifyId = static_pointer_cast<ConferenceNotifiedEvent>(eventLog)->getNotifyId();
588 589 590

		soci::session *session = dbSession.getBackendSession<soci::session>();
		*session << "INSERT INTO conference_notified_event (event_id, notify_id)"
Ronan's avatar
Ronan committed
591 592
			"  VALUES (:eventId, :notifyId)", soci::use(eventId), soci::use(lastNotifyId);
		*session << "UPDATE chat_room SET last_notify_id = :lastNotifyId WHERE peer_sip_address_id = :chatRoomId",
593 594 595 596
			soci::use(lastNotifyId), soci::use(curChatRoomId);

		if (chatRoomId)
			*chatRoomId = curChatRoomId;
597

598 599 600
		return eventId;
	}

Ronan's avatar
Ronan committed
601
	long long MainDbPrivate::insertConferenceParticipantEvent (const shared_ptr<EventLog> &eventLog) {
602
		long long eventId = insertConferenceNotifiedEvent(eventLog);
603 604 605
		if (eventId < 0)
			return -1;

606
		long long participantAddressId = insertSipAddress(
Ronan's avatar
Ronan committed
607
			static_pointer_cast<ConferenceParticipantEvent>(eventLog)->getParticipantAddress().asString()
608 609
		);

610
		soci::session *session = dbSession.getBackendSession<soci::session>();
611
		*session << "INSERT INTO conference_participant_event (event_id, participant_address_id)"
612
			"  VALUES (:eventId, :participantAddressId)", soci::use(eventId), soci::use(participantAddressId);
613

614 615 616
		return eventId;
	}

Ronan's avatar
Ronan committed
617
	long long MainDbPrivate::insertConferenceParticipantDeviceEvent (const shared_ptr<EventLog> &eventLog) {
618
		long long eventId = insertConferenceParticipantEvent(eventLog);
619 620 621 622 623
		if (eventId < 0)
			return -1;

		long long deviceAddressId = insertSipAddress(
			static_pointer_cast<ConferenceParticipantDeviceEvent>(eventLog)->getDeviceAddress().asString()
624 625 626
		);

		soci::session *session = dbSession.getBackendSession<soci::session>();
627 628
		*session << "INSERT INTO conference_participant_device_event (event_id, device_address_id)"
			"  VALUES (:eventId, :deviceAddressId)", soci::use(eventId), soci::use(deviceAddressId);
629

630
		return eventId;
631 632
	}

Ronan's avatar
Ronan committed
633
	long long MainDbPrivate::insertConferenceSubjectEvent (const shared_ptr<EventLog> &eventLog) {
634 635 636 637 638 639
		long long chatRoomId;
		long long eventId = insertConferenceNotifiedEvent(eventLog, &chatRoomId);
		if (eventId < 0)
			return -1;

		const string &subject = static_pointer_cast<ConferenceSubjectEvent>(eventLog)->getSubject();
640 641

		soci::session *session = dbSession.getBackendSession<soci::session>();
642
		*session << "INSERT INTO conference_subject_event (event_id, subject)"
643 644 645 646
			"  VALUES (:eventId, :subject)", soci::use(eventId), soci::use(subject);

		*session << "UPDATE chat_room SET subject = :subject"
			"  WHERE id = :chatRoomId", soci::use(subject), soci::use(chatRoomId);
647

648
		return eventId;
649 650
	}

651 652 653 654 655 656 657 658 659 660 661 662 663
// -----------------------------------------------------------------------------

	shared_ptr<EventLog> MainDbPrivate::getEventFromCache (long long eventId) const {
		auto it = storageIdToEvent.find(eventId);
		if (it == storageIdToEvent.cend())
			return nullptr;

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

664
	void MainDbPrivate::invalidConferenceEventsFromQuery (const string &query, long long chatRoomId) {
665 666 667
		L_Q();

		soci::session *session = dbSession.getBackendSession<soci::session>();
668
		soci::rowset<soci::row> rows = (session->prepare << query, soci::use(chatRoomId));
669 670 671 672 673 674 675 676 677 678 679 680
		for (const auto &row : rows) {
			shared_ptr<EventLog> eventLog = getEventFromCache(
				q->getBackend() == AbstractDb::Sqlite3 ? static_cast<long long>(row.get<int>(0)) : row.get<long long>(0)
			);
			if (eventLog) {
				const EventLogPrivate *dEventLog = eventLog->getPrivate();
				L_ASSERT(dEventLog->dbKey.isValid());
				dEventLog->dbKey = MainDbEventKey();
			}
		}
	}

681
// -----------------------------------------------------------------------------
Ronan's avatar
Ronan committed
682

683
	void MainDb::init () {
684
		L_D();
685 686

		const string charset = getBackend() == Mysql ? "DEFAULT CHARSET=utf8" : "";
Ronan's avatar
Ronan committed
687
		soci::session *session = d->dbSession.getBackendSession<soci::session>();
688

Ronan's avatar
Ronan committed
689
		*session <<
690
			"CREATE TABLE IF NOT EXISTS sip_address ("
Erwan Croze's avatar
Erwan Croze committed
691
			"  id" + primaryKeyStr("BIGINT UNSIGNED") + ","
Ronan's avatar
Ronan committed
692
			"  value VARCHAR(255) UNIQUE NOT NULL"
693
			") " + charset;
694

695
		*session <<
696
			"CREATE TABLE IF NOT EXISTS content_type ("
Erwan Croze's avatar
Erwan Croze committed
697
			"  id" + primaryKeyStr("SMALLINT UNSIGNED") + ","
Ronan's avatar
Ronan committed
698
			"  value VARCHAR(255) UNIQUE NOT NULL"
699
			") " + charset;
700

Ronan's avatar
Ronan committed
701
		*session <<
702
			"CREATE TABLE IF NOT EXISTS event ("
Erwan Croze's avatar
Erwan Croze committed
703
			"  id" + primaryKeyStr("BIGINT UNSIGNED") + ","
704
			"  type TINYINT UNSIGNED NOT NULL,"
705
			"  date DATE NOT NULL"
706
			") " + charset;
707

Ronan's avatar
Ronan committed
708
		*session <<
709
			"CREATE TABLE IF NOT EXISTS chat_room ("
710 711
			"  id" + primaryKeyStr("BIGINT UNSIGNED") + ","

712
			// Server (for conference) or user sip address.
713
			"  peer_sip_address_id" + primaryKeyRefStr("BIGINT UNSIGNED") + " NOT NULL,"
714

715
			"  local_sip_address_id" + primaryKeyRefStr("BIGINT UNSIGNED") + " NOT NULL,"
716 717

			// Dialog creation date.
718 719 720 721
			"  creation_date DATE NOT NULL,"

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

723
			// ConferenceChatRoom, BasicChatRoom, RTT...
724
			"  capabilities TINYINT UNSIGNED NOT NULL,"
725

726 727 728
			// Chatroom subject.
			"  subject VARCHAR(255),"

Ronan's avatar
Ronan committed
729
			"  last_notify_id INT UNSIGNED,"
730

731 732
			"  UNIQUE (peer_sip_address_id, local_sip_address_id),"

733
			"  FOREIGN KEY (peer_sip_address_id)"
734
			"    REFERENCES sip_address(id)"
735
			"    ON DELETE CASCADE,"
736 737 738
			"  FOREIGN KEY (local_sip_address_id)"
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
739
			") " + charset;
740

741 742
		*session <<
			"CREATE TABLE IF NOT EXISTS chat_room_participant ("
Erwan Croze's avatar
Erwan Croze committed
743
			"  chat_room_id" + primaryKeyRefStr("BIGINT UNSIGNED") + ","
744
			"  participant_address_id" + primaryKeyRefStr("BIGINT UNSIGNED") + ","
745

746 747
			"  is_admin BOOLEAN NOT NULL,"

748
			"  PRIMARY KEY (chat_room_id, participant_address_id),"
749

750
			"  FOREIGN KEY (chat_room_id)"
751
			"    REFERENCES chat_room(id)"
752
			"    ON DELETE CASCADE,"
753
			"  FOREIGN KEY (participant_address_id)"
754 755
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
756
			") " + charset;
757 758 759

		*session <<
			"CREATE TABLE IF NOT EXISTS conference_event ("
760
			"  event_id" + primaryKeyStr("BIGINT UNSIGNED") + ","
761

762
			"  chat_room_id" + primaryKeyRefStr("BIGINT UNSIGNED") + " NOT NULL,"
763

764 765 766 767
			"  FOREIGN KEY (event_id)"
			"    REFERENCES event(id)"
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (chat_room_id)"
768
			"    REFERENCES chat_room(id)"
769
			"    ON DELETE CASCADE"
770
			") " + charset;
771

772 773
		*session <<
			"CREATE TABLE IF NOT EXISTS conference_notified_event ("
Erwan Croze's avatar
Erwan Croze committed
774
			"  event_id" + primaryKeyStr("BIGINT UNSIGNED") + ","
775

776 777 778 779 780
			"  notify_id INT UNSIGNED NOT NULL,"

			"  FOREIGN KEY (event_id)"
			"    REFERENCES conference_event(event_id)"
			"    ON DELETE CASCADE"
781
			") " + charset;
782

783 784
		*session <<
			"CREATE TABLE IF NOT EXISTS conference_participant_event ("
Erwan Croze's avatar
Erwan Croze committed
785
			"  event_id" + primaryKeyStr("BIGINT UNSIGNED") + ","
786

787
			"  participant_address_id" + primaryKeyRefStr("BIGINT UNSIGNED") + " NOT NULL,"
788

789 790
			"  FOREIGN KEY (event_id)"
			"    REFERENCES conference_notified_event(event_id)"
791 792 793 794
			"    ON DELETE CASCADE,"
			"  FOREIGN KEY (participant_address_id)"
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
795
			") " + charset;
796 797 798

		*session <<
			"CREATE TABLE IF NOT EXISTS conference_participant_device_event ("
Erwan Croze's avatar
Erwan Croze committed
799
			"  event_id" + primaryKeyStr("BIGINT UNSIGNED") + ","
800

801
			"  device_address_id" + primaryKeyRefStr("BIGINT UNSIGNED") + " NOT NULL,"
802

803 804
			"  FOREIGN KEY (event_id)"
			"    REFERENCES conference_participant_event(event_id)"
805
			"    ON DELETE CASCADE,"
806
			"  FOREIGN KEY (device_address_id)"
807 808
			"    REFERENCES sip_address(id)"
			"    ON DELETE CASCADE"
809
			") " + charset;
810 811 812

		*session <<
			"CREATE TABLE IF NOT EXISTS conference_subject_event ("
813 814
			"  event_id" + primaryKeyStr("BIGINT") + ","

815
			"  subject VARCHAR(255) NOT NULL,"
816

817 818
			"  FOREIGN KEY (event_id)"
			"    REFERENCES conference_notified_event(event_id)"