[DEV] basic migration of to the new generation interface

This commit is contained in:
Edouard DUPIN 2024-03-11 00:07:46 +01:00
parent 48e14212db
commit 9a3f28553d
34 changed files with 2167 additions and 573 deletions

View File

@ -1,6 +1,19 @@
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;
@ -9,14 +22,25 @@ public class WebLauncherLocal extends WebLauncher {
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/model/");
final WebLauncherLocal launcher = new WebLauncherLocal();
launcher.process();
launcher.logger.info("end-configure the server & wait finish process:");
Thread.currentThread().join();
launcher.logger.info("STOP the REST server:");
}
@Override
public void process() throws InterruptedException {
if (true) {

View File

@ -5,6 +5,7 @@ import java.util.List;
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.AddOnManyToMany;
import org.kar.archidata.tools.DataTools;
@ -12,6 +13,7 @@ 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;
@ -28,73 +30,82 @@ import jakarta.ws.rs.core.Response;
@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 Response 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 })
public Response uploadCover(@PathParam("id") final Long id, @FormDataParam("fileName") final String fileName, @FormDataParam("file") final InputStream fileInputStream,
@Operation(description = "Add a cover on a specific album")
public Response addCover(@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")
@Operation(description = "Remove a cover on a specific album")
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();

View File

@ -5,6 +5,7 @@ import java.util.List;
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.AddOnManyToMany;
import org.kar.archidata.tools.DataTools;
@ -28,55 +29,55 @@ import jakarta.ws.rs.core.Response;
@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 Response 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 })
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);

View File

@ -28,14 +28,14 @@ import jakarta.ws.rs.core.Response;
@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 {
return DataAccess.get(Gender.class, id);
}
@GET
@RolesAllowed("USER")
public List<Gender> get() throws Exception {
@ -45,10 +45,10 @@ public class GenderResource {
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Gender put(final String jsonRequest) throws Exception {
public Gender post(final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Gender.class, jsonRequest);
}
@PATCH
@Path("{id}")
@RolesAllowed("ADMIN")
@ -57,26 +57,26 @@ public class GenderResource {
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 Response 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 })
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);

View File

@ -28,14 +28,14 @@ import jakarta.ws.rs.core.Response;
@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 {
return DataAccess.get(Playlist.class, id);
}
@GET
@RolesAllowed("USER")
public List<Playlist> get() throws Exception {
@ -45,10 +45,10 @@ public class PlaylistResource {
@POST
@RolesAllowed("ADMIN")
@Consumes(MediaType.APPLICATION_JSON)
public Playlist put(final String jsonRequest) throws Exception {
public Playlist post(final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Playlist.class, jsonRequest);
}
@PATCH
@Path("{id}")
@RolesAllowed("ADMIN")
@ -57,43 +57,43 @@ public class PlaylistResource {
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 Response 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 })
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);

View File

@ -37,14 +37,14 @@ import jakarta.ws.rs.core.Response;
@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 {
return DataAccess.get(Track.class, id);
}
@GET
@RolesAllowed("USER")
public List<Track> get() throws Exception {
@ -57,7 +57,7 @@ public class TrackResource {
public Track create(final String jsonRequest) throws Exception {
return DataAccess.insertWithJson(Track.class, jsonRequest);
}
@PATCH
@Path("{id}")
@RolesAllowed("ADMIN")
@ -66,49 +66,49 @@ public class TrackResource {
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 Response 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 })
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();
}
@POST
@Path("/upload/")
@RolesAllowed("ADMIN")
@ -133,7 +133,7 @@ public class TrackResource {
album = DataTools.multipartCorrection(album);
trackId = DataTools.multipartCorrection(trackId);
title = DataTools.multipartCorrection(title);
//public NodeSmall uploadFile(final FormDataMultiPart form) {
LOGGER.info("Upload media file: " + fileMetaData);
LOGGER.info(" > fileName: " + fileName);
@ -151,14 +151,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) {
LOGGER.info("Need to add the data in the BDD ... ");
try {
data = DataTools.createNewData(tmpUID, fileName, sha512);
} catch (final IOException ex) {
@ -194,7 +194,7 @@ public class TrackResource {
// return Response.notModified("TypeId does not exist ...").build();
// }
LOGGER.info(" ==> genderElem={}", genderElem);
Artist artistElem = null;
if (artist != null) {
LOGGER.info(" Try to find Artist: '{}'", artist);
@ -207,7 +207,7 @@ public class TrackResource {
}
}
LOGGER.info(" ==> artistElem={}", artistElem);
Album albumElem = null;
if (album != null) {
albumElem = DataAccess.getWhere(Album.class, new Condition(new QueryCondition("name", "=", album)));
@ -218,9 +218,9 @@ public class TrackResource {
}
}
LOGGER.info(" ==> " + album);
LOGGER.info("add media");
Track trackElem = new Track();
trackElem.name = title;
trackElem.track = trackId != null ? Long.parseLong(trackId) : null;
@ -238,7 +238,7 @@ public class TrackResource {
if (artistElem != null) {
DataAccess.addLink(Track.class, trackElem.id, "artist", artistElem.id);
}
*/
*/
return Response.ok(trackElem).build();
} catch (final Exception ex) {
LOGGER.info("Catch an unexpected error ... {}", ex.getMessage());
@ -246,5 +246,5 @@ public class TrackResource {
return Response.status(417).entity("Back-end error : " + ex.getMessage()).type("text/plain").build();
}
}
}

View File

@ -23,25 +23,25 @@ import jakarta.ws.rs.core.SecurityContext;
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public class UserResource {
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() {
public List<UserKarusic> gets() {
LOGGER.info("getUsers");
try {
return DataAccess.gets(UserKarusic.class);
@ -51,12 +51,12 @@ 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) {
public UserKarusic get(@Context final SecurityContext sc, @PathParam("id") final long userId) {
LOGGER.info("getUser {}", userId);
final GenericContext gc = (GenericContext) sc.getUserPrincipal();
LOGGER.info("===================================================");
@ -70,7 +70,7 @@ public class UserResource {
}
return null;
}
@GET
@Path("me")
@RolesAllowed("USER")

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),
@ -84,5 +83,5 @@ public class Initialization extends MigrationSqlStep {
ALTER TABLE `user` AUTO_INCREMENT = 1000;
""", "mysql");
}
}

View File

@ -10,9 +10,10 @@ 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.DataJson;
@ -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)
@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

@ -7,7 +7,7 @@
"": {
"name": "karusic",
"version": "0.0.0",
"license": "MIT",
"license": "MPL-2",
"dependencies": {
"@angular/animations": "^17.2.0",
"@angular/cdk": "^17.1.2",
@ -20,6 +20,7 @@
"@angular/platform-browser-dynamic": "^17.2.0",
"@angular/router": "^17.2.0",
"rxjs": "^7.8.1",
"zod": "3.22.4",
"zone.js": "^0.14.4"
},
"devDependencies": {
@ -17092,6 +17093,14 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/zod": {
"version": "3.22.4",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.22.4.tgz",
"integrity": "sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/zone.js": {
"version": "0.14.4",
"resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.14.4.tgz",

View File

@ -27,7 +27,8 @@
"@angular/platform-browser-dynamic": "^17.2.0",
"@angular/router": "^17.2.0",
"rxjs": "^7.8.1",
"zone.js": "^0.14.4"
"zone.js": "^0.14.4",
"zod": "3.22.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.2.0",
@ -41,4 +42,4 @@
"@angular/language-service": "^17.2.0",
"npm-check-updates": "^16.14.15"
}
}
}

View File

@ -3,16 +3,16 @@
* @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 { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { isArray, isNullOrUndefined } from 'common/utils';
import { NodeData } from 'common/model';
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 { Track } from 'app/model/server-karusic-api';
export enum PlayMode {
@ -81,7 +81,7 @@ export class ElementPlayerAudioComponent implements OnInit {
private titleService: Title) {
// nothing to do...
}
private currentLMedia: Media;
private currentLMedia: Track;
private localIdStreaming: number;
private localListStreaming: number[] = [];
ngOnInit() {
@ -107,7 +107,7 @@ export class ElementPlayerAudioComponent implements OnInit {
this.havePrevious = this.localIdStreaming <= 0;
this.haveNext = this.localIdStreaming >= this.localListStreaming.length - 1;
this.trackService.get(this.localListStreaming[this.localIdStreaming])
.then((response: Media) => {
.then((response: Track) => {
//console.log(`get response of video : ${ JSON.stringify(response, null, 2)}`);
self.currentLMedia = response;
self.dataTitle = response.name;
@ -127,11 +127,11 @@ export class ElementPlayerAudioComponent implements OnInit {
.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({
@ -139,7 +139,7 @@ export class ElementPlayerAudioComponent implements OnInit {
addURLToken: true,
}).replace("http://localhost:19080", "https://atria-soft.org");
}).catch(() => {
console.error("error not ùmanaged in audio player ... 111");
console.error("error not unmanaged in audio player ... 111");
})
}
updateTitle() {

View File

@ -4,7 +4,7 @@
* @license PROPRIETARY (see license file)
*/
import { Injectable, Component, OnInit, Input } from '@angular/core';
import { isMedia, Media } from 'app/model';
import { Track, isTrack } from 'app/model/server-karusic-api';
import { DataService } from 'app/service';
import { NodeData } from 'common/model';
@ -13,41 +13,36 @@ 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: NodeData;
data: 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)) {
if (!isTrack(this.element)) {
this.data = undefined;
this.name = 'Not a media';
this.name = 'Not a track';
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);
}
}

View File

@ -0,0 +1,185 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray } from "./rest-tools"
import {Response, isResponse, InputStream, isAlbum, Long, RestErrorResponse, Album, FormDataContentDisposition, } from "./model"
export namespace AlbumResource {
/**
* Remove a specific album
*/
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/album/{id}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
/**
* 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);
};
/**
* 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,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isAlbum);
};
/**
* Add a cover on a specific album
*/
export function addCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: FormDataContentDisposition,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/album/{id}/cover",
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isResponse);
};
/**
* Remove a cover on a specific album
*/
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: Long,
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/album/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
/**
* 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,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isAlbum);
};
}

View File

@ -1,34 +0,0 @@
import { 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

@ -0,0 +1,124 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray } from "./rest-tools"
import {Response, Artist, isResponse, InputStream, Long, RestErrorResponse, FormDataContentDisposition, isArtist, } from "./model"
export namespace ArtistResource {
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/artist/{id}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
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 uploadCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: FormDataContentDisposition,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/artist/{id}/cover",
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isResponse);
};
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: Long,
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/artist/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
export function gets({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<Artist[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/artist",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isArtist);
};
}

View File

@ -0,0 +1,100 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray } from "./rest-tools"
import {Response, isResponse, InputStream, Long, RestErrorResponse, FormDataContentDisposition, } from "./model"
export namespace DataResource {
/**
* Get back some data from the data environment
*/
export function retrieveDataId({ restConfig, queries, params, data, }: {
restConfig: RESTConfig,
queries: {
Authorization: string,
},
params: {
id: Long,
},
data: string,
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/data/{id}",
requestType: HTTPRequestModel.GET,
},
restConfig,
params,
queries,
data,
}, isResponse);
};
/**
* Get a thumbnail of from the data environment (if resize is possible)
*/
export function retrieveDataThumbnailId({ restConfig, queries, params, data, }: {
restConfig: RESTConfig,
queries: {
Authorization: string,
},
params: {
id: Long,
},
data: string,
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/data/thumbnail/{id}",
requestType: HTTPRequestModel.GET,
},
restConfig,
params,
queries,
data,
}, isResponse);
};
/**
* Get back some data from the data environment (with a beautifull name (permit download with basic name)
*/
export function retrieveDataFull({ restConfig, queries, params, data, }: {
restConfig: RESTConfig,
queries: {
Authorization: string,
},
params: {
name: string,
id: Long,
},
data: string,
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/data/{id}/{name}",
requestType: HTTPRequestModel.GET,
},
restConfig,
params,
queries,
data,
}, isResponse);
};
/**
* Insert a new data in the data environment
*/
export function uploadFile({ restConfig, data, }: {
restConfig: RESTConfig,
data: {
file: FormDataContentDisposition,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/data//upload/",
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, isResponse);
};
}

View File

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

View File

@ -0,0 +1,124 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray } from "./rest-tools"
import {Response, isResponse, InputStream, Long, RestErrorResponse, isGender, Gender, FormDataContentDisposition, } from "./model"
export namespace GenderResource {
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/gender/{id}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
export function get({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<Gender[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/gender",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isGender);
};
export function put({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: string,
}): 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: string,
}): Promise<Gender> {
return RESTRequestJson({
restModel: {
endPoint: "/gender",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, isGender);
};
export function uploadCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: FormDataContentDisposition,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/gender/{id}/cover",
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isResponse);
};
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: Long,
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/gender/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
export function getWithId({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Gender> {
return RESTRequestJson({
restModel: {
endPoint: "/gender/{id}",
requestType: HTTPRequestModel.GET,
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 } from "./rest-tools"
import {RestErrorResponse, isHealthResult, HealthResult, } 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

@ -1,5 +1,13 @@
import { Media, isMedia } from "./media";
export {
Media, isMedia,
}
/**
* 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

@ -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

@ -0,0 +1,462 @@
/**
* 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 ZodResponse = zod.object({
});
export type Response = zod.infer<typeof ZodResponse>;
export function isResponse(data: any): data is Response {
try {
ZodResponse.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(),
covers: zod.array(ZodLong).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 ZodInputStream = zod.object({
});
export type InputStream = zod.infer<typeof ZodInputStream>;
export function isInputStream(data: any): data is InputStream {
try {
ZodInputStream.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodContentDisposition = zod.object({
});
export type ContentDisposition = zod.infer<typeof ZodContentDisposition>;
export function isContentDisposition(data: any): data is ContentDisposition {
try {
ZodContentDisposition.parse(data);
return true;
} catch (e: any) {
console.log(`Fail to parse data ${e}`);
return false;
}
}
export const ZodFormDataContentDisposition = ZodContentDisposition.extend({
});
export type FormDataContentDisposition = zod.infer<typeof ZodFormDataContentDisposition>;
export function isFormDataContentDisposition(data: any): data is FormDataContentDisposition {
try {
ZodFormDataContentDisposition.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,158 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray } from "./rest-tools"
import {Response, Playlist, isPlaylist, isResponse, InputStream, Long, RestErrorResponse, FormDataContentDisposition, } from "./model"
export namespace PlaylistResource {
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
export function get({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<Playlist[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/playlist",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isPlaylist);
};
export function put({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: string,
}): 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: string,
}): Promise<Playlist> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, 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,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isPlaylist);
};
export function uploadCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: FormDataContentDisposition,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}/cover",
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isResponse);
};
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: Long,
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
export function getWithId({ 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 addTrack({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
trackId: Long,
id: Long,
},
}): Promise<Playlist> {
return RESTRequestJson({
restModel: {
endPoint: "/playlist/{id}/track/{trackId}",
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isPlaylist);
};
}

View File

@ -0,0 +1,217 @@
/** @file
* @author Edouard DUPIN
* @copyright 2024, Edouard DUPIN, all right reserved
* @license MPL-2 (Generate file)
*/
import { RestErrorResponse } from "./model"
export enum HTTPRequestModel {
DELETE = 'DELETE',
GET = 'GET',
PATCH = 'PATCH',
POST = 'POST',
PUT = 'PUT',
}
export enum HTTPMimeType {
ALL = '*/*',
IMAGE = 'image/*',
IMAGE_JPEG = 'image/jpeg',
IMAGE_PNG = 'image/png',
JSON = 'application/json',
OCTET_STREAM = 'application/octet-stream',
}
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 RESTRequest {
params?: object;
body?: any;
}
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,
};
/**
* This service permit to add some data like token and authorization..
*/
export function RESTRequest({ restModel, restConfig, data, params, queries }: RESTRequestType): Promise<ModelResponseHttp> {
// Create the URL PATH:
let generateUrl = `${restConfig.server}/${restModel.endPoint}`;
if (params !== undefined) {
for (let key of Object.keys(params)) {
generateUrl = generateUrl.replaceAll(`{${key}}`, `${params[key]}`);
}
}
if (queries !== undefined) {
const searchParams = new URLSearchParams();
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}`);
}
generateUrl += "?" + searchParams.toString();
}
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
headers['Content-Type'] = restModel.contentType;
}
let body = data;
if (restModel.contentType === HTTPMimeType.JSON) {
body = JSON.stringify(data);
}
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);
});
});
}

View File

@ -0,0 +1,180 @@
/**
* API of the server (auto-generated code)
*/
import { HTTPMimeType, HTTPRequestModel, ModelResponseHttp, RESTConfig, RESTRequestJson, RESTRequestJsonArray } from "./rest-tools"
import {Response, isTrack, isResponse, InputStream, Long, RestErrorResponse, FormDataContentDisposition, Track, } from "./model"
export namespace TrackResource {
export function remove({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
export function get({ restConfig, }: {
restConfig: RESTConfig,
}): Promise<Track[]> {
return RESTRequestJsonArray({
restModel: {
endPoint: "/track",
requestType: HTTPRequestModel.GET,
accept: HTTPMimeType.JSON,
},
restConfig,
}, isTrack);
};
export function put({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: string,
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}",
requestType: HTTPRequestModel.PATCH,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isTrack);
};
export function create({ restConfig, data, }: {
restConfig: RESTConfig,
data: string,
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track",
requestType: HTTPRequestModel.POST,
contentType: HTTPMimeType.JSON,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, 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,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isTrack);
};
export function uploadCover({ restConfig, params, data, }: {
restConfig: RESTConfig,
params: {
id: Long,
},
data: {
fileName: string,
file: FormDataContentDisposition,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}/cover",
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
data,
}, isResponse);
};
export function removeCover({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
coverId: Long,
id: Long,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}/cover/{coverId}",
requestType: HTTPRequestModel.DELETE,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isResponse);
};
export function uploadFile({ restConfig, data, }: {
restConfig: RESTConfig,
data: {
fileName: string,
file: FormDataContentDisposition,
gender: string,
artist: string,
album: string,
trackId: string,
title: string,
},
}): Promise<Response> {
return RESTRequestJson({
restModel: {
endPoint: "/track//upload/",
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
},
restConfig,
data,
}, isResponse);
};
export function getWithId({ 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 addTrack({ restConfig, params, }: {
restConfig: RESTConfig,
params: {
artistId: Long,
id: Long,
},
}): Promise<Track> {
return RESTRequestJson({
restModel: {
endPoint: "/track/{id}/artist/{artistId}",
requestType: HTTPRequestModel.POST,
accept: HTTPMimeType.JSON,
},
restConfig,
params,
}, isTrack);
};
}

View File

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

View File

@ -14,7 +14,7 @@ import { isNullOrUndefined } from 'common/utils';
export class ElementList {
constructor(
public value: number,
public value: bigint,
public label: string) {
// nothing to do.
}
@ -27,14 +27,14 @@ export class FileParsedElement {
public file: File,
public artist: string,
public album: string,
public trackId: number,
public trackId: bigint,
public title: string) {
// nothing to do.
}
}
export class FileFailParsedElement {
constructor(
public id: number,
public id: bigint,
public file: File,
public reason: string) {
// nothing to do.
@ -52,9 +52,9 @@ export class UploadScene implements OnInit {
parsedFailedElement: FileFailParsedElement[] = [];
uploadFileValue: string = '';
selectedFiles: FileList;
genderId: number = null;
artistId: number = null;
albumId: number = null;
genderId: bigint = null;
artistId: bigint = null;
albumId: bigint = null;
needSend: boolean = false;
// list of all files already registered in the bdd to compare with the current list of files.
@ -86,7 +86,7 @@ export class UploadScene implements OnInit {
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,
limitTo: 10, // number thats limits the no of options displayed in the UI (if zero, options will not be limited)
limitTo: 10, // bigint thats limits the no of options displayed in the UI (if zero, options will not be limited)
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,
@ -284,7 +284,7 @@ export class UploadScene implements OnInit {
// parsedElement: FileParsedElement[] = [];
let artist: string = undefined;
let album: string | null = undefined;
let trackIdNumber: number | null = undefined;
let trackIdbigint: bigint | null = undefined;
let title: string = '';
console.log(`select file ${file.name}`);
@ -305,19 +305,19 @@ export class UploadScene implements OnInit {
//console.log("ploppppp " + tmpName);
const splitElement3 = tmpName.split('-');
if (splitElement3.length > 1) {
trackIdNumber = parseInt(splitElement3[0], 10);
trackIdbigint = parseInt(splitElement3[0], 10);
tmpName = tmpName.substring(splitElement3[0].length + 1);
}
//console.log("KKKppppp " + tmpName);
//console.log(" ===> " + splitElement3[0]);
title = tmpName;
if (isNaN(trackIdNumber)) {
trackIdNumber = undefined;
if (isNaN(trackIdbigint)) {
trackIdbigint = undefined;
}
// remove extention
title = title.replace(new RegExp('\\.(webm|WEBM|Webm)'), '');
let tmp = new FileParsedElement(file, artist, album, trackIdNumber, title);
let tmp = new FileParsedElement(file, artist, album, trackIdbigint, title);
console.log(`==>${JSON.stringify(tmp)}`);
// add it in the list.
this.parsedElement.push(tmp);
@ -387,10 +387,10 @@ export class UploadScene implements OnInit {
this.globalUpLoad(0, this.parsedElement.length);
}
globalUpLoad(id: number, total: number): void {
globalUpLoad(id: bigint, total: bigint): void {
let self = this;
this.uploadFile(this.parsedElement[id], id, total, () => {
let id2 = id + 1;
let id2 = id + BigInt(1);
if (id2 < total) {
self.globalUpLoad(id2, total);
} else {
@ -400,7 +400,7 @@ export class UploadScene implements OnInit {
self.upload.error = `Error in the upload of the data...${value}`;
});
}
uploadFile(element: FileParsedElement, id: number, total: number, sendDone: any, errorOccurred: any): void {
uploadFile(element: FileParsedElement, id: bigint, total: bigint, sendDone: any, errorOccurred: any): void {
let self = this;
self.upload.labelMediaTitle = '';

View File

@ -66,12 +66,12 @@ export class GenericInterfaceModelDB {
}
reject("The model is wrong ...");
}).catch((response) => {
console.log(`[E] ${self.constructor.name}: can not retrive BDD values`);
console.log(`[E] ${self.constructor.name}: can not retrieve BDD values`);
reject(response);
});
});
}
get(id: number): Promise<NodeData> {
get(id: bigint): Promise<NodeData> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
@ -88,7 +88,7 @@ export class GenericInterfaceModelDB {
});
});
}
getAll(ids: number[]): Promise<NodeData[]> {
getAll(ids: bigint[]): Promise<NodeData[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
@ -128,17 +128,17 @@ export class GenericInterfaceModelDB {
return this.bdd.addAfterPost(this.serviceName, ret);
}
patch(id: number, data: any): any {
patch(id: bigint, data: any): any {
let ret = this.http.patchSpecific([this.serviceName, id], data);
return this.bdd.setAfterPut(this.serviceName, id, ret);
}
delete(id: number): any {
delete(id: bigint): any {
let ret = this.http.deleteSpecific([this.serviceName, id]);
return this.bdd.delete(this.serviceName, id, ret);
}
deleteCover(nodeId: number, coverId: number) {
deleteCover(nodeId: bigint, coverId: number) {
let self = this;
return new Promise((resolve, reject) => {
self.http.getSpecific([this.serviceName, nodeId, 'rm_cover', coverId])
@ -156,7 +156,7 @@ export class GenericInterfaceModelDB {
});
}
uploadCover(file: File,
nodeId: number,
nodeId: bigint,
progress: any = null) {
const formData = new FormData();
formData.append('fileName', file.name);
@ -168,7 +168,7 @@ export class GenericInterfaceModelDB {
.then((response) => {
let data = response;
if (data === null || data === undefined) {
reject('error retrive data from server');
reject('error retrieve data from server');
return;
}
self.bdd.asyncSetInDB(self.serviceName, nodeId, data);

View File

@ -13,12 +13,12 @@ import { GenericInterfaceModelDB } from './GenericInterfaceModelDB';
@Injectable()
export class AlbumService extends GenericInterfaceModelDB {
constructor(http: HttpWrapperService,
bdd: BddService) {
bdd: BddService) {
super('album', http, bdd);
}
getAllTracksForAlbums(idAlbums: number[]): Promise<number[]> {
getAllTracksForAlbums(idAlbums: bigint[]): Promise<bigint[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
@ -29,8 +29,8 @@ export class AlbumService extends GenericInterfaceModelDB {
key: 'albumId',
value: idAlbums,
},
],
[ 'name' ]); // tODO : set the Id in the track ...
],
['name']); // tODO : set the Id in the track ...
// filter with artist- ID !!!
const listId = DataInterface.extractLimitOne(data, "id");
resolve(listId);
@ -45,7 +45,7 @@ export class AlbumService extends GenericInterfaceModelDB {
* @param idAlbum - Id of the album.
* @returns a promise on the list of track elements
*/
getTrack(idAlbum:number): Promise<NodeData[]> {
getTrack(idAlbum: bigint): Promise<NodeData[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
@ -56,8 +56,8 @@ export class AlbumService extends GenericInterfaceModelDB {
key: 'albumId',
value: idAlbum,
},
],
[ 'name' ]); // tODO : set the Id in the track ...
],
['name']); // tODO : set the Id in the track ...
resolve(data);
}).catch((response) => {
reject(response);
@ -69,7 +69,7 @@ export class AlbumService extends GenericInterfaceModelDB {
* @param idAlbum - Id of the album.
* @returns a promise on the list of Artist names for this album
*/
getArtists(idAlbum:number): Promise<String[]> {
getArtists(idAlbum: bigint): Promise<String[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
@ -80,20 +80,20 @@ export class AlbumService extends GenericInterfaceModelDB {
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) => {
.then((response: DataInterface) => {
let dataArtist = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'id',
value: listArtistId,
},
], [ 'name']);
], ['name']);
const listArtistNames = DataInterface.extractLimitOne(dataArtist, "name");
resolve(listArtistNames);
return;
@ -107,11 +107,11 @@ export class AlbumService extends GenericInterfaceModelDB {
}
/**
* Get the number of track in this saison ID
* Get the bigint of track in this saison ID
* @param AlbumId - Id of the album.
* @returns The number of element present in this saison
* @returns The bigint of element present in this saison
*/
countTrack(AlbumId:number): Promise<number> {
countTrack(AlbumId: bigint): Promise<number> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
@ -122,7 +122,7 @@ export class AlbumService extends GenericInterfaceModelDB {
key: 'albumId',
value: AlbumId,
},
]);
]);
resolve(data.length);
}).catch((response) => {
reject(response);

View File

@ -18,87 +18,87 @@ import { NodeData } from 'common/model';
import { isNullOrUndefined, isStringNullOrUndefined, isUndefined } from 'common/utils';
export class InputOrders {
public genderId: number = undefined;
public playlistId: number = undefined;
public artistId: number = undefined;
public albumId: number = undefined;
public trackId: number = undefined;
public genderId: bigint = undefined;
public playlistId: bigint = undefined;
public artistId: bigint = undefined;
public albumId: bigint = undefined;
public trackId: bigint = undefined;
}
@Injectable()
export class ArianeService {
public genderId: number = undefined;
public genderId: bigint = undefined;
public typeName: string = undefined;
@Output() typeChange: EventEmitter<number> = new EventEmitter();
@Output() typeChange: EventEmitter<bigint> = new EventEmitter();
public playlistId: number = undefined;
public playlistName: string = undefined;
@Output() playlistChange: EventEmitter<number> = new EventEmitter();
public playlistId: bigint = undefined;
public playlistName: string = undefined;
@Output() playlistChange: EventEmitter<bigint> = new EventEmitter();
public artistId: number = undefined;
public artistName: string = undefined;
@Output() artistChange: EventEmitter<number> = new EventEmitter();
public artistId: bigint = undefined;
public artistName: string = undefined;
@Output() artistChange: EventEmitter<bigint> = new EventEmitter();
public albumId: number = undefined;
public albumName: string = undefined;
@Output() albumChange: EventEmitter<number> = new EventEmitter();
public albumId: bigint = undefined;
public albumName: string = undefined;
@Output() albumChange: EventEmitter<bigint> = new EventEmitter();
public trackId: number = undefined;
public trackName: string = undefined;
@Output() trackChange: EventEmitter<number> = new EventEmitter();
public trackId: bigint = undefined;
public trackName: string = undefined;
@Output() trackChange: EventEmitter<bigint> = 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 | bigint {
let valueStr = params.get(name);
if (isNullOrUndefined(valueStr) || isStringNullOrUndefined(valueStr)) {
return undefined;
}
return BigInt(valueStr);
}
updateProperties() {
updateProperties() {
let elem = this.router.routerState.root;
while (!isNullOrUndefined(elem.firstChild)) {
elem = elem.firstChild;
@ -122,17 +122,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 +140,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: bigint): 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(): bigint | 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: bigint | 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(): bigint | 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: bigint | 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(): bigint | 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: bigint | 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(): bigint | 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: bigint | 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(): bigint | 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: bigint[],
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: bigint,
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?: bigint; newWindows?: boolean; }): void {
this.genericNavigate('playlist', [id], newWindows);
}
navigatePlaylistEdit({ id, newWindows }: { id: bigint; 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?: bigint; 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: bigint; newWindows?: boolean; }): void {
this.genericNavigateEdit('gender', id, newWindows);
}
navigateAlbum({ albumId, newWindows }: { albumId?: bigint; newWindows?: boolean; }): void {
this.genericNavigate('album', [albumId], newWindows);
}
navigateAlbumEdit({ id, newWindows }: { id: bigint; 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?: bigint; albumId?: bigint, 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: bigint; 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?: bigint; 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: bigint; newWindows?: boolean; }): void {
this.genericNavigateEdit('track', id, newWindows);
}

View File

@ -27,7 +27,7 @@ export class ArtistService extends GenericInterfaceModelDB {
* @param idArtist - Id of the artist.
* @returns a promise on the list of track elements
*/
getTrackNoAlbum(idArtist:number): Promise<NodeData[]> {
getTrackNoAlbum(idArtist: bigint): Promise<NodeData[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
@ -42,8 +42,8 @@ export class ArtistService extends GenericInterfaceModelDB {
key: 'albumId',
value: undefined,
},
],
[ 'track', 'name' ]);
],
['track', 'name']);
resolve(data);
}).catch((response) => {
reject(response);
@ -55,7 +55,7 @@ export class ArtistService extends GenericInterfaceModelDB {
* @param idArtist - Id of the artist.
* @returns a promise on the list of track elements
*/
getAllTracks(idArtist:number): Promise<NodeData[]> {
getAllTracks(idArtist: bigint): Promise<NodeData[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
@ -66,8 +66,8 @@ export class ArtistService extends GenericInterfaceModelDB {
key: 'artists',
value: idArtist,
}
],
[ 'track', 'name' ]);
],
['track', 'name']);
resolve(data);
}).catch((response) => {
reject(response);
@ -80,18 +80,18 @@ export class ArtistService extends GenericInterfaceModelDB {
* @param id - Id of the artist.
* @returns The number of track present in this artist
*/
countTrack(artistId:number): Promise<number> {
countTrack(artistId: bigint): Promise<number> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response:DataInterface) => {
.then((response: DataInterface) => {
let data = response.getsWhere([
{
check: TypeCheck.CONTAINS,
key: 'artists',
value: artistId,
},
]);
]);
resolve(data.length);
}).catch((response) => {
reject(response);
@ -104,11 +104,11 @@ export class ArtistService extends GenericInterfaceModelDB {
* @param idArtist - ID of the artist
* @returns the required List.
*/
getAlbum(idArtist:number): Promise<NodeData[]> {
getAlbum(idArtist: bigint): Promise<NodeData[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response:DataInterface) => {
.then((response: DataInterface) => {
//console.log(" <<<========================================>>> " + idArtist);
let data = response.getsWhere([
{
@ -116,20 +116,20 @@ export class ArtistService extends GenericInterfaceModelDB {
key: 'artists',
value: idArtist,
},
], [ 'id' ]);
], ['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) => {
.then((response: DataInterface) => {
let dataAlbum = response.getsWhere([
{
check: TypeCheck.EQUAL,
key: 'id',
value: listAlbumId,
},
], [ 'publication', 'name', 'id' ]);
], ['publication', 'name', 'id']);
resolve(dataAlbum);
//console.log("==> get all albums: " + JSON.stringify(dataAlbum, null, 2));
return;
@ -142,11 +142,11 @@ export class ArtistService extends GenericInterfaceModelDB {
});
});
}
countAlbum(idArtist:number): Promise<number> {
countAlbum(idArtist: bigint): Promise<number> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get('track')
.then((response:DataInterface) => {
.then((response: DataInterface) => {
//console.log(" <<<========================================>>> " + idArtist);
let data = response.getsWhere([
{
@ -154,7 +154,7 @@ export class ArtistService extends GenericInterfaceModelDB {
key: 'artists',
value: idArtist,
},
], [ 'id' ]);
], ['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");

View File

@ -19,27 +19,27 @@ export class PlaylistService extends GenericInterfaceModelDB {
super('playlist', http, bdd);
}
getSubArtist(id:number, select:Array<string> = []):any {
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();
}
getAll(ids: number[]): Promise<NodeData[]> {
getAll(ids: bigint[]): 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' ]);
{
check: TypeCheck.EQUAL,
key: 'id',
value: ids,
},
],
['name', 'id']);
resolve(data);
return;
}).catch((response) => {

View File

@ -5,12 +5,12 @@
*/
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 { Track, isTrack } from 'app/model/server-karusic-api';
@Injectable()
export class TrackService extends GenericInterfaceModelDB {
@ -19,10 +19,10 @@ export class TrackService extends GenericInterfaceModelDB {
bdd: BddService) {
super('track', http, bdd);
}
get(id: number): Promise<Media> {
getTrack(id: bigint): Promise<Track> {
return new Promise((resolve, reject) => {
super.get(id).then((data: NodeData) => {
if (isMedia(data)) {
if (isTrack(data)) {
resolve(data);
return;
}
@ -33,7 +33,7 @@ export class TrackService extends GenericInterfaceModelDB {
});
});
}
getWithAlbum(idAlbum: number): Promise<Media[]> {
getWithAlbum(idAlbum: number): Promise<Track[]> {
let self = this;
return new Promise((resolve, reject) => {
self.bdd.get(self.serviceName)
@ -46,7 +46,7 @@ export class TrackService extends GenericInterfaceModelDB {
},
],
['track', 'name', 'id']);
if (isArrayOf(data, isMedia)) {
if (isArrayOf(data, isTrack)) {
resolve(data);
return;
}
@ -59,10 +59,10 @@ export class TrackService extends GenericInterfaceModelDB {
}
getData(): Promise<Media[]> {
getTrackData(): Promise<Track[]> {
return new Promise((resolve, reject) => {
super.getData().then((data: NodeData[]) => {
if (isArrayOf(data, isMedia)) {
if (isArrayOf(data, isTrack)) {
resolve(data);
return;
}
@ -99,22 +99,22 @@ export class TrackService extends GenericInterfaceModelDB {
}
uploadCoverBlob(blob: Blob,
mediaId: number,
TrackId: bigint,
progress: any = null) {
const formData = new FormData();
formData.append('fileName', 'take_screenshoot');
formData.append('typeId', mediaId.toString());
formData.append('typeId', TrackId.toString());
formData.append('file', blob);
let self = this;
return new Promise((resolve, reject) => {
self.http.uploadMultipart(`${this.serviceName}/${mediaId}/add_cover/`, formData, progress)
self.http.uploadMultipart(`${this.serviceName}/${TrackId}/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);
self.bdd.asyncSetInDB(self.serviceName, TrackId, data);
resolve(data);
}).catch((response) => {
reject(response);