Fixed bad optimize condition

This commit is contained in:
emeric
2023-11-08 20:16:31 +01:00
parent 6bb6dd6add
commit c2e1c5d9df
@@ -37,500 +37,500 @@ using namespace Database;
namespace namespace
{ {
Artist::pointer Artist::pointer
createArtist(Session& session, const MetaData::Artist& artistInfo) createArtist(Session& session, const MetaData::Artist& artistInfo)
{ {
Artist::pointer artist {session.create<Artist>(artistInfo.name)}; Artist::pointer artist{ session.create<Artist>(artistInfo.name) };
if (artistInfo.mbid) if (artistInfo.mbid)
artist.modify()->setMBID(*artistInfo.mbid); artist.modify()->setMBID(*artistInfo.mbid);
if (artistInfo.sortName) if (artistInfo.sortName)
artist.modify()->setSortName(*artistInfo.sortName); artist.modify()->setSortName(*artistInfo.sortName);
return artist; return artist;
} }
void void
updateArtistIfNeeded(Artist::pointer artist, const MetaData::Artist& artistInfo) updateArtistIfNeeded(Artist::pointer artist, const MetaData::Artist& artistInfo)
{ {
// Name may have been updated // Name may have been updated
if (artist->getName() != artistInfo.name) if (artist->getName() != artistInfo.name)
{ {
artist.modify()->setName(artistInfo.name); artist.modify()->setName(artistInfo.name);
} }
// Sortname may have been updated // Sortname may have been updated
if (artistInfo.sortName && *artistInfo.sortName != artist->getSortName() ) if (artistInfo.sortName && *artistInfo.sortName != artist->getSortName())
{ {
artist.modify()->setSortName(*artistInfo.sortName); artist.modify()->setSortName(*artistInfo.sortName);
} }
} }
std::vector<Artist::pointer> std::vector<Artist::pointer>
getOrCreateArtists(Session& session, const std::vector<MetaData::Artist>& artistsInfo, bool allowFallbackOnMBIDEntries) getOrCreateArtists(Session& session, const std::vector<MetaData::Artist>& artistsInfo, bool allowFallbackOnMBIDEntries)
{ {
std::vector<Artist::pointer> artists; std::vector<Artist::pointer> artists;
for (const MetaData::Artist& artistInfo : artistsInfo) for (const MetaData::Artist& artistInfo : artistsInfo)
{ {
Artist::pointer artist; Artist::pointer artist;
// First try to get by MBID // First try to get by MBID
if (artistInfo.mbid) if (artistInfo.mbid)
{ {
artist = Artist::find(session, *artistInfo.mbid); artist = Artist::find(session, *artistInfo.mbid);
if (!artist) if (!artist)
artist = createArtist(session, artistInfo); artist = createArtist(session, artistInfo);
else else
updateArtistIfNeeded(artist, artistInfo); updateArtistIfNeeded(artist, artistInfo);
artists.emplace_back(std::move(artist)); artists.emplace_back(std::move(artist));
continue; continue;
} }
// Fall back on artist name (collisions may occur) // Fall back on artist name (collisions may occur)
if (!artistInfo.name.empty()) if (!artistInfo.name.empty())
{ {
for (const Artist::pointer& sameNamedArtist : Artist::find(session, artistInfo.name)) for (const Artist::pointer& sameNamedArtist : Artist::find(session, artistInfo.name))
{ {
// Do not fallback on artist that is correctly tagged // Do not fallback on artist that is correctly tagged
if (!allowFallbackOnMBIDEntries && sameNamedArtist->getMBID()) if (!allowFallbackOnMBIDEntries && sameNamedArtist->getMBID())
continue; continue;
artist = sameNamedArtist; artist = sameNamedArtist;
break; break;
} }
// No Artist found with the same name and without MBID -> creating // No Artist found with the same name and without MBID -> creating
if (!artist) if (!artist)
artist = createArtist(session, artistInfo); artist = createArtist(session, artistInfo);
else else
updateArtistIfNeeded(artist, artistInfo); updateArtistIfNeeded(artist, artistInfo);
artists.emplace_back(std::move(artist)); artists.emplace_back(std::move(artist));
continue; continue;
} }
} }
return artists; return artists;
} }
ReleaseTypePrimary convertReleaseTypePrimary(MetaData::Release::PrimaryType type) ReleaseTypePrimary convertReleaseTypePrimary(MetaData::Release::PrimaryType type)
{ {
switch (type) switch (type)
{ {
case MetaData::Release::PrimaryType::Album: return ReleaseTypePrimary::Album; case MetaData::Release::PrimaryType::Album: return ReleaseTypePrimary::Album;
case MetaData::Release::PrimaryType::Single: return ReleaseTypePrimary::Single; case MetaData::Release::PrimaryType::Single: return ReleaseTypePrimary::Single;
case MetaData::Release::PrimaryType::EP: return ReleaseTypePrimary::EP; case MetaData::Release::PrimaryType::EP: return ReleaseTypePrimary::EP;
case MetaData::Release::PrimaryType::Broadcast: return ReleaseTypePrimary::Broadcast; case MetaData::Release::PrimaryType::Broadcast: return ReleaseTypePrimary::Broadcast;
case MetaData::Release::PrimaryType::Other: return ReleaseTypePrimary::Other; case MetaData::Release::PrimaryType::Other: return ReleaseTypePrimary::Other;
} }
return ReleaseTypePrimary::Other; return ReleaseTypePrimary::Other;
} }
EnumSet<ReleaseTypeSecondary> convertReleaseTypesSecondary(EnumSet<MetaData::Release::SecondaryType> types) EnumSet<ReleaseTypeSecondary> convertReleaseTypesSecondary(EnumSet<MetaData::Release::SecondaryType> types)
{ {
EnumSet<ReleaseTypeSecondary> res; EnumSet<ReleaseTypeSecondary> res;
for (MetaData::Release::SecondaryType type : types) for (MetaData::Release::SecondaryType type : types)
{ {
switch (type) switch (type)
{ {
case MetaData::Release::SecondaryType::Compilation: case MetaData::Release::SecondaryType::Compilation:
res.insert(ReleaseTypeSecondary::Compilation); res.insert(ReleaseTypeSecondary::Compilation);
break; break;
case MetaData::Release::SecondaryType::Soundtrack: case MetaData::Release::SecondaryType::Soundtrack:
res.insert(ReleaseTypeSecondary::Soundtrack); res.insert(ReleaseTypeSecondary::Soundtrack);
break; break;
case MetaData::Release::SecondaryType::Spokenword: case MetaData::Release::SecondaryType::Spokenword:
res.insert(ReleaseTypeSecondary::Spokenword); res.insert(ReleaseTypeSecondary::Spokenword);
break; break;
case MetaData::Release::SecondaryType::Interview: case MetaData::Release::SecondaryType::Interview:
res.insert(ReleaseTypeSecondary::Interview); res.insert(ReleaseTypeSecondary::Interview);
break; break;
case MetaData::Release::SecondaryType::Audiobook: case MetaData::Release::SecondaryType::Audiobook:
res.insert(ReleaseTypeSecondary::Audiobook); res.insert(ReleaseTypeSecondary::Audiobook);
break; break;
case MetaData::Release::SecondaryType::AudioDrama: case MetaData::Release::SecondaryType::AudioDrama:
res.insert(ReleaseTypeSecondary::AudioDrama); res.insert(ReleaseTypeSecondary::AudioDrama);
break; break;
case MetaData::Release::SecondaryType::Live: case MetaData::Release::SecondaryType::Live:
res.insert(ReleaseTypeSecondary::Live); res.insert(ReleaseTypeSecondary::Live);
break; break;
case MetaData::Release::SecondaryType::Remix: case MetaData::Release::SecondaryType::Remix:
res.insert(ReleaseTypeSecondary::Remix); res.insert(ReleaseTypeSecondary::Remix);
break; break;
case MetaData::Release::SecondaryType::DJMix: case MetaData::Release::SecondaryType::DJMix:
res.insert(ReleaseTypeSecondary::DJMix); res.insert(ReleaseTypeSecondary::DJMix);
break; break;
case MetaData::Release::SecondaryType::Mixtape_Street: case MetaData::Release::SecondaryType::Mixtape_Street:
res.insert(ReleaseTypeSecondary::Mixtape_Street); res.insert(ReleaseTypeSecondary::Mixtape_Street);
break; break;
case MetaData::Release::SecondaryType::Demo: case MetaData::Release::SecondaryType::Demo:
res.insert(ReleaseTypeSecondary::Demo); res.insert(ReleaseTypeSecondary::Demo);
break; break;
} }
} }
return res; return res;
} }
void void
updateReleaseIfNeeded(Release::pointer release, const MetaData::Release& releaseInfo) updateReleaseIfNeeded(Release::pointer release, const MetaData::Release& releaseInfo)
{ {
if (release->getName() != releaseInfo.name) if (release->getName() != releaseInfo.name)
release.modify()->setName(releaseInfo.name); release.modify()->setName(releaseInfo.name);
if (release->getTotalDisc() != releaseInfo.mediumCount) if (release->getTotalDisc() != releaseInfo.mediumCount)
release.modify()->setTotalDisc(releaseInfo.mediumCount); release.modify()->setTotalDisc(releaseInfo.mediumCount);
if (releaseInfo.primaryType) if (releaseInfo.primaryType)
{ {
const ReleaseTypePrimary primaryType {convertReleaseTypePrimary(*releaseInfo.primaryType)}; const ReleaseTypePrimary primaryType{ convertReleaseTypePrimary(*releaseInfo.primaryType) };
if (release->getPrimaryType() != primaryType) if (release->getPrimaryType() != primaryType)
release.modify()->setPrimaryType(primaryType); release.modify()->setPrimaryType(primaryType);
} }
const EnumSet<ReleaseTypeSecondary> secondaryTypes{ convertReleaseTypesSecondary(releaseInfo.secondaryTypes) }; const EnumSet<ReleaseTypeSecondary> secondaryTypes{ convertReleaseTypesSecondary(releaseInfo.secondaryTypes) };
if (release->getSecondaryTypes() != secondaryTypes) if (release->getSecondaryTypes() != secondaryTypes)
release.modify()->setSecondaryTypes(secondaryTypes); release.modify()->setSecondaryTypes(secondaryTypes);
if (release->getArtistDisplayName() != releaseInfo.artistDisplayName) if (release->getArtistDisplayName() != releaseInfo.artistDisplayName)
release.modify()->setArtistDisplayName(releaseInfo.artistDisplayName); release.modify()->setArtistDisplayName(releaseInfo.artistDisplayName);
} }
Release::pointer Release::pointer
getOrCreateRelease(Session& session, const MetaData::Release& releaseInfo) getOrCreateRelease(Session& session, const MetaData::Release& releaseInfo)
{ {
Release::pointer release; Release::pointer release;
// First try to get by MBID // First try to get by MBID
if (releaseInfo.mbid) if (releaseInfo.mbid)
{ {
release = Release::find(session, *releaseInfo.mbid); release = Release::find(session, *releaseInfo.mbid);
if (!release) if (!release)
release = session.create<Release>(releaseInfo.name, releaseInfo.mbid); release = session.create<Release>(releaseInfo.name, releaseInfo.mbid);
updateReleaseIfNeeded(release, releaseInfo); updateReleaseIfNeeded(release, releaseInfo);
return release; return release;
} }
// Fall back on release name (collisions may occur) // Fall back on release name (collisions may occur)
if (!releaseInfo.name.empty()) if (!releaseInfo.name.empty())
{ {
for (const Release::pointer& sameNamedRelease : Release::find(session, releaseInfo.name)) for (const Release::pointer& sameNamedRelease : Release::find(session, releaseInfo.name))
{ {
// do not fallback on properly tagged releases // do not fallback on properly tagged releases
if (sameNamedRelease->getMBID()) if (sameNamedRelease->getMBID())
continue; continue;
release = sameNamedRelease; release = sameNamedRelease;
break; break;
} }
// No release found with the same name and without MBID -> creating // No release found with the same name and without MBID -> creating
if (!release) if (!release)
release = session.create<Release>(releaseInfo.name); release = session.create<Release>(releaseInfo.name);
updateReleaseIfNeeded(release, releaseInfo); updateReleaseIfNeeded(release, releaseInfo);
return release; return release;
} }
return Release::pointer{}; return Release::pointer{};
} }
std::vector<Cluster::pointer> std::vector<Cluster::pointer>
getOrCreateClusters(Session& session, const MetaData::Tags& tags) getOrCreateClusters(Session& session, const MetaData::Tags& tags)
{ {
std::vector<Cluster::pointer> clusters; std::vector<Cluster::pointer> clusters;
for (const auto& [tag, values] : tags) for (const auto& [tag, values] : tags)
{ {
auto clusterType = ClusterType::find(session, tag); auto clusterType = ClusterType::find(session, tag);
if (!clusterType) if (!clusterType)
continue; continue;
for (auto clusterName : values) for (auto clusterName : values)
{ {
auto cluster = clusterType->getCluster(clusterName); auto cluster = clusterType->getCluster(clusterName);
if (!cluster) if (!cluster)
cluster = session.create<Cluster>(clusterType, clusterName); cluster = session.create<Cluster>(clusterType, clusterName);
clusters.push_back(cluster); clusters.push_back(cluster);
} }
} }
return clusters; return clusters;
} }
MetaData::ParserReadStyle MetaData::ParserReadStyle
getParserReadStyle() getParserReadStyle()
{ {
std::string_view readStyle {Service<IConfig>::get()->getString("scanner-parser-read-style", "accurate")}; std::string_view readStyle{ Service<IConfig>::get()->getString("scanner-parser-read-style", "accurate") };
if (readStyle == "fast") if (readStyle == "fast")
return MetaData::ParserReadStyle::Fast; return MetaData::ParserReadStyle::Fast;
else if (readStyle == "average") else if (readStyle == "average")
return MetaData::ParserReadStyle::Average; return MetaData::ParserReadStyle::Average;
else if (readStyle == "accurate") else if (readStyle == "accurate")
return MetaData::ParserReadStyle::Accurate; return MetaData::ParserReadStyle::Accurate;
throw LmsException {"Invalid value for 'scanner-parser-read-style'"}; throw LmsException{ "Invalid value for 'scanner-parser-read-style'" };
} }
} // namespace } // namespace
namespace Scanner namespace Scanner
{ {
ScanStepScanFiles::ScanStepScanFiles(InitParams& initParams) ScanStepScanFiles::ScanStepScanFiles(InitParams& initParams)
: ScanStepBase {initParams} : ScanStepBase{ initParams }
, _metadataParser {MetaData::createParser(MetaData::ParserType::TagLib, getParserReadStyle())} // For now, always use TagLib , _metadataParser{ MetaData::createParser(MetaData::ParserType::TagLib, getParserReadStyle()) } // For now, always use TagLib
{ {
} }
void void
ScanStepScanFiles::process(ScanContext& context) ScanStepScanFiles::process(ScanContext& context)
{ {
_metadataParser->setClusterTypeNames(_settings.clusterTypeNames); _metadataParser->setClusterTypeNames(_settings.clusterTypeNames);
context.currentStepStats.totalElems = context.stats.filesScanned; context.currentStepStats.totalElems = context.stats.filesScanned;
PathUtils::exploreFilesRecursive(context.directory, [&](std::error_code ec, const std::filesystem::path& path) PathUtils::exploreFilesRecursive(context.directory, [&](std::error_code ec, const std::filesystem::path& path)
{ {
if (_abortScan) if (_abortScan)
return false; return false;
if (ec) if (ec)
{ {
LMS_LOG(DBUPDATER, ERROR) << "Cannot process entry '" << path.string() << "': " << ec.message(); LMS_LOG(DBUPDATER, ERROR) << "Cannot process entry '" << path.string() << "': " << ec.message();
context.stats.errors.emplace_back(ScanError {path, ScanErrorType::CannotReadFile, ec.message()}); context.stats.errors.emplace_back(ScanError{ path, ScanErrorType::CannotReadFile, ec.message() });
} }
else if (PathUtils::hasFileAnyExtension(path, _settings.supportedExtensions)) else if (PathUtils::hasFileAnyExtension(path, _settings.supportedExtensions))
{ {
scanAudioFile(path, context); scanAudioFile(path, context);
context.currentStepStats.processedElems++; context.currentStepStats.processedElems++;
_progressCallback(context.currentStepStats); _progressCallback(context.currentStepStats);
// optimize the database during scan (if we import a very large database, it may be too late to do it once at end) // optimize the database during scan (if we import a very large database, it may be too late to do it once at end)
if ((context.stats.nbChanges() % 5'000) == 0) if ((context.currentStepStats.processedElems % 1'000) == 0)
_db.getTLSSession().optimize(); _db.getTLSSession().optimize();
} }
return true; return true;
}, &excludeDirFileName); }, &excludeDirFileName);
} }
void void
ScanStepScanFiles::scanAudioFile(const std::filesystem::path& file, ScanContext& context) ScanStepScanFiles::scanAudioFile(const std::filesystem::path& file, ScanContext& context)
{ {
ScanStats& stats {context.stats}; ScanStats& stats{ context.stats };
Wt::WDateTime lastWriteTime; Wt::WDateTime lastWriteTime;
try try
{ {
lastWriteTime = PathUtils::getLastWriteTime(file); lastWriteTime = PathUtils::getLastWriteTime(file);
} }
catch (LmsException& e) catch (LmsException& e)
{ {
LMS_LOG(DBUPDATER, ERROR) << e.what(); LMS_LOG(DBUPDATER, ERROR) << e.what();
stats.skips++; stats.skips++;
return; return;
} }
if (!context.forceScan) if (!context.forceScan)
{ {
// Skip file if last write is the same // Skip file if last write is the same
Database::Session& dbSession {_db.getTLSSession()}; Database::Session& dbSession{ _db.getTLSSession() };
auto transaction {_db.getTLSSession().createSharedTransaction()}; auto transaction{ _db.getTLSSession().createSharedTransaction() };
const Track::pointer track {Track::findByPath(dbSession, file)}; const Track::pointer track{ Track::findByPath(dbSession, file) };
if (track && track->getLastWriteTime().toTime_t() == lastWriteTime.toTime_t() if (track && track->getLastWriteTime().toTime_t() == lastWriteTime.toTime_t()
&& track->getScanVersion() == _settings.scanVersion) && track->getScanVersion() == _settings.scanVersion)
{ {
stats.skips++; stats.skips++;
return; return;
} }
} }
std::optional<MetaData::Track> trackInfo {_metadataParser->parse(file)}; std::optional<MetaData::Track> trackInfo{ _metadataParser->parse(file) };
if (!trackInfo) if (!trackInfo)
{ {
context.stats.errors.emplace_back(file, ScanErrorType::CannotParseFile); context.stats.errors.emplace_back(file, ScanErrorType::CannotParseFile);
return; return;
} }
stats.scans++; stats.scans++;
Database::Session& dbSession {_db.getTLSSession()}; Database::Session& dbSession{ _db.getTLSSession() };
auto uniqueTransaction {dbSession.createUniqueTransaction()}; auto uniqueTransaction{ dbSession.createUniqueTransaction() };
Track::pointer track {Track::findByPath(dbSession, file) }; Track::pointer track{ Track::findByPath(dbSession, file) };
if (trackInfo->mbid && (!track || _settings.skipDuplicateMBID)) if (trackInfo->mbid && (!track || _settings.skipDuplicateMBID))
{ {
std::vector<Track::pointer> duplicateTracks {Track::findByMBID(dbSession, *trackInfo->mbid)}; std::vector<Track::pointer> duplicateTracks{ Track::findByMBID(dbSession, *trackInfo->mbid) };
// find for existing MBIDs as the file may have just been moved // find for existing MBIDs as the file may have just been moved
if (!track && duplicateTracks.size() == 1) if (!track && duplicateTracks.size() == 1)
{ {
Track::pointer otherTrack {duplicateTracks.front()}; Track::pointer otherTrack{ duplicateTracks.front() };
std::error_code ec; std::error_code ec;
if (!std::filesystem::exists(otherTrack->getPath(), ec)) if (!std::filesystem::exists(otherTrack->getPath(), ec))
{ {
LMS_LOG(DBUPDATER, DEBUG) << "Considering track '" << file.string() << "' moved from '" << otherTrack->getPath() << "'"; LMS_LOG(DBUPDATER, DEBUG) << "Considering track '" << file.string() << "' moved from '" << otherTrack->getPath() << "'";
track = otherTrack; track = otherTrack;
track.modify()->setPath(file); track.modify()->setPath(file);
} }
} }
// Skip duplicate track MBID // Skip duplicate track MBID
if (_settings.skipDuplicateMBID) if (_settings.skipDuplicateMBID)
{ {
for (Track::pointer otherTrack : duplicateTracks) for (Track::pointer otherTrack : duplicateTracks)
{ {
// Skip ourselves // Skip ourselves
if (track && track->getId() == otherTrack->getId()) if (track && track->getId() == otherTrack->getId())
continue; continue;
// Skip if duplicate files no longer in media root: as it will be removed later, we will end up with no file // Skip if duplicate files no longer in media root: as it will be removed later, we will end up with no file
if (!PathUtils::isPathInRootPath(file, _settings.mediaDirectory, &excludeDirFileName)) if (!PathUtils::isPathInRootPath(file, _settings.mediaDirectory, &excludeDirFileName))
continue; continue;
LMS_LOG(DBUPDATER, DEBUG) << "Skipped '" << file.string() << "' (similar MBID in '" << otherTrack->getPath().string() << "')"; LMS_LOG(DBUPDATER, DEBUG) << "Skipped '" << file.string() << "' (similar MBID in '" << otherTrack->getPath().string() << "')";
// As this MBID already exists, just remove what we just scanned // As this MBID already exists, just remove what we just scanned
if (track) if (track)
{ {
track.remove(); track.remove();
stats.deletions++; stats.deletions++;
} }
return; return;
} }
} }
} }
// We estimate this is an audio file if: // We estimate this is an audio file if:
// - we found a least one audio stream // - we found a least one audio stream
// - the duration is not null // - the duration is not null
if (trackInfo->audioStreams.empty()) if (trackInfo->audioStreams.empty())
{ {
LMS_LOG(DBUPDATER, DEBUG) << "Skipped '" << file.string() << "' (no audio stream found)"; LMS_LOG(DBUPDATER, DEBUG) << "Skipped '" << file.string() << "' (no audio stream found)";
// If Track exists here, delete it! // If Track exists here, delete it!
if (track) if (track)
{ {
track.remove(); track.remove();
stats.deletions++; stats.deletions++;
} }
stats.errors.emplace_back(ScanError {file, ScanErrorType::NoAudioTrack}); stats.errors.emplace_back(ScanError{ file, ScanErrorType::NoAudioTrack });
return; return;
} }
if (trackInfo->duration == std::chrono::milliseconds::zero()) if (trackInfo->duration == std::chrono::milliseconds::zero())
{ {
LMS_LOG(DBUPDATER, DEBUG) << "Skipped '" << file.string() << "' (duration is 0)"; LMS_LOG(DBUPDATER, DEBUG) << "Skipped '" << file.string() << "' (duration is 0)";
// If Track exists here, delete it! // If Track exists here, delete it!
if (track) if (track)
{ {
track.remove(); track.remove();
stats.deletions++; stats.deletions++;
} }
stats.errors.emplace_back(ScanError {file, ScanErrorType::BadDuration}); stats.errors.emplace_back(ScanError{ file, ScanErrorType::BadDuration });
return; return;
} }
// ***** Title // ***** Title
std::string title; std::string title;
if (!trackInfo->title.empty()) if (!trackInfo->title.empty())
title = trackInfo->title; title = trackInfo->title;
else else
{ {
// TODO parse file name guess track etc. // TODO parse file name guess track etc.
// For now juste use file name as title // For now juste use file name as title
title = file.filename().string(); title = file.filename().string();
} }
// If file already exists, update its data // If file already exists, update its data
// Otherwise, create it // Otherwise, create it
if (!track) if (!track)
{ {
track = dbSession.create<Track>(file); track = dbSession.create<Track>(file);
LMS_LOG(DBUPDATER, DEBUG) << "Adding '" << file.string() << "'"; LMS_LOG(DBUPDATER, DEBUG) << "Adding '" << file.string() << "'";
stats.additions++; stats.additions++;
} }
else else
{ {
LMS_LOG(DBUPDATER, DEBUG) << "Updating '" << file.string() << "'"; LMS_LOG(DBUPDATER, DEBUG) << "Updating '" << file.string() << "'";
stats.updates++; stats.updates++;
} }
// Track related data // Track related data
assert(track); assert(track);
track.modify()->clearArtistLinks(); track.modify()->clearArtistLinks();
// Do not fallback on artists with the same name but having a MBID for artist and releaseArtists, as it may be corrected by properly tagging files // Do not fallback on artists with the same name but having a MBID for artist and releaseArtists, as it may be corrected by properly tagging files
for (const Artist::pointer& artist : getOrCreateArtists(dbSession, trackInfo->artists, false)) for (const Artist::pointer& artist : getOrCreateArtists(dbSession, trackInfo->artists, false))
track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, artist, TrackArtistLinkType::Artist)); track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, artist, TrackArtistLinkType::Artist));
if (trackInfo->medium && trackInfo->medium->release) if (trackInfo->medium && trackInfo->medium->release)
{ {
for (const Artist::pointer& releaseArtist : getOrCreateArtists(dbSession, trackInfo->medium->release->artists, false)) for (const Artist::pointer& releaseArtist : getOrCreateArtists(dbSession, trackInfo->medium->release->artists, false))
track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, releaseArtist, TrackArtistLinkType::ReleaseArtist)); track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, releaseArtist, TrackArtistLinkType::ReleaseArtist));
} }
// Allow fallbacks on artists with the same name even if they have MBID, since there is no tag to indicate the MBID of these artists // Allow fallbacks on artists with the same name even if they have MBID, since there is no tag to indicate the MBID of these artists
// We could ask MusicBrainz to get all the information, but that would heavily slow down the import process // We could ask MusicBrainz to get all the information, but that would heavily slow down the import process
for (const Artist::pointer& conductor : getOrCreateArtists(dbSession, trackInfo->conductorArtists, true)) for (const Artist::pointer& conductor : getOrCreateArtists(dbSession, trackInfo->conductorArtists, true))
track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, conductor, TrackArtistLinkType::Conductor)); track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, conductor, TrackArtistLinkType::Conductor));
for (const Artist::pointer& composer : getOrCreateArtists(dbSession, trackInfo->composerArtists, true)) for (const Artist::pointer& composer : getOrCreateArtists(dbSession, trackInfo->composerArtists, true))
track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, composer, TrackArtistLinkType::Composer)); track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, composer, TrackArtistLinkType::Composer));
for (const Artist::pointer& lyricist : getOrCreateArtists(dbSession, trackInfo->lyricistArtists, true)) for (const Artist::pointer& lyricist : getOrCreateArtists(dbSession, trackInfo->lyricistArtists, true))
track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, lyricist, TrackArtistLinkType::Lyricist)); track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, lyricist, TrackArtistLinkType::Lyricist));
for (const Artist::pointer& mixer : getOrCreateArtists(dbSession, trackInfo->mixerArtists, true)) for (const Artist::pointer& mixer : getOrCreateArtists(dbSession, trackInfo->mixerArtists, true))
track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, mixer, TrackArtistLinkType::Mixer)); track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, mixer, TrackArtistLinkType::Mixer));
for (const auto& [role, performers] : trackInfo->performerArtists) for (const auto& [role, performers] : trackInfo->performerArtists)
{ {
for (const Artist::pointer& performer : getOrCreateArtists(dbSession, performers, true)) for (const Artist::pointer& performer : getOrCreateArtists(dbSession, performers, true))
track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, performer, TrackArtistLinkType::Performer, role)); track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, performer, TrackArtistLinkType::Performer, role));
} }
for (const Artist::pointer& producer : getOrCreateArtists(dbSession, trackInfo->producerArtists, true)) for (const Artist::pointer& producer : getOrCreateArtists(dbSession, trackInfo->producerArtists, true))
track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, producer, TrackArtistLinkType::Producer)); track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, producer, TrackArtistLinkType::Producer));
for (const Artist::pointer& remixer : getOrCreateArtists(dbSession, trackInfo->remixerArtists, true)) for (const Artist::pointer& remixer : getOrCreateArtists(dbSession, trackInfo->remixerArtists, true))
track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, remixer, TrackArtistLinkType::Remixer)); track.modify()->addArtistLink(TrackArtistLink::create(dbSession, track, remixer, TrackArtistLinkType::Remixer));
track.modify()->setScanVersion(_settings.scanVersion); track.modify()->setScanVersion(_settings.scanVersion);
if (trackInfo->medium && trackInfo->medium->release) if (trackInfo->medium && trackInfo->medium->release)
track.modify()->setRelease(getOrCreateRelease(dbSession, *trackInfo->medium->release)); track.modify()->setRelease(getOrCreateRelease(dbSession, *trackInfo->medium->release));
else else
track.modify()->setRelease({}); track.modify()->setRelease({});
track.modify()->setTotalTrack(trackInfo->medium ? trackInfo->medium->trackCount : std::nullopt); track.modify()->setTotalTrack(trackInfo->medium ? trackInfo->medium->trackCount : std::nullopt);
track.modify()->setReleaseReplayGain(trackInfo->medium ? trackInfo->medium->replayGain : std::nullopt); track.modify()->setReleaseReplayGain(trackInfo->medium ? trackInfo->medium->replayGain : std::nullopt);
track.modify()->setDiscSubtitle(trackInfo->medium ? trackInfo->medium->name : ""); track.modify()->setDiscSubtitle(trackInfo->medium ? trackInfo->medium->name : "");
track.modify()->setClusters(getOrCreateClusters(dbSession, trackInfo->tags)); track.modify()->setClusters(getOrCreateClusters(dbSession, trackInfo->tags));
track.modify()->setLastWriteTime(lastWriteTime); track.modify()->setLastWriteTime(lastWriteTime);
track.modify()->setName(title); track.modify()->setName(title);
track.modify()->setDuration(trackInfo->duration); track.modify()->setDuration(trackInfo->duration);
track.modify()->setAddedTime(Wt::WDateTime::currentDateTime()); track.modify()->setAddedTime(Wt::WDateTime::currentDateTime());
track.modify()->setTrackNumber(trackInfo->position); track.modify()->setTrackNumber(trackInfo->position);
track.modify()->setDiscNumber(trackInfo->medium ? trackInfo->medium->position : std::nullopt); track.modify()->setDiscNumber(trackInfo->medium ? trackInfo->medium->position : std::nullopt);
track.modify()->setDate(trackInfo->date); track.modify()->setDate(trackInfo->date);
track.modify()->setOriginalDate(trackInfo->originalDate); track.modify()->setOriginalDate(trackInfo->originalDate);
// If a file has an OriginalYear but no Year, set it to ease filtering // If a file has an OriginalYear but no Year, set it to ease filtering
if (!trackInfo->date.isValid() && trackInfo->originalDate.isValid()) if (!trackInfo->date.isValid() && trackInfo->originalDate.isValid())
track.modify()->setDate(trackInfo->originalDate); track.modify()->setDate(trackInfo->originalDate);
track.modify()->setRecordingMBID(trackInfo->recordingMBID); track.modify()->setRecordingMBID(trackInfo->recordingMBID);
track.modify()->setTrackMBID(trackInfo->mbid); track.modify()->setTrackMBID(trackInfo->mbid);
if (auto trackFeatures {TrackFeatures::find(dbSession, track->getId())}) if (auto trackFeatures{ TrackFeatures::find(dbSession, track->getId()) })
trackFeatures.remove(); // TODO: only if MBID changed? trackFeatures.remove(); // TODO: only if MBID changed?
track.modify()->setHasCover(trackInfo->hasCover); track.modify()->setHasCover(trackInfo->hasCover);
track.modify()->setCopyright(trackInfo->copyright); track.modify()->setCopyright(trackInfo->copyright);
track.modify()->setCopyrightURL(trackInfo->copyrightURL); track.modify()->setCopyrightURL(trackInfo->copyrightURL);
track.modify()->setTrackReplayGain(trackInfo->replayGain); track.modify()->setTrackReplayGain(trackInfo->replayGain);
track.modify()->setArtistDisplayName(trackInfo->artistDisplayName); track.modify()->setArtistDisplayName(trackInfo->artistDisplayName);
} }
} }