void DeviceKitLister::DBusDeviceAdded(const QDBusObjectPath& path) {
  DeviceData data = ReadDeviceData(path);
  if (!data.suitable) return;

  {
    QMutexLocker l(&mutex_);
    device_data_[data.unique_id()] = data;
  }

  emit DeviceAdded(data.unique_id());
}
void DeviceKitLister::DBusDeviceChanged(const QDBusObjectPath &path) {
  bool already_known = false;
  {
    QMutexLocker l(&mutex_);
    already_known = !FindUniqueIdByPath(path).isNull();
  }

  DeviceData data = ReadDeviceData(path);

  if (already_known && !data.suitable)
    DBusDeviceRemoved(path);
  else if (!already_known && data.suitable)
    DBusDeviceAdded(path);
  else if (already_known && data.suitable) {
    {
      QMutexLocker l(&mutex_);
      device_data_[data.unique_id()] = data;
    }
    emit DeviceChanged(data.unique_id());
  }
}
void DeviceKitLister::Init() {
  interface_.reset(new OrgFreedesktopUDisksInterface(
      OrgFreedesktopUDisksInterface::staticInterfaceName(),
      "/org/freedesktop/UDisks", QDBusConnection::systemBus()));

  // Get all the devices currently attached
  QDBusPendingReply<QList<QDBusObjectPath> > reply =
      interface_->EnumerateDevices();
  reply.waitForFinished();

  if (!reply.isValid()) {
    qLog(Warning) << "Error enumerating DeviceKit-disks devices:"
                  << reply.error().name() << reply.error().message();
    interface_.reset();
    return;
  }

  // Listen for changes
  connect(interface_.get(), SIGNAL(DeviceAdded(QDBusObjectPath)),
          SLOT(DBusDeviceAdded(QDBusObjectPath)));
  connect(interface_.get(), SIGNAL(DeviceRemoved(QDBusObjectPath)),
          SLOT(DBusDeviceRemoved(QDBusObjectPath)));
  connect(interface_.get(), SIGNAL(DeviceChanged(QDBusObjectPath)),
          SLOT(DBusDeviceChanged(QDBusObjectPath)));

  // Get information about each one
  QMap<QString, DeviceData> device_data;
  for (const QDBusObjectPath& path : reply.value()) {
    DeviceData data = ReadDeviceData(path);
    if (data.suitable) device_data[data.unique_id()] = data;
  }

  // Update the internal cache
  {
    QMutexLocker l(&mutex_);
    device_data_ = device_data;
  }

  // Notify about the changes
  for (const QString& id : device_data.keys()) {
    emit DeviceAdded(id);
  }
}