31 Commits

Author SHA1 Message Date
6155ca5c0b [RELEASE] Release v0.2.0 2024-05-12 12:03:31 +02:00
45eb56a6fe [DEV] update relase for island 2024-05-12 11:57:08 +02:00
9e0a834b48 [DEV] update readme 2024-04-15 00:57:00 +02:00
d5f335e1e7 [DEV] add progress callback 2024-04-15 00:56:45 +02:00
df384cc8be [DEV] correct version with some ibrary update 2024-04-13 09:03:05 +02:00
4b545ebbe2 [FIX] update dockerfile 2024-04-07 19:25:07 +02:00
eb3cd1b1fe [DEV] all is operational 2024-04-07 19:13:06 +02:00
95e2e03686 [DEV] all work well 2024-04-07 17:08:43 +02:00
2402fc31ed [DEV] it works without security 2024-04-07 17:05:36 +02:00
763875fbdf {DEV] still work 2024-04-07 09:02:17 +02:00
4ff2b247b4 [DEV] update to basic work 2024-04-06 13:08:12 +02:00
e4246750c7 [DEV] Run but does not realy start 2024-04-05 23:51:48 +02:00
04633240b3 [DEV] find how to fix the error but not Ok with the result 2024-04-03 00:34:47 +02:00
c76a339caf [DEV] update new model with remote library (not work) 2024-03-29 18:39:33 +01:00
8a5758af78 [DEV] remove submodule and correct first init 2024-03-23 07:27:27 +01:00
e05fe70f80 [DEV] ready for deply new model of data UUID 2024-03-19 23:17:05 +01:00
f6f9fa199a [DEV] update new version 2024-03-19 19:17:04 +01:00
a1684f0fc0 [DEV] update new model 2024-03-19 08:37:07 +01:00
cebf7d35fb [DEV] update all the model 2024-03-17 23:45:38 +01:00
5d8dab3742 [DEV] finish base of port but not tested 2024-03-15 07:59:23 +01:00
9a3f28553d [DEV] basic migration of to the new generation interface 2024-03-11 00:07:46 +01:00
48e14212db [DEV] implement partial migration to support new uuid for data and local cover of model 2024-03-04 00:14:08 +01:00
c3e2b7240b [DEV] migrate with succes to angular17 2024-02-26 00:01:37 +01:00
0af1bbfb52 [DEV] correct the backend can not insert trach artist ... fail t in archidata model 2024-02-26 00:01:05 +01:00
619973459a [DEV] continue migration to Angular17 2024-02-23 00:37:47 +01:00
d37ce25621 [DEV] update to angular17 2024-02-15 22:59:35 +01:00
b4157877c3 [DEV] add search in artist and album 2024-01-27 19:34:53 +01:00
883866d5f6 [DEV] update display better 2024-01-27 18:09:29 +01:00
247064e412 [DEV] remove test replace 2024-01-25 23:39:41 +01:00
70c63882e4 [DEV] corrrect the desplay of the player overflow (and some redesign) 2024-01-25 23:37:36 +01:00
9da93a2831 [DEV] update dev tag version 2024-01-19 22:50:09 +01:00
113 changed files with 16233 additions and 25910 deletions

3
.gitmodules vendored
View File

@@ -1,3 +0,0 @@
[submodule "front/src/common"]
path = front/src/common
url = ../common_web.git

View File

@@ -1,7 +1,29 @@
#!/bin/bash
version_file="../version.txt"
# update new release dependency
cd back
mvn versions:set -DnewVersion=$(cat ../version.txt)
# update the Maven version number
mvn versions:set -DnewVersion=$(sed 's/DEV/SNAPSHOT/g' $version_file)
if grep -q "DEV" "$version_file"; then
# update all versions release of dependency
mvn versions:use-latest-releases
# update our manage dependency as snapshoot
mvn versions:use-latest-versions -Dincludes=kangaroo-and-rabbit
else
# update our manage dependency as release (must be done before)
mvn versions:use-latest-releases -Dincludes=kangaroo-and-rabbit
fi
cd -
cd front
if grep -q "DEV" "$version_file"; then
# update all dependency
pnpm install
pnpm run update_packages
else
# in case of release ==> can not do it automatically ...
fi
cd -

View File

@@ -6,7 +6,7 @@
FROM archlinux:base-devel AS builder
# update system
RUN pacman -Syu --noconfirm && pacman-db-upgrade \
&& pacman -S --noconfirm jdk-openjdk maven npm \
&& pacman -S --noconfirm jdk-openjdk maven npm pnpm \
&& pacman -Scc --noconfirm
ENV PATH /tmp/node_modules/.bin:$PATH
@@ -29,14 +29,15 @@ RUN mvn clean compile assembly:single
######################################################################################
FROM builder AS buildFront
ADD front/package-lock.json \
front/package.json \
RUN echo "@kangaroo-and-rabbit:registry=https://gitea.atria-soft.org/api/packages/kangaroo-and-rabbit/npm/" > /root/.npmrc
ADD front/package.json \
front/karma.conf.js \
front/protractor.conf.js \
/tmp/
# install and cache app dependencies
RUN npm install
RUN pnpm install
ADD front/e2e \
front/tsconfig.json \

View File

@@ -20,13 +20,18 @@
<dependency>
<groupId>kangaroo-and-rabbit</groupId>
<artifactId>archidata</artifactId>
<version>0.6.0</version>
<version>0.7.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.16.1</version>
</dependency>
<!--
************************************************************
** TEST dependency **

View File

@@ -13,6 +13,7 @@ import org.kar.archidata.api.DataResource;
import org.kar.archidata.catcher.ExceptionCatcher;
import org.kar.archidata.catcher.FailExceptionCatcher;
import org.kar.archidata.catcher.InputExceptionCatcher;
import org.kar.archidata.catcher.JacksonCatcher;
import org.kar.archidata.catcher.SystemExceptionCatcher;
import org.kar.archidata.filter.CORSFilter;
import org.kar.archidata.filter.OptionFilter;
@@ -29,6 +30,8 @@ import org.kar.karusic.api.UserResource;
import org.kar.karusic.filter.KarusicAuthenticationFilter;
import org.kar.karusic.migration.Initialization;
import org.kar.karusic.migration.Migration20231126;
import org.kar.karusic.migration.Migration20240225;
import org.kar.karusic.migration.Migration20240226;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -38,15 +41,15 @@ public class WebLauncher {
final static Logger LOGGER = LoggerFactory.getLogger(WebLauncher.class);
protected UpdateJwtPublicKey keyUpdater = null;
protected HttpServer server = null;
public WebLauncher() {
ConfigBaseVariable.bdDatabase = "karusic";
}
private static URI getBaseURI() {
return UriBuilder.fromUri(ConfigBaseVariable.getlocalAddress()).build();
}
public void migrateDB() throws Exception {
WebLauncher.LOGGER.info("Create migration engine");
final MigrationEngine migrationEngine = new MigrationEngine();
@@ -54,16 +57,18 @@ public class WebLauncher {
migrationEngine.setInit(new Initialization());
WebLauncher.LOGGER.info("Add migration since last version");
migrationEngine.add(new Migration20231126());
migrationEngine.add(new Migration20240225());
migrationEngine.add(new Migration20240226());
WebLauncher.LOGGER.info("Migrate the DB [START]");
migrationEngine.migrateWaitAdmin(GlobalConfiguration.dbConfig);
WebLauncher.LOGGER.info("Migrate the DB [STOP]");
}
public static void main(final String[] args) throws Exception {
WebLauncher.LOGGER.info("[START] application wake UP");
final WebLauncher launcher = new WebLauncher();
launcher.migrateDB();
launcher.process();
WebLauncher.LOGGER.info("end-configure the server & wait finish process:");
Thread.currentThread().join();
@@ -71,13 +76,13 @@ public class WebLauncher {
launcher.stopOther();
WebLauncher.LOGGER.info("STOP the REST server:");
}
public void process() throws InterruptedException {
// ===================================================================
// Configure resources
// ===================================================================
final ResourceConfig rc = new ResourceConfig();
// add multipart models ..
rc.register(MultiPartFeature.class);
// global authentication system
@@ -87,6 +92,7 @@ public class WebLauncher {
// global authentication system
rc.register(KarusicAuthenticationFilter.class);
// register exception catcher
rc.register(JacksonCatcher.class);
rc.register(InputExceptionCatcher.class);
rc.register(SystemExceptionCatcher.class);
rc.register(FailExceptionCatcher.class);
@@ -99,15 +105,15 @@ public class WebLauncher {
rc.register(PlaylistResource.class);
rc.register(TrackResource.class);
rc.register(DataResource.class);
rc.register(HealthCheck.class);
rc.register(Front.class);
// add jackson to be discover when we are ins standalone server
rc.register(JacksonFeature.class);
// enable this to show low level request
//rc.property(LoggingFeature.LOGGING_FEATURE_LOGGER_LEVEL_SERVER, Level.WARNING.getName());
//System.out.println("Connect on the BDD:");
//System.out.println(" getDBHost: '" + ConfigVariable.getDBHost() + "'");
//System.out.println(" getDBPort: '" + ConfigVariable.getDBPort() + "'");
@@ -125,13 +131,13 @@ public class WebLauncher {
serverLink.shutdownNow();
}
}, "shutdownHook"));
// ===================================================================
// start periodic update of the token ...
// ===================================================================
this.keyUpdater = new UpdateJwtPublicKey();
this.keyUpdater.start();
// ===================================================================
// run JERSEY
// ===================================================================
@@ -143,14 +149,14 @@ public class WebLauncher {
e.printStackTrace();
}
}
public void stop() {
if (this.server != null) {
this.server.shutdownNow();
this.server = null;
}
}
public void stopOther() {
this.keyUpdater.kill();
try {

View File

@@ -1,22 +1,46 @@
package org.kar.karusic;
import java.util.List;
import org.kar.archidata.api.DataResource;
import org.kar.archidata.dataAccess.DataFactoryTsApi;
import org.kar.archidata.tools.ConfigBaseVariable;
import org.kar.karusic.api.AlbumResource;
import org.kar.karusic.api.ArtistResource;
import org.kar.karusic.api.Front;
import org.kar.karusic.api.GenderResource;
import org.kar.karusic.api.HealthCheck;
import org.kar.karusic.api.PlaylistResource;
import org.kar.karusic.api.TrackResource;
import org.kar.karusic.api.UserResource;
import org.kar.karusic.migration.Initialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WebLauncherLocal extends WebLauncher {
final Logger logger = LoggerFactory.getLogger(WebLauncherLocal.class);
private static final Logger LOGGER = LoggerFactory.getLogger(WebLauncherLocal.class);
private WebLauncherLocal() {}
public static void main(final String[] args) throws InterruptedException {
public static void main(final String[] args) throws Exception {
DataFactoryTsApi.generatePackage(List.of(
AlbumResource.class,
ArtistResource.class,
Front.class,
GenderResource.class,
HealthCheck.class,
PlaylistResource.class,
UserResource.class,
TrackResource.class,
DataResource.class),
Initialization.CLASSES_BASE, "../front/src/app/back-api/");
final WebLauncherLocal launcher = new WebLauncherLocal();
launcher.process();
launcher.logger.info("end-configure the server & wait finish process:");
launcher.LOGGER.info("end-configure the server & wait finish process:");
Thread.currentThread().join();
launcher.logger.info("STOP the REST server:");
launcher.LOGGER.info("STOP the REST server:");
}
@Override
public void process() throws InterruptedException {
if (true) {

View File

@@ -2,14 +2,21 @@ package org.kar.karusic.api;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.AsyncType;
import org.kar.archidata.annotation.TypeScriptProgress;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.addOn.AddOnDataJson;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.tools.DataTools;
import org.kar.karusic.model.Album;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
@@ -25,75 +32,86 @@ import jakarta.ws.rs.core.Response;
@Path("/album")
@Produces({ MediaType.APPLICATION_JSON })
public class AlbumResource {
private static final Logger LOGGER = LoggerFactory.getLogger(AlbumResource.class);
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Album getWithId(@PathParam("id") final Long id) throws Exception {
@Operation(description = "Get a specific Album with his ID")
public static Album get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Album.class, id);
}
@GET
@RolesAllowed("USER")
public List<Album> get() throws Exception {
@Operation(description = "Get all the available Albums")
public List<Album> gets() throws Exception {
return DataAccess.gets(Album.class);
}
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Album post(final String jsonRequest) throws Exception {
@Operation(description = "Add an album (when all the data already exist)")
public Album post(@AsyncType(Album.class) final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Album.class, jsonRequest);
}
@PATCH
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Album put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
@Operation(description = "Update a specific album")
public Album patch(@PathParam("id") final Long id, @AsyncType(Album.class) final String jsonRequest) throws Exception {
DataAccess.updateWithJson(Album.class, id, jsonRequest);
return DataAccess.get(Album.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") final Long id) throws Exception {
@Operation(description = "Remove a specific album")
public void remove(@PathParam("id") final Long id) throws Exception {
DataAccess.delete(Album.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_track/{trackId}")
@Path("{id}/track/{trackId}")
@RolesAllowed("ADMIN")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Operation(description = "Add a Track on a specific album")
public Album addTrack(@PathParam("id") final Long id, @PathParam("trackId") final Long trackId) throws Exception {
AddOnManyToMany.removeLink(Album.class, id, "track", trackId);
return DataAccess.get(Album.class, id);
}
@GET
@Path("{id}/rm_track/{trackId}")
@DELETE
@Path("{id}/track/{trackId}")
@RolesAllowed("ADMIN")
@Operation(description = "Remove a Track on a specific album")
public Album removeTrack(@PathParam("id") final Long id, @PathParam("trackId") final Long trackId) throws Exception {
AddOnManyToMany.removeLink(Album.class, id, "track", trackId);
return DataAccess.get(Album.class, id);
}
@POST
@Path("{id}/add_cover")
@Path("{id}/cover")
@RolesAllowed("ADMIN")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@Operation(description = "Add a cover on a specific album")
@AsyncType(Album.class)
@TypeScriptProgress
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
return DataTools.uploadCover(Album.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@DELETE
@Path("{id}/cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") final Long id, @PathParam("coverId") final Long coverId) throws Exception {
AddOnManyToMany.removeLink(Album.class, id, "cover", coverId);
return Response.ok(DataAccess.get(Album.class, id)).build();
@Operation(description = "Remove a cover on a specific album")
public Album removeCover(@PathParam("id") final Long id, @PathParam("coverId") final UUID coverId) throws Exception {
AddOnDataJson.removeLink(Album.class, id, "covers", coverId);
return DataAccess.get(Album.class, id);
}
}

View File

@@ -2,13 +2,18 @@ package org.kar.karusic.api;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.AsyncType;
import org.kar.archidata.annotation.TypeScriptProgress;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.dataAccess.addOn.AddOnDataJson;
import org.kar.archidata.tools.DataTools;
import org.kar.karusic.model.Artist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
@@ -25,58 +30,61 @@ import jakarta.ws.rs.core.Response;
@Path("/artist")
@Produces({ MediaType.APPLICATION_JSON })
public class ArtistResource {
private static final Logger LOGGER = LoggerFactory.getLogger(ArtistResource.class);
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Artist getWithId(@PathParam("id") final Long id) throws Exception {
public static Artist get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Artist.class, id);
}
@GET
@RolesAllowed("USER")
public List<Artist> get() throws Exception {
public List<Artist> gets() throws Exception {
return DataAccess.gets(Artist.class);
}
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Artist put(final String jsonRequest) throws Exception {
public Artist post(@AsyncType(Artist.class) final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Artist.class, jsonRequest);
}
@PATCH
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Artist put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
public Artist patch(@PathParam("id") final Long id, @AsyncType(Artist.class) final String jsonRequest) throws Exception {
DataAccess.updateWithJson(Artist.class, id, jsonRequest);
return DataAccess.get(Artist.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") final Long id) throws Exception {
public void remove(@PathParam("id") final Long id) throws Exception {
DataAccess.delete(Artist.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_cover")
@Path("{id}/cover")
@RolesAllowed("ADMIN")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@AsyncType(Artist.class)
@TypeScriptProgress
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
return DataTools.uploadCover(Artist.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@DELETE
@Path("{id}/cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") final Long id, @PathParam("coverId") final Long coverId) throws Exception {
AddOnManyToMany.removeLink(Artist.class, id, "cover", coverId);
return Response.ok(DataAccess.get(Artist.class, id)).build();
public Artist removeCover(@PathParam("id") final Long id, @PathParam("coverId") final UUID coverId) throws Exception {
LOGGER.error("klmlmkmlkmlklmklmk");
AddOnDataJson.removeLink(Artist.class, id, "covers", coverId);
return DataAccess.get(Artist.class, id);
}
}

View File

@@ -2,13 +2,18 @@ package org.kar.karusic.api;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.AsyncType;
import org.kar.archidata.annotation.TypeScriptProgress;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.dataAccess.addOn.AddOnDataJson;
import org.kar.archidata.tools.DataTools;
import org.kar.karusic.model.Gender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
@@ -25,58 +30,60 @@ import jakarta.ws.rs.core.Response;
@Path("/gender")
@Produces({ MediaType.APPLICATION_JSON })
public class GenderResource {
private static final Logger LOGGER = LoggerFactory.getLogger(GenderResource.class);
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Gender getWithId(@PathParam("id") final Long id) throws Exception {
public static Gender get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Gender.class, id);
}
@GET
@RolesAllowed("USER")
public List<Gender> get() throws Exception {
public List<Gender> gets() throws Exception {
return DataAccess.gets(Gender.class);
}
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Gender put(final String jsonRequest) throws Exception {
public Gender post(@AsyncType(Gender.class) final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Gender.class, jsonRequest);
}
@PATCH
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Gender put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
public Gender patch(@PathParam("id") final Long id, @AsyncType(Gender.class) final String jsonRequest) throws Exception {
DataAccess.updateWithJson(Gender.class, id, jsonRequest);
return DataAccess.get(Gender.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") final Long id) throws Exception {
public void remove(@PathParam("id") final Long id) throws Exception {
DataAccess.delete(Gender.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_cover")
@Path("{id}/cover")
@RolesAllowed("ADMIN")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@AsyncType(Gender.class)
@TypeScriptProgress
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
return DataTools.uploadCover(Gender.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@DELETE
@Path("{id}/cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") final Long id, @PathParam("coverId") final Long coverId) throws Exception {
AddOnManyToMany.removeLink(Gender.class, id, "cover", coverId);
return Response.ok(DataAccess.get(Gender.class, id)).build();
public Gender removeCover(@PathParam("id") final Long id, @PathParam("coverId") final UUID coverId) throws Exception {
AddOnDataJson.removeLink(Gender.class, id, "covers", coverId);
return DataAccess.get(Gender.class, id);
}
}

View File

@@ -2,13 +2,18 @@ package org.kar.karusic.api;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.AsyncType;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.addOn.AddOnDataJson;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.tools.DataTools;
import org.kar.karusic.model.Playlist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
@@ -25,75 +30,76 @@ import jakarta.ws.rs.core.Response;
@Path("/playlist")
@Produces({ MediaType.APPLICATION_JSON })
public class PlaylistResource {
private static final Logger LOGGER = LoggerFactory.getLogger(PlaylistResource.class);
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Playlist getWithId(@PathParam("id") final Long id) throws Exception {
public static Playlist get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Playlist.class, id);
}
@GET
@RolesAllowed("USER")
public List<Playlist> get() throws Exception {
public List<Playlist> gets() throws Exception {
return DataAccess.gets(Playlist.class);
}
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Playlist put(final String jsonRequest) throws Exception {
public Playlist post(@AsyncType(Playlist.class) final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Playlist.class, jsonRequest);
}
@PATCH
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Playlist put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
public Playlist patch(@PathParam("id") final Long id, @AsyncType(Playlist.class) final String jsonRequest) throws Exception {
DataAccess.updateWithJson(Playlist.class, id, jsonRequest);
return DataAccess.get(Playlist.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") final Long id) throws Exception {
public void remove(@PathParam("id") final Long id) throws Exception {
DataAccess.delete(Playlist.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_track/{trackId}")
@Path("{id}/track/{trackId}")
@RolesAllowed("ADMIN")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public Playlist addTrack(@PathParam("id") final Long id, @PathParam("trackId") final Long trackId) throws Exception {
AddOnManyToMany.removeLink(Playlist.class, id, "track", trackId);
return DataAccess.get(Playlist.class, id);
}
@GET
@Path("{id}/rm_track/{trackId}")
@DELETE
@Path("{id}/track/{trackId}")
@RolesAllowed("ADMIN")
public Playlist removeTrack(@PathParam("id") final Long id, @PathParam("trackId") final Long trackId) throws Exception {
AddOnManyToMany.removeLink(Playlist.class, id, "track", trackId);
return DataAccess.get(Playlist.class, id);
}
@POST
@Path("{id}/add_cover")
@Path("{id}/cover")
@RolesAllowed("ADMIN")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@AsyncType(Playlist.class)
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
return DataTools.uploadCover(Playlist.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@DELETE
@Path("{id}/cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") final Long id, @PathParam("coverId") final Long coverId) throws Exception {
AddOnManyToMany.removeLink(Playlist.class, id, "cover", coverId);
return Response.ok(DataAccess.get(Playlist.class, id)).build();
public Playlist removeCover(@PathParam("id") final Long id, @PathParam("coverId") final UUID coverId) throws Exception {
AddOnDataJson.removeLink(Playlist.class, id, "covers", coverId);
return DataAccess.get(Playlist.class, id);
}
}

View File

@@ -5,11 +5,15 @@ import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
import org.kar.archidata.annotation.AsyncType;
import org.kar.archidata.annotation.TypeScriptProgress;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.QueryCondition;
import org.kar.archidata.dataAccess.addOn.AddOnDataJson;
import org.kar.archidata.dataAccess.addOn.AddOnManyToMany;
import org.kar.archidata.dataAccess.options.Condition;
import org.kar.archidata.model.Data;
@@ -18,6 +22,8 @@ import org.kar.karusic.model.Album;
import org.kar.karusic.model.Artist;
import org.kar.karusic.model.Gender;
import org.kar.karusic.model.Track;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.Consumes;
@@ -34,86 +40,99 @@ import jakarta.ws.rs.core.Response;
@Path("/track")
@Produces({ MediaType.APPLICATION_JSON })
public class TrackResource {
private static final Logger LOGGER = LoggerFactory.getLogger(TrackResource.class);
@GET
@Path("{id}")
@RolesAllowed("USER")
public static Track getWithId(@PathParam("id") final Long id) throws Exception {
public static Track get(@PathParam("id") final Long id) throws Exception {
return DataAccess.get(Track.class, id);
}
@GET
@RolesAllowed("USER")
public List<Track> get() throws Exception {
public List<Track> gets() throws Exception {
return DataAccess.gets(Track.class);
}
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Track create(final String jsonRequest) throws Exception {
public Track post(@AsyncType(Track.class) final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Track.class, jsonRequest);
}
@PATCH
@Path("{id}")
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Track put(@PathParam("id") final Long id, final String jsonRequest) throws Exception {
public Track patch(@PathParam("id") final Long id, @AsyncType(Track.class) final String jsonRequest) throws Exception {
DataAccess.updateWithJson(Track.class, id, jsonRequest);
return DataAccess.get(Track.class, id);
}
@DELETE
@Path("{id}")
@RolesAllowed("ADMIN")
public Response delete(@PathParam("id") final Long id) throws Exception {
public void remove(@PathParam("id") final Long id) throws Exception {
DataAccess.delete(Track.class, id);
return Response.ok().build();
}
@POST
@Path("{id}/add_artist/{artistId}")
@Path("{id}/artist/{artistId}")
@RolesAllowed("ADMIN")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public Track addTrack(@PathParam("id") final Long id, @PathParam("artistId") final Long artistId) throws Exception {
AddOnManyToMany.removeLink(Track.class, id, "artist", artistId);
return DataAccess.get(Track.class, id);
}
@GET
@Path("{id}/rm_artist/{trackId}")
@DELETE
@Path("{id}/artist/{trackId}")
@RolesAllowed("ADMIN")
public Track removeTrack(@PathParam("id") final Long id, @PathParam("artistId") final Long artistId) throws Exception {
AddOnManyToMany.removeLink(Track.class, id, "artist", artistId);
return DataAccess.get(Track.class, id);
}
@POST
@Path("{id}/add_cover")
@Path("{id}/cover")
@RolesAllowed("ADMIN")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
@AsyncType(Track.class)
@TypeScriptProgress
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
return DataTools.uploadCover(Track.class, id, fileName, fileInputStream, fileMetaData);
}
@GET
@Path("{id}/rm_cover/{coverId}")
@DELETE
@Path("{id}/cover/{coverId}")
@RolesAllowed("ADMIN")
public Response removeCover(@PathParam("id") final Long id, @PathParam("coverId") final Long coverId) throws Exception {
AddOnManyToMany.removeLink(Track.class, id, "cover", coverId);
return Response.ok(DataAccess.get(Track.class, id)).build();
public Track removeCover(@PathParam("id") final Long id, @PathParam("coverId") final UUID coverId) throws Exception {
AddOnDataJson.removeLink(Track.class, id, "covers", coverId);
return DataAccess.get(Track.class, id);
}
@POST
@Path("/upload/")
@Path("upload/")
@RolesAllowed("ADMIN")
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public Response uploadFile(@FormDataParam("fileName") String fileName, @FormDataParam("gender") String gender, @FormDataParam("artist") String artist,
// Formatter:off
@AsyncType(Track.class)
@TypeScriptProgress
public Response uploadTrack(
@FormDataParam("fileName") String fileName, //
@FormDataParam("gender") String gender, //
@FormDataParam("artist") String artist, //
//@FormDataParam("seriesId") String seriesId, Not used ...
@FormDataParam("album") String album, @FormDataParam("trackId") String trackId, @FormDataParam("title") String title, @FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition fileMetaData) {
@FormDataParam("album") String album, //
@AsyncType(Long.class) @FormDataParam("trackId") String trackId, //
@FormDataParam("title") String title, //
@FormDataParam("file") final InputStream fileInputStream, //
@FormDataParam("file") final FormDataContentDisposition fileMetaData //
) {
// Formatter:on
try {
// correct input string stream :
fileName = DataTools.multipartCorrection(fileName);
@@ -122,18 +141,17 @@ public class TrackResource {
album = DataTools.multipartCorrection(album);
trackId = DataTools.multipartCorrection(trackId);
title = DataTools.multipartCorrection(title);
//public NodeSmall uploadFile(final FormDataMultiPart form) {
System.out.println("Upload media file: " + fileMetaData);
System.out.println(" - fileName: " + fileName);
System.out.println(" - gender: " + gender);
System.out.println(" - artist: " + artist);
System.out.println(" - album: " + album);
System.out.println(" - trackId: " + trackId);
System.out.println(" - title: " + title);
System.out.println(" - fileInputStream: " + fileInputStream);
System.out.println(" - fileMetaData: " + fileMetaData);
System.out.flush();
LOGGER.info("Upload media file: " + fileMetaData);
LOGGER.info(" > fileName: " + fileName);
LOGGER.info(" > gender: " + gender);
LOGGER.info(" > artist: " + artist);
LOGGER.info(" > album: " + album);
LOGGER.info(" > trackId: " + trackId);
LOGGER.info(" > title: " + title);
LOGGER.info(" > fileInputStream: " + fileInputStream);
LOGGER.info(" > fileMetaData: " + fileMetaData);
/*
if (typeId == null) {
return Response.status(406).
@@ -141,14 +159,14 @@ public class TrackResource {
type("text/plain").
build();
}
*/
*/
final long tmpUID = DataTools.getTmpDataId();
final String sha512 = DataTools.saveTemporaryFile(fileInputStream, tmpUID);
Data data = DataTools.getWithSha512(sha512);
if (data == null) {
System.out.println("Need to add the data in the BDD ... ");
System.out.flush();
LOGGER.info("Need to add the data in the BDD ... ");
try {
data = DataTools.createNewData(tmpUID, fileName, sha512);
} catch (final IOException ex) {
@@ -161,16 +179,14 @@ public class TrackResource {
return Response.notModified("Error in SQL insertion ...").build();
}
} else if (data.deleted) {
System.out.println("Data already exist but deleted");
System.out.flush();
LOGGER.info("Data already exist but deleted");
DataTools.undelete(data.id);
data.deleted = false;
} else {
System.out.println("Data already exist ... all good");
System.out.flush();
LOGGER.info("Data already exist ... all good");
}
// Fist step: retrieve all the Id of each parents:...
System.out.println("Find typeNode");
LOGGER.info("Find typeNode");
Gender genderElem = null;
if (gender != null) {
genderElem = DataAccess.getWhere(Gender.class, new Condition(new QueryCondition("name", "=", gender)));
@@ -185,19 +201,21 @@ public class TrackResource {
// DataTools.removeTemporaryFile(tmpUID);
// return Response.notModified("TypeId does not exist ...").build();
// }
System.out.println(" ==> " + genderElem);
LOGGER.info(" ==> genderElem={}", genderElem);
Artist artistElem = null;
if (artist != null) {
LOGGER.info(" Try to find Artist: '{}'", artist);
artistElem = DataAccess.getWhere(Artist.class, new Condition(new QueryCondition("name", "=", artist)));
if (artistElem == null) {
LOGGER.info(" ** Create a new one...");
artistElem = new Artist();
artistElem.name = artist;
artistElem = DataAccess.insert(artistElem);
}
}
System.out.println(" ==> " + artistElem);
LOGGER.info(" ==> artistElem={}", artistElem);
Album albumElem = null;
if (album != null) {
albumElem = DataAccess.getWhere(Album.class, new Condition(new QueryCondition("name", "=", album)));
@@ -207,17 +225,17 @@ public class TrackResource {
albumElem = DataAccess.insert(albumElem);
}
}
System.out.println(" ==> " + album);
System.out.println("add media");
LOGGER.info(" ==> " + album);
LOGGER.info("add media");
Track trackElem = new Track();
trackElem.name = title;
trackElem.track = trackId != null ? Long.parseLong(trackId) : null;
trackElem.albumId = albumElem != null ? albumElem.id : null;
trackElem.genderId = genderElem != null ? genderElem.id : null;
trackElem.dataId = data.id;
// Now list of artis has an internal management:
// Now list of artist has an internal management:
if (artistElem != null) {
trackElem.artists = new ArrayList<>();
trackElem.artists.add(artistElem.id);
@@ -228,13 +246,13 @@ public class TrackResource {
if (artistElem != null) {
DataAccess.addLink(Track.class, trackElem.id, "artist", artistElem.id);
}
*/
*/
return Response.ok(trackElem).build();
} catch (final Exception ex) {
System.out.println("Catch an unexpected error ... " + ex.getMessage());
LOGGER.info("Catch an unexpected error ... {}", ex.getMessage());
ex.printStackTrace();
return Response.status(417).entity("Back-end error : " + ex.getMessage()).type("text/plain").build();
}
}
}

View File

@@ -22,27 +22,27 @@ import jakarta.ws.rs.core.SecurityContext;
@Path("/users")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class UserResource {
final Logger logger = LoggerFactory.getLogger(UserResource.class);
private static final Logger LOGGER = LoggerFactory.getLogger(UserResource.class);
@JsonInclude(JsonInclude.Include.NON_NULL)
public class UserOut {
public long id;
public String login;
public UserOut(final long id, final String login) {
this.id = id;
this.login = login;
}
}
public UserResource() {}
// curl http://localhost:9993/api/users
@GET
@RolesAllowed("ADMIN")
public List<UserKarusic> getUsers() {
System.out.println("getUsers");
public List<UserKarusic> gets() {
LOGGER.info("getUsers");
try {
return DataAccess.gets(UserKarusic.class);
} catch (final Exception e) {
@@ -51,17 +51,17 @@ public class UserResource {
}
return null;
}
// curl http://localhost:9993/api/users/3
@GET
@Path("{id}")
@RolesAllowed("ADMIN")
public UserKarusic getUsers(@Context final SecurityContext sc, @PathParam("id") final long userId) {
System.out.println("getUser " + userId);
public UserKarusic get(@Context final SecurityContext sc, @PathParam("id") final long userId) {
LOGGER.info("getUser {}", userId);
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
System.out.println("===================================================");
System.out.println("== USER ? " + gc.userByToken.name);
System.out.println("===================================================");
LOGGER.info("===================================================");
LOGGER.info("== USER {} ", gc.userByToken.name);
LOGGER.info("===================================================");
try {
return DataAccess.get(UserKarusic.class, userId);
} catch (final Exception e) {
@@ -70,14 +70,14 @@ public class UserResource {
}
return null;
}
@GET
@Path("me")
@RolesAllowed("USER")
public UserOut getMe(@Context final SecurityContext sc) {
this.logger.debug("getMe()");
LOGGER.debug("getMe()");
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
this.logger.debug("== USER ? {}", gc.userByToken);
LOGGER.debug("== USER ? {}", gc.userByToken);
return new UserOut(gc.userByToken.id, gc.userByToken.name);
}
}

View File

@@ -1,5 +1,7 @@
package org.kar.karusic.migration;
import java.util.List;
import org.kar.archidata.migration.MigrationSqlStep;
import org.kar.archidata.model.Data;
import org.kar.archidata.model.User;
@@ -10,28 +12,25 @@ import org.kar.karusic.model.Playlist;
import org.kar.karusic.model.Track;
public class Initialization extends MigrationSqlStep {
public static final int KARSO_INITIALISATION_ID = 1;
public static final List<Class<?>> CLASSES_BASE = List.of(Album.class,Artist.class,Data.class,Gender.class,Playlist.class,Track.class,User.class);
@Override
public String getName() {
return "Initialization";
}
public Initialization() {
}
@Override
public void generateStep() throws Exception {
addClass(Album.class);
addClass(Artist.class);
addClass(Data.class);
addClass(Gender.class);
addClass(Playlist.class);
addClass(Track.class);
addClass(User.class);
for (final Class<?> elem : CLASSES_BASE) {
addClass(elem);
}
addAction("""
INSERT INTO `gender` (`id`, `name`, `description`) VALUES
(1, 'Variété française', NULL),
@@ -68,9 +67,6 @@ public class Initialization extends MigrationSqlStep {
addAction("""
ALTER TABLE `artist` AUTO_INCREMENT = 1000;
""", "mysql");
addAction("""
ALTER TABLE `data` AUTO_INCREMENT = 1000;
""", "mysql");
addAction("""
ALTER TABLE `gender` AUTO_INCREMENT = 1000;
""", "mysql");
@@ -84,5 +80,5 @@ public class Initialization extends MigrationSqlStep {
ALTER TABLE `user` AUTO_INCREMENT = 1000;
""", "mysql");
}
}

View File

@@ -0,0 +1,26 @@
package org.kar.karusic.migration;
import org.kar.archidata.migration.MigrationSqlStep;
public class Migration20240225 extends MigrationSqlStep {
public static final int KARSO_INITIALISATION_ID = 1;
@Override
public String getName() {
return "migration-2024-02-25: change model of thrack to use real json";
}
public Migration20240225() {
}
@Override
public void generateStep() throws Exception {
// update migration update (last one)
addAction("""
UPDATE `track` SET artists = CONCAT('[', artists, ']') WHERE artists IS NOT NULL
""");
}
}

View File

@@ -0,0 +1,135 @@
package org.kar.karusic.migration;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.kar.archidata.api.DataResource;
import org.kar.archidata.dataAccess.DataAccess;
import org.kar.archidata.dataAccess.addOn.model.LinkTable;
import org.kar.archidata.dataAccess.options.AccessDeletedItems;
import org.kar.archidata.dataAccess.options.OverrideTableName;
import org.kar.archidata.migration.MigrationSqlStep;
import org.kar.archidata.tools.UuidUtils;
import org.kar.karusic.migration.model.CoverConversion;
import org.kar.karusic.migration.model.MediaConversion;
import org.kar.karusic.migration.model.UUIDConversion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Migration20240226 extends MigrationSqlStep {
private static final Logger LOGGER = LoggerFactory.getLogger(Migration20240226.class);
public static final int KARSO_INITIALISATION_ID = 1;
@Override
public String getName() {
return "migration-2024-02-26: convert base with UUID";
}
public Migration20240226() {
}
@Override
public void generateStep() throws Exception {
addAction("""
ALTER TABLE `data` ADD `uuid` binary(16) AFTER `id`;
""");
addAction(() -> {
final List<UUIDConversion> datas = DataAccess.gets(UUIDConversion.class, new AccessDeletedItems(), new OverrideTableName("data"));
for (final UUIDConversion elem: datas) {
elem.uuid = UuidUtils.nextUUID();
}
for (final UUIDConversion elem: datas) {
DataAccess.update(elem, elem.id, List.of("uuid"), new OverrideTableName("data"));
}
});
addAction("""
ALTER TABLE `data` CHANGE `uuid` `uuid` binary(16) DEFAULT (UUID_TO_BIN(UUID(), TRUE));
""");
final List<String> tableToTransform = List.of("album", "artist", "gender", "playlist", "track", "user");
for (final String tableName : tableToTransform ) {
addAction("ALTER TABLE `" + tableName + "` ADD `covers` text NULL;");
addAction(() -> {
final List<UUIDConversion> datas = DataAccess.gets(UUIDConversion.class, new AccessDeletedItems(), new OverrideTableName("data"));
final List<CoverConversion> medias = DataAccess.gets(CoverConversion.class, new AccessDeletedItems(), new OverrideTableName(tableName));
final List<LinkTable> links = DataAccess.gets(LinkTable.class, new OverrideTableName(tableName + "_link_cover"));
LOGGER.info("Get somes data: {} {} {}", datas.size(), medias.size(), links.size());
for (final CoverConversion media: medias) {
final List<UUID> values = new ArrayList<>();
for (final LinkTable link: links) {
if (link.object1Id.equals(media.id)) {
for (final UUIDConversion data: datas) {
if (data.id.equals(link.object2Id)) {
values.add(data.uuid);
break;
}
}
break;
}
}
if (values.size() != 0) {
media.covers = values;
LOGGER.info(" update: {} => {}", media.id, media.covers);
DataAccess.update(media, media.id, List.of("covers"), new OverrideTableName(tableName));
}
}
});
addAction("DROP TABLE `" + tableName + "_link_cover`;");
}
addAction("""
ALTER TABLE `track` ADD `dataUUID` binary(16) AFTER dataId;
""");
addAction(() -> {
final List<UUIDConversion> datas = DataAccess.gets(UUIDConversion.class, new AccessDeletedItems(), new OverrideTableName("data"));
final List<MediaConversion> medias = DataAccess.gets(MediaConversion.class, new AccessDeletedItems(), new OverrideTableName("track"));
for (final MediaConversion media: medias) {
for (final UUIDConversion data: datas) {
if (data.id.equals(media.dataId)) {
media.dataUUID = data.uuid;
DataAccess.update(media, media.id, List.of("dataUUID"), new OverrideTableName("track"));
break;
}
}
}
});
addAction("""
DROP TABLE `playlist`;
""");
addAction("""
DROP TABLE `playlist_link_track`;
""");
addAction("""
ALTER TABLE `track` DROP `dataId`;
""");
addAction("""
ALTER TABLE `track` CHANGE `dataUUID` `dataId` binary(16) NOT NULL;
""");
// Move the files...
addAction(() -> {
final List<UUIDConversion> datas = DataAccess.gets(UUIDConversion.class, new AccessDeletedItems(), new OverrideTableName("data"));
for (final UUIDConversion data: datas) {
final String origin = DataResource.getFileDataOld(data.id);
final String destination = DataResource.getFileData(data.uuid);
LOGGER.info("move file = {}", origin);
LOGGER.info(" ==> {}", destination);
Files.move(Paths.get(origin), Paths.get(destination), StandardCopyOption.ATOMIC_MOVE);
}
});
addAction("""
ALTER TABLE `data` DROP `id`;
""");
addAction("""
ALTER TABLE `data` CHANGE `uuid` `id` binary(16) DEFAULT (UUID_TO_BIN(UUID(), TRUE));
""");
addAction("""
ALTER TABLE `data` ADD PRIMARY KEY `id` (`id`);
""");
}
}

View File

@@ -0,0 +1,15 @@
package org.kar.karusic.migration.model;
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.DataJson;
import jakarta.persistence.Id;
public class CoverConversion {
@Id
public Long id = null;
@DataJson
public List<UUID> covers = null;
}

View File

@@ -0,0 +1,12 @@
package org.kar.karusic.migration.model;
import java.util.UUID;
import jakarta.persistence.Id;
public class MediaConversion {
@Id
public Long id = null;
public Long dataId = null;
public UUID dataUUID = null;
}

View File

@@ -0,0 +1,11 @@
package org.kar.karusic.migration.model;
import java.util.UUID;
import jakarta.persistence.Id;
public class UUIDConversion {
@Id
public Long id = null;
public UUID uuid = null;
}

View File

@@ -1,55 +0,0 @@
package org.kar.karusic.model;
/*
CREATE TABLE `data` (
`id` bigint NOT NULL COMMENT 'table ID' AUTO_INCREMENT PRIMARY KEY,
`deleted` BOOLEAN NOT NULL DEFAULT false,
`create_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been created',
`modify_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been update',
`sha512` varchar(129) COLLATE 'utf8_general_ci' NOT NULL,
`mime_type` varchar(128) COLLATE 'utf8_general_ci' NOT NULL,
`size` bigint,
`original_name` TEXT
) AUTO_INCREMENT=64;
*/
import java.sql.ResultSet;
import java.sql.SQLException;
public class DataSmall {
public Long id;
public String sha512;
public String mimeType;
public Long size;
public DataSmall() {
}
public DataSmall(ResultSet rs) {
int iii = 1;
try {
this.id = rs.getLong(iii++);
this.sha512 = rs.getString(iii++);
this.mimeType = rs.getString(iii++);
this.size = rs.getLong(iii++);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public String getTableSql() {
return """
DROP TABLE IF EXISTS `data`;
CREATE TABLE `data` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT 'table ID',
`deleted` tinyint(1) NOT NULL DEFAULT '0',
`create_date` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Time the element has been created',
`modify_date` timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT 'Time the element has been update',
`sha512` varchar(129) CHARACTER SET utf8mb3 COLLATE utf8_general_ci NOT NULL,
`mime_type` varchar(128) CHARACTER SET utf8mb3 COLLATE utf8_general_ci NOT NULL,
`size` bigint DEFAULT NULL,
`original_name` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
""";
}
}

View File

@@ -1,104 +0,0 @@
package org.kar.karusic.model;
/*
CREATE TABLE `node` (
`id` bigint NOT NULL COMMENT 'table ID' AUTO_INCREMENT PRIMARY KEY,
`deleted` BOOLEAN NOT NULL DEFAULT false,
`create_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been created',
`modify_date` datetime NOT NULL DEFAULT now() COMMENT 'Time the element has been update',
`type` enum("TYPE", "UNIVERSE", "SERIES", "SEASON") NOT NULL DEFAULT 'TYPE',
`name` TEXT COLLATE 'utf8_general_ci' NOT NULL,
`description` TEXT COLLATE 'utf8_general_ci',
`parent_id` bigint
) AUTO_INCREMENT=10;
*/
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MediaSmall {
public class MediaStreamProperty {
public Long id;
public Long timeSecond;
public Long width;
public Long height;
public Map<String, Long> videos = new HashMap<>();
public Map<String, Long> audios = new HashMap<>();
public Map<String, Long> subtitles = new HashMap<>();
}
public Long id;
public String name;
public String description;
public Long dataId;
public Long typeId;
public Long universeId;
public Long seriesId;
public Long seasonId;
public Integer episode;
public Integer date;
public Integer time;
public String ageLimit;
public List<Long> covers = null;
public MediaStreamProperty media;
public MediaSmall(ResultSet rs) {
int iii = 1;
try {
this.id = rs.getLong(iii++);
this.name = rs.getString(iii++);
this.description = rs.getString(iii++);
this.dataId = rs.getLong(iii++);
if (rs.wasNull()) {
this.dataId = null;
}
this.typeId = rs.getLong(iii++);
if (rs.wasNull()) {
this.typeId = null;
}
this.universeId = rs.getLong(iii++);
if (rs.wasNull()) {
this.universeId = null;
}
this.seriesId = rs.getLong(iii++);
if (rs.wasNull()) {
this.seriesId = null;
}
this.seasonId = rs.getLong(iii++);
if (rs.wasNull()) {
this.seasonId = null;
}
this.episode = rs.getInt(iii++);
if (rs.wasNull()) {
this.episode = null;
}
this.date = rs.getInt(iii++);
if (rs.wasNull()) {
this.date = null;
}
this.time = rs.getInt(iii++);
if (rs.wasNull()) {
this.time = null;
}
this.ageLimit = rs.getString(iii++);
String coversString = rs.getString(iii++);
if (!rs.wasNull()) {
covers = new ArrayList<>();
String[] elements = coversString.split("-");
for (String elem : elements) {
Long tmp = Long.parseLong(elem);
covers.add(tmp);
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}

View File

@@ -10,18 +10,19 @@ CREATE TABLE `node` (
`description` TEXT COLLATE 'utf8_general_ci',
`parent_id` bigint
) AUTO_INCREMENT=10;
*/
*/
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.DataJson;
import org.kar.archidata.model.Data;
import org.kar.archidata.model.GenericDataSoftDelete;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.persistence.Column;
import jakarta.persistence.FetchType;
import jakarta.persistence.ManyToMany;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class NodeSmall extends GenericDataSoftDelete {
@@ -29,6 +30,7 @@ public class NodeSmall extends GenericDataSoftDelete {
public String name = null;
@Column(length = 0)
public String description = null;
@ManyToMany(fetch = FetchType.LAZY, targetEntity = Data.class)
public List<Long> covers = null;
@Schema(description = "List of Id of the specific covers")
@DataJson(targetEntity = Data.class)
public List<UUID> covers = null;
}

View File

@@ -10,12 +10,13 @@ CREATE TABLE `node` (
`description` TEXT COLLATE 'utf8_general_ci',
`parent_id` bigint
) AUTO_INCREMENT=10;
*/
*/
import java.util.List;
import java.util.UUID;
import org.kar.archidata.annotation.DataIfNotExists;
import org.kar.archidata.annotation.addOn.SQLTableExternalForeinKeyAsList;
import org.kar.archidata.annotation.DataJson;
import com.fasterxml.jackson.annotation.JsonInclude;
@@ -29,12 +30,12 @@ public class Track extends NodeSmall {
public Long genderId = null;
public Long albumId = null;
public Long track = null;
public Long dataId = null;
public UUID dataId = null;
//@ManyToMany(fetch = FetchType.LAZY, targetEntity = Artist.class)
@SQLTableExternalForeinKeyAsList
@DataJson
@Column(length = 0)
public List<Long> artists = null;
@Override
public String toString() {
return "Track [id=" + this.id + ", deleted=" + this.deleted + ", createdAt=" + this.createdAt + ", updatedAt=" + this.updatedAt + ", name=" + this.name + ", description=" + this.description

View File

@@ -15,9 +15,7 @@ WORKDIR /application/
RUN npm install
ADD e2e /application/e2e
ADD tsconfig.json /application/
ADD tslint.json /application/
ADD angular.json /application/
ADD tsconfig.json tslint.json angular.json ./
ADD src /application/src
# generate build

View File

@@ -1,88 +1,117 @@
{
"$schema" : "./node_modules/@angular/cli/lib/config/schema.json",
"version" : 1,
"newProjectRoot" : "projects",
"defaultProject" : "karusic",
"projects" : {
"karusic" : {
"root" : "",
"sourceRoot" : "src",
"projectType" : "application",
"architect" : {
"build" : {
"builder" : "@angular-devkit/build-angular:browser",
"options" : {
"outputPath" : "dist",
"index" : "src/index.html",
"main" : "src/main.ts",
"tsConfig" : "src/tsconfig.app.json",
"polyfills" : "src/polyfills.ts",
"assets" : [ "src/assets", "src/favicon.ico" ],
"styles" : [ "src/styles.less", "src/generic_page.less", "src/theme.color.blue.less", "src/theme.checkbox.less", "src/theme.modal.less" ],
"scripts" : [ ]
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"karusic": {
"root": "",
"sourceRoot": "src",
"projectType": "application",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist",
"index": "src/index.html",
"main": "src/main.ts",
"tsConfig": "src/tsconfig.app.json",
"preserveSymlinks": true,
"polyfills": [
"zone.js"
],
"assets": [
"src/assets",
"src/favicon.ico"
],
"styles": [
"src/styles.less",
"src/generic_page.less",
"src/theme.color.blue.less",
"src/theme.checkbox.less",
"src/theme.modal.less"
],
"scripts": []
},
"configurations" : {
"production" : {
"optimization" : true,
"outputHashing" : "all",
"sourceMap" : false,
"namedChunks" : false,
"aot" : true,
"extractLicenses" : true,
"vendorChunk" : false,
"buildOptimizer" : true,
"fileReplacements" : [ {
"replace" : "src/environments/environment.ts",
"with" : "src/environments/environment.prod.ts"
} ]
"configurations": {
"production": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
]
},
"develop" : {
"optimization" : false,
"outputHashing" : "none",
"sourceMap" : true,
"namedChunks" : true,
"aot" : true,
"extractLicenses" : true,
"vendorChunk" : true,
"buildOptimizer" : false
"develop": {
"optimization": false,
"outputHashing": "none",
"namedChunks": true,
"aot": false,
"extractLicenses": true,
"vendorChunk": true,
"buildOptimizer": false,
"sourceMap": {
"scripts": true,
"styles": true,
"hidden": false,
"vendor": true
}
}
}
},
"serve" : {
"builder" : "@angular-devkit/build-angular:dev-server",
"options" : {
"browserTarget" : "karusic:build"
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"buildTarget": "karusic:build"
},
"configurations" : {
"production" : {
"browserTarget" : "karusic:build:production"
"configurations": {
"production": {
"buildTarget": "karusic:build:production"
},
"develop" : {
"browserTarget" : "karusic:build:develop"
"develop": {
"buildTarget": "karusic:build:develop"
}
}
},
"extract-i18n" : {
"builder" : "@angular-devkit/build-angular:extract-i18n",
"options" : {
"browserTarget" : "karusic:build"
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "karusic:build"
}
},
"test" : {
"builder" : "@angular-devkit/build-angular:karma",
"options" : {
"main" : "src/test.ts",
"karmaConfig" : "./karma.conf.js",
"polyfills" : "src/polyfills.ts",
"tsConfig" : "src/tsconfig.spec.json",
"scripts" : [ ],
"styles" : [ "src/styles.less", "src/generic_page.less", "src/theme.color.blue.less", "src/theme.checkbox.less", "src/theme.modal.less" ],
"assets" : [ "src/assets", "src/favicon.ico" ]
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"karmaConfig": "./karma.conf.js",
"polyfills": [
"zone.js"
],
"tsConfig": "src/tsconfig.spec.json",
"scripts": [],
"styles": [
"src/styles.less",
"src/generic_page.less",
"src/theme.color.blue.less",
"src/theme.checkbox.less",
"src/theme.modal.less"
],
"assets": [
"src/assets",
"src/favicon.ico"
]
}
},
"lint" : {
"builder" : "@angular-eslint/builder:lint",
"options" : {
"lint": {
"builder": "@angular-eslint/builder:lint",
"options": {
"fix": true,
"eslintConfig": ".eslintrc.js",
"lintFilePatterns": [
@@ -91,44 +120,53 @@
]
}
},
"TTTTTTlint" : {
"builder" : "@angular-devkit/build-angular:tslint",
"options" : {
"tsConfig" : [ "src/tsconfig.app.json", "src/tsconfig.spec.json" ],
"exclude" : [ "**/node_modules/**" ]
"TTTTTTlint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"src/tsconfig.app.json",
"src/tsconfig.spec.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
},
"karusic-e2e" : {
"root" : "e2e",
"sourceRoot" : "e2e",
"projectType" : "application",
"architect" : {
"e2e" : {
"builder" : "@angular-devkit/build-angular:protractor",
"options" : {
"protractorConfig" : "./protractor.conf.js",
"devServerTarget" : "karusic:serve"
"karusic-e2e": {
"root": "e2e",
"sourceRoot": "e2e",
"projectType": "application",
"architect": {
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "./protractor.conf.js",
"devServerTarget": "karusic:serve"
}
},
"lint" : {
"builder" : "@angular-devkit/build-angular:tslint",
"options" : {
"tsConfig" : [ "e2e/tsconfig.e2e.json" ],
"exclude" : [ "**/node_modules/**" ]
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": [
"e2e/tsconfig.e2e.json"
],
"exclude": [
"**/node_modules/**"
]
}
}
}
}
},
"schematics" : {
"@schematics/angular:component" : {
"prefix" : "app",
"style" : "less"
"schematics": {
"@schematics/angular:component": {
"prefix": "app",
"style": "less"
},
"@schematics/angular:directive" : {
"prefix" : "app"
"@schematics/angular:directive": {
"prefix": "app"
}
}
}

21733
front/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,40 +1,49 @@
{
"name": "karusic",
"version": "0.0.0",
"license": "MIT",
"license": "MPL-2",
"scripts": {
"all": "npm run build && npm run test",
"all": "npm run build && pnpm run test",
"ng": "ng",
"start": "ng serve --configuration=develop --watch --port 4203",
"dev": "ng serve --configuration=develop --watch --port 4203",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
"style": "prettier --write .",
"e2e": "ng e2e",
"update_packages": "ncu --upgrade",
"install_dependency": "pnpm install --force",
"link_kar_cw": "pnpm link ../../kar-cw/dist/kar-cw/",
"unlink_kar_cw": "pnpm unlink ../../kar-cw/dist/kar-cw/"
},
"private": true,
"dependencies": {
"@angular/animations": "^14.2.10",
"@angular/cdk": "^14.2.7",
"@angular/common": "^14.2.10",
"@angular/compiler": "^14.2.10",
"@angular/core": "^14.2.10",
"@angular/forms": "^14.2.10",
"@angular/material": "^14.2.7",
"@angular/platform-browser": "^14.2.10",
"@angular/platform-browser-dynamic": "^14.2.10",
"@angular/router": "^14.2.10",
"rxjs": "^7.5.7",
"zone.js": "^0.12.0"
"@angular/animations": "^17.3.4",
"@angular/cdk": "^17.3.4",
"@angular/common": "^17.3.4",
"@angular/compiler": "^17.3.4",
"@angular/core": "^17.3.4",
"@angular/forms": "^17.3.4",
"@angular/material": "^17.3.4",
"@angular/platform-browser": "^17.3.4",
"@angular/platform-browser-dynamic": "^17.3.4",
"@angular/router": "^17.3.4",
"rxjs": "^7.8.1",
"zone.js": "^0.14.4",
"zod": "3.22.4",
"@kangaroo-and-rabbit/kar-cw": "^0.2.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^14.2.9",
"@angular-eslint/builder": "14.2.0",
"@angular-eslint/eslint-plugin": "14.2.0",
"@angular-eslint/eslint-plugin-template": "14.2.0",
"@angular-eslint/schematics": "14.2.0",
"@angular-eslint/template-parser": "14.2.0",
"@angular/cli": "^14.2.9",
"@angular/compiler-cli": "^14.2.10",
"@angular/language-service": "^14.2.10"
"@angular-devkit/build-angular": "^17.3.4",
"@angular-eslint/builder": "17.3.0",
"@angular-eslint/eslint-plugin": "17.3.0",
"@angular-eslint/eslint-plugin-template": "17.3.0",
"@angular-eslint/schematics": "17.3.0",
"@angular-eslint/template-parser": "17.3.0",
"@angular/cli": "^17.3.4",
"@angular/compiler-cli": "^17.3.4",
"@angular/language-service": "^17.3.4",
"npm-check-updates": "^16.14.18",
"tslib": "^2.6.2"
}
}
}

9705
front/pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -6,12 +6,13 @@
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router'; // CLI imports router
import { ForbiddenScene, HomeOutScene, NotFound404Scene, SsoScene } from 'common/scene';
import { OnlyAdminGuard, OnlyUnregisteredGuardHome, OnlyUsersGuard, OnlyUsersGuardHome } from 'common/service';
import { HelpScene, HomeScene, AlbumEditScene, AlbumsScene, ArtistEditScene, ArtistScene, SettingsScene,
GenderScene, PlaylistScene, TrackEditScene, TrackScene, UploadScene, ArtistsScene, ArtistAlbumScene, AlbumScene } from './scene';
import {
HelpScene, HomeScene, AlbumEditScene, AlbumsScene, ArtistEditScene, ArtistScene, SettingsScene,
GenderScene, PlaylistScene, TrackEditScene, TrackScene, UploadScene, ArtistsScene, ArtistAlbumScene, AlbumScene
} from './scene';
import { ForbiddenScene, OnlyUsersGuardHome, HomeOutScene, OnlyUnregisteredGuardHome, SsoScene, OnlyAdminGuard, OnlyUsersGuard, NotFound404Scene } from '@kangaroo-and-rabbit/kar-cw';
// import { HelpComponent } from './help/help.component';
// see https://angular.io/guide/router
@@ -21,13 +22,13 @@ const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'forbidden', component: ForbiddenScene },
// ------------------------------------
// -- home global interface
// ------------------------------------
{
path: 'home',
component: HomeScene,
component: HomeScene,
canActivate: [OnlyUsersGuardHome], // this route to unregistered path when not logged ==> permit to simplify display
},
{
@@ -65,14 +66,14 @@ const routes: Routes = [
component: GenderScene,
canActivate: [OnlyUsersGuard],
},
// display all (artist | album | traks)
// display all (artist | album | tracks)
{
path: 'gender/:genderId',
component: GenderScene,
canActivate: [OnlyUsersGuard],
},
//{ path: 'gender-edit/:genderId', component: GenderEditScene },
//{ path: 'gender/:genderId', component: GenderScene },
//{ path: 'gender/:genderId/:artistId/:albumId/:trackId', component: GenderScene },
@@ -89,7 +90,7 @@ const routes: Routes = [
component: PlaylistScene,
canActivate: [OnlyUsersGuard],
},
//{ path: 'playlist-edit/:playlistId', component: PlaylistEditScene },
// ------------------------------------
@@ -107,16 +108,16 @@ const routes: Routes = [
component: ArtistScene,
canActivate: [OnlyUsersGuard],
},
{
path: 'artist/:artistId/edit',
component: ArtistEditScene,
canActivate: [OnlyAdminGuard],
},
{
path: 'artist/:artistId/:albumId',
component: ArtistAlbumScene,
canActivate: [OnlyUsersGuard],
},
{
path: 'artist-edit/:artistId',
component: ArtistEditScene,
canActivate: [OnlyAdminGuard],
},
// ------------------------------------
// -- Album:
@@ -127,30 +128,30 @@ const routes: Routes = [
component: AlbumsScene,
canActivate: [OnlyUsersGuard],
},
{
path: 'album/:albumId/edit',
component: AlbumEditScene,
canActivate: [OnlyAdminGuard],
},
{
path: 'album/:albumId',
component: AlbumScene,
canActivate: [OnlyUsersGuard],
},
{
path: 'album-edit/:albumId',
component: AlbumEditScene,
canActivate: [OnlyAdminGuard],
},
// ------------------------------------
// -- Tracks:
// ------------------------------------
{
path: 'track/:trackId/edit',
component: TrackEditScene,
canActivate: [OnlyAdminGuard],
},
{
path: 'track/:genderId/:artistId/:albumId/:trackId',
component: TrackScene,
canActivate: [OnlyUsersGuard],
},
{
path: 'track-edit/:trackId',
component: TrackEditScene,
canActivate: [OnlyAdminGuard],
},
// ------------------------------------
// -- setting:
@@ -164,7 +165,6 @@ const routes: Routes = [
path: '**',
component: NotFound404Scene,
},
];
@NgModule({
@@ -181,5 +181,4 @@ const routes: Routes = [
]
})
export class AppRoutingModule { }
// export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

View File

@@ -1,15 +1,17 @@
<!-- Generig global menu -->
<app-top-menu [menu]="currentMenu" (callback)="eventOnMenu($event)"></app-top-menu>
<!-- Generic global menu -->
<karcw-top-menu [menu]="currentMenu" (callback)="eventOnMenu($event)"/>
<!-- all interfaced pages -->
<div class="main-content" *ngIf="autoConnectedDone">
<div class="main-content">
@if(autoConnectedDone) {
<router-outlet ></router-outlet>
</div>
<div class="main-content" *ngIf="!autoConnectedDone">
}
@else {
<div class="generic-page">
<div class="fill-all colomn_mutiple">
<b style="color:red;">Auto-connection in progress</b>
<div class="clear"></div>
</div>
</div>
}
</div>
<app-element-player-audio></app-element-player-audio>

View File

@@ -5,12 +5,17 @@
*/
import { Component, OnInit } from '@angular/core';
import { EventOnMenu } from 'common/component/top-menu/top-menu';
import { MenuItem, MenuPosition } from 'common/model';
import { UserService, SessionService, SSOService } from 'common/service';
import { isNullOrUndefined } from 'common/utils';
import { ArianeService } from './service';
import { UserRoles222 } from 'common/service/session';
import {
MenuItem,
SSOService,
SessionService,
UserService,
UserRoles222,
EventOnMenu,
MenuPosition,
isNullOrUndefined,
} from '@kangaroo-and-rabbit/kar-cw';
enum MenuEventType {
SSO_LOGIN = "SSO_CALL_LOGIN",
@@ -40,11 +45,12 @@ export class AppComponent implements OnInit {
location: string = "home";
constructor(
private userService: UserService,
private sessionService: SessionService,
private ssoService: SSOService,
private arianeService: ArianeService) {
private arianeService: ArianeService,
private userService: UserService
) {
}
ngOnInit() {
@@ -53,7 +59,7 @@ export class AppComponent implements OnInit {
this.updateMainMenu();
let self = this;
this.sessionService.change.subscribe((isConnected) => {
console.log(`receive event from session ...${ isConnected}`);
console.log(`receive event from session ...${isConnected}`);
self.isConnected = isConnected;
self.autoConnectedDone = true;
self.updateMainMenu();
@@ -105,9 +111,8 @@ export class AppComponent implements OnInit {
}
eventOnMenu(data: EventOnMenu): void {
//console.log(`plopppppppppp ${JSON.stringify(this.route.snapshot.url)}`);
//console.log(`Get event on menu: ${JSON.stringify(data, null, 4)}`);
switch(data.menu.otherData) {
console.log(`Get event on menu: ${JSON.stringify(data, null, 4)}`);
switch (data.menu.otherData) {
case MenuEventType.SSO_LOGIN:
this.ssoService.requestSignIn();
break;
@@ -118,24 +123,24 @@ export class AppComponent implements OnInit {
this.ssoService.requestSignUp();
break;
case MenuEventType.SEGMENT:
if(this.arianeService.getCurrrentSegment() === "artist") {
if (this.arianeService.getCurrrentSegment() === "artist") {
this.arianeService.navigateArtist({});
} else if(this.arianeService.getCurrrentSegment() === "gender") {
} else if (this.arianeService.getCurrrentSegment() === "gender") {
this.arianeService.navigateGender({});
} else if(this.arianeService.getCurrrentSegment() === "playlist") {
} else if (this.arianeService.getCurrrentSegment() === "playlist") {
this.arianeService.navigatePlaylist({});
} else if(this.arianeService.getCurrrentSegment() === "track") {
} else if (this.arianeService.getCurrrentSegment() === "track") {
this.arianeService.navigateTrack({});
} else if(this.arianeService.getCurrrentSegment() === "album") {
} else if (this.arianeService.getCurrrentSegment() === "album") {
this.arianeService.navigateAlbum({});
}
break;
case MenuEventType.TYPE:
break;
case MenuEventType.ARTIST:
if(this.arianeService.getCurrrentSegment() === "artist") {
this.arianeService.navigateArtist({artistId: this.arianeService.getArtistId()});
if (this.arianeService.getCurrrentSegment() === "artist") {
this.arianeService.navigateArtist({ artistId: this.arianeService.getArtistId() });
}
break;
case MenuEventType.ALBUM:
@@ -145,15 +150,15 @@ export class AppComponent implements OnInit {
case MenuEventType.PLAYLIST:
break;
}
}
updateMainMenu(): void {
console.log("update main menu :");
if (this.isConnected) {
this.currentMenu = [
{
position: MenuPosition.LEFT,
hover: `You are logged as: ${this.sessionService.getLogin()}`,
hover: "lkjljlk", //`You are logged as: ${this.sessionService.getLogin()}`,
icon: "menu",
title: "Menu",
subMenu: [
@@ -201,13 +206,13 @@ export class AppComponent implements OnInit {
}, {
position: MenuPosition.LEFT,
icon: "queue_music",
title: this.arianeService.getPlaylistName(),
title: "true",//this.arianeService.getPlaylistName(),
otherData: MenuEventType.PLAYLIST,
callback: true,
enable: !isNullOrUndefined(this.arianeService.getPlaylistId()),
}
],
},{
}, {
position: MenuPosition.RIGHT,
image: "assets/images/avatar_generic.svg",
title: "",
@@ -257,7 +262,7 @@ export class AppComponent implements OnInit {
icon: "add_circle_outline",
title: "Sign-up",
callback: true,
model: this.signUpEnable?undefined:"disable",
model: this.signUpEnable ? undefined : "disable",
otherData: MenuEventType.SSO_SIGNUP,
}, {
position: MenuPosition.RIGHT,
@@ -287,7 +292,7 @@ export class AppComponent implements OnInit {
return "Tracks"
}
if (segment === "playlist") {
return "Playlistq"
return "Playlist"
}
return "";
}

View File

@@ -5,7 +5,7 @@
*/
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA } from '@angular/core';
import { CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA, NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
@@ -22,8 +22,13 @@ import {
} from './scene';
import { GenderService, DataService, PlaylistService, ArtistService, AlbumService, TrackService, ArianeService, PlayerService } from './service';
import { UploadScene } from './scene/upload/upload';
import { ElementSeriesComponent, ElementTrackComponent, ElementSeasonComponent, ElementVideoComponent, ElementPlayerAudioComponent } from './component';
import { common_module_declarations, common_module_imports, common_module_providers, common_module_exports } from 'common/module';
import { ElementSeriesComponent, ElementTrackComponent, ElementSeasonComponent, ElementVideoComponent, ElementPlayerAudioComponent, DescriptionAreaComponent } from './component';
import { KarCWModule } from '@kangaroo-and-rabbit/kar-cw';
import { environment } from 'environments/environment';
import { FormsModule, ReactiveFormsModule } from "@angular/forms";
import { CommonModule } from "@angular/common";
@NgModule({
declarations: [
@@ -35,8 +40,8 @@ import { common_module_declarations, common_module_imports, common_module_provid
ElementSeasonComponent,
ElementVideoComponent,
ElementPlayerAudioComponent,
DescriptionAreaComponent,
PopInCreateType,
HomeScene,
HelpScene,
GenderScene,
@@ -52,16 +57,21 @@ import { common_module_declarations, common_module_imports, common_module_provid
AlbumEditScene,
ArtistEditScene,
UploadScene,
...common_module_declarations,
],
imports: [
FormsModule,
ReactiveFormsModule,
CommonModule,
BrowserModule,
RouterModule,
AppRoutingModule,
HttpClientModule,
...common_module_imports,
KarCWModule,
],
providers: [
{ provide: 'ENVIRONMENT', useValue: environment },
ArianeService,
PlayerService,
GenderService,
DataService,
@@ -69,8 +79,6 @@ import { common_module_declarations, common_module_imports, common_module_provid
ArtistService,
AlbumService,
TrackService,
ArianeService,
...common_module_providers,
],
exports: [
AppComponent,
@@ -79,16 +87,10 @@ import { common_module_declarations, common_module_imports, common_module_provid
ElementSeasonComponent,
ElementVideoComponent,
PopInCreateType,
...common_module_exports,
],
bootstrap: [
AppComponent
],
/*
schemas: [
CUSTOM_ELEMENTS_SCHEMA,
NO_ERRORS_SCHEMA
]
*/
schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
})
export class AppModule { }

View File

@@ -0,0 +1,190 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray, RESTRequestVoid } from "./rest-tools"
import {UUID, Long, Album, isAlbum, } from "./model"
export namespace AlbumResource {
/**
* Remove a specific album
*/
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<void> {
return RESTRequestVoid({
restModel: {
endPoint: "/album/{id}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
});
};
/**
* Get a specific Album with his ID
*/
export function get({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Album> {
return RESTRequestJson({
restModel: {
endPoint: "/album/{id}",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isAlbum);
};
/**
* Update a specific album
*/
export function patch({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: Album,
}): Promise<Album> {
return RESTRequestJson({
restModel: {
endPoint: "/album/{id}",
requestType: HTTPRequestModel.PATCH,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isAlbum);
};
/**
* Add an album (when all the data already exist)
*/
export function post({ restConfig, data, }: {
restConfig: RESTConfig,
data: Album,
}): Promise<Album> {
return RESTRequestJson({
restModel: {
endPoint: "/album",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, isAlbum);
};
/**
* Get all the available Albums
*/
export function gets({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<Album[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/album",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isAlbum);
};
/**
* Add a Track on a specific album
*/
export function addTrack({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
trackId: Long,
id: Long,
},
}): Promise<Album> {
return RESTRequestJson({
restModel: {
endPoint: "/album/{id}/track/{trackId}",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isAlbum);
};
/**
* Remove a Track on a specific album
*/
export function removeTrack({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
trackId: Long,
id: Long,
},
}): Promise<Album> {
return RESTRequestJson({
restModel: {
endPoint: "/album/{id}/track/{trackId}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isAlbum);
};
/**
* Add a cover on a specific album
*/
export function uploadCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: File,
},
}): Promise<Album> {
return RESTRequestJson({
restModel: {
endPoint: "/album/{id}/cover",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isAlbum);
};
/**
* Remove a cover on a specific album
*/
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: UUID,
id: Long,
},
}): Promise<Album> {
return RESTRequestJson({
restModel: {
endPoint: "/album/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isAlbum);
};
}

View File

@@ -0,0 +1,127 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray, RESTRequestVoid } from "./rest-tools"
import {Artist, UUID, Long, isArtist, } from "./model"
export namespace ArtistResource {
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<void> {
return RESTRequestVoid({
restModel: {
endPoint: "/artist/{id}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
});
};
export function get({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Artist> {
return RESTRequestJson({
restModel: {
endPoint: "/artist/{id}",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isArtist);
};
export function patch({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: Artist,
}): Promise<Artist> {
return RESTRequestJson({
restModel: {
endPoint: "/artist/{id}",
requestType: HTTPRequestModel.PATCH,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isArtist);
};
export function post({ restConfig, data, }: {
restConfig: RESTConfig,
data: Artist,
}): Promise<Artist> {
return RESTRequestJson({
restModel: {
endPoint: "/artist",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, isArtist);
};
export function gets({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<Artist[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/artist",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isArtist);
};
export function uploadCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: File,
},
}): Promise<Artist> {
return RESTRequestJson({
restModel: {
endPoint: "/artist/{id}/cover",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isArtist);
};
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: UUID,
id: Long,
},
}): Promise<Artist> {
return RESTRequestJson({
restModel: {
endPoint: "/artist/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isArtist);
};
}

View File

@@ -0,0 +1,104 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray, RESTRequestVoid } from "./rest-tools"
import {UUID, } from "./model"
export namespace DataResource {
/**
* Insert a new data in the data environment
*/
export function uploadFile({ restConfig, data, }: {
restConfig: RESTConfig,
data: {
file: File,
},
}): Promise<void> {
return RESTRequestVoid({
restModel: {
endPoint: "/data//upload/",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
});
};
/**
* Get back some data from the data environment
*/
// TODO: unmanaged "Response" type: please specify @AsyncType or considered as 'void'.
export function retrieveDataId({ restConfig, queries, params, data, }: {
restConfig: RESTConfig,
queries: {
Authorization: string,
},
params: {
id: UUID,
},
data: string,
}): Promise<void> {
return RESTRequestVoid({
restModel: {
endPoint: "/data/{id}",
requestType: HTTPRequestModel.GET,
},
restConfig,
params,
queries,
data,
});
};
/**
* Get a thumbnail of from the data environment (if resize is possible)
*/
// TODO: unmanaged "Response" type: please specify @AsyncType or considered as 'void'.
export function retrieveDataThumbnailId({ restConfig, queries, params, data, }: {
restConfig: RESTConfig,
queries: {
Authorization: string,
},
params: {
id: UUID,
},
data: string,
}): Promise<void> {
return RESTRequestVoid({
restModel: {
endPoint: "/data/thumbnail/{id}",
requestType: HTTPRequestModel.GET,
},
restConfig,
params,
queries,
data,
});
};
/**
* Get back some data from the data environment (with a beautiful name (permit download with basic name)
*/
// TODO: unmanaged "Response" type: please specify @AsyncType or considered as 'void'.
export function retrieveDataFull({ restConfig, queries, params, data, }: {
restConfig: RESTConfig,
queries: {
Authorization: string,
},
params: {
name: string,
id: UUID,
},
data: string,
}): Promise<void> {
return RESTRequestVoid({
restModel: {
endPoint: "/data/{id}/{name}",
requestType: HTTPRequestModel.GET,
},
restConfig,
params,
queries,
data,
});
};
}

View File

@@ -0,0 +1,8 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray, RESTRequestVoid } from "./rest-tools"
import {} from "./model"
export namespace Front {
}

View File

@@ -0,0 +1,127 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray, RESTRequestVoid } from "./rest-tools"
import {UUID, Long, Gender, isGender, } from "./model"
export namespace GenderResource {
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<void> {
return RESTRequestVoid({
restModel: {
endPoint: "/gender/{id}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
});
};
export function get({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Gender> {
return RESTRequestJson({
restModel: {
endPoint: "/gender/{id}",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isGender);
};
export function patch({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: Gender,
}): Promise<Gender> {
return RESTRequestJson({
restModel: {
endPoint: "/gender/{id}",
requestType: HTTPRequestModel.PATCH,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isGender);
};
export function post({ restConfig, data, }: {
restConfig: RESTConfig,
data: Gender,
}): Promise<Gender> {
return RESTRequestJson({
restModel: {
endPoint: "/gender",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, isGender);
};
export function gets({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<Gender[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/gender",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isGender);
};
export function uploadCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: File,
},
}): Promise<Gender> {
return RESTRequestJson({
restModel: {
endPoint: "/gender/{id}/cover",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isGender);
};
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: UUID,
id: Long,
},
}): Promise<Gender> {
return RESTRequestJson({
restModel: {
endPoint: "/gender/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isGender);
};
}

View File

@@ -0,0 +1,20 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray, RESTRequestVoid } from "./rest-tools"
import {HealthResult, isHealthResult, } from "./model"
export namespace HealthCheck {
export function getHealth({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<HealthResult> {
return RESTRequestJson({
restModel: {
endPoint: "/health_check",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isHealthResult);
};
}

View File

@@ -0,0 +1,13 @@
/**
* Global import of the package
*/
export * from "./model";
export * from "./album-resource";
export * from "./artist-resource";
export * from "./front";
export * from "./gender-resource";
export * from "./health-check";
export * from "./playlist-resource";
export * from "./user-resource";
export * from "./track-resource";
export * from "./data-resource";

View File

@@ -0,0 +1,407 @@
/**
* Interface of the server (auto-generated code)
*/
import { z as zod } from "zod";
export const ZodUUID = zod.string().uuid();
export type UUID = zod.infer<typeof ZodUUID>;
export function isUUID(data: any): data is UUID {
try {
ZodUUID.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodLong = zod.number();
export type Long = zod.infer<typeof ZodLong>;
export function isLong(data: any): data is Long {
try {
ZodLong.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodInteger = zod.number().safe();
export type Integer = zod.infer<typeof ZodInteger>;
export function isInteger(data: any): data is Integer {
try {
ZodInteger.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodFloat = zod.number();
export type Float = zod.infer<typeof ZodFloat>;
export function isFloat(data: any): data is Float {
try {
ZodFloat.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodInstant = zod.string();
export type Instant = zod.infer<typeof ZodInstant>;
export function isInstant(data: any): data is Instant {
try {
ZodInstant.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodDate = zod.date();
export type Date = zod.infer<typeof ZodDate>;
export function isDate(data: any): data is Date {
try {
ZodDate.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodTimestamp = zod.date();
export type Timestamp = zod.infer<typeof ZodTimestamp>;
export function isTimestamp(data: any): data is Timestamp {
try {
ZodTimestamp.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodLocalDate = zod.date();
export type LocalDate = zod.infer<typeof ZodLocalDate>;
export function isLocalDate(data: any): data is LocalDate {
try {
ZodLocalDate.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodLocalTime = zod.date();
export type LocalTime = zod.infer<typeof ZodLocalTime>;
export function isLocalTime(data: any): data is LocalTime {
try {
ZodLocalTime.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodRestErrorResponse = zod.object({
uuid: ZodUUID.optional(),
time: zod.string().max(255).optional(),
error: zod.string().max(255).optional(),
message: zod.string().max(255).optional(),
status: ZodInteger,
statusMessage: zod.string().max(255).optional()
});
export type RestErrorResponse = zod.infer<typeof ZodRestErrorResponse>;
export function isRestErrorResponse(data: any): data is RestErrorResponse {
try {
ZodRestErrorResponse.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodGenericTiming = zod.object({
// Create time of the object
createdAt: ZodDate.readonly().optional(),
// When update the object
updatedAt: ZodDate.readonly().optional()
});
export type GenericTiming = zod.infer<typeof ZodGenericTiming>;
export function isGenericTiming(data: any): data is GenericTiming {
try {
ZodGenericTiming.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodGenericData = ZodGenericTiming.extend({
// Unique Id of the object
id: ZodLong.readonly().optional()
});
export type GenericData = zod.infer<typeof ZodGenericData>;
export function isGenericData(data: any): data is GenericData {
try {
ZodGenericData.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodGenericDataSoftDelete = ZodGenericData.extend({
// Deleted state
deleted: zod.boolean().readonly().optional()
});
export type GenericDataSoftDelete = zod.infer<typeof ZodGenericDataSoftDelete>;
export function isGenericDataSoftDelete(data: any): data is GenericDataSoftDelete {
try {
ZodGenericDataSoftDelete.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodNodeSmall = ZodGenericDataSoftDelete.extend({
name: zod.string().max(256).optional(),
description: zod.string().optional(),
// List of Id of the specific covers
covers: zod.array(ZodUUID).optional()
});
export type NodeSmall = zod.infer<typeof ZodNodeSmall>;
export function isNodeSmall(data: any): data is NodeSmall {
try {
ZodNodeSmall.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodAlbum = ZodNodeSmall.extend({
publication: ZodLocalDate.optional()
});
export type Album = zod.infer<typeof ZodAlbum>;
export function isAlbum(data: any): data is Album {
try {
ZodAlbum.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodArtist = ZodNodeSmall.extend({
firstName: zod.string().max(256).optional(),
surname: zod.string().max(256).optional(),
birth: ZodLocalDate.optional(),
death: ZodLocalDate.optional()
});
export type Artist = zod.infer<typeof ZodArtist>;
export function isArtist(data: any): data is Artist {
try {
ZodArtist.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodGender = ZodNodeSmall.extend({
});
export type Gender = zod.infer<typeof ZodGender>;
export function isGender(data: any): data is Gender {
try {
ZodGender.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodHealthResult = zod.object({
});
export type HealthResult = zod.infer<typeof ZodHealthResult>;
export function isHealthResult(data: any): data is HealthResult {
try {
ZodHealthResult.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodPlaylist = ZodNodeSmall.extend({
tracks: zod.array(ZodLong).optional()
});
export type Playlist = zod.infer<typeof ZodPlaylist>;
export function isPlaylist(data: any): data is Playlist {
try {
ZodPlaylist.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodUser = ZodGenericDataSoftDelete.extend({
login: zod.string().max(128).optional(),
lastConnection: ZodTimestamp.optional(),
admin: zod.boolean(),
blocked: zod.boolean(),
removed: zod.boolean(),
covers: zod.array(ZodLong).optional()
});
export type User = zod.infer<typeof ZodUser>;
export function isUser(data: any): data is User {
try {
ZodUser.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodUserKarusic = ZodUser.extend({
});
export type UserKarusic = zod.infer<typeof ZodUserKarusic>;
export function isUserKarusic(data: any): data is UserKarusic {
try {
ZodUserKarusic.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodUserOut = zod.object({
id: ZodLong,
login: zod.string().max(255).optional()
});
export type UserOut = zod.infer<typeof ZodUserOut>;
export function isUserOut(data: any): data is UserOut {
try {
ZodUserOut.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodTrack = ZodNodeSmall.extend({
genderId: ZodLong.optional(),
albumId: ZodLong.optional(),
track: ZodLong.optional(),
dataId: ZodUUID.optional(),
artists: zod.array(ZodLong).optional()
});
export type Track = zod.infer<typeof ZodTrack>;
export function isTrack(data: any): data is Track {
try {
ZodTrack.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodUUIDGenericData = ZodGenericTiming.extend({
// Unique UUID of the object
id: ZodUUID.readonly().optional()
});
export type UUIDGenericData = zod.infer<typeof ZodUUIDGenericData>;
export function isUUIDGenericData(data: any): data is UUIDGenericData {
try {
ZodUUIDGenericData.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodUUIDGenericDataSoftDelete = ZodUUIDGenericData.extend({
// Deleted state
deleted: zod.boolean().readonly().optional()
});
export type UUIDGenericDataSoftDelete = zod.infer<typeof ZodUUIDGenericDataSoftDelete>;
export function isUUIDGenericDataSoftDelete(data: any): data is UUIDGenericDataSoftDelete {
try {
ZodUUIDGenericDataSoftDelete.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodData = ZodUUIDGenericDataSoftDelete.extend({
// Sha512 of the data
sha512: zod.string().max(128).optional(),
// Mime -type of the media
mimeType: zod.string().max(128).optional(),
// Size in Byte of the data
size: ZodLong.optional()
});
export type Data = zod.infer<typeof ZodData>;
export function isData(data: any): data is Data {
try {
ZodData.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}

View File

@@ -0,0 +1,163 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray, RESTRequestVoid } from "./rest-tools"
import {UUID, Long, Playlist, isPlaylist, } from "./model"
export namespace PlaylistResource {
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<void> {
return RESTRequestVoid({
restModel: {
endPoint: "/playlist/{id}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
});
};
export function get({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Playlist> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isPlaylist);
};
export function patch({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: Playlist,
}): Promise<Playlist> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}",
requestType: HTTPRequestModel.PATCH,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isPlaylist);
};
export function post({ restConfig, data, }: {
restConfig: RESTConfig,
data: Playlist,
}): Promise<Playlist> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, isPlaylist);
};
export function gets({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<Playlist[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/playlist",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isPlaylist);
};
export function addTrack({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
trackId: Long,
id: Long,
},
}): Promise<Playlist> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}/track/{trackId}",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isPlaylist);
};
export function removeTrack({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
trackId: Long,
id: Long,
},
}): Promise<Playlist> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}/track/{trackId}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isPlaylist);
};
export function uploadCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: File,
},
}): Promise<Playlist> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}/cover",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isPlaylist);
};
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: UUID,
id: Long,
},
}): Promise<Playlist> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isPlaylist);
};
}

View File

@@ -0,0 +1,246 @@
/** @file
* @author Edouard DUPIN
* @copyright 2024, Edouard DUPIN, all right reserved
* @license MPL-2
*/
import { RestErrorResponse } from "./model"
export enum HTTPRequestModel {
DELETE = 'DELETE',
GET = 'GET',
PATCH = 'PATCH',
POST = 'POST',
PUT = 'PUT',
}
export enum HTTPMimeType {
ALL = '*/*',
CSV = 'text/csv',
IMAGE = 'image/*',
IMAGE_JPEG = 'image/jpeg',
IMAGE_PNG = 'image/png',
JSON = 'application/json',
MULTIPART = 'multipart/form-data',
OCTET_STREAM = 'application/octet-stream',
TEXT_PLAIN = 'text/plain',
}
export interface RESTConfig {
// base of the server: http(s)://my.server.org/plop/api/
server: string;
// Token to access of the data.
token?: string;
}
export interface RESTModel {
// base of the local API request: "sheep/{id}".
endPoint: string;
// Type of the request.
requestType?: HTTPRequestModel;
// Input type requested.
accept?: HTTPMimeType;
// Content of the local data.
contentType?: HTTPMimeType;
// Mode of the TOKEN in urk or Header
tokenInUrl?: boolean;
}
export interface ModelResponseHttp {
status: number;
data: any;
}
export function isArrayOf<TYPE>(
data: any,
typeChecker: (subData: any) => subData is TYPE,
length?: number
): data is TYPE[] {
if (!Array.isArray(data)) {
return false;
}
if (!data.every(typeChecker)) {
return false;
}
if (length !== undefined && data.length != length) {
return false;
}
return true;
}
export type RESTRequestType = {
restModel: RESTModel,
restConfig: RESTConfig,
data?: any,
params?: object,
queries?: object,
};
function removeTrailingSlashes(input: string): string {
return input.replace(/\/+$/, '');
}
function removeLeadingSlashes(input: string): string {
return input.replace(/^\/+/, '');
}
export function RESTUrl({ restModel, restConfig, data, params, queries }: RESTRequestType): string {
// Create the URL PATH:
let generateUrl = `${removeTrailingSlashes(restConfig.server)}/${removeLeadingSlashes(restModel.endPoint)}`;
if (params !== undefined) {
for (let key of Object.keys(params)) {
generateUrl = generateUrl.replaceAll(`{${key}}`, `${params[key]}`);
}
}
if (queries === undefined && (restConfig.token === undefined || restModel.tokenInUrl !== true)) {
return generateUrl;
}
const searchParams = new URLSearchParams();
if (queries !== undefined) {
for (let key of Object.keys(queries)) {
const value = queries[key];
if (Array.isArray(value)) {
for (let iii = 0; iii < value.length; iii++) {
searchParams.append(`${key}`, `${value[iii]}`);
}
} else {
searchParams.append(`${key}`, `${value}`);
}
}
}
if (restConfig.token !== undefined && restModel.tokenInUrl === true) {
searchParams.append('Authorization', `Bearer ${restConfig.token}`);
}
return generateUrl + "?" + searchParams.toString();
}
export function RESTRequest({ restModel, restConfig, data, params, queries }: RESTRequestType): Promise<ModelResponseHttp> {
// Create the URL PATH:
let generateUrl = RESTUrl({ restModel, restConfig, data, params, queries });
let headers: any = {};
if (restConfig.token !== undefined && restModel.tokenInUrl !== true) {
headers['Authorization'] = `Bearer ${restConfig.token}`;
}
if (restModel.accept !== undefined) {
headers['Accept'] = restModel.accept;
}
if (restModel.requestType !== HTTPRequestModel.GET) {
// if Get we have not a content type, the body is empty
if (restModel.contentType !== HTTPMimeType.MULTIPART) {
// special case of multi-part ==> no content type otherwise the browser does not set the ";bundary=--****"
headers['Content-Type'] = restModel.contentType;
}
}
let body = data;
if (restModel.contentType === HTTPMimeType.JSON) {
body = JSON.stringify(data);
} else if (restModel.contentType === HTTPMimeType.MULTIPART) {
const formData = new FormData();
for (const name in data) {
formData.append(name, data[name]);
}
body = formData
}
console.log(`Call ${generateUrl}`)
return new Promise((resolve, reject) => {
fetch(generateUrl, {
method: restModel.requestType,
headers,
body,
}).then((response: Response) => {
if (response.status >= 200 && response.status <= 299) {
const contentType = response.headers.get('Content-Type');
if (restModel.accept !== contentType) {
reject({
time: Date().toString(),
status: 901,
error: `REST check wrong type: ${restModel.accept} != ${contentType}`,
statusMessage: "Fetch error",
message: "rest-tools.ts Wrong type in the message return type"
} as RestErrorResponse);
} else if (contentType === HTTPMimeType.JSON) {
response
.json()
.then((value: any) => {
//console.log(`RECEIVE ==> ${response.status}=${ JSON.stringify(value, null, 2)}`);
resolve({ status: response.status, data: value });
})
.catch((reason: any) => {
reject({
time: Date().toString(),
status: 902,
error: `REST parse json fail: ${reason}`,
statusMessage: "Fetch parse error",
message: "rest-tools.ts Wrong message model to parse"
} as RestErrorResponse);
});
} else {
resolve({ status: response.status, data: response.body });
}
} else {
reject({
time: Date().toString(),
status: response.status,
error: `${response.body}`,
statusMessage: "Fetch code error",
message: "rest-tools.ts Wrong return code"
} as RestErrorResponse);
}
}).catch((error: any) => {
reject({
time: Date(),
status: 999,
error: error,
statusMessage: "Fetch catch error",
message: "http-wrapper.ts detect an error in the fetch request"
});
});
});
}
export function RESTRequestJson<TYPE>(request: RESTRequestType, checker: (data: any) => data is TYPE): Promise<TYPE> {
return new Promise((resolve, reject) => {
RESTRequest(request).then((value: ModelResponseHttp) => {
if (checker(value.data)) {
resolve(value.data);
} else {
reject({
time: Date().toString(),
status: 950,
error: "REST Fail to verify the data",
statusMessage: "API cast ERROR",
message: "api.ts Check type as fail"
} as RestErrorResponse);
}
}).catch((reason: RestErrorResponse) => {
reject(reason);
});
});
}
export function RESTRequestJsonArray<TYPE>(request: RESTRequestType, checker: (data: any) => data is TYPE): Promise<TYPE[]> {
return new Promise((resolve, reject) => {
RESTRequest(request).then((value: ModelResponseHttp) => {
if (isArrayOf(value.data, checker)) {
resolve(value.data);
} else {
reject({
time: Date().toString(),
status: 950,
error: "REST Fail to verify the data",
statusMessage: "API cast ERROR",
message: "api.ts Check type as fail"
} as RestErrorResponse);
}
}).catch((reason: RestErrorResponse) => {
reject(reason);
});
});
}
export function RESTRequestVoid(request: RESTRequestType): Promise<void> {
return new Promise((resolve, reject) => {
RESTRequest(request).then((value: ModelResponseHttp) => {
resolve();
}).catch((reason: RestErrorResponse) => {
reject(reason);
});
});
}

View File

@@ -0,0 +1,186 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray, RESTRequestVoid } from "./rest-tools"
import {UUID, Long, Track, isTrack, } from "./model"
export namespace TrackResource {
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<void> {
return RESTRequestVoid({
restModel: {
endPoint: "/track/{id}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
});
};
export function get({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isTrack);
};
export function patch({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: Track,
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}",
requestType: HTTPRequestModel.PATCH,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isTrack);
};
export function post({ restConfig, data, }: {
restConfig: RESTConfig,
data: Track,
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, isTrack);
};
export function gets({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<Track[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/track",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isTrack);
};
export function addTrack({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
artistId: Long,
id: Long,
},
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}/artist/{artistId}",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isTrack);
};
export function removeTrack({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
artistId: Long,
id: Long,
},
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}/artist/{trackId}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isTrack);
};
export function uploadCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: File,
},
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}/cover",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isTrack);
};
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: UUID,
id: Long,
},
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
contentType: HTTPMimeType.TEXT_PLAIN,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isTrack);
};
export function uploadTrack({ restConfig, data, }: {
restConfig: RESTConfig,
data: {
fileName: string,
file: File,
gender: string,
artist: string,
album: string,
trackId: Long,
title: string,
},
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track/upload/",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.MULTIPART,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, isTrack);
};
}

View File

@@ -0,0 +1,51 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray, RESTRequestVoid } from "./rest-tools"
import {UserOut, Long, UserKarusic, isUserOut, isUserKarusic, } from "./model"
export namespace UserResource {
export function get({ restConfig, params, produce, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
produce: HTTPMimeType.JSON,
}): Promise<UserKarusic> {
return RESTRequestJson({
restModel: {
endPoint: "/users/{id}",
requestType: HTTPRequestModel.GET,
accept: produce,
},
restConfig,
params,
}, isUserKarusic);
};
export function gets({ restConfig, produce, }: {
restConfig: RESTConfig,
produce: HTTPMimeType.JSON,
}): Promise<UserKarusic[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/users",
requestType: HTTPRequestModel.GET,
accept: produce,
},
restConfig,
}, isUserKarusic);
};
export function getMe({ restConfig, produce, }: {
restConfig: RESTConfig,
produce: HTTPMimeType.JSON,
}): Promise<UserOut> {
return RESTRequestJson({
restModel: {
endPoint: "/users/me",
requestType: HTTPRequestModel.GET,
accept: produce,
},
restConfig,
}, isUserOut);
};
}

View File

@@ -10,30 +10,30 @@ import { DataService } from 'app/service/data';
@Component({
selector: 'data-image',
templateUrl: './data-image.html',
styleUrls: [ './data-image.less' ]
styleUrls: ['./data-image.less']
})
export class ElementDataImageComponent implements OnInit {
// input parameters
@Input() id:number = -1;
@Input() id: string = "0";
cover: string = '';
/*
imageCanvas:any;
@ViewChild('imageCanvas')
set mainDivEl(el: ElementRef) {
if(el !== null && el !== undefined) {
this.imageCanvas = el.nativeElement;
/*
imageCanvas:any;
@ViewChild('imageCanvas')
set mainDivEl(el: ElementRef) {
if(el !== null && el !== undefined) {
this.imageCanvas = el.nativeElement;
}
}
}
*/
*/
constructor(private dataService: DataService) {
}
ngOnInit() {
this.cover = this.dataService.getCoverThumbnailUrl(this.id);
this.cover = this.dataService.getThumbnailUrl(this.id);
/*
let canvas = this.imageCanvas.nativeElement;
let ctx = canvas.getContext("2d");
console.log(`Request thumnail for ---> ${this.id}`);
console.log(`Request thumbnail for ---> ${this.id}`);
this.dataService.getImageThumbnail(this.id)
.then((result:ModelResponseHttp) => {
console.log(`plop ---> ${result.status}`);

View File

@@ -0,0 +1,42 @@
<div class="fill-title">
<div class="description-area">
@if(title) {
<div class="shadow-text title">
{{title}}
</div>
}
@if(name) {
<div class="shadow-text sub-title-main">
{{name}}
</div>
}
@if(description) {
<div class="description">
{{description}}
</div>
}
<div class="button-area">
<button class="circular-button" (click)="playAll($event)" type="submit">
<i class="material-icons">play_arrow</i>
</button>
<button class="circular-button" (click)="playShuffle($event)" type="submit">
<i class="material-icons">shuffle</i>
</button>
<div style="flex:1;"></div>
</div>
</div>
@if (cover1 && cover1.length > 0) {
<div class="cover-area">
<div class="cover">
<img src="{{cover1[0]}}"/>
</div>
</div>
}
@if (cover2 && cover2.length > 0) {
<div class="cover-area">
<div class="cover">
<img src="{{cover2[0]}}"/>
</div>
</div>
}
</div>

View File

@@ -0,0 +1,31 @@
/** @file
* @author Edouard DUPIN
* @copyright 2018, Edouard DUPIN, all right reserved
* @license PROPRIETARY (see license file)
*/
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'description-area',
templateUrl: './description-area.html',
styleUrls: ['./description-area.less']
})
export class DescriptionAreaComponent {
@Input() title: string;
@Input() name?: string;
@Input() description?: string;
@Input() cover1?: number[];
@Input() cover2?: number[];
@Output() play = new EventEmitter<void>();
@Output() shuffle = new EventEmitter<void>();
playShuffle(event: any): void {
this.shuffle.emit();
}
playAll(event: any): void {
this.play.emit();
}
}

View File

@@ -1,46 +1,52 @@
<div class="bottom" *ngIf="mediaSource">
<div class="media" >
<div class="media-elem">
<audio width="1" height="1" src="{{mediaSource}}"
#mediaPlayer
preload
(play)="changeStateToPlay()"
(pause)="changeStateToPause()"
(timeupdate)="changeTimeupdate($event.currentTime)"
(durationchange)="changeDurationchange($event.duration)"
(loadedmetadata)="changeMetadata()"
autoplay
(ended)="onAudioEnded()"
><!-- controls > --> <!--preload="none"-->
<!--<p>Your browser does not support HTML5 media player. download media: <a href="{{mediaSource}}>link here</a>.</p>-->
</audio>
</div>
@if(mediaSource) {
<div>
<audio width="1" height="1" src="{{mediaSource}}"
#mediaPlayer
preload
(play)="changeStateToPlay()"
(pause)="changeStateToPause()"
(timeupdate)="changeTimeupdate($event.currentTime)"
(durationchange)="changeDurationchange($event.duration)"
(loadedmetadata)="changeMetadata()"
autoplay
(ended)="onAudioEnded()"
>
</audio>
<div class="controls">
<div class="timer">
<div class="timer-title">
<label class="unselectable label">{{nameData}}</label>
<div class="controls-inner">
<div class="title text-ellipsis">
<label class="unselectable">{{dataTitle}}</label>
</div>
<div class="timer-lines">
<div class="text-ellipsis">
<label class="unselectable">{{dataAuthor}} / {{dataAlbum}}</label>
</div>
<div class="timer-slider">
<input type="range" min="0" class="slider"
[value]="currentTime"
[max]="duration"
(input)="seek($event.target)">
</div>
<div class="timer-text">
<label class="unselectable label">{{currentTimeDisplay}} / {{durationDisplay}}</label>
<div class="flex-row">
<label class="unselectable">{{currentTimeDisplay}}</label>
<label class="unselectable flex-row-last">{{durationDisplay}}</label>
</div>
<div class="timer-control">
<button (click)="onPlay()" *ngIf="!isPlaying" ><i class="material-icons">play_arrow</i></button>
<button (click)="onPause()" *ngIf="isPlaying" ><i class="material-icons">pause</i></button>
<button (click)="onStop()" ><i class="material-icons">stop</i></button>
<div class="control">
@if(!isPlaying) {
<button (click)="onPlay()"><i class="material-icons">play_arrow</i></button>
}
@else {
<button (click)="onPause()"><i class="material-icons">pause</i></button>
}
<button (click)="onStop()"><i class="material-icons">stop</i></button>
<div style="margin:auto"></div>
<button [disabled]="havePrevious" (click)="onBefore()"><i class="material-icons">navigate_before</i></button>
<button (click)="onRewind()"><i class="material-icons">fast_rewind</i></button>
<button (click)="onForward()"><i class="material-icons">fast_forward</i></button>
<button [disabled]="haveNext" (click)="onNext()"><i class="material-icons">navigate_next</i></button>
<div style="margin:auto"></div>
<button (click)="onPlayMode()"><i class="material-icons">{{playMode}}</i></button>
<!--<button (click)="onMore()" ><i class="material-icons">more_vert</i></button>-->
<!--<button (click)="onTakeScreenShoot()"><i class="material-icons">add_a_photo</i></button>-->
</div>
</div>
</div>
</div>
</div>
}

View File

@@ -1,159 +1,113 @@
.controls {
//visibility: hidden;
opacity: 0.85;
width: 96%;
//height: 150px;
border-radius: 10px;
position: absolute;
bottom: 20px;
left: 2%;
//margin-left: -200px;
background-color: black;
box-shadow: 3px 3px 5px black;
transition: 1s all;
display: flex;
font-size: 40px;
min-width: 380px;
.bottom {
.controls {
//visibility: hidden;
opacity: 0.85;
width: 96%;
height: 150px;
border-radius: 10px;
position: absolute;
bottom: 20px;
left: 2%;
//margin-left: -200px;
background-color: black;
box-shadow: 3px 3px 5px black;
transition: 1s all;
display: flex;
.controls-inner {
position: relative;
width: 100%;
height: 100%;
min-width: 350px;
font-family: monospace;
color: white;
margin: 10px 15px 1px 15px;
font-size: 20px;
}
.material-icons {
color: #FFF;
font-size: 40px;
}
button {
border: none;
background: none;
}
button:disabled,
button[disabled] {
.material-icons {
color: #FFF;
font-size: 40px;
}
button {
border: none;
background: none;
color: rgb(46, 46, 46);
}
}
button:disabled,
button[disabled] {
.material-icons {
color: rgb(46, 46, 46);
}
}
.slidecontainer {
line-height: 38px;
font-size: 10px;
font-family: monospace;
text-shadow: 1px 1px 0px black;
color: white;
flex: 5;
position: relative;
}
.slider {
position: relative;
-webkit-appearance: none;
//width: calc(100% - 60px);
width: 95%;
height: 10px;
top: 5px;
border-radius: 5px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
flex: 5;
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border-radius: 50%;
background: #4CAF50;
cursor: pointer;
}
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
border-radius: 50%;
background: #4CAF50;
cursor: pointer;
}
.slider {
position: relative;
//-webkit-appearance: none;
width: 100%;
height: 10px;
top: 5px;
border-radius: 5px;
background: #d3d3d3;
outline: none;
opacity: 0.7;
-webkit-transition: .2s;
transition: opacity .2s;
flex: 5;
}
.timer-title {
position: absolute;
left: 30px;
width: 100%;
font-size: 20px;
font-weight:bold;
bottom: 104px;
}
.timer-lines {
position: absolute;
left: 30px;
//width: calc(100%-60px);
font-size: 20px;
font-weight:bold;
bottom: 82px;
}
.timer-text {
position: absolute;
left: 30px;
width: 100%;
font-size: 20px;
font-weight:bold;
bottom: 40px;
}
.timer-control {
position: absolute;
//top: 25px;
left: 0px;
width: 100%;
//line-height: 38px;
font-size: 30px;
font-weight:bold;
bottom: 0px;
}
.label {
//transform: translate(-12px,-12px);
vertical-align: text-top;
line-height: 18px;
min-width: 50%;
//display: block,
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 25px;
height: 25px;
border-radius: 50%;
background: #4CAF50;
cursor: pointer;
}
/*
:hover .controls, :focus .controls {
opacity: 1;
.slider::-moz-range-thumb {
width: 25px;
height: 25px;
border-radius: 50%;
background: #4CAF50;
cursor: pointer;
}
*/
button:before {
font-family: HeydingsControlsRegular;
font-size: 30px;
position: relative;
color: #FFF;
//text-shadow: 1px 1px 0px black;
.text-ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.timer {
line-height: 38px;
.title {
font-size: 24px;
font-weight: bold;
}
.timer-slider {
width: 100%;
margin: 4px 0px 4px 0px;
font-size: 20px;
padding-bottom: 10px;
}
.control {
width: 100%;
font-size: 30px;
font-family: monospace;
text-shadow: 1px 1px 0px black;
color: white;
flex: 5;
position: relative;
font-weight: bold;
display: flex;
justify-content: center;
}
.timer div {
width:100%;
line-height: 38px;
font-size: 10px;
font-family: monospace;
text-shadow: 1px 1px 0px black;
color: white;
flex: 5;
position: relative;
}
.timer span {
position: absolute;
z-index: 3;
left: 19px;
}
}
button:before {
font-family: HeydingsControlsRegular;
font-size: 30px;
position: relative;
color: #FFF;
}

View File

@@ -3,16 +3,13 @@
* @copyright 2018, Edouard DUPIN, all right reserved
* @license PROPRIETARY (see license file)
*/
import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { isArray, isArrayOf, isNullOrUndefined, isNumberFinite } from 'common/utils';
import { NodeData } from 'common/model';
import { Component, OnInit, ViewChild, ElementRef, Inject } from '@angular/core';
import { GenderService, DataService, PlayerService, TrackService, AlbumService, ArtistService } from 'app/service';
import { DataService, PlayerService, TrackService, AlbumService, ArtistService } from 'app/service';
import { PlaylistCurrent } from 'app/service/player';
import { Media } from 'app/model';
import { HttpWrapperService } from 'common/service';
import { Title } from '@angular/platform-browser';
import { environment } from 'environments/environment';
import { Album, Artist, Track } from 'app/back-api';
import { isArray, isNullOrUndefined, Environment } from '@kangaroo-and-rabbit/kar-cw';
export enum PlayMode {
@@ -26,16 +23,16 @@ export enum PlayMode {
@Component({
selector: 'app-element-player-audio',
templateUrl: './element-player-audio.html',
styleUrls: [ './element-player-audio.less' ]
styleUrls: ['./element-player-audio.less']
})
export class ElementPlayerAudioComponent implements OnInit {
mediaPlayer: HTMLAudioElement;
duration: number;
durationDisplay: string;
@ViewChild('mediaPlayer')
set mainVideoEl(el: ElementRef) {
if(el !== null && el !== undefined) {
this.mediaPlayer = el.nativeElement;
set mainVideoEl(el: ElementRef) {
if (el !== null && el !== undefined) {
this.mediaPlayer = el.nativeElement;
}
}
public mediaSource: string = undefined;
@@ -43,14 +40,16 @@ export class ElementPlayerAudioComponent implements OnInit {
public name: string = 'rr';
public description: string;
public counttrack: number;
public countTrack: number;
public covers: string[];
public volume_value: number = 100;
public volume_displayMenu: boolean = false;
nameData: string;
dataTitle: string;
dataAlbum: string;
dataAuthor: string;
playStream: boolean;
isPlaying: boolean;
currentTime: any;
@@ -70,16 +69,16 @@ export class ElementPlayerAudioComponent implements OnInit {
}
}
constructor(
@Inject('ENVIRONMENT') private environment: Environment,
private playerService: PlayerService,
private trackService: TrackService,
private dataService: DataService,
private albumService: AlbumService,
private artistService: ArtistService,
private httpService: HttpWrapperService,
private dataService: DataService,
private titleService: Title) {
// nothing to do...
}
private currentLMedia: Media;
private currentLMedia: Track;
private localIdStreaming: number;
private localListStreaming: number[] = [];
ngOnInit() {
@@ -103,220 +102,74 @@ export class ElementPlayerAudioComponent implements OnInit {
}
let self = this;
this.havePrevious = this.localIdStreaming <= 0;
this.haveNext = this.localIdStreaming >= this.localListStreaming.length-1;
this.haveNext = this.localIdStreaming >= this.localListStreaming.length - 1;
this.trackService.get(this.localListStreaming[this.localIdStreaming])
.then((response: Media) => {
//console.log(`get response of video : ${ JSON.stringify(response, null, 2)}`);
.then((response: Track) => {
console.log(`get response of video : ${JSON.stringify(response, null, 2)}`);
self.currentLMedia = response;
self.nameData = response.name;
self.dataTitle = response.name;
if (!isNullOrUndefined(response.albumId)) {
this.albumService.get(response.albumId)
.then((response2: NodeData) => {
self.nameData = response2.name + " - " + self.nameData;
this.titleService.setTitle(`${environment.applName} > ${self.nameData}`)
.then((response2: Album) => {
self.dataAlbum = response2.name;
self.updateTitle();
})
.catch(() => {});
.catch(() => { });
}
if (!isNullOrUndefined(response.artists) && isArray(response.artists) && response.artists.length > 0) {
this.artistService.get(response.artists[0])
.then((response2: NodeData) => {
self.nameData = `${self.nameData} (${response2.name})`;
this.titleService.setTitle(`${environment.applName} > ${self.nameData}`)
.then((response2: Artist) => {
self.dataAuthor = response2.name;
})
.catch(() => {});
}
.catch(() => { });
}
if (isNullOrUndefined(self.currentLMedia)) {
console.log("Can not retreive the media ...")
console.log("Can not retrieve the media ...")
return;
}
if (isNullOrUndefined(self.currentLMedia.dataId)) {
console.log("Can not retreive the media ... null or undefined data ID")
console.log("Can not retrieve the media ... null or undefined data ID")
return;
}
self.mediaSource = self.httpService.createRESTCall2({
api: `data/${self.currentLMedia.dataId}/unknowMediaName.webm`, //${self.generatedName}`,
addURLToken: true,
});
}).catch(() => {
console.error("error not ùmanaged in audio player ... 111");
self.mediaSource = self.dataService.getUrl(self.currentLMedia.dataId, "unknownMediaName.webm");
}).catch((error) => {
console.error(`error not unmanaged in audio player ... 111 ${error}`);
})
}
updateTitle() {
let title = this.dataTitle;
if (!isNullOrUndefined(this.dataAlbum)) {
title = `${this.dataAlbum} - ${title}`;
}
if (!isNullOrUndefined(this.dataAuthor)) {
title = `${title} (${this.dataAuthor})`;
}
generateName() {
/*
this.generatedName = '';
if(this.seriesName !== undefined) {
this.generatedName = `${this.generatedName }${this.seriesName }-`;
}
if(this.seasonName !== undefined) {
if(this.seasonName.length < 2) {
this.generatedName = `${this.generatedName }s0${ this.seasonName }-`;
} else {
this.generatedName = `${this.generatedName }s${ this.seasonName }-`;
}
}
if(this.episode !== undefined) {
if(this.episode < 10) {
this.generatedName = `${this.generatedName }e0${ this.episode }-`;
} else {
this.generatedName = `${this.generatedName }e${ this.episode }-`;
}
}
this.generatedName = this.generatedName + this.name;
this.generatedName = this.generatedName.replace(new RegExp('&', 'g'), '_');
this.generatedName = this.generatedName.replace(new RegExp('/', 'g'), '_');
// update the path of the uri request
this.mediaSource = this.httpService.createRESTCall2({
api: `data/${ this.dataId}/${this.generatedName}`,
addURLToken: true,
});
*/
}
myPeriodicCheckFunction() {
console.log('check ... ');
this.titleService.setTitle(`${this.environment.applName} > ${title}`)
}
changeMetadata() {
console.log('list of the stream:');
/*
let captureStream = this.audioPlayer.audioTracks;
for (let iii=0; iii < captureStream.length; iii++) {
console.log(" - " + captureStream[iii].language);
if (captureStream[iii].language.substring(0,2) === "fr") {
captureStream[iii].enabled = true;
} else {
captureStream[iii].enabled = false;
}
}
*/
}
/*
ngOnInit() {
let self = this;
this.arianeService.updateManual(this.route.snapshot.paramMap);
this.idVideo = this.arianeService.getVideoId();
this.arianeService.mediaChange.subscribe((mediaId) => {
console.log(`Detect mediaId change...${ mediaId}`);
self.idVideo = mediaId;
self.updateDisplay();
});
self.updateDisplay();
}
*/
updateDisplay():void {
let self = this;
/*
self.haveNext = null;
self.havePrevious = null;
this.mediaService.get(this.idVideo)
.then((response) => {
console.log(`get response of media : ${ JSON.stringify(response, null, 2)}`);
self.error = '';
self.name = response.name;
self.description = response.description;
self.episode = response.episode;
self.seriesId = response.seriesId;
self.seasonId = response.seasonId;
self.dataId = response.dataId;
self.time = response.time;
self.generatedName = "????????? TODO: ???????" //response.generatedName;
if(self.dataId !== -1) {
self.mediaSource = self.httpService.createRESTCall2({
api: `data/${ self.dataId}/${self.generatedName}`,
addURLToken: true,
});
} else {
self.mediaSource = '';
}
self.covers = self.dataService.getCoverListUrl(response.covers);
self.generateName();
if(self.seriesId !== undefined && self.seriesId !== null) {
self.seriesService.get(self.seriesId)
.then((response2) => {
self.seriesName = response2.name;
self.generateName();
}).catch((response3) => {
// nothing to do ...
});
}
if(self.seasonId !== undefined && self.seasonId !== null) {
self.seasonService.get(self.seasonId)
.then((response4) => {
self.seasonName = response4.name;
self.generateName();
}).catch((response5) => {
// nothing to do ...
});
self.seasonService.getVideo(self.seasonId)
.then((response6:any) => {
// console.log("saison property: " + JSON.stringify(response, null, 2));
self.haveNext = null;
self.havePrevious = null;
for(let iii = 0; iii < response6.length; iii++) {
if(isNullOrUndefined(response6[iii].episode)) {
continue;
}
if(response6[iii].episode < self.episode) {
if(self.havePrevious === null) {
self.havePrevious = response6[iii];
} else if(self.havePrevious.episode < response6[iii].episode) {
self.havePrevious = response6[iii];
}
} else if(response6[iii].episode > self.episode) {
if(self.haveNext === null) {
self.haveNext = response6[iii];
} else if(self.haveNext.episode > response6[iii].episode) {
self.haveNext = response6[iii];
}
}
self.covers.push(self.dataService.getCoverUrl(response6[iii]));
}
}).catch((response7:any) => {
});
}
self.mediaIsLoading = false;
// console.log("display source " + self.mediaSource);
// console.log("set transformed : " + JSON.stringify(self, null, 2));
}).catch((response8) => {
self.error = 'Can not get the data';
self.name = '';
self.description = '';
self.episode = undefined;
self.seriesId = undefined;
self.seasonId = undefined;
self.dataId = -1;
self.time = undefined;
self.generatedName = '';
self.mediaSource = '';
self.covers = undefined;
self.seriesName = undefined;
self.seasonName = undefined;
self.mediaIsNotFound = true;
self.mediaIsLoading = false;
});
*/
myPeriodicCheckFunction() {
console.log('check ... ');
}
onRequirePlay() {
this.playStream = true;
}
onRequireStop() {
this.playStream = false;
}
onAudioEnded() {
if (this.playMode === PlayMode.PLAY_ONE) {
this.playStream = false;
this.playStream = false;
} else if (this.playMode === PlayMode.PLAY_ALL) {
this.onNext();
} else if (this.playMode === PlayMode.PLAY_ONE_LOOP) {
this.mediaPlayer.currentTime = 0;
this.onPlay();
} else {
if (this.localIdStreaming == this.localListStreaming.length-1) {
if (this.localIdStreaming == this.localListStreaming.length - 1) {
this.localIdStreaming = 0;
this.updateMediaStreamed();
if (this.localListStreaming.length == 1) {
@@ -336,25 +189,25 @@ export class ElementPlayerAudioComponent implements OnInit {
this.isPlaying = false;
}
convertIndisplayTime(time:number) : string {
let tmpp = parseInt(`${ time}`, 10);
let heures = parseInt(`${ tmpp / 3600}`, 10);
tmpp = tmpp - heures * 3600;
let minutes = parseInt(`${ tmpp / 60}`, 10);
let seconds = tmpp - minutes * 60;
convertInDisplayTime(time: number): string {
let temporaryValue = parseInt(`${time}`, 10);
let hours = parseInt(`${temporaryValue / 3600}`, 10);
temporaryValue = temporaryValue - hours * 3600;
let minutes = parseInt(`${temporaryValue / 60}`, 10);
let seconds = temporaryValue - minutes * 60;
let out = '';
if(heures !== 0) {
out = `${out }${heures }:`;
if (hours !== 0) {
out = `${out}${hours}:`;
}
if(minutes >= 10) {
out = `${out }${minutes }:`;
if (minutes >= 10) {
out = `${out}${minutes}:`;
} else {
out = `${out }0${ minutes }:`;
out = `${out}0${minutes}:`;
}
if(seconds >= 10) {
if (seconds >= 10) {
out = out + seconds;
} else {
out = `${out }0${ seconds}`;
out = `${out}0${seconds}`;
}
return out;
}
@@ -363,20 +216,20 @@ export class ElementPlayerAudioComponent implements OnInit {
// console.log("time change ");
// console.log(" ==> " + this.audioPlayer.currentTime);
this.currentTime = this.mediaPlayer.currentTime;
this.currentTimeDisplay = this.convertIndisplayTime(this.currentTime);
this.currentTimeDisplay = this.convertInDisplayTime(this.currentTime);
// console.log(" ==> " + this.currentTimeDisplay);
}
changeDurationchange(duration: any) {
console.log('duration change ');
console.log(` ==> ${ this.mediaPlayer.duration}`);
console.log(` ==> ${this.mediaPlayer.duration}`);
this.duration = this.mediaPlayer.duration;
this.durationDisplay = this.convertIndisplayTime(this.duration);
this.durationDisplay = this.convertInDisplayTime(this.duration);
}
onPlay() {
console.log('play');
if(isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${ this.mediaPlayer}`);
if (isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${this.mediaPlayer}`);
return;
}
this.lockPlayerEnable();
@@ -385,8 +238,8 @@ export class ElementPlayerAudioComponent implements OnInit {
onPause() {
console.log('pause');
if(isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${ this.mediaPlayer}`);
if (isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${this.mediaPlayer}`);
return;
}
this.unlockPlayerEnable();
@@ -395,7 +248,7 @@ export class ElementPlayerAudioComponent implements OnInit {
onPauseToggle() {
console.log('pause toggle ...');
if(this.isPlaying === true) {
if (this.isPlaying === true) {
this.onPause();
} else {
this.onPlay();
@@ -404,8 +257,12 @@ export class ElementPlayerAudioComponent implements OnInit {
onStop() {
console.log('stop');
if(isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${ this.mediaPlayer}`);
if (this.mediaPlayer.paused && this.mediaPlayer.currentTime == 0) {
this.mediaSource = null;
return;
}
if (isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${this.mediaPlayer}`);
return;
}
this.unlockPlayerEnable();
@@ -426,7 +283,7 @@ export class ElementPlayerAudioComponent implements OnInit {
onNext() {
console.log('next');
if (this.localIdStreaming >= this.localListStreaming.length-1) {
if (this.localIdStreaming >= this.localListStreaming.length - 1) {
console.error("have no next !!!");
return;
}
@@ -435,10 +292,10 @@ export class ElementPlayerAudioComponent implements OnInit {
this.playerService.next();
}
seek(newValue:any) {
console.log(`seek ${ newValue.value}`);
if(isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${ this.mediaPlayer}`);
seek(newValue: any) {
console.log(`seek ${newValue.value}`);
if (isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${this.mediaPlayer}`);
return;
}
this.mediaPlayer.currentTime = newValue.value;
@@ -446,8 +303,8 @@ export class ElementPlayerAudioComponent implements OnInit {
onRewind() {
console.log('rewind');
if(isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${ this.mediaPlayer}`);
if (isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${this.mediaPlayer}`);
return;
}
this.mediaPlayer.currentTime = this.currentTime - 10;
@@ -455,8 +312,8 @@ export class ElementPlayerAudioComponent implements OnInit {
onForward() {
console.log('forward');
if(isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${ this.mediaPlayer}`);
if (isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${this.mediaPlayer}`);
return;
}
this.mediaPlayer.currentTime = this.currentTime + 10;
@@ -464,8 +321,8 @@ export class ElementPlayerAudioComponent implements OnInit {
onMore() {
console.log('more');
if(isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${ this.mediaPlayer}`);
if (isNullOrUndefined(this.mediaPlayer)) {
console.log(`error element: ${this.mediaPlayer}`);
return;
}
}
@@ -474,28 +331,29 @@ export class ElementPlayerAudioComponent implements OnInit {
// these element is to permit to not stop music when sceen is off !!
wakeLock = null;
unlockPlayerEnable() {
let tmppp = this.wakeLock;
let temporaryValue = this.wakeLock;
this.wakeLock = null;
if (!isNullOrUndefined(tmppp)) {
tmppp.release();
if (!isNullOrUndefined(temporaryValue)) {
console.log(`plopppp ${temporaryValue}`);
temporaryValue.release();
}
try {
let tmp = navigator as any;
this.wakeLock = tmp.wakeLock.request('screen');
} catch (err) {
} catch (err) {
// The Wake Lock request has failed - usually system related, such as battery.
console.log(`Can not lock screen element: ${err.name}, ${err.message}`);
}
}
}
lockPlayerEnable() {
async lockPlayerEnable() {
if ('wakeLock' in navigator) {
try {
let tmp = navigator as any;
this.wakeLock = tmp.wakeLock.request('screen');
} catch (err) {
this.wakeLock = await tmp.wakeLock.request('screen');
} catch (err) {
// The Wake Lock request has failed - usually system related, such as battery.
console.log(`Can not lock screen element: ${err.name}, ${err.message}`);
}
}
}
}
}

View File

@@ -1,41 +1,45 @@
<div class="imgContainer-small">
<div *ngIf="covers">
<!--<data-image id="{{cover}}"></data-image>-->
<img src="{{covers[0]}}"/>
</div>
<div *ngIf="!covers" class="noImage">
</div>
@if(covers && covers.length > 0) {
<div>
<img src="{{covers[0]}}"/>
</div>
}
@else {
<div class="noImage"></div>
}
</div>
<div class="season-small">
{{prefixName}} {{numberAlbum}}
</div>
<div class="description-small" *ngIf="countSubType && (!count || count == 0)">
No {{countSubType}}
</div>
<div class="description-small" *ngIf="countSubType && count > 1">
{{count}} {{countSubType}}s
</div>
<div class="description-small" *ngIf="countSubType && count == 1">
{{count}} {{countSubType}}
</div>
@if(countSubType) {
<div class="description-small">
@if(!count || count == 0) {
No {{countSubType}}
}
@else {
{{count}} {{countSubType}}{{count>1?"s":""}}
}
</div>
}
<div class="description-small" *ngIf="countSubType2 && (!count2 || count2 == 0)">
No {{countSubType2}}
</div>
<div class="description-small" *ngIf="countSubType2 && count2 > 1">
{{count2}} {{countSubType2}}s
</div>
<div class="description-small" *ngIf="countSubType2 && count2 == 1">
{{count2}} {{countSubType2}}
</div>
<div class="description-small" *ngIf="subValueData">
{{subValues}}: {{subValueData}}
</div>
<div class="description-small" *ngIf="!description">
{{description}}
</div>
@if(countSubType2) {
<div class="description-small">
@if(!count2 || count2 == 0) {
No {{countSubType2}}
}
@else {
{{count2}} {{countSubType2}}{{count2>1?"s":""}}
}
</div>
}
@if(subValueData) {
<div class="description-small">
{{subValues}}: {{subValueData}}
</div>
}
@if(!description) {
<div class="description-small">
{{description}}
</div>
}

View File

@@ -3,28 +3,29 @@
* @copyright 2018, Edouard DUPIN, all right reserved
* @license PROPRIETARY (see license file)
*/
import {Component, OnInit, Input } from '@angular/core';
import { Component, OnInit, Input } from '@angular/core';
import { isNullOrUndefined } from '@kangaroo-and-rabbit/kar-cw';
import { NodeSmall } from 'app/back-api';
import { AlbumService, DataService } from 'app/service';
import { NodeData } from 'common/model';
import { isNullOrUndefined } from 'common/utils';
@Component({
selector: 'app-element-season',
templateUrl: './element-season.html',
styleUrls: [ './element-season.less' ]
styleUrls: ['./element-season.less']
})
export class ElementSeasonComponent implements OnInit {
// input parameters
@Input() element:NodeData;
@Input() prefix:String;
@Input() element: NodeSmall;
@Input() prefix: String;
@Input() countSubTypeCallBack: (arg0: number) => Promise<number>;
@Input() countSubType: String;
@Input() countSubType2CallBack: (arg0: number) => Promise<number>;
@Input() countSubType2: String;
@Input() subValuesCallBack: (arg0: number) => Promise<string[]>;
@Input() subValues: String;
prefixName: string = "";
numberAlbum: string;
count: number;
@@ -39,9 +40,10 @@ export class ElementSeasonComponent implements OnInit {
}
ngOnInit() {
this.prefix = this.prefixName??"";
this.prefix = this.prefixName ?? "";
this.count = undefined;
this.count2 = undefined;
//console.log(`element: ${JSON.stringify(this.element, null, 2)}`);
if (isNullOrUndefined(this.element)) {
this.numberAlbum = undefined;
@@ -50,7 +52,7 @@ export class ElementSeasonComponent implements OnInit {
}
this.numberAlbum = this.element.name;
this.description = this.element.description;
this.covers = this.dataService.getCoverListThumbnailUrl(this.element.covers);
this.covers = this.dataService.getListThumbnailUrl(this.element.covers);
let self = this;
if (!isNullOrUndefined(this.countSubTypeCallBack)) {
this.countSubTypeCallBack(this.element.id)
@@ -75,7 +77,7 @@ export class ElementSeasonComponent implements OnInit {
this.subValuesCallBack(this.element.id)
.then((response: string[]) => {
this.subValueData = "";
for (let kkk=0; kkk<response.length; kkk++) {
for (let kkk = 0; kkk < response.length; kkk++) {
if (kkk != 0) {
this.subValueData += ", ";
}

View File

@@ -1,24 +1,23 @@
<div>
<div class="count-base">
<div class="count" *ngIf="counttrack">
{{counttrack}}
</div>
@if(countTrack) {
<div class="count">
{{countTrack}}
</div>
}
</div>
<div class="imgContainer-small">
<div *ngIf="covers">
<!--<data-image id="{{cover}}"></data-image>-->
<img src="{{covers[0]}}"/>
</div>
<div *ngIf="!covers" class="noImage">
</div>
@if(covers && covers.length > 0) {
<div>
<!--<data-image id="{{cover}}"></data-image>-->
<img src="{{covers[0]}}"/>
</div>
}
@else {
<div class="noImage"></div>
}
</div>
<div class="title-small">
{{name}}
</div>
<!--
<div class="description-small" *ngIf="description">
{{description}}
</div>
-->
</div>

View File

@@ -4,28 +4,28 @@
* @license PROPRIETARY (see license file)
*/
import { Component, OnInit, Input } from '@angular/core';
import { NodeData } from 'common/model';
import { isNullOrUndefined } from 'common/utils';
import { ArtistService, DataService } from 'app/service';
import { DataService, TrackService } from 'app/service';
import { NodeSmall } from 'app/back-api';
import { isNullOrUndefined } from '@kangaroo-and-rabbit/kar-cw';
@Component({
selector: 'app-element-series',
templateUrl: './element-series.html',
styleUrls: [ './element-series.less' ]
styleUrls: ['./element-series.less']
})
export class ElementSeriesComponent implements OnInit {
// input parameters
@Input() element:NodeData;
name:string = 'plouf';
description:string = '';
counttrack:number = null;
@Input() element: NodeSmall;
covers:string[];
name: string = 'plouf';
description: string = '';
countTrack: number = null;
covers: string[];
constructor(
private artistService: ArtistService,
private trackService: TrackService,
private dataService: DataService) {
}
@@ -35,16 +35,15 @@ export class ElementSeriesComponent implements OnInit {
this.description = undefined;
return;
}
let self = this;
self.name = this.element.name;
self.description = this.element.description;
self.covers = self.dataService.getCoverListThumbnailUrl(this.element.covers);
this.name = this.element.name;
this.description = this.element.description;
this.covers = this.dataService.getListThumbnailUrl(this.element.covers);
this.artistService.countTrack(this.element.id)
this.trackService.countTracksOfAnArtist(this.element.id)
.then((response) => {
self.counttrack = response;
this.countTrack = response;
}).catch((response) => {
self.counttrack = 0;
this.countTrack = 0;
});
}
}

View File

@@ -2,7 +2,9 @@
<div class="season-small">
{{name}}
</div>
<div class="description-small" *ngIf="track">
n° {{track}}
</div>
@if(track) {
<div class="description-small">
n° {{track}}
</div>
}
</div>

View File

@@ -3,22 +3,22 @@
* @copyright 2018, Edouard DUPIN, all right reserved
* @license PROPRIETARY (see license file)
*/
import {Component, OnInit, Input } from '@angular/core';
import { Component, OnInit, Input } from '@angular/core';
import { isNullOrUndefined } from '@kangaroo-and-rabbit/kar-cw';
import { NodeSmall } from 'app/back-api';
import { AlbumService, DataService } from 'app/service';
import { NodeData } from 'common/model';
import { isNullOrUndefined } from 'common/utils';
import { DataService } from 'app/service';
@Component({
selector: 'app-element-track',
templateUrl: './element-track.html',
styleUrls: [ './element-track.less' ]
styleUrls: ['./element-track.less']
})
export class ElementTrackComponent implements OnInit {
// input parameters
@Input() element:NodeData;
@Input() prefix:String;
@Input() element: NodeSmall;
@Input() prefix: String;
prefixName: string = "";
name: string;
track: number;
@@ -26,12 +26,11 @@ export class ElementTrackComponent implements OnInit {
description: string;
constructor(
private albumService: AlbumService,
private dataService: DataService) {
}
ngOnInit() {
this.prefix = this.prefixName??"";
this.prefix = this.prefixName ?? "";
if (isNullOrUndefined(this.element)) {
this.name = undefined;
this.covers = undefined;
@@ -40,7 +39,6 @@ export class ElementTrackComponent implements OnInit {
this.name = this.element.name;
this.description = this.element.description;
this.track = this.element["track"];
this.covers = this.dataService.getCoverListThumbnailUrl(this.element.covers);
let self = this;
this.covers = this.dataService.getListThumbnailUrl(this.element.covers);
}
}

View File

@@ -1,16 +1,22 @@
<div>
<div class="count-base" *ngIf="counttrack">
<span class="count">{{counttrack}}</span>
</div>
<div class="imgContainer-small">
<div *ngIf="covers">
<img src="{{covers[0]}}" class="miniature-small"/>
@if(countTrack) {
<div class="count-base">
<span class="count">{{countTrack}}</span>
</div>
}
<div class="imgContainer-small">
@if(covers && covers.length > 0) {
<div>
<img src="{{covers[0]}}" class="miniature-small"/>
</div>
}
</div>
<div class="title-small">
{{name}}
</div>
<div class="description-small" *ngIf="description">
{{description}}
</div>
@if(description) {
<div class="description-small">
{{description}}
</div>
}
</div>

View File

@@ -4,30 +4,30 @@
* @license PROPRIETARY (see license file)
*/
import { Component, OnInit, Input } from '@angular/core';
import { isArrayOf, isNullOrUndefined, isNumberFinite } from 'common/utils';
import { NodeData } from 'common/model';
import { GenderService, DataService } from 'app/service';
import { DataService } from 'app/service';
import { NodeSmall } from 'app/back-api';
import { isNullOrUndefined } from '@kangaroo-and-rabbit/kar-cw';
@Component({
selector: 'app-element-type',
templateUrl: './element-type.html',
styleUrls: [ './element-type.less' ]
styleUrls: ['./element-type.less']
})
export class ElementTypeComponent implements OnInit {
// input parameters
@Input() element:NodeData;
@Input() functionVignette:(number) => Promise<Number>;
@Input() element: NodeSmall;
@Input() functionVignette: (number) => Promise<Number>;
public name: string = 'rr';
public description: string;
public counttrack: number;
public countTrack: number;
public covers: string[];
constructor(
private typeService: GenderService,
private dataService: DataService) {
}
@@ -35,7 +35,7 @@ export class ElementTypeComponent implements OnInit {
if (isNullOrUndefined(this.element)) {
this.name = 'Not a media';
this.description = undefined;
this.counttrack = undefined;
this.countTrack = undefined;
this.covers = undefined;
return;
}
@@ -43,14 +43,14 @@ export class ElementTypeComponent implements OnInit {
console.log(" ??? Get element ! " + JSON.stringify(this.element));
self.name = this.element.name;
self.description = this.element.description;
self.covers = self.dataService.getCoverListThumbnailUrl(this.element.covers);
self.covers = self.dataService.getListThumbnailUrl(this.element.covers);
if (!isNullOrUndefined(this.functionVignette)) {
this.functionVignette(this.element.id)
.then((response: number) => {
self.counttrack = response;
self.countTrack = response;
}).catch(() => {
self.counttrack = 0;
self.countTrack = 0;
});
}
}

View File

@@ -1,22 +1,23 @@
<div>
<div class="videoImgContainer">
<div *ngIf="covers">
<!--<data-image id="{{cover}}"></data-image>-->
<img src="{{covers[0]}}"/>
@if(covers && covers.length > 0) {
<div>
<!--<data-image id="{{cover}}"></data-image>-->
<img src="{{covers[0]}}"/>
</div>
}
@else {
<div class="noImage"></div>
}
</div>
@if(element) {
<div class="title-small">
{{episodeDisplay}} {{name}}
</div>
<div *ngIf="!covers" class="noImage">
}
@else {
<div class="title-small">
Error meda: {{element?.id}}
</div>
</div>
<div class="title-small" *ngIf="data">
{{episodeDisplay}} {{name}}
</div>
<div class="title-small" *ngIf="!data">
Error meda: {{element?.id}}
</div>
<!--
<div class="description-small" *ngIf="description">
{{description}}
</div>
-->
}
</div>

View File

@@ -4,50 +4,34 @@
* @license PROPRIETARY (see license file)
*/
import { Injectable, Component, OnInit, Input } from '@angular/core';
import { isMedia, Media } from 'app/model';
import { Track } from 'app/back-api';
import { DataService } from 'app/service';
import { NodeData } from 'common/model';
import { isNullOrUndefined } from 'common/utils';
@Component({
selector: 'app-element-video',
templateUrl: './element-video.html',
styleUrls: [ './element-video.less' ]
styleUrls: ['./element-video.less']
})
@Injectable()
export class ElementVideoComponent implements OnInit {
// input parameters
@Input() element:NodeData;
data:Media;
@Input() element: Track;
name: string = '';
description: string = '';
episodeDisplay: string = '';
name:string = '';
description:string = '';
episodeDisplay:string = '';
cover:string = '';
covers:string[];
cover: string = '';
covers: string[];
constructor(
private dataService: DataService) {
// nothing to do.
}
ngOnInit() {
if (!isMedia(this.element)) {
this.data = undefined;
this.name = 'Not a media';
this.description = undefined;
return;
}
this.data = this.element;
this.name = this.element.name;
this.description = this.element.description;
if(isNullOrUndefined(this.element.episode)) {
this.episodeDisplay = '';
} else {
this.episodeDisplay = `${this.element.episode } - `;
}
this.covers = this.dataService.getCoverListThumbnailUrl(this.element.covers);
this.covers = this.dataService.getListThumbnailUrl(this.element.covers);
}
}

View File

@@ -1,3 +1,4 @@
import { DescriptionAreaComponent } from "./description-area/description-area";
import { ElementPlayerAudioComponent } from "./element-player-audio/element-player-audio";
import { ElementSeasonComponent } from "./element-season/element-season";
import { ElementSeriesComponent } from "./element-series/element-series";
@@ -12,5 +13,6 @@ export {
ElementSeasonComponent,
ElementPlayerAudioComponent,
ElementTrackComponent,
DescriptionAreaComponent,
};

View File

@@ -1,34 +0,0 @@
import { isArrayOf, isNumberFinite, isObject, isOptionalOf, isOptionalArrayOf, isString } from "common/utils";
export interface AlbumModel {
id: number;
name: string;
description?: string;
covers?: number[];
tracks?: number[];
};
export function isAlbumModel(data: any): data is AlbumModel {
if (!isObject(data)) {
return false;
}
if (!isNumberFinite(data.id)) {
return false;
}
if (!isString(data.name)) {
return false;
}
if (!isOptionalOf(data.description, isString)) {
return false;
}
if (!isOptionalArrayOf(data.cover, isNumberFinite)) {
return false;
}
if (!isOptionalArrayOf(data.tracks, isNumberFinite)) {
return false;
}
return true;
}

View File

@@ -1,5 +0,0 @@
import { Media, isMedia } from "./media";
export {
Media, isMedia,
}

View File

@@ -1,47 +0,0 @@
import { isNumberFinite, isString, isOptionalOf, isArray } from "common/utils";
import { isNodeData, NodeData } from "common/model/node";
export interface Media extends NodeData {
dataId?: number;
genderId?: number;
artists?: number[];
albumId?: number;
episode?: number;
track?: number;
date?: number;
time?: number;
};
export function isMedia(data: any): data is Media {
if (!isNodeData(data) as any) {
return false;
}
if (!isOptionalOf(data.dataId, isNumberFinite)) {
return false;
}
if (!isOptionalOf(data.typeId, isNumberFinite)) {
return false;
}
if (!isOptionalOf(data.artists, isArray)) {
return false;
}
if (!isOptionalOf(data.albumId, isNumberFinite)) {
return false;
}
if (!isOptionalOf(data.track, isNumberFinite)) {
return false;
}
if (!isOptionalOf(data.episode, isNumberFinite)) {
return false;
}
if (!isOptionalOf(data.date, isNumberFinite)) {
return false;
}
if (!isOptionalOf(data.time, isNumberFinite)) {
return false;
}
return true;
}

View File

@@ -4,13 +4,12 @@
* @license PROPRIETARY (see license file)
*/
import { Component, OnInit } from '@angular/core';
import { PopInService } from 'common/service/popin';
import { PopInService } from '@kangaroo-and-rabbit/kar-cw';
@Component({
selector: 'create-type',
templateUrl: './create-type.html',
styleUrls: [ './create-type.less' ]
styleUrls: ['./create-type.less']
})
export class PopInCreateType implements OnInit {
name: string = '';
@@ -26,14 +25,14 @@ export class PopInCreateType implements OnInit {
}
eventPopUp(event: string): void {
console.log(`GET event: ${ event}`);
console.log(`GET event: ${event}`);
this.popInService.close('popin-create-type');
}
updateNeedSend():void {
updateNeedSend(): void {
}
onName(value:any):void {
if(value.length === 0) {
onName(value: any): void {
if (value.length === 0) {
this.name = '';
} else {
this.name = value;
@@ -41,8 +40,8 @@ export class PopInCreateType implements OnInit {
this.updateNeedSend();
}
onDescription(value:any):void {
if(value.length === 0) {
onDescription(value: any): void {
if (value.length === 0) {
this.description = '';
} else {
this.description = value;

View File

@@ -2,146 +2,160 @@
<div class="title">
Edit album
</div>
<div class="fill-all" *ngIf="itemIsRemoved">
<div class="message-big">
<br/><br/><br/>
The album has been removed
<br/><br/><br/>
</div>
</div>
<div class="fill-all" *ngIf="itemIsNotFound">
<div class="message-big">
<br/><br/><br/>
The album does not exist
<br/><br/><br/>
</div>
</div>
<div class="fill-all" *ngIf="itemIsLoading">
<div class="message-big">
<br/><br/><br/>
Loading ...<br/>
Please wait.
<br/><br/><br/>
</div>
</div>
<div class="fill-all" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
<div class="request_raw">
<div class="label">
name:
</div>
<div class="input">
<input type="text"
placeholder="Name of the album"
[value]="nameAlbum"
(input)="onName($event.target.value)"
/>
@if(itemIsRemoved) {
<div class="fill-all">
<div class="message-big">
<br/><br/><br/>
The album has been removed
<br/><br/><br/>
</div>
</div>
<!--
}
@else if (itemIsNotFound) {
<div class="fill-all">
<div class="message-big">
<br/><br/><br/>
The album does not exist
<br/><br/><br/>
</div>
</div>
}
@else if (itemIsLoading) {
<div class="fill-all">
<div class="message-big">
<br/><br/><br/>
Loading ...<br/>
Please wait.
<br/><br/><br/>
</div>
</div>
}
@else {
<div class="fill-all">
<div class="request_raw">
<div class="label">
<i class="material-icons">date_range</i> Date:
name:
</div>
<div class="input">
<input type="number"
pattern="[0-9]{0-4}"
placeholder="2112"
[value]="data.time"
(input)="onDate($event.target)"/>
<input type="text"
placeholder="Name of the album"
[value]="nameAlbum"
(input)="onName($event.target.value)"
/>
</div>
</div>
-->
<div class="request_raw">
<div class="label">
Description:
</div>
<div class="input">
<input type="text"
placeholder="Description of the Media"
[value]="description"
(input)="onDescription($event.target.value)"/>
</div>
</div>
<div class="send_value">
<button class="button fill-x color-button-validate color-shadow-black" (click)="sendValues()" type="submit"><i class="material-icons">save_alt</i> Save</button>
</div>
<div class="clear"></div>
</div>
<!-- ------------------------- Cover section --------------------------------- -->
<div class="title" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
Covers
</div>
<div class="fill-all" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
<div class="hide-element">
<input type="file"
#fileInput
(change)="onChangeCover($event.target)"
placeholder="Select a cover file"
accept=".png,.jpg,.jpeg,.webp"/>
</div>
<div class="request_raw">
<div class="input">
<div class="cover" *ngFor="let element of coversDisplay">
<div class="cover-image">
<img src="{{element.url}}"/>
<!--
<div class="request_raw">
<div class="label">
<i class="material-icons">date_range</i> Date:
</div>
<div class="cover-button">
<button (click)="removeCover(element.id)">
<i class="material-icons button-remove">highlight_off</i>
<div class="input">
<input type="number"
pattern="[0-9]{0-4}"
placeholder="2112"
[value]="data.time"
(input)="onDate($event.target)"/>
</div>
</div>
-->
<div class="request_raw">
<div class="label">
Description:
</div>
<div class="input">
<input type="text"
placeholder="Description of the Media"
[value]="description"
(input)="onDescription($event.target.value)"/>
</div>
</div>
<div class="send_value">
<button class="button fill-x color-button-validate color-shadow-black" (click)="sendValues()" type="submit"><i class="material-icons">save_alt</i> Save</button>
</div>
<div class="clear"></div>
</div>
<!-- ------------------------- Cover section --------------------------------- -->
<div class="title">
Covers
</div>
<div class="fill-all">
<div class="hide-element">
<input type="file"
#fileInput
(change)="onChangeCover($event.target)"
placeholder="Select a cover file"
accept=".png,.jpg,.jpeg,.webp"/>
</div>
<div class="request_raw">
<div class="input">
@for (element of coversDisplay; track element.id;) {
<div class="cover">
<div class="cover-image">
<img src="{{element.url}}"/>
</div>
<div class="cover-button">
<button (click)="removeCover(element.id)">
<i class="material-icons button-remove">highlight_off</i>
</button>
</div>
</div>
}
<div class="cover">
<div class="cover-no-image">
</div>
<div class="cover-button">
<button (click)="fileInput.click()">
<i class="material-icons button-add">add_circle_outline</i>
</button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<!-- ------------------------- ADMIN section --------------------------------- -->
<div class="title">
Administration
</div>
<div class="fill-all">
<div class="request_raw">
<div class="label">
<i class="material-icons">data_usage</i> ID:
</div>
<div class="input">
{{idAlbum}}
</div>
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
Tracks:
</div>
<div class="input">
{{trackCount}}
</div>
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
<i class="material-icons">delete_forever</i> Trash:
</div>
@if(trackCount == '0') {
<div class="input">
<button class="button color-button-cancel color-shadow-black" (click)="removeItem()" type="submit">
<i class="material-icons">delete</i> Remove album
</button>
</div>
</div>
<div class="cover">
<div class="cover-no-image">
}
@else {
<div class="input">
<i class="material-icons">new_releases</i> Can not remove album, track depending on it
</div>
<div class="cover-button">
<button (click)="fileInput.click()">
<i class="material-icons button-add">add_circle_outline</i>
</button>
</div>
</div>
}
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<!-- ------------------------- ADMIN section --------------------------------- -->
<div class="title" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
Administration
</div>
<div class="fill-all" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
<div class="request_raw">
<div class="label">
<i class="material-icons">data_usage</i> ID:
</div>
<div class="input">
{{idAlbum}}
</div>
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
Tracks:
</div>
<div class="input">
{{trackCount}}
</div>
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
<i class="material-icons">delete_forever</i> Trash:
</div>
<div class="input" *ngIf="(trackCount == '0')">
<button class="button color-button-cancel color-shadow-black" (click)="removeItem()" type="submit">
<i class="material-icons">delete</i> Remove album
</button>
</div>
<div class="input" *ngIf="(trackCount != '0')">
<i class="material-icons">new_releases</i> Can not remove album, track depending on it
</div>
</div>
<div class="clear"></div>
</div>
}
</div>
<upload-progress [mediaTitle]="upload.labelMediaTitle"
[mediaUploaded]="upload.mediaSendSize"

View File

@@ -5,12 +5,11 @@
*/
import { Component, OnInit } from '@angular/core';
import { UploadProgress, PopInService } from '@kangaroo-and-rabbit/kar-cw';
import { Album } from 'app/back-api';
import { AlbumService, ArianeService, DataService } from 'app/service';
import { NodeData } from 'common/model';
import { AlbumService, ArianeService, DataService, TrackService } from 'app/service';
import { UploadProgress } from 'common/popin/upload-progress/upload-progress';
import { PopInService } from 'common/service';
export interface ElementList {
value: number;
@@ -45,7 +44,7 @@ export class AlbumEditScene implements OnInit {
// --------------- confirm section ------------------
public confirmDeleteComment: string = null;
public confirmDeleteImageUrl: string = null;
private deleteCoverId: number = null;
private deleteCoverId: string = null;
private deleteItemId: number = null;
deleteConfirmed() {
if (this.deleteCoverId !== null) {
@@ -67,6 +66,7 @@ export class AlbumEditScene implements OnInit {
constructor(
private albumService: AlbumService,
private trackService: TrackService,
private arianeService: ArianeService,
private popInService: PopInService,
private dataService: DataService) {
@@ -77,7 +77,7 @@ export class AlbumEditScene implements OnInit {
this.idAlbum = this.arianeService.getAlbumId();
let self = this;
this.albumService.get(this.idAlbum)
.then((response: NodeData) => {
.then((response: Album) => {
console.log(`get response of album : ${JSON.stringify(response, null, 2)}`);
self.nameAlbum = response.name;
self.description = response.description;
@@ -91,7 +91,7 @@ export class AlbumEditScene implements OnInit {
self.itemIsNotFound = true;
self.itemIsLoading = false;
});
this.albumService.getTrack(this.idAlbum)
this.trackService.getTracksWithAlbumId(this.idAlbum)
.then((response: any) => {
self.trackCount = response.length;
}).catch((response: any) => {
@@ -105,7 +105,7 @@ export class AlbumEditScene implements OnInit {
for (let iii = 0; iii < covers.length; iii++) {
this.coversDisplay.push({
id: covers[iii],
url: this.dataService.getCoverThumbnailUrl(covers[iii])
url: this.dataService.getThumbnailUrl(covers[iii])
});
}
} else {
@@ -165,7 +165,7 @@ export class AlbumEditScene implements OnInit {
this.upload.clear();
// display the upload pop-in
this.popInService.open('popin-upload-progress');
this.albumService.uploadCover(file, this.idAlbum, (count, total) => {
this.albumService.uploadCover(this.idAlbum, file, (count, total) => {
self.upload.mediaSendSize = count;
self.upload.mediaSize = total;
})
@@ -179,14 +179,14 @@ export class AlbumEditScene implements OnInit {
});
}
removeCover(id: number) {
removeCover(id: string) {
this.cleanConfirm();
this.confirmDeleteComment = `Delete the cover ID: ${id}`;
this.confirmDeleteImageUrl = this.dataService.getCoverThumbnailUrl(id);
this.confirmDeleteImageUrl = this.dataService.getThumbnailUrl(id);
this.deleteCoverId = id;
this.popInService.open('popin-delete-confirm');
}
removeCoverAfterConfirm(id: number) {
removeCoverAfterConfirm(id: string) {
console.log(`Request remove cover: ${id}`);
let self = this;
this.albumService.deleteCover(this.idAlbum, id)

View File

@@ -1,40 +1,26 @@
<div class="generic-page">
<div class="fill-title colomn_mutiple">
<div class="cover-area">
<div class="cover" *ngIf="covers" >
<img src="{{covers[0]}}"/>
</div>
<description-area
[title]="name"
[name]="albumName"
[description]="albumDescription"
[cover1]="artistCovers"
[cover2]="albumCovers"
(play)="playAll()"
(shuffle)="playShuffle()"/>
@if (tracks) {
<div class="fill-content colomn_single">
<div class="clear"></div>
<div class="title">Track{{tracks.length > 1?"s":""}}:</div>
@for (data of tracks; track data.id;) {
<app-element-track
[element]="data"
(click)="onSelectTrack($event, data.id)"
(auxclick)="onSelectTrack($event, data.id)"/>
} @empty {
Aucune piste accessible.
}
</div>
<div [className]="covers ? 'description-area description-area-cover' : 'description-area description-area-no-cover'">
<div class="title">
{{name}}
</div>
<div class="title">
{{albumName}}
</div>
<div class="description" *ngIf="albumDescription">
{{albumDescription}}
</div>
<div class="description" *ngIf="albumDescription">
{{albumDescription}}
</div>
<button class="button color-button color-shadow-black" (click)="playAll($event)" type="submit">
<i class="material-icons">play_arrow</i> Play All
</button>
<button class="button color-button color-shadow-black" style="margin-left:10px;" (click)="playShuffe($event)" type="submit">
<i class="material-icons">shuffle</i> Shuffle
</button>
</div>
</div>
<div class="fill-content colomn_mutiple" *ngIf="tracks">
<div class="clear"></div>
<div class="title" *ngIf="tracks.length > 1">Tracks:</div>
<div class="title" *ngIf="tracks.length == 1">Track:</div>
<app-element-track
*ngFor="let data of tracks"
[element]="data"
(click)="onSelectTrack($event, data.id)"
(auxclick)="onSelectTrack($event, data.id)"></app-element-track>
</div>
}
<div class="clear-end"></div>
</div>
</div>

View File

@@ -4,117 +4,127 @@
* @license PROPRIETARY (see license file)
*/
import { Component, OnInit } from '@angular/core';
import { Media } from 'app/model';
import { ArtistService, DataService, ArianeService, AlbumService, TrackService, PlayerService } from 'app/service';
@Component({
selector: 'app-album',
templateUrl: './album.html'
})
export class AlbumScene implements OnInit {
public idArtist = -1;
public idAlbum = -1;
public name: string = '';
public description: string = undefined;
public covers: Array<string> = undefined;
public albumName: string = '';
public albumDescription: string = undefined;
public albumCovers: string[] = undefined;
public tracksIds: number[] = undefined;
public tracks: Media[] = undefined;
constructor(
private artistService: ArtistService,
private albumService: AlbumService,
private trackService: TrackService,
private arianeService: ArianeService,
private playerService: PlayerService,
private dataService: DataService) {
}
ngOnInit() {
// this.idPlaylist = parseInt(this.route.snapshot.paramMap.get('universId'));
// this.idType = parseInt(this.route.snapshot.paramMap.get('typeId'));
this.idArtist = this.arianeService.getArtistId();
this.idAlbum = this.arianeService.getAlbumId();
let self = this;
this.artistService.get(this.idArtist)
.then((response) => {
self.name = response.name;
self.description = response.description;
self.covers = this.dataService.getCoverListUrl(response.covers);
}).catch((response) => {
self.description = undefined;
self.name = '???';
self.covers = undefined;
// no check just ==> an error occured on album
});
this.albumService.get(this.idAlbum)
.then((response) => {
self.albumName = response.name;
self.albumDescription = response.description;
self.albumCovers = this.dataService.getCoverListUrl(response.covers);
}).catch((response) => {
self.albumDescription = undefined;
self.albumName = '???';
self.albumCovers = undefined;
// no check just ==> an error occured on album
});
//console.log("all the tracks: " + self.tracksIds);
this.trackService.getWithAlbum(self.idAlbum)
.then((response2: Media[]) => {
self.tracks = response2;
//console.log(`>>>>BBB get tracks : ${JSON.stringify(response2, null, 2)}`);
}).catch((response) => {
//console.log(`>>>>BBB plop`);
self.tracks = undefined;
});
}
onSelectTrack(event: any, idSelected: number):void {
if (event.ctrlKey === false) {
//this.arianeService.navigateTrack({trackId: idSelected, newWindows:event.which === 2} );
// TODO: add on global player ...
//this.playerService.play(idSelected);
let elements: number[] = [];
let valuePlayed: number = undefined;
for (let iii=0; iii< this.tracks.length; iii++) {
elements.push(this.tracks[iii].id);
//console.log(`plop: ${this.tracks[iii].id} == ${idSelected} ==> ${this.tracks[iii].name}`);
if (this.tracks[iii].id == idSelected) {
//console.log(` ==> find`);
valuePlayed = iii;
}
}
this.playerService.playInList(valuePlayed, elements);
} else {
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows:event.which === 2} );
}
}
playAll(event: any):void {
import { Component, OnInit } from '@angular/core';
import { Album, Track } from 'app/back-api';
import { arrayUnique } from '@kangaroo-and-rabbit/kar-cw';
import { ArtistService, DataService, ArianeService, AlbumService, TrackService, PlayerService } from 'app/service';
@Component({
selector: 'app-album',
templateUrl: './album.html',
})
export class AlbumScene implements OnInit {
public artistIds: number[] = [];
public idAlbum: number = -1;
public name: string = '???';
public description: string = undefined;
public artistCovers: Array<string> = undefined;
public albumName: string = '';
public albumDescription: string = undefined;
public albumCovers: string[] = undefined;
public tracksIds: number[] = undefined;
public tracks: Track[] = undefined;
constructor(
private artistService: ArtistService,
private albumService: AlbumService,
private trackService: TrackService,
private arianeService: ArianeService,
private playerService: PlayerService,
private dataService: DataService) {
}
ngOnInit() {
//this.artistIds = [this.arianeService.getArtistId()];
this.idAlbum = this.arianeService.getAlbumId();
let self = this;
this.albumService.get(this.idAlbum)
.then((response) => {
self.albumName = response.name;
self.albumDescription = response.description;
self.albumCovers = this.dataService.getListUrl(response.covers);
}).catch((error) => {
self.albumDescription = undefined;
self.albumName = '???';
self.albumCovers = undefined;
// no check just ==> an error occurred on album
});
console.log(`all the tracks for a specific album: ${self.idAlbum}`);
this.trackService.getTracksWithAlbumId(self.idAlbum)
.then((response2: Track[]) => {
self.tracks = response2;
console.log(`get tracks : ${JSON.stringify(self.tracks, null, 2)}`);
self.artistIds = []
self.tracks.forEach(element => {
self.artistIds = [...self.artistIds, ...element.artists];
});
self.artistIds = arrayUnique(self.artistIds);
if (self.artistIds.length === 0) {
console.error("No artist found !!!");
return;
} else if (self.artistIds.length > 1) {
console.error("More than 1 artist ==> not managed");
}
/*
// TODO: display more than 1 ...
self.artistService.get(self.artistIds[0])
.then((response) => {
self.name = response.name;
self.description = response.description;
self.artistCovers = self.dataService.getListUrl(response.covers);
}).catch((error) => {
self.description = undefined;
self.name = '???';
self.artistCovers = undefined;
});
*/
//console.log(`>>>>BBB get tracks : ${JSON.stringify(response2, null, 2)}`);
}).catch((response) => {
//console.log(`>>>>BBB plop`);
self.tracks = undefined;
});
}
onSelectTrack(event: any, idSelected: number): void {
if (event.ctrlKey === false) {
//this.arianeService.navigateTrack({trackId: idSelected, newWindows:event.which === 2} );
// TODO: add on global player ...
//this.playerService.play(idSelected);
let elements: number[] = [];
let valuePlayed: number = undefined;
for (let iii = 0; iii < this.tracks.length; iii++) {
elements.push(this.tracks[iii].id);
//console.log(`plop: ${this.tracks[iii].id} == ${idSelected} ==> ${this.tracks[iii].name}`);
if (this.tracks[iii].id == idSelected) {
//console.log(` ==> find`);
valuePlayed = iii;
}
}
this.playerService.playInList(valuePlayed, elements);
} else {
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows: event.which === 2 });
}
}
playAll(): void {
let elements: number[] = [];
for (let iii=0; iii< this.tracks.length; iii++) {
for (let iii = 0; iii < this.tracks.length; iii++) {
elements.push(this.tracks[iii].id);
}
this.playerService.clear();
this.playerService.setNewPlaylist(elements);
}
playShuffe(event: any):void {
}
playShuffle(): void {
let elements: number[] = [];
for (let iii=0; iii< this.tracks.length; iii++) {
for (let iii = 0; iii < this.tracks.length; iii++) {
elements.push(this.tracks[iii].id);
}
this.playerService.clear();
this.playerService.setNewPlaylistShuffle(elements);
}
}
}
}

View File

@@ -1,48 +1,40 @@
<div class="generic-page">
<div class="fill-title colomn_mutiple">
<div class="cover-area">
<div class="cover" *ngIf="covers" >
<img src="{{covers[0]}}"/>
</div>
<description-area
[title]="name"
[description]="description"
[cover1]="covers"
(play)="playAll()"
(shuffle)="playShuffle()"/>
@if(albums) {
<div class="fill-content colomn_single">
<div class="clear"></div>
<div class="title">Album{{albums.length > 1?"s":""}}: <app-entry placeholder="Search..." (changeValue)="onSearch($event)"></app-entry></div>
@for (data of albums; track data.id;) {
<div class="item-list"
(click)="onSelectAlbum($event, data.id)"
(auxclick)="onSelectAlbum($event, data.id)"
>
<app-element-season
[element]="data"
countSubType="Track"
[countSubTypeCallBack]="countTrack"
subValues="Artist"
[subValuesCallBack]="getArtistsString"/>
</div>
}
</div>
<div [className]="covers ? 'description-area description-area-cover' : 'description-area description-area-no-cover'">
<div class="title">
{{name}}
</div>
<div class="description" *ngIf="description">
{{description}}
</div>
<button class="button color-button color-shadow-black" (click)="playAll($event)" type="submit">
<i class="material-icons">play_arrow</i> Play All
</button>
<button class="button color-button color-shadow-black" style="margin-left:10px;" (click)="playShuffe($event)" type="submit">
<i class="material-icons">shuffle</i> Shuffle
</button>
}
@if(tracks) {
<div class="fill-content colomn_mutiple">
<div class="clear"></div>
<div class="title">Track{{tracks.length > 1?"s":""}}:</div>
@for (data of tracks; track data.id;) {
<div class="item item-video" (click)="onSelectTrack($event, data.id)" (auxclick)="onSelectTrack($event, data.id)">
<app-element-video
[element]="data"/>
</div>
}
</div>
</div>
<div class="fill-content colomn_mutiple" *ngIf="albums">
<div class="clear"></div>
<div class="title" *ngIf="albums.length > 1">Albums:</div>
<div class="title" *ngIf="albums.length == 1">Album:</div>
<div *ngFor="let data of albums" class="item-list" (click)="onSelectAlbum($event, data.id)" (auxclick)="onSelectAlbum($event, data.id)">
<app-element-season
[element]="data"
countSubType="Track"
[countSubTypeCallBack]="countTrack"
subValues="Artist"
[subValuesCallBack]="getArtistsString"
></app-element-season>
</div>
</div>
<div class="fill-content colomn_mutiple" *ngIf="tracks">
<div class="clear"></div>
<div class="title" *ngIf="tracks.length > 1">Tracks:</div>
<div class="title" *ngIf="tracks.length == 1">Track:</div>
<div *ngFor="let data of tracks" class="item item-video" (click)="onSelectTrack($event, data.id)" (auxclick)="onSelectTrack($event, data.id)">
<app-element-video
[element]="data"
></app-element-video>
</div>
</div>
}
<div class="clear-end"></div>
</div>

View File

@@ -4,118 +4,139 @@
* @license PROPRIETARY (see license file)
*/
import { Component, OnInit } from '@angular/core';
import { ArtistService, DataService, ArianeService, AlbumService, PlayerService, TrackService } from 'app/service';
import { NodeData } from 'common/model';
@Component({
selector: 'app-albums',
templateUrl: './albums.html'
})
export class AlbumsScene implements OnInit {
import { Component, OnInit } from '@angular/core';
import { DataTools } from '@kangaroo-and-rabbit/kar-cw';
import { Album, Artist, Track } from 'app/back-api';
import { ArtistService, DataService, ArianeService, AlbumService, PlayerService, TrackService } from 'app/service';
@Component({
selector: 'app-albums',
templateUrl: './albums.html'
})
export class AlbumsScene implements OnInit {
public name: string = '';
public description: string = undefined;
public covers: string[] = undefined;
public albums: NodeData[] = undefined;
public albums: Album[] = undefined;
public albumsSave: Album[] = undefined;
public tracks: any[] = undefined;
public countSubElement: number = undefined;
countTrack: (id: number) => Promise<Number>;
getArtistsString: (id: number) => Promise<String[]>;
constructor(
private albumService: AlbumService,
private artistService: ArtistService,
private arianeService: ArianeService,
private trackService: TrackService,
private playerService: PlayerService,
private dataService: DataService) {
private albumService: AlbumService,
private artistService: ArtistService,
private arianeService: ArianeService,
private trackService: TrackService,
private playerService: PlayerService,
private dataService: DataService) {
}
countTrackCallback(albumId: number) : Promise<Number> {
return this.albumService.countTrack(albumId);
}
getArtistsStringCallback(albumId: number) : Promise<String[]> {
countTrackCallback(albumId: number): Promise<Number> {
return this.trackService.countTracksWithAlbumId(albumId);
}
getArtistsStringCallback(albumId: number): Promise<String[]> {
//console.log(`request all artist for album: {albumId}`)
return this.albumService.getArtists(albumId);
let self = this;
return new Promise((resolve, reject) => {
self.trackService.getTracksWithAlbumId(albumId)
.then((response: Track[]) => {
const listArtists = DataTools.extractLimitOneList(response, "artists");
self.artistService.getAll(listArtists)
.then((listArtists: Artist[]) => {
resolve(DataTools.extractLimitOne(listArtists, "name"));
}).catch((error) => {
resolve([">> ERROR 1 <<"]);
})
}).catch((error) => {
resolve([">> ERROR 2 <<"]);
});
});
}
ngOnInit() {
this.getArtistsString = (id:number) => {return self.getArtistsStringCallback(id);};
this.countTrack = (id:number) => {return self.countTrackCallback(id);};
let self = this;
self.name = "All Albums";
self.description = "View all albums (no specific artist)";
//console.log(`get parameter id: ${ this.idArtist}`);
this.albumService.getOrder()
.then((response: NodeData[]) => {
//console.log(`>>>> get album : ${JSON.stringify(response)}`)
self.albums = response;
}).catch((response) => {
self.albums = undefined;
});
// TODO later: get all orfan tracks ...
/*
this.artistService.getTrack(this.idArtist)
.then((response: NodeData[]) => {
//console.log(`>>>> get track : ${JSON.stringify(response)}`)
self.tracks = response;
}).catch((response) => {
self.tracks = undefined;
});
*/
}
onSelectAlbum(event: any, idSelected: number):void {
const self = this;
this.getArtistsString = (id: number) => { return self.getArtistsStringCallback(id); };
this.countTrack = (id: number) => { return self.countTrackCallback(id); };
self.name = "All Albums";
self.description = "View all albums (no specific artist)";
//console.log(`get parameter id: ${ this.idArtist}`);
this.albumService.getOrder()
.then((response: Album[]) => {
//console.log(`>>>> get album : ${JSON.stringify(response)}`)
self.albums = response;
self.albumsSave = [...response];
}).catch((response) => {
self.albums = undefined;
});
// TODO later: get all orfans tracks ...
/*
this.artistService.getTrack(this.idArtist)
.then((response: NodeData[]) => {
//console.log(`>>>> get track : ${JSON.stringify(response)}`)
self.tracks = response;
}).catch((response) => {
self.tracks = undefined;
});
*/
}
onSearch(value: string) {
console.log(`Search value: ${value}`);
this.albums = this.albumsSave.filter(element => {
return element.name.toLowerCase().includes(value.toLowerCase());;
})
}
onSelectAlbum(event: any, idSelected: number): void {
if (event.ctrlKey) {
this.arianeService.navigateAlbumEdit({ id: idSelected, newWindows: event.which === 2 } );
this.arianeService.navigateAlbumEdit({ id: idSelected, newWindows: event.which === 2 });
} else {
this.arianeService.navigateAlbum({albumId: idSelected, newWindows: event.which === 2 } );
this.arianeService.navigateAlbum({ albumId: idSelected, newWindows: event.which === 2 });
}
}
onSelectTrack(event: any, idSelected: number):void {
if (event.ctrlKey) {
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows:event.which === 2} );
} else {
this.arianeService.navigateTrack({trackId: idSelected, newWindows:event.which === 2} );
}
}
playAll(event: any):void {
this.playerService.clear();
let self = this;
this.trackService.getData()
.then((response: NodeData[]) => {
let ids = [];
response.forEach(element => {
ids.push(element.id);
});
self.playerService.setNewPlaylist(ids);
})
.catch(() => {
console.log(`error to get list o ftrack ...`)
});
}
playShuffe(event: any):void {
this.playerService.clear();
let self = this;
this.trackService.getData()
.then((response: NodeData[]) => {
let ids = [];
response.forEach(element => {
ids.push(element.id);
});
self.playerService.setNewPlaylistShuffle(ids);
})
.catch(() => {
console.log(`error to get list o ftrack ...`)
});
}
}
}
onSelectTrack(event: any, idSelected: number): void {
if (event.ctrlKey) {
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows: event.which === 2 });
} else {
this.arianeService.navigateTrack({ trackId: idSelected, newWindows: event.which === 2 });
}
}
playAll(): void {
this.playerService.clear();
let self = this;
this.trackService.gets()
.then((response: Track[]) => {
let ids = [];
response.forEach(element => {
ids.push(element.id);
});
self.playerService.setNewPlaylist(ids);
})
.catch(() => {
console.log(`error to get list o ftrack ...`)
});
}
playShuffle(): void {
this.playerService.clear();
let self = this;
this.trackService.gets()
.then((response: Track[]) => {
let ids = [];
response.forEach(element => {
ids.push(element.id);
});
self.playerService.setNewPlaylistShuffle(ids);
})
.catch(() => {
console.log(`error to get list o ftrack ...`)
});
}
}

View File

@@ -2,153 +2,156 @@
<div class="title">
Edit artist
</div>
<div class="fill-all" *ngIf="itemIsRemoved">
<div class="message-big">
<br/><br/><br/>
The artist has been removed
<br/><br/><br/>
</div>
</div>
<div class="fill-all" *ngIf="itemIsNotFound">
<div class="message-big">
<br/><br/><br/>
The artist does not exist
<br/><br/><br/>
</div>
</div>
<div class="fill-all" *ngIf="itemIsLoading">
<div class="message-big">
<br/><br/><br/>
Loading ...<br/>
Please wait.
<br/><br/><br/>
</div>
</div>
<div class="fill-all" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
<div class="request_raw">
<div class="label">
Type:
</div>
<div class="input">
<select [ngModel]="typeId"
(ngModelChange)="onChangeType($event)">
<option *ngFor="let element of listType" [ngValue]="element.value">{{element.label}}</option>
</select>
@if(itemIsRemoved) {
<div class="fill-all">
<div class="message-big">
<br/><br/><br/>
The artist has been removed
<br/><br/><br/>
</div>
</div>
<div class="request_raw">
<div class="label">
Name:
</div>
<div class="input">
<input type="text"
placeholder="Name of the Artist"
[value]="name"
(input)="onName($event.target.value)"
/>
}
@else if (itemIsNotFound) {
<div class="fill-all">
<div class="message-big">
<br/><br/><br/>
The artist does not exist
<br/><br/><br/>
</div>
</div>
<div class="request_raw">
<div class="label">
Description:
</div>
<div class="input">
<input type="text"
placeholder="Description of the Media"
[value]="description"
(input)="onDescription($event.target.value)"/>
}
@else if (itemIsLoading) {
<div class="fill-all">
<div class="message-big">
<br/><br/><br/>
Loading ...<br/>
Please wait.
<br/><br/><br/>
</div>
</div>
<div class="clear"></div>
<div class="send_value">
<button class="button fill-x color-button-validate color-shadow-black" (click)="sendValues()" type="submit"><i class="material-icons">save_alt</i> Save</button>
</div>
<div class="clear"></div>
</div>
<!-- ------------------------- Cover section --------------------------------- -->
<div class="title" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
Covers
</div>
<div class="fill-all" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
<div class="hide-element">
<input type="file"
#fileInput
(change)="onChangeCover($event.target)"
placeholder="Select a cover file"
accept=".png,.jpg,.jpeg,.webp"/>
</div>
<div class="request_raw">
<div class="input">
<div class="cover" *ngFor="let element of coversDisplay">
<div class="cover-image">
<img src="{{element.url}}"/>
</div>
<div class="cover-button">
<button (click)="removeCover(element.id)">
<i class="material-icons button-remove">highlight_off</i>
</button>
</div>
}
@else {
<div class="fill-all">
<div class="request_raw">
<div class="label">
Name:
</div>
<div class="cover">
<div class="cover-no-image">
</div>
<div class="cover-button">
<button (click)="fileInput.click()">
<i class="material-icons button-add">add_circle_outline</i>
</button>
<div class="input">
<input type="text"
placeholder="Name of the Artist"
[value]="name"
(input)="onName($event.target.value)"
/>
</div>
</div>
<div class="request_raw">
<div class="label">
Description:
</div>
<div class="input">
<input type="text"
placeholder="Description of the Media"
[value]="description"
(input)="onDescription($event.target.value)"/>
</div>
</div>
<div class="clear"></div>
<div class="send_value">
<button class="button fill-x color-button-validate color-shadow-black" (click)="sendValues()" type="submit"><i class="material-icons">save_alt</i> Save</button>
</div>
<div class="clear"></div>
</div>
<!-- ------------------------- Cover section --------------------------------- -->
<div class="title">
Covers
</div>
<div class="fill-all">
<div class="hide-element">
<input type="file"
#fileInput
(change)="onChangeCover($event.target)"
placeholder="Select a cover file"
accept=".png,.jpg,.jpeg,.webp"/>
</div>
<div class="request_raw">
<div class="input">
@for (element of coversDisplay; track element.id;) {
<div class="cover">
<div class="cover-image">
<img src="{{element.url}}"/>
</div>
<div class="cover-button">
<button (click)="removeCover(element.id)">
<i class="material-icons button-remove">highlight_off</i>
</button>
</div>
</div>
}
<div class="cover">
<div class="cover-no-image">
</div>
<div class="cover-button">
<button (click)="fileInput.click()">
<i class="material-icons button-add">add_circle_outline</i>
</button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</div>
<!-- ------------------------- ADMIN section --------------------------------- -->
<div class="title" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
Administration
</div>
<div class="fill-all" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
<div class="request_raw">
<div class="label">
<i class="material-icons">data_usage</i> ID:
</div>
<div class="input">
{{idArtist}}
</div>
<!-- ------------------------- ADMIN section --------------------------------- -->
<div class="title">
Administration
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
Albums:
<div class="fill-all">
<div class="request_raw">
<div class="label">
<i class="material-icons">data_usage</i> ID:
</div>
<div class="input">
{{idArtist}}
</div>
</div>
<div class="input">
{{albumsCount}}
<div class="clear"></div>
<div class="request_raw">
<div class="label">
Albums:
</div>
<div class="input">
{{albumsCount}}
</div>
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
Tracks:
</div>
<div class="input">
{{trackCount}}
</div>
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
<i class="material-icons">delete_forever</i> Trash:
</div>
@if(trackCount == '0' && albumsCount == '0') {
<div class="input">
<button class="button color-button-cancel color-shadow-black" (click)="removeItem()" type="submit">
<i class="material-icons">delete</i> Remove Artist
</button>
</div>
}
@else {
<div class="input">
<i class="material-icons">new_releases</i> Can not remove album or track depending on it
</div>
}
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
Tracks:
</div>
<div class="input">
{{trackCount}}
</div>
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
<i class="material-icons">delete_forever</i> Trash:
</div>
<div class="input" *ngIf="(trackCount == '0' && albumsCount == '0')">
<button class="button color-button-cancel color-shadow-black" (click)="removeItem()" type="submit">
<i class="material-icons">delete</i> Remove Artist
</button>
</div>
<div class="input" *ngIf="(trackCount != '0' || albumsCount != '0')">
<i class="material-icons">new_releases</i> Can not remove album or track depending on it
</div>
</div>
<div class="clear"></div>
</div>
}
</div>
<upload-progress [mediaTitle]="upload.labelMediaTitle"

View File

@@ -5,10 +5,10 @@
*/
import { Component, OnInit } from '@angular/core';
import { PopInService, UploadProgress } from '@kangaroo-and-rabbit/kar-cw';
import { Artist, Track } from 'app/back-api';
import { ArtistService, DataService, GenderService, ArianeService } from 'app/service';
import { UploadProgress } from 'common/popin/upload-progress/upload-progress';
import { PopInService } from 'common/service';
import { ArtistService, DataService, GenderService, ArianeService, TrackService } from 'app/service';
export class ElementList {
constructor(
@@ -31,7 +31,6 @@ export class ArtistEditScene implements OnInit {
error: string = '';
typeId: number = null;
name: string = '';
description: string = '';
coverFile: File;
@@ -45,15 +44,10 @@ export class ArtistEditScene implements OnInit {
// section tha define the upload value to display in the pop-in of upload
public upload: UploadProgress = new UploadProgress();
listType: ElementList[] = [
{ value: undefined, label: '---' },
];
// --------------- confirm section ------------------
public confirmDeleteComment: string = null;
public confirmDeleteImageUrl: string = null;
private deleteCoverId: number = null;
private deleteCoverId: string = null;
private deleteItemId: number = null;
deleteConfirmed() {
if (this.deleteCoverId !== null) {
@@ -74,8 +68,9 @@ export class ArtistEditScene implements OnInit {
constructor(private dataService: DataService,
private typeService: GenderService,
private genderService: GenderService,
private artistService: ArtistService,
private trackService: TrackService,
private arianeService: ArianeService,
private popInService: PopInService) {
@@ -84,22 +79,11 @@ export class ArtistEditScene implements OnInit {
ngOnInit() {
this.idArtist = this.arianeService.getArtistId();
let self = this;
this.listType = [{ value: null, label: '---' }];
this.typeService.getData()
.then((response2) => {
for (let iii = 0; iii < response2.length; iii++) {
self.listType.push({ value: response2[iii].id, label: response2[iii].name });
}
}).catch((response2) => {
console.log(`get response22 : ${JSON.stringify(response2, null, 2)}`);
});
this.artistService.get(this.idArtist)
.then((response) => {
.then((response: Artist) => {
// console.log("get response of track : " + JSON.stringify(response, null, 2));
self.name = response.name;
self.typeId = response.parentId;
self.description = response.description;
self.updateCoverList(response.covers);
// console.log("covers_list : " + JSON.stringify(self.covers_display, null, 2));
@@ -113,14 +97,14 @@ export class ArtistEditScene implements OnInit {
self.itemIsLoading = false;
});
console.log(`get parameter id: ${this.idArtist}`);
this.artistService.getAlbum(this.idArtist)
.then((response) => {
this.trackService.getAlbumIdsOfAnArtist(this.idArtist)
.then((response: number[]) => {
self.albumsCount = "" + response.length;
}).catch((response) => {
self.albumsCount = '---';
});
this.artistService.getAllTracks(this.idArtist)
.then((response) => {
this.trackService.getTracksOfAnArtist(this.idArtist)
.then((response: Track[]) => {
self.trackCount = "" + response.length;
}).catch((response) => {
self.trackCount = '---';
@@ -133,7 +117,7 @@ export class ArtistEditScene implements OnInit {
for (let iii = 0; iii < covers.length; iii++) {
this.coversDisplay.push({
id: covers[iii],
url: this.dataService.getCoverThumbnailUrl(covers[iii])
url: this.dataService.getThumbnailUrl(covers[iii])
});
}
} else {
@@ -149,18 +133,9 @@ export class ArtistEditScene implements OnInit {
this.description = value;
}
onChangeType(value: any): void {
console.log(`Change requested of type ... ${value}`);
this.typeId = value;
if (this.typeId === undefined) {
this.typeId = null;
}
}
sendValues(): void {
console.log('send new values....');
let data = {
parentId: this.typeId,
name: this.name,
description: this.description
};
@@ -203,7 +178,7 @@ export class ArtistEditScene implements OnInit {
this.upload.clear();
// display the upload pop-in
this.popInService.open('popin-upload-progress');
this.artistService.uploadCover(file, this.idArtist, (count, total) => {
this.artistService.uploadCover(this.idArtist, file, (count, total) => {
self.upload.mediaSendSize = count;
self.upload.mediaSize = total;
})
@@ -216,14 +191,14 @@ export class ArtistEditScene implements OnInit {
console.log('Can not add the cover in the track...');
});
}
removeCover(id: number) {
removeCover(id: string) {
this.cleanConfirm();
this.confirmDeleteComment = `Delete the cover ID: ${id}`;
this.confirmDeleteImageUrl = this.dataService.getCoverThumbnailUrl(id);
this.confirmDeleteImageUrl = this.dataService.getThumbnailUrl(id);
this.deleteCoverId = id;
this.popInService.open('popin-delete-confirm');
}
removeCoverAfterConfirm(id: number) {
removeCoverAfterConfirm(id: string) {
console.log(`Request remove cover: ${id}`);
let self = this;
this.artistService.deleteCover(this.idArtist, id)

View File

@@ -1,38 +1,25 @@
<div class="generic-page">
<div class="fill-title colomn_mutiple">
<div class="cover-area">
<div class="cover" *ngIf="covers" >
<img src="{{covers[0]}}"/>
</div>
</div>
<div [className]="covers ? 'description-area description-area-cover' : 'description-area description-area-no-cover'">
<div class="title">
{{name}}
</div>
<div class="title">
{{albumName}}
</div>
<div class="description" *ngIf="albumDescription">
{{albumDescription}}
</div>
<description-area
[title]="name"
[name]="albumName"
[description]="albumDescription"
[cover1]="artistCovers"
[cover2]="albumCovers"
(play)="playAll()"
(shuffle)="playShuffle()"/>
@if(tracks) {
<div class="fill-content colomn_single">
<div class="clear"></div>
<button class="button color-button color-shadow-black" (click)="playAll($event)" type="submit">
<i class="material-icons">play_arrow</i> Play All
</button>
<button class="button color-button color-shadow-black" style="margin-left:10px;" (click)="playShuffe($event)" type="submit">
<i class="material-icons">shuffle</i> Shuffle
</button>
<div class="title">Track{{tracks.length > 1?"s":""}}:</div>
@for (data of tracks; track data.id;) {
<app-element-track
[element]="data"
(click)="onSelectTrack($event, data.id)"
(auxclick)="onSelectTrack($event, data.id)"></app-element-track>
} @empty {
Aucune piste accessible.
}
</div>
</div>
<div class="fill-content colomn_mutiple" *ngIf="tracks">
<div class="clear"></div>
<div class="title" *ngIf="tracks.length > 1">Tracks:</div>
<div class="title" *ngIf="tracks.length == 1">Track:</div>
<app-element-track
*ngFor="let data of tracks"
[element]="data"
(click)="onSelectTrack($event, data.id)"
(auxclick)="onSelectTrack($event, data.id)"></app-element-track>
</div>
}
<div class="clear-end"></div>
</div>

View File

@@ -5,7 +5,7 @@
*/
import { Component, OnInit } from '@angular/core';
import { Media } from 'app/model';
import { Track } from 'app/back-api';
import { ArtistService, DataService, ArianeService, AlbumService, TrackService, PlayerService } from 'app/service';
@@ -19,27 +19,25 @@ export class ArtistAlbumScene implements OnInit {
public idAlbum = -1;
public name: string = '';
public description: string = undefined;
public covers: Array<string> = undefined;
public artistCovers: Array<string> = undefined;
public albumName: string = '';
public albumDescription: string = undefined;
public albumCovers: string[] = undefined;
public tracksIds: number[] = undefined;
public tracks: Media[] = undefined;
public tracks: Track[] = undefined;
constructor(
private artistService: ArtistService,
private albumService: AlbumService,
private trackService: TrackService,
private arianeService: ArianeService,
private playerService: PlayerService,
private artistService: ArtistService,
private albumService: AlbumService,
private trackService: TrackService,
private arianeService: ArianeService,
private playerService: PlayerService,
private dataService: DataService) {
}
ngOnInit() {
// this.idPlaylist = parseInt(this.route.snapshot.paramMap.get('universId'));
// this.idType = parseInt(this.route.snapshot.paramMap.get('typeId'));
this.idArtist = this.arianeService.getArtistId();
this.idAlbum = this.arianeService.getAlbumId();
let self = this;
@@ -47,28 +45,28 @@ export class ArtistAlbumScene implements OnInit {
.then((response) => {
self.name = response.name;
self.description = response.description;
self.covers = this.dataService.getCoverListUrl(response.covers);
self.artistCovers = this.dataService.getListUrl(response.covers);
}).catch((response) => {
self.description = undefined;
self.name = '???';
self.covers = undefined;
self.artistCovers = undefined;
// no check just ==> an error occured on album
});
this.albumService.get(this.idAlbum)
.then((response) => {
self.albumName = response.name;
self.albumDescription = response.description;
self.albumCovers = this.dataService.getCoverListUrl(response.covers);
self.albumCovers = this.dataService.getListUrl(response.covers);
}).catch((response) => {
self.albumDescription = undefined;
self.albumName = '???';
self.albumCovers = undefined;
// no check just ==> an error occured on album
});
//console.log("all the tracks: " + self.tracksIds);
this.trackService.getWithAlbum(self.idAlbum)
.then((response2: Media[]) => {
this.trackService.getTracksWithAlbumId(self.idAlbum)
.then((response2: Track[]) => {
self.tracks = response2;
//console.log(`>>>>BBB get tracks : ${JSON.stringify(response2, null, 2)}`);
}).catch((response) => {
@@ -77,7 +75,7 @@ export class ArtistAlbumScene implements OnInit {
});
}
onSelectTrack(event: any, idSelected: number):void {
onSelectTrack(event: any, idSelected: number): void {
if (event.ctrlKey === false) {
//this.arianeService.navigateTrack({trackId: idSelected, newWindows:event.which === 2} );
// TODO: add on global player ...
@@ -85,7 +83,7 @@ export class ArtistAlbumScene implements OnInit {
let elements: number[] = [];
let valuePlayed: number = undefined;
for (let iii=0; iii< this.tracks.length; iii++) {
for (let iii = 0; iii < this.tracks.length; iii++) {
elements.push(this.tracks[iii].id);
//console.log(`plop: ${this.tracks[iii].id} == ${idSelected} ==> ${this.tracks[iii].name}`);
if (this.tracks[iii].id == idSelected) {
@@ -96,23 +94,23 @@ export class ArtistAlbumScene implements OnInit {
this.playerService.playInList(valuePlayed, elements);
} else {
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows:event.which === 2} );
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows: event.which === 2 });
}
}
playAll(event: any):void {
let elements: number[] = [];
for (let iii=0; iii< this.tracks.length; iii++) {
elements.push(this.tracks[iii].id);
}
this.playerService.clear();
this.playerService.setNewPlaylist(elements);
playAll(): void {
let elements: number[] = [];
for (let iii = 0; iii < this.tracks.length; iii++) {
elements.push(this.tracks[iii].id);
}
this.playerService.clear();
this.playerService.setNewPlaylist(elements);
}
playShuffe(event: any):void {
let elements: number[] = [];
for (let iii=0; iii< this.tracks.length; iii++) {
elements.push(this.tracks[iii].id);
}
this.playerService.clear();
this.playerService.setNewPlaylistShuffle(elements);
playShuffle(): void {
let elements: number[] = [];
for (let iii = 0; iii < this.tracks.length; iii++) {
elements.push(this.tracks[iii].id);
}
this.playerService.clear();
this.playerService.setNewPlaylistShuffle(elements);
}
}

View File

@@ -1,46 +1,37 @@
<div class="generic-page">
<div class="fill-title colomn_mutiple">
<div class="cover-area">
<div class="cover" *ngIf="covers" >
<img src="{{covers[0]}}"/>
</div>
<description-area
[title]="name"
[description]="description"
[cover1]="covers"
(play)="playAll()"
(shuffle)="playShuffle()"/>
@if(albums) {
<div class="fill-content colomn_single">
<div class="clear"></div>
<div class="title">Album{{albums.length > 1?"s":""}}:</div>
@for (data of albums; track data.id;) {
<div class="item-list" (click)="onSelectAlbum($event, data.id)" (auxclick)="onSelectAlbum($event, data.id)">
<app-element-season
[element]="data"
countSubType="Track"
[countSubTypeCallBack]="countTrack"
></app-element-season>
</div>
}
</div>
<div [className]="covers ? 'description-area description-area-cover' : 'description-area description-area-no-cover'">
<div class="title">
{{name}}
</div>
<div class="description" *ngIf="description">
{{description}}
</div>
<button class="button color-button color-shadow-black" (click)="playAll($event)" type="submit">
<i class="material-icons">play_arrow</i> Play All
</button>
<button class="button color-button color-shadow-black" style="margin-left:10px;" (click)="playShuffe($event)" type="submit">
<i class="material-icons">shuffle</i> Shuffle
</button>
}
@if(tracks) {
<div class="fill-content colomn_mutiple">
<div class="clear"></div>
<div class="title">Track{{tracks.length > 1?"s":""}}:</div>
@for (data of tracks; track data.id;) {
<div class="item item-video" (click)="onSelectTrack($event, data.id)" (auxclick)="onSelectTrack($event, data.id)">
<app-element-video
[element]="data"
></app-element-video>
</div>
}
</div>
</div>
<div class="fill-content colomn_mutiple" *ngIf="albums">
<div class="clear"></div>
<div class="title" *ngIf="albums.length > 1">Albums:</div>
<div class="title" *ngIf="albums.length == 1">Album:</div>
<div *ngFor="let data of albums" class="item-list" (click)="onSelectAlbum($event, data.id)" (auxclick)="onSelectAlbum($event, data.id)">
<app-element-season
[element]="data"
countSubType="Track"
[countSubTypeCallBack]="countTrack"
></app-element-season>
</div>
</div>
<div class="fill-content colomn_mutiple" *ngIf="tracks">
<div class="clear"></div>
<div class="title" *ngIf="tracks.length > 1">Tracks:</div>
<div class="title" *ngIf="tracks.length == 1">Track:</div>
<div *ngFor="let data of tracks" class="item item-video" (click)="onSelectTrack($event, data.id)" (auxclick)="onSelectTrack($event, data.id)">
<app-element-video
[element]="data"
></app-element-video>
</div>
</div>
}
<div class="clear-end"></div>
</div>

View File

@@ -5,9 +5,9 @@
*/
import { Component, OnInit } from '@angular/core';
import { Album, Track } from 'app/back-api';
import { ArtistService, DataService, ArianeService, AlbumService, PlayerService } from 'app/service';
import { NodeData } from 'common/model';
import { ArtistService, DataService, ArianeService, AlbumService, PlayerService, TrackService } from 'app/service';
@Component({
selector: 'app-artist',
@@ -19,46 +19,51 @@ export class ArtistScene implements OnInit {
public name: string = '';
public description: string = undefined;
public covers: string[] = undefined;
public albums: NodeData[] = undefined;
public tracks: any[] = undefined;
public albums: Album[] = undefined;
public tracks: Track[] = undefined;
public countSubElement: number = undefined;
countTrack: (id: number) => Promise<Number>;
constructor(
private albumService: AlbumService,
private artistService: ArtistService,
private playerService: PlayerService,
private arianeService: ArianeService,
private albumService: AlbumService,
private artistService: ArtistService,
private playerService: PlayerService,
private trackService: TrackService,
private arianeService: ArianeService,
private dataService: DataService) {
}
countTrackCallback(albumId: number) : Promise<Number> {
return this.albumService.countTrack(albumId);
countTrackCallback(albumId: number): Promise<Number> {
return this.trackService.countTracksWithAlbumId(albumId);
}
ngOnInit() {
this.countTrack = (id:number) => {return self.countTrackCallback(id);};
this.countTrack = (id: number) => { return self.countTrackCallback(id); };
// this.idPlaylist = parseInt(this.route.snapshot.paramMap.get('universId'));
// this.idType = parseInt(this.route.snapshot.paramMap.get('typeId'));
this.idArtist = this.arianeService.getArtistId();
let self = this;
this.artistService.get(this.idArtist)
.then((response) => {
self.name = response.name;
self.description = response.description;
self.covers = this.dataService.getCoverListUrl(response.covers);
self.covers = this.dataService.getListUrl(response.covers);
}).catch((response) => {
self.name = '???';
self.description = undefined;
self.covers = undefined;
});
//console.log(`get parameter id: ${ this.idArtist}`);
this.artistService.getAlbum(this.idArtist)
.then((response: NodeData[]) => {
//console.log(`>>>> get album : ${JSON.stringify(response)}`)
self.albums = response;
this.trackService.getAlbumIdsOfAnArtist(this.idArtist)
.then((albumIds: number[]) => {
this.albumService.getAll(albumIds)
.then((response: Album[]) => {
//console.log(`>>>> get album : ${JSON.stringify(response)}`)
self.albums = response;
}).catch((response) => {
self.albums = undefined;
});
}).catch((response) => {
self.albums = undefined;
});
@@ -76,48 +81,48 @@ export class ArtistScene implements OnInit {
onSelectAlbum(event: any, idSelected: number):void {
onSelectAlbum(event: any, idSelected: number): void {
if (event.ctrlKey) {
this.arianeService.navigateAlbumEdit({ id: idSelected, newWindows: event.which === 2 } );
this.arianeService.navigateAlbumEdit({ id: idSelected, newWindows: event.which === 2 });
} else {
this.arianeService.navigateArtist({artistId: this.idArtist, albumId: idSelected, newWindows: event.which === 2 } );
this.arianeService.navigateArtist({ artistId: this.idArtist, albumId: idSelected, newWindows: event.which === 2 });
}
}
onSelectTrack(event: any, idSelected: number):void {
onSelectTrack(event: any, idSelected: number): void {
if (event.ctrlKey === false) {
this.arianeService.navigateTrack({trackId: idSelected, newWindows:event.which === 2} );
this.arianeService.navigateTrack({ trackId: idSelected, newWindows: event.which === 2 });
} else {
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows:event.which === 2} );
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows: event.which === 2 });
}
}
getAllTracksIds(): Promise<number[]> {
let elements: number[] = [];
for (let iii=0; iii< this.albums.length; iii++) {
for (let iii = 0; iii < this.albums.length; iii++) {
elements.push(this.albums[iii].id);
}
return this.albumService.getAllTracksForAlbums(elements);
return this.trackService.getTracksIdsForAlbums(elements);
}
playAll(event: any):void {
this.playerService.clear();
playAll(): void {
this.playerService.clear();
let self = this;
this.getAllTracksIds()
this.getAllTracksIds()
.then((response: number[]) => {
self.playerService.setNewPlaylist(response);
})
})
.catch(() => {
console.log(`error to get list o ftrack ...`)
});
}
playShuffe(event: any):void {
this.playerService.clear();
playShuffle(): void {
this.playerService.clear();
let self = this;
this.getAllTracksIds()
this.getAllTracksIds()
.then((response: number[]) => {
self.playerService.setNewPlaylistShuffle(response);
})
})
.catch(() => {
console.log(`error to get list o ftrack ...`)
});

View File

@@ -1,38 +1,26 @@
<div class="generic-page">
<div class="fill-title colomn_mutiple">
<div class="cover-area">
<div class="cover" *ngIf="covers" >
<img src="{{covers[0]}}"/>
</div>
<description-area
[title]="name"
[description]="description"
[cover1]="covers"
(play)="playAll()"
(shuffle)="playShuffle()"/>
@if(artists) {
<div class="fill-content colomn_single">
<div class="clear"></div>
<div class="title">Artist{{artists.length > 1?"s":""}}: <app-entry placeholder="Search..." (changeValue)="onSearch($event)"></app-entry></div>
@for (data of artists; track data.id;) {
<div class="item-list" (click)="onSelectArtist($event, data.id)" (auxclick)="onSelectArtist($event, data.id)">
<app-element-season
[element]="data"
countSubType="Album"
[countSubTypeCallBack]="countAlbum"
countSubType2="Track"
[countSubType2CallBack]="countTrack"
></app-element-season>
</div>
}
</div>
<div [className]="covers ? 'description-area description-area-cover' : 'description-area description-area-no-cover'">
<div class="title">
{{name}}
</div>
<div class="description" *ngIf="description">
{{description}}
</div>
<button class="button color-button color-shadow-black" (click)="playAll($event)" type="submit">
<i class="material-icons">play_arrow</i> Play All
</button>
<button class="button color-button color-shadow-black" style="margin-left:10px;" (click)="playShuffe($event)" type="submit">
<i class="material-icons">shuffle</i> Shuffle
</button>
</div>
</div>
<div class="fill-content colomn_mutiple" *ngIf="artists">
<div class="clear"></div>
<div class="title" *ngIf="artists.length > 1">Artists:</div>
<div class="title" *ngIf="artists.length == 1">Artist:</div>
<div *ngFor="let data of artists" class="item-list" (click)="onSelectArtist($event, data.id)" (auxclick)="onSelectArtist($event, data.id)">
<app-element-season
[element]="data"
countSubType="Album"
[countSubTypeCallBack]="countAlbum"
countSubType2="Track"
[countSubType2CallBack]="countTrack"
></app-element-season>
</div>
</div>
}
<div class="clear-end"></div>
</div>

View File

@@ -5,9 +5,9 @@
*/
import { Component, OnInit } from '@angular/core';
import { Artist, Track } from 'app/back-api';
import { ArtistService, ArianeService, AlbumService, TrackService, PlayerService } from 'app/service';
import { NodeData } from 'common/model';
import { ArtistService, ArianeService, TrackService, PlayerService } from 'app/service';
@Component({
selector: 'app-artists',
@@ -19,75 +19,82 @@ export class ArtistsScene implements OnInit {
covers: Array<string> = [];
name: string = "Artists";
description: string = "All available artists";
artists: NodeData[];
artists: Artist[];
artistsSave: Artist[];
countTrack: (id: number) => Promise<Number>;
countAlbum: (id: number) => Promise<Number>;
constructor(
private artistService: ArtistService,
private albumService: AlbumService,
private trackService: TrackService,
private playerService: PlayerService,
private arianeService: ArianeService) {
private artistService: ArtistService,
private trackService: TrackService,
private playerService: PlayerService,
private arianeService: ArianeService) {
}
ngOnInit() {
let self = this;
this.countTrack = (id:number) => {return self.countTrackCallback(id);};
this.countAlbum = (id:number) => {return self.countAlbumCallback(id);};
// this.idPlaylist = parseInt(this.route.snapshot.paramMap.get('universId'));
// this.idType = parseInt(this.route.snapshot.paramMap.get('typeId'));
this.countTrack = (id: number) => { return self.countTrackCallback(id); };
this.countAlbum = (id: number) => { return self.countAlbumCallback(id); };
this.artistService.getOrder()
.then((response: NodeData[]) => {
.then((response: Artist[]) => {
self.artists = response;
self.artistsSave = [...response];
//console.log("get artists: " + JSON.stringify(self.artists));
}).catch((response) => {
self.artists = undefined;
});
}
onSelectArtist(event: any, idSelected: number):void {
onSearch(value: string) {
console.log(`Search value: ${value}`);
this.artists = this.artistsSave.filter(element => {
return element.name.toLowerCase().includes(value.toLowerCase());;
})
}
onSelectArtist(event: any, idSelected: number): void {
if (event.ctrlKey) {
this.arianeService.navigateArtistEdit({id: idSelected, newWindows:event.which === 2} );
this.arianeService.navigateArtistEdit({ id: idSelected, newWindows: event.which === 2 });
} else {
this.arianeService.navigateArtist({artistId: idSelected, newWindows:event.which === 2} );
this.arianeService.navigateArtist({ artistId: idSelected, newWindows: event.which === 2 });
}
}
countTrackCallback(artistId: number) : Promise<Number> {
return this.artistService.countTrack(artistId);
countTrackCallback(artistId: number): Promise<Number> {
return this.trackService.countTracksOfAnArtist(artistId);
}
countAlbumCallback(artistId: number) : Promise<Number> {
return this.artistService.countAlbum(artistId);
countAlbumCallback(artistId: number): Promise<Number> {
return this.trackService.countAlbumOfAnArtist(artistId);
}
playAll(event: any):void {
this.playerService.clear();
playAll(): void {
this.playerService.clear();
let self = this;
this.trackService.getData()
.then((response: NodeData[]) => {
this.trackService.gets()
.then((response: Track[]) => {
let ids = [];
response.forEach(element => {
ids.push(element.id);
});
self.playerService.setNewPlaylist(ids);
})
})
.catch(() => {
console.log(`error to get list o ftrack ...`)
});
}
playShuffe(event: any):void {
this.playerService.clear();
playShuffle(): void {
this.playerService.clear();
let self = this;
this.trackService.getData()
.then((response: NodeData[]) => {
this.trackService.gets()
.then((response: Track[]) => {
let ids = [];
response.forEach(element => {
ids.push(element.id);
});
self.playerService.setNewPlaylistShuffle(ids);
})
})
.catch(() => {
console.log(`error to get list o ftrack ...`)
console.log(`error to get list o track ...`)
});
}
}

View File

@@ -5,15 +5,14 @@
*/
import { Component, OnInit } from '@angular/core';
import { ArianeService } from '../../service/ariane';
@Component({
selector: 'app-error-viewer',
templateUrl: './error-viewer.html',
styleUrls: [ './error-viewer.less' ]
styleUrls: ['./error-viewer.less']
})
export class ErrorViewerScene implements OnInit {
constructor(private arianeService: ArianeService) { }
constructor() { }
ngOnInit() {
}

View File

@@ -1,30 +1,38 @@
<div class="generic-page">
<div class="fill-title colomn_mutiple">
<div class="cover-area">
<div class="cover" *ngIf="cover != null" >
<img src="{{cover}}"/>
</div>
@if (cover != null) {
<div class="cover">
<img src="{{cover}}"/>
</div>
}
</div>
<div [className]="cover != null ? 'description-area description-area-cover' : 'description-area description-area-no-cover'">
<div class="title">
{{name}}
</div>
<div class="description" *ngIf="description">
{{description}}
@if(description) {
<div class="description">
{{description}}
</div>
}
</div>
</div>
<div class="fill-content colomn_mutiple">
<div class="clear"></div>
@for (data of artists; track data.id;) {
<div class="item" (click)="onSelectArtist($event, data.id)" (auxclick)="onSelectArtist($event, data.id)">
<!--<app-element-artist [element]="data"/>-->
</div>
</div>
}
</div>
<div class="fill-content colomn_mutiple">
<div class="clear"></div>
<div *ngFor="let data of artists" class="item" (click)="onSelectArtist($event, data.id)" (auxclick)="onSelectArtist($event, data.id)">
<app-element-artist [element]="data"></app-element-artist>
</div>
</div>
<div class="fill-content colomn_mutiple">
<div class="clear"></div>
<div *ngFor="let data of tracks" class="item item-track" (click)="onSelectMedia($event, data.id)" (auxclick)="onSelectMedia($event, data.id)">
<app-element-track [element]="data"></app-element-track>
</div>
@for (data of tracks; track data.id;) {
<div class="item item-track" (click)="onSelectTrack($event, data.id)" (auxclick)="onSelectTrack($event, data.id)">
<app-element-track [element]="data"/>
</div>
}
</div>
<div class="clear"></div>
</div>

View File

@@ -6,26 +6,27 @@
import { Component, OnInit } from '@angular/core';
import { GenderService, DataService, ArianeService } from 'app/service';
import { GenderService, DataService, ArianeService, TrackService } from 'app/service';
@Component({
selector: 'app-gender',
templateUrl: './gender.html',
styleUrls: [ './gender.less' ]
styleUrls: ['./gender.less']
})
export class GenderScene implements OnInit {
genderId = -1;
name: string = '';
description: string = '';
cover:string = null;
covers:string[] = [];
cover: string = null;
covers: string[] = [];
artistsError = '';
artists = [];
tracksError = '';
tracks = [];
constructor(
private genderService: GenderService,
private trackService: TrackService,
private arianeService: ArianeService,
private dataService: DataService) {
//NOTHING TO DO ...
@@ -34,19 +35,19 @@ export class GenderScene implements OnInit {
ngOnInit() {
this.genderId = this.arianeService.getTypeId();
let self = this;
console.log(`get gender global id: ${ this.genderId}`);
console.log(`get gender global id: ${this.genderId}`);
this.genderService.get(this.genderId)
.then((response) => {
self.name = response.name;
self.description = response.description;
console.log(` ==> get answer gender detail: ${JSON.stringify(response)}`);
if(response.covers === undefined || response.covers === null || response.covers.length === 0) {
if (response.covers === undefined || response.covers === null || response.covers.length === 0) {
self.cover = null;
self.covers = [];
} else {
self.cover = self.dataService.getCoverUrl(response.covers[0]);
for(let iii = 0; iii < response.covers.length; iii++) {
self.covers.push(self.dataService.getCoverUrl(response.covers[iii]));
self.cover = self.dataService.getUrl(response.covers[0]);
for (let iii = 0; iii < response.covers.length; iii++) {
self.covers.push(self.dataService.getUrl(response.covers[iii]));
}
}
}).catch((response) => {
@@ -55,7 +56,9 @@ export class GenderScene implements OnInit {
self.covers = [];
self.cover = null;
});
this.genderService.getSubArtist(this.genderId)
/*
TODO ???
this.trackService.getSubArtist(this.genderId)
.then((response) => {
console.log(` ==> get answer sub-artist: ${JSON.stringify(response)}`);
self.artistsError = '';
@@ -65,7 +68,8 @@ export class GenderScene implements OnInit {
self.artistsError = 'Wrong e-mail/login or password';
self.artists = [];
});
this.genderService.getSubTrack(this.genderId)
*/
this.trackService.getTracksForGender(this.genderId)
.then((response) => {
console.log(` ==> get answer sub-track: ${JSON.stringify(response)}`);
self.tracksError = '';
@@ -76,19 +80,19 @@ export class GenderScene implements OnInit {
self.tracks = [];
});
}
onSelectArtist(event: any, idSelected: number):void {
onSelectArtist(event: any, idSelected: number): void {
if (event.ctrlKey === false) {
this.arianeService.navigateArtist({ artistId: idSelected, newWindows:event.which === 2} );
this.arianeService.navigateArtist({ artistId: idSelected, newWindows: event.which === 2 });
} else {
this.arianeService.navigateArtistEdit({ id: idSelected, newWindows:event.which === 2} );
this.arianeService.navigateArtistEdit({ id: idSelected, newWindows: event.which === 2 });
}
}
onSelectTrack(event: any, idSelected: number):void {
onSelectTrack(event: any, idSelected: number): void {
if (event.ctrlKey === false) {
this.arianeService.navigateTrack({ trackId: idSelected, newWindows:event.which === 2} );
this.arianeService.navigateTrack({ trackId: idSelected, newWindows: event.which === 2 });
} else {
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows:event.which === 2} );
this.arianeService.navigateTrackEdit({ id: idSelected, newWindows: event.which === 2 });
}
}
}

View File

@@ -3,9 +3,11 @@
Karusic
</div>
<div class="fill-all colomn_mutiple">
<div *ngFor="let data of dataList" class="item-home" (click)="onSelectType($event, data.id)" (auxclick)="onSelectType($event, data.id)">
<app-element-type [element]="data"></app-element-type>
</div>
@for (data of dataList; track data.id) {
<div class="item-home" (click)="onSelectType($event, data.id)" (auxclick)="onSelectType($event, data.id)">
<app-element-type [element]="data"/>
</div>
}
<div class="clear"></div>
</div>
</div>

View File

@@ -11,7 +11,7 @@ import { ArianeService, GenderService } from 'app/service';
@Component({
selector: 'app-home',
templateUrl: './home.html',
styleUrls: [ './home.less' ]
styleUrls: ['./home.less']
})
export class HomeScene implements OnInit {
dataList = [
@@ -53,17 +53,17 @@ export class HomeScene implements OnInit {
*/
this.arianeService.reset();
}
onSelectType(event: any, idSelected: number):void {
onSelectType(event: any, idSelected: number): void {
if (idSelected === 1) {
this.arianeService.navigateGender({newWindows: event.which === 2});
this.arianeService.navigateGender({ newWindows: event.which === 2 });
} else if (idSelected === 2) {
this.arianeService.navigateArtist({newWindows: event.which === 2});
this.arianeService.navigateArtist({ newWindows: event.which === 2 });
} else if (idSelected === 3) {
this.arianeService.navigateAlbum({newWindows: event.which === 2});
this.arianeService.navigateAlbum({ newWindows: event.which === 2 });
} else if (idSelected === 4) {
this.arianeService.navigateTrack({newWindows: event.which === 2});
this.arianeService.navigateTrack({ newWindows: event.which === 2 });
} else if (idSelected === 5) {
this.arianeService.navigatePlaylist({newWindows: event.which === 2});
this.arianeService.navigatePlaylist({ newWindows: event.which === 2 });
}
}
}

View File

@@ -1,8 +1,10 @@
<div class="generic-page">
<div class="fill-all colomn_mutiple">
<div *ngFor="let data of tracks" class="item item-track" (click)="onSelectTrack($event, data)" (auxclick)="onSelectTrack($event, data)">
<app-element-track [element]="data"></app-element-track>
</div>
@for (data of tracks; track data.id) {
<div class="item item-track" (click)="onSelectTrack($event, data)" (auxclick)="onSelectTrack($event, data)">
<app-element-track [element]="data"></app-element-track>
</div>
}
<div class="clear"></div>
</div>
</div>

View File

@@ -2,148 +2,161 @@
<div class="title">
Edit Media
</div>
<div class="fill-all" *ngIf="itemIsRemoved">
<div class="message-big">
<br/><br/><br/>
The media has been removed
<br/><br/><br/>
</div>
</div>
<div class="fill-all" *ngIf="itemIsNotFound">
<div class="message-big">
<br/><br/><br/>
The media does not exist
<br/><br/><br/>
</div>
</div>
<div class="fill-all" *ngIf="itemIsLoading">
<div class="message-big">
<br/><br/><br/>
Loading ...<br/>
Please wait.
<br/><br/><br/>
</div>
</div>
<div class="fill-all" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
<div class="request_raw">
<div class="label">
Title:
</div>
<div class="input">
<input type="text"
placeholder="Name of the Media"
[value]="data.name"
(input)="onName($event.target.value)"
/>
@if(itemIsRemoved) {
<div class="fill-all">
<div class="message-big">
<br/><br/><br/>
The media has been removed
<br/><br/><br/>
</div>
</div>
<div class="request_raw2">
<div class="label">
<i class="material-icons">description</i> Description:
</div>
<div class="input">
<textarea (input)="onDescription($event.target.value)" placeholder="Description of the Media" rows=6>{{data.description}}</textarea>
<!--<input type="text"
placeholder="Description of the Media"
[value]="data.description"
(input)="onDescription($event.target.value)"/>-->
}
@else if (itemIsNotFound) {
<div class="fill-all">
<div class="message-big">
<br/><br/><br/>
The media does not exist
<br/><br/><br/>
</div>
</div>
<div class="request_raw">
<div class="label">
Gender:
</div>
<div class="input">
<select [ngModel]="data.genderId"
(ngModelChange)="onChangeGender($event)">
<option *ngFor="let element of listGender" [ngValue]="element.value">{{element.label}}</option>
</select>
</div>
<div class="input_add">
<button class="button color-button-normal color-shadow-black" (click)="newGender()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
}
@else if (itemIsLoading) {
<div class="fill-all">
<div class="message-big">
<br/><br/><br/>
Loading ...<br/>
Please wait.
<br/><br/><br/>
</div>
</div>
<div class="request_raw">
<div class="label">
Artist:
}
@else {
<div class="fill-all">
<div class="request_raw">
<div class="label">
Title:
</div>
<div class="input">
<input type="text"
placeholder="Name of the Media"
[value]="data.name"
(input)="onName($event.target.value)"
/>
</div>
</div>
<div class="input">
<select [ngModel]="data.artistId"
(ngModelChange)="onChangeArtist($event)">
<option *ngFor="let element of listArtist" [ngValue]="element.value">{{element.label}}</option>
</select>
<div class="request_raw2">
<div class="label">
<i class="material-icons">description</i> Description:
</div>
<div class="input">
<textarea (input)="onDescription($event.target.value)" placeholder="Description of the Media" rows=6>{{data.description}}</textarea>
<!--<input type="text"
placeholder="Description of the Media"
[value]="data.description"
(input)="onDescription($event.target.value)"/>-->
</div>
</div>
<div class="input_add">
<button class="button color-button-normal color-shadow-black" (click)="newArtist()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
<div class="request_raw">
<div class="label">
Gender:
</div>
<div class="input">
<select [ngModel]="data.genderId"
(ngModelChange)="onChangeGender($event)">
@for (element of listGender; track element.value;) {
<option [ngValue]="element.value">{{element.label}}</option>
}
</select>
</div>
<div class="input_add">
<button class="button color-button-normal color-shadow-black" (click)="newGender()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
</div>
</div>
<div class="request_raw">
<div class="label">
Artist:
</div>
<div class="input">
<select [ngModel]="data.artistId"
(ngModelChange)="onChangeArtist($event)">
@for (element of listArtist; track element.value;) {
<option [ngValue]="element.value">{{element.label}}</option>
}
</select>
</div>
<div class="input_add">
<button class="button color-button-normal color-shadow-black" (click)="newArtist()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
</div>
</div>
<div class="request_raw">
<div class="label">
Album:
</div>
<div class="input">
<select [ngModel]="data.albumId"
(ngModelChange)="onChangeAlbum($event)">
@for (element of listAlbum; track element.value;) {
<option [ngValue]="element.value">{{element.label}}</option>
}
</select>
</div>
<div class="input_add">
<button class="button color-button-normal color-shadow-black" (click)="newAlbum()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
</div>
</div>
<div class="request_raw">
<div class="label">
Track n°:
</div>
<div class="input">
<input type="number"
pattern="[0-9]{0-4}"
placeholder="5"
[value]="data.track"
(input)="onTrack($event.target)"/>
</div>
</div>
<div class="send_value">
<button class="button fill-x color-button-validate color-shadow-black"
[disabled]="!needSend"
(click)="sendValues()"
type="submit"><i class="material-icons">save_alt</i> Save</button>
</div>
<div class="clear"></div>
</div>
<div class="request_raw">
<div class="label">
Album:
</div>
<div class="input">
<select [ngModel]="data.albumId"
(ngModelChange)="onChangeAlbum($event)">
<option *ngFor="let element of listAlbum" [ngValue]="element.value">{{element.label}}</option>
</select>
</div>
<div class="input_add">
<button class="button color-button-normal color-shadow-black" (click)="newAlbum()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
</div>
<!-- ------------------------- ADMIN section --------------------------------- -->
<div class="title">
Administration
</div>
<div class="request_raw">
<div class="label">
Track n°:
<div class="fill-all">
<div class="request_raw">
<div class="label">
<i class="material-icons">data_usage</i> ID:
</div>
<div class="input">
{{data.dataId}}
</div>
</div>
<div class="input">
<input type="number"
pattern="[0-9]{0-4}"
placeholder="5"
[value]="data.track"
(input)="onTrack($event.target)"/>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
<i class="material-icons">delete_forever</i> Trash:
</div>
<div class="input">
<button class="button color-button-cancel color-shadow-black" (click)="removeItem()" type="submit">
<i class="material-icons">delete</i> Remove Media
</button>
</div>
</div>
<div class="clear"></div>
</div>
<div class="send_value">
<button class="button fill-x color-button-validate color-shadow-black"
[disabled]="!needSend"
(click)="sendValues()"
type="submit"><i class="material-icons">save_alt</i> Save</button>
</div>
<div class="clear"></div>
</div>
<!-- ------------------------- ADMIN section --------------------------------- -->
<div class="title" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
Administration
</div>
<div class="fill-all" *ngIf="!itemIsRemoved && !itemIsNotFound && !itemIsLoading">
<div class="request_raw">
<div class="label">
<i class="material-icons">data_usage</i> ID:
</div>
<div class="input">
{{data.dataId}}
</div>
</div>
<div class="clear"></div>
<div class="request_raw">
<div class="label">
<i class="material-icons">delete_forever</i> Trash:
</div>
<div class="input">
<button class="button color-button-cancel color-shadow-black" (click)="removeItem()" type="submit">
<i class="material-icons">delete</i> Remove Media
</button>
</div>
</div>
<div class="clear"></div>
</div>
}
</div>
<create-type ></create-type>

View File

@@ -5,13 +5,11 @@
*/
import { Component, OnInit } from '@angular/core';
import { UploadProgress, PopInService, isNullOrUndefined } from '@kangaroo-and-rabbit/kar-cw';
import { Track } from 'app/back-api';
import { DataService, GenderService, ArtistService, TrackService, ArianeService, AlbumService } from 'app/service';
import { UploadProgress } from 'common/popin/upload-progress/upload-progress';
import { PopInService } from 'common/service';
import { Media } from 'app/model';
import { isNullOrUndefined } from 'common/utils';
export interface ElementList {
value?: number;
@@ -25,7 +23,7 @@ class DataToSend {
track?: number;
artistId: number = null;
albumId: number = null;
dataId: number = -1;
dataId: string = "";
genderId: number = null;
generatedName: string = '';
clone() {
@@ -164,7 +162,7 @@ export class TrackEditScene implements OnInit {
console.log(`get response3 : ${JSON.stringify(response3, null, 2)}`);
});
this.trackService.get(this.idTrack)
.then((response: Media) => {
.then((response: Track) => {
console.log(`get response of track : ${JSON.stringify(response, null, 2)}`);
self.data.name = response.name;
self.data.description = response.description;

View File

@@ -1,133 +1,172 @@
<div class="main-reduce">
<div class="fill-all" *ngIf="mediaIsNotFound">
<div class="title">
Play media<br/><br/><br/><br/><br/>
The media does not exist
</div>
</div>
<div class="fill-all" *ngIf="mediaIsLoading">
<div class="title">
Play media<br/><br/><br/><br/><br/>
Loading ...<br/>
Please wait.
</div>
</div>
<div class="fill-all" *ngIf="!mediaIsNotFound && !mediaIsLoading && !playTrack">
<div class="title">
{{name}}
</div>
<div class="cover-full">
<div class="cover">
<div class="cover-image" *ngIf="covers">
<img src="{{covers[0]}}"/>
</div>
<div class="cover-no-image" *ngIf="covers"></div>
<div class="cover-button">
<button (click)="onRequirePlay()">
<i class="material-icons big-button">play_circle_outline</i>
</button>
</div>
</div>
<div class="cover-button-next" *ngIf="haveNext !== null">
<button (click)="onRequireNext($event)" (auxclick)="onRequireNext($event)">
<i class="material-icons big-button">arrow_forward_ios</i>
</button>
</div>
<div class="cover-button-previous" *ngIf="havePrevious !== null">
<button (click)="onRequirePrevious($event)" (auxclick)="onRequirePrevious($event)">
<i class="material-icons big-button">arrow_back_ios</i>
</button>
@if(mediaIsNotFound) {
<div class="fill-all">
<div class="title">
Play media<br/><br/><br/><br/><br/>
The media does not exist
</div>
</div>
<div class="clear"></div>
<div class="episode" *ngIf="artistName!=null">
<b>Artist:</b> {{artistName}}
</div>
<div class="episode" *ngIf="albumName!=null">
<b>Album:</b> {{albumName}}
</div>
<div class="episode" *ngIf="episode!=null">
<b>Episode:</b> {{episode}}
</div>
<div class="episode">
<b>generatedName:</b> {{generatedName}}
</div>
<div class="description">
{{description}}
</div>
</div>
<div class="fill-all bg-black" *ngIf="playTrack">
<div class="track"
#globalVideoElement
(mousemove)="startHideTimer()"
(fullscreenchange)="onFullscreenChange($event)">
<div class="track-elem">
<video src="{{trackSource}}"
#trackPlayer
preload
(play)="changeStateToPlay()"
(pause)="changeStateToPause()"
(timeupdate)="changeTimeupdate($event.currentTime)"
(durationchange)="changeDurationchange($event.duration)"
(loadedmetadata)="changeMetadata()"
(audioTracks)="audioTracks($event)"
autoplay
(ended)="onTrackEnded()"
><!-- controls > --> <!--preload="none"-->
<!--<p>Your browser does not support HTML5 track player. download track: <a href="{{trackSource}}>link here</a>.</p>-->
</video>
}
@if(mediaIsLoading) {
<div class="fill-all">
<div class="title">
Play media<br/><br/><br/><br/><br/>
Loading ...<br/>
Please wait.
</div>
<div class="controls" *ngIf="!displayNeedHide || !isPlaying">
<button (click)="onPlay()" *ngIf="!isPlaying" ><i class="material-icons">play_arrow</i></button>
<button (click)="onPause()" *ngIf="isPlaying" ><i class="material-icons">pause</i></button>
<button (click)="onStop()" ><i class="material-icons">stop</i></button>
<div class="timer">
<div>
<input type="range" min="0" class="slider"
[value]="currentTime"
[max]="duration"
(input)="seek($event.target)">
</div>
<div class="timer-text">
<label class="unselectable">{{currentTimeDisplay}} / {{durationDisplay}}</label>
</div>
}
@if(!mediaIsNotFound && !mediaIsLoading && !playTrack) {
<div class="fill-all">
<div class="title">
{{name}}
</div>
<div class="cover-full">
<div class="cover">
@if (covers && covers.length > 0) {
<div class="cover-image">
<img src="{{covers[0]}}"/>
</div>
}
@else {
<div class="cover-no-image"></div>
}
<div class="cover-button">
<button (click)="onRequirePlay()">
<i class="material-icons big-button">play_circle_outline</i>
</button>
</div>
</div>
<!--<button (click)="onBefore()"><i class="material-icons">navigate_before</i></button>-->
<button (click)="onRewind()"><i class="material-icons">fast_rewind</i></button>
<button (click)="onForward()"><i class="material-icons">fast_forward</i></button>
<!--<button (click)="onNext()"><i class="material-icons">navigate_next</i></button>-->
<!--<button (click)="onMore()" ><i class="material-icons">more_vert</i></button>-->
<button (click)="onFullscreen()" *ngIf="!isFullScreen"><i class="material-icons">fullscreen</i></button>
<button (click)="onFullscreenExit()" *ngIf="isFullScreen"><i class="material-icons">fullscreen_exit</i></button>
<!--<button (click)="onTakeScreenShoot()"><i class="material-icons">add_a_photo</i></button>-->
<button (click)="onVolumeMenu()" ><i class="material-icons">volume_up</i></button>
<button class="bigPause" (click)="onPauseToggle()"><i *ngIf="!isPlaying" class="material-icons">play_circle_outline</i></button>
<button class="bigRewind" (click)="onRewind()"><i *ngIf="!isPlaying" class="material-icons">fast_rewind</i></button>
<button class="bigForward" (click)="onForward()"><i *ngIf="!isPlaying" class="material-icons">fast_forward</i></button>
</div>
<div class="title-inline" *ngIf="!isFullScreen || !isPlaying">
{{generatedName}}
</div>
<div class="track-button" *ngIf="!isFullScreen || !isPlaying">
<button (click)="onRequireStop()">
<i class="material-icons big-button">highlight_off</i>
</button>
</div>
<div class="volume" *ngIf="displayVolumeMenu && (!displayNeedHide || !isPlaying)">
<div class="volume-menu">
<div class="slidecontainer">
<input type="range" min="0" max="100" class="slider"
[value]="volumeValue"
(input)="onVolume($event.target)">
@if (haveNext !== null) {
<div class="cover-button-next">
<button (click)="onRequireNext($event)" (auxclick)="onRequireNext($event)">
<i class="material-icons big-button">arrow_forward_ios</i>
</button>
</div>
<button (click)="onVolumeMute()" *ngIf="!trackPlayer.muted"><i class="material-icons">volume_mute</i></button>
<button (click)="onVolumeUnMute()" *ngIf="trackPlayer.muted"><i class="material-icons">volume_off</i></button>
}
@if (havePrevious !== null) {
<div class="cover-button-previous">
<button (click)="onRequirePrevious($event)" (auxclick)="onRequirePrevious($event)">
<i class="material-icons big-button">arrow_back_ios</i>
</button>
</div>
}
</div>
<div class="clear"></div>
@if (artistName!=null) {
<div class="episode">
<b>Artist:</b> {{artistName}}
</div>
}
@if (albumName!=null) {
<div class="episode">
<b>Album:</b> {{albumName}}
</div>
}
@if (track!=null) {
<div class="episode">
<b>Piste:</b> {{track}}
</div>
}
<div class="episode">
<b>generatedName:</b> {{generatedName}}
</div>
<div class="description">
{{description}}
</div>
</div>
</div>
}
@if (playTrack) {
<div class="fill-all bg-black">
<div class="track"
#globalVideoElement
(mousemove)="startHideTimer()"
(fullscreenchange)="onFullscreenChange()">
<div class="track-elem">
<video src="{{trackSource}}"
#trackPlayer
preload
(play)="changeStateToPlay()"
(pause)="changeStateToPause()"
(timeupdate)="changeTimeupdate($event.currentTime)"
(durationchange)="changeDurationchange($event.duration)"
(loadedmetadata)="changeMetadata()"
(audioTracks)="audioTracks($event)"
autoplay
(ended)="onTrackEnded()"
><!-- controls > --> <!--preload="none"-->
<!--<p>Your browser does not support HTML5 track player. download track: <a href="{{trackSource}}>link here</a>.</p>-->
</video>
</div>
@if (!displayNeedHide || !isPlaying) {
<div class="controls">
@if (!isPlaying) {
<button (click)="onPlay()"><i class="material-icons">play_arrow</i></button>
}
@else {
<button (click)="onPause()"><i class="material-icons">pause</i></button>
}
<button (click)="onStop()" ><i class="material-icons">stop</i></button>
<div class="timer">
<div>
<input type="range" min="0" class="slider"
[value]="currentTime"
[max]="duration"
(input)="seek($event.target)">
</div>
<div class="timer-text">
<label class="unselectable">{{currentTimeDisplay}} / {{durationDisplay}}</label>
</div>
</div>
<!--<button (click)="onBefore()"><i class="material-icons">navigate_before</i></button>-->
<button (click)="onRewind()"><i class="material-icons">fast_rewind</i></button>
<button (click)="onForward()"><i class="material-icons">fast_forward</i></button>
<!--<button (click)="onNext()"><i class="material-icons">navigate_next</i></button>-->
<!--<button (click)="onMore()" ><i class="material-icons">more_vert</i></button>-->
@if (!isFullScreen) {
<button (click)="onFullscreen()"><i class="material-icons">fullscreen</i></button>
}
@else {
<button (click)="onFullscreenExit()"><i class="material-icons">fullscreen_exit</i></button>
}
<!--<button (click)="onTakeScreenShoot()"><i class="material-icons">add_a_photo</i></button>-->
<button (click)="onVolumeMenu()" ><i class="material-icons">volume_up</i></button>
@if (!isPlaying) {
<button class="bigPause" (click)="onPauseToggle()"><i class="material-icons">play_circle_outline</i></button>
<button class="bigRewind" (click)="onRewind()"><i class="material-icons">fast_rewind</i></button>
<button class="bigForward" (click)="onForward()"><i class="material-icons">fast_forward</i></button>
}
</div>
}
@if(!isFullScreen || !isPlaying) {
<div class="title-inline">
{{generatedName}}
</div>
<div class="track-button">
<button (click)="onRequireStop()">
<i class="material-icons big-button">highlight_off</i>
</button>
</div>
}
@if (displayVolumeMenu && (!displayNeedHide || !isPlaying)) {
<div class="volume">
<div class="volume-menu">
<div class="slidecontainer">
<input type="range" min="0" max="100" class="slider"
[value]="volumeValue"
(input)="onVolume($event.target)">
</div>
@if (!trackPlayer.muted) {
<button (click)="onVolumeMute()"><i class="material-icons">volume_mute</i></button>
}
@else {
<button (click)="onVolumeUnMute()"><i class="material-icons">volume_off</i></button>
}
</div>
</div>
}
</div>
</div>
}
<canvas #canvascreenshoot style="overflow:auto"></canvas>
</div>

View File

@@ -5,92 +5,90 @@
*/
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { isNullOrUndefined } from '@kangaroo-and-rabbit/kar-cw';
import { Track } from 'app/back-api';
import { DataService, TrackService, ArtistService, AlbumService, ArianeService } from 'app/service';
import { HttpWrapperService } from 'common/service';
import { isNullOrUndefined } from 'common/utils';
@Component({
selector: 'app-track',
templateUrl: './track.html',
styleUrls: [ './track.less' ]
styleUrls: ['./track.less']
})
export class TrackScene implements OnInit {
trackGlobal:any;
trackGlobal: any;
@ViewChild('globalTrackElement')
set mainDivEl(el: ElementRef) {
if(el !== null && el !== undefined) {
this.trackGlobal = el.nativeElement;
set mainDivEl(el: ElementRef) {
if (el !== null && el !== undefined) {
this.trackGlobal = el.nativeElement;
}
}
trackPlayer: HTMLVideoElement;
@ViewChild('videoPlayer')
set mainTrackEl(el: ElementRef) {
if(el !== null && el !== undefined) {
this.trackPlayer = el.nativeElement;
set mainTrackEl(el: ElementRef) {
if (el !== null && el !== undefined) {
this.trackPlayer = el.nativeElement;
}
}
videoCanva: any;
@ViewChild('canvascreenshoot')
set mainCanvaEl(el: ElementRef) {
if(el !== null && el !== undefined) {
this.videoCanva = el.nativeElement;
set mainCanvaEl(el: ElementRef) {
if (el !== null && el !== undefined) {
this.videoCanva = el.nativeElement;
}
}
haveNext = null;
havePrevious = null;
idTrack:number = -1;
idTrack: number = -1;
mediaIsNotFound:boolean = false;
mediaIsLoading:boolean = true;
error:string = '';
mediaIsNotFound: boolean = false;
mediaIsLoading: boolean = true;
error: string = '';
name:string = '';
description:string = '';
episode:number = undefined;
artists:number[] = undefined;
artistName:string = undefined;
albumId:number = undefined;
albumName:string = undefined;
dataId:number = -1;
time:number = undefined;
typeId:number = undefined;
generatedName:string = '';
trackSource:string = '';
name: string = '';
description: string = '';
track?: number;
artists?: number[];
artistName?: string;
albumId?: number;
albumName?: string;
dataId: string = "";
typeId?: number;
generatedName: string = '';
trackSource: string = '';
covers: string[];
playTrack:boolean = false;
displayVolumeMenu:boolean = false;
isPlaying:boolean = false;
isFullScreen:boolean = false;
currentTime:number = 0;
currentTimeDisplay:string = '00';
duration:number = 0;
durationDisplay:string = '00';
volumeValue:number = 100;
playTrack: boolean = false;
displayVolumeMenu: boolean = false;
isPlaying: boolean = false;
isFullScreen: boolean = false;
currentTime: number = 0;
currentTimeDisplay: string = '00';
duration: number = 0;
durationDisplay: string = '00';
volumeValue: number = 100;
displayNeedHide:boolean = false;
displayNeedHide: boolean = false;
timeLeft: number = 10;
interval = null;
constructor(private trackService: TrackService,
private artistService: ArtistService,
private albumService: AlbumService,
private httpService: HttpWrapperService,
private arianeService: ArianeService,
private dataService: DataService) {
private artistService: ArtistService,
private albumService: AlbumService,
private arianeService: ArianeService,
private dataService: DataService) {
}
startHideTimer() {
this.displayNeedHide = false;
this.timeLeft = 5;
if(this.interval !== null) {
if (this.interval !== null) {
return;
}
let self = this;
this.interval = setInterval(() => {
console.log(`periodic event: ${ self.timeLeft}`);
if(self.timeLeft > 0) {
console.log(`periodic event: ${self.timeLeft}`);
if (self.timeLeft > 0) {
self.timeLeft--;
} else {
clearInterval(self.interval);
@@ -105,50 +103,47 @@ export class TrackScene implements OnInit {
this.interval = null;
}
onRequireNext(event: any) {
console.log(`generate next : ${ this.haveNext.id}`);
console.log(`generate next : ${this.haveNext.id}`);
if (event.ctrlKey === false) {
this.arianeService.navigateTrack({ trackId: this.haveNext.id, newWindows:event.which === 2} );
this.arianeService.navigateTrack({ trackId: this.haveNext.id, newWindows: event.which === 2 });
} else {
this.arianeService.navigateTrackEdit({ id: this.haveNext.id, newWindows:event.which === 2} );
this.arianeService.navigateTrackEdit({ id: this.haveNext.id, newWindows: event.which === 2 });
}
this.arianeService.setTrack(this.haveNext.id);
}
onRequirePrevious(event: any) {
console.log(`generate previous : ${ this.havePrevious.id}`);
console.log(`generate previous : ${this.havePrevious.id}`);
if (event.ctrlKey === false) {
this.arianeService.navigateTrack({ trackId: this.haveNext.id, newWindows:event.which === 2} );
this.arianeService.navigateTrack({ trackId: this.haveNext.id, newWindows: event.which === 2 });
} else {
this.arianeService.navigateTrackEdit({ id: this.haveNext.id, newWindows:event.which === 2} );
this.arianeService.navigateTrackEdit({ id: this.haveNext.id, newWindows: event.which === 2 });
}
this.arianeService.setTrack(this.havePrevious.id);
}
generateName() {
this.generatedName = '';
if(this.artistName !== undefined) {
this.generatedName = `${this.generatedName }${this.artistName }-`;
if (this.artistName !== undefined) {
this.generatedName = `${this.generatedName}${this.artistName}-`;
}
if(this.albumName !== undefined) {
if(this.albumName.length < 2) {
this.generatedName = `${this.generatedName }s0${ this.albumName }-`;
if (this.albumName !== undefined) {
if (this.albumName.length < 2) {
this.generatedName = `${this.generatedName}s0${this.albumName}-`;
} else {
this.generatedName = `${this.generatedName }s${ this.albumName }-`;
this.generatedName = `${this.generatedName}s${this.albumName}-`;
}
}
if(this.episode !== undefined) {
if(this.episode < 10) {
this.generatedName = `${this.generatedName }e0${ this.episode }-`;
if (this.track !== undefined) {
if (this.track < 10) {
this.generatedName = `${this.generatedName}e0${this.track}-`;
} else {
this.generatedName = `${this.generatedName }e${ this.episode }-`;
this.generatedName = `${this.generatedName}e${this.track}-`;
}
}
this.generatedName = this.generatedName + this.name;
this.generatedName = this.generatedName.replace(new RegExp('&', 'g'), '_');
this.generatedName = this.generatedName.replace(new RegExp('/', 'g'), '_');
// update the path of the uri request
this.trackSource = this.httpService.createRESTCall2({
api: `data/${ this.dataId}/${this.generatedName}`,
addURLToken: true,
});
this.trackSource = this.dataService.getUrl(this.dataId, this.generatedName);
}
myPeriodicCheckFunction() {
@@ -160,27 +155,27 @@ export class TrackScene implements OnInit {
/*
let captureStream = this.trackPlayer.audioTracks;
for (let iii=0; iii < captureStream.length; iii++) {
console.log(" - " + captureStream[iii].language);
if (captureStream[iii].language.substring(0,2) === "fr") {
captureStream[iii].enabled = true;
} else {
captureStream[iii].enabled = false;
}
console.log(" - " + captureStream[iii].language);
if (captureStream[iii].language.substring(0,2) === "fr") {
captureStream[iii].enabled = true;
} else {
captureStream[iii].enabled = false;
}
}
*/
}
audioTracks(event) {
console.log(`list of the stream:${ event}`);
console.log(`list of the stream:${event}`);
/*
let captureStream = this.trackPlayer.audioTracks;
for (let iii=0; iii < captureStream.length; iii++) {
console.log(" - " + captureStream[iii].language);
if (captureStream[iii].language.substring(0,2) === "fr") {
captureStream[iii].enabled = true;
} else {
captureStream[iii].enabled = false;
}
console.log(" - " + captureStream[iii].language);
if (captureStream[iii].language.substring(0,2) === "fr") {
captureStream[iii].enabled = true;
} else {
captureStream[iii].enabled = false;
}
}
*/
}
@@ -190,40 +185,36 @@ export class TrackScene implements OnInit {
this.startHideTimer();
this.idTrack = this.arianeService.getTrackId();
this.arianeService.trackChange.subscribe((trackId) => {
console.log(`Detect trackId change...${ trackId}`);
console.log(`Detect trackId change...${trackId}`);
self.idTrack = trackId;
self.updateDisplay();
});
self.updateDisplay();
}
updateDisplay():void {
updateDisplay(): void {
let self = this;
self.haveNext = null;
self.havePrevious = null;
this.trackService.get(this.idTrack)
.then((response) => {
console.log(`get response of track : ${ JSON.stringify(response, null, 2)}`);
.then((response: Track) => {
console.log(`get response of track : ${JSON.stringify(response, null, 2)}`);
self.error = '';
self.name = response.name;
self.description = response.description;
self.episode = response.episode;
//self.episode = response.episode;
self.artists = response.artists;
self.albumId = response.albumId;
self.dataId = response.dataId;
self.time = response.time;
self.generatedName = "????????? TODO: ???????" //response.generatedName;
if(self.dataId !== -1) {
self.trackSource = self.httpService.createRESTCall2({
api: `data/${ self.dataId}/${self.generatedName}`,
addURLToken: true,
});
if (!isNullOrUndefined(self.dataId)) {
self.trackSource = this.dataService.getUrl(self.dataId);
} else {
self.trackSource = '';
}
self.covers = self.dataService.getCoverListUrl(response.covers);
self.covers = self.dataService.getListUrl(response.covers);
self.generateName();
if(!isNullOrUndefined(self.artists) && self.artists.length !== 0) {
if (!isNullOrUndefined(self.artists) && self.artists.length !== 0) {
self.artistService.get(self.artists[0])
.then((response2) => {
self.artistName = response2.name;
@@ -232,7 +223,7 @@ export class TrackScene implements OnInit {
// nothing to do ...
});
}
if(!isNullOrUndefined(self.albumId)) {
if (!isNullOrUndefined(self.albumId)) {
self.albumService.get(self.albumId)
.then((response4) => {
self.albumName = response4.name;
@@ -240,31 +231,30 @@ export class TrackScene implements OnInit {
}).catch((response5) => {
// nothing to do ...
});
self.albumService.getTrack(self.albumId)
.then((response6:any) => {
// console.log("saison property: " + JSON.stringify(response, null, 2));
self.trackService.getTracksWithAlbumId(self.albumId)
.then((response6: Track[]) => {
self.haveNext = null;
self.havePrevious = null;
for(let iii = 0; iii < response6.length; iii++) {
if(isNullOrUndefined(response6[iii].episode)) {
for (let iii = 0; iii < response6.length; iii++) {
if (isNullOrUndefined(response6[iii].track)) {
continue;
}
if(response6[iii].episode < self.episode) {
if(self.havePrevious === null) {
if (response6[iii].track < self.track) {
if (self.havePrevious === null) {
self.havePrevious = response6[iii];
} else if(self.havePrevious.episode < response6[iii].episode) {
} else if (self.havePrevious.episode < response6[iii].track) {
self.havePrevious = response6[iii];
}
} else if(response6[iii].episode > self.episode) {
if(self.haveNext === null) {
} else if (response6[iii].track > self.track) {
if (self.haveNext === null) {
self.haveNext = response6[iii];
} else if(self.haveNext.episode > response6[iii].episode) {
} else if (self.haveNext.episode > response6[iii].track) {
self.haveNext = response6[iii];
}
}
self.covers.push(self.dataService.getCoverUrl(response6[iii]));
//self.covers.push(self.dataService.getUrl(response6[iii].covers));
}
}).catch((response7:any) => {
}).catch((response7: any) => {
});
}
@@ -275,11 +265,10 @@ export class TrackScene implements OnInit {
self.error = 'Can not get the data';
self.name = '';
self.description = '';
self.episode = undefined;
self.track = undefined;
self.artists = undefined;
self.albumId = undefined;
self.dataId = -1;
self.time = undefined;
self.dataId = "";
self.generatedName = '';
self.trackSource = '';
self.covers = undefined;
@@ -313,7 +302,7 @@ export class TrackScene implements OnInit {
changeStateToPlay() {
this.isPlaying = true;
if(this.isFullScreen === true) {
if (this.isFullScreen === true) {
this.onFullscreen();
}
}
@@ -321,25 +310,25 @@ export class TrackScene implements OnInit {
this.isPlaying = false;
}
convertIndisplayTime(time:number) : string {
let tmpp = parseInt(`${ time}`, 10);
let heures = parseInt(`${ tmpp / 3600}`, 10);
convertIndisplayTime(time: number): string {
let tmpp = parseInt(`${time}`, 10);
let heures = parseInt(`${tmpp / 3600}`, 10);
tmpp = tmpp - heures * 3600;
let minutes = parseInt(`${ tmpp / 60}`, 10);
let minutes = parseInt(`${tmpp / 60}`, 10);
let seconds = tmpp - minutes * 60;
let out = '';
if(heures !== 0) {
out = `${out }${heures }:`;
if (heures !== 0) {
out = `${out}${heures}:`;
}
if(minutes >= 10) {
out = `${out }${minutes }:`;
if (minutes >= 10) {
out = `${out}${minutes}:`;
} else {
out = `${out }0${ minutes }:`;
out = `${out}0${minutes}:`;
}
if(seconds >= 10) {
if (seconds >= 10) {
out = out + seconds;
} else {
out = `${out }0${ seconds}`;
out = `${out}0${seconds}`;
}
return out;
}
@@ -353,7 +342,7 @@ export class TrackScene implements OnInit {
}
changeDurationchange(duration: any) {
console.log('duration change ');
console.log(` ==> ${ this.trackPlayer.duration}`);
console.log(` ==> ${this.trackPlayer.duration}`);
this.duration = this.trackPlayer.duration;
this.durationDisplay = this.convertIndisplayTime(this.duration);
}
@@ -361,9 +350,9 @@ export class TrackScene implements OnInit {
onPlay() {
console.log('play');
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
this.trackPlayer.volume = this.volumeValue / 100;
@@ -373,9 +362,9 @@ export class TrackScene implements OnInit {
onPause() {
console.log('pause');
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
this.trackPlayer.pause();
@@ -383,7 +372,7 @@ export class TrackScene implements OnInit {
onPauseToggle() {
console.log('pause toggle ...');
if(this.isPlaying === true) {
if (this.isPlaying === true) {
this.onPause();
} else {
this.onPlay();
@@ -393,9 +382,9 @@ export class TrackScene implements OnInit {
onStop() {
console.log('stop');
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
this.trackPlayer.pause();
@@ -412,12 +401,12 @@ export class TrackScene implements OnInit {
this.startHideTimer();
}
seek(newValue:any) {
console.log(`seek ${ newValue.value}`);
seek(newValue: any) {
console.log(`seek ${newValue.value}`);
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
this.trackPlayer.currentTime = newValue.value;
@@ -426,9 +415,9 @@ export class TrackScene implements OnInit {
onRewind() {
console.log('rewind');
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
this.trackPlayer.currentTime = this.currentTime - 10;
@@ -437,9 +426,9 @@ export class TrackScene implements OnInit {
onForward() {
console.log('forward');
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
this.trackPlayer.currentTime = this.currentTime + 10;
@@ -448,27 +437,27 @@ export class TrackScene implements OnInit {
onMore() {
console.log('more');
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
}
onFullscreen() {
console.log('fullscreen');
this.startHideTimer();
if(this.trackGlobal === null ||
this.trackGlobal === undefined) {
console.log(`error element: ${ this.trackGlobal}`);
if (this.trackGlobal === null ||
this.trackGlobal === undefined) {
console.log(`error element: ${this.trackGlobal}`);
return;
}
if(this.trackGlobal.requestFullscreen) {
if (this.trackGlobal.requestFullscreen) {
this.trackGlobal.requestFullscreen();
} else if(this.trackGlobal.mozRequestFullScreen) {
} else if (this.trackGlobal.mozRequestFullScreen) {
this.trackGlobal.mozRequestFullScreen();
} else if(this.trackGlobal.webkitRequestFullscreen) {
} else if (this.trackGlobal.webkitRequestFullscreen) {
this.trackGlobal.webkitRequestFullscreen();
} else if(this.trackGlobal.msRequestFullscreen) {
} else if (this.trackGlobal.msRequestFullscreen) {
this.trackGlobal.msRequestFullscreen();
}
}
@@ -476,21 +465,21 @@ export class TrackScene implements OnInit {
onFullscreenExit() {
this.onFullscreenExit22(document);
}
onFullscreenExit22(docc:any) {
onFullscreenExit22(docc: any) {
console.log('fullscreen EXIT');
this.startHideTimer();
if(this.trackGlobal === null ||
this.trackGlobal === undefined) {
console.log(`error element: ${ this.trackGlobal}`);
if (this.trackGlobal === null ||
this.trackGlobal === undefined) {
console.log(`error element: ${this.trackGlobal}`);
return;
}
if(docc.exitFullscreen) {
if (docc.exitFullscreen) {
docc.exitFullscreen();
} else if(docc.mozCancelFullScreen) {
} else if (docc.mozCancelFullScreen) {
docc.mozCancelFullScreen();
} else if(docc.webkitExitFullscreen) {
} else if (docc.webkitExitFullscreen) {
docc.webkitExitFullscreen();
} else if(docc.msExitFullscreen) {
} else if (docc.msExitFullscreen) {
docc.msExitFullscreen();
}
}
@@ -498,12 +487,12 @@ export class TrackScene implements OnInit {
onFullscreenChange() {
this.onFullscreenChange22(document);
}
onFullscreenChange22(element:any) {
onFullscreenChange22(element: any) {
let isInFullScreen = element.fullscreenElement && element.fullscreenElement !== null ||
element.webkitFullscreenElement && element.webkitFullscreenElement !== null ||
element.mozFullScreenElement && element.mozFullScreenElement !== null ||
element.msFullscreenElement && element.msFullscreenElement !== null;
console.log(`onFullscreenChange(${ isInFullScreen })`);
element.webkitFullscreenElement && element.webkitFullscreenElement !== null ||
element.mozFullScreenElement && element.mozFullScreenElement !== null ||
element.msFullscreenElement && element.msFullscreenElement !== null;
console.log(`onFullscreenChange(${isInFullScreen})`);
this.isFullScreen = isInFullScreen;
}
@@ -512,12 +501,12 @@ export class TrackScene implements OnInit {
this.startHideTimer();
}
onVolume(newValue:any) {
console.log(`onVolume ${ newValue.value}`);
onVolume(newValue: any) {
console.log(`onVolume ${newValue.value}`);
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
this.volumeValue = newValue.value;
@@ -527,9 +516,9 @@ export class TrackScene implements OnInit {
onVolumeMute() {
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
this.trackPlayer.muted = true;
@@ -537,9 +526,9 @@ export class TrackScene implements OnInit {
onVolumeUnMute() {
this.startHideTimer();
if(this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${ this.trackPlayer}`);
if (this.trackPlayer === null ||
this.trackPlayer === undefined) {
console.log(`error element: ${this.trackPlayer}`);
return;
}
this.trackPlayer.muted = false;
@@ -557,10 +546,12 @@ export class TrackScene implements OnInit {
// convert it and send it to the server
let self = this;
console.log("not implemented right now...");
/*
this.videoCanva.toBlob((blob) => {
self.trackService.uploadCoverBlob(blob, this.idTrack);
}, 'image/jpeg', 0.95);
*/
/*
let tmpUrl = this.videoCanva.toDataURL('image/jpeg', 0.95);
fetch(tmpUrl)
@@ -571,3 +562,4 @@ export class TrackScene implements OnInit {
*/
}
}

View File

@@ -32,207 +32,220 @@
</tbody>
</table>
</div>
<div *ngIf="this.parsedElement.length !== 0" class="title">
Meta-data:
</div>
@if(parsedElement.length !== 0) {
<div class="title">
Meta-data:
</div>
}
<div class="clear"><br/></div>
<div *ngIf="this.parsedElement.length !== 0" class="fill-all">
<div class="request_raw_table">
<table>
<colgroup>
<col style="width:10%">
<col style="width:70%">
<col style="width:10%">
</colgroup>
<tbody>
<tr>
<td class="left-colomn">Gender:</td>
<td class="right-colomn">
<input type="text"
placeholder="Genre of the Media"
[value]="globalGender"
(input)="onGender($event.target.value)"
/>
</td>
</tr>
<tr>
<td class="left-colomn"></td>
<td class="right-colomn">
<select [ngModel]="genreId"
(ngModelChange)="onChangeGender($event)">
<option *ngFor="let element of listGender" [ngValue]="element.value">{{element.label}}</option>
</select>
</td>
<td class="tool-colomn">
<!--
<button class="button color-button-normal color-shadow-black" (click)="newArtist()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
-->
</td>
</tr>
<tr>
<td class="left-colomn">Artist:</td>
<td class="right-colomn">
<input type="text"
placeholder="Artist of the Media"
[value]="globalArtist"
(input)="onArtist($event.target.value)"
/>
</td>
</tr>
<tr>
<td class="left-colomn"></td>
<td class="right-colomn">
<select [ngModel]="artistId"
(ngModelChange)="onChangeArtist($event)">
<option *ngFor="let element of listArtist" [ngValue]="element.value">{{element.label}}</option>
</select>
</td>
<td class="tool-colomn">
<!--
<button class="button color-button-normal color-shadow-black" (click)="newArtist()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
-->
</td>
</tr>
<tr>
<td class="left-colomn">Album:</td>
<td class="right-colomn">
<input type="text"
placeholder="Album title"
[value]="globalAlbum"
(input)="onAlbum($event.target.value)"
/>
</td>
</tr>
<tr>
<td class="left-colomn"></td>
<td class="right-colomn">
<select [ngModel]="albumId"
(ngModelChange)="onChangeAlbum($event)">
<option *ngFor="let element of listAlbum" [ngValue]="element.value">{{element.label}}</option>
</select>
</td>
<td class="tool-colomn">
<!--
<button class="button color-button-normal color-shadow-black" (click)="newArtist()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
-->
</td>
</tr>
</tbody>
</table>
</div>
<div class="clear"></div>
<div class="request_raw_table">
<table>
<colgroup>
@if(parsedElement.length !== 0) {
<div class="fill-all">
<div class="request_raw_table">
<table>
<colgroup>
<col style="width:10%">
<col style="width:70%">
<col style="width:10%">
</colgroup>
<thead>
<tr>
<th>Track ID:</th>
<th>Title:</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of this.parsedElement">
<td class="left-colomn">
<input type="number"
pattern="[0-9]{0-4}"
placeholder="e?"
[value]="data.trackId"
(input)="onTrackId(data, $event.target.value)"
[class.error]="data.trackIdDetected === true"
/>
</td>
<td class="right-colomn" >
<input type="text"
placeholder="Name of the Media"
[value]="data.title"
(input)="onTitle(data, $event.target.value)"
[class.error]="data.title === ''"
/>
<span *ngIf="data.nameDetected === true" class="error">
^^^This title already exist !!!
</span>
</td>
<td class="tool-colomn" >
<button class="button color-button-cancel color-shadow-black"
(click)="removeElmentFromList(data, $event.target.value)"
type="submit"
alt="Delete">
<i class="material-icons">delete</i>
</button>
</td>
</tr>
</tbody>
</table>
</colgroup>
<tbody>
<tr>
<td class="left-colomn">Gender:</td>
<td class="right-colomn">
<input type="text"
placeholder="Genre of the Media"
[value]="globalGender"
(input)="onGender($event.target.value)"
/>
</td>
</tr>
<tr>
<td class="left-colomn"></td>
<td class="right-colomn">
<!--<select [ngModel]="genreId"-->
<select (ngModelChange)="onChangeGender($event)">
@for (element of listGender; track element.value;) {
<option [ngValue]="element.value">{{element.label}}</option>
}
</select>
</td>
<td class="tool-colomn">
<!--
<button class="button color-button-normal color-shadow-black" (click)="newArtist()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
-->
</td>
</tr>
<tr>
<td class="left-colomn">Artist:</td>
<td class="right-colomn">
<input type="text"
placeholder="Artist of the Media"
[value]="globalArtist"
(input)="onArtist($event.target.value)"
/>
</td>
</tr>
<tr>
<td class="left-colomn"></td>
<td class="right-colomn">
<select [ngModel]="artistId"
(ngModelChange)="onChangeArtist($event)">
@for (element of listArtist; track element.value;) {
<option [ngValue]="element.value">{{element.label}}</option>
}
</select>
</td>
<td class="tool-colomn">
<!--
<button class="button color-button-normal color-shadow-black" (click)="newArtist()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
-->
</td>
</tr>
<tr>
<td class="left-colomn">Album:</td>
<td class="right-colomn">
<input type="text"
placeholder="Album title"
[value]="globalAlbum"
(input)="onAlbum($event.target.value)"
/>
</td>
</tr>
<tr>
<td class="left-colomn"></td>
<td class="right-colomn">
<select [ngModel]="albumId">
<!--(ngModelChange)="onChangeAlbum($event)">-->
@for (element of listAlbum; track element.value;) {
<option [ngValue]="element.value">{{element.label}}</option>
}
</select>
</td>
<td class="tool-colomn">
<!--
<button class="button color-button-normal color-shadow-black" (click)="newArtist()" type="submit">
<i class="material-icons">add_circle_outline</i>
</button>
-->
</td>
</tr>
</tbody>
</table>
</div>
<div class="clear"></div>
<div class="request_raw_table">
<table>
<colgroup>
<col style="width:10%">
<col style="width:70%">
<col style="width:10%">
</colgroup>
<thead>
<tr>
<th>Track ID:</th>
<th>Title:</th>
</tr>
</thead>
<tbody>
@for (data of parsedElement; track data.trackId;) {
<tr>
<td class="left-colomn">
<input type="number"
pattern="[0-9]{0-4}"
placeholder="e?"
[value]="data.trackId"
(input)="onTrackId(data, $event.target.value)"
[class.error]="data.trackIdDetected === true"
/>
</td>
<td class="right-colomn" >
<input type="text"
placeholder="Name of the Media"
[value]="data.title"
(input)="onTitle(data, $event.target.value)"
[class.error]="data.title === ''"
/>
@if(data.nameDetected === true) {
<span class="error">
^^^This title already exist !!!
</span>
}
</td>
<td class="tool-colomn" >
<button class="button color-button-cancel color-shadow-black"
(click)="removeElementFromList(data, $event.target.value)"
type="submit"
alt="Delete">
<i class="material-icons">delete</i>
</button>
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="clear"></div>
<div class="send_value">
<button class="button fill-x color-button-validate color-shadow-black"
[disabled]="!needSend"
(click)="sendFile()"
type="submit">
<i class="material-icons">cloud_upload</i> Upload
</button>
</div>
<div class="clear"></div>
@if(listFileInBdd) {
<div class="request_raw_table">
<table>
<colgroup>
<col style="width:10%">
<col style="width:70%">
<col style="width:10%">
</colgroup>
<thead>
<tr>
<th>Track ID:</th>
<th>Title:</th>
</tr>
</thead>
<tbody>
@for (data of listFileInBdd; track data.id;) {
<tr>
<td class="left-colomn" [class.error]="data.episodeDetected === true">{{data.episode}}</td>
<td class="right-colomn" [class.error]="data.nameDetected === true">{{data.name}}</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
<div class="clear"></div>
<div class="send_value">
<button class="button fill-x color-button-validate color-shadow-black"
[disabled]="!needSend"
(click)="sendFile()"
type="submit">
<i class="material-icons">cloud_upload</i> Upload
</button>
</div>
<div class="clear"></div>
<div class="request_raw_table" *ngIf="this.listFileInBdd">
<table>
<colgroup>
}
@if(parsedElement.length !== 0) {
<div class="fill-all">
<div class="request_raw_table">
<table>
<colgroup>
<col style="width:10%">
<col style="width:70%">
<col style="width:10%">
</colgroup>
<thead>
<tr>
<th>Track ID:</th>
<th>Title:</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of this.listFileInBdd">
<td class="left-colomn" [class.error]="data.episodeDetected === true">{{data.episode}}</td>
<td class="right-colomn" [class.error]="data.nameDetected === true">{{data.name}}</td>
</tr>
</tbody>
</table>
<col style="width:80%">
</colgroup>
<tbody>
@for (data of parsedFailedElement; track data.id;) {
<tr>
<td class="left-colomn">Rejected:</td>
<td class="right-colomn">
{{data.file.name}}<br/> ==&gt; {{data.reason}}
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</div>
<div *ngIf="this.parsedElement.length !== 0" class="fill-all">
<div class="request_raw_table">
<table>
<colgroup>
<col style="width:10%">
<col style="width:80%">
</colgroup>
<tbody>
<!-- no need
<tr *ngFor="let data of this.parsedElement">
<td class="left-colomn">Keep:</td>
<td class="right-colomn">
{{data.file.name}}
</td>
</tr>
-->
<tr *ngFor="let data of this.parsedFailedElement">
<td class="left-colomn">Rejected:</td>
<td class="right-colomn">
{{data.file.name}}<br/> ==&gt; {{data.reason}}
</td>
</tr>
</tbody>
</table>
</div>
</div>
}
</div>
<upload-progress [mediaTitle]="upload.labelMediaTitle"
[mediaUploaded]="upload.mediaSendSize"

View File

@@ -5,12 +5,12 @@
*/
import { Component, OnInit } from '@angular/core';
import { UploadProgress,PopInService, isNullOrUndefined } from '@kangaroo-and-rabbit/kar-cw';
import { } from '@kangaroo-and-rabbit/kar-cw/popin/upload-progress/upload-progress';
import { Artist, Gender } from 'app/back-api';
import { GenderService, ArtistService, TrackService, AlbumService } from 'app/service';
import { GenderService, ArtistService, TrackService, ArianeService, AlbumService } from 'app/service';
import { NodeData } from 'common/model';
import { UploadProgress } from 'common/popin/upload-progress/upload-progress';
import { PopInService } from 'common/service';
import { isNullOrUndefined } from 'common/utils';
export class ElementList {
constructor(
@@ -22,28 +22,29 @@ export class ElementList {
export class FileParsedElement {
public isSended: boolean = false;
public nameDetected: boolean = false;
public episodeDetected: boolean = false;s
public trackIdDetected: boolean = false; s
constructor(
public file: File,
public artist: string,
public album: string,
public trackId: number,
public title: string) {
// nothiing to do.
// nothing to do.
}
}
export class FileFailParsedElement {
constructor(
public id: number,
public file: File,
public reason: string) {
// nothiing to do.
// nothing to do.
}
}
@Component({
selector: 'app-track-edit',
templateUrl: './upload.html',
styleUrls: [ './upload.less' ]
styleUrls: ['./upload.less']
})
export class UploadScene implements OnInit {
@@ -56,11 +57,11 @@ export class UploadScene implements OnInit {
albumId: number = null;
needSend: boolean = false;
// list of all files already registered in the bdd to compare with the curent list of files.
// list of all files already registered in the bdd to compare with the current list of files.
listFileInBdd: any[] = undefined;
// section tha define the upload value to display in the pop-in of upload
public upload:UploadProgress = new UploadProgress();
public upload: UploadProgress = new UploadProgress();
listGender: ElementList[] = [
{ value: null, label: '---' },
@@ -74,19 +75,19 @@ export class UploadScene implements OnInit {
/*
config = {
displayKey: "label", // if objects array passed which key to be displayed defaults to description
search: true,
limitTo: 3,
displayKey: "label", // if objects array passed which key to be displayed defaults to description
search: true,
limitTo: 3,
};
*/
config = {
displayKey: 'description', // if objects array passed which key to be displayed defaults to description
search: true, // true/false for the search functionlity defaults to false,
search: true, // true/false for the search functionality defaults to false,
height: 'auto', // height of the list so that if there are more no of items it can show a scroll defaults to auto. With auto height scroll will never appear
placeholder: 'Select', // text to be displayed when no item is selected defaults to Select,
customComparator: () => {}, // a custom function using which user wants to sort the items. default is undefined and Array.sort() will be used in that case,
customComparator: () => { }, // a custom function using which user wants to sort the items. default is undefined and Array.sort() will be used in that case,
limitTo: 10, // number thats limits the no of options displayed in the UI (if zero, options will not be limited)
moreText: 'more', // text to be displayed whenmore than one items are selected like Option 1 + 5 more
moreText: 'more', // text to be displayed when more than one items are selected like Option 1 + 5 more
noResultsFound: 'No results found!', // text to be displayed when no items are found while searching
searchPlaceholder: 'Search', // label thats displayed in search input,
searchOnKey: 'description', // key on which search should be performed this will be selective search. if undefined this will be extensive search on all keys
@@ -99,51 +100,45 @@ export class UploadScene implements OnInit {
private artistService: ArtistService,
private albumService: AlbumService,
private trackService: TrackService,
private arianeService: ArianeService,
private popInService: PopInService) {
// nothing to do.
}
updateNeedSend(): boolean {
if(this.parsedElement.length === 0) {
if (this.parsedElement.length === 0) {
this.needSend = false;
return;
}
this.needSend = true;
for(let iii = 0; iii < this.parsedElement.length; iii++) {
if(isNullOrUndefined(this.parsedElement[iii].title) || this.parsedElement[iii].title === '') {
for (let iii = 0; iii < this.parsedElement.length; iii++) {
if (isNullOrUndefined(this.parsedElement[iii].title) || this.parsedElement[iii].title === '') {
this.needSend = false;
}
}
/*
if(isNullOrUndefined(this.genderId)) {
this.needSend = false;
}
*/
return this.needSend;
}
ngOnInit() {
let self = this;
this.listGender = [ { value: null, label: '---' } ];
this.listArtist = [ { value: null, label: '---' } ];
this.listAlbum = [ { value: null, label: '---' } ];
this.listGender = [{ value: null, label: '---' }];
this.listArtist = [{ value: null, label: '---' }];
this.listAlbum = [{ value: null, label: '---' }];
this.artistService.getOrder()
.then((response2) => {
for(let iii = 0; iii < response2.length; iii++) {
for (let iii = 0; iii < response2.length; iii++) {
self.listArtist.push({ value: response2[iii].id, label: response2[iii].name });
}
}).catch((response2) => {
console.log(`get response22 : ${ JSON.stringify(response2, null, 2)}`);
console.log(`get response22 : ${JSON.stringify(response2, null, 2)}`);
});
this.genderService.getOrder()
.then((response2: NodeData[]) => {
.then((response2: Gender[]) => {
//console.error(`Keep gender : ${ JSON.stringify(response2, null, 2)} ==> ${response2.length}`);
for(let iii = 0; iii < response2.length; iii++) {
for (let iii = 0; iii < response2.length; iii++) {
self.listGender.push({ value: response2[iii].id, label: response2[iii].name });
}
}).catch((response2) => {
console.log(`get response22 : ${ JSON.stringify(response2, null, 2)}`);
console.log(`get response22 : ${JSON.stringify(response2, null, 2)}`);
});
console.log(' END INIT ');
}
@@ -151,16 +146,16 @@ export class UploadScene implements OnInit {
onGender(value: any): void {
this.globalGender = value;
let self = this;
if(this.globalGender !== '') {
if (this.globalGender !== '') {
this.genderService.getLike(this.globalGender)
.then((response: any[]) => {
console.log(`find element: ${ response.length}`);
for(let iii = 0; iii < response.length; iii++) {
console.log(` - ${ JSON.stringify(response[iii])}`);
console.log(`find element: ${response.length}`);
for (let iii = 0; iii < response.length; iii++) {
console.log(` - ${JSON.stringify(response[iii])}`);
}
if(response.length === 0) {
if (response.length === 0) {
self.genderId = undefined;
} else if(response.length === 1) {
} else if (response.length === 1) {
self.genderId = response[0].id;
}
}).catch((response) => {
@@ -174,9 +169,9 @@ export class UploadScene implements OnInit {
onChangeGender(value: any): void {
this.globalGender = value;
if(!isNullOrUndefined(value)) {
for(let iii = 0; iii < this.listGender.length; iii++) {
if(this.listGender[iii].value === value) {
if (!isNullOrUndefined(value)) {
for (let iii = 0; iii < this.listGender.length; iii++) {
if (this.listGender[iii].value === value) {
this.globalGender = this.listGender[iii].label;
break;
}
@@ -186,31 +181,34 @@ export class UploadScene implements OnInit {
}
private updateTheListOfAlbum() {
this.listAlbum = [ { value: null, label: '---' } ];
this.listAlbum = [{ value: null, label: '---' }];
if (isNullOrUndefined(this.artistId)) {
return;
}
let self = this;
this.artistService.getAlbum(this.artistId)
.then((response2) => {
for(let iii = 0; iii < response2.length; iii++) {
self.listAlbum.push({ value: response2[iii].id, label: response2[iii].name });
}
}).catch((response2) => {
console.log(`get response22 : ${ JSON.stringify(response2, null, 2)}`);
this.trackService.getAlbumIdsOfAnArtist(this.artistId)
.then((listAlbumIds: number[]) => {
this.albumService.getAll(listAlbumIds)
.then((response2) => {
for (let iii = 0; iii < response2.length; iii++) {
self.listAlbum.push({ value: response2[iii].id, label: response2[iii].name });
}
}).catch((response2) => {
console.log(`get response22 : ${JSON.stringify(response2, null, 2)}`);
});
});
}
onArtist(value: any): void {
this.globalArtist = value;
let self = this;
if(this.globalArtist !== '') {
if (this.globalArtist !== '') {
console.log(`update artist List Element: ${this.globalArtist}`);
this.artistService.getLike(this.globalArtist)
.then((response: any[]) => {
console.log(` ==> find artist like ${this.globalArtist} : ${ JSON.stringify(response, null, 2)}`);
if(response.length === 0) {
console.log(` ==> find artist like ${this.globalArtist} : ${JSON.stringify(response, null, 2)}`);
if (response.length === 0) {
self.artistId = undefined;
} else if(response.length === 1) {
} else if (response.length === 1) {
self.artistId = response[0].id;
self.updateTheListOfAlbum();
}
@@ -220,7 +218,7 @@ export class UploadScene implements OnInit {
self.updateListOfTrackToCheck();
}
}).catch((response) => {
console.log(` ==> CAN NOT find artist like ${this.globalArtist} : ${ response.length}`);
console.log(` ==> CAN NOT find artist like ${this.globalArtist} : ${response.length}`);
self.artistId = undefined;
});
}
@@ -228,9 +226,9 @@ export class UploadScene implements OnInit {
}
onChangeArtist(value: any): void {
this.artistId = value;
if(!isNullOrUndefined(value)) {
for(let iii = 0; iii < this.listArtist.length; iii++) {
if(this.listArtist[iii].value === value) {
if (!isNullOrUndefined(value)) {
for (let iii = 0; iii < this.listArtist.length; iii++) {
if (this.listArtist[iii].value === value) {
this.globalArtist = this.listArtist[iii].label;
break;
}
@@ -250,18 +248,19 @@ export class UploadScene implements OnInit {
data.title = value;
this.updateNeedSend();
}
removeElmentFromList(data: FileParsedElement, value: any): void {
for(let iii = 0; iii < this.parsedElement.length; iii++) {
if(this.parsedElement[iii] === data) {
removeElementFromList(data: FileParsedElement, value: any): void {
for (let iii = 0; iii < this.parsedElement.length; iii++) {
if (this.parsedElement[iii] === data) {
this.parsedElement.splice(iii, 1);
break;
}
}
this.parsedFailedElement.push(new FileFailParsedElement(data.file, 'Removed by user.'));
this.parsedFailedElement.push(new FileFailParsedElement(this.parsedFailedElement.length, data.file, 'Removed by user.'));
this.updateNeedSend();
}
onEpisode(data: FileParsedElement, value: any): void {
onTrackId(data: FileParsedElement, value: any): void {
data.trackId = value;
// console.log("change episode ID: " + value + " ==> " + this.parseEpisode.toString());
this.updateNeedSend();
@@ -281,7 +280,7 @@ export class UploadScene implements OnInit {
this.artistId = null;
this.albumId = null;
//this.listGender = [ { value: null, label: '---' } ];
this.listAlbum = [ { value: null, label: '---' } ];
this.listAlbum = [{ value: null, label: '---' }];
}
addFileWithMetaData(file: File) {
@@ -291,38 +290,38 @@ export class UploadScene implements OnInit {
let trackIdNumber: number | null = undefined;
let title: string = '';
console.log(`select file ${ file.name}`);
console.log(`select file ${file.name}`);
let tmpName = file.name.replace(/[ \t]*-[ \t]*/g, '-');
//tmpName = tmpName.replace(/_/g, '-');
//tmpName = tmpName.replace(/--/g, '-');
console.log(`select file ${ tmpName}`);
console.log(`select file ${tmpName}`);
const splitElement = tmpName.split('~');
if(splitElement.length > 1) {
if (splitElement.length > 1) {
artist = splitElement[0];
tmpName = tmpName.substring(artist.length+1);
tmpName = tmpName.substring(artist.length + 1);
}
const splitElement2 = tmpName.split('\#');
if(splitElement2.length > 1) {
if (splitElement2.length > 1) {
album = splitElement2[0];
tmpName = tmpName.substring(album.length+1);
tmpName = tmpName.substring(album.length + 1);
}
//console.log("ploppppp " + tmpName);
const splitElement3 = tmpName.split('-');
if(splitElement3.length > 1) {
if (splitElement3.length > 1) {
trackIdNumber = parseInt(splitElement3[0], 10);
tmpName = tmpName.substring(splitElement3[0].length+1);
tmpName = tmpName.substring(splitElement3[0].length + 1);
}
//console.log("KKKppppp " + tmpName);
//console.log(" ===> " + splitElement3[0]);
title = tmpName;
if(isNaN(trackIdNumber)) {
if (isNaN(trackIdNumber)) {
trackIdNumber = undefined;
}
// remove extention
// remove extension
title = title.replace(new RegExp('\\.(webm|WEBM|Webm)'), '');
let tmp = new FileParsedElement(file, artist, album, trackIdNumber, title);
console.log(`==>${ JSON.stringify(tmp)}`);
console.log(`==>${JSON.stringify(tmp)}`);
// add it in the list.
this.parsedElement.push(tmp);
}
@@ -333,20 +332,20 @@ export class UploadScene implements OnInit {
onChangeFile(value: any): void {
this.clearData();
for(let iii = 0; iii < value.files.length; iii++) {
for (let iii = 0; iii < value.files.length; iii++) {
this.addFileWithMetaData(value.files[iii]);
}
// check if all global parameters are generic:
if(this.parsedElement.length === 0) {
if (this.parsedElement.length === 0) {
this.updateNeedSend();
return;
}
// we verify fith the first value to remove all unknown ...
// we verify with the first value to remove all unknown ...
// clean different gender:
/*for(let iii = 1; iii < this.parsedElement.length; iii++) {
console.log(`check gender [${ iii + 1 }/${ this.parsedElement.length }] '${ this.parsedElement[0].gender } !== ${ this.parsedElement[iii].gender }'`);
if(this.parsedElement[0].gender !== this.parsedElement[iii].gender) {
this.parsedFailedElement.push(new FileFailParsedElement(this.parsedElement[iii].file, 'Remove from list due to wrong gender value'));
this.parsedFailedElement.push(new FileFailParsedElement(this.parsedFailedElement.length, this.parsedElement[iii].file, 'Remove from list due to wrong gender value'));
console.log(`Remove from list (!= playlist) : [${ iii + 1 }/${ this.parsedElement.length }] '${ this.parsedElement[iii].file.name }'`);
this.parsedElement.splice(iii, 1);
iii--;
@@ -354,21 +353,21 @@ export class UploadScene implements OnInit {
}
*/
// clean different artist:
for(let iii = 1; iii < this.parsedElement.length; iii++) {
console.log(`check artist [${ iii + 1 }/${ this.parsedElement.length }] '${ this.parsedElement[0].artist } !== ${ this.parsedElement[iii].artist }'`);
if(this.parsedElement[0].artist !== this.parsedElement[iii].artist) {
this.parsedFailedElement.push(new FileFailParsedElement(this.parsedElement[iii].file, 'Remove from list due to wrong artist value'));
console.log(`Remove from list (!= artist) : [${ iii + 1 }/${ this.parsedElement.length }] '${ this.parsedElement[iii].file.name }'`);
for (let iii = 1; iii < this.parsedElement.length; iii++) {
console.log(`check artist [${iii + 1}/${this.parsedElement.length}] '${this.parsedElement[0].artist} !== ${this.parsedElement[iii].artist}'`);
if (this.parsedElement[0].artist !== this.parsedElement[iii].artist) {
this.parsedFailedElement.push(new FileFailParsedElement(this.parsedFailedElement.length, this.parsedElement[iii].file, 'Remove from list due to wrong artist value'));
console.log(`Remove from list (!= artist) : [${iii + 1}/${this.parsedElement.length}] '${this.parsedElement[iii].file.name}'`);
this.parsedElement.splice(iii, 1);
iii--;
}
}
// clean different album:
for(let iii = 1; iii < this.parsedElement.length; iii++) {
console.log(`check album [${ iii + 1 }/${ this.parsedElement.length }] '${ this.parsedElement[0].album } !== ${ this.parsedElement[iii].album }'`);
if(this.parsedElement[0].album !== this.parsedElement[iii].album) {
this.parsedFailedElement.push(new FileFailParsedElement(this.parsedElement[iii].file, 'Remove from list due to wrong album value'));
console.log(`Remove from list (!= album) : [${ iii + 1 }/${ this.parsedElement.length }] '${ this.parsedElement[iii].file.name }'`);
for (let iii = 1; iii < this.parsedElement.length; iii++) {
console.log(`check album [${iii + 1}/${this.parsedElement.length}] '${this.parsedElement[0].album} !== ${this.parsedElement[iii].album}'`);
if (this.parsedElement[0].album !== this.parsedElement[iii].album) {
this.parsedFailedElement.push(new FileFailParsedElement(this.parsedFailedElement.length, this.parsedElement[iii].file, 'Remove from list due to wrong album value'));
console.log(`Remove from list (!= album) : [${iii + 1}/${this.parsedElement.length}] '${this.parsedElement[iii].file.name}'`);
this.parsedElement.splice(iii, 1);
iii--;
}
@@ -384,7 +383,7 @@ export class UploadScene implements OnInit {
}
sendFile(): void {
console.log(`Send file requested ... ${ this.parsedElement.length}`);
console.log(`Send file requested ... ${this.parsedElement.length}`);
this.upload = new UploadProgress();
// display the upload pop-in
this.popInService.open('popin-upload-progress');
@@ -395,16 +394,16 @@ export class UploadScene implements OnInit {
let self = this;
this.uploadFile(this.parsedElement[id], id, total, () => {
let id2 = id + 1;
if(id2 < total) {
if (id2 < total) {
self.globalUpLoad(id2, total);
} else {
self.upload.result = 'Media creation done';
}
}, (value:string) => {
self.upload.error = `Error in the upload of the data...${ value}`;
}, (value: string) => {
self.upload.error = `Error in the upload of the data...${value}`;
});
}
uploadFile(elemnent: FileParsedElement, id: number, total: number, sendDone: any, errorOccured: any): void {
uploadFile(element: FileParsedElement, id: number, total: number, sendDone: any, errorOccurred: any): void {
let self = this;
self.upload.labelMediaTitle = '';
@@ -415,95 +414,95 @@ export class UploadScene implements OnInit {
}
*/
// add artist
if(!isNullOrUndefined(self.globalArtist)) {
if(self.upload.labelMediaTitle.length !== 0) {
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle }:`;
if (!isNullOrUndefined(self.globalArtist)) {
if (self.upload.labelMediaTitle.length !== 0) {
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle}:`;
}
self.upload.labelMediaTitle = self.upload.labelMediaTitle + self.globalArtist;
}
// add album
if(!isNullOrUndefined(self.globalAlbum) && self.globalAlbum.toString().length !== 0) {
if(self.upload.labelMediaTitle.length !== 0) {
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle }-`;
if (!isNullOrUndefined(self.globalAlbum) && self.globalAlbum.toString().length !== 0) {
if (self.upload.labelMediaTitle.length !== 0) {
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle}-`;
}
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle }s${ self.globalAlbum.toString()}`;
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle}s${self.globalAlbum.toString()}`;
}
// add episode ID
if(!isNullOrUndefined(elemnent.trackId) && elemnent.trackId.toString().length !== 0) {
if(self.upload.labelMediaTitle.length !== 0) {
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle }-`;
if (!isNullOrUndefined(element.trackId) && element.trackId.toString().length !== 0) {
if (self.upload.labelMediaTitle.length !== 0) {
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle}-`;
}
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle }e${ elemnent.trackId.toString()}`;
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle}e${element.trackId.toString()}`;
}
// add title
if(self.upload.labelMediaTitle.length !== 0) {
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle }-`;
if (self.upload.labelMediaTitle.length !== 0) {
self.upload.labelMediaTitle = `${self.upload.labelMediaTitle}-`;
}
self.upload.labelMediaTitle = `[${ id + 1 }/${ total }]${ self.upload.labelMediaTitle }${elemnent.title}`;
self.upload.labelMediaTitle = `[${id + 1}/${total}]${self.upload.labelMediaTitle}${element.title}`;
self.trackService.uploadFile(elemnent.file,
self.trackService.uploadFile(element.file,
self.globalGender,
self.globalArtist,
self.globalAlbum,
elemnent.trackId,
elemnent.title,
element.trackId,
element.title,
(count, totalTmp) => {
// console.log("upload : " + count*100/totalTmp);
// console.log("upload : " + count*100/totalTmp);
self.upload.mediaSendSize = count;
self.upload.mediaSize = totalTmp;
})
.then((response) => {
console.log(`get response of track : ${ JSON.stringify(response, null, 2)}`);
console.log(`get response of track : ${JSON.stringify(response, null, 2)}`);
sendDone();
}).catch((response) => {
// self.error = "Can not get the data";
// self.error = "Can not get the data";
console.log('Can not add the data in the system...');
errorOccured(JSON.stringify(response, null, 2));
errorOccurred(JSON.stringify(response, null, 2));
});
}
public checkSimilarString(valueA:string, valueB:string): boolean {
public checkSimilarString(valueA: string, valueB: string): boolean {
let valueAL = valueA.toLowerCase();
let valueBL = valueB.toLowerCase();
valueAL = valueAL.replace(/[ \t\n\r-_#~@]/g, '');
valueBL = valueBL.replace(/[ \t\n\r-_#~@]/g, '');
if(valueAL === valueBL) {
if (valueAL === valueBL) {
return true;
}
if(valueAL.startsWith(valueBL)) {
if (valueAL.startsWith(valueBL)) {
return true;
}
if(valueBL.startsWith(valueAL)) {
if (valueBL.startsWith(valueAL)) {
return true;
}
return false;
}
checkConcordence():void {
if(isNullOrUndefined(this.parsedElement)) {
checkConcordance(): void {
if (isNullOrUndefined(this.parsedElement)) {
return;
}
// ckear checker
for(let iii = 0; iii < this.parsedElement.length; iii++) {
for (let iii = 0; iii < this.parsedElement.length; iii++) {
this.parsedElement[iii].nameDetected = false;
this.parsedElement[iii].episodeDetected = false;
this.parsedElement[iii].trackIdDetected = false;
}
if(isNullOrUndefined(this.listFileInBdd)) {
if (isNullOrUndefined(this.listFileInBdd)) {
return;
}
for(let iii = 0; iii < this.listFileInBdd.length; iii++) {
for (let iii = 0; iii < this.listFileInBdd.length; iii++) {
this.listFileInBdd[iii].nameDetected = false;
this.listFileInBdd[iii].episodeDetected = false;
this.listFileInBdd[iii].trackIdDetected = false;
}
for(let iii = 0; iii < this.parsedElement.length; iii++) {
for(let jjj = 0; jjj < this.listFileInBdd.length; jjj++) {
if(this.checkSimilarString(this.parsedElement[iii].title, this.listFileInBdd[jjj].name)) {
for (let iii = 0; iii < this.parsedElement.length; iii++) {
for (let jjj = 0; jjj < this.listFileInBdd.length; jjj++) {
if (this.checkSimilarString(this.parsedElement[iii].title, this.listFileInBdd[jjj].name)) {
this.parsedElement[iii].nameDetected = true;
this.listFileInBdd[jjj].nameDetected = true;
}
if(this.parsedElement[iii].trackId === this.listFileInBdd[jjj].episode) {
this.parsedElement[iii].episodeDetected = true;
this.listFileInBdd[jjj].episodeDetected = true;
if (this.parsedElement[iii].trackId === this.listFileInBdd[jjj].episode) {
this.parsedElement[iii].trackIdDetected = true;
this.listFileInBdd[jjj].trackIdDetected = true;
}
}
}
@@ -511,22 +510,22 @@ export class UploadScene implements OnInit {
updateListOfTrackToCheck(): void {
// No artist ID set ==> nothing to do.
if(isNullOrUndefined(this.artistId)) {
if (isNullOrUndefined(this.artistId)) {
this.listFileInBdd = undefined;
return;
}
let self = this;
// no album check only the artist files.
if(isNullOrUndefined(this.globalAlbum)) {
if (isNullOrUndefined(this.globalAlbum)) {
console.error(`NO ALBUM ==> check artist ID...`);
self.artistService.getAllTracks(self.artistId)
self.trackService.getTracksOfAnArtist(self.artistId)
.then((response: any[]) => {
self.listFileInBdd = response;
console.error(`find track: ${JSON.stringify(response, null, 2)}`);
// for (let iii = 0; iii<response.length; iii++) {
// console.log(" - " + JSON.stringify(response[iii]));
// }
self.checkConcordence();
self.checkConcordance();
}).catch((response) => {
self.listFileInBdd = undefined;
});
@@ -536,50 +535,52 @@ export class UploadScene implements OnInit {
self.albumId = undefined;
console.error(`ALBUM ==> check album values...`);
// set 1 find the ID of the album:
this.artistService.getAlbum(this.artistId)
.then((response: any[]) => {
console.log(`find album: ${JSON.stringify(response, null, 2)}`);
for(let iii = 0; iii < response.length; iii++) {
// console.log(" - " + JSON.stringify(response[iii]) + 'compare with : ' + JSON.stringify(self.globalAlbum));
if(response[iii].name === `${self.globalAlbum}`) {
self.albumId = response[iii].id;
break;
}
}
if(isNullOrUndefined(self.albumId)) {
return;
}
self.albumService.getTrack(self.albumId)
.then((response2: any[]) => {
self.listFileInBdd = response2;
console.log(`find album: ${JSON.stringify(response, null, 2)}`);
// console.log("find track: " + response2.length);
// for (let iii = 0; iii<response2.length; iii++) {
// console.log(" - " + JSON.stringify(response2[iii]));
// }
self.checkConcordence();
}).catch((response3) => {
self.listFileInBdd = undefined;
});
this.trackService.getAlbumIdsOfAnArtist(this.artistId)
.then((listAlbumIds: number[]) => {
this.artistService.getAll(listAlbumIds)
.then((response: Artist[]) => {
for (let iii = 0; iii < response.length; iii++) {
// console.log(" - " + JSON.stringify(response[iii]) + 'compare with : ' + JSON.stringify(self.globalAlbum));
if (response[iii].name === `${self.globalAlbum}`) {
self.albumId = response[iii].id;
break;
}
}
if (isNullOrUndefined(self.albumId)) {
return;
}
self.trackService.getTracksWithAlbumId(self.albumId)
.then((response2: any[]) => {
self.listFileInBdd = response2;
console.log(`find album: ${JSON.stringify(response, null, 2)}`);
// console.log("find track: " + response2.length);
// for (let iii = 0; iii<response2.length; iii++) {
// console.log(" - " + JSON.stringify(response2[iii]));
// }
self.checkConcordance();
}).catch((response3) => {
self.listFileInBdd = undefined;
});
})
}).catch((response4) => {
self.listFileInBdd = undefined;
});
}
eventPopUpAlbum(event: string): void {
console.log(`GET event: ${ event}`);
console.log(`GET event: ${event}`);
this.popInService.close('popin-new-album');
}
eventPopUpArtist(event: string): void {
console.log(`GET event: ${ event}`);
console.log(`GET event: ${event}`);
this.popInService.close('popin-new-artist');
}
eventPopUpType(event: string): void {
console.log(`GET event: ${ event}`);
console.log(`GET event: ${event}`);
this.popInService.close('popin-new-type');
}
eventPopUpPlaylist(event: string): void {
console.log(`GET event: ${ event}`);
console.log(`GET event: ${event}`);
this.popInService.close('popin-new-playlist');
}

View File

@@ -0,0 +1,95 @@
import { DataStore, DataTools, TypeCheck, isNullOrUndefined } from "@kangaroo-and-rabbit/kar-cw";
export class GenericDataService<TYPE> {
protected dataStore: DataStore<TYPE>;
setStore(dataStore: DataStore<TYPE>) {
this.dataStore = dataStore;
}
gets(): Promise<TYPE[]> {
return this.dataStore.getData();
}
get(id: number): Promise<TYPE> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: TYPE[]) => {
let data = DataTools.get(response, id);
if (isNullOrUndefined(data)) {
reject('Data does not exist in the local BDD');
return;
}
resolve(data);
return;
}).catch((response) => {
reject(response);
});
});
}
getAll(ids: number[]): Promise<TYPE[]> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: TYPE[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.EQUAL,
key: 'id',
value: ids,
},
]);
resolve(data);
return;
}).catch((response) => {
reject(response);
});
});
}
getLike(value: string): Promise<TYPE[]> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: TYPE[]) => {
let data = DataTools.getNameLike(response, value);
if (isNullOrUndefined(data) || data.length === 0) {
reject('Data does not exist in the local BDD');
return;
}
resolve(data);
return;
}).catch((response) => {
reject(response);
});
});
}
getOrder(): Promise<TYPE[]> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: TYPE[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.NOT_EQUAL,
key: 'id',
value: [undefined, null],
},
],
["name", "id"],
);
resolve(data);
}).catch((response) => {
console.log(`[E] ${self.constructor.name}: can not retrieve BDD values`);
reject(response);
});
});
}
}

View File

@@ -1,182 +0,0 @@
import { isNodeData, NodeData } from "common/model";
import { HttpWrapperService, BddService } from "common/service";
import { DataInterface, isArrayOf, isNullOrUndefined, TypeCheck } from "common/utils";
export class GenericInterfaceModelDB {
constructor(
protected serviceName: string,
protected http: HttpWrapperService,
protected bdd: BddService) {
// nothing to do ...
}
gets(): Promise<NodeData[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
.then((response: DataInterface) => {
let data = response.gets();
if (isNullOrUndefined(data)) {
reject('Data does not exist in the local BDD');
return;
}
resolve(data);
return;
}).catch((response) => {
reject(response);
});
});
}
getLike(nameArtist: string): any {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
.then((response: DataInterface) => {
let data = response.getNameLike(nameArtist);
if (data === null || data === undefined || data.length === 0) {
reject('Data does not exist in the local BDD');
return;
}
resolve(data);
return;
}).catch((response) => {
reject(response);
});
});
}
getOrder(): Promise<NodeData[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.NOT_EQUAL,
key: 'id',
value: [undefined, null],
},
],
['name', 'id']);
//data = response.gets();
if (isArrayOf(data, isNodeData)) {
resolve(data);
}
reject("The model is wrong ...");
}).catch((response) => {
console.log(`[E] ${self.constructor.name}: can not retrive BDD values`);
reject(response);
});
});
}
get(id: number): Promise<NodeData> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
.then((response: DataInterface) => {
let data = response.get(id);
if (isNullOrUndefined(data)) {
reject('Data does not exist in the local BDD');
return;
}
resolve(data);
return;
}).catch((response) => {
reject(response);
});
});
}
getAll(ids: number[]): Promise<NodeData[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'id',
value: ids,
},
],
['name', 'id']);
resolve(data);
return;
}).catch((response) => {
reject(response);
});
});
}
getData(): Promise<NodeData[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
.then((response: DataInterface) => {
let data = response.gets();
resolve(data);
}).catch((response) => {
console.log(`[E] ${self.constructor.name}: can not retrive BDD values`);
reject(response);
});
});
}
insert(data: any): any {
let ret = this.http.postSpecific([this.serviceName], data);
return this.bdd.addAfterPost(this.serviceName, ret);
}
patch(id: number, data: any): any {
let ret = this.http.patchSpecific([this.serviceName, id], data);
return this.bdd.setAfterPut(this.serviceName, id, ret);
}
delete(id: number): any {
let ret = this.http.deleteSpecific([this.serviceName, id]);
return this.bdd.delete(this.serviceName, id, ret);
}
deleteCover(nodeId: number, coverId: number) {
let self = this;
return new Promise((resolve, reject) => {
self.http.getSpecific([this.serviceName, nodeId, 'rm_cover', coverId])
.then((response) => {
let data = response;
if (data === null || data === undefined) {
reject('error retrive data from server');
return;
}
self.bdd.asyncSetInDB(self.serviceName, nodeId, data);
resolve(data);
}).catch((response) => {
reject(response);
});
});
}
uploadCover(file: File,
nodeId: number,
progress: any = null) {
const formData = new FormData();
formData.append('fileName', file.name);
formData.append('id', nodeId.toString());
formData.append('file', file);
let self = this;
return new Promise((resolve, reject) => {
self.http.uploadMultipart(`${this.serviceName}/${nodeId}/add_cover/`, formData, progress)
.then((response) => {
let data = response;
if (data === null || data === undefined) {
reject('error retrive data from server');
return;
}
self.bdd.asyncSetInDB(self.serviceName, nodeId, data);
resolve(data);
}).catch((response) => {
reject(response);
});
});
}
}

View File

@@ -5,129 +5,153 @@
*/
import { Injectable } from '@angular/core';
import { NodeData } from 'common/model';
import { HttpWrapperService, BddService } from 'common/service';
import { DataInterface, TypeCheck } from 'common/utils';
import { GenericInterfaceModelDB } from './GenericInterfaceModelDB';
import { Album, AlbumResource, UUID } from 'app/back-api';
import { RESTConfig, isArrayOf } from 'app/back-api/rest-tools';
import { environment } from 'environments/environment';
import { GenericDataService } from './GenericDataService';
import { DataTools, DataStore, SessionService, TypeCheck, isNumber } from '@kangaroo-and-rabbit/kar-cw';
@Injectable()
export class AlbumService extends GenericInterfaceModelDB {
constructor(http: HttpWrapperService,
bdd: BddService) {
super('album', http, bdd);
}
getAllTracksForAlbums(idAlbums: number[]): Promise<number[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbums,
},
],
[ 'name' ]); // tODO : set the Id in the track ...
// filter with artist- ID !!!
const listId = DataInterface.extractLimitOne(data, "id");
resolve(listId);
}).catch((response) => {
reject(response);
});
});
export class AlbumService extends GenericDataService<Album> {
getRestConfig(): RESTConfig {
return {
server: environment.server.karusic,
token: this.session.getToken()
}
}
/**
* Get all the track for a specific album
* @param idAlbum - Id of the album.
* @returns a promise on the list of track elements
*/
getTrack(idAlbum:number): Promise<NodeData[]> {
let self = this;
private lambdaGets(): Promise<Album[]> {
const self = this;
return AlbumResource.gets({ restConfig: this.getRestConfig() });
}
constructor(private session: SessionService) {
super();
console.log('Start AlbumService');
this.setStore(new DataStore<Album>(() => this.lambdaGets()));
}
insert(data: Album): Promise<Album> {
const self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbum,
},
],
[ 'name' ]); // tODO : set the Id in the track ...
resolve(data);
}).catch((response) => {
reject(response);
});
AlbumResource.post({
restConfig: this.getRestConfig(),
data
}).then((value: Album) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
patch(id: number, data: Album): Promise<Album> {
const self = this;
return new Promise((resolve, reject) => {
AlbumResource.patch({
restConfig: this.getRestConfig(),
params: {
id
},
data
}).then((value: Album) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
delete(id: number): Promise<void> {
const self = this;
return new Promise((resolve, reject) => {
AlbumResource.remove({
restConfig: this.getRestConfig(),
params: {
id
}
}).then(() => {
self.dataStore.delete(id);
resolve();
}).catch((error) => {
reject(error);
});
});
}
deleteCover(id: number, coverId: UUID): Promise<Album> {
let self = this;
return new Promise((resolve, reject) => {
AlbumResource.removeCover({
restConfig: this.getRestConfig(),
params: {
id,
coverId
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
uploadCover(id: number,
file: File,
progress: any = null): Promise<Album> {
let self = this;
return new Promise((resolve, reject) => {
AlbumResource.uploadCover({
restConfig: this.getRestConfig(),
params: {
id,
},
data: {
file,
fileName: file.name
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
/**
* Get all the artists for a specific album
* @param idAlbum - Id of the album.
* @returns a promise on the list of Artist names for this album
* @returns a promise on the list of Artist ID for this album
*/
getArtists(idAlbum:number): Promise<String[]> {
getArtists(idAlbum: number): Promise<number[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbum,
},
self.gets()
.then((response: Album[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbum,
},
],
[ 'name' ]);
['name']);
// filter with artist- ID !!!
const listArtistId = DataInterface.extractLimitOneList(data, "artists");
//console.log(`${idAlbum} ==> List Of ids: ${JSON.stringify(listArtistId, null, 2)} `);
self.bdd.get('artist')
.then((response:DataInterface) => {
let dataArtist = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'id',
value: listArtistId,
},
], [ 'name']);
const listArtistNames = DataInterface.extractLimitOne(dataArtist, "name");
resolve(listArtistNames);
return;
}).catch((response) => {
reject(response);
});
const listArtistId = DataTools.extractLimitOneList(data, "artists");
if (isArrayOf(listArtistId, isNumber)) {
resolve(listArtistId);
} else {
reject(`Fail to get the ids (impossible case) ${listArtistId}`);
}
}).catch((response) => {
reject(response);
});
});
}
/**
* Get the number of track in this saison ID
* @param AlbumId - Id of the album.
* @returns The number of element present in this saison
*/
countTrack(AlbumId:number): Promise<number> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: AlbumId,
},
]);
resolve(data.length);
}).catch((response) => {
reject(response);
});
});
}
}

View File

@@ -14,8 +14,8 @@ import { ArtistService } from './artist';
import { AlbumService } from './album';
import { TrackService } from './track';
import { environment } from 'environments/environment';
import { NodeData } from 'common/model';
import { isNullOrUndefined, isStringNullOrUndefined, isUndefined } from 'common/utils';
import { NodeSmall } from 'app/back-api';
import { isNullOrUndefined, isStringNullOrUndefined, isUndefined } from '@kangaroo-and-rabbit/kar-cw';
export class InputOrders {
public genderId: number = undefined;
@@ -29,81 +29,79 @@ export class InputOrders {
export class ArianeService {
public genderId: number = undefined;
public typeName: string = undefined;
@Output() typeChange: EventEmitter<number> = new EventEmitter();
@Output() typeChange: EventEmitter<number> = new EventEmitter();
public playlistId: number = undefined;
public playlistName: string = undefined;
@Output() playlistChange: EventEmitter<number> = new EventEmitter();
public playlistId: number = undefined;
public playlistName: string = undefined;
@Output() playlistChange: EventEmitter<number> = new EventEmitter();
public artistId: number = undefined;
public artistName: string = undefined;
@Output() artistChange: EventEmitter<number> = new EventEmitter();
public artistId: number = undefined;
public artistName: string = undefined;
@Output() artistChange: EventEmitter<number> = new EventEmitter();
public albumId: number = undefined;
public albumName: string = undefined;
@Output() albumChange: EventEmitter<number> = new EventEmitter();
public albumId: number = undefined;
public albumName: string = undefined;
@Output() albumChange: EventEmitter<number> = new EventEmitter();
public trackId: number = undefined;
public trackName: string = undefined;
@Output() trackChange: EventEmitter<number> = new EventEmitter();
public trackId: number = undefined;
public trackName: string = undefined;
@Output() trackChange: EventEmitter<number> = new EventEmitter();
@Output() update: EventEmitter<InputOrders> = new EventEmitter();
@Output() update: EventEmitter<InputOrders> = new EventEmitter();
public segment: string = "";
@Output() segmentChange: EventEmitter<string> = new EventEmitter();
@Output() segmentChange: EventEmitter<string> = new EventEmitter();
constructor(private router: Router,
private typeService: GenderService,
private playlistService: PlaylistService,
private artistService: ArtistService,
private albumService: AlbumService,
private trackService: TrackService) {
//console.log('Start ArianeService');
//this.route.
let self = this;
this.router.events.subscribe((event: any) => {
if (event instanceof NavigationStart) {
// Show progress spinner or progress bar
//console.log('>>>>>>>>>>>>>> Route change detected');
}
constructor(private router: Router,
private typeService: GenderService,
private playlistService: PlaylistService,
private artistService: ArtistService,
private albumService: AlbumService,
private trackService: TrackService) {
console.log('Start ArianeService');
//this.route.
let self = this;
this.router.events.subscribe((event: any) => {
if (event instanceof NavigationStart) {
// Show progress spinner or progress bar
//console.log('>>>>>>>>>>>>>> Route change detected');
}
if (event instanceof NavigationEnd) {
// Hide progress spinner or progress bar
//this.currentRoute = event.url;
//console.log(`>>>>>>>>>>>> ${event}`);
self.updateProperties();
}
if (event instanceof NavigationEnd) {
// Hide progress spinner or progress bar
//this.currentRoute = event.url;
//console.log(`>>>>>>>>>>>> ${event}`);
self.updateProperties();
}
if (event instanceof NavigationError) {
// Hide progress spinner or progress bar
if (event instanceof NavigationError) {
// Hide progress spinner or progress bar
// Present error to user
//console.log(`<<<<<<<<<<<<< ${event.error}`);
}
});
// Present error to user
//console.log(`<<<<<<<<<<<<< ${event.error}`);
}
}
});
getCurrrentSegment(): string|undefined {
}
getCurrrentSegment(): string | undefined {
return this.segment;
}
getIsParam(params: any, name: string): undefined|number {
let valueStr = params.get(name);
if(isNullOrUndefined(valueStr) || isStringNullOrUndefined(valueStr)) {
return undefined;
}
return parseInt(valueStr, 10);
getIsParam(params: any, name: string): undefined | number {
let valueStr = params.get(name);
if (isNullOrUndefined(valueStr) || isStringNullOrUndefined(valueStr)) {
return undefined;
}
return parseInt(valueStr, 10);
}
updateProperties() {
updateProperties() {
let elem = this.router.routerState.root;
while (!isNullOrUndefined(elem.firstChild)) {
elem = elem.firstChild;
}
//console.log(`!!!!!!!!!!!!!!!!!!!!!!!!!! ${JSON.stringify(elem.snapshot.paramMap)}`);
let params = elem.snapshot.paramMap;
let segment: string[] = location.pathname.split("/");
while (segment.length > 1 && (segment[0] === "" || segment[0] === environment.applName)) {
@@ -122,17 +120,17 @@ export class ArianeService {
}
console.log(`segment: ${JSON.stringify(this.segment)}`);
console.log(`params: ${JSON.stringify(params)}`);
let genderId = this.getIsParam(params, 'genderId');
let playlistId = this.getIsParam(params, 'playlistId');
let artistId = this.getIsParam(params, 'artistId');
let albumId = this.getIsParam(params, 'albumId');
let trackId = this.getIsParam(params, 'trackId');
let genderId = this.getIsParam(params, 'genderId');
let playlistId = this.getIsParam(params, 'playlistId');
let artistId = this.getIsParam(params, 'artistId');
let albumId = this.getIsParam(params, 'albumId');
let trackId = this.getIsParam(params, 'trackId');
this.setType(genderId);
this.setPlaylist(playlistId);
this.setArtist(artistId);
this.setAlbum(albumId);
this.setTrack(trackId);
this.setType(genderId);
this.setPlaylist(playlistId);
this.setArtist(artistId);
this.setAlbum(albumId);
this.setTrack(trackId);
this.update.emit({
genderId: this.genderId,
playlistId: this.playlistId,
@@ -140,229 +138,229 @@ export class ArianeService {
albumId: this.albumId,
trackId: this.trackId,
});
}
reset():void {
this.genderId = undefined;
this.typeName = undefined;
this.typeChange.emit(this.genderId);
this.playlistId = undefined;
this.playlistName = undefined;
this.playlistChange.emit(this.playlistId);
this.artistId = undefined;
this.artistName = undefined;
this.artistChange.emit(this.artistId);
this.albumId = undefined;
this.albumName = undefined;
this.albumChange.emit(this.albumId);
this.trackId = undefined;
this.trackName = undefined;
this.trackChange.emit(this.trackId);
}
}
reset(): void {
this.genderId = undefined;
this.typeName = undefined;
this.typeChange.emit(this.genderId);
this.playlistId = undefined;
this.playlistName = undefined;
this.playlistChange.emit(this.playlistId);
this.artistId = undefined;
this.artistName = undefined;
this.artistChange.emit(this.artistId);
this.albumId = undefined;
this.albumName = undefined;
this.albumChange.emit(this.albumId);
this.trackId = undefined;
this.trackName = undefined;
this.trackChange.emit(this.trackId);
}
setType(id:number):void {
if(this.genderId === id) {
return;
}
this.genderId = id;
this.typeName = '??--??';
if(isUndefined(this.genderId)) {
this.typeChange.emit(this.genderId);
return;
}
let self = this;
this.typeService.get(id)
.then((response) => {
self.typeName = response.name;
self.typeChange.emit(self.genderId);
}).catch((response) => {
self.typeChange.emit(self.genderId);
});
}
getTypeId():number|undefined {
return this.genderId;
}
getTypeName():string|undefined {
return this.typeName;
}
setType(id: number): void {
if (this.genderId === id) {
return;
}
this.genderId = id;
this.typeName = '??--??';
if (isUndefined(this.genderId)) {
this.typeChange.emit(this.genderId);
return;
}
let self = this;
this.typeService.get(id)
.then((response) => {
self.typeName = response.name;
self.typeChange.emit(self.genderId);
}).catch((response) => {
self.typeChange.emit(self.genderId);
});
}
getTypeId(): number | undefined {
return this.genderId;
}
getTypeName(): string | undefined {
return this.typeName;
}
setPlaylist(id:number|undefined) {
if(this.playlistId === id) {
return;
}
this.playlistId = id;
this.playlistName = '??--??';
if(isUndefined(this.playlistId)) {
this.playlistChange.emit(this.playlistId);
return;
}
let self = this;
this.playlistService.get(id)
.then((response: NodeData) => {
self.playlistName = response.name;
self.playlistChange.emit(self.playlistId);
}).catch((response) => {
self.playlistChange.emit(self.playlistId);
});
}
getPlaylistId():number|undefined {
return this.playlistId;
}
getPlaylistName():string|undefined {
return this.playlistName;
}
setPlaylist(id: number | undefined) {
if (this.playlistId === id) {
return;
}
this.playlistId = id;
this.playlistName = '??--??';
if (isUndefined(this.playlistId)) {
this.playlistChange.emit(this.playlistId);
return;
}
let self = this;
this.playlistService.get(id)
.then((response: NodeSmall) => {
self.playlistName = response.name;
self.playlistChange.emit(self.playlistId);
}).catch((response) => {
self.playlistChange.emit(self.playlistId);
});
}
getPlaylistId(): number | undefined {
return this.playlistId;
}
getPlaylistName(): string | undefined {
return this.playlistName;
}
setArtist(id:number|undefined):void {
if(this.artistId === id) {
return;
}
this.artistId = id;
this.artistName = '??--??';
if(isUndefined(this.artistId)) {
this.artistChange.emit(this.artistId);
return;
}
let self = this;
this.artistService.get(id)
.then((response: NodeData) => {
self.artistName = response.name;
self.artistChange.emit(self.artistId);
}).catch((response) => {
self.artistChange.emit(self.artistId);
});
}
getArtistId():number|undefined {
return this.artistId;
}
getArtistName():string|undefined {
return this.artistName;
}
setArtist(id: number | undefined): void {
if (this.artistId === id) {
return;
}
this.artistId = id;
this.artistName = '??--??';
if (isUndefined(this.artistId)) {
this.artistChange.emit(this.artistId);
return;
}
let self = this;
this.artistService.get(id)
.then((response: NodeSmall) => {
self.artistName = response.name;
self.artistChange.emit(self.artistId);
}).catch((response) => {
self.artistChange.emit(self.artistId);
});
}
getArtistId(): number | undefined {
return this.artistId;
}
getArtistName(): string | undefined {
return this.artistName;
}
setAlbum(id:number|undefined):void {
if(this.albumId === id) {
return;
}
this.albumId = id;
this.albumName = '??--??';
if(isUndefined(this.albumId)) {
this.albumChange.emit(this.albumId);
return;
}
let self = this;
this.albumService.get(id)
.then((response: NodeData) => {
// self.setArtist(response.artistId);
self.albumName = response.name;
self.albumChange.emit(self.albumId);
}).catch((response) => {
self.albumChange.emit(self.albumId);
});
}
getAlbumId():number|undefined {
return this.albumId;
}
getAlbumName():string|undefined {
return this.albumName;
}
setAlbum(id: number | undefined): void {
if (this.albumId === id) {
return;
}
this.albumId = id;
this.albumName = '??--??';
if (isUndefined(this.albumId)) {
this.albumChange.emit(this.albumId);
return;
}
let self = this;
this.albumService.get(id)
.then((response: NodeSmall) => {
// self.setArtist(response.artistId);
self.albumName = response.name;
self.albumChange.emit(self.albumId);
}).catch((response) => {
self.albumChange.emit(self.albumId);
});
}
getAlbumId(): number | undefined {
return this.albumId;
}
getAlbumName(): string | undefined {
return this.albumName;
}
setTrack(id:number|undefined):void {
if(this.trackId === id) {
return;
}
this.trackId = id;
this.trackName = '??--??';
if(isUndefined(this.trackId)) {
this.trackChange.emit(this.trackId);
return;
}
let self = this;
this.trackService.get(id)
.then((response) => {
// self.setAlbum(response.albumId);
// self.setArtist(response.artistId);
self.trackName = response.name;
self.trackChange.emit(self.trackId);
}).catch((response) => {
self.trackChange.emit(self.trackId);
});
}
getTrackId():number|undefined {
return this.trackId;
}
getTrackName():string|undefined {
return this.trackName;
}
setTrack(id: number | undefined): void {
if (this.trackId === id) {
return;
}
this.trackId = id;
this.trackName = '??--??';
if (isUndefined(this.trackId)) {
this.trackChange.emit(this.trackId);
return;
}
let self = this;
this.trackService.get(id)
.then((response) => {
// self.setAlbum(response.albumId);
// self.setArtist(response.artistId);
self.trackName = response.name;
self.trackChange.emit(self.trackId);
}).catch((response) => {
self.trackChange.emit(self.trackId);
});
}
getTrackId(): number | undefined {
return this.trackId;
}
getTrackName(): string | undefined {
return this.trackName;
}
/**
* Generic navigation on the browser.
* @param destination - new destination url
* @param ids - list of successives ids
* @param newWindows - open in a new windows
* @param replaceCurrentPage - consider the curent page is removed from history
*/
genericNavigate(
destination:string,
ids:number[],
newWindows?:boolean,
replaceCurrentPage: boolean = false): void {
let addressOffset = `${destination }`;
/**
* Generic navigation on the browser.
* @param destination - new destination url
* @param ids - list of successives ids
* @param newWindows - open in a new windows
* @param replaceCurrentPage - consider the curent page is removed from history
*/
genericNavigate(
destination: string,
ids: number[],
newWindows?: boolean,
replaceCurrentPage: boolean = false): void {
let addressOffset = `${destination}`;
ids.forEach(element => {
if (!isUndefined(element)) {
addressOffset += `/${element}`;
}
});
if(!isNullOrUndefined(newWindows) && newWindows === true) {
window.open(`/${ addressOffset}`);
} else {
this.router.navigate([ addressOffset ], { replaceUrl: replaceCurrentPage });
}
}
genericNavigateEdit(
destination:string,
id:number,
newWindows?:boolean,
replaceCurrentPage: boolean = false): void {
let addressOffset = `${destination }/${ id }`;
if(!isNullOrUndefined(newWindows) && newWindows === true) {
window.open(`/${ addressOffset}/edit`);
} else {
this.router.navigate([ `${addressOffset}/edit` ], { replaceUrl: replaceCurrentPage });
}
}
navigatePlaylist({ id, newWindows}: { id?: number; newWindows?: boolean; }):void {
this.genericNavigate('playlist', [ id ], newWindows);
}
navigatePlaylistEdit({ id, newWindows }: { id: number; newWindows?: boolean; }):void {
this.genericNavigateEdit('playlist', id, newWindows);
if (!isNullOrUndefined(newWindows) && newWindows === true) {
window.open(`/${addressOffset}`);
} else {
this.router.navigate([addressOffset], { replaceUrl: replaceCurrentPage });
}
}
genericNavigateEdit(
destination: string,
id: number,
newWindows?: boolean,
replaceCurrentPage: boolean = false): void {
let addressOffset = `${destination}/${id}`;
if (!isNullOrUndefined(newWindows) && newWindows === true) {
window.open(`/${addressOffset}/edit`);
} else {
this.router.navigate([`${addressOffset}/edit`], { replaceUrl: replaceCurrentPage });
}
}
navigateGender({ genderId, newWindows }: { genderId?: number; newWindows?: boolean; }):void {
this.genericNavigate('gender', [ genderId ], newWindows);
}
navigateGenderEdit({ id, newWindows }: { id: number; newWindows?: boolean; }):void {
this.genericNavigateEdit('gender', id, newWindows);
navigatePlaylist({ id, newWindows }: { id?: number; newWindows?: boolean; }): void {
this.genericNavigate('playlist', [id], newWindows);
}
navigatePlaylistEdit({ id, newWindows }: { id: number; newWindows?: boolean; }): void {
this.genericNavigateEdit('playlist', id, newWindows);
}
navigateAlbum({ albumId, newWindows }: { albumId?: number; newWindows?: boolean; }):void {
this.genericNavigate('album', [ albumId ], newWindows);
navigateGender({ genderId, newWindows }: { genderId?: number; newWindows?: boolean; }): void {
this.genericNavigate('gender', [genderId], newWindows);
}
navigateAlbumEdit({ id, newWindows }: { id: number; newWindows?: boolean; }):void {
this.genericNavigateEdit('album', id, newWindows);
navigateGenderEdit({ id, newWindows }: { id: number; newWindows?: boolean; }): void {
this.genericNavigateEdit('gender', id, newWindows);
}
navigateAlbum({ albumId, newWindows }: { albumId?: number; newWindows?: boolean; }): void {
this.genericNavigate('album', [albumId], newWindows);
}
navigateAlbumEdit({ id, newWindows }: { id: number; newWindows?: boolean; }): void {
this.genericNavigateEdit('album', id, newWindows);
}
navigateArtist({ artistId, albumId, newWindows }: { artistId?: number; albumId?:number, newWindows?: boolean; }):void {
this.genericNavigate('artist', [ artistId, albumId ], newWindows);
navigateArtist({ artistId, albumId, newWindows }: { artistId?: number; albumId?: number, newWindows?: boolean; }): void {
this.genericNavigate('artist', [artistId, albumId], newWindows);
}
navigateArtistEdit({ id, newWindows }: { id: number; newWindows?: boolean; }):void {
this.genericNavigateEdit('artist', id, newWindows);
navigateArtistEdit({ id, newWindows }: { id: number; newWindows?: boolean; }): void {
this.genericNavigateEdit('artist', id, newWindows);
}
navigateTrack({ trackId, newWindows }: { trackId?: number; newWindows?: boolean; }):void {
this.genericNavigate('track', [ trackId ], newWindows);
navigateTrack({ trackId, newWindows }: { trackId?: number; newWindows?: boolean; }): void {
this.genericNavigate('track', [trackId], newWindows);
}
navigateTrackEdit({ id, newWindows }: { id: number; newWindows?: boolean; }):void {
this.genericNavigateEdit('track', id, newWindows);
navigateTrackEdit({ id, newWindows }: { id: number; newWindows?: boolean; }): void {
this.genericNavigateEdit('track', id, newWindows);
}

View File

@@ -6,164 +6,119 @@
import { Injectable } from '@angular/core';
import { HttpWrapperService, BddService } from 'common/service';
import { DataInterface, TypeCheck, isArrayOf } from 'common/utils';
import { isNodeData, NodeData } from 'common/model';
import { GenericInterfaceModelDB } from './GenericInterfaceModelDB';
import { Artist, ArtistResource, UUID } from 'app/back-api';
import { RESTConfig } from 'app/back-api/rest-tools';
import { environment } from 'environments/environment';
import { GenericDataService } from './GenericDataService';
import { DataStore, SessionService } from '@kangaroo-and-rabbit/kar-cw';
@Injectable()
export class ArtistService extends GenericInterfaceModelDB {
export class ArtistService extends GenericDataService<Artist> {
constructor(http: HttpWrapperService,
bdd: BddService) {
super('artist', http, bdd);
getRestConfig(): RESTConfig {
return {
server: environment.server.karusic,
token: this.session.getToken()
}
}
private lambdaGets(): Promise<Artist[]> {
return ArtistResource.gets({ restConfig: this.getRestConfig() });
}
/**
* Get all the track for a specific artist
* @param idArtist - Id of the artist.
* @returns a promise on the list of track elements
*/
getTrackNoAlbum(idArtist:number): Promise<NodeData[]> {
let self = this;
constructor(private session: SessionService) {
super();
console.log('Start ArtistService');
const self = this;
this.setStore(new DataStore<Artist>(() => self.lambdaGets()));
}
insert(data: Artist): Promise<Artist> {
const self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: idArtist,
}, {
check: TypeCheck.EQUAL,
key: 'albumId',
value: undefined,
},
],
[ 'track', 'name' ]);
resolve(data);
}).catch((response) => {
reject(response);
});
ArtistResource.post({
restConfig: this.getRestConfig(),
data
}).then((value: Artist) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
/**
* Get all the track for a specific artist
* @param idArtist - Id of the artist.
* @returns a promise on the list of track elements
*/
getAllTracks(idArtist:number): Promise<NodeData[]> {
let self = this;
patch(id: number, data: Artist): Promise<Artist> {
const self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: idArtist,
}
],
[ 'track', 'name' ]);
resolve(data);
}).catch((response) => {
reject(response);
});
ArtistResource.patch({
restConfig: this.getRestConfig(),
params: {
id
},
data
}).then((value: Artist) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
/**
* Get the number of track in this artist ID
* @param id - Id of the artist.
* @returns The number of track present in this artist
*/
countTrack(artistId:number): Promise<number> {
let self = this;
delete(id: number): Promise<void> {
const self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response:DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: artistId,
},
]);
resolve(data.length);
}).catch((response) => {
reject(response);
});
ArtistResource.remove({
restConfig: this.getRestConfig(),
params: {
id
}
}).then(() => {
self.dataStore.delete(id);
resolve();
}).catch((error) => {
reject(error);
});
});
}
/**
* Get all the album of a specific artist
* @param idArtist - ID of the artist
* @returns the required List.
*/
getAlbum(idArtist:number): Promise<NodeData[]> {
deleteCover(id: number, coverId: UUID): Promise<Artist> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response:DataInterface) => {
//console.log(" <<<========================================>>> " + idArtist);
let data = response.getsWhere([
{
check: TypeCheck.CONTAINS, //< this is for array containing
key: 'artists',
value: idArtist,
},
], [ 'id' ]);
//console.log("==> get all tracks of the artist: " + JSON.stringify(data, null, 2));
// extract a single time all value "id" in an array
const listAlbumId = DataInterface.extractLimitOne(data, "albumId");
//console.log("==> List Of ids: " + JSON.stringify(listAlbumId, null, 2));
self.bdd.get('album')
.then((response:DataInterface) => {
let dataAlbum = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'id',
value: listAlbumId,
},
], [ 'publication', 'name', 'id' ]);
resolve(dataAlbum);
//console.log("==> get all albums: " + JSON.stringify(dataAlbum, null, 2));
return;
}).catch((response) => {
reject(response);
});
return;
}).catch((response) => {
reject(response);
});
ArtistResource.removeCover({
restConfig: this.getRestConfig(),
params: {
id,
coverId
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
countAlbum(idArtist:number): Promise<number> {
uploadCover(id: number,
file: File,
progress: any = null): Promise<Artist> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response:DataInterface) => {
//console.log(" <<<========================================>>> " + idArtist);
let data = response.getsWhere([
{
check: TypeCheck.CONTAINS, //< this is for array containing
key: 'artists',
value: idArtist,
},
], [ 'id' ]);
//console.log("==> get all tracks of the artist: " + JSON.stringify(data, null, 2));
// extract a single time all value "id" in an array
const listAlbumId = DataInterface.extractLimitOne(data, "albumId");
resolve(listAlbumId.length);
}).catch((response) => {
reject(response);
});
ArtistResource.uploadCover({
restConfig: this.getRestConfig(),
params: {
id,
},
data: {
file,
fileName: file.name
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
}

View File

@@ -5,97 +5,112 @@
*/
import { Injectable } from '@angular/core';
import { isArrayOf, isNumberFinite } from 'common/utils';
import { SessionService, isArrayOf, isNullOrUndefined, isString } from '@kangaroo-and-rabbit/kar-cw';
import { HTTPMimeType, HTTPRequestModel, HttpWrapperService, ModelResponseHttp } from '../../common/service/http-wrapper';
import { RESTConfig, RESTUrl } from 'app/back-api/rest-tools';
import { environment } from 'environments/environment';
@Injectable()
export class DataService {
// 0: Not hide password; 1 hide password;
private serviceName:string = 'data';
constructor(private http: HttpWrapperService) {
getRestConfig(): RESTConfig {
return {
server: environment.server.karusic,
token: this.session.getToken()
}
}
constructor(private session: SessionService) {
console.log('Start DataService');
}
getData():any {
return this.http.getSpecific(this.serviceName);
}
get(_id:number):any {
return this.http.getSpecific([this.serviceName, _id]);
}
uploadFile(_form:FormData, _progress:any = null) {
// return this.http.uploadFileMultipart(this.serviceName, null, _file);
return this.http.uploadMultipart(`${this.serviceName }/upload/`, _form, _progress);
}
getImage(_id:number) : Promise<ModelResponseHttp> {
return this.http.requestImage({
endPoint: this.serviceName,
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.IMAGE,
contentType: HTTPMimeType.JSON,
});
}
getImageThumbnail(_id:number) : Promise<ModelResponseHttp> {
return this.http.requestImage({
endPoint: this.serviceName + "/thumbnail/" + _id,
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.ALL,//IMAGE,
contentType: HTTPMimeType.JSON,
});
}
/**
* Retreive the Cover URL of a specific data id
* Retrieve the Cover URL of a specific data id
* @param coverId Id of te cover
* @returns the url of the cover
*/
getCoverUrl(coverId: number): string {
return this.http.createRESTCall2({
api: `data/${coverId}`,
addURLToken: true,
getUrl(dataId: string, optionalName?: string): string {
if (isNullOrUndefined(optionalName)) {
const url = RESTUrl({
restModel: {
endPoint: "data/{dataId}",
tokenInUrl: true,
},
restConfig: this.getRestConfig(),
params: {
dataId
}
});
console.log(`get URL = ${url}`);
if (environment?.replaceDataToRealServer === true) {
return url.replace("http://localhost:19080", "https://atria-soft.org");
}
return url;
}
const url = RESTUrl({
restModel: {
endPoint: "data/{dataId}/{optionalName}",
tokenInUrl: true,
},
restConfig: this.getRestConfig(),
params: {
dataId,
optionalName
}
});
if (environment?.replaceDataToRealServer === true) {
return url.replace("http://localhost:19080", "https://atria-soft.org");
}
return url;
}
/**
* Retreive the list Cover URL of a specific data id
* Retrieve the list Cover URL of a specific data id
* @param coverId Id of te cover
* @returns the url of the cover
*/
getCoverListUrl(coverIds?: number[]): string[] | undefined {
if(!isArrayOf(coverIds, isNumberFinite) || coverIds.length === 0) {
getListUrl(dataIds?: string[]): string[] | undefined {
if (!isArrayOf(dataIds, isString) || dataIds.length === 0) {
return undefined;
}
let covers = [] as string[];
for(let iii = 0; iii < coverIds.length; iii++) {
covers.push(this.getCoverUrl(coverIds[iii]));
let covers: string[] = [];
for (let iii = 0; iii < dataIds.length; iii++) {
covers.push(this.getUrl(dataIds[iii]));
}
return covers;
}
/**
* Retreive the thumbnail cover URL of a specific data id
* Retrieve the thumbnail cover URL of a specific data id
* @param coverId Id of te cover
* @returns the url of the cover
*/
getCoverThumbnailUrl(coverId: number): string {
return this.http.createRESTCall2({
api: `data/thumbnail/${coverId}`,
addURLToken: true,
getThumbnailUrl(coverId: string): string {
const url = RESTUrl({
restModel: {
endPoint: "data/thumbnail/{coverId}",
tokenInUrl: true,
},
restConfig: this.getRestConfig(),
params: {
coverId
}
});
if (environment?.replaceDataToRealServer === true) {
return url.replace("http://localhost:19080", "https://atria-soft.org");
}
return url;
}
/**
* Retreive the list thumbnail cover URL of a specific data id
* Retrieve the list thumbnail cover URL of a specific data id
* @param coverId Id of te cover
* @returns the url of the cover
*/
getCoverListThumbnailUrl(coverIds?: number[]): string[] | undefined {
if(!isArrayOf(coverIds, isNumberFinite) || coverIds.length === 0) {
getListThumbnailUrl(dataIds?: string[]): string[] | undefined {
if (!isArrayOf(dataIds, isString) || dataIds.length === 0) {
return undefined;
}
let covers = [] as string[];
for(let iii = 0; iii < coverIds.length; iii++) {
covers.push(this.getCoverThumbnailUrl(coverIds[iii]));
let covers: string[] = [];
for (let iii = 0; iii < dataIds.length; iii++) {
covers.push(this.getThumbnailUrl(dataIds[iii]));
}
return covers;
}

View File

@@ -6,10 +6,11 @@
import { Injectable } from '@angular/core';
import { HttpWrapperService, BddService } from 'common/service';
import { DataInterface, isArrayOf, isNullOrUndefined, TypeCheck } from 'common/utils';
import { isNodeData, NodeData } from 'common/model';
import { GenericInterfaceModelDB } from './GenericInterfaceModelDB';
import { GenderResource, Gender, UUID } from 'app/back-api';
import { RESTConfig } from 'app/back-api/rest-tools';
import { environment } from 'environments/environment';
import { GenericDataService } from './GenericDataService';
import { DataStore, SessionService } from '@kangaroo-and-rabbit/kar-cw';
export interface MessageLogIn {
id: number;
@@ -18,109 +19,111 @@ export interface MessageLogIn {
}
@Injectable()
export class GenderService extends GenericInterfaceModelDB {
export class GenderService extends GenericDataService<Gender> {
constructor(http: HttpWrapperService,
bdd: BddService) {
super('gender', http, bdd);
getRestConfig(): RESTConfig {
return {
server: environment.server.karusic,
token: this.session.getToken()
}
}
private lambdaGets(): Promise<Gender[]> {
return GenderResource.gets({ restConfig: this.getRestConfig() });
}
countTrack(id:number): Promise<number> {
let self = this;
constructor(private session: SessionService) {
super();
console.log('Start GenderService');
const self = this;
this.setStore(new DataStore<Gender>(() => this.lambdaGets()));
}
insert(data: Gender): Promise<Gender> {
const self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'typeId',
value: id,
} ] );
resolve(data.length);
}).catch((response) => {
reject(response);
});
GenderResource.post({
restConfig: this.getRestConfig(),
data
}).then((value: Gender) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
patch(id: number, data: Gender): Promise<Gender> {
const self = this;
return new Promise((resolve, reject) => {
GenderResource.patch({
restConfig: this.getRestConfig(),
params: {
id
},
data
}).then((value: Gender) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
getSubTrack(id:number): Promise<NodeData[]> {
let self = this;
delete(id: number): Promise<void> {
const self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'typeId',
value: id,
}, {
check: TypeCheck.EQUAL,
key: 'artistId',
value: undefined,
}, {
check: TypeCheck.EQUAL,
key: 'playlistId',
value: undefined,
},
], [ 'name' ] );
resolve(data);
}).catch((response) => {
reject(response);
});
GenderResource.remove({
restConfig: this.getRestConfig(),
params: {
id
}
}).then(() => {
self.dataStore.delete(id);
resolve();
}).catch((error) => {
reject(error);
});
});
}
getSubArtist(id:number): Promise<NodeData[]> {
deleteCover(id: number, coverId: UUID): Promise<Gender> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('artist')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'parentId',
value: id,
} ],
[ 'name' ]);
resolve(data);
}).catch((response) => {
reject(response);
});
GenderResource.removeCover({
restConfig: this.getRestConfig(),
params: {
id,
coverId
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
getSubPlaylist(id:number): Promise<NodeData[]> {
uploadCover(id: number,
file: File,
progress: any = null): Promise<Gender> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'typeId',
value: id,
}, {
check: TypeCheck.EQUAL,
key: 'artistId',
value: [undefined, null],
}, {
check: TypeCheck.NOT_EQUAL,
key: 'playlistId',
value: undefined,
},
]);
//, [ 'universId' ]);
resolve(data);
return;
}).catch((response: any) => {
reject(response);
});
GenderResource.uploadCover({
restConfig: this.getRestConfig(),
params: {
id,
},
data: {
file,
fileName: file.name
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
}

View File

@@ -5,46 +5,124 @@
*/
import { Injectable } from '@angular/core';
import { NodeData } from 'common/model';
import { HttpWrapperService, BddService } from 'common/service';
import { DataInterface, TypeCheck } from 'common/utils';
import { GenericInterfaceModelDB } from './GenericInterfaceModelDB';
import { Playlist, PlaylistResource, UUID } from 'app/back-api';
import { RESTConfig } from 'app/back-api/rest-tools';
import { environment } from 'environments/environment';
import { GenericDataService } from './GenericDataService';
import { SessionService, DataStore } from '@kangaroo-and-rabbit/kar-cw';
@Injectable()
export class PlaylistService extends GenericInterfaceModelDB {
export class PlaylistService extends GenericDataService<Playlist> {
constructor(http: HttpWrapperService,
bdd: BddService) {
super('playlist', http, bdd);
getRestConfig(): RESTConfig {
return {
server: environment.server.karusic,
token: this.session.getToken()
}
}
private lambdaGets(): Promise<Playlist[]> {
return PlaylistResource.gets({ restConfig: this.getRestConfig() });
}
getSubArtist(id:number, select:Array<string> = []):any {
constructor(private session: SessionService) {
super();
console.log('Start PlaylistService');
const self = this;
this.setStore(new DataStore<Playlist>(() => this.lambdaGets()));
}
getSubArtist(id: bigint, select: Array<string> = []): any {
// this.checkLocalBdd();
}
getSubTrack(id:number, select:Array<string> = []):any {
getSubTrack(id: bigint, select: Array<string> = []): any {
// this.checkLocalBdd();
} insert(data: Playlist): Promise<Playlist> {
const self = this;
return new Promise((resolve, reject) => {
PlaylistResource.post({
restConfig: this.getRestConfig(),
data
}).then((value: Playlist) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
patch(id: number, data: Playlist): Promise<Playlist> {
const self = this;
return new Promise((resolve, reject) => {
PlaylistResource.patch({
restConfig: this.getRestConfig(),
params: {
id
},
data
}).then((value: Playlist) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
getAll(ids: number[]): Promise<NodeData[]> {
delete(id: number): Promise<void> {
const self = this;
return new Promise((resolve, reject) => {
PlaylistResource.remove({
restConfig: this.getRestConfig(),
params: {
id
}
}).then(() => {
self.dataStore.delete(id);
resolve();
}).catch((error) => {
reject(error);
});
});
}
deleteCover(id: number, coverId: UUID): Promise<Playlist> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'id',
value: ids,
},
],
[ 'name', 'id' ]);
resolve(data);
return;
}).catch((response) => {
reject(response);
});
PlaylistResource.removeCover({
restConfig: this.getRestConfig(),
params: {
id,
coverId
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
uploadCover(id: number,
file: File,
progress: any = null): Promise<Playlist> {
let self = this;
return new Promise((resolve, reject) => {
PlaylistResource.uploadCover({
restConfig: this.getRestConfig(),
params: {
id,
},
data: {
file,
fileName: file.name
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
}

View File

@@ -5,52 +5,133 @@
*/
import { Injectable } from '@angular/core';
import { isMedia, Media } from 'app/model';
import { NodeData } from 'common/model';
import { HttpWrapperService, BddService } from 'common/service';
import { DataInterface, isArrayOf, isNullOrUndefined, TypeCheck } from 'common/utils';
import { GenericInterfaceModelDB } from './GenericInterfaceModelDB';
import { RESTConfig } from 'app/back-api/rest-tools';
import { environment } from 'environments/environment';
import { Track, TrackResource, UUID } from 'app/back-api';
import { GenericDataService } from './GenericDataService';
import { TypeCheck, isArrayOf, isNumber, DataStore, DataTools, SessionService } from '@kangaroo-and-rabbit/kar-cw';
@Injectable()
export class TrackService extends GenericInterfaceModelDB {
export class TrackService extends GenericDataService<Track> {
constructor(http: HttpWrapperService,
bdd: BddService) {
super('track', http, bdd);
getRestConfig(): RESTConfig {
return {
server: environment.server.karusic,
token: this.session.getToken()
}
}
get(id: number): Promise<Media> {
private lambdaGets(): Promise<Track[]> {
return TrackResource.gets({ restConfig: this.getRestConfig() });
}
constructor(private session: SessionService) {
super();
console.log('Start TrackService');
const self = this;
this.setStore(new DataStore<Track>(() => this.lambdaGets()));
}
patch(id: number, data: Track): Promise<Track> {
const self = this;
return new Promise((resolve, reject) => {
super.get(id).then((data: NodeData) => {
if (isMedia(data)) {
resolve(data);
return;
}
reject("model is wrong !!!")
return
}).catch((reason: any) => {
reject(reason);
TrackResource.patch({
restConfig: this.getRestConfig(),
params: {
id
},
data
}).then((value: Track) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
getWithAlbum(idAlbum: number): Promise<Media[]> {
delete(id: number): Promise<void> {
const self = this;
return new Promise((resolve, reject) => {
TrackResource.remove({
restConfig: this.getRestConfig(),
params: {
id
}
}).then(() => {
self.dataStore.delete(id);
resolve();
}).catch((error) => {
reject(error);
});
});
}
getTracksIdsForAlbums(idAlbums: number[]): Promise<number[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbum,
},
],
self.dataStore.getData()
.then((response: Track[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbums,
},
],
['name']); // tODO : set the Id in the track ...
// filter with artist- ID !!!
const listId = DataTools.extractLimitOne(data, "id");
resolve(listId);
}).catch((response) => {
reject(response);
});
});
}
/**
* Get the number of track in this season ID
* @param AlbumId - Id of the album.
* @returns The number of element present in this season
*/
countTracksWithAlbumId(AlbumId: number): Promise<number> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: Track[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: AlbumId,
},
]);
resolve(data.length);
}).catch((response) => {
reject(response);
});
});
}
getTracksWithAlbumId(idAlbum: number): Promise<Track[]> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: Track[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.EQUAL,
key: 'albumId',
value: idAlbum,
},
],
['track', 'name', 'id']);
if (isArrayOf(data, isMedia)) {
resolve(data);
return;
}
reject("model is wrong !!!");
resolve(data);
return;
}).catch((response) => {
reject(response);
@@ -58,67 +139,288 @@ export class TrackService extends GenericInterfaceModelDB {
});
}
getData(): Promise<Media[]> {
/**
* Get all the track for a specific artist
* @param idArtist - Id of the artist.
* @returns a promise on the list of track elements
*/
getTracksOfArtistWithNoAlbum(idArtist: number): Promise<Track[]> {
let self = this;
return new Promise((resolve, reject) => {
super.getData().then((data: NodeData[]) => {
if (isArrayOf(data, isMedia)) {
self.gets()
.then((response: Track[]) => {
let data = DataTools.getsWhere(response, [
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: idArtist,
}, {
check: TypeCheck.EQUAL,
key: 'albumId',
value: undefined,
},
],
['track', 'name']);
resolve(data);
return;
}
reject("model is wrong !!!")
return
}).catch((reason: any) => {
reject(reason);
});
}).catch((response) => {
reject(response);
});
});
}
/**
* Get all the track for a specific artist
* @param idArtist - Id of the artist.
* @returns a promise on the list of track elements
*/
getTracksOfAnArtist(idArtist: number): Promise<Track[]> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: Track[]) => {
let data = DataTools.getsWhere(response, [
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: idArtist,
}
],
['track', 'name']);
resolve(data);
}).catch((response) => {
reject(response);
});
});
}
/**
* Get the number of track in this artist ID
* @param id - Id of the artist.
* @returns The number of track present in this artist
*/
countTracksOfAnArtist(artistId: number): Promise<number> {
let self = this;
return new Promise((resolve, reject) => {
self.getTracksOfAnArtist(artistId)
.then((response: Track[]) => {
resolve(response.length);
}).catch((error) => {
reject(error);
});
});
}
/**
* Get all the album of a specific artist
* @param artistId - ID of the artist
* @returns the required List.
*/
getAlbumIdsOfAnArtist(artistId: number): Promise<number[]> {
let self = this;
return new Promise((resolve, reject) => {
self.getTracksOfAnArtist(artistId)
.then((response: Track[]) => {
//console.log("==> get all tracks of the artist: " + JSON.stringify(data, null, 2));
// extract a single time all value "id" in an array
const listAlbumId = DataTools.extractLimitOne(response, "albumId");
if (isArrayOf(listAlbumId, isNumber)) {
resolve(listAlbumId);
} else {
reject(`Fail to get the ids (impossible case) ${listAlbumId}`);
}
}).catch((response) => {
reject(response);
});
});
}
countAlbumOfAnArtist(idArtist: number): Promise<number> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: Track[]) => {
//console.log(" <<<========================================>>> " + idArtist);
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.CONTAINS, //< this is for array containing
key: 'artists',
value: idArtist,
},
], ['id']);
//console.log("==> get all tracks of the artist: " + JSON.stringify(data, null, 2));
// extract a single time all value "id" in an array
const listAlbumId = DataTools.extractLimitOne(data, "albumId");
resolve(listAlbumId.length);
}).catch((response) => {
reject(response);
});
});
}
countTrackForGender(typeId: number): Promise<number> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: Track[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.EQUAL,
key: 'typeId',
value: typeId,
}]);
resolve(data.length);
}).catch((response) => {
reject(response);
});
});
}
getTracksForGender(id: number): Promise<Track[]> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: Track[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.EQUAL,
key: 'genderId',
value: id,
}, {
check: TypeCheck.EQUAL,
key: 'artistId',
value: undefined,
}, {
check: TypeCheck.EQUAL,
key: 'playlistId',
value: undefined,
},
], ['name']);
resolve(data);
}).catch((response) => {
reject(response);
});
});
}
getSubPlaylist(typeId: number): Promise<Track[]> {
let self = this;
return new Promise((resolve, reject) => {
self.gets()
.then((response: Track[]) => {
let data = DataTools.getsWhere(response,
[
{
check: TypeCheck.EQUAL,
key: 'typeId',
value: typeId,
}, {
check: TypeCheck.EQUAL,
key: 'artistId',
value: [undefined, null],
}, {
check: TypeCheck.NOT_EQUAL,
key: 'playlistId',
value: undefined,
},
]);
//, [ 'universId' ]);
resolve(data);
return;
}).catch((response: any) => {
reject(response);
});
});
}
uploadFile(file: File,
gender?: string,
artist?: string,
album?: string,
trackId?: number,
title?: string,
progress: any = null) {
const formData = new FormData();
formData.append('fileName', file.name);
// set the file at hte begining it will permit to abort the transmission
formData.append('file', file ?? null);
formData.append('gender', gender ?? null);
formData.append('artist', artist ?? null);
formData.append('album', album ?? null);
if (!isNullOrUndefined(trackId)) {
formData.append('trackId', trackId.toString());
} else {
formData.append('trackId', null);
}
formData.append('title', title ?? null);
return this.http.uploadMultipart(`${this.serviceName}/upload/`, formData, progress);
progress: any = null): Promise<Track> {
const self = this;
return new Promise((resolve, reject) => {
TrackResource.uploadTrack({
restConfig: this.getRestConfig(),
data: {
fileName: file.name,
file,
gender: gender ?? null,
artist: artist ?? null,
album: album ?? null,
trackId: trackId ?? null,
title: title ?? null,
}
}).then((value: Track) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
/*
const formData = new FormData();
formData.append('fileName', file.name);
// set the file at hte beginning it will permit to abort the transmission
formData.append('file', file ?? null);
formData.append('gender', gender ?? null);
formData.append('artist', artist ?? null);
formData.append('album', album ?? null);
if (!isNullOrUndefined(trackId)) {
formData.append('trackId', trackId.toString());
} else {
formData.append('trackId', null);
}
formData.append('title', title ?? null);
uploadCoverBlob(blob: Blob,
mediaId: number,
progress: any = null) {
const formData = new FormData();
formData.append('fileName', 'take_screenshoot');
formData.append('typeId', mediaId.toString());
formData.append('file', blob);
return this.http.uploadMultipart(`${this.serviceName}/upload/`, formData, progress);
*/
deleteCover(id: number, coverId: UUID): Promise<Track> {
let self = this;
return new Promise((resolve, reject) => {
self.http.uploadMultipart(`${this.serviceName}/${mediaId}/add_cover/`, formData, progress)
.then((response) => {
let data = response;
if (data === null || data === undefined) {
reject('error retrive data from server');
return;
}
self.bdd.asyncSetInDB(self.serviceName, mediaId, data);
resolve(data);
}).catch((response) => {
reject(response);
});
TrackResource.removeCover({
restConfig: this.getRestConfig(),
params: {
id,
coverId
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
uploadCover(id: number,
file: File,
progress: any = null): Promise<Track> {
let self = this;
return new Promise((resolve, reject) => {
TrackResource.uploadCover({
restConfig: this.getRestConfig(),
params: {
id,
},
data: {
file,
fileName: file.name
}
}).then((value) => {
self.dataStore.updateValue(value);
resolve(value);
}).catch((error) => {
reject(error);
});
});
}
}

Some files were not shown because too many files have changed in this diff Show More