Ejemplo n.º 1
0
void MainWindow::query()
{
  if (tag->text().isEmpty() && text->toPlainText().isEmpty())
    return;

  static Soprano::Model *model = Nepomuk2::ResourceManager::instance()->mainModel();

  Nepomuk2::Query::ComparisonTerm tag_term;
  Nepomuk2::Query::LiteralTerm text_term;
  if (!tag->text().isEmpty())
    tag_term = Nepomuk2::Query::ComparisonTerm(Soprano::Vocabulary::NAO::hasTag(), Nepomuk2::Query::LiteralTerm(tag->text()));
  if (!text->toPlainText().isEmpty())
    text_term = Nepomuk2::Query::LiteralTerm(text->toPlainText());

  Nepomuk2::Query::Query query(Nepomuk2::Query::AndTerm(tag_term, text_term));
  url->setText(query.toSearchUrl().url());

  Soprano::QueryResultIterator it = model->executeQuery(query.toSparqlQuery(), Soprano::Query::QueryLanguageSparql);
  QString text_result;
  while(it.next())
  {
    for (int i=0; i< it.bindingCount(); ++i)
    {
      text_result += it.binding(i).toString();
      text_result += "<br>";
    }
  }

  result->setText(text_result);
}
Ejemplo n.º 2
0
void moviemanager::queryTag(QString userTag)
{
    //This module is not working
    //get help from pnh for debugging
    //pnh code
    Nepomuk::Tag myTag;
    myTag.setLabel(userTag);
    QString query
       = QString("select distinct ?r where { ?r %1 %2 . ?r a %3 }")
         .arg( Soprano::Node::resourceToN3(Soprano::Vocabulary::NAO::hasTag()) )
         .arg( Soprano::Node::resourceToN3(myTag.resourceUri()) )
         .arg( Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::Video()) );

    QList<Nepomuk::Resource> myResourceList;
    Soprano::Model *model = Nepomuk::ResourceManager::instance()->mainModel();

    Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );
    while( it.next() ) {
        qDebug() << "looping";
       myResourceList << Nepomuk::Resource( it.binding( "r" ).uri() );
    }

    Q_FOREACH (const Nepomuk::Resource& r, myResourceList)
    {
        mainMovieList->addItem(r.property(Nepomuk::Vocabulary::NFO::fileName()).toString());
        //if(r.tags().contains(new Nepomuk:Tag("video"))) newList.append(r)
    }
Ejemplo n.º 3
0
void RemoveDuplicates::loadDuplicates()
{
    Soprano::Model* model = Nepomuk::ResourceManager::instance()->mainModel();
    QString query
       = QString( "select distinct ?u1 where { "
                 "?r1 a %1 . ?r2 a %1. ?r1 %2 ?h. ?r2 %2 ?h. "
                 "?r1 %3 ?u1. ?r2 %3 ?u2. filter(?r1!=?r2) . }order by ?h limit 50")
         .arg( Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::FileDataObject()))
         .arg( Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NFO::hasHash()))
         .arg( Soprano::Node::resourceToN3(Nepomuk::Vocabulary::NIE::url()));

    Soprano::QueryResultIterator it
       = model->executeQuery( query,
                              Soprano::Query::QueryLanguageSparql );
    Nepomuk::File tempRsc;
    while( it.next() ) {
        tempRsc = it.binding("u1").uri() ;
        QString usagecount = QString::number(tempRsc.usageCount());
        QListWidgetItem* item = new QListWidgetItem(tempRsc.genericLabel() + ":: Usage Count:" + usagecount,m_resourceList);
        item->setCheckState(Qt::Unchecked);
        item->setToolTip(tempRsc.url().path());
        qDebug()<<tempRsc.url().path();
    }

}
Ejemplo n.º 4
0
//
// We don't really care if the indexing level is in the incorrect graph
//
void Nepomuk2::updateIndexingLevel(const QUrl& uri, int level)
{
    QString uriN3 = Soprano::Node::resourceToN3( uri );

    QString query = QString::fromLatin1("select ?g ?l where { graph ?g { %1 kext:indexingLevel ?l . } }")
                    .arg ( uriN3 );
    Soprano::Model* model = ResourceManager::instance()->mainModel();
    Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparqlNoInference );

    QUrl graph;
    Soprano::Node prevLevel;
    if( it.next() ) {
        graph = it[0].uri();
        prevLevel = it[1];
        it.close();
    }

    if( !graph.isEmpty() ) {
        QString graphN3 = Soprano::Node::resourceToN3( graph );
        QString removeCommand = QString::fromLatin1("sparql delete { graph %1 { %2 kext:indexingLevel %3 . } }")
                                .arg( graphN3, uriN3, prevLevel.toN3() );
        model->executeQuery( removeCommand, Soprano::Query::QueryLanguageUser, QLatin1String("sql") );

        QString insertCommand = QString::fromLatin1("sparql insert { graph %1 { %2 kext:indexingLevel %3 . } }")
                                .arg( graphN3, uriN3, Soprano::Node::literalToN3(level) );
        model->executeQuery( insertCommand, Soprano::Query::QueryLanguageUser, QLatin1String("sql") );
    }
    // Practically, this should never happen, but still
    else {
        QScopedPointer<KJob> job( Nepomuk2::setProperty( QList<QUrl>() << uri, KExt::indexingLevel(),
                                                                QVariantList() << QVariant(level) ) );
        job->setAutoDelete(false);
        job->exec();
    }
}
Ejemplo n.º 5
0
void Nepomuk::ResourceCompletion::makeCompletion( const QString& string )
{
    kDebug() << string;

    if ( string.length() > 3 ) {
        Query::AndTerm term;
        term.addSubTerm( Query::LiteralTerm( string + '*' ) );
        if ( d->type.isValid() && d->type != Soprano::Vocabulary::RDFS::Resource() )
            term.addSubTerm( Query::ResourceTypeTerm( d->type ) );
        Query::Query query(term);
        query.setLimit( 10 );

        kDebug() << query.toSparqlQuery();

        Soprano::QueryResultIterator it
            = ResourceManager::instance()->mainModel()->executeQuery( query.toSparqlQuery(),
                                                                      Soprano::Query::QueryLanguageSparql );
        while ( it.next() ) {
            Resource res( it.binding( 0 ).uri() );
            double score = 1.0; //it[1].literal().toDouble();
            kDebug() << "Match for input" << string << res.uri();
            addCompletion( KCompletionItem( res.genericLabel(),
                                            QString( "%1 (%2)" ).arg( res.genericLabel() ).arg( Types::Class( res.type() ).label() ),
                                            res.genericDescription(),
                                            KIcon( res.genericIcon() ),
                                            score,
                                            res.resourceUri() ) );

        }
    }
}
Ejemplo n.º 6
0
    /**
     * Get all prefixes stored in the model
     */
    void buildPrefixMap()
    {
        QMutexLocker lock( &m_prefixMapMutex );

        m_prefixes.clear();

        // fixed prefixes
        m_prefixes.insert( "rdf", Soprano::Vocabulary::RDF::rdfNamespace() );
        m_prefixes.insert( "rdfs", Soprano::Vocabulary::RDFS::rdfsNamespace() );
        m_prefixes.insert( "xsd", Soprano::Vocabulary::XMLSchema::xsdNamespace() );
        m_prefixes.insert( "nrl", Soprano::Vocabulary::NRL::nrlNamespace() );
        m_prefixes.insert( "nao", Soprano::Vocabulary::NAO::naoNamespace() );

        // get prefixes from nepomuk
        Soprano::QueryResultIterator it =
            q->executeQuery( QString( "select ?ns ?ab where { "
                                      "?g %1 ?ns . "
                                      "?g %2 ?ab . }" )
                             .arg( Soprano::Node::resourceToN3( Soprano::Vocabulary::NAO::hasDefaultNamespace() ) )
                             .arg( Soprano::Node::resourceToN3( Soprano::Vocabulary::NAO::hasDefaultNamespaceAbbreviation() ) ),
                             Soprano::Query::QueryLanguageSparql );
        while ( it.next() ) {
            QString ab = it["ab"].toString();
            QUrl ns = it["ns"].toString();
            if ( !m_prefixes.contains( ab ) ) {
                m_prefixes.insert( ab, ns );
            }
        }
    }
void KoEventSemanticItemFactory::updateSemanticItems(QList<hKoRdfBasicSemanticItem> &semanticItems, const KoDocumentRdf *rdf, QSharedPointer<Soprano::Model> m)
{
    const QString sparqlQuery = QLatin1String(
        " prefix rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#> \n"
        " prefix cal:  <http://www.w3.org/2002/12/cal/icaltzd#>  \n"
        " select distinct ?graph ?ev ?uid ?dtstart ?dtend ?summary ?location ?geo ?long ?lat \n"
        " where {  \n"
        "  GRAPH ?graph { \n"
        "    ?ev rdf:type cal:Vevent . \n"
        "    ?ev cal:uid      ?uid . \n"
        "    ?ev cal:dtstart  ?dtstart . \n"
        "    ?ev cal:dtend    ?dtend \n"
        "    OPTIONAL { ?ev cal:summary  ?summary  } \n"
        "    OPTIONAL { ?ev cal:location ?location } \n"
        "    OPTIONAL {  \n"
        "               ?ev cal:geo ?geo . \n"
        "               ?geo rdf:first ?lat . \n"
       "               ?geo rdf:rest ?joiner . \n"
       "               ?joiner rdf:first ?long \n"
       "              } \n"
       "    } \n"
       "  } \n");

    Soprano::QueryResultIterator it =
        m->executeQuery(sparqlQuery,
                        Soprano::Query::QueryLanguageSparql);

    QList<hKoRdfBasicSemanticItem> oldSemanticItems = semanticItems;
    // uniqfilter is needed because soprano is not honouring
    // the DISTINCT sparql keyword
    QSet<QString> uniqfilter;
    while (it.next()) {
        const QString name = it.binding("uid").toString();
        if (uniqfilter.contains(name)) {
            continue;
        }
        uniqfilter += name;

        hKoRdfBasicSemanticItem newSemanticItem(new KoRdfCalendarEvent(0, rdf, it));

        const QString newSemanticItemLinkingSubject = newSemanticItem->linkingSubject().toString();
        foreach (hKoRdfBasicSemanticItem semItem, oldSemanticItems) {
            if (newSemanticItemLinkingSubject == semItem->linkingSubject().toString()) {
                oldSemanticItems.removeAll(semItem);
                newSemanticItem = 0;
                break;
            }
        }

        if (newSemanticItem) {
            semanticItems << newSemanticItem;
        }
    }

    foreach (hKoRdfBasicSemanticItem semItem, oldSemanticItems) {
        semanticItems.removeAll(semItem);
    }
Ejemplo n.º 8
0
 void startQuery( const Nepomuk::Query::Query& query ) {
     // we cannot use the query service since that would ignore our custom model
     // thus, we perform a sync query and call _k_newEntries async from there
     Nepomuk::Query::Query ourQuery(query);
     // disable result restrictions since we do not support those in our custom model
     ourQuery.setQueryFlags(Nepomuk::Query::Query::NoResultRestrictions);
     Soprano::QueryResultIterator it = ResourceManager::instance()->mainModel()->executeQuery( ourQuery.toSparqlQuery(), Soprano::Query::QueryLanguageSparql );
     QList<Nepomuk::Query::Result> results;
     while( it.next() ) {
         results << Result( it[0].uri() );
     }
     QMetaObject::invokeMethod( q, "_k_newEntries", Qt::QueuedConnection, Q_ARG(QList<Nepomuk::Query::Result>, results) );
 }
Ejemplo n.º 9
0
void GraphMigrationJob::mergeAgents()
{
    QString appQ = QString::fromLatin1("select distinct ?i where { ?r a %1 ; %2 ?i . }")
                   .arg( Soprano::Node::resourceToN3(NAO::Agent()),
                         Soprano::Node::resourceToN3(NAO::identifier()) );

    Soprano::QueryResultIterator it = m_model->executeQuery( appQ, Soprano::Query::QueryLanguageSparqlNoInference );
    while( it.next() ) {
        QString identifier = it[0].literal().toString();
        kDebug() << identifier;

        QString aQuery = QString::fromLatin1("select distinct ?r where { ?r a nao:Agent ; nao:identifier %1. }")
                         .arg( Soprano::Node::literalToN3(identifier) );

        Soprano::QueryResultIterator iter = m_model->executeQuery( aQuery, Soprano::Query::QueryLanguageSparqlNoInference );
        QList<QUrl> apps;
        while( iter.next() )
            apps << iter[0].uri();

        mergeAgents( apps );
    }
}
// static
void Nepomuk2::SubtitleLoader::eraseAllSubtitles()
{
    QString query = QString::fromLatin1("select distinct ?r where { ?r a %1 . }")
                    .arg( Soprano::Node::resourceToN3( NSBO::Subtitle() ) );
    kDebug() << query;

    Soprano::Model * model = Nepomuk2::ResourceManager::instance()->mainModel();
    Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );
    while( it.next() ) {
        Nepomuk2::Resource res( it["r"].uri() );
        kDebug() << "Removing " << res.uri();
        res.remove();
    }
}
Ejemplo n.º 11
0
bool Nepomuk::Types::EntityPrivate::load()
{
    const QString query = QString::fromLatin1( "select ?p ?o where { "
                          "graph ?g { <%1> ?p ?o . } . "
                          "{ ?g a %2 . } UNION { ?g a %3 . } . }" )
                          .arg( QString::fromAscii( uri.toEncoded() ),
                                Soprano::Node::resourceToN3( Soprano::Vocabulary::NRL::Ontology() ),
                                Soprano::Node::resourceToN3( Soprano::Vocabulary::NRL::KnowledgeBase() ) );

    Soprano::QueryResultIterator it
        = ResourceManager::instance()->mainModel()->executeQuery( query, Soprano::Query::QueryLanguageSparql );
    while ( it.next() ) {
        QUrl property = it.binding( "p" ).uri();
        Soprano::Node value = it.binding( "o" );

        if ( property == Soprano::Vocabulary::RDFS::label() ) {
            if ( value.language().isEmpty() ) {
                label = value.toString();
            }
            else if( value.language() == KGlobal::locale()->language() ) {
                l10nLabel = value.toString();
            }
        }

        else if ( property == Soprano::Vocabulary::RDFS::comment() ) {
            if ( value.language().isEmpty() ) {
                comment = value.toString();
            }
            else if( value.language() == KGlobal::locale()->language() ) {
                l10nComment = value.toString();
            }
        }

        else if ( property == Soprano::Vocabulary::NAO::hasSymbol() ) {
            icon = KIcon( value.toString() );
        }

        else if ( property == Soprano::Vocabulary::NAO::userVisible() ) {
            userVisible = value.literal().toBool();
        }

        else {
            addProperty( property, value );
        }
    }

    return !it.lastError();
}
Ejemplo n.º 12
0
QList<Soprano::Statement> Nepomuk::NepomukOntologyLoader::loadOntology( const QUrl& uri )
{
    QList<Soprano::Statement> sl;

    // get the complete named graph describing the ontology
    Soprano::QueryResultIterator it
        = ResourceManager::instance()->mainModel()->executeQuery( QString::fromLatin1( "construct {?s ?p ?o} "
                                                                                       "where { GRAPH %1 { ?s ?p ?o } . }" )
                                                                  .arg( Soprano::Node::resourceToN3(uri) ),
                                                                  Soprano::Query::QueryLanguageSparql );
    while ( it.next() ) {
        sl.append( it.currentStatement() );
    }

    return sl;
}
void Nepomuk::DbpediaAnnotationPlugin::slotQueryFinished( Soprano::Util::AsyncResult* result )
{
    m_currentResult = 0;

    kDebug() << result->lastError();

    Soprano::QueryResultIterator it = result->queryResultIterator();
    while ( it.next() ) {
        kDebug() << it.current();
    }

    // TODO: create annotations either as new pimo things that are related to the resource or as
    //       being the resource (ie. an occurrence of resource().pimoThing())

    emitFinished();
}
Ejemplo n.º 14
0
void Nepomuk2::TvshowProtocol::stat( const KUrl& url )
{
    // for basic functionality we only need to stat the folders
    const QStringList pathTokens = url.path().split('/', QString::SkipEmptyParts);
    if(pathTokens.count() == 1 && pathTokens.first() == QLatin1String("latest")) {
        KIO::UDSEntry uds = createFolderUDSEntry(QLatin1String("latest"), i18n("Next Episodes To Watch"));
        uds.insert(KIO::UDSEntry::UDS_ICON_NAME, QLatin1String("favorites"));
        statEntry(uds);
        finished();
    }

    else if(pathTokens.count() == 1) {
        // stat series folder
        Soprano::QueryResultIterator it
                = Nepomuk2::ResourceManager::instance()->mainModel()->executeQuery(QString::fromLatin1("select distinct * where { "
                                                                                                      "?r a nmm:TVSeries ; "
                                                                                                      "nie:title %1 ; "
                                                                                                      "nao:created ?cd ; "
                                                                                                      "nao:lastModified ?md ; "
                                                                                                      "nie:description ?d . } LIMIT 1")
                                                                                  .arg(Soprano::Node::literalToN3(pathTokens[0])),
                                                                                  Soprano::Query::QueryLanguageSparql);
        if(it.next()) {
            statEntry(createSeriesUDSEntry(it["r"].uri(),
                                           pathTokens[0],
                                           pathTokens[0],
                                           it["d"].toString(),
                                           it["cd"].literal().toDateTime(),
                                           it["md"].literal().toDateTime()));
            finished();
        }
        else {
            error( ERR_DOES_NOT_EXIST, url.prettyUrl() );
        }
    }

    else if(pathTokens.count() == 2) {
        // stat season folder
        statEntry(createFolderUDSEntry(pathTokens[0], pathTokens[1]));
        finished();
    }

    else {
        // FIXME
        error( ERR_UNSUPPORTED_ACTION, url.prettyUrl() );
    }
}
Ejemplo n.º 15
0
bool Nepomuk::Types::EntityPrivate::loadAncestors()
{
    const QString query = QString::fromLatin1( "select ?s ?p where { "
                          "graph ?g { ?s ?p <%1> . } . "
                          "{ ?g a %2 . } UNION { ?g a %3 . } . }" )
                          .arg( QString::fromAscii( uri.toEncoded() ),
                                Soprano::Node::resourceToN3( Soprano::Vocabulary::NRL::Ontology() ),
                                Soprano::Node::resourceToN3( Soprano::Vocabulary::NRL::KnowledgeBase() ) );

    Soprano::QueryResultIterator it
        = ResourceManager::instance()->mainModel()->executeQuery( query, Soprano::Query::QueryLanguageSparql );
    while ( it.next() ) {
        addAncestorProperty( it.binding( "s" ).uri(), it.binding( "p" ).uri() );
    }

    return !it.lastError();
}
Ejemplo n.º 16
0
QList< Result > MainWindow::generateMultipleSubtitleResults()
{
    QString fromWords = m_fromLineEdit->text();
    QString toWords = m_toLineEdit->text();

    QString query = QString::fromLatin1("select distinct ?url ?st1 ?st2 ?en1 ?en2 where  {"
                                        "?r nie:url ?url . ?sub1 nsbo:subtitleFor ?r . ?sub2 nsbo:subtitleFor ?r ."
                                        "?sub1 nie:plainTextContent ?text1 . ?sub2 nie:plainTextContent ?text2 . "
                                        "?sub1 nsbo:startTime ?st1 . ?sub1 nsbo:endTime ?en1 . "
                                        "?sub2 nsbo:startTime ?st2 . ?sub2 nsbo:endTime ?en2. "
                                        "%1 %2 } ")
                    .arg( createFilter( fromWords, "text1" ),
                          createFilter( toWords, "text2" ) );

    kDebug() << query;

    // Need to implement the second time restriction
    Soprano::Model * model = Nepomuk2::ResourceManager::instance()->mainModel();
    Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );
    QList<Result> results;
    while( it.next() ) {
        Result r;
        r.m_filePath = it["url"].uri().toLocalFile();

        QTime st1 = it["st1"].literal().toTime();
        QTime st2 = it["st2"].literal().toTime();
        QTime en1 = it["en1"].literal().toTime();
        QTime en2 = it["en2"].literal().toTime();

        int duration = en1.msecsTo(st2) / 1000;
        int minTime = m_minSpinBox->value();
        int maxTime = m_maxSpinBox->value();
        //kDebug() << "Duration : " << duration;
        if( minTime <= duration && duration <= maxTime ) {
            r.startTime = st1;
            r.endTime = en2;
            r.text = it["text1"].literal().toString() + it["text2"].literal().toString();

            kDebug() << "Pushing with duration " << duration;
            results << r;
        }
    }

    return results;
}
Ejemplo n.º 17
0
//TODO: next functions look like the ones from CAuSectionRdf. Maybe there is anyway to share code?
void CAuActorSemanticItemFactory::updateSemanticItems(
    QList<hKoRdfBasicSemanticItem> &semanticItems,
    const KoDocumentRdf *rdf,
    QSharedPointer<Soprano::Model> m)
{
    const QString sparqlQuery = CAuActorRdf::QUERY;

    Soprano::QueryResultIterator it = m->executeQuery(
        sparqlQuery,
        Soprano::Query::QueryLanguageSparql
    );

    QList<hKoRdfBasicSemanticItem> oldSemanticItems = semanticItems;

    // uniqfilter is needed because soprano is not honouring
    // the DISTINCT sparql keyword
    QSet<QString> uniqfilter;
    while (it.next()) {

        QString magicid = it.binding("magicid").toString();
        if (uniqfilter.contains(magicid)) {
            continue;
        }
        uniqfilter += magicid;

        hKoRdfBasicSemanticItem newSemanticItem(new CAuActorRdf(0, rdf, it));

        const QString newItemLs = newSemanticItem->linkingSubject().toString();
        foreach (hKoRdfBasicSemanticItem semItem, oldSemanticItems) {
            if (newItemLs == semItem->linkingSubject().toString()) {
                oldSemanticItems.removeAll(semItem);
                newSemanticItem = 0;
                break;
            }
        }

        if (newSemanticItem) {
            semanticItems << newSemanticItem;
        }
    }

    foreach (hKoRdfBasicSemanticItem semItem, oldSemanticItems) {
        semanticItems.removeAll(semItem);
    }
Ejemplo n.º 18
0
void TVNamerService::slotTVShowResourceCreated(const Nepomuk2::Resource &res)
{
    kDebug() << res.uri();
    // inform KIO about the change
    Soprano::QueryResultIterator it = mainModel()->executeQuery(QString::fromLatin1("select ?s ?t where { "
                                                                                    "%1 nmm:series [ nie:title ?t ] ; "
                                                                                    "nmm:isPartOfSeason [ nmm:seasonNumber ?s ] "
                                                                                    "} LIMIT 1")
                                                                .arg(Soprano::Node::resourceToN3(res.uri())),
                                                                Soprano::Query::QueryLanguageSparql);
    if(it.next()) {
        kDebug() << QString::fromLatin1("tvshow:/%1/%1 - Season %2")
                    .arg(it["t"].toString())
                    .arg(it["s"].literal().toInt(), 2, 10, QLatin1Char('0'));
        org::kde::KDirNotify::emitFilesAdded(QString::fromLatin1("tvshow:/%1/%1 - Season %2")
                                             .arg(it["t"].toString())
                                             .arg(it["s"].literal().toInt()));
    }
}
void Nepomuk2::SubtitleLoader::erase()
{
    //TODO: Avoid using Nepomuk2::Resource. Just query the nie:url
    Nepomuk2::Resource videoRes( m_videoUrl );
    kDebug() << videoRes.isFile();
    kDebug() << videoRes.uri();

    QString query = QString::fromLatin1("select distinct ?r where { ?r %1 %2 . }")
                    .arg( Soprano::Node::resourceToN3( NSBO::subtitleFor() ),
                          Soprano::Node::resourceToN3( videoRes.uri() ) );
    kDebug() << query;
    Soprano::Model * model = Nepomuk2::ResourceManager::instance()->mainModel();
    Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );
    while( it.next() ) {
        //TODO: Use datamangement APIs
        Nepomuk2::Resource res( it["r"].uri() );
        kDebug() << "Removing " << res.uri();
        res.remove();
    }
}
Ejemplo n.º 20
0
void Nepomuk::TypeCompletion::makeCompletion( const QString& string )
{
    // FIXME: if the string contains a : treat everything before it as a qname and match it to a namespace (for example by comparing the last section)

    kDebug() << string;

    if ( string.length() > 2 ) {
        Query::Query query(
            Query::AndTerm(
                Query::ResourceTypeTerm( Soprano::Vocabulary::RDFS::Class() ),
                Query::ComparisonTerm( Types::Property(), Query::LiteralTerm( string + '*' ) )
                )
            );

        Soprano::QueryResultIterator it
            = ResourceManager::instance()->mainModel()->executeQuery( query.toSparqlQuery(),
                                                                      Soprano::Query::QueryLanguageSparql );
        int cnt = 0;
        while ( it.next() ) {
            Types::Class type( it[0].uri() );
            double score = 1.0;// it[1].literal().toDouble();
            kDebug() << "possible match:" << type.label() << type.uri() << score;
            if ( ( !d->baseType.isValid() ||
                   type.isSubClassOf( d->baseType ) ) &&
                 score > 0.5 ) {
                kDebug() << "match:" << type.label() << type.uri();
                addCompletion( KCompletionItem( type.label(),
                                                type.label(),
                                                type.comment() + '\n' + '(' + type.uri().toString() + ')',
                                                type.icon(),
                                                score,
                                                type.uri() ) );

                if ( ++cnt >= 10 ) {
                    kDebug() << "Stopping at" << cnt << "results";
                    return;
                }
            }
        }
    }
}
Ejemplo n.º 21
0
void TVNamerService::slotTVShowUsageCountChanged(const Nepomuk2::Resource &res)
{
    // fetch the changed show's details and tell KIO to remove it in any case
    Soprano::QueryResultIterator it
            = mainModel()->executeQuery(QString::fromLatin1("select ?s ?e ?st ?t where { "
                                                            "%1 nmm:episodeNumber ?e ; "
                                                            "nmm:season ?s ; "
                                                            "nmm:series [ a nmm:TVSeries ; nie:title ?st ] ; "
                                                            "nie:title ?t . } LIMIT 1")
                                        .arg(Soprano::Node::resourceToN3(res.uri())),
                                        Soprano::Query::QueryLanguageSparql);
    if(it.next()) {
        const QString title = i18n("Next episode of %1: %2x%3 - %4",
                                   it["st"].toString(),
                                   QString::number(it["s"].literal().toInt()).rightJustified(2, QLatin1Char('0')),
                                   QString::number(it["e"].literal().toInt()).rightJustified(2, QLatin1Char('0')),
                                   it["t"].toString());
        org::kde::KDirNotify::emitFilesRemoved(QStringList() << (QLatin1String("tvshow:/latest/") + title));
    }

    // now simply tell KIO to check for added files
    org::kde::KDirNotify::emitFilesAdded(QLatin1String("tvshow:/latest"));
}
Ejemplo n.º 22
0
QList< Result > MainWindow::generateSingleSubtitleResults(const QString& expression)
{
    if( expression.isEmpty() )
        return QList<Result>();

    QString filterExpression = createFilter( expression, "text" );

    QString query = QString::fromLatin1("select distinct ?url ?st ?end ?text where {"
                                        "?r %1 ?url . ?sub %2 ?r ."
                                        "?sub %3 ?st . ?sub %4 ?end . "
                                        "?sub %5 ?text . "
                                        "%6 } order by ?url ?st ")
                    .arg( Soprano::Node::resourceToN3( NIE::url() ),
                          Soprano::Node::resourceToN3( NSBO::subtitleFor() ),
                          Soprano::Node::resourceToN3( NSBO::startTime() ),
                          Soprano::Node::resourceToN3( NSBO::endTime() ),
                          Soprano::Node::resourceToN3( NIE::plainTextContent() ),
                          filterExpression );

    kDebug() << query;

    Soprano::Model * model = Nepomuk2::ResourceManager::instance()->mainModel();
    Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );
    QList<Result> results;
    while( it.next() ) {
        Result r;
        r.m_filePath = it["url"].uri();
        r.startTime = it["st"].literal().toTime();
        r.endTime = it["end"].literal().toTime();
        r.text = it["text"].literal().toString();
        kDebug() << r.text;
        results << r;
    }

    return results;
}
Ejemplo n.º 23
0
bool Nepomuk2::Indexer::indexFile(const KUrl& url)
{
    QFileInfo info( url.toLocalFile() );
    if( !info.exists() ) {
        m_lastError = QString::fromLatin1("'%1' does not exist.").arg(info.filePath());
        return false;
    }

    QString query = QString::fromLatin1("select ?r ?mtype ?l where { ?r nie:url %1; nie:mimeType ?mtype ;"
                                        " kext:indexingLevel ?l . }")
                    .arg( Soprano::Node::resourceToN3( url ) );
    Soprano::Model* model = ResourceManager::instance()->mainModel();

    Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparqlNoInference );

    QUrl uri;
    QString mimeType;
    if( it.next() ) {
        uri = it[0].uri();
        mimeType = it[1].literal().toString();
        int level = it[2].literal().toInt();

        if( level > 1 ) {
            clearIndexingData( url );
            if( !simpleIndex( url, &uri, &mimeType ) )
                return false;
        }
    }
    else {
        if( !simpleIndex( url, &uri, &mimeType ) )
            return false;
    }

    kDebug() << uri << mimeType;
    return fileIndex( uri, url, mimeType );
}
void SemanticsListEngine::run()
{
    QThread::setTerminationEnabled(true);
    m_stop = false;

    if (m_updateSourceInfo || m_removeSourceInfo) {
        NepomukListEngine::run();
        return;
    }
    
    //Create media list based on engine argument and filter
    QList<MediaItem> mediaList;
    MediaVocabulary mediaVocabulary = MediaVocabulary();
    
    QString engineArg = m_mediaListProperties.engineArg();
    QString engineFilter = m_mediaListProperties.engineFilter();
    QStringList engineFilterList = m_mediaListProperties.engineFilterList();
    
    //Parse filter
    QString mediaType;
    QString groupByCategoryType;
    QString groupByField;
    QString limitFilter;
    int originalGenreLimit = 0;
    if (engineFilterList.count() != 0) {
        mediaType = engineFilterList.at(0);
        if (engineFilterList.filter("groupBy=").count() != 0) {
            QString groupByFilter = engineFilterList.filter("groupBy=").at(0);
            groupByField = groupByFilter.remove("groupBy=").trimmed();
            if (groupByField == "artist") {
                groupByCategoryType = "Artist";
            } else if (groupByField == "album") {
                groupByCategoryType = "Album";
            } else if (groupByField == "genre") {
                if (mediaType == "audio") {
                    groupByCategoryType = "AudioGenre";
                } else if (mediaType == "video") {
                    groupByCategoryType = "VideoGenre";
                }
            } else if (groupByField == "seriesName") {
                groupByCategoryType = "TV Series";
            } else if (groupByField == "actor") {
                groupByCategoryType = "Actor";
            } else if (groupByField == "director") {
                groupByCategoryType = "Director";
            } else if (groupByField == "tag") {
                if (mediaType == "audio") {
                    groupByCategoryType = "AudioTag";
                } else if (mediaType == "video") {
                    groupByCategoryType = "VideoTag";
                }
            }
        }
        if (engineFilterList.filter("limit=").count() !=0) {
            limitFilter = engineFilterList.filter("limit=").at(0);
            if (groupByField == "genre") {
                originalGenreLimit = m_mediaListProperties.filterValue(limitFilter).trimmed().toInt();
                int originalFilterIndex = engineFilterList.indexOf(limitFilter);
                limitFilter = QString("%1%2%3").arg(m_mediaListProperties.filterField(limitFilter))
                                               .arg(m_mediaListProperties.filterOperator(limitFilter))
                                               .arg(m_mediaListProperties.filterValue(limitFilter).trimmed().toInt()*3);
                engineFilterList.replace(originalFilterIndex, limitFilter);
            }
        }
    }
    
    if (m_nepomukInited) {
        if (engineArg.toLower() == "frequent") {
            mediaList.clear();
            if (mediaType == "audio" || mediaType == "video") {
                MediaQuery query;
                bool ignoreZeros = false;
                if (groupByCategoryType.isEmpty()) {
                    QStringList bindings;
                    bindings.append(mediaVocabulary.mediaResourceBinding());
                    bindings.append(mediaVocabulary.mediaResourceUrlBinding());
                    bindings.append(mediaVocabulary.playCountBinding());
                    query.select(bindings, MediaQuery::Distinct);
                    query.startWhere();
                    if (mediaType == "audio") {
                        query.addCondition(mediaVocabulary.hasTypeAnyAudio(MediaQuery::Required));
                    } else if (mediaType == "video") {
                        query.addCondition(mediaVocabulary.hasTypeAnyVideo(MediaQuery::Required));
                    }
                    query.addLRIFilterConditions(engineFilterList, mediaVocabulary);
                    if (m_mediaListProperties.filterForField("playCount").isEmpty()) {
                        query.addCondition(mediaVocabulary.hasPlayCount(MediaQuery::Required, 0, MediaQuery::GreaterThan));
                        ignoreZeros = true;
                    }
                    query.addCondition(mediaVocabulary.hasLastPlayed(MediaQuery::Optional));
                    query.endWhere();
                    QStringList orderByBindings;
                    QList<MediaQuery::Order> order;
                    orderByBindings.append(mediaVocabulary.playCountBinding());
                    order.append(MediaQuery::Descending);
                    orderByBindings.append(mediaVocabulary.lastPlayedBinding());
                    order.append(MediaQuery::Descending);
                    query.orderBy(orderByBindings, order);
                } else {
                    QStringList bindings;
                    //NOTE:query.addLRIFilterConditions will automatically add 
                    //the groupBy field name to the binding list.
                    QString groupByResourceBinding = MediaVocabulary::resourceBindingForCategory(groupByCategoryType);
                    if (!groupByResourceBinding.isEmpty()) {
                        bindings.append(groupByResourceBinding);
                    }
                    bindings.append(query.fieldBindingDictionary[groupByField]);
                    bindings.append(MediaQuery::aggregateBinding(mediaVocabulary.playCountBinding(), MediaQuery::Sum));
                    query.select(bindings, MediaQuery::Distinct);
                    query.startWhere();
                    MediaQuery subQuery;
                    QStringList subBindings;
                    subBindings.append(mediaVocabulary.playCountBinding());
                    subBindings.append(mediaVocabulary.mediaResourceBinding());
                    subQuery.select(subBindings, MediaQuery::Distinct);
                    subQuery.startWhere();
                    if (mediaType == "audio") {
                        subQuery.addCondition(mediaVocabulary.hasTypeAnyAudio(MediaQuery::Required));
                    } else if (mediaType == "video") {
                        subQuery.addCondition(mediaVocabulary.hasTypeAnyVideo(MediaQuery::Required));
                    }
                    if (m_mediaListProperties.filterForField("playCount").isEmpty()) {
                        subQuery.addCondition(mediaVocabulary.hasPlayCount(MediaQuery::Required, 0, MediaQuery::GreaterThan));
                        ignoreZeros = true;
                    }
                    QStringList subQueryLRIFilterList = engineFilterList;
                    subQueryLRIFilterList.removeAll(limitFilter);
                    subQuery.addLRIFilterConditions(subQueryLRIFilterList, mediaVocabulary);
                    subQuery.endWhere();
                    query.addSubQuery(subQuery);
                    query.endWhere();
                    query.addLRIFilterCondition(limitFilter,  mediaVocabulary);
                    QStringList orderByBindings;
                    QList<MediaQuery::Order> order;
                    orderByBindings.append(QString("%1_sum").arg(mediaVocabulary.playCountBinding()));
                    order.append(MediaQuery::Descending);
                    query.orderBy(orderByBindings, order);
                }

                Soprano::QueryResultIterator it = query.executeSelect(m_mainModel);
                
                //Build media list from results
                while( it.next() ) {
                    if (m_stop) {
                        return;
                    }
                    MediaItem mediaItem;
                    if (groupByCategoryType.isEmpty()) {
                        Nepomuk::Resource res = Nepomuk::Resource(it.binding(mediaVocabulary.mediaResourceBinding()).uri());
                        mediaItem = Utilities::mediaItemFromNepomuk(res, m_mediaListProperties.lri);
                        mediaItem.semanticComment = i18np("played once", "played %1 times", mediaItem.fields["playCount"].toInt());
                    } else {
                        mediaItem = Utilities::categoryMediaItemFromIterator(it, groupByCategoryType, m_mediaListProperties.lri);
                        int playCount = it.binding(QString("%1_sum").arg(mediaVocabulary.playCountBinding())).literal().toInt();
                        mediaItem.semanticComment = i18np("played once", "played %1 times", playCount);
                        mediaItem.fields["playCount"] = playCount;
                    }
                    if (!mediaItem.url.startsWith("nepomuk:/")) {
                        if ((ignoreZeros && mediaItem.fields["playCount"].toInt() > 0) ||
                            !ignoreZeros) {
                            if (groupByCategoryType == "AudioGenre") {
                                addUniqueGenreGroup("playCount", mediaItem, &mediaList, originalGenreLimit);
                            } else {
                                mediaList.append(mediaItem);
                            }
                        }
                    }
                }
                m_mediaListProperties.name = i18n("Frequently Played");
                m_mediaListProperties.type = QString("Sources");
            }
        }
        if (engineArg.toLower() == "recent") {
            mediaList.clear();
            if (!mediaType.isEmpty()) {
                MediaQuery query;
                QStringList bindings;
                if (groupByCategoryType.isEmpty()) {
                    bindings.append(mediaVocabulary.mediaResourceBinding());
                    bindings.append(mediaVocabulary.mediaResourceUrlBinding());
                    bindings.append(mediaVocabulary.lastPlayedBinding());
                } else {
                    //NOTE:query.addLRIFilterConditions will automatically add 
                    //the groupBy field name to the binding list.
                    QString groupByResourceBinding = MediaVocabulary::resourceBindingForCategory(groupByCategoryType);
                    if (!groupByResourceBinding.isEmpty()) {
                        bindings.append(groupByResourceBinding);
                    }
                    bindings.append(MediaQuery::aggregateBinding(mediaVocabulary.lastPlayedBinding(), MediaQuery::Max));
                } 
                query.select(bindings, MediaQuery::Distinct);
                query.startWhere();
                if (mediaType == "audio") {
                    query.addCondition(mediaVocabulary.hasTypeAnyAudio(MediaQuery::Required));
                } else if (mediaType == "video") {
                    query.addCondition(mediaVocabulary.hasTypeAnyVideo(MediaQuery::Required));
                }
                query.addLRIFilterConditions(engineFilterList, mediaVocabulary);
                query.addCondition(mediaVocabulary.hasLastPlayed(MediaQuery::Required));
                query.endWhere();
                QStringList orderByBindings;
                QList<MediaQuery::Order> order;
                if (groupByCategoryType.isEmpty()) {
                    orderByBindings.append(mediaVocabulary.lastPlayedBinding());
                } else {
                    orderByBindings.append(QString("%1_max").arg(mediaVocabulary.lastPlayedBinding()));
                }
                order.append(MediaQuery::Descending);
                query.orderBy(orderByBindings, order);
                
                Soprano::QueryResultIterator it = query.executeSelect(m_mainModel);
                
                //Build media list from results
                while( it.next() ) {
                    if (m_stop) {
                        return;
                    }
                    MediaItem mediaItem;
                    if (groupByCategoryType.isEmpty()) {
                        Nepomuk::Resource res = Nepomuk::Resource(it.binding(mediaVocabulary.mediaResourceBinding()).uri());
                        mediaItem = Utilities::mediaItemFromNepomuk(res, m_mediaListProperties.lri);
                        mediaItem.fields["lastPlayed"] = it.binding(mediaVocabulary.lastPlayedBinding()).literal().toDateTime();
                    } else {
                        mediaItem = Utilities::categoryMediaItemFromIterator(it, groupByCategoryType, m_mediaListProperties.lri);
                        mediaItem.fields["lastPlayed"] = it.binding(QString("%1_max").arg(mediaVocabulary.lastPlayedBinding())).literal().toDateTime();
                    }
                    mediaItem.semanticComment = Utilities::wordsForTimeSince(mediaItem.fields["lastPlayed"].toDateTime());
                    if (!mediaItem.url.startsWith("nepomuk:/")) {
                        if (groupByCategoryType == "AudioGenre") {
                            addUniqueGenreGroup("lastPlayed", mediaItem, &mediaList, originalGenreLimit);
                        } else {
                            mediaList.append(mediaItem);
                        }
                    }
                }
                m_mediaListProperties.name = i18n("Recently Played");
                m_mediaListProperties.type = QString("Sources");
            }
        }
        if (engineArg.toLower() == "highest") {
            mediaList.clear();
            if (!mediaType.isEmpty()) {
                bool ignoreZeros = false;
                MediaQuery query;
                QStringList bindings;
                if (groupByCategoryType.isEmpty()) {
                    bindings.append(mediaVocabulary.mediaResourceBinding());
                    bindings.append(mediaVocabulary.mediaResourceUrlBinding());
                    bindings.append(mediaVocabulary.ratingBinding());
                } else {
                    //NOTE:query.addLRIFilterConditions will automatically add 
                    //the groupBy field name to the binding list.
                    QString groupByResourceBinding = MediaVocabulary::resourceBindingForCategory(groupByCategoryType);
                    if (!groupByResourceBinding.isEmpty()) {
                        bindings.append(groupByResourceBinding);
                    }
                    bindings.append(MediaQuery::aggregateBinding(mediaVocabulary.ratingBinding(), MediaQuery::Sum));
                    bindings.append(MediaQuery::aggregateBinding(mediaVocabulary.ratingBinding(), MediaQuery::Count));
                } 
                query.select(bindings, MediaQuery::Distinct);
                query.startWhere();
                if (mediaType == "audio") {
                    query.addCondition(mediaVocabulary.hasTypeAnyAudio(MediaQuery::Required));
                } else if (mediaType == "video") {
                    query.addCondition(mediaVocabulary.hasTypeAnyVideo(MediaQuery::Required));
                }
                query.addLRIFilterConditions(engineFilterList, mediaVocabulary);
                if (m_mediaListProperties.filterForField("rating").isEmpty()) {
                    query.addCondition(mediaVocabulary.hasRating(MediaQuery::Required, 0, MediaQuery::GreaterThan));
                    ignoreZeros = true;
                }
                query.addCondition(mediaVocabulary.hasPlayCount(MediaQuery::Optional));
                query.endWhere();
                QStringList orderByBindings;
                QList<MediaQuery::Order> order;
                if (groupByCategoryType.isEmpty()) {
                    orderByBindings.append(mediaVocabulary.ratingBinding());
                    order.append(MediaQuery::Descending);
                    orderByBindings.append(mediaVocabulary.playCountBinding());
                    order.append(MediaQuery::Descending);
                } else {
                    orderByBindings.append(QString("%1_sum").arg(mediaVocabulary.ratingBinding()));
                    order.append(MediaQuery::Descending);
                    order.append(MediaQuery::Descending);
                }
                query.orderBy(orderByBindings, order);
                
                Soprano::QueryResultIterator it = query.executeSelect(m_mainModel);
                
                //Build media list from results
                while( it.next() ) {
                    if (m_stop) {
                        return;
                    }
                    MediaItem mediaItem;
                    if (groupByCategoryType.isEmpty()) {
                        Nepomuk::Resource res = Nepomuk::Resource(it.binding(mediaVocabulary.mediaResourceBinding()).uri());
                        mediaItem = Utilities::mediaItemFromNepomuk(res, m_mediaListProperties.lri);
                    } else {
                        mediaItem = Utilities::categoryMediaItemFromIterator(it, groupByCategoryType, m_mediaListProperties.lri);
                        int sum = it.binding(QString("%1_sum").arg(mediaVocabulary.ratingBinding())).literal().toInt();
                        int count = it.binding(QString("%1_count").arg(mediaVocabulary.ratingBinding())).literal().toInt();
                        int rating = sum/count;
                        mediaItem.fields["rating"] = rating;
                    }
                    if (!mediaItem.url.startsWith("nepomuk:/")) {
                        if ((ignoreZeros && mediaItem.fields["rating"].toInt() > 0) ||
                            !ignoreZeros) {
                            if (groupByCategoryType == "AudioGenre") {
                                addUniqueGenreGroup("rating", mediaItem, &mediaList, originalGenreLimit);
                            } else {
                                mediaList.append(mediaItem);
                            }
                        }
                    }
                }
                m_mediaListProperties.name = i18n("Highest Rated");
                m_mediaListProperties.type = QString("Sources");
            }
        }
        if (engineArg.toLower() == "recentlyadded") {
            mediaList.clear();
            if (!mediaType.isEmpty()) {
                MediaQuery query;
                QStringList bindings;
                bindings.append(mediaVocabulary.mediaResourceBinding());
                bindings.append("added");
                query.select(bindings, MediaQuery::Distinct);
                query.startWhere();
                query.addCondition("graph ?g { ");
                if (mediaType == "audio") {
                    query.addCondition(mediaVocabulary.hasTypeAnyAudio(MediaQuery::Required));
                } else if (mediaType == "video") {
                    query.addCondition(mediaVocabulary.hasTypeAnyVideo(MediaQuery::Required));
                }
                query.addLRIFilterConditions(engineFilterList, mediaVocabulary);
                query.addCondition("} ");
                query.addCondition("?g nao:created ?added . ");
                query.endWhere();
                QStringList orderByBindings;
                QList<MediaQuery::Order> order;
                orderByBindings.append("added");
                order.append(MediaQuery::Descending);
                query.orderBy(orderByBindings, order);

                Soprano::QueryResultIterator it = query.executeSelect(m_mainModel);

                //Build media list from results
                while( it.next() ) {
                    if (m_stop) {
                        return;
                    }
                    MediaItem mediaItem;
                    QDateTime added = it.binding("added").literal().toDateTime();
                    Nepomuk::Resource res = Nepomuk::Resource(it.binding(mediaVocabulary.mediaResourceBinding()).uri());
                    mediaItem = Utilities::mediaItemFromNepomuk(res, m_mediaListProperties.lri);
                    mediaItem.semanticComment = i18nc("for example, added 3 days ago", "added %1", Utilities::wordsForTimeSince(added));
                    if (!mediaItem.url.startsWith("nepomuk:/")) {
                        mediaList.append(mediaItem);
                    }
                }
                m_mediaListProperties.name = i18n("Recently Added");
                m_mediaListProperties.type = QString("Sources");
            }
        }
    }
    
    emit results(m_requestSignature, mediaList, m_mediaListProperties, true, m_subRequestSignature);
    
    //Check if MediaItems in mediaList exist
    QList<MediaItem> mediaItems = Utilities::mediaItemsDontExist(mediaList);
    if (mediaItems.count() > 0) {
        emit updateMediaItems(mediaItems);
    } else {
        //Get any remaining metadata for mediaItems
        if (mediaType == "video") {
            for (int i = 0; i < mediaList.count(); i++) {
                if (m_stop) {
                    return;
                }
                MediaItem mediaItem = Utilities::completeMediaItem(mediaList.at(i));
                emit updateMediaItem(mediaItem);
            }
        }
        
    }
    
    m_requestSignature = QString();
    m_subRequestSignature = QString();
}
Ejemplo n.º 25
0
bool NW::Executive::canProcess( const Nepomuk::Resource & res) const
{
    // If no filter set up, then no filter is necessary
    if ( d->typeFilters.isEmpty() )
        return true;

    // Create a query
    /*
    for( int i = 0; i < d->typeFilters; i++)
    {
    }*/
    static QString unionString = QString( "UNION" );
    QStringList queryExactList;
    QStringList querySubclassList;
    bool currentType = d->typeFilters[0].allowed;

            
    /* General idea - unite consiquent records with same .allowed field into
     * one group, and  when prepare to switch to another group - create a query
     * from accumulated strings, ask it and determine the result. 
     * Reaching the end of filter list is treated as switching to another group
     */
    foreach( const FilterRecord & record, d->typeFilters)
    {
        if ( record.allowed != currentType ) {

            // After this function call, queryExactList will change!
            QString query = buildFilterQuery(res.resourceUri(), queryExactList, querySubclassList);


            Soprano::QueryResultIterator it = res.manager()->mainModel()->executeQuery(query, Soprano::Query::QueryLanguageSparql );
            if ( it.next() ) {
                // Has answer
                if ( it.boolValue() ) {
                    return currentType;
                }
            }
            else {
                // Wow. Ask query doesn't return an answer. May be it is incorrect ?
                qCritical() << "Filter query is incorrect. Report a BUG please";
                return false;
            }

            // Clear
            queryExactList.clear();
            querySubclassList.clear();

            // Switch current type
            currentType = record.allowed;
        }

        // Accumulate to the group
        if ( record.matchType == ExactMatch or record.matchType == SubclassOrExactMatch ) {
            queryExactList << FilterRecord::queryString(ExactMatch, record.typeUrl) << unionString;
        }

        if ( record.matchType == SubclassOrExactMatch or record.matchType == SubclassMatch ) {
            querySubclassList << FilterRecord::queryString(SubclassMatch, record.typeUrl) << unionString;
        }
    }
    // Build for the last group
    QString query = buildFilterQuery(res.resourceUri(), queryExactList, querySubclassList);


    Soprano::QueryResultIterator it = res.manager()->mainModel()->executeQuery(query, Soprano::Query::QueryLanguageSparql );
    if ( it.isBool() ) {
        // Has answer
        if ( it.boolValue() ) {
            return currentType;
        }
        else {
            // return default rule
            return d->defaultTypeRule;
        }
    }
    else {
        // Wow. Ask query doesn't return an answer. May be it is incorrect ?
        qCritical() << "Filter query is incorrect. Report a BUG please";
        return false;
    }


}
Ejemplo n.º 26
0
void Nepomuk2::TvshowProtocol::listDir( const KUrl& url )
{
    // root folder
    if(url.path().length() <= 1) {
        // list all tv shows including title, description, and an optional depiction (for now we simply take one of them)
        Soprano::QueryResultIterator it
                = Nepomuk2::ResourceManager::instance()->mainModel()->executeQuery(QString::fromLatin1("select distinct ?r ?t ?d where { "
                                                                                                      "?r a %1 . "
                                                                                                      "?r %2 ?t . "
                                                                                                      "?r %3 ?d . "
                                                                                                      "?r %4 ?cd . "
                                                                                                      "?r %5 ?md . }")
                                                                                  .arg(Soprano::Node::resourceToN3(NMM::TVSeries()),
                                                                                       Soprano::Node::resourceToN3(NIE::title()),
                                                                                       Soprano::Node::resourceToN3(NIE::description()),
                                                                                       Soprano::Node::resourceToN3(NAO::created()),
                                                                                       Soprano::Node::resourceToN3(NAO::lastModified())),
                                                                                  Soprano::Query::QueryLanguageSparql);
        while(it.next()) {
            UDSEntry uds = createSeriesUDSEntry(it["r"].uri(),
                                                it["t"].toString(),
                                                it["t"].toString(),
                                                it["d"].toString(),
                                                it["cd"].literal().toDateTime(),
                                                it["md"].literal().toDateTime());
            listEntry(uds, false);
        }

        KIO::UDSEntry uds = createFolderUDSEntry(QLatin1String("latest"), i18n("Next Episodes To Watch"));
        uds.insert(KIO::UDSEntry::UDS_ICON_NAME, QLatin1String("favorites"));
        listEntry(uds, false);

        listEntry(UDSEntry(), true);
        finished();
    }

    // all other URLS
    else {
        const QStringList pathTokens = url.path().split('/', QString::SkipEmptyParts);
        if(pathTokens.count() == 1 && pathTokens.first() == QLatin1String("latest")) {
            // list the next unwatched episodes of all series
            // query the min episode which does not have any watched episode after it
            // TODO: find a way to also query the episode at the same time
            Soprano::QueryResultIterator it
                    = Nepomuk2::ResourceManager::instance()->mainModel()->executeQuery(QLatin1String("select ?st ?series min(1000*?s+?e) as ?x where { "
                                                                                                    "?r a nmm:TVShow ; "
                                                                                                    "nmm:episodeNumber ?e ; "
                                                                                                    "nmm:season ?s ; "
                                                                                                    "nmm:series ?series . "
                                                                                                    "?series nie:title ?st "
                                                                                                    "FILTER NOT EXISTS { ?r nuao:usageCount ?u . filter(?u>0) . } "
                                                                                                    "FILTER NOT EXISTS { "
                                                                                                    "?r2 a nmm:TVShow ; "
                                                                                                    "nmm:series ?series ; "
                                                                                                    "nmm:episodeNumber ?e2 ; "
                                                                                                    "nmm:season ?s2 ; "
                                                                                                    "nuao:usageCount ?uc . "
                                                                                                    "filter(?uc>0) . "
                                                                                                    "filter((1000*?s2+?e2) > (1000*?s+?e)) . } "
                                                                                                    "}"),
                                                                                      Soprano::Query::QueryLanguageSparql);
            while(it.next()) {
                const QString seriesTitle = it["st"].toString();
                const int seasonNum = it["x"].literal().toInt() / 1000;
                const int episodeNum = it["x"].literal().toInt() % 1000;
                Soprano::QueryResultIterator it2
                        = Nepomuk2::ResourceManager::instance()->mainModel()->executeQuery(QString::fromLatin1("select ?r ?url ?t where { "
                                                                                                              "?r a nmm:TVShow ; "
                                                                                                              "nie:url ?url ; "
                                                                                                              "nie:title ?t ; "
                                                                                                              "nmm:series %1 ; "
                                                                                                              "nmm:episodeNumber %2 ; "
                                                                                                              "nmm:season %3 . "
                                                                                                              "OPTIONAL { ?r nmm:releaseDate ?rd ; "
                                                                                                              "nmm:synopsis ?d . } . }")
                                                                                          .arg(it["series"].toN3())
                                                                                          .arg(episodeNum)
                                                                                          .arg(seasonNum),
                                                                                          Soprano::Query::QueryLanguageSparql);
                if(it2.next()) {
                    const QString episodeTitle = it2["t"].toString();
                    const QString title = i18n("Next episode of %1: %2x%3 - %4",
                                               seriesTitle,
                                               QString::number(seasonNum).rightJustified(2, QLatin1Char('0')),
                                               QString::number(episodeNum).rightJustified(2, QLatin1Char('0')),
                                               episodeTitle);
                    UDSEntry uds;
                    uds.insert( KIO::UDSEntry::UDS_NAME, title );
                    uds.insert( KIO::UDSEntry::UDS_FILE_TYPE, S_IFREG );
                    uds.insert( KIO::UDSEntry::UDS_DISPLAY_TYPE, i18n("TV Show") );
                    uds.insert( KIO::UDSEntry::UDS_ACCESS, 0700 );
                    uds.insert( KIO::UDSEntry::UDS_USER, KUser().loginName() );
                    uds.insert( KIO::UDSEntry::UDS_CREATION_TIME, it2["rd"].literal().toDateTime().toTime_t() );
                    uds.insert( KIO::UDSEntry::UDS_COMMENT, it2["d"].toString() );
                    uds.insert( KIO::UDSEntry::UDS_URL, KUrl(it2["url"].uri()).url() );
                    uds.insert( KIO::UDSEntry::UDS_NEPOMUK_URI, KUrl(it2["r"].uri()).url() );
                    listEntry(uds, false);
                }
            }
            listEntry(UDSEntry(), true);
            finished();
        }

        if(pathTokens.count() == 1) {
            // list one TV Series: list seasons
            Soprano::QueryResultIterator it
                    = Nepomuk2::ResourceManager::instance()->mainModel()->executeQuery(QString::fromLatin1("select distinct ?s where { "
                                                                                                          "?r nmm:series ?tv . "
                                                                                                          "?tv nie:title %1 . "
                                                                                                          "?r nmm:season ?s . "
                                                                                                          "OPTIONAL { ?sr a nmm:TVSeason ; nmm:seasonOf ?tv ; nmm:seasonNumber ?s . } . }")
                                                                                      .arg(Soprano::Node::literalToN3(pathTokens.first())),
                                                                                      Soprano::Query::QueryLanguageSparql);
            while(it.next()) {
                const QString name = pathTokens.first() + QLatin1String(" - ") + i18n("Season %1", it["s"].literal().toInt());
                UDSEntry uds = createFolderUDSEntry(name, name);
                if(it["sr"].isResource()) {
                    uds.insert( KIO::UDSEntry::UDS_NEPOMUK_URI, KUrl(it["sr"].uri()).url() );
                }
                listEntry(uds, false);
            }
            listEntry(UDSEntry(), true);
            finished();
        }

        else if(pathTokens.count() == 2) {
            const QString seriesTitle = pathTokens[0];
            const int season = pathTokens[1].mid(pathTokens[1].lastIndexOf(' ')+1).toInt();
            Soprano::QueryResultIterator it
                    = Nepomuk2::ResourceManager::instance()->mainModel()->executeQuery(QString::fromLatin1("select distinct * where { "
                                                                                                          "?r a nmm:TVShow ; "
                                                                                                          "nmm:season %1 ; "
                                                                                                          "nmm:series [ nie:title %2 ] ; "
                                                                                                          "nie:title ?t ; "
                                                                                                          "nmm:episodeNumber ?e ; "
                                                                                                          "nie:url ?url . "
                                                                                                          "OPTIONAL { ?r nmm:releaseDate ?rd ; "
                                                                                                          "nmm:synopsis ?d . } . }")
                                                                                      .arg(Soprano::Node::literalToN3(season),
                                                                                           Soprano::Node::literalToN3(seriesTitle)),
                                                                                      Soprano::Query::QueryLanguageSparql);
            while(it.next()) {
                const QString episodeName = seriesTitle + QString::fromLatin1(" - %1x%2 - ").arg(season, 2, 10, QLatin1Char('0')).arg(it["e"].literal().toInt(), 2, 10, QLatin1Char('0')) + it["t"].toString();
                UDSEntry uds;
                uds.insert( KIO::UDSEntry::UDS_NAME, episodeName );
                uds.insert( KIO::UDSEntry::UDS_FILE_TYPE, S_IFREG );
                uds.insert( KIO::UDSEntry::UDS_DISPLAY_TYPE, i18n("TV Show") );
                uds.insert( KIO::UDSEntry::UDS_ACCESS, 0700 );
                uds.insert( KIO::UDSEntry::UDS_USER, KUser().loginName() );
                uds.insert( KIO::UDSEntry::UDS_CREATION_TIME, it["rd"].literal().toDateTime().toTime_t() );
                uds.insert( KIO::UDSEntry::UDS_COMMENT, it["d"].toString() );
                uds.insert( KIO::UDSEntry::UDS_URL, KUrl(it["url"].uri()).url() );
                uds.insert( KIO::UDSEntry::UDS_NEPOMUK_URI, KUrl(it["r"].uri()).url() );
                listEntry(uds, false);
            }
            listEntry(UDSEntry(), true);
            finished();
        }

        else {
            error( KIO::ERR_CANNOT_ENTER_DIRECTORY, url.prettyUrl() );
        }
    }
}
Ejemplo n.º 27
0
QList<CachedRowEntry> EventQuery::processQueryResults(const QString &query, const QUrl &uri)
{
    Soprano::Model* model = Nepomuk2::ResourceManager::instance()->mainModel();
    Soprano::QueryResultIterator it = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );

    // combine all search results again, so we get a just a single resource with a list of all authors and the list of types
    // instead of many resources with all types again
    QMap<QString, QStringList> resultList;
    while( it.next() ) {
        Soprano::BindingSet p = it.current();

        // get either a new entry or what we have inserted beforehand
        QStringList curEntry = resultList.value( p.value("r").toString(), QStringList());

        // now set / add each queried value into the StringList
        if (curEntry.isEmpty() ) {

            curEntry << p.value("star").toString() << p.value("title").toString()
                     << p.value("date").toString() << p.value("publication").toString() << p.value("r").toString();
        }
        else {
            QString star = p.value("star").toString();
            if(!star.isEmpty())
                curEntry[Column_StarRate] = star;

            QString title = p.value("title").toString();
            if(!title.isEmpty())
                curEntry[Column_Title] = title;

            QString date = p.value("date").toString();
            if( !date.isEmpty() )
                curEntry[Column_Date] = date;

            QString publication = p.value("publication").toString();
            if(!publication.isEmpty() && !curEntry[Column_Publication] .contains(publication)) {

                //create content for the HTMLDelegate looks a lot better when several entries are being displayed
                curEntry[Column_Publication] = curEntry[Column_Publication].append("&#8226; ");
                curEntry[Column_Publication] = curEntry[Column_Publication].append(publication);
                curEntry[Column_Publication] = curEntry[Column_Publication].append("<br/>");
            }
        }

        // and save the result back into the map
        if(p.value("r").isEmpty()) {
            Q_ASSERT(!uri.isEmpty());
            resultList.insert(uri.toString(), curEntry);
        }
        else {
            resultList.insert(p.value("r").toString(), curEntry);
        }
    }

    // now create the cache entries from all returned search results
    QList<CachedRowEntry> newCache;
    QMapIterator<QString, QStringList> i(resultList);
    while (i.hasNext()) {
        i.next();

        CachedRowEntry cre;
        cre.uri = QUrl( i.key() );
        cre.displayColums = createDisplayData(i.value());
        cre.decorationColums = createDecorationData(i.value());
        cre.resource = Nepomuk2::Resource::fromResourceUri( cre.uri  );
        cre.timestamp = QDateTime::currentDateTime();
        cre.resourceType = 0; //Unused
        newCache.append(cre);
    }

    return newCache;
}
Ejemplo n.º 28
0
void AudioStreamListEngine::run()
{
    QThread::setTerminationEnabled(true);
    m_stop = false;

    if (m_updateSourceInfo || m_removeSourceInfo) {
        NepomukListEngine::run();
        return;
    }
    
    //Create media list based on engine argument and filter
    QList<MediaItem> mediaList;
    MediaVocabulary mediaVocabulary = MediaVocabulary();
    
    QString engineArg = m_mediaListProperties.engineArg();
    QString engineFilter = m_mediaListProperties.engineFilter();
    
    if (m_nepomukInited) {
        if (engineArg.isEmpty()) {
            MediaQuery query;
            QStringList bindings;
            bindings.append(mediaVocabulary.mediaResourceBinding());
            bindings.append(mediaVocabulary.mediaResourceUrlBinding());
            bindings.append(mediaVocabulary.titleBinding());
            bindings.append(mediaVocabulary.ratingBinding());
            bindings.append(mediaVocabulary.descriptionBinding());
            bindings.append(mediaVocabulary.artworkBinding());
            //bindings.append(mediaVocabulary.genreBinding());
            query.select(bindings, MediaQuery::Distinct);
            query.startWhere();
            query.addCondition(mediaVocabulary.hasTypeAudioStream(MediaQuery::Required));
            query.addCondition(mediaVocabulary.hasTitle(MediaQuery::Required));
            query.addCondition(mediaVocabulary.hasRating(MediaQuery::Optional));
            query.addCondition(mediaVocabulary.hasDescription(MediaQuery::Optional));
            query.addCondition(mediaVocabulary.hasArtwork(MediaQuery::Optional));
            query.endWhere();
            QStringList orderByBindings;
            orderByBindings.append(mediaVocabulary.titleBinding());
            query.orderBy(orderByBindings);
            
            Soprano::QueryResultIterator it = query.executeSelect(m_mainModel);
            
            //Build media list from results
            while( it.next() ) {
                if (m_stop) {
                    return;
                }
                MediaItem mediaItem = Utilities::mediaItemFromIterator(it, QString("Audio Stream"), m_mediaListProperties.lri);
                if (!mediaItem.url.startsWith(QLatin1String("nepomuk:/"))) {
                    mediaList.append(mediaItem);
                }
            }
            
            m_mediaListProperties.summary = i18np("1 stream", "%1 streams", mediaList.count());
            
            MediaItem mediaItem;
            mediaItem.type = "Audio";
            mediaItem.url.clear();
            mediaItem.title = i18n("New Audio Stream");
            mediaItem.subTitle = i18n("Edit info to create new audio stream");
            mediaItem.artwork = KIcon("text-html");
            mediaItem.fields["title"] = i18n("Untitled");
            mediaItem.fields["audioType"] = "Audio Stream";
            mediaItem.fields["isTemplate"] = true;
            mediaList.append(mediaItem);
            
            m_mediaListProperties.type = QString("Sources");
            
        } else if (engineArg.toLower() == "search") {
            MediaQuery query;
            QStringList bindings;
            bindings.append(mediaVocabulary.mediaResourceBinding());
            bindings.append(mediaVocabulary.mediaResourceUrlBinding());
            bindings.append(mediaVocabulary.titleBinding());
            bindings.append(mediaVocabulary.ratingBinding());
            bindings.append(mediaVocabulary.descriptionBinding());
            bindings.append(mediaVocabulary.artworkBinding());
            //bindings.append(mediaVocabulary.genreBinding());
            query.select(bindings, MediaQuery::Distinct);
            query.startWhere();
            query.addCondition(mediaVocabulary.hasTypeAudioStream(MediaQuery::Required));
            query.addCondition(mediaVocabulary.hasTitle(MediaQuery::Required));
            query.addCondition(mediaVocabulary.hasRating(MediaQuery::Optional));
            query.addCondition(mediaVocabulary.hasDescription(MediaQuery::Optional));
            query.addCondition(mediaVocabulary.hasArtwork(MediaQuery::Optional));
            query.startFilter();
            query.addFilterConstraint(mediaVocabulary.titleBinding(), engineFilter, MediaQuery::Contains);
            query.addFilterOr();
            query.addFilterConstraint(mediaVocabulary.descriptionBinding(), engineFilter, MediaQuery::Contains);
            query.endFilter();
            query.endWhere();
            QStringList orderByBindings;
            orderByBindings.append(mediaVocabulary.titleBinding());
            query.orderBy(orderByBindings);
            
            Soprano::QueryResultIterator it = query.executeSelect(m_mainModel);
            
            //Build media list from results
            while( it.next() ) {
                MediaItem mediaItem = Utilities::mediaItemFromIterator(it, QString("Audio Stream"), m_mediaListProperties.lri);
                if (!mediaItem.url.startsWith(QLatin1String("nepomuk:/"))) {
                    mediaList.append(mediaItem);
                }
            }
            
            m_mediaListProperties.summary = i18np("1 stream", "%1 streams", mediaList.count());
            m_mediaListProperties.type = QString("Sources");
        }
    }
    
    emit results(m_requestSignature, mediaList, m_mediaListProperties, true, m_subRequestSignature);
    
    m_requestSignature.clear();
    m_subRequestSignature.clear();
}
Ejemplo n.º 29
0
void Worker::run()
{
    m_canceled = false;
    m_errorText.truncate( 0 );

    Soprano::Model* model = Soprano::createModel( Soprano::BackendSettings() << Soprano::BackendSetting( Soprano::BackendOptionStorageMemory ) );
    if ( !model ) {
        m_errorText = i18n( "Failed to create Soprano memory model. Most likely the installation misses Soprano backend plugins" );
        return;
    }

    model->addStatements( m_data.toList() );

    // select all instances that do not have a subject -> these should be the extracted entities
    Soprano::QueryResultIterator it = model->executeQuery( QString::fromLatin1( "select * where { "
                                                                                "?r a ?type . "
                                                                                "OPTIONAL { ?r <http://s.opencalais.com/1/pred/subject> ?sub . } . "
                                                                                "FILTER(!bound(?sub)) . "
                                                                                "}" ),
                                                           Soprano::Query::QueryLanguageSparql );
    while ( !m_canceled && it.next() ) {
        Soprano::Node r = it["r"];
        Soprano::Graph graph;
        Soprano::QueryResultIterator it2 = model->executeQuery( QString::fromLatin1( "construct { ?entity ?ep ?eo . ?rel ?relp ?relo . } "
                                                                                     "where { "
                                                                                     "?entity <http://s.opencalais.com/1/pred/subject> %1 . "
                                                                                     "?entity ?ep ?eo . "
                                                                                     "?rel a <http://s.opencalais.com/1/type/sys/RelevanceInfo> . "
                                                                                     "?rel <http://s.opencalais.com/1/pred/subject> %1 . "
                                                                                     "?rel ?relp ?relo . "
                                                                                     "}" )
                                                                .arg( r.toN3() ),
                                                                Soprano::Query::QueryLanguageSparql );
        while ( !m_canceled && it2.next() ) {
            graph << it2.currentStatement();
        }

        if ( m_canceled )
            break;

        it2 = model->executeQuery( QString::fromLatin1( "select ?name ?rel ?type ?offset ?length where { "
                                                        "%1 <http://s.opencalais.com/1/pred/name> ?name . "
                                                        "%1 a ?type . "
                                                        "?relInfo a <http://s.opencalais.com/1/type/sys/RelevanceInfo> . "
                                                        "?relInfo <http://s.opencalais.com/1/pred/subject> %1 . "
                                                        "?relInfo <http://s.opencalais.com/1/pred/relevance> ?rel . "
                                                        "?info a <http://s.opencalais.com/1/type/sys/InstanceInfo> . "
                                                        "?info <http://s.opencalais.com/1/pred/subject> %1 . "
                                                        "?info <http://s.opencalais.com/1/pred/offset> ?offset . "
                                                        "?info <http://s.opencalais.com/1/pred/length> ?length . "
                                                        "}" )
                                   .arg( r.toN3() ),
                                   Soprano::Query::QueryLanguageSparql );
        if ( !m_canceled && it2.next() ) {
            Nepomuk::Types::Class type( m_plugin->matchPimoType( it2["type"].uri() ) );
            QString name = it2["name"].toString();

            // FIXME: actually the opencalais resource should be used as the pimo:hasOtherRepresentation of the pimo thing
            //        but that would mean that Entity needs more information or the graph needs to be really used
            Scribo::Entity entity( name, type, graph );
            do {
                double rel = it2["rel"].literal().toDouble();
                int offset = it2["offset"].literal().toInt();
                int length = it2["length"].literal().toInt();

                Scribo::TextOccurrence oc;
                oc.setStartPos( offset );
                oc.setLength( length );
                oc.setRelevance( rel );
                entity.addOccurrence( oc );

                kDebug() << type << type.label() << name << rel << offset << length;
            } while ( !m_canceled && it2.next() );

            if ( m_canceled )
                break;

            addNewMatch( entity );

            // find relations for the entity
            Soprano::QueryResultIterator it3 = model->executeQuery( QString::fromLatin1( "select ?verb ?offset ?length ?exact where { "
                                                                                         "?s a <http://s.opencalais.com/1/type/em/r/GenericRelations> . "
                                                                                         "?s <http://s.opencalais.com/1/pred/relationsubject> %1 . "
                                                                                         "?s <http://s.opencalais.com/1/pred/verb> ?verb . "
                                                                                         "?info a <http://s.opencalais.com/1/type/sys/InstanceInfo> . "
                                                                                         "?info <http://s.opencalais.com/1/pred/subject> ?s . "
                                                                                         "?info <http://s.opencalais.com/1/pred/offset> ?offset . "
                                                                                         "?info <http://s.opencalais.com/1/pred/length> ?length . "
                                                                                         "?info <http://s.opencalais.com/1/pred/exact> ?exact . "
                                                                                         "}" )
                                                                    .arg( r.toN3() ),
                                                                    Soprano::Query::QueryLanguageSparql );
            if ( !m_canceled && it3.next() ) {
                QString verb = it3["verb"].toString();
                QString exact = it3["exact"].toString();
                int offset = it3["offset"].literal().toInt();
                int length = it3["length"].literal().toInt();

                // FIXME: get the graph
                Scribo::Statement s( verb, entity, exact, Soprano::Graph() );

                Scribo::TextOccurrence oc;
                oc.setStartPos( offset );
                oc.setLength( length );
                s.addOccurrence( oc );

                addNewMatch( s );
            }
        }
    }

    delete model;
}
Ejemplo n.º 30
0
void OntologyUpdater::start()
{
    QApplication::processEvents();
    Soprano::Model *m_mainModel;
    bool m_nepomukInited = Utilities::nepomukInited();
    if (m_nepomukInited) {
        m_mainModel = Nepomuk2::ResourceManager::instance()->mainModel();
    } else {
        return;
    }
    
    m_stopUpdate = false;
    
    MediaVocabulary mediaVocabulary;
    
    //Update audio
    QString queryPrefix = QString("PREFIX xesam: <%1> "
                    "PREFIX rdf: <%2> "
                    "PREFIX xls: <%3> "
                    "PREFIX nmm: <http://www.semanticdesktop.org/ontologies/nmm#> "
                    "PREFIX nie: <http://www.semanticdesktop.org/ontologies/2007/01/19/nie#> "
                    "PREFIX nfo: <http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#> ")
                    .arg(Soprano::Vocabulary::Xesam::xesamNamespace().toString())
                    .arg(Soprano::Vocabulary::RDF::rdfNamespace().toString())
                    .arg(Soprano::Vocabulary::XMLSchema::xsdNamespace().toString());
    QString queryStr = queryPrefix + QString("SELECT ?r "
                       "WHERE { {?r rdf:type <http://www.semanticdesktop.org/ontologies/nfo#Audio>} "
                       "UNION "
                       "{?r rdf:type <http://www.semanticdesktop.org/ontologies/nmm#MusicPiece>} "
                       "UNION "
                       "{?r rdf:type <http://www.semanticdesktop.org/ontologies/nmm#DigitalRadio>} "
                       "UNION "
                       "{?r rdf:type <http://www.semanticdesktop.org/ontologies/nmm#MusicAlbum>} "
                       "UNION "
                       "{?r rdf:type <%1>} "
                       "UNION "
                       "{?r rdf:type <%2>} "
                       "UNION "
                       "{?r rdf:type <%3>} }")
                       .arg(mediaVocabulary.typeAudio().toString())
                       .arg(mediaVocabulary.typeAudioMusic().toString())
                       .arg(mediaVocabulary.typeMediaStream().toString());
    
    Soprano::QueryResultIterator it = m_mainModel->executeQuery(queryStr, Soprano::Query::QueryLanguageSparql);
    emit infoMessage(i18n("<b>Updating audio types and properties</b><br>0 items updated..."));
    QApplication::processEvents();
    int i = 0;
    while( it.next() && !m_stopUpdate) {
        QApplication::processEvents();
        i++;
        Nepomuk2::Resource resource = Nepomuk2::Resource(it.binding("r").uri());
        //Update types
        QUrl type = QUrl("http://www.semanticdesktop.org/ontologies/nfo#Audio");
        if (resource.hasType(type)) {
            removeType(resource, type);
            if (!resource.hasType(mediaVocabulary.typeAudio())) {
                resource.addType(mediaVocabulary.typeAudio());
            }
        }
        type = QUrl("http://www.semanticdesktop.org/ontologies/nmm#MusicPiece");
        if (resource.hasType(type)) {
            removeType(resource, type);
            if (!resource.hasType(mediaVocabulary.typeAudioMusic())) {
                resource.addType(mediaVocabulary.typeAudioMusic());
            }
            //Update properties
            QUrl property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#musicAlbum");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.musicAlbum(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#trackNumber");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.musicTrackNumber(), value);
            }
        }
        type = QUrl("http://www.semanticdesktop.org/ontologies/nmm#DigitalRadio");
        if (resource.hasType(type)) {
            removeType(resource, type);
            if (!resource.hasType(mediaVocabulary.typeMediaStream())) {
                resource.addType(mediaVocabulary.typeMediaStream());
            }
        }
        type = QUrl("http://www.semanticdesktop.org/ontologies/nmm#MusicAlbum");
        if (resource.hasType(type)) {
            removeType(resource, type);
            if (!resource.hasType(mediaVocabulary.typeMusicAlbum())) {
                resource.addType(mediaVocabulary.typeMusicAlbum());
            }
        }
        
        //Update common properties
        QUrl property = QUrl("http://www.semanticdesktop.org/ontologies/nfo#duration");
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.duration(), value);
        }
        property = Nepomuk2::Vocabulary::NMM::artwork();
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.artwork(), value);
        }
        property = Nepomuk2::Vocabulary::NIE::hasLogicalPart();
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            if (value.toResource().hasType(Nepomuk2::Vocabulary::NFO::Image())) {
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.artwork(), value);
            }
        }
        property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#genre");
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.genre(), value);
        }
        property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#releaseDate");
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.releaseDate(), value);
        }
        property = Soprano::Vocabulary::Xesam::useCount();
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.playCount(), value);
        }
        property = Soprano::Vocabulary::Xesam::lastUsed();
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.lastPlayed(), value);
        }
        emit infoMessage(i18n("<b>Updating audio types and properties</b><br>%1 audio items done...", i));
        QApplication::processEvents();
    }


    //Update video
    queryStr = queryPrefix + QString("SELECT ?r "
                       "WHERE { {?r rdf:type <http://www.semanticdesktop.org/ontologies/nfo#Video>} "
                       "UNION "
                       "{?r rdf:type <http://www.semanticdesktop.org/ontologies/nmm#Movie>} "
                       "UNION "
                       "{?r rdf:type <http://www.semanticdesktop.org/ontologies/nmm#TVShow>} "
                       "UNION "
                       "{?r rdf:type <http://www.semanticdesktop.org/ontologies/2009/02/19/nmm#TVSeries>} "
                       "UNION "
                       "{?r rdf:type <%1>} "
                       "UNION "
                       "{?r rdf:type <%2>} "
                       "UNION "
                       "{?r rdf:type <%3>} }")
                       .arg(mediaVocabulary.typeVideo().toString())
                       .arg(mediaVocabulary.typeVideoMovie().toString())
                       .arg(mediaVocabulary.typeVideoTVShow().toString());

    
    it = m_mainModel->executeQuery(queryStr, Soprano::Query::QueryLanguageSparql);
    emit infoMessage(i18n("<b>Updating audio types and properties</b><br>0 items updated..."));
    QApplication::processEvents();
    i = 0;
    while( it.next() && !m_stopUpdate) {
        QApplication::processEvents();
        i++;
        Nepomuk2::Resource resource = Nepomuk2::Resource(it.binding("r").uri());
        //Update types
        QUrl type = QUrl("http://www.semanticdesktop.org/ontologies/nfo#Video");
        if (resource.hasType(type)) {
            removeType(resource, type);
            if (!resource.hasType(mediaVocabulary.typeVideo())) {
                resource.addType(mediaVocabulary.typeVideo());
            }
        }
        type = QUrl("http://www.semanticdesktop.org/ontologies/nmm#Movie");
        if (resource.hasType(type)) {
            removeType(resource, type);
            if (!resource.hasType(mediaVocabulary.typeVideoMovie())) {
                resource.addType(mediaVocabulary.typeVideoMovie());
            }
            //Update properties
            QUrl property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#synopsis");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoSynopsis(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#writer");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoWriter(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#actor");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoActor(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#director");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoDirector(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#producer");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoProducer(), value);
            }
        }
        type = QUrl("http://www.semanticdesktop.org/ontologies/nmm#TVShow");
        if (resource.hasType(type)) {
            removeType(resource, type);
            if (!resource.hasType(mediaVocabulary.typeVideoTVShow())) {
                resource.addType(mediaVocabulary.typeVideoTVShow());
            }
            //Update properties
            QUrl property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#series");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoSeries(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#synopsis");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoSynopsis(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#season");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoSeason(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#episodeNumber");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoEpisodeNumber(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#writer");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoWriter(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#actor");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoActor(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#director");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoDirector(), value);
            }
            property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#producer");
            if (resource.hasProperty(property)) {
                Nepomuk2::Variant value = resource.property(property);
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.videoProducer(), value);
            }
        }
        type = QUrl("http://www.semanticdesktop.org/ontologies/2009/02/19/nmm#TVSeries");
        if (resource.hasType(type)) {
            removeType(resource, type);
            if (!resource.hasType(mediaVocabulary.typeTVSeries())) {
                resource.addType(mediaVocabulary.typeTVSeries());
            }
        }
        
        //Update common properties
        QUrl property = QUrl("http://www.semanticdesktop.org/ontologies/nfo#duration");
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.duration(), value);
        }
        property = Nepomuk2::Vocabulary::NMM::artwork();
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.artwork(), value);
        }
        property = Nepomuk2::Vocabulary::NIE::hasLogicalPart();
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            if (value.toResource().hasType(Nepomuk2::Vocabulary::NFO::Image())) {
                resource.removeProperty(property);
                resource.setProperty(mediaVocabulary.artwork(), value);
            }
        }
        property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#genre");
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.genre(), value);
        }
        property = QUrl("http://www.semanticdesktop.org/ontologies/nmm#releaseDate");
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.releaseDate(), value);
        }
        property = Soprano::Vocabulary::Xesam::useCount();
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.playCount(), value);
        }
        property = Soprano::Vocabulary::Xesam::lastUsed();
        if (resource.hasProperty(property)) {
            Nepomuk2::Variant value = resource.property(property);
            resource.removeProperty(property);
            resource.setProperty(mediaVocabulary.lastPlayed(), value);
        }
        
        emit infoMessage(i18n("<b>Updating video types and properties</b><br>%1 video items done...", i));
        QApplication::processEvents();
    }


    //Fix screwed up properties
    MediaQuery query;
    QStringList bindings;
    bindings.append(mediaVocabulary.mediaResourceBinding());
    bindings.append(mediaVocabulary.ratingBinding());
    query.select(bindings, MediaQuery::Distinct);
    query.startWhere();
    query.addCondition(mediaVocabulary.hasTypeAnyAudio(MediaQuery::Required));
    query.addCondition(mediaVocabulary.hasRating(MediaQuery::Required, 10, MediaQuery::GreaterThan));
    query.endWhere();
    it = m_mainModel->executeQuery(query.query(), Soprano::Query::QueryLanguageSparql);
    emit infoMessage(i18n("<b>Updating audio types and properties</b><br>0 items updated..."));
    QApplication::processEvents();
    i = 0;
    while( it.next() && !m_stopUpdate) {
        QApplication::processEvents();
        i++;
        Nepomuk2::Resource resource = Nepomuk2::Resource(it.binding("r").uri());
        QUrl property = QUrl("http://www.semanticdesktop.org/ontologies/2007/08/15/nao#numericRating");
        if (resource.hasProperty(property)) {
            int rating = resource.property(property).toInt();
            if (rating > 10) {
                resource.removeProperty(property);
            }
        }
        emit infoMessage(i18n("<b>Cleaning up erroneous audio properties</b><br>%1 audio items done...", i));
        QApplication::processEvents();
    }

    MediaQuery query1;
    bindings.clear();
    bindings.append(mediaVocabulary.mediaResourceBinding());
    bindings.append(mediaVocabulary.ratingBinding());
    query1.select(bindings, MediaQuery::Distinct);
    query1.startWhere();
    query1.addCondition(mediaVocabulary.hasTypeAnyVideo(MediaQuery::Required));
    query1.addCondition(mediaVocabulary.hasRating(MediaQuery::Required, 10, MediaQuery::GreaterThan));
    query1.endWhere();
    it = m_mainModel->executeQuery(query.query(), Soprano::Query::QueryLanguageSparql);
    emit infoMessage(i18n("<b>Updating audio types and properties</b><br>0 items updated..."));
    QApplication::processEvents();
    i = 0;
    while( it.next() && !m_stopUpdate) {
        QApplication::processEvents();
        i++;
        Nepomuk2::Resource resource = Nepomuk2::Resource(it.binding("r").uri());
        QUrl property = QUrl("http://www.semanticdesktop.org/ontologies/2007/08/15/nao#numericRating");
        if (resource.hasProperty(property)) {
            int rating = resource.property(property).toInt();
            if (rating > 10) {
                resource.removeProperty(property);
            }
        }
        emit infoMessage(i18n("<b>Cleaning up erroneous video properties</b><br>%1 video items done...", i));
        QApplication::processEvents();
    }

    if (!m_stopUpdate) {
        emit infoMessage(i18n("<b>Update complete.</b>"));
    } else {
        emit infoMessage(i18n("<b>Update stopped.</b>"));
    }
    emit done();
}