summaryrefslogtreecommitdiff
path: root/rockworkd/platformintegration/sailfish/sailfishplatform.cpp
blob: 09e1426c08673ed89ea5c2407703a7860d8be376 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#include "sailfishplatform.h"

#include "callchannelobserver.h"
#include "organizeradapter.h"
#include "syncmonitorclient.h"

#include <QDBusConnection>
#include <QDBusConnectionInterface>
#include <QDebug>

SailfishPlatform::SailfishPlatform(QObject *parent):
    PlatformInterface(parent),
    _pulseBus(NULL),
    _maxVolume(0)
{
    // Notifications
    QDBusConnection::sessionBus().registerObject("/org/freedesktop/Notifications", this, QDBusConnection::ExportAllSlots);
    m_iface = new QDBusInterface("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus");
    m_iface->call("AddMatch", "interface='org.freedesktop.Notifications',member='Notify',type='method_call',eavesdrop='true'");
    m_iface->call("AddMatch", "interface='org.freedesktop.Notifications',member='CloseNotification',type='method_call',eavesdrop='true'");

    // Music
    QDBusConnectionInterface *iface = QDBusConnection::sessionBus().interface();
    const QStringList &services = iface->registeredServiceNames();
    foreach (QString service, services) {
        if (service.startsWith("org.mpris.MediaPlayer2.")) {
            qDebug() << "have mpris service" << service;
            m_mprisService = service;
            fetchMusicMetadata();
            QDBusConnection::sessionBus().connect(m_mprisService, "/org/mpris/MediaPlayer2", "", "PropertiesChanged", this, SLOT(mediaPropertiesChanged(QString,QVariantMap,QStringList)));
            break;
        }
    }

    QDBusMessage call = QDBusMessage::createMethodCall("org.PulseAudio1", "/org/pulseaudio/server_lookup1", "org.freedesktop.DBus.Properties", "Get" );
    call << "org.PulseAudio.ServerLookup1" << "Address";
    QDBusReply<QDBusVariant> lookupReply = QDBusConnection::sessionBus().call(call);
    if (lookupReply.isValid()) {
        //
        qDebug() << "PulseAudio Bus address: " << lookupReply.value().variant().toString();
        _pulseBus = new QDBusConnection(QDBusConnection::connectToPeer(lookupReply.value().variant().toString(), "org.PulseAudio1"));
    }
    // Query max volume
    call = QDBusMessage::createMethodCall("com.Meego.MainVolume2", "/com/meego/mainvolume2",
                                                       "org.freedesktop.DBus.Properties", "Get");
    call << "com.Meego.MainVolume2" << "StepCount";
    QDBusReply<QDBusVariant> volumeMaxReply = _pulseBus->call(call);
    if (volumeMaxReply.isValid()) {
        _maxVolume = volumeMaxReply.value().variant().toUInt();
        qDebug() << "Max volume: " << _maxVolume;
    }
    else {
        qWarning() << "Could not read volume max, cannot adjust volume: " << volumeMaxReply.error().message();
    }

    // Calls
    m_telepathyMonitor = new TelepathyMonitor(this);
    connect(m_telepathyMonitor, &TelepathyMonitor::incomingCall, this, &SailfishPlatform::incomingCall);
    connect(m_telepathyMonitor, &TelepathyMonitor::callStarted, this, &SailfishPlatform::callStarted);
    connect(m_telepathyMonitor, &TelepathyMonitor::callEnded, this, &SailfishPlatform::callEnded);

    // Organizer
    m_organizerAdapter = new OrganizerAdapter(this);
    m_organizerAdapter->refresh();
    connect(m_organizerAdapter, &OrganizerAdapter::itemsChanged, this, &SailfishPlatform::organizerItemsChanged);
    m_syncMonitorClient = new SyncMonitorClient(this);
    connect(m_syncMonitorClient, &SyncMonitorClient::stateChanged, [this]() { if (m_syncMonitorClient->state() == "idle") m_organizerAdapter->refresh();});
    m_syncTimer.start(1000 * 60 * 60);
    connect(&m_syncTimer, &QTimer::timeout, [this]() { m_syncMonitorClient->sync({"calendar"});});
    m_syncMonitorClient->sync({"calendar"});
}

QDBusInterface *SailfishPlatform::interface() const
{
    return m_iface;
}

uint SailfishPlatform::Notify(const QString &app_name, uint replaces_id, const QString &app_icon, const QString &summary, const QString &body, const QStringList &actions, const QVariantHash &hints, int expire_timeout)
{
    qDebug() << "Notification received" << app_name << replaces_id << app_icon << summary << body << actions << hints << expire_timeout;
    QString owner = hints.value("x-nemo-owner", "").toString();

    // Look up the notification category and its parameters
    QString category = hints.value("category", "").toString();
    QHash<QString, QString> categoryParams = this->getCategoryParams(category);

    // Ignore transient and hidden notifications (notif hints override category hints)
    // Hack this to accept transient -preview and -summary notifications, as we don't know how to decode the actual notifs yet
    if (hints.value("transient", categoryParams.value("transient", "false")).toString() == "true") {
        qDebug() << "Ignoring transient notification from " << owner;
        return 0;
    }
    else if (hints.value("x-nemo-hidden", "false").toString() == "true" ) {
        qDebug() << "Ignoring hidden notification from " << owner;
        return 0;
    }

    Notification n(app_name);
    if (owner == "twitter-notifications-client") {
        n.setType(Notification::NotificationTypeTwitter);
        n.setSourceName("Twitter");
    } else if (category == "x-nemo.email") {
        if (app_name.toLower().contains("gmail")) {
            n.setType(Notification::NotificationTypeGMail);
            n.setSourceName("GMail");
        }
        else {
            n.setType(Notification::NotificationTypeEmail);
            n.setSubject(app_name);
        }
    } else if (owner == "facebook-notifications-client") {
        n.setType(Notification::NotificationTypeFacebook);
        n.setSourceName("Facebook");
    } else if (hints.value("x-nemo-origin-package").toString() == "org.telegram.messenger"
               || category.startsWith("harbour.sailorgram")) {
        n.setType(Notification::NotificationTypeTelegram);
        n.setSourceName("Telegram");
    } else if (hints.value("x-nemo-origin-package").toString() == "com.google.android.apps.babel"
               || owner == "harbour-hangish") {
        n.setType(Notification::NotificationTypeHangout);
        n.setSourceName("Hangouts");
    } else if (hints.value("x-nemo-origin-package").toString() == "com.whatsapp"
               || owner.toLower().contains("whatsup")) {
        n.setType(Notification::NotificationTypeWhatsApp);
        n.setSourceName("Whatsapp");
    } else if (app_name.contains("indicator-datetime")) {
        n.setType(Notification::NotificationTypeReminder);
        n.setSourceName("reminders");
    } else {
        n.setType(Notification::NotificationTypeGeneric);
    }
    n.setSender(summary);
    n.setBody(body);
    foreach (const QString &action, actions) {
        if (action == "default") {
            n.setActToken(hints.value("x-nemo-remote-action-default").toString());
            break;
        }
    }
    qDebug() << "have act token" << n.actToken();

    emit notificationReceived(n);
    // We never return something. We're just snooping in...
    setDelayedReply(true);
    return 0;
}

    QHash<QString, QString> SailfishPlatform::getCategoryParams(QString category)
    {
        if (!category.isEmpty()) {
            QString categoryConfigFile = QString("/usr/share/lipstick/notificationcategories/%1.conf").arg(category);
            QFile testFile(categoryConfigFile);
            if (testFile.exists()) {
                QHash<QString, QString> categories;
                QSettings settings(categoryConfigFile, QSettings::IniFormat);
                const QStringList settingKeys = settings.allKeys();
                foreach (const QString &settingKey, settingKeys) {
                    categories[settingKey] = settings.value(settingKey).toString();
                }
                return categories;
            }
        }
        return QHash<QString, QString>();
    }

void SailfishPlatform::sendMusicControlCommand(MusicControlButton controlButton)
{
    QString method;
    switch (controlButton) {
    case MusicControlPlayPause:
        method = "PlayPause";
        break;
    case MusicControlSkipBack:
        method = "Previous";
        break;
    case MusicControlSkipNext:
        method = "Next";
        break;
    default:
        ;
    }

    if (!method.isEmpty()) {
        QDBusMessage call = QDBusMessage::createMethodCall(m_mprisService, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player", method);
        QDBusError err = QDBusConnection::sessionBus().call(call);

        if (err.isValid()) {
            qWarning() << "Error calling mpris method on" << m_mprisService << ":" << err.message();
        }
        return;
    }

    if (controlButton == MusicControlVolumeUp || controlButton == MusicControlVolumeDown) {
        QDBusMessage call = QDBusMessage::createMethodCall("com.Meego.MainVolume2", "/com/meego/mainvolume2",
                                                       "org.freedesktop.DBus.Properties", "Get");
        call << "com.Meego.MainVolume2" << "CurrentStep";

        QDBusReply<QDBusVariant> volumeReply = _pulseBus->call(call);
        if (volumeReply.isValid()) {
            // Decide the new value for volume, taking limits into account
            uint volume = volumeReply.value().variant().toUInt();
            uint newVolume;
            qDebug() << "Current volume: " << volumeReply.value().variant().toUInt();
            if (controlButton == MusicControlVolumeUp && volume < _maxVolume-1 ) {
                newVolume = volume + 1;
            }
            else if (controlButton == MusicControlVolumeDown && volume > 0) {
                newVolume = volume - 1;
            }
            else {
            qDebug() << "Volume already at limit";
            newVolume = volume;
            }

            // If we have a new volume level, change it
            if (newVolume != volume) {
                qDebug() << "Setting volume: " << newVolume;

                call = QDBusMessage::createMethodCall("com.Meego.MainVolume2", "/com/meego/mainvolume2",
                                                      "org.freedesktop.DBus.Properties", "Set");
                call << "com.Meego.MainVolume2" << "CurrentStep" << QVariant::fromValue(QDBusVariant(newVolume));

                QDBusError err = _pulseBus->call(call);
                if (err.isValid()) {
                    qWarning() << err.message();
                }
            }
        }
    }
}

MusicMetaData SailfishPlatform::musicMetaData() const
{
    return m_musicMetaData;
}

void SailfishPlatform::hangupCall(uint cookie)
{
    m_telepathyMonitor->hangupCall(cookie);
}

QList<CalendarEvent> SailfishPlatform::organizerItems() const
{
    return m_organizerAdapter->items();
}

void SailfishPlatform::actionTriggered(const QString &actToken)
{
   QVariantMap action;
   // Extract the element of the DBus call
   QStringList elements(actToken.split(' ', QString::SkipEmptyParts));
   if (elements.size() <= 3) {
    qWarning() << "Unable to decode invalid remote action:" << actToken;
    } else {
    int index = 0;
    action.insert(QStringLiteral("service"), elements.at(index++));
    action.insert(QStringLiteral("path"), elements.at(index++));
    action.insert(QStringLiteral("iface"), elements.at(index++));
    action.insert(QStringLiteral("method"), elements.at(index++));

    if (index < elements.size()) {
        QVariantList args;
        while (index < elements.size()) {
            const QString &arg(elements.at(index++));
            const QByteArray buffer(QByteArray::fromBase64(arg.toUtf8()));

            QDataStream stream(buffer);
            QVariant var;
            stream >> var;
            args.append(var);
        }
      action.insert(QStringLiteral("arguments"), args);
    }
    qDebug() << "Calling: " << action;
    QDBusMessage call = QDBusMessage::createMethodCall(action.value("service").toString(), action.value("path").toString(), action.value("iface").toString(), action.value("method").toString());
    if (action.contains("arguments")) call.setArguments(action.value("arguments").toList());
    QDBusConnection::sessionBus().call(call);
   }
}

void SailfishPlatform::fetchMusicMetadata()
{
    if (!m_mprisService.isEmpty()) {
        QDBusMessage call = QDBusMessage::createMethodCall(m_mprisService, "/org/mpris/MediaPlayer2", "org.freedesktop.DBus.Properties", "Get");
        call << "org.mpris.MediaPlayer2.Player" << "Metadata";
        QDBusPendingCall pcall = QDBusConnection::sessionBus().asyncCall(call);
        QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, this);
        connect(watcher, &QDBusPendingCallWatcher::finished, this, &SailfishPlatform::fetchMusicMetadataFinished);
    }
}

void SailfishPlatform::fetchMusicMetadataFinished(QDBusPendingCallWatcher *watcher)
{
    watcher->deleteLater();
    QDBusReply<QDBusVariant> reply = watcher->reply();
    if (reply.isValid()) {
        QVariantMap curMetadata = qdbus_cast<QVariantMap>(reply.value().variant().value<QDBusArgument>());
        m_musicMetaData.artist = curMetadata.value("xesam:artist").toString();
        m_musicMetaData.album = curMetadata.value("xesam:album").toString();
        m_musicMetaData.title = curMetadata.value("xesam:title").toString();
        emit musicMetadataChanged(m_musicMetaData);
    } else {
        qWarning() << reply.error().message();
    }
}

void SailfishPlatform::mediaPropertiesChanged(const QString &interface, const QVariantMap &changedProps, const QStringList &invalidatedProps)
{
    Q_UNUSED(interface)
    Q_UNUSED(changedProps)
    Q_UNUSED(invalidatedProps)
    fetchMusicMetadata();
}