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

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>