From 9c8def3341c51713e6a62ac275a9bfa386151c00 Mon Sep 17 00:00:00 2001 From: Edouard DUPIN Date: Sun, 15 Oct 2023 23:37:58 +0200 Subject: [PATCH] [DEV] update new JPA --- back/pom.xml | 2 +- back/src/org/kar/karideo/WebLauncher.java | 130 +++--- .../org/kar/karideo/api/SeasonResource.java | 184 ++++---- .../org/kar/karideo/api/SeriesResource.java | 186 ++++---- .../src/org/kar/karideo/api/TypeResource.java | 193 +++++---- .../api/UserMediaAdvancementResource.java | 185 ++++---- .../src/org/kar/karideo/api/UserResource.java | 133 +++--- .../org/kar/karideo/api/VideoResource.java | 405 +++++++++--------- .../karideo/migration/Migration20231015.java | 27 ++ back/src/org/kar/karideo/model/Media.java | 77 ++-- back/src/org/kar/karideo/model/Season.java | 36 +- back/src/org/kar/karideo/model/Series.java | 36 +- back/src/org/kar/karideo/model/Type.java | 26 +- .../org/kar/karideo/model/UserKarideo.java | 5 +- .../karideo/model/UserMediaAdvancement.java | 43 +- front/package.json | 4 +- 16 files changed, 855 insertions(+), 817 deletions(-) create mode 100644 back/src/org/kar/karideo/migration/Migration20231015.java diff --git a/back/pom.xml b/back/pom.xml index 301222c..c172ba3 100644 --- a/back/pom.xml +++ b/back/pom.xml @@ -20,7 +20,7 @@ kangaroo-and-rabbit archidata - 0.3.8 + 0.4.0 org.slf4j diff --git a/back/src/org/kar/karideo/WebLauncher.java b/back/src/org/kar/karideo/WebLauncher.java index 733f60c..f83fecc 100755 --- a/back/src/org/kar/karideo/WebLauncher.java +++ b/back/src/org/kar/karideo/WebLauncher.java @@ -1,16 +1,12 @@ package org.kar.karideo; -import org.glassfish.grizzly.http.server.HttpServer; +import java.net.URI; +import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; +import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; -import org.kar.karideo.api.*; -import org.kar.karideo.filter.KarideoAuthenticationFilter; -import org.kar.karideo.migration.Initialization; -import org.kar.karideo.migration.Migration20230810; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.kar.archidata.GlobalConfiguration; import org.kar.archidata.UpdateJwtPublicKey; import org.kar.archidata.api.DataResource; @@ -23,23 +19,36 @@ import org.kar.archidata.filter.CORSFilter; import org.kar.archidata.filter.OptionFilter; import org.kar.archidata.migration.MigrationEngine; import org.kar.archidata.util.ConfigBaseVariable; -import org.glassfish.jersey.jackson.JacksonFeature; +import org.kar.karideo.api.Front; +import org.kar.karideo.api.HealthCheck; +import org.kar.karideo.api.SeasonResource; +import org.kar.karideo.api.SeriesResource; +import org.kar.karideo.api.TypeResource; +import org.kar.karideo.api.UserMediaAdvancementResource; +import org.kar.karideo.api.UserResource; +import org.kar.karideo.api.VideoResource; +import org.kar.karideo.filter.KarideoAuthenticationFilter; +import org.kar.karideo.migration.Initialization; +import org.kar.karideo.migration.Migration20230810; +import org.kar.karideo.migration.Migration20231015; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import jakarta.ws.rs.core.UriBuilder; -import java.net.URI; public class WebLauncher { final static Logger LOGGER = LoggerFactory.getLogger(WebLauncher.class); - public static DBConfig dbConfig; - protected UpdateJwtPublicKey keyUpdater = null; + public static DBConfig dbConfig; + protected UpdateJwtPublicKey keyUpdater = null; + public WebLauncher() { ConfigBaseVariable.bdDatabase = "karideo"; } - - private static URI getBaseURI() { - return UriBuilder.fromUri(ConfigBaseVariable.getlocalAddress()).build(); - } - + + private static URI getBaseURI() { + return UriBuilder.fromUri(ConfigBaseVariable.getlocalAddress()).build(); + } + public void migrateDB() throws Exception { WebLauncher.LOGGER.info("Create migration engine"); MigrationEngine migrationEngine = new MigrationEngine(); @@ -47,15 +56,16 @@ public class WebLauncher { migrationEngine.setInit(new Initialization()); WebLauncher.LOGGER.info("Add migration since last version"); migrationEngine.add(new Migration20230810()); + migrationEngine.add(new Migration20231015()); WebLauncher.LOGGER.info("Migrate the DB [START]"); migrationEngine.migrate(GlobalConfiguration.dbConfig); WebLauncher.LOGGER.info("Migrate the DB [STOP]"); } - + public static void main(String[] args) throws Exception { WebLauncher.LOGGER.info("[START] application wake UP"); WebLauncher launcher = new WebLauncher(); - launcher.migrateDB(); + launcher.migrateDB(); launcher.process(); WebLauncher.LOGGER.info("end-configure the server & wait finish process:"); Thread.currentThread().join(); @@ -63,45 +73,44 @@ public class WebLauncher { launcher.stopOther(); WebLauncher.LOGGER.info("STOP the REST server"); } - - - public void process() throws InterruptedException { + + public void process() throws InterruptedException { // =================================================================== // Configure resources // =================================================================== - ResourceConfig rc = new ResourceConfig(); + ResourceConfig rc = new ResourceConfig(); + + // add multi-part models .. + rc.register(MultiPartFeature.class); + // global authentication system + rc.register(OptionFilter.class); + // remove cors ==> all time called by an other system... + rc.register(CORSFilter.class); + // global authentication system + rc.register(KarideoAuthenticationFilter.class); + // register exception catcher + rc.register(InputExceptionCatcher.class); + rc.register(SystemExceptionCatcher.class); + rc.register(FailExceptionCatcher.class); + rc.register(ExceptionCatcher.class); + // add default resource: + rc.register(UserResource.class); + rc.register(SeriesResource.class); + rc.register(DataResource.class); + rc.register(SeasonResource.class); + rc.register(TypeResource.class); + rc.register(VideoResource.class); + rc.register(UserMediaAdvancementResource.class); + + rc.register(HealthCheck.class); + rc.register(Front.class); + + // add jackson to be discover when we are ins stand-alone server + rc.register(JacksonFeature.class); + // enable this to show low level request + //rc.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, Level.WARNING.getName()); - // add multi-part models .. - rc.register(MultiPartFeature.class); - // global authentication system - rc.register(OptionFilter.class); - // remove cors ==> all time called by an other system... - rc.register(CORSFilter.class); - // global authentication system - rc.register(KarideoAuthenticationFilter.class); - // register exception catcher - rc.register(InputExceptionCatcher.class); - rc.register(SystemExceptionCatcher.class); - rc.register(FailExceptionCatcher.class); - rc.register(ExceptionCatcher.class); - // add default resource: - rc.register(UserResource.class); - rc.register(SeriesResource.class); - rc.register(DataResource.class); - rc.register(SeasonResource.class); - rc.register(TypeResource.class); - rc.register(VideoResource.class); - rc.register(UserMediaAdvancementResource.class); - - rc.register(HealthCheck.class); - rc.register(Front.class); - - // add jackson to be discover when we are ins stand-alone server - rc.register(JacksonFeature.class); - // enable this to show low level request - //rc.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, Level.WARNING.getName()); - HttpServer server = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override @@ -110,17 +119,16 @@ public class WebLauncher { server.shutdownNow(); } }, "shutdownHook")); - - + // =================================================================== // start periodic update of the token ... // =================================================================== this.keyUpdater = new UpdateJwtPublicKey(); keyUpdater.start(); - - // =================================================================== + + // =================================================================== // run JERSEY - // =================================================================== + // =================================================================== try { server.start(); LOGGER.info("Jersey app started at {}", getBaseURI()); @@ -128,9 +136,9 @@ public class WebLauncher { LOGGER.error("There was an error while starting Grizzly HTTP server."); e.printStackTrace(); } - } - - public void stopOther() { + } + + public void stopOther() { keyUpdater.kill(); try { keyUpdater.join(4000, 0); @@ -138,5 +146,5 @@ public class WebLauncher { // TODO Auto-generated catch block e.printStackTrace(); } - } + } } diff --git a/back/src/org/kar/karideo/api/SeasonResource.java b/back/src/org/kar/karideo/api/SeasonResource.java index 86a0980..b4f102d 100644 --- a/back/src/org/kar/karideo/api/SeasonResource.java +++ b/back/src/org/kar/karideo/api/SeasonResource.java @@ -1,97 +1,105 @@ package org.kar.karideo.api; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; -import org.kar.karideo.model.Season; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.kar.archidata.SqlWrapper; -import org.kar.archidata.annotation.security.RolesAllowed; -import org.kar.archidata.util.DataTools; - -import jakarta.ws.rs.*; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; import java.io.InputStream; import java.util.List; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; +import org.kar.archidata.annotation.security.RolesAllowed; +import org.kar.archidata.sqlWrapper.QuerryAnd; +import org.kar.archidata.sqlWrapper.QuerryCondition; +import org.kar.archidata.sqlWrapper.SqlWrapper; +import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany; +import org.kar.archidata.util.DataTools; +import org.kar.karideo.model.Season; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + @Path("/season") -@Produces({MediaType.APPLICATION_JSON}) +@Produces({ MediaType.APPLICATION_JSON }) public class SeasonResource { static final Logger LOGGER = LoggerFactory.getLogger(SeasonResource.class); - - @GET - @Path("{id}") - @RolesAllowed("USER") - public static Season getWithId(@PathParam("id") Long id) throws Exception { - return SqlWrapper.get(Season.class, id); - } - - @GET - @RolesAllowed("USER") - public List get() throws Exception { - return SqlWrapper.gets(Season.class, false); - } - - @GET - @Path("{id}") - @RolesAllowed("USER") - @Consumes(MediaType.APPLICATION_JSON) - public Season get(@PathParam("id") Long id) throws Exception { - return SqlWrapper.get(Season.class, id); - } - - /* ============================================================================= - * ADMIN SECTION: - * ============================================================================= */ - - @POST - @RolesAllowed("ADMIN") - @Consumes(MediaType.APPLICATION_JSON) - public Season put(String jsonRequest) throws Exception { - return SqlWrapper.insertWithJson(Season.class, jsonRequest); - } - - @PUT - @Path("{id}") - @RolesAllowed("ADMIN") - @Consumes(MediaType.APPLICATION_JSON) - public Season put(@PathParam("id") Long id, String jsonRequest) throws Exception { - SqlWrapper.update(Season.class, id, jsonRequest); - return SqlWrapper.get(Season.class, id); - } - - @DELETE - @Path("{id}") - @RolesAllowed("ADMIN") - public Response delete(@PathParam("id") Long id) throws Exception { - SqlWrapper.setDelete(Season.class, id); + + @GET + @Path("{id}") + @RolesAllowed("USER") + public static Season getWithId(@PathParam("id") Long id) throws Exception { + return SqlWrapper.get(Season.class, id); + } + + @GET + @RolesAllowed("USER") + public List get() throws Exception { + return SqlWrapper.gets(Season.class); + } + + @GET + @Path("{id}") + @RolesAllowed("USER") + @Consumes(MediaType.APPLICATION_JSON) + public Season get(@PathParam("id") Long id) throws Exception { + return SqlWrapper.get(Season.class, id); + } + + /* ============================================================================= + * ADMIN SECTION: + * ============================================================================= */ + + @POST + @RolesAllowed("ADMIN") + @Consumes(MediaType.APPLICATION_JSON) + public Season put(String jsonRequest) throws Exception { + return SqlWrapper.insertWithJson(Season.class, jsonRequest); + } + + @PUT + @Path("{id}") + @RolesAllowed("ADMIN") + @Consumes(MediaType.APPLICATION_JSON) + public Season put(@PathParam("id") Long id, String jsonRequest) throws Exception { + SqlWrapper.update(Season.class, id, jsonRequest); + return SqlWrapper.get(Season.class, id); + } + + @DELETE + @Path("{id}") + @RolesAllowed("ADMIN") + public Response delete(@PathParam("id") Long id) throws Exception { + SqlWrapper.delete(Season.class, id); return Response.ok().build(); - } - - @POST - @Path("{id}/add_cover") - @RolesAllowed("ADMIN") - @Consumes({MediaType.MULTIPART_FORM_DATA}) - public Response uploadCover(@PathParam("id") Long id, - @FormDataParam("fileName") String fileName, - @FormDataParam("file") InputStream fileInputStream, - @FormDataParam("file") FormDataContentDisposition fileMetaData - ) { - return DataTools.uploadCover(Season.class, id, fileName, fileInputStream, fileMetaData); - } - - @GET - @Path("{id}/rm_cover/{coverId}") - @RolesAllowed("ADMIN") - public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception { - SqlWrapper.removeLink(Season.class, id, "cover", coverId); - return Response.ok(SqlWrapper.get(Season.class, id)).build(); - } - - public static Season getOrCreate(String name, Long seriesId) { - try { - Season out = SqlWrapper.getWhere(Season.class, "name", "=", name, "parentId", "=", seriesId); + } + + @POST + @Path("{id}/add_cover") + @RolesAllowed("ADMIN") + @Consumes({ MediaType.MULTIPART_FORM_DATA }) + public Response uploadCover(@PathParam("id") Long id, @FormDataParam("fileName") String fileName, @FormDataParam("file") InputStream fileInputStream, + @FormDataParam("file") FormDataContentDisposition fileMetaData) { + return DataTools.uploadCover(Season.class, id, fileName, fileInputStream, fileMetaData); + } + + @GET + @Path("{id}/rm_cover/{coverId}") + @RolesAllowed("ADMIN") + public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception { + AddOnManyToMany.removeLink(Season.class, id, "cover", coverId); + return Response.ok(SqlWrapper.get(Season.class, id)).build(); + } + + public static Season getOrCreate(String name, Long seriesId) { + try { + Season out = SqlWrapper.getWhere(Season.class, new QuerryAnd(new QuerryCondition("name", "=", name), new QuerryCondition("parentId", "=", seriesId))); if (out == null) { out = new Season(); out.name = name; @@ -103,7 +111,7 @@ public class SeasonResource { // TODO Auto-generated catch block e.printStackTrace(); } - return null; - } - + return null; + } + } diff --git a/back/src/org/kar/karideo/api/SeriesResource.java b/back/src/org/kar/karideo/api/SeriesResource.java index 7b61446..6cd4ab0 100644 --- a/back/src/org/kar/karideo/api/SeriesResource.java +++ b/back/src/org/kar/karideo/api/SeriesResource.java @@ -1,98 +1,105 @@ package org.kar.karideo.api; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; -import org.kar.karideo.model.Season; -import org.kar.karideo.model.Series; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.kar.archidata.SqlWrapper; -import org.kar.archidata.annotation.security.RolesAllowed; -import org.kar.archidata.util.DataTools; - -import jakarta.ws.rs.*; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; import java.io.InputStream; import java.util.List; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; +import org.kar.archidata.annotation.security.RolesAllowed; +import org.kar.archidata.sqlWrapper.QuerryAnd; +import org.kar.archidata.sqlWrapper.QuerryCondition; +import org.kar.archidata.sqlWrapper.SqlWrapper; +import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany; +import org.kar.archidata.util.DataTools; +import org.kar.karideo.model.Series; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + @Path("/series") -@Produces({MediaType.APPLICATION_JSON}) +@Produces({ MediaType.APPLICATION_JSON }) public class SeriesResource { static final Logger LOGGER = LoggerFactory.getLogger(SeriesResource.class); - - @GET - @Path("{id}") - @RolesAllowed("USER") - public static Series getWithId(@PathParam("id") Long id) throws Exception { - return SqlWrapper.get(Series.class, id); - } - - @GET - @RolesAllowed("USER") - public List get() throws Exception { - return SqlWrapper.gets(Series.class, false); - } - - @GET - @Path("{id}") - @RolesAllowed("USER") - @Consumes(MediaType.APPLICATION_JSON) - public Series get(@PathParam("id") Long id) throws Exception { - return SqlWrapper.get(Series.class, id); - } - - /* ============================================================================= - * ADMIN SECTION: - * ============================================================================= */ - - @POST - @RolesAllowed("ADMIN") - @Consumes(MediaType.APPLICATION_JSON) - public Series put(String jsonRequest) throws Exception { - return SqlWrapper.insertWithJson(Series.class, jsonRequest); - } - - @PUT - @Path("{id}") - @RolesAllowed("ADMIN") - @Consumes(MediaType.APPLICATION_JSON) - public Series put(@PathParam("id") Long id, String jsonRequest) throws Exception { - SqlWrapper.update(Series.class, id, jsonRequest); - return SqlWrapper.get(Series.class, id); - } - - @DELETE - @Path("{id}") - @RolesAllowed("ADMIN") - public Response delete(@PathParam("id") Long id) throws Exception { - SqlWrapper.setDelete(Series.class, id); + + @GET + @Path("{id}") + @RolesAllowed("USER") + public static Series getWithId(@PathParam("id") Long id) throws Exception { + return SqlWrapper.get(Series.class, id); + } + + @GET + @RolesAllowed("USER") + public List get() throws Exception { + return SqlWrapper.gets(Series.class); + } + + @GET + @Path("{id}") + @RolesAllowed("USER") + @Consumes(MediaType.APPLICATION_JSON) + public Series get(@PathParam("id") Long id) throws Exception { + return SqlWrapper.get(Series.class, id); + } + + /* ============================================================================= + * ADMIN SECTION: + * ============================================================================= */ + + @POST + @RolesAllowed("ADMIN") + @Consumes(MediaType.APPLICATION_JSON) + public Series put(String jsonRequest) throws Exception { + return SqlWrapper.insertWithJson(Series.class, jsonRequest); + } + + @PUT + @Path("{id}") + @RolesAllowed("ADMIN") + @Consumes(MediaType.APPLICATION_JSON) + public Series put(@PathParam("id") Long id, String jsonRequest) throws Exception { + SqlWrapper.update(Series.class, id, jsonRequest); + return SqlWrapper.get(Series.class, id); + } + + @DELETE + @Path("{id}") + @RolesAllowed("ADMIN") + public Response delete(@PathParam("id") Long id) throws Exception { + SqlWrapper.delete(Series.class, id); return Response.ok().build(); - } - - @POST - @Path("{id}/add_cover") - @RolesAllowed("ADMIN") - @Consumes({MediaType.MULTIPART_FORM_DATA}) - public Response uploadCover(@PathParam("id") Long id, - @FormDataParam("fileName") String fileName, - @FormDataParam("file") InputStream fileInputStream, - @FormDataParam("file") FormDataContentDisposition fileMetaData - ) { - return DataTools.uploadCover(Series.class, id, fileName, fileInputStream, fileMetaData); - } - - @GET - @Path("{id}/rm_cover/{coverId}") - @RolesAllowed("ADMIN") - public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception { - SqlWrapper.removeLink(Series.class, id, "cover", coverId); - return Response.ok(SqlWrapper.get(Series.class, id)).build(); - } - - public static Series getOrCreate(String name, Long typeId) { - try { - Series out = SqlWrapper.getWhere(Series.class, "name", "=", name, "parentId", "=", typeId); + } + + @POST + @Path("{id}/add_cover") + @RolesAllowed("ADMIN") + @Consumes({ MediaType.MULTIPART_FORM_DATA }) + public Response uploadCover(@PathParam("id") Long id, @FormDataParam("fileName") String fileName, @FormDataParam("file") InputStream fileInputStream, + @FormDataParam("file") FormDataContentDisposition fileMetaData) { + return DataTools.uploadCover(Series.class, id, fileName, fileInputStream, fileMetaData); + } + + @GET + @Path("{id}/rm_cover/{coverId}") + @RolesAllowed("ADMIN") + public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception { + AddOnManyToMany.removeLink(Series.class, id, "cover", coverId); + return Response.ok(SqlWrapper.get(Series.class, id)).build(); + } + + public static Series getOrCreate(String name, Long typeId) { + try { + Series out = SqlWrapper.getWhere(Series.class, new QuerryAnd(new QuerryCondition("name", "=", name), new QuerryCondition("parentId", "=", typeId))); if (out == null) { out = new Series(); out.name = name; @@ -104,8 +111,7 @@ public class SeriesResource { // TODO Auto-generated catch block e.printStackTrace(); } - return null; - } - + return null; + } + } - diff --git a/back/src/org/kar/karideo/api/TypeResource.java b/back/src/org/kar/karideo/api/TypeResource.java index 6a17a77..acb30a4 100644 --- a/back/src/org/kar/karideo/api/TypeResource.java +++ b/back/src/org/kar/karideo/api/TypeResource.java @@ -1,102 +1,108 @@ package org.kar.karideo.api; -import org.glassfish.jersey.media.multipart.FormDataContentDisposition; -import org.glassfish.jersey.media.multipart.FormDataParam; -import org.kar.karideo.model.Type; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.kar.archidata.SqlWrapper; -import org.kar.archidata.annotation.security.RolesAllowed; -import org.kar.archidata.util.DataTools; - -import jakarta.ws.rs.*; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.Response; import java.io.InputStream; import java.util.List; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.FormDataParam; +import org.kar.archidata.annotation.security.RolesAllowed; +import org.kar.archidata.sqlWrapper.QuerryCondition; +import org.kar.archidata.sqlWrapper.SqlWrapper; +import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany; +import org.kar.archidata.util.DataTools; +import org.kar.karideo.model.Type; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.Response; + @Path("/type") -@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) +@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public class TypeResource { static final Logger LOGGER = LoggerFactory.getLogger(TypeResource.class); - - - @GET - @Path("{id}") - @RolesAllowed("USER") - public static Type getWithId(@PathParam("id") Long id) throws Exception { - return SqlWrapper.get(Type.class, id); - } - - @GET - @RolesAllowed("USER") - public List get() throws Exception { - return SqlWrapper.gets(Type.class, false); - } - - @GET - @Path("{id}") - @RolesAllowed("USER") - @Consumes(MediaType.APPLICATION_JSON) - public Type get(@PathParam("id") Long id) throws Exception { - return SqlWrapper.get(Type.class, id); - } - - public static Type getId(Long id) throws Exception { - return SqlWrapper.get(Type.class, id); - } - - /* ============================================================================= - * ADMIN SECTION: - * ============================================================================= */ - - @POST - @RolesAllowed("ADMIN") - @Consumes(MediaType.APPLICATION_JSON) - public Type put(String jsonRequest) throws Exception { - return SqlWrapper.insertWithJson(Type.class, jsonRequest); - } - - @PUT - @Path("{id}") - @RolesAllowed("ADMIN") - @Consumes(MediaType.APPLICATION_JSON) - public Type put(@PathParam("id") Long id, String jsonRequest) throws Exception { - SqlWrapper.update(Type.class, id, jsonRequest); - return SqlWrapper.get(Type.class, id); - } - - @DELETE - @Path("{id}") - @RolesAllowed("ADMIN") - public Response delete(@PathParam("id") Long id) throws Exception { - SqlWrapper.setDelete(Type.class, id); + + @GET + @Path("{id}") + @RolesAllowed("USER") + public static Type getWithId(@PathParam("id") Long id) throws Exception { + return SqlWrapper.get(Type.class, id); + } + + @GET + @RolesAllowed("USER") + public List get() throws Exception { + return SqlWrapper.gets(Type.class); + } + + @GET + @Path("{id}") + @RolesAllowed("USER") + @Consumes(MediaType.APPLICATION_JSON) + public Type get(@PathParam("id") Long id) throws Exception { + return SqlWrapper.get(Type.class, id); + } + + public static Type getId(Long id) throws Exception { + return SqlWrapper.get(Type.class, id); + } + + /* ============================================================================= + * ADMIN SECTION: + * ============================================================================= */ + + @POST + @RolesAllowed("ADMIN") + @Consumes(MediaType.APPLICATION_JSON) + public Type put(String jsonRequest) throws Exception { + return SqlWrapper.insertWithJson(Type.class, jsonRequest); + } + + @PUT + @Path("{id}") + @RolesAllowed("ADMIN") + @Consumes(MediaType.APPLICATION_JSON) + public Type put(@PathParam("id") Long id, String jsonRequest) throws Exception { + SqlWrapper.update(Type.class, id, jsonRequest); + return SqlWrapper.get(Type.class, id); + } + + @DELETE + @Path("{id}") + @RolesAllowed("ADMIN") + public Response delete(@PathParam("id") Long id) throws Exception { + SqlWrapper.delete(Type.class, id); return Response.ok().build(); - } - - @POST - @Path("{id}/add_cover") - @RolesAllowed("ADMIN") - @Consumes({MediaType.MULTIPART_FORM_DATA}) - public Response uploadCover(@PathParam("id") Long id, - @FormDataParam("fileName") String fileName, - @FormDataParam("file") InputStream fileInputStream, - @FormDataParam("file") FormDataContentDisposition fileMetaData - ) { - return DataTools.uploadCover(Type.class, id, fileName, fileInputStream, fileMetaData); - } - - @GET - @Path("{id}/rm_cover/{coverId}") - @RolesAllowed("ADMIN") - public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception { - SqlWrapper.removeLink(Type.class, id, "cover", coverId); - return Response.ok(SqlWrapper.get(Type.class, id)).build(); - } - - public static Type getOrCreate(String name) { - try { - Type out = SqlWrapper.getWhere(Type.class, "name", "=", name); + } + + @POST + @Path("{id}/add_cover") + @RolesAllowed("ADMIN") + @Consumes({ MediaType.MULTIPART_FORM_DATA }) + public Response uploadCover(@PathParam("id") Long id, @FormDataParam("fileName") String fileName, @FormDataParam("file") InputStream fileInputStream, + @FormDataParam("file") FormDataContentDisposition fileMetaData) { + return DataTools.uploadCover(Type.class, id, fileName, fileInputStream, fileMetaData); + } + + @GET + @Path("{id}/rm_cover/{coverId}") + @RolesAllowed("ADMIN") + public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception { + AddOnManyToMany.removeLink(Type.class, id, "cover", coverId); + return Response.ok(SqlWrapper.get(Type.class, id)).build(); + } + + public static Type getOrCreate(String name) { + try { + Type out = SqlWrapper.getWhere(Type.class, new QuerryCondition("name", "=", name)); if (out == null) { out = new Type(); out.name = name; @@ -107,8 +113,7 @@ public class TypeResource { // TODO Auto-generated catch block e.printStackTrace(); } - return null; - } - - + return null; + } + } diff --git a/back/src/org/kar/karideo/api/UserMediaAdvancementResource.java b/back/src/org/kar/karideo/api/UserMediaAdvancementResource.java index a7a20a3..246514a 100644 --- a/back/src/org/kar/karideo/api/UserMediaAdvancementResource.java +++ b/back/src/org/kar/karideo/api/UserMediaAdvancementResource.java @@ -1,107 +1,110 @@ package org.kar.karideo.api; +import java.util.List; + +import org.kar.archidata.annotation.security.RolesAllowed; +import org.kar.archidata.filter.GenericContext; +import org.kar.archidata.sqlWrapper.QuerryAnd; +import org.kar.archidata.sqlWrapper.QuerryCondition; +import org.kar.archidata.sqlWrapper.SqlWrapper; import org.kar.karideo.model.UserMediaAdvancement; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.kar.archidata.SqlWrapper; -import org.kar.archidata.WhereCondition; -import org.kar.archidata.annotation.security.RolesAllowed; -import org.kar.archidata.filter.GenericContext; -import jakarta.ws.rs.*; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; -import java.util.List; - @Path("/advancement") -@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) +@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public class UserMediaAdvancementResource { static final Logger LOGGER = LoggerFactory.getLogger(UserMediaAdvancementResource.class); - - - @GET - @Path("{id}") - @RolesAllowed("USER") - public UserMediaAdvancement getWithId(@Context SecurityContext sc, @PathParam("id") Long id) throws Exception { - GenericContext gc = (GenericContext) sc.getUserPrincipal(); - return SqlWrapper.getWhere(UserMediaAdvancement.class, - List.of( - new WhereCondition("mediaId", "=", id), - new WhereCondition("userId", "=", gc.userByToken.id), - new WhereCondition("deleted", "=", 0) - ), false); - } - - @GET - @RolesAllowed("USER") - public List gets(@Context SecurityContext sc ) throws Exception { - GenericContext gc = (GenericContext) sc.getUserPrincipal(); - return SqlWrapper.getsWhere(UserMediaAdvancement.class, - List.of( - new WhereCondition("userId", "=", gc.userByToken.id), - new WhereCondition("deleted", "=", 0) - ), false); - } - - - /* ============================================================================= - * Modification SECTION: - * ============================================================================= */ - - public record MediaInformations(int time, float percent, int count) {}; - - //@POST - //@Path("{id}") - //@RolesAllowed("USER") - //@Consumes(MediaType.APPLICATION_JSON) - public UserMediaAdvancement post(@Context SecurityContext sc, @PathParam("id") Long id, MediaInformations data) throws Exception { - GenericContext gc = (GenericContext) sc.getUserPrincipal(); - UserMediaAdvancement elem = new UserMediaAdvancement(); - elem.userId = gc.userByToken.id; - elem.mediaId = id; - elem.time = data.time; - elem.percent = data.percent; - elem.count = data.count; - return SqlWrapper.insert(elem); - } - public record MediaInformationsDelta(int time, float percent, boolean addCount) {}; - - @PUT - @Path("{id}") - @RolesAllowed("USER") - @Consumes(MediaType.APPLICATION_JSON) - public UserMediaAdvancement put(@Context SecurityContext sc, @PathParam("id") Long id, MediaInformationsDelta data) throws Exception { - UserMediaAdvancement elem = this.getWithId(sc, id); - if (elem == null) { - // insert element - if (data.addCount) { - return this.post(sc, id, new MediaInformations(data.time(), data.percent(), 1)); - } else { - return this.post(sc, id, new MediaInformations(data.time(), data.percent(), 0)); - } - } - elem.time = data.time; - elem.percent = data.percent; - if (data.addCount) { - elem.count++; - } - LOGGER.info("{},{},{}", elem.time, elem.percent, elem.count); - int nbAfected = SqlWrapper.update(elem, elem.id, List.of("time", "percent","count")); - // TODO: manage the fact that no element has been updated ... - UserMediaAdvancement ret = SqlWrapper.get(UserMediaAdvancement.class, elem.id); - return ret; - } - @DELETE - @Path("{id}") - @RolesAllowed("USER") - public Response delete(@Context SecurityContext sc, @PathParam("id") Long id) throws Exception { - UserMediaAdvancement elem = this.getWithId(sc, id); - SqlWrapper.setDelete(UserMediaAdvancement.class, elem.id); + + @GET + @Path("{id}") + @RolesAllowed("USER") + public UserMediaAdvancement getWithId(@Context SecurityContext sc, @PathParam("id") Long id) throws Exception { + GenericContext gc = (GenericContext) sc.getUserPrincipal(); + return SqlWrapper.getWhere(UserMediaAdvancement.class, new QuerryAnd(new QuerryCondition("mediaId", "=", id), new QuerryCondition("userId", "=", gc.userByToken.id))); + } + + @GET + @RolesAllowed("USER") + public List gets(@Context SecurityContext sc) throws Exception { + GenericContext gc = (GenericContext) sc.getUserPrincipal(); + return SqlWrapper.getsWhere(UserMediaAdvancement.class, new QuerryCondition("userId", "=", gc.userByToken.id)); + } + + /* ============================================================================= + * Modification SECTION: + * ============================================================================= */ + + public record MediaInformations( + int time, + float percent, + int count) {}; + + //@POST + //@Path("{id}") + //@RolesAllowed("USER") + //@Consumes(MediaType.APPLICATION_JSON) + public UserMediaAdvancement post(@Context SecurityContext sc, @PathParam("id") Long id, MediaInformations data) throws Exception { + GenericContext gc = (GenericContext) sc.getUserPrincipal(); + UserMediaAdvancement elem = new UserMediaAdvancement(); + elem.userId = gc.userByToken.id; + elem.mediaId = id; + elem.time = data.time; + elem.percent = data.percent; + elem.count = data.count; + return SqlWrapper.insert(elem); + } + + public record MediaInformationsDelta( + int time, + float percent, + boolean addCount) {}; + + @PUT + @Path("{id}") + @RolesAllowed("USER") + @Consumes(MediaType.APPLICATION_JSON) + public UserMediaAdvancement put(@Context SecurityContext sc, @PathParam("id") Long id, MediaInformationsDelta data) throws Exception { + UserMediaAdvancement elem = this.getWithId(sc, id); + if (elem == null) { + // insert element + if (data.addCount) { + return this.post(sc, id, new MediaInformations(data.time(), data.percent(), 1)); + } else { + return this.post(sc, id, new MediaInformations(data.time(), data.percent(), 0)); + } + } + elem.time = data.time; + elem.percent = data.percent; + if (data.addCount) { + elem.count++; + } + LOGGER.info("{},{},{}", elem.time, elem.percent, elem.count); + int nbAfected = SqlWrapper.update(elem, elem.id, List.of("time", "percent", "count")); + // TODO: manage the fact that no element has been updated ... + UserMediaAdvancement ret = SqlWrapper.get(UserMediaAdvancement.class, elem.id); + return ret; + } + + @DELETE + @Path("{id}") + @RolesAllowed("USER") + public Response delete(@Context SecurityContext sc, @PathParam("id") Long id) throws Exception { + UserMediaAdvancement elem = this.getWithId(sc, id); + SqlWrapper.delete(UserMediaAdvancement.class, elem.id); return Response.ok().build(); - } - - + } + } diff --git a/back/src/org/kar/karideo/api/UserResource.java b/back/src/org/kar/karideo/api/UserResource.java index dfcf829..5f24d07 100755 --- a/back/src/org/kar/karideo/api/UserResource.java +++ b/back/src/org/kar/karideo/api/UserResource.java @@ -1,31 +1,34 @@ package org.kar.karideo.api; -import org.kar.archidata.SqlWrapper; -import org.kar.archidata.filter.GenericContext; -import org.kar.archidata.model.User; -import org.kar.karideo.model.UserKarideo; - -import com.fasterxml.jackson.annotation.JsonInclude; +import java.util.List; import org.kar.archidata.annotation.security.RolesAllowed; -import jakarta.ws.rs.*; -import jakarta.ws.rs.core.Context; -import jakarta.ws.rs.core.MediaType; -import jakarta.ws.rs.core.SecurityContext; -import java.util.List; +import org.kar.archidata.filter.GenericContext; +import org.kar.archidata.sqlWrapper.SqlWrapper; +import org.kar.karideo.model.UserKarideo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import com.fasterxml.jackson.annotation.JsonInclude; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.SecurityContext; @Path("/users") -@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) +@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public class UserResource { static final Logger LOGGER = LoggerFactory.getLogger(UserResource.class); - + @JsonInclude(JsonInclude.Include.NON_NULL) public class UserOut { public long id; public String login; + public UserOut(long id, String login) { super(); this.id = id; @@ -33,82 +36,50 @@ public class UserResource { } } - public UserResource() { - } - - // curl http://localhost:9993/api/users - @GET - @RolesAllowed("ADMIN") - public List getUsers() { - System.out.println("getUsers"); - try { - return SqlWrapper.gets(UserKarideo.class, false); + + public UserResource() {} + + // curl http://localhost:9993/api/users + @GET + @RolesAllowed("ADMIN") + public List getUsers() { + System.out.println("getUsers"); + try { + return SqlWrapper.gets(UserKarideo.class); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; - } - - // curl http://localhost:9993/api/users/3 - @GET - @Path("{id}") - @RolesAllowed("ADMIN") - public UserKarideo getUsers(@Context SecurityContext sc, @PathParam("id") long userId) { - System.out.println("getUser " + userId); - GenericContext gc = (GenericContext) sc.getUserPrincipal(); - System.out.println("==================================================="); - System.out.println("== USER ? " + gc.userByToken.name); - System.out.println("==================================================="); - try { + } + + // curl http://localhost:9993/api/users/3 + @GET + @Path("{id}") + @RolesAllowed("ADMIN") + public UserKarideo getUsers(@Context SecurityContext sc, @PathParam("id") long userId) { + System.out.println("getUser " + userId); + GenericContext gc = (GenericContext) sc.getUserPrincipal(); + System.out.println("==================================================="); + System.out.println("== USER ? " + gc.userByToken.name); + System.out.println("==================================================="); + try { return SqlWrapper.get(UserKarideo.class, userId); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } - return null; - } - - @GET - @Path("me") - @RolesAllowed("USER") - public UserOut getMe(@Context SecurityContext sc) { - LOGGER.debug("getMe()"); - GenericContext gc = (GenericContext) sc.getUserPrincipal(); - LOGGER.debug("== USER ? {}", gc.userByToken); - return new UserOut(gc.userByToken.id, gc.userByToken.name); - } - + return null; + } + + @GET + @Path("me") + @RolesAllowed("USER") + public UserOut getMe(@Context SecurityContext sc) { + LOGGER.debug("getMe()"); + GenericContext gc = (GenericContext) sc.getUserPrincipal(); + LOGGER.debug("== USER ? {}", gc.userByToken); + return new UserOut(gc.userByToken.id, gc.userByToken.name); + } + } - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/back/src/org/kar/karideo/api/VideoResource.java b/back/src/org/kar/karideo/api/VideoResource.java index 6ce6d99..81cfa8c 100644 --- a/back/src/org/kar/karideo/api/VideoResource.java +++ b/back/src/org/kar/karideo/api/VideoResource.java @@ -1,8 +1,19 @@ package org.kar.karideo.api; +import java.io.IOException; +import java.io.InputStream; +import java.sql.SQLException; +import java.util.List; + import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.FormDataParam; +import org.kar.archidata.annotation.security.RolesAllowed; +import org.kar.archidata.api.DataResource; +import org.kar.archidata.exception.FailException; +import org.kar.archidata.exception.InputException; import org.kar.archidata.model.Data; +import org.kar.archidata.sqlWrapper.SqlWrapper; +import org.kar.archidata.sqlWrapper.addOn.AddOnManyToMany; import org.kar.archidata.util.DataTools; import org.kar.karideo.model.Media; import org.kar.karideo.model.Season; @@ -10,215 +21,203 @@ import org.kar.karideo.model.Series; import org.kar.karideo.model.Type; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.kar.archidata.SqlWrapper; -import org.kar.archidata.annotation.security.RolesAllowed; -import org.kar.archidata.api.DataResource; -import org.kar.archidata.exception.FailException; -import org.kar.archidata.exception.InputException; -import jakarta.ws.rs.*; +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; -import java.io.IOException; -import java.io.InputStream; -import java.sql.*; -import java.util.List; - @Path("/video") -@Produces({MediaType.APPLICATION_JSON}) +@Produces({ MediaType.APPLICATION_JSON }) public class VideoResource { static final Logger LOGGER = LoggerFactory.getLogger(VideoResource.class); - - @GET - @RolesAllowed("USER") - public List get() throws Exception { - return SqlWrapper.gets(Media.class, false); - } - - @GET - @Path("{id}") - @RolesAllowed("USER") - public Media get(@PathParam("id") Long id) throws Exception { - return SqlWrapper.get(Media.class, id); - } - - @PUT - @Path("{id}") - @RolesAllowed("ADMIN") - @Consumes(MediaType.APPLICATION_JSON) - public Media put(@PathParam("id") Long id, String jsonRequest) throws Exception { - System.out.println("update video " + id + " ==> '" + jsonRequest + "'"); - SqlWrapper.update(Media.class, id, jsonRequest); - return SqlWrapper.get(Media.class, id); - } - - private String multipartCorrection(String data) { - if (data == null) { - return null; - } - if (data.isEmpty()) { - return null; - } - if (data.contentEquals("null")) { - return null; - } - return data; - } - - @POST - @Path("/upload/") - @RolesAllowed("ADMIN") - @Consumes({MediaType.MULTIPART_FORM_DATA}) - public Response uploadFile(@FormDataParam("fileName") String fileName, - @FormDataParam("universe") String universe, - @FormDataParam("series") String series, - //@FormDataParam("seriesId") String seriesId, Not used ... - @FormDataParam("season") String season, - @FormDataParam("episode") String episode, - @FormDataParam("title") String title, - @FormDataParam("typeId") String typeId, - @FormDataParam("file") InputStream fileInputStream, - @FormDataParam("file") FormDataContentDisposition fileMetaData - ) throws FailException { - try { - // correct input string stream : - fileName = multipartCorrection(fileName); - universe = multipartCorrection(universe); - series = multipartCorrection(series); - season = multipartCorrection(season); - episode = multipartCorrection(episode); - title = multipartCorrection(title); - typeId = multipartCorrection(typeId); - - //public NodeSmall uploadFile(final FormDataMultiPart form) { - System.out.println("Upload media file: " + fileMetaData); - System.out.println(" - fileName: " + fileName); - System.out.println(" - universe: " + universe); - System.out.println(" - series: " + series); - System.out.println(" - season: " + season); - System.out.println(" - episode: " + episode); - System.out.println(" - title: " + title); - System.out.println(" - type: " + typeId); - System.out.println(" - fileInputStream: " + fileInputStream); - System.out.println(" - fileMetaData: " + fileMetaData); - System.out.flush(); - if (typeId == null) { - throw new InputException("typeId", "TypiId is not specified"); - } - - long tmpUID = DataResource.getTmpDataId(); - String sha512 = DataResource.saveTemporaryFile(fileInputStream, tmpUID); - Data data = DataResource.getWithSha512(sha512); - if (data == null) { - System.out.println("Need to add the data in the BDD ... "); - System.out.flush(); - try { - data = DataResource.createNewData(tmpUID, fileName, sha512); - } catch (IOException ex) { - DataResource.removeTemporaryFile(tmpUID); - ex.printStackTrace(); - throw new FailException("can not create input media (the data model has an internal error"); - } - } else if (data.deleted == true) { - System.out.println("Data already exist but deleted"); - System.out.flush(); - DataResource.undelete(data.id); - data.deleted = false; - } else { - System.out.println("Data already exist ... all good"); - System.out.flush(); - } - // Fist step: retive all the Id of each parents:... - System.out.println("Find typeNode"); - // check if id of type exist: - Type typeNode = TypeResource.getId(Long.parseLong(typeId)); - if (typeNode == null) { - DataResource.removeTemporaryFile(tmpUID); - throw new InputException("typeId", "TypeId does not exist ..."); - } - System.out.println(" ==> " + typeNode); - System.out.println("Find seriesNode"); - // get uid of group: - Series seriesNode = null; - if (series != null) { - seriesNode = SeriesResource.getOrCreate(series, typeNode.id); - } - - System.out.println(" ==> " + seriesNode); - System.out.println("Find seasonNode"); - // get uid of season: - Season seasonNode = null; - if (seriesNode == null && season != null) { - DataResource.removeTemporaryFile(tmpUID); - throw new InputException("season", "Season is set but no seraies is set !!"); - } - if (season != null) { - seasonNode = SeasonResource.getOrCreate(season, seriesNode.id); - } - - System.out.println(" ==> " + seasonNode); - System.out.println("add media"); - - - long uniqueSQLID = -1; - try { - Media media = new Media(); - media.name = title; - media.dataId = data.id; - media.typeId = typeNode.id; - media.seriesId = null; - if(seriesNode != null) { - media.seriesId = seriesNode.id; - } - media.seasonId = null; - if (seasonNode != null) { - media.seasonId = seasonNode.id; - } - media.episode = null; - if (episode != null && ! episode.contentEquals("")) { - media.episode = Integer.parseInt(episode); - } - Media out = SqlWrapper.insert(media); - DataResource.removeTemporaryFile(tmpUID); - System.out.println("uploaded .... compleate: " + uniqueSQLID); - Media creation = get(uniqueSQLID); - return Response.ok(creation).build(); - } catch (SQLException ex) { - ex.printStackTrace(); - System.out.println("Catch error:" + ex.getMessage()); - throw new FailException("Catch SQLerror ==> check server logs"); - } - } catch (Exception ex) { - System.out.println("Catch an unexpected error ... " + ex.getMessage()); - ex.printStackTrace(); - throw new FailException("Catch Exception ==> check server logs"); - } - } - @POST - @Path("{id}/add_cover") - @RolesAllowed("ADMIN") - @Consumes({MediaType.MULTIPART_FORM_DATA}) - public Response uploadCover(@PathParam("id") Long id, - @FormDataParam("fileName") String fileName, - @FormDataParam("file") InputStream fileInputStream, - @FormDataParam("file") FormDataContentDisposition fileMetaData - ) { - return DataTools.uploadCover(Media.class, id, fileName, fileInputStream, fileMetaData); - } - @GET - @Path("{id}/rm_cover/{coverId}") - @RolesAllowed("ADMIN") - public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception { - SqlWrapper.removeLink(Media.class, id, "cover", coverId); - return Response.ok(SqlWrapper.get(Media.class, id)).build(); - } - - @DELETE - @Path("{id}") - @RolesAllowed("ADMIN") - public Response delete(@PathParam("id") Long id) throws Exception { - SqlWrapper.setDelete(Media.class, id); + + @GET + @RolesAllowed("USER") + public List get() throws Exception { + return SqlWrapper.gets(Media.class); + } + + @GET + @Path("{id}") + @RolesAllowed("USER") + public Media get(@PathParam("id") Long id) throws Exception { + return SqlWrapper.get(Media.class, id); + } + + @PUT + @Path("{id}") + @RolesAllowed("ADMIN") + @Consumes(MediaType.APPLICATION_JSON) + public Media put(@PathParam("id") Long id, String jsonRequest) throws Exception { + System.out.println("update video " + id + " ==> '" + jsonRequest + "'"); + SqlWrapper.update(Media.class, id, jsonRequest); + return SqlWrapper.get(Media.class, id); + } + + private String multipartCorrection(String data) { + if (data == null) { + return null; + } + if (data.isEmpty()) { + return null; + } + if (data.contentEquals("null")) { + return null; + } + return data; + } + + @POST + @Path("/upload/") + @RolesAllowed("ADMIN") + @Consumes({ MediaType.MULTIPART_FORM_DATA }) + public Response uploadFile(@FormDataParam("fileName") String fileName, @FormDataParam("universe") String universe, @FormDataParam("series") String series, + //@FormDataParam("seriesId") String seriesId, Not used ... + @FormDataParam("season") String season, @FormDataParam("episode") String episode, @FormDataParam("title") String title, @FormDataParam("typeId") String typeId, + @FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition fileMetaData) throws FailException { + try { + // correct input string stream : + fileName = multipartCorrection(fileName); + universe = multipartCorrection(universe); + series = multipartCorrection(series); + season = multipartCorrection(season); + episode = multipartCorrection(episode); + title = multipartCorrection(title); + typeId = multipartCorrection(typeId); + + //public NodeSmall uploadFile(final FormDataMultiPart form) { + System.out.println("Upload media file: " + fileMetaData); + System.out.println(" - fileName: " + fileName); + System.out.println(" - universe: " + universe); + System.out.println(" - series: " + series); + System.out.println(" - season: " + season); + System.out.println(" - episode: " + episode); + System.out.println(" - title: " + title); + System.out.println(" - type: " + typeId); + System.out.println(" - fileInputStream: " + fileInputStream); + System.out.println(" - fileMetaData: " + fileMetaData); + System.out.flush(); + if (typeId == null) { + throw new InputException("typeId", "TypiId is not specified"); + } + + long tmpUID = DataResource.getTmpDataId(); + String sha512 = DataResource.saveTemporaryFile(fileInputStream, tmpUID); + Data data = DataResource.getWithSha512(sha512); + if (data == null) { + System.out.println("Need to add the data in the BDD ... "); + System.out.flush(); + try { + data = DataResource.createNewData(tmpUID, fileName, sha512); + } catch (IOException ex) { + DataResource.removeTemporaryFile(tmpUID); + ex.printStackTrace(); + throw new FailException("can not create input media (the data model has an internal error"); + } + } else if (data.deleted == true) { + System.out.println("Data already exist but deleted"); + System.out.flush(); + DataResource.undelete(data.id); + data.deleted = false; + } else { + System.out.println("Data already exist ... all good"); + System.out.flush(); + } + // Fist step: retive all the Id of each parents:... + System.out.println("Find typeNode"); + // check if id of type exist: + Type typeNode = TypeResource.getId(Long.parseLong(typeId)); + if (typeNode == null) { + DataResource.removeTemporaryFile(tmpUID); + throw new InputException("typeId", "TypeId does not exist ..."); + } + System.out.println(" ==> " + typeNode); + System.out.println("Find seriesNode"); + // get uid of group: + Series seriesNode = null; + if (series != null) { + seriesNode = SeriesResource.getOrCreate(series, typeNode.id); + } + + System.out.println(" ==> " + seriesNode); + System.out.println("Find seasonNode"); + // get uid of season: + Season seasonNode = null; + if (seriesNode == null && season != null) { + DataResource.removeTemporaryFile(tmpUID); + throw new InputException("season", "Season is set but no seraies is set !!"); + } + if (season != null) { + seasonNode = SeasonResource.getOrCreate(season, seriesNode.id); + } + + System.out.println(" ==> " + seasonNode); + System.out.println("add media"); + + long uniqueSQLID = -1; + try { + Media media = new Media(); + media.name = title; + media.dataId = data.id; + media.typeId = typeNode.id; + media.seriesId = null; + if (seriesNode != null) { + media.seriesId = seriesNode.id; + } + media.seasonId = null; + if (seasonNode != null) { + media.seasonId = seasonNode.id; + } + media.episode = null; + if (episode != null && !episode.contentEquals("")) { + media.episode = Integer.parseInt(episode); + } + Media out = SqlWrapper.insert(media); + DataResource.removeTemporaryFile(tmpUID); + System.out.println("uploaded .... compleate: " + uniqueSQLID); + Media creation = get(uniqueSQLID); + return Response.ok(creation).build(); + } catch (SQLException ex) { + ex.printStackTrace(); + System.out.println("Catch error:" + ex.getMessage()); + throw new FailException("Catch SQLerror ==> check server logs"); + } + } catch (Exception ex) { + System.out.println("Catch an unexpected error ... " + ex.getMessage()); + ex.printStackTrace(); + throw new FailException("Catch Exception ==> check server logs"); + } + } + + @POST + @Path("{id}/add_cover") + @RolesAllowed("ADMIN") + @Consumes({ MediaType.MULTIPART_FORM_DATA }) + public Response uploadCover(@PathParam("id") Long id, @FormDataParam("fileName") String fileName, @FormDataParam("file") InputStream fileInputStream, + @FormDataParam("file") FormDataContentDisposition fileMetaData) { + return DataTools.uploadCover(Media.class, id, fileName, fileInputStream, fileMetaData); + } + + @GET + @Path("{id}/rm_cover/{coverId}") + @RolesAllowed("ADMIN") + public Response removeCover(@PathParam("id") Long id, @PathParam("coverId") Long coverId) throws Exception { + AddOnManyToMany.removeLink(Media.class, id, "cover", coverId); + return Response.ok(SqlWrapper.get(Media.class, id)).build(); + } + + @DELETE + @Path("{id}") + @RolesAllowed("ADMIN") + public Response delete(@PathParam("id") Long id) throws Exception { + SqlWrapper.delete(Media.class, id); return Response.ok().build(); - } + } } diff --git a/back/src/org/kar/karideo/migration/Migration20231015.java b/back/src/org/kar/karideo/migration/Migration20231015.java new file mode 100644 index 0000000..8b7cd98 --- /dev/null +++ b/back/src/org/kar/karideo/migration/Migration20231015.java @@ -0,0 +1,27 @@ +package org.kar.karideo.migration; + +import java.util.List; + +import org.kar.archidata.migration.MigrationSqlStep; + +public class Migration20231015 extends MigrationSqlStep { + + public static final int KARSO_INITIALISATION_ID = 1; + + @Override + public String getName() { + return "refactor creation and update time"; + } + + public Migration20231015() throws Exception { + for (String elem : List.of("data", "media", "media_link_cover", "season", "season_link_cover", "series", "series_link_cover", "type", "type_link_cover", "user", "userMediaAdvancement")) { + addAction(""" + ALTER TABLE `""" + elem + """ + ` + RENAME COLUMN `create_date` TO `createdAt`, + RENAME COLUMN `modify_date` TO `updatedAt`; + """); + } + display(); + } +} diff --git a/back/src/org/kar/karideo/model/Media.java b/back/src/org/kar/karideo/model/Media.java index 31b0102..fb15785 100644 --- a/back/src/org/kar/karideo/model/Media.java +++ b/back/src/org/kar/karideo/model/Media.java @@ -2,48 +2,51 @@ package org.kar.karideo.model; import java.util.List; -import org.kar.archidata.annotation.SQLComment; -import org.kar.archidata.annotation.SQLForeignKey; -import org.kar.archidata.annotation.SQLIfNotExists; -import org.kar.archidata.annotation.SQLNotNull; -import org.kar.archidata.annotation.SQLTableLinkGeneric; -import org.kar.archidata.annotation.SQLTableName; +import org.kar.archidata.model.Data; import org.kar.archidata.model.GenericTable; import com.fasterxml.jackson.annotation.JsonInclude; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.FetchType; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; -@SQLTableName ("media") -@SQLIfNotExists +@Entity +@Table(name = "media") @JsonInclude(JsonInclude.Include.NON_NULL) +//@SQLDelete(sql = "UPDATE table_product SET deleted = true WHERE id=?") +//@Where(clause = "deleted=false") public class Media extends GenericTable { - @SQLNotNull - @SQLComment("Name of the media (this represent the title)") - public String name; - @SQLComment("Description of the media") - public String description; - @SQLNotNull - @SQLComment("Foreign Key Id of the data") - @SQLForeignKey("data") - public Long dataId; - @SQLComment("Type of the media") - @SQLForeignKey("type") - public Long typeId; - @SQLComment("Series reference of the media") - @SQLForeignKey("series") - public Long seriesId; - @SQLComment("Saison reference of the media") - @SQLForeignKey("season") - public Long seasonId; - @SQLComment("Episide Id") - public Integer episode; - @SQLComment("") - public Integer date; - @SQLComment("Creation years of the media") - public Integer time; - @SQLComment("Limitation Age of the media") - public Integer ageLimit; - @SQLComment("List of Id of the sopecific covers") - @SQLTableLinkGeneric - public List covers = null; + // Name of the media (this represent the title) + @Column(nullable = false) + public String name; + // Description of the media + public String description; + // Foreign Key Id of the data + @ManyToOne(fetch = FetchType.LAZY, targetEntity = Data.class) + @Column(nullable = false) + public Long dataId; + // Type of the media") + @ManyToOne(fetch = FetchType.LAZY, targetEntity = Type.class) + public Long typeId; + // Series reference of the media + @ManyToOne(fetch = FetchType.LAZY, targetEntity = Series.class) + public Long seriesId; + // Saison reference of the media + @ManyToOne(fetch = FetchType.LAZY, targetEntity = Season.class) + public Long seasonId; + // Episide Id + public Integer episode; + // ") + public Integer date; + // Creation years of the media + public Integer time; + // Limitation Age of the media + public Integer ageLimit; + // List of Id of the specific covers + @ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class) + public List covers = null; } diff --git a/back/src/org/kar/karideo/model/Season.java b/back/src/org/kar/karideo/model/Season.java index 33dcf0a..249a64f 100644 --- a/back/src/org/kar/karideo/model/Season.java +++ b/back/src/org/kar/karideo/model/Season.java @@ -3,30 +3,32 @@ package org.kar.karideo.model; import java.util.List; import org.kar.archidata.annotation.SQLComment; -import org.kar.archidata.annotation.SQLForeignKey; import org.kar.archidata.annotation.SQLIfNotExists; -import org.kar.archidata.annotation.SQLNotNull; -import org.kar.archidata.annotation.SQLTableLinkGeneric; -import org.kar.archidata.annotation.SQLTableName; +import org.kar.archidata.model.Data; import org.kar.archidata.model.GenericTable; import com.fasterxml.jackson.annotation.JsonInclude; +import jakarta.persistence.Column; +import jakarta.persistence.FetchType; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; -@SQLTableName ("season") +@Table(name = "season") @SQLIfNotExists @JsonInclude(JsonInclude.Include.NON_NULL) public class Season extends GenericTable { - @SQLNotNull - @SQLComment("Name of the media (this represent the title)") - public String name; - @SQLComment("Description of the media") - public String description; - @SQLNotNull - @SQLComment("series parent ID") - @SQLForeignKey("series") - public Long parentId; - @SQLComment("List of Id of the sopecific covers") - @SQLTableLinkGeneric - public List covers = null; + @Column(nullable = false) + @SQLComment("Name of the media (this represent the title)") + public String name; + @SQLComment("Description of the media") + public String description; + @Column(nullable = false) + @SQLComment("series parent ID") + @ManyToOne(fetch = FetchType.LAZY, targetEntity = Series.class) + public Long parentId; + @SQLComment("List of Id of the sopecific covers") + @ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class) + public List covers = null; } \ No newline at end of file diff --git a/back/src/org/kar/karideo/model/Series.java b/back/src/org/kar/karideo/model/Series.java index 05956ec..47228bb 100644 --- a/back/src/org/kar/karideo/model/Series.java +++ b/back/src/org/kar/karideo/model/Series.java @@ -3,30 +3,32 @@ package org.kar.karideo.model; import java.util.List; import org.kar.archidata.annotation.SQLComment; -import org.kar.archidata.annotation.SQLForeignKey; import org.kar.archidata.annotation.SQLIfNotExists; -import org.kar.archidata.annotation.SQLNotNull; -import org.kar.archidata.annotation.SQLTableLinkGeneric; -import org.kar.archidata.annotation.SQLTableName; +import org.kar.archidata.model.Data; import org.kar.archidata.model.GenericTable; import com.fasterxml.jackson.annotation.JsonInclude; +import jakarta.persistence.Column; +import jakarta.persistence.FetchType; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; -@SQLTableName ("series") +@Table(name = "series") @SQLIfNotExists @JsonInclude(JsonInclude.Include.NON_NULL) public class Series extends GenericTable { - @SQLNotNull - @SQLComment("Name of the media (this represent the title)") - public String name; - @SQLComment("Description of the media") - public String description; - @SQLNotNull - @SQLComment("series parent ID") - @SQLForeignKey("type") - public Long parentId; - @SQLComment("List of Id of the sopecific covers") - @SQLTableLinkGeneric - public List covers = null; + @Column(nullable = false) + @SQLComment("Name of the media (this represent the title)") + public String name; + @SQLComment("Description of the media") + public String description; + @Column(nullable = false) + @SQLComment("series parent ID") + @ManyToOne(fetch = FetchType.LAZY, targetEntity = Type.class) + public Long parentId; + @SQLComment("List of Id of the sopecific covers") + @ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class) + public List covers = null; } diff --git a/back/src/org/kar/karideo/model/Type.java b/back/src/org/kar/karideo/model/Type.java index 3d3c3e7..73ccb11 100644 --- a/back/src/org/kar/karideo/model/Type.java +++ b/back/src/org/kar/karideo/model/Type.java @@ -4,24 +4,26 @@ import java.util.List; import org.kar.archidata.annotation.SQLComment; import org.kar.archidata.annotation.SQLIfNotExists; -import org.kar.archidata.annotation.SQLNotNull; -import org.kar.archidata.annotation.SQLTableLinkGeneric; -import org.kar.archidata.annotation.SQLTableName; +import org.kar.archidata.model.Data; import org.kar.archidata.model.GenericTable; import com.fasterxml.jackson.annotation.JsonInclude; +import jakarta.persistence.Column; +import jakarta.persistence.FetchType; +import jakarta.persistence.ManyToMany; +import jakarta.persistence.Table; -@SQLTableName ("type") +@Table(name = "type") @SQLIfNotExists @JsonInclude(JsonInclude.Include.NON_NULL) public class Type extends GenericTable { - @SQLNotNull - @SQLComment("Name of the media (this represent the title)") - public String name; - @SQLComment("Description of the media") - public String description; - @SQLComment("List of Id of the sopecific covers") - @SQLTableLinkGeneric - public List covers = null; + @Column(nullable = false) + @SQLComment("Name of the media (this represent the title)") + public String name; + @SQLComment("Description of the media") + public String description; + @SQLComment("List of Id of the sopecific covers") + @ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class) + public List covers = null; } diff --git a/back/src/org/kar/karideo/model/UserKarideo.java b/back/src/org/kar/karideo/model/UserKarideo.java index 739e6a9..ee780dc 100644 --- a/back/src/org/kar/karideo/model/UserKarideo.java +++ b/back/src/org/kar/karideo/model/UserKarideo.java @@ -1,12 +1,13 @@ package org.kar.karideo.model; import org.kar.archidata.annotation.SQLIfNotExists; -import org.kar.archidata.annotation.SQLTableName; import org.kar.archidata.model.User; import com.fasterxml.jackson.annotation.JsonInclude; -@SQLTableName ("user") +import jakarta.persistence.Table; + +@Table(name = "user") @SQLIfNotExists @JsonInclude(JsonInclude.Include.NON_NULL) public class UserKarideo extends User { diff --git a/back/src/org/kar/karideo/model/UserMediaAdvancement.java b/back/src/org/kar/karideo/model/UserMediaAdvancement.java index f75e015..6923098 100644 --- a/back/src/org/kar/karideo/model/UserMediaAdvancement.java +++ b/back/src/org/kar/karideo/model/UserMediaAdvancement.java @@ -1,34 +1,35 @@ package org.kar.karideo.model; import org.kar.archidata.annotation.SQLComment; -import org.kar.archidata.annotation.SQLForeignKey; import org.kar.archidata.annotation.SQLIfNotExists; -import org.kar.archidata.annotation.SQLNotNull; -import org.kar.archidata.annotation.SQLTableName; import org.kar.archidata.model.GenericTable; import com.fasterxml.jackson.annotation.JsonInclude; +import jakarta.persistence.Column; +import jakarta.persistence.FetchType; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; -@SQLTableName ("userMediaAdvancement") +@Table(name = "userMediaAdvancement") @SQLIfNotExists @JsonInclude(JsonInclude.Include.NON_NULL) public class UserMediaAdvancement extends GenericTable { - @SQLNotNull - @SQLComment("Foreign Key Id of the user") - @SQLForeignKey("user") - public long userId; - @SQLNotNull - @SQLComment("Id of the media") - @SQLForeignKey("media") - public long mediaId; - @SQLNotNull - @SQLComment("Percent of admencement in the media") - public float percent; - @SQLNotNull - @SQLComment("Number of second of admencement in the media") - public int time; - @SQLNotNull - @SQLComment("Number of time this media has been read") - public int count; + @Column(nullable = false) + @SQLComment("Foreign Key Id of the user") + @ManyToOne(fetch = FetchType.LAZY, targetEntity = UserKarideo.class) + public long userId; + @Column(nullable = false) + @SQLComment("Id of the media") + @ManyToOne(fetch = FetchType.LAZY, targetEntity = Media.class) + public long mediaId; + @Column(nullable = false) + @SQLComment("Percent of admencement in the media") + public float percent; + @Column(nullable = false) + @SQLComment("Number of second of admencement in the media") + public int time; + @Column(nullable = false) + @SQLComment("Number of time this media has been read") + public int count; } diff --git a/front/package.json b/front/package.json index a4c5ce1..88496c9 100644 --- a/front/package.json +++ b/front/package.json @@ -5,7 +5,7 @@ "scripts": { "all": "npm run build && npm run test", "ng": "ng", - "start": "ng serve --configuration=develop --watch --port 4202", + "dev": "ng serve --configuration=develop --watch --port 4202", "build": "ng build --prod", "test": "ng test", "lint": "ng lint", @@ -38,4 +38,4 @@ "@angular/compiler-cli": "^14.2.10", "@angular/language-service": "^14.2.10" } -} +} \ No newline at end of file