diff --git a/interfaces/conversationmessage.cpp b/interfaces/conversationmessage.cpp index 6319c656..1a3816ae 100644 --- a/interfaces/conversationmessage.cpp +++ b/interfaces/conversationmessage.cpp @@ -1,113 +1,125 @@ /** * Copyright 2018 Simon Redman * * 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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * 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 * along with this program. If not, see . */ #include "conversationmessage.h" #include #include ConversationMessage::ConversationMessage(const QVariantMap& args, QObject* parent) : QObject(parent), m_body(args["body"].toString()), m_address(args["address"].toString()), m_date(args["date"].toLongLong()), m_type(args["type"].toInt()), m_read(args["read"].toInt()), m_threadID(args["thread_id"].toInt()) { } ConversationMessage::ConversationMessage (const QString& body, const QString& address, const qint64& date, const qint32& type, const qint32& read, const qint32& threadID, QObject* parent) : QObject(parent) , m_body(body) , m_address(address) , m_date(date) , m_type(type) , m_read(read) , m_threadID(threadID) { } ConversationMessage::ConversationMessage(const ConversationMessage& other, QObject* parent) : QObject(parent) , m_body(other.m_body) , m_address(other.m_address) , m_date(other.m_date) , m_type(other.m_type) , m_read(other.m_read) , m_threadID(other.m_threadID) { } ConversationMessage::~ConversationMessage() { } ConversationMessage& ConversationMessage::operator=(const ConversationMessage& other) { this->m_body = other.m_body; this->m_address = other.m_address; this->m_date = other.m_date; this->m_type = other.m_type; this->m_read = other.m_read; this->m_threadID = other.m_threadID; return *this; } +QVariantMap ConversationMessage::toVariant() const +{ + return { + {"body", m_body}, + {"address", m_address}, + {"date", m_date}, + {"type", m_type}, + {"read", m_read}, + {"thread_id", m_threadID} + }; +} + QDBusArgument &operator<<(QDBusArgument &argument, const ConversationMessage &message) { argument.beginStructure(); argument << message.body() << message.address() << message.date() << message.type() << message.read() << message.threadID(); argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, ConversationMessage &message) { QString body; QString address; qint64 date; qint32 type; qint32 read; qint32 threadID; argument.beginStructure(); argument >> body; argument >> address; argument >> date; argument >> type; argument >> read; argument >> threadID; argument.endStructure(); message = ConversationMessage(body, address, date, type, read, threadID); return argument; } void ConversationMessage::registerDbusType() { qDBusRegisterMetaType(); qRegisterMetaType(); } diff --git a/interfaces/conversationmessage.h b/interfaces/conversationmessage.h index 16758d38..28226b16 100644 --- a/interfaces/conversationmessage.h +++ b/interfaces/conversationmessage.h @@ -1,113 +1,115 @@ /** * Copyright 2018 Simon Redman * * 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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * 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 * along with this program. If not, see . */ #ifndef PLUGINS_TELEPHONY_CONVERSATIONMESSAGE_H_ #define PLUGINS_TELEPHONY_CONVERSATIONMESSAGE_H_ #include #include #include #include #include "interfaces/kdeconnectinterfaces_export.h" class KDECONNECTINTERFACES_EXPORT ConversationMessage : public QObject { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kdeconnect.device.telephony.messages") Q_PROPERTY(QString body READ body) Q_PROPERTY(QString address READ address) Q_PROPERTY(qint64 date READ date) Q_PROPERTY(qint32 type READ type) Q_PROPERTY(qint32 read READ read) Q_PROPERTY(qint32 threadID READ threadID) public: // TYPE field values from Android enum Types { MessageTypeAll = 0, MessageTypeInbox = 1, MessageTypeSent = 2, MessageTypeDraft = 3, MessageTypeOutbox = 4, MessageTypeFailed = 5, MessageTypeQueued = 6, }; Q_ENUM(Types); /** * Build a new message from a keyword argument dictionary * * @param args mapping of field names to values as might be contained in a network packet containing a message */ ConversationMessage(const QVariantMap& args = QVariantMap(), QObject* parent = Q_NULLPTR); ConversationMessage(const QString& body, const QString& address, const qint64& date, const qint32& type, const qint32& read, const qint32& threadID, QObject* parent = Q_NULLPTR); ConversationMessage(const ConversationMessage& other, QObject* parent = Q_NULLPTR); ~ConversationMessage(); ConversationMessage& operator=(const ConversationMessage& other); static void registerDbusType(); QString body() const { return m_body; } QString address() const { return m_address; } qint64 date() const { return m_date; } qint32 type() const { return m_type; } qint32 read() const { return m_read; } qint32 threadID() const { return m_threadID; } + QVariantMap toVariant() const; + protected: /** * Body of the message */ QString m_body; /** * Remote-side address of the message. Most likely a phone number, but may be an email address */ QString m_address; /** * Date stamp (Unix epoch millis) associated with the message */ qint64 m_date; /** * Type of the message. See the message.type enum */ qint32 m_type; /** * Whether we have a read report for this message */ qint32 m_read; /** * Tag which binds individual messages into a thread */ qint32 m_threadID; }; Q_DECLARE_METATYPE(ConversationMessage); #endif /* PLUGINS_TELEPHONY_CONVERSATIONMESSAGE_H_ */ diff --git a/plugins/telephony/conversationsdbusinterface.cpp b/plugins/telephony/conversationsdbusinterface.cpp index a5f9568d..781552ed 100644 --- a/plugins/telephony/conversationsdbusinterface.cpp +++ b/plugins/telephony/conversationsdbusinterface.cpp @@ -1,121 +1,114 @@ /** * Copyright 2018 Simon Redman * * 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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * 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 * along with this program. If not, see . */ #include "conversationsdbusinterface.h" #include "interfaces/dbusinterfaces.h" #include "interfaces/conversationmessage.h" #include #include #include #include "telephonyplugin.h" ConversationsDbusInterface::ConversationsDbusInterface(KdeConnectPlugin* plugin) : QDBusAbstractAdaptor(const_cast(plugin->device())) , m_device(plugin->device()) , m_plugin(plugin) , m_lastId(0) , m_telephonyInterface(m_device->id()) { ConversationMessage::registerDbusType(); } ConversationsDbusInterface::~ConversationsDbusInterface() { - qCDebug(KDECONNECT_PLUGIN_TELEPHONY) << "Destroying ConversationsDbusInterface"; - for (const auto& conversation_list : m_conversations) - { - for (const QPointer& message : conversation_list) - { - delete message.data(); - } - } } QStringList ConversationsDbusInterface::activeConversations() { return m_conversations.keys(); } -ConversationMessage ConversationsDbusInterface::getFirstFromConversation(const QString& conversationId) +void ConversationsDbusInterface::requestConversation(const QString& conversationID, int start, int end) const { - const QList> messagesList = m_conversations[conversationId]; + const auto messagesList = m_conversations[conversationID]; if (messagesList.isEmpty()) { // Since there are no messages in the conversation, we can't do anything sensible - qCWarning(KDECONNECT_PLUGIN_TELEPHONY) << "Got a conversationID for a conversation with no messages!"; - return ConversationMessage(); + qCWarning(KDECONNECT_PLUGIN_TELEPHONY) << "Got a conversationID for a conversation with no messages!" << conversationID; + return; } - return *messagesList.first().data(); + for(int i=start; idbusPath()+"/messages/"+publicId, message, QDBusConnection::ExportScriptableContents); - // Store the Message in the list corresponding to its thread - const QString& threadId = QString::number(message->threadID()); + const QString& threadId = QString::number(message.threadID()); bool newConversation = m_conversations.contains(threadId); m_conversations[threadId].append(message); // Tell the world about what just happened if (newConversation) { Q_EMIT conversationCreated(threadId); } else { Q_EMIT conversationUpdated(threadId); } } void ConversationsDbusInterface::removeMessage(const QString& internalId) { // TODO: Delete the specified message from our internal structures } void ConversationsDbusInterface::replyToConversation(const QString& conversationID, const QString& message) { - const QList> messagesList = m_conversations[conversationID]; + const auto messagesList = m_conversations[conversationID]; if (messagesList.isEmpty()) { // Since there are no messages in the conversation, we can't do anything sensible qCWarning(KDECONNECT_PLUGIN_TELEPHONY) << "Got a conversationID for a conversation with no messages!"; return; } - const QString& address = m_conversations[conversationID].front().data()->address(); + const QString& address = messagesList.front().address(); m_telephonyInterface.sendSms(address, message); } void ConversationsDbusInterface::requestAllConversationThreads() { // Prepare the list of conversations by requesting the first in every thread m_telephonyInterface.requestAllConversations(); } QString ConversationsDbusInterface::newId() { return QString::number(++m_lastId); } diff --git a/plugins/telephony/conversationsdbusinterface.h b/plugins/telephony/conversationsdbusinterface.h index 2bf2f421..8949e9a1 100644 --- a/plugins/telephony/conversationsdbusinterface.h +++ b/plugins/telephony/conversationsdbusinterface.h @@ -1,94 +1,91 @@ /** * Copyright 2013 Albert Vaca * * 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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * 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 * along with this program. If not, see . */ #ifndef CONVERSATIONSDBUSINTERFACE_H #define CONVERSATIONSDBUSINTERFACE_H #include #include #include #include #include #include #include #include "interfaces/conversationmessage.h" #include "interfaces/dbusinterfaces.h" class KdeConnectPlugin; class Device; class ConversationsDbusInterface : public QDBusAbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.kde.kdeconnect.device.conversations") public: explicit ConversationsDbusInterface(KdeConnectPlugin* plugin); ~ConversationsDbusInterface() override; - void addMessage(ConversationMessage* message); + void addMessage(const ConversationMessage &message); void removeMessage(const QString& internalId); public Q_SLOTS: /** * Return a list of the threadID for all valid conversations */ QStringList activeConversations(); - /** - * Get the first message in the requested conversation - */ - ConversationMessage getFirstFromConversation(const QString& conversationId); + void requestConversation(const QString &conversationID, int start, int end) const; /** * Send a new message to this conversation */ void replyToConversation(const QString& conversationID, const QString& message); /** * Send the request to the Telephony plugin to update the list of conversation threads */ void requestAllConversationThreads(); Q_SIGNALS: Q_SCRIPTABLE void conversationCreated(const QString& threadID); Q_SCRIPTABLE void conversationRemoved(const QString& threadID); Q_SCRIPTABLE void conversationUpdated(const QString& threadID); + Q_SCRIPTABLE void conversationMessageReceived(const QVariantMap & msg, int pos) const; private /*methods*/: QString newId(); //Generates successive identifitiers to use as public ids - void notificationReady(); private /*attributes*/: const Device* m_device; KdeConnectPlugin* m_plugin; /** * Mapping of threadID to the list of messages which make up that thread */ - QHash>> m_conversations; + QHash> m_conversations; int m_lastId; TelephonyDbusInterface m_telephonyInterface; }; #endif // CONVERSATIONSDBUSINTERFACE_H diff --git a/plugins/telephony/telephonyplugin.cpp b/plugins/telephony/telephonyplugin.cpp index 396c49c7..2c09fbf1 100644 --- a/plugins/telephony/telephonyplugin.cpp +++ b/plugins/telephony/telephonyplugin.cpp @@ -1,232 +1,232 @@ /** * Copyright 2013 Albert Vaca * Copyright 2018 Simon Redman * * 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) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * 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 * along with this program. If not, see . */ #include "telephonyplugin.h" #include "sendreplydialog.h" #include "conversationsdbusinterface.h" #include "interfaces/conversationmessage.h" #include #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON( KdeConnectPluginFactory, "kdeconnect_telephony.json", registerPlugin< TelephonyPlugin >(); ) Q_LOGGING_CATEGORY(KDECONNECT_PLUGIN_TELEPHONY, "kdeconnect.plugin.telephony") TelephonyPlugin::TelephonyPlugin(QObject* parent, const QVariantList& args) : KdeConnectPlugin(parent, args) , m_telepathyInterface(QStringLiteral("org.freedesktop.Telepathy.ConnectionManager.kdeconnect"), QStringLiteral("/kdeconnect")) , m_conversationInterface(new ConversationsDbusInterface(this)) { } TelephonyPlugin::~TelephonyPlugin() { // FIXME: Same problem as discussed in the BatteryPlugin destructor and for the same reason: // QtDbus does not allow us to delete m_conversationInterface. If we do so, we get a crash in the // next DBus access to the parent //m_conversationInterface->deleteLater(); } KNotification* TelephonyPlugin::createNotification(const NetworkPacket& np) { const QString event = np.get(QStringLiteral("event")); const QString phoneNumber = np.get(QStringLiteral("phoneNumber"), i18n("unknown number")); const QString contactName = np.get(QStringLiteral("contactName"), phoneNumber); const QByteArray phoneThumbnail = QByteArray::fromBase64(np.get(QStringLiteral("phoneThumbnail"), "")); const QString messageBody = np.get(QStringLiteral("messageBody"),{}); // In case telepathy can handle the message, don't do anything else if (event == QLatin1String("sms") && m_telepathyInterface.isValid()) { // Telepathy has already been tried (in receivePacket) // There is a chance that it somehow failed, but since nobody uses Telepathy anyway... // TODO: When upgrading telepathy, handle failure case (in case m_telepathyInterface.call returns false) return nullptr; } QString content, type, icon; KNotification::NotificationFlags flags = KNotification::CloseOnTimeout; const QString title = device()->name(); if (event == QLatin1String("ringing")) { type = QStringLiteral("callReceived"); icon = QStringLiteral("call-start"); content = i18n("Incoming call from %1", contactName); } else if (event == QLatin1String("missedCall")) { type = QStringLiteral("missedCall"); icon = QStringLiteral("call-start"); content = i18n("Missed call from %1", contactName); flags |= KNotification::Persistent; //Note that in Unity this generates a message box! } else if (event == QLatin1String("sms")) { type = QStringLiteral("smsReceived"); icon = QStringLiteral("mail-receive"); QString messageBody = np.get(QStringLiteral("messageBody"), QLatin1String("")); content = i18n("SMS from %1
%2", contactName, messageBody); flags |= KNotification::Persistent; //Note that in Unity this generates a message box! } else if (event == QLatin1String("talking")) { return nullptr; } else { #ifndef NDEBUG return nullptr; #else type = QStringLiteral("callReceived"); icon = QStringLiteral("phone"); content = i18n("Unknown telephony event: %1", event); #endif } qCDebug(KDECONNECT_PLUGIN_TELEPHONY) << "Creating notification with type:" << type; KNotification* notification = new KNotification(type, flags, this); if (!phoneThumbnail.isEmpty()) { QPixmap photo; photo.loadFromData(phoneThumbnail, "JPEG"); notification->setPixmap(photo); } else { notification->setIconName(icon); } notification->setComponentName(QStringLiteral("kdeconnect")); notification->setTitle(title); notification->setText(content); if (event == QLatin1String("ringing")) { notification->setActions( QStringList(i18n("Mute Call")) ); connect(notification, &KNotification::action1Activated, this, &TelephonyPlugin::sendMutePacket); } else if (event == QLatin1String("sms")) { notification->setActions( QStringList(i18n("Reply")) ); notification->setProperty("phoneNumber", phoneNumber); notification->setProperty("contactName", contactName); notification->setProperty("originalMessage", messageBody); connect(notification, &KNotification::action1Activated, this, &TelephonyPlugin::showSendSmsDialog); } return notification; } bool TelephonyPlugin::receivePacket(const NetworkPacket& np) { if (np.get(QStringLiteral("isCancel"))) { //TODO: Clear the old notification return true; } const QString& event = np.get(QStringLiteral("event"), QStringLiteral("unknown")); // Handle old-style packets if (np.type() == PACKET_TYPE_TELEPHONY) { if (event == QLatin1String("sms")) { // New-style packets should be a PACKET_TYPE_TELEPHONY_MESSAGE (15 May 2018) qCDebug(KDECONNECT_PLUGIN_TELEPHONY) << "Handled an old-style Telephony sms packet. You should update your Android app to get the latest features!"; ConversationMessage message(np.body()); forwardToTelepathy(message); } KNotification* n = createNotification(np); if (n != nullptr) n->sendEvent(); return true; } if (np.type() == PACKET_TYPE_TELEPHONY_MESSAGE) { return handleBatchMessages(np); } return true; } void TelephonyPlugin::sendMutePacket() { NetworkPacket packet(PACKET_TYPE_TELEPHONY_REQUEST, {{"action", "mute"}}); sendPacket(packet); } void TelephonyPlugin::sendSms(const QString& phoneNumber, const QString& messageBody) { NetworkPacket np(PACKET_TYPE_SMS_REQUEST, { {"sendSms", true}, {"phoneNumber", phoneNumber}, {"messageBody", messageBody} }); qDebug() << "sending sms!"; sendPacket(np); } void TelephonyPlugin::showSendSmsDialog() { QString phoneNumber = sender()->property("phoneNumber").toString(); QString contactName = sender()->property("contactName").toString(); QString originalMessage = sender()->property("originalMessage").toString(); SendReplyDialog* dialog = new SendReplyDialog(originalMessage, phoneNumber, contactName); connect(dialog, &SendReplyDialog::sendReply, this, &TelephonyPlugin::sendSms); dialog->show(); dialog->raise(); } void TelephonyPlugin::requestAllConversations() { NetworkPacket np(PACKET_TYPE_TELEPHONY_REQUEST_CONVERSATIONS); sendPacket(np); } void TelephonyPlugin::forwardToTelepathy(const ConversationMessage& message) { // In case telepathy can handle the message, don't do anything else if (m_telepathyInterface.isValid()) { qCDebug(KDECONNECT_PLUGIN_TELEPHONY) << "Passing a text message to the telepathy interface"; connect(&m_telepathyInterface, SIGNAL(messageReceived(QString,QString)), SLOT(sendSms(QString,QString)), Qt::UniqueConnection); const QString messageBody = message.body(); const QString contactName; // TODO: When telepathy support is improved, look up the contact with KPeople const QString phoneNumber = message.address(); m_telepathyInterface.call(QDBus::NoBlock, QStringLiteral("sendMessage"), phoneNumber, contactName, messageBody); } } bool TelephonyPlugin::handleBatchMessages(const NetworkPacket& np) { const auto messages = np.get("messages"); for (const QVariant& body : messages) { - ConversationMessage* message = new ConversationMessage(body.toMap()); - forwardToTelepathy(*message); + ConversationMessage message(body.toMap()); + forwardToTelepathy(message); m_conversationInterface->addMessage(message); } return true; } QString TelephonyPlugin::dbusPath() const { return "/modules/kdeconnect/devices/" + device()->id() + "/telephony"; } #include "telephonyplugin.moc" diff --git a/smsapp/conversationlistmodel.cpp b/smsapp/conversationlistmodel.cpp index 6fd08a2e..13577223 100644 --- a/smsapp/conversationlistmodel.cpp +++ b/smsapp/conversationlistmodel.cpp @@ -1,160 +1,159 @@ /* * This file is part of KDE Telepathy Chat * * Copyright (C) 2018 Aleix Pol Gonzalez * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "conversationlistmodel.h" #include #include "interfaces/conversationmessage.h" Q_LOGGING_CATEGORY(KDECONNECT_SMS_CONVERSATIONS_LIST_MODEL, "kdeconnect.sms.conversations_list") ConversationListModel::ConversationListModel(QObject* parent) : QStandardItemModel(parent) , m_conversationsInterface(nullptr) { qCCritical(KDECONNECT_SMS_CONVERSATIONS_LIST_MODEL) << "Constructing" << this; auto roles = roleNames(); roles.insert(FromMeRole, "fromMe"); roles.insert(AddressRole, "address"); roles.insert(PersonUriRole, "personUri"); roles.insert(ConversationIdRole, "conversationId"); roles.insert(DateRole, "date"); setItemRoleNames(roles); ConversationMessage::registerDbusType(); } ConversationListModel::~ConversationListModel() { } void ConversationListModel::setDeviceId(const QString& deviceId) { qCCritical(KDECONNECT_SMS_CONVERSATIONS_LIST_MODEL) << "setDeviceId" << deviceId << "of" << this; if (deviceId == m_deviceId) return; if (m_conversationsInterface) { disconnect(m_conversationsInterface, SIGNAL(conversationCreated(QString)), this, SLOT(handleCreatedConversation(QString))); delete m_conversationsInterface; } m_deviceId = deviceId; m_conversationsInterface = new DeviceConversationsDbusInterface(deviceId, this); connect(m_conversationsInterface, SIGNAL(conversationCreated(QString)), this, SLOT(handleCreatedConversation(QString))); + connect(m_conversationsInterface, SIGNAL(conversationMessageReceived(QVariantMap, int)), this, SLOT(createRowFromMessage(QVariantMap, int))); prepareConversationsList(); m_conversationsInterface->requestAllConversationThreads(); } void ConversationListModel::prepareConversationsList() { - clear(); QDBusPendingReply validThreadIDsReply = m_conversationsInterface->activeConversations(); - validThreadIDsReply.waitForFinished(); - - for (const QString& conversationId : validThreadIDsReply.value()) - { - handleCreatedConversation(conversationId); - } + setWhenAvailable(validThreadIDsReply, [this](const QStringList& convs) { + clear(); + for (const QString& conversationId : convs) { + handleCreatedConversation(conversationId); + } + }, this); } void ConversationListModel::handleCreatedConversation(const QString& conversationId) { - QVariantList args; - args.append(conversationId); - - m_conversationsInterface->callWithCallback("getFirstFromConversation", args, - this, SLOT(createRowFromMessage(ConversationMessage)), SLOT(printDBusError(QDBusError))); + m_conversationsInterface->requestConversation(conversationId, 0, 1); } void ConversationListModel::printDBusError(const QDBusError& error) { qCWarning(KDECONNECT_SMS_CONVERSATIONS_LIST_MODEL) << error; } -void ConversationListModel::createRowFromMessage(const ConversationMessage& message) +void ConversationListModel::createRowFromMessage(const QVariantMap& msg, int row) { + if (row != 0) + return; + + const ConversationMessage message(msg); if (message.type() == -1) { // The Android side currently hacks in -1 if something weird comes up // TODO: Remove this hack when MMS support is implemented return; } QStandardItem* item = new QStandardItem(); - KPeople::PersonData* personData = lookupPersonByAddress(message.address()); + QScopedPointer personData(lookupPersonByAddress(message.address())); if (personData) { item->setText(personData->name()); item->setIcon(QIcon(personData->photo())); item->setData(personData->personUri(), PersonUriRole); } else { item->setData(QString(), PersonUriRole); item->setText(message.address()); } item->setData(message.address(), AddressRole); - + item->setData(message.body(), Qt::ToolTipRole); item->setData(message.threadID(), ConversationIdRole); item->setData(message.type() == ConversationMessage::MessageTypeSent, FromMeRole); item->setData(message.date(), DateRole); appendRow(item); - delete personData; } KPeople::PersonData* ConversationListModel::lookupPersonByAddress(const QString& address) { int rowIndex = 0; for (rowIndex = 0; rowIndex < m_people.rowCount(); rowIndex++) { const QString& uri = m_people.get(rowIndex, KPeople::PersonsModel::PersonUriRole).toString(); KPeople::PersonData* person = new KPeople::PersonData(uri); const QString& email = person->email(); const QString& phoneNumber = canonicalizePhoneNumber(person->contactCustomProperty("phoneNumber").toString()); if (address == email || canonicalizePhoneNumber(address) == phoneNumber) { qCDebug(KDECONNECT_SMS_CONVERSATIONS_LIST_MODEL) << "Matched" << address << "to" << person->name(); return person; } delete person; } return nullptr; } QString ConversationListModel::canonicalizePhoneNumber(const QString& phoneNumber) { QString toReturn(phoneNumber); toReturn = toReturn.remove(' '); toReturn = toReturn.remove('-'); toReturn = toReturn.remove('('); toReturn = toReturn.remove(')'); toReturn = toReturn.remove('+'); return toReturn; } diff --git a/smsapp/conversationlistmodel.h b/smsapp/conversationlistmodel.h index b1c5031a..747df11b 100644 --- a/smsapp/conversationlistmodel.h +++ b/smsapp/conversationlistmodel.h @@ -1,83 +1,83 @@ /* * This file is part of KDE Telepathy Chat * * Copyright (C) 2018 Aleix Pol Gonzalez * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONVERSATIONLISTMODEL_H #define CONVERSATIONLISTMODEL_H #include #include #include #include #include "interfaces/conversationmessage.h" #include "interfaces/dbusinterfaces.h" #include "interfaces/kdeconnectinterfaces_export.h" Q_DECLARE_LOGGING_CATEGORY(KDECONNECT_SMS_CONVERSATIONS_LIST_MODEL) class KDECONNECTINTERFACES_EXPORT ConversationListModel : public QStandardItemModel { Q_OBJECT Q_PROPERTY(QString deviceId READ deviceId WRITE setDeviceId) public: ConversationListModel(QObject* parent = nullptr); ~ConversationListModel(); enum Roles { FromMeRole = Qt::UserRole, PersonUriRole, AddressRole, ConversationIdRole, DateRole, }; QString deviceId() const { return m_deviceId; } void setDeviceId(const QString &/*deviceId*/); public Q_SLOTS: void handleCreatedConversation(const QString& conversationId); - void createRowFromMessage(const ConversationMessage& message); + void createRowFromMessage(const QVariantMap& message, int row); void printDBusError(const QDBusError& error); private: /** * Get all conversations currently known by the conversationsInterface, if any */ void prepareConversationsList(); /** * Get the data for a particular person given their contact address */ KPeople::PersonData* lookupPersonByAddress(const QString& address); /** * Simplify a phone number to a known form */ QString canonicalizePhoneNumber(const QString& phoneNumber); DeviceConversationsDbusInterface* m_conversationsInterface; QString m_deviceId; KPeople::PersonsModel m_people; }; #endif // CONVERSATIONLISTMODEL_H diff --git a/smsapp/conversationmodel.cpp b/smsapp/conversationmodel.cpp index 8e31ea11..216260df 100644 --- a/smsapp/conversationmodel.cpp +++ b/smsapp/conversationmodel.cpp @@ -1,71 +1,84 @@ /* * This file is part of KDE Telepathy Chat * * Copyright (C) 2018 Aleix Pol Gonzalez * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "conversationmodel.h" #include +#include "conversationmessage.h" Q_LOGGING_CATEGORY(KDECONNECT_SMS_CONVERSATION_MODEL, "kdeconnect.sms.conversation") ConversationModel::ConversationModel(QObject* parent) : QStandardItemModel(parent) , m_conversationsInterface(nullptr) { auto roles = roleNames(); roles.insert(FromMeRole, "fromMe"); setItemRoleNames(roles); } ConversationModel::~ConversationModel() { - if (m_conversationsInterface) delete m_conversationsInterface; } QString ConversationModel::threadId() const { qCCritical(KDECONNECT_SMS_CONVERSATION_MODEL) << "Hi"; return {}; } void ConversationModel::setThreadId(const QString &threadId) { - qCCritical(KDECONNECT_SMS_CONVERSATION_MODEL) << "Setting threadId of" << this << "to" << threadId; + if (m_threadId == threadId) + return; + m_threadId = threadId; clear(); - appendRow(new QStandardItem(threadId + QStringLiteral(" - A"))); - appendRow(new QStandardItem(threadId + QStringLiteral(" - A1"))); - appendRow(new QStandardItem(threadId + QStringLiteral(" - A2"))); - appendRow(new QStandardItem(threadId + QStringLiteral(" - A3"))); + if (!threadId.isEmpty()) { + m_conversationsInterface->requestConversation(threadId, 0, 10); + } } void ConversationModel::setDeviceId(const QString& deviceId) { + if (deviceId == m_deviceId) + return; + qCCritical(KDECONNECT_SMS_CONVERSATION_MODEL) << "setDeviceId" << "of" << this; if (m_conversationsInterface) delete m_conversationsInterface; m_deviceId = deviceId; - m_conversationsInterface = new DeviceConversationsDbusInterface(deviceId); + m_conversationsInterface = new DeviceConversationsDbusInterface(deviceId, this); + connect(m_conversationsInterface, SIGNAL(conversationMessageReceived(QVariantMap, int)), this, SLOT(createRowFromMessage(QVariantMap, int))); } void ConversationModel::sendReplyToConversation(const QString& message) { qCCritical(KDECONNECT_SMS_CONVERSATION_MODEL) << "Should have sent " << message; m_conversationsInterface->replyToConversation(m_threadId, message); } + +void ConversationModel::createRowFromMessage(const QVariantMap& msg, int pos) +{ + const ConversationMessage message(msg); + auto item = new QStandardItem; + item->setText(message.body()); + insertRow(pos, item); +} diff --git a/smsapp/conversationmodel.h b/smsapp/conversationmodel.h index 3d1eff28..7a8ea051 100644 --- a/smsapp/conversationmodel.h +++ b/smsapp/conversationmodel.h @@ -1,60 +1,63 @@ /* * This file is part of KDE Telepathy Chat * * Copyright (C) 2018 Aleix Pol Gonzalez * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef CONVERSATIONMODEL_H #define CONVERSATIONMODEL_H #include #include #include "interfaces/dbusinterfaces.h" #include "interfaces/kdeconnectinterfaces_export.h" Q_DECLARE_LOGGING_CATEGORY(KDECONNECT_SMS_CONVERSATION_MODEL) class KDECONNECTINTERFACES_EXPORT ConversationModel : public QStandardItemModel { Q_OBJECT Q_PROPERTY(QString threadId READ threadId WRITE setThreadId) Q_PROPERTY(QString deviceId READ deviceId WRITE setDeviceId) public: ConversationModel(QObject* parent = nullptr); ~ConversationModel(); enum Roles { FromMeRole = Qt::UserRole }; QString threadId() const; void setThreadId(const QString &threadId); QString deviceId() const { return m_deviceId; } void setDeviceId(const QString &/*deviceId*/); Q_INVOKABLE void sendReplyToConversation(const QString& message); +private Q_SLOTS: + void createRowFromMessage(const QVariantMap &msg, int pos); + private: DeviceConversationsDbusInterface* m_conversationsInterface; QString m_deviceId; QString m_threadId; }; #endif // CONVERSATIONMODEL_H diff --git a/smsapp/qml/ConversationDisplay.qml b/smsapp/qml/ConversationDisplay.qml index efe94626..ef3fdba3 100644 --- a/smsapp/qml/ConversationDisplay.qml +++ b/smsapp/qml/ConversationDisplay.qml @@ -1,69 +1,69 @@ /* * This file is part of KDE Telepathy Chat * * Copyright (C) 2015 Aleix Pol Gonzalez * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ import QtQuick 2.1 import QtQuick.Controls 2.1 import QtQuick.Layouts 1.1 import org.kde.kirigami 2.2 as Kirigami import org.kde.kdeconnect.sms 1.0 Kirigami.ScrollablePage { id: page property QtObject person property QtObject device - property QtObject conversationId + property string conversationId property string phoneNumber title: person ? i18n("%1: %2", person.name, phoneNumber) : phoneNumber ListView { model: ConversationModel { id: model deviceId: device.id() - threadId: conversationId + threadId: page.conversationId } delegate: Kirigami.BasicListItem { readonly property real margin: 100 x: fromMe ? Kirigami.Units.gridUnit : margin width: parent.width - margin - Kirigami.Units.gridUnit contentItem: Label { text: model.display } } } footer: RowLayout { enabled: page.device TextField { id: message Layout.fillWidth: true placeholderText: i18n("Say hi...") onAccepted: { console.log("sending sms", page.phoneNumber) model.sendReplyToConversation(message.text) } } Button { text: "Send" onClicked: { message.accepted() } } } } diff --git a/smsapp/qml/ConversationList.qml b/smsapp/qml/ConversationList.qml index 352d397f..b163c75e 100644 --- a/smsapp/qml/ConversationList.qml +++ b/smsapp/qml/ConversationList.qml @@ -1,102 +1,102 @@ /* * This file is part of KDE Telepathy Chat * * Copyright (C) 2015 Aleix Pol Gonzalez * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ import QtQuick 2.5 import QtQuick.Controls 2.1 import QtQuick.Layouts 1.1 import org.kde.people 1.0 import org.kde.plasma.core 2.0 as Core import org.kde.kirigami 2.2 as Kirigami import org.kde.kdeconnect 1.0 import org.kde.kdeconnect.sms 1.0 Kirigami.ScrollablePage { footer: ComboBox { id: devicesCombo enabled: count > 0 displayText: enabled ? undefined : i18n("No devices available") model: DevicesSortProxyModel { id: devicesModel //TODO: make it possible to sort only if they can do sms sourceModel: DevicesModel { displayFilter: DevicesModel.Paired | DevicesModel.Reachable } onRowsInserted: if (devicesCombo.currentIndex < 0) { devicesCombo.currentIndex = 0 } } textRole: "display" } readonly property QtObject device: devicesCombo.currentIndex >= 0 ? devicesModel.data(devicesModel.index(devicesCombo.currentIndex, 0), DevicesModel.DeviceRole) : null Component { id: chatView ConversationDisplay {} } ListView { id: view currentIndex: 0 model: ConversationListModel { deviceId: device ? device.id() : "" } header: TextField { id: filter placeholderText: i18n("Filter...") width: parent.width onTextChanged: { view.model.filterRegExp = new RegExp(filter.text) view.currentIndex = 0 } Keys.onUpPressed: view.currentIndex = Math.max(view.currentIndex-1, 0) Keys.onDownPressed: view.currentIndex = Math.min(view.currentIndex+1, view.count-1) onAccepted: { view.currentItem.startChat() } Shortcut { sequence: "Ctrl+F" onActivated: filter.forceActiveFocus() } } delegate: Kirigami.BasicListItem { hoverEnabled: true readonly property var person: PersonData { personUri: model.personUri } - label: display + label: i18n("%1 - %2", display, toolTip) icon: decoration function startChat() { applicationWindow().pageStack.push(chatView, { person: person.person, phoneNumber: address, conversationId: model.conversationId, device: device}) } onClicked: { startChat(); } } } }