Skip to content

Commit

Permalink
#212 add rating calculation logic to
Browse files Browse the repository at this point in the history
getHighestRatedAlbums method
  • Loading branch information
kagemomiji committed Nov 27, 2023
1 parent 80468a4 commit 7d9d09e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@
@Repository
public interface MediaFileRepository extends JpaRepository<MediaFile, Integer> {

public Optional<MediaFile> findByIdAndFolderInAndMediaTypeAndPresentTrue(Integer id, Iterable<MusicFolder> folders, MediaType mediaType);

public List<MediaFile> findByIdInAndFolderInAndMediaTypeAndPresentTrue(Iterable<Integer> ids, Iterable<MusicFolder> folders, MediaType mediaType);

public List<MediaFile> findByPath(String path);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,12 @@
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
* Provides services for user ratings.
*
Expand All @@ -62,21 +66,20 @@ public class RatingService {
* @param musicFolders Only return albums in these folders.
* @return The highest rated albums.
*/
@Transactional
@Transactional(readOnly = true)
public List<MediaFile> getHighestRatedAlbums(int offset, int count, List<MusicFolder> musicFolders) {

if (count < 1 || musicFolders.isEmpty()) {
return Collections.emptyList();
}
List<MediaFile> albums = mediaFileRepository.findByFolderInAndMediaTypeAndPresentTrue(musicFolders, MediaFile.MediaType.ALBUM);
List<MediaFile> sortedAlbums = albums.parallelStream()
.filter(file -> securityService.isReadAllowed(file, true))
.map(file -> {
Double rating = getAverageRating(file);
file.setAverageRating(rating);
Map<Integer, Double> averagePerMediaFileId = userRatingRepository.findAll().stream().collect(groupingBy(UserRating::getMediaFileId, Collectors.averagingDouble(UserRating::getRating)));

List<MediaFile> sortedAlbums = averagePerMediaFileId.entrySet().stream().map(entry -> {
return mediaFileRepository.findByIdAndFolderInAndMediaTypeAndPresentTrue(entry.getKey(), musicFolders, MediaFile.MediaType.ALBUM).map(file -> {
file.setAverageRating(entry.getValue());
return file;
})
.filter(file -> file.getAverageRating() != null)
}).orElse(null);
}).filter(file -> Objects.nonNull(file) && securityService.isReadAllowed(file, true))
.sorted(Comparator.comparing(MediaFile::getAverageRating).reversed())
.collect(Collectors.toList());

Expand Down

0 comments on commit 7d9d09e

Please sign in to comment.