diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..6db6770 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,43 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + id("org.springframework.boot") version "3.1.0" + id("io.spring.dependency-management") version "1.1.0" + kotlin("jvm") version "1.8.21" + kotlin("plugin.spring") version "1.8.21" +} + +group = "net.piedpiper" +version = "0.0.1-SNAPSHOT" +java.sourceCompatibility = JavaVersion.VERSION_17 + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-security:3.1.0") + implementation("org.springframework.boot:spring-boot-starter-web:3.1.0") + implementation("org.springframework.boot:spring-boot-starter-validation:3.1.0") + implementation("org.mybatis.spring.boot:mybatis-spring-boot-starter:3.0.2") + implementation("org.apache.logging.log4j:log4j-api:2.20.0") + implementation("org.apache.logging.log4j:log4j-core:2.20.0") + implementation("org.jetbrains.kotlin:kotlin-reflect:1.8.21") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + + runtimeOnly("mysql:mysql-connector-java:8.0.33") + + testImplementation("org.springframework.boot:spring-boot-starter-test") + testImplementation("org.springframework.security:spring-security-test") +} + +tasks.withType { + kotlinOptions { + freeCompilerArgs = listOf("-Xjsr305=strict") + jvmTarget = "17" + } +} + +tasks.withType { + useJUnitPlatform() +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..249e583 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.jar Binary files differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..774fae8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..a69d9cb --- /dev/null +++ b/gradlew @@ -0,0 +1,240 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..53a6b23 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,91 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..14a7278 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "Bremer" diff --git a/src/main/kotlin/BremerApplication.kt b/src/main/kotlin/BremerApplication.kt new file mode 100644 index 0000000..5ea1655 --- /dev/null +++ b/src/main/kotlin/BremerApplication.kt @@ -0,0 +1,15 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer + +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class BremerApplication + +fun main(args: Array) { + runApplication(*args) +} diff --git a/src/main/kotlin/ExceptionControllerAdvice.kt b/src/main/kotlin/ExceptionControllerAdvice.kt new file mode 100644 index 0000000..d62fb62 --- /dev/null +++ b/src/main/kotlin/ExceptionControllerAdvice.kt @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer + +import net.piedpiper.bremer.exception.BadRequestException +import net.piedpiper.bremer.exception.NotFoundException +import org.springframework.http.HttpStatus +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.ControllerAdvice +import org.springframework.web.bind.annotation.ExceptionHandler + +@ControllerAdvice +class ExceptionControllerAdvice { + class ErrorMessageModel( + val status: Int, + val message: String? + ) + + @ExceptionHandler + fun handleNotFoundException(e: BadRequestException): ResponseEntity { + return ResponseEntity( + ErrorMessageModel( + HttpStatus.BAD_REQUEST.value(), + e.message + ), HttpStatus.BAD_REQUEST + ) + } + + @ExceptionHandler + fun handleBadRequestException(e: NotFoundException): ResponseEntity { + return ResponseEntity( + ErrorMessageModel( + HttpStatus.NOT_FOUND.value(), + e.message + ), HttpStatus.NOT_FOUND + ) + } +} \ No newline at end of file diff --git a/src/main/kotlin/config/BremerConfig.kt b/src/main/kotlin/config/BremerConfig.kt new file mode 100644 index 0000000..5aab926 --- /dev/null +++ b/src/main/kotlin/config/BremerConfig.kt @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.config + +import net.piedpiper.bremer.service.app.LoginAppService +import org.apache.logging.log4j.LogManager +import org.apache.logging.log4j.Logger +import org.springframework.beans.factory.annotation.Qualifier +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder +import org.springframework.security.crypto.password.PasswordEncoder +import org.springframework.security.web.SecurityFilterChain +import org.springframework.web.filter.ForwardedHeaderFilter +import kotlin.reflect.KProperty + +@Configuration +class AppConfig { + @Bean("bremer.PasswordEncoder") + fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder() + + @Bean + fun forwardedHeaderFilter(): ForwardedHeaderFilter = ForwardedHeaderFilter() +} + +@Configuration +@EnableWebSecurity +class WebSecurityConfig( + @Qualifier("bremer.service.LoginAppService") + private val loginAppService: LoginAppService +) { + @Bean + fun securityFilterChain(http: HttpSecurity): SecurityFilterChain { + http.authorizeHttpRequests { authorize -> + authorize + .requestMatchers( + "/bremer/login", + "/bremer/login.html" + ).permitAll() + .anyRequest().authenticated() + }.formLogin { login -> + login.loginPage("/bremer/login.html").permitAll() + .loginProcessingUrl("/bremer/login").permitAll() + .usernameParameter("id") + .passwordParameter("password") + .defaultSuccessUrl("/bremer/hello.html") + .failureUrl("/bremer/login.html?failed") + }.logout { logout -> + logout + .logoutUrl("/bremer/logout") + .deleteCookies("JSESSIONID") + .invalidateHttpSession(true) + .logoutSuccessUrl("/bremer/login.html?logout") + } + .csrf { it.disable() } + .userDetailsService(loginAppService) + return http.build() + } +} + +class Log { + companion object { + private val log = LogManager.getLogger(Log::class.java) + } + + operator fun getValue(thisRef: Any, property: KProperty<*>): Logger = log +} diff --git a/src/main/kotlin/controller/api/AudioApiController.kt b/src/main/kotlin/controller/api/AudioApiController.kt new file mode 100644 index 0000000..c3ada9e --- /dev/null +++ b/src/main/kotlin/controller/api/AudioApiController.kt @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.controller.api + +import net.piedpiper.bremer.model.api.AudioListResponse +import net.piedpiper.bremer.service.app.AudioAppService +import org.springframework.beans.factory.annotation.Qualifier +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.RestController + +@RestController +@RequestMapping("bremer/api/audio") +class AudioApiController( + @Qualifier("bremer.service.AudioAppService") + private val audioAppService: AudioAppService +) { + @GetMapping + fun getAudioList( + @RequestParam("audio", required = false) audioName: String?, + @RequestParam("artist", required = false) artistName: String?, + @RequestParam("album", required = false) albumName: String? + ): ResponseEntity = + ResponseEntity.ok(audioAppService.getByKeywords(audioName, artistName, albumName)) + + @GetMapping("history") + fun getLeastRecentlyPlayedList(): ResponseEntity = + ResponseEntity.ok(audioAppService.getLeastRecentlyAccessedAudio()) +} \ No newline at end of file diff --git a/src/main/kotlin/controller/api/PlaylistApiController.kt b/src/main/kotlin/controller/api/PlaylistApiController.kt new file mode 100644 index 0000000..5e4b8ad --- /dev/null +++ b/src/main/kotlin/controller/api/PlaylistApiController.kt @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.controller.api + +import jakarta.validation.Valid +import net.piedpiper.bremer.entity.AudioEntity +import net.piedpiper.bremer.model.PlaylistAudioResponse +import net.piedpiper.bremer.model.PlaylistListResponse +import net.piedpiper.bremer.model.PlaylistRequest +import net.piedpiper.bremer.service.app.PlaylistAppService +import org.springframework.beans.factory.annotation.Qualifier +import org.springframework.http.ResponseEntity +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.PostMapping +import org.springframework.web.bind.annotation.PutMapping +import org.springframework.web.bind.annotation.RequestBody +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.RestController +import java.util.UUID + +@RestController +@RequestMapping("bremer/api/playlist") +class PlaylistApiController( + @Qualifier("bremer.service.PlaylistAppService") + private val playlistAppService: PlaylistAppService, +) { + @GetMapping + fun getAll(): ResponseEntity = + ResponseEntity.ok(playlistAppService.getAllPlaylists()) + + @GetMapping("{slug}") + fun get(@PathVariable("slug") slug: String): ResponseEntity = + ResponseEntity.ok(playlistAppService.getPlaylist(slug)) + + @PostMapping + fun create( + @Valid @RequestBody request: PlaylistRequest + ): ResponseEntity = + ResponseEntity.ok(playlistAppService.createPlaylist(request)) + + @PutMapping("{slug}") + fun update( + @PathVariable("slug") slug: String, + @Valid @RequestBody request: PlaylistRequest + ): ResponseEntity = + ResponseEntity.ok(playlistAppService.updatePlaylist(slug, request)) +} diff --git a/src/main/kotlin/controller/view/AudioViewController.kt b/src/main/kotlin/controller/view/AudioViewController.kt new file mode 100644 index 0000000..13a9a62 --- /dev/null +++ b/src/main/kotlin/controller/view/AudioViewController.kt @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.controller.view + +import jakarta.servlet.http.HttpServletResponse +import net.piedpiper.bremer.service.app.AudioAppService +import org.springframework.beans.factory.annotation.Qualifier +import org.springframework.http.MediaType +import org.springframework.stereotype.Controller +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestMapping +import java.nio.file.Files + +@Controller("bremer.controller.AudioController") +@RequestMapping("bremer/audio") +class AudioViewController( + @Qualifier("bremer.service.AudioAppService") + private val audioAppService: AudioAppService +) { + + @GetMapping("{slug}") + fun download( + @PathVariable("slug") slug: String, + response: HttpServletResponse + ) { + val file = audioAppService.getAudioFile(slug) + response.outputStream.use { + response.setContentLengthLong(file.length()) + response.contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE + Files.copy(file.toPath(), it) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/dao/AlbumDao.kt b/src/main/kotlin/dao/AlbumDao.kt new file mode 100644 index 0000000..57b3b7d --- /dev/null +++ b/src/main/kotlin/dao/AlbumDao.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.dao + +import net.piedpiper.bremer.entity.AlbumEntity +import net.piedpiper.bremer.entity.AudioPlayHistoryEntity +import org.apache.ibatis.annotations.Mapper +import org.apache.ibatis.annotations.Param +import org.apache.ibatis.annotations.ResultMap +import org.apache.ibatis.annotations.Select +import org.springframework.stereotype.Repository + +@Repository("bremer.dao.AlbumDao") +@Mapper +interface AlbumDao { + + @ResultMap("net.piedpiper.bremer.AlbumEntity") + @Select("SELECT * FROM album WHERE name LIKE CONCAT('%', #{nameLike}, '%') LIMIT #{limit}") + fun findAllByNameLikeLimit( + @Param("nameLike") nameLike: String, + @Param("limit") limit: Int + ): List +} \ No newline at end of file diff --git a/src/main/kotlin/dao/ArtistDao.kt b/src/main/kotlin/dao/ArtistDao.kt new file mode 100644 index 0000000..277f3a9 --- /dev/null +++ b/src/main/kotlin/dao/ArtistDao.kt @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.dao + +import net.piedpiper.bremer.entity.AlbumEntity +import net.piedpiper.bremer.entity.ArtistEntity +import org.apache.ibatis.annotations.Mapper +import org.apache.ibatis.annotations.Param +import org.apache.ibatis.annotations.ResultMap +import org.apache.ibatis.annotations.Select +import org.springframework.stereotype.Repository + +@Repository("bremer.dao.ArtistDao") +@Mapper +interface ArtistDao { + + @ResultMap("net.piedpiper.bremer.ArtistEntity") + @Select("SELECT * FROM artist WHERE name LIKE CONCAT('%', #{nameLike}, '%') LIMIT #{limit}") + fun findAllByNameLikeLimit( + @Param("nameLike") nameLike: String, + @Param("limit") limit: Int + ): List +} \ No newline at end of file diff --git a/src/main/kotlin/dao/AudioDao.kt b/src/main/kotlin/dao/AudioDao.kt new file mode 100644 index 0000000..b910e77 --- /dev/null +++ b/src/main/kotlin/dao/AudioDao.kt @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.dao + +import net.piedpiper.bremer.entity.AlbumEntity +import net.piedpiper.bremer.entity.ArtistEntity +import net.piedpiper.bremer.entity.AudioEntity +import net.piedpiper.bremer.utils.SelectSQLBuilder +import net.piedpiper.bremer.utils.WHERE_IN +import org.apache.ibatis.annotations.* +import org.springframework.stereotype.Repository + +@Repository("bremer.dao.AudioDao") +@Mapper +interface AudioDao { + + @ResultMap("net.piedpiper.bremer.AudioEntity") + @SelectProvider(type = Sql::class, method = "findOneById") + fun findOneById(@Param("id") id: Long): AudioEntity? + + @ResultMap("net.piedpiper.bremer.AudioEntity") + @SelectProvider(type = Sql::class, method = "findOneBySlug") + fun findOneBySlug(@Param("slug") slug: String): AudioEntity? + + @ResultMap("net.piedpiper.bremer.AudioEntity") + @SelectProvider(type = Sql::class, method = "findAllByArtistIdIn") + fun findAllByArtistIdIn(@Param("artistIds") artistIds: List): List + + @ResultMap("net.piedpiper.bremer.AudioEntity") + @SelectProvider(type = Sql::class, method = "findAllByAlbumIdIn") + fun findAllByAlbumIdIn(@Param("albumIds") albumIds: List): List + + @ResultMap("net.piedpiper.bremer.AudioEntity") + @SelectProvider(type = Sql::class, method = "findAllByIdIn") + fun findAllByIdIn(@Param("ids") ids: List): List + + @ResultMap("net.piedpiper.bremer.AudioEntity") + @SelectProvider(type = Sql::class, method = "findAllBySlugIn") + fun findAllBySlugIn(@Param("slugs") ids: List): List + + @ResultMap("net.piedpiper.bremer.AudioEntity") + @SelectProvider(type = Sql::class, method = "findAllByNameLikeLimit") + fun findAllByNameLikeLimit( + @Param("nameLike") nameLike: String, + @Param("limit") limit: Int + ): List + + class Sql { + companion object { + @JvmStatic + fun findOneById(): String = SelectSQLBuilder(AudioEntity::class) + .leftOuterJoin(AlbumEntity::class, "audio.album_id = album.id") + .leftOuterJoin(ArtistEntity::class, "audio.artist_id = artist.id") + .toSql() + .WHERE("audio.id = #{id}") + .toString() + + @JvmStatic + fun findOneBySlug(): String = SelectSQLBuilder(AudioEntity::class) + .leftOuterJoin(AlbumEntity::class, "audio.album_id = album.id") + .leftOuterJoin(ArtistEntity::class, "audio.artist_id = artist.id") + .toSql() + .WHERE("audio.slug = #{slug}") + .toString() + + @JvmStatic + fun findAllByArtistIdIn(@Param("artistIds") artistIds: List): String = + SelectSQLBuilder(AudioEntity::class) + .leftOuterJoin(AlbumEntity::class, "audio.album_id = album.id") + .leftOuterJoin(ArtistEntity::class, "audio.artist_id = artist.id") + .toSql() + .WHERE_IN("audio.artist_id", "artistIds", artistIds.size) + .toString() + + @JvmStatic + fun findAllByAlbumIdIn(@Param("albumIds") albumIds: List): String = + SelectSQLBuilder(AudioEntity::class) + .leftOuterJoin(AlbumEntity::class, "audio.album_id = album.id") + .leftOuterJoin(ArtistEntity::class, "audio.artist_id = artist.id") + .toSql() + .WHERE_IN("audio.album_id", "albumIds", albumIds.size) + .toString() + + @JvmStatic + fun findAllByIdIn(@Param("ids") ids: List): String = + SelectSQLBuilder(AudioEntity::class) + .leftOuterJoin(AlbumEntity::class, "audio.album_id = album.id") + .leftOuterJoin(ArtistEntity::class, "audio.artist_id = artist.id") + .toSql() + .WHERE_IN("audio.id", "ids", ids.size) + .toString() + + @JvmStatic + fun findAllBySlugIn(@Param("slugs") slugs: List): String = + SelectSQLBuilder(AudioEntity::class) + .leftOuterJoin(AlbumEntity::class, "audio.album_id = album.id") + .leftOuterJoin(ArtistEntity::class, "audio.artist_id = artist.id") + .toSql() + .WHERE_IN("audio.slug", "slugs", slugs.size) + .toString() + + @JvmStatic + fun findAllByNameLikeLimit( + @Param("nameLike") nameLike: String, + @Param("limit") limit: Long + ): String = + SelectSQLBuilder(AudioEntity::class) + .leftOuterJoin(AlbumEntity::class, "audio.album_id = album.id") + .leftOuterJoin(ArtistEntity::class, "audio.artist_id = artist.id") + .toSql() + .WHERE("audio.name LIKE CONCAT('%', #{nameLike}, '%')") + .LIMIT("#{limit}") + .toString() + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/dao/AudioPlayHistoryDao.kt b/src/main/kotlin/dao/AudioPlayHistoryDao.kt new file mode 100644 index 0000000..d535a84 --- /dev/null +++ b/src/main/kotlin/dao/AudioPlayHistoryDao.kt @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.dao + +import net.piedpiper.bremer.entity.AudioPlayHistoryEntity +import org.apache.ibatis.annotations.* +import org.springframework.stereotype.Repository + +@Repository("bremer.dao.AudioPlayHistoryDao") +@Mapper +interface AudioPlayHistoryDao { + + @ResultMap("net.piedpiper.bremer.AudioPlayHistoryEntity") + @Select("SELECT * FROM audio_play_history ORDER BY last_played_at DESC LIMIT #{limit}") + fun findAllOrderLastPlayedAtDescLimit(@Param("limit") limit: Int): List + + @Insert( + """ + INSERT INTO audio_play_history (audio_id,last_played_at) VALUES (#{entity.audioId}, + #{entity.lastPlayedAt, typeHandler=net.piedpiper.bremer.dao.handler.LocalDateTimeTypeHandler}) + ON DUPLICATE KEY UPDATE last_played_at = VALUES (last_played_at); + """ + ) + @Options(useGeneratedKeys = true, keyProperty = "id") + fun insertOrUpdateOne(@Param("entity") entity: AudioPlayHistoryEntity): Boolean +} \ No newline at end of file diff --git a/src/main/kotlin/dao/PlaylistAudioDao.kt b/src/main/kotlin/dao/PlaylistAudioDao.kt new file mode 100644 index 0000000..e42f735 --- /dev/null +++ b/src/main/kotlin/dao/PlaylistAudioDao.kt @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.dao + +import net.piedpiper.bremer.entity.PlaylistAudioEntity +import net.piedpiper.bremer.utils.DaoUtils +import net.piedpiper.bremer.utils.WHERE_IN +import org.apache.ibatis.annotations.* +import org.springframework.stereotype.Repository + +@Repository("bremer.dao.PlaylistAudioDao") +@Mapper +interface PlaylistAudioDao { + + @InsertProvider(type = Sql::class, method = "insertOne") + @Options(useGeneratedKeys = true, keyProperty = "id") + fun insertOne(@Param("entity") entity: PlaylistAudioEntity): Boolean + + @UpdateProvider(type = Sql::class, method = "updateOne") + fun updateOne(@Param("entity") entity: PlaylistAudioEntity) + + @DeleteProvider(type = Sql::class, method = "deleteAllByIds") + fun deleteAllByIds(@Param("ids") ids: List); + + class Sql { + companion object { + @JvmStatic + fun insertOne(@Param("entity") entity: PlaylistAudioEntity): String = + DaoUtils.insertOne(entity) + + @JvmStatic + fun updateOne(@Param("entity") entity: PlaylistAudioEntity): String = + DaoUtils.updateOne(entity) + + @JvmStatic + fun deleteAllByIds(@Param("ids") ids: List): String = + DaoUtils.deleteQuery(PlaylistAudioEntity::class) + .WHERE_IN("id", "ids", ids.size) + .toString() + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/dao/PlaylistDao.kt b/src/main/kotlin/dao/PlaylistDao.kt new file mode 100644 index 0000000..5c024d1 --- /dev/null +++ b/src/main/kotlin/dao/PlaylistDao.kt @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.dao + +import net.piedpiper.bremer.entity.PlaylistAudioEntity +import net.piedpiper.bremer.entity.PlaylistEntity +import net.piedpiper.bremer.utils.DaoUtils +import net.piedpiper.bremer.utils.SelectSQLBuilder +import org.apache.ibatis.annotations.* +import org.springframework.stereotype.Repository + +@Repository("bremer.dao.PlaylistDao") +@Mapper +interface PlaylistDao { + + @ResultMap("net.piedpiper.bremer.PlaylistEntity") + @SelectProvider(type = Sql::class, method = "findOneById") + fun findOneById(@Param("id") id: Long): PlaylistEntity? + + @ResultMap("net.piedpiper.bremer.PlaylistEntity") + @SelectProvider(type = Sql::class, method = "findOneBySlug") + fun findOneBySlug(@Param("slug") slug: String): PlaylistEntity? + + @ResultMap("net.piedpiper.bremer.PlaylistEntity") + @Select("SELECT * FROM playlist") + fun findAll(): List + + @InsertProvider(type = Sql::class, method = "insertOne") + @Options(useGeneratedKeys = true, keyProperty = "id") + fun insertOne(@Param("entity") entity: PlaylistEntity): Boolean + + @UpdateProvider(type = Sql::class, method = "updateOne") + fun updateOne(@Param("entity") entity: PlaylistEntity) + + class Sql { + companion object { + @JvmStatic + fun findOneById(): String = + SelectSQLBuilder(PlaylistEntity::class) + .leftOuterJoin( + PlaylistAudioEntity::class, + "playlist.id = playlist_audio.playlist_id" + ) + .toSql() + .WHERE("playlist.id = #{id}") + .ORDER_BY("playlist_audio.sequence ASC") + .toString() + + @JvmStatic + fun findOneBySlug(): String = + SelectSQLBuilder(PlaylistEntity::class) + .leftOuterJoin( + PlaylistAudioEntity::class, + "playlist.id = playlist_audio.playlist_id" + ) + .toSql() + .WHERE("playlist.slug = #{slug}") + .ORDER_BY("playlist_audio.sequence ASC") + .toString() + + @JvmStatic + @Options(useGeneratedKeys = true, keyColumn = "id") + fun insertOne(@Param("entity") entity: PlaylistEntity): String = + DaoUtils.insertOne(entity) + + @JvmStatic + fun updateOne(@Param("entity") entity: PlaylistEntity): String = + DaoUtils.updateOne(entity) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/dao/UserDao.kt b/src/main/kotlin/dao/UserDao.kt new file mode 100644 index 0000000..6c12a5c --- /dev/null +++ b/src/main/kotlin/dao/UserDao.kt @@ -0,0 +1,21 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.dao + +import net.piedpiper.bremer.entity.UserEntity +import org.apache.ibatis.annotations.Mapper +import org.apache.ibatis.annotations.Param +import org.apache.ibatis.annotations.ResultMap +import org.apache.ibatis.annotations.Select +import org.springframework.stereotype.Repository + +@Repository("bremer.dao.UserDao") +@Mapper +interface UserDao { + + @ResultMap("net.piedpiper.bremer.UserEntity") + @Select("SELECT * FROM user WHERE account_id = #{accountId}") + fun findByName(@Param("accountId") accountId: String): UserEntity? +} \ No newline at end of file diff --git a/src/main/kotlin/dao/handler/LocalDateTimeTypeHandler.kt b/src/main/kotlin/dao/handler/LocalDateTimeTypeHandler.kt new file mode 100644 index 0000000..97745eb --- /dev/null +++ b/src/main/kotlin/dao/handler/LocalDateTimeTypeHandler.kt @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.dao.handler + +import org.apache.ibatis.type.BaseTypeHandler +import org.apache.ibatis.type.JdbcType +import java.sql.CallableStatement +import java.sql.PreparedStatement +import java.sql.ResultSet +import java.time.LocalDateTime +import java.time.ZoneOffset + +class LocalDateTimeTypeHandler : BaseTypeHandler() { + private val jst = ZoneOffset.ofHours(9) + + override fun setNonNullParameter( + ps: PreparedStatement?, + i: Int, + parameter: LocalDateTime?, + jdbcType: JdbcType? + ) { + ps?.setLong( + i, + if (LocalDateTime.MIN.isEqual(parameter)) 0L else parameter?.toEpochSecond(jst) ?: 0L + ) + } + + override fun getNullableResult(rs: ResultSet?, columnName: String?): LocalDateTime = + rs?.getLong(columnName)?.let { LocalDateTime.ofEpochSecond(it, 0, jst) } + ?: LocalDateTime.MIN + + override fun getNullableResult(rs: ResultSet?, columnIndex: Int): LocalDateTime = + rs?.getLong(columnIndex)?.let { LocalDateTime.ofEpochSecond(it, 0, jst) } + ?: LocalDateTime.MIN + + override fun getNullableResult(cs: CallableStatement?, columnIndex: Int): LocalDateTime = + cs?.getLong(columnIndex)?.let { LocalDateTime.ofEpochSecond(it, 0, jst) } + ?: LocalDateTime.MIN +} \ No newline at end of file diff --git a/src/main/kotlin/entity/Audio.kt b/src/main/kotlin/entity/Audio.kt new file mode 100644 index 0000000..5c1ca01 --- /dev/null +++ b/src/main/kotlin/entity/Audio.kt @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.entity + +import net.piedpiper.bremer.utils.sql.Column +import net.piedpiper.bremer.utils.sql.Table +import java.time.LocalDateTime + +@Table("audio") +data class AudioEntity( + @property:Column("id", insertable = false, updatable = false) + var id: Long = 0L, + @property:Column("slug") + var slug: String = "", + @property:Column("name") + var name: String = "", + @property:Column("artist_id") + var artistId: Long = 0L, + @property:Column("album_id") + var albumId: Long = 0L, + @property:Column("path") + var path: String = "", + // join + var artist: ArtistEntity? = null, + var album: AlbumEntity? = null +) + +@Table("album") +data class AlbumEntity( + @property:Column("id", insertable = false, updatable = false) + var id: Long = 0L, + @property:Column("name") + var name: String = "", +) + +@Table("artist") +data class ArtistEntity( + @property:Column("id", insertable = false, updatable = false) + var id: Long = 0L, + @property:Column("name") + var name: String = "", +) + +@Table("audio_play_history") +data class AudioPlayHistoryEntity( + @property:Column("id", insertable = false, updatable = false) + var id: Long = 0L, + @property:Column("audio_id") + var audioId: Long = 0L, + @property:Column("last_played_at") + var lastPlayedAt: LocalDateTime = LocalDateTime.MIN +) diff --git a/src/main/kotlin/entity/Playlist.kt b/src/main/kotlin/entity/Playlist.kt new file mode 100644 index 0000000..e9680a2 --- /dev/null +++ b/src/main/kotlin/entity/Playlist.kt @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.entity + +import net.piedpiper.bremer.utils.sql.Column +import net.piedpiper.bremer.utils.sql.Table + + +@Table("playlist") +data class PlaylistEntity( + @property:Column("id", insertable = false, updatable = false) + var id: Long = 0L, + @property:Column("slug") + var slug: String = "", + @property:Column("name") + var name: String = "", + // join + var playlistAudio: List = mutableListOf() +) + +@Table("playlist_audio") +data class PlaylistAudioEntity( + @property:Column("id", insertable = false, updatable = false) + var id: Long = 0L, + @property:Column("playlist_id") + var playlistId: Long = 0L, + @property:Column("sequence") + var sequence: Int = 0, + @property:Column("audio_id") + var audioId: Long = 0L +) diff --git a/src/main/kotlin/entity/User.kt b/src/main/kotlin/entity/User.kt new file mode 100644 index 0000000..90f2d5c --- /dev/null +++ b/src/main/kotlin/entity/User.kt @@ -0,0 +1,18 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.entity + +import net.piedpiper.bremer.utils.sql.Column +import net.piedpiper.bremer.utils.sql.Table + +@Table("user") +data class UserEntity( + @property:Column("id", insertable = false, updatable = false) + var id: Long = 0L, + @property:Column("account_id") + var accountId: String = "", + @property:Column("secret") + var secret: String = "", +) \ No newline at end of file diff --git a/src/main/kotlin/exception/Exception.kt b/src/main/kotlin/exception/Exception.kt new file mode 100644 index 0000000..8f5b5b7 --- /dev/null +++ b/src/main/kotlin/exception/Exception.kt @@ -0,0 +1,9 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.exception + +class NotFoundException : RuntimeException() + +class BadRequestException : RuntimeException() diff --git a/src/main/kotlin/model/api/Audio.kt b/src/main/kotlin/model/api/Audio.kt new file mode 100644 index 0000000..e27178c --- /dev/null +++ b/src/main/kotlin/model/api/Audio.kt @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2023. yo-saito. All Rights Reserved. + */ + +package net.piedpiper.bremer.model.api + +import net.piedpiper.bremer.entity.AudioEntity + +data class AudioListResponse( + private val entities: List +) { + val audio: List