First usable stage

This commit is contained in:
2021-05-22 18:43:31 +02:00
commit b618ee182b
36 changed files with 2251 additions and 0 deletions

4
.dockerignore Normal file
View File

@@ -0,0 +1,4 @@
*
!target/*-runner
!target/*-runner.jar
!target/lib/*

39
.gitignore vendored Normal file
View File

@@ -0,0 +1,39 @@
# Eclipse
.project
.classpath
.settings/
bin/
# IntelliJ
.idea
*.ipr
*.iml
*.iws
# NetBeans
nb-configuration.xml
# Visual Studio Code
.vscode
# OSX
.DS_Store
# Vim
*.swp
*.swo
# patch
*.orig
*.rej
# Maven
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
release.properties
application.yaml
build.sh
*log

117
.mvn/wrapper/MavenWrapperDownloader.java vendored Normal file
View File

@@ -0,0 +1,117 @@
/*
* Copyright 2007-present 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.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

BIN
.mvn/wrapper/maven-wrapper.jar vendored Normal file

Binary file not shown.

2
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

7
Makefile Normal file
View File

@@ -0,0 +1,7 @@
executable:
./mvnw package -Pnative
image:
docker build -t rhiobet/lalafin . -f src/main/docker/Dockerfile.native
all: executable image

30
README.md Normal file
View File

@@ -0,0 +1,30 @@
# lalafin project
This project uses Quarkus, the Supersonic Subatomic Java Framework.
If you want to learn more about Quarkus, please visit its website: https://quarkus.io/ .
## Running the application in dev mode
You can run your application in dev mode that enables live coding using:
```
./mvnw quarkus:dev
```
## Packaging and running the application
The application can be packaged using `./mvnw package`.
It produces the `lalafin-1.0-SNAPSHOT-runner.jar` file in the `/target` directory.
Be aware that its not an _über-jar_ as the dependencies are copied into the `target/lib` directory.
The application is now runnable using `java -jar target/lalafin-1.0-SNAPSHOT-runner.jar`.
## Creating a native executable
You can create a native executable using: `./mvnw package -Pnative`.
Or, if you don't have GraalVM installed, you can run the native executable build in a container using: `./mvnw package -Pnative -Dquarkus.native.container-build=true`.
You can then execute your native executable with: `./target/lalafin-1.0-SNAPSHOT-runner`
If you want to learn more about building native executables, please consult https://quarkus.io/guides/building-native-image-guide.

310
mvnw vendored Executable file
View File

@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
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
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
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
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. 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,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

129
pom.xml Normal file
View File

@@ -0,0 +1,129 @@
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>ninja.rhiobet</groupId>
<artifactId>lalafin</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<compiler-plugin.version>3.8.1</compiler-plugin.version>
<maven.compiler.parameters>true</maven.compiler.parameters>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<quarkus-plugin.version>1.13.4.Final</quarkus-plugin.version>
<quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id>
<quarkus.platform.group-id>io.quarkus</quarkus.platform.group-id>
<quarkus.platform.version>1.13.4.Final</quarkus.platform.version>
<surefire-plugin.version>2.22.1</surefire-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>${quarkus.platform.artifact-id}</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-qute</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-resteasy-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-config-yaml</artifactId>
</dependency>
<!-- Instance specific-->
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-oidc</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>build</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<systemProperties>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
</systemProperties>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus-plugin.version}</version>
<executions>
<execution>
<configuration>
<enableHttpUrlHandler>true</enableHttpUrlHandler>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
<configuration>
<systemPropertyVariables>
<native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@@ -0,0 +1,47 @@
####
# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode
#
# Before building the docker image run:
#
# mvn package
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/lalafin-jvm .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/lalafin-jvm
#
###
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.1
ARG JAVA_PACKAGE=java-8-openjdk-headless
ARG RUN_JAVA_VERSION=1.3.5
ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en'
# Install java and the run-java script
# Also set up permissions for user `1001`
RUN microdnf install openssl curl ca-certificates ${JAVA_PACKAGE} \
&& microdnf update \
&& microdnf clean all \
&& mkdir /deployments \
&& chown 1001 /deployments \
&& chmod "g+rwX" /deployments \
&& chown 1001:root /deployments \
&& curl https://repo1.maven.org/maven2/io/fabric8/run-java-sh/${RUN_JAVA_VERSION}/run-java-sh-${RUN_JAVA_VERSION}-sh.sh -o /deployments/run-java.sh \
&& chown 1001 /deployments/run-java.sh \
&& chmod 540 /deployments/run-java.sh \
&& echo "securerandom.source=file:/dev/urandom" >> /etc/alternatives/jre/lib/security/java.security
# Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size.
ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager"
COPY target/lib/* /deployments/lib/
COPY target/*-runner.jar /deployments/app.jar
EXPOSE 8080
USER 1001
ENTRYPOINT [ "/deployments/run-java.sh" ]

View File

@@ -0,0 +1,25 @@
####
# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode
#
# Before building the docker image run:
#
# mvn package -Pnative -Dquarkus.native.container-build=true
#
# Then, build the image with:
#
# docker build -f src/main/docker/Dockerfile.native -t quarkus/lalafin .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/lalafin
#
###
FROM registry.access.redhat.com/ubi8/ubi-minimal:latest
WORKDIR /work/
COPY target/*-runner /work/application
RUN chmod 775 /work
EXPOSE 8080
CMD ["./application", "-Dquarkus.http.host=0.0.0.0"]

View File

@@ -0,0 +1,64 @@
package sh.rhiobet.lalafin.api;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
import io.quarkus.security.Authenticated;
import io.quarkus.security.identity.SecurityIdentity;
import io.vertx.core.http.HttpServerRequest;
import sh.rhiobet.lalafin.api.internal.FileTokenProvider;
import sh.rhiobet.lalafin.api.internal.RoleAccessService;
import sh.rhiobet.lalafin.api.model.FileInfoBase;
import sh.rhiobet.lalafin.file.FileInfoService;
@Authenticated
@Path("/api/private/file")
public class FilePrivateAPI {
@Inject
SecurityIdentity securityIdentity;
@Context
HttpServerRequest request;
@Inject
FileInfoService fileInfoService;
@Inject
RoleAccessService roleAccessService;
@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response getFileInfo() {
return this.getFileInfo(new ArrayList<>());
}
@GET
@Path("/{names: .+}")
@Produces(MediaType.APPLICATION_JSON)
public Response getFileInfo(@PathParam List<PathSegment> names) {
if (!roleAccessService.checkRouteAccess(securityIdentity.getRoles(), names)) {
return Response.status(Response.Status.FORBIDDEN).build();
}
FileTokenProvider fileTokenProvider =
new FileTokenProvider(securityIdentity.getPrincipal().getName(),
request.remoteAddress().host().toString());
FileInfoBase fileInfo = fileInfoService.getInfo(names, fileTokenProvider);
if (fileInfo == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(fileInfo).build();
}
}

View File

@@ -0,0 +1,81 @@
package sh.rhiobet.lalafin.api;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
import io.vertx.core.http.HttpServerRequest;
import sh.rhiobet.lalafin.api.model.FileInfo;
import sh.rhiobet.lalafin.api.model.FileInfoBase;
import sh.rhiobet.lalafin.api.model.FileToken;
import sh.rhiobet.lalafin.api.model.FolderInfo;
import sh.rhiobet.lalafin.file.FileInfoService;
import sh.rhiobet.lalafin.file.FileServeService;
import sh.rhiobet.lalafin.api.configuration.FolderApiConfiguration;
import sh.rhiobet.lalafin.api.configuration.FolderApiConfiguration.Token;
import sh.rhiobet.lalafin.api.internal.RSAKey;
@Path("/api/public/file")
public class FilePublicAPI {
@Context
HttpServerRequest request;
@Inject
FileServeService fileServeService;
@Inject
FileInfoService fileInfoService;
@Inject
FolderApiConfiguration folderApiConfiguration;
@GET
@Path("/token/{fileToken}{fileName: (/.*)?}")
public Response getFileFromToken(@PathParam String fileToken,
@HeaderParam("Range") String range) throws JsonProcessingException {
String decryptedToken = RSAKey.decrypt(fileToken);
ObjectMapper obj = new ObjectMapper();
FileToken token = obj.readValue(decryptedToken, FileToken.class);
String decodedFile = URLDecoder.decode(token.file, StandardCharsets.UTF_8);
if (request.remoteAddress().host().toString().equals(token.ip)
&& System.currentTimeMillis() < token.timestamp + 172800000) {
FileInfoBase fileInfoBase = fileInfoService.getInfo(decodedFile.split("/"), null);
if (fileInfoBase instanceof FileInfo) {
return fileServeService.serveFile((FileInfo) fileInfoBase, range);
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
} else {
return Response.status(Response.Status.FORBIDDEN).build();
}
}
@GET
@Path("/folder/{folderToken}/{names: .+}")
public Response getFolderFile(@PathParam String folderToken, @PathParam List<PathSegment> names,
@HeaderParam("Range") String range) {
for (Token token : folderApiConfiguration.tokens()) {
if (token.value().equals(folderToken)) {
FileInfoBase fileInfoBase = fileInfoService.getInfo(names, token.path(), null);
if (fileInfoBase instanceof FileInfo) {
return fileServeService.serveFile((FileInfo) fileInfoBase, range);
} else if (fileInfoBase instanceof FolderInfo) {
return fileServeService.serveFolder((FolderInfo) fileInfoBase);
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
}
return Response.status(Response.Status.FORBIDDEN).build();
}
}

View File

@@ -0,0 +1,19 @@
package sh.rhiobet.lalafin.api.configuration;
import java.util.List;
import java.util.Optional;
import io.smallrye.config.ConfigMapping;
@ConfigMapping(prefix = "api.file")
public interface FileApiConfiguration {
public String directory();
public List<String> ignored();
public List<Route> routes();
public static interface Route {
public String path();
public Optional<List<String>> roles();
}
}

View File

@@ -0,0 +1,16 @@
package sh.rhiobet.lalafin.api.configuration;
import java.util.List;
import io.smallrye.config.ConfigMapping;
@ConfigMapping(prefix = "api.folder")
public interface FolderApiConfiguration {
public List<Token> tokens();
public static interface Token {
public String path();
public String value();
}
}

View File

@@ -0,0 +1,30 @@
package sh.rhiobet.lalafin.api.internal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import sh.rhiobet.lalafin.api.model.FileToken;
public class FileTokenProvider {
private String username;
private String ip;
public FileTokenProvider(String username, String ip) {
this.username = username;
this.ip = ip;
}
public String getFileToken(String file) {
FileToken token = new FileToken(username, System.currentTimeMillis(), ip, file);
ObjectMapper obj = new ObjectMapper();
try {
return URLEncoder.encode(RSAKey.encrypt(obj.writeValueAsString(token)),
StandardCharsets.UTF_8);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,62 @@
package sh.rhiobet.lalafin.api.internal;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
public class RSAKey {
private static volatile SecretKey secretKey = null;
private static volatile IvParameterSpec ivParameterSpec = null;
private static SecretKey getKey() throws NoSuchAlgorithmException {
if (secretKey == null) {
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
secretKey = keyGen.generateKey();
byte[] iv = new byte[16];
new SecureRandom().nextBytes(iv);
ivParameterSpec = new IvParameterSpec(iv);
}
return secretKey;
}
public static String encrypt(String input) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, getKey(), ivParameterSpec);
byte[] cipherText = cipher.doFinal(input.getBytes());
return Base64.getEncoder().encodeToString(cipherText);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
| IllegalBlockSizeException | BadPaddingException
| InvalidAlgorithmParameterException e) {
throw new RuntimeException("Could not create cipher", e);
// Should never happen tbh
}
}
public static String decrypt(String input) {
try {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, getKey(), ivParameterSpec);
byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(input));
return new String(plainText);
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
| IllegalBlockSizeException | BadPaddingException
| InvalidAlgorithmParameterException e) {
throw new RuntimeException("Could not create cipher", e);
// Should never happen tbh
}
}
}

View File

@@ -0,0 +1,55 @@
package sh.rhiobet.lalafin.api.internal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.core.PathSegment;
import sh.rhiobet.lalafin.api.configuration.FileApiConfiguration;
import sh.rhiobet.lalafin.api.configuration.FileApiConfiguration.Route;
@ApplicationScoped
public class RoleAccessService {
@Inject
FileApiConfiguration fileApiConfiguration;
public boolean checkRouteAccess(final Set<String> userRoles, final List<PathSegment> names) {
List<Route> matchingRoutes = new ArrayList<>();
for (Route route : fileApiConfiguration.routes()) {
String[] splittedPath = route.path().replaceFirst("^/", "").split("/");
// split returns a non empty array if the path is "/"
if (splittedPath.length == 1 && splittedPath[0].isEmpty()) {
matchingRoutes.add(route);
continue;
}
boolean match = true;
for (int i = 0; i < splittedPath.length; i++) {
if (i >= names.size() || !splittedPath[i].equals(names.get(i).getPath())) {
match = false;
break;
}
}
if (match) {
matchingRoutes.add(route);
}
}
if (matchingRoutes.isEmpty()) {
return false;
}
for (Route route : matchingRoutes) {
if (route.roles().isPresent()) {
for (String role : route.roles().get()) {
if (!userRoles.contains(role)) {
return false;
}
}
}
}
return true;
}
}

View File

@@ -0,0 +1,19 @@
package sh.rhiobet.lalafin.api.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public class FileInfo extends FileInfoBase {
public String publicApiUrl;
public FileInfo(String filename, String thumbnailUrl, String directUrl, String publicApiUrl) {
super(filename, "file", thumbnailUrl, directUrl);
this.publicApiUrl = publicApiUrl;
}
public FileInfo(String filename, String directUrl) {
this(filename, "", directUrl, "");
}
}

View File

@@ -0,0 +1,32 @@
package sh.rhiobet.lalafin.api.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public abstract class FileInfoBase implements Comparable<FileInfoBase> {
public String filename;
public String type;
public String thumbnailUrl;
public String directUrl;
public String viewUrl;
public FileInfoBase(String filename, String type, String thumbnailUrl, String directUrl,
String viewUrl) {
this.filename = filename;
this.type = type;
this.thumbnailUrl = thumbnailUrl;
this.directUrl = directUrl;
this.viewUrl = viewUrl;
}
public FileInfoBase(String filename, String type, String thumbnailUrl, String directUrl) {
this(filename, type, thumbnailUrl, directUrl, "");
}
@Override
public int compareTo(FileInfoBase f) {
return this.filename.compareToIgnoreCase(f.filename);
}
}

View File

@@ -0,0 +1,23 @@
package sh.rhiobet.lalafin.api.model;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
public class FileToken {
public String user;
public long timestamp;
public String ip;
public String file;
public FileToken() {
}
public FileToken(String user, long timestamp, String ip, String file) {
this.user = user;
this.timestamp = timestamp;
this.ip = ip;
this.file = file;
}
}

View File

@@ -0,0 +1,30 @@
package sh.rhiobet.lalafin.api.model;
import java.util.Set;
import java.util.TreeSet;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.quarkus.runtime.annotations.RegisterForReflection;
@RegisterForReflection
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FolderInfo extends FileInfoBase {
public String publicPersistentUrl;
public Set<FileInfoBase> content;
public FolderInfo(String filename, String thumbnailUrl, String directUrl, String viewUrl,
String publicPersistentUrl) {
super(filename, "folder", thumbnailUrl, directUrl, viewUrl);
this.publicPersistentUrl = publicPersistentUrl;
this.content = new TreeSet<>();
}
public FolderInfo(String filename, String thumbnailUrl, String directUrl, String viewUrl) {
this(filename, thumbnailUrl, directUrl, viewUrl, "");
}
public FolderInfo(String filename, String directUrl) {
this(filename, "", directUrl, "");
}
}

View File

@@ -0,0 +1,163 @@
package sh.rhiobet.lalafin.file;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.core.PathSegment;
import sh.rhiobet.lalafin.api.configuration.FileApiConfiguration;
import sh.rhiobet.lalafin.api.internal.FileTokenProvider;
import sh.rhiobet.lalafin.api.model.FileInfo;
import sh.rhiobet.lalafin.api.model.FileInfoBase;
import sh.rhiobet.lalafin.api.model.FolderInfo;
@ApplicationScoped
public class FileInfoService {
@Inject
FileApiConfiguration fileApiConfiguration;
public FileInfoBase getInfo(List<PathSegment> names, FileTokenProvider fileTokenProvider) {
String requestedPath = "";
String requestedFilename = "";
String requestedUri = "";
for (PathSegment name : names) {
requestedPath += "/" + name.getPath();
requestedFilename = name.getPath();
requestedUri += "/"
+ URLEncoder.encode(name.getPath(), StandardCharsets.UTF_8).replace("+", "%20");
}
return this.getInfo(requestedPath, requestedFilename, requestedUri, fileTokenProvider);
}
public FileInfoBase getInfo(String[] names, FileTokenProvider fileTokenProvider) {
String requestedPath = "";
String requestedFilename = "";
String requestedUri = "";
for (String name : names) {
requestedPath += "/" + name;
requestedFilename = name;
requestedUri +=
"/" + URLEncoder.encode(name, StandardCharsets.UTF_8).replace("+", "%20");
}
return this.getInfo(requestedPath, requestedFilename, requestedUri, fileTokenProvider);
}
public FileInfoBase getInfo(List<PathSegment> names, String uriPrefix,
FileTokenProvider fileTokenProvider) {
String requestedPath = URLDecoder.decode(uriPrefix, StandardCharsets.UTF_8);
String requestedFilename = "";
String requestedUri = uriPrefix;
for (PathSegment name : names) {
requestedPath += "/" + name.getPath();
requestedFilename = name.getPath();
requestedUri += "/"
+ URLEncoder.encode(name.getPath(), StandardCharsets.UTF_8).replace("+", "%20");
}
return this.getInfo(requestedPath, requestedFilename, requestedUri, fileTokenProvider);
}
private FileInfoBase getInfo(String requestedPath, String requestedFilename,
String requestedUri, FileTokenProvider fileTokenProvider) {
Path rootFolderPath = Paths.get(fileApiConfiguration.directory());
Path path = null;
try {
path = rootFolderPath.resolve("file").resolve(requestedPath.replaceAll("^/*", ""));
} catch (Exception ignored) {
ignored.printStackTrace();
return null;
}
if (Files.exists(path)) {
String requestedThumbUrl = "";
try {
Path requestedThumbPath =
path.getParent().resolve(".thumbnails").resolve(requestedFilename + ".jpg");
if (Files.exists(requestedThumbPath)) {
requestedThumbUrl =
rootFolderPath.relativize(requestedThumbPath).toUri().getRawPath();
// For some reason, url starts with '/work'
requestedThumbUrl = requestedThumbUrl.substring(5);
}
} catch (Exception ignored) {
}
if (Files.isDirectory(path)) {
if (requestedFilename.isEmpty()) {
requestedFilename = "/";
}
FolderInfo folderInfo = new FolderInfo(requestedFilename, requestedThumbUrl,
"/file" + requestedUri, "/view" + requestedUri + "/1");
try {
Files.list(path).forEach(p -> {
String fileName = p.getFileName().toString();
String fileUri = URLEncoder.encode(fileName, StandardCharsets.UTF_8)
.replace("+", "%20");
for (String ignoreString : fileApiConfiguration.ignored()) {
if (fileName.startsWith(".") || fileName.endsWith(ignoreString)) {
return;
}
}
Path thumbPath = null;
try {
thumbPath = Paths.get("/lalafin/file" + requestedPath + "/.thumbnails/"
+ fileName + ".jpg");
} catch (Exception ignored) {
}
FileInfoBase contentInfo;
if (Files.isDirectory(p)) {
contentInfo = new FolderInfo(fileName,
"/file" + requestedUri + "/" + fileUri);
} else {
contentInfo =
new FileInfo(fileName, "/file" + requestedUri + "/" + fileUri);
if (fileTokenProvider != null) {
((FileInfo) contentInfo).publicApiUrl =
"/api/public/file/token/"
+ fileTokenProvider
.getFileToken(requestedUri + "/" + fileUri)
+ "/" + fileUri;
}
if (fileName.endsWith(".zip")) {
contentInfo.viewUrl = "/view" + requestedUri + "/" + fileUri + "/1";
} else if (fileName.endsWith(".epub")) {
contentInfo.viewUrl = "/view" + requestedUri + "/" + fileUri + "/0";
}
}
if (thumbPath != null && Files.exists(thumbPath)) {
contentInfo.thumbnailUrl =
"/file" + requestedUri + "/.thumbnails/" + fileUri + ".jpg";
}
folderInfo.content.add(contentInfo);
});
} catch (IOException ignored) {
}
return folderInfo;
} else {
String requestedFilenameUri = URLEncoder
.encode(requestedFilename, StandardCharsets.UTF_8).replace("+", "%20");
FileInfo fileInfo = new FileInfo(requestedFilename, "/file" + requestedUri);
if (!requestedThumbUrl.isEmpty()) {
fileInfo.thumbnailUrl = requestedThumbUrl;
}
if (fileTokenProvider != null) {
fileInfo.publicApiUrl =
"/api/public/file/token/" + fileTokenProvider.getFileToken(requestedUri)
+ "/" + requestedFilenameUri;
}
if (requestedFilename.endsWith(".zip")) {
fileInfo.viewUrl = "/view" + requestedUri + "/" + requestedFilenameUri + "/1";
} else if (requestedFilename.endsWith(".epub")) {
fileInfo.viewUrl = "/view" + requestedUri + "/" + requestedFilenameUri + "/0";
}
return fileInfo;
}
}
return null;
}
}

View File

@@ -0,0 +1,73 @@
package sh.rhiobet.lalafin.file;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
import io.quarkus.security.Authenticated;
import io.quarkus.security.identity.SecurityIdentity;
import io.vertx.core.http.HttpServerRequest;
import sh.rhiobet.lalafin.api.internal.FileTokenProvider;
import sh.rhiobet.lalafin.api.internal.RoleAccessService;
import sh.rhiobet.lalafin.api.model.FileInfo;
import sh.rhiobet.lalafin.api.model.FileInfoBase;
import sh.rhiobet.lalafin.api.model.FolderInfo;
@Authenticated
@Path("/file")
public class FileResource {
@Inject
SecurityIdentity securityIdentity;
@Context
UriInfo uriInfo;
@Context
HttpServerRequest request;
@Inject
FileServeService fileServeService;
@Inject
FileInfoService fileInfoService;
@Inject
RoleAccessService roleAccessService;
@GET
@Path("/")
public Response serveRoot(@HeaderParam("Range") String range) {
return this.serve(new ArrayList<>(), range);
}
@GET
@Path("/{names: .+}")
public Response serve(@PathParam List<PathSegment> names, @HeaderParam("Range") String range) {
if (!roleAccessService.checkRouteAccess(securityIdentity.getRoles(), names)) {
return Response.status(Response.Status.FORBIDDEN).build();
}
FileTokenProvider fileTokenProvider =
new FileTokenProvider(securityIdentity.getPrincipal().getName(),
request.remoteAddress().host().toString());
FileInfoBase fileInfoBase = fileInfoService.getInfo(names, fileTokenProvider);
if (fileInfoBase instanceof FolderInfo) {
return fileServeService.serveFolder((FolderInfo) fileInfoBase);
} else if (fileInfoBase instanceof FileInfo) {
return fileServeService.serveFile((FileInfo) fileInfoBase, range);
}
return Response.status(Response.Status.NOT_FOUND).build();
}
}

View File

@@ -0,0 +1,114 @@
package sh.rhiobet.lalafin.file;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import io.quarkus.qute.Template;
import io.quarkus.qute.Location;
import sh.rhiobet.lalafin.api.configuration.FileApiConfiguration;
import sh.rhiobet.lalafin.api.model.FileInfo;
import sh.rhiobet.lalafin.api.model.FileInfoBase;
import sh.rhiobet.lalafin.api.model.FolderInfo;
@ApplicationScoped
public class FileServeService {
@Inject
FileApiConfiguration fileApiConfiguration;
@Location("directory-index.html")
Template directoryTemplate;
public Response serveFolder(FolderInfo folderInfo) {
// Look for index file
for (FileInfoBase content : folderInfo.content) {
if (content instanceof FileInfo && content.filename.startsWith("index.")) {
return this.serveFile((FileInfo) content, null);
}
}
ResponseBuilder response = Response.ok(directoryTemplate.data("info", folderInfo).render());
response.header("Content-Type", "text/html");
return response.build();
}
public Response serveFile(FileInfo fileInfo, String range) {
try {
Path path = Paths.get(fileApiConfiguration.directory(),
URLDecoder.decode(fileInfo.directUrl, StandardCharsets.UTF_8));
FileChannel channel = FileChannel.open(path);
InputStream is = Channels.newInputStream(channel);
long fileSize = channel.size();
long rangeStart = 0;
if (range != null) {
rangeStart = Long.parseLong(range.substring(6, range.length() - 1));
is.skip(rangeStart);
}
ResponseBuilder response = Response.ok(path.toFile());
response.entity(is);
response.header("Accept-Ranges", "bytes");
response.header("Content-Length", fileSize);
response.header("Content-Disposition",
"inline; filename=\"" + fileInfo.filename + "\"");
if (rangeStart > 0) {
response.status(Response.Status.PARTIAL_CONTENT);
response.header("Content-Range",
"bytes " + rangeStart + "-" + fileSize + "/" + fileSize);
}
response.header("Content-Type", this.getMimeType(fileInfo.filename));
if (path.toString().contains("/.thumbnails/")) {
response.header("Cache-Control", "max-age=604800");
}
return response.build();
} catch (IOException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
private String getMimeType(String filename) {
String extension = filename.substring(filename.lastIndexOf('.') + 1);
switch (extension) {
case "3gp":
return "video/3gpp";
case "avi":
return "video/x-msvideo";
case "flac":
return "audio/x-flac";
case "flv":
return "video/x-flv";
case "html":
return "text/html";
case "jpg":
return "image/jpeg";
case "mkv":
return "video/x-matroska";
case "mp3":
return "audio/mp3";
case "mp4":
return "video/mp4";
case "png":
return "image/png";
case "ts":
return "video/MP2T";
case "wav":
return "audio/x-wav";
case "webm":
return "video/webm";
case "wmv":
return "video/x-ms-wmv";
case "zip":
return "application/zip";
default:
return "application/octet-stream";
}
}
}

View File

@@ -0,0 +1,54 @@
package sh.rhiobet.lalafin.file;
import java.util.List;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.PathSegment;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
import io.quarkus.security.Authenticated;
import io.quarkus.security.identity.SecurityIdentity;
import io.vertx.core.http.HttpServerRequest;
import sh.rhiobet.lalafin.api.internal.FileTokenProvider;
import sh.rhiobet.lalafin.api.internal.RoleAccessService;
import sh.rhiobet.lalafin.api.model.FileInfoBase;
@Authenticated
@Path("/view")
public class ViewerResource {
@Inject
ViewerService viewerService;
@Inject
RoleAccessService roleAccessService;
@Inject
FileInfoService fileInfoService;
@Inject
SecurityIdentity securityIdentity;
@Context
HttpServerRequest request;
@GET
@Path("/{names: .+}/{page}")
public Response view(@PathParam List<PathSegment> names, @PathParam int page) {
if (!roleAccessService.checkRouteAccess(securityIdentity.getRoles(), names)) {
return Response.status(Response.Status.FORBIDDEN).build();
}
FileTokenProvider fileTokenProvider =
new FileTokenProvider(securityIdentity.getPrincipal().getName(),
request.remoteAddress().host().toString());
FileInfoBase fileInfoBase = fileInfoService.getInfo(names, fileTokenProvider);
return viewerService.view(fileInfoBase, page);
}
}

View File

@@ -0,0 +1,121 @@
package sh.rhiobet.lalafin.file;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import io.quarkus.qute.Location;
import io.quarkus.qute.Template;
import io.quarkus.qute.TemplateInstance;
import sh.rhiobet.lalafin.api.configuration.FileApiConfiguration;
import sh.rhiobet.lalafin.api.model.FileInfo;
import sh.rhiobet.lalafin.api.model.FileInfoBase;
import sh.rhiobet.lalafin.api.model.FolderInfo;
@ApplicationScoped
public class ViewerService {
@Inject
FileApiConfiguration fileApiConfiguration;
@Location("view-index.html")
Template viewTemplate;
@Location("epub-index.html")
Template epubTemplate;
public Response view(FileInfoBase fileInfoBase, int page) {
if (fileInfoBase instanceof FolderInfo) {
return this.folderResponse((FolderInfo) fileInfoBase, page);
} else if (fileInfoBase.filename.endsWith("zip")) {
return this.zipResponse((FileInfo) fileInfoBase, page);
} else if (fileInfoBase.filename.endsWith("epub")) {
return this.epubResponse((FileInfo) fileInfoBase);
}
return null;
}
private Response epubResponse(FileInfo fileInfo) {
TemplateInstance epubTemplateInstance = epubTemplate.instance().data("info", fileInfo);
ResponseBuilder response = Response.ok(epubTemplateInstance.render());
response.header("Content-Type", "text/html");
return response.build();
}
private Response zipResponse(FileInfo fileInfo, int page) {
String image = "";
Path zipPath = Paths.get(fileApiConfiguration.directory()
+ URLDecoder.decode(fileInfo.directUrl, StandardCharsets.UTF_8));
List<ZipEntry> entries = new ArrayList<>();
try {
ZipFile zipFile = new ZipFile(zipPath.toFile());
entries = zipFile.stream().filter(e -> !e.isDirectory()).collect(Collectors.toList());
if (page < 1 || page > entries.size()) {
zipFile.close();
return Response.status(Response.Status.NOT_FOUND).build();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
InputStream is = zipFile.getInputStream(entries.get(page - 1));
int read = is.read();
while (read != -1) {
byteArrayOutputStream.write(read);
read = is.read();
}
image = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
zipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
String viewUriBase = fileInfo.viewUrl.replaceAll("/[^/]*$", "/");
TemplateInstance viewTemplateInstance = viewTemplate.instance().data("info", fileInfo)
.data("image", "data:image/png;base64, " + image).data("currpage", page)
.data("totpage", entries.size()).data("prevuri", viewUriBase + (page - 1))
.data("nexturi", viewUriBase + (page + 1));
ResponseBuilder response = Response.ok(viewTemplateInstance.render());
response.header("Content-Type", "text/html");
return response.build();
}
private Response folderResponse(FolderInfo folderInfo, int page) {
List<FileInfo> viewableFiles =
folderInfo.content.stream().filter(f -> f instanceof FileInfo)
.map(f -> (FileInfo) f).collect(Collectors.toList());
if (page < 1 || page > viewableFiles.size()) {
return Response.status(Response.Status.NOT_FOUND).build();
}
FileInfo requestedFile = viewableFiles.get(page - 1);
String viewUriBase = folderInfo.viewUrl.replaceAll("/[^/]*$", "/");
TemplateInstance viewTemplateInstance = viewTemplate.instance().data("info", requestedFile)
.data("image", requestedFile.directUrl).data("currpage", page)
.data("totpage", viewableFiles.size()).data("prevuri", viewUriBase + (page - 1))
.data("nexturi", viewUriBase + (page + 1));
ResponseBuilder response = Response.ok(viewTemplateInstance.render());
response.header("Content-Type", "text/html");
return response.build();
}
}

View File

@@ -0,0 +1,24 @@
package sh.rhiobet.lalafin.nzb;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.annotations.jaxrs.PathParam;
@RolesAllowed("japan7")
@Path("/nzb")
public class NzbResource {
@Inject
NzbResultService resultService;
@GET
@Path("/id/{id}")
public Response getResult(@PathParam String id) {
return resultService.getResult(id);
}
}

View File

@@ -0,0 +1,35 @@
package sh.rhiobet.lalafin.nzb;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
@ApplicationScoped
public class NzbResultService {
public Response getResult(String id) {
File idFile = new File("/lalafin/nzb/" + id);
if (idFile.exists()) {
String resultFilePath = null;
try {
Scanner idFileReader = new Scanner(idFile);
resultFilePath = idFileReader.nextLine();
idFileReader.close();
} catch (FileNotFoundException ignored) {
}
resultFilePath = "/lalafin/nzb/files/" + resultFilePath;
File resultFile = new File(resultFilePath);
ResponseBuilder response = Response.ok(resultFile);
response.header("Content-Disposition",
"attachment; filename=\"" + resultFile.getName() + "\"");
return response.build();
}
return Response.noContent().build();
}
}

View File

@@ -0,0 +1,7 @@
<!DOCTYPE html>
<html>
<head>
<title>Faq you</title>
<meta http-equiv="refresh" content="0;URL='/file'" />
</head>
</html>

View File

@@ -0,0 +1,166 @@
/* Sakura.css v1.0.0
* ================
* Minimal css theme.
* Project: https://github.com/oxalorg/sakura
*/
/* Body */
html {
font-size: 62.5%;
font-family: serif; }
body {
font-size: 1.8rem;
line-height: 1.618;
max-width: 38em;
margin: auto;
color: #4a4a4a;
background-color: #f9f9f9;
padding: 13px; }
@media (max-width: 684px) {
body {
font-size: 1.53rem; } }
@media (max-width: 382px) {
body {
font-size: 1.35rem; } }
h1, h2, h3, h4, h5, h6 {
line-height: 1.1;
font-family: Verdana, Geneva, sans-serif;
font-weight: 700;
overflow-wrap: break-word;
word-wrap: break-word;
-ms-word-break: break-all;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto; }
h1 {
font-size: 2.35em; }
h2 {
font-size: 2.00em; }
h3 {
font-size: 1.75em; }
h4 {
font-size: 1.5em; }
h5 {
font-size: 1.25em; }
h6 {
font-size: 1em; }
small, sub, sup {
font-size: 75%; }
hr {
border-color: #2c8898; }
a {
text-decoration: none;
color: #2c8898; }
a:hover {
color: #982c61;
border-bottom: 2px solid #4a4a4a; }
ul {
padding-left: 1.4em; }
li {
margin-bottom: 0.4em; }
blockquote {
font-style: italic;
margin-left: 1.5em;
padding-left: 1em;
border-left: 3px solid #2c8898; }
img {
height: auto;
max-width: 100%; }
/* Pre and Code */
pre {
background-color: #f1f1f1;
display: block;
padding: 1em;
overflow-x: auto; }
code {
font-size: 0.9em;
padding: 0 0.5em;
background-color: #f1f1f1;
white-space: pre-wrap; }
pre > code {
padding: 0;
background-color: transparent;
white-space: pre; }
/* Tables */
table {
text-align: justify;
width: 100%;
border-collapse: collapse; }
td, th {
padding: 0.5em;
border-bottom: 1px solid #f1f1f1; }
/* Buttons, forms and input */
input, textarea {
border: 1px solid #4a4a4a; }
input:focus, textarea:focus {
border: 1px solid #2c8898; }
textarea {
width: 100%; }
.button, button, input[type="submit"], input[type="reset"], input[type="button"] {
display: inline-block;
padding: 5px 10px;
text-align: center;
text-decoration: none;
white-space: nowrap;
background-color: #2c8898;
color: #f9f9f9;
border-radius: 1px;
border: 1px solid #2c8898;
cursor: pointer;
box-sizing: border-box; }
.button[disabled], button[disabled], input[type="submit"][disabled], input[type="reset"][disabled], input[type="button"][disabled] {
cursor: default;
opacity: .5; }
.button:focus, .button:hover, button:focus, button:hover, input[type="submit"]:focus, input[type="submit"]:hover, input[type="reset"]:focus, input[type="reset"]:hover, input[type="button"]:focus, input[type="button"]:hover {
background-color: #982c61;
border-color: #982c61;
color: #f9f9f9;
outline: 0; }
textarea, select, input[type] {
color: #4a4a4a;
padding: 6px 10px;
/* The 6px vertically centers text on FF, ignored by Webkit */
margin-bottom: 10px;
background-color: #f1f1f1;
border: 1px solid #f1f1f1;
border-radius: 4px;
box-shadow: none;
box-sizing: border-box; }
textarea:focus, select:focus, input[type]:focus {
border: 1px solid #2c8898;
outline: 0; }
input[type="checkbox"]:focus {
outline: 1px dotted #2c8898; }
label, legend, fieldset {
display: block;
margin-bottom: .5rem;
font-weight: 600; }

View File

@@ -0,0 +1,33 @@
# Configuration file
quarkus:
http:
port: 8910
proxy:
proxy-address-forwarding: true
native:
container-build: true
container-runtime: docker
enable-all-security-services: true
enable-https-url-handler: true
oidc:
application-type: web-app
auth-server-url: <url>
client-id: <id>
credentials:
secret: <secret>
tls:
verification: none
token:
refresh-expired: true
api:
file:
directory: /lalafin # Files need to be in {directory}/file
ignored: {} # Files ending with these suffixes will not show up
routes:
- path: / # Root corresonds to the endpoint /file/
roles: {} # Only users with these roles will have access to this route (empty = ALL)
folder:
tokens: {} # List of tokens to make some routes available trhough the public folders API

View File

@@ -0,0 +1,49 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="mobile-web-app-capable" content="yes" />
<link rel="stylesheet" href="/style/sakura.css">
<title>{info.filename}</title>
</head>
<body>
<h1>{info.filename}</h1>
{#if !info.filename is '/'}
<a href="{info.directUrl}/..">back</a>
<span style="float:right;">
<a href="{info.viewUrl}/">viewer</a>
</span>
{/if}
<hr />
<table style="table-layout: fixed; text-align: center">
{#each info.content}
{#if count.mod(3) == 1}
<tr>
{/if}
<td>
{#if it.thumbnailUrl}
{#if it.type is 'file'}
{#if it.viewUrl}
<a href="{it.viewUrl}">
{#else}
<a href="{it.publicApiUrl}">
{/if}
{#else}
<a href="{it.directUrl}">
{/if}<img src="{it.thumbnailUrl}" loading="lazy" /></a><br />
{/if}
{#if it.type is 'file'}
<a href="{it.publicApiUrl}">
{#else}
<a href="{it.directUrl}">
{/if}{it.filename}</a>
</td>
{#if count.mod(3) == 0}
</tr>
{/if}
{/each}
</table>
<hr />
</body>
</html>

View File

@@ -0,0 +1,67 @@
<!doctype html>
<html style="height: 100%">
<head>
<meta charset="utf-8" />
<meta name="mobile-web-app-capable" content="yes" />
<link rel="stylesheet" href="/style/sakura.css" />
<title>{info.filename}</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/detect_swipe/2.1.1/jquery.detect_swipe.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.5/jszip.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/epubjs/dist/epub.min.js"></script>
</head>
<body style="max-width: 100%; padding: 0px; display: flex; flex-flow: column; height: 100%;">
<div style="flex: 0 1 auto;margin: 13px 13px 0px 13px;">
<table style="table-layout: fixed;">
<tr>
<td style="text-align: left; padding-top: 0; padding-bottom: 0;"><a href="{info.directUrl}/..">back</a></td>
<td style="text-align: right; padding-top: 0; padding-bottom: 0;"><a href="#" onclick="rendition.prev()">&lt;</a> <a href="#" onclick="rendition.next()">&gt;</a></td>
</tr>
</table>
<hr />
</div>
<div id="epub" style="flex: 1 0 auto; margin: 0px 13px 0px 13px;"></div>
<div style="flex: 0 1 auto; margin: 0px 13px 13px 13px;">
<hr />
</div>
<script>
var book = ePub("{info.directUrl}");
var rendition = book.renderTo("epub", { method: "default", width: "100%", height: "100%", minSpreadWidth: "1000" });
function setEvents(doc) {
doc.addEventListener("keyup", function(e){
if ((e.keyCode || e.which) == 37) {
rendition.prev();
}
if ((e.keyCode || e.which) == 39) {
rendition.next();
}
}, false);
doc.addEventListener("wheel", function(e) {
if (e.deltaY < 0) {
rendition.prev();
} else {
rendition.next();
}
}, false);
$(doc).on("swipeleft", function(event) {
rendition.next();
});
$(doc).on("swiperight", function(event) {
rendition.prev();
});
$(doc).on("swipeup", function(event) {
rendition.prev();
});
$(doc).on("swipedown", function(event) {
rendition.next();
});
}
rendition.on("rendered", (e0,i) => {
setEvents(i.document);
});
setEvents(document);
rendition.display();
</script>
</body>
</html>

View File

@@ -0,0 +1,22 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="mobile-web-app-capable" content="yes" />
<link rel="stylesheet" href="/style/sakura.css" />
<title>{info.filename}</title>
</head>
<body>
<table style="table-layout: fixed;">
<tr>
<td style="text-align: left; padding-top: 0; padding-bottom: 0;"><a href="{info.directUrl}/..">back</a></td>
<td style="text-align: center; padding-top: 0; padding-bottom: 0;">{currpage}/{totpage}</td>
<td style="text-align: right; padding-top: 0; padding-bottom: 0;">{#if currpage > 1}<a href="{prevuri}">&lt;</a> {/if}{#if currpage < totpage}<a href="{nexturi}">&gt;</a>{/if}</td>
</tr>
</table>
<hr />
{#if currpage < totpage}<a href="{nexturi}">{/if}<img style="position: absolute; left: 50%; transform: translate(-50%, 0);" src="{image}" />{#if currpage < totpage}</a>{/if}
<hr />
</body>
</html>