MetadataParser.cpp 32.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*****************************************************************************
 * Media Library
 *****************************************************************************
 * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs
 *
 * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

23
24
25
26
#if HAVE_CONFIG_H
# include "config.h"
#endif

27
28
29
30
31
#include "MetadataParser.h"
#include "Album.h"
#include "AlbumTrack.h"
#include "Artist.h"
#include "File.h"
32
33
34
#include "filesystem/IDevice.h"
#include "filesystem/IDirectory.h"
#include "Folder.h"
35
#include "Genre.h"
36
#include "Media.h"
37
#include "Playlist.h"
38
#include "Show.h"
39
#include "utils/Directory.h"
40
#include "utils/Filename.h"
41
#include "utils/Url.h"
42
#include "utils/ModificationsNotifier.h"
43
44
45
#include "discoverer/FsDiscoverer.h"
#include "discoverer/probe/PathProbe.h"

46
#include <cstdlib>
47

48
49
50
namespace medialibrary
{

51
MetadataParser::MetadataParser()
52
53
    : m_ml( nullptr )
    , m_previousFolderId( 0 )
54
55
56
{
}

57
bool MetadataParser::cacheUnknownArtist()
58
{
59
    m_unknownArtist = Artist::fetch( m_ml, UnknownArtistID );
60
61
62
63
64
    if ( m_unknownArtist == nullptr )
        LOG_ERROR( "Failed to cache unknown artist" );
    return m_unknownArtist != nullptr;
}

65
66
67
68
bool MetadataParser::initialize( MediaLibrary* ml)
{
    m_ml = ml;
    m_notifier = ml->getNotifier();
69
    return cacheUnknownArtist();
70
71
}

72
int MetadataParser::toInt( parser::Task& task, parser::Task::Item::Metadata meta )
73
{
74
    auto str = task.item().meta( meta );
75
76
77
78
79
80
81
82
    if ( str.empty() == false )
    {
        try
        {
            return std::stoi( str );
        }
        catch( std::logic_error& ex)
        {
83
            LOG_WARN( "Invalid meta #",
84
                      static_cast<typename std::underlying_type<parser::Task::Item::Metadata>::type>( meta ),
85
                      " provided (", str, "): ", ex.what() );
86
87
88
89
90
        }
    }
    return 0;
}

91
92
parser::Task::Status MetadataParser::run( parser::Task& task )
{
93
    bool alreadyInParser = false;
94
    int nbSubitem = task.item().subItems().size();
95
96
97
    // Assume that file containing subitem(s) is a Playlist
    if ( nbSubitem > 0 )
    {
98
        auto res = addPlaylistMedias( task );
99
100
101
        if ( res == false ) // playlist addition may fail due to constraint violation
            return parser::Task::Status::Fatal;

102
        assert( task.item().file() != nullptr );
103
        task.markStepCompleted( parser::Task::ParserStep::Completed );
104
        task.saveParserStep();
105
106
107
        return parser::Task::Status::Success;
    }

108
    if ( task.item().file() == nullptr )
109
    {
110
        assert( task.item().media() == nullptr );
111
        // Try to create Media & File
112
        auto mrl = task.item().mrl();
113
        try
114
        {
115
            auto t = m_ml->getConn()->newTransaction();
116
            LOG_INFO( "Adding ", mrl );
117
118
            auto m = Media::create( m_ml, IMedia::Type::Unknown, utils::file::fileName( mrl ) );
            if ( m == nullptr )
119
            {
120
                LOG_ERROR( "Failed to add media ", mrl, " to the media library" );
121
122
123
                return parser::Task::Status::Fatal;
            }
            // For now, assume all media are made of a single file
124
125
126
127
128
            auto file = m->addFile( *task.item().fileFs(),
                                    task.item().parentFolder()->id(),
                                    task.item().parentFolderFs()->device()->isRemovable(),
                                    File::Type::Main );
            if ( file == nullptr )
129
            {
130
                LOG_ERROR( "Failed to add file ", mrl, " to media #", m->id() );
131
132
                return parser::Task::Status::Fatal;
            }
133
134
            task.item().setMedia( std::move( m ) );
            task.item().setFile( std::move( file ) );
135
            task.updateFileId();
136
            t->commit();
137
        }
138
139
        // Voluntarily trigger an exception for a valid, but less common case, to avoid database overhead
        catch ( sqlite::errors::ConstraintViolation& ex )
140
        {
141
142
143
            LOG_INFO( "Creation of Media & File failed because ", ex.what(),
                      ". Assuming this task is a duplicate" );
            // Try to retrieve file & Media from database
144
            auto fileInDB = File::fromMrl( m_ml, mrl );
145
146
            if ( fileInDB == nullptr ) // The file is no longer present in DB, gracefully delete task
            {
147
                LOG_ERROR( "File ", mrl, " no longer present in DB, aborting");
148
149
                return parser::Task::Status::Fatal;
            }
150
151
            auto media = fileInDB->media();
            if ( media == nullptr ) // Without a media, we cannot go further
152
                return parser::Task::Status::Fatal;
153
154
155
            task.item().setFile( std::move( fileInDB ) );
            task.item().setMedia( std::move( media ) );

156
            alreadyInParser = true;
157
        }
158
    }
159
    else if ( task.item().media() == nullptr )
160
161
162
163
164
165
166
167
    {
        // If we have a file but no media, this is a problem, we can analyze as
        // much as we want, but won't be able to store anything.
        // Keep in mind that if we are in this code path, we are not analyzing
        // a playlist.
        assert( false );
        return parser::Task::Status::Fatal;
    }
168

169
170
    if ( task.item().parentPlaylist() != nullptr )
        task.item().parentPlaylist()->add( task.item().media()->id(), task.item().parentPlaylistIndex() );
171
172
173

    if ( alreadyInParser == true )
    {
174
175
        // Let the worker drop this duplicate task
        task.markStepCompleted( parser::Task::ParserStep::Completed );
176
177
        // And remove it from DB
        task.destroy( m_ml, task.id() );
178
        return parser::Task::Status::Success;
179
180
    }

181
    const auto& tracks = task.item().tracks();
182
183

    if ( tracks.empty() == true )
184
        return parser::Task::Status::Fatal;
185

186
    bool isAudio = true;
187
    {
188
189
190
        using TracksT = decltype( tracks );
        sqlite::Tools::withRetries( 3, [this, &isAudio, &task]( TracksT tracks ) {
            auto t = m_ml->getConn()->newTransaction();
191
            for ( const auto& track : tracks )
192
            {
193
                if ( track.type == parser::Task::Item::Track::Type::Video )
194
                {
195
                    task.item().media()->addVideoTrack( track.codec, track.v.width, track.v.height,
196
197
198
                                          static_cast<float>( track.v.fpsNum ) /
                                              static_cast<float>( track.v.fpsDen ),
                                          track.language, track.description );
199
200
                    isAudio = false;
                }
201
                else
202
                {
203
                    assert( track.type == parser::Task::Item::Track::Type::Audio );
204
                    task.item().media()->addAudioTrack( track.codec, track.bitrate,
205
206
                                               track.a.rate, track.a.nbChannels,
                                               track.language, track.description );
207
                }
208
            }
209
            task.item().media()->setDuration( task.item().duration() );
210
211
            t->commit();
        }, std::move( tracks ) );
212
213
214
    }
    if ( isAudio == true )
    {
215
        if ( parseAudioFile( task ) == false )
216
217
218
219
            return parser::Task::Status::Fatal;
    }
    else
    {
220
        if (parseVideoFile( task ) == false )
221
222
            return parser::Task::Status::Fatal;
    }
223

224
    if ( task.item().file()->isDeleted() == true || task.item().media()->isDeleted() == true )
225
226
        return parser::Task::Status::Fatal;

227
    task.markStepCompleted( parser::Task::ParserStep::MetadataAnalysis );
228
    if ( task.saveParserStep() == false )
229
        return parser::Task::Status::Fatal;
230
    m_notifier->notifyMediaCreation( task.item().media() );
231
232
233
    return parser::Task::Status::Success;
}

234
235
/* Playlist files */

236
bool MetadataParser::addPlaylistMedias( parser::Task& task ) const
237
238
{
    auto t = m_ml->getConn()->newTransaction();
239
240
    const auto& mrl = task.item().mrl();
    LOG_INFO( "Try to import ", mrl, " as a playlist" );
241
    auto playlistName = task.item().meta( parser::Task::Item::Metadata::Title );
242
    if ( playlistName.empty() == true )
243
        playlistName = utils::url::decode( utils::file::fileName( mrl ) );
244
245
246
    auto playlistPtr = Playlist::create( m_ml, playlistName );
    if ( playlistPtr == nullptr )
    {
247
        LOG_ERROR( "Failed to create playlist ", mrl, " to the media library" );
248
249
        return false;
    }
250
251
252
253
    auto file = playlistPtr->addFile( *task.item().fileFs(),
                                      task.item().parentFolder()->id(),
                                      task.item().parentFolderFs()->device()->isRemovable() );
    if ( file == nullptr )
254
    {
255
        LOG_ERROR( "Failed to add playlist file ", mrl );
256
257
        return false;
    }
258
    task.item().setFile( std::move( file ) );
259
    t->commit();
260
    auto subitems = task.item().subItems();
261
262
    for ( const auto& subItem : subitems ) // FIXME: Interrupt loop if paused
        addPlaylistElement( task, playlistPtr, subItem );
263
264
265
266

    return true;
}

267
void MetadataParser::addPlaylistElement( parser::Task& task, std::shared_ptr<Playlist> playlistPtr,
268
                                         const parser::Task::Item& subitem ) const
269
{
270
    const auto& mrl = subitem.mrl();
271
    LOG_INFO( "Try to add ", mrl, " to the playlist ", mrl );
272
273
274
    auto media = m_ml->media( mrl );
    if ( media != nullptr )
    {
275
        LOG_INFO( "Media for ", mrl, " already exists, adding it to the playlist ", mrl );
276
        playlistPtr->add( media->id(), subitem.parentPlaylistIndex() );
277
278
279
280
281
282
283
284
285
        return;
    }
    // Create Media, etc.
    auto fsFactory = m_ml->fsFactoryForMrl( mrl );

    if ( fsFactory == nullptr ) // Media not supported by any FsFactory, registering it as external
    {
        auto t2 = m_ml->getConn()->newTransaction();
        auto externalMedia = Media::create( m_ml, IMedia::Type::Unknown, utils::url::encode(
286
                subitem.meta( parser::Task::Item::Metadata::Title ) ) );
287
288
        if ( externalMedia == nullptr )
        {
289
            LOG_ERROR( "Failed to create external media for ", mrl, " in the playlist ", task.item().mrl() );
290
291
292
293
294
            return;
        }
        // Assuming that external mrl present in playlist file is a main media resource
        auto externalFile = externalMedia->addExternalMrl( mrl, IFile::Type::Main );
        if ( externalFile == nullptr )
295
            LOG_ERROR( "Failed to create external file for ", mrl, " in the playlist ", task.item().mrl() );
296
        playlistPtr->add( externalMedia->id(), subitem.parentPlaylistIndex() );
297
298
299
300
301
302
303
304
305
306
307
308
309
        t2->commit();
        return;
    }
    bool isDirectory;
    try
    {
        isDirectory = utils::fs::isDirectory( utils::file::toLocalPath( mrl ) );
    }
    catch ( std::system_error& ex )
    {
        LOG_ERROR( ex.what() );
        return;
    }
310
    LOG_INFO( "Importing ", isDirectory ? "folder " : "file ", mrl, " in the playlist ", task.item().mrl() );
311
312
313
314
    auto directoryMrl = utils::file::directory( mrl );
    auto parentFolder = Folder::fromMrl( m_ml, directoryMrl );
    bool parentKnown = parentFolder != nullptr;

315
316
317
318
319
320
321
322
    // The minimal entrypoint must be a device mountpoint
    auto device = fsFactory->createDeviceFromMrl( mrl );
    if ( device == nullptr )
    {
        LOG_ERROR( "Can't add a local folder with unknown storage device. ");
        return;
    }
    auto entryPoint = device->mountpoint();
323
324
    if ( parentKnown == false && Folder::fromMrl( m_ml, entryPoint ) != nullptr )
    {
325
326
327
328
        auto probePtr = std::unique_ptr<prober::PathProbe>(
                    new prober::PathProbe{ utils::file::stripScheme( mrl ),
                       isDirectory, std::move( playlistPtr ), parentFolder,
                       utils::file::stripScheme( directoryMrl ), subitem.parentPlaylistIndex(), true } );
329
        FsDiscoverer discoverer( fsFactory, m_ml, nullptr, std::move( probePtr ) );
330
331
332
        discoverer.reload( entryPoint );
        return;
    }
333
334
335
336
    auto probePtr = std::unique_ptr<prober::PathProbe>(
                new prober::PathProbe{ utils::file::stripScheme( mrl ),
                   isDirectory, std::move( playlistPtr ), parentFolder,
                   utils::file::stripScheme( directoryMrl ), subitem.parentPlaylistIndex(), false } );
337
    FsDiscoverer discoverer( fsFactory, m_ml, nullptr, std::move( probePtr ) );
338
339
340
    if ( parentKnown == false )
    {
        discoverer.discover( entryPoint );
341
342
343
        auto entryFolder = Folder::fromMrl( m_ml, entryPoint );
        if ( entryFolder != nullptr )
            Folder::excludeEntryFolder( m_ml, entryFolder->id() );
344
345
346
347
348
        return;
    }
    discoverer.reload( directoryMrl );
}

349
350
/* Video files */

351
bool MetadataParser::parseVideoFile( parser::Task& task ) const
352
{
353
    auto media = task.item().media().get();
354
    media->setType( IMedia::Type::Video );
355
    const auto& title = task.item().meta( parser::Task::Item::Metadata::Title );
356
    if ( title.length() == 0 )
357
        return true;
358

359
360
    const auto& showName = task.item().meta( parser::Task::Item::Metadata::ShowName );
    const auto& artworkMrl = task.item().meta( parser::Task::Item::Metadata::ArtworkUrl );
361

362
    return sqlite::Tools::withRetries( 3, [this, &showName, &title, &task, &artworkMrl]() {
363
        auto t = m_ml->getConn()->newTransaction();
364
        task.item().media()->setTitleBuffered( title );
365

366
        if ( artworkMrl.empty() == false )
367
            task.item().media()->setThumbnail( artworkMrl, Thumbnail::Origin::Media );
368

369
370
        if ( showName.length() != 0 )
        {
371
            auto show = m_ml->show( showName );
372
            if ( show == nullptr )
373
374
375
376
377
            {
                show = m_ml->createShow( showName );
                if ( show == nullptr )
                    return false;
            }
378
            auto episode = toInt( task, parser::Task::Item::Metadata::Episode );
379
380
381
            if ( episode != 0 )
            {
                std::shared_ptr<Show> s = std::static_pointer_cast<Show>( show );
382
                s->addEpisode( *task.item().media(), title, episode );
383
            }
384
385
386
387
388
        }
        else
        {
            // How do we know if it's a movie or a random video?
        }
389
        task.item().media()->save();
390
391
392
        t->commit();
        return true;
    });
393
394
395
396
397
    return true;
}

/* Audio files */

398
bool MetadataParser::parseAudioFile( parser::Task& task )
399
{
400
    task.item().media()->setType( IMedia::Type::Audio );
401

402
    auto artworkMrl = task.item().meta( parser::Task::Item::Metadata::ArtworkUrl );
403
    if ( artworkMrl.empty() == false )
404
    {
405
        task.item().media()->setThumbnail( artworkMrl, Thumbnail::Origin::Media );
406
407
408
409
410
        // Don't use an attachment as default artwork for album/artists
        if ( utils::file::schemeIs( "attachment", artworkMrl ) )
            artworkMrl.clear();
    }

411

412
    auto genre = handleGenre( task );
413
    auto artists = findOrCreateArtist( task );
414
415
    if ( artists.first == nullptr && artists.second == nullptr )
        return false;
416
    auto album = findAlbum( task, artists.first, artists.second );
417
418
419
    return sqlite::Tools::withRetries( 3, [this, &task, &artists]( std::string artworkMrl,
                                                  std::shared_ptr<Album> album, std::shared_ptr<Genre> genre ) {
        auto t = m_ml->getConn()->newTransaction();
420
        if ( album == nullptr )
421
        {
422
            const auto& albumName = task.item().meta( parser::Task::Item::Metadata::Album );
423
424
425
426
427
428
429
430
431
            int64_t thumbnailId = 0;
            if ( artworkMrl.empty() == false )
            {
                auto thumbnail = Thumbnail::create( m_ml, artworkMrl,
                                                    Thumbnail::Origin::Album );
                if ( thumbnail != nullptr )
                    thumbnailId = thumbnail->id();
            }
            album = m_ml->createAlbum( albumName, thumbnailId );
432
433
434
435
436
437
438
439
            if ( album == nullptr )
                return false;
            m_notifier->notifyAlbumCreation( album );
        }
        // If we know a track artist, specify it, otherwise, fallback to the album/unknown artist
        auto track = handleTrack( album, task, artists.second ? artists.second : artists.first,
                                  genre.get() );

440
441
        auto res = link( *task.item().media(), album, artists.first, artists.second );
        task.item().media()->save();
442
443
444
        t->commit();
        return res;
    }, std::move( artworkMrl ), std::move( album ), std::move( genre ) );
445
446
}

447
448
std::shared_ptr<Genre> MetadataParser::handleGenre( parser::Task& task ) const
{
449
    const auto& genreStr = task.item().meta( parser::Task::Item::Metadata::Genre );
450
    if ( genreStr.length() == 0 )
451
        return nullptr;
452
    auto genre = Genre::fromName( m_ml, genreStr );
453
454
    if ( genre == nullptr )
    {
455
        genre = Genre::create( m_ml, genreStr );
456
        if ( genre == nullptr )
457
            LOG_ERROR( "Failed to get/create Genre", genreStr );
458
459
460
461
    }
    return genre;
}

462
/* Album handling */
463
464

std::shared_ptr<Album> MetadataParser::findAlbum( parser::Task& task, std::shared_ptr<Artist> albumArtist,
465
                                                    std::shared_ptr<Artist> trackArtist )
466
{
467
    const auto& albumName = task.item().meta( parser::Task::Item::Metadata::Album );
468
    if ( albumName.empty() == true )
469
    {
470
471
        if ( albumArtist != nullptr )
            return albumArtist->unknownAlbum();
472
        if ( trackArtist != nullptr )
473
474
            return trackArtist->unknownAlbum();
        return m_unknownArtist->unknownAlbum();
475
476
    }

477
    if ( m_previousAlbum != nullptr && albumName == m_previousAlbum->title() &&
478
         m_previousFolderId != 0 && task.item().file()->folderId() == m_previousFolderId )
479
480
481
482
        return m_previousAlbum;
    m_previousAlbum.reset();
    m_previousFolderId = 0;

483
484
    // Album matching depends on the difference between artist & album artist.
    // Specificaly pass the albumArtist here.
485
486
    static const std::string req = "SELECT * FROM " + policy::AlbumTable::Name +
            " WHERE title = ?";
487
    auto albums = Album::fetchAll<Album>( m_ml, req, albumName );
488
489
490
491

    if ( albums.size() == 0 )
        return nullptr;

492
493
    const auto discTotal = toInt( task, parser::Task::Item::Metadata::DiscTotal );
    const auto discNumber = toInt( task, parser::Task::Item::Metadata::DiscNumber );
494
495
496
497
498
    /*
     * Even if we get only 1 album, we need to filter out invalid matches.
     * For instance, if we have already inserted an album "A" by an artist "john"
     * but we are now trying to handle an album "A" by an artist "doe", not filtering
     * candidates would yield the only "A" album we know, while we should return
499
     * nullptr, so the link() method can create a new one.
500
501
502
503
     */
    for ( auto it = begin( albums ); it != end( albums ); )
    {
        auto a = (*it).get();
504
        auto candidateAlbumArtist = a->albumArtist();
505
506
507
508
        // When we find an album, we will systematically assign an artist to it.
        // Not having an album artist (even it it's only a temporary one in the
        // case of a compilation album) is not expected at all.
        assert( candidateAlbumArtist != nullptr );
509
510
511
512
        if ( albumArtist != nullptr )
        {
            // We assume that an album without album artist is a positive match.
            // At the end of the day, without proper tags, there's only so much we can do.
513
            if ( candidateAlbumArtist->id() != albumArtist->id() )
514
515
516
517
518
519
520
521
522
523
524
            {
                it = albums.erase( it );
                continue;
            }
        }
        // If this is a multidisc album, assume it could be in a multiple amount of folders.
        // Since folders can come in any order, we can't assume the first album will be the
        // first media we see. If the discTotal or discNumber meta are provided, that's easy. If not,
        // we assume that another CD with the same name & artists, and a disc number > 1
        // denotes a multi disc album
        // Check the first case early to avoid fetching tracks if unrequired.
525
        if ( discTotal > 1 || discNumber > 1 )
526
527
528
529
        {
            ++it;
            continue;
        }
530
        const auto tracks = a->cachedTracks();
531
532
533
534
535
536
537
        // If there is no tracks to compare with, we just have to hope this will be the only valid
        // album match
        if ( tracks.size() == 0 )
        {
            ++it;
            continue;
        }
538
539

        auto multiDisc = false;
540
541
        auto multipleArtists = false;
        int64_t previousArtistId = trackArtist != nullptr ? trackArtist->id() : 0;
542
543
544
545
        for ( auto& t : tracks )
        {
            auto at = t->albumTrack();
            assert( at != nullptr );
546
547
548
            if ( at == nullptr )
                continue;
            if ( at->discNumber() > 1 )
549
                multiDisc = true;
550
551
552
553
554
            if ( previousArtistId != 0 && previousArtistId != at->artist()->id() )
                multipleArtists = true;
            previousArtistId = at->artist()->id();
            // We now know enough about the album, we can stop looking at its tracks
            if ( multiDisc == true && multipleArtists == true )
555
556
557
558
559
560
561
562
                break;
        }
        if ( multiDisc )
        {
            ++it;
            continue;
        }

563
        // Assume album files will be in the same folder.
564
        auto newFileFolder = utils::file::directory( task.item().file()->mrl() );
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
        auto trackFiles = tracks[0]->files();
        bool differentFolder = false;
        for ( auto& f : trackFiles )
        {
            auto candidateFolder = utils::file::directory( f->mrl() );
            if ( candidateFolder != newFileFolder )
            {
                differentFolder = true;
                break;
            }
        }
        // We now have a candidate by the same artist in the same folder, assume it to be
        // a positive match.
        if ( differentFolder == false )
        {
            ++it;
            continue;
        }

584
585
586
587
        // Attempt to discriminate by date, but only for the same artists.
        // Not taking the artist in consideration would cause compilation to
        // create multiple albums, especially when track are only partially
        // tagged with a year.
588
        if ( multipleArtists == false )
589
        {
590
            auto candidateDate = task.item().meta( parser::Task::Item::Metadata::Date );
591
            if ( candidateDate.empty() == false )
592
            {
593
594
595
596
597
598
599
600
601
602
603
604
605
                try
                {
                    unsigned int year = std::stoi( candidateDate );
                    if ( year != a->releaseYear() )
                        it = albums.erase( it );
                    else
                        ++it;
                    continue;
                }
                catch (...)
                {
                    // Date wasn't helpful, simply ignore the error and continue
                }
606
607
            }
        }
608
609
610
611
612
613
614
615
616
        // The candidate is :
        // - in a different folder
        // - not a multidisc album
        // - Either:
        //      - from the same artist & without a date to discriminate
        //      - from the same artist & with a different date
        //      - from different artists
        // Assume it's a negative match.
        it = albums.erase( it );
617
618
619
620
621
    }
    if ( albums.size() == 0 )
        return nullptr;
    if ( albums.size() > 1 )
    {
622
        LOG_WARN( "Multiple candidates for album ", albumName, ". Selecting first one out of luck" );
623
    }
624
    m_previousFolderId = task.item().file()->folderId();
625
626
    m_previousAlbum = albums[0];
    return albums[0];
627
628
629
630
}

///
/// \brief MetadataParser::handleArtists Returns Artist's involved on a track
631
/// \param task The current parser task
632
633
634
635
/// \return A pair containing:
/// The album artist as a first element
/// The track artist as a second element, or nullptr if it is the same as album artist
///
636
std::pair<std::shared_ptr<Artist>, std::shared_ptr<Artist>> MetadataParser::findOrCreateArtist( parser::Task& task ) const
637
638
639
{
    std::shared_ptr<Artist> albumArtist;
    std::shared_ptr<Artist> artist;
640
    static const std::string req = "SELECT * FROM " + policy::ArtistTable::Name + " WHERE name = ?";
641

642
643
    const auto& albumArtistStr = task.item().meta( parser::Task::Item::Metadata::AlbumArtist );
    const auto& artistStr = task.item().meta( parser::Task::Item::Metadata::Artist );
644
    if ( albumArtistStr.empty() == true && artistStr.empty() == true )
645
    {
646
        return {m_unknownArtist, m_unknownArtist};
647
648
    }

649
    if ( albumArtistStr.empty() == false )
650
    {
651
        albumArtist = Artist::fetch( m_ml, req, albumArtistStr );
652
653
        if ( albumArtist == nullptr )
        {
654
            albumArtist = m_ml->createArtist( albumArtistStr );
655
656
            if ( albumArtist == nullptr )
            {
657
                LOG_ERROR( "Failed to create new artist ", albumArtistStr );
658
659
                return {nullptr, nullptr};
            }
660
            m_notifier->notifyArtistCreation( albumArtist );
661
662
        }
    }
663
    if ( artistStr.empty() == false && artistStr != albumArtistStr )
664
    {
665
        artist = Artist::fetch( m_ml, req, artistStr );
666
667
        if ( artist == nullptr )
        {
668
            artist = m_ml->createArtist( artistStr );
669
670
            if ( artist == nullptr )
            {
671
                LOG_ERROR( "Failed to create new artist ", artistStr );
672
673
                return {nullptr, nullptr};
            }
674
            m_notifier->notifyArtistCreation( artist );
675
676
677
678
679
680
681
        }
    }
    return {albumArtist, artist};
}

/* Tracks handling */

682
683
std::shared_ptr<AlbumTrack> MetadataParser::handleTrack( std::shared_ptr<Album> album, parser::Task& task,
                                                         std::shared_ptr<Artist> artist, Genre* genre ) const
684
{
685
686
    assert( sqlite::Transaction::transactionInProgress() == true );

687
688
689
    auto title = task.item().meta( parser::Task::Item::Metadata::Title );
    const auto trackNumber = toInt( task, parser::Task::Item::Metadata::TrackNumber );
    const auto discNumber = toInt( task, parser::Task::Item::Metadata::DiscNumber );
690
691
692
    if ( title.empty() == true )
    {
        LOG_WARN( "Failed to get track title" );
693
        if ( trackNumber != 0 )
694
695
        {
            title = "Track #";
696
            title += std::to_string( trackNumber );
697
698
699
        }
    }
    if ( title.empty() == false )
700
        task.item().media()->setTitleBuffered( title );
701

702
    auto track = std::static_pointer_cast<AlbumTrack>( album->addTrack( task.item().media(), trackNumber,
703
                                                                        discNumber, artist->id(),
704
                                                                        genre ) );
705
706
707
708
709
    if ( track == nullptr )
    {
        LOG_ERROR( "Failed to create album track" );
        return nullptr;
    }
710

711
    const auto& releaseDate = task.item().meta( parser::Task::Item::Metadata::Date );
712
    if ( releaseDate.empty() == false )
713
    {
714
        auto releaseYear = atoi( releaseDate.c_str() );
715
        task.item().media()->setReleaseDate( releaseYear );
716
717
718
719
720
        // Let the album handle multiple dates. In order to do this properly, we need
        // to know if the date has been changed before, which can be known only by
        // using Album class internals.
        album->setReleaseYear( releaseYear, false );
    }
721
    m_notifier->notifyAlbumTrackCreation( track );
722
723
724
725
726
727
    return track;
}

/* Misc */

bool MetadataParser::link( Media& media, std::shared_ptr<Album> album,
728
                               std::shared_ptr<Artist> albumArtist, std::shared_ptr<Artist> artist )
729
{
730
    if ( albumArtist == nullptr )
731
732
    {
        assert( artist != nullptr );
733
        albumArtist = artist;
734
    }
735
    assert( album != nullptr );
736

737
738
    auto albumThumbnail = album->thumbnail();

739
740
741
742
    // We might modify albumArtist later, hence handle thumbnails before.
    // If we have an albumArtist (meaning the track was properly tagged, we
    // can assume this artist is a correct match. We can use the thumbnail from
    // the current album for the albumArtist, if none has been set before.
743
744
745
746
    // Although we don't want to do this for unknown/various artists, as the
    // thumbnail wouldn't reflect those "special" artists
    if ( albumArtist != nullptr && albumArtist->id() != UnknownArtistID &&
         albumArtist->id() != VariousArtistID &&
747
748
749
750
751
752
753
754
755
756
757
758
759
760
         albumThumbnail != nullptr )
    {
        auto albumArtistThumbnail = albumArtist->thumbnail();
        // If the album artist has no thumbnail, let's assign it
        if ( albumArtistThumbnail == nullptr )
        {
            albumArtist->setArtworkMrl( albumThumbnail->mrl(), Thumbnail::Origin::AlbumArtist );
        }
        else if ( albumArtistThumbnail->origin() == Thumbnail::Origin::Artist )
        {
            // We only want to change the thumbnail if it was assigned from an
            // album this artist was only featuring on
        }
    }
761

762
763
764
765
    // Until we have a better artwork extraction/assignation, simply do the same
    // for artists
    if ( artist != nullptr && artist->id() != UnknownArtistID &&
         artist->id() != VariousArtistID &&
766
767
768
769
         albumThumbnail != nullptr && artist->thumbnail() == nullptr )
    {
        artist->setArtworkMrl( album->artworkMrl(), Thumbnail::Origin::Artist );
    }
770

771
772
773
774
775
776
777
778
779
780
781
782
783
    if ( albumArtist != nullptr )
        albumArtist->addMedia( media );
    if ( artist != nullptr && ( albumArtist == nullptr || albumArtist->id() != artist->id() ) )
        artist->addMedia( media );

    auto currentAlbumArtist = album->albumArtist();

    // If we have no main artist yet, that's easy, we need to assign one.
    if ( currentAlbumArtist == nullptr )
    {
        // We don't know if the artist was tagged as artist or albumartist, however, we simply add it
        // as the albumartist until proven we were wrong (ie. until one of the next tracks
        // has a different artist)
784
        album->setAlbumArtist( albumArtist );
785
786
        // Always add the album artist as an artist
        album->addArtist( albumArtist );
787
788
789
        // Always update the album artist number of tracks.
        // The artist might be different, and will be handled a few lines below
        albumArtist->updateNbTrack( 1 );
790
        if ( artist != nullptr )
791
792
793
794
795
        {
            // If the album artist is not the artist, we need to update the
            // album artist track count as well.
            if ( albumArtist->id() != artist->id() )
                artist->updateNbTrack( 1 );
796
            album->addArtist( artist );
797
        }
798
799
800
    }
    else
    {
801
        // We have more than a single artist on this album, fallback to various artists
802
803
        if ( albumArtist->id() != currentAlbumArtist->id() )
        {
804
805
            if ( m_variousArtists == nullptr )
                m_variousArtists = Artist::fetch( m_ml, VariousArtistID );
806
807
808
809
810
811
812
813
814
815
816
817
818
819
            // If we already switched to various artist, no need to do it again
            if ( m_variousArtists->id() != currentAlbumArtist->id() )
            {
                // All tracks from this album must now also be reflected in various
                // artist number of tracks
                m_variousArtists->updateNbTrack( album->nbTracks() );
                album->setAlbumArtist( m_variousArtists );
            }
            // However we always need to bump the various artist number of tracks
            else
            {
                m_variousArtists->updateNbTrack( 1 );
            }
            // Add this artist as "featuring".
820
821
822
823
            album->addArtist( albumArtist );
        }
        if ( artist != nullptr && artist->id() != albumArtist->id() )
        {
824
825
           album->addArtist( artist );
           artist->updateNbTrack( 1 );
826
        }
827
        albumArtist->updateNbTrack( 1 );
828
829
830
831
832
833
834
835
836
    }

    return true;
}

const char* MetadataParser::name() const
{
    return "Metadata";
}
837
838
839
840
841
842
843
844
845
846

uint8_t MetadataParser::nbThreads() const
{
//    auto nbProcs = std::thread::hardware_concurrency();
//    if ( nbProcs == 0 )
//        return 1;
//    return nbProcs;
    // Let's make this code thread-safe first :)
    return 1;
}
847

848
void MetadataParser::onFlushing()
849
850
851
852
853
854
{
    m_variousArtists = nullptr;
    m_previousAlbum = nullptr;
    m_previousFolderId = 0;
}

855
void MetadataParser::onRestarted()
856
857
{
    // Reset locally cached entities
858
    cacheUnknownArtist();
859
860
}

861
bool MetadataParser::isCompleted( const parser::Task& task ) const
862
{
863
    // We always need to run this task if the metadata extraction isn't completed
864
    return task.isStepCompleted( parser::Task::ParserStep::MetadataAnalysis );
865
866
}

867
}