Newer
Older
bremer / src / main / kotlin / service / AudioService.kt
/*
 * Copyright (c) 2023. yo-saito. All Rights Reserved.
 */

package net.piedpiper.bremer.service

import net.piedpiper.bremer.entity.AudioEntity
import net.piedpiper.bremer.entity.AudioPlayHistoryEntity
import net.piedpiper.bremer.exception.NotFoundException
import net.piedpiper.bremer.model.api.AudioListResponse
import net.piedpiper.bremer.repository.AudioRepository
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.io.File
import java.time.LocalDateTime
import java.time.ZoneId

@Service("bremer.service.AudioService")
class AudioService(
    @Qualifier("bremer.repository.AudioRepository")
    private val audioRepository: AudioRepository
) {
    companion object {
        private const val PAGE_LIMIT = 50
    }

    @Transactional
    fun getAudioFile(slug: String): File {
        val audio = audioRepository.findOneBySlug(slug) ?: throw NotFoundException()
        val file = File(audio.path)
        if (!file.exists()) {
            throw NotFoundException()
        }
        audioRepository.saveAudioPlayHistory(
            AudioPlayHistoryEntity(
                audioId = audio.id,
                lastPlayedAt = LocalDateTime.now(ZoneId.of("Asia/Tokyo"))
            )
        )
        return file
    }

    @Transactional
    fun getLeastRecentlyAccessedAudio(): AudioListResponse =
        AudioListResponse(audioRepository.findAllLruLimit(PAGE_LIMIT))

    @Transactional
    fun getByKeywords(
        audioNameLike: String?,
        artistNameLike: String?,
        albumNameLike: String?,
        tagNameLike: String?
    ): AudioListResponse {
        val set = mutableSetOf<AudioEntity>()
        if (audioNameLike?.isNotEmpty() == true) {
            set.addAll(audioRepository.findAllByNameLikeLimit(audioNameLike, PAGE_LIMIT))
        }
        if (artistNameLike?.isNotEmpty() == true) {
            set.addAll(audioRepository.findAllByArtistNameLikeLimit(artistNameLike, PAGE_LIMIT))
        }
        if (albumNameLike?.isNotEmpty() == true) {
            set.addAll(audioRepository.findAllByAlbumNameLikeLimit(albumNameLike, PAGE_LIMIT))
        }
        if (tagNameLike?.isNotEmpty() == true) {
            set.addAll(audioRepository.findAllByTagLikeLimit(tagNameLike, PAGE_LIMIT))
        }
        return AudioListResponse(
            set.sortedWith(compareBy({ it.albumId }, { it.sequence }))
                .take(PAGE_LIMIT)
                .toList()
        )
    }
}