commit 6b0d849d25b18b377561bc404e3a228a149c6c15 Author: Gauthier Roebroeck Date: Thu Aug 8 17:55:56 2019 +0800 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..7fffc52d7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,26 @@ +.gradle +!gradle/wrapper/gradle-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +nbproject/private/ +build/ +nbbuild/ +dist/ +nbdist/ +.nb-gradle/ + +/nestor/src/main/resources/public \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 000000000..1b90ec8b7 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,4 @@ +tasks.wrapper { + gradleVersion = "5.5.1" + distributionType = Wrapper.DistributionType.ALL +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..5c2d1cf01 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..e0c4de36d --- /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-5.5-all.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 000000000..b0d6d0ab5 --- /dev/null +++ b/gradlew @@ -0,0 +1,188 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or 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 +# +# http://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 UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$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 "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# 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 + ;; + 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" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 000000000..9991c5032 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,100 @@ +@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 http://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 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%" == "0" goto init + +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 init + +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 + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +: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 %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="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! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/komga/Dockerfile b/komga/Dockerfile new file mode 100644 index 000000000..6d650541f --- /dev/null +++ b/komga/Dockerfile @@ -0,0 +1,7 @@ +FROM openjdk:8-jre-slim +VOLUME /tmp +ARG DEPENDENCY=target/dependency +COPY ${DEPENDENCY}/BOOT-INF/lib /app/lib +COPY ${DEPENDENCY}/META-INF /app/META-INF +COPY ${DEPENDENCY}/BOOT-INF/classes /app +ENTRYPOINT ["java","-cp","app:app/lib/*","org.gotson.komga.ApplicationKt"] \ No newline at end of file diff --git a/komga/build.gradle.kts b/komga/build.gradle.kts new file mode 100644 index 000000000..7a00221e8 --- /dev/null +++ b/komga/build.gradle.kts @@ -0,0 +1,99 @@ +import com.palantir.gradle.docker.DockerExtension +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +plugins { + run { + val kotlinVersion = "1.3.41" + kotlin("jvm") version kotlinVersion + kotlin("plugin.spring") version kotlinVersion + kotlin("plugin.jpa") version kotlinVersion + kotlin("kapt") version kotlinVersion + } + id("org.springframework.boot") version "2.1.6.RELEASE" + id("io.spring.dependency-management") version "1.0.8.RELEASE" + id("com.github.ben-manes.versions") version "0.22.0" + id("com.palantir.docker") version "0.22.1" + jacoco +} + +group = "org.gotson" +version = "0.1.0" + +repositories { + jcenter() + mavenCentral() + maven("https://jitpack.io") +} + +dependencies { + implementation(kotlin("stdlib-jdk8")) + implementation(kotlin("reflect")) + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.0-M2") + + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.springframework.boot:spring-boot-starter-data-jpa") + implementation("org.springframework.boot:spring-boot-starter-actuator") + implementation("org.springframework.boot:spring-boot-starter-cache") + implementation("org.springframework.boot:spring-boot-starter-security") + + kapt("org.springframework.boot:spring-boot-configuration-processor") + +// implementation("com.github.ben-manes.caffeine:caffeine:2.7.0") + + implementation("io.github.microutils:kotlin-logging:1.6.26") + + run { + val springfoxVersion = "2.9.2" + implementation("io.springfox:springfox-swagger2:$springfoxVersion") + implementation("io.springfox:springfox-swagger-ui:$springfoxVersion") + } + + implementation("com.fasterxml.jackson.module:jackson-module-kotlin:2.9.9") + + implementation("com.github.klinq:klinq-jpaspec:0.8") + + runtimeOnly("com.h2database:h2:1.4.199") + + testImplementation("org.springframework.boot:spring-boot-starter-test") { + exclude(module = "junit") + exclude(module = "mockito-core") + } + testImplementation("org.springframework.security:spring-security-test") + testImplementation("org.junit.jupiter:junit-jupiter:5.5.0") + testImplementation("com.ninja-squad:springmockk:1.1.2") + testImplementation("io.mockk:mockk:1.9.3") +} + +tasks { + withType { + kotlinOptions { + jvmTarget = "1.8" + freeCompilerArgs = listOf("-Xjsr305=strict") + } + } + + withType { + useJUnitPlatform() + systemProperty("spring.profiles.active", "test") + } + + withType { + filesMatching("application*.yml") { + expand(project.properties) + } + } + + register("unpack") { + dependsOn(bootJar) + from(zipTree(getByName("bootJar").outputs.files.singleFile)) + into("$buildDir/dependency") + } +} + +configure { + name = "gotson/komga:latest" + copySpec.from(tasks.getByName("unpack").outputs).into("dependency") + buildArgs(mapOf("DEPENDENCY" to "dependency")) + dependsOn(tasks.getByName("clean"), tasks.getByName("test")) +} + diff --git a/komga/src/main/kotlin/org/gotson/komga/Application.kt b/komga/src/main/kotlin/org/gotson/komga/Application.kt new file mode 100644 index 000000000..15d1fa3ed --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/Application.kt @@ -0,0 +1,18 @@ +package org.gotson.komga + +import org.gotson.komga.infrastructure.configuration.KomgaProperties +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.context.properties.EnableConfigurationProperties +import org.springframework.boot.runApplication +import org.springframework.scheduling.annotation.EnableScheduling + +@SpringBootApplication +@EnableScheduling +@EnableConfigurationProperties( + KomgaProperties::class +) +class Application + +fun main(args: Array) { + runApplication(*args) +} \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/domain/model/Book.kt b/komga/src/main/kotlin/org/gotson/komga/domain/model/Book.kt new file mode 100644 index 000000000..886a96135 --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/domain/model/Book.kt @@ -0,0 +1,23 @@ +package org.gotson.komga.domain.model + +import com.fasterxml.jackson.annotation.JsonManagedReference +import java.net.URL +import javax.persistence.Entity +import javax.persistence.FetchType +import javax.persistence.GeneratedValue +import javax.persistence.Id +import javax.persistence.ManyToOne + +@Entity +data class Book( + @Id + @GeneratedValue + val id: Long? = null, + + val name: String, + val url: URL, + + @ManyToOne(fetch = FetchType.EAGER) + @JsonManagedReference + var serie: Serie? = null +) \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/domain/model/Serie.kt b/komga/src/main/kotlin/org/gotson/komga/domain/model/Serie.kt new file mode 100644 index 000000000..17719c2b0 --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/domain/model/Serie.kt @@ -0,0 +1,24 @@ +package org.gotson.komga.domain.model + +import com.fasterxml.jackson.annotation.JsonBackReference +import java.net.URL +import javax.persistence.CascadeType +import javax.persistence.Entity +import javax.persistence.FetchType +import javax.persistence.GeneratedValue +import javax.persistence.Id +import javax.persistence.OneToMany + +@Entity +data class Serie( + @Id + @GeneratedValue + val id: Long? = null, + + val name: String, + val url: URL, + + @OneToMany(cascade = [CascadeType.ALL], fetch = FetchType.EAGER, mappedBy = "serie") + @JsonBackReference + val books: List = emptyList() +) \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/domain/persistence/BookRepository.kt b/komga/src/main/kotlin/org/gotson/komga/domain/persistence/BookRepository.kt new file mode 100644 index 000000000..c5dd56458 --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/domain/persistence/BookRepository.kt @@ -0,0 +1,12 @@ +package org.gotson.komga.domain.persistence + +import org.gotson.komga.domain.model.Book +import org.springframework.data.domain.Page +import org.springframework.data.domain.Pageable +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +@Repository +interface BookRepository : JpaRepository { + fun findAllBySerieId(serieId: Long, pageable: Pageable): Page +} \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/domain/persistence/SerieRepository.kt b/komga/src/main/kotlin/org/gotson/komga/domain/persistence/SerieRepository.kt new file mode 100644 index 000000000..c19f06e5a --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/domain/persistence/SerieRepository.kt @@ -0,0 +1,8 @@ +package org.gotson.komga.domain.persistence + +import org.gotson.komga.domain.model.Serie +import org.springframework.data.jpa.repository.JpaRepository +import org.springframework.stereotype.Repository + +@Repository +interface SerieRepository : JpaRepository \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/domain/service/FileSystemScanner.kt b/komga/src/main/kotlin/org/gotson/komga/domain/service/FileSystemScanner.kt new file mode 100644 index 000000000..d578be310 --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/domain/service/FileSystemScanner.kt @@ -0,0 +1,37 @@ +package org.gotson.komga.domain.service + +import mu.KotlinLogging +import org.gotson.komga.domain.model.Book +import org.gotson.komga.domain.model.Serie +import org.springframework.stereotype.Service +import java.io.File + +private val logger = KotlinLogging.logger {} + +@Service +class FileSystemScanner( +) { + fun scanRootFolder(root: String): List { + logger.info { "Scanning folder: $root" } + return File(root).walk() + .filter { !it.isHidden } + .filter { it.isDirectory } + .filter { it.path != root } + .mapNotNull { dir -> + val books = dir.listFiles { f -> f.isFile } + ?.map { + Book( + name = it.nameWithoutExtension, + url = it.toURI().toURL() + ) + } ?: return@mapNotNull null + Serie( + name = dir.name, + url = dir.toURI().toURL(), + books = books + ).also { serie -> + serie.books.forEach { it.serie = serie } + } + }.toList() + } +} \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/infrastructure/configuration/KomgaProperties.kt b/komga/src/main/kotlin/org/gotson/komga/infrastructure/configuration/KomgaProperties.kt new file mode 100644 index 000000000..4616fbdeb --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/infrastructure/configuration/KomgaProperties.kt @@ -0,0 +1,12 @@ +package org.gotson.komga.infrastructure.configuration + +import org.springframework.boot.context.properties.ConfigurationProperties +import org.springframework.stereotype.Component + +@Component +@ConfigurationProperties(prefix = "komga") +class KomgaProperties { + var rootFolder: String = "" + var rootFolderScanCron: String = "" +} + diff --git a/komga/src/main/kotlin/org/gotson/komga/infrastructure/development/DevelopmentConfiguration.kt b/komga/src/main/kotlin/org/gotson/komga/infrastructure/development/DevelopmentConfiguration.kt new file mode 100644 index 000000000..67f6e32ea --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/infrastructure/development/DevelopmentConfiguration.kt @@ -0,0 +1,10 @@ +package org.gotson.komga.infrastructure.development + +import org.springframework.context.annotation.Configuration +import org.springframework.context.annotation.ImportResource +import org.springframework.context.annotation.Profile + +@Profile("dev") +@Configuration +@ImportResource("classpath:h2server.xml") +class DevelopmentConfiguration \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/infrastructure/security/SecurityConfiguration.kt b/komga/src/main/kotlin/org/gotson/komga/infrastructure/security/SecurityConfiguration.kt new file mode 100644 index 000000000..49b6bb5e9 --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/infrastructure/security/SecurityConfiguration.kt @@ -0,0 +1,68 @@ +package org.gotson.komga.infrastructure.security + +import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest +import org.springframework.boot.autoconfigure.security.servlet.PathRequest +import org.springframework.context.annotation.Bean +import org.springframework.http.HttpMethod +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity +import org.springframework.security.config.annotation.web.builders.HttpSecurity +import org.springframework.security.config.annotation.web.builders.WebSecurity +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter +import org.springframework.web.cors.CorsConfiguration +import org.springframework.web.cors.UrlBasedCorsConfigurationSource + +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +class SecurityConfiguration : WebSecurityConfigurerAdapter() { + override fun configure(http: HttpSecurity) { + http + .cors().and() + .csrf().disable() + .authorizeRequests() + + // unrestricted endpoints + .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() + + // restrict all actuator endpoints to ADMIN only + .requestMatchers(EndpointRequest.toAnyEndpoint()).hasRole("ADMIN") + + // restrict H2 console to ADMIN only + .requestMatchers(PathRequest.toH2Console()).hasRole("ADMIN") + + // all other endpoints are restricted to authenticated users + .antMatchers("/api/**").hasRole("USER") + + // authorize frames for H2 console + .and().headers().frameOptions().sameOrigin() + + .and().httpBasic() +// .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) + } + + override fun configure(web: WebSecurity) { + web.ignoring() + .antMatchers( + "/error**", + "/", + "/index.html") + } + + override fun configure(auth: AuthenticationManagerBuilder) { + auth.inMemoryAuthentication() + .withUser("admin").password("{noop}admin").roles("ADMIN", "USER") + } + + @Bean + fun corsConfigurationSource(): UrlBasedCorsConfigurationSource = + UrlBasedCorsConfigurationSource().apply { + registerCorsConfiguration( + "/**", + CorsConfiguration().applyPermitDefaultValues().apply { + addExposedHeader("Authorization") + HttpMethod.values().forEach { addAllowedMethod(it) } + } + ) + } +} \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/infrastructure/swagger/SwaggerConfiguration.kt b/komga/src/main/kotlin/org/gotson/komga/infrastructure/swagger/SwaggerConfiguration.kt new file mode 100644 index 000000000..ec8e874d8 --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/infrastructure/swagger/SwaggerConfiguration.kt @@ -0,0 +1,19 @@ +package org.gotson.komga.infrastructure.swagger + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration +import org.springframework.security.core.annotation.AuthenticationPrincipal +import springfox.documentation.spi.DocumentationType +import springfox.documentation.spring.web.plugins.Docket +import springfox.documentation.swagger2.annotations.EnableSwagger2 + +@Configuration +@EnableSwagger2 +class SwaggerConfiguration { + + @Bean + fun getDocket(): Docket { + return Docket(DocumentationType.SWAGGER_2) + .ignoredParameterTypes(AuthenticationPrincipal::class.java) + } +} \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/interfaces/scheduler/RootScannerController.kt b/komga/src/main/kotlin/org/gotson/komga/interfaces/scheduler/RootScannerController.kt new file mode 100644 index 000000000..6e0cdb3df --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/interfaces/scheduler/RootScannerController.kt @@ -0,0 +1,33 @@ +package org.gotson.komga.interfaces.scheduler + +import mu.KotlinLogging +import org.gotson.komga.domain.persistence.SerieRepository +import org.gotson.komga.domain.service.FileSystemScanner +import org.gotson.komga.infrastructure.configuration.KomgaProperties +import org.springframework.boot.context.event.ApplicationReadyEvent +import org.springframework.context.event.EventListener +import org.springframework.scheduling.annotation.Scheduled +import org.springframework.stereotype.Controller +import kotlin.system.measureTimeMillis + +private val logger = KotlinLogging.logger {} + +@Controller +class RootScannerController( + private val komgaProperties: KomgaProperties, + private val fileSystemScanner: FileSystemScanner, + private val serieRepository: SerieRepository +) { + + @EventListener(ApplicationReadyEvent::class) + @Scheduled(cron = "#{@komgaProperties.rootFolderScanCron ?: '-'}") + fun scanRootFolder() { + logger.info { "Scanning root folder: ${komgaProperties.rootFolder}" } + measureTimeMillis { + val series = fileSystemScanner.scanRootFolder(komgaProperties.rootFolder) + + if (series.isNotEmpty()) + serieRepository.saveAll(series) + }.also { logger.info { "Scan finished in $it ms" } } + } +} \ No newline at end of file diff --git a/komga/src/main/kotlin/org/gotson/komga/interfaces/web/SerieController.kt b/komga/src/main/kotlin/org/gotson/komga/interfaces/web/SerieController.kt new file mode 100644 index 000000000..4eac3a89c --- /dev/null +++ b/komga/src/main/kotlin/org/gotson/komga/interfaces/web/SerieController.kt @@ -0,0 +1,82 @@ +package org.gotson.komga.interfaces.web + +import org.gotson.komga.domain.model.Book +import org.gotson.komga.domain.model.Serie +import org.gotson.komga.domain.persistence.BookRepository +import org.gotson.komga.domain.persistence.SerieRepository +import org.springframework.data.domain.Page +import org.springframework.data.domain.Pageable +import org.springframework.data.repository.findByIdOrNull +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.PathVariable +import org.springframework.web.bind.annotation.RequestMapping +import org.springframework.web.bind.annotation.RestController +import org.springframework.web.server.ResponseStatusException +import java.io.File +import java.net.URL + +@RestController +@RequestMapping("api/v1/series") +class SerieController( + private val serieRepository: SerieRepository, + private val bookRepository: BookRepository +) { + + @GetMapping + fun getAllSeries(page: Pageable) = + serieRepository.findAll(page).map { it.toDto() } + + @GetMapping("{id}") + fun getOneSerie( + @PathVariable id: Long + ): SerieDto = + serieRepository.findByIdOrNull(id)?.toDto() ?: throw ResponseStatusException(HttpStatus.NOT_FOUND) + + @GetMapping("{id}/books") + fun getAllBooksBySerie( + @PathVariable id: Long, + page: Pageable + ): Page { + if (!serieRepository.existsById(id)) throw ResponseStatusException(HttpStatus.NOT_FOUND) + return bookRepository.findAllBySerieId(id, page).map { it.toDto() } + } + + @GetMapping("{serieId}/books/{bookId}") + fun getOneBook( + @PathVariable serieId: Long, + @PathVariable bookId: Long + ): BookDto { + if (!serieRepository.existsById(serieId)) throw ResponseStatusException(HttpStatus.NOT_FOUND) + return bookRepository.findByIdOrNull(bookId)?.toDto() ?: throw ResponseStatusException(HttpStatus.NOT_FOUND) + } + + @GetMapping(value = ["{serieId}/books/{bookId}/content"], produces = [MediaType.APPLICATION_OCTET_STREAM_VALUE]) + fun getBookContent( + @PathVariable serieId: Long, + @PathVariable bookId: Long + ): ByteArray { + if (!serieRepository.existsById(serieId)) throw ResponseStatusException(HttpStatus.NOT_FOUND) + return bookRepository.findByIdOrNull(bookId)?.let { + File(it.url.toURI()).readBytes() + } ?: throw ResponseStatusException(HttpStatus.NOT_FOUND) + } +} + +data class SerieDto( + val id: Long, + val name: String, + val url: URL +) + +fun Serie.toDto() = SerieDto(id!!, name, url) + + +data class BookDto( + val id: Long, + val name: String, + val url: URL +) + +fun Book.toDto() = BookDto(id!!, name, url) \ No newline at end of file diff --git a/komga/src/main/resources/application-dev.yml b/komga/src/main/resources/application-dev.yml new file mode 100644 index 000000000..5d968b168 --- /dev/null +++ b/komga/src/main/resources/application-dev.yml @@ -0,0 +1,4 @@ +#logging.level.org.springframework.security.web.FilterChainProxy: DEBUG +komga: + root-folder: D:\\files +# root-folder-scan-cron: 0 0 * * * ? \ No newline at end of file diff --git a/komga/src/main/resources/application-localdb.yml b/komga/src/main/resources/application-localdb.yml new file mode 100644 index 000000000..930a12bca --- /dev/null +++ b/komga/src/main/resources/application-localdb.yml @@ -0,0 +1,6 @@ +spring: + datasource: + url: jdbc:h2:./testdb;DB_CLOSE_DELAY=-1 + jpa: + hibernate: + ddl-auto: update diff --git a/komga/src/main/resources/application.yml b/komga/src/main/resources/application.yml new file mode 100644 index 000000000..28d19b24a --- /dev/null +++ b/komga/src/main/resources/application.yml @@ -0,0 +1,15 @@ +application.version: ${version} + +spring: + # cache: + # caffeine-spec: maximumSize=500,expireAfterWrite=300s + h2: + console: + enabled: true + +management: + endpoints.web.exposure.include: "*" + endpoint: + health: + roles: ADMIN + show-details: when_authorized \ No newline at end of file diff --git a/komga/src/main/resources/banner.txt b/komga/src/main/resources/banner.txt new file mode 100644 index 000000000..771650d34 --- /dev/null +++ b/komga/src/main/resources/banner.txt @@ -0,0 +1,8 @@ + ____ __. +| |/ _|____ _____ _________ +| < / _ \ / \ / ___\__ \ +| | ( <_> ) Y Y \/ /_/ > __ \_ +|____|__ \____/|__|_| /\___ (____ / + \/ \//_____/ \/ + +Version: ${application.version} diff --git a/komga/src/main/resources/h2server.xml b/komga/src/main/resources/h2server.xml new file mode 100644 index 000000000..d86b01ccd --- /dev/null +++ b/komga/src/main/resources/h2server.xml @@ -0,0 +1,12 @@ + + + + + + \ No newline at end of file diff --git a/komga/src/test/kotlin/org/gotson/komga/AutowiringTest.kt b/komga/src/test/kotlin/org/gotson/komga/AutowiringTest.kt new file mode 100644 index 000000000..5dbdd9db8 --- /dev/null +++ b/komga/src/test/kotlin/org/gotson/komga/AutowiringTest.kt @@ -0,0 +1,14 @@ +package org.gotson.komga + +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.extension.ExtendWith +import org.springframework.boot.test.context.SpringBootTest +import org.springframework.test.context.junit.jupiter.SpringExtension + +@ExtendWith(SpringExtension::class) +@SpringBootTest +class AutowiringTriggerTest { + + @Test + fun `Application loads properly with test properties`() = Unit +} \ No newline at end of file diff --git a/komga/src/test/resources/application-test.yml b/komga/src/test/resources/application-test.yml new file mode 100644 index 000000000..5946d9847 --- /dev/null +++ b/komga/src/test/resources/application-test.yml @@ -0,0 +1 @@ +application.version: TESTING diff --git a/komga/src/test/resources/io/mockk/settings.properties b/komga/src/test/resources/io/mockk/settings.properties new file mode 100644 index 000000000..66cdfac7e --- /dev/null +++ b/komga/src/test/resources/io/mockk/settings.properties @@ -0,0 +1 @@ +relaxed=false \ No newline at end of file diff --git a/komga/src/test/resources/junit-platform.properties b/komga/src/test/resources/junit-platform.properties new file mode 100644 index 000000000..90f056db2 --- /dev/null +++ b/komga/src/test/resources/junit-platform.properties @@ -0,0 +1 @@ +junit.jupiter.testinstance.lifecycle.default=per_class \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..685813407 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +include 'komga' +