telepathy-ofono-0.2+16.04.20151120/0000755000015300001610000000000012623676450017030 5ustar pbuserpbgroup00000000000000telepathy-ofono-0.2+16.04.20151120/mmsdservice.cpp0000644000015300001610000001123412623675611022054 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include "dbustypes.h" #include "mmsdservice.h" QDBusArgument &operator<<(QDBusArgument &argument, const MessageStruct &message) { argument.beginStructure(); argument << message.path << message.properties; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, MessageStruct &message) { argument.beginStructure(); argument >> message.path >> message.properties; argument.endStructure(); return argument; } QDBusArgument &operator<<(QDBusArgument&argument, const OutgoingAttachmentStruct &attachment) { argument.beginStructure(); argument << attachment.id << attachment.contentType << attachment.filePath; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, OutgoingAttachmentStruct &attachment) { argument.beginStructure(); argument >> attachment.id >> attachment.contentType >> attachment.filePath; argument.endStructure(); return argument; } MMSDService::MMSDService(QString objectPath, oFonoConnection* connection, QObject *parent) : QObject(parent), m_servicePath(objectPath) { QDBusReply replyMessages; QDBusReply replyProperties; QDBusMessage request; qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); qDBusRegisterMetaType(); request = QDBusMessage::createMethodCall("org.ofono.mms", m_servicePath, "org.ofono.mms.Service", "GetProperties"); replyProperties = QDBusConnection::sessionBus().call(request); m_properties = replyProperties; request = QDBusMessage::createMethodCall("org.ofono.mms", m_servicePath, "org.ofono.mms.Service", "GetMessages"); replyMessages = QDBusConnection::sessionBus().call(request); m_messages = replyMessages; QDBusConnection::sessionBus().connect("org.ofono.mms", m_servicePath, "org.ofono.mms.Service", "MessageAdded", this, SLOT(onMessageAdded(const QDBusObjectPath&, const QVariantMap&))); QDBusConnection::sessionBus().connect("org.ofono.mms", m_servicePath, "org.ofono.mms.Service", "MessageRemoved", this, SLOT(onMessageRemoved(const QDBusObjectPath&))); } MMSDService::~MMSDService() { } QString MMSDService::path() const { return m_servicePath; } QString MMSDService::modemObjectPath() const { return m_properties["ModemObjectPath"].value().path(); } QVariantMap MMSDService::properties() const { return m_properties; } MessageList MMSDService::messages() const { return m_messages; } void MMSDService::onMessageAdded(const QDBusObjectPath &path, const QVariantMap &properties) { qDebug() << "message added" << path.path() << properties; Q_EMIT messageAdded(path.path(), properties); } void MMSDService::onMessageRemoved(const QDBusObjectPath& path) { qDebug() << "message removed" << path.path(); Q_EMIT messageRemoved(path.path()); } QDBusObjectPath MMSDService::sendMessage(QStringList recipients, OutgoingAttachmentList attachments) { QDBusMessage request; QList arguments; QDBusReply reply; arguments.append(recipients); arguments.append(QVariant::fromValue(attachments)); request = QDBusMessage::createMethodCall("org.ofono.mms", m_servicePath, "org.ofono.mms.Service", "SendMessage"); request.setArguments(arguments); reply = QDBusConnection::sessionBus().call(request); return reply; } telepathy-ofono-0.2+16.04.20151120/powerddbus.h0000644000015300001610000000205712623675611021361 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2014 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Andreas Pokorny */ #ifndef POWERD_DUBS_H #define POWERD_DBUS_H #include "powerd.h" #include class QDBusInterface; class PowerDDBus : public PowerD { public: PowerDDBus(); void enableProximityHandling() override; void disableProximityHandling() override; private: std::unique_ptr mPowerDIface; }; #endif telepathy-ofono-0.2+16.04.20151120/connection.h0000644000015300001610000001572312623675611021346 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef OFONOCONNECTION_H #define OFONOCONNECTION_H // telepathy-qt #include #include #include #include #include // ofono-qt #include #include #include #include #include #include #include #include #include #include // telepathy-ofono #include "ofonotextchannel.h" #include "ofonocallchannel.h" #include "emergencymodeiface.h" #include "voicemailiface.h" #include "mmsdmanager.h" #include "mmsdmessage.h" #include "dbustypes.h" #include "audiooutputsiface.h" #include "ussdiface.h" #ifdef USE_PULSEAUDIO #include "qpulseaudioengine.h" #endif class oFonoConnection; class oFonoTextChannel; class oFonoCallChannel; class oFonoConferenceCallChannel; class MMSDService; class oFonoConnection : public Tp::BaseConnection { Q_OBJECT Q_DISABLE_COPY(oFonoConnection) public: oFonoConnection(const QDBusConnection &dbusConnection, const QString &cmName, const QString &protocolName, const QVariantMap ¶meters); QStringList inspectHandles(uint handleType, const Tp::UIntList& handles, Tp::DBusError *error); Tp::UIntList requestHandles(uint handleType, const QStringList& identifiers, Tp::DBusError* error); Tp::BaseChannelPtr createChannel(const QVariantMap &request, Tp::DBusError *error); Tp::ContactAttributesMap getContactAttributes(const Tp::UIntList &handles, const QStringList &ifaces, Tp::DBusError *error); uint setPresence(const QString& status, const QString& statusMessage, Tp::DBusError *error); void connect(Tp::DBusError *error); void setSpeakerMode(bool active); void setActiveAudioOutput(const QString &id); AudioOutputList audioOutputs(); QString activeAudioOutput(); QStringList emergencyNumbers(Tp::DBusError *error); bool voicemailIndicator(Tp::DBusError *error); QString voicemailNumber(Tp::DBusError *error); uint voicemailCount(Tp::DBusError *error); void USSDInitiate(const QString &command, Tp::DBusError *error); void USSDRespond(const QString &reply, Tp::DBusError *error); void USSDCancel(Tp::DBusError *error); Tp::BaseConnectionRequestsInterfacePtr requestsIface; Tp::BaseConnectionSimplePresenceInterfacePtr simplePresenceIface; Tp::BaseConnectionContactsInterfacePtr contactsIface; BaseConnectionEmergencyModeInterfacePtr emergencyModeIface; BaseConnectionVoicemailInterfacePtr voicemailIface; BaseConnectionUSSDInterfacePtr supplementaryServicesIface; uint newHandle(const QString &identifier); OfonoMessageManager *messageManager(); OfonoVoiceCallManager *voiceCallManager(); OfonoCallVolume *callVolume(); QMap callChannels(); uint ensureHandle(const QString &phoneNumber); oFonoTextChannel* textChannelForMembers(const QStringList &members); Tp::BaseChannelPtr createTextChannel(const QVariantMap &request, Tp::DBusError *error); Tp::BaseChannelPtr createCallChannel(const QVariantMap &request, Tp::DBusError *error); bool matchChannel(const Tp::BaseChannelPtr &channel, const QVariantMap &request, Tp::DBusError *error); QString uniqueName() const; QDBusObjectPath sendMMS(const QStringList &numbers, const OutgoingAttachmentList& attachments); ~oFonoConnection(); Q_SIGNALS: void activeAudioOutputChanged(const QString &id); void audioOutputsChanged(const AudioOutputList &outputs); void channelMerged(const QDBusObjectPath &objPath); void channelSplitted(const QDBusObjectPath &objPath); void channelHangup(const QDBusObjectPath &objPath); void lastChannelClosed(); public Q_SLOTS: void updateAudioRoute(); void updateAudioRouteToEarpiece(); private Q_SLOTS: void onOfonoIncomingMessage(const QString &message, const QVariantMap &info); void onOfonoImmediateMessage(const QString &message, const QVariantMap &info); void onOfonoCallAdded(const QString &call, const QVariantMap &properties); void onTextChannelClosed(); void onCallChannelClosed(); void onCallChannelDestroyed(); void onValidityChanged(bool valid); void onMMSDServiceAdded(const QString&); void onMMSDServiceRemoved(const QString&); void onMMSAdded(const QString &, const QVariantMap&); void onMMSRemoved(const QString &); void onCheckMMSServices(); void onMessageRead(const QString &id); void onDeliveryReportReceived(const QString &messageId, const QVariantMap &info); void onConferenceCallChannelClosed(); void onCallChannelMerged(); void onCallChannelSplitted(); void onMultipartyCallHeld(); void onMultipartyCallActive(); void updateOnlineStatus(); void onDisconnected(); #ifdef USE_PULSEAUDIO void onAudioModeChanged(AudioMode mode); void onAvailableAudioModesChanged(AudioModes modes); #endif private: void updateMcc(); bool isNetworkRegistered(); void addMMSToService(const QString &path, const QVariantMap &properties, const QString &servicePath); void ensureTextChannel(const QString &message, const QVariantMap &info, bool flash); QMap mHandles; #ifdef USE_PULSEAUDIO bool mHasPulseAudio; #endif QList mTextChannels; QMap mCallChannels; QStringList mModems; OfonoModemManager *mOfonoModemManager; OfonoMessageManager *mOfonoMessageManager; OfonoVoiceCallManager *mOfonoVoiceCallManager; OfonoCallVolume *mOfonoCallVolume; OfonoNetworkRegistration *mOfonoNetworkRegistration; OfonoMessageWaiting *mOfonoMessageWaiting; OfonoSupplementaryServices *mOfonoSupplementaryServices; OfonoSimManager *mOfonoSimManager; OfonoModem *mOfonoModem; uint mHandleCount; Tp::SimplePresence mSelfPresence; MMSDManager *mMmsdManager; QMap mMmsdServices; QMap > mServiceMMSList; oFonoConferenceCallChannel *mConferenceCall; QString mModemPath; QString mActiveAudioOutput; AudioOutputList mAudioOutputs; }; #endif telepathy-ofono-0.2+16.04.20151120/voicemailiface.cpp0000644000015300001610000001632112623675611022475 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include #include "voicemailiface.h" // Conn.I.Voicemail BaseConnectionVoicemailInterface::Adaptee::Adaptee(BaseConnectionVoicemailInterface *interface) : QObject(interface), mInterface(interface) { } struct TP_QT_NO_EXPORT BaseConnectionVoicemailInterface::Private { Private(BaseConnectionVoicemailInterface *parent) : adaptee(new BaseConnectionVoicemailInterface::Adaptee(parent)) { } VoicemailCountCallback voicemailCountCB; VoicemailNumberCallback voicemailNumberCB; VoicemailIndicatorCallback voicemailIndicatorCB; BaseConnectionVoicemailInterface::Adaptee *adaptee; }; BaseConnectionVoicemailInterface::Adaptee::~Adaptee() { } void BaseConnectionVoicemailInterface::Adaptee::voicemailIndicator(const ConnectionInterfaceVoicemailAdaptor::VoicemailIndicatorContextPtr &context) { if (!mInterface->mPriv->voicemailIndicatorCB.isValid()) { context->setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")); return; } Tp::DBusError error; bool active = mInterface->mPriv->voicemailIndicatorCB(&error); if (error.isValid()) { context->setFinishedWithError(error.name(), error.message()); return; } context->setFinished(active); } void BaseConnectionVoicemailInterface::Adaptee::voicemailNumber(const ConnectionInterfaceVoicemailAdaptor::VoicemailNumberContextPtr &context) { if (!mInterface->mPriv->voicemailNumberCB.isValid()) { context->setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")); return; } Tp::DBusError error; QString number = mInterface->mPriv->voicemailNumberCB(&error); if (error.isValid()) { context->setFinishedWithError(error.name(), error.message()); return; } context->setFinished(number); } void BaseConnectionVoicemailInterface::Adaptee::voicemailCount(const ConnectionInterfaceVoicemailAdaptor::VoicemailCountContextPtr &context) { if (!mInterface->mPriv->voicemailCountCB.isValid()) { context->setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")); return; } Tp::DBusError error; uint count = mInterface->mPriv->voicemailCountCB(&error); if (error.isValid()) { context->setFinishedWithError(error.name(), error.message()); return; } context->setFinished(count); } BaseConnectionVoicemailInterface::BaseConnectionVoicemailInterface() : AbstractConnectionInterface(TP_QT_IFACE_CONNECTION_VOICEMAIL), mPriv(new Private(this)) { } BaseConnectionVoicemailInterface::~BaseConnectionVoicemailInterface() { delete mPriv; } void BaseConnectionVoicemailInterface::setVoicemailIndicatorCallback(const VoicemailIndicatorCallback &cb) { mPriv->voicemailIndicatorCB = cb; } void BaseConnectionVoicemailInterface::setVoicemailNumberCallback(const VoicemailNumberCallback &cb) { mPriv->voicemailNumberCB = cb; } void BaseConnectionVoicemailInterface::setVoicemailCountCallback(const VoicemailCountCallback &cb) { mPriv->voicemailCountCB = cb; } void BaseConnectionVoicemailInterface::setVoicemailCount(int count) { Q_EMIT mPriv->adaptee->voicemailCountChanged(uint(count)); } void BaseConnectionVoicemailInterface::setVoicemailNumber(const QString &voicemailNumber) { Q_EMIT mPriv->adaptee->voicemailNumberChanged(voicemailNumber); } void BaseConnectionVoicemailInterface::setVoicemailIndicator(bool active) { Q_EMIT mPriv->adaptee->voicemailIndicatorChanged(active); } QVariantMap BaseConnectionVoicemailInterface::immutableProperties() const { QVariantMap map; return map; } void BaseConnectionVoicemailInterface::createAdaptor() { (void) new ConnectionInterfaceVoicemailAdaptor(dbusObject()->dbusConnection(), mPriv->adaptee, dbusObject()); } ConnectionInterfaceVoicemailAdaptor::ConnectionInterfaceVoicemailAdaptor(const QDBusConnection& bus, QObject* adaptee, QObject* parent) : Tp::AbstractAdaptor(bus, adaptee, parent) { connect(adaptee, SIGNAL(voicemailCountChanged(uint)), SIGNAL(VoicemailCountChanged(uint))); connect(adaptee, SIGNAL(voicemailIndicatorChanged(bool)), SIGNAL(VoicemailIndicatorChanged(bool))); connect(adaptee, SIGNAL(voicemailNumberChanged(QString)), SIGNAL(VoicemailNumberChanged(QString))); } ConnectionInterfaceVoicemailAdaptor::~ConnectionInterfaceVoicemailAdaptor() { } bool ConnectionInterfaceVoicemailAdaptor::VoicemailIndicator(const QDBusMessage& dbusMessage) { if (!adaptee()->metaObject()->indexOfMethod("voicemailIndicator(ConnectionInterfaceVoicemailAdaptor::VoicemailIndicatorContextPtr)") == -1) { dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented"))); return bool(); } VoicemailIndicatorContextPtr ctx = VoicemailIndicatorContextPtr( new Tp::MethodInvocationContext< bool >(dbusConnection(), dbusMessage)); QMetaObject::invokeMethod(adaptee(), "voicemailIndicator", Q_ARG(ConnectionInterfaceVoicemailAdaptor::VoicemailIndicatorContextPtr, ctx)); return bool(); } QString ConnectionInterfaceVoicemailAdaptor::VoicemailNumber(const QDBusMessage& dbusMessage) { if (!adaptee()->metaObject()->indexOfMethod("voicemailNumber(ConnectionInterfaceVoicemailAdaptor::VoicemailNumberContextPtr)") == -1) { dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented"))); return QString(); } VoicemailNumberContextPtr ctx = VoicemailNumberContextPtr( new Tp::MethodInvocationContext< QString >(dbusConnection(), dbusMessage)); QMetaObject::invokeMethod(adaptee(), "voicemailNumber", Q_ARG(ConnectionInterfaceVoicemailAdaptor::VoicemailNumberContextPtr, ctx)); return QString(); } uint ConnectionInterfaceVoicemailAdaptor::VoicemailCount(const QDBusMessage& dbusMessage) { if (!adaptee()->metaObject()->indexOfMethod("voicemailCount(ConnectionInterfaceVoicemailAdaptor::VoicemailCountContextPtr)") == -1) { dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented"))); return uint(); } VoicemailCountContextPtr ctx = VoicemailCountContextPtr( new Tp::MethodInvocationContext< uint >(dbusConnection(), dbusMessage)); QMetaObject::invokeMethod(adaptee(), "voicemailCount", Q_ARG(ConnectionInterfaceVoicemailAdaptor::VoicemailCountContextPtr, ctx)); return uint(); } telepathy-ofono-0.2+16.04.20151120/powerd.h0000644000015300001610000000204412623675611020477 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2014 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Andreas Pokorny */ #ifndef POWERD_H #define POWERD_H class PowerD { public: PowerD() = default; virtual ~PowerD() = default; PowerD(PowerD const&) = delete; PowerD& operator=(PowerD const&) = delete; virtual void enableProximityHandling() = 0; virtual void disableProximityHandling() = 0; }; #endif // POWERD_H telepathy-ofono-0.2+16.04.20151120/powerdaudiomodemediator.cpp0000644000015300001610000000374612623675611024460 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2014 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Andreas Pokorny */ #include #include "powerdaudiomodemediator.h" PowerDAudioModeMediator::PowerDAudioModeMediator(PowerD &powerd) : powerd(powerd) { } void PowerDAudioModeMediator::audioModeChanged(const QString &mode) { bool enableProximity = !(mode == "speaker" || mode == "bluetooth" || mode == "wired_headset"); if (mProximityEnabled != enableProximity) { mProximityEnabled = enableProximity; apply(); } } void PowerDAudioModeMediator::apply() const { if (mProximityEnabled) { powerd.enableProximityHandling(); } else { // we need to power the screen on before disabling the proximity handling QDBusInterface unityIface("com.canonical.Unity.Screen", "/com/canonical/Unity/Screen", "com.canonical.Unity.Screen", QDBusConnection::systemBus()); QList args; args.append("on"); args.append(3); unityIface.callWithArgumentList(QDBus::NoBlock, "setScreenPowerMode", args); powerd.disableProximityHandling(); } } void PowerDAudioModeMediator::audioOutputClosed() { if (mProximityEnabled) { mProximityEnabled = false; apply(); } } telepathy-ofono-0.2+16.04.20151120/ofono.service.in0000644000015300001610000000020112623675611022126 0ustar pbuserpbgroup00000000000000[D-BUS Service] Name=org.freedesktop.Telepathy.ConnectionManager.ofono Exec=@CMAKE_INSTALL_PREFIX@/@LIBEXEC_DIR@/telepathy-ofono telepathy-ofono-0.2+16.04.20151120/mmsdmanager.cpp0000644000015300001610000000606512623675611022034 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include "mmsdmanager.h" struct ServiceStruct { QDBusObjectPath path; QVariantMap properties; }; typedef QList ServiceList; Q_DECLARE_METATYPE(ServiceStruct) Q_DECLARE_METATYPE(ServiceList) QDBusArgument &operator<<(QDBusArgument &argument, const ServiceStruct &service) { argument.beginStructure(); argument << service.path << service.properties; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, ServiceStruct &service) { argument.beginStructure(); argument >> service.path >> service.properties; argument.endStructure(); return argument; } MMSDManager::MMSDManager(QObject *parent) : QObject(parent) { QDBusReply reply; ServiceList services; QDBusMessage request; qDBusRegisterMetaType(); qDBusRegisterMetaType(); request = QDBusMessage::createMethodCall("org.ofono.mms", "/org/ofono/mms", "org.ofono.mms.Manager", "GetServices"); reply = QDBusConnection::sessionBus().call(request); services = reply; Q_FOREACH(ServiceStruct service, services) { m_services << service.path.path(); } QDBusConnection::sessionBus().connect("org.ofono.mms","/org/ofono/mms","org.ofono.mms.Manager", "ServiceAdded", this, SLOT(onServiceAdded(const QDBusObjectPath&, const QVariantMap&))); QDBusConnection::sessionBus().connect("org.ofono.mms","/org/ofono/mms","org.ofono.mms.Manager", "ServiceRemoved", this, SLOT(onServiceRemoved(const QDBusObjectPath&))); } MMSDManager::~MMSDManager() { } QStringList MMSDManager::services() const { return m_services; } void MMSDManager::onServiceAdded(const QDBusObjectPath& path, const QVariantMap& map) { qDebug() << "service added" << path.path() << map; m_services << path.path(); Q_EMIT serviceAdded(path.path()); } void MMSDManager::onServiceRemoved(const QDBusObjectPath& path) { qDebug() << "service removed" << path.path(); m_services.removeAll(path.path()); Q_EMIT serviceRemoved(path.path()); } telepathy-ofono-0.2+16.04.20151120/main.cpp0000644000015300001610000000255212623675611020462 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include #include "protocol.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Tp::registerTypes(); Tp::enableDebug(true); Tp::enableWarnings(true); Tp::BaseProtocolPtr proto = Tp::BaseProtocol::create( QDBusConnection::sessionBus(), QLatin1String("ofono")); Tp::BaseConnectionManagerPtr cm = Tp::BaseConnectionManager::create( QDBusConnection::sessionBus(), QLatin1String("ofono")); cm->addProtocol(proto); cm->registerObject(); return a.exec(); } telepathy-ofono-0.2+16.04.20151120/phoneutils.cpp0000644000015300001610000001135012623675611021724 0ustar pbuserpbgroup00000000000000/* * Copyright (C) 2012-2015 Canonical, Ltd. * * Authors: * Gustavo Pichorim Boiko * Renato Araujo Oliveira Filho * Tiago Salem Herrmann * * This file is part of telepathy-ofono. * * telepathy-ofono 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. * * telepathy-ofono 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 "phoneutils_p.h" #include #include #include #include #include #include #include QString PhoneUtils::mMcc = QString(); void PhoneUtils::setMcc(const QString &mcc) { mMcc = mcc; } QString PhoneUtils::countryCodeForMCC(const QString &mcc, bool useFallback) { static QMap countryCodes; if (countryCodes.isEmpty()) { QFile countryCodesFile(":/countrycodes.txt"); if (!countryCodesFile.open(QFile::ReadOnly)) { qCritical() << "Failed to open " << countryCodesFile.fileName(); if (useFallback) { return region(); } return QString(); } QTextStream stream(&countryCodesFile); while (!stream.atEnd()) { QString line = stream.readLine(); QStringList tuple = line.split(":"); if (tuple.size() != 2) { qCritical() << "Failed to parse line" << line; if (useFallback) { return region(); } return QString(); } countryCodes[tuple[0]] = tuple[1]; } } if (!countryCodes.contains(mcc) && useFallback) { return region(); } return countryCodes[mcc]; } QString PhoneUtils::region() { QString countryCode = QLocale::system().name().split("_").last(); if (countryCode.size() < 2) { // fallback to US if no valid country code was provided, otherwise libphonenumber // will fail to parse any numbers return QString("US"); } return countryCode; } QString PhoneUtils::normalizePhoneNumber(const QString &phoneNumber) { static i18n::phonenumbers::PhoneNumberUtil *phonenumberUtil = i18n::phonenumbers::PhoneNumberUtil::GetInstance(); if (!isPhoneNumber(phoneNumber)) { return phoneNumber; } std::string number = phoneNumber.toStdString(); phonenumberUtil->NormalizeDiallableCharsOnly(&number); return QString::fromStdString(number); } bool PhoneUtils::comparePhoneNumbers(const QString &phoneNumberA, const QString &phoneNumberB) { static i18n::phonenumbers::PhoneNumberUtil *phonenumberUtil = i18n::phonenumbers::PhoneNumberUtil::GetInstance(); // if any of the number isn't a phone number, just do a simple string comparison if (!isPhoneNumber(phoneNumberA) || !isPhoneNumber(phoneNumberB)) { return phoneNumberA == phoneNumberB; } i18n::phonenumbers::PhoneNumberUtil::MatchType match = phonenumberUtil-> IsNumberMatchWithTwoStrings(phoneNumberA.toStdString(), phoneNumberB.toStdString()); return (match > i18n::phonenumbers::PhoneNumberUtil::NO_MATCH); } bool PhoneUtils::isPhoneNumber(const QString &phoneNumber) { static i18n::phonenumbers::PhoneNumberUtil *phonenumberUtil = i18n::phonenumbers::PhoneNumberUtil::GetInstance(); std::string formattedNumber; i18n::phonenumbers::PhoneNumber number; i18n::phonenumbers::PhoneNumberUtil::ErrorType error; error = phonenumberUtil->Parse(phoneNumber.toStdString(), countryCodeForMCC(mMcc, true).toStdString(), &number); switch(error) { case i18n::phonenumbers::PhoneNumberUtil::INVALID_COUNTRY_CODE_ERROR: qWarning() << "Invalid country code for:" << phoneNumber; return false; case i18n::phonenumbers::PhoneNumberUtil::NOT_A_NUMBER: qWarning() << "The phone number is not a valid number:" << phoneNumber; return false; case i18n::phonenumbers::PhoneNumberUtil::TOO_SHORT_AFTER_IDD: case i18n::phonenumbers::PhoneNumberUtil::TOO_SHORT_NSN: case i18n::phonenumbers::PhoneNumberUtil::TOO_LONG_NSN: qWarning() << "Invalid phone number" << phoneNumber; return false; default: break; } return true; } telepathy-ofono-0.2+16.04.20151120/phoneutils_p.h0000644000015300001610000000303612623675611021712 0ustar pbuserpbgroup00000000000000/* * Copyright (C) 2015 Canonical, Ltd. * * Authors: * Gustavo Pichorim Boiko * Renato Araujo Oliveira Filho * Tiago Salem Herrmann * * This file is part of telepathy-ofono. * * telepathy-ofono 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. * * telepathy-ofono 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 TELEPHONY_PHONEUTILS_H #define TELEPHONY_PHONEUTILS_H #include class PhoneUtils : public QObject { Q_OBJECT public: enum PhoneNumberFormat { E164 = 0, International, National, RFC3966, Auto }; static QString normalizePhoneNumber(const QString &phoneNumber); static bool comparePhoneNumbers(const QString &phoneNumberA,const QString &phoneNumberB); static bool isPhoneNumber(const QString &identifier); static QString countryCodeForMCC(const QString &mcc, bool useFallback = true); static void setMcc(const QString &mcc); private: static QString region(); static QString mMcc; }; #endif telepathy-ofono-0.2+16.04.20151120/ussdiface.cpp0000644000015300001610000002471312623675611021507 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include #include "ussdiface.h" // Conn.I.USSD BaseConnectionUSSDInterface::Adaptee::Adaptee(BaseConnectionUSSDInterface *interface) : QObject(interface), mInterface(interface) { } struct TP_QT_NO_EXPORT BaseConnectionUSSDInterface::Private { Private(BaseConnectionUSSDInterface *parent) : adaptee(new BaseConnectionUSSDInterface::Adaptee(parent)) { } QString state; QString serial; InitiateCallback initiateCB; RespondCallback respondCB; CancelCallback cancelCB; BaseConnectionUSSDInterface::Adaptee *adaptee; }; BaseConnectionUSSDInterface::Adaptee::~Adaptee() { } void BaseConnectionUSSDInterface::Adaptee::initiate(const QString &command, const ConnectionInterfaceUSSDAdaptor::InitiateContextPtr &context) { if (!mInterface->mPriv->initiateCB.isValid()) { context->setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")); return; } Tp::DBusError error; mInterface->mPriv->initiateCB(command, &error); if (error.isValid()) { context->setFinishedWithError(error.name(), error.message()); return; } context->setFinished(); } void BaseConnectionUSSDInterface::Adaptee::respond(const QString &reply, const ConnectionInterfaceUSSDAdaptor::RespondContextPtr &context) { if (!mInterface->mPriv->respondCB.isValid()) { context->setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")); return; } Tp::DBusError error; mInterface->mPriv->respondCB(reply, &error); if (error.isValid()) { context->setFinishedWithError(error.name(), error.message()); return; } context->setFinished(); } void BaseConnectionUSSDInterface::Adaptee::cancel(const ConnectionInterfaceUSSDAdaptor::CancelContextPtr &context) { if (!mInterface->mPriv->cancelCB.isValid()) { context->setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")); return; } Tp::DBusError error; mInterface->mPriv->cancelCB(&error); if (error.isValid()) { context->setFinishedWithError(error.name(), error.message()); return; } context->setFinished(); } BaseConnectionUSSDInterface::BaseConnectionUSSDInterface() : AbstractConnectionInterface(TP_QT_IFACE_CONNECTION_USSD), mPriv(new Private(this)) { } BaseConnectionUSSDInterface::~BaseConnectionUSSDInterface() { delete mPriv; } void BaseConnectionUSSDInterface::setInitiateCallback(const InitiateCallback &cb) { mPriv->initiateCB = cb; } void BaseConnectionUSSDInterface::setRespondCallback(const RespondCallback &cb) { mPriv->respondCB = cb; } void BaseConnectionUSSDInterface::setCancelCallback(const CancelCallback &cb) { mPriv->cancelCB = cb; } QString BaseConnectionUSSDInterface::state() const { return mPriv->state; } void BaseConnectionUSSDInterface::setSerial(const QString &serial) const { mPriv->serial = serial; } QString BaseConnectionUSSDInterface::serial() const { return mPriv->serial; } void BaseConnectionUSSDInterface::StateChanged(const QString &state) { mPriv->state = state; Q_EMIT mPriv->adaptee->stateChanged(state); } void BaseConnectionUSSDInterface::InitiateUSSDComplete(const QString &ussdResp) { Q_EMIT mPriv->adaptee->initiateUSSDComplete(ussdResp); } void BaseConnectionUSSDInterface::RespondComplete(bool success, const QString &ussdResp) { Q_EMIT mPriv->adaptee->respondComplete(success, ussdResp); } void BaseConnectionUSSDInterface::BarringComplete(const QString &ssOp, const QString &cbService, const QVariantMap &cbMap) { Q_EMIT mPriv->adaptee->barringComplete(ssOp, cbService, cbMap); } void BaseConnectionUSSDInterface::ForwardingComplete(const QString &ssOp, const QString &cfService, const QVariantMap &cfMap) { Q_EMIT mPriv->adaptee->forwardingComplete(ssOp, cfService, cfMap); } void BaseConnectionUSSDInterface::WaitingComplete(const QString &ssOp, const QVariantMap &cwMap) { Q_EMIT mPriv->adaptee->waitingComplete(ssOp, cwMap); } void BaseConnectionUSSDInterface::CallingLinePresentationComplete(const QString &ssOp, const QString &status) { Q_EMIT mPriv->adaptee->callingLinePresentationComplete(ssOp, status); } void BaseConnectionUSSDInterface::ConnectedLinePresentationComplete(const QString &ssOp, const QString &status) { Q_EMIT mPriv->adaptee->connectedLinePresentationComplete(ssOp, status); } void BaseConnectionUSSDInterface::CallingLineRestrictionComplete(const QString &ssOp, const QString &status) { Q_EMIT mPriv->adaptee->callingLineRestrictionComplete(ssOp, status); } void BaseConnectionUSSDInterface::ConnectedLineRestrictionComplete(const QString &ssOp, const QString &status) { Q_EMIT mPriv->adaptee->connectedLineRestrictionComplete(ssOp, status); } void BaseConnectionUSSDInterface::InitiateFailed() { Q_EMIT mPriv->adaptee->initiateFailed(); } void BaseConnectionUSSDInterface::NotificationReceived(const QString &message) { Q_EMIT mPriv->adaptee->notificationReceived(message); } void BaseConnectionUSSDInterface::RequestReceived(const QString &message) { Q_EMIT mPriv->adaptee->requestReceived(message); } QVariantMap BaseConnectionUSSDInterface::immutableProperties() const { QVariantMap map; return map; } void BaseConnectionUSSDInterface::createAdaptor() { (void) new ConnectionInterfaceUSSDAdaptor(dbusObject()->dbusConnection(), mPriv->adaptee, dbusObject()); } ConnectionInterfaceUSSDAdaptor::ConnectionInterfaceUSSDAdaptor(const QDBusConnection& bus, QObject* adaptee, QObject* parent) : Tp::AbstractAdaptor(bus, adaptee, parent) { connect(adaptee, SIGNAL(notificationReceived(const QString &)), SIGNAL(NotificationReceived(const QString &))); connect(adaptee, SIGNAL(requestReceived(const QString &)), SIGNAL(RequestReceived(const QString &))); connect(adaptee, SIGNAL(initiateUSSDComplete(const QString &)), SIGNAL(InitiateUSSDComplete(const QString &))); connect(adaptee, SIGNAL(barringComplete(const QString &, const QString &, const QVariantMap &)), SIGNAL(BarringComplete(const QString &, const QString &, const QVariantMap &))); connect(adaptee, SIGNAL(forwardingComplete(const QString &, const QString &, const QVariantMap &)), SIGNAL(ForwardingComplete(const QString &, const QString &, const QVariantMap &))); connect(adaptee, SIGNAL(waitingComplete(const QString &, const QVariantMap &)), SIGNAL(WaitingComplete(const QString &, const QVariantMap &))); connect(adaptee, SIGNAL(callingLinePresentationComplete(const QString &, const QString &)), SIGNAL(CallingLinePresentationComplete(const QString &, const QString &))); connect(adaptee, SIGNAL(connectedLinePresentationComplete(const QString &, const QString &)), SIGNAL(ConnectedLinePresentationComplete(const QString &, const QString &))); connect(adaptee, SIGNAL(callingLineRestrictionComplete(const QString &, const QString &)), SIGNAL(CallingLineRestrictionComplete(const QString &, const QString &))); connect(adaptee, SIGNAL(connectedLineRestrictionComplete(const QString &, const QString &)), SIGNAL(ConnectedLineRestrictionComplete(const QString &, const QString &))); connect(adaptee, SIGNAL(initiateFailed()), SIGNAL(InitiateFailed())); connect(adaptee, SIGNAL(stateChanged(const QString&)), SIGNAL(StateChanged(const QString&))); connect(adaptee, SIGNAL(respondComplete(bool, const QString &)), SIGNAL(RespondComplete(bool, const QString &))); } ConnectionInterfaceUSSDAdaptor::~ConnectionInterfaceUSSDAdaptor() { } void ConnectionInterfaceUSSDAdaptor::Initiate(const QString &command, const QDBusMessage& dbusMessage) { if (!adaptee()->metaObject()->indexOfMethod("initiate(const QString &,ConnectionInterfaceUSSDAdaptor::InitiateContextPtr)") == -1) { dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented"))); return; } InitiateContextPtr ctx = InitiateContextPtr( new Tp::MethodInvocationContext< >(dbusConnection(), dbusMessage)); QMetaObject::invokeMethod(adaptee(), "initiate", Q_ARG(QString, command), Q_ARG(ConnectionInterfaceUSSDAdaptor::InitiateContextPtr, ctx)); return; } void ConnectionInterfaceUSSDAdaptor::Respond(const QString &reply, const QDBusMessage& dbusMessage) { if (!adaptee()->metaObject()->indexOfMethod("respond(QConnectionInterfaceUSSDAdaptor::RespondContextPtr)") == -1) { dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented"))); return; } RespondContextPtr ctx = RespondContextPtr( new Tp::MethodInvocationContext< >(dbusConnection(), dbusMessage)); QMetaObject::invokeMethod(adaptee(), "respond", Q_ARG(QString, reply), Q_ARG(ConnectionInterfaceUSSDAdaptor::RespondContextPtr, ctx)); return; } void ConnectionInterfaceUSSDAdaptor::Cancel(const QDBusMessage& dbusMessage) { if (!adaptee()->metaObject()->indexOfMethod("cancel(ConnectionInterfaceUSSDAdaptor::CancelContextPtr)") == -1) { dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented"))); return; } CancelContextPtr ctx = CancelContextPtr( new Tp::MethodInvocationContext< >(dbusConnection(), dbusMessage)); QMetaObject::invokeMethod(adaptee(), "cancel", Q_ARG(ConnectionInterfaceUSSDAdaptor::CancelContextPtr, ctx)); return; } QString ConnectionInterfaceUSSDAdaptor::Serial() const { return qvariant_cast< QString >(adaptee()->property("serial")); } QString ConnectionInterfaceUSSDAdaptor::State() const { return qvariant_cast< QString >(adaptee()->property("state")); } telepathy-ofono-0.2+16.04.20151120/CMakeLists.txt0000644000015300001610000001066512623675611021576 0ustar pbuserpbgroup00000000000000project(telepathy-ofono) cmake_minimum_required(VERSION 2.8) set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules) set(TELEPATHY_OFONO telepathy-ofono) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") # Find includes in corresponding build directories set(CMAKE_INCLUDE_CURRENT_DIR ON) # Standard install paths include(GNUInstallDirs) # Check for include files include(CheckIncludeFileCXX) include(EnableCoverageReport) ##################################################################### # Enable code coverage calculation with gcov/gcovr/lcov # Usage: # * Switch build type to coverage (use ccmake or cmake-gui) # * Invoke make, make test, make coverage # * Find html report in subdir coveragereport # * Find xml report feasible for jenkins in coverage.xml ##################################################################### IF(CMAKE_BUILD_TYPE MATCHES [cC][oO][vV][eE][rR][aA][gG][eE]) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftest-coverage -fprofile-arcs" ) SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -ftest-coverage -fprofile-arcs" ) SET(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -coverage" ) SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -coverage" ) ENABLE_COVERAGE_REPORT(TARGETS ${TELEPATHY_OFONO}) ENDIF(CMAKE_BUILD_TYPE MATCHES [cC][oO][vV][eE][rR][aA][gG][eE]) find_package(LibPhoneNumber REQUIRED) find_package(Qt5Core) find_package(Qt5DBus) add_definitions(-DQT_NO_KEYWORDS) find_package(PkgConfig REQUIRED) pkg_check_modules(TP_QT5 REQUIRED TelepathyQt5) pkg_check_modules(SQLITE3 REQUIRED sqlite3) pkg_check_modules(MC_PLUGINS REQUIRED mission-control-plugins) pkg_check_modules(PULSEAUDIO libpulse) if (PULSEAUDIO_FOUND) add_definitions(-DUSE_PULSEAUDIO) set(USE_PULSEAUDIO ON) include_directories(${PULSEAUDIO_INCLUDE_DIRS}) endif (PULSEAUDIO_FOUND) find_program(DBUS_RUNNER dbus-test-runner) if(NOT DAEMON_DIR) set(DAEMON_DIR lib/telepathy) endif(NOT DAEMON_DIR) set(CMAKE_AUTOMOC ON) include_directories(${TP_QT5_INCLUDE_DIRS}) include_directories(${Qt5Core_INCLUDE_DIRS}) include_directories(${Qt5DBus_INCLUDE_DIRS}) include_directories(${SQLITE3_INCLUDE_DIRS}) include_directories(${LibPhoneNumber_INCLUDE_DIRS}) include_directories(/usr/include/telepathy-qt5/) include_directories(/usr/include/ofono-qt/) find_library(TELEPATHY_QT5_LIBRARIES telepathy-qt5) find_library(TELEPATHY_QT5_SERVICE_LIBRARIES telepathy-qt5-service) find_library(OFONO_QT_LIBRARIES ofono-qt) qt5_add_resources(telepathyfono_RES sqlitetelepathyofono.qrc countrycodes.qrc) # update the .qrc file automatically when there are new schema files file(GLOB QRC_RESOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/schema/*.sql ${CMAKE_CURRENT_SOURCE_DIR}/schema/*.info) set(QRC_FILE ${CMAKE_CURRENT_SOURCE_DIR}/sqlitetelepathyofono.qrc) add_custom_command( OUTPUT ${QRC_FILE} COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/update_qrc.sh ${QRC_FILE} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ${QRC_RESOURCE_FILES} ) add_custom_target(qrc_update DEPENDS ${QRC_FILE} schema_update) set(TELEPATHY_OFONO_SRC main.cpp protocol.cpp connection.cpp ofonotextchannel.cpp ofonocallchannel.cpp ofonoconferencecallchannel.cpp emergencymodeiface.cpp voicemailiface.cpp audiooutputsiface.cpp mmsdmanager.cpp mmsdservice.cpp mmsdmessage.cpp pendingmessagesmanager.cpp phoneutils.cpp powerdaudiomodemediator.cpp powerddbus.cpp sqlitedatabase.cpp ussdiface.cpp ${telepathyfono_RES}) if(USE_PULSEAUDIO) add_executable(${TELEPATHY_OFONO} qpulseaudioengine.cpp ${TELEPATHY_OFONO_SRC}) else(USE_PULSEAUDIO) add_executable(${TELEPATHY_OFONO} ${TELEPATHY_OFONO_SRC}) endif(USE_PULSEAUDIO) qt5_use_modules(${TELEPATHY_OFONO} Core DBus Sql) add_dependencies(${TELEPATHY_OFONO} schema_update qrc_update) enable_testing() target_link_libraries(${TELEPATHY_OFONO} ${Qt5Core_LIBRARIES} ${Qt5DBus_LIBRARIES} ${WAUDIO_LIBRARIES} -ltelepathy-qt5 ${TELEPATHY_QT5_SERVICE_LIBRARIES} ${OFONO_QT_LIBRARIES} ${PULSEAUDIO_LIBRARIES} ${SQLITE3_LIBRARIES} ${LibPhoneNumber_LIBRARIES}) install(TARGETS ${TELEPATHY_OFONO} DESTINATION ${DAEMON_DIR}) configure_file(ofono.service.in org.freedesktop.Telepathy.ConnectionManager.ofono.service) install (FILES ofono.manager DESTINATION share/telepathy/managers) install (FILES ${CMAKE_CURRENT_BINARY_DIR}/org.freedesktop.Telepathy.ConnectionManager.ofono.service DESTINATION share/dbus-1/services) add_subdirectory(schema) add_subdirectory(tests) add_subdirectory(mc-plugin) telepathy-ofono-0.2+16.04.20151120/emergencymodeiface.cpp0000644000015300001610000001351712623675611023354 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann * Gustavo Pichorim Boiko */ #include #include #include #include "emergencymodeiface.h" BaseConnectionEmergencyModeInterface::Adaptee::Adaptee(BaseConnectionEmergencyModeInterface *interface) : QObject(interface), mInterface(interface) { } struct TP_QT_NO_EXPORT BaseConnectionEmergencyModeInterface::Private { Private(BaseConnectionEmergencyModeInterface *parent) : adaptee(new BaseConnectionEmergencyModeInterface::Adaptee(parent)) { } EmergencyNumbersCallback emergencyNumbersCB; BaseConnectionEmergencyModeInterface::Adaptee *adaptee; QString fakeEmergencyNumber; QString countryCode; }; BaseConnectionEmergencyModeInterface::Adaptee::~Adaptee() { } void BaseConnectionEmergencyModeInterface::Adaptee::emergencyNumbers(const ConnectionInterfaceEmergencyModeAdaptor::EmergencyNumbersContextPtr &context) { if (!mInterface->mPriv->emergencyNumbersCB.isValid()) { context->setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")); return; } Tp::DBusError error; QStringList numbers = mInterface->mPriv->emergencyNumbersCB(&error); if (error.isValid()) { context->setFinishedWithError(error.name(), error.message()); return; } if (mInterface->mPriv->fakeEmergencyNumber.isEmpty()) { context->setFinished(numbers); } else { context->setFinished(QStringList() << numbers << mInterface->mPriv->fakeEmergencyNumber); } } void BaseConnectionEmergencyModeInterface::Adaptee::countryCode(const ConnectionInterfaceEmergencyModeAdaptor::CountryCodeContextPtr &context) { context->setFinished(mInterface->mPriv->countryCode); } BaseConnectionEmergencyModeInterface::BaseConnectionEmergencyModeInterface() : AbstractConnectionInterface(TP_QT_IFACE_CONNECTION_EMERGENCYMODE), mPriv(new Private(this)) { } BaseConnectionEmergencyModeInterface::~BaseConnectionEmergencyModeInterface() { delete mPriv; } void BaseConnectionEmergencyModeInterface::setEmergencyNumbersCallback(const EmergencyNumbersCallback &cb) { mPriv->emergencyNumbersCB = cb; } void BaseConnectionEmergencyModeInterface::setEmergencyNumbers(const QStringList &numbers) { QStringList finalEmergencyList(numbers); if (!mPriv->fakeEmergencyNumber.isEmpty()) { finalEmergencyList << mPriv->fakeEmergencyNumber; } Q_EMIT mPriv->adaptee->emergencyNumbersChanged(finalEmergencyList); } void BaseConnectionEmergencyModeInterface::setCountryCode(const QString &countryCode) { if (mPriv->countryCode == countryCode) { return; } mPriv->countryCode = countryCode; Q_EMIT mPriv->adaptee->countryCodeChanged(mPriv->countryCode); } void BaseConnectionEmergencyModeInterface::setFakeEmergencyNumber(const QString &fakeEmergencyNumber) { mPriv->fakeEmergencyNumber = fakeEmergencyNumber; } QVariantMap BaseConnectionEmergencyModeInterface::immutableProperties() const { QVariantMap map; return map; } void BaseConnectionEmergencyModeInterface::createAdaptor() { (void) new ConnectionInterfaceEmergencyModeAdaptor(dbusObject()->dbusConnection(), mPriv->adaptee, dbusObject()); } ConnectionInterfaceEmergencyModeAdaptor::ConnectionInterfaceEmergencyModeAdaptor(const QDBusConnection& bus, QObject* adaptee, QObject* parent) : Tp::AbstractAdaptor(bus, adaptee, parent) { connect(adaptee, SIGNAL(emergencyNumbersChanged(QStringList)), SIGNAL(EmergencyNumbersChanged(QStringList))); connect(adaptee, SIGNAL(countryCodeChanged(QString)), SIGNAL(CountryCodeChanged(QString))); } ConnectionInterfaceEmergencyModeAdaptor::~ConnectionInterfaceEmergencyModeAdaptor() { } QStringList ConnectionInterfaceEmergencyModeAdaptor::EmergencyNumbers(const QDBusMessage& dbusMessage) { if (!adaptee()->metaObject()->indexOfMethod("emergencyNumbers(ConnectionInterfaceEmergencyModeAdaptor::EmergencyNumbersContextPtr)") == -1) { dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented"))); return QStringList(); } EmergencyNumbersContextPtr ctx = EmergencyNumbersContextPtr( new Tp::MethodInvocationContext< QStringList >(dbusConnection(), dbusMessage)); QMetaObject::invokeMethod(adaptee(), "emergencyNumbers", Q_ARG(ConnectionInterfaceEmergencyModeAdaptor::EmergencyNumbersContextPtr, ctx)); return QStringList(); } QString ConnectionInterfaceEmergencyModeAdaptor::CountryCode(const QDBusMessage& dbusMessage) { if (!adaptee()->metaObject()->indexOfMethod("countryCode(ConnectionInterfaceEmergencyModeAdaptor::CountryCodeContextPtr)") == -1) { dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented"))); return QString(); } CountryCodeContextPtr ctx = CountryCodeContextPtr( new Tp::MethodInvocationContext< QString >(dbusConnection(), dbusMessage)); QMetaObject::invokeMethod(adaptee(), "countryCode", Q_ARG(ConnectionInterfaceEmergencyModeAdaptor::CountryCodeContextPtr, ctx)); return QString(); } telepathy-ofono-0.2+16.04.20151120/mmsdmessage.cpp0000644000015300001610000000430412623675611022040 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include "mmsdmessage.h" MMSDMessage::MMSDMessage(QString objectPath, QVariantMap properties, QObject *parent) : QObject(parent), m_messagePath(objectPath), m_properties(properties) { QDBusConnection::sessionBus().connect("org.ofono.mms", m_messagePath, "org.ofono.mms.Message", "PropertyChanged", this, SLOT(onPropertyChanged(QString,QDBusVariant))); } MMSDMessage::~MMSDMessage() { } QString MMSDMessage::path() const { return m_messagePath; } QVariantMap MMSDMessage::properties() const { return m_properties; } void MMSDMessage::onPropertyChanged(const QString &property, const QDBusVariant &value) { QVariant variantValue = value.variant(); m_properties[property] = variantValue; Q_EMIT propertyChanged(property, variantValue); } void MMSDMessage::markRead() const { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono.mms", m_messagePath, "org.ofono.mms.Message", "MarkRead"); QDBusConnection::sessionBus().call(request); } void MMSDMessage::remove() const { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono.mms", m_messagePath, "org.ofono.mms.Message", "Delete"); QDBusConnection::sessionBus().call(request); } telepathy-ofono-0.2+16.04.20151120/pendingmessagesmanager.h0000644000015300001610000000240012623675611023702 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include struct PendingMessage { QString recipientId; QDateTime timestamp; }; class PendingMessagesManager : public QObject { Q_OBJECT public: static PendingMessagesManager *instance(); void addPendingMessage(const QString &objectPath, const QString &id); void removePendingMessage(const QString &objectPath); QString recipientIdForMessageId(const QString &messageId); private: explicit PendingMessagesManager(QObject *parent = 0); QSqlDatabase mDatabase; }; telepathy-ofono-0.2+16.04.20151120/audiooutputsiface.h0000644000015300001610000001146112623675611022737 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef OFONOAUDIOOUTPUTSIFACE_H #define OFONOAUDIOOUTPUTSIFACE_H // telepathy-qt #include #include #include #include #include #include "dbustypes.h" #define TP_QT_IFACE_CHANNEL_AUDIOOUTPUTS "com.canonical.Telephony.AudioOutputs" class BaseChannelAudioOutputsInterface; typedef Tp::SharedPtr BaseChannelAudioOutputsInterfacePtr; class TP_QT_EXPORT BaseChannelAudioOutputsInterface : public Tp::AbstractChannelInterface { Q_OBJECT Q_DISABLE_COPY(BaseChannelAudioOutputsInterface) public: static BaseChannelAudioOutputsInterfacePtr create() { return BaseChannelAudioOutputsInterfacePtr(new BaseChannelAudioOutputsInterface()); } template static Tp::SharedPtr create() { return Tp::SharedPtr( new BaseChannelAudioOutputsInterfaceSubclass()); } QVariantMap immutableProperties() const; virtual ~BaseChannelAudioOutputsInterface(); AudioOutputList audioOutputs() const; QString activeAudioOutput() const; typedef Tp::Callback2 SetActiveAudioOutputCallback; void setSetActiveAudioOutputCallback(const SetActiveAudioOutputCallback &cb); public Q_SLOTS: void setActiveAudioOutput(const QString &id); void setAudioOutputs(const AudioOutputList &outputs); protected: BaseChannelAudioOutputsInterface(); private: void createAdaptor(); class Adaptee; friend class Adaptee; struct Private; friend struct Private; Private *mPriv; }; class TP_QT_EXPORT ChannelInterfaceAudioOutputsAdaptor : public Tp::AbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", TP_QT_IFACE_CHANNEL_AUDIOOUTPUTS) Q_CLASSINFO("D-Bus Introspection", "" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" "") Q_PROPERTY(AudioOutputList AudioOutputs READ AudioOutputs) Q_PROPERTY(QString ActiveAudioOutput READ ActiveAudioOutput) public: ChannelInterfaceAudioOutputsAdaptor(const QDBusConnection& dbusConnection, QObject* adaptee, QObject* parent); virtual ~ChannelInterfaceAudioOutputsAdaptor(); typedef Tp::MethodInvocationContextPtr< > SetActiveAudioOutputContextPtr; public: // PROPERTIES QString ActiveAudioOutput() const; AudioOutputList AudioOutputs() const; public Q_SLOTS: // METHODS void SetActiveAudioOutput(const QString &id, const QDBusMessage& dbusMessage); Q_SIGNALS: // SIGNALS void AudioOutputsChanged(const AudioOutputList &outputs); void ActiveAudioOutputChanged(const QString &id); }; class TP_QT_NO_EXPORT BaseChannelAudioOutputsInterface::Adaptee : public QObject { Q_OBJECT Q_PROPERTY(AudioOutputList audioOutputs READ audioOutputs) Q_PROPERTY(QString activeAudioOutput READ activeAudioOutput) public: Adaptee(BaseChannelAudioOutputsInterface *interface); ~Adaptee(); AudioOutputList audioOutputs() const { return mInterface->audioOutputs(); } QString activeAudioOutput() const { return mInterface->activeAudioOutput(); } private Q_SLOTS: void setActiveAudioOutput(const QString &id, const ChannelInterfaceAudioOutputsAdaptor::SetActiveAudioOutputContextPtr &context); Q_SIGNALS: void activeAudioOutputChanged(const QString &id); void audioOutputsChanged(const AudioOutputList &outputs); public: BaseChannelAudioOutputsInterface *mInterface; }; #endif telepathy-ofono-0.2+16.04.20151120/qpulseaudioengine.cpp0000644000015300001610000007344612623675611023271 0ustar pbuserpbgroup00000000000000/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file was taken from qt5 and modified by ** David Henningsson for usage in ** telepathy-ofono. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #include #include "qpulseaudioengine.h" #include #include #define PULSEAUDIO_PROFILE_HSP "headset_head_unit" #define PULSEAUDIO_PROFILE_A2DP "a2dp_sink" QT_BEGIN_NAMESPACE static void contextStateCallbackInit(pa_context *context, void *userdata) { Q_UNUSED(context); QPulseAudioEngineWorker *pulseEngine = reinterpret_cast(userdata); pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } static void contextStateCallback(pa_context *context, void *userdata) { Q_UNUSED(userdata); Q_UNUSED(context); } static void success_cb(pa_context *context, int success, void *userdata) { QPulseAudioEngineWorker *pulseEngine = reinterpret_cast(userdata); pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); } /* Callbacks used when handling events from PulseAudio */ static void plug_card_cb(pa_context *c, const pa_card_info *info, int isLast, void *userdata) { QPulseAudioEngineWorker *pulseEngine = static_cast(userdata); if (isLast != 0 || !pulseEngine || !info) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->plugCardCallback(info); } static void update_card_cb(pa_context *c, const pa_card_info *info, int isLast, void *userdata) { QPulseAudioEngineWorker *pulseEngine = static_cast(userdata); if (isLast != 0 || !pulseEngine || !info) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->updateCardCallback(info); } static void unplug_card_cb(pa_context *c, const pa_card_info *info, int isLast, void *userdata) { QPulseAudioEngineWorker *pulseEngine = static_cast(userdata); if (!pulseEngine) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } if (info == NULL) { /* That means that the card used to query card_info was removed */ pulseEngine->unplugCardCallback(); } } static void subscribeCallback(pa_context *context, pa_subscription_event_type_t t, uint32_t idx, void *userdata) { /* For card change events (slot plug/unplug and add/remove card) */ if ((t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK) == PA_SUBSCRIPTION_EVENT_CARD) { if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_CHANGE) { QMetaObject::invokeMethod((QPulseAudioEngineWorker *) userdata, "handleCardEvent", Qt::QueuedConnection, Q_ARG(int, PA_SUBSCRIPTION_EVENT_CHANGE), Q_ARG(unsigned int, idx)); } else if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_NEW) { QMetaObject::invokeMethod((QPulseAudioEngineWorker *) userdata, "handleCardEvent", Qt::QueuedConnection, Q_ARG(int, PA_SUBSCRIPTION_EVENT_NEW), Q_ARG(unsigned int, idx)); } else if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE) { QMetaObject::invokeMethod((QPulseAudioEngineWorker *) userdata, "handleCardEvent", Qt::QueuedConnection, Q_ARG(int, PA_SUBSCRIPTION_EVENT_REMOVE), Q_ARG(unsigned int, idx)); } } } QPulseAudioEngineWorker::QPulseAudioEngineWorker(QObject *parent) : QObject(parent) , m_mainLoopApi(0) , m_context(0) , m_callstatus(CallEnded) , m_audiomode(AudioModeSpeaker) , m_micmute(false) , m_defaultsink("sink.primary") , m_defaultsource("source.primary") , m_voicecallcard("") , m_voicecallhighest("") , m_voicecallprofile("") , m_bt_hsp("") , m_bt_hsp_a2dp("") { m_mainLoop = pa_threaded_mainloop_new(); if (m_mainLoop == 0) { qWarning("Unable to create pulseaudio mainloop"); return; } if (pa_threaded_mainloop_start(m_mainLoop) != 0) { qWarning("Unable to start pulseaudio mainloop"); pa_threaded_mainloop_free(m_mainLoop); m_mainLoop = 0; return; } createPulseContext(); } bool QPulseAudioEngineWorker::createPulseContext() { bool keepGoing = true; bool ok = true; if (m_context) return true; m_mainLoopApi = pa_threaded_mainloop_get_api(m_mainLoop); pa_threaded_mainloop_lock(m_mainLoop); m_context = pa_context_new(m_mainLoopApi, QString(QLatin1String("QtmPulseContext:%1")).arg(::getpid()).toLatin1().constData()); pa_context_set_state_callback(m_context, contextStateCallbackInit, this); if (!m_context) { qWarning("Unable to create new pulseaudio context"); pa_threaded_mainloop_unlock(m_mainLoop); return false; } if (pa_context_connect(m_context, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL) < 0) { qWarning("Unable to create a connection to the pulseaudio context"); pa_threaded_mainloop_unlock(m_mainLoop); releasePulseContext(); return false; } pa_threaded_mainloop_wait(m_mainLoop); while (keepGoing) { switch (pa_context_get_state(m_context)) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: break; case PA_CONTEXT_READY: qDebug("Pulseaudio connection established."); keepGoing = false; break; case PA_CONTEXT_TERMINATED: qCritical("Pulseaudio context terminated."); keepGoing = false; ok = false; break; case PA_CONTEXT_FAILED: default: qCritical() << QString("Pulseaudio connection failure: %1").arg(pa_strerror(pa_context_errno(m_context))); keepGoing = false; ok = false; } if (keepGoing) { pa_threaded_mainloop_wait(m_mainLoop); } } if (ok) { pa_context_set_state_callback(m_context, contextStateCallback, this); pa_context_set_subscribe_callback(m_context, subscribeCallback, this); pa_context_subscribe(m_context, PA_SUBSCRIPTION_MASK_CARD, NULL, this); } else { if (m_context) { pa_context_unref(m_context); m_context = 0; } } pa_threaded_mainloop_unlock(m_mainLoop); return true; } void QPulseAudioEngineWorker::releasePulseContext() { if (m_context) { pa_threaded_mainloop_lock(m_mainLoop); pa_context_disconnect(m_context); pa_context_unref(m_context); pa_threaded_mainloop_unlock(m_mainLoop); m_context = 0; } } QPulseAudioEngineWorker::~QPulseAudioEngineWorker() { releasePulseContext(); if (m_mainLoop) { pa_threaded_mainloop_stop(m_mainLoop); pa_threaded_mainloop_free(m_mainLoop); m_mainLoop = 0; } } void QPulseAudioEngineWorker::cardInfoCallback(const pa_card_info *info) { pa_card_profile_info2 *voice_call = NULL, *highest = NULL; pa_card_profile_info2 *hsp = NULL, *a2dp = NULL; /* For now we only support one card with the voicecall feature */ for (int i = 0; i < info->n_profiles; i++) { if (!highest || info->profiles2[i]->priority > highest->priority) highest = info->profiles2[i]; if (!strcmp(info->profiles2[i]->name, "voicecall")) voice_call = info->profiles2[i]; else if (!strcmp(info->profiles2[i]->name, PULSEAUDIO_PROFILE_HSP) && info->profiles2[i]->available != 0) hsp = info->profiles2[i]; else if (!strcmp(info->profiles2[i]->name, PULSEAUDIO_PROFILE_A2DP) && info->profiles2[i]->available != 0) a2dp = info->profiles2[i]; } /* Record the card that supports voicecall (default one to be used) */ if (voice_call) { qDebug("Found card that supports voicecall: '%s'", info->name); m_voicecallcard = info->name; m_voicecallhighest = highest->name; m_voicecallprofile = voice_call->name; } /* Handle the use cases needed for bluetooth */ if (hsp && a2dp) { qDebug("Found card that supports hsp and a2dp: '%s'", info->name); m_bt_hsp_a2dp = info->name; } else if (hsp && (a2dp == NULL)) { /* This card only provides the hsp profile */ qDebug("Found card that supports only hsp: '%s'", info->name); m_bt_hsp = info->name; } } void QPulseAudioEngineWorker::sinkInfoCallback(const pa_sink_info *info) { pa_sink_port_info *earpiece = NULL, *speaker = NULL; pa_sink_port_info *wired_headset = NULL, *wired_headphone = NULL; pa_sink_port_info *preferred = NULL; pa_sink_port_info *bluetooth_sco = NULL; pa_sink_port_info *speaker_and_wired_headphone = NULL; AudioMode audiomodetoset; AudioModes modes; for (int i = 0; i < info->n_ports; i++) { if (!strcmp(info->ports[i]->name, "output-earpiece")) earpiece = info->ports[i]; else if (!strcmp(info->ports[i]->name, "output-wired_headset") && (info->ports[i]->available != PA_PORT_AVAILABLE_NO)) wired_headset = info->ports[i]; else if (!strcmp(info->ports[i]->name, "output-wired_headphone") && (info->ports[i]->available != PA_PORT_AVAILABLE_NO)) wired_headphone = info->ports[i]; else if (!strcmp(info->ports[i]->name, "output-speaker")) speaker = info->ports[i]; else if (!strcmp(info->ports[i]->name, "output-bluetooth_sco")) bluetooth_sco = info->ports[i]; else if (!strcmp(info->ports[i]->name, "output-speaker+wired_headphone")) speaker_and_wired_headphone = info->ports[i]; } if (!earpiece || !speaker) return; /* Not the right sink */ /* Refresh list of available audio modes */ modes.append(AudioModeEarpiece); modes.append(AudioModeSpeaker); if (wired_headset || wired_headphone) modes.append(AudioModeWiredHeadset); if (bluetooth_sco && ((m_bt_hsp != "") || (m_bt_hsp_a2dp != ""))) modes.append(AudioModeBluetooth); /* Check if the requested mode is available (earpiece*/ if (((m_audiomode == AudioModeWiredHeadset) && !modes.contains(AudioModeWiredHeadset)) || ((m_audiomode == AudioModeBluetooth) && !modes.contains(AudioModeBluetooth))) return; /* Now to decide which output to be used, depending on the active mode */ if (m_audiomode & AudioModeEarpiece) { preferred = earpiece; audiomodetoset = AudioModeEarpiece; } if (m_audiomode & AudioModeSpeaker) { preferred = speaker; audiomodetoset = AudioModeSpeaker; } if ((m_audiomode & AudioModeWiredHeadset) && (modes.contains(AudioModeWiredHeadset))) { preferred = wired_headset ? wired_headset : wired_headphone; audiomodetoset = AudioModeWiredHeadset; } if (m_callstatus == CallRinging && speaker_and_wired_headphone) { preferred = speaker_and_wired_headphone; } if ((m_audiomode & AudioModeBluetooth) && (modes.contains(AudioModeBluetooth))) { preferred = bluetooth_sco; audiomodetoset = AudioModeBluetooth; } m_audiomode = audiomodetoset; m_nametoset = info->name; if (info->active_port != preferred) m_valuetoset = preferred->name; if (modes != m_availableAudioModes) m_availableAudioModes = modes; } void QPulseAudioEngineWorker::sourceInfoCallback(const pa_source_info *info) { pa_source_port_info *builtin_mic = NULL, *preferred = NULL; pa_source_port_info *wired_headset = NULL, *bluetooth_sco = NULL; if (info->monitor_of_sink != PA_INVALID_INDEX) return; /* Not the right source */ for (int i = 0; i < info->n_ports; i++) { if (!strcmp(info->ports[i]->name, "input-builtin_mic")) builtin_mic = info->ports[i]; else if (!strcmp(info->ports[i]->name, "input-wired_headset") && (info->ports[i]->available != PA_PORT_AVAILABLE_NO)) wired_headset = info->ports[i]; else if (!strcmp(info->ports[i]->name, "input-bluetooth_sco_headset")) bluetooth_sco = info->ports[i]; } if (!builtin_mic) return; /* Not the right source */ /* Now to decide which output to be used, depending on the active mode */ if ((m_audiomode & AudioModeEarpiece) || (m_audiomode & AudioModeSpeaker)) preferred = builtin_mic; if ((m_audiomode & AudioModeWiredHeadset) && (m_availableAudioModes.contains(AudioModeWiredHeadset))) preferred = wired_headset ? wired_headset : builtin_mic; if ((m_audiomode & AudioModeBluetooth) && (m_availableAudioModes.contains(AudioModeBluetooth))) preferred = bluetooth_sco; m_nametoset = info->name; if (info->active_port != preferred) m_valuetoset = preferred->name; } void QPulseAudioEngineWorker::serverInfoCallback(const pa_server_info *info) { /* Saving default sink/source to restore after call hangup */ m_defaultsink = info->default_sink_name; m_defaultsource = info->default_source_name; /* In the case of a server callback we need to signal the mainloop */ pa_threaded_mainloop_signal(mainloop(), 0); } static void cardinfo_cb(pa_context *context, const pa_card_info *info, int isLast, void *userdata) { QPulseAudioEngineWorker *pulseEngine = static_cast(userdata); if (isLast != 0 || !pulseEngine || !info) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->cardInfoCallback(info); } static void sinkinfo_cb(pa_context *context, const pa_sink_info *info, int isLast, void *userdata) { QPulseAudioEngineWorker *pulseEngine = static_cast(userdata); if (isLast != 0 || !pulseEngine || !info) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->sinkInfoCallback(info); } static void sourceinfo_cb(pa_context *context, const pa_source_info *info, int isLast, void *userdata) { QPulseAudioEngineWorker *pulseEngine = static_cast(userdata); if (isLast != 0 || !pulseEngine || !info) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->sourceInfoCallback(info); } static void serverinfo_cb(pa_context *context, const pa_server_info *info, void *userdata) { QPulseAudioEngineWorker *pulseEngine = static_cast(userdata); if (!pulseEngine || !info) { pa_threaded_mainloop_signal(pulseEngine->mainloop(), 0); return; } pulseEngine->serverInfoCallback(info); } bool QPulseAudioEngineWorker::handleOperation(pa_operation *operation, const char *func_name) { if (!operation) { qCritical("'%s' failed (lost PulseAudio connection?)", func_name); /* Free resources so it can retry a new connection during next operation */ pa_threaded_mainloop_unlock(m_mainLoop); releasePulseContext(); return false; } while (pa_operation_get_state(operation) == PA_OPERATION_RUNNING) pa_threaded_mainloop_wait(m_mainLoop); pa_operation_unref(operation); return true; } int QPulseAudioEngineWorker::setupVoiceCall() { pa_operation *o; qDebug("Setting up pulseaudio for voice call"); pa_threaded_mainloop_lock(m_mainLoop); /* Get and set the default sink/source to be restored later */ o = pa_context_get_server_info(m_context, serverinfo_cb, this); if (!handleOperation(o, "pa_context_get_server_info")) return -1; qDebug("Recorded default sink: %s default source: %s", m_defaultsink.c_str(), m_defaultsource.c_str()); /* Walk through the list of devices, find the voice call capable card and * identify if we have bluetooth capable devices (hsp and a2dp) */ m_voicecallcard = m_voicecallhighest = m_voicecallprofile = ""; m_bt_hsp = m_bt_hsp_a2dp = ""; o = pa_context_get_card_info_list(m_context, cardinfo_cb, this); if (!handleOperation(o, "pa_context_get_card_info_list")) return -1; /* In case we have only one bt device that provides hsp and a2dp, we need * to make sure we switch the default profile for that card (to hsp) */ if ((m_bt_hsp_a2dp != "") && (m_bt_hsp == "")) { qDebug("Setting PulseAudio card '%s' profile '%s'", m_bt_hsp_a2dp.c_str(), PULSEAUDIO_PROFILE_HSP); o = pa_context_set_card_profile_by_name(m_context, m_bt_hsp_a2dp.c_str(), PULSEAUDIO_PROFILE_HSP, success_cb, this); if (!handleOperation(o, "pa_context_set_card_profile_by_name")) return -1; } pa_threaded_mainloop_unlock(m_mainLoop); return 0; } void QPulseAudioEngineWorker::restoreVoiceCall() { pa_operation *o; qDebug("Restoring pulseaudio previous state"); /* Then restore previous settings */ pa_threaded_mainloop_lock(m_mainLoop); /* See if we need to restore any HSP+AD2P device state */ if ((m_bt_hsp_a2dp != "") && (m_bt_hsp == "")) { qDebug("Restoring PulseAudio card '%s' to profile '%s'", m_bt_hsp_a2dp.c_str(), PULSEAUDIO_PROFILE_A2DP); o = pa_context_set_card_profile_by_name(m_context, m_bt_hsp_a2dp.c_str(), PULSEAUDIO_PROFILE_A2DP, success_cb, this); if (!handleOperation(o, "pa_context_set_card_profile_by_name")) return; } /* Restore default sink/source */ if (m_defaultsink != "") { qDebug("Restoring PulseAudio default sink to '%s'", m_defaultsink.c_str()); o = pa_context_set_default_sink(m_context, m_defaultsink.c_str(), success_cb, this); if (!handleOperation(o, "pa_context_set_default_sink")) return; } if (m_defaultsource != "") { qDebug("Restoring PulseAudio default source to '%s'", m_defaultsource.c_str()); o = pa_context_set_default_source(m_context, m_defaultsource.c_str(), success_cb, this); if (!handleOperation(o, "pa_context_set_default_source")) return; } pa_threaded_mainloop_unlock(m_mainLoop); } void QPulseAudioEngineWorker::setCallMode(CallStatus callstatus, AudioMode audiomode) { if (!createPulseContext()) { return; } CallStatus p_callstatus = m_callstatus; AudioMode p_audiomode = m_audiomode; AudioModes p_availableAudioModes = m_availableAudioModes; pa_operation *o; /* Check if we need to save the current pulseaudio state (e.g. when starting a call) */ if ((callstatus != CallEnded) && (p_callstatus == CallEnded)) { if (setupVoiceCall() < 0) { qCritical("Failed to setup PulseAudio for Voice Call"); return; } } /* If we have an active call, update internal state (used later when updating sink/source ports) */ m_callstatus = callstatus; m_audiomode = audiomode; pa_threaded_mainloop_lock(m_mainLoop); /* Switch the virtual card mode when call is active and not active * This needs to be done before sink/source gets updated, because after changing mode * it will automatically move to input/output-parking */ if ((m_callstatus == CallActive) && (p_callstatus != CallActive) && (m_voicecallcard != "") && (m_voicecallprofile != "")) { qDebug("Setting PulseAudio card '%s' profile '%s'", m_voicecallcard.c_str(), m_voicecallprofile.c_str()); o = pa_context_set_card_profile_by_name(m_context, m_voicecallcard.c_str(), m_voicecallprofile.c_str(), success_cb, this); if (!handleOperation(o, "pa_context_set_card_profile_by_name")) return; } else if ((m_callstatus == CallEnded) && (m_voicecallcard != "") && (m_voicecallhighest != "")) { /* If using droid, make sure to restore to the profile that has the highest score */ qDebug("Restoring PulseAudio card '%s' to profile '%s'", m_voicecallcard.c_str(), m_voicecallhighest.c_str()); o = pa_context_set_card_profile_by_name(m_context, m_voicecallcard.c_str(), m_voicecallhighest.c_str(), success_cb, this); if (!handleOperation(o, "pa_context_set_card_profile_by_name")) return; } /* Find highest compatible sink/source elements from the voicecall compatible card (on touch this means the pulse droid element) */ m_nametoset = m_valuetoset = ""; o = pa_context_get_sink_info_list(m_context, sinkinfo_cb, this); if (!handleOperation(o, "pa_context_get_sink_info_list")) return; if ((m_nametoset != "") && (m_nametoset != m_defaultsink)) { qDebug("Setting PulseAudio default sink to '%s'", m_nametoset.c_str()); o = pa_context_set_default_sink(m_context, m_nametoset.c_str(), success_cb, this); if (!handleOperation(o, "pa_context_set_default_sink")) return; } if (m_valuetoset != "") { qDebug("Setting PulseAudio sink '%s' port '%s'", m_nametoset.c_str(), m_valuetoset.c_str()); o = pa_context_set_sink_port_by_name(m_context, m_nametoset.c_str(), m_valuetoset.c_str(), success_cb, this); if (!handleOperation(o, "pa_context_set_sink_port_by_name")) return; } /* Same for source */ m_nametoset = m_valuetoset = ""; o = pa_context_get_source_info_list(m_context, sourceinfo_cb, this); if (!handleOperation(o, "pa_context_get_source_info_list")) return; if ((m_nametoset != "") && (m_nametoset != m_defaultsource)) { qDebug("Setting PulseAudio default source to '%s'", m_nametoset.c_str()); o = pa_context_set_default_source(m_context, m_nametoset.c_str(), success_cb, this); if (!handleOperation(o, "pa_context_set_default_source")) return; } if (m_valuetoset != "") { qDebug("Setting PulseAudio source '%s' port '%s'", m_nametoset.c_str(), m_valuetoset.c_str()); o = pa_context_set_source_port_by_name(m_context, m_nametoset.c_str(), m_valuetoset.c_str(), success_cb, this); if (!handleOperation(o, "pa_context_set_source_port_by_name")) return; } pa_threaded_mainloop_unlock(m_mainLoop); /* Notify if the list of audio modes changed */ if (p_availableAudioModes != m_availableAudioModes) Q_EMIT availableAudioModesChanged(m_availableAudioModes); /* Notify if call mode changed */ if (p_audiomode != m_audiomode) { Q_EMIT audioModeChanged(m_audiomode); } /* If no more active voicecall, restore previous saved pulseaudio state */ if (callstatus == CallEnded) { restoreVoiceCall(); } /* In case the app had set mute when the call wasn't active, make sure we reflect it here */ if (m_callstatus != CallEnded) setMicMute(m_micmute); } void QPulseAudioEngineWorker::setMicMute(bool muted) { if (!createPulseContext()) { return; } m_micmute = muted; if (m_callstatus == CallEnded) return; pa_threaded_mainloop_lock(m_mainLoop); m_nametoset = ""; pa_operation *o = pa_context_get_source_info_list(m_context, sourceinfo_cb, this); if (!handleOperation(o, "pa_context_get_source_info_list")) return; if (m_nametoset != "") { int m = m_micmute ? 1 : 0; qDebug("Setting PulseAudio source '%s' muted '%d'", m_nametoset.c_str(), m); o = pa_context_set_source_mute_by_name(m_context, m_nametoset.c_str(), m, success_cb, this); if (!handleOperation(o, "pa_context_set_source_mute_by_name")) return; } pa_threaded_mainloop_unlock(m_mainLoop); } void QPulseAudioEngineWorker::plugCardCallback(const pa_card_info *info) { qDebug("Notified about card (%s) add event from PulseAudio", info->name); /* We only care about BT (HSP) devices, and if one is not already available */ if ((m_callstatus != CallEnded) && ((m_bt_hsp == "") || (m_bt_hsp_a2dp == ""))) { /* Check if it's indeed a BT device (with at least one hsp profile) */ pa_card_profile_info *hsp = NULL; for (int i = 0; i < info->n_profiles; i++) { if (!strcmp(info->profiles[i].name, PULSEAUDIO_PROFILE_HSP)) hsp = &info->profiles[i]; } if (hsp) m_handleevent = true; } } void QPulseAudioEngineWorker::updateCardCallback(const pa_card_info *info) { qDebug("Notified about card (%s) changes event from PulseAudio", info->name); /* We only care if the card event for the voicecall capable card */ if ((m_callstatus == CallActive) && (!strcmp(info->name, m_voicecallcard.c_str()))) { if (m_audiomode == AudioModeWiredHeadset) { /* If previous mode is wired, it means it got unplugged */ m_handleevent = true; m_audiomodetoset = AudioModeBtOrWiredOrEarpiece; } else if ((m_audiomode == AudioModeEarpiece) || ((m_audiomode == AudioModeSpeaker))) { /* Now only trigger the event in case wired headset/headphone is now available */ pa_card_port_info *port_info = NULL; for (int i = 0; i < info->n_ports; i++) { if (info->ports[i] && (info->ports[i]->available == PA_PORT_AVAILABLE_YES) && ( !strcmp(info->ports[i]->name, "output-wired_headset") || !strcmp(info->ports[i]->name, "output-wired_headphone"))) { m_handleevent = true; m_audiomodetoset = AudioModeWiredOrEarpiece; } } } else if (m_audiomode == AudioModeBluetooth) { /* Handle the event so we can update the audiomodes */ m_handleevent = true; m_audiomodetoset = AudioModeBluetooth; } } } void QPulseAudioEngineWorker::unplugCardCallback() { if (m_callstatus != CallEnded) { m_handleevent = true; } } void QPulseAudioEngineWorker::handleCardEvent(const int evt, const unsigned int idx) { pa_operation *o = NULL; /* Internal state var used to know if we need to update our internal state */ m_handleevent = false; if (evt == PA_SUBSCRIPTION_EVENT_NEW) { o = pa_context_get_card_info_by_index(m_context, idx, plug_card_cb, this); if (!handleOperation(o, "pa_context_get_card_info_by_index")) return; if (m_handleevent) { qDebug("Adding new BT-HSP capable device"); /* In case A2DP is available, switch to HSP */ if (setupVoiceCall() < 0) return; /* Enable the HSP output port */ setCallMode(m_callstatus, AudioModeBluetooth); } } else if (evt == PA_SUBSCRIPTION_EVENT_CHANGE) { o = pa_context_get_card_info_by_index(m_context, idx, update_card_cb, this); if (!handleOperation(o, "pa_context_get_card_info_by_index")) return; if (m_handleevent) { /* In this case it means the handset state changed */ qDebug("Notifying card changes for the voicecall capable card"); setCallMode(m_callstatus, m_audiomodetoset); } } else if (evt == PA_SUBSCRIPTION_EVENT_REMOVE) { /* Check if the main HSP card was removed */ if (m_bt_hsp != "") { o = pa_context_get_card_info_by_name(m_context, m_bt_hsp.c_str(), unplug_card_cb, this); if (!handleOperation(o, "pa_context_get_sink_info_by_name")) return; } if (m_bt_hsp_a2dp != "") { o = pa_context_get_card_info_by_name(m_context, m_bt_hsp_a2dp.c_str(), unplug_card_cb, this); if (!handleOperation(o, "pa_context_get_sink_info_by_name")) return; } if (m_handleevent) { qDebug("Notifying about BT-HSP card removal"); /* Needed in order to save the default sink/source */ if (setupVoiceCall() < 0) return; /* Enable the default handset output port */ setCallMode(m_callstatus, AudioModeWiredOrEarpiece); } } } Q_GLOBAL_STATIC(QPulseAudioEngine, pulseEngine); QPulseAudioEngine::QPulseAudioEngine(QObject *parent) : QObject(parent) { qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); mWorker = new QPulseAudioEngineWorker(); QObject::connect(mWorker, SIGNAL(audioModeChanged(const AudioMode)), this, SIGNAL(audioModeChanged(const AudioMode)), Qt::QueuedConnection); QObject::connect(mWorker, SIGNAL(availableAudioModesChanged(const AudioModes)), this, SIGNAL(availableAudioModesChanged(const AudioModes)), Qt::QueuedConnection); mWorker->createPulseContext(); mWorker->moveToThread(&mThread); mThread.start(); } QPulseAudioEngine::~QPulseAudioEngine() { mThread.quit(); mThread.wait(); } QPulseAudioEngine *QPulseAudioEngine::instance() { QPulseAudioEngine *engine = pulseEngine(); return engine; } void QPulseAudioEngine::setCallMode(CallStatus callstatus, AudioMode audiomode) { QMetaObject::invokeMethod(mWorker, "setCallMode", Qt::QueuedConnection, Q_ARG(CallStatus, callstatus), Q_ARG(AudioMode, audiomode)); } void QPulseAudioEngine::setMicMute(bool muted) { QMetaObject::invokeMethod(mWorker, "setMicMute", Qt::QueuedConnection, Q_ARG(bool, muted)); } QT_END_NAMESPACE telepathy-ofono-0.2+16.04.20151120/ofonotextchannel.h0000644000015300001610000000566112623675611022565 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef OFONOTEXTCHANNEL_H #define OFONOTEXTCHANNEL_H #include #include #include #include #include #include "connection.h" class oFonoConnection; class oFonoTextChannel : public QObject { Q_OBJECT public: oFonoTextChannel(oFonoConnection *conn, QStringList phoneNumbers, bool flash = false, QObject *parent = 0); QString sendMessage(Tp::MessagePartList message, uint flags, Tp::DBusError* error); void messageReceived(const QString & message, uint handle, const QVariantMap &info); Tp::BaseChannelPtr baseChannel(); void messageAcknowledged(const QString &id); void mmsReceived(const QString &id, uint handle, const QVariantMap &properties); void deliveryReportReceived(const QString& messageId, uint handle, bool success); void sendDeliveryReport(const QString &messageId, uint handle, Tp::DeliveryStatus status); void addMembers(QStringList phoneNumbers); Tp::UIntList members(); void onAddMembers(const Tp::UIntList& handles, const QString& message, Tp::DBusError* error); void onRemoveMembers(const Tp::UIntList& handles, const QString& message, Tp::DBusError* error); private Q_SLOTS: void onMMSPropertyChanged(QString property, QVariant value); void onOfonoMessageStateChanged(QString status); void onProcessPendingDeliveryReport(); Q_SIGNALS: void messageRead(const QString &id); private: ~oFonoTextChannel(); Tp::BaseChannelPtr mBaseChannel; QStringList mPhoneNumbers; oFonoConnection *mConnection; Tp::BaseChannelMessagesInterfacePtr mMessagesIface; Tp::BaseChannelGroupInterfacePtr mGroupIface; Tp::BaseChannelSMSInterfacePtr mSMSIface; Tp::BaseChannelTextTypePtr mTextChannel; uint mMessageCounter; QMap mPendingDeliveryReportTemporarilyFailed; QMap mPendingDeliveryReportPermanentlyFailed; QMap mPendingDeliveryReportAccepted; QMap mPendingDeliveryReportDelivered; QMap mPendingDeliveryReportUnknown; Tp::UIntList mMembers; QMap mFilesToRemove; bool mFlash; }; #endif // OFONOTEXTCHANNEL_H telepathy-ofono-0.2+16.04.20151120/audiooutputsiface.cpp0000644000015300001610000001257412623675611023300 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include #include "audiooutputsiface.h" QDBusArgument &operator<<(QDBusArgument &argument, const AudioOutput &output) { argument.beginStructure(); argument << output.id << output.type << output.name; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, AudioOutput &output) { argument.beginStructure(); argument >> output.id >> output.type >> output.name; argument.endStructure(); return argument; } // Chan.I.AudioOutputs BaseChannelAudioOutputsInterface::Adaptee::Adaptee(BaseChannelAudioOutputsInterface *interface) : QObject(interface), mInterface(interface) { qDBusRegisterMetaType(); qDBusRegisterMetaType(); } struct TP_QT_NO_EXPORT BaseChannelAudioOutputsInterface::Private { Private(BaseChannelAudioOutputsInterface *parent) : adaptee(new BaseChannelAudioOutputsInterface::Adaptee(parent)) { } AudioOutputList audioOutputs; QString activeAudioOutput; SetActiveAudioOutputCallback setActiveAudioOutputCB; BaseChannelAudioOutputsInterface::Adaptee *adaptee; }; BaseChannelAudioOutputsInterface::Adaptee::~Adaptee() { } void BaseChannelAudioOutputsInterface::Adaptee::setActiveAudioOutput(const QString &id, const ChannelInterfaceAudioOutputsAdaptor::SetActiveAudioOutputContextPtr &context) { if (!mInterface->mPriv->setActiveAudioOutputCB.isValid()) { context->setFinishedWithError(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented")); return; } Tp::DBusError error; mInterface->mPriv->setActiveAudioOutputCB(id, &error); if (error.isValid()) { context->setFinishedWithError(error.name(), error.message()); return; } context->setFinished(); } BaseChannelAudioOutputsInterface::BaseChannelAudioOutputsInterface() : AbstractChannelInterface(TP_QT_IFACE_CHANNEL_AUDIOOUTPUTS), mPriv(new Private(this)) { } BaseChannelAudioOutputsInterface::~BaseChannelAudioOutputsInterface() { delete mPriv; } QString BaseChannelAudioOutputsInterface::activeAudioOutput() const { return mPriv->activeAudioOutput; } AudioOutputList BaseChannelAudioOutputsInterface::audioOutputs() const { return mPriv->audioOutputs; } void BaseChannelAudioOutputsInterface::setSetActiveAudioOutputCallback(const SetActiveAudioOutputCallback &cb) { mPriv->setActiveAudioOutputCB = cb; } void BaseChannelAudioOutputsInterface::setActiveAudioOutput(const QString &id) { mPriv->activeAudioOutput = id; Q_EMIT mPriv->adaptee->activeAudioOutputChanged(id); } void BaseChannelAudioOutputsInterface::setAudioOutputs(const AudioOutputList &outputs) { mPriv->audioOutputs = outputs; Q_EMIT mPriv->adaptee->audioOutputsChanged(outputs); } QVariantMap BaseChannelAudioOutputsInterface::immutableProperties() const { QVariantMap map; return map; } void BaseChannelAudioOutputsInterface::createAdaptor() { (void) new ChannelInterfaceAudioOutputsAdaptor(dbusObject()->dbusConnection(), mPriv->adaptee, dbusObject()); } ChannelInterfaceAudioOutputsAdaptor::ChannelInterfaceAudioOutputsAdaptor(const QDBusConnection& bus, QObject* adaptee, QObject* parent) : Tp::AbstractAdaptor(bus, adaptee, parent) { connect(adaptee, SIGNAL(audioOutputsChanged(AudioOutputList)), SIGNAL(AudioOutputsChanged(AudioOutputList))); connect(adaptee, SIGNAL(activeAudioOutputChanged(QString)), SIGNAL(ActiveAudioOutputChanged(QString))); } ChannelInterfaceAudioOutputsAdaptor::~ChannelInterfaceAudioOutputsAdaptor() { } void ChannelInterfaceAudioOutputsAdaptor::SetActiveAudioOutput(const QString &id, const QDBusMessage& dbusMessage) { if (!adaptee()->metaObject()->indexOfMethod("setActiveAudioOutput(QString,ChannelInterfaceAudioOutputsAdaptor::SetActiveAudioOutputContextPtr)") == -1) { dbusConnection().send(dbusMessage.createErrorReply(TP_QT_ERROR_NOT_IMPLEMENTED, QLatin1String("Not implemented"))); return; } SetActiveAudioOutputContextPtr ctx = SetActiveAudioOutputContextPtr( new Tp::MethodInvocationContext< >(dbusConnection(), dbusMessage)); QMetaObject::invokeMethod(adaptee(), "setActiveAudioOutput", Q_ARG(QString, id), Q_ARG(ChannelInterfaceAudioOutputsAdaptor::SetActiveAudioOutputContextPtr, ctx)); return; } QString ChannelInterfaceAudioOutputsAdaptor::ActiveAudioOutput() const { return qvariant_cast< QString >(adaptee()->property("activeAudioOutput")); } AudioOutputList ChannelInterfaceAudioOutputsAdaptor::AudioOutputs() const { return qvariant_cast< AudioOutputList >(adaptee()->property("audioOutputs")); } telepathy-ofono-0.2+16.04.20151120/schema/0000755000015300001610000000000012623676450020270 5ustar pbuserpbgroup00000000000000telepathy-ofono-0.2+16.04.20151120/schema/CMakeLists.txt0000644000015300001610000000077712623675611023041 0ustar pbuserpbgroup00000000000000file(GLOB SCHEMA_FILES ${CMAKE_CURRENT_SOURCE_DIR}/v*.sql) set(SCHEMA_FILE ${CMAKE_CURRENT_SOURCE_DIR}/schema.sql) set(VERSION_FILE ${CMAKE_CURRENT_SOURCE_DIR}/version.info) add_custom_command( OUTPUT ${SCHEMA_FILE} ${VERSION_FILE} COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/update_schema.sh ${CMAKE_CURRENT_SOURCE_DIR} ${SCHEMA_FILE} ${VERSION_FILE} WORKING DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} DEPENDS ${SCHEMA_FILES} ) add_custom_target(schema_update DEPENDS ${SCHEMA_FILE} ${VERSION_FILE}) telepathy-ofono-0.2+16.04.20151120/schema/update_schema.sh0000755000015300001610000000100212623675611023420 0ustar pbuserpbgroup00000000000000#!/bin/sh if [ $# -lt 3 ]; then echo "Usage: $0 " fi SOURCE_DIR=$1 TARGET_FILE=$2 VERSION_FILE=$3 VERSION="1" LATEST_VERSION="1" TMPFILE=`tempfile` SCHEMA_FILE="$SOURCE_DIR/v${VERSION}.sql" while [ -e $SCHEMA_FILE ]; do cat $SCHEMA_FILE >> $TMPFILE LATEST_VERSION=$VERSION VERSION=$(($VERSION+1)) SCHEMA_FILE="$SOURCE_DIR/v${VERSION}.sql" done sqlite3 -init $TMPFILE :memory: .schema > $TARGET_FILE echo $LATEST_VERSION > $VERSION_FILE telepathy-ofono-0.2+16.04.20151120/schema/v1.sql0000644000015300001610000000024612623675611021337 0ustar pbuserpbgroup00000000000000CREATE TABLE schema_version ( version int ); CREATE TABLE pending_messages ( messageId varchar(255), recipientId varchar(255), timestamp datetime ); telepathy-ofono-0.2+16.04.20151120/sqlitedatabase.cpp0000644000015300001610000001551312623675611022525 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Gustavo Pichorim Boiko */ #include "phoneutils_p.h" #include "sqlite3.h" #include "sqlitedatabase.h" #include #include #include #include #include #include #include Q_DECLARE_OPAQUE_POINTER(sqlite3*) Q_DECLARE_METATYPE(sqlite3*) // custom sqlite function "comparePhoneNumbers" used to compare IDs if necessary void comparePhoneNumbers(sqlite3_context *context, int argc, sqlite3_value **argv) { QString arg1((const char*)sqlite3_value_text(argv[0])); QString arg2((const char*)sqlite3_value_text(argv[1])); sqlite3_result_int(context, (int)PhoneUtils::comparePhoneNumbers(arg1, arg2)); } SQLiteDatabase::SQLiteDatabase(QObject *parent) : QObject(parent), mSchemaVersion(0) { initializeDatabase(); } SQLiteDatabase *SQLiteDatabase::instance() { static SQLiteDatabase *self = new SQLiteDatabase(); return self; } bool SQLiteDatabase::initializeDatabase() { mDatabasePath = qgetenv("TP_OFONO_SQLITE_DBPATH"); if (mDatabasePath.isEmpty()) { mDatabasePath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation); QDir dir(mDatabasePath); if (!dir.exists("telepathy-ofono") && !dir.mkpath("telepathy-ofono")) { qCritical() << "Failed to create dir"; return false; } dir.cd("telepathy-ofono"); mDatabasePath = dir.absoluteFilePath("telepathy-ofono.sqlite"); } mDatabase = QSqlDatabase::addDatabase("QSQLITE"); mDatabase.setDatabaseName(mDatabasePath); // always run the createDatabase function at least during the development if (!createOrUpdateDatabase()) { qCritical() << "Failed to create or update the database"; return false; } return true; } QSqlDatabase SQLiteDatabase::database() const { return mDatabase; } bool SQLiteDatabase::beginTransation() { return mDatabase.transaction(); } bool SQLiteDatabase::finishTransaction() { return mDatabase.commit(); } bool SQLiteDatabase::rollbackTransaction() { return mDatabase.rollback(); } /// this method is to be used mainly by unit tests in order to clean up the database between /// tests. bool SQLiteDatabase::reopen() { mDatabase.close(); mDatabase.open(); // make sure the database is up-to-date after reopening. // this is mainly required for the memory backend used for testing createOrUpdateDatabase(); } bool SQLiteDatabase::createOrUpdateDatabase() { bool create = !QFile(mDatabasePath).exists(); if (!mDatabase.open()) { return false; } // create the comparePhoneNumbers custom sqlite function sqlite3 *handle = database().driver()->handle().value(); sqlite3_create_function(handle, "comparePhoneNumbers", 2, SQLITE_ANY, NULL, &comparePhoneNumbers, NULL, NULL); parseVersionInfo(); QSqlQuery query(mDatabase); QStringList statements; if (create) { statements = parseSchemaFile(":/database/schema/schema.sql"); } else { // if the database already exists, we don´t need to create the tables // only check if an update is needed query.exec("SELECT * FROM schema_version"); if (!query.exec() || !query.next()) { return false; } int upgradeToVersion = query.value(0).toInt() + 1; while (upgradeToVersion <= mSchemaVersion) { statements += parseSchemaFile(QString(":/database/schema/v%1.sql").arg(QString::number(upgradeToVersion))); ++upgradeToVersion; } } // if at this point needsUpdate is still false, it means the database is up-to-date if (statements.isEmpty()) { return true; } beginTransation(); Q_FOREACH(const QString &statement, statements) { if (!query.exec(statement)) { qCritical() << "Failed to create or update database. SQL Statements:" << query.lastQuery() << "Error:" << query.lastError(); rollbackTransaction(); return false; } } // now set the new database schema version if (!query.exec("DELETE FROM schema_version")) { qCritical() << "Failed to remove previous schema versions. SQL Statement:" << query.lastQuery() << "Error:" << query.lastError(); rollbackTransaction(); return false; } if (!query.exec(QString("INSERT INTO schema_version VALUES (%1)").arg(mSchemaVersion))) { qCritical() << "Failed to insert new schema version. SQL Statement:" << query.lastQuery() << "Error:" << query.lastError(); rollbackTransaction(); return false; } finishTransaction(); return true; } QStringList SQLiteDatabase::parseSchemaFile(const QString &fileName) { QFile schema(fileName); if (!schema.open(QFile::ReadOnly)) { qCritical() << "Failed to open " << fileName; return QStringList(); } bool parsingBlock = false; QString statement; QStringList statements; // FIXME: this parser is very basic, it needs to be improved in the future // it does a lot of assumptions based on the structure of the schema.sql file QTextStream stream(&schema); while (!stream.atEnd()) { QString line = stream.readLine(); bool statementEnded = false; statement += line; // check if we are parsing a trigger command if (line.trimmed().startsWith("CREATE TRIGGER", Qt::CaseInsensitive)) { parsingBlock = true; } else if (parsingBlock) { if (line.contains("END;")) { parsingBlock = false; statementEnded = true; } } else if (statement.contains(";")) { statementEnded = true; } statement += "\n"; if (statementEnded) { statements.append(statement); statement.clear(); } } return statements; } void SQLiteDatabase::parseVersionInfo() { QFile schema(":/database/schema/version.info"); if (!schema.open(QFile::ReadOnly)) { qDebug() << schema.error(); qCritical() << "Failed to get database version"; } QString version = schema.readAll(); mSchemaVersion = version.toInt(); } telepathy-ofono-0.2+16.04.20151120/qpulseaudioengine.h0000644000015300001610000000750412623675611022726 0ustar pbuserpbgroup00000000000000/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file was taken from qt5 and modified by ** David Henningsson for usage in ** telepathy-ofono. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #ifndef QPULSEAUDIOENGINE_H #define QPULSEAUDIOENGINE_H #include #include #include #include enum AudioMode { AudioModeEarpiece = 0x0001, AudioModeWiredHeadset = 0x0002, AudioModeSpeaker = 0x0004, AudioModeBluetooth = 0x0008, AudioModeBtOrWiredOrEarpiece = AudioModeBluetooth | AudioModeWiredHeadset | AudioModeEarpiece, AudioModeWiredOrEarpiece = AudioModeWiredHeadset | AudioModeEarpiece, AudioModeWiredOrSpeaker = AudioModeWiredHeadset | AudioModeSpeaker }; Q_DECLARE_METATYPE(AudioMode) typedef QList AudioModes; Q_DECLARE_METATYPE(AudioModes) enum CallStatus { CallRinging, CallActive, CallEnded }; Q_DECLARE_METATYPE(CallStatus) QT_BEGIN_NAMESPACE class QPulseAudioEngineWorker : public QObject { Q_OBJECT public: QPulseAudioEngineWorker(QObject *parent = 0); ~QPulseAudioEngineWorker(); pa_threaded_mainloop *mainloop() { return m_mainLoop; } pa_context *context() { return m_context; } bool createPulseContext(void); int setupVoiceCall(void); void restoreVoiceCall(void); /* Callbacks to be used internally */ void cardInfoCallback(const pa_card_info *card); void sinkInfoCallback(const pa_sink_info *sink); void sourceInfoCallback(const pa_source_info *source); void serverInfoCallback(const pa_server_info *server); void plugCardCallback(const pa_card_info *card); void updateCardCallback(const pa_card_info *card); void unplugCardCallback(); Q_SIGNALS: void audioModeChanged(const AudioMode mode); void availableAudioModesChanged(const AudioModes modes); public Q_SLOTS: void handleCardEvent(const int evt, const unsigned int idx); void setCallMode(CallStatus callstatus, AudioMode audiomode); void setMicMute(bool muted); /* True if muted, false if unmuted */ private: pa_mainloop_api *m_mainLoopApi; pa_threaded_mainloop *m_mainLoop; pa_context *m_context; AudioModes m_availableAudioModes; CallStatus m_callstatus; AudioMode m_audiomode; AudioMode m_audiomodetoset; bool m_micmute, m_handleevent; std::string m_nametoset, m_valuetoset; std::string m_defaultsink, m_defaultsource; std::string m_bt_hsp, m_bt_hsp_a2dp; std::string m_voicecallcard, m_voicecallhighest, m_voicecallprofile; bool handleOperation(pa_operation *operation, const char *func_name); void releasePulseContext(void); }; class QPulseAudioEngine : public QObject { Q_OBJECT public: explicit QPulseAudioEngine(QObject *parent = 0); ~QPulseAudioEngine(); static QPulseAudioEngine *instance(); void setCallMode(CallStatus callstatus, AudioMode audiomode); void setMicMute(bool muted); /* True if muted, false if unmuted */ Q_SIGNALS: void audioModeChanged(const AudioMode mode); void availableAudioModesChanged(const AudioModes modes); private: QPulseAudioEngineWorker *mWorker; QThread mThread; }; QT_END_NAMESPACE #endif telepathy-ofono-0.2+16.04.20151120/mc-plugin/0000755000015300001610000000000012623676450020723 5ustar pbuserpbgroup00000000000000telepathy-ofono-0.2+16.04.20151120/mc-plugin/mcp-account-manager-ofono.h0000644000015300001610000000267112623675611026037 0ustar pbuserpbgroup00000000000000#ifndef __MCP_ACCOUNT_MANAGER_OFONO_H__ #define __MCP_ACCOUNT_MANAGER_OFONO_H__ #include G_BEGIN_DECLS #define MCP_TYPE_ACCOUNT_MANAGER_OFONO \ (mcp_account_manager_ofono_get_type ()) #define MCP_ACCOUNT_MANAGER_OFONO(o) \ (G_TYPE_CHECK_INSTANCE_CAST ((o), MCP_TYPE_ACCOUNT_MANAGER_OFONO, \ McpAccountManagerOfono)) #define MCP_ACCOUNT_MANAGER_OFONO_CLASS(k) \ (G_TYPE_CHECK_CLASS_CAST((k), MCP_TYPE_ACCOUNT_MANAGER_OFONO, \ McpAccountManagerOfonoClass)) #define MCP_IS_ACCOUNT_MANAGER_OFONO(o) \ (G_TYPE_CHECK_INSTANCE_TYPE ((o), MCP_TYPE_ACCOUNT_MANAGER_OFONO)) #define MCP_IS_ACCOUNT_MANAGER_OFONO_CLASS(k) \ (G_TYPE_CHECK_CLASS_TYPE ((k), MCP_TYPE_ACCOUNT_MANAGER_OFONO)) #define MCP_ACCOUNT_MANAGER_OFONO_GET_CLASS(o) \ (G_TYPE_INSTANCE_GET_CLASS ((o), MCP_TYPE_ACCOUNT_MANAGER_OFONO, \ McpAccountManagerOfonoClass)) typedef struct _McpAccountManagerOfonoPrivate McpAccountManagerOfonoPrivate; typedef struct { GObject parent; McpAccountManagerOfonoPrivate *priv; } _McpAccountManagerOfono; typedef struct { GObjectClass parent_class; } _McpAccountManagerOfonoClass; typedef _McpAccountManagerOfono McpAccountManagerOfono; typedef _McpAccountManagerOfonoClass McpAccountManagerOfonoClass; GType mcp_account_manager_ofono_get_type (void) G_GNUC_CONST; McpAccountManagerOfono *mcp_account_manager_ofono_new (void); G_END_DECLS #endif telepathy-ofono-0.2+16.04.20151120/mc-plugin/CMakeLists.txt0000644000015300001610000000132212623675611023457 0ustar pbuserpbgroup00000000000000set(MCP_ACCOUNT_MANAGER_NAME mcp-account-manager-ofono) set(MC_PLUGIN_SRC mcp-account-manager-ofono.c mission-control-plugin.c ) set(MC_PLUGIN_HDRS mcp-account-manager-ofono.h ) execute_process(COMMAND pkg-config --variable=plugindir mission-control-plugins OUTPUT_VARIABLE MC_PLUGINS_DIR) string(REPLACE "\n" "" MC_PLUGINS_DIR ${MC_PLUGINS_DIR}) include_directories(${MC_PLUGINS_INCLUDE_DIRS}) add_library(${MCP_ACCOUNT_MANAGER_NAME} SHARED ${MC_PLUGIN_SRC} ${MC_PLUGIN_HDRS}) set_target_properties(${MCP_ACCOUNT_MANAGER_NAME} PROPERTIES PREFIX "") target_link_libraries(${MCP_ACCOUNT_MANAGER_NAME} ${MC_PLUGINS_LIBRARIES}) install(TARGETS ${MCP_ACCOUNT_MANAGER_NAME} DESTINATION ${MC_PLUGINS_DIR}) telepathy-ofono-0.2+16.04.20151120/mc-plugin/mission-control-plugin.c0000644000015300001610000000230312623675611025516 0ustar pbuserpbgroup00000000000000/* * Copyright (C) 2012 Jolla Ltd. * Contact: John Brooks * * 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, see . */ #include #include "mcp-account-manager-ofono.h" GObject * mcp_plugin_ref_nth_object (guint n) { static void *plugin_0 = NULL; switch (n) { case 0: if (plugin_0 == NULL) { plugin_0 = g_object_new (MCP_TYPE_ACCOUNT_MANAGER_OFONO, NULL); } else { g_object_ref (plugin_0); } return plugin_0; default: return NULL; } } telepathy-ofono-0.2+16.04.20151120/mc-plugin/mcp-account-manager-ofono.c0000644000015300001610000003036012623675611026026 0ustar pbuserpbgroup00000000000000/* * Copyright (C) 2015 Canonical, Ltd. * Contact: Tiago Salem Herrmann * * Based on Empathy ubuntu-online-accounts, mcp-account-manager-ring: * Contact: John Brooks * Copyright (C) 2012 Jolla Ltd. * Copyright (C) 2012 Collabora Ltd. * * 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, see . */ #include #include #include #include #include #include "mcp-account-manager-ofono.h" #define PLUGIN_NAME "ofono-account" #define PLUGIN_PRIORITY (MCP_ACCOUNT_STORAGE_PLUGIN_PRIO_DEFAULT - 10) #define PLUGIN_DESCRIPTION "Provide ril modem accounts for telepathy-ofono" #define PLUGIN_PROVIDER "im.telepathy.Account.Storage.Ofono" static void account_storage_iface_init(McpAccountStorageIface *iface); G_DEFINE_TYPE_WITH_CODE (McpAccountManagerOfono, mcp_account_manager_ofono, G_TYPE_OBJECT, G_IMPLEMENT_INTERFACE (MCP_TYPE_ACCOUNT_STORAGE, account_storage_iface_init)); struct ofono_account { gchar *account_name; int index; GHashTable *params; }; typedef struct ofono_account OfonoAccount; struct _McpAccountManagerOfonoPrivate { GList *accounts; }; void free_ofono_struct (gpointer data) { OfonoAccount *account = (OfonoAccount*)data; g_hash_table_unref(account->params); g_free(account->account_name); } static void mcp_account_manager_ofono_dispose(GObject *object) { McpAccountManagerOfono *self = (McpAccountManagerOfono*) object; g_list_free_full(self->priv->accounts, free_ofono_struct); G_OBJECT_CLASS (mcp_account_manager_ofono_parent_class)->dispose(object); } static void mcp_account_manager_ofono_init(McpAccountManagerOfono *self) { g_debug("MC ril ofono accounts plugin initialized"); gchar *output = NULL; gchar *output2 = NULL; const gchar *force_num_modems = g_getenv("FORCE_RIL_NUM_MODEMS"); GError *error = NULL; int num_modems = 0; int index; setlocale(LC_ALL, ""); self->priv = G_TYPE_INSTANCE_GET_PRIVATE(self, MCP_TYPE_ACCOUNT_MANAGER_OFONO, McpAccountManagerOfonoPrivate); if (force_num_modems) { num_modems = atoi(force_num_modems); g_debug("forced number of modems: %d", num_modems); } else { if (!g_file_test ("/usr/bin/getprop", G_FILE_TEST_IS_EXECUTABLE)) { return; } if (!g_spawn_command_line_sync("/usr/bin/getprop rild.libpath ''", &output, NULL, NULL, &error)) { g_debug("%s", error->message); g_error_free (error); return; } if (strlen(g_strstrip(output)) != 0) { g_spawn_command_line_sync("/usr/bin/getprop ril.num_slots 1", &output2, NULL, NULL, &error); num_modems = atoi(output2); } } GSettings *settings = NULL; GSettingsSchemaSource *source = g_settings_schema_source_get_default(); if (source != NULL && g_settings_schema_source_lookup(source, "com.ubuntu.phone", TRUE) != NULL) { settings = g_settings_new("com.ubuntu.phone"); } for (index = 0; index < num_modems; index++) { OfonoAccount *account = (OfonoAccount*)malloc(sizeof(OfonoAccount)); char account_name[30] = {0}; char ril_modem[10] = {0}; account->index = index; sprintf(account_name, "ofono/ofono/account%d", index); sprintf(ril_modem, "/ril_%d", index); account->params = g_hash_table_new(g_str_hash, g_str_equal); account->account_name = g_strdup(account_name); g_hash_table_insert(account->params, g_strdup("manager"), g_strdup("ofono")); g_hash_table_insert(account->params, g_strdup("protocol"), g_strdup("ofono")); g_hash_table_insert(account->params, g_strdup("Enabled"), g_strdup("true")); g_hash_table_insert(account->params, g_strdup("ConnectAutomatically"), g_strdup("true")); g_hash_table_insert(account->params, g_strdup("always_dispatch"), g_strdup("true")); g_hash_table_insert(account->params, g_strdup("param-modem-objpath"), g_strdup(ril_modem)); if (settings) { GVariant *sim_names = g_settings_get_value(settings, "sim-names"); if (sim_names) { GVariantIter iter; GVariant *value; GVariantBuilder *builder = g_variant_builder_new(G_VARIANT_TYPE("a(ss)")); gchar *key; int found = 0; g_variant_iter_init (&iter, sim_names); while (g_variant_iter_next (&iter, "{ss}", &key, &value)) { g_variant_builder_add(builder, "(ss)", key, value); if (!strcmp(key, ril_modem)) { g_hash_table_insert(account->params, g_strdup("DisplayName"), g_strdup((char *)value)); found = 1; } g_free (key); g_free (value); } if (!found) { char *sim_name = dgettext("telephony-service", "SIM %1"); char *final_sim_name = NULL; char sim_index[10] = {0}; const char *placeholder = "%1"; sprintf(sim_index, "%d", index+1); const char *pos = strstr(sim_name, placeholder); if (pos) { // this is used to replace %1 by the actual index // FIXME: change telephony-service's string to %d to make everything easier final_sim_name = calloc(1, strlen(sim_name) - strlen(placeholder) + strlen(sim_index) + 1); strncpy(final_sim_name, sim_name, pos - sim_name); strcat(final_sim_name, sim_index); strcat(final_sim_name, pos + strlen(placeholder)); } else { final_sim_name = strdup(sim_name); } g_hash_table_insert(account->params, g_strdup("DisplayName"), g_strdup(final_sim_name)); g_settings_set_value(settings, "sim-names", g_variant_new("a(ss)", builder)); free(final_sim_name); } g_variant_builder_unref(builder); } if (sim_names) { g_variant_unref(sim_names); } } self->priv->accounts = g_list_append(self->priv->accounts, account); } if (settings) { g_object_unref (settings); } if (output) { g_free(output); } if (output2) { g_free (output2); } } static void mcp_account_manager_ofono_class_init(McpAccountManagerOfonoClass *klass) { GObjectClass *gobject_class = G_OBJECT_CLASS(klass); gobject_class->dispose = mcp_account_manager_ofono_dispose; g_type_class_add_private(gobject_class, sizeof(McpAccountManagerOfonoPrivate)); } static GList *account_manager_ofono_list(const McpAccountStorage *storage, const McpAccountManager *am) { McpAccountManagerOfono *self = (McpAccountManagerOfono*) storage; GList *accounts = NULL; OfonoAccount *account = NULL; GList *l; for (l = self->priv->accounts; l != NULL; l = l->next) { account = (OfonoAccount*)l->data; accounts = g_list_prepend(accounts, g_strdup(account->account_name)); } return accounts; } static gboolean account_manager_ofono_get(const McpAccountStorage *storage, const McpAccountManager *am, const gchar *account_name, const gchar *key) { McpAccountManagerOfono *self = (McpAccountManagerOfono*) storage; GList *l; OfonoAccount *account = NULL; int found = 0; for (l = self->priv->accounts; l != NULL; l = l->next) { account = (OfonoAccount*)l->data; if (!strcmp(account_name, account->account_name)) { found = 1; break; } } if (!found) { return FALSE; } if (key == NULL) { GHashTableIter iter; gpointer itkey, value; g_hash_table_iter_init(&iter, account->params); while (g_hash_table_iter_next(&iter, &itkey, &value)) { g_debug("%s: %s, %s %s", G_STRFUNC, account_name, (char*)itkey, (char*)value); mcp_account_manager_set_value(am, account_name, itkey, value); } } else { gchar *value = g_hash_table_lookup(account->params, key); g_debug("%s: %s, %s %s", G_STRFUNC, account_name, (char*)key, (char*)value); mcp_account_manager_set_value(am, account_name, key, value); } return TRUE; } static gboolean account_manager_ofono_set(const McpAccountStorage *storage, const McpAccountManager *am, const gchar *account_name, const gchar *key, const gchar *val) { return FALSE; } static gchar *account_manager_ofono_create(const McpAccountStorage *storage, const McpAccountManager *am, const gchar *cm_name, const gchar *protocol_name, GHashTable *params, GError **error) { g_set_error(error, TP_ERROR, TP_ERROR_INVALID_ARGUMENT, "Ofono ril account manager cannot create accounts"); return NULL; } static gboolean account_manager_ofono_delete(const McpAccountStorage *storage, const McpAccountManager *am, const gchar *account_name, const gchar *key) { g_debug("%s: %s, %s", G_STRFUNC, account_name, key); return FALSE; } static gboolean account_manager_ofono_commit(const McpAccountStorage *storage, const McpAccountManager *am) { g_debug("%s", G_STRFUNC); return FALSE; } static void account_manager_ofono_get_identifier(const McpAccountStorage *storage, const gchar *account_name, GValue *identifier) { McpAccountManagerOfono *self = (McpAccountManagerOfono*) storage; GList *l; OfonoAccount *account = NULL; int found = 0; for (l = self->priv->accounts; l != NULL; l = l->next) { account = (OfonoAccount*)l->data; if (!strcmp(account_name, account->account_name)) { found = 1; break; } } if (!found) { return; } g_debug("%s: %s", G_STRFUNC, account_name); g_value_init(identifier, G_TYPE_UINT); g_value_set_uint(identifier, account->index); } static guint account_manager_ofono_get_restrictions(const McpAccountStorage *storage, const gchar *account_name) { McpAccountManagerOfono *self = (McpAccountManagerOfono*) storage; GList *l; OfonoAccount *account = NULL; int found = 0; for (l = self->priv->accounts; l != NULL; l = l->next) { account = (OfonoAccount*)l->data; if (!strcmp(account_name, account->account_name)) { found = 1; break; } } if (!found) { return G_MAXUINT; } return TP_STORAGE_RESTRICTION_FLAG_CANNOT_SET_PARAMETERS | TP_STORAGE_RESTRICTION_FLAG_CANNOT_SET_ENABLED | TP_STORAGE_RESTRICTION_FLAG_CANNOT_SET_PRESENCE | TP_STORAGE_RESTRICTION_FLAG_CANNOT_SET_SERVICE; } static void account_storage_iface_init(McpAccountStorageIface *iface) { iface->name = PLUGIN_NAME; iface->desc = PLUGIN_DESCRIPTION; iface->priority = PLUGIN_PRIORITY; iface->provider = PLUGIN_PROVIDER; #define IMPLEMENT(x) iface->x = account_manager_ofono_##x IMPLEMENT (get); IMPLEMENT (list); IMPLEMENT (set); IMPLEMENT (create); IMPLEMENT (delete); IMPLEMENT (commit); IMPLEMENT (get_identifier); IMPLEMENT (get_restrictions); #undef IMPLEMENT } McpAccountManagerOfono *mcp_account_manager_ofono_new(void) { return g_object_new(MCP_TYPE_ACCOUNT_MANAGER_OFONO, NULL); } telepathy-ofono-0.2+16.04.20151120/sqlitedatabase.h0000644000015300001610000000262412623675611022171 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Gustavo Pichorim Boiko */ #ifndef SQLITEDATABASE_H #define SQLITEDATABASE_H #include #include class SQLiteDatabase : public QObject { Q_OBJECT public: static SQLiteDatabase *instance(); bool initializeDatabase(); QSqlDatabase database() const; bool beginTransation(); bool finishTransaction(); bool rollbackTransaction(); bool reopen(); protected: bool createOrUpdateDatabase(); QStringList parseSchemaFile(const QString &fileName); void parseVersionInfo(); private: explicit SQLiteDatabase(QObject *parent = 0); QString mDatabasePath; QSqlDatabase mDatabase; int mSchemaVersion; }; #endif // SQLITEDATABASE_H telepathy-ofono-0.2+16.04.20151120/protocol.cpp0000644000015300001610000000521012623675611021371 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include "protocol.h" #include "connection.h" #include #include #include Protocol::Protocol(const QDBusConnection &dbusConnection, const QString &name) : Tp::BaseProtocol(dbusConnection, name), mAudioModeMediator(mPowerDDBus) { addressingIface = Tp::BaseProtocolAddressingInterface::create(); addressingIface->setAddressableVCardFields(QStringList() << QLatin1String("tel")); addressingIface->setAddressableUriSchemes(QStringList() << QLatin1String("tel")); plugInterface(Tp::AbstractProtocolInterfacePtr::dynamicCast(addressingIface)); setRequestableChannelClasses(Tp::RequestableChannelClassSpecList() << Tp::RequestableChannelClassSpec::textChat() << Tp::RequestableChannelClassSpec::audioCall()); setCreateConnectionCallback(memFun(this, &Protocol::createConnection)); Tp::ProtocolParameterList parameters; Tp::ProtocolParameter parameter("modem-objpath", "s", 0); Tp::ProtocolParameter parameter2("fakeEmergencyNumber", "s", 0); parameters << parameter << parameter2; setParameters(parameters); } Tp::BaseConnectionPtr Protocol::createConnection(const QVariantMap ¶meters, Tp::DBusError *error) { Q_UNUSED(error); Tp::BaseConnectionPtr connection_ptr = Tp::BaseConnection::create("ofono", name().toLatin1(), parameters); connect( static_cast(connection_ptr.data()), &oFonoConnection::activeAudioOutputChanged, Tp::memFun(&mAudioModeMediator, &PowerDAudioModeMediator::audioModeChanged) ); connect( static_cast(connection_ptr.data()), &oFonoConnection::lastChannelClosed, Tp::memFun(&mAudioModeMediator, &PowerDAudioModeMediator::audioOutputClosed) ); return connection_ptr; } telepathy-ofono-0.2+16.04.20151120/ofonocallchannel.cpp0000644000015300001610000003414712623675611023050 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include "ofonocallchannel.h" #ifdef USE_PULSEAUDIO #include "qpulseaudioengine.h" #endif oFonoCallChannel::oFonoCallChannel(oFonoConnection *conn, QString phoneNumber, uint targetHandle, QString voiceObj, QObject *parent): OfonoVoiceCall(voiceObj), mIncoming(false), mRequestedHangup(false), mConnection(conn), mPhoneNumber(phoneNumber), mTargetHandle(targetHandle), mDtmfLock(false), mMultiparty(false) { Tp::BaseChannelPtr baseChannel = Tp::BaseChannel::create(mConnection, TP_QT_IFACE_CHANNEL_TYPE_CALL, Tp::HandleTypeContact, targetHandle); Tp::BaseChannelCallTypePtr callType = Tp::BaseChannelCallType::create(baseChannel.data(), true, Tp::StreamTransportTypeUnknown, true, false, "",""); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(callType)); mHoldIface = Tp::BaseChannelHoldInterface::create(); mHoldIface->setSetHoldStateCallback(Tp::memFun(this,&oFonoCallChannel::onHoldStateChanged)); mMuteIface = Tp::BaseCallMuteInterface::create(); mMuteIface->setSetMuteStateCallback(Tp::memFun(this,&oFonoCallChannel::onMuteStateChanged)); mAudioOutputsIface = BaseChannelAudioOutputsInterface::create(); mAudioOutputsIface->setSetActiveAudioOutputCallback(Tp::memFun(this,&oFonoCallChannel::onSetActiveAudioOutput)); mSplittableIface = Tp::BaseChannelSplittableInterface::create(); mSplittableIface->setSplitCallback(Tp::memFun(this,&oFonoCallChannel::onSplit)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mHoldIface)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mMuteIface)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mAudioOutputsIface)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mSplittableIface)); mBaseChannel = baseChannel; mCallChannel = Tp::BaseChannelCallTypePtr::dynamicCast(mBaseChannel->interface(TP_QT_IFACE_CHANNEL_TYPE_CALL)); mCallChannel->setHangupCallback(Tp::memFun(this,&oFonoCallChannel::onHangup)); mCallChannel->setAcceptCallback(Tp::memFun(this,&oFonoCallChannel::onAccept)); QObject::connect(this, SIGNAL(hangupComplete(bool)), this, SLOT(onHangupComplete(bool))); QObject::connect(this, SIGNAL(answerComplete(bool)), this, SLOT(onAnswerComplete(bool))); // init must be called after initialization, otherwise we will have no object path registered. QTimer::singleShot(0, this, SLOT(init())); #ifdef USE_PULSEAUDIO QByteArray pulseAudioDisabled = qgetenv("PA_DISABLED"); mHasPulseAudio = true; if (!pulseAudioDisabled.isEmpty()) mHasPulseAudio = false; #endif } Tp::CallState oFonoCallChannel::callState() { return (Tp::CallState)mCallChannel->callState(); } void oFonoCallChannel::onSplit(Tp::DBusError *error) { mConnection->voiceCallManager()->privateChat(path()); } void oFonoCallChannel::onSetActiveAudioOutput(const QString &id, Tp::DBusError *error) { #ifdef USE_PULSEAUDIO // fallback to earpiece/headset AudioMode mode = AudioModeWiredOrEarpiece; if (id == "bluetooth") { mode = AudioModeBluetooth; } else if (id == "speaker") { mode = AudioModeSpeaker; } if (mHasPulseAudio) QPulseAudioEngine::instance()->setCallMode(CallActive, mode); #endif } void oFonoCallChannel::onHangupComplete(bool status) { if (!status) { QTimer::singleShot(2000, this, SLOT(hangup())); } } void oFonoCallChannel::onAnswerComplete(bool status) { if (!status) { QTimer::singleShot(1000, this, SLOT(answer())); } } void oFonoCallChannel::onHangup(uint reason, const QString &detailedReason, const QString &message, Tp::DBusError *error) { // TODO: use the parameters sent by telepathy mRequestedHangup = true; hangup(); } void oFonoCallChannel::onAccept(Tp::DBusError*) { QVariantMap stateDetails; Tp::CallStateReason reason; reason.actor = 0; reason.reason = Tp::CallStateChangeReasonUserRequested; reason.message = ""; reason.DBusReason = ""; mCallChannel->setCallState(Tp::CallStateAccepted, 0, reason, stateDetails); if (this->state() == "waiting") { mConnection->voiceCallManager()->holdAndAnswer(); } else { answer(); } } void oFonoCallChannel::init() { mIncoming = this->state() == "incoming" || this->state() == "waiting"; mMultiparty = this->multiparty(); mPreviousState = this->state(); mObjPath = mBaseChannel->objectPath(); Tp::CallMemberMap memberFlags; Tp::HandleIdentifierMap identifiers; QVariantMap stateDetails; Tp::CallStateReason reason; identifiers[mTargetHandle] = mPhoneNumber; reason.actor = 0; reason.reason = Tp::CallStateChangeReasonProgressMade; reason.message = ""; reason.DBusReason = ""; if (mIncoming) { memberFlags[mTargetHandle] = 0; } else { memberFlags[mTargetHandle] = Tp::CallMemberFlagRinging; } mCallChannel->setCallState(Tp::CallStateInitialising, 0, reason, stateDetails); mCallContent = Tp::BaseCallContent::create(baseChannel()->dbusConnection(), baseChannel().data(), "audio", Tp::MediaStreamTypeAudio, Tp::MediaStreamDirectionNone); mDTMFIface = Tp::BaseCallContentDTMFInterface::create(); mCallContent->plugInterface(Tp::AbstractCallContentInterfacePtr::dynamicCast(mDTMFIface)); mCallChannel->addContent(mCallContent); mDTMFIface->setStartToneCallback(Tp::memFun(this,&oFonoCallChannel::onDTMFStartTone)); mDTMFIface->setStopToneCallback(Tp::memFun(this,&oFonoCallChannel::onDTMFStopTone)); mCallChannel->setMembersFlags(memberFlags, identifiers, Tp::UIntList(), reason); mCallChannel->setCallState(Tp::CallStateInitialised, 0, reason, stateDetails); QObject::connect(mBaseChannel.data(), SIGNAL(closed()), this, SLOT(deleteLater())); QObject::connect(mConnection->callVolume(), SIGNAL(mutedChanged(bool)), SLOT(onOfonoMuteChanged(bool))); QObject::connect(this, SIGNAL(stateChanged(QString)), SLOT(onOfonoCallStateChanged(QString))); QObject::connect(mConnection, SIGNAL(activeAudioOutputChanged(QString)), mAudioOutputsIface.data(), SLOT(setActiveAudioOutput(QString))); QObject::connect(mConnection, SIGNAL(audioOutputsChanged(AudioOutputList)), mAudioOutputsIface.data(), SLOT(setAudioOutputs(AudioOutputList))); QObject::connect(mConnection->voiceCallManager(), SIGNAL(sendTonesComplete(bool)), SLOT(onDtmfComplete(bool))); QObject::connect(this, SIGNAL(multipartyChanged(bool)), this, SLOT(onMultipartyChanged(bool))); QObject::connect(this, SIGNAL(disconnectReason(const QString &)), this, SLOT(onDisconnectReason(const QString &))); mAudioOutputsIface->setAudioOutputs(mConnection->audioOutputs()); mAudioOutputsIface->setActiveAudioOutput(mConnection->activeAudioOutput()); } void oFonoCallChannel::onDisconnectReason(const QString &reason) { mRequestedHangup = reason == "local"; } void oFonoCallChannel::onMultipartyChanged(bool multiparty) { // if previous state was multparty then split if (multiparty) { Q_EMIT merged(); } else { Q_EMIT splitted(); } mMultiparty = multiparty; } void oFonoCallChannel::onOfonoMuteChanged(bool mute) { Tp::LocalMuteState state = mute ? Tp::LocalMuteStateMuted : Tp::LocalMuteStateUnmuted; mMuteIface->setMuteState(state); } void oFonoCallChannel::onHoldStateChanged(const Tp::LocalHoldState &state, const Tp::LocalHoldStateReason &reason, Tp::DBusError *error) { if (state == Tp::LocalHoldStateHeld && this->state() == "active") { QObject::connect(mConnection->voiceCallManager(), SIGNAL(swapCallsComplete(bool)), this, SLOT(onSwapCallsComplete(bool))); mConnection->voiceCallManager()->swapCalls(); mHoldIface->setHoldState(Tp::LocalHoldStatePendingHold, Tp::LocalHoldStateReasonRequested); } else if (state == Tp::LocalHoldStateUnheld && this->state() == "held") { QObject::connect(mConnection->voiceCallManager(), SIGNAL(swapCallsComplete(bool)), this, SLOT(onSwapCallsComplete(bool))); mConnection->voiceCallManager()->swapCalls(); mHoldIface->setHoldState(Tp::LocalHoldStatePendingUnhold, Tp::LocalHoldStateReasonRequested); } } void oFonoCallChannel::onSwapCallsComplete(bool success) { if (!success && errorName() == "org.ofono.Error.InProgress") { QTimer::singleShot(2000, mConnection->voiceCallManager(), SLOT(swapCalls())); return; } Tp::LocalHoldState holdState = this->state() == "active" ? Tp::LocalHoldStateUnheld : Tp::LocalHoldStateHeld; Tp::LocalHoldStateReason reason = success ? Tp::LocalHoldStateReasonRequested : Tp::LocalHoldStateReasonResourceNotAvailable; QObject::disconnect(mConnection->voiceCallManager(), SIGNAL(swapCallsComplete(bool)), this, SLOT(onSwapCallsComplete(bool))); mHoldIface->setHoldState(holdState, reason); } void oFonoCallChannel::onMuteStateChanged(const Tp::LocalMuteState &state, Tp::DBusError *error) { if (state == Tp::LocalMuteStateMuted) { mConnection->callVolume()->setMuted(true); #ifdef USE_PULSEAUDIO if (mHasPulseAudio) QPulseAudioEngine::instance()->setMicMute(true); #endif } else if (state == Tp::LocalMuteStateUnmuted) { mConnection->callVolume()->setMuted(false); #ifdef USE_PULSEAUDIO if (mHasPulseAudio) QPulseAudioEngine::instance()->setMicMute(false); #endif } } void oFonoCallChannel::sendNextDtmf() { if (mDtmfLock) { return; } if (!mDtmfPendingStrings.isEmpty()) { mDtmfLock = true; mConnection->voiceCallManager()->sendTones(mDtmfPendingStrings.front()); } } void oFonoCallChannel::onDtmfComplete(bool success) { // this might be a response for another channel if (mCallChannel->callState() != Tp::CallStateActive) { return; } mDtmfLock = false; if (success) { if (mDtmfPendingStrings.count() > 0) { mDtmfPendingStrings.removeFirst(); } if (mDtmfPendingStrings.isEmpty()) { return; } sendNextDtmf(); } else { QTimer::singleShot(1000, this, SLOT(sendNextDtmf())); } } void oFonoCallChannel::onDTMFStartTone(uchar event, Tp::DBusError *error) { QString finalString; if (event == 10) { finalString = "*"; } else if (event == 11) { finalString = "#"; } else { finalString = QString::number(event); } qDebug() << "start tone" << finalString; // we can't append to the first item in the queue as it is being sent and // we dont know yet if it will succeed or not. if (mDtmfPendingStrings.count() > 1) { mDtmfPendingStrings[1] += finalString; } else { mDtmfPendingStrings << finalString; } sendNextDtmf(); } void oFonoCallChannel::onDTMFStopTone(Tp::DBusError *error) { } oFonoCallChannel::~oFonoCallChannel() { qDebug() << "call channel closed"; // TODO - for some reason the object is not being removed mConnection->dbusConnection().unregisterObject(mObjPath, QDBusConnection::UnregisterTree); } Tp::BaseChannelPtr oFonoCallChannel::baseChannel() { return mBaseChannel; } void oFonoCallChannel::onOfonoCallStateChanged(const QString &state) { Tp::CallStateReason reason; QVariantMap stateDetails; reason.actor = 0; reason.reason = Tp::CallStateChangeReasonUserRequested; reason.message = ""; reason.DBusReason = ""; // we invalidate the pending dtmf strings if the call status is changed mDtmfPendingStrings.clear(); mDtmfLock = false; if (state == "disconnected") { qDebug() << "disconnected"; if (mIncoming && (mPreviousState == "incoming" || mPreviousState == "waiting") && !mRequestedHangup) { reason.reason = Tp::CallStateChangeReasonNoAnswer; } mCallChannel->setCallState(Tp::CallStateEnded, 0, reason, stateDetails); Q_EMIT closed(); mBaseChannel->close(); } else if (state == "active") { qDebug() << "active"; mHoldIface->setHoldState(Tp::LocalHoldStateUnheld, Tp::LocalHoldStateReasonNone); if (mMultiparty) { Q_EMIT multipartyCallActive(); } if (mPreviousState == "incoming") { mConnection->updateAudioRouteToEarpiece(); } if (mPreviousState == "dialing" || mPreviousState == "alerting" || mPreviousState == "incoming") { mConnection->callVolume()->setMuted(false); mCallChannel->setCallState(Tp::CallStateAccepted, 0, reason, stateDetails); } mCallChannel->setCallState(Tp::CallStateActive, 0, reason, stateDetails); } else if (state == "held") { mHoldIface->setHoldState(Tp::LocalHoldStateHeld, Tp::LocalHoldStateReasonNone); if (mMultiparty) { Q_EMIT multipartyCallHeld(); } qDebug() << "held"; } else if (state == "dialing") { qDebug() << "dialing"; } else if (state == "alerting") { qDebug() << "alerting"; } else if (state == "incoming") { qDebug() << "incoming"; } else if (state == "waiting") { qDebug() << "waiting"; } // always update the audio route when call state changes mConnection->updateAudioRoute(); mPreviousState = state; } telepathy-ofono-0.2+16.04.20151120/ofonoconferencecallchannel.h0000644000015300001610000000562012623675611024537 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef OFONOCONFERENCECALLCHANNEL_H #define OFONOCONFERENCECALLCHANNEL_H #include #include #include #include #include #include #include "connection.h" #include "audiooutputsiface.h" class oFonoConnection; class oFonoConferenceCallChannel : public QObject { Q_OBJECT public: oFonoConferenceCallChannel(oFonoConnection *conn, QObject *parent = 0); ~oFonoConferenceCallChannel(); void onHangup(uint reason, const QString &detailedReason, const QString &message, Tp::DBusError* error); void onMuteStateChanged(const Tp::LocalMuteState &state, Tp::DBusError *error); void onHoldStateChanged(const Tp::LocalHoldState &state, const Tp::LocalHoldStateReason &reason, Tp::DBusError *error); void onDTMFStartTone(uchar event, Tp::DBusError *error); void onDTMFStopTone(Tp::DBusError *error); void onSetActiveAudioOutput(const QString &id, Tp::DBusError *error); void onMerge(const QDBusObjectPath &channel, Tp::DBusError *error); Tp::BaseChannelPtr baseChannel(); void setConferenceActive(bool active); private Q_SLOTS: void onDtmfComplete(bool success); void sendNextDtmf(); void init(); void onOfonoMuteChanged(bool mute); void onChannelMerged(const QDBusObjectPath &path); void onChannelSplitted(const QDBusObjectPath &path); void onSwapCallsComplete(bool success); private: QString mObjPath; QString mPreviousState; bool mIncoming; bool mRequestedHangup; oFonoConnection *mConnection; QList mCallChannels; Tp::BaseChannelPtr mBaseChannel; Tp::BaseChannelHoldInterfacePtr mHoldIface; Tp::BaseChannelConferenceInterfacePtr mConferenceIface; Tp::BaseChannelMergeableConferenceInterfacePtr mMergeableIface; Tp::BaseCallMuteInterfacePtr mMuteIface; BaseChannelAudioOutputsInterfacePtr mAudioOutputsIface; Tp::BaseChannelCallTypePtr mCallChannel; Tp::BaseCallContentDTMFInterfacePtr mDTMFIface; Tp::BaseCallContentPtr mCallContent; bool mDtmfLock; QStringList mDtmfPendingStrings; }; #endif // OFONOCONFERENCECALLCHANNEL_H telepathy-ofono-0.2+16.04.20151120/cmake/0000755000015300001610000000000012623676450020110 5ustar pbuserpbgroup00000000000000telepathy-ofono-0.2+16.04.20151120/cmake/modules/0000755000015300001610000000000012623676450021560 5ustar pbuserpbgroup00000000000000telepathy-ofono-0.2+16.04.20151120/cmake/modules/LibFindMacros.cmake0000644000015300001610000001106012623675611025232 0ustar pbuserpbgroup00000000000000# Version 1.0 (2013-04-12) # Public Domain, originally written by Lasse Kärkkäinen # Published at http://www.cmake.org/Wiki/CMake:How_To_Find_Libraries # If you improve the script, please modify the forementioned wiki page because # I no longer maintain my scripts (hosted as static files at zi.fi). Feel free # to remove this entire header if you use real version control instead. # Changelog: # 2013-04-12 Added version number (1.0) and this header, no other changes # 2009-10-08 Originally published # Works the same as find_package, but forwards the "REQUIRED" and "QUIET" arguments # used for the current package. For this to work, the first parameter must be the # prefix of the current package, then the prefix of the new package etc, which are # passed to find_package. macro (libfind_package PREFIX) set (LIBFIND_PACKAGE_ARGS ${ARGN}) if (${PREFIX}_FIND_QUIETLY) set (LIBFIND_PACKAGE_ARGS ${LIBFIND_PACKAGE_ARGS} QUIET) endif (${PREFIX}_FIND_QUIETLY) if (${PREFIX}_FIND_REQUIRED) set (LIBFIND_PACKAGE_ARGS ${LIBFIND_PACKAGE_ARGS} REQUIRED) endif (${PREFIX}_FIND_REQUIRED) find_package(${LIBFIND_PACKAGE_ARGS}) endmacro (libfind_package) # CMake developers made the UsePkgConfig system deprecated in the same release (2.6) # where they added pkg_check_modules. Consequently I need to support both in my scripts # to avoid those deprecated warnings. Here's a helper that does just that. # Works identically to pkg_check_modules, except that no checks are needed prior to use. macro (libfind_pkg_check_modules PREFIX PKGNAME) if (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4) include(UsePkgConfig) pkgconfig(${PKGNAME} ${PREFIX}_INCLUDE_DIRS ${PREFIX}_LIBRARY_DIRS ${PREFIX}_LDFLAGS ${PREFIX}_CFLAGS) else (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4) find_package(PkgConfig) if (PKG_CONFIG_FOUND) pkg_check_modules(${PREFIX} ${PKGNAME}) endif (PKG_CONFIG_FOUND) endif (${CMAKE_MAJOR_VERSION} EQUAL 2 AND ${CMAKE_MINOR_VERSION} EQUAL 4) endmacro (libfind_pkg_check_modules) # Do the final processing once the paths have been detected. # If include dirs are needed, ${PREFIX}_PROCESS_INCLUDES should be set to contain # all the variables, each of which contain one include directory. # Ditto for ${PREFIX}_PROCESS_LIBS and library files. # Will set ${PREFIX}_FOUND, ${PREFIX}_INCLUDE_DIRS and ${PREFIX}_LIBRARIES. # Also handles errors in case library detection was required, etc. macro (libfind_process PREFIX) # Skip processing if already processed during this run if (NOT ${PREFIX}_FOUND) # Start with the assumption that the library was found set (${PREFIX}_FOUND TRUE) # Process all includes and set _FOUND to false if any are missing foreach (i ${${PREFIX}_PROCESS_INCLUDES}) if (${i}) set (${PREFIX}_INCLUDE_DIRS ${${PREFIX}_INCLUDE_DIRS} ${${i}}) mark_as_advanced(${i}) else (${i}) set (${PREFIX}_FOUND FALSE) endif (${i}) endforeach (i) # Process all libraries and set _FOUND to false if any are missing foreach (i ${${PREFIX}_PROCESS_LIBS}) if (${i}) set (${PREFIX}_LIBRARIES ${${PREFIX}_LIBRARIES} ${${i}}) mark_as_advanced(${i}) else (${i}) set (${PREFIX}_FOUND FALSE) endif (${i}) endforeach (i) # Print message and/or exit on fatal error if (${PREFIX}_FOUND) if (NOT ${PREFIX}_FIND_QUIETLY) message (STATUS "Found ${PREFIX} ${${PREFIX}_VERSION}") endif (NOT ${PREFIX}_FIND_QUIETLY) else (${PREFIX}_FOUND) if (${PREFIX}_FIND_REQUIRED) foreach (i ${${PREFIX}_PROCESS_INCLUDES} ${${PREFIX}_PROCESS_LIBS}) message("${i}=${${i}}") endforeach (i) message (FATAL_ERROR "Required library ${PREFIX} NOT FOUND.\nInstall the library (dev version) and try again. If the library is already installed, use ccmake to set the missing variables manually.") endif (${PREFIX}_FIND_REQUIRED) endif (${PREFIX}_FOUND) endif (NOT ${PREFIX}_FOUND) endmacro (libfind_process) macro(libfind_library PREFIX basename) set(TMP "") if(MSVC80) set(TMP -vc80) endif(MSVC80) if(MSVC90) set(TMP -vc90) endif(MSVC90) set(${PREFIX}_LIBNAMES ${basename}${TMP}) if(${ARGC} GREATER 2) set(${PREFIX}_LIBNAMES ${basename}${TMP}-${ARGV2}) string(REGEX REPLACE "\\." "_" TMP ${${PREFIX}_LIBNAMES}) set(${PREFIX}_LIBNAMES ${${PREFIX}_LIBNAMES} ${TMP}) endif(${ARGC} GREATER 2) find_library(${PREFIX}_LIBRARY NAMES ${${PREFIX}_LIBNAMES} PATHS ${${PREFIX}_PKGCONF_LIBRARY_DIRS} ) endmacro(libfind_library) telepathy-ofono-0.2+16.04.20151120/cmake/modules/FindLcov.cmake0000644000015300001610000000172012623675611024264 0ustar pbuserpbgroup00000000000000# - Find lcov # Will define: # # LCOV_EXECUTABLE - the lcov binary # GENHTML_EXECUTABLE - the genhtml executable # # Copyright (C) 2010 by Johannes Wienke # # 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, or (at your option) # any later version. # # 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. # INCLUDE(FindPackageHandleStandardArgs) FIND_PROGRAM(LCOV_EXECUTABLE lcov) FIND_PROGRAM(GENHTML_EXECUTABLE genhtml) FIND_PACKAGE_HANDLE_STANDARD_ARGS(Lcov DEFAULT_MSG LCOV_EXECUTABLE GENHTML_EXECUTABLE) # only visible in advanced view MARK_AS_ADVANCED(LCOV_EXECUTABLE GENHTML_EXECUTABLE) telepathy-ofono-0.2+16.04.20151120/cmake/modules/ParseArguments.cmake0000644000015300001610000000340612623675611025523 0ustar pbuserpbgroup00000000000000# Parse arguments passed to a function into several lists separated by # upper-case identifiers and options that do not have an associated list e.g.: # # SET(arguments # hello OPTION3 world # LIST3 foo bar # OPTION2 # LIST1 fuz baz # ) # PARSE_ARGUMENTS(ARG "LIST1;LIST2;LIST3" "OPTION1;OPTION2;OPTION3" ${arguments}) # # results in 7 distinct variables: # * ARG_DEFAULT_ARGS: hello;world # * ARG_LIST1: fuz;baz # * ARG_LIST2: # * ARG_LIST3: foo;bar # * ARG_OPTION1: FALSE # * ARG_OPTION2: TRUE # * ARG_OPTION3: TRUE # # taken from http://www.cmake.org/Wiki/CMakeMacroParseArguments MACRO(PARSE_ARGUMENTS prefix arg_names option_names) SET(DEFAULT_ARGS) FOREACH(arg_name ${arg_names}) SET(${prefix}_${arg_name}) ENDFOREACH(arg_name) FOREACH(option ${option_names}) SET(${prefix}_${option} FALSE) ENDFOREACH(option) SET(current_arg_name DEFAULT_ARGS) SET(current_arg_list) FOREACH(arg ${ARGN}) SET(larg_names ${arg_names}) LIST(FIND larg_names "${arg}" is_arg_name) IF (is_arg_name GREATER -1) SET(${prefix}_${current_arg_name} ${current_arg_list}) SET(current_arg_name ${arg}) SET(current_arg_list) ELSE (is_arg_name GREATER -1) SET(loption_names ${option_names}) LIST(FIND loption_names "${arg}" is_option) IF (is_option GREATER -1) SET(${prefix}_${arg} TRUE) ELSE (is_option GREATER -1) SET(current_arg_list ${current_arg_list} ${arg}) ENDIF (is_option GREATER -1) ENDIF (is_arg_name GREATER -1) ENDFOREACH(arg) SET(${prefix}_${current_arg_name} ${current_arg_list}) ENDMACRO(PARSE_ARGUMENTS) telepathy-ofono-0.2+16.04.20151120/cmake/modules/Findgcovr.cmake0000644000015300001610000000170212623675611024501 0ustar pbuserpbgroup00000000000000# - Find gcovr scrip # Will define: # # GCOVR_EXECUTABLE - the gcovr script # # Uses: # # GCOVR_ROOT - root to search for the script # # Copyright (C) 2011 by Johannes Wienke # # 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, or (at your option) # any later version. # # 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. # INCLUDE(FindPackageHandleStandardArgs) FIND_PROGRAM(GCOVR_EXECUTABLE gcovr HINTS ${GCOVR_ROOT} "${GCOVR_ROOT}/bin") FIND_PACKAGE_HANDLE_STANDARD_ARGS(gcovr DEFAULT_MSG GCOVR_EXECUTABLE) # only visible in advanced view MARK_AS_ADVANCED(GCOVR_EXECUTABLE) telepathy-ofono-0.2+16.04.20151120/cmake/modules/FindLibPhoneNumber.cmake0000644000015300001610000000141412623675611026232 0ustar pbuserpbgroup00000000000000set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/modules) include(GNUInstallDirs) include(LibFindMacros) # Include dir find_path(LibPhoneNumber_INCLUDE_DIR NAMES phonenumberutil.h PATHS "/usr/local/${CMAKE_INSTALL_INCLUDEDIR}" ${CMAKE_INSTALL_FULL_INCLUDEDIR} PATH_SUFFIXES "phonenumbers" ) # library itself find_library(LibPhoneNumber_LIBRARY NAMES phonenumber PATHS "/usr/local/${CMAKE_INSTALL_LIBDIR}" ${CMAKE_INSTALL_FULL_LIBDIR} ) # Set the include dir variables and the libraries and let libfind_process do the rest. # NOTE: Singular variables for this library, plural for libraries this this lib depends on. set(LibPhoneNumber_PROCESS_INCLUDES LibPhoneNumber_INCLUDE_DIR) set(LibPhoneNumber_PROCESS_LIBS LibPhoneNumber_LIBRARY) libfind_process(LibPhoneNumber) telepathy-ofono-0.2+16.04.20151120/cmake/modules/EnableCoverageReport.cmake0000644000015300001610000001531112623675611026617 0ustar pbuserpbgroup00000000000000# - Creates a special coverage build type and target on GCC. # # Defines a function ENABLE_COVERAGE_REPORT which generates the coverage target # for selected targets. Optional arguments to this function are used to filter # unwanted results using globbing expressions. Moreover targets with tests for # the source code can be specified to trigger regenerating the report if the # test has changed # # ENABLE_COVERAGE_REPORT(TARGETS target... [FILTER filter...] [TESTS test targets...]) # # To generate a coverage report first build the project with # CMAKE_BUILD_TYPE=coverage, then call make test and afterwards make coverage. # # The coverage report is based on gcov. Depending on the availability of lcov # a HTML report will be generated and/or an XML report of gcovr is found. # The generated coverage target executes all found solutions. Special targets # exist to create e.g. only the xml report: coverage-xml. # # Copyright (C) 2010 by Johannes Wienke # # 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, or (at your option) # any later version. # # 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. # INCLUDE(ParseArguments) FIND_PACKAGE(Lcov) FIND_PACKAGE(gcovr) FUNCTION(ENABLE_COVERAGE_REPORT) # argument parsing PARSE_ARGUMENTS(ARG "FILTER;TARGETS;TESTS" "" ${ARGN}) SET(COVERAGE_RAW_FILE "${CMAKE_BINARY_DIR}/coverage.raw.info") SET(COVERAGE_FILTERED_FILE "${CMAKE_BINARY_DIR}/coverage.info") SET(COVERAGE_REPORT_DIR "${CMAKE_BINARY_DIR}/coveragereport") SET(COVERAGE_XML_FILE "${CMAKE_BINARY_DIR}/coverage.xml") SET(COVERAGE_XML_COMMAND_FILE "${CMAKE_BINARY_DIR}/coverage-xml.cmake") # decide if there is any tool to create coverage data SET(TOOL_FOUND FALSE) IF(LCOV_FOUND OR GCOVR_FOUND) SET(TOOL_FOUND TRUE) ENDIF() IF(NOT TOOL_FOUND) MESSAGE(STATUS "Cannot enable coverage targets because neither lcov nor gcovr are found.") ENDIF() STRING(TOLOWER "${CMAKE_BUILD_TYPE}" COVERAGE_BUILD_TYPE) IF(CMAKE_COMPILER_IS_GNUCXX AND TOOL_FOUND AND "${COVERAGE_BUILD_TYPE}" MATCHES "coverage") MESSAGE(STATUS "Coverage support enabled for targets: ${ARG_TARGETS}") # create coverage build type SET(CMAKE_CXX_FLAGS_COVERAGE ${CMAKE_CXX_FLAGS_DEBUG} PARENT_SCOPE) SET(CMAKE_C_FLAGS_COVERAGE ${CMAKE_C_FLAGS_DEBUG} PARENT_SCOPE) SET(CMAKE_CONFIGURATION_TYPES ${CMAKE_CONFIGURATION_TYPES} coverage PARENT_SCOPE) # instrument targets SET_TARGET_PROPERTIES(${ARG_TARGETS} PROPERTIES COMPILE_FLAGS --coverage LINK_FLAGS --coverage) # html report IF (LCOV_FOUND) MESSAGE(STATUS "Enabling HTML coverage report") # set up coverage target ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_RAW_FILE} COMMAND ${LCOV_EXECUTABLE} -c -d ${CMAKE_BINARY_DIR} -o ${COVERAGE_RAW_FILE} WORKING_DIRECTORY ${CMAKE_BINARY_DIR} COMMENT "Collecting coverage data" DEPENDS ${ARG_TARGETS} ${ARG_TESTS} VERBATIM) # filter unwanted stuff LIST(LENGTH ARG_FILTER FILTER_LENGTH) IF(${FILTER_LENGTH} GREATER 0) SET(FILTER COMMAND ${LCOV_EXECUTABLE}) FOREACH(F ${ARG_FILTER}) SET(FILTER ${FILTER} -r ${COVERAGE_FILTERED_FILE} ${F}) ENDFOREACH() SET(FILTER ${FILTER} -o ${COVERAGE_FILTERED_FILE}) ELSE() SET(FILTER "") ENDIF() ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_FILTERED_FILE} COMMAND ${LCOV_EXECUTABLE} -e ${COVERAGE_RAW_FILE} "${CMAKE_SOURCE_DIR}*" -o ${COVERAGE_FILTERED_FILE} ${FILTER} DEPENDS ${COVERAGE_RAW_FILE} COMMENT "Filtering recorded coverage data for project-relevant entries" VERBATIM) ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_REPORT_DIR} COMMAND ${CMAKE_COMMAND} -E make_directory ${COVERAGE_REPORT_DIR} COMMAND ${GENHTML_EXECUTABLE} --legend --show-details -t "${PROJECT_NAME} test coverage" -o ${COVERAGE_REPORT_DIR} ${COVERAGE_FILTERED_FILE} DEPENDS ${COVERAGE_FILTERED_FILE} COMMENT "Generating HTML coverage report in ${COVERAGE_REPORT_DIR}" VERBATIM) ADD_CUSTOM_TARGET(coverage-html DEPENDS ${COVERAGE_REPORT_DIR}) ENDIF() # xml coverage report IF(GCOVR_FOUND) MESSAGE(STATUS "Enabling XML coverage report") # gcovr cannot write directly to a file so the execution needs to # be wrapped in a cmake file that generates the file output FILE(WRITE ${COVERAGE_XML_COMMAND_FILE} "SET(ENV{LANG} en)\n") FILE(APPEND ${COVERAGE_XML_COMMAND_FILE} "EXECUTE_PROCESS(COMMAND \"${GCOVR_EXECUTABLE}\" -x -r \"${CMAKE_SOURCE_DIR}\" OUTPUT_FILE \"${COVERAGE_XML_FILE}\" WORKING_DIRECTORY \"${CMAKE_BINARY_DIR}\")\n") ADD_CUSTOM_COMMAND(OUTPUT ${COVERAGE_XML_FILE} COMMAND ${CMAKE_COMMAND} ARGS -P ${COVERAGE_XML_COMMAND_FILE} COMMENT "Generating coverage XML report" VERBATIM) ADD_CUSTOM_TARGET(coverage-xml DEPENDS ${COVERAGE_XML_FILE}) ENDIF() # provide a global coverage target executing both steps if available SET(GLOBAL_DEPENDS "") IF(LCOV_FOUND) LIST(APPEND GLOBAL_DEPENDS ${COVERAGE_REPORT_DIR}) ENDIF() IF(GCOVR_FOUND) LIST(APPEND GLOBAL_DEPENDS ${COVERAGE_XML_FILE}) ENDIF() IF(LCOV_FOUND OR GCOVR_FOUND) ADD_CUSTOM_TARGET(coverage DEPENDS ${GLOBAL_DEPENDS}) ENDIF() ENDIF() ENDFUNCTION() telepathy-ofono-0.2+16.04.20151120/powerddbus.cpp0000644000015300001610000000243512623675611021714 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2014 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Andreas Pokorny */ #include "powerddbus.h" #include #include #include PowerDDBus::PowerDDBus() : mPowerDIface{ new QDBusInterface( "com.canonical.powerd", "/com/canonical/powerd", "com.canonical.powerd", QDBusConnection::systemBus())} { } void PowerDDBus::enableProximityHandling() { mPowerDIface->call("enableProximityHandling", "telepathy-ofono"); } void PowerDDBus::disableProximityHandling() { mPowerDIface->call("disableProximityHandling", "telepathy-ofono"); } telepathy-ofono-0.2+16.04.20151120/ussdiface.h0000644000015300001610000002220612623675611021147 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef OFONOUSSDIFACE_H #define OFONOUSSDIFACE_H // telepathy-qt #include #include #include #include #include class BaseConnectionUSSDInterface; typedef Tp::SharedPtr BaseConnectionUSSDInterfacePtr; #define TP_QT_IFACE_CONNECTION_USSD "com.canonical.Telephony.USSD" class TP_QT_EXPORT BaseConnectionUSSDInterface : public Tp::AbstractConnectionInterface { Q_OBJECT Q_DISABLE_COPY(BaseConnectionUSSDInterface) public: static BaseConnectionUSSDInterfacePtr create() { return BaseConnectionUSSDInterfacePtr(new BaseConnectionUSSDInterface()); } template static Tp::SharedPtr create() { return Tp::SharedPtr( new BaseConnectionUSSDInterfaceSubclass()); } QVariantMap immutableProperties() const; virtual ~BaseConnectionUSSDInterface(); typedef Tp::Callback2 InitiateCallback; void setInitiateCallback(const InitiateCallback &cb); typedef Tp::Callback2 RespondCallback; void setRespondCallback(const RespondCallback &cb); typedef Tp::Callback1 CancelCallback; void setCancelCallback(const CancelCallback &cb); QString state() const; QString serial() const; public Q_SLOTS: void NotificationReceived(const QString &message); void RequestReceived(const QString &message); void InitiateUSSDComplete(const QString &ussdResp); void RespondComplete(bool success, const QString &ussdResp); void BarringComplete(const QString &ssOp, const QString &cbService, const QVariantMap &cbMap); void ForwardingComplete(const QString &ssOp, const QString &cfService, const QVariantMap &cfMap); void WaitingComplete(const QString &ssOp, const QVariantMap &cwMap); void CallingLinePresentationComplete(const QString &ssOp, const QString &status); void ConnectedLinePresentationComplete(const QString &ssOp, const QString &status); void CallingLineRestrictionComplete(const QString &ssOp, const QString &status); void ConnectedLineRestrictionComplete(const QString &ssOp, const QString &status); void InitiateFailed(); void StateChanged(const QString &state); void setSerial(const QString& serial) const; protected: BaseConnectionUSSDInterface(); private: void createAdaptor(); class Adaptee; friend class Adaptee; struct Private; friend struct Private; Private *mPriv; }; class TP_QT_EXPORT ConnectionInterfaceUSSDAdaptor : public Tp::AbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", TP_QT_IFACE_CONNECTION_USSD) Q_CLASSINFO("D-Bus Introspection", "" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" "") Q_PROPERTY(QString State READ State) Q_PROPERTY(QString Serial READ Serial) public: ConnectionInterfaceUSSDAdaptor(const QDBusConnection& dbusConnection, QObject* adaptee, QObject* parent); virtual ~ConnectionInterfaceUSSDAdaptor(); typedef Tp::MethodInvocationContextPtr< > InitiateContextPtr; typedef Tp::MethodInvocationContextPtr< > RespondContextPtr; typedef Tp::MethodInvocationContextPtr< > CancelContextPtr; public Q_SLOTS: // METHODS void Initiate(const QString &command, const QDBusMessage& dbusMessage); void Respond(const QString &reply, const QDBusMessage& dbusMessage); void Cancel(const QDBusMessage& dbusMessage); QString State() const; QString Serial() const; Q_SIGNALS: // SIGNALS void NotificationReceived(const QString &message); void RequestReceived(const QString &message); void InitiateUSSDComplete(const QString &ussdResp); void RespondComplete(bool success, const QString &ussdResp); void BarringComplete(const QString &ssOp, const QString &cbService, const QVariantMap &cbMap); void ForwardingComplete(const QString &ssOp, const QString &cfService, const QVariantMap &cfMap); void WaitingComplete(const QString &ssOp, const QVariantMap &cwMap); void CallingLinePresentationComplete(const QString &ssOp, const QString &status); void ConnectedLinePresentationComplete(const QString &ssOp, const QString &status); void CallingLineRestrictionComplete(const QString &ssOp, const QString &status); void ConnectedLineRestrictionComplete(const QString &ssOp, const QString &status); void InitiateFailed(); void StateChanged(const QString &state); }; class TP_QT_NO_EXPORT BaseConnectionUSSDInterface::Adaptee : public QObject { Q_OBJECT Q_PROPERTY(QString state READ state) Q_PROPERTY(QString serial READ serial) public: Adaptee(BaseConnectionUSSDInterface *interface); ~Adaptee(); QString state() const { return mInterface->state(); } QString serial() const { return mInterface->serial(); } private Q_SLOTS: void initiate(const QString &command, const ConnectionInterfaceUSSDAdaptor::InitiateContextPtr &context); void respond(const QString &reply, const ConnectionInterfaceUSSDAdaptor::RespondContextPtr &context); void cancel(const ConnectionInterfaceUSSDAdaptor::CancelContextPtr &context); Q_SIGNALS: void notificationReceived(const QString &message); void requestReceived(const QString &message); void initiateUSSDComplete(const QString &ussdResp); void barringComplete(const QString &ssOp, const QString &cbService, const QVariantMap &cbMap); void forwardingComplete(const QString &ssOp, const QString &cfService, const QVariantMap &cfMap); void waitingComplete(const QString &ssOp, const QVariantMap &cwMap); void callingLinePresentationComplete(const QString &ssOp, const QString &status); void connectedLinePresentationComplete(const QString &ssOp, const QString &status); void callingLineRestrictionComplete(const QString &ssOp, const QString &status); void connectedLineRestrictionComplete(const QString &ssOp, const QString &status); void initiateFailed(); void respondComplete(bool success, const QString &response); void stateChanged(const QString &state); public: BaseConnectionUSSDInterface *mInterface; }; #endif telepathy-ofono-0.2+16.04.20151120/mmsdmessage.h0000644000015300001610000000266312623675611021513 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef MMSDMESSAGE_H #define MMSDMESSAGE_H #include #include #include #include class MMSDMessage : public QObject { Q_OBJECT public: MMSDMessage(QString objectPath, QVariantMap properties, QObject *parent=0); ~MMSDMessage(); QVariantMap properties() const; QString path() const; void markRead() const; // it should be called delete, but it is a reserved keyword in c++ void remove() const; Q_SIGNALS: void propertyChanged(const QString&, const QVariant&); private Q_SLOTS: void onPropertyChanged(const QString&, const QDBusVariant&); private: QVariantMap m_properties; QString m_messagePath; }; #endif telepathy-ofono-0.2+16.04.20151120/ofono.manager0000644000015300001610000000106012623675611021477 0ustar pbuserpbgroup00000000000000[ConnectionManager] Name = ofono BusName = org.freedesktop.Telepathy.ConnectionManager.ofono ObjectPath = /org/freedesktop/Telepathy/ConnectionManager/ofono [Protocol ofono] param-modem-objpath=s param-fakeEmergencyNumber=s AddressableVCardFields=tel AddressableURISchemes=tel EnglishName=ofono Interfaces=org.freedesktop.Telepathy.Protocol.Interface.Addressing; ConnectionInterfaces=org.freedesktop.Telepathy.Connection.Interface.Requests;org.freedesktop.Telepathy.Connection.Interface.Contacts;org.freedesktop.Telepathy.Connection.Interface.SimplePresence; telepathy-ofono-0.2+16.04.20151120/ofonoconferencecallchannel.cpp0000644000015300001610000003001412623675611025065 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include "ofonoconferencecallchannel.h" #ifdef USE_PULSEAUDIO #include "qpulseaudioengine.h" #endif #include "ofonocallchannel.h" oFonoConferenceCallChannel::oFonoConferenceCallChannel(oFonoConnection *conn, QObject *parent): mRequestedHangup(false), mConnection(conn), mDtmfLock(false) { Q_FOREACH(oFonoCallChannel *channel, mConnection->callChannels().values()) { if (channel->callState() == Tp::CallStateActive) { QDBusObjectPath path(channel->baseChannel()->objectPath()); mCallChannels << path; } } Tp::BaseChannelPtr baseChannel = Tp::BaseChannel::create(mConnection, TP_QT_IFACE_CHANNEL_TYPE_CALL); Tp::BaseChannelCallTypePtr callType = Tp::BaseChannelCallType::create(baseChannel.data(), true, Tp::StreamTransportTypeUnknown, true, false, "",""); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(callType)); mHoldIface = Tp::BaseChannelHoldInterface::create(); mHoldIface->setSetHoldStateCallback(Tp::memFun(this,&oFonoConferenceCallChannel::onHoldStateChanged)); mMuteIface = Tp::BaseCallMuteInterface::create(); mMuteIface->setSetMuteStateCallback(Tp::memFun(this,&oFonoConferenceCallChannel::onMuteStateChanged)); mAudioOutputsIface = BaseChannelAudioOutputsInterface::create(); mAudioOutputsIface->setSetActiveAudioOutputCallback(Tp::memFun(this,&oFonoConferenceCallChannel::onSetActiveAudioOutput)); mConferenceIface = Tp::BaseChannelConferenceInterface::create(mCallChannels); mMergeableIface = Tp::BaseChannelMergeableConferenceInterface::create(); mMergeableIface->setMergeCallback(Tp::memFun(this,&oFonoConferenceCallChannel::onMerge)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mHoldIface)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mMuteIface)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mAudioOutputsIface)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mConferenceIface)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mMergeableIface)); mBaseChannel = baseChannel; mCallChannel = Tp::BaseChannelCallTypePtr::dynamicCast(mBaseChannel->interface(TP_QT_IFACE_CHANNEL_TYPE_CALL)); mCallChannel->setHangupCallback(Tp::memFun(this,&oFonoConferenceCallChannel::onHangup)); Tp::CallStateReason reason; QVariantMap stateDetails; reason.actor = 0; reason.reason = Tp::CallStateChangeReasonUserRequested; reason.message = ""; reason.DBusReason = ""; mCallChannel->setCallState(Tp::CallStateActive, 0, reason, stateDetails); // init must be called after initialization, otherwise we will have no object path registered. QTimer::singleShot(0, this, SLOT(init())); } Tp::BaseChannelPtr oFonoConferenceCallChannel::baseChannel() { return mBaseChannel; } void oFonoConferenceCallChannel::onMerge(const QDBusObjectPath &channel, Tp::DBusError *error) { // on gsm we always merge all the existing calls mConnection->voiceCallManager()->createMultiparty(); } void oFonoConferenceCallChannel::onChannelMerged(const QDBusObjectPath &path) { if (!mCallChannels.contains(path)) { mCallChannels << path; mConferenceIface->mergeChannel(path, 0, QVariantMap()); } } void oFonoConferenceCallChannel::onChannelSplitted(const QDBusObjectPath &path) { if (mCallChannels.contains(path)) { mCallChannels.removeAll(path); mConferenceIface->removeChannel(path, QVariantMap()); } if (mCallChannels.size() == 1) { // remove the call channel from the conference before closing it. mConferenceIface->removeChannel(mCallChannels.takeFirst(), QVariantMap()); Tp::CallStateReason reason; QVariantMap stateDetails; reason.actor = 0; reason.reason = Tp::CallStateChangeReasonUserRequested; reason.message = ""; reason.DBusReason = ""; mCallChannel->setCallState(Tp::CallStateEnded, 0, reason, stateDetails); mBaseChannel->close(); } } void oFonoConferenceCallChannel::onSetActiveAudioOutput(const QString &id, Tp::DBusError *error) { #ifdef USE_PULSEAUDIO // fallback to earpiece/headset AudioMode mode = AudioModeWiredOrEarpiece; if (id == "bluetooth") { mode = AudioModeBluetooth; } else if (id == "speaker") { mode = AudioModeSpeaker; } QPulseAudioEngine::instance()->setCallMode(CallActive, mode); #endif } void oFonoConferenceCallChannel::onHangup(uint reason, const QString &detailedReason, const QString &message, Tp::DBusError *error) { // TODO: use the parameters sent by telepathy //mRequestedHangup = true; mConnection->voiceCallManager()->hangupMultiparty(); //hangup(); } void oFonoConferenceCallChannel::init() { QVariantMap stateDetails; Tp::CallStateReason reason; mObjPath = mBaseChannel->objectPath(); reason.actor = 0; reason.reason = Tp::CallStateChangeReasonProgressMade; reason.message = ""; reason.DBusReason = ""; mCallChannel->setCallState(Tp::CallStateActive, 0, reason, stateDetails); mDTMFIface = Tp::BaseCallContentDTMFInterface::create(); mCallContent = Tp::BaseCallContent::create(baseChannel()->dbusConnection(), baseChannel().data(), "audio", Tp::MediaStreamTypeAudio, Tp::MediaStreamDirectionNone); mDTMFIface = Tp::BaseCallContentDTMFInterface::create(); mCallContent->plugInterface(Tp::AbstractCallContentInterfacePtr::dynamicCast(mDTMFIface)); mCallChannel->addContent(mCallContent); mDTMFIface->setStartToneCallback(Tp::memFun(this,&oFonoConferenceCallChannel::onDTMFStartTone)); mDTMFIface->setStopToneCallback(Tp::memFun(this,&oFonoConferenceCallChannel::onDTMFStopTone)); QObject::connect(mBaseChannel.data(), SIGNAL(closed()), this, SLOT(deleteLater())); QObject::connect(mConnection->callVolume(), SIGNAL(mutedChanged(bool)), SLOT(onOfonoMuteChanged(bool))); QObject::connect(mConnection, SIGNAL(activeAudioOutputChanged(QString)), mAudioOutputsIface.data(), SLOT(setActiveAudioOutput(QString))); QObject::connect(mConnection, SIGNAL(audioOutputsChanged(AudioOutputList)), mAudioOutputsIface.data(), SLOT(setAudioOutputs(AudioOutputList))); QObject::connect(mConnection->voiceCallManager(), SIGNAL(sendTonesComplete(bool)), SLOT(onDtmfComplete(bool))); mAudioOutputsIface->setAudioOutputs(mConnection->audioOutputs()); mAudioOutputsIface->setActiveAudioOutput(mConnection->activeAudioOutput()); QObject::connect(mConnection, SIGNAL(channelMerged(const QDBusObjectPath&)), this, SLOT(onChannelMerged(const QDBusObjectPath&))); QObject::connect(mConnection, SIGNAL(channelSplitted(const QDBusObjectPath&)), this, SLOT(onChannelSplitted(const QDBusObjectPath&))); QObject::connect(mConnection, SIGNAL(channelHangup(const QDBusObjectPath&)), this, SLOT(onChannelSplitted(const QDBusObjectPath&))); } void oFonoConferenceCallChannel::onOfonoMuteChanged(bool mute) { Tp::LocalMuteState state = mute ? Tp::LocalMuteStateMuted : Tp::LocalMuteStateUnmuted; mMuteIface->setMuteState(state); } void oFonoConferenceCallChannel::setConferenceActive(bool active) { if (active) { mHoldIface->setHoldState(Tp::LocalHoldStateUnheld, Tp::LocalHoldStateReasonRequested); } else { mHoldIface->setHoldState(Tp::LocalHoldStateHeld, Tp::LocalHoldStateReasonRequested); } } void oFonoConferenceCallChannel::onHoldStateChanged(const Tp::LocalHoldState &state, const Tp::LocalHoldStateReason &reason, Tp::DBusError *error) { if (state == Tp::LocalHoldStateHeld && mHoldIface->getHoldState() == Tp::LocalHoldStateUnheld) { QObject::connect(mConnection->voiceCallManager(), SIGNAL(swapCallsComplete(bool)), this, SLOT(onSwapCallsComplete(bool))); mHoldIface->setHoldState(Tp::LocalHoldStatePendingHold, Tp::LocalHoldStateReasonRequested); mConnection->voiceCallManager()->swapCalls(); } else if (state == Tp::LocalHoldStateUnheld && mHoldIface->getHoldState() == Tp::LocalHoldStateHeld) { QObject::connect(mConnection->voiceCallManager(), SIGNAL(swapCallsComplete(bool)), this, SLOT(onSwapCallsComplete(bool))); mHoldIface->setHoldState(Tp::LocalHoldStatePendingUnhold, Tp::LocalHoldStateReasonRequested); mConnection->voiceCallManager()->swapCalls(); } } void oFonoConferenceCallChannel::onSwapCallsComplete(bool success) { QObject::disconnect(mConnection->voiceCallManager(), SIGNAL(swapCallsComplete(bool)), this, SLOT(onSwapCallsComplete(bool))); if (!success) { // only change hold state in case of failure. Successful action will happen through setConferenceActive() Tp::LocalHoldState holdState = mHoldIface->getHoldState() == Tp::LocalHoldStatePendingHold ? Tp::LocalHoldStateUnheld : Tp::LocalHoldStateHeld; mHoldIface->setHoldState(holdState, Tp::LocalHoldStateReasonResourceNotAvailable); } } void oFonoConferenceCallChannel::onMuteStateChanged(const Tp::LocalMuteState &state, Tp::DBusError *error) { if (state == Tp::LocalMuteStateMuted) { mConnection->callVolume()->setMuted(true); #ifdef USE_PULSEAUDIO QPulseAudioEngine::instance()->setMicMute(true); #endif } else if (state == Tp::LocalMuteStateUnmuted) { mConnection->callVolume()->setMuted(false); #ifdef USE_PULSEAUDIO QPulseAudioEngine::instance()->setMicMute(false); #endif } } void oFonoConferenceCallChannel::sendNextDtmf() { if (mDtmfLock) { return; } if (!mDtmfPendingStrings.isEmpty()) { mDtmfLock = true; mConnection->voiceCallManager()->sendTones(mDtmfPendingStrings.front()); } } void oFonoConferenceCallChannel::onDtmfComplete(bool success) { // this might be a response for another channel if (mCallChannel->callState() != Tp::CallStateActive) { return; } mDtmfLock = false; if (success) { if (mDtmfPendingStrings.count() > 0) { mDtmfPendingStrings.removeFirst(); } if (mDtmfPendingStrings.isEmpty()) { return; } sendNextDtmf(); } else { QTimer::singleShot(1000, this, SLOT(sendNextDtmf())); } } void oFonoConferenceCallChannel::onDTMFStartTone(uchar event, Tp::DBusError *error) { QString finalString; if (event == 10) { finalString = "*"; } else if (event == 11) { finalString = "#"; } else { finalString = QString::number(event); } qDebug() << "start tone" << finalString; // we can't append to the first item in the queue as it is being sent and // we dont know yet if it will succeed or not. if (mDtmfPendingStrings.count() > 1) { mDtmfPendingStrings[1] += finalString; } else { mDtmfPendingStrings << finalString; } sendNextDtmf(); } void oFonoConferenceCallChannel::onDTMFStopTone(Tp::DBusError *error) { } oFonoConferenceCallChannel::~oFonoConferenceCallChannel() { qDebug() << "conference call channel closed"; // TODO - for some reason the object is not being removed mConnection->dbusConnection().unregisterObject(mObjPath, QDBusConnection::UnregisterTree); } telepathy-ofono-0.2+16.04.20151120/powerdaudiomodemediator.h0000644000015300001610000000270712623675611024121 0ustar pbuserpbgroup00000000000000/**************************************************************************** ** ** Copyright (C) 2014 Canonical, Ltd. ** ** Authors: ** Andreas Pokorny ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ****************************************************************************/ #ifndef POWERDAUDIOMODEMEDIATOR_H #define POWERDAUDIOMODEMEDIATOR_H #include "powerd.h" #include #include #include class PowerD; /*! * \brief PowerDAudioModeMediator is responsible for configuring proximity * handling of powerd during different call states and used audio outputs. * In General that mean enabling sreen blanking on proximity events, when * a call is active and neither a bluetooth headset nor the speakers are used. */ class PowerDAudioModeMediator { public: PowerDAudioModeMediator(PowerD &powerd); void audioModeChanged(const QString &mode); void audioOutputClosed(); private: void apply() const; PowerD &powerd; bool mProximityEnabled{false}; }; #endif telepathy-ofono-0.2+16.04.20151120/ofonocallchannel.h0000644000015300001610000000624012623675611022506 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef OFONOCALLCHANNEL_H #define OFONOCALLCHANNEL_H #include #include #include #include #include #include #include "connection.h" #include "audiooutputsiface.h" class oFonoConnection; class oFonoCallChannel : public OfonoVoiceCall { Q_OBJECT public: oFonoCallChannel(oFonoConnection *conn, QString phoneNumber, uint targetHandle, QString voiceObj, QObject *parent = 0); ~oFonoCallChannel(); Tp::BaseChannelPtr baseChannel(); void onHangup(uint reason, const QString &detailedReason, const QString &message, Tp::DBusError* error); void onAccept(Tp::DBusError*); void onMuteStateChanged(const Tp::LocalMuteState &state, Tp::DBusError *error); void onHoldStateChanged(const Tp::LocalHoldState &state, const Tp::LocalHoldStateReason &reason, Tp::DBusError *error); void onDTMFStartTone(uchar event, Tp::DBusError *error); void onDTMFStopTone(Tp::DBusError *error); void onSetActiveAudioOutput(const QString &id, Tp::DBusError *error); void onSplit(Tp::DBusError *error); Tp::CallState callState(); Q_SIGNALS: void splitted(); void merged(); void closed(); void multipartyCallHeld(); void multipartyCallActive(); private Q_SLOTS: void onOfonoCallStateChanged(const QString &state); void onDtmfComplete(bool success); void onSwapCallsComplete(bool success); void sendNextDtmf(); void init(); void onAnswerComplete(bool success); void onHangupComplete(bool success); void onOfonoMuteChanged(bool mute); void onMultipartyChanged(bool multiparty); void onDisconnectReason(const QString &reason); private: QString mObjPath; QString mPreviousState; #ifdef USE_PULSEAUDIO bool mHasPulseAudio; #endif bool mIncoming; bool mRequestedHangup; Tp::BaseChannelPtr mBaseChannel; QString mPhoneNumber; oFonoConnection *mConnection; uint mTargetHandle; Tp::BaseChannelHoldInterfacePtr mHoldIface; Tp::BaseChannelSplittableInterfacePtr mSplittableIface; Tp::BaseCallMuteInterfacePtr mMuteIface; BaseChannelAudioOutputsInterfacePtr mAudioOutputsIface; Tp::BaseChannelCallTypePtr mCallChannel; Tp::BaseCallContentDTMFInterfacePtr mDTMFIface; Tp::BaseCallContentPtr mCallContent; bool mDtmfLock; QStringList mDtmfPendingStrings; bool mMultiparty; }; #endif // OFONOCALLCHANNEL_H telepathy-ofono-0.2+16.04.20151120/emergencymodeiface.h0000644000015300001610000001107712623675611023020 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann * Gustavo Pichorim Boiko */ #ifndef OFONOEMERGENCYMODEIFACE_H #define OFONOEMERGENCYMODEIFACE_H // telepathy-qt #include #include #include #include #include class BaseConnectionEmergencyModeInterface; typedef Tp::SharedPtr BaseConnectionEmergencyModeInterfacePtr; #define TP_QT_IFACE_CONNECTION_EMERGENCYMODE "com.canonical.Telephony.EmergencyMode" class TP_QT_EXPORT BaseConnectionEmergencyModeInterface : public Tp::AbstractConnectionInterface { Q_OBJECT Q_DISABLE_COPY(BaseConnectionEmergencyModeInterface) public: static BaseConnectionEmergencyModeInterfacePtr create() { return BaseConnectionEmergencyModeInterfacePtr(new BaseConnectionEmergencyModeInterface()); } template static Tp::SharedPtr create() { return Tp::SharedPtr( new BaseConnectionEmergencyModeInterfaceSubclass()); } QVariantMap immutableProperties() const; virtual ~BaseConnectionEmergencyModeInterface(); typedef Tp::Callback1 EmergencyNumbersCallback; void setEmergencyNumbersCallback(const EmergencyNumbersCallback &cb); void setFakeEmergencyNumber(const QString &fakeEmergencyNumber); public Q_SLOTS: void setEmergencyNumbers(const QStringList &numbers); void setCountryCode(const QString &countryCode); protected: BaseConnectionEmergencyModeInterface(); private: void createAdaptor(); class Adaptee; friend class Adaptee; struct Private; friend struct Private; Private *mPriv; }; class TP_QT_EXPORT ConnectionInterfaceEmergencyModeAdaptor : public Tp::AbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", TP_QT_IFACE_CONNECTION_EMERGENCYMODE) Q_CLASSINFO("D-Bus Introspection", "" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" "") public: ConnectionInterfaceEmergencyModeAdaptor(const QDBusConnection& dbusConnection, QObject* adaptee, QObject* parent); virtual ~ConnectionInterfaceEmergencyModeAdaptor(); typedef Tp::MethodInvocationContextPtr< QStringList > EmergencyNumbersContextPtr; typedef Tp::MethodInvocationContextPtr< QString > CountryCodeContextPtr; public Q_SLOTS: // METHODS QStringList EmergencyNumbers(const QDBusMessage& dbusMessage); QString CountryCode(const QDBusMessage& dbusMessage); Q_SIGNALS: // SIGNALS void EmergencyNumbersChanged(const QStringList &numbers); void CountryCodeChanged(const QString &countryCode); }; class TP_QT_NO_EXPORT BaseConnectionEmergencyModeInterface::Adaptee : public QObject { Q_OBJECT public: Adaptee(BaseConnectionEmergencyModeInterface *interface); ~Adaptee(); private Q_SLOTS: void emergencyNumbers(const ConnectionInterfaceEmergencyModeAdaptor::EmergencyNumbersContextPtr &context); void countryCode(const ConnectionInterfaceEmergencyModeAdaptor::CountryCodeContextPtr &context); Q_SIGNALS: void emergencyNumbersChanged(const QStringList &numbers); void countryCodeChanged(const QString &countryCode); public: BaseConnectionEmergencyModeInterface *mInterface; }; #endif telepathy-ofono-0.2+16.04.20151120/update_qrc.sh0000755000015300001610000000057312623675611021521 0ustar pbuserpbgroup00000000000000#!/bin/sh QRC_FILE=$1 FILES=`ls schema/*.sql schema/*.info` # clear the file if [ -e $QRC_FILE ]; then rm -f $QRC_FILE fi # and print the contents echo '' >> $QRC_FILE echo ' ' >> $QRC_FILE for file in $FILES; do echo " $file" >> $QRC_FILE done echo ' ' >> $QRC_FILE echo '' >> $QRC_FILE telepathy-ofono-0.2+16.04.20151120/mmsdmanager.h0000644000015300001610000000251412623675611021474 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef MMSDMANAGER_H #define MMSDMANAGER_H #include #include #include #include class MMSDManager : public QObject { Q_OBJECT public: MMSDManager(QObject *parent=0); ~MMSDManager(); QStringList services() const; Q_SIGNALS: void serviceAdded(const QString &servicePath); void serviceRemoved(const QString &servicePath); private Q_SLOTS: void onServiceAdded(const QDBusObjectPath &path, const QVariantMap &properties); void onServiceRemoved(const QDBusObjectPath &path); private: QStringList m_services; }; #endif telepathy-ofono-0.2+16.04.20151120/COPYING.LGPL0000644000015300001610000001674312623675611020631 0ustar pbuserpbgroup00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. telepathy-ofono-0.2+16.04.20151120/ofonotextchannel.cpp0000644000015300001610000004776012623675617023134 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ // ofono-qt #include // telepathy-ofono #include "ofonotextchannel.h" #include "pendingmessagesmanager.h" QDBusArgument &operator<<(QDBusArgument&argument, const IncomingAttachmentStruct &attachment) { argument.beginStructure(); argument << attachment.id << attachment.contentType << attachment.filePath << attachment.offset << attachment.length; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, IncomingAttachmentStruct &attachment) { argument.beginStructure(); argument >> attachment.id >> attachment.contentType >> attachment.filePath >> attachment.offset >> attachment.length; argument.endStructure(); return argument; } oFonoTextChannel::oFonoTextChannel(oFonoConnection *conn, QStringList phoneNumbers, bool flash, QObject *parent): QObject(parent), mConnection(conn), mPhoneNumbers(phoneNumbers), mFlash(flash), mMessageCounter(1) { qDBusRegisterMetaType(); qDBusRegisterMetaType(); Tp::BaseChannelPtr baseChannel; if (phoneNumbers.size() == 1) { baseChannel = Tp::BaseChannel::create(mConnection, TP_QT_IFACE_CHANNEL_TYPE_TEXT, Tp::HandleTypeContact, mConnection->ensureHandle(mPhoneNumbers[0])); } else { baseChannel = Tp::BaseChannel::create(mConnection, TP_QT_IFACE_CHANNEL_TYPE_TEXT); } Tp::BaseChannelTextTypePtr textType = Tp::BaseChannelTextType::create(baseChannel.data()); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(textType)); QStringList supportedContentTypes = QStringList() << "text/plain"; Tp::UIntList messageTypes = Tp::UIntList() << Tp::ChannelTextMessageTypeNormal << Tp::ChannelTextMessageTypeDeliveryReport; uint messagePartSupportFlags = 0; uint deliveryReportingSupport = Tp::DeliveryReportingSupportFlagReceiveSuccesses; mMessagesIface = Tp::BaseChannelMessagesInterface::create(textType.data(), supportedContentTypes, messageTypes, messagePartSupportFlags, deliveryReportingSupport); mMessagesIface->setSendMessageCallback(Tp::memFun(this,&oFonoTextChannel::sendMessage)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mMessagesIface)); mGroupIface = Tp::BaseChannelGroupInterface::create(Tp::ChannelGroupFlagCanAdd, conn->selfHandle()); mGroupIface->setAddMembersCallback(Tp::memFun(this,&oFonoTextChannel::onAddMembers)); mGroupIface->setRemoveMembersCallback(Tp::memFun(this,&oFonoTextChannel::onRemoveMembers)); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mGroupIface)); addMembers(phoneNumbers); mSMSIface = Tp::BaseChannelSMSInterface::create(flash, true); baseChannel->plugInterface(Tp::AbstractChannelInterfacePtr::dynamicCast(mSMSIface)); mBaseChannel = baseChannel; mTextChannel = Tp::BaseChannelTextTypePtr::dynamicCast(mBaseChannel->interface(TP_QT_IFACE_CHANNEL_TYPE_TEXT)); mTextChannel->setMessageAcknowledgedCallback(Tp::memFun(this,&oFonoTextChannel::messageAcknowledged)); QObject::connect(mBaseChannel.data(), SIGNAL(closed()), this, SLOT(deleteLater())); } void oFonoTextChannel::onAddMembers(const Tp::UIntList& handles, const QString& message, Tp::DBusError* error) { addMembers(mConnection->inspectHandles(Tp::HandleTypeContact, handles, error)); } void oFonoTextChannel::onRemoveMembers(const Tp::UIntList& handles, const QString& message, Tp::DBusError* error) { Q_FOREACH(uint handle, handles) { Q_FOREACH(const QString &phoneNumber, mConnection->inspectHandles(Tp::HandleTypeContact, Tp::UIntList() << handle, error)) { mPhoneNumbers.removeAll(phoneNumber); } mMembers.removeAll(handle); } mGroupIface->removeMembers(handles); } void oFonoTextChannel::addMembers(QStringList phoneNumbers) { Tp::UIntList handles; Q_FOREACH(const QString &phoneNumber, phoneNumbers) { uint handle = mConnection->ensureHandle(phoneNumber); handles << handle; if (!mPhoneNumbers.contains(phoneNumber)) { mPhoneNumbers << phoneNumber; } if (!mMembers.contains(handle)) { mMembers << handle; } } mGroupIface->addMembers(handles, phoneNumbers); } Tp::UIntList oFonoTextChannel::members() { return mMembers; } oFonoTextChannel::~oFonoTextChannel() { Q_FOREACH(const QStringList &fileList, mFilesToRemove) { Q_FOREACH(const QString& file, fileList) { QFile::remove(file); } } } Tp::BaseChannelPtr oFonoTextChannel::baseChannel() { return mBaseChannel; } void oFonoTextChannel::sendDeliveryReport(const QString &messageId, uint handle, Tp::DeliveryStatus status) { Tp::MessagePartList partList; Tp::MessagePart header; header["message-sender"] = QDBusVariant(handle); header["message-sender-id"] = QDBusVariant(mPhoneNumbers[0]); header["message-type"] = QDBusVariant(Tp::ChannelTextMessageTypeDeliveryReport); header["delivery-status"] = QDBusVariant(status); header["delivery-token"] = QDBusVariant(messageId); partList << header; mTextChannel->addReceivedMessage(partList); } void oFonoTextChannel::deliveryReportReceived(const QString &messageId, uint handle, bool success) { sendDeliveryReport(messageId, handle, success ? Tp::DeliveryStatusDelivered : Tp::DeliveryStatusPermanentlyFailed); } void oFonoTextChannel::messageAcknowledged(const QString &id) { Q_EMIT messageRead(id); } QString oFonoTextChannel::sendMessage(Tp::MessagePartList message, uint flags, Tp::DBusError* error) { bool success = true; Tp::MessagePart header = message.at(0); Tp::MessagePart body = message.at(1); QString objpath; bool mms = header["x-canonical-mms"].variant().toBool(); if (mms) { // pop header out message.removeFirst(); OutgoingAttachmentList attachments; // FIXME group chat QString phoneNumber = mPhoneNumbers[0]; uint handle = mConnection->ensureHandle(phoneNumber); QStringList temporaryFiles; Q_FOREACH(const Tp::MessagePart &part, message) { OutgoingAttachmentStruct attachment; attachment.id = part["identifier"].variant().toString(); attachment.contentType = part["content-type"].variant().toString(); QString attachmentsPath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/telepathy-ofono/attachments"; if (!QDir().exists(attachmentsPath) && !QDir().mkpath(attachmentsPath)) { qCritical() << "Failed to create attachments directory"; objpath = QDateTime::currentDateTimeUtc().toString(Qt::ISODate) + "-" + QString::number(mMessageCounter++); error->set(TP_QT_ERROR_INVALID_ARGUMENT, "Failed to create attachments to disk"); mPendingDeliveryReportPermanentlyFailed[objpath] = handle; QTimer::singleShot(0, this, SLOT(onProcessPendingDeliveryReport())); return objpath; } QTemporaryFile file(attachmentsPath + "/attachmentXXXXXX"); file.setAutoRemove(false); if (!file.open()) { Q_FOREACH(const QString& file, temporaryFiles) { QFile::remove(file); } objpath = QDateTime::currentDateTimeUtc().toString(Qt::ISODate) + "-" + QString::number(mMessageCounter++); error->set(TP_QT_ERROR_INVALID_ARGUMENT, "Failed to create attachments to disk"); mPendingDeliveryReportPermanentlyFailed[objpath] = handle; QTimer::singleShot(0, this, SLOT(onProcessPendingDeliveryReport())); return objpath; } temporaryFiles << file.fileName(); file.write(part["content"].variant().toByteArray()); file.close(); attachment.filePath = file.fileName(); attachments << attachment; } objpath = mConnection->sendMMS(mPhoneNumbers, attachments).path(); if (objpath.isEmpty()) { Q_FOREACH(const QString& file, temporaryFiles) { QFile::remove(file); } // give a temporary id for this message objpath = QDateTime::currentDateTimeUtc().toString(Qt::ISODate) + "-" + QString::number(mMessageCounter++); // TODO: get error message from nuntium error->set(TP_QT_ERROR_INVALID_ARGUMENT, "Failed to send MMS"); mPendingDeliveryReportPermanentlyFailed[objpath] = handle; QTimer::singleShot(0, this, SLOT(onProcessPendingDeliveryReport())); return objpath; } MMSDMessage *msg = new MMSDMessage(objpath, QVariantMap(), this); QObject::connect(msg, SIGNAL(propertyChanged(QString,QVariant)), SLOT(onMMSPropertyChanged(QString,QVariant))); mPendingDeliveryReportUnknown[objpath] = handle; QTimer::singleShot(0, this, SLOT(onProcessPendingDeliveryReport())); if (temporaryFiles.size() > 0) { mFilesToRemove[objpath] = temporaryFiles; } return objpath; } if (mPhoneNumbers.size() == 1) { QString phoneNumber = mPhoneNumbers[0]; uint handle = mConnection->ensureHandle(phoneNumber); objpath = mConnection->messageManager()->sendMessage(phoneNumber, body["content"].variant().toString(), success).path(); if (objpath.isEmpty() || !success) { if (!success) { qWarning() << mConnection->messageManager()->errorName() << mConnection->messageManager()->errorMessage(); } else { error->set(TP_QT_ERROR_INVALID_ARGUMENT, mConnection->messageManager()->errorMessage()); } // create an unique id for this message that ofono failed to send objpath = QDateTime::currentDateTimeUtc().toString(Qt::ISODate) + "-" + QString::number(mMessageCounter++); mPendingDeliveryReportPermanentlyFailed[objpath] = handle; QTimer::singleShot(0, this, SLOT(onProcessPendingDeliveryReport())); return objpath; } OfonoMessage *msg = new OfonoMessage(objpath); if (msg->state() == "") { // message was already sent or failed too fast (this case is only reproducible with the emulator) msg->deleteLater(); mPendingDeliveryReportUnknown[objpath] = handle; QTimer::singleShot(0, this, SLOT(onProcessPendingDeliveryReport())); return objpath; } // FIXME: track pending messages only if delivery reports are enabled. We need a system config option for it. PendingMessagesManager::instance()->addPendingMessage(objpath, mPhoneNumbers[0]); QObject::connect(msg, SIGNAL(stateChanged(QString)), SLOT(onOfonoMessageStateChanged(QString))); return objpath; } else { bool someMessageSent = false; QString lastPhoneNumber; Q_FOREACH(const QString &phoneNumber, mPhoneNumbers) { uint handle = mConnection->ensureHandle(mPhoneNumbers[0]); objpath = mConnection->messageManager()->sendMessage(phoneNumber, body["content"].variant().toString(), success).path(); lastPhoneNumber = phoneNumber; // dont fail if this is a group chat as we cannot track individual messages if (objpath.isEmpty() || !success) { if (!success) { qWarning() << mConnection->messageManager()->errorName() << mConnection->messageManager()->errorMessage(); } else { error->set(TP_QT_ERROR_INVALID_ARGUMENT, mConnection->messageManager()->errorMessage()); } continue; } someMessageSent = true; } if (!someMessageSent) { // for group chat we only fail if all the messages failed to send objpath = QDateTime::currentDateTimeUtc().toString(Qt::ISODate) + "-" + QString::number(mMessageCounter++); uint handle = mConnection->ensureHandle(lastPhoneNumber); mPendingDeliveryReportPermanentlyFailed[objpath] = handle; QTimer::singleShot(0, this, SLOT(onProcessPendingDeliveryReport())); return objpath; } OfonoMessage *msg = new OfonoMessage(objpath); if (msg->state() == "") { // message was already sent or failed too fast (this case is only reproducible with the emulator) msg->deleteLater(); uint handle = mConnection->ensureHandle(lastPhoneNumber); mPendingDeliveryReportUnknown[objpath] = handle; QTimer::singleShot(0, this, SLOT(onProcessPendingDeliveryReport())); // return only the last one in case of group chat for history purposes return objpath; } QObject::connect(msg, SIGNAL(stateChanged(QString)), SLOT(onOfonoMessageStateChanged(QString))); return objpath; } } void oFonoTextChannel::onMMSPropertyChanged(QString property, QVariant value) { qDebug() << "oFonoTextChannel::onMMSPropertyChanged" << property << value; MMSDMessage *msg = qobject_cast(sender()); // FIXME - mms groupchat uint handle = mConnection->ensureHandle(mPhoneNumbers[0]); if (!msg) { return; } if (property == "Status") { Tp::DeliveryStatus status = Tp::DeliveryStatusUnknown; if (value == "Sent") { status = Tp::DeliveryStatusAccepted; } else if (value == "TransientError" || value == "PermanentError") { // transient error in telepathy means it is still trying, so we need to // set a permanent error here so the user can retry status = Tp::DeliveryStatusPermanentlyFailed; } else if (value == "draft") { // while it is draft we dont actually send a delivery report return; } Q_FOREACH(const QString& file, mFilesToRemove[msg->path()]) { QFile::remove(file); } mFilesToRemove.remove(msg->path()); sendDeliveryReport(msg->path(), handle, status); } } void oFonoTextChannel::onProcessPendingDeliveryReport() { QMapIterator iterator(mPendingDeliveryReportPermanentlyFailed); while(iterator.hasNext()) { iterator.next(); sendDeliveryReport(iterator.key(), iterator.value(), Tp::DeliveryStatusPermanentlyFailed); } iterator = mPendingDeliveryReportDelivered; while(iterator.hasNext()) { iterator.next(); sendDeliveryReport(iterator.key(), iterator.value(), Tp::DeliveryStatusDelivered); } iterator = mPendingDeliveryReportAccepted; while(iterator.hasNext()) { iterator.next(); sendDeliveryReport(iterator.key(), iterator.value(), Tp::DeliveryStatusAccepted); } iterator = mPendingDeliveryReportTemporarilyFailed; while(iterator.hasNext()) { iterator.next(); sendDeliveryReport(iterator.key(), iterator.value(), Tp::DeliveryStatusTemporarilyFailed); } iterator = mPendingDeliveryReportUnknown; while(iterator.hasNext()) { iterator.next(); sendDeliveryReport(iterator.key(), iterator.value(), Tp::DeliveryStatusUnknown); } mPendingDeliveryReportTemporarilyFailed.clear(); mPendingDeliveryReportPermanentlyFailed.clear(); mPendingDeliveryReportDelivered.clear(); mPendingDeliveryReportAccepted.clear(); mPendingDeliveryReportUnknown.clear(); } void oFonoTextChannel::onOfonoMessageStateChanged(QString status) { OfonoMessage *msg = static_cast(sender()); if(msg) { Tp::DeliveryStatus delivery_status; if (status == "sent") { delivery_status = Tp::DeliveryStatusAccepted; msg->deleteLater(); } else if(status == "failed") { delivery_status = Tp::DeliveryStatusPermanentlyFailed; PendingMessagesManager::instance()->removePendingMessage(msg->path()); msg->deleteLater(); } else if(status == "pending") { delivery_status = Tp::DeliveryStatusTemporarilyFailed; } else { delivery_status = Tp::DeliveryStatusUnknown; } sendDeliveryReport(msg->path(), mConnection->ensureHandle(mPhoneNumbers[0]), delivery_status); } } void oFonoTextChannel::messageReceived(const QString &message, uint handle, const QVariantMap &info) { Tp::MessagePartList partList; Tp::MessagePart body; body["content-type"] = QDBusVariant("text/plain"); body["content"] = QDBusVariant(message); Tp::MessagePart header; header["message-token"] = QDBusVariant(info["SentTime"].toString() +"-" + QString::number(mMessageCounter++)); header["message-received"] = QDBusVariant(QDateTime::currentDateTime().toTime_t()); header["message-sender"] = QDBusVariant(handle); header["message-sender-id"] = QDBusVariant(mPhoneNumbers[0]); header["message-type"] = QDBusVariant(Tp::ChannelTextMessageTypeNormal); partList << header << body; mTextChannel->addReceivedMessage(partList); } void oFonoTextChannel::mmsReceived(const QString &id, uint handle, const QVariantMap &properties) { Tp::MessagePartList message; QString subject = properties["Subject"].toString(); QString smil = properties["Smil"].toString(); Tp::MessagePart header; header["message-token"] = QDBusVariant(id); header["message-sender"] = QDBusVariant(handle); header["message-received"] = QDBusVariant(QDateTime::currentDateTimeUtc().toTime_t()); header["message-type"] = QDBusVariant(Tp::DeliveryStatusDelivered); header["x-canonical-mms"] = QDBusVariant(true); if (!subject.isEmpty()) { header["subject"] = QDBusVariant(subject); } message << header; IncomingAttachmentList mmsdAttachments = qdbus_cast(properties["Attachments"]); Q_FOREACH(const IncomingAttachmentStruct &attachment, mmsdAttachments) { QFile attachmentFile(attachment.filePath); if (!attachmentFile.open(QIODevice::ReadOnly)) { qWarning() << "fail to load attachment" << attachmentFile.errorString() << attachment.filePath; continue; } // FIXME check if we managed to read the total attachment file attachmentFile.seek(attachment.offset); QByteArray fileData = attachmentFile.read(attachment.length); Tp::MessagePart part; part["content-type"] = QDBusVariant(attachment.contentType); part["identifier"] = QDBusVariant(attachment.id); part["content"] = QDBusVariant(fileData); part["size"] = QDBusVariant(attachment.length); message << part; } if (!smil.isEmpty()) { Tp::MessagePart part; part["content-type"] = QDBusVariant(QString("application/smil")); part["identifier"] = QDBusVariant(QString("smil")); part["content"] = QDBusVariant(smil); part["size"] = QDBusVariant(smil.size()); message << part; } mTextChannel->addReceivedMessage(message); } telepathy-ofono-0.2+16.04.20151120/tools/0000755000015300001610000000000012623676450020170 5ustar pbuserpbgroup00000000000000telepathy-ofono-0.2+16.04.20151120/tools/generate_country_codes.py0000644000015300001610000000125612623675611025276 0ustar pbuserpbgroup00000000000000# originally available at https://github.com/musalbas/mcc-mnc-table/blob/master/get-mcc-mnc-table-csv.py import re import urllib2 html = urllib2.urlopen('http://mcc-mnc.com/').read() td_re = re.compile('([^<]*)'*6) codes = {} tbody_start = False for line in html.split('\n'): if '' in line: tbody_start = True elif '' in line: break elif tbody_start: td_search = td_re.search(line) mcc = int(td_search.group(1)) isoCountryCode = td_search.group(3).upper() if (len(isoCountryCode) != 2): continue codes[mcc] = isoCountryCode for mcc in codes: print str(mcc) + ":" + codes[mcc] telepathy-ofono-0.2+16.04.20151120/mmsdservice.h0000644000015300001610000000333712623675611021526 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef MMSDSERVICE_H #define MMSDSERVICE_H #include #include #include #include #include "dbustypes.h" #include "connection.h" #include "mmsdmessage.h" class MMSDService : public QObject { Q_OBJECT public: MMSDService(QString objectPath, oFonoConnection *connection, QObject *parent=0); ~MMSDService(); QVariantMap properties() const; MessageList messages() const; QString path() const; QString modemObjectPath() const; QDBusObjectPath sendMessage(QStringList recipients, OutgoingAttachmentList attachments); Q_SIGNALS: void messageAdded(const QString &messagePath, const QVariantMap &properties); void messageRemoved(const QString &messagePath); private Q_SLOTS: void onMessageAdded(const QDBusObjectPath &path, const QVariantMap &properties); void onMessageRemoved(const QDBusObjectPath &path); private: QVariantMap m_properties; QString m_servicePath; MessageList m_messages; }; #endif telepathy-ofono-0.2+16.04.20151120/countrycodes.qrc0000644000015300001610000000013712623675611022257 0ustar pbuserpbgroup00000000000000 countrycodes.txt telepathy-ofono-0.2+16.04.20151120/voicemailiface.h0000644000015300001610000001233112623675611022137 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef OFONOVOICEMAILIFACE_H #define OFONOVOICEMAILIFACE_H // telepathy-qt #include #include #include #include #include class BaseConnectionVoicemailInterface; typedef Tp::SharedPtr BaseConnectionVoicemailInterfacePtr; #define TP_QT_IFACE_CONNECTION_VOICEMAIL "com.canonical.Telephony.Voicemail" class TP_QT_EXPORT BaseConnectionVoicemailInterface : public Tp::AbstractConnectionInterface { Q_OBJECT Q_DISABLE_COPY(BaseConnectionVoicemailInterface) public: static BaseConnectionVoicemailInterfacePtr create() { return BaseConnectionVoicemailInterfacePtr(new BaseConnectionVoicemailInterface()); } template static Tp::SharedPtr create() { return Tp::SharedPtr( new BaseConnectionVoicemailInterfaceSubclass()); } QVariantMap immutableProperties() const; virtual ~BaseConnectionVoicemailInterface(); typedef Tp::Callback1 VoicemailCountCallback; void setVoicemailCountCallback(const VoicemailCountCallback &cb); typedef Tp::Callback1 VoicemailIndicatorCallback; void setVoicemailIndicatorCallback(const VoicemailIndicatorCallback &cb); typedef Tp::Callback1 VoicemailNumberCallback; void setVoicemailNumberCallback(const VoicemailNumberCallback &cb); public Q_SLOTS: void setVoicemailCount(int count); void setVoicemailIndicator(bool active); void setVoicemailNumber(const QString &voicemailNumber); protected: BaseConnectionVoicemailInterface(); private: void createAdaptor(); class Adaptee; friend class Adaptee; struct Private; friend struct Private; Private *mPriv; }; class TP_QT_EXPORT ConnectionInterfaceVoicemailAdaptor : public Tp::AbstractAdaptor { Q_OBJECT Q_CLASSINFO("D-Bus Interface", TP_QT_IFACE_CONNECTION_VOICEMAIL) Q_CLASSINFO("D-Bus Introspection", "" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" " \n" "") public: ConnectionInterfaceVoicemailAdaptor(const QDBusConnection& dbusConnection, QObject* adaptee, QObject* parent); virtual ~ConnectionInterfaceVoicemailAdaptor(); typedef Tp::MethodInvocationContextPtr< bool > VoicemailIndicatorContextPtr; typedef Tp::MethodInvocationContextPtr< QString > VoicemailNumberContextPtr; typedef Tp::MethodInvocationContextPtr< uint > VoicemailCountContextPtr; public Q_SLOTS: // METHODS bool VoicemailIndicator(const QDBusMessage& dbusMessage); QString VoicemailNumber(const QDBusMessage& dbusMessage); uint VoicemailCount(const QDBusMessage& dbusMessage); Q_SIGNALS: // SIGNALS void VoicemailCountChanged(uint count); void VoicemailIndicatorChanged(bool active); void VoicemailNumberChanged(const QString &voicemailNumber); }; class TP_QT_NO_EXPORT BaseConnectionVoicemailInterface::Adaptee : public QObject { Q_OBJECT public: Adaptee(BaseConnectionVoicemailInterface *interface); ~Adaptee(); private Q_SLOTS: void voicemailIndicator(const ConnectionInterfaceVoicemailAdaptor::VoicemailIndicatorContextPtr &context); void voicemailNumber(const ConnectionInterfaceVoicemailAdaptor::VoicemailNumberContextPtr &context); void voicemailCount(const ConnectionInterfaceVoicemailAdaptor::VoicemailCountContextPtr &context); Q_SIGNALS: void voicemailCountChanged(uint count); void voicemailIndicatorChanged(bool active); void voicemailNumberChanged(const QString &voicemailNumber); public: BaseConnectionVoicemailInterface *mInterface; }; #endif telepathy-ofono-0.2+16.04.20151120/tests/0000755000015300001610000000000012623676450020172 5ustar pbuserpbgroup00000000000000telepathy-ofono-0.2+16.04.20151120/tests/approvercall.cpp0000644000015300001610000001144212623675611023370 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include "approvercall.h" #include #include #include #include #include Approver::Approver(QObject* parent) : QObject(parent), Tp::AbstractClientApprover(channelFilters()) { } Approver::~Approver() { } Tp::ChannelClassSpecList Approver::channelFilters() const { Tp::ChannelClassSpecList specList; specList << Tp::ChannelClassSpec::audioCall(); return specList; } void Approver::addDispatchOperation(const Tp::MethodInvocationContextPtr<> &context, const Tp::ChannelDispatchOperationPtr &dispatchOperation) { bool willHandle = false; QList channels = dispatchOperation->channels(); Q_FOREACH (Tp::ChannelPtr channel, channels) { Tp::CallChannelPtr callChannel = Tp::CallChannelPtr::dynamicCast(channel); if (!callChannel.isNull()) { Tp::PendingReady *pr = callChannel->becomeReady(Tp::Features() << Tp::CallChannel::FeatureCore << Tp::CallChannel::FeatureCallState << Tp::CallChannel::FeatureLocalHoldState); mChannels[pr] = callChannel; connect(pr, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onChannelReady(Tp::PendingOperation*))); callChannel->setProperty("accountId", QVariant(dispatchOperation->account()->uniqueIdentifier())); willHandle = true; continue; } } if (willHandle) { mDispatchOps.append(dispatchOperation); } context->setFinished(); } void Approver::acceptCall() { Q_FOREACH (Tp::ChannelDispatchOperationPtr dispatchOperation, mDispatchOps) { QList channels = dispatchOperation->channels(); Q_FOREACH (Tp::ChannelPtr channel, channels) { if (dispatchOperation->possibleHandlers().contains(TELEPHONY_SERVICE_HANDLER)) { dispatchOperation->handleWith(TELEPHONY_SERVICE_HANDLER); mDispatchOps.removeAll(dispatchOperation); } } } } void Approver::rejectCall() { Q_FOREACH (Tp::ChannelDispatchOperationPtr dispatchOperation, mDispatchOps) { QList channels = dispatchOperation->channels(); Q_FOREACH (Tp::ChannelPtr channel, channels) { if (dispatchOperation->possibleHandlers().contains(TELEPHONY_SERVICE_HANDLER)) { Tp::PendingOperation *claimop = dispatchOperation->claim(); mChannels[claimop] = dispatchOperation->channels().first(); connect(claimop, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onClaimFinished(Tp::PendingOperation*))); } } } } void Approver::onClaimFinished(Tp::PendingOperation* op) { if(!op || op->isError()) { return; } Tp::CallChannelPtr callChannel = Tp::CallChannelPtr::dynamicCast(mChannels[op]); if (callChannel) { Tp::PendingOperation *hangupop = callChannel->hangup(Tp::CallStateChangeReasonUserRequested, TP_QT_ERROR_REJECTED, QString()); mChannels[hangupop] = callChannel; connect(hangupop, SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onHangupFinished(Tp::PendingOperation*))); } } void Approver::onHangupFinished(Tp::PendingOperation* op) { if(!op || op->isError()) { return; } mDispatchOps.removeAll(dispatchOperation(op)); mChannels.remove(op); } Tp::ChannelDispatchOperationPtr Approver::dispatchOperation(Tp::PendingOperation *op) { Tp::ChannelPtr channel = mChannels[op]; QString accountId = channel->property("accountId").toString(); Q_FOREACH (Tp::ChannelDispatchOperationPtr dispatchOperation, mDispatchOps) { if (dispatchOperation->account()->uniqueIdentifier() == accountId) { return dispatchOperation; } } return Tp::ChannelDispatchOperationPtr(); } void Approver::onChannelReady(Tp::PendingOperation *op) { Q_EMIT newCall(); } telepathy-ofono-0.2+16.04.20151120/tests/PhoneUtilsTest.cpp0000644000015300001610000000720212623675611023627 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: * Gustavo Pichorim Boiko */ #include #include #include "phoneutils_p.h" class PhoneUtilsTest : public QObject { Q_OBJECT private Q_SLOTS: void testIsPhoneNumber_data(); void testIsPhoneNumber(); void testComparePhoneNumbers_data(); void testComparePhoneNumbers(); }; void PhoneUtilsTest::testIsPhoneNumber_data() { QTest::addColumn("number"); QTest::addColumn("expectedResult"); QTest::newRow("simple number") << "12345678" << true; QTest::newRow("number with dash") << "1234-5678" << true; QTest::newRow("number with area code") << "(123)12345678" << true; QTest::newRow("number with extension") << "12345678#123" << true; QTest::newRow("number with comma") << "33333333,1,1" << false; QTest::newRow("number with semicolon") << "33333333;1" << false; QTest::newRow("short/emergency number") << "190" << true; QTest::newRow("non phone numbers") << "abcdefg" << false; QTest::newRow("phone number with dots") << "+31 (475) 12.34.56" << true; QTest::newRow("number with slash") << "+421 2/123 456 78" << true; } void PhoneUtilsTest::testIsPhoneNumber() { QFETCH(QString, number); QFETCH(bool, expectedResult); bool result = PhoneUtils::isPhoneNumber(number); QCOMPARE(result, expectedResult); } void PhoneUtilsTest::testComparePhoneNumbers_data() { QTest::addColumn("number1"); QTest::addColumn("number2"); QTest::addColumn("expectedResult"); QTest::newRow("string equal") << "12345678" << "12345678" << true; QTest::newRow("number with dash") << "1234-5678" << "12345678" << true; QTest::newRow("number with area code") << "12312345678" << "12345678" << true; QTest::newRow("number with extension") << "12345678#123" << "12345678" << true; QTest::newRow("both numbers with extension") << "(123)12345678#1" << "12345678#1" << true; QTest::newRow("numbers with different extension") << "1234567#1" << "1234567#2" << false; QTest::newRow("short/emergency numbers") << "190" << "190" << true; QTest::newRow("different numbers") << "12345678" << "1234567" << false; QTest::newRow("both non phone numbers") << "abcdefg" << "abcdefg" << true; QTest::newRow("different non phone numbers") << "abcdefg" << "bcdefg" << false; QTest::newRow("phone number and custom string") << "abc12345678" << "12345678" << true; QTest::newRow("phone number with dots") << "+31 (475) 12.34.56" << "+31 (475) 12 34 56" << true; QTest::newRow("phone number with slash") << "+421 2/123 456 78" << "212345678" << true; // FIXME: check what other cases we need to test here" } void PhoneUtilsTest::testComparePhoneNumbers() { QFETCH(QString, number1); QFETCH(QString, number2); QFETCH(bool, expectedResult); bool result = PhoneUtils::comparePhoneNumbers(number1, number2); QCOMPARE(result, expectedResult); } QTEST_MAIN(PhoneUtilsTest) #include "PhoneUtilsTest.moc" telepathy-ofono-0.2+16.04.20151120/tests/CMakeLists.txt0000644000015300001610000000453512623675611022737 0ustar pbuserpbgroup00000000000000include_directories( ${CMAKE_CURRENT_BINARY_DIR} ${CMAKE_SOURCE_DIR} ) macro(generate_test TESTNAME USE_DBUS) add_executable(${TESTNAME} ${ARGN} ${TESTNAME}.cpp) qt5_use_modules(${TESTNAME} Core DBus Test) set(TEST_COMMAND ) if (${USE_DBUS}) set(TEST_COMMAND -p ${CMAKE_CURRENT_BINARY_DIR}/${TESTNAME} -p -xunitxml -p -o -p ${CMAKE_BINARY_DIR}/test_${TESTNAME}.xml) add_test(${TESTNAME} ${DBUS_RUNNER} --keep-env --task ${CMAKE_CURRENT_BINARY_DIR}/dbus-test-wrapper.sh ${TEST_COMMAND}) else (${USE_DBUS}) add_test(${TESTNAME} ${CMAKE_CURRENT_BINARY_DIR}/${TESTNAME} -xunitxml -o ${CMAKE_BINARY_DIR}/test_${TESTNAME}.xml) endif(${USE_DBUS}) # force telepathy not to use system approvers when available, # also force usage of memory backend in history-service set(TMPDIR "/tmp/tpofono_test_home") set(TEST_ENVIRONMENT "HOME=${TMPDIR}; HISTORY_SQLITE_DBPATH=:memory:; TP_OFONO_SQLITE_DBPATH=:memory:; XDG_CONFIG_HOME=${TMPDIR}; XDG_DATA_HOME=${TMPDIR}; XDG_CACHE_DIR=${TMPDIR}; XDG_CACHE_HOME=${TMPDIR}; XDG_DATA_DIRS=${TMPDIR}; MC_ACCOUNT_DIR=${TMPDIR}; MC_MANAGER_DIR=${TMPDIR}; MC_CLIENTS_DIR=${TMPDIR}; PA_DISABLED=1") set_tests_properties(${TESTNAME} PROPERTIES ENVIRONMENT "${TEST_ENVIRONMENT}" TIMEOUT 30) target_link_libraries(${TESTNAME} ${TP_QT5_LIBRARIES} ${LibPhoneNumber_LIBRARIES} ) endmacro(generate_test) configure_file(dbus-test-wrapper.sh.in ${CMAKE_CURRENT_BINARY_DIR}/dbus-test-wrapper.sh) generate_test(PhoneUtilsTest False ${CMAKE_SOURCE_DIR}/phoneutils.cpp) if (DBUS_RUNNER) generate_test(ConnectionTest True telepathyhelper.cpp ofonomockcontroller.cpp) generate_test(ProtocolTest True telepathyhelper.cpp) generate_test(MessagesTest True telepathyhelper.cpp ofonomockcontroller.cpp handler.cpp approvertext.cpp) generate_test(CallTest True telepathyhelper.cpp ofonomockcontroller.cpp handler.cpp approvercall.cpp) endif(DBUS_RUNNER) add_subdirectory(mock) telepathy-ofono-0.2+16.04.20151120/tests/mock/0000755000015300001610000000000012623676450021123 5ustar pbuserpbgroup00000000000000telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomodem.cpp0000644000015300001610000001464712623675611024003 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonomodem.h" #include "ofonointerface.h" #include "ofonomodemmanager.h" #include "ofonomessage.h" #include "ofonovoicecall.h" #include "modemprivate.h" OfonoModem::OfonoModem(SelectionSetting setting, const QString &modemPath, QObject *parent) : QObject(parent), m_selectionSetting(setting) { m_mm = new OfonoModemManager(this); connect(m_mm, SIGNAL(modemAdded(QString)), this, SLOT(modemAdded(QString))); connect(m_mm, SIGNAL(modemRemoved(QString)), this, SLOT(modemRemoved(QString))); QString finalModemPath; if (setting == AutomaticSelect) finalModemPath = m_mm->modems().value(0); else if (setting == ManualSelect) if (m_mm->modems().contains(modemPath)) finalModemPath = modemPath; if (finalModemPath.isEmpty()) { finalModemPath = "/"; } if (!modemData.keys().contains(finalModemPath)) { modemData[finalModemPath] = new ModemPrivate(); } m_if = new OfonoInterface(finalModemPath, "org.ofono.Modem", OfonoGetAllOnStartup, this); connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); connect(m_if, SIGNAL(setPropertyFailed(const QString&)), this, SLOT(setPropertyFailed(const QString&))); m_isValid = m_mm->modems().contains(finalModemPath); } OfonoModem::~OfonoModem() { } void OfonoModem::propertyChanged(const QString& property, const QVariant& value) { if (property == "Online") Q_EMIT onlineChanged(value.value()); else if (property == "Powered") Q_EMIT poweredChanged(value.value()); else if (property == "Lockdown") Q_EMIT lockdownChanged(value.value()); else if (property == "Emergency") Q_EMIT emergencyChanged(value.value()); else if (property == "Name") Q_EMIT nameChanged(value.value()); else if (property == "Manufacturer") Q_EMIT manufacturerChanged(value.value()); else if (property == "Model") Q_EMIT modelChanged(value.value()); else if (property == "Revision") Q_EMIT revisionChanged(value.value()); else if (property == "Serial") Q_EMIT serialChanged(value.value()); else if (property == "Type") Q_EMIT typeChanged(value.value()); else if (property == "Features") Q_EMIT featuresChanged(value.value()); else if (property == "Interfaces") Q_EMIT interfacesChanged(value.value()); } void OfonoModem::setPropertyFailed(const QString& property) { if (property == "Online") Q_EMIT setOnlineFailed(); else if (property == "Powered") Q_EMIT setPoweredFailed(); else if (property == "Lockdown") Q_EMIT setLockdownFailed(); } void OfonoModem::modemAdded(const QString& /*modem*/) { modemsChanged(); } void OfonoModem::modemRemoved(const QString& /*modem*/) { modemsChanged(); } void OfonoModem::modemsChanged() { // validity has changed if (isValid() != m_mm->modems().contains(path())) { m_isValid = m_mm->modems().contains(path()); Q_EMIT validityChanged(isValid()); } if (!m_mm->modems().contains(path())) { if (m_selectionSetting == AutomaticSelect) { QString modemPath = m_mm->modems().value(0); if (modemPath.isEmpty()) { modemPath = "/"; } m_if->setPath(modemPath); Q_EMIT pathChanged(modemPath); } else if (m_selectionSetting == ManualSelect) { m_if->setPath("/"); } } // validity has changed if (isValid() != m_mm->modems().contains(path())) { m_isValid = m_mm->modems().contains(path()); Q_EMIT validityChanged(isValid()); } } bool OfonoModem::isValid() const { return m_isValid; } QString OfonoModem::path() const { return m_if->path(); } QString OfonoModem::errorName() const { return m_if->errorMessage(); } QString OfonoModem::errorMessage() const { return m_if->errorMessage(); } bool OfonoModem::powered() const { return m_if->properties()["Powered"].value(); } void OfonoModem::setPowered(bool powered) { m_if->setProperty("Powered", qVariantFromValue(powered)); } bool OfonoModem::online() const { return m_if->properties()["Online"].value(); } void OfonoModem::setOnline(bool online) { m_if->setProperty("Online", qVariantFromValue(online)); } bool OfonoModem::lockdown() const { return m_if->properties()["Lockdown"].value(); } void OfonoModem::setLockdown(bool lockdown) { m_if->setProperty("Lockdown", qVariantFromValue(lockdown)); } bool OfonoModem::emergency() const { return m_if->properties()["Emergency"].value(); } QString OfonoModem::name() const { return m_if->properties()["Name"].value(); } QString OfonoModem::manufacturer() const { return m_if->properties()["Manufacturer"].value(); } QString OfonoModem::model() const { return m_if->properties()["Model"].value(); } QString OfonoModem::revision() const { return m_if->properties()["Revision"].value(); } QString OfonoModem::serial() const { return m_if->properties()["Serial"].value(); } QString OfonoModem::type() const { return m_if->properties()["Type"].value(); } QStringList OfonoModem::features() const { return m_if->properties()["Features"].value(); } QStringList OfonoModem::interfaces() const { return m_if->properties()["Interfaces"].value(); } telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonosimmanager.cpp0000644000015300001610000002201012623675611025004 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonosimmanager.h" #include "ofonointerface.h" #include "simmanagerprivate.h" OfonoSimManager::OfonoSimManager(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent) : OfonoModemInterface(modemSetting, modemPath, "org.ofono.SimManager", OfonoGetAllOnStartup, parent) { qRegisterMetaType("OfonoServiceNumbers"); qRegisterMetaType("OfonoPinRetries"); m_if->setPath(OFONO_MOCK_SIM_MANAGER_OBJECT); if (!simManagerData.keys().contains(modem()->path())) { simManagerData[modem()->path()] = new SimManagerPrivate(); } connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); connect(m_if, SIGNAL(setPropertyFailed(const QString&)), this, SLOT(setPropertyFailed(const QString&))); } OfonoSimManager::~OfonoSimManager() { } void OfonoSimManager::changePin(const QString &pintype, const QString &oldpin, const QString &newpin) { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "ChangePin"); request << pintype << oldpin << newpin; QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(changePinResp()), SLOT(changePinErr(const QDBusError&))); } void OfonoSimManager::enterPin(const QString &pintype, const QString &pin) { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "EnterPin"); request << pintype << pin; QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(enterPinResp()), SLOT(enterPinErr(const QDBusError&))); } void OfonoSimManager::resetPin(const QString &pintype, const QString &puk, const QString &newpin) { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "ResetPin"); request << pintype << puk << newpin; QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(resetPinResp()), SLOT(resetPinErr(const QDBusError&))); } void OfonoSimManager::lockPin(const QString &pintype, const QString &pin) { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "LockPin"); request << pintype << pin; QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(lockPinResp()), SLOT(lockPinErr(const QDBusError&))); } void OfonoSimManager::unlockPin(const QString &pintype, const QString &pin) { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "UnlockPin"); request << pintype << pin; QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(unlockPinResp()), SLOT(unlockPinErr(const QDBusError&))); } void OfonoSimManager::getIcon(quint8 id) { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "GetIcon"); request << qVariantFromValue(id); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(getIconResp(QByteArray)), SLOT(getIconErr(const QDBusError&))); } void OfonoSimManager::setSubscriberNumbers(const QStringList &numbers) { m_if->setProperty("SubscriberNumbers", qVariantFromValue(numbers)); } bool OfonoSimManager::present() const { return m_if->properties()["Present"].value(); } QString OfonoSimManager::subscriberIdentity() const { return m_if->properties()["SubscriberIdentity"].value(); } QString OfonoSimManager::mobileCountryCode() const { return m_if->properties()["MobileCountryCode"].value(); } QString OfonoSimManager::mobileNetworkCode() const { return m_if->properties()["MobileNetworkCode"].value(); } QStringList OfonoSimManager::subscriberNumbers() const { return m_if->properties()["SubscriberNumbers"].value(); } OfonoServiceNumbers OfonoSimManager::serviceNumbers() const { OfonoServiceNumbers map; m_if->properties()["ServiceNumbers"].value() >> map; return map; } QString OfonoSimManager::pinRequired() const { return m_if->properties()["PinRequired"].value(); } QStringList OfonoSimManager::lockedPins() const { return m_if->properties()["LockedPins"].value(); } QString OfonoSimManager::cardIdentifier() const { return m_if->properties()["CardIdentifier"].value(); } QStringList OfonoSimManager::preferredLanguages() const { return m_if->properties()["PreferredLanguages"].value(); } OfonoPinRetries OfonoSimManager::pinRetries() const { OfonoPinRetries retries; m_if->properties()["Retries"].value() >> retries; return retries; } bool OfonoSimManager::fixedDialing() const { return m_if->properties()["FixedDialing"].value(); } bool OfonoSimManager::barredDialing() const { return m_if->properties()["BarredDialing"].value(); } void OfonoSimManager::propertyChanged(const QString& property, const QVariant& value) { if (property == "Present") { Q_EMIT presenceChanged(value.value()); } else if (property == "SubscriberIdentity") { Q_EMIT subscriberIdentityChanged(value.value()); } else if (property == "MobileCountryCode") { Q_EMIT mobileCountryCodeChanged(value.value()); } else if (property == "MobileNetworkCode") { Q_EMIT mobileNetworkCodeChanged(value.value()); } else if (property == "SubscriberNumbers") { Q_EMIT subscriberNumbersChanged(value.value()); } else if (property == "ServiceNumbers") { OfonoServiceNumbers map; value.value() >> map; Q_EMIT serviceNumbersChanged(map); } else if (property == "PinRequired") { Q_EMIT pinRequiredChanged(value.value()); } else if (property == "LockedPins") { Q_EMIT lockedPinsChanged(value.value()); } else if (property == "CardIdentifier") { Q_EMIT cardIdentifierChanged(value.value()); } else if (property == "PreferredLanguages") { Q_EMIT preferredLanguagesChanged(value.value()); } else if (property == "Retries") { OfonoPinRetries retries; value.value() >> retries; Q_EMIT pinRetriesChanged(retries); } else if (property == "FixedDialing") { Q_EMIT fixedDialingChanged(value.value()); } else if (property == "BarredDialing") { Q_EMIT barredDialingChanged(value.value()); } } void OfonoSimManager::setPropertyFailed(const QString& property) { if (property == "SubscriberNumbers") Q_EMIT setSubscriberNumbersFailed(); } void OfonoSimManager::changePinResp() { Q_EMIT changePinComplete(true); } void OfonoSimManager::changePinErr(QDBusError error) { m_if->setError(error.name(), error.message()); Q_EMIT changePinComplete(false); } void OfonoSimManager::enterPinResp() { Q_EMIT enterPinComplete(true); } void OfonoSimManager::enterPinErr(QDBusError error) { m_if->setError(error.name(), error.message()); Q_EMIT enterPinComplete(false); } void OfonoSimManager::resetPinResp() { Q_EMIT resetPinComplete(true); } void OfonoSimManager::resetPinErr(QDBusError error) { m_if->setError(error.name(), error.message()); Q_EMIT resetPinComplete(false); } void OfonoSimManager::lockPinResp() { Q_EMIT lockPinComplete(true); } void OfonoSimManager::lockPinErr(QDBusError error) { m_if->setError(error.name(), error.message()); Q_EMIT lockPinComplete(false); } void OfonoSimManager::unlockPinResp() { Q_EMIT unlockPinComplete(true); } void OfonoSimManager::unlockPinErr(QDBusError error) { m_if->setError(error.name(), error.message()); Q_EMIT unlockPinComplete(false); } void OfonoSimManager::getIconResp(QByteArray icon) { Q_EMIT getIconComplete(true, icon); } void OfonoSimManager::getIconErr(QDBusError error) { m_if->setError(error.name(), error.message()); Q_EMIT getIconComplete(false, QByteArray()); } telepathy-ofono-0.2+16.04.20151120/tests/mock/callvolumeprivate.h0000644000015300001610000000257412623675611025040 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef CALLVOLUMEPRIVATE_H #define CALLVOLUMEPRIVATE_H #include #include #include "mock_common.h" class CallVolumePrivate : public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ofono.CallVolume") public: CallVolumePrivate(QObject *parent = 0); ~CallVolumePrivate(); Q_SIGNALS: void PropertyChanged(const QString &name, const QDBusVariant &value); public Q_SLOTS: QVariantMap GetProperties(); void SetProperty(const QString &name, const QDBusVariant &value); private: QVariantMap mProperties; }; extern QMap callVolumeData; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/modemprivate.h0000644000015300001610000000263112623675611023770 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef MODEMPRIVATE_H #define MODEMPRIVATE_H #include #include #include #include "mock_common.h" class ModemPrivate : public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ofono.Modem") public: ModemPrivate(QObject *parent = 0); ~ModemPrivate(); Q_SIGNALS: void PropertyChanged(const QString &name, const QDBusVariant& value); public Q_SLOTS: void MockSetOnline(bool online); QVariantMap GetProperties(); void SetProperty(const QString &name, const QDBusVariant& value); private: QVariantMap mProperties; }; extern QMap modemData; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/simmanagerprivate.h0000644000015300001610000000253312623675611025013 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef SIMMANAGERPRIVATE_H #define SIMMANAGERPRIVATE_H #include #include "mock_common.h" class SimManagerPrivate : public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ofono.SimManager") public: SimManagerPrivate(QObject *parent = 0); ~SimManagerPrivate(); Q_SIGNALS: void PropertyChanged(const QString &, const QDBusVariant &); public Q_SLOTS: QVariantMap GetProperties(); void SetProperty(const QString &name, const QDBusVariant &value); private: QVariantMap mProperties; }; extern QMap simManagerData; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomodemmanager.h0000644000015300001610000000336412623675611024775 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOMODEMMANAGER_H #define OFONOMODEMMANAGER_H #include #include #include #include #include "libofono-qt_global.h" //! Provides access to the list of available modems and changes in that list. class OFONO_QT_EXPORT OfonoModemManager : public QObject { Q_OBJECT public: OfonoModemManager(QObject *parent=0); ~OfonoModemManager(); //! Returns a list of d-bus object paths that represent available modems Q_INVOKABLE QStringList modems() const; Q_SIGNALS: //! Issued when a modem has been added void modemAdded(const QString &modemPath); //! Issued when a modem has been removed void modemRemoved(const QString &modemPath); private Q_SLOTS: void onModemAdded(const QDBusObjectPath &path, const QVariantMap &map); void onModemRemoved(const QDBusObjectPath &path); private: QStringList m_modems; }; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonosimmanager.h0000644000015300001610000001231312623675611024456 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOSIMMANAGER_H #define OFONOSIMMANAGER_H #include #include #include #include "ofonomodeminterface.h" #include "libofono-qt_global.h" typedef QMap OfonoServiceNumbers; Q_DECLARE_METATYPE(OfonoServiceNumbers); typedef QMap OfonoPinRetries; Q_DECLARE_METATYPE(OfonoPinRetries); //! This class is used to access oFono SIM API /*! * The API is documented in * http://git.kernel.org/?p=network/ofono/ofono.git;a=blob_plain;f=doc/sim-api.txt */ class OFONO_QT_EXPORT OfonoSimManager : public OfonoModemInterface { Q_OBJECT Q_PROPERTY(bool present READ present NOTIFY presenceChanged) Q_PROPERTY(QString subscriberIdentity READ subscriberIdentity NOTIFY subscriberIdentityChanged) Q_PROPERTY(QString mobileCountryCode READ mobileCountryCode NOTIFY mobileCountryCodeChanged) Q_PROPERTY(QString mobileNetworkCode READ mobileNetworkCode NOTIFY mobileNetworkCodeChanged) Q_PROPERTY(QStringList subscriberNumbers READ subscriberNumbers WRITE setSubscriberNumbers NOTIFY subscriberNumbersChanged) Q_PROPERTY(QString pinRequired READ pinRequired NOTIFY pinRequiredChanged) Q_PROPERTY(QStringList lockedPins READ lockedPins NOTIFY lockedPinsChanged) Q_PROPERTY(QString cardIdentifier READ cardIdentifier NOTIFY cardIdentifierChanged) Q_PROPERTY(QStringList preferredLanguages READ preferredLanguages NOTIFY preferredLanguagesChanged) Q_PROPERTY(OfonoPinRetries pinRetries READ pinRetries NOTIFY pinRetriesChanged) Q_PROPERTY(bool fixedDialing READ fixedDialing NOTIFY fixedDialingChanged) Q_PROPERTY(bool barredDialing READ barredDialing NOTIFY barredDialingChanged) public: OfonoSimManager(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent=0); ~OfonoSimManager(); /* Properties */ bool present() const; QString subscriberIdentity() const; QString mobileCountryCode() const; QString mobileNetworkCode() const; QStringList subscriberNumbers() const; OfonoServiceNumbers serviceNumbers() const; QString pinRequired() const; QStringList lockedPins() const; QString cardIdentifier() const; QStringList preferredLanguages() const; OfonoPinRetries pinRetries() const; bool fixedDialing() const; bool barredDialing() const; public Q_SLOTS: void changePin(const QString &pintype, const QString &oldpin, const QString &newpin); void enterPin(const QString &pintype, const QString &pin); void resetPin(const QString &pintype, const QString &puk, const QString &newpin); void lockPin(const QString &pintype, const QString &pin); void unlockPin(const QString &pintype, const QString &pin); void getIcon(quint8 id); void setSubscriberNumbers(const QStringList &numbers); Q_SIGNALS: void presenceChanged(bool ispresent); void subscriberIdentityChanged(const QString &imsi); void mobileCountryCodeChanged(const QString &mcc); void mobileNetworkCodeChanged(const QString &mnc); void subscriberNumbersChanged(const QStringList &msisdns); void setSubscriberNumbersFailed(); void serviceNumbersChanged(const OfonoServiceNumbers &sdns); void pinRequiredChanged(const QString &pintype); void lockedPinsChanged(const QStringList &pins); void cardIdentifierChanged(const QString &iccid); void preferredLanguagesChanged(const QStringList &languages); void pinRetriesChanged(const OfonoPinRetries &pinRetries); void fixedDialingChanged(bool fixedDialing); void barredDialingChanged(bool barredDialing); void changePinComplete(bool success); void enterPinComplete(bool success); void resetPinComplete(bool success); void lockPinComplete(bool success); void unlockPinComplete(bool success); void getIconComplete(bool success, const QByteArray &icon); private Q_SLOTS: void propertyChanged(const QString& property, const QVariant& value); void setPropertyFailed(const QString& property); void changePinResp(); void changePinErr(QDBusError error); void enterPinResp(); void enterPinErr(QDBusError error); void resetPinResp(); void resetPinErr(QDBusError error); void lockPinResp(); void lockPinErr(QDBusError error); void unlockPinResp(); void unlockPinErr(QDBusError error); void getIconResp(QByteArray icon); void getIconErr(QDBusError error); private: }; #endif /* !OFONOSIMMANAGER_H */ telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonovoicecallmanager.cpp0000644000015300001610000003500612623675611026166 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * Portions of this file are Copyright (C) 2011 Intel Corporation * Contact: Shane Bryan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonovoicecallmanager.h" #include "ofonointerface.h" #include "voicecallmanagerprivate.h" #define DIAL_TIMEOUT 30000 #define TONE_TIMEOUT 10000 #define TRANSFER_TIMEOUT 20000 #define SWAP_TIMEOUT 20000 #define HANGUP_TIMEOUT 30000 #define HOLD_TIMEOUT 30000 #define PRIVATE_CHAT_TIMEOUT 30000 #define CREATE_MULTIPARTY_TIMEOUT 30000 QDBusArgument &operator<<(QDBusArgument &argument, const OfonoVoiceCallManagerStruct &call) { argument.beginStructure(); argument << call.path << call.properties; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, OfonoVoiceCallManagerStruct &call) { argument.beginStructure(); argument >> call.path >> call.properties; argument.endStructure(); return argument; } OfonoVoiceCallManager::OfonoVoiceCallManager(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent) : OfonoModemInterface(modemSetting, modemPath, "org.ofono.VoiceCallManager", OfonoGetAllOnStartup, parent) { qDBusRegisterMetaType(); qDBusRegisterMetaType(); if (!voiceCallManagerData.keys().contains(modem()->path())) { m_if->setPath(OFONO_MOCK_VOICECALL_MANAGER_OBJECT); voiceCallManagerData[modem()->path()] = new VoiceCallManagerPrivate(); } m_calllist = getCallList(); connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); connect(this, SIGNAL(validityChanged(bool)), this, SLOT(validityChanged(bool))); connect(modem(), SIGNAL(pathChanged(QString)), this, SLOT(pathChanged(const QString&))); connectDbusSignals(path()); } OfonoVoiceCallManager::~OfonoVoiceCallManager() { } void OfonoVoiceCallManager::validityChanged(bool /*validity*/) { m_calllist = getCallList(); } void OfonoVoiceCallManager::pathChanged(const QString& path) { connectDbusSignals(path); } QStringList OfonoVoiceCallManager::getCallList() { QDBusReply reply; OfonoVoiceCallManagerList calls; QDBusMessage request; QStringList messageList; qDBusRegisterMetaType(); qDBusRegisterMetaType(); request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "GetCalls"); reply = QDBusConnection::sessionBus().call(request); calls = reply; Q_FOREACH(OfonoVoiceCallManagerStruct call, calls) { messageList<< call.path.path(); } return messageList; } void OfonoVoiceCallManager::connectDbusSignals(const QString& path) { QDBusConnection::sessionBus().disconnect("org.ofono", QString(), m_if->ifname(), "CallAdded", this, SLOT(callAddedChanged(const QDBusObjectPath&, const QVariantMap&))); QDBusConnection::sessionBus().disconnect("org.ofono", QString(), m_if->ifname(), "CallRemoved", this, SLOT(callRemovedChanged(const QDBusObjectPath&))); QDBusConnection::sessionBus().disconnect("org.ofono", QString(), m_if->ifname(), "BarringActive", this, SIGNAL(barringActive(const QString&))); QDBusConnection::sessionBus().disconnect("org.ofono", QString(), m_if->ifname(), "Forwarded", this, SIGNAL(forwarded(const QString&))); QDBusConnection::sessionBus().connect("org.ofono", path, m_if->ifname(), "CallAdded", this, SLOT(callAddedChanged(const QDBusObjectPath&, const QVariantMap&))); QDBusConnection::sessionBus().connect("org.ofono", path, m_if->ifname(), "CallRemoved", this, SLOT(callRemovedChanged(const QDBusObjectPath&))); QDBusConnection::sessionBus().connect("org.ofono", path, m_if->ifname(), "BarringActive", this, SIGNAL(barringActive(const QString&))); QDBusConnection::sessionBus().connect("org.ofono", path, m_if->ifname(), "Forwarded", this, SIGNAL(forwarded(const QString&))); } QDBusObjectPath OfonoVoiceCallManager::dial(const QString &number, const QString &callerid_hide, bool &success) { QDBusMessage request; QDBusReply reply; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "Dial"); QListarg; arg.append(QVariant(number)); arg.append(QVariant(callerid_hide)); request.setArguments(arg); reply = QDBusConnection::sessionBus().call(request); success = reply.isValid(); if (!success) { m_if->setError(reply.error().name(), reply.error().message()); } return reply; } void OfonoVoiceCallManager::hangupAll() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "HangupAll"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(hangupAllResp()), SLOT(hangupAllErr(const QDBusError&)), HANGUP_TIMEOUT); } void OfonoVoiceCallManager::sendTones(const QString &tonestring) { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "SendTones"); QListarg; arg.append(QVariant(tonestring)); request.setArguments(arg); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(sendTonesResp()), SLOT(sendTonesErr(const QDBusError&)), (TONE_TIMEOUT*tonestring.length())); } void OfonoVoiceCallManager::transfer() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "Transfer"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(transferResp()), SLOT(transferErr(const QDBusError&)), TRANSFER_TIMEOUT); } void OfonoVoiceCallManager::swapCalls() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "SwapCalls"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(swapCallsResp()), SLOT(swapCallsErr(const QDBusError&)), SWAP_TIMEOUT); } void OfonoVoiceCallManager::releaseAndAnswer() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "ReleaseAndAnswer"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(releaseAndAnswerResp()), SLOT(releaseAndAnswerErr(const QDBusError&)), HANGUP_TIMEOUT); } void OfonoVoiceCallManager::holdAndAnswer() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "HoldAndAnswer"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(holdAndAnswerResp()), SLOT(holdAndAnswerErr(const QDBusError&)), HOLD_TIMEOUT); } void OfonoVoiceCallManager::privateChat(const QString &call) { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "PrivateChat"); QListarg; arg.append(qVariantFromValue(QDBusObjectPath(call))); request.setArguments(arg); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(privateChatResp(const QList&)), SLOT(privateChatErr(const QDBusError&)), PRIVATE_CHAT_TIMEOUT); } QList OfonoVoiceCallManager::createMultiparty() { QDBusMessage request; QDBusReply > reply; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "CreateMultiparty"); reply = QDBusConnection::sessionBus().call(request); bool success = reply.isValid(); if (!success) { m_if->setError(reply.error().name(), reply.error().message()); } return reply; } void OfonoVoiceCallManager::hangupMultiparty() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "HangupMultiparty"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(hangupMultipartyResp()), SLOT(hangupMultipartyErr(const QDBusError&)), HANGUP_TIMEOUT); } void OfonoVoiceCallManager::hangupMultipartyResp() { Q_EMIT hangupMultipartyComplete(true); } void OfonoVoiceCallManager::hangupMultipartyErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT hangupMultipartyComplete(false); } void OfonoVoiceCallManager::createMultipartyResp(const QList &paths) { QStringList calls; Q_FOREACH(QDBusObjectPath path, paths) calls << path.path(); Q_EMIT createMultipartyComplete(true, calls); } void OfonoVoiceCallManager::createMultipartyErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT createMultipartyComplete(false, QStringList()); } void OfonoVoiceCallManager::privateChatResp(const QList &paths) { QStringList calls; Q_FOREACH(QDBusObjectPath path, paths) calls << path.path(); Q_EMIT privateChatComplete(true, calls); } void OfonoVoiceCallManager::privateChatErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT privateChatComplete(false, QStringList()); } void OfonoVoiceCallManager::holdAndAnswerResp() { Q_EMIT holdAndAnswerComplete(true); } void OfonoVoiceCallManager::holdAndAnswerErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT holdAndAnswerComplete(false); } void OfonoVoiceCallManager::releaseAndAnswerResp() { Q_EMIT releaseAndAnswerComplete(true); } void OfonoVoiceCallManager::releaseAndAnswerErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT releaseAndAnswerComplete(false); } void OfonoVoiceCallManager::swapCallsResp() { Q_EMIT swapCallsComplete(true); } void OfonoVoiceCallManager::swapCallsErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT swapCallsComplete(false); } void OfonoVoiceCallManager::hangupAllResp() { Q_EMIT hangupAllComplete(true); } void OfonoVoiceCallManager::hangupAllErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT hangupAllComplete(false); } void OfonoVoiceCallManager::sendTonesResp() { Q_EMIT sendTonesComplete(true); } void OfonoVoiceCallManager::sendTonesErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT sendTonesComplete(false); } void OfonoVoiceCallManager::transferResp() { Q_EMIT transferComplete(true); } void OfonoVoiceCallManager::transferErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT transferComplete(false); } QStringList OfonoVoiceCallManager::emergencyNumbers() const { return m_if->properties()["EmergencyNumbers"].value(); } void OfonoVoiceCallManager::propertyChanged(const QString &property, const QVariant &value) { if (property == "EmergencyNumbers") { Q_EMIT emergencyNumbersChanged(value.value()); } } QStringList OfonoVoiceCallManager::getCalls() const { return m_calllist; } void OfonoVoiceCallManager::callAddedChanged(const QDBusObjectPath &path, const QVariantMap& values) { m_calllist << path.path(); Q_EMIT callAdded(path.path(), values); } void OfonoVoiceCallManager::callRemovedChanged(const QDBusObjectPath &path) { m_calllist.removeAll(path.path()); Q_EMIT callRemoved(path.path()); } telepathy-ofono-0.2+16.04.20151120/tests/mock/messageprivate.cpp0000644000015300001610000000352312623675611024647 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include "messageprivateadaptor.h" QMap messageData; MessagePrivate::MessagePrivate(const QString &path, QObject *parent) : QObject(parent) { QDBusConnection::sessionBus().registerObject(path, this); QDBusConnection::sessionBus().registerService("org.ofono"); SetProperty("State", QDBusVariant(QVariant("pending"))); new MessageAdaptor(this); } MessagePrivate::~MessagePrivate() { } QVariantMap MessagePrivate::GetProperties() { return mProperties; } void MessagePrivate::SetProperty(const QString &name, const QDBusVariant& value) { qDebug() << "MessagePrivate::SetProperty" << name << value.variant(); mProperties[name] = value.variant(); Q_EMIT PropertyChanged(name, value); } void MessagePrivate::Cancel() { SetProperty("State", QDBusVariant(QVariant("failed"))); deleteLater(); } void MessagePrivate::MockMarkFailed() { SetProperty("State", QDBusVariant(QVariant("failed"))); deleteLater(); } void MessagePrivate::MockMarkSent() { SetProperty("State", QDBusVariant(QVariant("sent"))); deleteLater(); } telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomessagewaiting.cpp0000644000015300001610000000517412623675611025704 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonomessagewaiting.h" #include "ofonointerface.h" OfonoMessageWaiting::OfonoMessageWaiting(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent) : OfonoModemInterface(modemSetting, modemPath, "org.ofono.MessageWaiting", OfonoGetAllOnStartup, parent) { connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); connect(m_if, SIGNAL(setPropertyFailed(const QString&)), this, SLOT(setPropertyFailed(const QString&))); } OfonoMessageWaiting::~OfonoMessageWaiting() { } bool OfonoMessageWaiting::voicemailWaiting() const { return m_if->properties()["VoicemailWaiting"].value(); } int OfonoMessageWaiting::voicemailMessageCount() const { return m_if->properties()["VoicemailMessageCount"].value(); } QString OfonoMessageWaiting::voicemailMailboxNumber() const { return m_if->properties()["VoicemailMailboxNumber"].value(); } void OfonoMessageWaiting::setVoicemailMailboxNumber(QString mailboxnumber) { m_if->setProperty("VoicemailMailboxNumber", qVariantFromValue(mailboxnumber)); } void OfonoMessageWaiting::setPropertyFailed(const QString& property) { if (property == "VoicemailMailboxNumber") Q_EMIT setVoicemailMailboxNumberFailed(); } void OfonoMessageWaiting::propertyChanged(const QString& property, const QVariant& value) { if (property == "VoicemailWaiting") Q_EMIT voicemailWaitingChanged(value.value()); else if (property == "VoicemailMessageCount") Q_EMIT voicemailMessageCountChanged(value.value()); else if (property == "VoicemailMailboxNumber") Q_EMIT voicemailMailboxNumberChanged(value.value()); } telepathy-ofono-0.2+16.04.20151120/tests/mock/CMakeLists.txt0000644000015300001610000000330112623675611023656 0ustar pbuserpbgroup00000000000000set(library_SRCS callvolumeprivate.cpp messagemanagerprivate.cpp messageprivate.cpp modemprivate.cpp voicecallmanagerprivate.cpp voicecallprivate.cpp simmanagerprivate.cpp networkregistrationprivate.cpp ofonocallvolume.cpp ofonointerface.cpp ofonomessage.cpp ofonomessagemanager.cpp ofonomessagewaiting.cpp ofonomodem.cpp ofonomodeminterface.cpp ofonomodemmanager.cpp ofononetworkregistration.cpp ofonovoicecall.cpp ofonovoicecallmanager.cpp ofonosimmanager.cpp ) include_directories( ${CMAKE_BINARY_DIR} ) qt5_add_dbus_adaptor(library_SRCS CallVolumePrivate.xml callvolumeprivate.h CallVolumePrivate) qt5_add_dbus_adaptor(library_SRCS ModemPrivate.xml modemprivate.h ModemPrivate) qt5_add_dbus_adaptor(library_SRCS NetworkRegistrationPrivate.xml networkregistrationprivate.h NetworkRegistrationPrivate) qt5_add_dbus_adaptor(library_SRCS MessageManagerPrivate.xml messagemanagerprivate.h MessageManagerPrivate) qt5_add_dbus_adaptor(library_SRCS MessagePrivate.xml messageprivate.h MessagePrivate) qt5_add_dbus_adaptor(library_SRCS VoiceCallManagerPrivate.xml voicecallmanagerprivate.h VoiceCallManagerPrivate) qt5_add_dbus_adaptor(library_SRCS VoiceCallPrivate.xml voicecallprivate.h VoiceCallPrivate) qt5_add_dbus_adaptor(library_SRCS SimManagerPrivate.xml simmanagerprivate.h SimManagerPrivate) add_library(ofono-qt SHARED ${library_SRCS}) # Set the library version and the SOVERSION #set_target_properties(historyservice PROPERTIES # SOVERSION ${HISTORY_VERSION_MAJOR} # VERSION ${HISTORY_VERSION_MAJOR}.${HISTORY_VERSION_MINOR}.${HISTORY_VERSION_PATCH}) qt5_use_modules(ofono-qt Core DBus) telepathy-ofono-0.2+16.04.20151120/tests/mock/SimManagerPrivate.xml0000644000015300001610000000122412623675611025220 0ustar pbuserpbgroup00000000000000 telepathy-ofono-0.2+16.04.20151120/tests/mock/voicecallmanagerprivate.h0000644000015300001610000000421212623675611026160 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef VOICECALLMANAGERPRIVATE_H #define VOICECALLMANAGERPRIVATE_H #include #include #include "mock_common.h" class OfonoVoiceCall; class VoiceCallManagerPrivate : public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ofono.VoiceCallManager") public: VoiceCallManagerPrivate(QObject *parent = 0); ~VoiceCallManagerPrivate(); Q_SIGNALS: void CallRemoved(const QDBusObjectPath &obj); void CallAdded(const QDBusObjectPath &obj, const QVariantMap &value); void PropertyChanged(const QString &name, const QDBusVariant &value); void TonesReceived(const QString &tones); private Q_SLOTS: void onVoiceCallDestroyed(); public Q_SLOTS: QVariantMap GetProperties(); void SetProperty(const QString &name, const QDBusVariant &value); QDBusObjectPath MockIncomingCall(const QString &from); void MockFailNextDtmf(); QDBusObjectPath Dial(const QString &to, const QString &hideCallerId); QMap GetCalls(); void SwapCalls(); void SendTones(const QString &tones); QList CreateMultiparty(); QList PrivateChat(const QDBusObjectPath &path); private: QVariantMap mProperties; QMap mVoiceCalls; int voiceCallCount; bool failNextDtmf; }; extern QMap voiceCallManagerData; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/voicecallprivate.cpp0000644000015300001610000000607012623675611025164 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include "voicecallprivateadaptor.h" QMap voiceCallData; QMap initialCallProperties; VoiceCallPrivate::VoiceCallPrivate(const QString &path, QObject *parent) : QObject(parent), mObjectPath(path) { QDBusConnection::sessionBus().registerObject(path, this); QDBusConnection::sessionBus().registerService("org.ofono"); SetProperty("LineIdentification", QDBusVariant(QVariant(""))); SetProperty("IncomingLine", QDBusVariant(QVariant(""))); SetProperty("Name", QDBusVariant(QVariant(""))); SetProperty("Multiparty", QDBusVariant(QVariant(false))); SetProperty("State", QDBusVariant(QVariant(""))); SetProperty("StartTime", QDBusVariant(QVariant(""))); SetProperty("Information", QDBusVariant(QVariant(""))); SetProperty("Icon", QDBusVariant(QVariant(""))); SetProperty("Emergency", QDBusVariant(QVariant(false))); SetProperty("RemoteHeld", QDBusVariant(QVariant(false))); SetProperty("RemoteMultiparty", QDBusVariant(QVariant(false))); QMapIterator i(initialCallProperties[path]); while (i.hasNext()) { i.next(); SetProperty(i.key(), QDBusVariant(i.value())); } new VoiceCallAdaptor(this); } VoiceCallPrivate::~VoiceCallPrivate() { } QString VoiceCallPrivate::objectPath() const { return mObjectPath; } QVariantMap VoiceCallPrivate::GetProperties() { return mProperties; } void VoiceCallPrivate::SetProperty(const QString &name, const QDBusVariant& value) { qDebug() << "VoiceCallPrivate::SetProperty" << name << value.variant(); mProperties[name] = value.variant(); Q_EMIT PropertyChanged(name, value); } void VoiceCallPrivate::Hangup() { SetProperty("State", QDBusVariant(QVariant("disconnected"))); deleteLater(); } void VoiceCallPrivate::Answer() { if (mProperties["State"] == QString("incoming")) { SetProperty("State", QDBusVariant(QVariant("active"))); } } void VoiceCallPrivate::MockSetAlerting() { if (mProperties["State"] == QString("dialing")) { SetProperty("State", QDBusVariant(QVariant("alerting"))); } } void VoiceCallPrivate::MockAnswer() { if (mProperties["State"] == QString("dialing") || mProperties["State"] == QString("alerting")) { SetProperty("State", QDBusVariant(QVariant("active"))); } } telepathy-ofono-0.2+16.04.20151120/tests/mock/networkregistrationprivate.h0000644000015300001610000000264312623675611027016 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef NETWORKREGISTRATIONPRIVATE_H #define NETWORKREGISTRATIONPRIVATE_H #include #include "mock_common.h" class NetworkRegistrationPrivate : public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ofono.NetworkRegistration") public: NetworkRegistrationPrivate(QObject *parent = 0); ~NetworkRegistrationPrivate(); Q_SIGNALS: void PropertyChanged(const QString &, const QDBusVariant &); public Q_SLOTS: QVariantMap GetProperties(); void SetProperty(const QString &name, const QDBusVariant &value); private: QVariantMap mProperties; }; extern QMap networkRegistrationData; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomessage.h0000644000015300001610000000476512623675611023773 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOMESSAGE_H #define OFONOMESSAGE_H #include #include #include #include #include "libofono-qt_global.h" class OfonoInterface; //! This class is used to access oFono message API /*! * oFono message API is documented in * http://git.kernel.org/?p=network/ofono/ofono.git;a=blob_plain;f=doc/message-api.txt */ class OFONO_QT_EXPORT OfonoMessage : public QObject { Q_OBJECT Q_PROPERTY(QString path READ path) Q_PROPERTY(QString errorName READ errorName) Q_PROPERTY(QString errorMessage READ errorMessage) Q_PROPERTY(QString state READ state NOTIFY stateChanged) public: OfonoMessage(const QString &messageId, QObject *parent=0); OfonoMessage(const OfonoMessage &message); ~OfonoMessage(); OfonoMessage operator=(const OfonoMessage &message); bool operator==(const OfonoMessage &message); //! Returns the D-Bus object path of the message object QString path() const; //! Get the D-Bus error name of the last operation. /*! * Returns the D-Bus error name of the last operation (setting a property * or calling a method) if it has failed */ QString errorName() const; //! Get the D-Bus error message of the last operation. /*! * Returns the D-Bus error message of the last operation (setting a property * or calling a method) if it has failed */ QString errorMessage() const; QString state() const; Q_SIGNALS: void stateChanged(const QString &state); private Q_SLOTS: void propertyChanged(const QString &property, const QVariant &value); private: OfonoInterface *m_if; }; #endif // OFONOMESSAGE_H telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomodemmanager.cpp0000644000015300001610000000074612623675611025331 0ustar pbuserpbgroup00000000000000#include "ofonomodemmanager.h" #include "modemprivate.h" // mock implementation of ofono-qt OfonoModemManager::OfonoModemManager(QObject *parent) : QObject(parent) { } OfonoModemManager::~OfonoModemManager() { } QStringList OfonoModemManager::modems() const { return QStringList() << OFONO_MOCK_MODEM_OBJECT; } void OfonoModemManager::onModemAdded(const QDBusObjectPath &path, const QVariantMap &map) { } void OfonoModemManager::onModemRemoved(const QDBusObjectPath &path) { } telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonointerface.cpp0000644000015300001610000001502712623675611024633 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonointerface.h" #define GET_PROPERTIES_TIMEOUT 300000 #define SET_PROPERTY_TIMEOUT 300000 OfonoInterface::OfonoInterface(const QString& path, const QString& ifname, OfonoGetPropertySetting setting, QObject *parent) : QObject(parent) , m_path(path), m_ifname(ifname), m_getpropsetting(setting) { QDBusConnection::sessionBus().connect("org.ofono", path, ifname, "PropertyChanged", this, SLOT(onPropertyChanged(QString, QDBusVariant))); if (setting == OfonoGetAllOnStartup && path != "/") m_properties = getAllPropertiesSync(); } OfonoInterface::~OfonoInterface() { } void OfonoInterface::setPath(const QString& path) { QDBusConnection::sessionBus().disconnect("org.ofono", m_path, m_ifname, "PropertyChanged", this, SLOT(onPropertyChanged(QString, QDBusVariant))); m_path = path; QDBusConnection::sessionBus().connect("org.ofono", m_path, m_ifname, "PropertyChanged", this, SLOT(onPropertyChanged(QString, QDBusVariant))); if (m_getpropsetting == OfonoGetAllOnStartup) m_properties = getAllPropertiesSync(); else resetProperties(); } QVariantMap OfonoInterface::properties() const { return m_properties; } void OfonoInterface::resetProperties() { m_properties = QVariantMap(); } QVariantMap OfonoInterface::getAllPropertiesSync() { QDBusReply reply; QVariantMap map; QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", m_path, m_ifname, "GetProperties"); reply = QDBusConnection::sessionBus().call(request); map = reply; Q_FOREACH (QString property, map.keys()) { Q_EMIT propertyChanged(property, map[property]); } return map; } void OfonoInterface::requestProperty(const QString& name) { if (m_pendingProperty.length() > 0) { // FIXME: should indicate that a get/setProperty is already in progress setError(QString(), QString("Already in progress")); Q_EMIT requestPropertyComplete(false, name, QVariant()); return; } if (m_properties.keys().contains(name)) { Q_EMIT requestPropertyComplete(true, name, m_properties[name]); return; } QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", m_path, m_ifname, "GetProperties"); bool result = QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(getPropertiesAsyncResp(QVariantMap)), SLOT(getPropertiesAsyncErr(const QDBusError&)), GET_PROPERTIES_TIMEOUT); if (!result) { // FIXME: should indicate that sending a message failed setError(QString(), QString("Sending a message failed")); Q_EMIT requestPropertyComplete(false, name, QVariant()); return; } m_pendingProperty = name; } void OfonoInterface::getPropertiesAsyncResp(QVariantMap properties) { QString prop = m_pendingProperty; m_properties = properties; m_pendingProperty = QString(); if (m_properties.keys().contains(prop)) { Q_EMIT requestPropertyComplete(true, prop, m_properties[prop]); } else { // FIXME: should indicate that property is not available setError(QString(), QString("Property not available")); Q_EMIT requestPropertyComplete(false, prop, QVariant()); } Q_FOREACH (QString property, properties.keys()) { Q_EMIT propertyChanged(property, properties[property]); } } void OfonoInterface::getPropertiesAsyncErr(const QDBusError& error) { QString prop = m_pendingProperty; setError(error.name(), error.message()); m_pendingProperty = QString(); Q_EMIT requestPropertyComplete(false, prop, QVariant()); } void OfonoInterface::onPropertyChanged(QString property, QDBusVariant value) { qDebug() << "OfonoInterface::onPropertyChanged" << property << value.variant(); m_properties[property] = value.variant(); Q_EMIT propertyChanged(property, value.variant()); } void OfonoInterface::setProperty(const QString& name, const QVariant& property, const QString& password) { if (m_pendingProperty.length() > 0) { // FIXME: should indicate that a get/setProperty is already in progress setError(QString(), QString("Already in progress")); Q_EMIT setPropertyFailed(name); return; } QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", m_path, m_ifname, "SetProperty"); QVariantList arguments; arguments << QVariant(name) << QVariant::fromValue(QDBusVariant(property)); if (!password.isNull()) arguments << QVariant(password); request.setArguments(arguments); bool result = QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(setPropertyResp()), SLOT(setPropertyErr(const QDBusError&)), SET_PROPERTY_TIMEOUT); if (!result) { // FIXME: should indicate that sending a message failed setError(QString(), QString("Sending a message failed")); Q_EMIT setPropertyFailed(name); return; } m_pendingProperty = name; } void OfonoInterface::setPropertyResp() { m_pendingProperty = QString(); // Q_EMIT nothing; we will get a PropertyChanged signal } void OfonoInterface::setPropertyErr(const QDBusError& error) { QString prop = m_pendingProperty; setError(error.name(), error.message()); m_pendingProperty = QString(); Q_EMIT setPropertyFailed(prop); } void OfonoInterface::setError(const QString& errorName, const QString& errorMessage) { m_errorName = errorName; m_errorMessage = errorMessage; } telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomodem.h0000644000015300001610000001273612623675611023445 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOMODEM_H #define OFONOMODEM_H #include #include #include #include "libofono-qt_global.h" class OfonoModemManager; class OfonoInterface; //! This class is used to access an oFono modem object and its properties /*! * oFono modem properties are documented in * http://git.kernel.org/?p=network/ofono/ofono.git;a=blob_plain;f=doc/modem-api.txt */ class OFONO_QT_EXPORT OfonoModem : public QObject { Q_OBJECT Q_PROPERTY(bool isValid READ isValid NOTIFY validityChanged) Q_PROPERTY(QString path READ path NOTIFY pathChanged) Q_PROPERTY(QString errorName READ errorName) Q_PROPERTY(QString errorMessage READ errorMessage) Q_PROPERTY(bool powered READ powered WRITE setPowered NOTIFY poweredChanged) Q_PROPERTY(bool online READ online WRITE setOnline NOTIFY onlineChanged) Q_PROPERTY(bool lockdown READ lockdown WRITE setLockdown NOTIFY lockdownChanged) Q_PROPERTY(bool emergency READ emergency NOTIFY emergencyChanged) Q_PROPERTY(QString name READ name NOTIFY nameChanged) Q_PROPERTY(QString manufacturer READ manufacturer NOTIFY manufacturerChanged) Q_PROPERTY(QString model READ model NOTIFY modelChanged) Q_PROPERTY(QString revision READ revision NOTIFY revisionChanged) Q_PROPERTY(QString serial READ serial NOTIFY serialChanged) Q_PROPERTY(QString type READ type NOTIFY typeChanged) Q_PROPERTY(QStringList features READ features NOTIFY featuresChanged) Q_PROPERTY(QStringList interfaces READ interfaces NOTIFY interfacesChanged) public: //! How the modem object should select a modem enum SelectionSetting { AutomaticSelect, /*!< Select the first available modem automatically; * if that modem becomes unavailable, select the first available * modem again. */ ManualSelect /*!< Do not select a modem automatically, * use the modem path provided in the constructor, and do not * attempt to select another modem if the first one becomes * unavailable. */ }; /*! * \param setting sets the modem selection policy for the object * \param modemPath if modem selection policy is ManualSelect, then this contains * the D-Bus path to the modem object. Otherwise, it is ignored. */ OfonoModem(SelectionSetting setting, const QString& modemPath, QObject *parent=0); ~OfonoModem(); //! Returns true if D-Bus modem object exists. bool isValid() const; //! Returns the D-Bus object path of the modem QString path() const; //! Get the D-Bus error name of the last operation. /*! * Returns the D-Bus error name of the last operation (setting a property * or calling a method) if it has failed */ QString errorName() const; //! Get the D-Bus error message of the last operation. /*! * Returns the D-Bus error message of the last operation (setting a property * or calling a method) if it has failed */ QString errorMessage() const; bool powered() const; bool online() const; bool lockdown() const; bool emergency() const; QString name() const; QString manufacturer() const; QString model() const; QString revision() const; QString serial() const; QString type() const; QStringList features() const; QStringList interfaces() const; public Q_SLOTS: void setPowered(bool powered); void setOnline(bool online); void setLockdown(bool lockdown); Q_SIGNALS: //! Issued when a modem becomes unavailable or available again void validityChanged(bool validity); //! Issued when the object has switched to another modem void pathChanged(QString modemPath); void poweredChanged(bool powered); void setPoweredFailed(); void onlineChanged(bool online); void setOnlineFailed(); void lockdownChanged(bool lockdown); void setLockdownFailed(); void emergencyChanged(bool emergency); void nameChanged(const QString &name); void manufacturerChanged(const QString &manufacturer); void modelChanged(const QString &model); void revisionChanged(const QString &revision); void serialChanged(const QString &serial); void typeChanged(const QString &type); void featuresChanged(const QStringList &features); void interfacesChanged(const QStringList &interfaces); private Q_SLOTS: void propertyChanged(const QString &property, const QVariant &value); void setPropertyFailed(const QString& property); void modemAdded(const QString &modem); void modemRemoved(const QString &modem); private: void modemsChanged(); private: OfonoModemManager *m_mm; OfonoInterface *m_if; SelectionSetting m_selectionSetting; bool m_isValid; }; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/MessageManagerPrivate.xml0000644000015300001610000000426612623675611026065 0ustar pbuserpbgroup00000000000000 telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonointerface.h0000644000015300001610000001152712623675611024301 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOINTERFACE_H #define OFONOINTERFACE_H #include #include #include #include #include "ofonopropertysetting.h" #include "libofono-qt_global.h" //! Basic oFono interface class /*! * This class implements basic access to properties of oFono interfaces. * It should not be instantiated directly; instead you should instantiate * interface-specific classes. */ class OFONO_QT_EXPORT OfonoInterface : public QObject { Q_OBJECT public: /*! * \param path D-Bus path to the interface * \param ifname D-Bus name of the interface * \param setting specifies how the object should handle oFono properties of the interface */ OfonoInterface(const QString &path, const QString &ifname, OfonoGetPropertySetting setting, QObject *parent=0); ~OfonoInterface(); //! Get all properties /*! * Returns the full set of current properties. If the object was constructed with * OfonoInterface::GetAllOnFirstRequest, and no properties have been explicitly queried yet * via requestProperty(), then returns nothing. */ QVariantMap properties() const; //! Request a property asynchronously. /*! * Result is returned via requestPropertyComplete() signal. */ void requestProperty(const QString &name); //! Set a property asynchronously. /*! * Result is returned via propertyChanged() signal * if setting is successful or via setPropertyFailed() signal if setting has failed. */ void setProperty(const QString &name, const QVariant &property, const QString& password=0); //! Resets the property cache. void resetProperties(); //! Get the interface D-Bus path QString path() const {return m_path;} //! Get the interface D-Bus name QString ifname() const {return m_ifname;} //! Get the D-Bus error name of the last operation. /*! * Returns the D-Bus error name of the last operation (setting a property * or calling a method) if it has failed */ QString errorName() const {return m_errorName;} //! Get the D-Bus error message of the last operation. /*! * Returns the D-Bus error message of the last operation (setting a property * or calling a method) if it has failed */ QString errorMessage() const {return m_errorMessage;} public Q_SLOTS: //! Changes the interface path /*! * This method changes the D-Bus path to the interface. * Properties are updated immediately if property setting is set to * GetAllOnStartup or reset otherwise. */ void setPath(const QString &path); //! Sets the last error explicitly void setError(const QString &errorName, const QString &errorMessage); Q_SIGNALS: //! Issued when a property has changed /*! * \param name name of the property * \param property value of the property */ void propertyChanged(const QString &name, const QVariant &property); //! Issued when requesting a property has completed /*! * \param success true if requesting a property was successful, false if there was an error * \param name name of the property * \param property value of the property */ void requestPropertyComplete(bool success, const QString &name, const QVariant &property); //! Issued when setting a property has failed /*! * \param name name of the property */ void setPropertyFailed(const QString &name); private Q_SLOTS: void onPropertyChanged(QString property, QDBusVariant value); void getPropertiesAsyncResp(QVariantMap properties); void getPropertiesAsyncErr(const QDBusError&); void setPropertyResp(); void setPropertyErr(const QDBusError& error); protected Q_SLOTS: private: QVariantMap getAllPropertiesSync(); protected: QString m_errorName; QString m_errorMessage; private: QString m_path; QString m_ifname; QVariantMap m_properties; QString m_pendingProperty; OfonoGetPropertySetting m_getpropsetting; }; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/mock_common.h0000644000015300001610000000056112623675611023575 0ustar pbuserpbgroup00000000000000#define OFONO_MOCK_MESSAGE_MANAGER_OBJECT "/OfonoMessageManager" #define OFONO_MOCK_MODEM_OBJECT "/OfonoModem" #define OFONO_MOCK_NETWORK_REGISTRATION_OBJECT "/OfonoNetworkRegistration" #define OFONO_MOCK_VOICECALL_MANAGER_OBJECT "/OfonoVoiceCallManager" #define OFONO_MOCK_CALL_VOLUME_OBJECT "/OfonoCallVolume" #define OFONO_MOCK_SIM_MANAGER_OBJECT "/OfonoSimManager" telepathy-ofono-0.2+16.04.20151120/tests/mock/ofononetworkregistration.h0000644000015300001610000000742712623675611026471 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONONETWORKREGISTRATION_H #define OFONONETWORKREGISTRATION_H #include #include #include #include #include "ofonomodeminterface.h" #include "libofono-qt_global.h" struct OfonoOperatorStruct { QDBusObjectPath path; QVariantMap properties; }; typedef QList OfonoOperatorList; Q_DECLARE_METATYPE(OfonoOperatorStruct) Q_DECLARE_METATYPE(OfonoOperatorList) //! This class is used to access oFono network registration API /*! * The API is documented in * http://git.kernel.org/?p=network/ofono/ofono.git;a=blob_plain;f=doc/network-api.txt */ class OFONO_QT_EXPORT OfonoNetworkRegistration : public OfonoModemInterface { Q_OBJECT Q_PROPERTY(QString mode READ mode NOTIFY modeChanged) Q_PROPERTY(QString status READ status NOTIFY statusChanged) Q_PROPERTY(uint locationAreaCode READ locationAreaCode NOTIFY locationAreaCodeChanged) Q_PROPERTY(uint cellId READ cellId NOTIFY cellIdChanged) Q_PROPERTY(QString mcc READ mcc NOTIFY mccChanged) Q_PROPERTY(QString mnc READ mnc NOTIFY mncChanged) Q_PROPERTY(QString technology READ technology NOTIFY technologyChanged) Q_PROPERTY(QString name READ name NOTIFY nameChanged) Q_PROPERTY(uint strength READ strength NOTIFY strengthChanged) Q_PROPERTY(QString baseStation READ baseStation NOTIFY baseStationChanged) public: OfonoNetworkRegistration(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent=0); ~OfonoNetworkRegistration(); /* Properties */ QString mode() const; QString status() const; uint locationAreaCode() const; uint cellId() const; QString mcc() const; QString mnc() const; QString technology() const; QString name() const; uint strength() const; QString baseStation() const; public Q_SLOTS: void registerOp(); void getOperators(); void scan(); Q_SIGNALS: void modeChanged(const QString &mode); void statusChanged(const QString &status); void locationAreaCodeChanged(uint locationAreaCode); void cellIdChanged(uint cellId); void mccChanged(const QString &mcc); void mncChanged(const QString &mnc); void technologyChanged(const QString &technology); void nameChanged(const QString &name); void strengthChanged(uint strength); void baseStationChanged(const QString &baseStation); void registerComplete(bool success); void getOperatorsComplete(bool success, const QStringList &operatorIds); void scanComplete(bool success, const QStringList &operatorIds); private Q_SLOTS: void propertyChanged(const QString& property, const QVariant& value); void registerResp(); void registerErr(QDBusError error); void getOperatorsResp(OfonoOperatorList list); void getOperatorsErr(QDBusError error); void scanResp(OfonoOperatorList list); void scanErr(QDBusError error); private: }; #endif /* !OFONONETWORKREGISTRATION_H */ telepathy-ofono-0.2+16.04.20151120/tests/mock/CallVolumePrivate.xml0000644000015300001610000000125512623675611025244 0ustar pbuserpbgroup00000000000000 telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonovoicecall.cpp0000644000015300001610000001651712623675611024641 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonointerface.h" #include "ofonovoicecall.h" #include "voicecallprivate.h" #define VOICECALL_TIMEOUT 30000 OfonoVoiceCall::OfonoVoiceCall(const QString& callId, QObject *parent) : QObject(parent) { m_if = new OfonoInterface(callId, "org.ofono.VoiceCall", OfonoGetAllOnStartup, this); if (!voiceCallData.keys().contains(callId)) { m_if->setPath(callId); voiceCallData[callId] = new VoiceCallPrivate(callId); } connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); QDBusConnection::sessionBus().connect("org.ofono",path(),m_if->ifname(), "DisconnectReason", this, SIGNAL(disconnectReason(const QString&))); } OfonoVoiceCall::OfonoVoiceCall(const OfonoVoiceCall& call) : QObject(call.parent()) { m_if = new OfonoInterface(call.path(), "org.ofono.VoiceCall", OfonoGetAllOnStartup, this); if (!voiceCallData.keys().contains(call.path())) { m_if->setPath(call.path()); voiceCallData[call.path()] = new VoiceCallPrivate(call.path()); } connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); QDBusConnection::sessionBus().connect("org.ofono",path(),m_if->ifname(), "DisconnectReason", this, SIGNAL(disconnectReason(const QString&))); } bool OfonoVoiceCall::operator==(const OfonoVoiceCall &call) { return path() == call.path(); } OfonoVoiceCall::~OfonoVoiceCall() { } void OfonoVoiceCall::answer() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "Answer"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(answerResp()), SLOT(answerErr(const QDBusError&)), VOICECALL_TIMEOUT); } void OfonoVoiceCall::hangup() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "Hangup"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(hangupResp()), SLOT(hangupErr(const QDBusError&)), VOICECALL_TIMEOUT); } void OfonoVoiceCall::deflect(const QString &number) { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "Deflect"); QListarg; arg.append(QVariant(number)); request.setArguments(arg); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(deflectResp()), SLOT(deflectErr(const QDBusError&)), VOICECALL_TIMEOUT); } void OfonoVoiceCall::answerResp() { Q_EMIT answerComplete(true); } void OfonoVoiceCall::answerErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT answerComplete(false); } void OfonoVoiceCall::hangupResp() { Q_EMIT hangupComplete(true); } void OfonoVoiceCall::hangupErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT hangupComplete(false); } void OfonoVoiceCall::deflectResp() { Q_EMIT deflectComplete(true); } void OfonoVoiceCall::deflectErr(const QDBusError &error) { m_if->setError(error.name(), error.message()); Q_EMIT deflectComplete(false); } QString OfonoVoiceCall::incomingLine() const { return m_if->properties()["IncomingLine"].value(); } QString OfonoVoiceCall::lineIdentification() const { return m_if->properties()["LineIdentification"].value(); } QString OfonoVoiceCall::name() const { return m_if->properties()["Name"].value(); } QString OfonoVoiceCall::state() const { return m_if->properties()["State"].value(); } QString OfonoVoiceCall::startTime() const { return m_if->properties()["StartTime"].value(); } QString OfonoVoiceCall::information() const { return m_if->properties()["Information"].value(); } bool OfonoVoiceCall::multiparty() const { return m_if->properties()["Multiparty"].value(); } bool OfonoVoiceCall::emergency() const { return m_if->properties()["Emergency"].value(); } quint8 OfonoVoiceCall::icon() const { return m_if->properties()["Icon"].value(); } bool OfonoVoiceCall::remoteHeld() const { return m_if->properties()["RemoteHeld"].value(); } bool OfonoVoiceCall::remoteMultiparty() const { return m_if->properties()["RemoteMultiparty"].value(); } void OfonoVoiceCall::propertyChanged(const QString &property, const QVariant &value) { if (property == "LineIdentification") { Q_EMIT lineIdentificationChanged(value.value()); } else if (property == "Name") { Q_EMIT nameChanged(value.value()); } else if (property == "State") { Q_EMIT stateChanged(value.value()); } else if (property == "Information") { Q_EMIT informationChanged(value.value()); } else if (property == "IncomingLine") { Q_EMIT incomingLineChanged(value.value()); } else if (property == "Multiparty") { Q_EMIT multipartyChanged(value.value()); } else if (property == "Emergency") { Q_EMIT emergencyChanged(value.value()); } else if (property == "StartTime") { Q_EMIT startTimeChanged(value.value()); } else if (property == "Icon") { Q_EMIT iconChanged(value.value()); } else if (property == "RemoteHeld") { Q_EMIT remoteHeldChanged(value.value()); } else if (property == "RemoteMultiparty") { Q_EMIT remoteMultipartyChanged(value.value()); } } QString OfonoVoiceCall::path() const { return m_if->path(); } QString OfonoVoiceCall::errorName() const { return m_if->errorName(); } QString OfonoVoiceCall::errorMessage() const { return m_if->errorMessage(); } telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomodeminterface.cpp0000644000015300001610000000502012623675611025645 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonomodeminterface.h" #include "ofonomodem.h" #include "ofonointerface.h" OfonoModemInterface::OfonoModemInterface(OfonoModem::SelectionSetting modemSetting, const QString& modemPath, const QString& ifname, OfonoGetPropertySetting propertySetting, QObject *parent) : QObject(parent) { m_m = new OfonoModem(modemSetting, modemPath, this); connect(m_m, SIGNAL(validityChanged(bool)), this, SLOT(modemValidityChanged(bool))); connect(m_m, SIGNAL(interfacesChanged(QStringList)), this, SLOT(interfacesChanged(QStringList))); m_if = new OfonoInterface(m_m->path(), ifname, propertySetting, this); connect(m_m, SIGNAL(pathChanged(QString)), m_if, SLOT(setPath(const QString&))); m_isValid = checkValidity(); } OfonoModemInterface::~OfonoModemInterface() { } bool OfonoModemInterface::isValid() const { return m_isValid; } OfonoModem* OfonoModemInterface::modem() const { return m_m; } bool OfonoModemInterface::checkValidity() { return (m_m->isValid() && m_m->interfaces().contains(m_if->ifname())); } void OfonoModemInterface::updateValidity() { if (isValid() != checkValidity()) { m_isValid = checkValidity(); Q_EMIT validityChanged(isValid()); } } void OfonoModemInterface::modemValidityChanged(bool /*validity*/) { updateValidity(); } void OfonoModemInterface::interfacesChanged(const QStringList& /*interfaces*/) { updateValidity(); } QString OfonoModemInterface::path() const { return m_if->path(); } QString OfonoModemInterface::errorName() const { return m_if->errorName(); } QString OfonoModemInterface::errorMessage() const { return m_if->errorMessage(); } telepathy-ofono-0.2+16.04.20151120/tests/mock/VoiceCallManagerPrivate.xml0000644000015300001610000000412612623675611026335 0ustar pbuserpbgroup00000000000000 telepathy-ofono-0.2+16.04.20151120/tests/mock/callvolumeprivate.cpp0000644000015300001610000000302312623675611025361 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include "callvolumeprivateadaptor.h" QMap callVolumeData; CallVolumePrivate::CallVolumePrivate(QObject *parent) : QObject(parent) { QDBusConnection::sessionBus().registerObject(OFONO_MOCK_CALL_VOLUME_OBJECT, this); QDBusConnection::sessionBus().registerService("org.ofono"); SetProperty("Muted", QDBusVariant(QVariant(false))); new CallVolumeAdaptor(this); } CallVolumePrivate::~CallVolumePrivate() { } QVariantMap CallVolumePrivate::GetProperties() { return mProperties; } void CallVolumePrivate::SetProperty(const QString &name, const QDBusVariant& value) { qDebug() << "CallVolumePrivate::SetProperty" << name << value.variant(); mProperties[name] = value.variant(); Q_EMIT PropertyChanged(name, value); } telepathy-ofono-0.2+16.04.20151120/tests/mock/ofononetworkregistration.cpp0000644000015300001610000001513712623675611027021 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofononetworkregistration.h" #include "ofonointerface.h" #include "modemprivate.h" #include "networkregistrationprivate.h" #define REGISTER_TIMEOUT 300000 #define SCAN_TIMEOUT 300000 QDBusArgument &operator<<(QDBusArgument &argument, const OfonoOperatorStruct &op) { argument.beginStructure(); argument << op.path << op.properties; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, OfonoOperatorStruct &op) { argument.beginStructure(); argument >> op.path >> op.properties; argument.endStructure(); return argument; } OfonoNetworkRegistration::OfonoNetworkRegistration(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent) : OfonoModemInterface(modemSetting, modemPath, "org.ofono.NetworkRegistration", OfonoGetAllOnStartup, parent) { qDBusRegisterMetaType(); qDBusRegisterMetaType(); m_if->setPath(OFONO_MOCK_NETWORK_REGISTRATION_OBJECT); if (!networkRegistrationData.keys().contains(modem()->path())) { networkRegistrationData[modem()->path()] = new NetworkRegistrationPrivate(); } connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); } OfonoNetworkRegistration::~OfonoNetworkRegistration() { } void OfonoNetworkRegistration::registerOp() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", OFONO_MOCK_NETWORK_REGISTRATION_OBJECT, m_if->ifname(), "Register"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(registerResp()), SLOT(registerErr(const QDBusError&)), REGISTER_TIMEOUT); } void OfonoNetworkRegistration::scan() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", OFONO_MOCK_NETWORK_REGISTRATION_OBJECT, m_if->ifname(), "Scan"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(scanResp(OfonoOperatorList)), SLOT(scanErr(const QDBusError&)), REGISTER_TIMEOUT); } void OfonoNetworkRegistration::getOperators() { QDBusMessage request; request = QDBusMessage::createMethodCall("org.ofono", OFONO_MOCK_NETWORK_REGISTRATION_OBJECT, m_if->ifname(), "GetOperators"); QDBusConnection::sessionBus().callWithCallback(request, this, SLOT(getOperatorsResp(OfonoOperatorList)), SLOT(getOperatorsErr(const QDBusError&)), SCAN_TIMEOUT); } QString OfonoNetworkRegistration::mode() const { return m_if->properties()["Mode"].value(); } QString OfonoNetworkRegistration::status() const { return m_if->properties()["Status"].value(); } uint OfonoNetworkRegistration::locationAreaCode() const { return m_if->properties()["LocationAreaCode"].value(); } uint OfonoNetworkRegistration::cellId() const { return m_if->properties()["CellId"].value(); } QString OfonoNetworkRegistration::mcc() const { return m_if->properties()["MobileCountryCode"].value(); } QString OfonoNetworkRegistration::mnc() const { return m_if->properties()["MobileNetworkCode"].value(); } QString OfonoNetworkRegistration::technology() const { return m_if->properties()["Technology"].value(); } QString OfonoNetworkRegistration::name() const { return m_if->properties()["Name"].value(); } uint OfonoNetworkRegistration::strength() const { return m_if->properties()["Strength"].value(); } QString OfonoNetworkRegistration::baseStation() const { return m_if->properties()["BaseStation"].value(); } void OfonoNetworkRegistration::propertyChanged(const QString& property, const QVariant& value) { if (property == "Mode") { Q_EMIT modeChanged(value.value()); } else if (property == "Status") { Q_EMIT statusChanged(value.value()); } else if (property == "LocationAreaCode") { Q_EMIT locationAreaCodeChanged(value.value()); } else if (property == "CellId") { Q_EMIT cellIdChanged(value.value()); } else if (property == "MobileCountryCode") { Q_EMIT mccChanged(value.value()); } else if (property == "MobileNetworkCode") { Q_EMIT mncChanged(value.value()); } else if (property == "Technology") { Q_EMIT technologyChanged(value.value()); } else if (property == "Name") { Q_EMIT nameChanged(value.value()); } else if (property == "Strength") { Q_EMIT strengthChanged(value.value()); } else if (property == "BaseStation") { Q_EMIT baseStationChanged(value.value()); } } void OfonoNetworkRegistration::registerResp() { Q_EMIT registerComplete(true); } void OfonoNetworkRegistration::registerErr(QDBusError error) { m_if->setError(error.name(), error.message()); Q_EMIT registerComplete(false); } void OfonoNetworkRegistration::getOperatorsResp(OfonoOperatorList list) { QStringList oplist; Q_FOREACH(OfonoOperatorStruct op, list) { oplist << op.path.path(); } Q_EMIT getOperatorsComplete(true, oplist); } void OfonoNetworkRegistration::getOperatorsErr(QDBusError error) { m_if->setError(error.name(), error.message()); Q_EMIT getOperatorsComplete(false, QStringList()); } void OfonoNetworkRegistration::scanResp(OfonoOperatorList list) { QStringList oplist; Q_FOREACH(OfonoOperatorStruct op, list) { oplist << op.path.path(); } Q_EMIT scanComplete(true, oplist); } void OfonoNetworkRegistration::scanErr(QDBusError error) { m_if->setError(error.name(), error.message()); Q_EMIT scanComplete(false, QStringList()); } telepathy-ofono-0.2+16.04.20151120/tests/mock/messagemanagerprivate.h0000644000015300001610000000400612623675611025644 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef MESSAGEMANAGERPRIVATE_H #define MESSAGEMANAGERPRIVATE_H #include #include #include "mock_common.h" class OfonoMessage; class MessageManagerPrivate : public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ofono.MessageManager") public: MessageManagerPrivate(QObject *parent = 0); ~MessageManagerPrivate(); Q_SIGNALS: void MessageRemoved(const QDBusObjectPath &obj); void PropertyChanged(const QString &name, const QDBusVariant &value); void MessageAdded(const QDBusObjectPath &obj, const QVariantMap &value); void IncomingMessage(const QString &text, const QVariantMap &info); void StatusReport(const QString &message, const QVariantMap &info); private Q_SLOTS: void onMessageDestroyed(); public Q_SLOTS: QVariantMap GetProperties(); void SetProperty(const QString &name, const QDBusVariant &value); void MockSendMessage(const QString &from, const QString &text); QDBusObjectPath SendMessage(const QString &to, const QString &text); void MockStatusReport(const QString &message, bool success); private: QVariantMap mProperties; QMap mMessages; int messageCount; }; extern QMap messageManagerData; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonopropertysetting.h0000644000015300001610000000243212623675611025616 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOPROPERTYSETTING_H #define OFONOPROPERTYSETTING_H //! How to handle getting the properties enum OfonoGetPropertySetting { OfonoGetAllOnStartup, /*!< Get all properties synchronously on startup; * they would be immediately available. */ OfonoGetAllOnFirstRequest /*!< Do not get properties on startup; * get them in an asynhronous way when the first * property is requested. */ }; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonovoicecallmanager.h0000644000015300001610000001070612623675611025633 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * Portions of this file are Copyright (C) 2011 Intel Corporation * Contact: Shane Bryan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOVOICECALLMANAGER_H #define OFONOVOICECALLMANAGER_H #include #include #include #include #include "ofonomodeminterface.h" #include "libofono-qt_global.h" struct OfonoVoiceCallManagerStruct { QDBusObjectPath path; QVariantMap properties; }; typedef QList OfonoVoiceCallManagerList; Q_DECLARE_METATYPE(OfonoVoiceCallManagerStruct) Q_DECLARE_METATYPE(OfonoVoiceCallManagerList) //! This class is used to access oFono voice call manager API /*! * The API is documented in * http://git.kernel.org/?p=network/ofono/ofono.git;a=blob_plain;f=doc/voicecallmanager-api.txt */ class OFONO_QT_EXPORT OfonoVoiceCallManager : public OfonoModemInterface { Q_OBJECT Q_PROPERTY(QStringList emergencyNumbers READ emergencyNumbers NOTIFY emergencyNumbersChanged) public: OfonoVoiceCallManager(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent=0); ~OfonoVoiceCallManager(); /* Properties */ QStringList emergencyNumbers() const; Q_INVOKABLE QStringList getCalls() const; public Q_SLOTS: QDBusObjectPath dial(const QString &number, const QString &callerid_hide, bool &success); void hangupAll(); void sendTones(const QString &tonestring); void transfer(); void swapCalls(); void releaseAndAnswer(); void holdAndAnswer(); void privateChat(const QString &path); QList createMultiparty(); void hangupMultiparty(); Q_SIGNALS: void emergencyNumbersChanged(const QStringList &numbers); void callAdded(const QString &call, const QVariantMap &values); void callRemoved(const QString &call); void hangupAllComplete(const bool status); void sendTonesComplete(const bool status); void transferComplete(const bool status); void swapCallsComplete(const bool status); void releaseAndAnswerComplete(const bool status); void holdAndAnswerComplete(const bool status); void privateChatComplete(const bool status, const QStringList& calls); void createMultipartyComplete(const bool status, const QStringList& calls); void hangupMultipartyComplete(const bool status); void barringActive(const QString &type); void forwarded(const QString &type); private Q_SLOTS: void validityChanged(bool); void pathChanged(const QString& path); void propertyChanged(const QString &property, const QVariant &value); void callAddedChanged(const QDBusObjectPath &call, const QVariantMap &values); void callRemovedChanged(const QDBusObjectPath &call); void hangupAllResp(); void hangupAllErr(const QDBusError &error); void sendTonesResp(); void sendTonesErr(const QDBusError &error); void transferResp(); void transferErr(const QDBusError &error); void swapCallsResp(); void swapCallsErr(const QDBusError &error); void releaseAndAnswerResp(); void releaseAndAnswerErr(const QDBusError &error); void holdAndAnswerResp(); void holdAndAnswerErr(const QDBusError &error); void privateChatResp(const QList &paths); void privateChatErr(const QDBusError &error); void createMultipartyResp(const QList &paths); void createMultipartyErr(const QDBusError &error); void hangupMultipartyResp(); void hangupMultipartyErr(const QDBusError &error); private: QStringList getCallList(); void connectDbusSignals(const QString& path); private: QStringList m_calllist; }; #endif /* !OFONOVOICECALLMANAGER_H */ telepathy-ofono-0.2+16.04.20151120/tests/mock/messagemanagerprivate.cpp0000644000015300001610000000600012623675611026173 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include "messagemanagerprivateadaptor.h" #include "ofonomessage.h" QMap messageManagerData; MessageManagerPrivate::MessageManagerPrivate(QObject *parent) : messageCount(0), QObject(parent) { QDBusConnection::sessionBus().registerObject(OFONO_MOCK_MESSAGE_MANAGER_OBJECT, this); QDBusConnection::sessionBus().registerService("org.ofono"); SetProperty("ServiceCenterAddress", QDBusVariant(QVariant(""))); SetProperty("UseDeliveryReports", QDBusVariant(QVariant(false))); SetProperty("Bearer", QDBusVariant(QVariant(""))); SetProperty("Alphabet", QDBusVariant(QVariant(""))); new MessageManagerAdaptor(this); } MessageManagerPrivate::~MessageManagerPrivate() { } QVariantMap MessageManagerPrivate::GetProperties() { return mProperties; } void MessageManagerPrivate::SetProperty(const QString &name, const QDBusVariant& value) { qDebug() << "MessageManagerPrivate::SetProperty" << name << value.variant(); mProperties[name] = value.variant(); Q_EMIT PropertyChanged(name, value); } void MessageManagerPrivate::MockSendMessage(const QString &from, const QString &text) { QVariantMap properties; properties["Sender"] = from; properties["SentTime"] = QDateTime::currentDateTime().toString(Qt::ISODate); properties["LocalSentTime"] = QDateTime::currentDateTime().toString(Qt::ISODate); Q_EMIT IncomingMessage(text, properties); } QDBusObjectPath MessageManagerPrivate::SendMessage(const QString &to, const QString &text) { QString newPath("/OfonoMessage"+QString::number(++messageCount)); QDBusObjectPath newPathObj(newPath); mMessages[newPath] = new OfonoMessage(newPath); connect(mMessages[newPath], SIGNAL(destroyed()), this, SLOT(onMessageDestroyed())); Q_EMIT MessageAdded(newPathObj, QVariantMap()); return newPathObj; } void MessageManagerPrivate::MockStatusReport(const QString &message, bool success) { QVariantMap info; info["Delivered"] = success; Q_EMIT StatusReport(message, info); } void MessageManagerPrivate::onMessageDestroyed() { OfonoMessage *message = static_cast(sender()); if (message) { mMessages.remove(message->path()); Q_EMIT MessageRemoved(QDBusObjectPath(message->path())); } } telepathy-ofono-0.2+16.04.20151120/tests/mock/messageprivate.h0000644000015300001610000000261712623675611024317 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef MESSAGEPRIVATE_H #define MESSAGEPRIVATE_H #include class MessagePrivate : public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ofono.Message") public: MessagePrivate(const QString &path, QObject *parent = 0); ~MessagePrivate(); Q_SIGNALS: void PropertyChanged(const QString &name, const QDBusVariant &value); public Q_SLOTS: QVariantMap GetProperties(); void SetProperty(const QString &name, const QDBusVariant &value); void Cancel(); void MockMarkFailed(); void MockMarkSent(); private: QVariantMap mProperties; }; extern QMap messageData; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonocallvolume.h0000644000015300001610000000456512623675611024510 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOCALLVOLUME_H #define OFONOCALLVOLUME_H #include #include "ofonomodeminterface.h" #include "libofono-qt_global.h" //! This class is used to access oFono call volume API /*! * The API is documented in * http://git.kernel.org/?p=network/ofono/ofono.git;a=blob_plain;f=doc/call-volume-api.txt */ class OFONO_QT_EXPORT OfonoCallVolume : public OfonoModemInterface { Q_OBJECT Q_PROPERTY(bool muted READ muted WRITE setMuted NOTIFY mutedChanged) Q_PROPERTY(quint8 speakerVolume READ speakerVolume WRITE setSpeakerVolume NOTIFY speakerVolumeChanged) Q_PROPERTY(quint8 microphoneVolume READ microphoneVolume WRITE setMicrophoneVolume NOTIFY microphoneVolumeChanged) public: OfonoCallVolume(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent=0); ~OfonoCallVolume(); /* Properties */ bool muted() const; quint8 speakerVolume() const; quint8 microphoneVolume()const ; public Q_SLOTS: void setMuted(const bool mute); void setSpeakerVolume(const quint8 &spvolume); void setMicrophoneVolume(const quint8 &mpvolume); Q_SIGNALS: void mutedChanged(const bool &muted); void speakerVolumeChanged(const quint8 &volume); void microphoneVolumeChanged(const quint8 &mvolume); void setMutedFailed(); void setSpeakerVolumeFailed(); void setMicrophoneVolumeFailed(); private Q_SLOTS: void propertyChanged(const QString& property, const QVariant& value); void setPropertyFailed(const QString& property); }; #endif // OFONOCALLVOLUME_H telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomessagemanager.cpp0000644000015300001610000002333112623675611025647 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonomessagemanager.h" #include "ofonointerface.h" #include "messagemanagerprivate.h" QDBusArgument &operator<<(QDBusArgument &argument, const OfonoMessageManagerStruct &message) { argument.beginStructure(); argument << message.path << message.properties; argument.endStructure(); return argument; } const QDBusArgument &operator>>(const QDBusArgument &argument, OfonoMessageManagerStruct &message) { argument.beginStructure(); argument >> message.path >> message.properties; argument.endStructure(); return argument; } OfonoMessageManager::OfonoMessageManager(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent) : OfonoModemInterface(modemSetting, modemPath, "org.ofono.MessageManager", OfonoGetAllOnFirstRequest, parent) { qDBusRegisterMetaType(); qDBusRegisterMetaType(); if (!messageManagerData.keys().contains(modem()->path())) { m_if->setPath(OFONO_MOCK_MESSAGE_MANAGER_OBJECT); messageManagerData[modem()->path()] = new MessageManagerPrivate(); } m_messagelist = getMessageList(); connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); connect(m_if, SIGNAL(setPropertyFailed(const QString&)), this, SLOT(setPropertyFailed(const QString&))); connect(m_if, SIGNAL(requestPropertyComplete(bool, const QString&, const QVariant&)), this, SLOT(requestPropertyComplete(bool, const QString&, const QVariant&))); connect(this, SIGNAL(validityChanged(bool)), this, SLOT(validityChanged(bool))); connect(modem(), SIGNAL(pathChanged(QString)), this, SLOT(pathChanged(const QString&))); connectDbusSignals(path()); } OfonoMessageManager::~OfonoMessageManager() { } void OfonoMessageManager::validityChanged(bool /*validity*/) { m_messagelist = getMessageList(); } void OfonoMessageManager::pathChanged(const QString& path) { connectDbusSignals(path); } QStringList OfonoMessageManager::getMessageList() { QDBusReply reply; OfonoMessageManagerList messages; QDBusMessage request; QStringList messageList; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "GetMessages"); reply = QDBusConnection::sessionBus().call(request); messages = reply; Q_FOREACH(OfonoMessageManagerStruct message, messages) { messageList << message.path.path(); } return messageList; } void OfonoMessageManager::connectDbusSignals(const QString& path) { QDBusConnection::sessionBus().disconnect("org.ofono", QString(), m_if->ifname(), "MessageAdded", this, SLOT(onMessageAdded(const QDBusObjectPath&, const QVariantMap&))); QDBusConnection::sessionBus().disconnect("org.ofono", QString(), m_if->ifname(), "MessageRemoved", this, SLOT(onMessageRemoved(const QDBusObjectPath&))); QDBusConnection::sessionBus().disconnect("org.ofono", QString(), m_if->ifname(), "IncomingMessage", this, SIGNAL(incomingMessage(QString, QVariantMap))); QDBusConnection::sessionBus().disconnect("org.ofono", QString(), m_if->ifname(), "ImmediateMessage", this, SIGNAL(immediateMessage(QString, QVariantMap))); QDBusConnection::sessionBus().disconnect("org.ofono", QString(), m_if->ifname(), "StatusReport", this, SIGNAL(statusReport(QString, QVariantMap))); QDBusConnection::sessionBus().connect("org.ofono", path, m_if->ifname(), "MessageAdded", this, SLOT(onMessageAdded(const QDBusObjectPath&, const QVariantMap&))); QDBusConnection::sessionBus().connect("org.ofono", path, m_if->ifname(), "MessageRemoved", this, SLOT(onMessageRemoved(const QDBusObjectPath&))); QDBusConnection::sessionBus().connect("org.ofono", path, m_if->ifname(), "IncomingMessage", this, SIGNAL(incomingMessage(QString, QVariantMap))); QDBusConnection::sessionBus().connect("org.ofono", path, m_if->ifname(), "ImmediateMessage", this, SIGNAL(immediateMessage(QString, QVariantMap))); QDBusConnection::sessionBus().connect("org.ofono", path, m_if->ifname(), "StatusReport", this, SIGNAL(statusReport(QString, QVariantMap))); } void OfonoMessageManager::requestServiceCenterAddress() { m_if->requestProperty("ServiceCenterAddress"); } void OfonoMessageManager::setServiceCenterAddress(QString address) { m_if->setProperty("ServiceCenterAddress", qVariantFromValue(address)); } void OfonoMessageManager::requestUseDeliveryReports() { m_if->requestProperty("UseDeliveryReports"); } void OfonoMessageManager::setUseDeliveryReports(bool useDeliveryReports) { m_if->setProperty("UseDeliveryReports", qVariantFromValue(useDeliveryReports)); } void OfonoMessageManager::requestBearer() { m_if->requestProperty("Bearer"); } void OfonoMessageManager::setBearer(QString bearer) { m_if->setProperty("Bearer", qVariantFromValue(bearer)); } void OfonoMessageManager::requestAlphabet() { m_if->requestProperty("Alphabet"); } void OfonoMessageManager::setAlphabet(QString alphabet) { m_if->setProperty("Alphabet", qVariantFromValue(alphabet)); } QDBusObjectPath OfonoMessageManager::sendMessage(const QString &to, const QString &message, bool &success) { QDBusMessage request; QDBusReply reply; request = QDBusMessage::createMethodCall("org.ofono", path(), m_if->ifname(), "SendMessage"); request << to << message; reply = QDBusConnection::sessionBus().call(request); success = reply.isValid(); if (!success) { m_if->setError(reply.error().name(), reply.error().message()); } return reply; } void OfonoMessageManager::requestPropertyComplete(bool success, const QString& property, const QVariant& value) { if (property == "ServiceCenterAddress") { Q_EMIT serviceCenterAddressComplete(success, value.value()); } else if (property == "UseDeliveryReports") { Q_EMIT useDeliveryReportsComplete(success, value.value()); } else if (property == "Bearer") { Q_EMIT bearerComplete(success, value.value()); } else if (property == "Alphabet") { Q_EMIT alphabetComplete(success, value.value()); } } void OfonoMessageManager::propertyChanged(const QString& property, const QVariant& value) { if (property == "ServiceCenterAddress") { Q_EMIT serviceCenterAddressChanged(value.value()); } else if (property == "UseDeliveryReports") { Q_EMIT useDeliveryReportsChanged(value.value()); } else if (property == "Bearer") { Q_EMIT bearerChanged(value.value()); } else if (property == "Alphabet") { Q_EMIT alphabetChanged(value.value()); } } void OfonoMessageManager::setPropertyFailed(const QString& property) { if (property == "ServiceCenterAddress") { Q_EMIT setServiceCenterAddressFailed(); } else if (property == "UseDeliveryReports") { Q_EMIT setUseDeliveryReportsFailed(); } else if (property == "Bearer") { Q_EMIT setBearerFailed(); } else if (property == "Alphabet") { Q_EMIT setAlphabetFailed(); } } QStringList OfonoMessageManager::getMessages() const { return m_messagelist; } void OfonoMessageManager::onMessageAdded(const QDBusObjectPath &path, const QVariantMap& /*properties*/) { m_messagelist << path.path(); Q_EMIT messageAdded(path.path()); } void OfonoMessageManager::onMessageRemoved(const QDBusObjectPath &path) { m_messagelist.removeAll(path.path()); Q_EMIT messageRemoved(path.path()); } telepathy-ofono-0.2+16.04.20151120/tests/mock/NetworkRegistrationPrivate.xml0000644000015300001610000000123512623675611027223 0ustar pbuserpbgroup00000000000000 telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonocallvolume.cpp0000644000015300001610000000611412623675611025033 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonocallvolume.h" #include "ofonointerface.h" #include "callvolumeprivate.h" OfonoCallVolume::OfonoCallVolume(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent) : OfonoModemInterface(modemSetting, modemPath, "org.ofono.CallVolume", OfonoGetAllOnStartup, parent) { if (!callVolumeData.keys().contains(modem()->path())) { m_if->setPath(OFONO_MOCK_CALL_VOLUME_OBJECT); callVolumeData[modem()->path()] = new CallVolumePrivate(); } connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); connect(m_if, SIGNAL(setPropertyFailed(const QString&)), this, SLOT(setPropertyFailed(const QString&))); } OfonoCallVolume::~OfonoCallVolume() { } void OfonoCallVolume::propertyChanged(const QString &property, const QVariant &value) { if (property == "SpeakerVolume") { Q_EMIT speakerVolumeChanged(value.value()); } else if (property == "MicrophoneVolume") { Q_EMIT microphoneVolumeChanged(value.value()); } else if (property == "Muted") { Q_EMIT mutedChanged(value.value()); } } quint8 OfonoCallVolume::speakerVolume() const { return m_if->properties()["SpeakerVolume"].value(); } quint8 OfonoCallVolume::microphoneVolume() const { return m_if->properties()["MicrophoneVolume"].value(); } bool OfonoCallVolume::muted() const { return m_if->properties()["Muted"].value(); } void OfonoCallVolume::setMuted(const bool value) { m_if->setProperty("Muted",QVariant(value)); } void OfonoCallVolume::setPropertyFailed(const QString &property) { if (property == "SpeakerVolume") { Q_EMIT setSpeakerVolumeFailed(); } else if (property == "MicrophoneVolume") { Q_EMIT setMicrophoneVolumeFailed(); } else if (property == "Muted") { Q_EMIT setMutedFailed(); } } void OfonoCallVolume::setSpeakerVolume(const quint8 &spvolume) { m_if->setProperty("SpeakerVolume",qVariantFromValue(spvolume)); } void OfonoCallVolume::setMicrophoneVolume(const quint8 &mpvolume) { m_if->setProperty("MicrophoneVolume",qVariantFromValue(mpvolume)); } telepathy-ofono-0.2+16.04.20151120/tests/mock/voicecallprivate.h0000644000015300001610000000304312623675611024626 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef VOICECALLPRIVATE_H #define VOICECALLPRIVATE_H #include class VoiceCallPrivate : public QObject, protected QDBusContext { Q_OBJECT Q_CLASSINFO("D-Bus Interface", "org.ofono.VoiceCall") public: VoiceCallPrivate(const QString &path, QObject *parent = 0); ~VoiceCallPrivate(); QString objectPath() const; Q_SIGNALS: void PropertyChanged(const QString &name, const QDBusVariant &value); public Q_SLOTS: QVariantMap GetProperties(); void SetProperty(const QString &name, const QDBusVariant &value); void Hangup(); void Answer(); void MockSetAlerting(); void MockAnswer(); private: QVariantMap mProperties; QString mObjectPath; }; extern QMap voiceCallData; extern QMap initialCallProperties; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/MessagePrivate.xml0000644000015300001610000000146312623675611024566 0ustar pbuserpbgroup00000000000000 telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomodeminterface.h0000644000015300001610000000706112623675611025321 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOMODEMINTERFACE_H #define OFONOMODEMINTERFACE_H #include #include #include "ofonomodem.h" #include "ofonopropertysetting.h" #include "libofono-qt_global.h" class OfonoInterface; //! This class implements a generic modem interface object /*! * It provides validity checking and modem binding. * It should not be instantiated directly; instead you should instantiate * interface-specific subclasses. */ class OFONO_QT_EXPORT OfonoModemInterface : public QObject { Q_OBJECT Q_PROPERTY(bool isValid READ isValid NOTIFY validityChanged) Q_PROPERTY(QString path READ path) Q_PROPERTY(QString errorName READ errorName) Q_PROPERTY(QString errorMessage READ errorMessage) public: //! Construct a modem interface object /*! * \param modemSetting modem selection setting * \param modemPath path to the modem (may not be significant, depending on modemSetting) * \param ifname d-bus interface name * \param propertySetting oFono d-bus properties setting */ OfonoModemInterface(OfonoModem::SelectionSetting modemSetting, const QString& modemPath, const QString& ifname, OfonoGetPropertySetting propertySetting, QObject *parent=0); ~OfonoModemInterface(); //! Check that the modem interface object is valid /*! * This means that a modem d-bus object * exists and has the d-bus interface specified in the contstructor. */ bool isValid() const; //! Get the modem object that this interface belongs to. /*! * The ownership of the modem object stays with the OfonoModemInterface object. */ OfonoModem *modem() const; //! Returns the D-Bus object path of the interface QString path() const; //! Get the D-Bus error name of the last operation. /*! * Returns the D-Bus error name of the last operation (setting a property * or calling a method) if it has failed */ QString errorName() const; //! Get the D-Bus error message of the last operation. /*! * Returns the D-Bus error message of the last operation (setting a property * or calling a method) if it has failed */ QString errorMessage() const; Q_SIGNALS: //! Interface validity has changed /*! * This may mean that modem has become unavailable * (or available again) or that the modem interface has become unavailable * (or available again) */ void validityChanged(bool validity); private: bool checkValidity(); void updateValidity(); private Q_SLOTS: void modemValidityChanged(bool validity); void interfacesChanged(const QStringList &interfaces); protected: OfonoInterface *m_if; private: OfonoModem *m_m; bool m_isValid; }; #endif telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomessage.cpp0000644000015300001610000000510412623675611024312 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 #include #include "ofonointerface.h" #include "ofonomessage.h" #include "messageprivate.h" OfonoMessage::OfonoMessage(const QString& messageId, QObject *parent) : QObject(parent) { m_if = new OfonoInterface(messageId, "org.ofono.Message", OfonoGetAllOnStartup, this); if (!messageData.keys().contains(messageId)) { m_if->setPath(messageId); messageData[messageId] = new MessagePrivate(messageId); } connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); } OfonoMessage::OfonoMessage(const OfonoMessage& message) : QObject(message.parent()) { m_if = new OfonoInterface(message.path(), "org.ofono.Message", OfonoGetAllOnStartup, this); if (!messageData.keys().contains(message.path())) { m_if->setPath(message.path()); messageData[message.path()] = new MessagePrivate(message.path()); } connect(m_if, SIGNAL(propertyChanged(const QString&, const QVariant&)), this, SLOT(propertyChanged(const QString&, const QVariant&))); } bool OfonoMessage::operator==(const OfonoMessage &message) { return path() == message.path(); } OfonoMessage::~OfonoMessage() { } QString OfonoMessage::state() const { return m_if->properties()["State"].value(); } void OfonoMessage::propertyChanged(const QString &property, const QVariant &value) { if (property == "State") { Q_EMIT stateChanged(value.value()); } } QString OfonoMessage::path() const { return m_if->path(); } QString OfonoMessage::errorName() const { return m_if->errorName(); } QString OfonoMessage::errorMessage() const { return m_if->errorMessage(); } telepathy-ofono-0.2+16.04.20151120/tests/mock/voicecallmanagerprivate.cpp0000644000015300001610000001535212623675611026522 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include "voicecallmanagerprivateadaptor.h" #include "ofonovoicecall.h" #include "voicecallprivate.h" QMap voiceCallManagerData; VoiceCallManagerPrivate::VoiceCallManagerPrivate(QObject *parent) : voiceCallCount(0), failNextDtmf(false), QObject(parent) { qDBusRegisterMetaType >(); QDBusConnection::sessionBus().registerObject(OFONO_MOCK_VOICECALL_MANAGER_OBJECT, this); QDBusConnection::sessionBus().registerService("org.ofono"); SetProperty("EmergencyNumbers", QDBusVariant(QVariant(QStringList()))); new VoiceCallManagerAdaptor(this); } VoiceCallManagerPrivate::~VoiceCallManagerPrivate() { } QMap VoiceCallManagerPrivate::GetCalls() { QMap props; Q_FOREACH(const QString &key, mVoiceCalls.keys()) { VoiceCallPrivate *callPrivate = voiceCallData[key]; if (callPrivate) { props[QDBusObjectPath(key)] = callPrivate->GetProperties(); } } return props; } QVariantMap VoiceCallManagerPrivate::GetProperties() { return mProperties; } void VoiceCallManagerPrivate::SetProperty(const QString &name, const QDBusVariant& value) { qDebug() << "VoiceCallManagerPrivate::SetProperty" << name << value.variant(); if (mProperties[name] != value.variant()) { mProperties[name] = value.variant(); Q_EMIT PropertyChanged(name, value); } } void VoiceCallManagerPrivate::MockFailNextDtmf() { failNextDtmf = true; } QDBusObjectPath VoiceCallManagerPrivate::MockIncomingCall(const QString &from) { qDebug() << "VoiceCallManagerPrivate::MockIncomingCall" << from; QString newPath("/OfonoVoiceCall/OfonoVoiceCall"+QString::number(++voiceCallCount)); QDBusObjectPath newPathObj(newPath); QVariantMap callProperties; callProperties["State"] = "incoming"; callProperties["LineIdentification"] = from; callProperties["Name"] = ""; callProperties["Multiparty"] = false; callProperties["RemoteHeld"] = false; callProperties["RemoteMultiparty"] = false; callProperties["Emergency"] = false; initialCallProperties[newPath] = callProperties; mVoiceCalls[newPath] = new OfonoVoiceCall(newPath); connect(voiceCallData[newPath], SIGNAL(destroyed()), this, SLOT(onVoiceCallDestroyed())); Q_EMIT CallAdded(newPathObj, callProperties); return newPathObj; } void VoiceCallManagerPrivate::SwapCalls() { Q_FOREACH(const QString &objPath, mVoiceCalls.keys()) { QDBusInterface iface("org.ofono", objPath, "org.ofono.VoiceCall"); if (mVoiceCalls[objPath]->state() == "active") { iface.call("SetProperty", "State", QVariant::fromValue(QDBusVariant("held")));; } else if (mVoiceCalls[objPath]->state() == "held") { iface.call("SetProperty", "State", QVariant::fromValue(QDBusVariant("active")));; } } } QList VoiceCallManagerPrivate::CreateMultiparty() { QList calls; if (mVoiceCalls.size() < 2) { return QList(); } // set everything as active Q_FOREACH(const QString &objPath, mVoiceCalls.keys()) { QDBusInterface iface("org.ofono", objPath, "org.ofono.VoiceCall"); iface.call("SetProperty", "State", QVariant::fromValue(QDBusVariant("active")));; iface.call("SetProperty", "Multiparty", QVariant::fromValue(QDBusVariant(true)));; calls << QDBusObjectPath(objPath); } return calls; } QList VoiceCallManagerPrivate::PrivateChat(const QDBusObjectPath &objPath) { QList remainingCalls; Q_FOREACH(const QString &path, mVoiceCalls.keys()) { QDBusInterface iface("org.ofono", objPath.path(), "org.ofono.VoiceCall"); if (objPath.path() == path) { iface.call("SetProperty", "State", QVariant::fromValue(QDBusVariant("active"))); } else { iface.call("SetProperty", "State", QVariant::fromValue(QDBusVariant("held"))); remainingCalls << objPath; } } // remove the multiparty call if there are only 2 calls if (mVoiceCalls.size() == 2) { Q_FOREACH(const QString &objPath, mVoiceCalls.keys()) { QDBusInterface iface("org.ofono", objPath, "org.ofono.VoiceCall"); iface.call("SetProperty", "Multiparty", QVariant::fromValue(QDBusVariant(false)));; } } if (remainingCalls.size() < 2) { return QList(); } return remainingCalls; } void VoiceCallManagerPrivate::SendTones(const QString &tones) { if (failNextDtmf) { failNextDtmf = false; sendErrorReply("org.ofono.Error.InProgress", "Operation already in progress"); return; } Q_EMIT TonesReceived(tones); } QDBusObjectPath VoiceCallManagerPrivate::Dial(const QString &to, const QString &hideCallerId) { qDebug() << "DIAL" << to; QString newPath("/OfonoVoiceCall/OfonoVoiceCall"+QString::number(++voiceCallCount)); QDBusObjectPath newPathObj(newPath); QVariantMap callProperties; callProperties["State"] = "dialing"; callProperties["LineIdentification"] = to; callProperties["Name"] = ""; callProperties["Multiparty"] = false; callProperties["RemoteHeld"] = false; callProperties["RemoteMultiparty"] = false; callProperties["Emergency"] = false; initialCallProperties[newPath] = callProperties; mVoiceCalls[newPath] = new OfonoVoiceCall(newPath); connect(voiceCallData[newPath], SIGNAL(destroyed()), this, SLOT(onVoiceCallDestroyed())); Q_EMIT CallAdded(newPathObj, callProperties); return newPathObj; } void VoiceCallManagerPrivate::onVoiceCallDestroyed() { VoiceCallPrivate *voiceCall = static_cast(sender()); if (voiceCall) { voiceCallData.remove(voiceCall->objectPath()); mVoiceCalls[voiceCall->objectPath()]->deleteLater(); mVoiceCalls.remove(voiceCall->objectPath()); Q_EMIT CallRemoved(QDBusObjectPath(voiceCall->objectPath())); } } telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomessagewaiting.h0000644000015300001610000000454512623675611025352 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOMESSAGEWAITING_H #define OFONOMESSAGEWAITING_H #include #include "ofonomodeminterface.h" #include "libofono-qt_global.h" //! This class is used to access oFono message waiting API /*! * oFono message manager API is documented in * http://git.kernel.org/?p=network/ofono/ofono.git;a=blob_plain;f=doc/message-waiting-api.txt */ class OFONO_QT_EXPORT OfonoMessageWaiting : public OfonoModemInterface { Q_OBJECT Q_PROPERTY(bool voicemailWaiting READ voicemailWaiting NOTIFY voicemailWaitingChanged) Q_PROPERTY(int voicemailMessageCount READ voicemailMessageCount NOTIFY voicemailMessageCountChanged) Q_PROPERTY(QString voicemailMailboxNumber READ voicemailMailboxNumber WRITE setVoicemailMailboxNumber NOTIFY voicemailMailboxNumberChanged) public: OfonoMessageWaiting(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent=0); ~OfonoMessageWaiting(); bool voicemailWaiting() const; int voicemailMessageCount() const; QString voicemailMailboxNumber() const; public Q_SLOTS: void setVoicemailMailboxNumber(QString mailboxnumber); Q_SIGNALS: void voicemailWaitingChanged(bool waiting); void voicemailMessageCountChanged(int count); void voicemailMailboxNumberChanged(const QString &mailboxnumber); void setVoicemailMailboxNumberFailed(); private Q_SLOTS: void propertyChanged(const QString& property, const QVariant& value); void setPropertyFailed(const QString& property); }; #endif /* !OFONOMESSAGEWAITING_H */ telepathy-ofono-0.2+16.04.20151120/tests/mock/libofono-qt_global.h0000644000015300001610000000207212623675611025044 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONO_QT_GLOBAL_H #define OFONO_QT_GLOBAL_H #include #ifdef BUILD_OFONO_QT_LIBRARY # define OFONO_QT_EXPORT Q_DECL_EXPORT #else # define OFONO_QT_EXPORT Q_DECL_IMPORT #endif #endif // OFONO_QT_GLOBAL_H telepathy-ofono-0.2+16.04.20151120/tests/mock/VoiceCallPrivate.xml0000644000015300001610000000153512623675611025043 0ustar pbuserpbgroup00000000000000 telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonomessagemanager.h0000644000015300001610000000744212623675611025321 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2010-2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOMESSAGEMANAGER_H #define OFONOMESSAGEMANAGER_H #include #include #include #include "ofonomodeminterface.h" #include "libofono-qt_global.h" struct OfonoMessageManagerStruct { QDBusObjectPath path; QVariantMap properties; }; typedef QList OfonoMessageManagerList; Q_DECLARE_METATYPE(OfonoMessageManagerStruct) Q_DECLARE_METATYPE(OfonoMessageManagerList) //! This class is used to access oFono message manager API /*! * oFono message manager API is documented in * http://git.kernel.org/?p=network/ofono/ofono.git;a=blob_plain;f=doc/messagemanager-api.txt */ class OFONO_QT_EXPORT OfonoMessageManager : public OfonoModemInterface { Q_OBJECT public: OfonoMessageManager(OfonoModem::SelectionSetting modemSetting, const QString &modemPath, QObject *parent=0); ~OfonoMessageManager(); Q_INVOKABLE QStringList getMessages() const; public Q_SLOTS: /* Properties */ void requestServiceCenterAddress(); void setServiceCenterAddress(QString address); void requestUseDeliveryReports(); void setUseDeliveryReports(bool useDeliveryReports); void requestBearer(); void setBearer(QString bearer); void requestAlphabet(); void setAlphabet(QString alphabet); QDBusObjectPath sendMessage(const QString &to, const QString &message, bool &success); Q_SIGNALS: void serviceCenterAddressChanged(const QString &address); void useDeliveryReportsChanged(const bool &useDeliveryReports); void bearerChanged(const QString &bearer); void alphabetChanged(const QString &alphabet); void serviceCenterAddressComplete(bool success, const QString &address); void useDeliveryReportsComplete(bool success, const bool &useDeliveryReports); void bearerComplete(bool success, const QString &bearer); void alphabetComplete(bool success, const QString &alphabet); void setServiceCenterAddressFailed(); void setUseDeliveryReportsFailed(); void setBearerFailed(); void setAlphabetFailed(); void messageAdded(const QString &message); void messageRemoved(const QString &message); void immediateMessage(const QString &message, const QVariantMap &info); void incomingMessage(const QString &message, const QVariantMap &info); void statusReport(const QString &message, const QVariantMap &info); private Q_SLOTS: void validityChanged(bool); void pathChanged(const QString& path); void propertyChanged(const QString &property, const QVariant &value); void setPropertyFailed(const QString &property); void requestPropertyComplete(bool success, const QString &property, const QVariant &value); void onMessageAdded(const QDBusObjectPath &message, const QVariantMap &properties); void onMessageRemoved(const QDBusObjectPath &message); private: QStringList getMessageList(); void connectDbusSignals(const QString& path); private: QStringList m_messagelist; }; #endif /* !OFONOMESSAGEMANAGER_H */ telepathy-ofono-0.2+16.04.20151120/tests/mock/modemprivate.cpp0000644000015300001610000000562212623675611024326 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include "modemprivate.h" #include "modemprivateadaptor.h" QMap modemData; ModemPrivate::ModemPrivate(QObject *parent) : QObject(parent) { QDBusConnection::sessionBus().registerObject(OFONO_MOCK_MODEM_OBJECT, this); QDBusConnection::sessionBus().registerService("org.ofono"); SetProperty("Powered", QDBusVariant(QVariant(false))); SetProperty("Online", QDBusVariant(QVariant(false))); SetProperty("Lockdown", QDBusVariant(QVariant(false))); SetProperty("Emergency", QDBusVariant(QVariant(false))); SetProperty("Name", QDBusVariant(QVariant("Mock Modem"))); SetProperty("Manufacturer", QDBusVariant(QVariant("Canonical"))); SetProperty("Model", QDBusVariant(QVariant("Mock Modem"))); SetProperty("Revision", QDBusVariant(QVariant("1.0"))); SetProperty("Serial", QDBusVariant(QVariant("ABC123"))); SetProperty("Type", QDBusVariant(QVariant("Software"))); SetProperty("Features", QDBusVariant(QVariant(QStringList() << "gprs" << "cbs" << "net" << "sms" << "sim"))); SetProperty("Interfaces", QDBusVariant(QVariant(QStringList() << "org.ofono.ConnectionManager" << "org.ofono.AssistedSatelliteNavigation" << "org.ofono.CellBroadcast" << "org.ofono.NetworkRegistration" << "org.ofono.CallVolume" << "org.ofono.CallMeter" << "org.ofono.SupplementaryServices" << "org.ofono.CallBarring" << "org.ofono.CallSettings" << "org.ofono.MessageWaiting" << "org.ofono.SmartMessaging" << "org.ofono.PushNotification" << "org.ofono.MessageManager" << "org.ofono.Phonebook" << "org.ofono.TextTelephony" << "org.ofono.CallForwarding" << "org.ofono.SimToolkit" << "org.ofono.NetworkTime" << "org.ofono.VoiceCallManager" << "org.ofono.SimManager"))); new ModemAdaptor(this); } ModemPrivate::~ModemPrivate() { } void ModemPrivate::MockSetOnline(bool online) { SetProperty("Powered", QDBusVariant(QVariant(online))); SetProperty("Online", QDBusVariant(QVariant(online))); } QVariantMap ModemPrivate::GetProperties() { return mProperties; } void ModemPrivate::SetProperty(const QString &name, const QDBusVariant& value) { mProperties[name] = value.variant(); Q_EMIT PropertyChanged(name, value); } telepathy-ofono-0.2+16.04.20151120/tests/mock/networkregistrationprivate.cpp0000644000015300001610000000275612623675611027356 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include "networkregistrationprivateadaptor.h" QMap networkRegistrationData; NetworkRegistrationPrivate::NetworkRegistrationPrivate(QObject *parent) : QObject(parent) { QDBusConnection::sessionBus().registerObject(OFONO_MOCK_NETWORK_REGISTRATION_OBJECT, this); QDBusConnection::sessionBus().registerService("org.ofono"); new NetworkRegistrationAdaptor(this); } NetworkRegistrationPrivate::~NetworkRegistrationPrivate() { } QVariantMap NetworkRegistrationPrivate::GetProperties() { return mProperties; } void NetworkRegistrationPrivate::SetProperty(const QString &name, const QDBusVariant& value) { mProperties[name] = value.variant(); Q_EMIT PropertyChanged(name, value); } telepathy-ofono-0.2+16.04.20151120/tests/mock/ModemPrivate.xml0000644000015300001610000000141312623675611024236 0ustar pbuserpbgroup00000000000000 telepathy-ofono-0.2+16.04.20151120/tests/mock/simmanagerprivate.cpp0000644000015300001610000000261312623675611025345 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include "simmanagerprivateadaptor.h" QMap simManagerData; SimManagerPrivate::SimManagerPrivate(QObject *parent) : QObject(parent) { QDBusConnection::sessionBus().registerObject(OFONO_MOCK_SIM_MANAGER_OBJECT, this); QDBusConnection::sessionBus().registerService("org.ofono"); new SimManagerAdaptor(this); } SimManagerPrivate::~SimManagerPrivate() { } QVariantMap SimManagerPrivate::GetProperties() { return mProperties; } void SimManagerPrivate::SetProperty(const QString &name, const QDBusVariant& value) { mProperties[name] = value.variant(); Q_EMIT PropertyChanged(name, value); } telepathy-ofono-0.2+16.04.20151120/tests/mock/ofonovoicecall.h0000644000015300001610000001050212623675611024272 0ustar pbuserpbgroup00000000000000/* * This file is part of ofono-qt * * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * * Contact: Alexander Kanavin * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * 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 OFONOVOICECALL_H #define OFONOVOICECALL_H #include #include #include #include #include "libofono-qt_global.h" class OfonoInterface; //! This class is used to access oFono voice call API /*! * The API is documented in * http://git.kernel.org/?p=network/ofono/ofono.git;a=blob;f=doc/voicecall-api.txt */ class OFONO_QT_EXPORT OfonoVoiceCall : public QObject { Q_OBJECT Q_PROPERTY(QString path READ path) Q_PROPERTY(QString errorName READ errorName) Q_PROPERTY(QString errorMessage READ errorMessage) Q_PROPERTY(QString lineIdentification READ lineIdentification NOTIFY lineIdentificationChanged) Q_PROPERTY(QString incomingLine READ incomingLine NOTIFY incomingLineChanged) Q_PROPERTY(QString name READ name NOTIFY nameChanged) Q_PROPERTY(QString state READ state NOTIFY stateChanged) Q_PROPERTY(QString startTime READ startTime NOTIFY startTimeChanged) Q_PROPERTY(QString information READ information NOTIFY informationChanged) Q_PROPERTY(bool multiparty READ multiparty NOTIFY multipartyChanged) Q_PROPERTY(bool emergency READ emergency NOTIFY emergencyChanged) Q_PROPERTY(quint8 icon READ icon NOTIFY iconChanged) public: OfonoVoiceCall(const QString &callId, QObject *parent=0); OfonoVoiceCall(const OfonoVoiceCall &op); ~OfonoVoiceCall(); OfonoVoiceCall operator=(const OfonoVoiceCall &op); bool operator==(const OfonoVoiceCall &op); //! Returns the D-Bus object path of the voice call object QString path() const; //! Get the D-Bus error name of the last operation. /*! * Returns the D-Bus error name of the last operation (setting a property * or calling a method) if it has failed */ QString errorName() const; //! Get the D-Bus error message of the last operation. /*! * Returns the D-Bus error message of the last operation (setting a property * or calling a method) if it has failed */ QString errorMessage() const; QString lineIdentification() const; QString incomingLine() const; QString name() const; QString state() const; QString startTime() const; QString information() const; bool multiparty() const; bool emergency() const; quint8 icon() const; bool remoteHeld() const; bool remoteMultiparty() const; public Q_SLOTS: void answer(); void hangup(); void deflect(const QString &number); Q_SIGNALS: void answerComplete(bool status); void hangupComplete(bool status); void deflectComplete(bool status); void lineIdentificationChanged(const QString &name); void nameChanged(const QString &name); void stateChanged(const QString &state); void startTimeChanged(const QString &time); void informationChanged(const QString &mcc); void incomingLineChanged(const QString &line); void disconnectReason(const QString &reason); void multipartyChanged(const bool multiparty); void iconChanged(const quint8 &icon); void emergencyChanged(const bool emergency); void remoteHeldChanged(const bool remoteHeld); void remoteMultipartyChanged(const bool remoteMultiparty); private Q_SLOTS: void propertyChanged(const QString &property, const QVariant &value); void answerResp(); void answerErr(const QDBusError &error); void hangupResp(); void hangupErr(const QDBusError &error); void deflectResp(); void deflectErr(const QDBusError &error); private: OfonoInterface *m_if; }; #endif // OFONOVOICECALL_H telepathy-ofono-0.2+16.04.20151120/tests/approvertext.cpp0000644000015300001610000000565412623675611023451 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include "approvertext.h" #include #include #include #include #include Approver::Approver(QObject* parent) : QObject(parent), Tp::AbstractClientApprover(channelFilters()) { } Approver::~Approver() { } Tp::ChannelClassSpecList Approver::channelFilters() const { Tp::ChannelClassSpecList specList; specList << Tp::ChannelClassSpec::textChat(); return specList; } void Approver::addDispatchOperation(const Tp::MethodInvocationContextPtr<> &context, const Tp::ChannelDispatchOperationPtr &dispatchOperation) { bool willHandle = false; QList channels = dispatchOperation->channels(); Q_FOREACH (Tp::ChannelPtr channel, channels) { // Text Channel Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(channel); if (!textChannel.isNull()) { // right now we are not using any of the text channel's features in the approver // so no need to call becomeReady() on it. willHandle = true; } } if (willHandle) { mDispatchOps.append(dispatchOperation); } context->setFinished(); // check if we need to approve channels already or if we should wait. processChannels(); } void Approver::processChannels() { Q_FOREACH (Tp::ChannelDispatchOperationPtr dispatchOperation, mDispatchOps) { QList channels = dispatchOperation->channels(); Q_FOREACH (Tp::ChannelPtr channel, channels) { // approve only text channels Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(channel); if (textChannel.isNull()) { continue; } if (dispatchOperation->possibleHandlers().contains(TELEPHONY_SERVICE_HANDLER)) { dispatchOperation->handleWith(TELEPHONY_SERVICE_HANDLER); mDispatchOps.removeAll(dispatchOperation); } // FIXME: this shouldn't happen, but in any case, we need to check what to do when // the phone app client is not available } } } telepathy-ofono-0.2+16.04.20151120/tests/approvertext.h0000644000015300001610000000307012623675611023104 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef APPROVER_H #define APPROVER_H #include #include #include #include #define TELEPHONY_SERVICE_HANDLER TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler" #define TELEPHONY_SERVICE_APPROVER TP_QT_IFACE_CLIENT + ".TpOfonoTestApprover" class Approver : public QObject, public Tp::AbstractClientApprover { Q_OBJECT public: Approver(QObject *parent = 0); ~Approver(); Tp::ChannelClassSpecList channelFilters() const; void addDispatchOperation(const Tp::MethodInvocationContextPtr<> &context, const Tp::ChannelDispatchOperationPtr &dispatchOperation); private Q_SLOTS: void processChannels(); private: QList mDispatchOps; }; #endif // APPROVER_H telepathy-ofono-0.2+16.04.20151120/tests/approvercall.h0000644000015300001610000000362112623675611023035 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef APPROVER_H #define APPROVER_H #include #include #include #include #define TELEPHONY_SERVICE_HANDLER TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler" #define TELEPHONY_SERVICE_APPROVER TP_QT_IFACE_CLIENT + ".TpOfonoTestApprover" class Approver : public QObject, public Tp::AbstractClientApprover { Q_OBJECT public: Approver(QObject *parent = 0); ~Approver(); Tp::ChannelClassSpecList channelFilters() const; void addDispatchOperation(const Tp::MethodInvocationContextPtr<> &context, const Tp::ChannelDispatchOperationPtr &dispatchOperation); Tp::ChannelDispatchOperationPtr dispatchOperation(Tp::PendingOperation *op); void acceptCall(); void rejectCall(); private Q_SLOTS: void onClaimFinished(Tp::PendingOperation* op); void onHangupFinished(Tp::PendingOperation* op); void onChannelReady(Tp::PendingOperation *op); Q_SIGNALS: void newCall(); private: QList mDispatchOps; QMap mChannels; }; #endif // APPROVER_H telepathy-ofono-0.2+16.04.20151120/tests/ofonomockcontroller.h0000644000015300001610000000500112623675611024433 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: * Tiago Salem Herrmann * Gustavo Pichorim Boiko */ #ifndef OFONOMOCKCONTROLLER_H #define OFONOMOCKCONTROLLER_H #include #include class OfonoMockController : public QObject { Q_OBJECT public: static OfonoMockController *instance(); Q_SIGNALS: void MessageAdded(QDBusObjectPath, QVariantMap); void CallAdded(QDBusObjectPath, QVariantMap); void TonesReceived(QString); void CallVolumeMuteChanged(bool muted); void SimManagerPresenceChanged(bool present); public Q_SLOTS: void NetworkRegistrationSetStatus(const QString &status); void MessageManagerSendMessage(const QString &from, const QString &text); void MessageManagerStatusReport(const QString &message, bool success); void MessageMarkFailed(const QString &objPath); void MessageMarkSent(const QString &objPath); void MessageCancel(const QString &objPath); void VoiceCallManagerIncomingCall(const QString &from); void VoiceCallManagerFailNextDtmf(); void VoiceCallHangup(const QString &objPath); void VoiceCallAnswer(const QString &objPath); void VoiceCallSetAlerting(const QString &objPath); void ModemSetOnline(bool online = true); void SimManagerSetPresence(bool present); void SimManagerSetPinRequired(const QString &type); private Q_SLOTS: void onCallVolumePropertyChanged(const QString &name, const QDBusVariant &value); void onSimManagerPropertyChanged(const QString &name, const QDBusVariant &value); private: explicit OfonoMockController(QObject *parent = 0); QDBusInterface mNetworkRegistrationInterface; QDBusInterface mMessageManagerInterface; QDBusInterface mVoiceCallManagerInterface; QDBusInterface mModemInterface; QDBusInterface mSimManagerInterface; }; #endif // OFONOMOCKCONTROLLER_H telepathy-ofono-0.2+16.04.20151120/tests/handler.cpp0000644000015300001610000001205112623675611022310 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: * Tiago Salem Herrmann * Gustavo Pichorim Boiko */ #include "handler.h" #include "telepathyhelper.h" #include #include #include #include #include Handler::Handler(QObject *parent) : QObject(parent), Tp::AbstractClientHandler(channelFilters()), mBypassApproval(false) { } void Handler::setBypassApproval(bool bypass) { mBypassApproval = bypass; } bool Handler::bypassApproval() const { return mBypassApproval; } void Handler::handleChannels(const Tp::MethodInvocationContextPtr<> &context, const Tp::AccountPtr &account, const Tp::ConnectionPtr &connection, const QList &channels, const QList &requestsSatisfied, const QDateTime &userActionTime, const Tp::AbstractClientHandler::HandlerInfo &handlerInfo) { Q_UNUSED(account) Q_UNUSED(connection) Q_UNUSED(requestsSatisfied) Q_UNUSED(userActionTime) Q_UNUSED(handlerInfo) Q_FOREACH(const Tp::ChannelPtr channel, channels) { Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(channel); if (textChannel) { Tp::PendingReady *pr = textChannel->becomeReady(Tp::Features() << Tp::TextChannel::FeatureCore << Tp::TextChannel::FeatureChatState << Tp::TextChannel::FeatureMessageCapabilities << Tp::TextChannel::FeatureMessageQueue << Tp::TextChannel::FeatureMessageSentSignal); connect(pr, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onTextChannelReady(Tp::PendingOperation*))); mReadyRequests[pr] = textChannel; continue; } Tp::CallChannelPtr callChannel = Tp::CallChannelPtr::dynamicCast(channel); if (callChannel) { Tp::PendingReady *pr = callChannel->becomeReady(Tp::Features() << Tp::CallChannel::FeatureCore << Tp::CallChannel::FeatureCallState << Tp::CallChannel::FeatureContents << Tp::CallChannel::FeatureLocalHoldState); connect(pr, SIGNAL(finished(Tp::PendingOperation*)), SLOT(onCallChannelReady(Tp::PendingOperation*))); mReadyRequests[pr] = callChannel; continue; } } context->setFinished(); } Tp::ChannelClassSpecList Handler::channelFilters() { Tp::ChannelClassSpecList specList; Tp::ChannelClassSpec spec(TP_QT_IFACE_CHANNEL_TYPE_CALL, Tp::HandleTypeNone); spec.setCallInitialAudioFlag(); specList << spec; specList << Tp::ChannelClassSpec::audioCall(); specList << Tp::ChannelClassSpec::textChat(); return specList; } void Handler::onTextChannelReady(Tp::PendingOperation *op) { Tp::PendingReady *pr = qobject_cast(op); if (!pr) { qCritical() << "The pending object is not a Tp::PendingReady"; return; } Tp::ChannelPtr channel = mReadyRequests[pr]; Tp::TextChannelPtr textChannel = Tp::TextChannelPtr::dynamicCast(channel); if(!textChannel) { qCritical() << "The saved channel is not a Tp::TextChannel"; return; } mReadyRequests.remove(pr); Q_EMIT textChannelAvailable(textChannel); } void Handler::onCallChannelReady(Tp::PendingOperation *op) { Tp::PendingReady *pr = qobject_cast(op); if (!pr) { qCritical() << "The pending object is not a Tp::PendingReady"; return; } Tp::ChannelPtr channel = mReadyRequests[pr]; Tp::CallChannelPtr callChannel = Tp::CallChannelPtr::dynamicCast(channel); if(!callChannel) { qCritical() << "The saved channel is not a Tp::CallChannel"; return; } mReadyRequests.remove(pr); Q_EMIT callChannelAvailable(callChannel); } telepathy-ofono-0.2+16.04.20151120/tests/telepathyhelper.cpp0000644000015300001610000002112512623675611024074 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: * Tiago Salem Herrmann * Gustavo Pichorim Boiko */ #include "telepathyhelper.h" #include #include #include #include #include #include #include TelepathyHelper::TelepathyHelper(QObject *parent) : QObject(parent), //mChannelObserver(0), mFirstTime(true), mConnected(false), mHandlerInterface(0) { Tp::registerTypes(); mAccountFeatures << Tp::Account::FeatureCore << Tp::Account::FeatureProtocolInfo; mContactFeatures << Tp::Contact::FeatureAlias << Tp::Contact::FeatureAvatarData << Tp::Contact::FeatureAvatarToken << Tp::Contact::FeatureCapabilities << Tp::Contact::FeatureSimplePresence; mConnectionFeatures << Tp::Connection::FeatureCore << Tp::Connection::FeatureSelfContact << Tp::Connection::FeatureSimplePresence; Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(QDBusConnection::sessionBus()); channelFactory->addCommonFeatures(Tp::Channel::FeatureCore); Tp::ChannelClassSpec audioConferenceSpec(TP_QT_IFACE_CHANNEL_TYPE_CALL, Tp::HandleTypeNone); audioConferenceSpec.setCallInitialAudioFlag(); channelFactory->setSubclassFor(audioConferenceSpec); mAccountManager = Tp::AccountManager::create( Tp::AccountFactory::create(QDBusConnection::sessionBus(), mAccountFeatures), Tp::ConnectionFactory::create(QDBusConnection::sessionBus(), mConnectionFeatures), channelFactory, Tp::ContactFactory::create(mContactFeatures)); connect(mAccountManager->becomeReady(Tp::AccountManager::FeatureCore), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountManagerReady(Tp::PendingOperation*))); mClientRegistrar = Tp::ClientRegistrar::create(mAccountManager); } TelepathyHelper::~TelepathyHelper() { } TelepathyHelper *TelepathyHelper::instance() { static TelepathyHelper* helper = new TelepathyHelper(); return helper; } QString TelepathyHelper::accountId() const { if (mAccount) { return mAccount->uniqueIdentifier(); } return QString(); } Tp::AccountPtr TelepathyHelper::account() const { return mAccount; } /* ChannelObserver *TelepathyHelper::channelObserver() const { return mChannelObserver; } */ bool TelepathyHelper::connected() const { return mConnected; } /* void TelepathyHelper::registerChannelObserver(const QString &observerName) { QString name = observerName; if (name.isEmpty()) { name = "TelephonyPluginObserver"; } if (mChannelObserver) { mChannelObserver->deleteLater(); } mChannelObserver = new ChannelObserver(this); registerClient(mChannelObserver, name); // messages connect(mChannelObserver, SIGNAL(textChannelAvailable(Tp::TextChannelPtr)), ChatManager::instance(), SLOT(onTextChannelAvailable(Tp::TextChannelPtr))); // calls connect(mChannelObserver, SIGNAL(callChannelAvailable(Tp::CallChannelPtr)), CallManager::instance(), SLOT(onCallChannelAvailable(Tp::CallChannelPtr))); Q_EMIT channelObserverCreated(mChannelObserver); } void TelepathyHelper::unregisterChannelObserver() { Tp::AbstractClientPtr clientPtr(mChannelObserver); if (clientPtr) { mClientRegistrar->unregisterClient(clientPtr); } mChannelObserver->deleteLater(); mChannelObserver = NULL; Q_EMIT channelObserverUnregistered(); } */ QStringList TelepathyHelper::supportedProtocols() const { QStringList protocols; protocols << "ufa" << "tel" << "ofono"; return protocols; } void TelepathyHelper::initializeAccount() { // watch for account state and connection changes connect(mAccount.data(), SIGNAL(stateChanged(bool)), SLOT(onAccountStateChanged(bool))); connect(mAccount.data(), SIGNAL(connectionChanged(const Tp::ConnectionPtr&)), SLOT(onAccountConnectionChanged(const Tp::ConnectionPtr&))); // and make sure it is enabled and connected if (!mAccount->isEnabled()) { ensureAccountEnabled(); } else { ensureAccountConnected(); } } void TelepathyHelper::ensureAccountEnabled() { mAccount->setConnectsAutomatically(true); connect(mAccount->setEnabled(true), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onAccountEnabled(Tp::PendingOperation*))); } void TelepathyHelper::ensureAccountConnected() { // if the account is not connected, request it to connect if (!mAccount->connection() || mAccount->connectionStatus() != Tp::ConnectionStatusConnected) { Tp::Presence presence(Tp::ConnectionPresenceTypeAvailable, "available", "online"); mAccount->setRequestedPresence(presence); } else { watchSelfContactPresence(); } if (mFirstTime) { Q_EMIT accountReady(); mFirstTime = false; } } void TelepathyHelper::watchSelfContactPresence() { if (mAccount.isNull() || mAccount->connection().isNull()) { return; } connect(mAccount->connection()->selfContact().data(), SIGNAL(presenceChanged(Tp::Presence)), SLOT(onPresenceChanged(Tp::Presence))); onPresenceChanged(mAccount->connection()->selfContact()->presence()); } void TelepathyHelper::registerClient(Tp::AbstractClient *client, QString name) { Tp::AbstractClientPtr clientPtr(client); bool succeeded = mClientRegistrar->registerClient(clientPtr, name); if (!succeeded) { name.append("%1"); int count = 0; // limit the number of registered clients to 20, that should be a safe margin while (!succeeded && count < 20) { succeeded = mClientRegistrar->registerClient(clientPtr, name.arg(++count)); if (succeeded) { name = name.arg(count); } } } if (succeeded) { QObject *object = dynamic_cast(client); if (object) { object->setProperty("clientName", TP_QT_IFACE_CLIENT + "." + name ); } } } void TelepathyHelper::onAccountManagerReady(Tp::PendingOperation *op) { Q_UNUSED(op) Tp::AccountSetPtr accountSet; // try to find an account of the one of supported protocols Q_FOREACH(const QString &protocol, supportedProtocols()) { accountSet = mAccountManager->accountsByProtocol(protocol); if (accountSet->accounts().count() > 0) { break; } } if (accountSet->accounts().count() == 0) { qCritical() << "No compatible telepathy account found!"; return; } mAccount = accountSet->accounts()[0]; // in case we have more than one account, the first one to show on the list is going to be used if (accountSet->accounts().count() > 1) { qWarning() << "There are more than just one account of type" << mAccount->protocolName(); } Q_EMIT accountIdChanged(); initializeAccount(); } void TelepathyHelper::onAccountEnabled(Tp::PendingOperation *op) { // we might need to do more stuff once the account is enabled, but making sure it is connected is a good start ensureAccountConnected(); } void TelepathyHelper::onAccountStateChanged(bool enabled) { if (!enabled) { ensureAccountEnabled(); } } void TelepathyHelper::onAccountConnectionChanged(const Tp::ConnectionPtr &connection) { if (connection.isNull()) { ensureAccountConnected(); } else { watchSelfContactPresence(); } Q_EMIT connectionChanged(); } void TelepathyHelper::onPresenceChanged(const Tp::Presence &presence) { mConnected = (presence.type() == Tp::ConnectionPresenceTypeAvailable); Q_EMIT connectedChanged(); } telepathy-ofono-0.2+16.04.20151120/tests/ProtocolTest.cpp0000644000015300001610000000262512623675611023342 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2015 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include "telepathyhelper.h" #include "ofonomockcontroller.h" class ProtocolTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void testVCardField(); }; void ProtocolTest::initTestCase() { TelepathyHelper::instance(); QSignalSpy spy(TelepathyHelper::instance(), SIGNAL(accountReady())); QTRY_COMPARE(spy.count(), 1); } void ProtocolTest::testVCardField() { QStringList fields = TelepathyHelper::instance()->account()->protocolInfo().addressableVCardFields(); QCOMPARE(fields, QStringList() << "tel"); } QTEST_MAIN(ProtocolTest) #include "ProtocolTest.moc" telepathy-ofono-0.2+16.04.20151120/tests/dbus-test-wrapper.sh.in0000755000015300001610000000211312623675611024521 0ustar pbuserpbgroup00000000000000#!/bin/sh -x # export the home folder to somewhere in /tmp TMPDIR=/tmp/tpofono_test_home rm -rf $TMPDIR export HOME=$TMPDIR mkdir -p $TMPDIR # copy mcp plugin to a temporary directory cp ${CMAKE_BINARY_DIR}/mc-plugin/mcp-account-manager-ofono.so $TMPDIR # now run gnome-keyring gnome-keyring-daemon -r -d # we need to set this otherwise mission-control doesn't work properly dconf write /org/gnome/empathy/use-conn false export PA_DISABLED=1 # start telepathy-ofono with the ofono-qt mock library LD_PRELOAD=@CMAKE_CURRENT_BINARY_DIR@/mock/libofono-qt.so ${CMAKE_BINARY_DIR}/telepathy-ofono & TP_OFONO_PID=$! sleep 2 FORCE_RIL_NUM_MODEMS=1 MC_FILTER_PLUGIN_DIR=$TMPDIR G_MESSAGES_DEBUG=all MC_DEBUG=all MCP_DEBUG=all /usr/lib/telepathy/mission-control-5 & MC_CONTROL_PID=$! sleep 2 mc-tool update ofono/ofono/account0 string:modem-objpath=/OfonoModem mc-tool reconnect ofono/ofono/account0 $@ RESULT=$? kill -9 $TP_OFONO_PID kill -9 $MC_CONTROL_PID #FIXME for some reason history-daemon is not being finished, so we have to kill it here pgrep history-daemon | xargs kill -9 return $RESULT telepathy-ofono-0.2+16.04.20151120/tests/CallTest.cpp0000644000015300001610000005360112623675611022414 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include #include #include #include #include #include #include "telepathyhelper.h" #include "ofonomockcontroller.h" #include "handler.h" #include "approvercall.h" Q_DECLARE_METATYPE(Tp::CallChannelPtr); Q_DECLARE_METATYPE(Tp::ChannelPtr); Q_DECLARE_METATYPE(Tp::CallState); Q_DECLARE_METATYPE(QList); #define TELEPATHY_MUTE_IFACE "org.freedesktop.Telepathy.Call1.Interface.Mute" class CallTest : public QObject { Q_OBJECT Q_SIGNALS: void contactsReceived(QList contacts); private Q_SLOTS: void initTestCase(); void testCallIncoming(); void testCallIncomingPrivateNumber(); void testCallIncomingUnknownNumber(); void testNumberNormalization_data(); void testNumberNormalization(); void testCallOutgoing(); void testCallHold(); void testCallDTMF(); void testCallMute(); void testCallConference(); // helper slots void onPendingContactsFinished(Tp::PendingOperation*); private: Approver *mApprover; Handler *mHandler; }; void CallTest::initTestCase() { qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType >(); TelepathyHelper::instance(); QSignalSpy spy(TelepathyHelper::instance(), SIGNAL(accountReady())); QTRY_COMPARE(spy.count(), 1); OfonoMockController::instance()->SimManagerSetPresence(true); OfonoMockController::instance()->SimManagerSetPinRequired("none"); OfonoMockController::instance()->ModemSetOnline(); OfonoMockController::instance()->NetworkRegistrationSetStatus("registered"); // the account should be connected QTRY_VERIFY(TelepathyHelper::instance()->connected()); mHandler = new Handler(this); TelepathyHelper::instance()->registerClient(mHandler, "TpOfonoTestHandler"); QTRY_VERIFY(mHandler->isRegistered()); mApprover = new Approver(this); TelepathyHelper::instance()->registerClient(mApprover, "TpOfonoTestApprover"); QTRY_VERIFY(QDBusConnection::sessionBus().interface()->isServiceRegistered(TELEPHONY_SERVICE_APPROVER)); // we need to wait in order to give telepathy time to notify about the approver and handler QTest::qWait(10000); } void CallTest::testCallIncoming() { QSignalSpy spyNewCallChannel(mHandler, SIGNAL(callChannelAvailable(Tp::CallChannelPtr))); QSignalSpy spyNewCallApprover(mApprover, SIGNAL(newCall())); QSignalSpy spyOfonoCallAdded(OfonoMockController::instance(), SIGNAL(CallAdded(QDBusObjectPath, QVariantMap))); OfonoMockController::instance()->VoiceCallManagerIncomingCall("123"); QTRY_COMPARE(spyOfonoCallAdded.count(), 1); QTRY_COMPARE(spyNewCallApprover.count(), 1); mApprover->acceptCall(); QTRY_COMPARE(spyNewCallChannel.count(), 1); Tp::CallChannelPtr channel = spyNewCallChannel.first().first().value(); QVERIFY(channel); QDBusObjectPath path = spyOfonoCallAdded.first().first().value(); OfonoMockController::instance()->VoiceCallHangup(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateEnded); } void CallTest::testCallIncomingPrivateNumber() { QSignalSpy spyNewCallChannel(mHandler, SIGNAL(callChannelAvailable(Tp::CallChannelPtr))); QSignalSpy spyNewCallApprover(mApprover, SIGNAL(newCall())); QSignalSpy spyOfonoCallAdded(OfonoMockController::instance(), SIGNAL(CallAdded(QDBusObjectPath, QVariantMap))); OfonoMockController::instance()->VoiceCallManagerIncomingCall("withheld"); QTRY_COMPARE(spyOfonoCallAdded.count(), 1); QTRY_COMPARE(spyNewCallApprover.count(), 1); mApprover->acceptCall(); QTRY_COMPARE(spyNewCallChannel.count(), 1); Tp::CallChannelPtr channel = spyNewCallChannel.first().first().value(); QVERIFY(channel); QCOMPARE(channel->initiatorContact()->id(), QString("x-ofono-private")); QDBusObjectPath path = spyOfonoCallAdded.first().first().value(); OfonoMockController::instance()->VoiceCallHangup(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateEnded); } void CallTest::testCallIncomingUnknownNumber() { QSignalSpy spyNewCallChannel(mHandler, SIGNAL(callChannelAvailable(Tp::CallChannelPtr))); QSignalSpy spyNewCallApprover(mApprover, SIGNAL(newCall())); QSignalSpy spyOfonoCallAdded(OfonoMockController::instance(), SIGNAL(CallAdded(QDBusObjectPath, QVariantMap))); OfonoMockController::instance()->VoiceCallManagerIncomingCall(""); QTRY_COMPARE(spyOfonoCallAdded.count(), 1); QTRY_COMPARE(spyNewCallApprover.count(), 1); mApprover->acceptCall(); QTRY_COMPARE(spyNewCallChannel.count(), 1); Tp::CallChannelPtr channel = spyNewCallChannel.first().first().value(); QVERIFY(channel); QCOMPARE(channel->initiatorContact()->id(), QString("x-ofono-unknown")); QDBusObjectPath path = spyOfonoCallAdded.first().first().value(); OfonoMockController::instance()->VoiceCallHangup(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateEnded); } void CallTest::testNumberNormalization_data() { QTest::addColumn("number"); QTest::addColumn("expectedNumber"); QTest::newRow("simple number") << "12345678" << "12345678"; QTest::newRow("number with dash") << "1234-5678" << "12345678"; QTest::newRow("number with area code") << "(123)12345678" << "12312345678"; QTest::newRow("number with slash") << "+421 2/123 456 78" << "+421212345678"; } void CallTest::testNumberNormalization() { QFETCH(QString, number); QFETCH(QString, expectedNumber); Tp::AccountPtr account = TelepathyHelper::instance()->account(); QSignalSpy spy(this, SIGNAL(contactsReceived(QList))); connect(account->connection()->contactManager()->contactsForIdentifiers(QStringList() << number), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingContactsFinished(Tp::PendingOperation*))); QTRY_COMPARE(spy.count(), 1); QList contacts = spy.first().first().value >(); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts.first()->id(), QString(expectedNumber)); } void CallTest::testCallOutgoing() { // Request the contact to start chatting to Tp::AccountPtr account = TelepathyHelper::instance()->account(); QSignalSpy spy(this, SIGNAL(contactsReceived(QList))); connect(account->connection()->contactManager()->contactsForIdentifiers(QStringList() << "321"), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingContactsFinished(Tp::PendingOperation*))); QTRY_COMPARE(spy.count(), 1); QList contacts = spy.first().first().value >(); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts.first()->id(), QString("321")); QSignalSpy spyOfonoCallAdded(OfonoMockController::instance(), SIGNAL(CallAdded(QDBusObjectPath, QVariantMap))); QSignalSpy spyCallChannel(mHandler, SIGNAL(callChannelAvailable(Tp::CallChannelPtr))); Q_FOREACH(Tp::ContactPtr contact, contacts) { account->ensureAudioCall(contact, "audio", QDateTime::currentDateTime(), TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler"); } QTRY_COMPARE(spyOfonoCallAdded.count(), 1); QTRY_COMPARE(spyCallChannel.count(), 1); QDBusObjectPath path = spyOfonoCallAdded.first().first().value(); Tp::CallChannelPtr channel = spyCallChannel.first().first().value(); QVERIFY(channel); OfonoMockController::instance()->VoiceCallSetAlerting(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateInitialised); OfonoMockController::instance()->VoiceCallAnswer(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateActive); OfonoMockController::instance()->VoiceCallHangup(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateEnded); } void CallTest::testCallHold() { QSignalSpy spyNewCallChannel(mHandler, SIGNAL(callChannelAvailable(Tp::CallChannelPtr))); QSignalSpy spyNewCallApprover(mApprover, SIGNAL(newCall())); OfonoMockController::instance()->VoiceCallManagerIncomingCall("123"); QTRY_COMPARE(spyNewCallApprover.count(), 1); mApprover->acceptCall(); QTRY_COMPARE(spyNewCallChannel.count(), 1); Tp::CallChannelPtr channel = spyNewCallChannel.first().first().value(); QVERIFY(channel); channel->accept(); QTRY_COMPARE(channel->callState(), Tp::CallStateActive); channel->requestHold(true); QTRY_COMPARE(channel->localHoldState(), Tp::LocalHoldStateHeld); channel->requestHold(false); QTRY_COMPARE(channel->localHoldState(), Tp::LocalHoldStateUnheld); channel->hangup(); } void CallTest::testCallDTMF() { // Request the contact to start chatting to Tp::AccountPtr account = TelepathyHelper::instance()->account(); QSignalSpy spy(this, SIGNAL(contactsReceived(QList))); connect(account->connection()->contactManager()->contactsForIdentifiers(QStringList() << "321"), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingContactsFinished(Tp::PendingOperation*))); QTRY_COMPARE(spy.count(), 1); QList contacts = spy.first().first().value >(); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts.first()->id(), QString("321")); QSignalSpy spyOfonoCallAdded(OfonoMockController::instance(), SIGNAL(CallAdded(QDBusObjectPath, QVariantMap))); QSignalSpy spyCallChannel(mHandler, SIGNAL(callChannelAvailable(Tp::CallChannelPtr))); Q_FOREACH(Tp::ContactPtr contact, contacts) { account->ensureAudioCall(contact, "audio", QDateTime::currentDateTime(), TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler"); } QTRY_COMPARE(spyOfonoCallAdded.count(), 1); QTRY_COMPARE(spyCallChannel.count(), 1); QDBusObjectPath path = spyOfonoCallAdded.first().first().value(); Tp::CallChannelPtr channel = spyCallChannel.first().first().value(); QVERIFY(channel); OfonoMockController::instance()->VoiceCallSetAlerting(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateInitialised); OfonoMockController::instance()->VoiceCallAnswer(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateActive); Q_FOREACH(const Tp::CallContentPtr &content, channel->contents()) { if (content->supportsDTMF()) { bool ok; QStringList keys; keys << "0" << "1" << "2" << "3" << "4" << "5" << "6" << "7" << "8" << "9" << "*" << "#"; QStringListIterator keysIterator(keys); while (keysIterator.hasNext()) { QString key = keysIterator.next(); Tp::DTMFEvent event = (Tp::DTMFEvent)key.toInt(&ok); if (!ok) { if (!key.compare("*")) { event = Tp::DTMFEventAsterisk; } else if (!key.compare("#")) { event = Tp::DTMFEventHash; } else { qWarning() << "Tone not recognized. DTMF failed"; return; } } QSignalSpy spyOfonoTonesReceived(OfonoMockController::instance(), SIGNAL(TonesReceived(const QString&))); content->startDTMFTone(event); QTRY_COMPARE(spyOfonoTonesReceived.count(), 1); QCOMPARE(spyOfonoTonesReceived.first().first().value(), key); } // test failed tones QSignalSpy spyOfonoTonesReceived(OfonoMockController::instance(), SIGNAL(TonesReceived(const QString&))); OfonoMockController::instance()->VoiceCallManagerFailNextDtmf(); content->startDTMFTone((Tp::DTMFEvent)QString("1").toInt(&ok)); OfonoMockController::instance()->VoiceCallManagerFailNextDtmf(); content->startDTMFTone((Tp::DTMFEvent)QString("2").toInt(&ok)); content->startDTMFTone((Tp::DTMFEvent)QString("3").toInt(&ok)); QTRY_COMPARE(spyOfonoTonesReceived.count(), 2); QCOMPARE(spyOfonoTonesReceived.first().first().value(), QString("1")); spyOfonoTonesReceived.removeFirst(); QCOMPARE(spyOfonoTonesReceived.first().first().value(), QString("23")); } } OfonoMockController::instance()->VoiceCallHangup(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateEnded); } void CallTest::testCallMute() { // Request the contact to start chatting to Tp::AccountPtr account = TelepathyHelper::instance()->account(); QSignalSpy spy(this, SIGNAL(contactsReceived(QList))); connect(account->connection()->contactManager()->contactsForIdentifiers(QStringList() << "321"), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingContactsFinished(Tp::PendingOperation*))); QTRY_COMPARE(spy.count(), 1); QList contacts = spy.first().first().value >(); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts.first()->id(), QString("321")); QSignalSpy spyOfonoCallAdded(OfonoMockController::instance(), SIGNAL(CallAdded(QDBusObjectPath, QVariantMap))); QSignalSpy spyCallChannel(mHandler, SIGNAL(callChannelAvailable(Tp::CallChannelPtr))); Q_FOREACH(Tp::ContactPtr contact, contacts) { account->ensureAudioCall(contact, "audio", QDateTime::currentDateTime(), TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler"); } QTRY_COMPARE(spyOfonoCallAdded.count(), 1); QTRY_COMPARE(spyCallChannel.count(), 1); QDBusObjectPath path = spyOfonoCallAdded.first().first().value(); Tp::CallChannelPtr channel = spyCallChannel.first().first().value(); QVERIFY(channel); OfonoMockController::instance()->VoiceCallSetAlerting(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateInitialised); OfonoMockController::instance()->VoiceCallAnswer(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateActive); QDBusInterface muteInterface(channel->busName(), channel->objectPath(), TELEPATHY_MUTE_IFACE); QSignalSpy spyMuteChanged(OfonoMockController::instance(), SIGNAL(CallVolumeMuteChanged(bool))); muteInterface.call("RequestMuted", true); QTRY_COMPARE(spyMuteChanged.count(), 1); QTRY_COMPARE(spyMuteChanged.first().first().value(), true); spyMuteChanged.clear(); muteInterface.call("RequestMuted", false); QTRY_COMPARE(spyMuteChanged.count(), 1); QTRY_COMPARE(spyMuteChanged.first().first().value(), false); OfonoMockController::instance()->VoiceCallHangup(path.path()); QTRY_COMPARE(channel->callState(), Tp::CallStateEnded); } void CallTest::testCallConference() { // Request the contact to start chatting to Tp::AccountPtr account = TelepathyHelper::instance()->account(); QSignalSpy spy(this, SIGNAL(contactsReceived(QList))); QSignalSpy spyOfonoCallAdded(OfonoMockController::instance(), SIGNAL(CallAdded(QDBusObjectPath, QVariantMap))); QSignalSpy spyCallChannel(mHandler, SIGNAL(callChannelAvailable(Tp::CallChannelPtr))); // Call #1 connect(account->connection()->contactManager()->contactsForIdentifiers(QStringList() << "333"), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingContactsFinished(Tp::PendingOperation*))); QTRY_COMPARE(spy.count(), 1); QList contacts = spy.first().first().value >(); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts.first()->id(), QString("333")); Q_FOREACH(Tp::ContactPtr contact, contacts) { account->ensureAudioCall(contact, "audio", QDateTime::currentDateTime(), TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler"); } QTRY_COMPARE(spyOfonoCallAdded.count(), 1); QTRY_COMPARE(spyCallChannel.count(), 1); QDBusObjectPath path1 = spyOfonoCallAdded.first().first().value(); Tp::CallChannelPtr channel1 = spyCallChannel.first().first().value(); QVERIFY(channel1); OfonoMockController::instance()->VoiceCallSetAlerting(path1.path()); QTRY_COMPARE(channel1->callState(), Tp::CallStateInitialised); OfonoMockController::instance()->VoiceCallAnswer(path1.path()); QTRY_COMPARE(channel1->callState(), Tp::CallStateActive); spy.clear(); spyOfonoCallAdded.clear(); spyCallChannel.clear(); // Call #2 connect(account->connection()->contactManager()->contactsForIdentifiers(QStringList() << "444"), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingContactsFinished(Tp::PendingOperation*))); QTRY_COMPARE(spy.count(), 1); contacts = spy.first().first().value >(); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts.first()->id(), QString("444")); Q_FOREACH(Tp::ContactPtr contact, contacts) { account->ensureAudioCall(contact, "audio", QDateTime::currentDateTime(), TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler"); } QTRY_COMPARE(spyOfonoCallAdded.count(), 1); QTRY_COMPARE(spyCallChannel.count(), 1); QDBusObjectPath path2 = spyOfonoCallAdded.first().first().value(); Tp::CallChannelPtr channel2 = spyCallChannel.first().first().value(); QVERIFY(channel2); OfonoMockController::instance()->VoiceCallSetAlerting(path2.path()); QTRY_COMPARE(channel2->callState(), Tp::CallStateInitialised); OfonoMockController::instance()->VoiceCallAnswer(path2.path()); QTRY_COMPARE(channel2->callState(), Tp::CallStateActive); spy.clear(); spyOfonoCallAdded.clear(); spyCallChannel.clear(); // create conference QList calls; calls << channel1 << channel2; TelepathyHelper::instance()->account()->createConferenceCall(calls, QStringList(), QDateTime::currentDateTime(), TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler"); QTRY_COMPARE(spyCallChannel.count(), 1); Tp::CallChannelPtr conferenceChannel = spyCallChannel.first().first().value(); QVERIFY(conferenceChannel); QSignalSpy spyConferenceChannelMerged(conferenceChannel.data(), SIGNAL(conferenceChannelMerged(const Tp::ChannelPtr &))); QSignalSpy spyConferenceChannelRemoved(conferenceChannel.data(), SIGNAL(conferenceChannelRemoved(const Tp::ChannelPtr &, const Tp::Channel::GroupMemberChangeDetails &))); spy.clear(); spyOfonoCallAdded.clear(); spyCallChannel.clear(); // Call #3 connect(account->connection()->contactManager()->contactsForIdentifiers(QStringList() << "555"), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingContactsFinished(Tp::PendingOperation*))); QTRY_COMPARE(spy.count(), 1); contacts = spy.first().first().value >(); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts.first()->id(), QString("555")); Q_FOREACH(Tp::ContactPtr contact, contacts) { account->ensureAudioCall(contact, "audio", QDateTime::currentDateTime(), TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler"); } QTRY_COMPARE(spyOfonoCallAdded.count(), 1); QTRY_COMPARE(spyCallChannel.count(), 1); QDBusObjectPath path3 = spyOfonoCallAdded.first().first().value(); Tp::CallChannelPtr channel3 = spyCallChannel.first().first().value(); QVERIFY(channel3); OfonoMockController::instance()->VoiceCallSetAlerting(path3.path()); QTRY_COMPARE(channel3->callState(), Tp::CallStateInitialised); OfonoMockController::instance()->VoiceCallAnswer(path3.path()); QTRY_COMPARE(channel3->callState(), Tp::CallStateActive); spy.clear(); spyOfonoCallAdded.clear(); spyCallChannel.clear(); // merge channel 3 into the conference conferenceChannel->conferenceMergeChannel(channel3); QTRY_COMPARE(spyConferenceChannelMerged.count(), 1); // hangup first call so we end up with 2 calls in a conference OfonoMockController::instance()->VoiceCallHangup(path1.path()); QTRY_COMPARE(channel1->callState(), Tp::CallStateEnded); QTRY_COMPARE(spyConferenceChannelRemoved.count(), 1); // split conference so we end up with 2 individual calls channel2->conferenceSplitChannel(); QTRY_COMPARE(channel2->callState(), Tp::CallStateActive); // check if the conference was finished QTRY_COMPARE(conferenceChannel->callState(), Tp::CallStateEnded); OfonoMockController::instance()->VoiceCallHangup(path2.path()); QTRY_COMPARE(channel2->callState(), Tp::CallStateEnded); OfonoMockController::instance()->VoiceCallHangup(path3.path()); QTRY_COMPARE(channel3->callState(), Tp::CallStateEnded); } void CallTest::onPendingContactsFinished(Tp::PendingOperation *op) { Tp::PendingContacts *pc = qobject_cast(op); if (!pc) { return; } Q_EMIT contactsReceived(pc->contacts()); } QTEST_MAIN(CallTest) #include "CallTest.moc" telepathy-ofono-0.2+16.04.20151120/tests/MessagesTest.cpp0000644000015300001610000001602212623675611023304 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include #include #include #include #include #include #include #include "telepathyhelper.h" #include "ofonomockcontroller.h" #include "handler.h" #include "approvertext.h" Q_DECLARE_METATYPE(Tp::TextChannelPtr); Q_DECLARE_METATYPE(QList); class MessagesTest : public QObject { Q_OBJECT Q_SIGNALS: void contactsReceived(QList contacts); private Q_SLOTS: void initTestCase(); void testMessageReceived(); void testMessageSend(); void testMessageSendGroupChat(); // helper slots void onPendingContactsFinished(Tp::PendingOperation*); private: Approver *mApprover; Handler *mHandler; }; void MessagesTest::initTestCase() { qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType(); qRegisterMetaType >(); TelepathyHelper::instance(); QSignalSpy spy(TelepathyHelper::instance(), SIGNAL(accountReady())); QTRY_COMPARE(spy.count(), 1); OfonoMockController::instance()->SimManagerSetPresence(true); OfonoMockController::instance()->SimManagerSetPinRequired("none"); OfonoMockController::instance()->ModemSetOnline(); OfonoMockController::instance()->NetworkRegistrationSetStatus("registered"); // the account should be connected QTRY_VERIFY(TelepathyHelper::instance()->connected()); mHandler = new Handler(this); TelepathyHelper::instance()->registerClient(mHandler, "TpOfonoTestHandler"); QTRY_VERIFY(mHandler->isRegistered()); // register the approver mApprover = new Approver(this); TelepathyHelper::instance()->registerClient(mApprover, "TpOfonoTestApprover"); // Tp-qt does not set registered status to approvers QTRY_VERIFY(QDBusConnection::sessionBus().interface()->isServiceRegistered(TELEPHONY_SERVICE_APPROVER)); // we need to wait in order to give telepathy time to notify about the approver and handler QTest::qWait(10000); } void MessagesTest::testMessageReceived() { QSignalSpy spy(mHandler, SIGNAL(textChannelAvailable(Tp::TextChannelPtr))); OfonoMockController::instance()->MessageManagerSendMessage("123", "text"); QTRY_COMPARE(spy.count(), 1); Tp::TextChannelPtr channel = spy.first().first().value(); QVERIFY(channel); QCOMPARE(channel->messageQueue().count(), 1); Tp::ReceivedMessage message = channel->messageQueue().first(); QCOMPARE(message.sender()->id(), QString("123")); QCOMPARE(message.text(), QString("text")); } void MessagesTest::testMessageSend() { // Request the contact to start chatting to Tp::AccountPtr account = TelepathyHelper::instance()->account(); QSignalSpy spy(this, SIGNAL(contactsReceived(QList))); connect(account->connection()->contactManager()->contactsForIdentifiers(QStringList() << "321"), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingContactsFinished(Tp::PendingOperation*))); QTRY_COMPARE(spy.count(), 1); QList contacts = spy.first().first().value >(); QCOMPARE(contacts.count(), 1); QCOMPARE(contacts.first()->id(), QString("321")); QSignalSpy spyTextChannel(mHandler, SIGNAL(textChannelAvailable(Tp::TextChannelPtr))); Q_FOREACH(Tp::ContactPtr contact, contacts) { account->ensureTextChat(contact, QDateTime::currentDateTime(), TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler"); } QTRY_COMPARE(spyTextChannel.count(), 1); Tp::TextChannelPtr channel = spyTextChannel.first().first().value(); QVERIFY(channel); QSignalSpy spyOfonoMessageAdded(OfonoMockController::instance(), SIGNAL(MessageAdded(QDBusObjectPath, QVariantMap))); Tp::PendingSendMessage *message = channel->send("text"); QTRY_COMPARE(spyOfonoMessageAdded.count(), 1); QDBusObjectPath path = spyOfonoMessageAdded.first().first().value(); OfonoMockController::instance()->MessageMarkSent(path.path()); QTRY_COMPARE(channel->messageQueue().count(), 1); QVERIFY(channel->messageQueue()[0].isDeliveryReport()); QCOMPARE(channel->messageQueue()[0].deliveryDetails().status(), Tp::DeliveryStatusAccepted); OfonoMockController::instance()->MessageManagerStatusReport(path.path(), true); QTRY_COMPARE(channel->messageQueue().count(), 2); QVERIFY(channel->messageQueue()[1].isDeliveryReport()); QCOMPARE(channel->messageQueue()[1].deliveryDetails().status(), Tp::DeliveryStatusDelivered); } void MessagesTest::testMessageSendGroupChat() { // Request the contact to start chatting to Tp::AccountPtr account = TelepathyHelper::instance()->account(); QSignalSpy spy(this, SIGNAL(contactsReceived(QList))); connect(account->connection()->contactManager()->contactsForIdentifiers(QStringList() << "321" << "123"), SIGNAL(finished(Tp::PendingOperation*)), SLOT(onPendingContactsFinished(Tp::PendingOperation*))); QTRY_COMPARE(spy.count(), 1); QList contacts = spy.first().first().value >(); QCOMPARE(contacts.count(), 2); QCOMPARE(contacts[0]->id(), QString("321")); QCOMPARE(contacts[1]->id(), QString("123")); QSignalSpy spyTextChannel(mHandler, SIGNAL(textChannelAvailable(Tp::TextChannelPtr))); account->createConferenceTextChat(QList(), contacts, QDateTime::currentDateTime(), TP_QT_IFACE_CLIENT + ".TpOfonoTestHandler"); QTRY_COMPARE(spyTextChannel.count(), 1); Tp::TextChannelPtr channel = spyTextChannel.first().first().value(); QVERIFY(channel); QSignalSpy spyOfonoMessageAdded(OfonoMockController::instance(), SIGNAL(MessageAdded(QDBusObjectPath, QVariantMap))); Tp::PendingSendMessage *message = channel->send("text"); QTRY_COMPARE(spyOfonoMessageAdded.count(), 2); } void MessagesTest::onPendingContactsFinished(Tp::PendingOperation *op) { Tp::PendingContacts *pc = qobject_cast(op); if (!pc) { return; } Q_EMIT contactsReceived(pc->contacts()); } QTEST_MAIN(MessagesTest) #include "MessagesTest.moc" telepathy-ofono-0.2+16.04.20151120/tests/handler.h0000644000015300001610000000415312623675611021761 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: * Tiago Salem Herrmann * Gustavo Pichorim Boiko */ #ifndef HANDLER_H #define HANDLER_H #include #include #include #include #include class Handler : public QObject, public Tp::AbstractClientHandler { Q_OBJECT public: Handler(QObject *parent = 0); ~Handler() { } bool bypassApproval() const; void handleChannels(const Tp::MethodInvocationContextPtr<> &context, const Tp::AccountPtr &account, const Tp::ConnectionPtr &connection, const QList &channels, const QList &requestsSatisfied, const QDateTime &userActionTime, const Tp::AbstractClientHandler::HandlerInfo &handlerInfo); Tp::ChannelClassSpecList channelFilters(); void setBypassApproval(bool bypass); Q_SIGNALS: void textChannelAvailable(Tp::TextChannelPtr textChannel); void callChannelAvailable(Tp::CallChannelPtr callChannel); private Q_SLOTS: void onTextChannelReady(Tp::PendingOperation *op); void onCallChannelReady(Tp::PendingOperation *op); private: QMap mReadyRequests; bool mBypassApproval; }; #endif // HANDLER_H telepathy-ofono-0.2+16.04.20151120/tests/ConnectionTest.cpp0000644000015300001610000001111212623675611023627 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include #include #include "telepathyhelper.h" #include "ofonomockcontroller.h" class ConnectionTest : public QObject { Q_OBJECT private Q_SLOTS: void initTestCase(); void testConnected(); void testModemStatus(); }; void ConnectionTest::initTestCase() { TelepathyHelper::instance(); QSignalSpy spy(TelepathyHelper::instance(), SIGNAL(accountReady())); QTRY_COMPARE(spy.count(), 1); OfonoMockController::instance()->SimManagerSetPresence(true); OfonoMockController::instance()->SimManagerSetPinRequired("none"); OfonoMockController::instance()->ModemSetOnline(); OfonoMockController::instance()->NetworkRegistrationSetStatus("registered"); qRegisterMetaType(); QTest::qWait(3000); } void ConnectionTest::testConnected() { // the account should be connected automatically QTRY_VERIFY(TelepathyHelper::instance()->connected()); } void ConnectionTest::testModemStatus() { Tp::ContactPtr selfContact = TelepathyHelper::instance()->account()->connection()->selfContact(); QSignalSpy signalSpy(selfContact.data(), SIGNAL(presenceChanged(Tp::Presence))); // set the status as unregistered OfonoMockController::instance()->NetworkRegistrationSetStatus("unregistered"); QTRY_COMPARE(signalSpy.count(), 1); Tp::Presence presence = signalSpy.first().first().value(); QCOMPARE(presence.type(), Tp::ConnectionPresenceTypeAway); signalSpy.clear(); // now set the modem as registered to the network again to see if it works OfonoMockController::instance()->NetworkRegistrationSetStatus("registered"); QTRY_COMPARE(signalSpy.count(), 1); presence = signalSpy.first().first().value(); QCOMPARE(presence.type(), Tp::ConnectionPresenceTypeAvailable); signalSpy.clear(); // searching should be reported as away OfonoMockController::instance()->NetworkRegistrationSetStatus("searching"); QTRY_COMPARE(signalSpy.count(), 1); presence = signalSpy.first().first().value(); QCOMPARE(presence.type(), Tp::ConnectionPresenceTypeAway); signalSpy.clear(); // denied should be reported as away (set registered first to force the signal to be emitted) OfonoMockController::instance()->NetworkRegistrationSetStatus("registered"); QTRY_COMPARE(signalSpy.count(), 1); signalSpy.clear(); OfonoMockController::instance()->NetworkRegistrationSetStatus("denied"); QTRY_COMPARE(signalSpy.count(), 1); presence = signalSpy.first().first().value(); QCOMPARE(presence.type(), Tp::ConnectionPresenceTypeAway); signalSpy.clear(); // unknown should be reported as offline (set registered first to force the signal to be emitted) OfonoMockController::instance()->NetworkRegistrationSetStatus("registered"); QTRY_COMPARE(signalSpy.count(), 1); signalSpy.clear(); OfonoMockController::instance()->NetworkRegistrationSetStatus("unknown"); QTRY_COMPARE(signalSpy.count(), 1); presence = signalSpy.first().first().value(); QCOMPARE(presence.type(), Tp::ConnectionPresenceTypeAway); signalSpy.clear(); // roaming should be reported as available OfonoMockController::instance()->NetworkRegistrationSetStatus("roaming"); QTRY_COMPARE(signalSpy.count(), 1); presence = signalSpy.first().first().value(); QCOMPARE(presence.type(), Tp::ConnectionPresenceTypeAvailable); signalSpy.clear(); // offline modem should be reported as offline (flightmode) OfonoMockController::instance()->ModemSetOnline(false); QTRY_COMPARE(signalSpy.count(), 1); presence = signalSpy.first().first().value(); QCOMPARE(presence.type(), Tp::ConnectionPresenceTypeOffline); } QTEST_MAIN(ConnectionTest) #include "ConnectionTest.moc" telepathy-ofono-0.2+16.04.20151120/tests/ofonomockcontroller.cpp0000644000015300001610000001254112623675611024775 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: * Tiago Salem Herrmann * Gustavo Pichorim Boiko */ #include "ofonomockcontroller.h" #include "mock/mock_common.h" OfonoMockController::OfonoMockController(QObject *parent) : QObject(parent), mNetworkRegistrationInterface("org.ofono", OFONO_MOCK_NETWORK_REGISTRATION_OBJECT, "org.ofono.NetworkRegistration"), mMessageManagerInterface("org.ofono", OFONO_MOCK_MESSAGE_MANAGER_OBJECT, "org.ofono.MessageManager"), mVoiceCallManagerInterface("org.ofono", OFONO_MOCK_VOICECALL_MANAGER_OBJECT, "org.ofono.VoiceCallManager"), mModemInterface("org.ofono", OFONO_MOCK_MODEM_OBJECT, "org.ofono.Modem"), mSimManagerInterface("org.ofono", OFONO_MOCK_SIM_MANAGER_OBJECT, "org.ofono.SimManager") { QDBusConnection::sessionBus().connect("org.ofono", OFONO_MOCK_MESSAGE_MANAGER_OBJECT, "org.ofono.MessageManager", "MessageAdded", this, SIGNAL(MessageAdded(QDBusObjectPath, QVariantMap))); QDBusConnection::sessionBus().connect("org.ofono", OFONO_MOCK_VOICECALL_MANAGER_OBJECT, "org.ofono.VoiceCallManager", "CallAdded", this, SIGNAL(CallAdded(QDBusObjectPath, QVariantMap))); QDBusConnection::sessionBus().connect("org.ofono", OFONO_MOCK_VOICECALL_MANAGER_OBJECT, "org.ofono.VoiceCallManager", "TonesReceived", this, SIGNAL(TonesReceived(QString))); QDBusConnection::sessionBus().connect("org.ofono", OFONO_MOCK_CALL_VOLUME_OBJECT, "org.ofono.CallVolume", "PropertyChanged", this, SLOT(onCallVolumePropertyChanged(QString, QDBusVariant))); QDBusConnection::sessionBus().connect("org.ofono", OFONO_MOCK_SIM_MANAGER_OBJECT, "org.ofono.SimManager", "PropertyChanged", this, SLOT(onSimManagerPropertyChanged(QString, QDBusVariant))); } OfonoMockController *OfonoMockController::instance() { static OfonoMockController *self = new OfonoMockController(); return self; } void OfonoMockController::onSimManagerPropertyChanged(const QString& name, const QDBusVariant& value) { if (name == "Present") { Q_EMIT SimManagerPresenceChanged(value.variant().value()); } } void OfonoMockController::onCallVolumePropertyChanged(const QString& name, const QDBusVariant& value) { if (name == "Muted") { Q_EMIT CallVolumeMuteChanged(value.variant().value()); } } void OfonoMockController::NetworkRegistrationSetStatus(const QString &status) { mNetworkRegistrationInterface.call("SetProperty", "Status", QVariant::fromValue(QDBusVariant(status))); } void OfonoMockController::MessageManagerSendMessage(const QString &from, const QString &text) { mMessageManagerInterface.call("MockSendMessage", from, text); } void OfonoMockController::MessageManagerStatusReport(const QString &message, bool success) { mMessageManagerInterface.call("MockStatusReport", message, success); } void OfonoMockController::MessageMarkSent(const QString &objPath) { QDBusInterface iface("org.ofono", objPath, "org.ofono.Message"); iface.call("MockMarkSent"); } void OfonoMockController::MessageMarkFailed(const QString &objPath) { QDBusInterface iface("org.ofono", objPath, "org.ofono.Message"); iface.call("MockMarkFailed"); } void OfonoMockController::MessageCancel(const QString &objPath) { QDBusInterface iface("org.ofono", objPath, "org.ofono.Message"); iface.call("Cancel"); } void OfonoMockController::VoiceCallManagerIncomingCall(const QString &from) { QDBusInterface iface("org.ofono", OFONO_MOCK_VOICECALL_MANAGER_OBJECT, "org.ofono.VoiceCallManager"); iface.call("MockIncomingCall", from); } void OfonoMockController::VoiceCallManagerFailNextDtmf() { QDBusInterface iface("org.ofono", OFONO_MOCK_VOICECALL_MANAGER_OBJECT, "org.ofono.VoiceCallManager"); iface.call("MockFailNextDtmf"); } void OfonoMockController::VoiceCallSetAlerting(const QString &objPath) { QDBusInterface iface("org.ofono", objPath, "org.ofono.VoiceCall"); iface.call("MockSetAlerting"); } void OfonoMockController::VoiceCallAnswer(const QString &objPath) { QDBusInterface iface("org.ofono", objPath, "org.ofono.VoiceCall"); iface.call("MockAnswer"); } void OfonoMockController::VoiceCallHangup(const QString &objPath) { QDBusInterface iface("org.ofono", objPath, "org.ofono.VoiceCall"); iface.call("Hangup"); } void OfonoMockController::ModemSetOnline(bool online) { mModemInterface.call("SetProperty", "Online", QVariant::fromValue(QDBusVariant(online))); } void OfonoMockController::SimManagerSetPresence(bool present) { mSimManagerInterface.call("SetProperty", "Present", QVariant::fromValue(QDBusVariant(present))); } void OfonoMockController::SimManagerSetPinRequired(const QString &type) { mSimManagerInterface.call("SetProperty", "PinRequired", QVariant::fromValue(QDBusVariant(type))); } telepathy-ofono-0.2+16.04.20151120/tests/telepathyhelper.h0000644000015300001610000000602712623675611023545 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: * Tiago Salem Herrmann * Gustavo Pichorim Boiko */ #ifndef TELEPATHYHELPER_H #define TELEPATHYHELPER_H #include #include #include #include #include #include //#include "channelobserver.h" #define CANONICAL_TELEPHONY_VOICEMAIL_IFACE "com.canonical.Telephony.Voicemail" #define CANONICAL_TELEPHONY_SPEAKER_IFACE "com.canonical.Telephony.Speaker" class TelepathyHelper : public QObject { Q_OBJECT Q_PROPERTY(bool connected READ connected NOTIFY connectedChanged) Q_PROPERTY(QString accountId READ accountId NOTIFY accountIdChanged) public: ~TelepathyHelper(); static TelepathyHelper *instance(); Tp::AccountPtr account() const; //ChannelObserver *channelObserver() const; bool connected() const; QString accountId() const; void registerClient(Tp::AbstractClient *client, QString name); Q_SIGNALS: //void channelObserverCreated(ChannelObserver *observer); //void channelObserverUnregistered(); void accountReady(); void connectionChanged(); void connectedChanged(); void accountIdChanged(); public Q_SLOTS: //Q_INVOKABLE void registerChannelObserver(const QString &observerName = QString::null); //Q_INVOKABLE void unregisterChannelObserver(); protected: QStringList supportedProtocols() const; void initializeAccount(); void ensureAccountEnabled(); void ensureAccountConnected(); void watchSelfContactPresence(); private Q_SLOTS: void onAccountManagerReady(Tp::PendingOperation *op); void onAccountEnabled(Tp::PendingOperation *op); void onAccountStateChanged(bool enabled); void onAccountConnectionChanged(const Tp::ConnectionPtr &connection); void onPresenceChanged(const Tp::Presence &presence); private: explicit TelepathyHelper(QObject *parent = 0); Tp::AccountManagerPtr mAccountManager; Tp::Features mAccountManagerFeatures; Tp::Features mAccountFeatures; Tp::Features mContactFeatures; Tp::Features mConnectionFeatures; Tp::ClientRegistrarPtr mClientRegistrar; Tp::AccountPtr mAccount; //ChannelObserver *mChannelObserver; bool mFirstTime; bool mConnected; QDBusInterface *mHandlerInterface; }; #endif // TELEPATHYHELPER_H telepathy-ofono-0.2+16.04.20151120/pendingmessagesmanager.cpp0000644000015300001610000000554412623675611024251 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #include #include #include #include "pendingmessagesmanager.h" #include "sqlitedatabase.h" PendingMessagesManager::PendingMessagesManager(QObject *parent) : QObject(parent), mDatabase(SQLiteDatabase::instance()->database()) { } PendingMessagesManager *PendingMessagesManager::instance() { static PendingMessagesManager *self = new PendingMessagesManager(); return self; } QString PendingMessagesManager::recipientIdForMessageId(const QString &messageId) { QSqlQuery query(SQLiteDatabase::instance()->database()); QString queryString("SELECT recipientId FROM pending_messages WHERE messageId=:messageId"); query.prepare(queryString); query.bindValue(":messageId", messageId); if (!query.exec()) { qCritical() << "Error:" << query.lastError() << query.lastQuery(); return QString(); } if(!query.next()) { return QString(); } return query.value(0).toString(); } void PendingMessagesManager::addPendingMessage(const QString &messageId, const QString &recipientId) { QSqlQuery query(SQLiteDatabase::instance()->database()); PendingMessage message; message.recipientId = recipientId; message.timestamp = QDateTime::currentDateTimeUtc(); QString queryString("INSERT into pending_messages (messageId, recipientId, timestamp) VALUES (:messageId, :recipientId, :timestamp)"); query.prepare(queryString); query.bindValue(":messageId", messageId); query.bindValue(":recipientId", message.recipientId); query.bindValue(":timestamp", message.timestamp.toString(Qt::ISODate)); if (!query.exec()) { qCritical() << "Error:" << query.lastError() << query.lastQuery(); return; } } void PendingMessagesManager::removePendingMessage(const QString &messageId) { QSqlQuery query(SQLiteDatabase::instance()->database()); QString queryString("DELETE FROM pending_messages WHERE messageId=:messageId"); query.prepare(queryString); query.bindValue(":messageId", messageId); if (!query.exec()) { qCritical() << "Error:" << query.lastError() << query.lastQuery(); return; } } telepathy-ofono-0.2+16.04.20151120/countrycodes.txt0000644000015300001610000000304012623675611022305 0ustar pbuserpbgroup00000000000000514:TP 515:PH 520:TH 525:SG 528:BN 530:NZ 537:PG 539:TO 540:SB 541:VU 542:FJ 544:AS 545:KI 546:NC 547:PF 548:CK 549:WS 550:FM 552:PW 553:TV 555:NU 602:EG 603:DZ 604:MA 605:TN 606:LY 607:GM 608:SN 609:MR 610:ML 611:GN 612:CI 613:BF 614:NE 615:TG 616:BJ 617:MU 618:LR 619:SL 620:GH 621:NG 622:TD 623:CF 624:CM 625:CV 626:ST 627:GQ 628:GA 629:CG 630:CD 631:AO 632:GW 633:SC 634:SD 635:RW 636:ET 637:SO 638:DJ 639:KE 640:TZ 641:UG 642:BI 643:MZ 645:ZM 646:MG 647:RE 648:ZW 649:NA 650:MW 651:LS 652:BW 653:SZ 654:KM 655:ZA 657:ER 659:SS 714:PA 702:BZ 704:GT 706:SV 708:HN 710:NI 712:CR 716:PE 202:GR 204:NL 206:BE 208:FR 722:AR 724:BR 213:AD 214:ES 216:HU 730:CL 219:HR 732:CO 222:IT 736:BO 738:GY 740:EC 230:CZ 231:SK 232:AT 746:SR 235:GB 748:UY 750:FK 240:SE 242:NO 244:FI 246:LT 247:LV 248:EE 212:MC 250:RU 255:UA 257:BY 259:MD 260:PL 262:DE 266:GI 268:PT 270:LU 272:IE 274:IS 276:AL 278:MT 280:CY 282:GE 283:AM 284:BG 218:BA 286:TR 288:FO 289:GE 290:GL 292:SM 293:SI 294:MK 295:LI 297:ME 302:CA 308:PM 734:VE 310:US 311:US 312:US 316:US 330:PR 226:RO 334:MX 338:JM 340:MQ 342:BB 344:AG 228:CH 346:KY 348:VG 350:BM 352:GD 354:MS 356:KN 358:LC 360:VC 362:AN 363:AW 364:BS 365:AI 366:DM 368:CU 744:PY 370:DO 372:HT 374:TT 376:VI 234:GB 405:IN 400:AZ 401:KZ 402:BT 404:IN 238:DK 410:PK 412:AF 413:LK 414:MM 415:LB 416:JO 417:SY 418:IQ 419:KW 420:SA 421:YE 422:OM 424:AE 425:PS 426:BH 427:QA 428:MN 429:NP 430:AE 431:AE 432:IR 434:UZ 436:TK 437:KG 438:TM 440:JP 441:JP 450:KR 452:VN 454:HK 455:MO 456:KH 457:LA 460:CN 466:TW 467:KP 220:RS 470:BD 472:MV 502:MY 505:AU 510:ID telepathy-ofono-0.2+16.04.20151120/dbustypes.h0000644000015300001610000000332112623675611021220 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann */ #ifndef DBUSTYPES #define DBUSTYPES #include struct AudioOutput { QString id; QString type; QString name; }; struct MessageStruct { QDBusObjectPath path; QVariantMap properties; }; struct IncomingAttachmentStruct { QString id; QString contentType; QString filePath; quint64 offset; quint64 length; }; struct OutgoingAttachmentStruct { QString id; QString contentType; QString filePath; }; Q_DECLARE_METATYPE(AudioOutput) typedef QList AudioOutputList; Q_DECLARE_METATYPE(AudioOutputList) typedef QList IncomingAttachmentList; typedef QList OutgoingAttachmentList; Q_DECLARE_METATYPE(IncomingAttachmentStruct) Q_DECLARE_METATYPE(OutgoingAttachmentStruct) Q_DECLARE_METATYPE(IncomingAttachmentList) Q_DECLARE_METATYPE(OutgoingAttachmentList) typedef QList MessageList; Q_DECLARE_METATYPE(MessageStruct) Q_DECLARE_METATYPE(MessageList) #endif telepathy-ofono-0.2+16.04.20151120/connection.cpp0000644000015300001610000014326412623675611021703 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License version 3, as published by * the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, * SATISFACTORY QUALITY, 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 program. If not, see . * * Authors: Tiago Salem Herrmann * Gustavo Pichorim Boiko */ #include #include #include #include #include // telepathy-ofono #include "connection.h" #include "phoneutils_p.h" #include "protocol.h" #include "ofonoconferencecallchannel.h" #include "mmsdmessage.h" #include "mmsdservice.h" #ifdef USE_PULSEAUDIO #include "qpulseaudioengine.h" #endif #include "sqlitedatabase.h" #include "pendingmessagesmanager.h" #include "dbustypes.h" static void enable_earpiece() { #ifdef USE_PULSEAUDIO QPulseAudioEngine::instance()->setCallMode(CallActive, AudioModeBtOrWiredOrEarpiece); #endif } static void enable_normal() { #ifdef USE_PULSEAUDIO QTimer* timer = new QTimer(); timer->setSingleShot(true); QObject::connect(timer, &QTimer::timeout, [=](){ QPulseAudioEngine::instance()->setMicMute(false); QPulseAudioEngine::instance()->setCallMode(CallEnded, AudioModeWiredOrSpeaker); timer->deleteLater(); }); timer->start(2000); #endif } static void enable_speaker() { #ifdef USE_PULSEAUDIO QPulseAudioEngine::instance()->setCallMode(CallActive, AudioModeSpeaker); #endif } static void enable_ringtone() { #ifdef USE_PULSEAUDIO QPulseAudioEngine::instance()->setCallMode(CallRinging, AudioModeWiredOrSpeaker); #endif } oFonoConnection::oFonoConnection(const QDBusConnection &dbusConnection, const QString &cmName, const QString &protocolName, const QVariantMap ¶meters) : Tp::BaseConnection(dbusConnection, cmName, protocolName, parameters), mOfonoModemManager(new OfonoModemManager(this)), mHandleCount(0), mMmsdManager(new MMSDManager(this)), mConferenceCall(NULL) { qRegisterMetaType(); qRegisterMetaType(); OfonoModem::SelectionSetting setting = OfonoModem::AutomaticSelect; mModemPath = parameters["modem-objpath"].toString(); if (!mModemPath.isEmpty()) { setting = OfonoModem::ManualSelect; } mOfonoMessageManager = new OfonoMessageManager(setting, mModemPath); mOfonoVoiceCallManager = new OfonoVoiceCallManager(setting, mModemPath); mOfonoCallVolume = new OfonoCallVolume(setting, mModemPath); mOfonoNetworkRegistration = new OfonoNetworkRegistration(setting, mModemPath); mOfonoMessageWaiting = new OfonoMessageWaiting(setting, mModemPath); mOfonoSupplementaryServices = new OfonoSupplementaryServices(setting, mModemPath); mOfonoSimManager = new OfonoSimManager(setting, mModemPath); mOfonoModem = mOfonoSimManager->modem(); if (mOfonoSimManager->subscriberNumbers().size() > 0) { setSelfHandle(newHandle(mOfonoSimManager->subscriberNumbers()[0])); } else { setSelfHandle(newHandle("")); } setConnectCallback(Tp::memFun(this,&oFonoConnection::connect)); setInspectHandlesCallback(Tp::memFun(this,&oFonoConnection::inspectHandles)); setRequestHandlesCallback(Tp::memFun(this,&oFonoConnection::requestHandles)); setCreateChannelCallback(Tp::memFun(this,&oFonoConnection::createChannel)); // initialise requests interface (Connection.Interface.Requests) requestsIface = Tp::BaseConnectionRequestsInterface::create(this); // set requestable text channel properties Tp::RequestableChannelClass text; text.fixedProperties[TP_QT_IFACE_CHANNEL+".ChannelType"] = TP_QT_IFACE_CHANNEL_TYPE_TEXT; text.fixedProperties[TP_QT_IFACE_CHANNEL+".TargetHandleType"] = Tp::HandleTypeContact; text.allowedProperties.append(TP_QT_IFACE_CHANNEL+".TargetHandle"); text.allowedProperties.append(TP_QT_IFACE_CHANNEL+".TargetID"); text.allowedProperties.append(TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles")); // set requestable call channel properties Tp::RequestableChannelClass call; call.fixedProperties[TP_QT_IFACE_CHANNEL+".ChannelType"] = TP_QT_IFACE_CHANNEL_TYPE_CALL; call.fixedProperties[TP_QT_IFACE_CHANNEL+".TargetHandleType"] = Tp::HandleTypeContact; call.fixedProperties[TP_QT_IFACE_CHANNEL_TYPE_CALL+".InitialAudio"] = true; call.allowedProperties.append(TP_QT_IFACE_CHANNEL+".TargetHandle"); call.allowedProperties.append(TP_QT_IFACE_CHANNEL+".TargetID"); call.allowedProperties.append(TP_QT_IFACE_CHANNEL_TYPE_CALL+".InitialAudio"); call.allowedProperties.append(TP_QT_IFACE_CHANNEL_TYPE_CALL+".InitialVideo"); call.allowedProperties.append(TP_QT_IFACE_CHANNEL_TYPE_CALL+".InitialAudioName"); call.allowedProperties.append(TP_QT_IFACE_CHANNEL_TYPE_CALL+".InitialVideoName"); call.allowedProperties.append(TP_QT_IFACE_CHANNEL_TYPE_CALL+".InitialTransport"); call.allowedProperties.append(TP_QT_IFACE_CHANNEL_TYPE_CALL+".HardwareStreaming"); call.allowedProperties.append(TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels")); requestsIface->requestableChannelClasses << text << call; plugInterface(Tp::AbstractConnectionInterfacePtr::dynamicCast(requestsIface)); // init presence interface simplePresenceIface = Tp::BaseConnectionSimplePresenceInterface::create(); simplePresenceIface->setSetPresenceCallback(Tp::memFun(this,&oFonoConnection::setPresence)); plugInterface(Tp::AbstractConnectionInterfacePtr::dynamicCast(simplePresenceIface)); // init custom emergency mode interface (not provided by telepathy emergencyModeIface = BaseConnectionEmergencyModeInterface::create(); emergencyModeIface->setEmergencyNumbersCallback(Tp::memFun(this,&oFonoConnection::emergencyNumbers)); QObject::connect(mOfonoVoiceCallManager, SIGNAL(emergencyNumbersChanged(QStringList)), emergencyModeIface.data(), SLOT(setEmergencyNumbers(QStringList))); plugInterface(Tp::AbstractConnectionInterfacePtr::dynamicCast(emergencyModeIface)); emergencyModeIface->setEmergencyNumbers(mOfonoVoiceCallManager->emergencyNumbers()); emergencyModeIface->setFakeEmergencyNumber(parameters["fakeEmergencyNumber"].toString()); // init custom voicemail interface (not provided by telepathy) voicemailIface = BaseConnectionVoicemailInterface::create(); voicemailIface->setVoicemailCountCallback(Tp::memFun(this,&oFonoConnection::voicemailCount)); voicemailIface->setVoicemailIndicatorCallback(Tp::memFun(this,&oFonoConnection::voicemailIndicator)); voicemailIface->setVoicemailNumberCallback(Tp::memFun(this,&oFonoConnection::voicemailNumber)); plugInterface(Tp::AbstractConnectionInterfacePtr::dynamicCast(voicemailIface)); supplementaryServicesIface = BaseConnectionUSSDInterface::create(); supplementaryServicesIface->setInitiateCallback(Tp::memFun(this,&oFonoConnection::USSDInitiate)); supplementaryServicesIface->setRespondCallback(Tp::memFun(this,&oFonoConnection::USSDRespond)); supplementaryServicesIface->setCancelCallback(Tp::memFun(this,&oFonoConnection::USSDCancel)); supplementaryServicesIface->StateChanged(mOfonoSupplementaryServices->state()); supplementaryServicesIface->setSerial(mOfonoModem->serial()); plugInterface(Tp::AbstractConnectionInterfacePtr::dynamicCast(supplementaryServicesIface)); // Set Presence Tp::SimpleStatusSpec presenceOnline; presenceOnline.type = Tp::ConnectionPresenceTypeAvailable; presenceOnline.maySetOnSelf = false; presenceOnline.canHaveMessage = true; Tp::SimpleStatusSpec presenceOffline; presenceOffline.type = Tp::ConnectionPresenceTypeOffline; presenceOffline.maySetOnSelf = false; presenceOffline.canHaveMessage = true; Tp::SimpleStatusSpec presenceAway; presenceAway.type = Tp::ConnectionPresenceTypeAway; presenceAway.maySetOnSelf = false; presenceAway.canHaveMessage = true; Tp::SimpleStatusSpecMap statuses; statuses.insert(QLatin1String("registered"), presenceOnline); statuses.insert(QLatin1String("roaming"), presenceOnline); statuses.insert(QLatin1String("flightmode"), presenceOffline); statuses.insert(QLatin1String("nosim"), presenceOffline); statuses.insert(QLatin1String("nomodem"), presenceOffline); statuses.insert(QLatin1String("simlocked"), presenceAway); statuses.insert(QLatin1String("unregistered"), presenceAway); statuses.insert(QLatin1String("denied"), presenceAway); statuses.insert(QLatin1String("unknown"), presenceAway); statuses.insert(QLatin1String("searching"), presenceAway); simplePresenceIface->setStatuses(statuses); if (mOfonoModem->isValid()) { supplementaryServicesIface->setSerial(mOfonoModem->serial()); } // force update current presence updateOnlineStatus(); contactsIface = Tp::BaseConnectionContactsInterface::create(); contactsIface->setGetContactAttributesCallback(Tp::memFun(this,&oFonoConnection::getContactAttributes)); contactsIface->setContactAttributeInterfaces(QStringList() << TP_QT_IFACE_CONNECTION << TP_QT_IFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE); plugInterface(Tp::AbstractConnectionInterfacePtr::dynamicCast(contactsIface)); QObject::connect(mOfonoModem, SIGNAL(onlineChanged(bool)), SLOT(updateOnlineStatus())); QObject::connect(mOfonoModem, SIGNAL(serialChanged(QString)), supplementaryServicesIface.data(), SLOT(setSerial(QString))); QObject::connect(mOfonoModem, SIGNAL(interfacesChanged(QStringList)), SLOT(updateOnlineStatus())); QObject::connect(mOfonoMessageManager, SIGNAL(incomingMessage(QString,QVariantMap)), this, SLOT(onOfonoIncomingMessage(QString,QVariantMap))); QObject::connect(mOfonoMessageManager, SIGNAL(immediateMessage(QString,QVariantMap)), this, SLOT(onOfonoImmediateMessage(QString,QVariantMap))); QObject::connect(mOfonoMessageManager, SIGNAL(statusReport(QString,QVariantMap)), this, SLOT(onDeliveryReportReceived(QString,QVariantMap))); QObject::connect(mOfonoVoiceCallManager, SIGNAL(callAdded(QString,QVariantMap)), SLOT(onOfonoCallAdded(QString, QVariantMap))); QObject::connect(mOfonoVoiceCallManager, SIGNAL(validityChanged(bool)), SLOT(onValidityChanged(bool))); QObject::connect(mOfonoSimManager, SIGNAL(validityChanged(bool)), SLOT(onValidityChanged(bool))); QObject::connect(mOfonoSimManager, SIGNAL(presenceChanged(bool)), SLOT(updateOnlineStatus())); QObject::connect(mOfonoSimManager, SIGNAL(pinRequiredChanged(QString)), SLOT(updateOnlineStatus())); QObject::connect(mOfonoSimManager, SIGNAL(subscriberNumbersChanged(QStringList)), SLOT(updateOnlineStatus())); QObject::connect(mOfonoNetworkRegistration, SIGNAL(statusChanged(QString)), SLOT(updateOnlineStatus())); QObject::connect(mOfonoNetworkRegistration, SIGNAL(nameChanged(QString)), SLOT(updateOnlineStatus())); QObject::connect(mOfonoNetworkRegistration, SIGNAL(mccChanged(QString)), SLOT(updateOnlineStatus(QString))); QObject::connect(mOfonoNetworkRegistration, SIGNAL(validityChanged(bool)), SLOT(onValidityChanged(bool))); QObject::connect(mOfonoMessageWaiting, SIGNAL(voicemailMessageCountChanged(int)), voicemailIface.data(), SLOT(setVoicemailCount(int))); QObject::connect(mOfonoMessageWaiting, SIGNAL(voicemailWaitingChanged(bool)), voicemailIface.data(), SLOT(setVoicemailIndicator(bool))); QObject::connect(mOfonoMessageWaiting, SIGNAL(voicemailMailboxNumberChanged(QString)), voicemailIface.data(), SLOT(setVoicemailNumber(QString))); QObject::connect(mMmsdManager, SIGNAL(serviceAdded(const QString&)), SLOT(onMMSDServiceAdded(const QString&))); QObject::connect(mMmsdManager, SIGNAL(serviceRemoved(const QString&)), SLOT(onMMSDServiceRemoved(const QString&))); // update audio route QObject::connect(mOfonoVoiceCallManager, SIGNAL(callAdded(QString,QVariantMap)), SLOT(updateAudioRoute())); QObject::connect(mOfonoVoiceCallManager, SIGNAL(callRemoved(QString)), SLOT(updateAudioRoute())); #ifdef USE_PULSEAUDIO // update audio modes QObject::connect(QPulseAudioEngine::instance(), SIGNAL(audioModeChanged(AudioMode)), SLOT(onAudioModeChanged(AudioMode))); QObject::connect(QPulseAudioEngine::instance(), SIGNAL(availableAudioModesChanged(AudioModes)), SLOT(onAvailableAudioModesChanged(AudioModes))); // check if we should indeed use pulseaudio QByteArray pulseAudioDisabled = qgetenv("PA_DISABLED"); mHasPulseAudio = true; if (!pulseAudioDisabled.isEmpty()) mHasPulseAudio = false; #endif QObject::connect(mOfonoSupplementaryServices, SIGNAL(notificationReceived(const QString &)), supplementaryServicesIface.data(), SLOT(NotificationReceived(const QString &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(requestReceived(const QString &)), supplementaryServicesIface.data(), SLOT(RequestReceived(const QString &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(initiateUSSDComplete(const QString &)), supplementaryServicesIface.data(), SLOT(InitiateUSSDComplete(const QString &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(barringComplete(const QString &, const QString &, const QVariantMap &)), supplementaryServicesIface.data(), SLOT(BarringComplete(const QString &, const QString &, const QVariantMap &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(forwardingComplete(const QString &, const QString &, const QVariantMap &)), supplementaryServicesIface.data(), SLOT(ForwardingComplete(const QString &, const QString &, const QVariantMap &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(waitingComplete(const QString &, const QVariantMap &)), supplementaryServicesIface.data(), SLOT(WaitingComplete(const QString &, const QVariantMap &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(callingLinePresentationComplete(const QString &, const QString &)), supplementaryServicesIface.data(), SLOT(CallingLinePresentationComplete(const QString &, const QString &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(connectedLinePresentationComplete(const QString &, const QString &)), supplementaryServicesIface.data(), SLOT(ConnectedLinePresentationComplete(const QString &, const QString &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(callingLineRestrictionComplete(const QString &, const QString &)), supplementaryServicesIface.data(), SLOT(CallingLineRestrictionComplete(const QString &, const QString &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(connectedLineRestrictionComplete(const QString &, const QString &)), supplementaryServicesIface.data(), SLOT(ConnectedLineRestrictionComplete(const QString &, const QString &))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(initiateFailed()), supplementaryServicesIface.data(), SLOT(InitiateFailed())); QObject::connect(mOfonoSupplementaryServices, SIGNAL(stateChanged(const QString&)), supplementaryServicesIface.data(), SLOT(StateChanged(const QString&))); QObject::connect(mOfonoSupplementaryServices, SIGNAL(respondComplete(bool, const QString &)), supplementaryServicesIface.data(), SLOT(RespondComplete(bool, const QString &))); QObject::connect(this, SIGNAL(disconnected()), this, SLOT(onDisconnected())); // workaround: we can't add services here as tp-ofono interfaces are not exposed on dbus // todo: use QDBusServiceWatcher QTimer::singleShot(1000, this, SLOT(onCheckMMSServices())); } void oFonoConnection::onDisconnected() { setStatus(Tp::ConnectionStatusDisconnected, Tp::ConnectionStatusReasonRequested); } QMap oFonoConnection::callChannels() { return mCallChannels; } void oFonoConnection::onCheckMMSServices() { Q_FOREACH(QString servicePath, mMmsdManager->services()) { onMMSDServiceAdded(servicePath); } } void oFonoConnection::updateMcc() { QString mcc; // check if the network mcc is available first, then try the sim card mcc if (!mOfonoNetworkRegistration->mcc().isEmpty()) { mcc = mOfonoNetworkRegistration->mcc(); } else if (!mOfonoSimManager->mobileCountryCode().isEmpty()) { mcc = mOfonoSimManager->mobileCountryCode(); } PhoneUtils::setMcc(mcc); emergencyModeIface->setCountryCode(PhoneUtils::countryCodeForMCC(mcc)); } void oFonoConnection::onMMSDServiceAdded(const QString &path) { MMSDService *service = new MMSDService(path, this); if (service->modemObjectPath() != mModemPath) { service->deleteLater(); return; } qDebug() << "oFonoConnection::onMMSServiceAdded" << path; mMmsdServices[path] = service; QObject::connect(service, SIGNAL(messageAdded(const QString&, const QVariantMap&)), SLOT(onMMSAdded(const QString&, const QVariantMap&))); QObject::connect(service, SIGNAL(messageRemoved(const QString&)), SLOT(onMMSRemoved(const QString&))); Q_FOREACH(MessageStruct message, service->messages()) { addMMSToService(message.path.path(), message.properties, service->path()); } } QDBusObjectPath oFonoConnection::sendMMS(const QStringList &numbers, const OutgoingAttachmentList& attachments) { // FIXME: dualsim: mms's for now will only be sent using the first modem if (mMmsdServices.count() > 0) { return mMmsdServices.first()->sendMessage(numbers, attachments); } qDebug() << "No mms service available"; return QDBusObjectPath(); } void oFonoConnection::onMMSDServiceRemoved(const QString &path) { MMSDService *service = mMmsdServices.take(path); if (!service) { qWarning() << "oFonoConnection::onMMSServiceRemoved failed" << path; return; } // remove all messages from this service Q_FOREACH(MMSDMessage *message, mServiceMMSList[service->path()]) { qDebug() << "removing message " << message->path() << " from service " << service->path(); message->deleteLater(); mServiceMMSList[service->path()].removeAll(message); } mServiceMMSList.remove(service->path()); service->deleteLater(); qDebug() << "oFonoConnection::onMMSServiceRemoved" << path; } oFonoTextChannel* oFonoConnection::textChannelForMembers(const QStringList &members) { Q_FOREACH(oFonoTextChannel* channel, mTextChannels) { int count = 0; Tp::DBusError error; if (members.size() != channel->members().size()) { continue; } QStringList phoneNumbersOld = inspectHandles(Tp::HandleTypeContact, channel->members(), &error); if (error.isValid()) { continue; } Q_FOREACH(const QString &phoneNumberNew, members) { Q_FOREACH(const QString &phoneNumberOld, phoneNumbersOld) { if (PhoneUtils::normalizePhoneNumber(phoneNumberOld) == PhoneUtils::normalizePhoneNumber(phoneNumberNew)) { count++; } } } if (count == members.size()) { return channel; } } return NULL; } void oFonoConnection::addMMSToService(const QString &path, const QVariantMap &properties, const QString &servicePath) { qDebug() << "addMMSToService " << path << properties << servicePath; MMSDMessage *msg = new MMSDMessage(path, properties); mServiceMMSList[servicePath].append(msg); if (properties["Status"] == "received") { QString senderNormalizedNumber = PhoneUtils::normalizePhoneNumber(properties["Sender"].toString()); QStringList recipientList = properties["Recipients"].toStringList(); // we use QSet to avoid having duplicate entries QSet recipients; Tp::UIntList initialInviteeHandles; // remove empty strings if any recipientList.removeAll(""); if (recipientList.size() > 1) { // remove ourselves from the recipient list Q_FOREACH(const QString &myNumber, mOfonoSimManager->subscriberNumbers()) { Q_FOREACH(const QString &remoteNumber, recipientList) { if (PhoneUtils::comparePhoneNumbers(remoteNumber, myNumber)) { recipientList.removeAll(remoteNumber); break; } } } Q_FOREACH(const QString &recipient, recipientList) { recipients << PhoneUtils::normalizePhoneNumber(recipient); initialInviteeHandles << ensureHandle(recipient); } } else if (senderNormalizedNumber.isEmpty() && recipientList.size() == 1) { // if this is a message coming from the server (no sender), clear the recipient list; recipientList.clear(); senderNormalizedNumber = "x-ofono-unknown"; } // check if there is an open channel for this number and use it oFonoTextChannel *channel = textChannelForMembers(QStringList() << senderNormalizedNumber << recipients.toList()); if (channel) { channel->mmsReceived(path, ensureHandle(senderNormalizedNumber), properties); return; } Tp::DBusError error; bool yours; QVariantMap request; uint handle = ensureHandle(senderNormalizedNumber); qDebug() << "ensure handle" << senderNormalizedNumber << handle; request[TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType")] = TP_QT_IFACE_CHANNEL_TYPE_TEXT; request[TP_QT_IFACE_CHANNEL + QLatin1String(".InitiatorHandle")] = handle; if (initialInviteeHandles.size() > 0) { initialInviteeHandles << handle; request[TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles")] = QVariant::fromValue(initialInviteeHandles); ensureChannel(request, yours, false, &error); } else { request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType")] = Tp::HandleTypeContact; request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle")] = handle; ensureChannel(request, yours, false, &error); } if(error.isValid()) { qCritical() << "Error creating channel for incoming message " << error.name() << error.message(); return; } channel = textChannelForMembers(QStringList() << senderNormalizedNumber << recipients.toList()); if (channel) { channel->mmsReceived(path, handle, properties); } } } void oFonoConnection::onMMSAdded(const QString &path, const QVariantMap &properties) { qDebug() << "oFonoConnection::onMMSAdded" << path << properties; MMSDService *service = qobject_cast(sender()); if (!service) { qWarning() << "oFonoConnection::onMMSAdded failed"; return; } addMMSToService(path, properties, service->path()); } void oFonoConnection::onMMSRemoved(const QString &path) { qDebug() << "oFonoConnection::onMMSRemoved" << path; MMSDService *service = qobject_cast(sender()); if (!service) { qWarning() << "oFonoConnection::onMMSRemoved failed"; return; } // remove this message from the service Q_FOREACH(MMSDMessage *message, mServiceMMSList[service->path()]) { if (message->path() == path) { message->deleteLater(); mServiceMMSList[service->path()].removeAll(message); break; } } } oFonoConnection::~oFonoConnection() { dbusConnection().unregisterObject(objectPath(), QDBusConnection::UnregisterTree); dbusConnection().unregisterService(busName()); mOfonoModemManager->deleteLater(); mOfonoMessageManager->deleteLater(); mOfonoVoiceCallManager->deleteLater(); mOfonoCallVolume->deleteLater(); mOfonoMessageWaiting->deleteLater(); mOfonoNetworkRegistration->deleteLater(); mOfonoSupplementaryServices->deleteLater(); mOfonoSimManager->deleteLater(); mMmsdManager->deleteLater(); Q_FOREACH(MMSDService *service, mMmsdServices) { onMMSDServiceRemoved(service->path()); } } bool oFonoConnection::isNetworkRegistered() { QString status = mOfonoNetworkRegistration->status(); if (!mOfonoNetworkRegistration->isValid()) { return false; } return !(!mOfonoModem->isValid() || !mOfonoModem->online() || status == "unregistered" || status == "denied" || status == "unknown" || status == "searching" || status.isEmpty()); } uint oFonoConnection::setPresence(const QString& status, const QString& statusMessage, Tp::DBusError *error) { qDebug() << "setPresence" << status; // this prevents tp-qt to propagate the available status error->set(TP_QT_ERROR_NOT_AVAILABLE, "Can't change online status: Operation not supported"); return selfHandle(); } Tp::ContactAttributesMap oFonoConnection::getContactAttributes(const Tp::UIntList &handles, const QStringList &ifaces, Tp::DBusError *error) { qDebug() << "getContactAttributes" << handles << ifaces; Tp::ContactAttributesMap attributesMap; QVariantMap attributes; Q_FOREACH(uint handle, handles) { QStringList inspectedHandles = inspectHandles(Tp::HandleTypeContact, Tp::UIntList() << handle, error); if (inspectedHandles.size() > 0) { attributes[TP_QT_IFACE_CONNECTION+"/contact-id"] = inspectedHandles.at(0); } else { continue; } if (ifaces.contains(TP_QT_IFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE)) { attributes[TP_QT_IFACE_CONNECTION_INTERFACE_SIMPLE_PRESENCE+"/presence"] = QVariant::fromValue(mSelfPresence); } attributesMap[handle] = attributes; } return attributesMap; } void oFonoConnection::onValidityChanged(bool valid) { // WORKAROUND: ofono-qt does not refresh the properties once the interface // becomes available, so it contains old values. if (sender() == mOfonoSimManager) { Q_EMIT mOfonoSimManager->modem()->pathChanged(mOfonoModem->path()); } else if (sender() == mOfonoNetworkRegistration) { Q_EMIT mOfonoNetworkRegistration->modem()->pathChanged(mOfonoModem->path()); } else if (sender() == mOfonoVoiceCallManager) { Q_EMIT mOfonoVoiceCallManager->modem()->pathChanged(mOfonoModem->path()); } QString modemSerial; if (valid) { modemSerial = mOfonoModem->serial(); } supplementaryServicesIface->setSerial(modemSerial); emergencyModeIface->setEmergencyNumbers(mOfonoVoiceCallManager->emergencyNumbers()); updateOnlineStatus(); } void oFonoConnection::updateOnlineStatus() { Tp::SimpleContactPresences presences; mSelfPresence.statusMessage = ""; mSelfPresence.type = Tp::ConnectionPresenceTypeOffline; Tp::DBusError *error; QString selfHandleId = inspectHandles(Tp::HandleTypeContact, Tp::UIntList() << selfHandle(), error)[0]; if (!mOfonoModem->isValid()) { mSelfPresence.status = "nomodem"; } else if (!mOfonoModem->online()) { mSelfPresence.status = "flightmode"; } else if ((mOfonoSimManager->isValid() && !mOfonoSimManager->present()) || !mOfonoSimManager->isValid()) { mSelfPresence.status = "nosim"; } else if (mOfonoSimManager->isValid() && mOfonoSimManager->present() && mOfonoSimManager->pinRequired() != "none" && !mOfonoSimManager->pinRequired().isEmpty()) { mSelfPresence.status = "simlocked"; mSelfPresence.type = Tp::ConnectionPresenceTypeAway; } else if (isNetworkRegistered()) { mSelfPresence.status = mOfonoNetworkRegistration->status(); mSelfPresence.statusMessage = mOfonoNetworkRegistration->name(); mSelfPresence.type = Tp::ConnectionPresenceTypeAvailable; } else { mSelfPresence.status = mOfonoNetworkRegistration->status(); mSelfPresence.type = Tp::ConnectionPresenceTypeAway; } if (mOfonoSimManager->subscriberNumbers().size() > 0 && selfHandleId != mOfonoSimManager->subscriberNumbers()[0]) { setSelfHandle(newHandle(mOfonoSimManager->subscriberNumbers()[0])); } presences[selfHandle()] = mSelfPresence; simplePresenceIface->setPresences(presences); updateMcc(); } uint oFonoConnection::newHandle(const QString &identifier) { mHandles[++mHandleCount] = identifier; return mHandleCount; } QStringList oFonoConnection::inspectHandles(uint handleType, const Tp::UIntList& handles, Tp::DBusError *error) { QStringList identifiers; if( handleType != Tp::HandleTypeContact ) { error->set(TP_QT_ERROR_INVALID_ARGUMENT,"Not supported"); return QStringList(); } qDebug() << "oFonoConnection::inspectHandles " << handles; Q_FOREACH( uint handle, handles) { if (mHandles.keys().contains(handle)) { identifiers.append(mHandles.value(handle)); } else { error->set(TP_QT_ERROR_INVALID_HANDLE, "Handle not found"); return QStringList(); } } qDebug() << "oFonoConnection::inspectHandles " << identifiers; return identifiers; } void oFonoConnection::connect(Tp::DBusError *error) { qDebug() << "oFonoConnection::connect"; setStatus(Tp::ConnectionStatusConnected, Tp::ConnectionStatusReasonRequested); } Tp::UIntList oFonoConnection::requestHandles(uint handleType, const QStringList& identifiers, Tp::DBusError* error) { qDebug() << "requestHandles"; Tp::UIntList handles; if( handleType != Tp::HandleTypeContact ) { error->set(TP_QT_ERROR_INVALID_ARGUMENT, "Not supported"); return Tp::UIntList(); } Q_FOREACH( const QString& identifier, identifiers) { const QString normalizedNumber = PhoneUtils::normalizePhoneNumber(identifier); if (mHandles.values().contains(normalizedNumber)) { handles.append(mHandles.key(normalizedNumber)); } else if (PhoneUtils::isPhoneNumber(normalizedNumber)) { handles.append(newHandle(normalizedNumber)); } else { handles.append(newHandle(identifier)); } } qDebug() << "requestHandles" << handles; return handles; } Tp::BaseChannelPtr oFonoConnection::createTextChannel(const QVariantMap &request, Tp::DBusError *error) { uint targetHandle = request.value(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle")).toUInt(); if (mSelfPresence.type != Tp::ConnectionPresenceTypeAvailable) { error->set(TP_QT_ERROR_NETWORK_ERROR, "No network available"); return Tp::BaseChannelPtr(); } QStringList phoneNumbers; bool flash = false; if (request.contains(TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles"))) { phoneNumbers << inspectHandles(Tp::HandleTypeContact, qdbus_cast(request[TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles")]), error); } else { phoneNumbers << mHandles.value(targetHandle); } if (request.contains(TP_QT_IFACE_CHANNEL_INTERFACE_SMS + QLatin1String(".Flash"))) { flash = request[TP_QT_IFACE_CHANNEL_INTERFACE_SMS + QLatin1String(".Flash")].toBool(); } oFonoTextChannel *channel = new oFonoTextChannel(this, phoneNumbers, flash); mTextChannels << channel; QObject::connect(channel, SIGNAL(messageRead(QString)), SLOT(onMessageRead(QString))); QObject::connect(channel, SIGNAL(destroyed()), SLOT(onTextChannelClosed())); return channel->baseChannel(); } void oFonoConnection::onMessageRead(const QString &id) { Q_FOREACH(QList messages, mServiceMMSList.values()) { Q_FOREACH(MMSDMessage* message, messages) { if (message->path() == id) { message->markRead(); message->remove(); return; } } } } void oFonoConnection::onConferenceCallChannelClosed() { if (mConferenceCall) { mConferenceCall = NULL; } } Tp::BaseChannelPtr oFonoConnection::createCallChannel(const QVariantMap &request, Tp::DBusError *error) { uint targetHandle = request.value(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle")).toUInt(); uint initiatorHandle = request.value(TP_QT_IFACE_CHANNEL + QLatin1String(".InitiatorHandle")).toUInt(); bool success = true; QString newPhoneNumber = mHandles.value(targetHandle); bool available = (mSelfPresence.type == Tp::ConnectionPresenceTypeAvailable); bool isConference = (request.contains(TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialChannels")) && (!request.contains(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType")) || request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType")] == Tp::HandleTypeNone) && (!request.contains(TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle")) || request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle")] == 0)); if (!available && isConference) { error->set(TP_QT_ERROR_NETWORK_ERROR, "No network available"); return Tp::BaseChannelPtr(); } if (initiatorHandle == 0 && targetHandle != selfHandle()) { initiatorHandle = selfHandle(); } if (isConference) { // conference call request if (mConferenceCall) { error->set(TP_QT_ERROR_NOT_AVAILABLE, "Conference call already exists"); return Tp::BaseChannelPtr(); } QList channels = mOfonoVoiceCallManager->createMultiparty(); if (!channels.isEmpty()) { mConferenceCall = new oFonoConferenceCallChannel(this); QObject::connect(mConferenceCall, SIGNAL(destroyed()), SLOT(onConferenceCallChannelClosed())); mConferenceCall->baseChannel()->setInitiatorHandle(initiatorHandle); return mConferenceCall->baseChannel(); } error->set(TP_QT_ERROR_NOT_AVAILABLE, "Impossible to merge calls"); return Tp::BaseChannelPtr(); } QDBusObjectPath objpath(request["ofonoObjPath"].toString()); if (objpath.path().isEmpty()) { objpath = mOfonoVoiceCallManager->dial(newPhoneNumber, "", success); } qDebug() << "success " << success; if (objpath.path().isEmpty() || !success) { if (!success) { error->set(TP_QT_ERROR_NOT_AVAILABLE, mOfonoVoiceCallManager->errorMessage()); } else { error->set(TP_QT_ERROR_NOT_AVAILABLE, "Channel could not be created"); } return Tp::BaseChannelPtr(); } oFonoCallChannel *channel = new oFonoCallChannel(this, newPhoneNumber, targetHandle, objpath.path()); channel->baseChannel()->setInitiatorHandle(initiatorHandle); mCallChannels[objpath.path()] = channel; QObject::connect(channel, SIGNAL(destroyed()), SLOT(onCallChannelDestroyed())); QObject::connect(channel, SIGNAL(closed()), SLOT(onCallChannelClosed())); QObject::connect(channel, SIGNAL(merged()), SLOT(onCallChannelMerged())); QObject::connect(channel, SIGNAL(splitted()), SLOT(onCallChannelSplitted())); QObject::connect(channel, SIGNAL(multipartyCallHeld()), SLOT(onMultipartyCallHeld())); QObject::connect(channel, SIGNAL(multipartyCallActive()), SLOT(onMultipartyCallActive())); qDebug() << channel; return channel->baseChannel(); } void oFonoConnection::onMultipartyCallHeld() { if (!mConferenceCall) { return; } mConferenceCall->setConferenceActive(false); } void oFonoConnection::onMultipartyCallActive() { if (!mConferenceCall) { return; } mConferenceCall->setConferenceActive(true); } void oFonoConnection::onCallChannelMerged() { if (!mConferenceCall) { return; } oFonoCallChannel *channel = static_cast(sender()); Q_EMIT channelMerged(QDBusObjectPath(channel->baseChannel()->objectPath())); } void oFonoConnection::onCallChannelSplitted() { if (!mConferenceCall) { return; } oFonoCallChannel *channel = static_cast(sender()); Q_EMIT channelSplitted(QDBusObjectPath(channel->baseChannel()->objectPath())); } Tp::BaseChannelPtr oFonoConnection::createChannel(const QVariantMap &request, Tp::DBusError *error) { const QString channelType = request.value(TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType")).toString(); if (channelType == TP_QT_IFACE_CHANNEL_TYPE_TEXT) { return createTextChannel(request, error); } else if (channelType == TP_QT_IFACE_CHANNEL_TYPE_CALL) { return createCallChannel(request, error); } else { error->set(TP_QT_ERROR_NOT_IMPLEMENTED, "Channel type not available"); } return Tp::BaseChannelPtr(); } OfonoMessageManager *oFonoConnection::messageManager() { return mOfonoMessageManager; } OfonoVoiceCallManager *oFonoConnection::voiceCallManager() { return mOfonoVoiceCallManager; } OfonoCallVolume *oFonoConnection::callVolume() { return mOfonoCallVolume; } void oFonoConnection::onDeliveryReportReceived(const QString &messageId, const QVariantMap& info) { const QString pendingMessageNumber = PendingMessagesManager::instance()->recipientIdForMessageId(messageId); if (pendingMessageNumber.isEmpty()) { return; } const QString normalizedNumber = PhoneUtils::normalizePhoneNumber(pendingMessageNumber); PendingMessagesManager::instance()->removePendingMessage(messageId); // check if there is an open channel for this sender and use it oFonoTextChannel *channel = textChannelForMembers(QStringList() << normalizedNumber); if(channel) { channel->deliveryReportReceived(messageId, ensureHandle(normalizedNumber), info["Delivered"].toBool()); return; } Tp::DBusError error; bool yours; uint handle = ensureHandle(normalizedNumber); QVariantMap request; request[TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType")] = TP_QT_IFACE_CHANNEL_TYPE_TEXT; request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType")] = Tp::HandleTypeContact; request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle")] = handle; request[TP_QT_IFACE_CHANNEL + QLatin1String(".InitiatorHandle")] = handle; ensureChannel(request, yours, false, &error); if(error.isValid()) { qWarning() << "Error creating channel for incoming message" << error.name() << error.message(); return; } channel = textChannelForMembers(QStringList() << normalizedNumber); if(channel) { channel->deliveryReportReceived(messageId, ensureHandle(normalizedNumber), info["Delivered"].toBool()); return; } } void oFonoConnection::onOfonoIncomingMessage(const QString &message, const QVariantMap &info) { ensureTextChannel(message, info, false); } void oFonoConnection::onOfonoImmediateMessage(const QString &message, const QVariantMap &info) { ensureTextChannel(message, info, true); } void oFonoConnection::ensureTextChannel(const QString &message, const QVariantMap &info, bool flash) { QString normalizedNumber = PhoneUtils::normalizePhoneNumber(info["Sender"].toString()).trimmed(); if (normalizedNumber.isEmpty()) { normalizedNumber = "x-ofono-unknown"; } // check if there is an open channel for this sender and use it oFonoTextChannel *channel = textChannelForMembers(QStringList() << normalizedNumber); if(channel) { channel->messageReceived(message, ensureHandle(normalizedNumber), info); return; } Tp::DBusError error; bool yours; uint handle = ensureHandle(normalizedNumber); QVariantMap request; request[TP_QT_IFACE_CHANNEL_INTERFACE_SMS + QLatin1String(".Flash")] = flash; request[TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType")] = TP_QT_IFACE_CHANNEL_TYPE_TEXT; request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType")] = Tp::HandleTypeContact; request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle")] = handle; request[TP_QT_IFACE_CHANNEL + QLatin1String(".InitiatorHandle")] = handle; ensureChannel(request, yours, false, &error); if(error.isValid()) { qWarning() << "Error creating channel for incoming message" << error.name() << error.message(); return; } channel = textChannelForMembers(QStringList() << normalizedNumber); if (channel) { channel->messageReceived(message, ensureHandle(normalizedNumber), info); } } void oFonoConnection::onTextChannelClosed() { oFonoTextChannel *channel = static_cast(sender()); if (channel) { qDebug() << "text channel closed"; mTextChannels.removeAll(channel); } } void oFonoConnection::onCallChannelClosed() { qDebug() << "onCallChannelClosed()"; oFonoCallChannel *channel = static_cast(sender()); if (channel) { Q_EMIT channelHangup(QDBusObjectPath(channel->baseChannel()->objectPath())); } } void oFonoConnection::onCallChannelDestroyed() { qDebug() << "onCallChannelDestroyed()"; oFonoCallChannel *channel = static_cast(sender()); if (channel) { QString key = mCallChannels.key(channel); qDebug() << "call channel closed for number " << key; mCallChannels.remove(key); } } uint oFonoConnection::ensureHandle(const QString &phoneNumber) { const QString normalizedNumber = PhoneUtils::normalizePhoneNumber(phoneNumber); Q_FOREACH(const QString &phone, mHandles.values()) { if (normalizedNumber == phone) { // this user already exists return mHandles.key(phone); } } return newHandle(normalizedNumber); } bool oFonoConnection::matchChannel(const Tp::BaseChannelPtr &channel, const QVariantMap &request, Tp::DBusError *error) { QString channelType = request[TP_QT_IFACE_CHANNEL + QLatin1String(".ChannelType")].toString(); uint targetHandleType = request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandleType")].toUInt(); uint targetHandle = request[TP_QT_IFACE_CHANNEL + QLatin1String(".TargetHandle")].toUInt(); if (channelType == TP_QT_IFACE_CHANNEL_TYPE_TEXT && channel->targetHandleType() == targetHandleType && channel->targetHandle() == targetHandle && targetHandleType == Tp::HandleTypeNone) { // check invitee handles if (request.contains(TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles"))) { QStringList phoneNumbers = inspectHandles(Tp::HandleTypeContact, request[TP_QT_IFACE_CHANNEL_INTERFACE_CONFERENCE + QLatin1String(".InitialInviteeHandles")].value(), error); oFonoTextChannel *existingChannel = textChannelForMembers(phoneNumbers); return existingChannel && (channel == existingChannel->baseChannel()); } } // we only match text channels return (channelType == TP_QT_IFACE_CHANNEL_TYPE_TEXT) && BaseConnection::matchChannel(channel, request, error); } void oFonoConnection::onOfonoCallAdded(const QString &call, const QVariantMap &properties) { qDebug() << "new call" << call << properties; bool yours; Tp::DBusError error; QString lineIdentification = properties["LineIdentification"].toString(); // check if there is an open channel for this call, if so, ignore it if (mCallChannels.keys().contains(call)) { qWarning() << "call channel for this object path already exists: " << call; return; } QString normalizedNumber; // TODO check if more than one private/unknown calls are supported at the same time if (lineIdentification.isEmpty()) { // unknown caller Id lineIdentification = QString("x-ofono-unknown"); normalizedNumber = lineIdentification; } else if (lineIdentification == "withheld") { // private caller lineIdentification = QString("x-ofono-private"); normalizedNumber = lineIdentification; } else { normalizedNumber = PhoneUtils::normalizePhoneNumber(lineIdentification); } uint handle = ensureHandle(normalizedNumber); uint initiatorHandle = 0; if (properties["State"] == "incoming" || properties["State"] == "waiting") { initiatorHandle = handle; } else { initiatorHandle = selfHandle(); } qDebug() << "initiatorHandle " <voicemailMessageCount(); } QString oFonoConnection::voicemailNumber(Tp::DBusError *error) { return mOfonoMessageWaiting->voicemailMailboxNumber(); } bool oFonoConnection::voicemailIndicator(Tp::DBusError *error) { return mOfonoMessageWaiting->voicemailWaiting(); } QString oFonoConnection::activeAudioOutput() { return mActiveAudioOutput; } AudioOutputList oFonoConnection::audioOutputs() { return mAudioOutputs; } QStringList oFonoConnection::emergencyNumbers(Tp::DBusError *error) { return mOfonoVoiceCallManager->emergencyNumbers(); } void oFonoConnection::setActiveAudioOutput(const QString &id) { mActiveAudioOutput = id; Q_EMIT activeAudioOutputChanged(id); } void oFonoConnection::USSDInitiate(const QString &command, Tp::DBusError *error) { mOfonoSupplementaryServices->initiate(command); } void oFonoConnection::USSDRespond(const QString &reply, Tp::DBusError *error) { mOfonoSupplementaryServices->respond(reply); } void oFonoConnection::USSDCancel(Tp::DBusError *error) { mOfonoSupplementaryServices->cancel(); } #ifdef USE_PULSEAUDIO void oFonoConnection::onAudioModeChanged(AudioMode mode) { qDebug("PulseAudio audio mode changed: 0x%x", mode); if (mode == AudioModeEarpiece && mActiveAudioOutput != "earpiece") { setActiveAudioOutput("earpiece"); } else if (mode == AudioModeWiredHeadset && mActiveAudioOutput != "wired_headset") { setActiveAudioOutput("wired_headset"); } else if (mode == AudioModeSpeaker && mActiveAudioOutput != "speaker") { setActiveAudioOutput("speaker"); } else if (mode == AudioModeBluetooth && mActiveAudioOutput != "bluetooth") { setActiveAudioOutput("bluetooth"); } } void oFonoConnection::onAvailableAudioModesChanged(AudioModes modes) { qDebug("PulseAudio available audio modes changed"); bool defaultFound = false; mAudioOutputs.clear(); Q_FOREACH(const AudioMode &mode, modes) { AudioOutput output; if (mode == AudioModeBluetooth) { // there can be only one bluetooth output.id = "bluetooth"; output.type = "bluetooth"; // we dont support names for now, so we set a default value output.name = "bluetooth"; } else if (mode == AudioModeEarpiece || mode == AudioModeWiredHeadset) { if (!defaultFound) { defaultFound = true; output.id = "default"; output.type = "default"; output.name = "default"; } else { continue; } } else if (mode == AudioModeSpeaker) { output.id = "speaker"; output.type = "speaker"; output.name = "speaker"; } mAudioOutputs << output; } Q_EMIT audioOutputsChanged(mAudioOutputs); } #endif void oFonoConnection::updateAudioRoute() { #ifdef USE_PULSEAUDIO if (!mHasPulseAudio) return; #endif int currentCalls = mOfonoVoiceCallManager->getCalls().size(); if (currentCalls != 0) { if (currentCalls == 1) { // if we have only one call, check if it's incoming and // enable speaker mode so the ringtone is audible OfonoVoiceCall *call = new OfonoVoiceCall(mOfonoVoiceCallManager->getCalls().first()); if (call) { if (call->state() == "incoming") { enable_ringtone(); call->deleteLater(); return; } if (call->state() == "disconnected") { enable_normal(); call->deleteLater(); return; } // if only one call and dialing, default to earpiece if (call->state() == "dialing") { enable_earpiece(); call->deleteLater(); return; } if (call->state().isEmpty()) { call->deleteLater(); return; } call->deleteLater(); } } } else { enable_normal(); Q_EMIT lastChannelClosed(); } } // this method is only called when call channels go from incoming to active. // please call this method only from oFonoCallChannel instances void oFonoConnection::updateAudioRouteToEarpiece() { #ifdef USE_PULSEAUDIO if (!mHasPulseAudio) return; #endif if (mOfonoVoiceCallManager->getCalls().size() == 1) { enable_earpiece(); } } QString oFonoConnection::uniqueName() const { QString timestamp(QString::number(QDateTime::currentMSecsSinceEpoch())); QString md5(QCryptographicHash::hash(timestamp.toLatin1(), QCryptographicHash::Md5).toHex()); return QString(QLatin1String("connection_%1")).arg(md5); } telepathy-ofono-0.2+16.04.20151120/protocol.h0000644000015300001610000000247112623675611021044 0ustar pbuserpbgroup00000000000000/** * Copyright (C) 2013 Canonical, Ltd. * * Authors: * Tiago Salem Herrmann * * This file is part of telepathy-ofono. * * telepathy-ofono 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; version 3. * * telepathy-ofono 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 LESSER General Public License * along with this program. If not, see . */ #ifndef OFONOPROTOCOL_H #define OFONOPROTOCOL_H #include #include "powerdaudiomodemediator.h" #include "powerddbus.h" class Protocol : public Tp::BaseProtocol { Q_OBJECT Q_DISABLE_COPY(Protocol) public: Protocol(const QDBusConnection &dbusConnection, const QString &name); private: Tp::BaseConnectionPtr createConnection(const QVariantMap ¶meters, Tp::DBusError *error); Tp::BaseProtocolAddressingInterfacePtr addressingIface; PowerDDBus mPowerDDBus; PowerDAudioModeMediator mAudioModeMediator; }; #endif