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

Ronan's avatar
Ronan committed
29
#include "chat/chat-message/chat-message-p.h"
30
#include "chat/chat-room/chat-room-p.h"
31
#include "chat/chat-room/client-group-chat-room.h"
32
#include "chat/chat-room/server-group-chat-room.h"
33
#include "conference/participant-p.h"
34
#include "content/content-type.h"
Ronan's avatar
Ronan committed
35
#include "content/content.h"
Ronan's avatar
Ronan committed
36
#include "core/core-p.h"
37
#include "db/session/db-session-provider.h"
Ronan's avatar
Ronan committed
38
#include "event-log/event-log-p.h"
39
#include "event-log/events.h"
Ronan's avatar
Ronan committed
40
#include "logger/logger.h"
41
#include "main-db-key-p.h"
Ronan's avatar
Ronan committed
42
#include "main-db-p.h"
Ronan's avatar
Ronan committed
43 44 45

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

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

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

Ronan's avatar
Ronan committed
51 52
using namespace std;

Ronan's avatar
Ronan committed
53 54 55 56
LINPHONE_BEGIN_NAMESPACE

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

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

59 60
#ifdef SOCI_ENABLED

Ronan's avatar
Ronan committed
61
// -----------------------------------------------------------------------------
62
// Soci backend.
Ronan's avatar
Ronan committed
63 64
// -----------------------------------------------------------------------------

65 66 67 68 69
	template<typename T>
	struct EnumToSql {
		T first;
		const char *second;
	};
70

71 72 73 74 75 76 77
	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)
		);
	}

78
	static constexpr EnumToSql<MainDb::Filter> eventFilterToSql[] = {
79
		{ MainDb::ConferenceCallFilter, "3, 4" },
Ronan's avatar
Ronan committed
80
		{ MainDb::ConferenceChatMessageFilter, "5" },
81
		{ MainDb::ConferenceInfoFilter, "1, 2, 6, 7, 8, 9, 10, 11, 12" }
82
	};
83

84
	static constexpr const char *mapEventFilterToSql (MainDb::Filter filter) {
85 86 87
		return mapEnumToSql(
			eventFilterToSql, sizeof eventFilterToSql / sizeof eventFilterToSql[0], filter
		);
88 89
	}

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

Ronan's avatar
Ronan committed
92 93 94 95 96
	static string buildSqlEventFilter (
		const list<MainDb::Filter> &filters,
		MainDb::FilterMask mask,
		const string &condKeyWord = "WHERE"
	) {
97
		L_ASSERT(
98
			find_if(filters.cbegin(), filters.cend(), [](const MainDb::Filter &filter) {
99 100
				return filter == MainDb::NoFilter;
			}) == filters.cend()
101 102
		);

103
		if (mask == MainDb::NoFilter)
104 105 106 107 108 109 110 111 112 113
			return "";

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

			if (isStart) {
				isStart = false;
Ronan's avatar
Ronan committed
114
				sql += " " + condKeyWord + " type IN (";
115
			} else
Ronan's avatar
Ronan committed
116
				sql += ", ";
117 118 119
			sql += mapEventFilterToSql(filter);
		}

Ronan's avatar
Ronan committed
120 121 122
		if (!isStart)
			sql += ") ";

123 124 125
		return sql;
	}

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
// -----------------------------------------------------------------------------

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

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

142 143 144 145
static constexpr string &blobToString (string &in) {
	return in;
}

146 147
// -----------------------------------------------------------------------------

148 149 150 151 152 153
	long long MainDbPrivate::resolveId (const soci::row &row, int col) const {
		L_Q();
		// See: http://soci.sourceforge.net/doc/master/backends/
		// `row id` is not supported by soci on Sqlite3. It's necessary to cast id to int...
		return q->getBackend() == AbstractDb::Sqlite3
			? static_cast<long long>(row.get<int>(0))
Benjamin REIS's avatar
Benjamin REIS committed
154
			: static_cast<long long>(row.get<unsigned long long>(0));
155 156
	}

157 158
// -----------------------------------------------------------------------------

159
	long long MainDbPrivate::insertSipAddress (const string &sipAddress) {
160 161 162
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

163 164
		long long id = selectSipAddressId(sipAddress);
		if (id >= 0)
165 166
			return id;

Ronan's avatar
Ronan committed
167
		lInfo() << "Insert new sip address in database: `" << sipAddress << "`.";
168 169
		*session << "INSERT INTO sip_address (value) VALUES (:sipAddress)", soci::use(sipAddress);
		return q->getLastInsertId();
170 171
	}

172
	void MainDbPrivate::insertContent (long long eventId, const Content &content) {
173
		L_Q();
174 175
		soci::session *session = dbSession.getBackendSession<soci::session>();

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

182
		const long long &chatMessageContentId = q->getLastInsertId();
Sylvain Berfini's avatar
Sylvain Berfini committed
183
		if (content.getContentType().isFile()) {
184
			const FileContent &fileContent = static_cast<const FileContent &>(content);
185 186 187
			const string &name = fileContent.getFileName();
			const size_t &size = fileContent.getFileSize();
			const string &path = fileContent.getFilePath();
Sylvain Berfini's avatar
Sylvain Berfini committed
188
			*session << "INSERT INTO chat_message_file_content (chat_message_content_id, name, size, path) VALUES "
189 190
				" (:chatMessageContentId, :name, :size, :path)",
				soci::use(chatMessageContentId), soci::use(name), soci::use(size), soci::use(path);
Sylvain Berfini's avatar
Sylvain Berfini committed
191 192
		}

193
		for (const auto &appData : content.getAppDataMap())
Ronan's avatar
Ronan committed
194
			*session << "INSERT INTO chat_message_content_app_data (chat_message_content_id, name, data) VALUES"
195 196
				" (:chatMessageContentId, :name, :data)",
				soci::use(chatMessageContentId), soci::use(appData.first), soci::use(appData.second);
197 198
	}

199
	long long MainDbPrivate::insertContentType (const string &contentType) {
200 201 202
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

203
		long long id;
204 205
		*session << "SELECT id FROM content_type WHERE value = :contentType", soci::use(contentType), soci::into(id);
		if (session->got_data())
206 207
			return id;

Ronan's avatar
Ronan committed
208
		lInfo() << "Insert new content type in database: `" << contentType << "`.";
209 210
		*session << "INSERT INTO content_type (value) VALUES (:contentType)", soci::use(contentType);
		return q->getLastInsertId();
211 212
	}

213
	long long MainDbPrivate::insertOrUpdateBasicChatRoom (
214 215
		long long peerSipAddressId,
		long long localSipAddressId,
216
		const tm &creationTime
217 218 219
	) {
		L_Q();

220 221
		soci::session *session = dbSession.getBackendSession<soci::session>();

222
		long long id = selectChatRoomId(peerSipAddressId, localSipAddressId);
223 224 225
		if (id >= 0) {
			*session << "UPDATE chat_room SET last_update_time = :lastUpdateTime WHERE id = :id",
				soci::use(creationTime), soci::use(id);
226
			return id;
227
		}
228

229
		static const int capabilities = static_cast<int>(ChatRoom::Capabilities::Basic);
230 231 232 233 234 235 236 237 238
		lInfo() << "Insert new chat room in database: (peer=" << peerSipAddressId <<
			", local=" << localSipAddressId << ", capabilities=" << capabilities << ").";
		*session << "INSERT INTO chat_room ("
			"  peer_sip_address_id, local_sip_address_id, creation_time, last_update_time, capabilities"
			") VALUES (:peerSipAddressId, :localSipAddressId, :creationTime, :lastUpdateTime, :capabilities)",
			soci::use(peerSipAddressId), soci::use(localSipAddressId), soci::use(creationTime), soci::use(creationTime),
			soci::use(capabilities);

		return q->getLastInsertId();
239 240
	}

241
	long long MainDbPrivate::insertChatRoom (const shared_ptr<AbstractChatRoom> &chatRoom) {
242 243 244 245 246
		L_Q();

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

		const ChatRoomId &chatRoomId = chatRoom->getChatRoomId();
247 248
		const long long &peerSipAddressId = insertSipAddress(chatRoomId.getPeerAddress().asString());
		const long long &localSipAddressId = insertSipAddress(chatRoomId.getLocalAddress().asString());
249 250 251

		long long id = selectChatRoomId(peerSipAddressId, localSipAddressId);
		if (id >= 0) {
252
			lError() << "Unable to insert chat room (it already exists): (peer=" << peerSipAddressId <<
253 254 255 256 257 258 259
				", local=" << localSipAddressId << ").";
			return id;
		}

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

260 261 262
		const tm &creationTime = Utils::getTimeTAsTm(chatRoom->getCreationTime());
		const int &capabilities = static_cast<int>(chatRoom->getCapabilities());
		const string &subject = chatRoom->getSubject();
263
		const int &flags = chatRoom->hasBeenLeft();
264
		*session << "INSERT INTO chat_room ("
265
			"  peer_sip_address_id, local_sip_address_id, creation_time, last_update_time, capabilities, subject, flags"
266
			") VALUES (:peerSipAddressId, :localSipAddressId, :creationTime, :lastUpdateTime, :capabilities, :subject, :flags)",
267
			soci::use(peerSipAddressId), soci::use(localSipAddressId), soci::use(creationTime), soci::use(creationTime),
268
			soci::use(capabilities), soci::use(subject), soci::use(flags);
269 270

		id = q->getLastInsertId();
271 272 273
		if (!chatRoom->canHandleParticipants())
			return id;

274 275 276
		// Do not add 'me' when creating a server-group-chat-room.
		if (chatRoomId.getLocalAddress() != chatRoomId.getPeerAddress()) {
			shared_ptr<Participant> me = chatRoom->getMe();
277 278 279 280 281 282 283
			long long meId = insertChatRoomParticipant(
				id,
				insertSipAddress(me->getAddress().asString()),
				me->isAdmin()
			);
			for (const auto &device : me->getPrivate()->getDevices())
				insertChatRoomParticipantDevice(meId, insertSipAddress(device->getAddress().asString()));
284 285
		}

286 287 288 289 290 291 292 293 294
		for (const auto &participant : chatRoom->getParticipants()) {
			long long participantId = insertChatRoomParticipant(
				id,
				insertSipAddress(participant->getAddress().asString()),
				participant->isAdmin()
			);
			for (const auto &device : participant->getPrivate()->getDevices())
				insertChatRoomParticipantDevice(participantId, insertSipAddress(device->getAddress().asString()));
		}
295 296

		return id;
297 298
	}

299 300 301 302 303
	long long MainDbPrivate::insertChatRoomParticipant (
		long long chatRoomId,
		long long participantSipAddressId,
		bool isAdmin
	) {
304
		L_Q();
305

306
		soci::session *session = dbSession.getBackendSession<soci::session>();
307
		long long id = selectChatRoomParticipantId(chatRoomId, participantSipAddressId);
308 309
		if (id >= 0) {
			// See: https://stackoverflow.com/a/15299655 (cast to reference)
310
			*session << "UPDATE chat_room_participant SET is_admin = :isAdmin WHERE id = :id",
311 312
				soci::use(static_cast<const int &>(isAdmin)), soci::use(id);
			return id;
Ronan's avatar
Ronan committed
313
		}
314

315 316
		lInfo() << "Insert new chat room participant in database: `" << participantSipAddressId <<
			"` (isAdmin=" << isAdmin << ").";
317
		*session << "INSERT INTO chat_room_participant (chat_room_id, participant_sip_address_id, is_admin)"
318 319
			" VALUES (:chatRoomId, :participantSipAddressId, :isAdmin)",
			soci::use(chatRoomId), soci::use(participantSipAddressId), soci::use(static_cast<const int &>(isAdmin));
320 321 322 323

		return q->getLastInsertId();
	}

324 325 326 327
	void MainDbPrivate::insertChatRoomParticipantDevice (
		long long participantId,
		long long participantDeviceSipAddressId
	) {
328 329 330
		soci::session *session = dbSession.getBackendSession<soci::session>();
		long long count;
		*session << "SELECT COUNT(*) FROM chat_room_participant_device"
331 332 333
			" WHERE chat_room_participant_id = :participantId"
			" AND participant_device_sip_address_id = :participantDeviceSipAddressId",
			soci::into(count), soci::use(participantId), soci::use(participantDeviceSipAddressId);
334 335 336
		if (count)
			return;

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

343
	void MainDbPrivate::insertChatMessageParticipant (long long eventId, long long sipAddressId, int state) {
344 345
		// TODO: Deal with read messages.
		// Remove if displayed? Think a good alorithm for mark as read.
346 347
		soci::session *session = dbSession.getBackendSession<soci::session>();
		soci::statement statement = (
348
			session->prepare << "UPDATE chat_message_participant SET state = :state"
349
				" WHERE event_id = :eventId AND participant_sip_address_id = :sipAddressId",
Ronan's avatar
Ronan committed
350
				soci::use(state), soci::use(eventId), soci::use(sipAddressId)
351
		);
352
		statement.execute();
353
		if (statement.get_affected_rows() == 0 && state != static_cast<int>(ChatMessage::State::Displayed))
354
			*session << "INSERT INTO chat_message_participant (event_id, participant_sip_address_id, state)"
355
				" VALUES (:eventId, :sipAddressId, :state)",
Ronan's avatar
Ronan committed
356
				soci::use(eventId), soci::use(sipAddressId), soci::use(state);
357 358
	}

359 360
// -----------------------------------------------------------------------------

361
	long long MainDbPrivate::selectSipAddressId (const string &sipAddress) const {
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
		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);
	}

391
	long long MainDbPrivate::selectChatRoomParticipantId (long long chatRoomId, long long participantSipAddressId) const {
392 393 394
		long long id;
		soci::session *session = dbSession.getBackendSession<soci::session>();
		*session << "SELECT id from chat_room_participant"
395 396
			" WHERE chat_room_id = :chatRoomId AND participant_sip_address_id = :participantSipAddressId",
			soci::into(id), soci::use(chatRoomId), soci::use(participantSipAddressId);
397 398 399
		return session->got_data() ? id : -1;
	}

400 401
// -----------------------------------------------------------------------------

402 403 404 405 406
	void MainDbPrivate::deleteContents (long long messageEventId) {
		soci::session *session = dbSession.getBackendSession<soci::session>();
		*session << "DELETE FROM chat_message_content WHERE event_id = :messageEventId", soci::use(messageEventId);
	}

407 408 409 410 411 412 413
	void MainDbPrivate::deleteChatRoomParticipant (long long chatRoomId, long long participantSipAddressId) {
		soci::session *session = dbSession.getBackendSession<soci::session>();
		*session << "DELETE FROM chat_room_participant"
			"  WHERE chat_room_id = :chatRoomId AND participant_sip_address_id = :participantSipAddressId",
			soci::use(chatRoomId), soci::use(participantSipAddressId);
	}

414 415 416 417 418 419 420 421 422 423 424
	void MainDbPrivate::deleteChatRoomParticipantDevice (
		long long participantId,
		long long participantDeviceSipAddressId
	) {
		soci::session *session = dbSession.getBackendSession<soci::session>();
		*session << "DELETE FROM chat_room_participant_device"
			"  WHERE chat_room_participant_id = :participantId"
			"  AND participant_device_sip_address_id = :participantDeviceSipAddressId",
			soci::use(participantId), soci::use(participantDeviceSipAddressId);
	}

Ronan's avatar
Ronan committed
425 426
// -----------------------------------------------------------------------------

427
	shared_ptr<EventLog> MainDbPrivate::selectGenericConferenceEvent (
428
		long long eventId,
429
		EventLog::Type type,
430
		time_t creationTime,
431
		const ChatRoomId &chatRoomId
432
	) const {
Ronan's avatar
Ronan committed
433 434
		shared_ptr<EventLog> eventLog;

Ronan's avatar
Ronan committed
435 436 437 438 439
		switch (type) {
			case EventLog::Type::None:
				return nullptr;

			case EventLog::Type::ConferenceCreated:
440
			case EventLog::Type::ConferenceTerminated:
Ronan's avatar
Ronan committed
441 442
				eventLog = selectConferenceEvent(eventId, type, creationTime, chatRoomId);
				break;
Ronan's avatar
Ronan committed
443

444 445
			case EventLog::Type::ConferenceCallStart:
			case EventLog::Type::ConferenceCallEnd:
Ronan's avatar
Ronan committed
446 447
				eventLog = selectConferenceCallEvent(eventId, type, creationTime, chatRoomId);
				break;
Ronan's avatar
Ronan committed
448 449

			case EventLog::Type::ConferenceChatMessage:
Ronan's avatar
Ronan committed
450 451
				eventLog = selectConferenceChatMessageEvent(eventId, type, creationTime, chatRoomId);
				break;
Ronan's avatar
Ronan committed
452 453 454 455 456

			case EventLog::Type::ConferenceParticipantAdded:
			case EventLog::Type::ConferenceParticipantRemoved:
			case EventLog::Type::ConferenceParticipantSetAdmin:
			case EventLog::Type::ConferenceParticipantUnsetAdmin:
Ronan's avatar
Ronan committed
457 458
				eventLog = selectConferenceParticipantEvent(eventId, type, creationTime, chatRoomId);
				break;
Ronan's avatar
Ronan committed
459 460 461

			case EventLog::Type::ConferenceParticipantDeviceAdded:
			case EventLog::Type::ConferenceParticipantDeviceRemoved:
Ronan's avatar
Ronan committed
462 463
				eventLog = selectConferenceParticipantDeviceEvent(eventId, type, creationTime, chatRoomId);
				break;
Ronan's avatar
Ronan committed
464 465

			case EventLog::Type::ConferenceSubjectChanged:
Ronan's avatar
Ronan committed
466 467 468 469
				eventLog = selectConferenceSubjectEvent(eventId, type, creationTime, chatRoomId);
				break;
		}

470 471
		if (eventLog)
			cache(eventLog, eventId);
Ronan's avatar
Ronan committed
472

473
		return eventLog;
Ronan's avatar
Ronan committed
474 475
	}

476
	shared_ptr<EventLog> MainDbPrivate::selectConferenceEvent (
477
		long long,
478
		EventLog::Type type,
479
		time_t creationTime,
480
		const ChatRoomId &chatRoomId
481
	) const {
482 483
		return make_shared<ConferenceEvent>(
			type,
484
			creationTime,
485
			chatRoomId
486
		);
Ronan's avatar
Ronan committed
487 488
	}

489
	shared_ptr<EventLog> MainDbPrivate::selectConferenceCallEvent (
490
		long long eventId,
491
		EventLog::Type type,
492
		time_t creationTime,
493
		const ChatRoomId &chatRoomId
494
	) const {
Ronan's avatar
Ronan committed
495 496 497 498
		// TODO.
		return nullptr;
	}

499 500 501 502 503 504 505 506 507 508 509 510
	template<typename T>
	static void fetchContentAppData (soci::session *session, Content &content, long long contentId, T &data) {
		static const string query = "SELECT name, data FROM chat_message_content_app_data"
			" WHERE chat_message_content_id = :contentId";

		string name;
		soci::statement statement = (session->prepare << query, soci::use(contentId), soci::into(name), soci::into(data));
		statement.execute();
		while (statement.fetch())
			content.setAppData(name, blobToString(data));
	}

511
	shared_ptr<EventLog> MainDbPrivate::selectConferenceChatMessageEvent (
512
		long long eventId,
513
		EventLog::Type type,
514
		time_t creationTime,
515
		const ChatRoomId &chatRoomId
516
	) const {
Ronan's avatar
Ronan committed
517 518 519
		L_Q();

		shared_ptr<Core> core = q->getCore();
520
		shared_ptr<AbstractChatRoom> chatRoom = core->findChatRoom(chatRoomId);
521 522 523 524
		if (!chatRoom) {
			lError() << "Unable to find chat room storage id of (peer=" +
				chatRoomId.getPeerAddress().asString() +
				", local=" + chatRoomId.getLocalAddress().asString() + "`).";
Ronan's avatar
Ronan committed
525
			return nullptr;
526
		}
Ronan's avatar
Ronan committed
527

528 529
		bool hasFileTransferContent = false;

530
		// 1 - Fetch chat message.
531 532 533
		shared_ptr<ChatMessage> chatMessage = getChatMessageFromCache(eventId);
		if (chatMessage)
			goto end;
534
		{
535 536
			string fromSipAddress;
			string toSipAddress;
537 538 539

			tm messageTime;

540
			string imdnMessageId;
541

542 543 544 545 546
			int state;
			int direction;
			int isSecured;

			soci::session *session = dbSession.getBackendSession<soci::session>();
547
			*session << "SELECT from_sip_address.value, to_sip_address.value, time, imdn_message_id, state, direction, is_secured"
548 549 550 551 552
				" FROM event, conference_chat_message_event, sip_address AS from_sip_address, sip_address AS to_sip_address"
				" WHERE event_id = :eventId"
				" AND event_id = event.id"
				" AND from_sip_address_id = from_sip_address.id"
				" AND to_sip_address_id = to_sip_address.id", soci::into(fromSipAddress), soci::into(toSipAddress),
553 554
				soci::into(messageTime), soci::into(imdnMessageId), soci::into(state), soci::into(direction),
				soci::into(isSecured), soci::use(eventId);
555

556 557 558 559
			chatMessage = shared_ptr<ChatMessage>(new ChatMessage(
				chatRoom,
				static_cast<ChatMessage::Direction>(direction)
			));
560
			chatMessage->setIsSecured(static_cast<bool>(isSecured));
561

562 563
			ChatMessagePrivate *dChatMessage = chatMessage->getPrivate();
			dChatMessage->setState(static_cast<ChatMessage::State>(state), true);
564

565 566 567 568
			dChatMessage->forceFromAddress(IdentityAddress(fromSipAddress));
			dChatMessage->forceToAddress(IdentityAddress(toSipAddress));

			dChatMessage->setTime(Utils::getTmAsTimeT(messageTime));
569
			dChatMessage->setImdnMessageId(imdnMessageId);
570
		}
Ronan's avatar
Ronan committed
571

572 573 574
		// 2 - Fetch contents.
		{
			soci::session *session = dbSession.getBackendSession<soci::session>();
575
			static const string query = "SELECT chat_message_content.id, content_type.id, content_type.value, body"
576 577
				" FROM chat_message_content, content_type"
				" WHERE event_id = :eventId AND content_type_id = content_type.id";
578 579
			soci::rowset<soci::row> rows = (session->prepare << query, soci::use(eventId));
			for (const auto &row : rows) {
580
				ContentType contentType(row.get<string>(2));
581
				const long long &contentId = resolveId(row, 0);
582 583
				Content *content;

584 585
				if (contentType == ContentType::FileTransfer) {
					hasFileTransferContent = true;
586
					content = new FileTransferContent();
587
				}
588
				else if (contentType.isFile()) {
589
					// 2.1 - Fetch contents' file informations.
590 591 592 593 594
					string name;
					int size;
					string path;

					*session << "SELECT name, size, path FROM chat_message_file_content"
595
						" WHERE chat_message_content_id = :contentId",
Ronan's avatar
Ronan committed
596
						soci::into(name), soci::into(size), soci::into(path), soci::use(contentId);
597 598 599 600 601 602 603 604

					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
605
					content = new Content();
606

607 608 609
				content->setContentType(contentType);
				content->setBody(row.get<string>(3));

610
				// 2.2 - Fetch contents' app data.
611 612 613 614 615 616 617
				if (q->getBackend() == MainDb::Backend::Sqlite3) {
					soci::blob data(*session);
					fetchContentAppData(session, *content, contentId, data);
				} else {
					string data;
					fetchContentAppData(session, *content, contentId, data);
				}
618
				chatMessage->addContent(*content);
619
			}
Ronan's avatar
Ronan committed
620
		}
621

622 623 624
		// 3 - Load external body url from body into FileTransferContent if needed.
		if (hasFileTransferContent)
			chatMessage->getPrivate()->loadFileTransferUrlFromBodyToContent();
625

626 627
		cache(chatMessage, eventId);

628
	end:
629
		return make_shared<ConferenceChatMessageEvent>(
630
			creationTime,
631 632
			chatMessage
		);
Ronan's avatar
Ronan committed
633 634
	}

635
	shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantEvent (
636
		long long eventId,
637
		EventLog::Type type,
638
		time_t creationTime,
639
		const ChatRoomId &chatRoomId
640
	) const {
641 642 643 644
		unsigned int notifyId;
		string participantAddress;

		soci::session *session = dbSession.getBackendSession<soci::session>();
645 646
		*session << "SELECT notify_id, participant_address.value"
			"  FROM conference_notified_event, conference_participant_event, sip_address as participant_address"
647
			"  WHERE conference_participant_event.event_id = :eventId"
Ronan's avatar
Ronan committed
648
			"    AND conference_notified_event.event_id = conference_participant_event.event_id"
649
			"    AND participant_address.id = participant_sip_address_id",
650 651 652 653
			soci::into(notifyId), soci::into(participantAddress), soci::use(eventId);

		return make_shared<ConferenceParticipantEvent>(
			type,
654
			creationTime,
655
			chatRoomId,
656
			notifyId,
657
			IdentityAddress(participantAddress)
658
		);
Ronan's avatar
Ronan committed
659 660
	}

661
	shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantDeviceEvent (
662
		long long eventId,
663
		EventLog::Type type,
664
		time_t creationTime,
665
		const ChatRoomId &chatRoomId
666
	) const {
667 668
		unsigned int notifyId;
		string participantAddress;
669
		string deviceAddress;
670 671

		soci::session *session = dbSession.getBackendSession<soci::session>();
672
		*session << "SELECT notify_id, participant_address.value, device_address.value"
673
			"  FROM conference_notified_event, conference_participant_event, conference_participant_device_event,"
674
			"    sip_address AS participant_address, sip_address AS device_address"
675 676
			"  WHERE conference_participant_device_event.event_id = :eventId"
			"    AND conference_participant_event.event_id = conference_participant_device_event.event_id"
677
			"    AND conference_notified_event.event_id = conference_participant_event.event_id"
678 679
			"    AND participant_address.id = participant_sip_address_id"
			"    AND device_address.id = device_sip_address_id",
680
			soci::into(notifyId), soci::into(participantAddress), soci::into(deviceAddress), soci::use(eventId);
681 682 683

		return make_shared<ConferenceParticipantDeviceEvent>(
			type,
684
			creationTime,
685
			chatRoomId,
686
			notifyId,
687 688
			IdentityAddress(participantAddress),
			IdentityAddress(deviceAddress)
689
		);
Ronan's avatar
Ronan committed
690 691
	}

692
	shared_ptr<EventLog> MainDbPrivate::selectConferenceSubjectEvent (
693
		long long eventId,
694
		EventLog::Type type,
695
		time_t creationTime,
696
		const ChatRoomId &chatRoomId
697 698 699 700
	) const {
		unsigned int notifyId;
		string subject;

701 702
		soci::session *session = dbSession.getBackendSession<soci::session>();
		*session << "SELECT notify_id, subject"
703 704 705
			" 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",
706
			soci::into(notifyId), soci::into(subject), soci::use(eventId);
707 708

		return make_shared<ConferenceSubjectEvent>(
709
			creationTime,
710
			chatRoomId,
711 712 713
			notifyId,
			subject
		);
Ronan's avatar
Ronan committed
714 715
	}

716 717
// -----------------------------------------------------------------------------

Ronan's avatar
Ronan committed
718
	long long MainDbPrivate::insertEvent (const shared_ptr<EventLog> &eventLog) {
719 720 721
		L_Q();
		soci::session *session = dbSession.getBackendSession<soci::session>();

722 723
		const int &type = static_cast<int>(eventLog->getType());
		const tm &creationTime = Utils::getTimeTAsTm(eventLog->getCreationTime());
724
		*session << "INSERT INTO event (type, creation_time) VALUES (:type, :creationTime)",
725 726 727
			soci::use(type),
			soci::use(creationTime);

728
		return q->getLastInsertId();
729 730
	}

Ronan's avatar
Ronan committed
731
	long long MainDbPrivate::insertConferenceEvent (const shared_ptr<EventLog> &eventLog, long long *chatRoomId) {
732 733 734
		shared_ptr<ConferenceEvent> conferenceEvent = static_pointer_cast<ConferenceEvent>(eventLog);

		long long eventId = -1;
735
		const long long &curChatRoomId = selectChatRoomId(conferenceEvent->getChatRoomId());
736 737 738 739 740 741 742 743 744
		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);
745

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

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

			if (eventLog->getType() == EventLog::Type::ConferenceTerminated)
756
				*session << "UPDATE chat_room SET flags = 1 WHERE id = :chatRoomId", soci::use(curChatRoomId);
757
		}
758 759 760 761 762 763 764

		if (chatRoomId)
			*chatRoomId = curChatRoomId;

		return eventId;
	}

Ronan's avatar
Ronan committed
765
	long long MainDbPrivate::insertConferenceCallEvent (const shared_ptr<EventLog> &eventLog) {
766 767 768 769
		// TODO.
		return 0;
	}

Ronan's avatar
Ronan committed
770 771
	long long MainDbPrivate::insertConferenceChatMessageEvent (const shared_ptr<EventLog> &eventLog) {
		shared_ptr<ChatMessage> chatMessage = static_pointer_cast<ConferenceChatMessageEvent>(eventLog)->getChatMessage();
772
		shared_ptr<AbstractChatRoom> chatRoom = chatMessage->getChatRoom();
773 774 775 776 777
		if (!chatRoom) {
			lError() << "Unable to get a valid chat room. It was removed from database.";
			return -1;
		}

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

782
		soci::session *session = dbSession.getBackendSession<soci::session>();
783 784 785 786 787 788 789 790 791

		const long long &fromSipAddressId = insertSipAddress(chatMessage->getFromAddress().asString());
		const long long &toSipAddressId = insertSipAddress(chatMessage->getToAddress().asString());
		const tm &messageTime = Utils::getTimeTAsTm(chatMessage->getTime());
		const int &state = static_cast<int>(chatMessage->getState());
		const int &direction = static_cast<int>(chatMessage->getDirection());
		const string &imdnMessageId = chatMessage->getImdnMessageId();
		const int &isSecured = chatMessage->isSecured() ? 1 : 0;

792
		*session << "INSERT INTO conference_chat_message_event ("
793
			"  event_id, from_sip_address_id, to_sip_address_id,"
794
			"  time, state, direction, imdn_message_id, is_secured"
795 796
			") VALUES ("
			"  :eventId, :localSipaddressId, :remoteSipaddressId,"
797
			"  :time, :state, :direction, :imdnMessageId, :isSecured"
798
			")", soci::use(eventId), soci::use(fromSipAddressId), soci::use(toSipAddressId),
799 800
			soci::use(messageTime), soci::use(state), soci::use(direction),
			soci::use(imdnMessageId), soci::use(isSecured);
801

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