Compare commits

..

No commits in common. "0ad45adac1645cc3b0d93f1a979e697b7134b4df" and "a38ac6b6f5a9b3c281028a2505f31fa84b562ff8" have entirely different histories.

41 changed files with 890 additions and 380 deletions

View File

@ -29,10 +29,6 @@ sourceSets {
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
testFixturesImplementation {
extendsFrom implementation
}
@ -64,8 +60,6 @@ dependencies {
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
// flyway
implementation 'org.flywaydb:flyway-core'

Binary file not shown.

View File

@ -1,6 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.0-bin.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME

13
gradlew vendored
View File

@ -1,7 +1,7 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -15,8 +15,6 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
@ -86,7 +84,7 @@ done
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@ -114,6 +112,7 @@ case "$( uname )" in #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@ -171,6 +170,7 @@ fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
@ -203,14 +203,15 @@ fi
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.

5
gradlew.bat vendored
View File

@ -13,8 +13,6 @@
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@ -70,10 +68,11 @@ goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell

View File

@ -1,7 +1,7 @@
package app.mealsmadeeasy.api.recipe;
import app.mealsmadeeasy.api.IntegrationTestsExtension;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import app.mealsmadeeasy.api.user.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -26,9 +26,9 @@ public class RecipeRepositoryTests {
@Autowired
private UserRepository userRepository;
private User seedUser() {
private UserEntity seedUser() {
final String uuid = UUID.randomUUID().toString();
final User draft = User.getDefaultDraft();
final UserEntity draft = UserEntity.getDefaultDraft();
draft.setUsername(uuid);
draft.setEmail(uuid + "@test.com");
draft.setPassword("test");
@ -37,57 +37,57 @@ public class RecipeRepositoryTests {
@Test
public void findsAllPublicRecipes() {
final Recipe publicRecipe = new Recipe();
final RecipeEntity publicRecipe = new RecipeEntity();
publicRecipe.setCreated(OffsetDateTime.now());
publicRecipe.setSlug(UUID.randomUUID().toString());
publicRecipe.setIsPublic(true);
publicRecipe.setPublic(true);
publicRecipe.setOwner(this.seedUser());
publicRecipe.setTitle("Public Recipe");
publicRecipe.setRawText("Hello, World!");
final Recipe savedRecipe = this.recipeRepository.save(publicRecipe);
final RecipeEntity savedRecipe = this.recipeRepository.save(publicRecipe);
final List<Recipe> publicRecipes = this.recipeRepository.findAllByIsPublicIsTrue();
final List<RecipeEntity> publicRecipes = this.recipeRepository.findAllByIsPublicIsTrue();
assertThat(publicRecipes).anyMatch(recipeEntity -> recipeEntity.getId().equals(savedRecipe.getId()));
}
@Test
public void doesNotFindNonPublicRecipe() {
final Recipe nonPublicRecipe = new Recipe();
final RecipeEntity nonPublicRecipe = new RecipeEntity();
nonPublicRecipe.setCreated(OffsetDateTime.now());
nonPublicRecipe.setSlug(UUID.randomUUID().toString());
nonPublicRecipe.setOwner(this.seedUser());
nonPublicRecipe.setTitle("Non-Public Recipe");
nonPublicRecipe.setRawText("Hello, World!");
final Recipe savedRecipe = this.recipeRepository.save(nonPublicRecipe);
final RecipeEntity savedRecipe = this.recipeRepository.save(nonPublicRecipe);
final List<Recipe> publicRecipes = this.recipeRepository.findAllByIsPublicIsTrue();
final List<RecipeEntity> publicRecipes = this.recipeRepository.findAllByIsPublicIsTrue();
assertThat(publicRecipes).noneMatch(recipeEntity -> recipeEntity.getId().equals(savedRecipe.getId()));
}
@Test
public void findsAllForViewer() {
final Recipe recipe = new Recipe();
final RecipeEntity recipe = new RecipeEntity();
recipe.setCreated(OffsetDateTime.now());
recipe.setSlug(UUID.randomUUID().toString());
recipe.setOwner(this.seedUser());
recipe.setTitle("Test Recipe");
recipe.setRawText("Hello, World!");
final Recipe saved = this.recipeRepository.save(recipe);
final RecipeEntity saved = this.recipeRepository.save(recipe);
final User viewer = this.seedUser();
final Set<User> viewers = new HashSet<>(recipe.getViewers());
final UserEntity viewer = this.seedUser();
final Set<UserEntity> viewers = new HashSet<>(recipe.getViewerEntities());
viewers.add(viewer);
saved.setViewers(viewers);
this.recipeRepository.save(saved);
final List<Recipe> viewable = this.recipeRepository.findAllByViewersContaining(viewer);
final List<RecipeEntity> viewable = this.recipeRepository.findAllByViewersContaining(viewer);
assertThat(viewable.size()).isEqualTo(1);
}
@Test
public void doesNotIncludeNonViewable() {
final Recipe recipe = new Recipe();
final RecipeEntity recipe = new RecipeEntity();
recipe.setCreated(OffsetDateTime.now());
recipe.setSlug(UUID.randomUUID().toString());
recipe.setOwner(this.seedUser());
@ -95,8 +95,8 @@ public class RecipeRepositoryTests {
recipe.setRawText("Hello, World!");
this.recipeRepository.save(recipe);
final User viewer = this.seedUser();
final List<Recipe> viewable = this.recipeRepository.findAllByViewersContaining(viewer);
final UserEntity viewer = this.seedUser();
final List<RecipeEntity> viewable = this.recipeRepository.findAllByViewersContaining(viewer);
assertThat(viewable.size()).isEqualTo(0);
}

View File

@ -8,6 +8,7 @@ import app.mealsmadeeasy.api.recipe.star.RecipeStar;
import app.mealsmadeeasy.api.recipe.star.RecipeStarService;
import app.mealsmadeeasy.api.recipe.view.RecipeInfoView;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import app.mealsmadeeasy.api.user.UserRepository;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.Test;
@ -44,9 +45,9 @@ public class RecipeServiceTests {
@Autowired
private UserRepository userRepository;
private User seedUser() {
private UserEntity seedUser() {
final String uuid = UUID.randomUUID().toString();
final User draft = User.getDefaultDraft();
final UserEntity draft = UserEntity.getDefaultDraft();
draft.setUsername(uuid);
draft.setEmail(uuid + "@test.com");
draft.setPassword("test");
@ -99,7 +100,7 @@ public class RecipeServiceTests {
assertThat(byId.getSlug(), is(recipe.getSlug()));
assertThat(byId.getTitle(), is("My Recipe"));
assertThat(byId.getRawText(), is("Hello!"));
assertThat(byId.getIsPublic(), is(true));
assertThat(byId.isPublic(), is(true));
}
@Test

View File

@ -1,9 +1,9 @@
package app.mealsmadeeasy.api.recipe.star;
import app.mealsmadeeasy.api.IntegrationTestsExtension;
import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.recipe.RecipeEntity;
import app.mealsmadeeasy.api.recipe.RecipeRepository;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import app.mealsmadeeasy.api.user.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -29,8 +29,8 @@ public class RecipeStarRepositoryTests {
@Autowired
private UserRepository userRepository;
private User seedUser() {
final User draft = User.getDefaultDraft();
private UserEntity seedUser() {
final UserEntity draft = UserEntity.getDefaultDraft();
final String uuid = UUID.randomUUID().toString();
draft.setUsername(uuid);
draft.setEmail(uuid + "@test.com");
@ -38,8 +38,8 @@ public class RecipeStarRepositoryTests {
return this.userRepository.save(draft);
}
private Recipe getTestRecipe(User owner) {
final Recipe recipeDraft = new Recipe();
private RecipeEntity getTestRecipe(UserEntity owner) {
final RecipeEntity recipeDraft = new RecipeEntity();
recipeDraft.setCreated(OffsetDateTime.now());
recipeDraft.setSlug(UUID.randomUUID().toString());
recipeDraft.setOwner(owner);
@ -50,10 +50,10 @@ public class RecipeStarRepositoryTests {
@Test
public void returnsTrueIfStarer() {
final User owner = this.seedUser();
final Recipe recipe = this.getTestRecipe(owner);
final UserEntity owner = this.seedUser();
final RecipeEntity recipe = this.getTestRecipe(owner);
final RecipeStar starDraft = new RecipeStar();
final RecipeStarEntity starDraft = new RecipeStarEntity();
final RecipeStarId starId = new RecipeStarId();
starId.setRecipeId(recipe.getId());
starId.getOwnerId(owner.getId());
@ -72,8 +72,8 @@ public class RecipeStarRepositoryTests {
@Test
public void returnsFalseIfNotStarer() {
final User owner = this.seedUser();
final Recipe recipe = this.getTestRecipe(owner);
final UserEntity owner = this.seedUser();
final RecipeEntity recipe = this.getTestRecipe(owner);
assertThat(
this.recipeStarRepository.isStarer(
recipe.getOwner().getUsername(),

View File

@ -1,7 +1,7 @@
package app.mealsmadeeasy.api;
import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.recipe.RecipeEmbeddingEntity;
import app.mealsmadeeasy.api.recipe.RecipeEntity;
import app.mealsmadeeasy.api.recipe.RecipeRepository;
import app.mealsmadeeasy.api.recipe.RecipeService;
import org.slf4j.Logger;
@ -37,20 +37,20 @@ public class BackfillRecipeEmbeddings implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
final List<Recipe> recipeEntities = this.recipeRepository.findAllByEmbeddingIsNull();
for (final Recipe recipe : recipeEntities) {
logger.info("Calculating embedding for {}", recipe);
final String renderedMarkdown = this.recipeService.getRenderedMarkdown(recipe);
final String toEmbed = "<h1>" + recipe.getTitle() + "</h1>" + renderedMarkdown;
final List<RecipeEntity> recipeEntities = this.recipeRepository.findAllByEmbeddingIsNull();
for (final RecipeEntity recipeEntity : recipeEntities) {
logger.info("Calculating embedding for {}", recipeEntity);
final String renderedMarkdown = this.recipeService.getRenderedMarkdown(recipeEntity);
final String toEmbed = "<h1>" + recipeEntity.getTitle() + "</h1>" + renderedMarkdown;
final float[] embedding = this.embeddingModel.embed(toEmbed);
final RecipeEmbeddingEntity recipeEmbedding = new RecipeEmbeddingEntity();
recipeEmbedding.setRecipe(recipe);
recipeEmbedding.setRecipe(recipeEntity);
recipeEmbedding.setEmbedding(embedding);
recipeEmbedding.setTimestamp(OffsetDateTime.now());
recipe.setEmbedding(recipeEmbedding);
recipeEntity.setEmbedding(recipeEmbedding);
this.recipeRepository.save(recipe);
this.recipeRepository.save(recipeEntity);
}
this.recipeRepository.flush();
}

View File

@ -1,7 +1,7 @@
package app.mealsmadeeasy.api.auth;
import app.mealsmadeeasy.api.jwt.JwtService;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import jakarta.transaction.Transactional;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Value;
@ -36,7 +36,7 @@ public class AuthServiceImpl implements AuthService {
this.refreshTokenLifetime = refreshTokenLifetime;
}
private RefreshToken createRefreshToken(User principal) {
private RefreshToken createRefreshToken(UserEntity principal) {
final RefreshTokenEntity refreshTokenDraft = new RefreshTokenEntity();
refreshTokenDraft.setToken(UUID.randomUUID());
refreshTokenDraft.setIssued(OffsetDateTime.now());
@ -51,7 +51,7 @@ public class AuthServiceImpl implements AuthService {
final Authentication authentication = this.authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(username, password)
);
final User principal = (User) authentication.getPrincipal();
final UserEntity principal = (UserEntity) authentication.getPrincipal();
return new LoginDetails(
username,
this.jwtService.generateAccessToken(username),
@ -87,7 +87,7 @@ public class AuthServiceImpl implements AuthService {
throw new LoginException(LoginExceptionReason.EXPIRED_REFRESH_TOKEN, "Refresh token is expired.");
}
final User principal = old.getOwner();
final UserEntity principal = old.getOwner();
old.setDeleted(true);
this.refreshTokenRepository.save(old);

View File

@ -1,6 +1,6 @@
package app.mealsmadeeasy.api.auth;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import jakarta.persistence.*;
import java.time.OffsetDateTime;
@ -23,7 +23,7 @@ public class RefreshTokenEntity implements RefreshToken {
@ManyToOne(optional = false)
@JoinColumn(name = "owner_id", nullable = false)
private User owner;
private UserEntity owner;
@Column(nullable = false)
private Boolean deleted = false;
@ -67,11 +67,11 @@ public class RefreshTokenEntity implements RefreshToken {
this.revoked = revoked;
}
public User getOwner() {
public UserEntity getOwner() {
return this.owner;
}
public void setOwner(User owner) {
public void setOwner(UserEntity owner) {
this.owner = owner;
}

View File

@ -1,6 +1,7 @@
package app.mealsmadeeasy.api.image;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import jakarta.persistence.*;
import org.jetbrains.annotations.Nullable;
@ -41,7 +42,7 @@ public class S3ImageEntity implements Image {
@ManyToOne(optional = false)
@JoinColumn(name = "owner_id", nullable = false)
private User owner;
private UserEntity owner;
@Column(nullable = false)
private Boolean isPublic = false;
@ -52,7 +53,7 @@ public class S3ImageEntity implements Image {
joinColumns = @JoinColumn(name = "image_id"),
inverseJoinColumns = @JoinColumn(name = "viewer_id")
)
private Set<User> viewers = new HashSet<>();
private Set<UserEntity> viewers = new HashSet<>();
@Override
public Integer getId() {
@ -148,7 +149,7 @@ public class S3ImageEntity implements Image {
return this.owner;
}
public void setOwner(User owner) {
public void setOwner(UserEntity owner) {
this.owner = owner;
}
@ -166,11 +167,11 @@ public class S3ImageEntity implements Image {
return Set.copyOf(this.viewers);
}
public Set<User> getViewerEntities() {
public Set<UserEntity> getViewerEntities() {
return this.viewers;
}
public void setViewers(Set<User> viewers) {
public void setViewers(Set<UserEntity> viewers) {
this.viewers = viewers;
}

View File

@ -1,6 +1,6 @@
package app.mealsmadeeasy.api.image;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
@ -14,8 +14,8 @@ public interface S3ImageRepository extends JpaRepository<S3ImageEntity, Long> {
@EntityGraph(attributePaths = { "viewers" })
S3ImageEntity getByIdWithViewers(long id);
List<S3ImageEntity> findAllByOwner(User owner);
Optional<S3ImageEntity> findByOwnerAndUserFilename(User owner, String filename);
List<S3ImageEntity> findAllByOwner(UserEntity owner);
Optional<S3ImageEntity> findByOwnerAndUserFilename(UserEntity owner, String filename);
@Query("SELECT image from Image image WHERE image.owner.username = ?1 AND image.userFilename = ?2")
Optional<S3ImageEntity> findByOwnerUsernameAndFilename(String username, String filename);

View File

@ -5,6 +5,7 @@ import app.mealsmadeeasy.api.image.spec.ImageUpdateInfoSpec;
import app.mealsmadeeasy.api.image.view.ImageView;
import app.mealsmadeeasy.api.s3.S3Manager;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PostAuthorize;
@ -94,9 +95,9 @@ public class S3ImageService implements ImageService {
}
final @Nullable Set<User> viewersToAdd = spec.getViewersToAdd();
if (viewersToAdd != null) {
final Set<User> viewers = new HashSet<>(entity.getViewerEntities());
final Set<UserEntity> viewers = new HashSet<>(entity.getViewerEntities());
for (final User viewerToAdd : spec.getViewersToAdd()) {
viewers.add((User) viewerToAdd);
viewers.add((UserEntity) viewerToAdd);
}
entity.setViewers(viewers);
didTransfer = true;
@ -153,7 +154,7 @@ public class S3ImageService implements ImageService {
inputStream.close();
final S3ImageEntity draft = new S3ImageEntity();
draft.setOwner((User) owner);
draft.setOwner((UserEntity) owner);
draft.setUserFilename(userFilename);
draft.setMimeType(mimeType);
draft.setObjectName(objectName);
@ -174,7 +175,7 @@ public class S3ImageService implements ImageService {
@Override
@PostAuthorize("@imageSecurity.isViewableBy(returnObject, #viewer)")
public Image getByOwnerAndFilename(User owner, String filename, User viewer) throws ImageException {
return this.imageRepository.findByOwnerAndUserFilename((User) owner, filename)
return this.imageRepository.findByOwnerAndUserFilename((UserEntity) owner, filename)
.orElseThrow(() -> new ImageException(
ImageException.Type.IMAGE_NOT_FOUND,
"No such image for owner " + owner + " with filename " + filename
@ -200,7 +201,7 @@ public class S3ImageService implements ImageService {
@Override
public List<Image> getImagesOwnedBy(User user) {
return new ArrayList<>(this.imageRepository.findAllByOwner((User) user));
return new ArrayList<>(this.imageRepository.findAllByOwner((UserEntity) user));
}
@Override
@ -215,9 +216,9 @@ public class S3ImageService implements ImageService {
} else {
final @Nullable Set<User> viewersToRemove = updateSpec.getViewersToRemove();
if (viewersToRemove != null) {
final Set<User> currentViewers = new HashSet<>(entity.getViewerEntities());
final Set<UserEntity> currentViewers = new HashSet<>(entity.getViewerEntities());
for (final User toRemove : updateSpec.getViewersToRemove()) {
currentViewers.remove((User) toRemove);
currentViewers.remove((UserEntity) toRemove);
}
entity.setViewers(currentViewers);
didUpdate = true;

View File

@ -1,83 +1,28 @@
package app.mealsmadeeasy.api.recipe;
import app.mealsmadeeasy.api.image.S3ImageEntity;
import app.mealsmadeeasy.api.image.Image;
import app.mealsmadeeasy.api.recipe.comment.RecipeComment;
import app.mealsmadeeasy.api.recipe.star.RecipeStar;
import app.mealsmadeeasy.api.user.User;
import jakarta.persistence.*;
import lombok.Data;
import org.jetbrains.annotations.Nullable;
import java.time.OffsetDateTime;
import java.util.HashSet;
import java.util.Set;
@Entity(name = "Recipe")
@Data
public final class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false)
private Integer id;
@Column(nullable = false)
private OffsetDateTime created;
private OffsetDateTime modified;
@Column(nullable = false, unique = true)
private String slug;
@Column(nullable = false)
private String title;
@Nullable
private Integer preparationTime;
@Nullable
private Integer cookingTime;
@Nullable
private Integer totalTime;
@Lob
@Column(name = "raw_text", columnDefinition = "TEXT", nullable = false)
@Basic(fetch = FetchType.LAZY)
private String rawText;
@Lob
@Column(name = "cached_rendered_text", columnDefinition = "TEXT")
@Basic(fetch = FetchType.LAZY)
private String cachedRenderedText;
@ManyToOne(optional = false)
@JoinColumn(name = "owner_id", nullable = false)
private User owner;
@OneToMany
@JoinColumn(name = "recipe_id")
private Set<RecipeStar> stars = new HashSet<>();
@OneToMany(mappedBy = "recipe")
private Set<RecipeComment> comments = new HashSet<>();
@Column(nullable = false)
private Boolean isPublic = false;
@ManyToMany
@JoinTable(
name = "recipe_viewer",
joinColumns = @JoinColumn(name = "recipe_id"),
inverseJoinColumns = @JoinColumn(name = "viewer_id")
)
private Set<User> viewers = new HashSet<>();
@ManyToOne
@JoinColumn(name = "main_image_id")
private S3ImageEntity mainImage;
@OneToOne(mappedBy = "recipe", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private RecipeEmbeddingEntity embedding;
public interface Recipe {
Integer getId();
OffsetDateTime getCreated();
@Nullable OffsetDateTime getModified();
String getSlug();
String getTitle();
@Nullable Integer getPreparationTime();
@Nullable Integer getCookingTime();
@Nullable Integer getTotalTime();
String getRawText();
User getOwner();
Set<RecipeStar> getStars();
boolean isPublic();
Set<User> getViewers();
Set<RecipeComment> getComments();
@Nullable Image getMainImage();
}

View File

@ -18,7 +18,7 @@ public class RecipeEmbeddingEntity {
@OneToOne(fetch = FetchType.LAZY, optional = false)
@MapsId
@JoinColumn(name = "recipe_id")
private Recipe recipe;
private RecipeEntity recipe;
@JdbcTypeCode(SqlTypes.VECTOR)
@Array(length = 1024)
@ -36,11 +36,11 @@ public class RecipeEmbeddingEntity {
this.id = id;
}
public Recipe getRecipe() {
public RecipeEntity getRecipe() {
return this.recipe;
}
public void setRecipe(Recipe recipe) {
public void setRecipe(RecipeEntity recipe) {
this.recipe = recipe;
}

View File

@ -0,0 +1,252 @@
package app.mealsmadeeasy.api.recipe;
import app.mealsmadeeasy.api.image.S3ImageEntity;
import app.mealsmadeeasy.api.recipe.comment.RecipeComment;
import app.mealsmadeeasy.api.recipe.comment.RecipeCommentEntity;
import app.mealsmadeeasy.api.recipe.star.RecipeStar;
import app.mealsmadeeasy.api.recipe.star.RecipeStarEntity;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import jakarta.persistence.*;
import org.jetbrains.annotations.Nullable;
import java.time.OffsetDateTime;
import java.util.HashSet;
import java.util.Set;
@Entity(name = "Recipe")
public final class RecipeEntity implements Recipe {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false)
private Integer id;
@Column(nullable = false)
private OffsetDateTime created;
private OffsetDateTime modified;
@Column(nullable = false, unique = true)
private String slug;
@Column(nullable = false)
private String title;
@Nullable
private Integer preparationTime;
@Nullable
private Integer cookingTime;
@Nullable
private Integer totalTime;
@Lob
@Column(name = "raw_text", columnDefinition = "TEXT", nullable = false)
@Basic(fetch = FetchType.LAZY)
private String rawText;
@Lob
@Column(name = "cached_rendered_text", columnDefinition = "TEXT")
@Basic(fetch = FetchType.LAZY)
private String cachedRenderedText;
@ManyToOne(optional = false)
@JoinColumn(name = "owner_id", nullable = false)
private UserEntity owner;
@OneToMany
@JoinColumn(name = "recipe_id")
private Set<RecipeStarEntity> stars = new HashSet<>();
@OneToMany(mappedBy = "recipe")
private Set<RecipeCommentEntity> comments = new HashSet<>();
@Column(nullable = false)
private Boolean isPublic = false;
@ManyToMany
@JoinTable(
name = "recipe_viewer",
joinColumns = @JoinColumn(name = "recipe_id"),
inverseJoinColumns = @JoinColumn(name = "viewer_id")
)
private Set<UserEntity> viewers = new HashSet<>();
@ManyToOne
@JoinColumn(name = "main_image_id")
private S3ImageEntity mainImage;
@OneToOne(mappedBy = "recipe", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
private RecipeEmbeddingEntity embedding;
@Override
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public OffsetDateTime getCreated() {
return this.created;
}
public void setCreated(OffsetDateTime created) {
this.created = created;
}
@Override
public @Nullable OffsetDateTime getModified() {
return this.modified;
}
public void setModified(@Nullable OffsetDateTime modified) {
this.modified = modified;
}
@Override
public String getSlug() {
return this.slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
@Override
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public @Nullable Integer getPreparationTime() {
return this.preparationTime;
}
public void setPreparationTime(@Nullable Integer preparationTime) {
this.preparationTime = preparationTime;
}
@Override
public @Nullable Integer getCookingTime() {
return this.cookingTime;
}
public void setCookingTime(@Nullable Integer cookingTime) {
this.cookingTime = cookingTime;
}
@Override
public @Nullable Integer getTotalTime() {
return this.totalTime;
}
public void setTotalTime(@Nullable Integer totalTime) {
this.totalTime = totalTime;
}
@Override
public String getRawText() {
return this.rawText;
}
public void setRawText(String rawText) {
this.rawText = rawText;
}
public @Nullable String getCachedRenderedText() {
return this.cachedRenderedText;
}
public void setCachedRenderedText(@Nullable String cachedRenderedText) {
this.cachedRenderedText = cachedRenderedText;
}
@Override
public UserEntity getOwner() {
return this.owner;
}
public void setOwner(UserEntity owner) {
this.owner = owner;
}
@Override
public boolean isPublic() {
return this.isPublic;
}
public void setPublic(Boolean isPublic) {
this.isPublic = isPublic;
}
@Override
public Set<User> getViewers() {
return Set.copyOf(this.viewers);
}
public Set<UserEntity> getViewerEntities() {
return this.viewers;
}
public void setViewers(Set<UserEntity> viewers) {
this.viewers = viewers;
}
@Override
public Set<RecipeStar> getStars() {
return Set.copyOf(this.stars);
}
public Set<RecipeStarEntity> getStarEntities() {
return this.stars;
}
public void setStarEntities(Set<RecipeStarEntity> starGazers) {
this.stars = starGazers;
}
@Override
public Set<RecipeComment> getComments() {
return Set.copyOf(this.comments);
}
public Set<RecipeCommentEntity> getCommentEntities() {
return this.comments;
}
public void setComments(Set<RecipeCommentEntity> comments) {
this.comments = comments;
}
@Override
public String toString() {
return "RecipeEntity(" + this.id + ", " + this.title + ")";
}
@Override
public @Nullable S3ImageEntity getMainImage() {
return this.mainImage;
}
public void setMainImage(@Nullable S3ImageEntity image) {
this.mainImage = image;
}
public RecipeEmbeddingEntity getEmbedding() {
return this.embedding;
}
public void setEmbedding(RecipeEmbeddingEntity embedding) {
this.embedding = embedding;
}
}

View File

@ -1,6 +1,6 @@
package app.mealsmadeeasy.api.recipe;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.EntityGraph;
@ -10,27 +10,27 @@ import org.springframework.data.jpa.repository.Query;
import java.util.List;
import java.util.Optional;
public interface RecipeRepository extends JpaRepository<Recipe, Long> {
public interface RecipeRepository extends JpaRepository<RecipeEntity, Long> {
List<Recipe> findAllByIsPublicIsTrue();
List<RecipeEntity> findAllByIsPublicIsTrue();
List<Recipe> findAllByViewersContaining(User viewer);
List<RecipeEntity> findAllByViewersContaining(UserEntity viewer);
List<Recipe> findAllByOwner(User owner);
List<RecipeEntity> findAllByOwner(UserEntity owner);
@Query("SELECT r from Recipe r WHERE r.owner.username = ?1 AND r.slug = ?2")
Optional<Recipe> findByOwnerUsernameAndSlug(String ownerUsername, String slug);
Optional<RecipeEntity> findByOwnerUsernameAndSlug(String ownerUsername, String slug);
@Query("SELECT r FROM Recipe r WHERE size(r.stars) >= ?1 AND (r.isPublic OR ?2 MEMBER OF r.viewers)")
List<Recipe> findAllViewableByStarsGreaterThanEqual(long stars, User viewer);
List<RecipeEntity> findAllViewableByStarsGreaterThanEqual(long stars, UserEntity viewer);
@Query("SELECT r FROM Recipe r WHERE r.id = ?1")
@EntityGraph(attributePaths = { "viewers" })
Optional<Recipe> findByIdWithViewers(long id);
Optional<RecipeEntity> findByIdWithViewers(long id);
@Query("SELECT r FROM Recipe r WHERE r.id = ?1")
@EntityGraph(attributePaths = { "stars" })
Optional<Recipe> findByIdWithStars(long id);
Optional<RecipeEntity> findByIdWithStars(long id);
@Query("SELECT size(r.stars) FROM Recipe r WHERE r.id = ?1")
int getStarCount(long recipeId);
@ -39,9 +39,9 @@ public interface RecipeRepository extends JpaRepository<Recipe, Long> {
int getViewerCount(long recipeId);
@Query("SELECT r FROM Recipe r WHERE r.isPublic OR r.owner = ?1 OR ?1 MEMBER OF r.viewers")
Slice<Recipe> findAllViewableBy(User viewer, Pageable pageable);
Slice<RecipeEntity> findAllViewableBy(UserEntity viewer, Pageable pageable);
List<Recipe> findAllByEmbeddingIsNull();
List<RecipeEntity> findAllByEmbeddingIsNull();
@Query(
nativeQuery = true,
@ -57,7 +57,7 @@ public interface RecipeRepository extends JpaRepository<Recipe, Long> {
ORDER BY d.distance;
"""
)
List<Recipe> searchByEmbeddingAndViewableBy(float[] queryEmbedding, float similarity, Integer viewerId);
List<RecipeEntity> searchByEmbeddingAndViewableBy(float[] queryEmbedding, float similarity, Integer viewerId);
@Query(
nativeQuery = true,
@ -69,6 +69,6 @@ public interface RecipeRepository extends JpaRepository<Recipe, Long> {
ORDER BY d.distance;
"""
)
List<Recipe> searchByEmbeddingAndIsPublic(float[] queryEmbedding, float similarity);
List<RecipeEntity> searchByEmbeddingAndIsPublic(float[] queryEmbedding, float similarity);
}

View File

@ -42,7 +42,7 @@ public class RecipeSecurityImpl implements RecipeSecurity {
@Override
public boolean isViewableBy(Recipe recipe, @Nullable User user) throws RecipeException {
if (recipe.getIsPublic()) {
if (recipe.isPublic()) {
// public recipe
return true;
} else if (user == null) {
@ -53,7 +53,7 @@ public class RecipeSecurityImpl implements RecipeSecurity {
return true;
} else {
// check if viewer
final Recipe withViewers = this.recipeRepository.findByIdWithViewers(recipe.getId())
final RecipeEntity withViewers = this.recipeRepository.findByIdWithViewers(recipe.getId())
.orElseThrow(() -> new RecipeException(
RecipeException.Type.INVALID_ID, "No such Recipe with id: " + recipe.getId()
));

View File

@ -58,6 +58,6 @@ public interface RecipeService {
@Nullable Boolean isOwner(String username, String slug, @Nullable User viewer);
@ApiStatus.Internal
String getRenderedMarkdown(Recipe entity);
String getRenderedMarkdown(RecipeEntity entity);
}

View File

@ -13,6 +13,7 @@ import app.mealsmadeeasy.api.recipe.star.RecipeStarRepository;
import app.mealsmadeeasy.api.recipe.view.FullRecipeView;
import app.mealsmadeeasy.api.recipe.view.RecipeInfoView;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
@ -57,18 +58,18 @@ public class RecipeServiceImpl implements RecipeService {
if (owner == null) {
throw new AccessDeniedException("Must be logged in.");
}
final Recipe draft = new Recipe();
final RecipeEntity draft = new RecipeEntity();
draft.setCreated(OffsetDateTime.now());
draft.setOwner((User) owner);
draft.setOwner((UserEntity) owner);
draft.setSlug(spec.getSlug());
draft.setTitle(spec.getTitle());
draft.setRawText(spec.getRawText());
draft.setMainImage((S3ImageEntity) spec.getMainImage());
draft.setIsPublic(spec.isPublic());
draft.setPublic(spec.isPublic());
return this.recipeRepository.save(draft);
}
private Recipe findRecipeEntity(long id) throws RecipeException {
private RecipeEntity findRecipeEntity(long id) throws RecipeException {
return this.recipeRepository.findById(id).orElseThrow(() -> new RecipeException(
RecipeException.Type.INVALID_ID, "No such Recipe with id: " + id
));
@ -100,7 +101,7 @@ public class RecipeServiceImpl implements RecipeService {
@Override
@ApiStatus.Internal
public String getRenderedMarkdown(Recipe entity) {
public String getRenderedMarkdown(RecipeEntity entity) {
if (entity.getCachedRenderedText() == null) {
entity.setCachedRenderedText(this.markdownService.renderAndCleanMarkdown(entity.getRawText()));
entity = this.recipeRepository.save(entity);
@ -125,7 +126,7 @@ public class RecipeServiceImpl implements RecipeService {
}
}
private FullRecipeView getFullView(Recipe recipe, boolean includeRawText, @Nullable User viewer) {
private FullRecipeView getFullView(RecipeEntity recipe, boolean includeRawText, @Nullable User viewer) {
return FullRecipeView.from(
recipe,
this.getRenderedMarkdown(recipe),
@ -136,7 +137,7 @@ public class RecipeServiceImpl implements RecipeService {
);
}
private RecipeInfoView getInfoView(Recipe recipe, @Nullable User viewer) {
private RecipeInfoView getInfoView(RecipeEntity recipe, @Nullable User viewer) {
return RecipeInfoView.from(
recipe,
this.getStarCount(recipe),
@ -147,7 +148,7 @@ public class RecipeServiceImpl implements RecipeService {
@Override
@PreAuthorize("@recipeSecurity.isViewableBy(#id, #viewer)")
public FullRecipeView getFullViewById(long id, @Nullable User viewer) throws RecipeException {
final Recipe recipe = this.recipeRepository.findById(id).orElseThrow(() -> new RecipeException(
final RecipeEntity recipe = this.recipeRepository.findById(id).orElseThrow(() -> new RecipeException(
RecipeException.Type.INVALID_ID, "No such Recipe for id: " + id
));
return this.getFullView(recipe, false, viewer);
@ -161,7 +162,7 @@ public class RecipeServiceImpl implements RecipeService {
boolean includeRawText,
@Nullable User viewer
) throws RecipeException {
final Recipe recipe = this.recipeRepository.findByOwnerUsernameAndSlug(username, slug)
final RecipeEntity recipe = this.recipeRepository.findByOwnerUsernameAndSlug(username, slug)
.orElseThrow(() -> new RecipeException(
RecipeException.Type.INVALID_USERNAME_OR_SLUG,
"No such Recipe for username " + username + " and slug: " + slug
@ -171,7 +172,7 @@ public class RecipeServiceImpl implements RecipeService {
@Override
public Slice<RecipeInfoView> getInfoViewsViewableBy(Pageable pageable, @Nullable User viewer) {
return this.recipeRepository.findAllViewableBy((User) viewer, pageable).map(recipe ->
return this.recipeRepository.findAllViewableBy((UserEntity) viewer, pageable).map(recipe ->
this.getInfoView(recipe, viewer)
);
}
@ -179,7 +180,7 @@ public class RecipeServiceImpl implements RecipeService {
@Override
public List<Recipe> getByMinimumStars(long minimumStars, User viewer) {
return List.copyOf(
this.recipeRepository.findAllViewableByStarsGreaterThanEqual(minimumStars, (User) viewer)
this.recipeRepository.findAllViewableByStarsGreaterThanEqual(minimumStars, (UserEntity) viewer)
);
}
@ -190,18 +191,18 @@ public class RecipeServiceImpl implements RecipeService {
@Override
public List<Recipe> getRecipesViewableBy(User viewer) {
return List.copyOf(this.recipeRepository.findAllByViewersContaining((User) viewer));
return List.copyOf(this.recipeRepository.findAllByViewersContaining((UserEntity) viewer));
}
@Override
public List<Recipe> getRecipesOwnedBy(User owner) {
return List.copyOf(this.recipeRepository.findAllByOwner((User) owner));
return List.copyOf(this.recipeRepository.findAllByOwner((UserEntity) owner));
}
@Override
public List<RecipeInfoView> aiSearch(RecipeAiSearchSpec searchSpec, @Nullable User viewer) {
final float[] queryEmbedding = this.embeddingModel.embed(searchSpec.getPrompt());
final List<Recipe> results;
final List<RecipeEntity> results;
if (viewer == null) {
results = this.recipeRepository.searchByEmbeddingAndIsPublic(queryEmbedding, 0.5f);
} else {
@ -216,7 +217,7 @@ public class RecipeServiceImpl implements RecipeService {
@PreAuthorize("@recipeSecurity.isOwner(#username, #slug, #modifier)")
public Recipe update(String username, String slug, RecipeUpdateSpec spec, User modifier)
throws RecipeException, ImageException {
final Recipe recipe = this.recipeRepository.findByOwnerUsernameAndSlug(username, slug).orElseThrow(() ->
final RecipeEntity recipe = this.recipeRepository.findByOwnerUsernameAndSlug(username, slug).orElseThrow(() ->
new RecipeException(
RecipeException.Type.INVALID_USERNAME_OR_SLUG,
"No such Recipe for username " + username + " and slug: " + slug
@ -229,7 +230,7 @@ public class RecipeServiceImpl implements RecipeService {
recipe.setTotalTime(spec.getTotalTime());
recipe.setRawText(spec.getRawText());
recipe.setCachedRenderedText(null);
recipe.setIsPublic(spec.getIsPublic());
recipe.setPublic(spec.getIsPublic());
final S3ImageEntity mainImage;
if (spec.getMainImage() == null) {
@ -250,11 +251,11 @@ public class RecipeServiceImpl implements RecipeService {
@Override
@PreAuthorize("@recipeSecurity.isOwner(#id, #modifier)")
public Recipe addViewer(long id, User modifier, User viewer) throws RecipeException {
final Recipe entity = this.recipeRepository.findByIdWithViewers(id).orElseThrow(() -> new RecipeException(
final RecipeEntity entity = this.recipeRepository.findByIdWithViewers(id).orElseThrow(() -> new RecipeException(
RecipeException.Type.INVALID_ID, "No such Recipe with id: " + id
));
final Set<User> viewers = new HashSet<>(entity.getViewers());
viewers.add((User) viewer);
final Set<UserEntity> viewers = new HashSet<>(entity.getViewerEntities());
viewers.add((UserEntity) viewer);
entity.setViewers(viewers);
return this.recipeRepository.save(entity);
}
@ -262,9 +263,9 @@ public class RecipeServiceImpl implements RecipeService {
@Override
@PreAuthorize("@recipeSecurity.isOwner(#id, #modifier)")
public Recipe removeViewer(long id, User modifier, User viewer) throws RecipeException {
final Recipe entity = this.findRecipeEntity(id);
final Set<User> viewers = new HashSet<>(entity.getViewers());
viewers.remove((User) viewer);
final RecipeEntity entity = this.findRecipeEntity(id);
final Set<UserEntity> viewers = new HashSet<>(entity.getViewerEntities());
viewers.remove((UserEntity) viewer);
entity.setViewers(viewers);
return this.recipeRepository.save(entity);
}
@ -272,7 +273,7 @@ public class RecipeServiceImpl implements RecipeService {
@Override
@PreAuthorize("@recipeSecurity.isOwner(#id, #modifier)")
public Recipe clearAllViewers(long id, User modifier) throws RecipeException {
final Recipe entity = this.findRecipeEntity(id);
final RecipeEntity entity = this.findRecipeEntity(id);
entity.setViewers(new HashSet<>());
return this.recipeRepository.save(entity);
}
@ -285,12 +286,12 @@ public class RecipeServiceImpl implements RecipeService {
@Override
public FullRecipeView toFullRecipeView(Recipe recipe, boolean includeRawText, @Nullable User viewer) {
return this.getFullView((Recipe) recipe, includeRawText, viewer);
return this.getFullView((RecipeEntity) recipe, includeRawText, viewer);
}
@Override
public RecipeInfoView toRecipeInfoView(Recipe recipe, @Nullable User viewer) {
return this.getInfoView((Recipe) recipe, viewer);
return this.getInfoView((RecipeEntity) recipe, viewer);
}
@Override

View File

@ -2,39 +2,15 @@ package app.mealsmadeeasy.api.recipe.comment;
import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.user.User;
import jakarta.persistence.*;
import lombok.Data;
import org.jetbrains.annotations.Nullable;
import java.time.OffsetDateTime;
@Entity
@Data
public final class RecipeComment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Integer id;
@Column(nullable = false, updatable = false)
private OffsetDateTime created = OffsetDateTime.now();
private OffsetDateTime modified;
@Lob
@Basic(fetch = FetchType.LAZY)
private String rawText;
@Lob
@Basic(fetch = FetchType.LAZY)
private String cachedRenderedText;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false, updatable = false)
private User owner;
@ManyToOne
@JoinColumn(name = "recipe_id", nullable = false, updatable = false)
private Recipe recipe;
public interface RecipeComment {
Integer getId();
OffsetDateTime getCreated();
@Nullable OffsetDateTime getModified();
String getRawText();
User getOwner();
Recipe getRecipe();
}

View File

@ -0,0 +1,100 @@
package app.mealsmadeeasy.api.recipe.comment;
import app.mealsmadeeasy.api.recipe.RecipeEntity;
import app.mealsmadeeasy.api.user.UserEntity;
import jakarta.persistence.*;
import java.time.OffsetDateTime;
@Entity(name = "RecipeComment")
@Table(name = "recipe_comment")
public final class RecipeCommentEntity implements RecipeComment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Integer id;
@Column(nullable = false, updatable = false)
private OffsetDateTime created = OffsetDateTime.now();
private OffsetDateTime modified;
@Lob
@Basic(fetch = FetchType.LAZY)
private String rawText;
@Lob
@Basic(fetch = FetchType.LAZY)
private String cachedRenderedText;
@ManyToOne
@JoinColumn(name = "owner_id", nullable = false, updatable = false)
private UserEntity owner;
@ManyToOne
@JoinColumn(name = "recipe_id", nullable = false, updatable = false)
private RecipeEntity recipe;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public OffsetDateTime getCreated() {
return this.created;
}
public void setCreated(OffsetDateTime created) {
this.created = created;
}
@Override
public OffsetDateTime getModified() {
return this.modified;
}
public void setModified(OffsetDateTime modified) {
this.modified = modified;
}
@Override
public String getRawText() {
return this.rawText;
}
public void setRawText(String rawText) {
this.rawText = rawText;
}
public String getCachedRenderedText() {
return this.cachedRenderedText;
}
public void setCachedRenderedText(String cachedRenderedText) {
this.cachedRenderedText = cachedRenderedText;
}
@Override
public UserEntity getOwner() {
return this.owner;
}
public void setOwner(UserEntity owner) {
this.owner = owner;
}
@Override
public RecipeEntity getRecipe() {
return this.recipe;
}
public void setRecipe(RecipeEntity recipe) {
this.recipe = recipe;
}
}

View File

@ -1,11 +1,11 @@
package app.mealsmadeeasy.api.recipe.comment;
import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.recipe.RecipeEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RecipeCommentRepository extends JpaRepository<RecipeComment, Long> {
void deleteAllByRecipe(Recipe recipe);
Slice<RecipeComment> findAllByRecipe(Recipe recipe, Pageable pageable);
public interface RecipeCommentRepository extends JpaRepository<RecipeCommentEntity, Long> {
void deleteAllByRecipe(RecipeEntity recipe);
Slice<RecipeCommentEntity> findAllByRecipe(RecipeEntity recipe, Pageable pageable);
}

View File

@ -1,10 +1,11 @@
package app.mealsmadeeasy.api.recipe.comment;
import app.mealsmadeeasy.api.markdown.MarkdownService;
import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.recipe.RecipeEntity;
import app.mealsmadeeasy.api.recipe.RecipeException;
import app.mealsmadeeasy.api.recipe.RecipeRepository;
import app.mealsmadeeasy.api.user.User;
import app.mealsmadeeasy.api.user.UserEntity;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.security.access.prepost.PostAuthorize;
@ -41,12 +42,12 @@ public class RecipeCommentServiceImpl implements RecipeCommentService {
RecipeCommentCreateBody body
) throws RecipeException {
requireNonNull(commenter);
final RecipeComment draft = new RecipeComment();
final RecipeCommentEntity draft = new RecipeCommentEntity();
draft.setCreated(OffsetDateTime.now());
draft.setRawText(body.getText());
draft.setCachedRenderedText(this.markdownService.renderAndCleanMarkdown(body.getText()));
draft.setOwner((User) commenter);
final Recipe recipe = this.recipeRepository.findByOwnerUsernameAndSlug(recipeUsername, recipeSlug)
draft.setOwner((UserEntity) commenter);
final RecipeEntity recipe = this.recipeRepository.findByOwnerUsernameAndSlug(recipeUsername, recipeSlug)
.orElseThrow(() -> new RecipeException(
RecipeException.Type.INVALID_USERNAME_OR_SLUG,
"Invalid username or slug: " + recipeUsername + "/" + recipeSlug
@ -56,7 +57,7 @@ public class RecipeCommentServiceImpl implements RecipeCommentService {
}
@PostAuthorize("@recipeSecurity.isViewableBy(returnObject.recipe, #viewer)")
private RecipeComment loadCommentEntity(long commentId, User viewer) throws RecipeException {
private RecipeCommentEntity loadCommentEntity(long commentId, User viewer) throws RecipeException {
return this.recipeCommentRepository.findById(commentId).orElseThrow(() -> new RecipeException(
RecipeException.Type.INVALID_COMMENT_ID, "No such RecipeComment for id: " + commentId
));
@ -70,13 +71,13 @@ public class RecipeCommentServiceImpl implements RecipeCommentService {
@Override
@PreAuthorize("@recipeSecurity.isViewableBy(#recipeUsername, #recipeSlug, #viewer)")
public Slice<RecipeCommentView> getComments(String recipeUsername, String recipeSlug, Pageable pageable, User viewer) throws RecipeException {
final Recipe recipe = this.recipeRepository.findByOwnerUsernameAndSlug(recipeUsername, recipeSlug).orElseThrow(
final RecipeEntity recipe = this.recipeRepository.findByOwnerUsernameAndSlug(recipeUsername, recipeSlug).orElseThrow(
() -> new RecipeException(
RecipeException.Type.INVALID_USERNAME_OR_SLUG,
"No such Recipe for username/slug: " + recipeUsername + "/" + recipeSlug
)
);
final Slice<RecipeComment> commentEntities = this.recipeCommentRepository.findAllByRecipe(recipe, pageable);
final Slice<RecipeCommentEntity> commentEntities = this.recipeCommentRepository.findAllByRecipe(recipe, pageable);
return commentEntities.map(commentEntity -> RecipeCommentView.from(
commentEntity,
false
@ -85,13 +86,13 @@ public class RecipeCommentServiceImpl implements RecipeCommentService {
@Override
public RecipeComment update(long commentId, User viewer, RecipeCommentUpdateSpec spec) throws RecipeException {
final RecipeComment entity = this.loadCommentEntity(commentId, viewer);
final RecipeCommentEntity entity = this.loadCommentEntity(commentId, viewer);
entity.setRawText(spec.getRawText());
return this.recipeCommentRepository.save(entity);
}
@PostAuthorize("@recipeSecurity.isOwner(returnObject.recipe, #modifier)")
private RecipeComment loadForDelete(long commentId, User modifier) throws RecipeException {
private RecipeCommentEntity loadForDelete(long commentId, User modifier) throws RecipeException {
return this.recipeCommentRepository.findById(commentId).orElseThrow(() -> new RecipeException(
RecipeException.Type.INVALID_COMMENT_ID, "No such RecipeComment for id: " + commentId
));
@ -99,7 +100,7 @@ public class RecipeCommentServiceImpl implements RecipeCommentService {
@Override
public void delete(long commentId, User modifier) throws RecipeException {
final RecipeComment entityToDelete = this.loadForDelete(commentId, modifier);
final RecipeCommentEntity entityToDelete = this.loadForDelete(commentId, modifier);
this.recipeCommentRepository.delete(entityToDelete);
}

View File

@ -12,7 +12,7 @@ public class RecipeCommentView {
view.setId(comment.getId());
view.setCreated(comment.getCreated());
view.setModified(comment.getModified());
view.setText(((RecipeComment) comment).getCachedRenderedText());
view.setText(((RecipeCommentEntity) comment).getCachedRenderedText());
if (includeRawText) {
view.setRawText(comment.getRawText());
}

View File

@ -53,7 +53,7 @@ public class RecipeUpdateSpec {
this.cookingTime = recipe.getCookingTime();
this.totalTime = recipe.getTotalTime();
this.rawText = recipe.getRawText();
this.isPublic = recipe.getIsPublic();
this.isPublic = recipe.isPublic();
final @Nullable Image mainImage = recipe.getMainImage();
if (mainImage != null) {
this.mainImage = new MainImageUpdateSpec();

View File

@ -1,22 +1,7 @@
package app.mealsmadeeasy.api.recipe.star;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import lombok.Data;
import java.time.OffsetDateTime;
@Entity(name = "RecipeStar")
@Table(name = "recipe_star")
@Data
public final class RecipeStar {
@EmbeddedId
private RecipeStarId id;
@Column(nullable = false, updatable = false)
private OffsetDateTime timestamp = OffsetDateTime.now();
public interface RecipeStar {
OffsetDateTime getTimestamp();
}

View File

@ -0,0 +1,41 @@
package app.mealsmadeeasy.api.recipe.star;
import jakarta.persistence.Column;
import jakarta.persistence.EmbeddedId;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
import java.time.OffsetDateTime;
@Entity(name = "RecipeStar")
@Table(name = "recipe_star")
public final class RecipeStarEntity implements RecipeStar {
@EmbeddedId
private RecipeStarId id;
@Column(nullable = false, updatable = false)
private OffsetDateTime timestamp = OffsetDateTime.now();
public RecipeStarId getId() {
return this.id;
}
public void setId(RecipeStarId id) {
this.id = id;
}
public OffsetDateTime getTimestamp() {
return this.timestamp;
}
public void setTimestamp(OffsetDateTime date) {
this.timestamp = date;
}
@Override
public String toString() {
return "RecipeStarEntity(" + this.id + ")";
}
}

View File

@ -7,10 +7,10 @@ import org.springframework.data.jpa.repository.Query;
import java.util.Optional;
public interface RecipeStarRepository extends JpaRepository<RecipeStar, Long> {
public interface RecipeStarRepository extends JpaRepository<RecipeStarEntity, Long> {
@Query("SELECT star FROM RecipeStar star WHERE star.id.recipeId = ?1 AND star.id.ownerId = ?2")
Optional<RecipeStar> findByRecipeIdAndOwnerId(Integer recipeId, Integer ownerId);
Optional<RecipeStarEntity> findByRecipeIdAndOwnerId(Integer recipeId, Integer ownerId);
@Query("SELECT count(rs) > 0 FROM RecipeStar rs, Recipe r WHERE r.owner.username = ?1 AND r.slug = ?2 AND r.id = rs.id.recipeId AND rs.id.ownerId = ?3")
boolean isStarer(String ownerUsername, String slug, Integer viewerId);

View File

@ -22,7 +22,7 @@ public class RecipeStarServiceImpl implements RecipeStarService {
@Override
public RecipeStar create(Integer recipeId, Integer ownerId) {
final RecipeStar draft = new RecipeStar();
final RecipeStarEntity draft = new RecipeStarEntity();
final RecipeStarId id = new RecipeStarId();
id.setRecipeId(recipeId);
id.getOwnerId(ownerId);
@ -34,7 +34,7 @@ public class RecipeStarServiceImpl implements RecipeStarService {
@Override
public RecipeStar create(String recipeOwnerUsername, String recipeSlug, User starer) throws RecipeException {
final Recipe recipe = this.recipeService.getByUsernameAndSlug(recipeOwnerUsername, recipeSlug, starer);
final Optional<RecipeStar> existing = this.recipeStarRepository.findByRecipeIdAndOwnerId(
final Optional<RecipeStarEntity> existing = this.recipeStarRepository.findByRecipeIdAndOwnerId(
recipe.getId(),
starer.getId()
);
@ -47,7 +47,8 @@ public class RecipeStarServiceImpl implements RecipeStarService {
@Override
public Optional<RecipeStar> find(String recipeOwnerUsername, String recipeSlug, User starer) throws RecipeException {
final Recipe recipe = this.recipeService.getByUsernameAndSlug(recipeOwnerUsername, recipeSlug, starer);
return this.recipeStarRepository.findByRecipeIdAndOwnerId(recipe.getId(), starer.getId());
return this.recipeStarRepository.findByRecipeIdAndOwnerId(recipe.getId(), starer.getId())
.map(RecipeStar.class::cast);
}
@Override

View File

@ -36,7 +36,7 @@ public class FullRecipeView {
view.setStarCount(starCount);
view.setViewerCount(viewerCount);
view.setMainImage(mainImage);
view.setIsPublic(recipe.getIsPublic());
view.setIsPublic(recipe.isPublic());
return view;
}

View File

@ -3,13 +3,11 @@ package app.mealsmadeeasy.api.recipe.view;
import app.mealsmadeeasy.api.image.view.ImageView;
import app.mealsmadeeasy.api.recipe.Recipe;
import app.mealsmadeeasy.api.user.view.UserInfoView;
import lombok.Data;
import org.jetbrains.annotations.Nullable;
import java.time.OffsetDateTime;
@Data
public class RecipeInfoView {
public final class RecipeInfoView {
public static RecipeInfoView from(Recipe recipe, int starCount, @Nullable ImageView mainImage) {
final RecipeInfoView view = new RecipeInfoView();
@ -22,7 +20,7 @@ public class RecipeInfoView {
view.setCookingTime(recipe.getCookingTime());
view.setTotalTime(recipe.getTotalTime());
view.setOwner(UserInfoView.from(recipe.getOwner()));
view.setPublic(recipe.getIsPublic());
view.setIsPublic(recipe.isPublic());
view.setStarCount(starCount);
view.setMainImage(mainImage);
return view;
@ -41,4 +39,100 @@ public class RecipeInfoView {
private int starCount;
private @Nullable ImageView mainImage;
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public OffsetDateTime getCreated() {
return this.created;
}
public void setCreated(OffsetDateTime created) {
this.created = created;
}
public OffsetDateTime getModified() {
return this.modified;
}
public void setModified(OffsetDateTime modified) {
this.modified = modified;
}
public String getSlug() {
return this.slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public @Nullable Integer getPreparationTime() {
return this.preparationTime;
}
public void setPreparationTime(@Nullable Integer preparationTime) {
this.preparationTime = preparationTime;
}
public @Nullable Integer getCookingTime() {
return this.cookingTime;
}
public void setCookingTime(@Nullable Integer cookingTime) {
this.cookingTime = cookingTime;
}
public @Nullable Integer getTotalTime() {
return this.totalTime;
}
public void setTotalTime(@Nullable Integer totalTime) {
this.totalTime = totalTime;
}
public UserInfoView getOwner() {
return this.owner;
}
public void setOwner(UserInfoView owner) {
this.owner = owner;
}
public boolean getIsPublic() {
return this.isPublic;
}
public void setIsPublic(boolean isPublic) {
this.isPublic = isPublic;
}
public int getStarCount() {
return this.starCount;
}
public void setStarCount(int starCount) {
this.starCount = starCount;
}
public @Nullable ImageView getMainImage() {
return this.mainImage;
}
public void setMainImage(@Nullable ImageView mainImage) {
this.mainImage = mainImage;
}
}

View File

@ -1,92 +1,18 @@
package app.mealsmadeeasy.api.user;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
@Entity(name = "User")
@Table(name = "\"user\"")
@Data
public final class User implements UserDetails {
public interface User extends UserDetails {
public static User getDefaultDraft() {
final var user = new User();
user.setEnabled(true);
user.setExpired(false);
user.setLocked(false);
user.setCredentialsExpired(false);
return user;
}
Integer getId();
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Integer id;
String getEmail();
void setEmail(String email);
@Column(unique = true, nullable = false)
private String username;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "user")
private final Set<UserGrantedAuthority> authorities = new HashSet<>();
@Column(nullable = false)
private Boolean enabled;
@Column(nullable = false)
private Boolean expired;
@Column(nullable = false)
private Boolean locked;
@Column(nullable = false)
private Boolean credentialsExpired;
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
public void addAuthority(UserGrantedAuthority userGrantedAuthority) {
this.authorities.add(userGrantedAuthority);
}
public void addAuthorities(Set<? extends UserGrantedAuthority> userGrantedAuthorities) {
userGrantedAuthorities.forEach(this::addAuthority);
}
public void removeAuthority(UserGrantedAuthority userGrantedAuthority) {
this.authorities.remove(userGrantedAuthority);
}
@Override
public boolean isAccountNonExpired() {
return !this.expired;
}
@Override
public boolean isAccountNonLocked() {
return !this.locked;
}
@Override
public boolean isCredentialsNonExpired() {
return !this.credentialsExpired;
}
@Override
public boolean isEnabled() {
return this.enabled;
}
void addAuthority(UserGrantedAuthority userGrantedAuthority);
void addAuthorities(Set<? extends UserGrantedAuthority> userGrantedAuthorities);
void removeAuthority(UserGrantedAuthority userGrantedAuthority);
}

View File

@ -0,0 +1,183 @@
package app.mealsmadeeasy.api.user;
import jakarta.persistence.*;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
@Entity(name = "User")
@Table(name = "\"user\"")
public final class UserEntity implements User {
public static UserEntity getDefaultDraft() {
final var user = new UserEntity();
user.setEnabled(true);
user.setExpired(false);
user.setLocked(false);
user.setCredentialsExpired(false);
return user;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Integer id;
@Column(unique = true, nullable = false)
private String username;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String password;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "userEntity")
private final Set<UserGrantedAuthorityEntity> authorities = new HashSet<>();
@Column(nullable = false)
private Boolean enabled;
@Column(nullable = false)
private Boolean expired;
@Column(nullable = false)
private Boolean locked;
@Column(nullable = false)
private Boolean credentialsExpired;
@Override
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String getEmail() {
return this.email;
}
@Override
public void setEmail(String email) {
this.email = email;
}
@Override
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public void addAuthority(UserGrantedAuthority userGrantedAuthority) {
this.authorities.add((UserGrantedAuthorityEntity) userGrantedAuthority);
}
@Override
public void addAuthorities(Set<? extends UserGrantedAuthority> userGrantedAuthorities) {
userGrantedAuthorities.forEach(this::addAuthority);
}
@Override
public void removeAuthority(UserGrantedAuthority userGrantedAuthority) {
this.authorities.remove((UserGrantedAuthorityEntity) userGrantedAuthority);
}
@Override
public boolean isAccountNonExpired() {
return !this.expired;
}
public void setExpired(Boolean expired) {
this.expired = expired;
}
@Override
public boolean isAccountNonLocked() {
return !this.locked;
}
public void setLocked(Boolean locked) {
this.locked = locked;
}
@Override
public boolean isCredentialsNonExpired() {
return !this.credentialsExpired;
}
public void setCredentialsExpired(Boolean credentialsExpired) {
this.credentialsExpired = credentialsExpired;
}
@Override
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
@Override
public int hashCode() {
return Objects.hash(
this.id,
this.username,
this.email,
this.password,
this.authorities,
this.enabled,
this.expired,
this.locked,
this.credentialsExpired
);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj instanceof User o) {
return Objects.equals(this.id, o.getId())
&& Objects.equals(this.username, o.getUsername())
&& Objects.equals(this.password, o.getPassword())
&& Objects.equals(this.authorities, o.getAuthorities())
&& Objects.equals(this.enabled, o.isEnabled())
&& Objects.equals(this.expired, !o.isAccountNonExpired())
&& Objects.equals(this.locked, !o.isAccountNonLocked())
&& Objects.equals(this.credentialsExpired, !o.isCredentialsNonExpired());
} else {
return false;
}
}
@Override
public String toString() {
return "UserEntity(" + this.id + ", " + this.username + ", " + this.email + ")";
}
}

View File

@ -1,23 +1,5 @@
package app.mealsmadeeasy.api.user;
import jakarta.persistence.*;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
@Entity(name = "UserGrantedAuthority")
@Table(name = "user_granted_authority")
@Data
public final class UserGrantedAuthority implements GrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Integer id;
private String authority;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
}
public interface UserGrantedAuthority extends GrantedAuthority {}

View File

@ -0,0 +1,25 @@
package app.mealsmadeeasy.api.user;
import jakarta.persistence.*;
@Entity(name = "UserGrantedAuthority")
@Table(name = "user_granted_authority")
public final class UserGrantedAuthorityEntity implements UserGrantedAuthority {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false)
private Integer id;
private String authority;
@ManyToOne
@JoinColumn(name = "user_id")
private UserEntity userEntity;
@Override
public String getAuthority() {
return this.authority;
}
}

View File

@ -2,4 +2,4 @@ package app.mealsmadeeasy.api.user;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserGrantedAuthorityRepository extends JpaRepository<UserGrantedAuthority, Long> {}
public interface UserGrantedAuthorityRepository extends JpaRepository<UserGrantedAuthorityEntity, Long> {}

View File

@ -4,9 +4,9 @@ import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
User getByUsername(String username);
public interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByUsername(String username);
UserEntity getByUsername(String username);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
void deleteByUsername(String username);

View File

@ -32,7 +32,7 @@ public final class UserServiceImpl implements UserService {
if (this.userRepository.existsByEmail(email)) {
throw new UserCreateException(UserCreateException.Type.EMAIL_TAKEN, "Email " + email + " is taken.");
}
final User draft = User.getDefaultDraft();
final UserEntity draft = UserEntity.getDefaultDraft();
draft.setUsername(username);
draft.setEmail(email);
draft.setPassword(this.passwordEncoder.encode(rawPassword));
@ -47,12 +47,12 @@ public final class UserServiceImpl implements UserService {
@Override
public User updateUser(User user) {
return this.userRepository.save((User) user);
return this.userRepository.save((UserEntity) user);
}
@Override
public void deleteUser(User user) {
this.userRepository.delete((User) user);
this.userRepository.delete((UserEntity) user);
}
@Override

View File

@ -2,6 +2,7 @@ package app.mealsmadeeasy.api.recipe;
import app.mealsmadeeasy.api.matchers.ContainsItemsMatcher;
import app.mealsmadeeasy.api.recipe.star.RecipeStar;
import app.mealsmadeeasy.api.recipe.star.RecipeStarEntity;
import app.mealsmadeeasy.api.recipe.star.RecipeStarId;
import java.util.List;
@ -17,8 +18,8 @@ public class ContainsRecipeStarsMatcher extends ContainsItemsMatcher<RecipeStar,
super(
List.of(allExpected),
o -> o instanceof RecipeStar,
RecipeStar::getId,
RecipeStar::getId,
recipeStar -> ((RecipeStarEntity) recipeStar).getId(),
recipeStar -> ((RecipeStarEntity) recipeStar).getId(),
(id0, id1) -> Objects.equals(id0.getRecipeId(), id1.getRecipeId())
&& Objects.equals(id0.getOwnerId(), id1.getOwnerId())
);