chat-message.cpp 29.3 KB
Newer Older
1
/*
2
 * chat-message.cpp
Ghislain MARY's avatar
Ghislain MARY committed
3
 * Copyright (C) 2010-2017 Belledonne Communications SARL
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.
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.
18
 */
Ronan's avatar
Ronan committed
19 20 21

#include "object/object-p.h"

22 23
#include "linphone/core.h"
#include "linphone/lpconfig.h"
24
#include "c-wrapper/c-wrapper.h"
25
#include "address/address.h"
26

Ronan's avatar
Ronan committed
27
#include "chat/chat-message/chat-message-p.h"
Ronan's avatar
Ronan committed
28

Ronan's avatar
Ronan committed
29 30 31 32
#include "chat/chat-room/chat-room-p.h"
#include "chat/chat-room/real-time-text-chat-room.h"
#include "chat/modifier/cpim-chat-message-modifier.h"
#include "chat/modifier/encryption-chat-message-modifier.h"
33
#include "chat/modifier/file-transfer-chat-message-modifier.h"
Ronan's avatar
Ronan committed
34
#include "chat/modifier/multipart-chat-message-modifier.h"
35
#include "content/file-content.h"
36 37
#include "content/content.h"
#include "core/core.h"
38
#include "logger/logger.h"
39

40
#include "ortp/b64.h"
41

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

using namespace std;

46
using namespace B64_NAMESPACE;
47

48
LINPHONE_BEGIN_NAMESPACE
49

50 51 52 53
void ChatMessagePrivate::setDirection (ChatMessage::Direction dir) {
	direction = dir;
}

54
void ChatMessagePrivate::setTime (time_t t) {
55 56 57
	time = t;
}

58
void ChatMessagePrivate::setIsReadOnly (bool readOnly) {
59 60 61
	isReadOnly = readOnly;
}

62
void ChatMessagePrivate::setState (ChatMessage::State s, bool force) {
63 64
	L_Q();

65 66 67
	if (force)
		state = s;

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
	if (s == state || !q->getChatRoom())
		return;

	if (
		(state == ChatMessage::State::Displayed || state == ChatMessage::State::DeliveredToUser) &&
		(
			s == ChatMessage::State::DeliveredToUser ||
			s == ChatMessage::State::Delivered ||
			s == ChatMessage::State::NotDelivered
		)
	)
		return;

	lInfo() << "Chat message " << this << ": moving from state " <<
		linphone_chat_message_state_to_string((LinphoneChatMessageState)state) << " to " <<
		linphone_chat_message_state_to_string((LinphoneChatMessageState)s);
	state = s;

	LinphoneChatMessage *msg = L_GET_C_BACK_PTR(q);
	if (linphone_chat_message_get_message_state_changed_cb(msg))
		linphone_chat_message_get_message_state_changed_cb(msg)(
			msg,
			(LinphoneChatMessageState)state,
			linphone_chat_message_get_message_state_changed_cb_user_data(msg)
		);

	LinphoneChatMessageCbs *cbs = linphone_chat_message_get_callbacks(msg);
	if (cbs && linphone_chat_message_cbs_get_msg_state_changed(cbs))
		linphone_chat_message_cbs_get_msg_state_changed(cbs)(msg, linphone_chat_message_get_state(msg));
97 98
}

99
unsigned int ChatMessagePrivate::getStorageId () const {
100 101 102
	return storageId;
}

103
void ChatMessagePrivate::setStorageId (unsigned int id) {
104 105 106
	storageId = id;
}

107
belle_http_request_t *ChatMessagePrivate::getHttpRequest () const {
108
	return fileTransferChatMessageModifier.getHttpRequest();
109 110
}

111
void ChatMessagePrivate::setHttpRequest (belle_http_request_t *request) {
112
	fileTransferChatMessageModifier.setHttpRequest(request);
113 114
}

115
SalOp *ChatMessagePrivate::getSalOp () const {
116 117 118
	return salOp;
}

119
void ChatMessagePrivate::setSalOp (SalOp *op) {
120 121 122
	salOp = op;
}

123
SalCustomHeader *ChatMessagePrivate::getSalCustomHeaders () const {
124 125 126
	return salCustomHeaders;
}

127
void ChatMessagePrivate::setSalCustomHeaders (SalCustomHeader *headers) {
128 129 130
	salCustomHeaders = headers;
}

131
void ChatMessagePrivate::addSalCustomHeader (const string &name, const string &value) {
132 133 134
	salCustomHeaders = sal_custom_header_append(salCustomHeaders, name.c_str(), value.c_str());
}

135
void ChatMessagePrivate::removeSalCustomHeader (const string &name) {
136 137 138
	salCustomHeaders = sal_custom_header_remove(salCustomHeaders, name.c_str());
}

139
string ChatMessagePrivate::getSalCustomHeaderValue (const string &name) {
140
	return L_C_TO_STRING(sal_custom_header_find(salCustomHeaders, name.c_str()));
141 142
}

143 144
// -----------------------------------------------------------------------------
// Below methods are only for C API backward compatibility...
145 146
// -----------------------------------------------------------------------------

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
bool ChatMessagePrivate::hasTextContent() const {
	for (const Content *c : contents) {
		if (c->getContentType() == ContentType::PlainText) {
			return true;
		}
	}
	return false;
}

const Content* ChatMessagePrivate::getTextContent() const {
	for (const Content *c : contents) {
		if (c->getContentType() == ContentType::PlainText) {
			return c;
		}
	}
	return &Content::Empty;
}

bool ChatMessagePrivate::hasFileTransferContent() const {
	for (const Content *c : contents) {
		if (c->getContentType() == ContentType::FileTransfer) {
			return true;
		}
	}
	return false;
}

const Content* ChatMessagePrivate::getFileTransferContent() const {
	for (const Content *c : contents) {
		if (c->getContentType() == ContentType::FileTransfer) {
			return c;
		}
	}
	return &Content::Empty;
}

const string &ChatMessagePrivate::getFileTransferFilepath () const {
	return fileTransferFilePath;
}

void ChatMessagePrivate::setFileTransferFilepath (const string &path) {
	fileTransferFilePath = path;
}

const string &ChatMessagePrivate::getAppdata () const {
192 193 194 195 196 197 198
	for (const Content *c : contents) {
		if (c->getContentType().isFile()) {
			FileContent *fileContent = (FileContent *)c;
			return fileContent->getFilePath();
		}
	}
	return Utils::getEmptyConstRefObject<string>();
199 200 201
}

void ChatMessagePrivate::setAppdata (const string &data) {
202 203 204 205 206 207
	for (const Content *c : contents) {
		if (c->getContentType().isFile()) {
			FileContent *fileContent = (FileContent *)c;
			return fileContent->setFilePath(data);
		}
	}
208 209 210 211 212 213 214 215 216 217
}

const string &ChatMessagePrivate::getExternalBodyUrl () const {
	if (hasFileTransferContent()) {
		FileTransferContent *content = (FileTransferContent*) getFileTransferContent();
		return content->getFileUrl();
	}
	return Utils::getEmptyConstRefObject<string>();
}

218
const ContentType &ChatMessagePrivate::getContentType () {
219
	if (direction == ChatMessage::Direction::Incoming) {
220
		if (contents.size() > 0) {
221 222
			Content *content = contents.front();
			cContentType = content->getContentType();
223 224 225 226 227 228 229 230
		} else {
			cContentType = internalContent.getContentType();
		}
	} else {
		if (internalContent.getContentType().isValid()) {
			cContentType = internalContent.getContentType();
		} else {
			if (contents.size() > 0) {
231 232
				Content *content = contents.front();
				cContentType = content->getContentType();
233
			}
234
		}
235
	}
236 237 238
	return cContentType;
}

239
void ChatMessagePrivate::setContentType (const ContentType &contentType) {
240
	internalContent.setContentType(contentType);
241 242
}

243
const string &ChatMessagePrivate::getText () {
244
	if (direction == ChatMessage::Direction::Incoming) {
245 246
		if (hasTextContent()) {
			cText = getTextContent()->getBodyAsString();
247 248 249
		} else if (contents.size() > 0) {
			Content *content = contents.front();
			cText = content->getBodyAsString();
250 251 252 253
		} else {
			cText = internalContent.getBodyAsString();
		}
	} else {
254 255
		if (hasTextContent()) {
			cText = getTextContent()->getBodyAsString();
256
		} else if (!internalContent.isEmpty()) {
257 258 259
			cText = internalContent.getBodyAsString();
		} else {
			if (contents.size() > 0) {
260 261
				Content *content = contents.front();
				cText = content->getBodyAsString();
262
			}
263
		}
264
	}
265 266 267
	return cText;
}

268
void ChatMessagePrivate::setText (const string &text) {
269
	internalContent.setBody(text);
270 271
}

272
LinphoneContent *ChatMessagePrivate::getFileTransferInformation () const {
273 274
	if (hasFileTransferContent()) {
		return getFileTransferContent()->toLinphoneContent();
275
	}
276 277 278 279 280 281
	for (const Content *c : contents) {
		if (c->getContentType().isFile()) {
			FileContent *fileContent = (FileContent *)c;
			return fileContent->toLinphoneContent();
		}
	}
282
	return NULL;
283 284
}

285 286 287
void ChatMessagePrivate::setFileTransferInformation (const LinphoneContent *c_content) {
	L_Q();

288
	// Create a FileContent, it will create the FileTransferContent at upload time
289
	FileContent *fileContent = new FileContent();
290
	ContentType contentType(linphone_content_get_type(c_content), linphone_content_get_subtype(c_content));
291 292 293
	fileContent->setContentType(contentType);
	fileContent->setFileSize(linphone_content_get_size(c_content));
	fileContent->setFileName(linphone_content_get_name(c_content));
294
	if (linphone_content_get_string_buffer(c_content) != NULL) {
295
		fileContent->setBody(linphone_content_get_string_buffer(c_content));
296 297
	}

298
	q->addContent(*fileContent);
299 300
}

301
bool ChatMessagePrivate::downloadFile () {
302 303
	L_Q();

304 305 306
	for (auto &content : contents)
		if (content->getContentType() == ContentType::FileTransfer)
			return q->downloadFile(*static_cast<FileTransferContent *>(content));
307

308
	return false;
309 310 311 312
}

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

313
string ChatMessagePrivate::createImdnXml (Imdn::Type imdnType, LinphoneReason reason) {
314
	xmlBufferPtr buf;
315 316
	xmlTextWriterPtr writer;
	int err;
317
	string content;
318
	char *datetime = nullptr;
319

320 321
	// Check that the chat message has a message id.
	if (id.empty()) return nullptr;
322 323

	buf = xmlBufferCreate();
324
	if (buf == nullptr) {
325
		lError() << "Error creating the XML buffer";
326 327 328
		return content;
	}
	writer = xmlNewTextWriterMemory(buf, 0);
329
	if (writer == nullptr) {
330
		lError() << "Error creating the XML writer";
331 332 333
		return content;
	}

334
	datetime = linphone_timestamp_to_rfc3339_string(time);
335
	err = xmlTextWriterStartDocument(writer, "1.0", "UTF-8", nullptr);
336
	if (err >= 0) {
337 338
		err = xmlTextWriterStartElementNS(writer, nullptr, (const xmlChar *)"imdn",
				(const xmlChar *)"urn:ietf:params:xml:ns:imdn");
339 340
	}
	if ((err >= 0) && (reason != LinphoneReasonNone)) {
341
		err = xmlTextWriterWriteAttributeNS(writer, (const xmlChar *)"xmlns", (const xmlChar *)"linphoneimdn", nullptr, (const xmlChar *)"http://www.linphone.org/xsds/imdn.xsd");
342 343
	}
	if (err >= 0) {
344
		err = xmlTextWriterWriteElement(writer, (const xmlChar *)"message-id", (const xmlChar *)id.c_str());
345 346 347 348 349
	}
	if (err >= 0) {
		err = xmlTextWriterWriteElement(writer, (const xmlChar *)"datetime", (const xmlChar *)datetime);
	}
	if (err >= 0) {
350
		if (imdnType == Imdn::Type::Delivery) {
351 352 353 354 355 356 357 358 359 360
			err = xmlTextWriterStartElement(writer, (const xmlChar *)"delivery-notification");
		} else {
			err = xmlTextWriterStartElement(writer, (const xmlChar *)"display-notification");
		}
	}
	if (err >= 0) {
		err = xmlTextWriterStartElement(writer, (const xmlChar *)"status");
	}
	if (err >= 0) {
		if (reason == LinphoneReasonNone) {
361
			if (imdnType == Imdn::Type::Delivery) {
362 363 364 365 366 367 368 369 370 371 372 373 374
				err = xmlTextWriterStartElement(writer, (const xmlChar *)"delivered");
			} else {
				err = xmlTextWriterStartElement(writer, (const xmlChar *)"displayed");
			}
		} else {
			err = xmlTextWriterStartElement(writer, (const xmlChar *)"error");
		}
	}
	if (err >= 0) {
		// Close the "delivered", "displayed" or "error" element.
		err = xmlTextWriterEndElement(writer);
	}
	if ((err >= 0) && (reason != LinphoneReasonNone)) {
375
		err = xmlTextWriterStartElementNS(writer, (const xmlChar *)"linphoneimdn", (const xmlChar *)"reason", nullptr);
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
		if (err >= 0) {
			char codestr[16];
			snprintf(codestr, 16, "%d", linphone_reason_to_error_code(reason));
			err = xmlTextWriterWriteAttribute(writer, (const xmlChar *)"code", (const xmlChar *)codestr);
		}
		if (err >= 0) {
			err = xmlTextWriterWriteString(writer, (const xmlChar *)linphone_reason_to_string(reason));
		}
		if (err >= 0) {
			err = xmlTextWriterEndElement(writer);
		}
	}
	if (err >= 0) {
		// Close the "status" element.
		err = xmlTextWriterEndElement(writer);
	}
	if (err >= 0) {
		// Close the "delivery-notification" or "display-notification" element.
		err = xmlTextWriterEndElement(writer);
	}
	if (err >= 0) {
		// Close the "imdn" element.
		err = xmlTextWriterEndElement(writer);
	}
	if (err >= 0) {
		err = xmlTextWriterEndDocument(writer);
	}
	if (err > 0) {
		// xmlTextWriterEndDocument returns the size of the content.
405
		content = string((char *)buf->content);
406 407 408 409
	}
	xmlFreeTextWriter(writer);
	xmlBufferFree(buf);
	ms_free(datetime);
410
	return content;
411 412
}

413
void ChatMessagePrivate::sendImdn (Imdn::Type imdnType, LinphoneReason reason) {
414 415 416
	// FIXME: Add impl.
	// L_Q();
	// q->getChatRoom()->getPrivate()->sendImdn(createImdnXml(imdnType, reason), reason);
417 418 419
}

LinphoneReason ChatMessagePrivate::receive () {
420
	L_Q();
421
	int errorCode = 0;
422
	LinphoneReason reason = LinphoneReasonNone;
423

424 425 426
	shared_ptr<Core> core = q->getCore();
	shared_ptr<ChatRoom> chatRoom = q->getChatRoom();

427 428 429 430
	// ---------------------------------------
	// Start of message modification
	// ---------------------------------------

431 432 433 434 435 436 437 438 439

	if ((currentRecvStep &ChatMessagePrivate::Step::Cpim) == ChatMessagePrivate::Step::Cpim) {
		lInfo() << "Cpim step already done, skipping";
	} else {
		if (internalContent.getContentType() == ContentType::Cpim) {
			CpimChatMessageModifier ccmm;
			ccmm.decode(q->getSharedFromThis(), errorCode);
		}
		currentRecvStep |= ChatMessagePrivate::Step::Cpim;
440 441
	}

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
	if ((currentRecvStep &ChatMessagePrivate::Step::Encryption) == ChatMessagePrivate::Step::Encryption) {
		lInfo() << "Encryption step already done, skipping";
	} else {
		EncryptionChatMessageModifier ecmm;
		ChatMessageModifier::Result result = ecmm.decode(q->getSharedFromThis(), errorCode);
		if (result == ChatMessageModifier::Result::Error) {
			/* Unable to decrypt message */
			if (chatRoom)
				chatRoom->getPrivate()->notifyUndecryptableMessageReceived(q->getSharedFromThis());
			reason = linphone_error_code_to_reason(errorCode);
			q->sendDeliveryNotification(reason);
			return reason;
		} else if (result == ChatMessageModifier::Result::Suspended) {
			currentRecvStep |= ChatMessagePrivate::Step::Encryption;
			return LinphoneReasonNone;
		}
		currentRecvStep |= ChatMessagePrivate::Step::Encryption;
459
	}
460

461 462 463 464 465 466 467
	if ((currentRecvStep &ChatMessagePrivate::Step::Multipart) == ChatMessagePrivate::Step::Multipart) {
		lInfo() << "Multipart step already done, skipping";
	} else {
		MultipartChatMessageModifier mcmm;
		mcmm.decode(q->getSharedFromThis(), errorCode);
		currentRecvStep |= ChatMessagePrivate::Step::Multipart;
	}
468

469
	if ((currentRecvStep & ChatMessagePrivate::Step::FileUpload) == ChatMessagePrivate::Step::FileUpload) {
Sylvain Berfini's avatar
Sylvain Berfini committed
470
		lInfo() << "File download step already done, skipping";
471 472 473 474 475
	} else {
		// This will check if internal content is FileTransfer and make the appropriate changes
		fileTransferChatMessageModifier.decode(q->getSharedFromThis(), errorCode);
		currentRecvStep |= ChatMessagePrivate::Step::FileUpload;
	}
476

477 478
	if (contents.size() == 0) {
		// All previous modifiers only altered the internal content, let's fill the content list
479
		contents.push_back(&internalContent);
480 481
	}

482 483 484 485
	// ---------------------------------------
	// End of message modification
	// ---------------------------------------

486 487
	if (errorCode <= 0) {
		bool foundSupportContentType = false;
488 489
		for (Content *c : contents) {
			if (linphone_core_is_content_type_supported(core->getCCore(), c->getContentType().asString().c_str())) {
490 491 492
				foundSupportContentType = true;
				break;
			} else
493
			lError() << "Unsupported content-type: " << c->getContentType().asString();
494
		}
495 496 497 498 499

		if (!foundSupportContentType) {
			errorCode = 415;
			lError() << "No content-type in the contents list is supported...";
		}
500 501
	}

502
	// Check if this is in fact an outgoing message (case where this is a message sent by us from an other device).
503
	Address me(linphone_core_get_identity(core->getCCore()));
504
	if (me.weakEqual(q->getFromAddress()))
505
		setDirection(ChatMessage::Direction::Outgoing);
506

507
	// Check if this is a duplicate message.
508
	if (chatRoom && chatRoom->findMessageWithDirection(q->getImdnMessageId(), direction))
509
		return core->getCCore()->chat_deny_code;
510

511 512
	if (errorCode > 0) {
		reason = linphone_error_code_to_reason(errorCode);
513
		q->sendDeliveryNotification(reason);
514
		return reason;
515 516
	}

517
	bool messageToBeStored = false;
518 519
	for (Content *c : contents) {
		if (c->getContentType() == ContentType::FileTransfer || c->getContentType() == ContentType::PlainText) {
520
			messageToBeStored = true;
521
		}
522
	}
523
	if (messageToBeStored)
524 525 526 527 528
		q->store();

	return reason;
}

529
void ChatMessagePrivate::send () {
530 531
	L_Q();
	SalOp *op = salOp;
532
	LinphoneCall *call = nullptr;
533
	int errorCode = 0;
534

535
	if ((currentSendStep & ChatMessagePrivate::Step::FileUpload) == ChatMessagePrivate::Step::FileUpload) {
536 537
		lInfo() << "File upload step already done, skipping";
	} else {
538
		ChatMessageModifier::Result result = fileTransferChatMessageModifier.encode(q->getSharedFromThis(), errorCode);
539
		if (result == ChatMessageModifier::Result::Error) {
540
			setState(ChatMessage::State::NotDelivered);
541 542 543 544 545
			return;
		} else if (result == ChatMessageModifier::Result::Suspended) {
			setState(ChatMessage::State::InProgress);
			return;
		}
546
		currentSendStep |= ChatMessagePrivate::Step::FileUpload;
547 548
	}

549
	shared_ptr<Core> core = q->getCore();
550
	if (lp_config_get_int(core->getCCore()->config, "sip", "chat_use_call_dialogs", 0) != 0) {
551
		call = linphone_core_get_call_by_remote_address(core->getCCore(), q->getToAddress().asString().c_str());
552 553
		if (call) {
			if (linphone_call_get_state(call) == LinphoneCallConnected || linphone_call_get_state(call) == LinphoneCallStreamsRunning ||
554 555
					linphone_call_get_state(call) == LinphoneCallPaused || linphone_call_get_state(call) == LinphoneCallPausing ||
					linphone_call_get_state(call) == LinphoneCallPausedByRemote) {
556
				lInfo() << "send SIP msg through the existing call.";
557
				op = linphone_call_get_op(call);
558
				string identity = linphone_core_find_best_identity(core->getCCore(), linphone_call_get_remote_address(call));
559
				if (identity.empty()) {
560
					LinphoneAddress *addr = linphone_address_new(q->getToAddress().asString().c_str());
561
					LinphoneProxyConfig *proxy = linphone_core_lookup_known_proxy(core->getCCore(), addr);
562 563 564
					if (proxy) {
						identity = L_GET_CPP_PTR_FROM_C_OBJECT(linphone_proxy_config_get_identity_address(proxy))->asString();
					} else {
565
						identity = linphone_core_get_primary_contact(core->getCCore());
566 567 568 569 570 571 572
					}
					linphone_address_unref(addr);
				}
			}
		}
	}

573
	if (!op) {
574
		LinphoneAddress *peer = linphone_address_new(q->getToAddress().asString().c_str());
575
		/* Sending out of call */
576
		salOp = op = new SalMessageOp(core->getCCore()->sal);
577
		op->setUseGruuInFrom(true);
578
		linphone_configure_op(
579 580
			core->getCCore(), op, peer, getSalCustomHeaders(),
			!!lp_config_get_int(core->getCCore()->config, "sip", "chat_msg_with_contact", 0)
581
		);
582
		op->set_user_pointer(L_GET_C_BACK_PTR(q));     /* If out of call, directly store msg */
583 584
		linphone_address_unref(peer);
	}
585

586 587 588 589
	// ---------------------------------------
	// Start of message modification
	// ---------------------------------------

590
	if (applyModifiers) {
591
		if ((currentSendStep &ChatMessagePrivate::Step::Multipart) == ChatMessagePrivate::Step::Multipart) {
592 593 594 595 596 597 598
			lInfo() << "Multipart step already done, skipping";
		} else {
			if (contents.size() > 1) {
				MultipartChatMessageModifier mcmm;
				mcmm.encode(q->getSharedFromThis(), errorCode);
			}
			currentSendStep |= ChatMessagePrivate::Step::Multipart;
599
		}
600

601
		if ((currentSendStep &ChatMessagePrivate::Step::Encryption) == ChatMessagePrivate::Step::Encryption) {
602 603 604 605 606 607 608 609 610 611 612 613 614
			lInfo() << "Encryption step already done, skipping";
		} else {
			EncryptionChatMessageModifier ecmm;
			ChatMessageModifier::Result result = ecmm.encode(q->getSharedFromThis(), errorCode);
			if (result == ChatMessageModifier::Result::Error) {
				sal_error_info_set((SalErrorInfo *)op->get_error_info(), SalReasonNotAcceptable, "SIP", errorCode, "Unable to encrypt IM", nullptr);
				q->updateState(ChatMessage::State::NotDelivered);
				q->store();
				return;
			} else if (result == ChatMessageModifier::Result::Suspended) {
				currentSendStep |= ChatMessagePrivate::Step::Encryption;
				return;
			}
615
			currentSendStep |= ChatMessagePrivate::Step::Encryption;
616
		}
617

618
		if ((currentSendStep &ChatMessagePrivate::Step::Cpim) == ChatMessagePrivate::Step::Cpim) {
619 620
			lInfo() << "Cpim step already done, skipping";
		} else {
621 622
			int defaultValue = !!lp_config_get_string(core->getCCore()->config, "misc", "conference_factory_uri", nullptr);
			if (lp_config_get_int(core->getCCore()->config, "sip", "use_cpim", defaultValue) == 1) {
623 624 625 626
				CpimChatMessageModifier ccmm;
				ccmm.encode(q->getSharedFromThis(), errorCode);
			}
			currentSendStep |= ChatMessagePrivate::Step::Cpim;
627
		}
628
	}
629

630 631 632 633
	// ---------------------------------------
	// End of message modification
	// ---------------------------------------

634
	if (internalContent.isEmpty())
635
		internalContent = *(contents.front());
636

637 638
	auto msgOp = dynamic_cast<SalMessageOpInterface *>(op);
	if (internalContent.getContentType().isValid()) {
639 640 641
		msgOp->send_message(internalContent.getContentType().asString().c_str(), internalContent.getBodyAsString().c_str());
	} else
		msgOp->send_message(ContentType::PlainText.asString().c_str(), internalContent.getBodyAsString().c_str());
642

643
	for (Content *content : contents) {
644
		// Restore FileContents and remove FileTransferContents
645 646
		if (content->getContentType() == ContentType::FileTransfer) {
			FileTransferContent *fileTransferContent = (FileTransferContent *)content;
647 648 649
			q->removeContent(*content);
			q->addContent(*fileTransferContent->getFileContent());
			delete fileTransferContent;
650
		}
651
	}
652

653
	q->setImdnMessageId(op->get_call_id());   /* must be known at that time */
654 655 656 657 658 659

	if (call && linphone_call_get_op(call) == op) {
		/* In this case, chat delivery status is not notified, so unrefing chat message right now */
		/* Might be better fixed by delivering status, but too costly for now */
		return;
	}
660

661
	/* If operation failed, we should not change message state */
662
	if (direction == ChatMessage::Direction::Outgoing) {
663 664 665 666 667
		setIsReadOnly(true);
		setState(ChatMessage::State::InProgress);
	}
}

668 669
// -----------------------------------------------------------------------------

670
ChatMessage::ChatMessage (const shared_ptr<ChatRoom> &chatRoom, ChatMessage::Direction direction) :
671 672 673 674 675 676
	Object(*new ChatMessagePrivate), CoreAccessor(chatRoom->getCore()) {
	L_ASSERT(chatRoom);
	L_D();

	d->chatRoom = chatRoom;
	d->chatRoomId = chatRoom->getChatRoomId();
677
	if (direction == Direction::Outgoing) {
678 679
		d->fromAddress = d->chatRoomId.getLocalAddress();
		d->toAddress = d->chatRoomId.getPeerAddress();
680
	} else {
681 682
		d->fromAddress = d->chatRoomId.getPeerAddress();
		d->toAddress = d->chatRoomId.getLocalAddress();
683 684
	}
	d->direction = direction;
685 686 687 688 689 690 691 692 693
}

ChatMessage::~ChatMessage () {
	L_D();
	for (Content *content : d->contents)
		delete content;

	if (d->salOp)
		d->salOp->release();
694
}
695 696 697

shared_ptr<ChatRoom> ChatMessage::getChatRoom () const {
	L_D();
698 699

	shared_ptr<ChatRoom> chatRoom = d->chatRoom.lock();
700
	if (!chatRoom)
701
		chatRoom = getCore()->getOrCreateBasicChatRoom(d->chatRoomId);
702 703

	return chatRoom;
704 705 706 707 708 709 710 711 712 713 714 715 716 717
}

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

time_t ChatMessage::getTime () const {
	L_D();
	return d->time;
}

bool ChatMessage::isSecured () const {
	L_D();
	return d->isSecured;
}

718
void ChatMessage::setIsSecured (bool isSecured) {
719 720 721 722 723 724 725 726 727
	L_D();
	d->isSecured = isSecured;
}

ChatMessage::Direction ChatMessage::getDirection () const {
	L_D();
	return d->direction;
}

728
ChatMessage::State ChatMessage::getState () const {
729 730 731 732
	L_D();
	return d->state;
}

733
const string &ChatMessage::getImdnMessageId () const {
734 735 736 737
	L_D();
	return d->id;
}

738
void ChatMessage::setImdnMessageId (const string &id) {
739 740 741 742
	L_D();
	d->id = id;
}

743
bool ChatMessage::isRead () const {
744
	L_D();
745

746
	LinphoneImNotifPolicy *policy = linphone_core_get_im_notif_policy(getCore()->getCCore());
747 748 749 750 751 752 753 754 755
	if (linphone_im_notif_policy_get_recv_imdn_displayed(policy) && d->state == State::Displayed)
		return true;

	if (
		linphone_im_notif_policy_get_recv_imdn_delivered(policy) &&
		(d->state == State::DeliveredToUser || d->state == State::Displayed)
	)
		return true;

756
	return d->state == State::Delivered || d->state == State::Displayed || d->state == State::DeliveredToUser;
757 758
}

759
const IdentityAddress &ChatMessage::getFromAddress () const {
760
	L_D();
761
	return d->fromAddress;
762 763
}

764
const IdentityAddress &ChatMessage::getToAddress () const {
765
	L_D();
766
	return d->toAddress;
767 768 769 770
}

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

771
const LinphoneErrorInfo *ChatMessage::getErrorInfo () const {
772
	L_D();
773
	if (!d->errorInfo) d->errorInfo = linphone_error_info_new();   // let's do it mutable
774 775 776 777 778 779 780 781 782
	linphone_error_info_from_sal_op(d->errorInfo, d->salOp);
	return d->errorInfo;
}

bool ChatMessage::isReadOnly () const {
	L_D();
	return d->isReadOnly;
}

783
const list<Content *> &ChatMessage::getContents () const {
784
	L_D();
785
	return d->contents;
786 787
}

788
void ChatMessage::addContent (Content &content) {
789 790 791
	L_D();
	if (d->isReadOnly) return;

792
	d->contents.push_back(&content);
793 794
}

795
void ChatMessage::removeContent (const Content &content) {
796 797 798
	L_D();
	if (d->isReadOnly) return;

799
	d->contents.remove(&const_cast<Content &>(content));
800 801
}

802
const Content &ChatMessage::getInternalContent () const {
Sylvain Berfini's avatar
Sylvain Berfini committed
803 804 805 806
	L_D();
	return d->internalContent;
}

807
void ChatMessage::setInternalContent (const Content &content) {
808 809 810 811
	L_D();
	d->internalContent = content;
}

812 813 814 815 816 817 818
string ChatMessage::getCustomHeaderValue (const string &headerName) const {
	L_D();
	try {
		return d->customHeaders.at(headerName);
	} catch (const exception &) {
		// Key doesn't exist.
	}
819
	return nullptr;
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
}

void ChatMessage::addCustomHeader (const string &headerName, const string &headerValue) {
	L_D();
	if (d->isReadOnly) return;

	d->customHeaders[headerName] = headerValue;
}

void ChatMessage::removeCustomHeader (const string &headerName) {
	L_D();
	if (d->isReadOnly) return;

	d->customHeaders.erase(headerName);
}

836
void ChatMessage::store () {
837 838 839 840
	L_D();

	if (d->storageId != 0) {
		/* The message has already been stored (probably because of file transfer), update it */
841 842
		// TODO: history.
		// linphone_chat_message_store_update(L_GET_C_BACK_PTR(this));
843 844
	} else {
		/* Store the new message */
845 846
		// TODO: history.
		// linphone_chat_message_store(L_GET_C_BACK_PTR(this));
847 848 849
	}
}

850
void ChatMessage::updateState (State state) {
851 852 853
	L_D();

	d->setState(state);
854 855
	// TODO: history.
	// linphone_chat_message_store_state(L_GET_C_BACK_PTR(this));
856

857 858 859 860 861
	if (state == State::Delivered || state == State::NotDelivered) {
		shared_ptr<ChatRoom> chatRoom = getChatRoom();
		if (chatRoom)
			chatRoom->getPrivate()->moveTransientMessageToWeakMessages(getSharedFromThis());
	}
862 863
}

864
void ChatMessage::send () {
865 866
	L_D();

867
	// Do not allow sending a message that is already being sent or that has been correctly delivered/displayed
868 869
	if ((d->state == State::InProgress) || (d->state == State::Delivered) || (d->state == State::FileTransferDone) ||
			(d->state == State::DeliveredToUser) || (d->state == State::Displayed)) {
870
		lWarning() << "Cannot send chat message in state " << linphone_chat_message_state_to_string((LinphoneChatMessageState)d->state);
871 872 873
		return;
	}

874 875 876
	shared_ptr<ChatRoom> chatRoom = getChatRoom();
	if (chatRoom)
		chatRoom->getPrivate()->sendMessage(getSharedFromThis());
877 878
}

879
void ChatMessage::sendDeliveryNotification (LinphoneReason reason) {
880
	L_D();
881

882
	LinphoneImNotifPolicy *policy = linphone_core_get_im_notif_policy(getCore()->getCCore());
883
	if (linphone_im_notif_policy_get_send_imdn_delivered(policy))
884
		d->sendImdn(Imdn::Type::Delivery, reason);
885 886
}

887
void ChatMessage::sendDisplayNotification () {
888
	L_D();
889

890
	LinphoneImNotifPolicy *policy = linphone_core_get_im_notif_policy(getCore()->getCCore());
891
	if (linphone_im_notif_policy_get_send_imdn_displayed(policy))
892
		d->sendImdn(Imdn::Type::Display, LinphoneReasonNone);
893
}
894

895
bool ChatMessage::downloadFile(FileTransferContent &fileTransferContent) {
896
	L_D();
897
	return d->fileTransferChatMessageModifier.downloadFile(getSharedFromThis(), &fileTransferContent);
898 899
}

900
void ChatMessage::cancelFileTransfer () {
901
	L_D();
902
	if (d->fileTransferChatMessageModifier.isFileTransferInProgressAndValid()) {
903 904
		if (d->state == State::InProgress) {
			d->setState(State::NotDelivered);
905
		}
906
		d->fileTransferChatMessageModifier.cancelFileTransfer();
907
	} else {
908
		lInfo() << "No existing file transfer - nothing to cancel";
909
	}
910 911
}

912
int ChatMessage::putCharacter (uint32_t character) {
913
	L_D();
914 915 916 917 918 919 920 921 922 923 924

	shared_ptr<Core> core = getCore();
	if (linphone_core_realtime_text_enabled(core->getCCore())) {
		static const uint32_t new_line = 0x2028;
		static const uint32_t crlf = 0x0D0A;
		static const uint32_t lf = 0x0A;

		shared_ptr<ChatRoom> chatRoom = getChatRoom();
		if (!chatRoom)
			return -1;

925
		shared_ptr<LinphonePrivate::RealTimeTextChatRoom> rttcr =
926
			static_pointer_cast<LinphonePrivate::RealTimeTextChatRoom>(chatRoom);
927 928
		LinphoneCall *call = rttcr->getCall();

929
		if (!call || !linphone_call_get_stream(call, LinphoneStreamTypeText))
930 931 932
			return -1;

		if (character == new_line || character == crlf || character == lf) {
933
			if (lp_config_get_int(core->getCCore()->config, "misc", "store_rtt_messages", 1) == 1) {
934
				// TODO: History.
935
				lDebug() << "New line sent, forge a message with content " << d->rttMessage.c_str();
936
				d->setTime(ms_time(0));
937
				d->state = State::Displayed;
938 939 940 941
				// d->direction = Direction::Outgoing;
				// setFromAddress(Address(
				// 	linphone_address_as_string(linphone_address_new(linphone_core_get_identity(core->getCCore())))
				// ));
942
				// linphone_chat_message_store(L_GET_C_BACK_PTR(this));
943
				d->rttMessage = "";
944 945 946
			}
		} else {
			char *value = LinphonePrivate::Utils::utf8ToChar(character);
947
			d->rttMessage = d->rttMessage + string(value);
948 949
			lDebug() << "Sent RTT character: " << value << "(" << (unsigned long)character <<
				"), pending text is " << d->rttMessage.c_str();
950 951 952
			delete value;
		}

953 954 955
		text_stream_putchar32(reinterpret_cast<TextStream *>(
			linphone_call_get_stream(call, LinphoneStreamTypeText)), character
		);
956
		return 0;
957
	}
958 959 960
	return -1;
}

Ronan's avatar
Ronan committed
961
LINPHONE_END_NAMESPACE