summaryrefslogtreecommitdiff
path: root/mpris2/interfacetest.cpp
blob: 69a2283e8118ecd8e0afe8dbb8ce4424696aa611 (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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) 2011  Alex Merry <dev@randomguy3.me.uk>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) 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.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#define MPRIS2_PATH "/org/mpris/MediaPlayer2"
#define DBUS_PROPS_IFACE "org.freedesktop.DBus.Properties"

#include "interfacetest.h"

#include <QtDBus>
#include <QDebug>
#include <QTimer>

using namespace Mpris2;

InterfaceTest::InterfaceTest ( const QString& interface, const QString& service, QObject* parent ) : QObject(parent)
{
    iface = new QDBusInterface(service, MPRIS2_PATH, interface, QDBusConnection::sessionBus(), this);
    propsIface = new QDBusInterface(service, MPRIS2_PATH, DBUS_PROPS_IFACE, QDBusConnection::sessionBus(), this);
    delayedCheckTimer = new QTimer(this);
    delayedCheckTimer->setInterval(2000);
    connect(delayedCheckTimer, SIGNAL(timeout()),
            this, SLOT(delayedIncrementalCheck()));
}

InterfaceTest::~InterfaceTest()
{
}

void InterfaceTest::connectSignals()
{
}

QVariantMap InterfaceTest::properties() const
{
    return props;
}

bool InterfaceTest::getAllProps()
{
    if (!propsIface->isValid() || !iface->isValid()) {
        emit interfaceError(Other, "",
                            "No object with the "
                            + iface->interface() +
                            " and "
                            DBUS_PROPS_IFACE
                            " interfaces was not found at "
                            MPRIS2_PATH);
        return false;
    }

    QDBusReply<QVariantMap> propsReply = propsIface->call("GetAll", iface->interface());
    if (!propsReply.isValid()) {
        emit interfaceError(Other, "",
                            "The " DBUS_PROPS_IFACE
                            " interface was not implemented correctly at "
                            MPRIS2_PATH);
        return false;
    }
    props = propsReply.value();

    return true;
}

bool InterfaceTest::getProp(const QString& propName, InterfaceTest::PropErrorAllowance allowError)
{
    if (!propsIface->isValid() || !iface->isValid()) {
        emit interfaceError(Other, "",
                            "No object with the "
                            + iface->interface() +
                            " and "
                            DBUS_PROPS_IFACE
                            " interfaces was not found at "
                            MPRIS2_PATH);
        return false;
    }

    QDBusReply<QVariant> propsReply = propsIface->call("Get", iface->interface(), propName);
    if (!propsReply.isValid()) {
        if (propsReply.error().type() == QDBusError::UnknownInterface) {
            emit interfaceError(Other, "",
                                "The " DBUS_PROPS_IFACE
                                " interface was not implemented correctly at "
                                MPRIS2_PATH "(replied \"unknown interface\")");
        } else if (propsReply.error().type() == QDBusError::UnknownMethod) {
            emit interfaceError(Other, "",
                                "The " DBUS_PROPS_IFACE
                                " interface was not implemented correctly at "
                                MPRIS2_PATH "(replied \"unknown method\" for method \"Get\")");
        } else if (propsReply.error().type() == QDBusError::InvalidArgs) {
            if (allowError & PropAllowMissing) {
                emit interfaceInfo(Property, propName,
                                   DBUS_PROPS_IFACE ".Get failed; reported \"invalid args\" (ie: unknown property)");
            } else {
                emit interfaceError(Property, propName,
                                    DBUS_PROPS_IFACE ".Get failed; reported \"invalid args\" (ie: unknown property)");
            }
        } else if (propsReply.error().name() == "org.freedesktop.DBus.UnknownProperty") {
            if (allowError & PropAllowMissing) {
                emit interfaceInfo(Property, propName,
                                   DBUS_PROPS_IFACE ".Get failed; reported \"unknown property\"");
            } else {
                emit interfaceError(Property, propName,
                                    DBUS_PROPS_IFACE ".Get failed; reported \"unknown property\"");
            }
        } else {
            if (allowError) {
                emit interfaceWarning(Other, "",
                                    "Calling " DBUS_PROPS_IFACE
                                    ".Get resulted in the unexpected error " + propsReply.error().name());
            } else {
                emit interfaceError(Other, "",
                                    "Calling " DBUS_PROPS_IFACE
                                    ".Get resulted in the error " + propsReply.error().name());
            }
        }
        return false;
    }
    props[propName] = propsReply.value();

    return true;
}

bool InterfaceTest::setProp(const QString& propName, const QDBusVariant& propValue, InterfaceTest::PropErrorAllowance allowError)
{
    if (!propsIface->isValid() || !iface->isValid()) {
        emit interfaceError(Other, "",
                            "No object with the "
                            + iface->interface() +
                            " and "
                            DBUS_PROPS_IFACE
                            " interfaces was not found at "
                            MPRIS2_PATH);
        return false;
    }

    QDBusReply<void> propsReply = propsIface->call("Set", iface->interface(), propName, QVariant::fromValue<QDBusVariant>(propValue));
    if (propsReply.isValid()) {
        return true;
    } else {
        if (propsReply.error().type() == QDBusError::UnknownInterface) {
            emit interfaceError(Other, "",
                                "The " DBUS_PROPS_IFACE
                                " interface was not implemented correctly at "
                                MPRIS2_PATH "(replied \"unknown interface\")");
        } else if (propsReply.error().type() == QDBusError::UnknownMethod) {
            emit interfaceError(Other, "",
                                "The " DBUS_PROPS_IFACE
                                " interface was not implemented correctly at "
                                MPRIS2_PATH "(replied \"unknown method\" for method \"Set\")");
        } else if (propsReply.error().type() == QDBusError::InvalidArgs) {
            if (allowError & PropAllowMissing || allowError & PropAllowReadOnly) {
                emit interfaceInfo(Property, propName,
                                   DBUS_PROPS_IFACE ".Set failed; reported \"invalid args\"");
            } else {
                emit interfaceError(Property, propName,
                                    DBUS_PROPS_IFACE ".Set failed; reported \"invalid args\"");
            }
        } else if (propsReply.error().name() == "org.freedesktop.DBus.UnknownProperty") {
            if (allowError & PropAllowMissing) {
                emit interfaceInfo(Property, propName,
                                   DBUS_PROPS_IFACE ".Set failed; reported \"unknown property\"");
            } else {
                emit interfaceError(Property, propName,
                                    DBUS_PROPS_IFACE ".Set failed; reported \"unknown property\"");
            }
        } else if (propsReply.error().name() == "com.trolltech.QtDBus.Error.InternalError") {
            // Qt returns InternalError for read-only properties
            if (allowError & PropAllowReadOnly) {
                emit interfaceInfo(Property, propName,
                                   DBUS_PROPS_IFACE ".Set failed; reported \"internal error\" (Qt's way of saying \"read only\")");
            } else {
                emit interfaceError(Property, propName,
                                    DBUS_PROPS_IFACE ".Set failed; reported \"internal error\" (Qt's way of saying \"read only\")");
            }
        } else {
            if (allowError) {
                emit interfaceWarning(Other, "",
                                    "Calling " DBUS_PROPS_IFACE
                                    ".Set resulted in the unexpected error " + propsReply.error().name());
            } else {
                emit interfaceError(Other, "",
                                    "Calling " DBUS_PROPS_IFACE
                                    ".Set resulted in the error " + propsReply.error().name());
            }
        }
        return false;
    }
}


bool InterfaceTest::checkPropValid(const QString& propName, QVariant::Type expType, const QVariantMap& oldProps) {
    if (!props.contains(propName)) {
        emit interfaceError(Property, propName, "Property " + propName + " is missing");
        return false;
    } else if (props.value(propName).type() != expType) {
        // FIXME: generate D-Bus type description
        const char * gotTypeCh = QDBusMetaType::typeToSignature(props.value(propName).userType());
        QString gotType = gotTypeCh ? QString::fromAscii(gotTypeCh) : "<unknown>";
        const char * expTypeCh = QDBusMetaType::typeToSignature(expType);
        QString expType = expTypeCh ? QString::fromAscii(expTypeCh) : "<unknown>";

        emit interfaceError(Property, propName, "Property " + propName + " has type '" + gotType + "', but should be type '" + expType + "'");
        return false;
    } else if (oldProps.contains(propName)) {
        // FIXME: QVariant equality only works for builtin types
        if (props.value(propName).type() < QVariant::UserType) {
            if (props.value(propName) != oldProps.value(propName)) {
                outOfDateProperties.insert(propName, props.value(propName));
                props[propName] = oldProps.value(propName);
            }
        } else {
            qDebug() << "Could not check equality for" << propName;
        }
        // we have either already checked this, or we will check it
        // soon
        return false;
    }
    return true;
}

bool InterfaceTest::checkNonEmptyStringPropValid(const QString& propName, const QVariantMap& oldProps) {
    if (checkPropValid(propName, QVariant::String, oldProps)) {
        if (props[propName].toString().isEmpty()) {
            emit interfaceError(Property, propName, "Property " + propName + " is present, but empty");
        } else {
            return true;
        }
    }
    return false;
}

void InterfaceTest::initialTest()
{
    if (!getAllProps())
        return;

    checkProps();

    QDBusConnection::sessionBus().connect(
            iface->service(),
            iface->path(),
            DBUS_PROPS_IFACE,
            "PropertiesChanged", /* signature, */
            this,
            SLOT( _m_propertiesChanged(QString,QVariantMap,QStringList,QDBusMessage)));
    connectSignals();

    emit propertiesChanged(properties().keys());
}

void InterfaceTest::incrementalTest()
{
    QVariantMap oldProps = props;

    if (!getAllProps())
        return;

    checkProps(oldProps);

    if (!delayedCheckTimer->isActive())
        delayedCheckTimer->start();
}

void InterfaceTest::_m_propertiesChanged(const QString& interface,
                                         const QVariantMap& changedProperties,
                                         const QStringList& invalidatedProperties,
                                         const QDBusMessage& signalMessage)
{
    Q_UNUSED(interface)
    Q_UNUSED(signalMessage)

    QStringList changedPropsList = invalidatedProperties;
    QVariantMap::const_iterator i = changedProperties.constBegin();
    while (i != changedProperties.constEnd()) {
        if (propsNotUpdated.contains(i.key())) {
            emit interfaceError(Signal, "PropertiesChanged", "PropertiesChanged signal sent for " + i.key() + "; you almost certainly didn't want to do this");
        } else {
            props[i.key()] = i.value();
            checkUpdatedProperty(i.key());
            outOfDateProperties.remove(i.key());
            changedPropsList << i.key();
        }
        ++i;
    }
    QStringList::const_iterator j = invalidatedProperties.constBegin();
    while (j != invalidatedProperties.constEnd()) {
        if (propsNotUpdated.contains(*j)) {
            emit interfaceError(Signal, "PropertiesChanged", "PropertiesChanged signal sent for " + *j + "; you almost certainly didn't want to do this");
        } else {
            if (getProp(*j))
                checkUpdatedProperty(*j);
            outOfDateProperties.remove(*j);
        }
        ++j;
    }
    checkConsistency();

    emit propertiesChanged(changedPropsList);
}

void InterfaceTest::delayedIncrementalCheck()
{
    QVariantMap::const_iterator i = outOfDateProperties.constBegin();
    while (i != outOfDateProperties.constEnd()) {
        int warningsSoFar = propertyUpdateWarningCount.value(i.key());
        if (warningsSoFar < 4) {
            emit interfaceWarning(Property, i.key(), "Property was not updated via PropertiesChanged signal");
        } else if (warningsSoFar == 4) {
            emit interfaceWarning(Property, i.key(), "Property was not updated via PropertiesChanged signal [further warnings for this property suppressed]");
        }
        propertyUpdateWarningCount.insert(i.key(), warningsSoFar + 1);
        props[i.key()] = i.value();
        ++i;
    }
    outOfDateProperties.clear();
}

void InterfaceTest::checkMetadata(const QVariantMap& metadata,
                                  QStringList* errors,
                                  QStringList* warnings,
                                  QStringList* infoMessages)
{
    if (!metadata.contains("mpris:trackid")) {
        (*errors) << "No mpris:trackid entry";
    } else if (metadata.value("mpris:trackid").userType() != qMetaTypeId<QDBusObjectPath>()) {
        (*errors) << "mpris:trackid entry was not sent as a D-Bus object path (D-Bus type 'o')";
    } else {
        QDBusObjectPath trackid = metadata.value("mpris:trackid").value<QDBusObjectPath>();
        if (trackid.path().isEmpty()) {
            (*errors) << "mpris:trackid entry is an empty path";
        } else if (trackid.path().startsWith("/org/mpris/") && trackid.path() != "/org/mpris/MediaPlayer2/TrackList/NoTrack") {
            (*warnings) << "The /org/mpris/ namespace is reserved, and should not be used for track ids";
        }
    }

    checkMetadataEntry(metadata, "mpris:length", QVariant::LongLong, errors, warnings, infoMessages);

    if (checkMetadataEntry(metadata, "mpris:artUrl", QVariant::Url, errors, warnings, infoMessages)) {
        QString artUrl = metadata.value("mpris:artUrl").toString();
        QUrl asUrl(artUrl, QUrl::StrictMode);
        if (asUrl.scheme() != "file" && asUrl.scheme() != "http" && asUrl.scheme() != "https") {
            (*infoMessages) << "mpris:artUrl has a scheme (" + asUrl.scheme() + ") which not all clients may recognise";
        } else {
            if (asUrl.scheme() == "file") {
                if (!QFile::exists(asUrl.toLocalFile())) {
                    (*infoMessages) << "mpris:artUrl references a file that does not exist";
                }
            }
            // TODO: check network files
        }
    }

    Q_FOREACH( QString key, metadata.keys() ) {
        if (!key.startsWith("xesam:")) {
            if (key != "mpris:trackid" &&
                key != "mpris:length" &&
                key != "mpris:artUrl")
            {
                (*warnings) << "Unrecognised entry " + key;
            }
        }
    }

    checkMetadataEntry(metadata, "xesam:album", QVariant::String, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:albumArtist", QVariant::StringList, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:artist", QVariant::StringList, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:asText", QVariant::String, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:audioBpm", QVariant::Int, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:autoRating", QVariant::Double, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:comment", QVariant::StringList, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:composer", QVariant::StringList, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:contentCreator", QVariant::DateTime, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:discNumber", QVariant::Int, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:firstUsed", QVariant::DateTime, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:genre", QVariant::StringList, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:lastUsed", QVariant::DateTime, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:lyricist", QVariant::StringList, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:title", QVariant::String, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:trackNumber", QVariant::Int, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:url", QVariant::Url, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:useCount", QVariant::Int, errors, warnings, infoMessages);
    checkMetadataEntry(metadata, "xesam:userRating", QVariant::Double, errors, warnings, infoMessages);
}

bool InterfaceTest::checkMetadataEntry(const QVariantMap& metadata,
                                       const QString& entry,
                                       QVariant::Type expType,
                                       QStringList* errors,
                                       QStringList* warnings,
                                       QStringList* infoMessages)
{
    if (metadata.contains(entry)) {
        QVariant value = metadata.value(entry);

        bool propertyTypeError = false;
        bool propertyTypeWarning = false;
        QVariant::Type realExpectedType = expType;
        if (expType == QVariant::DateTime || expType == QVariant::Url) {
            realExpectedType = QVariant::String;
        }

        // be lax about integers
        if (realExpectedType == QVariant::Int) {
            if (value.type() == QVariant::UInt ||
                value.type() == QVariant::LongLong ||
                value.type() == QVariant::ULongLong)
            {
                propertyTypeWarning = true;
            } else if (value.type() != QVariant::Int) {
                propertyTypeError = true;
            }
        } else if (realExpectedType == QVariant::UInt || realExpectedType == QVariant::LongLong) {
            if (value.type() == QVariant::ULongLong) {
                propertyTypeWarning = true;
            } else if (value.type() != realExpectedType) {
                propertyTypeError = true;
            }
        } else if (value.type() != realExpectedType) {
            propertyTypeError = true;
        }

        if (propertyTypeError || propertyTypeWarning) {
            const char * gotTypeCh = QDBusMetaType::typeToSignature(value.userType());
            QString gotType = gotTypeCh ? QString::fromAscii(gotTypeCh) : "<unknown>";
            const char * expTypeCh = QDBusMetaType::typeToSignature(realExpectedType);
            QString expType = expTypeCh ? QString::fromAscii(expTypeCh) : "<unknown>";
            if (propertyTypeError) {
                (*errors) << entry + " entry is of type '" + gotType + "' but should have been of type '" + expType + "'";
                return false;
            } else {
                (*warnings) << entry + " entry is of type '" + gotType + "' but should have been of type '" + expType + "'";
                return true;
            }
        }

        // extra checks for special types
        if (expType == QVariant::DateTime) {
            QDateTime dtValue = QDateTime::fromString(value.toString(), Qt::ISODate);
            if (!dtValue.isValid()) {
                (*errors) << entry + " entry does not contain a valid date/time string (value was " + value.toString() + ")";
                return false;
            }
        } else if (expType == QVariant::Url) {
            if (value.toString().isEmpty()) {
                return false;
            } else {
                QUrl asUrl(value.toString(), QUrl::StrictMode);
                if (!asUrl.isValid()) {
                    (*errors) << entry + " entry is not a valid URL";
                    return false;
                }
            }
        }
        return true;
    }
    return false;
}

// vim:et:sw=4:sts=4