예제 #1
0
파일: util.cpp 프로젝트: KDE/nepomuk-core
//
// 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();
    }
}
예제 #2
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();
    }

}
예제 #3
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);
}
예제 #4
0
파일: nrlmodel.cpp 프로젝트: KDE/soprano
    /**
     * 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 );
            }
        }
    }
예제 #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() ) );

        }
    }
}
예제 #6
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)
    }
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);
    }
예제 #8
0
KoRdfLocation::KoRdfLocation(QObject *parent, const KoDocumentRdf *rdf, Soprano::QueryResultIterator &it, bool isGeo84)
    : KoRdfSemanticItem(parent, rdf, it)
{
    m_linkSubject = it.binding("geo");
    m_dlong = KoTextRdfCore::optionalBindingAsString(it, "long", "0").toDouble();
    m_dlat  = KoTextRdfCore::optionalBindingAsString(it, "lat",  "0").toDouble();
    m_name  = QString("%1,%2").arg(m_dlong).arg(m_dlat);
    m_joiner = it.binding("joiner");
    m_isGeo84 = isGeo84;
}
예제 #9
0
KoRdfFoaF::KoRdfFoaF(QObject *parent, const KoDocumentRdf *rdf, Soprano::QueryResultIterator &it)
    : KoRdfSemanticItem(parent, rdf, it)
{
    m_uri      = it.binding("person").toString();
    m_name     = it.binding("name").toString();
    m_nick     = KoTextRdfCore::optionalBindingAsString(it, "nick");
    m_homePage = KoTextRdfCore::optionalBindingAsString(it, "homepage");
    m_imageUrl = KoTextRdfCore::optionalBindingAsString(it, "img");
    m_phone    = KoTextRdfCore::optionalBindingAsString(it, "phone");
    kDebug(30015) << "+++xmlid:" << it.binding("xmlid").toString();
}
예제 #10
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) );
 }
// 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();
    }
}
예제 #12
0
파일: entity.cpp 프로젝트: vasi/kdelibs
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();
}
KoRdfBasicSemanticItem::KoRdfBasicSemanticItem(QObject *parent, const KoDocumentRdf *rdf, Soprano::QueryResultIterator &it)
    : QObject(parent)
    , m_rdf(rdf)
{
    m_context = it.binding("graph");
    kDebug(30015) << "KoRdfBasicSemanticItem() context:" << m_context.toString();
}
예제 #14
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();
}
예제 #16
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() );
    }
}
예제 #17
0
파일: entity.cpp 프로젝트: vasi/kdelibs
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();
}
예제 #18
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;
}
//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);
    }
예제 #20
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();
    }
}
예제 #22
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;
                }
            }
        }
    }
}
예제 #23
0
KoRdfCalendarEvent::KoRdfCalendarEvent(QObject *parent, const KoDocumentRdf *rdf, Soprano::QueryResultIterator &it)
    : KoRdfSemanticItem(parent, rdf, it)
{
    m_location = KoTextRdfCore::optionalBindingAsString(it, "location");
    m_summary = KoTextRdfCore::optionalBindingAsString(it, "summary");
    m_uid = KoTextRdfCore::optionalBindingAsString(it, "uid");
    m_linkSubject = it.binding("ev");
    // floating time is the default
    m_startTimespec = KSystemTimeZones::local();
    m_endTimespec = KSystemTimeZones::local();
    // check for timezones in the type of each date-time binding.
    m_startTimespec = toKTimeZone(it.binding("dtstart"));
    m_endTimespec = toKTimeZone(it.binding("dtend"));
    m_dtstart = VEventDateTimeToKDateTime(it.binding("dtstart").toString(),
                   m_startTimespec);
    m_dtend = VEventDateTimeToKDateTime(it.binding("dtend").toString(),
                                           m_endTimespec);
    kDebug(30015) << "KoRdfCalendarEvent() start:" << m_dtstart.toString()
        << " end:" << m_dtend.toString();
    kDebug(30015) << "KoRdfCalendarEvent() long:" << KoTextRdfCore::optionalBindingAsString(it, "long")
        << " lat:" << KoTextRdfCore::optionalBindingAsString(it, "lat");
    kDebug(30015) << "KoRdfCalendarEvent() context-direct:" << it.binding("graph").toString();
    kDebug(30015) << "KoRdfCalendarEvent() context():" << context().toString();
    kDebug(30015) << "m_startTimespec.offset:" << m_startTimespec.timeZone().currentOffset();
    kDebug(30015) << "dtstart:" << m_dtstart.date();
    kDebug(30015) << "dtstart:" << m_dtstart.time();
    kDebug(30015) << "dtend:" << m_dtend.date();
    kDebug(30015) << "dtend:" << m_dtend.time();
}
예제 #24
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 );
    }
}
예제 #25
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"));
}
예제 #26
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;
}
예제 #27
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 );
}
예제 #28
0
파일: worker.cpp 프로젝트: KDE/scribo
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;
}
예제 #29
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();
}
예제 #30
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() );
        }
    }
}