1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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
97
98
99
100
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
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
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
|
/*
* Copyright (C) 2012-2016 Canonical, Ltd.
*
* Authors:
* Gustavo Pichorim Boiko <gustavo.boiko@canonical.com>
* Tiago Salem Herrmann <tiago.herrmann@canonical.com>
*
* This file is part of telephony-service.
*
* telephony-service 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; version 3.
*
* telephony-service 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
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "chatmanager.h"
#include "chatentry.h"
#include "telepathyhelper.h"
#include "phoneutils.h"
#include "config.h"
#include "dbustypes.h"
#include "accountentry.h"
#include <TelepathyQt/Contact>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/PendingContacts>
#include <QDBusArgument>
QDBusArgument &operator<<(QDBusArgument &argument, const AttachmentStruct &attachment)
{
argument.beginStructure();
argument << attachment.id << attachment.contentType << attachment.filePath;
argument.endStructure();
return argument;
}
const QDBusArgument &operator>>(const QDBusArgument &argument, AttachmentStruct &attachment)
{
argument.beginStructure();
argument >> attachment.id >> attachment.contentType >> attachment.filePath;
argument.endStructure();
return argument;
}
QVariantMap convertPropertiesForDBus(const QVariantMap &properties)
{
QVariantMap propMap = properties;
// participants coming from qml are variants
if (properties.contains("participantIds")) {
QStringList participants = properties["participantIds"].toStringList();
if (!participants.isEmpty()) {
propMap["participantIds"] = participants;
}
}
return propMap;
}
ChatManager::ChatManager(QObject *parent)
: QObject(parent)
{
qDBusRegisterMetaType<AttachmentList>();
qDBusRegisterMetaType<AttachmentStruct>();
// wait one second for other acknowledge calls before acknowledging messages to avoid many round trips
mMessagesAckTimer.setInterval(25);
mMessagesAckTimer.setSingleShot(true);
connect(TelepathyHelper::instance(), SIGNAL(channelObserverUnregistered()), SLOT(onChannelObserverUnregistered()));
connect(&mMessagesAckTimer, SIGNAL(timeout()), SLOT(onAckTimerTriggered()));
connect(TelepathyHelper::instance(), SIGNAL(setupReady()), SLOT(onConnectedChanged()));
}
void ChatManager::onChannelObserverUnregistered()
{
mTextChannels.clear();
}
void ChatManager::onConnectedChanged()
{
if (TelepathyHelper::instance()->ready()) {
onAckTimerTriggered();
}
}
ChatManager *ChatManager::instance()
{
static ChatManager *manager = new ChatManager();
return manager;
}
QString ChatManager::startChat(const QString &accountId, const QVariantMap &properties)
{
QVariantMap propMap = convertPropertiesForDBus(properties);
QDBusInterface *phoneAppHandler = TelepathyHelper::instance()->handlerInterface();
QDBusReply<QString> reply = phoneAppHandler->call("StartChat", accountId, propMap);
return reply.value();
}
QString ChatManager::sendMessage(const QString &accountId, const QString &message, const QVariant &attachments, const QVariantMap &properties)
{
AccountEntry *account = TelepathyHelper::instance()->accountForId(accountId);
if (!account) {
return QString();
}
QVariantMap propMap = convertPropertiesForDBus(properties);
// check if files should be copied to a temporary location before passing them to handler
bool tmpFiles = (properties.contains("x-canonical-tmp-files") && properties["x-canonical-tmp-files"].toBool());
AttachmentList newAttachments;
Q_FOREACH (const QVariant &attachment, attachments.toList()) {
AttachmentStruct newAttachment;
QVariantList list = attachment.toList();
newAttachment.id = list.at(0).toString();
newAttachment.contentType = list.at(1).toString();
if (tmpFiles) {
// we can't give the original path to handler, as it might be removed
// from history database by the time it tries to read the file,
// so we duplicate the file and the handler will remove it
QTemporaryFile tmpFile("/tmp/XXXXX");
tmpFile.setAutoRemove(false);
if (!tmpFile.open()) {
qWarning() << "Unable to create a temporary file";
return QString();
}
QFile originalFile(list.at(2).toString());
if (!originalFile.open(QIODevice::ReadOnly)) {
qWarning() << "Attachment file not found";
return QString();
}
if (tmpFile.write(originalFile.readAll()) == -1) {
qWarning() << "Failed to write attachment to a temporary file";
return QString();
}
newAttachment.filePath = tmpFile.fileName();
tmpFile.close();
originalFile.close();
} else {
newAttachment.filePath = list.at(2).toString();
}
newAttachments << newAttachment;
}
QDBusInterface *phoneAppHandler = TelepathyHelper::instance()->handlerInterface();
QDBusReply<QString> reply = phoneAppHandler->call("SendMessage", account->accountId(), message, QVariant::fromValue(newAttachments), propMap);
if (reply.isValid()) {
return reply.value();
}
return QString();
}
QList<Tp::TextChannelPtr> ChatManager::channelForProperties(const QVariantMap &properties)
{
QList<Tp::TextChannelPtr> channels;
Q_FOREACH (Tp::TextChannelPtr channel, mTextChannels) {
if (channelMatchProperties(channel, properties)) {
channels << channel;
}
}
return channels;
}
Tp::TextChannelPtr ChatManager::channelForObjectPath(const QString &objectPath)
{
Q_FOREACH(Tp::TextChannelPtr channel, mTextChannels) {
if (channel->objectPath() == objectPath) {
return channel;
}
}
return Tp::TextChannelPtr();
}
bool ChatManager::channelMatchProperties(const Tp::TextChannelPtr &channel, const QVariantMap &properties)
{
QVariantMap propMap = properties;
ChatEntry::ChatType chatType = ChatEntry::ChatTypeNone;
QStringList participants;
// participants coming from qml are variants
if (properties.contains("participantIds")) {
participants = properties["participantIds"].toStringList();
if (!participants.isEmpty()) {
propMap["participantIds"] = participants;
}
}
if (participants.isEmpty() && propMap.contains("participants")) {
// try to generate list of participants from "participants"
Q_FOREACH(const QVariant &participantMap, propMap["participants"].toList()) {
if (participantMap.toMap().contains("identifier")) {
participants << participantMap.toMap()["identifier"].toString();
}
}
if (!participants.isEmpty()) {
propMap["participantIds"] = participants;
}
}
if (properties.contains("chatType")) {
chatType = (ChatEntry::ChatType)properties["chatType"].toInt();
} else {
if (participants.length() == 1) {
chatType = ChatEntry::ChatTypeContact;
}
}
QString accountId;
if (propMap.contains("accountId")) {
accountId = propMap["accountId"].toString();
}
if (participants.count() == 0 && chatType == ChatEntry::ChatTypeContact) {
return false;
}
AccountEntry *account = TelepathyHelper::instance()->accountForConnection(channel->connection());
if (!account) {
return false;
}
// only channels of the correct type should be returned
if ((ChatEntry::ChatType)channel->targetHandleType() != chatType) {
return false;
}
if (chatType == ChatEntry::ChatTypeRoom) {
QString chatId = propMap["threadId"].toString();
if (!chatId.isEmpty() && channel->targetId() == chatId) {
// if we are filtering by one specific accountId, make sure it matches
if (!accountId.isEmpty() && accountId != account->accountId()) {
return false;
}
return true;
}
return false;
}
Tp::Contacts contacts = channel->groupContacts(false);
if (participants.count() != contacts.count()) {
return false;
}
int participantCount = 0;
// iterate over participants
Q_FOREACH (const Tp::ContactPtr &contact, contacts) {
// try the easiest first
if (participants.contains(contact->id())) {
participantCount++;
continue;
}
// if no exact match, try to use the account's compare function
Q_FOREACH(const QString &participant, participants) {
if (account->compareIds(participant, contact->id())) {
participantCount++;
break;
}
}
}
return (participantCount == participants.count());
}
void ChatManager::onTextChannelAvailable(Tp::TextChannelPtr channel)
{
mTextChannels << channel;
connect(channel.data(),
SIGNAL(invalidated(Tp::DBusProxy*,const QString&, const QString&)),
SLOT(onChannelInvalidated()));
Q_EMIT textChannelAvailable(channel);
}
void ChatManager::onChannelInvalidated()
{
Tp::TextChannelPtr channel(qobject_cast<Tp::TextChannel*>(sender()));
mTextChannels.removeAll(channel);
Q_EMIT textChannelInvalidated(channel);
}
void ChatManager::acknowledgeMessage(const QVariantMap &properties)
{
mMessagesToAck << QVariant::fromValue(convertPropertiesForDBus(properties));
mMessagesAckTimer.start();
}
void ChatManager::acknowledgeAllMessages(const QVariantMap &properties)
{
QDBusInterface *phoneAppHandler = TelepathyHelper::instance()->handlerInterface();
phoneAppHandler->asyncCall("AcknowledgeAllMessages", convertPropertiesForDBus(properties));
}
void ChatManager::onAckTimerTriggered()
{
// ack all pending messages
QDBusInterface *phoneAppHandler = TelepathyHelper::instance()->handlerInterface();
phoneAppHandler->asyncCall("AcknowledgeMessages", mMessagesToAck);
mMessagesToAck.clear();
}
|