main-db.cpp 96.3 KB
Newer Older
Ronan's avatar
Ronan committed
1
/*
2
 * main-db.cpp
Ronan's avatar
Ronan committed
3
 * Copyright (C) 2010-2018 Belledonne Communications SARL
Ronan's avatar
Ronan committed
4
 *
Ghislain MARY's avatar
Ghislain MARY committed
5 6 7 8
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
Ronan's avatar
Ronan committed
9 10 11 12 13 14 15
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
Ghislain MARY's avatar
Ghislain MARY committed
16 17
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Ronan's avatar
Ronan committed
18 19
 */

20
#include <algorithm>
21
#include <ctime>
22

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

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

39
#define DB_MODULE_VERSION_EVENTS L_VERSION(1, 0, 1)
Ronan's avatar
Ronan committed
40 41
#define DB_MODULE_VERSION_FRIENDS L_VERSION(1, 0, 0)
#define DB_MODULE_VERSION_LEGACY_FRIENDS_IMPORT L_VERSION(1, 0, 0)
42
#define DB_MODULE_VERSION_LEGACY_HISTORY_IMPORT L_VERSION(1, 0, 0)
43

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

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

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

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

61 62 63 64 65
// -----------------------------------------------------------------------------
// Errors handling.
// -----------------------------------------------------------------------------

#define L_SAFE_TRANSACTION_C(CONTEXT) \
66
	LinphonePrivate::SafeTransactionInfo().set(__func__, CONTEXT) * [&]()
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89

#define L_SAFE_TRANSACTION L_SAFE_TRANSACTION_C(this)

struct SafeTransactionInfo {
	SafeTransactionInfo &set (const char *_name, const MainDb *_mainDb) {
		name = _name;
		mainDb = const_cast<MainDb *>(_mainDb);
		return *this;
	}

	const char *name = nullptr;
	MainDb *mainDb = nullptr;
};

template<typename Function>
class SafeTransaction {
public:
	using ReturnType = typename remove_reference<decltype(declval<Function>()())>::type;

	SafeTransaction (SafeTransactionInfo &info, Function function) : mFunction(move(function)) {
		try {
			mResult = mFunction();
		} catch (const soci::soci_error &e) {
90
			lWarning() << "Catched exception in MainDb::" << info.name << "(" << e.what() << ").";
91
			soci::soci_error::error_category category = e.get_error_category();
92 93 94 95
			if (
				(category == soci::soci_error::connection_error || category == soci::soci_error::unknown) &&
				info.mainDb->forceReconnect()
			) {
96 97 98 99 100
				try {
					mResult = mFunction();
				} catch (const exception &e) {
					lWarning() << "Unable to execute query after reconnect in MainDb::" << info.name << "(" << e.what() << ").";
				}
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
				return;
			}
			lError() << "Unhandled [" << getErrorCategoryAsString(category) << "] exception in MainDb::" <<
				info.name << ": `" << e.what() << "`.";
		} catch (const exception &e) {
			lError() << "Unhandled generic exception in MainDb::" << info.name << ": `" << e.what() << "`.";
		}
	}

	SafeTransaction (SafeTransaction &&safeTransaction) : mFunction(move(safeTransaction.mFunction)) {}

	operator ReturnType () const {
		return mResult;
	}

private:
	static const char *getErrorCategoryAsString (soci::soci_error::error_category category) {
		switch (category) {
			case soci::soci_error::connection_error:
				return "CONNECTION ERROR";
			case soci::soci_error::invalid_statement:
				return "INVALID STATEMENT";
			case soci::soci_error::no_privilege:
				return "NO PRIVILEGE";
			case soci::soci_error::no_data:
				return "NO DATA";
			case soci::soci_error::constraint_violation:
				return "CONSTRAINT VIOLATION";
			case soci::soci_error::unknown_transaction_state:
				return "UNKNOWN TRANSACTION STATE";
			case soci::soci_error::system_error:
				return "SYSTEM ERROR";
			case soci::soci_error::unknown:
				return "UNKNOWN";
		}

		// Unreachable.
		L_ASSERT(false);
		return nullptr;
	}

	Function mFunction;
	ReturnType mResult{};

	L_DISABLE_COPY(SafeTransaction);
};

template<typename Function>
149
typename SafeTransaction<Function>::ReturnType operator* (SafeTransactionInfo &info, Function &&function) {
150 151 152
	return SafeTransaction<Function>(info, forward<Function>(function));
}

Ronan's avatar
Ronan committed
153
// -----------------------------------------------------------------------------
154
// Soci backend.
Ronan's avatar
Ronan committed
155 156
// -----------------------------------------------------------------------------

157 158 159 160 161 162 163 164 165 166 167 168
template<typename T>
struct EnumToSql {
	T first;
	const char *second;
};

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

170 171 172 173 174
static constexpr EnumToSql<MainDb::Filter> eventFilterToSql[] = {
	{ MainDb::ConferenceCallFilter, "3, 4" },
	{ MainDb::ConferenceChatMessageFilter, "5" },
	{ MainDb::ConferenceInfoFilter, "1, 2, 6, 7, 8, 9, 10, 11, 12" }
};
175

176 177 178 179 180
static constexpr const char *mapEventFilterToSql (MainDb::Filter filter) {
	return mapEnumToSql(
		eventFilterToSql, sizeof eventFilterToSql / sizeof eventFilterToSql[0], filter
	);
}
181

Ronan's avatar
Ronan committed
182 183
// -----------------------------------------------------------------------------

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
static string buildSqlEventFilter (
	const list<MainDb::Filter> &filters,
	MainDb::FilterMask mask,
	const string &condKeyWord = "WHERE"
) {
	L_ASSERT(
		find_if(filters.cbegin(), filters.cend(), [](const MainDb::Filter &filter) {
			return filter == MainDb::NoFilter;
		}) == filters.cend()
	);

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

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

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

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

	return sql;
}
217

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
// -----------------------------------------------------------------------------

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

234 235 236 237
static constexpr string &blobToString (string &in) {
	return in;
}

238 239
// -----------------------------------------------------------------------------

240 241 242 243 244 245 246 247
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))
		: static_cast<long long>(row.get<unsigned long long>(0));
}
248

249 250
// -----------------------------------------------------------------------------

251
long long MainDbPrivate::insertSipAddress (const string &sipAddress) {
252
	soci::session *session = dbSession.getBackendSession();
253

254 255 256
	long long id = selectSipAddressId(sipAddress);
	if (id >= 0)
		return id;
257

258 259
	lInfo() << "Insert new sip address in database: `" << sipAddress << "`.";
	*session << "INSERT INTO sip_address (value) VALUES (:sipAddress)", soci::use(sipAddress);
260
	return dbSession.getLastInsertId();
261
}
262

263
void MainDbPrivate::insertContent (long long eventId, const Content &content) {
264
	soci::session *session = dbSession.getBackendSession();
265 266 267 268 269 270 271

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

272
	const long long &chatMessageContentId = dbSession.getLastInsertId();
273
	if (content.isFile()) {
274 275 276 277 278 279 280 281 282 283 284 285 286 287
		const FileContent &fileContent = static_cast<const FileContent &>(content);
		const string &name = fileContent.getFileName();
		const size_t &size = fileContent.getFileSize();
		const string &path = fileContent.getFilePath();
		*session << "INSERT INTO chat_message_file_content (chat_message_content_id, name, size, path) VALUES "
			" (:chatMessageContentId, :name, :size, :path)",
			soci::use(chatMessageContentId), soci::use(name), soci::use(size), soci::use(path);
	}

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

289
long long MainDbPrivate::insertContentType (const string &contentType) {
290
	soci::session *session = dbSession.getBackendSession();
Sylvain Berfini's avatar
Sylvain Berfini committed
291

292 293 294 295
	long long id;
	*session << "SELECT id FROM content_type WHERE value = :contentType", soci::use(contentType), soci::into(id);
	if (session->got_data())
		return id;
296

297 298
	lInfo() << "Insert new content type in database: `" << contentType << "`.";
	*session << "INSERT INTO content_type (value) VALUES (:contentType)", soci::use(contentType);
299
	return dbSession.getLastInsertId();
300 301 302 303 304 305 306
}

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

309 310 311 312 313
	long long id = selectChatRoomId(peerSipAddressId, localSipAddressId);
	if (id >= 0) {
		*session << "UPDATE chat_room SET last_update_time = :lastUpdateTime WHERE id = :id",
			soci::use(creationTime), soci::use(id);
		return id;
314 315
	}

316 317 318 319 320 321 322 323 324 325
	static const int capabilities = ChatRoom::CapabilitiesMask(
		{ ChatRoom::Capabilities::Basic, ChatRoom::Capabilities::Migratable }
	);
	lInfo() << "Insert new chat room in database: (peer=" << peerSipAddressId <<
		", local=" << localSipAddressId << ", capabilities=" << capabilities << ").";
	*session << "INSERT INTO chat_room ("
		"  peer_sip_address_id, local_sip_address_id, creation_time, last_update_time, capabilities"
		") VALUES (:peerSipAddressId, :localSipAddressId, :creationTime, :lastUpdateTime, :capabilities)",
		soci::use(peerSipAddressId), soci::use(localSipAddressId), soci::use(creationTime), soci::use(creationTime),
		soci::use(capabilities);
326

327
	return dbSession.getLastInsertId();
328
}
329

330
long long MainDbPrivate::insertChatRoom (const shared_ptr<AbstractChatRoom> &chatRoom) {
331
	soci::session *session = dbSession.getBackendSession();
332

333 334 335
	const ChatRoomId &chatRoomId = chatRoom->getChatRoomId();
	const long long &peerSipAddressId = insertSipAddress(chatRoomId.getPeerAddress().asString());
	const long long &localSipAddressId = insertSipAddress(chatRoomId.getLocalAddress().asString());
336

337 338 339 340 341 342
	long long id = selectChatRoomId(peerSipAddressId, localSipAddressId);
	if (id >= 0) {
		lError() << "Unable to insert chat room (it already exists): (peer=" << peerSipAddressId <<
			", local=" << localSipAddressId << ").";
		return id;
	}
343

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

347 348
	const tm &creationTime = Utils::getTimeTAsTm(chatRoom->getCreationTime());
	// Remove capabilities like `Proxy`.
349
	const int &capabilities = chatRoom->getCapabilities() & ~ChatRoom::CapabilitiesMask(ChatRoom::Capabilities::Proxy);
350

351 352 353 354 355 356 357
	const string &subject = chatRoom->getSubject();
	const int &flags = chatRoom->hasBeenLeft();
	*session << "INSERT INTO chat_room ("
		"  peer_sip_address_id, local_sip_address_id, creation_time, last_update_time, capabilities, subject, flags"
		") VALUES (:peerSipAddressId, :localSipAddressId, :creationTime, :lastUpdateTime, :capabilities, :subject, :flags)",
		soci::use(peerSipAddressId), soci::use(localSipAddressId), soci::use(creationTime), soci::use(creationTime),
		soci::use(capabilities), soci::use(subject), soci::use(flags);
358

359
	id = dbSession.getLastInsertId();
360 361
	if (!chatRoom->canHandleParticipants())
		return id;
362

363 364 365 366 367 368 369 370 371 372 373
	// Do not add 'me' when creating a server-group-chat-room.
	if (chatRoomId.getLocalAddress() != chatRoomId.getPeerAddress()) {
		shared_ptr<Participant> me = chatRoom->getMe();
		long long meId = insertChatRoomParticipant(
			id,
			insertSipAddress(me->getAddress().asString()),
			me->isAdmin()
		);
		for (const auto &device : me->getPrivate()->getDevices())
			insertChatRoomParticipantDevice(meId, insertSipAddress(device->getAddress().asString()));
	}
374

375 376 377 378 379 380 381 382
	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()));
383 384
	}

385 386
	return id;
}
387

388 389 390 391 392
long long MainDbPrivate::insertChatRoomParticipant (
	long long chatRoomId,
	long long participantSipAddressId,
	bool isAdmin
) {
393
	soci::session *session = dbSession.getBackendSession();
394 395 396 397 398 399 400
	long long id = selectChatRoomParticipantId(chatRoomId, participantSipAddressId);
	if (id >= 0) {
		// See: https://stackoverflow.com/a/15299655 (cast to reference)
		*session << "UPDATE chat_room_participant SET is_admin = :isAdmin WHERE id = :id",
			soci::use(static_cast<const int &>(isAdmin)), soci::use(id);
		return id;
	}
401

402 403 404 405 406
	lInfo() << "Insert new chat room participant in database: `" << participantSipAddressId <<
		"` (isAdmin=" << isAdmin << ").";
	*session << "INSERT INTO chat_room_participant (chat_room_id, participant_sip_address_id, is_admin)"
		" VALUES (:chatRoomId, :participantSipAddressId, :isAdmin)",
		soci::use(chatRoomId), soci::use(participantSipAddressId), soci::use(static_cast<const int &>(isAdmin));
407

408
	return dbSession.getLastInsertId();
409
}
410

411 412 413 414
void MainDbPrivate::insertChatRoomParticipantDevice (
	long long participantId,
	long long participantDeviceSipAddressId
) {
415
	soci::session *session = dbSession.getBackendSession();
416 417 418 419 420 421 422 423 424 425 426 427 428
	long long count;
	*session << "SELECT COUNT(*) FROM chat_room_participant_device"
		" WHERE chat_room_participant_id = :participantId"
		" AND participant_device_sip_address_id = :participantDeviceSipAddressId",
		soci::into(count), soci::use(participantId), soci::use(participantDeviceSipAddressId);
	if (count)
		return;

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

430 431 432
void MainDbPrivate::insertChatMessageParticipant (long long eventId, long long sipAddressId, int state) {
	// TODO: Deal with read messages.
	// Remove if displayed? Think a good alorithm for mark as read.
433
	soci::session *session = dbSession.getBackendSession();
434 435 436 437 438 439 440 441 442 443 444
	soci::statement statement = (
		session->prepare << "UPDATE chat_message_participant SET state = :state"
			" WHERE event_id = :eventId AND participant_sip_address_id = :sipAddressId",
			soci::use(state), soci::use(eventId), soci::use(sipAddressId)
	);
	statement.execute();
	if (statement.get_affected_rows() == 0 && state != static_cast<int>(ChatMessage::State::Displayed))
		*session << "INSERT INTO chat_message_participant (event_id, participant_sip_address_id, state)"
			" VALUES (:eventId, :sipAddressId, :state)",
			soci::use(eventId), soci::use(sipAddressId), soci::use(state);
}
445

446 447
// -----------------------------------------------------------------------------

448
long long MainDbPrivate::selectSipAddressId (const string &sipAddress) const {
449
	soci::session *session = dbSession.getBackendSession();
450

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

456
long long MainDbPrivate::selectChatRoomId (long long peerSipAddressId, long long localSipAddressId) const {
457
	soci::session *session = dbSession.getBackendSession();
458

459 460 461 462 463 464
	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;
}
465

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

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

475 476
	return selectChatRoomId(peerSipAddressId, localSipAddressId);
}
477

478 479
long long MainDbPrivate::selectChatRoomParticipantId (long long chatRoomId, long long participantSipAddressId) const {
	long long id;
480
	soci::session *session = dbSession.getBackendSession();
481 482 483 484 485
	*session << "SELECT id from chat_room_participant"
		" WHERE chat_room_id = :chatRoomId AND participant_sip_address_id = :participantSipAddressId",
		soci::into(id), soci::use(chatRoomId), soci::use(participantSipAddressId);
	return session->got_data() ? id : -1;
}
486

487 488
long long MainDbPrivate::selectOneToOneChatRoomId (long long sipAddressIdA, long long sipAddressIdB) const {
	long long id;
489
	soci::session *session = dbSession.getBackendSession();
490 491 492 493 494 495 496 497 498
	*session << "SELECT chat_room_id"
		"  FROM one_to_one_chat_room"
		"  WHERE participant_a_sip_address_id IN (:sipAddressIdA, :sipAddressIdB)"
		"  AND participant_b_sip_address_id IN (:sipAddressIdABis, :sipAddressIdBBis)",
		soci::into(id),
		soci::use(sipAddressIdA), soci::use(sipAddressIdB), soci::use(sipAddressIdA), soci::use(sipAddressIdB);
	return session->got_data() ? id : -1;
}

499 500
// -----------------------------------------------------------------------------

501
void MainDbPrivate::deleteContents (long long messageEventId) {
502
	soci::session *session = dbSession.getBackendSession();
503 504
	*session << "DELETE FROM chat_message_content WHERE event_id = :messageEventId", soci::use(messageEventId);
}
505

506
void MainDbPrivate::deleteChatRoomParticipant (long long chatRoomId, long long participantSipAddressId) {
507
	soci::session *session = dbSession.getBackendSession();
508 509 510 511
	*session << "DELETE FROM chat_room_participant"
		"  WHERE chat_room_id = :chatRoomId AND participant_sip_address_id = :participantSipAddressId",
		soci::use(chatRoomId), soci::use(participantSipAddressId);
}
512

513 514 515 516
void MainDbPrivate::deleteChatRoomParticipantDevice (
	long long participantId,
	long long participantDeviceSipAddressId
) {
517
	soci::session *session = dbSession.getBackendSession();
518 519 520 521 522
	*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);
}
523

Ronan's avatar
Ronan committed
524 525
// -----------------------------------------------------------------------------

526 527 528 529 530 531 532 533 534 535 536
shared_ptr<EventLog> MainDbPrivate::selectGenericConferenceEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	shared_ptr<EventLog> eventLog;

	switch (type) {
		case EventLog::Type::None:
			return nullptr;
Ronan's avatar
Ronan committed
537

538 539 540 541
		case EventLog::Type::ConferenceCreated:
		case EventLog::Type::ConferenceTerminated:
			eventLog = selectConferenceEvent(eventId, type, creationTime, chatRoomId);
			break;
Ronan's avatar
Ronan committed
542

543 544 545 546
		case EventLog::Type::ConferenceCallStart:
		case EventLog::Type::ConferenceCallEnd:
			eventLog = selectConferenceCallEvent(eventId, type, creationTime, chatRoomId);
			break;
Ronan's avatar
Ronan committed
547

548 549 550
		case EventLog::Type::ConferenceChatMessage:
			eventLog = selectConferenceChatMessageEvent(eventId, type, creationTime, chatRoomId);
			break;
Ronan's avatar
Ronan committed
551

552 553 554 555 556 557
		case EventLog::Type::ConferenceParticipantAdded:
		case EventLog::Type::ConferenceParticipantRemoved:
		case EventLog::Type::ConferenceParticipantSetAdmin:
		case EventLog::Type::ConferenceParticipantUnsetAdmin:
			eventLog = selectConferenceParticipantEvent(eventId, type, creationTime, chatRoomId);
			break;
Ronan's avatar
Ronan committed
558

559 560 561 562
		case EventLog::Type::ConferenceParticipantDeviceAdded:
		case EventLog::Type::ConferenceParticipantDeviceRemoved:
			eventLog = selectConferenceParticipantDeviceEvent(eventId, type, creationTime, chatRoomId);
			break;
563

564 565 566
		case EventLog::Type::ConferenceSubjectChanged:
			eventLog = selectConferenceSubjectEvent(eventId, type, creationTime, chatRoomId);
			break;
567 568
	}

569 570
	if (eventLog)
		cache(eventLog, eventId);
Ronan's avatar
Ronan committed
571

572 573
	return eventLog;
}
Ronan's avatar
Ronan committed
574

575 576 577 578 579 580 581 582 583 584 585 586
shared_ptr<EventLog> MainDbPrivate::selectConferenceEvent (
	long long,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	return make_shared<ConferenceEvent>(
		type,
		creationTime,
		chatRoomId
	);
}
587

588 589 590 591 592 593 594 595 596
shared_ptr<EventLog> MainDbPrivate::selectConferenceCallEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	// TODO.
	return nullptr;
}
Ronan's avatar
Ronan committed
597

598 599 600 601
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";
602

603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
	string name;
	soci::statement statement = (session->prepare << query, soci::use(contentId), soci::into(name), soci::into(data));
	statement.execute();
	while (statement.fetch())
		content.setAppData(name, blobToString(data));
}

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

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

627
	bool hasFileTransferContent = false;
628

629 630 631 632 633 634 635
	// 1 - Fetch chat message.
	shared_ptr<ChatMessage> chatMessage = getChatMessageFromCache(eventId);
	if (chatMessage)
		goto end;
	{
		string fromSipAddress;
		string toSipAddress;
636

637 638 639
		tm messageTime;

		string imdnMessageId;
Ronan's avatar
Ronan committed
640

641 642 643
		int state;
		int direction;
		int isSecured;
644

645
		soci::session *session = dbSession.getBackendSession();
646 647 648 649 650 651 652 653 654 655 656 657 658 659
		*session << "SELECT from_sip_address.value, to_sip_address.value, time, imdn_message_id, state, direction, is_secured"
			" FROM event, conference_chat_message_event, sip_address AS from_sip_address, sip_address AS to_sip_address"
			" WHERE event_id = :eventId"
			" AND event_id = event.id"
			" AND from_sip_address_id = from_sip_address.id"
			" AND to_sip_address_id = to_sip_address.id", soci::into(fromSipAddress), soci::into(toSipAddress),
			soci::into(messageTime), soci::into(imdnMessageId), soci::into(state), soci::into(direction),
			soci::into(isSecured), soci::use(eventId);

		chatMessage = shared_ptr<ChatMessage>(new ChatMessage(
			chatRoom,
			static_cast<ChatMessage::Direction>(direction)
		));
		chatMessage->setIsSecured(static_cast<bool>(isSecured));
Ronan's avatar
Ronan committed
660

661 662
		ChatMessagePrivate *dChatMessage = chatMessage->getPrivate();
		dChatMessage->setState(static_cast<ChatMessage::State>(state), true);
663

664 665
		dChatMessage->forceFromAddress(IdentityAddress(fromSipAddress));
		dChatMessage->forceToAddress(IdentityAddress(toSipAddress));
Ronan's avatar
Ronan committed
666

667 668 669
		dChatMessage->setTime(Utils::getTmAsTimeT(messageTime));
		dChatMessage->setImdnMessageId(imdnMessageId);
	}
670

671 672
	// 2 - Fetch contents.
	{
673
		soci::session *session = dbSession.getBackendSession();
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
		static const string query = "SELECT chat_message_content.id, content_type.id, 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>(2));
			const long long &contentId = resolveId(row, 0);
			Content *content;

			if (contentType == ContentType::FileTransfer) {
				hasFileTransferContent = true;
				content = new FileTransferContent();
			}
			else if (contentType.isFile()) {
				// 2.1 - Fetch contents' file informations.
				string name;
				int size;
				string path;

				*session << "SELECT name, size, path FROM chat_message_file_content"
					" WHERE chat_message_content_id = :contentId",
					soci::into(name), soci::into(size), soci::into(path), soci::use(contentId);

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

				content = fileContent;
			} else
				content = new Content();

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

			// 2.2 - Fetch contents' app data.
			if (q->getBackend() == MainDb::Backend::Sqlite3) {
				soci::blob data(*session);
				fetchContentAppData(session, *content, contentId, data);
			} else {
				string data;
				fetchContentAppData(session, *content, contentId, data);
			}
			chatMessage->addContent(*content);
		}
Ronan's avatar
Ronan committed
719 720
	}

721 722 723
	// 3 - Load external body url from body into FileTransferContent if needed.
	if (hasFileTransferContent)
		chatMessage->getPrivate()->loadFileTransferUrlFromBodyToContent();
724

725
	cache(chatMessage, eventId);
726

727 728 729 730 731 732
end:
	return make_shared<ConferenceChatMessageEvent>(
		creationTime,
		chatMessage
	);
}
733

734 735 736 737 738 739 740 741 742
shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	unsigned int notifyId;
	string participantAddress;

743
	soci::session *session = dbSession.getBackendSession();
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
	*session << "SELECT notify_id, participant_address.value"
		"  FROM conference_notified_event, conference_participant_event, sip_address as participant_address"
		"  WHERE conference_participant_event.event_id = :eventId"
		"    AND conference_notified_event.event_id = conference_participant_event.event_id"
		"    AND participant_address.id = participant_sip_address_id",
		soci::into(notifyId), soci::into(participantAddress), soci::use(eventId);

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

760 761 762 763 764 765 766 767 768 769
shared_ptr<EventLog> MainDbPrivate::selectConferenceParticipantDeviceEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	unsigned int notifyId;
	string participantAddress;
	string deviceAddress;

770
	soci::session *session = dbSession.getBackendSession();
771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
	*session << "SELECT notify_id, participant_address.value, device_address.value"
		"  FROM conference_notified_event, conference_participant_event, conference_participant_device_event,"
		"    sip_address AS participant_address, sip_address AS device_address"
		"  WHERE conference_participant_device_event.event_id = :eventId"
		"    AND conference_participant_event.event_id = conference_participant_device_event.event_id"
		"    AND conference_notified_event.event_id = conference_participant_event.event_id"
		"    AND participant_address.id = participant_sip_address_id"
		"    AND device_address.id = device_sip_address_id",
		soci::into(notifyId), soci::into(participantAddress), soci::into(deviceAddress), soci::use(eventId);

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

791 792 793 794 795 796 797 798 799
shared_ptr<EventLog> MainDbPrivate::selectConferenceSubjectEvent (
	long long eventId,
	EventLog::Type type,
	time_t creationTime,
	const ChatRoomId &chatRoomId
) const {
	unsigned int notifyId;
	string subject;

800
	soci::session *session = dbSession.getBackendSession();
801 802 803 804 805 806 807 808 809 810 811 812 813
	*session << "SELECT notify_id, subject"
		" FROM conference_notified_event, conference_subject_event"
		" WHERE conference_subject_event.event_id = :eventId"
		" AND conference_notified_event.event_id = conference_subject_event.event_id",
		soci::into(notifyId), soci::into(subject), soci::use(eventId);

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

815
// -----------------------------------------------------------------------------
816

817
long long MainDbPrivate::insertEvent (const shared_ptr<EventLog> &eventLog) {
818
	soci::session *session = dbSession.getBackendSession();
819

820 821 822 823 824 825
	const int &type = static_cast<int>(eventLog->getType());
	const tm &creationTime = Utils::getTimeTAsTm(eventLog->getCreationTime());
	*session << "INSERT INTO event (type, creation_time) VALUES (:type, :creationTime)",
		soci::use(type),
		soci::use(creationTime);

826
	return dbSession.getLastInsertId();
827
}
828

829 830 831 832 833 834 835 836 837 838 839 840 841 842
long long MainDbPrivate::insertConferenceEvent (const shared_ptr<EventLog> &eventLog, long long *chatRoomId) {
	shared_ptr<ConferenceEvent> conferenceEvent = static_pointer_cast<ConferenceEvent>(eventLog);

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

844
		soci::session *session = dbSession.getBackendSession();
845 846 847 848 849 850 851
		*session << "INSERT INTO conference_event (event_id, chat_room_id)"
			" VALUES (:eventId, :chatRoomId)", soci::use(eventId), soci::use(curChatRoomId);

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

853 854
		if (eventLog->getType() == EventLog::Type::ConferenceTerminated)
			*session << "UPDATE chat_room SET flags = 1 WHERE id = :chatRoomId", soci::use(curChatRoomId);
855 856
	}

857 858 859 860 861
	if (chatRoomId)
		*chatRoomId = curChatRoomId;

	return eventId;
}
862

863 864 865 866
long long MainDbPrivate::insertConferenceCallEvent (const shared_ptr<EventLog> &eventLog) {
	// TODO.
	return 0;
}
867

868 869 870 871 872 873 874 875 876 877 878 879
long long MainDbPrivate::insertConferenceChatMessageEvent (const shared_ptr<EventLog> &eventLog) {
	shared_ptr<ChatMessage> chatMessage = static_pointer_cast<ConferenceChatMessageEvent>(eventLog)->getChatMessage();
	shared_ptr<AbstractChatRoom> chatRoom = chatMessage->getChatRoom();
	if (!chatRoom) {
		lError() << "Unable to get a valid chat room. It was removed from database.";
		return -1;
	}

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

880
	soci::session *session = dbSession.getBackendSession();
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911

	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;

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

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

	return eventId;
}

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

914 915 916
	const EventLogPrivate *dEventLog = eventLog->getPrivate();
	MainDbKeyPrivate *dEventKey = static_cast<MainDbKey &>(dEventLog->dbKey).getPrivate();
	const long long &eventId = dEventKey->storageId;
917

918
	soci::session *session = dbSession.getBackendSession();
919 920 921 922 923
	const int &state = static_cast<int>(chatMessage->getState());
	const string &imdnMessageId = chatMessage->getImdnMessageId();
	*session << "UPDATE conference_chat_message_event SET state = :state, imdn_message_id = :imdnMessageId"
		" WHERE event_id = :eventId",
		soci::use(state), soci::use(imdnMessageId), soci::use(eventId);
924

925 926 927 928
	deleteContents(eventId);
	for (const auto &content : chatMessage->getContents())
		insertContent(eventId, *content);
}
929

930 931 932 933 934
long long MainDbPrivate::insertConferenceNotifiedEvent (const shared_ptr<EventLog> &eventLog, long long *chatRoomId) {
	long long curChatRoomId;
	const long long &eventId = insertConferenceEvent(eventLog, &curChatRoomId);
	if (eventId < 0)
		return -1;
935

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

938
	soci::session *session = dbSession.getBackendSession();
939 940 941 942
	*session << "INSERT INTO conference_notified_event (event_id, notify_id)"
		" VALUES (:eventId, :notifyId)", soci::use(eventId), soci::use(lastNotifyId);
	*session << "UPDATE chat_room SET last_notify_id = :lastNotifyId WHERE id = :chatRoomId",
		soci::use(lastNotifyId), soci::use(curChatRoomId);
943

944 945
	if (chatRoomId)
		*chatRoomId = curChatRoomId;
946

947 948
	return eventId;
}
949

950 951 952 953 954 955 956 957
long long MainDbPrivate::insertConferenceParticipantEvent (
	const shared_ptr<EventLog> &eventLog,
	long long *chatRoomId
) {
	long long curChatRoomId;
	const long long &eventId = insertConferenceNotifiedEvent(eventLog, &curChatRoomId);
	if (eventId < 0)
		return -1;
958

959 960
	shared_ptr<ConferenceParticipantEvent> participantEvent =
		static_pointer_cast<ConferenceParticipantEvent>(eventLog);
961

962 963 964 965
	const long long &participantAddressId = insertSipAddress(
		participantEvent->getParticipantAddress().asString()
	);

966
	soci::session *session = dbSession.getBackendSession();
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
	*session << "INSERT INTO conference_participant_event (event_id, participant_sip_address_id)"
		"  VALUES (:eventId, :participantAddressId)", soci::use(eventId), soci::use(participantAddressId);

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

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

		default:
			break;
984 985
	}

986 987
	if (chatRoomId)
		*chatRoomId = curChatRoomId;
988

989 990
	return eventId;
}
991

992 993 994 995 996
long long MainDbPrivate::insertConferenceParticipantDeviceEvent (const shared_ptr<EventLog> &eventLog) {
	long long chatRoomId;
	const long long &eventId = insertConferenceParticipantEvent(eventLog, &chatRoomId);
	if (eventId < 0)
		return -1;
997

998 999
	shared_ptr<ConferenceParticipantDeviceEvent> participantDeviceEvent =
		static_pointer_cast<ConferenceParticipantDeviceEvent>(eventLog);
1000

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
	const string participantAddress = participantDeviceEvent->getParticipantAddress().asString();
	const long long &participantAddressId = selectSipAddressId(participantAddress);
	if (participantAddressId < 0) {
		lError() << "Unable to find sip address id of: `" << participantAddress << "`.";
		return -1;
	}
	const long long &participantId = selectChatRoomParticipantId(chatRoomId, participantAddressId);
	if (participantId < 0) {
		lError() << "Unable to find valid participant id in database with chat room id = " << chatRoomId <<
		" and participant address id = " << participantId;
		return -1;
	}
	const long long &deviceAddressId = insertSipAddress(
		participantDeviceEvent->getDeviceAddress().asString()
	);
1016

1017
	soci::session *session = dbSession.getBackendSession();
1018 1019
	*session << "INSERT INTO conference_participant_device_event (event_id, device_sip_address_id)"
		" VALUES (:eventId, :deviceAddressId)", soci::use(eventId), soci::use(deviceAddressId);
1020

1021 1022 1023 1024
	switch (eventLog->getType()) {
		case EventLog::Type::ConferenceParticipantDeviceAdded:
			insertChatRoomParticipantDevice(participantId, deviceAddressId);
			break;
1025

1026 1027 1028 1029 1030 1031
		case EventLog::Type::ConferenceParticipantDeviceRemoved:
			deleteChatRoomParticipantDevice(participantId, deviceAddressId);
			break;

		default:
			break;
1032 1033
	}

1034 1035
	return eventId;
}
1036

1037 1038 1039 1040 1041
long long MainDbPrivate::insertConferenceSubjectEvent (const shared_ptr<EventLog> &eventLog) {
	long long chatRoomId;
	const long long &eventId = insertConferenceNotifiedEvent(eventLog, &chatRoomId);
	if (eventId < 0)
		return -1;