diff --git a/plugins/contacts/contactsplugin.cpp b/plugins/contacts/contactsplugin.cpp index 8306d724..1473f5b5 100644 --- a/plugins/contacts/contactsplugin.cpp +++ b/plugins/contacts/contactsplugin.cpp @@ -1,211 +1,212 @@ /** * 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 #include #include #include #include #include #include #include #include #include #include #include K_PLUGIN_FACTORY_WITH_JSON(KdeConnectPluginFactory, "kdeconnect_contacts.json", registerPlugin(); ) Q_LOGGING_CATEGORY(KDECONNECT_PLUGIN_CONTACTS, "kdeconnect.plugin.contacts") ContactsPlugin::ContactsPlugin (QObject* parent, const QVariantList& args) : - KdeConnectPlugin(parent, args) { + KdeConnectPlugin(parent, args) +{ vcardsPath = QString(*vcardsLocation).append("/kdeconnect-").append(device()->id()); // Register custom types with dbus qRegisterMetaType("uID"); qDBusRegisterMetaType(); qRegisterMetaType("uIDList_t"); qDBusRegisterMetaType(); // Create the storage directory if it doesn't exist if (!QDir().mkpath(vcardsPath)) { qCWarning(KDECONNECT_PLUGIN_CONTACTS) << "handleResponseVCards:" << "Unable to create VCard directory"; } this->synchronizeRemoteWithLocal(); qCDebug(KDECONNECT_PLUGIN_CONTACTS) << "Contacts constructor for device " << device()->name(); } ContactsPlugin::~ContactsPlugin () { QDBusConnection::sessionBus().unregisterObject(dbusPath(), QDBusConnection::UnregisterTree); // qCDebug(KDECONNECT_PLUGIN_CONTACTS) << "Contacts plugin destructor for device" << device()->name(); } bool ContactsPlugin::receivePacket (const NetworkPacket& np) { qCDebug(KDECONNECT_PLUGIN_CONTACTS) << "Packet Received for device " << device()->name(); qCDebug(KDECONNECT_PLUGIN_CONTACTS) << np.body(); if (np.type() == PACKAGE_TYPE_CONTACTS_RESPONSE_UIDS_TIMESTAMPS) { return this->handleResponseUIDsTimestamps(np); } else if (np.type() == PACKET_TYPE_CONTACTS_RESPONSE_VCARDS) { return this->handleResponseVCards(np); } else { // Is this check necessary? qCDebug(KDECONNECT_PLUGIN_CONTACTS) << "Unknown package type received from device: " << device()->name() << ". Maybe you need to upgrade KDE Connect?"; return false; } } void ContactsPlugin::synchronizeRemoteWithLocal () { this->sendRequest(PACKET_TYPE_CONTACTS_REQUEST_ALL_UIDS_TIMESTAMP); } bool ContactsPlugin::handleResponseUIDsTimestamps (const NetworkPacket& np) { if (!np.has("uids")) { qCDebug(KDECONNECT_PLUGIN_CONTACTS) << "handleResponseUIDsTimestamps:" << "Malformed packet does not have uids key"; return false; } uIDList_t uIDsToUpdate; QDir vcardsDir(vcardsPath); // Get a list of all file info in this directory // Clean out IDs returned from the remote. Anything leftover should be deleted QFileInfoList localVCards = vcardsDir.entryInfoList( { "*.vcard", "*.vcf" }); const QStringList& uIDs = np.get("uids"); // Check local storage for the contacts: // If the contact is not found in local storage, request its vcard be sent // If the contact is in local storage but not reported, delete it // If the contact is in local storage, compare its timestamp. If different, request the contact for (const QString& ID : uIDs) { QString filename = vcardsDir.filePath(ID + VCARD_EXTENSION); QFile vcardFile(filename); if (!QFile().exists(filename)) { // We do not have a vcard for this contact. Request it. uIDsToUpdate.push_back(ID); continue; } // Remove this file from the list of known files QFileInfo fileInfo(vcardFile); bool success = localVCards.removeOne(fileInfo); Q_ASSERT(success); // We should have always been able to remove the existing file from our listing // Check if the vcard needs to be updated if (!vcardFile.open(QIODevice::ReadOnly)) { qCWarning(KDECONNECT_PLUGIN_CONTACTS) << "handleResponseUIDsTimestamps:" << "Unable to open" << filename << "to read even though it was reported to exist"; continue; } QTextStream fileReadStream(&vcardFile); QString line; while (!fileReadStream.atEnd()) { fileReadStream >> line; // TODO: Check that the saved ID is the same as the one we were expecting. This requires parsing the VCard if (!line.startsWith("X-KDECONNECT-TIMESTAMP:")) { continue; } QStringList parts = line.split(":"); QString timestamp = parts[1]; qint32 remoteTimestamp = np.get(ID); qint32 localTimestamp = timestamp.toInt(); if (!(localTimestamp == remoteTimestamp)) { uIDsToUpdate.push_back(ID); } } } // Delete all locally-known files which were not reported by the remote device for (const QFileInfo& unknownFile : localVCards) { QFile toDelete(unknownFile.filePath()); toDelete.remove(); } this->sendRequestWithIDs(PACKET_TYPE_CONTACTS_REQUEST_VCARDS_BY_UIDS, uIDsToUpdate); return true; } bool ContactsPlugin::handleResponseVCards (const NetworkPacket& np) { if (!np.has("uids")) { qCDebug(KDECONNECT_PLUGIN_CONTACTS) << "handleResponseVCards:" << "Malformed packet does not have uids key"; return false; } QDir vcardsDir(vcardsPath); const QStringList& uIDs = np.get("uids"); // Loop over all IDs, extract the VCard from the packet and write the file for (const auto& ID : uIDs) { qCDebug(KDECONNECT_PLUGIN_CONTACTS) << "Got VCard:" << np.get(ID); QString filename = vcardsDir.filePath(ID + VCARD_EXTENSION); QFile vcardFile(filename); bool vcardFileOpened = vcardFile.open(QIODevice::WriteOnly); // Want to smash anything that might have already been there if (!vcardFileOpened) { qCWarning(KDECONNECT_PLUGIN_CONTACTS) << "handleResponseVCards:" << "Unable to open" << filename; continue; } QTextStream fileWriteStream(&vcardFile); const QString& vcard = np.get(ID); fileWriteStream << vcard; } qCDebug(KDECONNECT_PLUGIN_CONTACTS) << "handleResponseVCards:" << "Got" << uIDs.size() << "VCards"; Q_EMIT localCacheSynchronized(uIDs); return true; } bool ContactsPlugin::sendRequest (const QString& packetType) { NetworkPacket np(packetType); bool success = sendPacket(np); qCDebug(KDECONNECT_PLUGIN_CONTACTS) << "sendRequest: Sending " << packetType << success; return success; } bool ContactsPlugin::sendRequestWithIDs (const QString& packetType, const uIDList_t& uIDs) { NetworkPacket np(packetType); np.set("uids", uIDs); bool success = sendPacket(np); return success; } QString ContactsPlugin::dbusPath () const { return "/modules/kdeconnect/devices/" + device()->id() + "/contacts"; } #include "contactsplugin.moc" diff --git a/smsapp/conversationlistmodel.cpp b/smsapp/conversationlistmodel.cpp index 4f796478..6fd08a2e 100644 --- a/smsapp/conversationlistmodel.cpp +++ b/smsapp/conversationlistmodel.cpp @@ -1,157 +1,160 @@ /* * 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))); prepareConversationsList(); m_conversationsInterface->requestAllConversationThreads(); } void ConversationListModel::prepareConversationsList() { clear(); QDBusPendingReply validThreadIDsReply = m_conversationsInterface->activeConversations(); validThreadIDsReply.waitForFinished(); for (const QString& conversationId : validThreadIDsReply.value()) { handleCreatedConversation(conversationId); } } void ConversationListModel::handleCreatedConversation(const QString& conversationId) { QVariantList args; args.append(conversationId); m_conversationsInterface->callWithCallback("getFirstFromConversation", args, this, SLOT(createRowFromMessage(ConversationMessage)), SLOT(printDBusError(QDBusError))); } void ConversationListModel::printDBusError(const QDBusError& error) { qCWarning(KDECONNECT_SMS_CONVERSATIONS_LIST_MODEL) << error; } void ConversationListModel::createRowFromMessage(const ConversationMessage& message) { 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()); 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.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 7dbab3c0..b1c5031a 100644 --- a/smsapp/conversationlistmodel.h +++ b/smsapp/conversationlistmodel.h @@ -1,82 +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 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/qml/ConversationDisplay.qml b/smsapp/qml/ConversationDisplay.qml index b3ab859b..efe94626 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 - readonly property string phoneNumber: person.contactCustomProperty("phoneNumber") - title: i18n("%1: %2", person.name, phoneNumber) + property string phoneNumber + title: person ? i18n("%1: %2", person.name, phoneNumber) : phoneNumber ListView { model: ConversationModel { id: model deviceId: device.id() threadId: 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 ec26376d..352d397f 100644 --- a/smsapp/qml/ConversationList.qml +++ b/smsapp/qml/ConversationList.qml @@ -1,101 +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 icon: decoration function startChat() { applicationWindow().pageStack.push(chatView, { person: person.person, + phoneNumber: address, conversationId: model.conversationId, device: device}) } onClicked: { startChat(); } } } }