summaryrefslogtreecommitdiffstats
path: root/amarok/src/scancontroller.cpp
blob: 57fd7c9a12b2ae499d91d92ad6d09e97fa9dc7eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
/***************************************************************************
 *   Copyright (C) 2003-2005 by The Amarok Developers                      *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Steet, Fifth Floor, Boston, MA  02110-1301, USA.          *
 ***************************************************************************/

#define DEBUG_PREFIX "ScanController"

#include "amarok.h"
#include "amarokconfig.h"
#include "collectiondb.h"
#include "debug.h"
#include "metabundle.h"
#include "mountpointmanager.h"
#include "playlist.h"
#include "playlistbrowser.h"
#include "scancontroller.h"
#include "statusbar.h"

#include <tqdeepcopy.h>
#include <tqfileinfo.h>
#include <tqtextcodec.h>

#include <dcopref.h>
#include <tdeapplication.h>
#include <tdelocale.h>
#include <tdemessagebox.h>

////////////////////////////////////////////////////////////////////////////////
// class ScanController
////////////////////////////////////////////////////////////////////////////////

ScanController* ScanController::currController = 0;

ScanController* ScanController::instance()
{
    return currController;
}

void ScanController::setInstance( ScanController* curr )
{
    currController = curr;
}

ScanController::ScanController( CollectionDB* parent, bool incremental, const TQStringList& folders )
    : DependentJob( parent, "CollectionScanner" )
    , TQXmlDefaultHandler()
    , m_scanner( new Amarok::ProcIO() )
    , m_folders( TQDeepCopy<TQStringList>( folders ) )
    , m_incremental( incremental )
    , m_hasChanged( false )
    , m_source( new TQXmlInputSource() )
    , m_reader( new TQXmlSimpleReader() )
    , m_waitingBundle( 0 )
    , m_lastCommandPaused( false )
    , m_isPaused( false )
    , m_tablesCreated( false )
    , m_scanCount( 0 )
{
    DEBUG_BLOCK

    ScanController::setInstance( this );
    m_reader->setContentHandler( this );
    m_reader->parse( m_source, true );

    connect( this, TQT_SIGNAL( scanDone( bool ) ), MountPointManager::instance(), TQT_SLOT( updateStatisticsURLs( bool ) ) );

    connect( m_scanner, TQT_SIGNAL( readReady( KProcIO* ) ), TQT_SLOT( slotReadReady() ) );

    *m_scanner << "amarokcollectionscanner";
    *m_scanner << "--nocrashhandler"; // We want to be able to catch SIGSEGV

    // TDEProcess must be started from the GUI thread, so we're invoking the scanner
    // here in the ctor:
    if( incremental )
    {
        setDescription( i18n( "Updating Collection" ) );
        initIncremental();
    }
    else
    {
        setDescription( i18n( "Building Collection" ) );
        *m_scanner << "-p";
        if( AmarokConfig::scanRecursively() ) *m_scanner << "-r";
        *m_scanner << m_folders;
        m_scanner->start();
    }
}


ScanController::~ScanController()
{
    DEBUG_BLOCK

    if( !isAborted() && !m_crashedFiles.empty() ) {
        KMessageBox::information( 0, i18n( "<p>The Collection Scanner was unable to process these files:</p>" ) +
                                  "<i>" + m_crashedFiles.join( "<br>" ) + "</i>",
                                  i18n( "Collection Scan Report" ) );
    }
    else if( m_crashedFiles.size() >= MAX_RESTARTS ) {
        KMessageBox::error( 0, i18n( "<p>Sorry, the Collection Scan was aborted, since too many problems were encountered.</p>" ) +
                            "<p>Advice: A common source for this problem is a broken 'TagLib' package on your computer. Replacing this package may help fixing the issue.</p>"
                            "<p>The following files caused problems:</p>" +
                            "<i>" + m_crashedFiles.join( "<br>" ) + "</i>",
                            i18n( "Collection Scan Error" ) );
    }

    m_scanner->kill();
    delete m_scanner;
    delete m_reader;
    delete m_source;
    ScanController::setInstance( 0 );
}


// Cause the CollectionDB to emit fileDeleted() signals
void
ScanController::completeJob( void )
{
    m_fileMapsMutex.lock();

    TQMap<TQString,TQString>::Iterator it;
    if( !m_incremental )
    {
        CollectionDB::instance()->emitFilesAdded( m_filesAdded );
    }
    else
    {
        for( it = m_filesAdded.begin(); it != m_filesAdded.end(); ++it )
        {
            if( m_filesDeleted.contains( it.key() ) )
                m_filesDeleted.remove( it.key() );
        }
        for( it = m_filesAdded.begin(); it != m_filesAdded.end(); ++it )
            CollectionDB::instance()->emitFileAdded( it.data(), it.key() );
        for( it = m_filesDeleted.begin(); it != m_filesDeleted.end(); ++it )
            CollectionDB::instance()->emitFileDeleted( it.data(), it.key() );
    }

    m_fileMapsMutex.unlock();

    emit scanDone( !m_incremental || m_hasChanged );

    ThreadManager::DependentJob::completeJob();
}


/**
 * The Incremental Scanner works as follows: Here we check the mtime of every directory in the "directories"
 * table and store all changed directories in m_folders.
 *
 * These directories are then scanned in CollectionReader::doJob(), with m_recursively set according to the
 * user's preference, so the user can add directories or whole directory trees, too. Since we don't want to
 * rescan unchanged subdirectories, CollectionReader::readDir() checks if we are scanning recursively and
 * prevents that.
 */
void
ScanController::initIncremental()
{
    DEBUG_BLOCK

    connect( CollectionDB::instance(),
             TQT_SIGNAL( fileMoved( const TQString &, const TQString & ) ),
             TQT_SLOT( slotFileMoved( const TQString &, const TQString & ) ) );
    connect( CollectionDB::instance(),
             TQT_SIGNAL( fileMoved( const TQString &, const TQString &, const TQString & ) ),
             TQT_SLOT( slotFileMoved( const TQString &, const TQString & ) ) );

    IdList list = MountPointManager::instance()->getMountedDeviceIds();
    TQString deviceIds;
    foreachType( IdList, list )
    {
        if ( !deviceIds.isEmpty() ) deviceIds += ',';
        deviceIds += TQString::number(*it);
    }

    const TQStringList values = CollectionDB::instance()->query(
            TQString( "SELECT deviceid, dir, changedate FROM directories WHERE deviceid IN (%1);" )
            .arg( deviceIds ) );

    foreach( values )
    {
        int id = (*it).toInt();
        const TQString folder = MountPointManager::instance()->getAbsolutePath( id, (*++it) );
        const TQString mtime  = *++it;

        const TQFileInfo info( folder );
        if( info.exists() )
        {
            if( info.lastModified().toTime_t() != mtime.toUInt() )
            {
                m_folders << folder;
                debug() << "Collection dir changed: " << folder << endl;
            }
        }
        else
        {
            // this folder has been removed
            m_folders << folder;
            debug() << "Collection dir removed: " << folder << endl;
        }

        kapp->processEvents(); // Don't block the GUI
    }

    if ( !m_folders.isEmpty() )
    {
        debug() << "Collection was modified." << endl;
        m_hasChanged = true;
        Amarok::StatusBar::instance()->shortMessage( i18n( "Updating Collection..." ) );

        // Start scanner process
        if( AmarokConfig::scanRecursively() ) *m_scanner << "-r";
        *m_scanner << "-i";
        *m_scanner << m_folders;
        m_scanner->start();
    }
}


bool
ScanController::doJob()
{
    DEBUG_BLOCK

    if( !CollectionDB::instance()->isConnected() )
        return false;
    if( m_incremental && !m_hasChanged )
        return true;

    CollectionDB::instance()->createTables( true );
    m_tablesCreated = true;

    //For a full rescan, we might not have cleared tags table (for devices not plugged
    //in), so preserve the necessary other tables (eg artist)
    CollectionDB::instance()->prepareTempTables();

    CollectionDB::instance()->invalidateArtistAlbumCache();

main_loop:
    uint delayCount = 100;

    /// Main Loop
    while( !isAborted() ) {
        if( m_xmlData.isNull() ) {
            if( !m_scanner->isRunning() )
                delayCount--;
            // Wait a bit after process has exited, so that we have time to parse all data
            if( delayCount == 0 )
                break;
            msleep( 15 );
        }
        else {
            m_dataMutex.lock();

            TQDeepCopy<TQString> data = m_xmlData;
            m_source->setData( data );
            m_xmlData = TQString();

            m_dataMutex.unlock();

            if( !m_reader->parseContinue() )
                ::warning() << "parseContinue() failed: " << errorString() << endl << data << endl;
        }
    }

    if( !isAborted() ) {
        if( m_scanner->normalExit() && !m_scanner->signalled() ) {
            CollectionDB::instance()->sanitizeCompilations();
            if ( m_incremental ) {
                m_foldersToRemove += m_folders;
                foreach( m_foldersToRemove ) {
                    m_fileMapsMutex.lock();
                    CollectionDB::instance()->removeSongsInDir( *it, &m_filesDeleted );
                    m_fileMapsMutex.unlock();
                    CollectionDB::instance()->removeDirFromCollection( *it );
                }
                CollectionDB::instance()->removeOrphanedEmbeddedImages();
            }
            else
                CollectionDB::instance()->clearTables( false ); // empty permanent tables

            CollectionDB::instance()->copyTempTables(); // copy temp into permanent tables

            //Clean up unused entries in the main tables (eg artist, composer)
            CollectionDB::instance()->deleteAllRedundant( "artist" );
            CollectionDB::instance()->deleteAllRedundant( "composer" );
            CollectionDB::instance()->deleteAllRedundant( "year" );
            CollectionDB::instance()->deleteAllRedundant( "genre" );
            CollectionDB::instance()->deleteAllRedundant( "album" );

            //Remove free space and fragmentation in the DB. Used to run on shutdown, but
            //that took too long, sometimes causing Amarok to be killed.
            CollectionDB::instance()->vacuum();

        }
        else {
            if( m_crashedFiles.size() <= MAX_RESTARTS ||
                    m_crashedFiles.size() <= (m_scanCount * MAX_FAILURE_PERCENTAGE) / 100 ) {
                kapp->postEvent( this, new RestartEvent() );
                sleep( 3 );
            }
            else
                m_aborted = true;

            goto main_loop;
        }
    }

    if( CollectionDB::instance()->isConnected() )
    {
        m_tablesCreated = false;
        CollectionDB::instance()->dropTables( true ); // drop temp tables
    }

    setProgress100Percent();
    return !isAborted();
}


void
ScanController::slotReadReady()
{
    TQString line;

    m_dataMutex.lock();

    while( m_scanner->readln( line, true, 0 ) != -1 ) {
        if( !line.startsWith( "exepath=" ) ) // skip binary location info from scanner
            m_xmlData += line;
    }
    m_dataMutex.unlock();
}

bool
ScanController::requestPause()
{
    DEBUG_BLOCK
    debug() << "Attempting to pause the collection scanner..." << endl;
    DCOPRef dcopRef( "amarokcollectionscanner", "scanner" );
    m_lastCommandPaused = true;
    return dcopRef.send( "pause" );
}

bool
ScanController::requestUnpause()
{
    DEBUG_BLOCK
    debug() << "Attempting to unpause the collection scanner..." << endl;
    DCOPRef dcopRef( "amarokcollectionscanner", "scanner" );
    m_lastCommandPaused = false;
    return dcopRef.send( "unpause" );
}

void
ScanController::requestAcknowledged()
{
    DEBUG_BLOCK
    if( m_waitingBundle )
        m_waitingBundle->scannerAcknowledged();
    if( m_lastCommandPaused )
        m_isPaused = true;
    else
        m_isPaused = false;
}

void
ScanController::slotFileMoved( const TQString &/*src*/, const TQString &/*dest*/)
{
    //why is this needed?  TQBob, take a look at this
    /*
    if( m_incremental ) // pedantry
      {
        m_fileMapsMutex.lock();
        m_filesFound[ src ] = true;
        m_fileMapsMutex.unlock();
      }
    */
}

void
ScanController::notifyThisBundle( MetaBundle* bundle )
{
    DEBUG_BLOCK
    m_waitingBundle = bundle;
    debug() << "will notify " << m_waitingBundle << endl;
}

bool
ScanController::startElement( const TQString&, const TQString& localName, const TQString&, const TQXmlAttributes& attrs )
{
    // List of entity names:
    //
    // itemcount     Number of files overall
    // folder        Folder which is being processed
    // dud           Invalid audio file
    // tags          Valid audio file with metadata
    // playlist      Playlist file
    // image         Cover image
    // compilation   Folder to check for compilation
    // filesize      Size of the track in bytes


    if( localName == "dud" || localName == "tags" || localName == "playlist" ) {
        incrementProgress();
    }

    if( localName == "itemcount") {
        const int totalSteps = attrs.value( "count" ).toInt();
        debug() << "itemcount event: " << totalSteps << endl;
        setProgressTotalSteps( totalSteps );
    }

    else if( localName == "tags") {
        MetaBundle bundle;
        bundle.setPath      ( attrs.value( "path" ) );
        bundle.setTitle     ( attrs.value( "title" ) );
        bundle.setArtist    ( attrs.value( "artist" ) );
        bundle.setComposer  ( attrs.value( "composer" ) );
        bundle.setAlbum     ( attrs.value( "album" ) );
        bundle.setComment   ( attrs.value( "comment" ) );
        bundle.setGenre     ( attrs.value( "genre" ) );
        bundle.setYear      ( attrs.value( "year" ).toInt() );
        bundle.setTrack     ( attrs.value( "track" ).toInt() );
        bundle.setDiscNumber( attrs.value( "discnumber" ).toInt() );
        bundle.setBpm       ( attrs.value( "bpm" ).toFloat() );
        bundle.setFileType( attrs.value( "filetype" ).toInt() );
        bundle.setUniqueId( attrs.value( "uniqueid" ) );
        bundle.setCompilation( attrs.value( "compilation" ).toInt() );

        if( attrs.value( "audioproperties" ) == "true" ) {
            bundle.setBitrate   ( attrs.value( "bitrate" ).toInt() );
            bundle.setLength    ( attrs.value( "length" ).toInt() );
            bundle.setSampleRate( attrs.value( "samplerate" ).toInt() );
        }

        if( !attrs.value( "filesize" ).isNull()
                && !attrs.value( "filesize" ).isEmpty() )
        {
            bundle.setFilesize( attrs.value( "filesize" ).toInt() );
        }

        CollectionDB::instance()->addSong( &bundle, m_incremental );
        if( !bundle.uniqueId().isEmpty() )
        {
            m_fileMapsMutex.lock();
            m_filesAdded[bundle.uniqueId()] = bundle.url().path();
            m_fileMapsMutex.unlock();
        }

        m_scanCount++;
    }

    else if( localName == "folder" ) {
        const TQString folder = attrs.value( "path" );
        const TQFileInfo info( folder );

        // Update dir statistics for rescanning purposes
        if( info.exists() )
            CollectionDB::instance()->updateDirStats( folder, info.lastModified().toTime_t(), true);

        if( m_incremental ) {
            m_foldersToRemove += folder;
        }
    }

    else if( localName == "playlist" )
        TQApplication::postEvent( PlaylistBrowser::instance(), new PlaylistFoundEvent( attrs.value( "path" ) ) );

    else if( localName == "compilation" )
        CollectionDB::instance()->checkCompilations( attrs.value( "path" ), !m_incremental);

    else if( localName == "image" ) {
        // Deserialize CoverBundle list
        TQStringList list = TQStringList::split( "AMAROK_MAGIC", attrs.value( "list" ), true );
        TQValueList< TQPair<TQString, TQString> > covers;

        for( uint i = 0; i < list.count(); ) {
            covers += tqMakePair( list[i], list[i + 1] );
            i += 2;
        }

        CollectionDB::instance()->addImageToAlbum( attrs.value( "path" ), covers, CollectionDB::instance()->isConnected() );
    }

    else if( localName == "embed" ) {
        CollectionDB::instance()->addEmbeddedImage( attrs.value( "path" ), attrs.value( "hash" ), attrs.value( "description" ) );
    }

    return true;
}


void
ScanController::customEvent( TQCustomEvent* e )
{
    if( e->type() == RestartEventType )
    {
        debug() << "RestartEvent received." << endl;

        TQFile log( Amarok::saveLocation( TQString() ) + "collection_scan.log" );
        if ( !log.open( IO_ReadOnly ) )
        ::warning() << "Failed opening log file " << log.name() << endl;
        else {
            TQCString path = TQCString(log.readAll());
            m_crashedFiles << TQString::fromUtf8( path, path.length() );

        }

        m_dataMutex.lock();
        m_xmlData = TQString();
        delete m_source;
        m_source = new TQXmlInputSource();
        m_dataMutex.unlock();

        delete m_reader;
        m_reader = new TQXmlSimpleReader();

        m_reader->setContentHandler( this );
        m_reader->parse( m_source, true );

        delete m_scanner; // Reusing doesn't work, so we have to destroy and reinstantiate
        m_scanner = new Amarok::ProcIO();
        connect( m_scanner, TQT_SIGNAL( readReady( KProcIO* ) ), TQT_SLOT( slotReadReady() ) );

        *m_scanner << "amarokcollectionscanner";
        *m_scanner << "--nocrashhandler"; // We want to be able to catch SIGSEGV
        if( m_incremental )
            *m_scanner << "-i";

        *m_scanner << "-p";
        *m_scanner << "-s";
        m_scanner->start();
    }
    else
        ThreadManager::Job::customEvent( e );
}


#include "scancontroller.moc"