Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

- Introduced property min.score #152

Merged
merged 2 commits into from
Oct 29, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions src/main/java/org/hihn/ampd/server/model/AmpdSettings.java
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,18 @@ public class AmpdSettings {
@Value("${delete.existing.playlists:false}")
private boolean deleteExistingPlaylists;

/**
* Strictness of the cover-search. A low will propably load wrong cover.
*/
@Value("${min.score:75}")
private int minScore;

/**
* Artwork finder: filename pattern for glob.
*/
@Value("${artwork.filename.pattern}")
private String artworkFilenamePattern;

/**
* Prints the applied properties to the console.
*/
Expand All @@ -85,6 +97,8 @@ public void init() {
LOG.debug("resetModesOnClear: {}", resetModesOnClear);
LOG.debug("createNewPlaylists: {}", createNewPlaylists);
LOG.debug("deleteExistingPlaylists: {}", deleteExistingPlaylists);
LOG.debug("minScore: {}", minScore);
LOG.debug("artworkFilenamePattern: {}", artworkFilenamePattern);
}

public String getMpdPassword() {
Expand Down Expand Up @@ -122,4 +136,12 @@ public boolean isCreateNewPlaylists() {
public boolean isDeleteExistingPlaylists() {
return deleteExistingPlaylists;
}

public int getMinScore() {
return minScore;
}

public String getArtworkFilenamePattern() {
return artworkFilenamePattern;
}
}
40 changes: 13 additions & 27 deletions src/main/java/org/hihn/ampd/server/service/CoverCacheService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.Normalizer;
import java.util.Optional;
import java.util.regex.Pattern;

import org.bff.javampd.song.MPDSong;
import org.hihn.ampd.server.model.AmpdSettings;
import org.hihn.ampd.server.model.CoverType;
Expand All @@ -24,8 +24,6 @@ public class CoverCacheService {

private final boolean cacheEnabled;

private final AmpdSettings ampdSettings;

private Path cacheDir;

/**
Expand All @@ -36,7 +34,6 @@ public class CoverCacheService {
*/
public CoverCacheService(final AmpdSettings ampdSettings,
final AmpdDirService ampdDirService) {
this.ampdSettings = ampdSettings;
cacheEnabled = ampdSettings.isLocalCoverCache() && ampdDirService.getCacheDir().isPresent();
if (cacheEnabled) {
cacheDir = ampdDirService.getCacheDir().get();
Expand Down Expand Up @@ -89,8 +86,8 @@ public Optional<byte[]> loadCover(MPDSong track) {
return Optional.empty();
}
final Path fullPath = buildCacheFullPath(track);
if (!fullPath.toFile().exists()) {
LOG.debug("File does not exist in cache, aborting: {}", fullPath.toString());
if (fullPath == null || !fullPath.toFile().exists()) {
LOG.debug("File does not exist in cache, aborting: {}", track);
return Optional.empty();
}
try {
Expand All @@ -115,7 +112,7 @@ public void saveCover(final MPDSong track, final byte[] file) {
final Path fullPath = buildCacheFullPath(track);
try {
// Don't write the file if it already exists
if (!fullPath.toFile().exists()) {
if (fullPath != null && !fullPath.toFile().exists()) {
LOG.debug("Saving cover: {}", fullPath);
Files.write(fullPath, file);
}
Expand All @@ -127,34 +124,23 @@ public void saveCover(final MPDSong track, final byte[] file) {
private String buildFileName(final CoverType coverType, final String artist,
final String titleOrAlbum) {
return coverType.getPrefix()
+ stripAccents(artist)
+ artist.trim().hashCode()
+ "_"
+ stripAccents(titleOrAlbum)
+ titleOrAlbum.trim().hashCode()
+ ".jpg";
}

/**
* Strips all unpleasant characters from a string.
*
* @param input Input string to strip.
* @return The stripped string.
*/
private String stripAccents(String input) {
if (input == null) {
return null;
}
Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+"); // $NON-NLS-1$
StringBuilder decomposed =
new StringBuilder(Normalizer.normalize(input, Normalizer.Form.NFD));
return pattern.matcher(decomposed).replaceAll("");
}

private Path buildCacheFullPath(MPDSong track) {
final CoverType coverType =
(track.getAlbumName().isEmpty()) ? CoverType.SINGLETON : CoverType.ALBUM;
final String titleOrAlbum =
(coverType == CoverType.ALBUM) ? track.getAlbumName() : track.getTitle();
final String fileName = buildFileName(coverType, track.getArtistName(), titleOrAlbum);
return Paths.get(cacheDir.toString(), fileName).toAbsolutePath();
try {
return Paths.get(cacheDir.toString(), fileName).toAbsolutePath();
} catch (InvalidPathException e) {
LOG.error("Error getting Path for: {}", fileName, e);
return null;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ private Optional<byte[]> loadMusicDirCover(final String trackFilePath) {
}
final List<Path> covers = new ArrayList<>();
try (final DirectoryStream<Path> stream = Files
.newDirectoryStream(parent, "cover.{jpg,jpeg,png,bmp}")) {
.newDirectoryStream(parent, ampdSettings.getArtworkFilenamePattern())) {
stream.forEach(covers::add);
} catch (final IOException e) {
LOG.debug("No covers found in: {}", path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,13 @@ private Optional<byte[]> downloadCover(final String uuid) {
private Optional<byte[]> searchAlbumMusicBrainzCover(final MPDSong track) {
final Release releaseController = new Release();
releaseController.getSearchFilter().setLimit((long) 10);
releaseController.getSearchFilter().setMinScore((long) 60);
releaseController.getSearchFilter().setMinScore((long) ampdSettings.getMinScore());
final String query;
List<ReleaseResultWs2> releaseResults = new ArrayList<>();
try {
query = String
.format("artist:%s%%20AND%%title:%s", URLEncoder.encode(track.getArtistName(),
StandardCharsets.UTF_8),
StandardCharsets.UTF_8),
URLEncoder.encode(track.getAlbumName(), StandardCharsets.UTF_8));
releaseController.search(query);
releaseResults = releaseController.getFirstSearchResultPage();
Expand All @@ -129,13 +129,13 @@ private Optional<byte[]> searchSingletonMusicBrainzCover(final MPDSong track) {
Optional<byte[]> cover = Optional.empty();
final Recording recordingController = new Recording();
recordingController.getSearchFilter().setLimit((long) 10);
recordingController.getSearchFilter().setMinScore((long) 60);
recordingController.getSearchFilter().setMinScore((long) ampdSettings.getMinScore());
final String query;
List<RecordingResultWs2> recordingResults = null;
try {
query = String
.format("artist:%s%%20AND%%20title:%s", URLEncoder.encode(track.getArtistName(),
StandardCharsets.UTF_8),
StandardCharsets.UTF_8),
URLEncoder.encode(track.getTitle(), StandardCharsets.UTF_8));
recordingController.search(query);
recordingResults = recordingController.getFirstSearchResultPage();
Expand Down
4 changes: 4 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ create.new.playlists=true
delete.existing.playlists=true
# The interval (in ms) in which ampd sends updates
publisher.delay=900
# Strictness of the cover-search. A low will propably load wrong cover
min.score=75
# Artwork finder: filename pattern for glob
artwork.filename.pattern=**.{jpg,jpeg,png}
# Logging
logging.level.com.fasterxml=ERROR
logging.level.fm.last.musicbrainz.coverart.impl.DefaultCoverArtArchiveClient=WARN
Expand Down