void
DatabaseCommand_PlaybackHistory::exec( DatabaseImpl* dbi )
{
    TomahawkSqlQuery query = dbi->newquery();
    QList<Tomahawk::query_ptr> ql;

    QString whereToken;
    if ( !source().isNull() )
    {
        whereToken = QString( "WHERE source %1" ).arg( source()->isLocal() ? "IS NULL" : QString( "= %1" ).arg( source()->id() ) );
    }

    QString sql = QString(
            "SELECT track, playtime, secs_played, source "
            "FROM playback_log "
            "%1 "
            "ORDER BY playtime DESC "
            "%2" ).arg( whereToken )
                  .arg( m_amount > 0 ? QString( "LIMIT 0, %1" ).arg( m_amount ) : QString() );

    query.prepare( sql );
    query.exec();

    while( query.next() )
    {
        TomahawkSqlQuery query_track = dbi->newquery();

        QString sql = QString(
                "SELECT track.name, artist.name "
                "FROM track, artist "
                "WHERE artist.id = track.artist "
                "AND track.id = %1"
                ).arg( query.value( 0 ).toUInt() );

        query_track.prepare( sql );
        query_track.exec();

        if ( query_track.next() )
        {
            Tomahawk::query_ptr q = Tomahawk::Query::get( query_track.value( 1 ).toString(), query_track.value( 0 ).toString(), QString() );

            if ( query.value( 3 ).toUInt() == 0 )
            {
                q->setPlayedBy( SourceList::instance()->getLocal(), query.value( 1 ).toUInt() );
            }
            else
            {
                q->setPlayedBy( SourceList::instance()->get( query.value( 3 ).toUInt() ), query.value( 1 ).toUInt() );
            }

            ql << q;
        }
    }

    if ( ql.count() )
        emit tracks( ql );
}
void
DatabaseCommand_LogPlayback::postCommitHook()
{
    connect( this, SIGNAL( trackPlaying( Tomahawk::query_ptr ) ),
             source().data(), SLOT( onPlaybackStarted( Tomahawk::query_ptr ) ), Qt::QueuedConnection );
    connect( this, SIGNAL( trackPlayed( Tomahawk::query_ptr ) ),
             source().data(), SLOT( onPlaybackFinished( Tomahawk::query_ptr ) ), Qt::QueuedConnection );

    Tomahawk::query_ptr q;
    if ( !m_result.isNull() )
    {
        q = m_result->toQuery();
    }
    else
    {
        // do not auto resolve this track
        q = Tomahawk::Query::get( m_artist, m_track, QString() );
    }
    q->setPlayedBy( source(), m_playtime );

    if ( m_action == Finished )
    {
        emit trackPlayed( q );
    }
    // if the play time is more than 10 minutes in the past, ignore
    else if ( m_action == Started && QDateTime::fromTime_t( playtime() ).secsTo( QDateTime::currentDateTime() ) < STARTED_THRESHOLD )
    {
        emit trackPlaying( q );
    }

    if ( source()->isLocal() )
    {
        Servent::instance()->triggerDBSync();
    }
}