This commit is contained in:
Gregor Lohaus
2026-02-25 12:30:27 +01:00
parent df3adf0e3c
commit bd72a98e64
51 changed files with 2103 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
package com.gregor_lohaus.gtransfer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportRuntimeHints;
import org.springframework.web.bind.annotation.RestController;
import com.gregor_lohaus.gtransfer.config.ConfigRuntimeHints;
import com.gregor_lohaus.gtransfer.model.ModelRuntimeHints;
import com.gregor_lohaus.gtransfer.native_image.HibernateRuntimeHints;
import com.gregor_lohaus.gtransfer.native_image.WebRuntimeHints;
@SpringBootApplication
@RestController
@ImportRuntimeHints({ConfigRuntimeHints.class, HibernateRuntimeHints.class, ModelRuntimeHints.class, WebRuntimeHints.class})
public class GtransferApplication {
public static void main(String[] args) {
SpringApplication.run(GtransferApplication.class, args);
}
}

View File

@@ -0,0 +1,55 @@
package com.gregor_lohaus.gtransfer.config;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.gregor_lohaus.gtransfer.config.types.Config;
import org.springframework.boot.EnvironmentPostProcessor;
// import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.SpringApplication;
import org.springframework.core.env.ConfigurableEnvironment;
import io.github.wasabithumb.jtoml.JToml;
import io.github.wasabithumb.jtoml.value.table.TomlTable;
public class ConfigEnvironmentPostProcessor implements EnvironmentPostProcessor {
private static final Path CONFIG_FILE_PATH;
static {
Path sysPath = Paths.get("etc","gtransfer","config.toml");
Path userPath = Paths.get(System.getProperty("user.home"),".config","gtransfer","config.toml");
if (Files.isReadable(sysPath) && !Files.isReadable(userPath)) {
CONFIG_FILE_PATH = sysPath;
} else {
CONFIG_FILE_PATH = userPath;
}
}
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
JToml toml = JToml.jToml();
TomlTable table;
if (Files.isReadable(CONFIG_FILE_PATH)) {
table = toml.read(CONFIG_FILE_PATH);
} else {
try {
Files.createDirectories(CONFIG_FILE_PATH.getParent());
Files.createFile(CONFIG_FILE_PATH);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
Config defaultConfig = DefaultConfig.config;
table = ConfigSerializer.toToml(defaultConfig);
toml.write(CONFIG_FILE_PATH, table);
}
;
Config config = new Config();
config = ConfigSerializer.fromToml(table);
ReflectionPropertySource<Config> source = new ReflectionPropertySource<Config>("gtransfer-config", config);
environment.getPropertySources()
.addLast(source);
}
}

View File

@@ -0,0 +1,57 @@
package com.gregor_lohaus.gtransfer.config;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
import com.gregor_lohaus.gtransfer.config.types.*;
import io.github.wasabithumb.jtoml.serial.reflect.adapter.TypeAdapter;
public class ConfigRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.reflection().registerType(Config.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(StorageService.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(StorageServiceType.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(SpringConfig.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(JpaConfig.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(DataSourceConfig.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(ServletConfig.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(MultipartConfig.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
hints.reflection().registerType(TypeAdapter.class,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.ACCESS_PUBLIC_FIELDS);
}
}

View File

@@ -0,0 +1,33 @@
package com.gregor_lohaus.gtransfer.config;
import io.github.wasabithumb.jtoml.serial.reflect.ReflectTomlSerializer;
import io.github.wasabithumb.jtoml.serial.reflect.adapter.TypeAdapter;
import io.github.wasabithumb.jtoml.serial.reflect.adapter.TypeAdapters;
import io.github.wasabithumb.jtoml.value.TomlValue;
import io.github.wasabithumb.jtoml.value.table.TomlTable;
import com.gregor_lohaus.gtransfer.config.types.Config;
import com.gregor_lohaus.gtransfer.config.types.StorageServiceType;
public class ConfigSerializer {
static final private ReflectTomlSerializer<Config> s;
static {
TypeAdapter<StorageServiceType> fileWritTypeAdapter = TypeAdapter.of(
StorageServiceType.class,
(TomlValue v) -> StorageServiceType.fromToml(v),
(StorageServiceType f) -> StorageServiceType.toToml(f)
);
TypeAdapters typeAdapters = TypeAdapters.builder()
.add(TypeAdapters.standard())
.add(fileWritTypeAdapter)
.build();
s = new ReflectTomlSerializer<Config>(Config.class,typeAdapters);
}
public static Config fromToml(TomlTable t) {
return s.fromToml(t);
}
public static TomlTable toToml(Config c) {
return s.toToml(c);
}
}

View File

@@ -0,0 +1,47 @@
package com.gregor_lohaus.gtransfer.config;
import java.nio.file.Path;
import com.gregor_lohaus.gtransfer.config.types.Config;
import com.gregor_lohaus.gtransfer.config.types.DataSourceConfig;
import com.gregor_lohaus.gtransfer.config.types.JpaConfig;
import com.gregor_lohaus.gtransfer.config.types.MultipartConfig;
import com.gregor_lohaus.gtransfer.config.types.ServletConfig;
import com.gregor_lohaus.gtransfer.config.types.SpringConfig;
import com.gregor_lohaus.gtransfer.config.types.StorageService;
import com.gregor_lohaus.gtransfer.config.types.StorageServiceType;
public class DefaultConfig {
public static final Config config;
static {
Config c = new Config();
StorageService ss = new StorageService();
ss.type = StorageServiceType.LOCAL;
ss.path = Path.of(System.getProperty("user.home"),".local","share","gtransfer").toString();
c.storageService= ss;
SpringConfig sc = new SpringConfig();
DataSourceConfig dsc = new DataSourceConfig();
dsc.password = "gtransfer";
dsc.url = "jdbc:postgresql://localhost:5432/gtransfer";
dsc.username = "gtransfer";
sc.dataSourceConfig = dsc;
JpaConfig jc = new JpaConfig();
jc.ddlAuto = "update";
jc.dialect = "org.hibernate.dialect.PostgreSQLDialect";
jc.showSql = true;
sc.jpaConfig = jc;
MultipartConfig mc = new MultipartConfig();
mc.maxFileSize = "10GB";
mc.maxRequestSize = "10GB";
ServletConfig svc = new ServletConfig();
svc.multipartConfig = mc;
sc.servletConfig = svc;
c.springConfig = sc;
config = c;
}
}

View File

@@ -0,0 +1,98 @@
package com.gregor_lohaus.gtransfer.config;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Optional;
import org.jspecify.annotations.Nullable;
import org.springframework.core.env.PropertySource;
import com.gregor_lohaus.gtransfer.config.annotations.Named;
import com.gregor_lohaus.gtransfer.config.annotations.Nested;
import com.gregor_lohaus.gtransfer.config.annotations.NoPrefix;
import com.gregor_lohaus.gtransfer.config.annotations.Property;
public class ReflectionPropertySource<T> extends PropertySource<T> {
private HashMap<String, Object> fields;
private ArrayList<String> propNameBuffer;
public ReflectionPropertySource(String name, T source) {
super(name);
this.fields = new HashMap<String, Object>();
this.propNameBuffer = new ArrayList<String>();
this.propNameBuffer.add(this.getName());
this.getFields(source, 0);
}
private boolean hasPrefix() {
if (propNameBuffer.size() > 0 && propNameBuffer.getFirst() == this.getName()) {
return true;
}
return false;
}
private void handleNoPrefix(Field field) {
NoPrefix np = field.getAnnotation(NoPrefix.class);
if (np != null && this.hasPrefix()) {
this.propNameBuffer.remove(0);
}
}
public void handleAnnotated(Field field, Object object, int depth) throws IllegalAccessException {
Annotation annotation;
annotation = field.getAnnotation(Property.class);
if (annotation == null) {
annotation = field.getAnnotation(Nested.class);
}
Optional<String> name = Named.nameOf(annotation);
if (name.isEmpty()) {
return;
}
field.setAccessible(true);
Object fieldValue = field.get(object);
if (fieldValue == null) {
return;
}
handleNoPrefix(field);
propNameBuffer.add(name.get());
switch (annotation) {
case Nested _ -> getFields(fieldValue, depth + 1);
case Property _ -> fields.put(String.join(".", propNameBuffer), fieldValue);
case null -> {}
default -> {}
}
propNameBuffer.removeLast();
}
private void getFields(Object object, int depth) {
Class<?> c = object.getClass();
Field[] fields = c.getDeclaredFields();
for (Field field : fields) {
try {
handleAnnotated(field, object, depth);
} catch (IllegalAccessException e) {
e.printStackTrace();
System.exit(1);
}
if (depth == 0 && !hasPrefix()) {
propNameBuffer.addFirst(this.getName());
}
}
};
@Override
public @Nullable Object getProperty(String name) {
return this.fields.get(name);
}
public String toString() {
StringBuilder out = new StringBuilder();
this.fields.forEach((String f, Object o) -> {
out.append(f + ":" + o.toString() + "\n");
});
return out.toString();
}
}

View File

@@ -0,0 +1,15 @@
package com.gregor_lohaus.gtransfer.config.annotations;
import java.lang.annotation.Annotation;
import java.util.Optional;
public interface Named {
static Optional<String> nameOf(Annotation annotation) {
return switch (annotation) {
case Property p -> Optional.of(p.name());
case Nested n -> Optional.of(n.name());
case null -> Optional.empty();
default -> Optional.empty();
};
}
}

View File

@@ -0,0 +1,12 @@
package com.gregor_lohaus.gtransfer.config.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Nested {
String name() default "";
}

View File

@@ -0,0 +1,10 @@
package com.gregor_lohaus.gtransfer.config.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoPrefix {}

View File

@@ -0,0 +1,12 @@
package com.gregor_lohaus.gtransfer.config.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Property {
String name() default "";
}

View File

@@ -0,0 +1,14 @@
package com.gregor_lohaus.gtransfer.config.types;
import com.gregor_lohaus.gtransfer.config.annotations.Nested;
import com.gregor_lohaus.gtransfer.config.annotations.NoPrefix;
import io.github.wasabithumb.jtoml.serial.TomlSerializable;
public class Config implements TomlSerializable {
@Nested(name = "spring")
@NoPrefix
public SpringConfig springConfig;
@Nested(name = "storageService")
public StorageService storageService;
}

View File

@@ -0,0 +1,14 @@
package com.gregor_lohaus.gtransfer.config.types;
import com.gregor_lohaus.gtransfer.config.annotations.Property;
import io.github.wasabithumb.jtoml.serial.TomlSerializable;
public class DataSourceConfig implements TomlSerializable {
@Property(name = "url")
public String url;
@Property(name = "username")
public String username;
@Property(name = "password")
public String password;
}

View File

@@ -0,0 +1,14 @@
package com.gregor_lohaus.gtransfer.config.types;
import com.gregor_lohaus.gtransfer.config.annotations.Property;
import io.github.wasabithumb.jtoml.serial.TomlSerializable;
public class JpaConfig implements TomlSerializable {
@Property(name = "hibernate.ddl-auto")
public String ddlAuto;
@Property(name = "show-sql")
public boolean showSql;
@Property(name = "properties.hibernate.dialect")
public String dialect;
}

View File

@@ -0,0 +1,12 @@
package com.gregor_lohaus.gtransfer.config.types;
import com.gregor_lohaus.gtransfer.config.annotations.Property;
import io.github.wasabithumb.jtoml.serial.TomlSerializable;
public class MultipartConfig implements TomlSerializable {
@Property(name = "max-file-size")
public String maxFileSize;
@Property(name = "max-request-size")
public String maxRequestSize;
}

View File

@@ -0,0 +1,10 @@
package com.gregor_lohaus.gtransfer.config.types;
import com.gregor_lohaus.gtransfer.config.annotations.Nested;
import io.github.wasabithumb.jtoml.serial.TomlSerializable;
public class ServletConfig implements TomlSerializable {
@Nested(name = "multipart")
public MultipartConfig multipartConfig;
}

View File

@@ -0,0 +1,14 @@
package com.gregor_lohaus.gtransfer.config.types;
import com.gregor_lohaus.gtransfer.config.annotations.Nested;
import io.github.wasabithumb.jtoml.serial.TomlSerializable;
public class SpringConfig implements TomlSerializable {
@Nested(name = "datasource")
public DataSourceConfig dataSourceConfig;
@Nested(name = "jpa")
public JpaConfig jpaConfig;
@Nested(name = "servlet")
public ServletConfig servletConfig;
}

View File

@@ -0,0 +1,12 @@
package com.gregor_lohaus.gtransfer.config.types;
import com.gregor_lohaus.gtransfer.config.annotations.Property;
import io.github.wasabithumb.jtoml.serial.TomlSerializable;
public class StorageService implements TomlSerializable {
@Property(name = "type")
public StorageServiceType type;
@Property(name = "root")
public String path;
}

View File

@@ -0,0 +1,26 @@
package com.gregor_lohaus.gtransfer.config.types;
import io.github.wasabithumb.jtoml.serial.TomlSerializable;
import io.github.wasabithumb.jtoml.value.TomlValue;
import io.github.wasabithumb.jtoml.value.primitive.TomlPrimitive;;
public enum StorageServiceType implements TomlSerializable {
LOCAL,
S3,
DUMMY;
public static StorageServiceType fromToml(TomlValue value) {
return switch (value.asPrimitive().asString().toLowerCase()) {
case "dummy" -> DUMMY;
case "local" -> LOCAL;
case "s3" -> S3;
default -> throw new IllegalArgumentException("couldnt parse filewriter type");
};
}
public static TomlValue toToml(StorageServiceType t) {
return switch (t) {
case LOCAL -> TomlPrimitive.of("local");
case S3 -> TomlPrimitive.of("s3");
case DUMMY -> TomlPrimitive.of("dummy");
default -> throw new IllegalArgumentException();
};
}
}

View File

@@ -0,0 +1,28 @@
package com.gregor_lohaus.gtransfer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.gregor_lohaus.gtransfer.services.filewriter.AbstractStorageService;
@RestController
public class Env {
@Autowired
private ConfigurableEnvironment env;
@Autowired
private AbstractStorageService storageService;
@GetMapping("/env")
public String env() {
StringBuilder b = new StringBuilder();
MutablePropertySources sources = this.env.getPropertySources();
sources.forEach((var m) -> {
b.append(m.toString());
b.append("\n");
});
b.append(storageService.getClass().toString());
return b.toString();
}
}

View File

@@ -0,0 +1,19 @@
package com.gregor_lohaus.gtransfer.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@Value("${spring.servlet.multipart.max-file-size:10GB}")
private String maxFileSize;
@GetMapping("/")
public String index(Model model) {
model.addAttribute("maxFileSize", maxFileSize);
return "index";
}
}

View File

@@ -0,0 +1,37 @@
package com.gregor_lohaus.gtransfer.controller;
import java.io.IOException;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.gregor_lohaus.gtransfer.model.File;
import com.gregor_lohaus.gtransfer.model.FileRepository;
import com.gregor_lohaus.gtransfer.services.filewriter.AbstractStorageService;
@RestController
public class UploadController {
@Autowired
private AbstractStorageService storageService;
@Autowired
private FileRepository fileRepository;
@PostMapping("/upload")
public ResponseEntity<Map<String, String>> upload(
@RequestParam("file") MultipartFile file,
@RequestParam("hash") String hash,
@RequestParam("name") String name) throws IOException {
storageService.put(hash, file.getBytes());
fileRepository.save(new File(hash, hash, name, null));
return ResponseEntity.ok(Map.of("id", hash));
}
}

View File

@@ -0,0 +1,54 @@
package com.gregor_lohaus.gtransfer.model;
import java.time.LocalDateTime;
import jakarta.persistence.*;
@Entity
@Table(name = "files")
public class File {
protected File() {}
@Id
private String id;
private String path;
private String name;
private LocalDateTime expireyDateTime;
private Integer downloadLimit;
public LocalDateTime getExpireyDateTime() {
return expireyDateTime;
}
public void setExpireyDateTime(LocalDateTime expireyDateTime) {
this.expireyDateTime = expireyDateTime;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getDownloadLimit() {
return downloadLimit;
}
public void setDownloadLimit(Integer downloadLimit) {
this.downloadLimit = downloadLimit;
}
public File(String id, String path, String name, LocalDateTime expDateTime) {
this.path = path;
this.name = name;
this.id = id;
this.expireyDateTime = expDateTime;
}
}

View File

@@ -0,0 +1,8 @@
package com.gregor_lohaus.gtransfer.model;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface FileRepository extends JpaRepository<File, String> {
}

View File

@@ -0,0 +1,17 @@
package com.gregor_lohaus.gtransfer.model;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
public class ModelRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.reflection().registerType(File.class,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.ACCESS_DECLARED_FIELDS,
MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS);
}
}

View File

@@ -0,0 +1,121 @@
package com.gregor_lohaus.gtransfer.native_image;
import org.springframework.aot.hint.MemberCategory;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
public class HibernateRuntimeHints implements RuntimeHintsRegistrar {
private static final String[] LOGGER_IMPLEMENTATIONS = {
"org.hibernate.jpa.internal.JpaLogger_$logger",
"org.hibernate.internal.CoreMessageLogger_$logger",
"org.hibernate.internal.log.DeprecationLogger_$logger",
"org.hibernate.internal.log.IncubationLogger_$logger",
"org.hibernate.internal.log.ConnectionAccessLogger_$logger",
"org.hibernate.internal.log.ConnectionInfoLogger_$logger",
"org.hibernate.internal.log.StatisticsLogger_$logger",
"org.hibernate.internal.log.UrlMessageBundle_$logger",
"org.hibernate.internal.SessionFactoryLogging_$logger",
"org.hibernate.internal.SessionFactoryRegistryMessageLogger_$logger",
"org.hibernate.internal.SessionLogging_$logger",
"org.hibernate.boot.BootLogging_$logger",
"org.hibernate.boot.archive.scan.internal.ScannerLogger_$logger",
"org.hibernate.boot.beanvalidation.BeanValidationLogger_$logger",
"org.hibernate.boot.jaxb.JaxbLogger_$logger",
"org.hibernate.dialect.DialectLogging_$logger",
"org.hibernate.engine.jdbc.JdbcLogging_$logger",
"org.hibernate.engine.jdbc.batch.JdbcBatchLogging_$logger",
"org.hibernate.engine.jdbc.connections.internal.ConnectionProviderLogging_$logger",
"org.hibernate.engine.jdbc.env.internal.LobCreationLogging_$logger",
"org.hibernate.engine.jdbc.spi.SQLExceptionLogging_$logger",
"org.hibernate.engine.internal.NaturalIdLogging_$logger",
"org.hibernate.engine.internal.PersistenceContextLogging_$logger",
"org.hibernate.engine.internal.SessionMetricsLogger_$logger",
"org.hibernate.engine.internal.VersionLogger_$logger",
"org.hibernate.resource.jdbc.internal.LogicalConnectionLogging_$logger",
"org.hibernate.resource.jdbc.internal.ResourceRegistryLogger_$logger",
"org.hibernate.resource.transaction.internal.SynchronizationLogging_$logger",
"org.hibernate.resource.transaction.backend.jta.internal.JtaLogging_$logger",
"org.hibernate.resource.beans.internal.BeansMessageLogger_$logger",
"org.hibernate.service.internal.ServiceLogger_$logger",
"org.hibernate.sql.ast.tree.SqlAstTreeLogger_$logger",
"org.hibernate.sql.exec.SqlExecLogger_$logger",
"org.hibernate.sql.model.ModelMutationLogging_$logger",
"org.hibernate.sql.results.LoadingLogger_$logger",
"org.hibernate.sql.results.ResultsLogger_$logger",
"org.hibernate.sql.results.graph.embeddable.EmbeddableLoadingLogger_$logger",
"org.hibernate.query.QueryLogging_$logger",
"org.hibernate.query.hql.HqlLogging_$logger",
"org.hibernate.id.UUIDLogger_$logger",
"org.hibernate.id.enhanced.OptimizerLogger_$logger",
"org.hibernate.id.enhanced.SequenceGeneratorLogger_$logger",
"org.hibernate.id.enhanced.TableGeneratorLogger_$logger",
"org.hibernate.action.internal.ActionLogging_$logger",
"org.hibernate.cache.spi.SecondLevelCacheLogger_$logger",
"org.hibernate.collection.internal.CollectionLogger_$logger",
"org.hibernate.context.internal.CurrentSessionLogging_$logger",
"org.hibernate.event.internal.EntityCopyLogging_$logger",
"org.hibernate.event.internal.EventListenerLogging_$logger",
"org.hibernate.loader.ast.internal.MultiKeyLoadLogging_$logger",
"org.hibernate.metamodel.mapping.MappingModelCreationLogging_$logger",
"org.hibernate.bytecode.enhance.internal.BytecodeEnhancementLogging_$logger",
"org.hibernate.bytecode.enhance.spi.interceptor.BytecodeInterceptorLogging_$logger",
};
private static final Class<?>[] EVENT_LISTENER_TYPES = {
org.hibernate.event.spi.AutoFlushEventListener.class,
org.hibernate.event.spi.ClearEventListener.class,
org.hibernate.event.spi.DeleteEventListener.class,
org.hibernate.event.spi.DirtyCheckEventListener.class,
org.hibernate.event.spi.EvictEventListener.class,
org.hibernate.event.spi.FlushEntityEventListener.class,
org.hibernate.event.spi.FlushEventListener.class,
org.hibernate.event.spi.InitializeCollectionEventListener.class,
org.hibernate.event.spi.LoadEventListener.class,
org.hibernate.event.spi.LockEventListener.class,
org.hibernate.event.spi.MergeEventListener.class,
org.hibernate.event.spi.PersistEventListener.class,
org.hibernate.event.spi.PostCollectionRecreateEventListener.class,
org.hibernate.event.spi.PostCollectionRemoveEventListener.class,
org.hibernate.event.spi.PostCollectionUpdateEventListener.class,
org.hibernate.event.spi.PostCommitDeleteEventListener.class,
org.hibernate.event.spi.PostCommitInsertEventListener.class,
org.hibernate.event.spi.PostCommitUpdateEventListener.class,
org.hibernate.event.spi.PostDeleteEventListener.class,
org.hibernate.event.spi.PostInsertEventListener.class,
org.hibernate.event.spi.PostLoadEventListener.class,
org.hibernate.event.spi.PostUpdateEventListener.class,
org.hibernate.event.spi.PostUpsertEventListener.class,
org.hibernate.event.spi.PreCollectionRecreateEventListener.class,
org.hibernate.event.spi.PreCollectionRemoveEventListener.class,
org.hibernate.event.spi.PreCollectionUpdateEventListener.class,
org.hibernate.event.spi.PreDeleteEventListener.class,
org.hibernate.event.spi.PreFlushEventListener.class,
org.hibernate.event.spi.PreInsertEventListener.class,
org.hibernate.event.spi.PreLoadEventListener.class,
org.hibernate.event.spi.PreUpdateEventListener.class,
org.hibernate.event.spi.PreUpsertEventListener.class,
org.hibernate.event.spi.RefreshEventListener.class,
org.hibernate.event.spi.ReplicateEventListener.class,
};
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
for (String logger : LOGGER_IMPLEMENTATIONS) {
hints.reflection().registerTypeIfPresent(classLoader, logger,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS,
MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS,
MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_PUBLIC_METHODS);
}
for (Class<?> listenerType : EVENT_LISTENER_TYPES) {
hints.reflection().registerType(
listenerType.arrayType(),
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
hints.reflection().registerTypeIfPresent(classLoader,
"org.hibernate.event.spi.PostActionEventListener[]",
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS);
}
}

View File

@@ -0,0 +1,12 @@
package com.gregor_lohaus.gtransfer.native_image;
import org.springframework.aot.hint.RuntimeHints;
import org.springframework.aot.hint.RuntimeHintsRegistrar;
public class WebRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
hints.resources().registerPattern("templates/**");
hints.resources().registerPattern("static/**");
}
}

View File

@@ -0,0 +1,16 @@
package com.gregor_lohaus.gtransfer.services.filewriter;
import java.nio.file.Path;
import java.util.Optional;
import java.util.OptionalLong;
public abstract class AbstractStorageService {
protected Path root;
public AbstractStorageService(Path root) {
this.root = root;
}
abstract public OptionalLong put(String id, byte[] data);
abstract public Optional<byte[]> get(String id);
}

View File

@@ -0,0 +1,22 @@
package com.gregor_lohaus.gtransfer.services.filewriter;
import java.nio.file.Path;
import java.util.Optional;
import java.util.OptionalLong;
public class DummyStorageService extends AbstractStorageService {
public DummyStorageService(Path root) {
super(root);
}
@Override
public OptionalLong put(String id, byte[] data) {
return OptionalLong.empty();
}
@Override
public Optional<byte[]> get(String id) {
return Optional.empty();
}
}

View File

@@ -0,0 +1,36 @@
package com.gregor_lohaus.gtransfer.services.filewriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.OptionalLong;
public class LocalStorageService extends AbstractStorageService {
public LocalStorageService(Path root) {
super(root);
}
@Override
public OptionalLong put(String id, byte[] data) {
try {
Files.createDirectories(root);
Files.write(root.resolve(id), data);
return OptionalLong.of(data.length);
} catch (IOException e) {
return OptionalLong.empty();
}
}
@Override
public Optional<byte[]> get(String id) {
try {
Path target = root.resolve(id);
if (!Files.exists(target)) return Optional.empty();
return Optional.of(Files.readAllBytes(target));
} catch (IOException e) {
return Optional.empty();
}
}
}

View File

@@ -0,0 +1,25 @@
package com.gregor_lohaus.gtransfer.services.filewriter;
import java.nio.file.Path;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.gregor_lohaus.gtransfer.config.types.StorageServiceType;
@Configuration
public class StorageServiceConfiguration {
//TODO S3 implementation
@Bean
public AbstractStorageService storageService(
@Value("${gtransfer-config.storageService.type}") StorageServiceType type,
@Value("${gtransfer-config.storageService.root}") String root) {
return switch (type) {
case LOCAL -> new LocalStorageService(Path.of(root));
case DUMMY -> new DummyStorageService(Path.of(root));
case S3 -> new LocalStorageService(Path.of(root));
};
}
}

View File

@@ -0,0 +1 @@
org.springframework.boot.EnvironmentPostProcessor=com.gregor_lohaus.gtransfer.config.ConfigEnvironmentPostProcessor

View File

@@ -0,0 +1 @@
spring.application.name=gtransfer

View File

@@ -0,0 +1,67 @@
body {
background-color: #0d1117;
color: #e6edf3;
}
.brand {
letter-spacing: -0.5px;
color: #e6edf3;
}
.brand span {
color: #3fb950;
}
.hero-title {
font-size: 3rem;
font-weight: 800;
letter-spacing: -1px;
line-height: 1.1;
}
.hero-title span {
color: #3fb950;
}
.hero-subtitle {
color: #8b949e;
max-width: 480px;
}
.drop-zone {
border: 2px dashed #30363d;
border-radius: 16px;
background-color: #161b22;
cursor: pointer;
transition: border-color 0.2s, background-color 0.2s;
max-width: 520px;
}
.drop-zone:hover,
.drop-zone.dragover {
border-color: #3fb950;
background-color: #0d1117;
}
.drop-zone-icon {
font-size: 2.5rem;
opacity: 0.6;
}
.drop-zone-text {
color: #8b949e;
}
.drop-zone-text strong {
color: #3fb950;
}
.badge-e2e {
background-color: #1a2f1e;
color: #3fb950;
border: 1px solid #2ea043;
font-size: 0.78rem;
}
footer, footer a {
color: #484f58;
}
footer a:hover {
color: #8b949e;
}

View File

@@ -0,0 +1,135 @@
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const views = {
prompt: document.getElementById('view-prompt'),
selected: document.getElementById('view-selected'),
uploading: document.getElementById('view-uploading'),
result: document.getElementById('view-result'),
};
let selectedFile = null;
function showView(name) {
Object.entries(views).forEach(([key, el]) => el.classList.toggle('d-none', key !== name));
}
// ── File selection ────────────────────────────────────────────────────────────
dropZone.addEventListener('click', () => {
if (views.prompt.classList.contains('d-none')) return;
fileInput.click();
});
fileInput.addEventListener('change', e => {
if (e.target.files[0]) selectFile(e.target.files[0]);
});
dropZone.addEventListener('dragover', e => {
e.preventDefault();
dropZone.classList.add('dragover');
});
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
dropZone.addEventListener('drop', e => {
e.preventDefault();
dropZone.classList.remove('dragover');
if (e.dataTransfer.files[0]) selectFile(e.dataTransfer.files[0]);
});
function selectFile(file) {
selectedFile = file;
document.getElementById('selected-name').textContent = file.name;
showView('selected');
}
document.getElementById('reset-btn').addEventListener('click', e => {
e.stopPropagation();
selectedFile = null;
fileInput.value = '';
showView('prompt');
});
document.getElementById('new-upload-btn').addEventListener('click', e => {
e.stopPropagation();
selectedFile = null;
fileInput.value = '';
showView('prompt');
});
// ── Upload ────────────────────────────────────────────────────────────────────
document.getElementById('upload-btn').addEventListener('click', async e => {
e.stopPropagation();
await upload();
});
function setStatus(msg) {
document.getElementById('upload-status').textContent = msg;
}
async function upload() {
const file = selectedFile;
showView('uploading');
try {
setStatus('Generating encryption key\u2026');
const key = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['encrypt', 'decrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
setStatus('Encrypting\u2026');
const ciphertext = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
await file.arrayBuffer()
);
// Payload: 12-byte IV prepended to ciphertext
const payload = new Uint8Array(12 + ciphertext.byteLength);
payload.set(iv, 0);
payload.set(new Uint8Array(ciphertext), 12);
// SHA-256(rawKey) → file identifier sent to server (server never sees the key)
const rawKey = await crypto.subtle.exportKey('raw', key);
const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', rawKey)))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
// Base64url-encode key for URL fragment
const base64urlKey = btoa(String.fromCharCode(...new Uint8Array(rawKey)))
.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
setStatus('Uploading\u2026');
const formData = new FormData();
formData.append('file', new Blob([payload]), file.name);
formData.append('hash', hash);
formData.append('name', file.name);
const response = await fetch('/upload', { method: 'POST', body: formData });
if (!response.ok) throw new Error(`Server responded with ${response.status}`);
const { id } = await response.json();
document.getElementById('share-link').value =
`${window.location.origin}/download/${id}#${base64urlKey}`;
showView('result');
} catch (err) {
setStatus(`Error: ${err.message}`);
}
}
// ── Copy link ─────────────────────────────────────────────────────────────────
document.getElementById('copy-btn').addEventListener('click', async e => {
e.stopPropagation();
await navigator.clipboard.writeText(document.getElementById('share-link').value);
const btn = document.getElementById('copy-btn');
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Copy'; }, 2000);
});

View File

@@ -0,0 +1,87 @@
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" data-bs-theme="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GTransfer</title>
<link rel="stylesheet" th:href="@{/webjars/bootstrap/dist/css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{/style.css}">
<script th:src="@{/webjars/bootstrap/dist/js/bootstrap.bundle.min.js}" defer></script>
<script th:src="@{/webjars/htmx.org/dist/htmx.min.js}" defer></script>
<script th:src="@{/upload.js}" defer></script>
</head>
<body class="d-flex flex-column min-vh-100">
<nav class="navbar px-4 pt-3">
<a class="brand fw-bold text-decoration-none fs-4" href="/">G<span>Transfer</span></a>
<span class="badge-e2e rounded-pill fw-medium px-3 py-1">&#x1F512; End-to-end encrypted</span>
</nav>
<main class="flex-grow-1 d-flex align-items-center justify-content-center py-5 px-3">
<div class="row align-items-center g-5" style="max-width: 960px; width: 100%;">
<div class="col-lg-5">
<h1 class="hero-title">Send files.<br><span>Privately.</span></h1>
<p class="hero-subtitle mt-3">
Share files of any size with end-to-end encryption.
No account needed. Files are encrypted before they leave your device.
</p>
</div>
<div class="col-lg-7 d-flex justify-content-center justify-content-lg-end">
<div id="drop-zone" class="drop-zone text-center py-5 px-4 w-100">
<!-- State: prompt (default) -->
<div id="view-prompt">
<div class="drop-zone-icon mb-3">&#x1F4C2;</div>
<div class="mb-2">
<strong>Choose a file</strong>
<span class="drop-zone-text"> or drag and drop here</span>
</div>
<div class="drop-zone-text small">Any file type &middot; Up to <span th:text="${maxFileSize}">10GB</span></div>
</div>
<!-- State: file selected -->
<div id="view-selected" class="d-none">
<div class="drop-zone-icon mb-3">&#x1F4C4;</div>
<div class="fw-medium mb-3" id="selected-name"></div>
<div class="d-flex gap-2 justify-content-center">
<button id="upload-btn" class="btn btn-success px-4">Send</button>
<button id="reset-btn" class="btn btn-link drop-zone-text text-decoration-none">Change file</button>
</div>
</div>
<!-- State: uploading -->
<div id="view-uploading" class="d-none">
<div class="mb-3">
<div class="spinner-border text-success" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
<div class="drop-zone-text" id="upload-status">Preparing&hellip;</div>
</div>
<!-- State: result -->
<div id="view-result" class="d-none">
<div class="drop-zone-icon mb-3">&#x2705;</div>
<div class="drop-zone-text mb-3">Your file is ready to share</div>
<div class="input-group mb-2">
<input type="text" id="share-link" class="form-control form-control-sm" readonly>
<button id="copy-btn" class="btn btn-outline-success btn-sm">Copy</button>
</div>
<button id="new-upload-btn" class="btn btn-link drop-zone-text text-decoration-none small">
Send another file
</button>
</div>
<input type="file" id="file-input" hidden>
</div>
</div>
</div>
</main>
<footer class="text-center p-4 small">
<a href="https://github.com/gregor-lohaus/gtransfer">Open source</a>
&middot; No tracking &middot; No ads
</footer>
</body>
</html>

View File

@@ -0,0 +1,13 @@
package com.gregor_lohaus.gtransfer;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class GtransferApplicationTests {
@Test
void contextLoads() {
}
}