87 Commits

Author SHA1 Message Date
Florian THIERRY
9463ad5935 Change backend container image build. 2025-09-17 14:34:07 +02:00
Florian THIERRY
55d6a6328f Switch from maven to gradle. 2025-09-17 14:25:14 +02:00
03dd52de71 gitea-actions (#8)
All checks were successful
Build and Deploy Java Gradle Application / build-and-deploy (push) Successful in 1m36s
Co-authored-by: Florian THIERRY <florian.thierry@protonmail.com>
Reviewed-on: #8
2025-07-23 22:59:51 +02:00
Florian THIERRY
859273a9c1 Change backend ip address after freebox migration. 2025-07-23 20:48:00 +02:00
653536b0da Merge pull request 'design-system' (#7) from design-system into main
Reviewed-on: #7
2024-10-22 08:36:07 +02:00
Florian THIERRY
5fca5bde55 Rename cod-btn into cod-button. 2024-10-22 08:32:46 +02:00
Florian THIERRY
d36fd17690 Add i18n. 2024-10-22 08:23:27 +02:00
Florian THIERRY
295f977a21 Add icon button style. 2024-10-22 08:17:07 +02:00
Florian THIERRY
1a00d0cd19 Add missing ripple. 2024-10-22 08:17:07 +02:00
Florian THIERRY
2da6a58b20 Change version number. 2024-10-22 08:17:07 +02:00
Florian THIERRY
0d2883fe2a Code cleanning. 2024-10-22 08:17:07 +02:00
Florian THIERRY
7f99d11209 Add ripple everywhere. 2024-10-22 08:17:07 +02:00
Florian THIERRY
053ac89e3c Misc changes about form inputs. 2024-10-22 08:17:07 +02:00
Florian THIERRY
cfca22bf66 Factorization of input styling. 2024-10-22 08:17:07 +02:00
Florian THIERRY
7c5cc38cff Initiate design system and refactor login page buttons. 2024-10-22 08:17:07 +02:00
Florian THIERRY
dae0a4b78d Fix field edition problem. 2024-10-18 10:37:31 +02:00
Florian THIERRY
882ffe7094 Several changes about token refreshing. 2024-10-15 16:11:46 +02:00
Florian THIERRY
136771ab60 Add i18n missing translation. 2024-10-15 09:35:14 +02:00
3865c26397 Merge pull request 'Add a guard to deny access for some routes.' (#6) from already-auth-guard into main
Add a guard to deny access for some routes.
2024-10-15 08:26:45 +02:00
Florian THIERRY
26a217cd50 Add a guard to deny access for some routes. 2024-10-15 08:25:49 +02:00
ff52a198dc Upgrade to angular 18. 2024-09-24 22:47:15 +02:00
Florian THIERRY
f3d59a0ef3 conf cleaning. 2024-09-22 13:18:08 +02:00
Florian THIERRY
d84485e52b test 2024-09-22 13:03:39 +02:00
Florian THIERRY
f789d89995 test 2024-09-22 12:53:55 +02:00
Florian THIERRY
7e0174bcc2 test 2024-09-22 12:46:41 +02:00
Florian THIERRY
fe1d59a3bb test 2024-09-22 12:37:01 +02:00
Florian THIERRY
69a99c9312 test 2024-09-22 12:34:02 +02:00
Florian THIERRY
a6414ae64d test 2024-09-22 12:30:18 +02:00
Florian THIERRY
9cf47f0e2a test 2024-09-22 12:27:59 +02:00
Florian THIERRY
6c89562dc3 test 2024-09-22 12:14:04 +02:00
Florian THIERRY
e85eabbed5 test 2024-09-22 12:01:05 +02:00
Florian THIERRY
1ec4ba8212 test conf prod. 2024-09-22 11:10:01 +02:00
Florian THIERRY
a1ff181443 test conf prod. 2024-09-22 11:09:14 +02:00
Florian THIERRY
ee8f48bc43 Fix prod fr configuration. 2024-09-22 10:55:49 +02:00
Florian THIERRY
7ec1aee884 test 2024-09-21 23:39:46 +02:00
Florian THIERRY
a3adfa8ee0 Fix bug of preview content. 2024-09-21 22:20:00 +02:00
Florian THIERRY
d893afa1f3 i18n 2024-09-21 21:43:09 +02:00
Florian THIERRY
d984128176 i18n 2024-09-21 21:40:49 +02:00
Florian THIERRY
f8d73c9ed0 i18n 2024-09-21 21:34:16 +02:00
Florian THIERRY
208b935ffa i18n for some components. 2024-09-21 21:17:31 +02:00
Florian THIERRY
f12dfc7029 i18n for files in core package. 2024-09-21 21:09:36 +02:00
Florian THIERRY
98a890e915 i18n for signin page. 2024-09-21 21:06:47 +02:00
Florian THIERRY
0c1b52d734 i18n for publication search page. 2024-09-21 21:03:34 +02:00
Florian THIERRY
3f6764dd7d i18n for publication update page. 2024-09-21 21:00:59 +02:00
Florian THIERRY
67c3d0b3e6 i18n of publication creation page. 2024-09-21 20:57:05 +02:00
Florian THIERRY
36208ef071 i18n of publication page. 2024-09-21 12:28:55 +02:00
Florian THIERRY
b546a0cf01 Add i18n completion tool. 2024-09-21 12:20:22 +02:00
Florian THIERRY
3935f6ad21 i18n for login page. 2024-09-21 11:22:35 +02:00
Florian THIERRY
fd5ad7e88e i18n for disconnection page. 2024-09-21 11:13:08 +02:00
Florian THIERRY
8c957fe694 i18n for home page. 2024-09-21 11:12:07 +02:00
Florian THIERRY
cb0ef7ddd5 Test 2024-09-20 18:38:17 +02:00
Florian THIERRY
42e466fe8b test ci. 2024-09-20 17:32:43 +02:00
Florian THIERRY
2c5fa4fa13 test ci. 2024-09-20 17:25:37 +02:00
Florian THIERRY
ebce44c889 test ci 2024-09-20 17:12:13 +02:00
Florian THIERRY
955dc48f51 test ci 2024-09-20 16:46:11 +02:00
Florian THIERRY
29e75e6298 Test ci. 2024-09-20 16:34:29 +02:00
Florian THIERRY
187fd105d3 Fix pictures paths. 2024-09-20 09:36:10 +02:00
Florian THIERRY
1b92fd269e Fix config. 2024-09-19 22:24:39 +02:00
Florian THIERRY
23025e3606 Fix fucking MIME types of javascript files. 2024-09-19 22:13:10 +02:00
Florian THIERRY
38c11e2d9f gitignore. 2024-09-19 18:03:33 +02:00
Florian THIERRY
610723c561 CI/CD drafting. 2024-09-19 18:03:23 +02:00
Florian THIERRY
0e2fb945a4 Initialize docker build configuration. 2024-09-18 10:18:40 +02:00
Florian THIERRY
ef32572521 Change favicon. 2024-09-18 09:22:11 +02:00
Florian THIERRY
e5a128a7f6 Fix style. 2024-09-18 09:10:46 +02:00
Florian THIERRY
f5e1e10ebd Add confirmation dialog to delete publications. 2024-09-18 09:05:18 +02:00
Florian THIERRY
500952d4d4 Implementation of categoryId edition. 2024-09-10 10:47:58 +02:00
Florian THIERRY
1cc4abc24e Add default picture and factorization of title in publication edition. 2024-09-10 09:40:45 +02:00
Florian THIERRY
00945de270 Code cleaning about publication edition component. 2024-09-06 10:20:05 +02:00
Florian THIERRY
5804d8cc9f Extract publication edition into a separated component. 2024-09-05 17:28:30 +02:00
Florian THIERRY
5610bd170a Minor changes 2024-09-05 09:35:46 +02:00
Florian THIERRY
21d19d4ecd Styling elements. 2024-09-05 09:33:07 +02:00
Florian THIERRY
f3dfac6bc7 Add delete button. 2024-09-05 09:23:25 +02:00
Florian THIERRY
4565192d0b Remote temp configuration. 2024-09-04 14:20:31 +02:00
Florian THIERRY
d7ac4966c9 Add "new publication" button. 2024-09-04 14:19:26 +02:00
Florian THIERRY
64119a956a Add "my-publications" page. 2024-09-04 14:06:10 +02:00
Florian THIERRY
c4dea2cc85 Dependency cleaning. 2024-09-04 10:28:22 +02:00
Florian THIERRY
b0cc42fddd Implementaiton of preview tab. 2024-09-04 10:26:47 +02:00
Florian THIERRY
db669114b2 Add Prism.js. 2024-09-04 09:29:10 +02:00
Florian THIERRY
ca6b207816 Fix refresh token mecanism. 2024-09-04 08:58:47 +02:00
Florian THIERRY
b091dc52b7 Fix authentication errors handling. 2024-09-03 11:45:47 +02:00
Florian THIERRY
4d44b6f53c First implementation of refresh token. 2024-09-03 10:37:58 +02:00
Florian THIERRY
be34c555a5 Implementation of code-block addition in the publication. 2024-09-03 10:07:13 +02:00
Florian THIERRY
c03d977028 Add code-block dialog and style it. 2024-09-03 10:00:45 +02:00
Florian THIERRY
afd184f936 Fix author-id publications search. 2024-08-30 22:37:03 +02:00
Florian THIERRY
c09c68e1ac Implementation of picture addition button in editor. 2024-08-30 18:13:43 +02:00
Florian THIERRY
b84ba15f4c Implementaiton of h1, h2, h3 and link button on publication editor. 2024-08-30 18:01:29 +02:00
Florian THIERRY
51af25666d Fix search bar navigation. 2024-08-30 09:59:21 +02:00
143 changed files with 6537 additions and 3789 deletions

View File

@@ -0,0 +1,75 @@
name: Build and Deploy Java Gradle Application
on:
push:
branches:
- main
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: 📄 Checkout code
uses: actions/checkout@v4
- name: 📄 Checkout configuration
env:
SSH_PRIVATE_KEY: ${{ secrets.PROD_PROPERTIES_SSH_KEY }}
run: |
mkdir -p ~/.ssh
echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
git clone -b hexagonal-reforged ssh://gitea@gitea.takiguchi.ovh:12960/Codiki/codiki-properties.git --config core.sshCommand='ssh -o StrictHostKeyChecking=no'
- name: 📄 Edit configuration
run: |
sed -i "s/<POSTGRES_PASSWORD>/$(cat ./codiki-properties/passwords/postgresql/codiki_user)/g" ./codiki-properties/application-prod.yml
cp ./codiki-properties/application-prod.yml ./backend/codiki-launcher/src/main/resources/application.yml
sed -i "s/<POSTGRES_ADMIN_PASSWORD>/$(cat ./codiki-properties/passwords/postgresql/codiki_admin)/g" ./docker-compose.yml
- name: 🔨 Build backend docker image
run: |
sudo /usr/bin/docker build -t codiki-backend -f ./Dockerfile-backend . --no-cache
- name: 📦 Extract backend docker image into archive
run: |
sudo /usr/bin/docker save codiki-backend:latest -o ./codiki-backend.tar
- name: 🔨 Build frontend docker image
run: |
sudo /usr/bin/docker build -t codiki-frontend -f ./Dockerfile-frontend . --no-cache
- name: 📦 Extract frontend docker image into archive
run: |
sudo /usr/bin/docker save codiki-frontend:latest -o ./codiki-frontend.tar
- name: 📤 Transfer artifacts to remote server
env:
SSH_PRIVATE_KEY: ${{ secrets.PROD_SSH_PRIVATE_KEY }}
REMOTE_USER: ${{ secrets.PROD_REMOTE_USER }}
REMOTE_HOST: ${{ secrets.PROD_REMOTE_HOST }}
REMOTE_PORT: ${{ secrets.PROD_REMOTE_PORT }}
REMOTE_PATH: ${{ secrets.PROD_REMOTE_PATH }}
run: |
mkdir -p ~/.ssh
echo "$SSH_PRIVATE_KEY" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
scp -o StrictHostKeyChecking=no -P $REMOTE_PORT ./codiki-backend.tar $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH
scp -o StrictHostKeyChecking=no -P $REMOTE_PORT ./codiki-frontend.tar $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH
scp -o StrictHostKeyChecking=no -P $REMOTE_PORT ./docker-compose.yml $REMOTE_USER@$REMOTE_HOST:$REMOTE_PATH
- name: 🚀 Launch application onto remote server
env:
SSH_PRIVATE_KEY: ${{ secrets.PROD_SSH_PRIVATE_KEY }}
REMOTE_USER: ${{ secrets.PROD_REMOTE_USER }}
REMOTE_HOST: ${{ secrets.PROD_REMOTE_HOST }}
REMOTE_PORT: ${{ secrets.PROD_REMOTE_PORT }}
REMOTE_PATH: ${{ secrets.PROD_REMOTE_PATH }}
run: |
ssh -o StrictHostKeyChecking=no $REMOTE_HOST -l $REMOTE_USER -p $REMOTE_PORT << EOC
cd $REMOTE_PATH
sudo /usr/bin/docker load < $REMOTE_PATH/codiki-backend.tar
sudo /usr/bin/docker load < $REMOTE_PATH/codiki-frontend.tar
sudo /usr/bin/docker compose down
sudo /usr/bin/docker compose up --detach
EOC

14
.gitignore vendored
View File

@@ -81,4 +81,16 @@ testem.log
# System files
.DS_Store
Thumbs.db
Thumbs.db
**/ci/bin/
# Linux start script should use lf
/gradlew text eol=lf
# These are Windows script files and should use crlf
*.bat text eol=crlf
# Binary files should be left untouched
*.jar binary
**/.gradle

16
Dockerfile-backend Normal file
View File

@@ -0,0 +1,16 @@
FROM gradle:9.0.0-jdk21 AS builder
WORKDIR /app
COPY backend/gradlew /app/
COPY backend/build.gradle.kts /app/
COPY backend/settings.gradle.kts /app/
COPY backend/codiki-application /app/codiki-application
COPY backend/codiki-domain /app/codiki-domain
COPY backend/codiki-exposition /app/codiki-exposition
COPY backend/codiki-infrastructure /app/codiki-infrastructure
COPY backend/codiki-launcher /app/codiki-launcher
WORKDIR /app
RUN gradle build jar
FROM eclipse-temurin:21-jre-alpine AS final
COPY --from=builder /app/codiki-launcher/build/libs/codiki-launcher.jar /app/codiki.jar
CMD ["java", "-jar", "/app/codiki.jar"]

12
Dockerfile-frontend Normal file
View File

@@ -0,0 +1,12 @@
FROM node:24-alpine AS builder
WORKDIR /app
COPY frontend /app
RUN npm install
RUN npm run build-prod-en
RUN npm run build-prod-fr
FROM nginx:1.29-alpine AS final
WORKDIR /app
COPY --from=builder /app/dist/codiki/en/browser /usr/share/nginx/html/en/
COPY --from=builder /app/dist/codiki/fr/browser/fr /usr/share/nginx/html/fr/
COPY frontend/conf/nginx.conf /etc/nginx/nginx.conf

84
Jenkinsfile vendored Normal file
View File

@@ -0,0 +1,84 @@
pipeline {
agent any
stages {
stage('Configuration') {
steps {
dir('codiki-properties') {
git url:'https://gitea.takiguchi.ovh/Codiki/codiki-properties.git', branch: 'hexagonal-reforged', credentialsId: 'Jenkins-gitea'
}
script {
sh 'sed -i "s/<POSTGRES_PASSWORD>/$(cat ./codiki-properties/passwords/postgresql/codiki_user)/g" ./codiki-properties/application-prod.yml'
sh 'cp ./codiki-properties/application-prod.yml ./backend/codiki-launcher/src/main/resources/application-prod.yml'
sh 'sed -i "s/<POSTGRES_PASSWORD>/$(cat ./codiki-properties/passwords/postgresql/codiki_admin)/g" ./docker-compose.yml'
}
}
}
stage('Build') {
steps {
script {
sh """
sudo /usr/bin/docker build -t codiki-backend -f ./Dockerfile-backend . --no-cache
sudo /usr/bin/docker build -t codiki-frontend -f ./Dockerfile-frontend . --no-cache
sudo /usr/bin/docker save codiki-backend:latest -o ./codiki-backend.tar
sudo /usr/bin/docker save codiki-frontend:latest -o ./codiki-frontend.tar
sudo chown jenkins:jenkins ./codiki-backend.tar
sudo chown jenkins:jenkins ./codiki-frontend.tar
chmod 644 ./codiki-backend.tar
chmod 644 ./codiki-frontend.tar
"""
}
}
}
stage('Deploy') {
steps {
sshPublisher(
publishers: [
sshPublisherDesc(
configName: 'DebianServer [codiki]',
transfers: [
sshTransfer(
cleanRemote: false,
excludes: '',
execCommand: '',
execTimeout: 120000,
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[, ]+',
remoteDirectory: '',
remoteDirectorySDF: false,
removePrefix: '',
sourceFiles: 'codiki-backend.tar,codiki-frontend.tar,docker-compose.yml'
),
sshTransfer(
cleanRemote: false,
excludes: '',
execCommand: """
cd /opt/codiki
sudo /usr/bin/docker load < /opt/codiki/codiki-backend.tar
sudo /usr/bin/docker load < /opt/codiki/codiki-frontend.tar
sudo /usr/bin/docker compose down
sudo /usr/bin/docker compose up --detach
""",
execTimeout: 120000,
flatten: false,
makeEmptyDirs: false,
noDefaultExcludes: false,
patternSeparator: '[, ]+',
remoteDirectory: '',
remoteDirectorySDF: false,
removePrefix: '',
sourceFiles: ''
)
],
usePromotionTimestamp: false,
useWorkspaceInPromotion: false,
verbose: true
)
]
)
}
}
}
}

56
backend/build.gradle.kts Normal file
View File

@@ -0,0 +1,56 @@
plugins {
kotlin("jvm") version "2.2.20"
kotlin("plugin.spring") version "2.2.20"
id("io.spring.dependency-management") version "1.1.7"
}
group = "org.codiki"
version = "0.0.1-SNAPSHOT"
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
repositories {
mavenCentral()
}
subprojects {
apply(plugin = "java")
apply(plugin = "org.jetbrains.kotlin.jvm")
repositories {
mavenCentral()
}
dependencies {
implementation(platform("org.springframework.boot:spring-boot-dependencies:3.5.5"))
compileOnly("org.projectlombok:lombok:1.18.40")
annotationProcessor("org.projectlombok:lombok:1.18.40")
testImplementation("org.assertj:assertj-core:3.27.4")
testImplementation("org.junit.jupiter:junit-jupiter-api")
testImplementation("org.junit.jupiter:junit-jupiter-params")
}
tasks.withType<Test> {
useJUnitPlatform()
}
}
dependencyManagement {
imports {
mavenBom("org.springframework.boot:spring-boot-dependencies:3.5.5")
}
}
kotlin {
compilerOptions {
freeCompilerArgs.addAll("-Xjsr305=strict")
}
}
tasks.withType<Test> {
useJUnitPlatform()
}

View File

@@ -0,0 +1,11 @@
plugins {
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation(project(":codiki-domain"))
implementation("org.springframework:spring-context")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("com.auth0:java-jwt:4.5.0")
implementation("org.apache.commons:commons-lang3") //:3.18.0
}

View File

@@ -1,56 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.codiki</groupId>
<artifactId>codiki-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<artifactId>codiki-application</artifactId>
<name>codiki-application</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-domain</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,6 +1,7 @@
package org.codiki.application.picture;
import java.io.File;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@@ -31,6 +32,7 @@ public class PictureUseCases {
.withId(UUID.randomUUID())
.withPublisher(authenticatedUser)
.withContentFile(pictureFile)
.withPublicationDate(ZonedDateTime.now())
.build();
picturePort.save(newPicture);

View File

@@ -195,4 +195,8 @@ public class PublicationUseCases {
public List<Publication> getLatest() {
return publicationPort.getLatest();
}
public String previewContent(String publicationText) {
return parserService.parse(publicationText);
}
}

View File

@@ -5,6 +5,7 @@ import java.util.stream.IntStream;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
class KeyGeneratorTest {
@@ -16,6 +17,7 @@ class KeyGeneratorTest {
}
@Test
@Disabled
public void generateKey_should_generate_random_keys_with_alphanumeric_characters() {
Pattern validationRegex = Pattern.compile("^[0-9A-Z]{10}$");

View File

@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.codiki</groupId>
<artifactId>codiki-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<artifactId>codiki-domain</artifactId>
<name>codiki-domain</name>
<description>Demo project for Spring Boot</description>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>16</source>
<target>16</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>jar</packaging>
</project>

View File

@@ -0,0 +1,11 @@
plugins {
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation(project(":codiki-application"))
implementation(project(":codiki-domain"))
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.apache.tika:tika-core:3.2.3")
}

View File

@@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.codiki</groupId>
<artifactId>codiki-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<artifactId>codiki-exposition</artifactId>
<name>codiki-exposition</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-application</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
</dependency>
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-data-jpa</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-security</artifactId>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.postgresql</groupId>-->
<!-- <artifactId>postgresql</artifactId>-->
<!-- <scope>runtime</scope>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.boot</groupId>-->
<!-- <artifactId>spring-boot-starter-test</artifactId>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
<!-- <dependency>-->
<!-- <groupId>org.springframework.security</groupId>-->
<!-- <artifactId>spring-security-test</artifactId>-->
<!-- <scope>test</scope>-->
<!-- </dependency>-->
</dependencies>
</project>

View File

@@ -7,10 +7,7 @@ import static org.springframework.http.HttpStatus.UNAUTHORIZED;
import org.codiki.domain.category.exception.CategoryDeletionException;
import org.codiki.domain.category.exception.CategoryEditionException;
import org.codiki.domain.category.exception.CategoryNotFoundException;
import org.codiki.domain.exception.LoginFailureException;
import org.codiki.domain.exception.RefreshTokenDoesNotExistException;
import org.codiki.domain.exception.RefreshTokenExpiredException;
import org.codiki.domain.exception.UserDoesNotExistException;
import org.codiki.domain.exception.*;
import org.codiki.domain.picture.exception.PictureNotFoundException;
import org.codiki.domain.picture.exception.PictureUploadException;
import org.codiki.domain.publication.exception.*;
@@ -51,7 +48,8 @@ public class GlobalControllerExceptionHandler extends ResponseEntityExceptionHan
}
@ExceptionHandler({
RefreshTokenExpiredException.class
RefreshTokenExpiredException.class,
AuthenticationRequiredException.class,
})
public ProblemDetail handleUnauthorizedExceptions(Exception exception) {
return buildProblemDetail(UNAUTHORIZED, exception);

View File

@@ -1,28 +1,22 @@
package org.codiki.exposition.publication;
import org.codiki.application.publication.PublicationUseCases;
import org.codiki.domain.publication.exception.NoPublicationSearchResultException;
import org.codiki.domain.publication.exception.PublicationNotFoundException;
import org.codiki.domain.publication.model.Publication;
import org.codiki.domain.publication.model.PublicationEditionRequest;
import org.codiki.exposition.publication.model.PreviewContentRequest;
import org.codiki.exposition.publication.model.PreviewContentResponse;
import org.codiki.exposition.publication.model.PublicationDto;
import org.codiki.exposition.publication.model.PublicationEditionRequestDto;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.UUID;
import static org.springframework.http.HttpStatus.CREATED;
import static org.springframework.http.HttpStatus.NO_CONTENT;
import static org.springframework.util.ObjectUtils.isEmpty;
import org.codiki.application.publication.PublicationUseCases;
import org.codiki.domain.publication.exception.NoPublicationSearchResultException;
import org.codiki.domain.publication.exception.PublicationNotFoundException;
import org.codiki.domain.publication.model.Publication;
import org.codiki.domain.publication.model.PublicationEditionRequest;
import org.codiki.exposition.publication.model.PublicationDto;
import org.codiki.exposition.publication.model.PublicationEditionRequestDto;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/publications")
@@ -91,4 +85,10 @@ public class PublicationController {
return publications;
}
@PostMapping(value = "/preview")
public PreviewContentResponse previewPublicationContent(@RequestBody PreviewContentRequest request) {
String previewContent = publicationUseCases.previewContent(request.text());
return new PreviewContentResponse(previewContent);
}
}

View File

@@ -0,0 +1,5 @@
package org.codiki.exposition.publication.model;
public record PreviewContentRequest(
String text
) {}

View File

@@ -0,0 +1,5 @@
package org.codiki.exposition.publication.model;
public record PreviewContentResponse(
String text
) {}

View File

@@ -0,0 +1,13 @@
plugins {
id("io.spring.dependency-management") version "1.1.7"
// kotlin("plugin.jpa") version "2.1.20"
}
dependencies {
// implementation(kotlin("stdlib"))
implementation(project(":codiki-application"))
implementation(project(":codiki-domain"))
implementation("org.springframework:spring-context")
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.postgresql:postgresql:42.7.5")
}

View File

@@ -1,60 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.codiki</groupId>
<artifactId>codiki-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<artifactId>codiki-infrastructure</artifactId>
<name>codiki-infrastructure</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-domain</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -31,6 +31,7 @@ public class PictureEntity {
public PictureEntity(Picture picture) {
id = picture.id();
publisherId = picture.publisherId();
publishedAt = picture.publishedAt();
}
public Picture toDomain() {

View File

@@ -9,6 +9,7 @@ import org.codiki.infrastructure.publication.model.PublicationSearchJpaField;
import org.springframework.stereotype.Component;
import static jakarta.persistence.criteria.JoinType.LEFT;
import static org.codiki.infrastructure.publication.model.PublicationSearchJpaField.AUTHOR_ID;
import static org.codiki.infrastructure.publication.model.PublicationSearchJpaField.AUTHOR_PSEUDO;
import jakarta.persistence.criteria.CriteriaBuilder;
@@ -53,9 +54,13 @@ public class PublicationPredicateMapper {
From<?, ?> from = fromPublication;
String attributeName = searchField.getFieldName();
if (searchField == AUTHOR_PSEUDO) {
if (List.of(AUTHOR_PSEUDO, AUTHOR_ID).contains(searchField)) {
from = fromPublication.join("author", LEFT);
attributeName = "pseudo";
attributeName = switch(searchField) {
case AUTHOR_ID -> "id";
case AUTHOR_PSEUDO -> "pseudo";
default -> null;
};
}
if (value instanceof UUID) {

View File

@@ -0,0 +1,17 @@
plugins {
id("org.springframework.boot") version "3.5.5"
id("io.spring.dependency-management") version "1.1.7"
}
dependencies {
implementation(project(":codiki-domain"))
implementation(project(":codiki-application"))
implementation(project(":codiki-infrastructure"))
implementation(project(":codiki-exposition"))
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-devtools")
}
springBoot {
mainClass = "org.codiki.launcher.ApplicationLauncher"
}

View File

@@ -1,46 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.codiki</groupId>
<artifactId>codiki-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<artifactId>codiki-launcher</artifactId>
<name>codiki-launcher</name>
<description>Demo project for Spring Boot</description>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-exposition</artifactId>
</dependency>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-application</artifactId>
</dependency>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-domain</artifactId>
</dependency>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-infrastructure</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -1,7 +1,11 @@
application:
pictures:
path: /home/florian/Developpement/codiki-hexagonal/backend/pictures-folder/
temp-path : /home/florian/Developpement/codiki-hexagonal/backend/pictures-folder/temp/
path: /Users/florian/Documents/Developpement/codiki-hexagonal/backend/pictures-folder/
temp-path : /Users/florian/Documents/Developpement/codiki-hexagonal/backend/pictures-folder/temp/
logging:
level:
org.springframework.security: DEBUG
server:
port: 8987

View File

@@ -9,10 +9,6 @@ application:
path: /opt/codiki/pictures/
temp-path: /opt/codiki/pictures/temp/
logging:
level:
org.springframework.security: DEBUG
server:
http2:
enabled: true

View File

@@ -3,7 +3,7 @@ version: '3.9'
services:
codiki-database:
container_name: "codiki-database"
image: "postgres:16"
image: "postgres:17"
ports:
- "50001:5432"
networks:

251
backend/gradlew vendored Executable file
View File

@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
backend/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1,100 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.codiki</groupId>
<artifactId>codiki-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>codiki</name>
<properties>
<java.version>21</java.version>
<maven.compiler.source>21</maven.compiler.source>
<maven.compiler.target>21</maven.compiler.target>
<jakarta.servlet-api.version>6.0.0</jakarta.servlet-api.version>
<java-jwt.version>4.4.0</java-jwt.version>
<postgresql.version>42.7.0</postgresql.version>
<tika-core.version>2.9.0</tika-core.version>
<commons-lang3.version>3.14.0</commons-lang3.version>
</properties>
<modules>
<module>codiki-domain</module>
<module>codiki-application</module>
<module>codiki-infrastructure</module>
<module>codiki-exposition</module>
<module>codiki-launcher</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>3.2.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-exposition</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-application</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-domain</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.codiki</groupId>
<artifactId>codiki-infrastructure</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>${jakarta.servlet-api.version}</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>${java-jwt.version}</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>${postgresql.version}</version>
</dependency>
<dependency>
<groupId>org.apache.tika</groupId>
<artifactId>tika-core</artifactId>
<version>${tika-core.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,21 @@
meta {
name: Preview content
type: http
seq: 7
}
post {
url: {{url}}/api/publications/preview
body: json
auth: bearer
}
auth:bearer {
token: {{bearerToken}}
}
body:json {
{
"text" : "[h1]Test[/h1]"
}
}

View File

@@ -0,0 +1,11 @@
meta {
name: Refresh token
type: http
seq: 4
}
post {
url: {{url}}/api/users/refresh-token
body: none
auth: none
}

View File

@@ -1,7 +1,7 @@
vars {
url: http://localhost:8987
publicationId: ec76602f-5501-4091-868e-b471611e63de
bearerToken: eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1YWQ0NjJiOC04ZjllLTRhMjYtYmI4Ni1jNzRmZWY1ZDExYjYiLCJleHAiOjE3MTA4Mzc2ODQsInBzZXVkbyI6IlN0YW5kYXJkIHVzZXIiLCJlbWFpbCI6InN0YW5kYXJkLnVzZXJAY29kaWtpLm9yZyIsInJvbGVzIjoiU1RBTkRBUkQifQ.2HggC3T_4I14IpW02DZJiYfgYwc074kU8Y4AmuGf1mZzv0U8OUxpAw_xEhnKtn8NcaCozz_2vFv4o_CaBqS8Ag
bearerToken: eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkMWQ1NTdhNi04OGIxLTQyNzQtOTk0ZS1mOWE5YTYwOTc5OTciLCJleHAiOjE3MjY5NTExNTgsInBob3RvSWQiOiI2MjhkYTFhNy0wNzAyLTRlNDktOGIwNi00ZDg2MGE2YTNkZTUiLCJwc2V1ZG8iOiJUYWtpZ3VjaGkiLCJlbWFpbCI6ImZsb3JpYW4udGhpZXJyeTcyQGdtYWlsLmNvbSIsInJvbGVzIjoiU1RBTkRBUkQifQ.4OQglB0cT2hTMO7_Bfxj7nQPYi42e0Gh06jmHj2q-SQTM6Md70Ii_BiKR__GxY14bahPAjLcIWfAYS2A0Tc1Vw
categoryId: 172fa901-3f4b-4540-92f3-1c15820e8ec9
pictureId: 65b660b7-66bb-4e4a-a62c-fd0ca101f972
}

View File

@@ -0,0 +1,2 @@
rootProject.name = "codiki-backend"
include("codiki-domain", "codiki-application", "codiki-exposition", "codiki-infrastructure", "codiki-launcher")

95
ci.bash Normal file
View File

@@ -0,0 +1,95 @@
#!/bin/bash
SERVER_CODIKI_ROOT_FOLDER='/home/florian/codiki-hexagonal'
SERVER_ADDRESS='192.168.0.153'
SERVER_USER='florian'
SERVER_PORT='22'
function handle_error() {
local resultCode=$1
if [[ $resultCode -ne 0 ]]
then
echo "$errorMessage"
echo
exit 1
else
echo 'Operation succeded.'
echo
fi
}
function change_configuration_files() {
echo 'Copy production configuration file of backend...'
cp ./ci/configuration/backend/application-prod.yml ./backend/codiki-launcher/src/main/resources/application-prod.yml
handle_error $?
}
function build_backend() {
echo 'Backend docker image building...'
docker build -t codiki-backend -f ./Dockerfile-backend . --no-cache
handle_error $?
}
function build_frontend() {
echo 'Frontend docker image building...'
docker build -t codiki-frontend -f ./Dockerfile-frontend . --no-cache
handle_error $?
}
function extract_docker_images() {
echo 'Extraction of backend docker image into an archive...'
docker save codiki-backend:latest -o ./ci/bin/codiki-backend.tar
handle_error $?
echo 'Extraction of frontend docker image into an archive...'
docker save codiki-frontend:latest -o ./ci/bin/codiki-frontend.tar
handle_error $?
}
function copy_docker_compose_file_in_bin_folder() {
echo 'Copy of docker compose file in bin folder...'
cp ./docker-compose.yml ./ci/bin/docker-compose.yml
handle_error $?
}
function upload_files_on_server() {
echo 'Sending of docker images on server'
scp -P $SERVER_PORT ./ci/bin/* $SERVER_USER@$SERVER_ADDRESS:$SERVER_CODIKI_ROOT_FOLDER/
handle_error $?
}
# execute_remote_command_on_server
function ercos() {
local command=$1
ssh -p $SERVER_PORT -l $SERVER_USER $SERVER_ADDRESS $command
handle_error $1
}
function deploy_docker_images_on_server() {
echo 'Import backend docker image archive on server...'
ercos "docker load < $SERVER_CODIKI_ROOT_FOLDER/codiki-backend.tar"
echo 'Import frontend docker image archive on server...'
ercos "docker load < $SERVER_CODIKI_ROOT_FOLDER/codiki-frontend.tar"
}
function restart_services() {
echo 'Stop services on server...'
ercos "cd $SERVER_CODIKI_ROOT_FOLDER && docker compose down"
echo 'Start services on server...'
ercos "cd $SERVER_CODIKI_ROOT_FOLDER && docker compose up --detach"
}
function main() {
change_configuration_files
build_backend
build_frontend
extract_docker_images
copy_docker_compose_file_in_bin_folder
upload_files_on_server
deploy_docker_images_on_server
restart_services
}
main

83
ci/i18n-completer/app.ts Normal file
View File

@@ -0,0 +1,83 @@
'use strict';
import fs from 'fs';
const englishI18nFilePath='../../frontend/src/locale/messages.json';
const frenchI18nFilePath='../../frontend/src/locale/messages-fr.json';
interface Translations {
[key: string]: string;
}
interface I18nFileContent {
locale: string;
translations: Translations;
};
interface Translation {
key: string;
value: string;
}
interface I18nTranslations {
locale: string;
translations: Translation[];
}
function readAndParseFile(filePath): I18nTranslations {
const fileContent = fs.readFileSync(filePath);
const parsedFileContent: I18nFileContent = JSON.parse(fileContent.toString());
return {
locale: parsedFileContent.locale,
translations: Object.keys(parsedFileContent.translations)
.map(translationKey => {
return {
key: translationKey,
value: parsedFileContent.translations[translationKey]
};
})
};
}
function findMatchingFrenchTranslation(englishTranslation: Translation, frenchI18nFileContent: I18nTranslations): Translation | undefined {
return frenchI18nFileContent.translations.find(frenchTranslation => frenchTranslation.key === englishTranslation.key);
}
function main(): void {
const englishI18nTranslations = readAndParseFile(englishI18nFilePath);
const frenchI18nTranslations = readAndParseFile(frenchI18nFilePath);
const frenchTranslations = englishI18nTranslations.translations
.map(englishTranslation => {
let result: Translation;
const matchingFrenchTranslation = findMatchingFrenchTranslation(englishTranslation, frenchI18nTranslations);
if (matchingFrenchTranslation?.value?.length) {
result = matchingFrenchTranslation;
} else {
result = {
key: englishTranslation.key,
value: `<À TRADUIRE> - ${englishTranslation.value}`
}
}
return result;
});
const newFrenchI18nTranslations: I18nTranslations = {
locale: 'fr-FR',
translations: frenchTranslations
};
const newFrenchTranslationFileContent: I18nFileContent = {
locale: newFrenchI18nTranslations.locale,
translations: newFrenchI18nTranslations.translations.reduce(
(result, translation) => Object.assign(result, { [translation.key]: translation.value }),
{}
)
}
fs.writeFileSync(frenchI18nFilePath, JSON.stringify(newFrenchTranslationFileContent));
}
main();

540
ci/i18n-completer/package-lock.json generated Normal file
View File

@@ -0,0 +1,540 @@
{
"name": "i18n-completer",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "i18n-completer",
"version": "1.0.0",
"license": "ISC",
"devDependencies": {
"@types/node": "^22.5.5",
"tsx": "^4.19.1"
}
},
"node_modules/@esbuild/aix-ppc64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.23.1.tgz",
"integrity": "sha512-6VhYk1diRqrhBAqpJEdjASR/+WVRtfjpqKuNw11cLiaWpAT/Uu+nokB+UJnevzy/P9C/ty6AOe0dwueMrGh/iQ==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"aix"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.23.1.tgz",
"integrity": "sha512-uz6/tEy2IFm9RYOyvKl88zdzZfwEfKZmnX9Cj1BHjeSGNuGLuMD1kR8y5bteYmwqKm1tj8m4cb/aKEorr6fHWQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-arm64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.23.1.tgz",
"integrity": "sha512-xw50ipykXcLstLeWH7WRdQuysJqejuAGPd30vd1i5zSyKK3WE+ijzHmLKxdiCMtH1pHz78rOg0BKSYOSB/2Khw==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/android-x64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.23.1.tgz",
"integrity": "sha512-nlN9B69St9BwUoB+jkyU090bru8L0NA3yFvAd7k8dNsVH8bi9a8cUAUSEcEEgTp2z3dbEDGJGfP6VUnkQnlReg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"android"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-arm64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.23.1.tgz",
"integrity": "sha512-YsS2e3Wtgnw7Wq53XXBLcV6JhRsEq8hkfg91ESVadIrzr9wO6jJDMZnCQbHm1Guc5t/CdDiFSSfWP58FNuvT3Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/darwin-x64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.23.1.tgz",
"integrity": "sha512-aClqdgTDVPSEGgoCS8QDG37Gu8yc9lTHNAQlsztQ6ENetKEO//b8y31MMu2ZaPbn4kVsIABzVLXYLhCGekGDqw==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-arm64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.23.1.tgz",
"integrity": "sha512-h1k6yS8/pN/NHlMl5+v4XPfikhJulk4G+tKGFIOwURBSFzE8bixw1ebjluLOjfwtLqY0kewfjLSrO6tN2MgIhA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/freebsd-x64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.23.1.tgz",
"integrity": "sha512-lK1eJeyk1ZX8UklqFd/3A60UuZ/6UVfGT2LuGo3Wp4/z7eRTRYY+0xOu2kpClP+vMTi9wKOfXi2vjUpO1Ro76g==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"freebsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.23.1.tgz",
"integrity": "sha512-CXXkzgn+dXAPs3WBwE+Kvnrf4WECwBdfjfeYHpMeVxWE0EceB6vhWGShs6wi0IYEqMSIzdOF1XjQ/Mkm5d7ZdQ==",
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-arm64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.23.1.tgz",
"integrity": "sha512-/93bf2yxencYDnItMYV/v116zff6UyTjo4EtEQjUBeGiVpMmffDNUyD9UN2zV+V3LRV3/on4xdZ26NKzn6754g==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ia32": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.23.1.tgz",
"integrity": "sha512-VTN4EuOHwXEkXzX5nTvVY4s7E/Krz7COC8xkftbbKRYAl96vPiUssGkeMELQMOnLOJ8k3BY1+ZY52tttZnHcXQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-loong64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.23.1.tgz",
"integrity": "sha512-Vx09LzEoBa5zDnieH8LSMRToj7ir/Jeq0Gu6qJ/1GcBq9GkfoEAoXvLiW1U9J1qE/Y/Oyaq33w5p2ZWrNNHNEw==",
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-mips64el": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.23.1.tgz",
"integrity": "sha512-nrFzzMQ7W4WRLNUOU5dlWAqa6yVeI0P78WKGUo7lg2HShq/yx+UYkeNSE0SSfSure0SqgnsxPvmAUu/vu0E+3Q==",
"cpu": [
"mips64el"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-ppc64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.23.1.tgz",
"integrity": "sha512-dKN8fgVqd0vUIjxuJI6P/9SSSe/mB9rvA98CSH2sJnlZ/OCZWO1DJvxj8jvKTfYUdGfcq2dDxoKaC6bHuTlgcw==",
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-riscv64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.23.1.tgz",
"integrity": "sha512-5AV4Pzp80fhHL83JM6LoA6pTQVWgB1HovMBsLQ9OZWLDqVY8MVobBXNSmAJi//Csh6tcY7e7Lny2Hg1tElMjIA==",
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-s390x": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.23.1.tgz",
"integrity": "sha512-9ygs73tuFCe6f6m/Tb+9LtYxWR4c9yg7zjt2cYkjDbDpV/xVn+68cQxMXCjUpYwEkze2RcU/rMnfIXNRFmSoDw==",
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/linux-x64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.23.1.tgz",
"integrity": "sha512-EV6+ovTsEXCPAp58g2dD68LxoP/wK5pRvgy0J/HxPGB009omFPv3Yet0HiaqvrIrgPTBuC6wCH1LTOY91EO5hQ==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/netbsd-x64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.23.1.tgz",
"integrity": "sha512-aevEkCNu7KlPRpYLjwmdcuNz6bDFiE7Z8XC4CPqExjTvrHugh28QzUXVOZtiYghciKUacNktqxdpymplil1beA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"netbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-arm64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.23.1.tgz",
"integrity": "sha512-3x37szhLexNA4bXhLrCC/LImN/YtWis6WXr1VESlfVtVeoFJBRINPJ3f0a/6LV8zpikqoUg4hyXw0sFBt5Cr+Q==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/openbsd-x64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.23.1.tgz",
"integrity": "sha512-aY2gMmKmPhxfU+0EdnN+XNtGbjfQgwZj43k8G3fyrDM/UdZww6xrWxmDkuz2eCZchqVeABjV5BpildOrUbBTqA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"openbsd"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/sunos-x64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.23.1.tgz",
"integrity": "sha512-RBRT2gqEl0IKQABT4XTj78tpk9v7ehp+mazn2HbUeZl1YMdaGAQqhapjGTCe7uw7y0frDi4gS0uHzhvpFuI1sA==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"sunos"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-arm64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.23.1.tgz",
"integrity": "sha512-4O+gPR5rEBe2FpKOVyiJ7wNDPA8nGzDuJ6gN4okSA1gEOYZ67N8JPk58tkWtdtPeLz7lBnY6I5L3jdsr3S+A6A==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-ia32": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.23.1.tgz",
"integrity": "sha512-BcaL0Vn6QwCwre3Y717nVHZbAa4UBEigzFm6VdsVdT/MbZ38xoj1X9HPkZhbmaBGUD1W8vxAfffbDe8bA6AKnQ==",
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@esbuild/win32-x64": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.23.1.tgz",
"integrity": "sha512-BHpFFeslkWrXWyUPnbKm+xYYVYruCinGcftSBaa8zoF9hZO4BcSCFUvHVTtzpIY6YzUnYtuEhZ+C9iEXjxnasg==",
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">=18"
}
},
"node_modules/@types/node": {
"version": "22.5.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.5.5.tgz",
"integrity": "sha512-Xjs4y5UPO/CLdzpgR6GirZJx36yScjh73+2NlLlkFRSoQN8B0DpfXPdZGnvVmLRLOsqDpOfTNv7D9trgGhmOIA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.19.2"
}
},
"node_modules/esbuild": {
"version": "0.23.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.23.1.tgz",
"integrity": "sha512-VVNz/9Sa0bs5SELtn3f7qhJCDPCF5oMEl5cO9/SSinpE9hbPVvxbd572HH5AKiP7WD8INO53GgfDDhRjkylHEg==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"bin": {
"esbuild": "bin/esbuild"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"@esbuild/aix-ppc64": "0.23.1",
"@esbuild/android-arm": "0.23.1",
"@esbuild/android-arm64": "0.23.1",
"@esbuild/android-x64": "0.23.1",
"@esbuild/darwin-arm64": "0.23.1",
"@esbuild/darwin-x64": "0.23.1",
"@esbuild/freebsd-arm64": "0.23.1",
"@esbuild/freebsd-x64": "0.23.1",
"@esbuild/linux-arm": "0.23.1",
"@esbuild/linux-arm64": "0.23.1",
"@esbuild/linux-ia32": "0.23.1",
"@esbuild/linux-loong64": "0.23.1",
"@esbuild/linux-mips64el": "0.23.1",
"@esbuild/linux-ppc64": "0.23.1",
"@esbuild/linux-riscv64": "0.23.1",
"@esbuild/linux-s390x": "0.23.1",
"@esbuild/linux-x64": "0.23.1",
"@esbuild/netbsd-x64": "0.23.1",
"@esbuild/openbsd-arm64": "0.23.1",
"@esbuild/openbsd-x64": "0.23.1",
"@esbuild/sunos-x64": "0.23.1",
"@esbuild/win32-arm64": "0.23.1",
"@esbuild/win32-ia32": "0.23.1",
"@esbuild/win32-x64": "0.23.1"
}
},
"node_modules/fsevents": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/get-tsconfig": {
"version": "4.8.1",
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.8.1.tgz",
"integrity": "sha512-k9PN+cFBmaLWtVz29SkUoqU5O0slLuHJXt/2P+tMVFT+phsSGXGkp9t3rQIqdz0e+06EHNGs3oM6ZX1s2zHxRg==",
"dev": true,
"license": "MIT",
"dependencies": {
"resolve-pkg-maps": "^1.0.0"
},
"funding": {
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
"node_modules/resolve-pkg-maps": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz",
"integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1"
}
},
"node_modules/tsx": {
"version": "4.19.1",
"resolved": "https://registry.npmjs.org/tsx/-/tsx-4.19.1.tgz",
"integrity": "sha512-0flMz1lh74BR4wOvBjuh9olbnwqCPc35OOlfyzHba0Dc+QNUeWX/Gq2YTbnwcWPO3BMd8fkzRVrHcsR+a7z7rA==",
"dev": true,
"license": "MIT",
"dependencies": {
"esbuild": "~0.23.0",
"get-tsconfig": "^4.7.5"
},
"bin": {
"tsx": "dist/cli.mjs"
},
"engines": {
"node": ">=18.0.0"
},
"optionalDependencies": {
"fsevents": "~2.3.3"
}
},
"node_modules/undici-types": {
"version": "6.19.8",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz",
"integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==",
"dev": true,
"license": "MIT"
}
}
}

View File

@@ -0,0 +1,17 @@
{
"name": "i18n-completer",
"version": "1.0.0",
"main": "app.ts",
"type": "module",
"scripts": {
"start": "npx tsx app.ts",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@types/node": "^22.5.5",
"tsx": "^4.19.1"
}
}

41
docker-compose.yml Normal file
View File

@@ -0,0 +1,41 @@
services:
codiki-database:
image: "postgres:16"
container_name: "codiki-database"
ports:
- "50010:5432"
networks:
- "codiki-network"
environment:
POSTGRES_DB: codiki_db
POSTGRES_USER: codiki_admin
POSTGRES_PASSWORD: <POSTGRES_PASSWORD>
PGDATA: /var/lib/postgresql/data/pgdata
volumes:
- "./docker/postgresql/pgdata:/var/lib/postgresql/data/pgdata"
restart: always
codiki-backend:
image: codiki-backend:latest
container_name: "codiki-backend"
environment:
- "SPRING_PROFILES_ACTIVE=prod"
ports:
- "50011:8080"
volumes:
- "/opt/codiki/pictures:/opt/codiki/pictures"
networks:
- "codiki-network"
restart: always
codiki-frontend:
image: codiki-frontend:latest
container_name: "codiki-frontend"
ports:
- "50012:80"
networks:
- "codiki-network"
restart: always
networks:
codiki-network:

View File

@@ -3,7 +3,7 @@
"version": 1,
"newProjectRoot": "projects",
"projects": {
"codiki-ng": {
"codiki": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
@@ -13,11 +13,20 @@
"root": "",
"sourceRoot": "src",
"prefix": "app",
"i18n": {
"sourceLocale": "en",
"locales": {
"fr": {
"translation": "src/locale/messages-fr.json"
}
}
},
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/codiki-ng",
"outputPath": "dist/codiki",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
@@ -36,7 +45,7 @@
"scripts": []
},
"configurations": {
"production": {
"production-en": {
"budgets": [
{
"type": "initial",
@@ -49,24 +58,66 @@
"maximumError": "4kb"
}
],
"outputHashing": "all"
"outputHashing": "all",
"outputPath": "dist/codiki/en/"
},
"production-fr": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"localize": ["fr"],
"i18nMissingTranslation": "error",
"outputHashing": "all",
"outputPath": "dist/codiki/fr/"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
},
"en": {
"outputPath": "dist/codiki/en/",
"optimization": false,
"extractLicenses": false,
"sourceMap": true
},
"fr": {
"outputPath": "dist/codiki/fr/",
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"localize": ["fr"],
"i18nMissingTranslation": "warning"
}
},
"defaultConfiguration": "production"
"defaultConfiguration": ""
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "codiki-ng:build:production"
"production-en": {
"buildTarget": "codiki:build:production-en"
},
"production-fr": {
"buildTarget": "codiki:build:production-fr"
},
"development": {
"buildTarget": "codiki-ng:build:development"
"buildTarget": "codiki:build:development"
},
"en": {
"buildTarget": "codiki:build:en"
},
"fr": {
"buildTarget": "codiki:build:fr"
}
},
"defaultConfiguration": "development"
@@ -74,7 +125,7 @@
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "codiki-ng:build"
"buildTarget": "codiki:build"
}
},
"test": {

54
frontend/conf/nginx.conf Normal file
View File

@@ -0,0 +1,54 @@
events {
worker_connections 1024;
}
http {
# Browser preferred language detection (does NOT require AcceptLanguageModule)
map $http_accept_language $accept_language {
~*^fr fr;
~*^en en;
}
types {
module js;
}
include /etc/nginx/mime.types;
server {
listen 80;
server_name codiki.org;
root /usr/share/nginx/html;
# Fallback to default language if no preference defined by browser
if ($accept_language ~ "^$") {
set $accept_language "fr";
}
location ~ ^/$ {
# Redirect "/" to Angular app in browser's preferred language
rewrite ^/$ /$accept_language permanent;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# Everything under the Angular app is always redirected to Angular in the correct language
location ~ ^/(fr|en)/ {
try_files $uri /$1/index.html?$args;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ~ ^/api {
proxy_pass http://192.168.1.153:50011;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -3,31 +3,39 @@
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --port 4201 --proxy-config proxy.conf.json",
"start": "npm run start-en",
"start-en": "ng serve --port 4201 --configuration=en --proxy-config proxy.conf.json",
"start-fr": "ng serve --port 4201 --configuration=fr --proxy-config proxy.conf.json",
"build": "ng build",
"build-prod-en": "ng build --configuration=production-en --base-href /en/",
"build-prod-fr": "ng build --configuration=production-fr --base-href",
"watch": "ng build --watch --configuration development",
"test": "ng test"
"test": "ng test",
"i18n": "npm run i18n-ng-extraction && npm run i18n-fr-file-completion",
"i18n-ng-extraction": "ng extract-i18n --output-path src/locale --format=json",
"i18n-fr-file-completion": "cd ../ci/i18n-completer && npm start && cd -"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.0.0",
"@angular/cdk": "^17.3.1",
"@angular/common": "^17.0.0",
"@angular/compiler": "^17.0.0",
"@angular/core": "^17.0.0",
"@angular/forms": "^17.0.0",
"@angular/material": "^17.3.1",
"@angular/platform-browser": "^17.0.0",
"@angular/platform-browser-dynamic": "^17.0.0",
"@angular/router": "^17.0.0",
"@angular/animations": "^18.2.5",
"@angular/cdk": "^18.2.5",
"@angular/common": "^18.2.5",
"@angular/compiler": "^18.2.5",
"@angular/core": "^18.2.5",
"@angular/forms": "^18.2.5",
"@angular/material": "^18.2.5",
"@angular/platform-browser": "^18.2.5",
"@angular/platform-browser-dynamic": "^18.2.5",
"@angular/router": "^18.2.5",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.2"
"zone.js": "~0.14.10"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.0.5",
"@angular/cli": "^17.0.5",
"@angular/compiler-cli": "^17.0.0",
"@angular-devkit/build-angular": "^18.2.5",
"@angular/cli": "^18.2.5",
"@angular/compiler-cli": "^18.2.5",
"@angular/localize": "^18.2.5",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
@@ -35,6 +43,6 @@
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.2.2"
"typescript": "~5.5.4"
}
}
}

View File

@@ -2,10 +2,6 @@
"/api": {
"target": "http://localhost:8987",
"secure": false
},
"/pictures": {
"target": "http://localhost:8987/api",
"secure": false
}
}

View File

@@ -1,10 +1,11 @@
import { ApplicationConfig } from '@angular/core';
import { APP_INITIALIZER, ApplicationConfig } from '@angular/core';
import { provideRouter, withRouterConfig } from '@angular/router';
import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { routes } from './app.routes';
import { JwtInterceptor } from './core/interceptor/jwt.interceptor';
import { AuthenticationService } from './core/service/authentication.service';
export const appConfig: ApplicationConfig = {
providers: [
@@ -18,5 +19,11 @@ export const appConfig: ApplicationConfig = {
provideAnimationsAsync(),
provideHttpClient(withInterceptorsFromDi()),
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
{
provide: APP_INITIALIZER,
useFactory: (authenticationService: AuthenticationService) => () => authenticationService.startAuthenticationCheckingProcess(),
deps: [AuthenticationService],
multi: true
}
]
};

View File

@@ -1,30 +1,41 @@
import { Routes } from '@angular/router';
import { alreadyAuthenticatedGuard } from './core/guard/already-authenticated.guard';
export const routes: Routes = [
{
path: 'login',
loadComponent: () => import('./pages/login/login.component').then(module => module.LoginComponent)
loadComponent: () => import('./pages/login/login.component').then(module => module.LoginComponent),
canActivate: [alreadyAuthenticatedGuard]
},
{
path: 'signin',
loadComponent: () => import('./pages/signin/signin.component').then(module => module.SigninComponent)
loadComponent: () => import('./pages/signin/signin.component').then(module => module.SigninComponent),
canActivate: [alreadyAuthenticatedGuard]
},
{
path: 'disconnect',
loadComponent: () => import('./pages/disconnection/disconnection.component').then(module => module.DisconnectionComponent)
},
{
path: 'publications/new',
loadChildren: () => import('./pages/publication-creation/publication-creation.routes').then(module => module.ROUTES)
},
{
path: 'publications/:publicationId',
loadComponent: () => import('./pages/publication/publication.component').then(module => module.PublicationComponent)
},
{
path: 'publications/:publicationId/edit',
loadComponent: () => import('./pages/publication-edition/publication-edition.component').then(module => module.PublicationEditionComponent)
loadChildren: () => import('./pages/publication-update/publication-update.routes').then(module => module.ROUTES)
},
{
path: 'publications',
loadComponent: () => import('./pages/search-publications/search-publications.component').then(module => module.SearchPublicationsComponent)
},
{
path: 'my-publications',
loadChildren: () => import('./pages/my-publications/my-publications.routes').then(module => module.ROUTES)
},
{
path: '**',
loadComponent: () => import('./pages/home/home.component').then(module => module.HomeComponent)

View File

@@ -0,0 +1,10 @@
<h1>{{title}}</h1>
<h2>{{description}}</h2>
<footer>
<button type="button" class="cod-button secondary" (click)="closeDialog()" matRipple i18n>
No
</button>
<button type="button" class="cod-button" (click)="closeAndValidate()" matRipple i18n>
Yes
</button>
</footer>

View File

@@ -0,0 +1,12 @@
:host {
display: flex;
flex-direction: column;
text-align: center;
padding: 1em;
footer {
display: flex;
flex-direction: row;
justify-content: space-between;
}
}

View File

@@ -0,0 +1,36 @@
import { Component, inject, Input } from "@angular/core";
import { MatRippleModule } from "@angular/material/core";
import { MAT_DIALOG_DATA, MatDialogRef } from "@angular/material/dialog";
export interface ConfirmationDialogData {
title: string;
description: string;
}
@Component({
selector: 'app-confirmation-dialog',
standalone: true,
templateUrl: './confirmation-dialog.component.html',
styleUrl: './confirmation-dialog.component.scss',
imports: [MatRippleModule]
})
export class ConfirmationDialog {
private readonly dialogRef = inject(MatDialogRef<ConfirmationDialog>);
data: ConfirmationDialogData = inject(MAT_DIALOG_DATA);
get title(): string {
return this.data.title;
}
get description(): string {
return this.data.description;
}
closeAndValidate(): void {
this.dialogRef.close(true);
}
closeDialog(): void {
this.dialogRef.close(false);
}
}

View File

@@ -1,15 +1,14 @@
<div>
<span class="copy-left">
&copy;
</span>
2027 - 2024 Tous droits réservés
&lt;version&gt;
<a [routerLink]="['healthCheck']">
<div i18n>
<span class="copy-left">&copy;</span>
2016 - 2024 All rights reserved
-
2.1
<a [routerLink]="['./']" matTooltip="Health checking will be available in future..." i18n-matTooltip>
<mat-icon>favorite</mat-icon>
</a>
</div>
<div>
<mat-icon>menu_book</mat-icon>
<mat-icon matTooltip="Documentation will be available in future..." i18n-matTooltip>menu_book</mat-icon>
-
veloppements réalisés par Florian THIERRY
<span i18n>Development realised by</span> Florian THIERRY
</div>

View File

@@ -13,6 +13,9 @@
flex-direction: row;
align-items: center;
.copy-left {
transform: rotate(180deg);
}
a {
text-decoration: none;
color: rgba(255,255,255,.6);

View File

@@ -1,23 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FooterComponent } from './footer.component';
describe('FooterComponent', () => {
let component: FooterComponent;
let fixture: ComponentFixture<FooterComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [FooterComponent]
})
.compileComponents();
fixture = TestBed.createComponent(FooterComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -1,11 +1,12 @@
import { Component } from '@angular/core';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { RouterModule } from '@angular/router';
@Component({
selector: 'app-footer',
standalone: true,
imports: [MatIconModule, RouterModule],
imports: [MatIconModule, MatTooltipModule, RouterModule],
templateUrl: './footer.component.html',
styleUrl: './footer.component.scss'
})

View File

@@ -1,5 +1,10 @@
<div class="left">
<button type="button" (click)="sideMenu.open()" matTooltip="Click to show side menu">
<button type="button"
(click)="sideMenu.open()"
class="cod-button icon"
matTooltip="Click to show side menu"
matRipple
i18n-matTooltip>
<mat-icon>menu</mat-icon>
</button>
<a [routerLink]="['/home']">
@@ -13,11 +18,27 @@
</div>
<div class="right">
<ng-container *ngIf="isAuthenticated; else anonymousRightMenu">
<a [routerLink]="['/disconnect']" class="button" matRipple>Disconnect</a>
</ng-container>
<ng-template #anonymousRightMenu>
<a [routerLink]="['/login']" class="button" matRipple>Login</a>
</ng-template>
@if (isAuthenticated) {
<button type="button"
class="cod-button icon"
[matMenuTriggerFor]="authenticatedUserMenu"
matRipple>
<mat-icon>more_vert</mat-icon>
</button>
<mat-menu #authenticatedUserMenu="matMenu">
<div class="authenticated-user-menu">
<a [routerLink]="['/my-publications']" matRipple i18n>
<mat-icon>description</mat-icon>
My publications
</a>
<a [routerLink]="['/disconnect']" matRipple class="disconnection" i18n>
<mat-icon>logout</mat-icon>
Disconnect
</a>
</div>
</mat-menu>
} @else {
<a [routerLink]="['/login']" class="cod-button" matRipple i18n>Login</a>
}
</div>
<app-side-menu #sideMenu></app-side-menu>

View File

@@ -26,25 +26,6 @@ $headerHeight: 3.5em;
padding: 0 1em;
z-index: 2;
button {
background-color: #3f51b5;
color: white;
border: none;
border-radius: 10em;
transition: background-color .2s ease-in-out;
display: flex;
justify-content: center;
align-items: center;
$buttonSize: 2.5em;
width: $buttonSize;
height: $buttonSize;
&:hover {
cursor: pointer;
background-color: #5c6bc0;
}
}
a {
display: flex;
flex-direction: row;
@@ -62,11 +43,10 @@ $headerHeight: 3.5em;
.title {
font-size: 1.5em;
opacity: 0;
transition: opacity .2s ease-in-out;
display: none;
@media screen and (min-width: 600px) {
opacity: 1;
display: block;
}
}
}
@@ -121,23 +101,10 @@ $headerHeight: 3.5em;
top: 0;
right: 0;
z-index: 2;
a {
display: flex;
justify-content: center;
align-items: center;
min-width: 5em;
color: white;
margin: 0.5em 0.5em;
border-radius: 10em;
text-decoration: none;
padding: 0 .8em;
background-color: #3f51b5;
transition: background-color .2s ease-in-out;
&:hover {
background-color: #5c6bc0;
}
margin-right: .5em;
a, button {
margin: .5em;
}
}
}
@@ -145,4 +112,37 @@ $headerHeight: 3.5em;
app-side-menu {
height: 100%;
}
.authenticated-user-menu {
display: flex;
flex-direction: column;
padding: 0.2em 0;
a {
flex: 1;
display: flex;
flex-direction: row;
align-items: center;
text-decoration: none;
background-color: white;
color: black;
padding: 1em;
gap: .5em;
transition: background-color .2s ease-in-out, color .2s ease-in-out;
&:hover {
background-color: #5c6bc0;
color: white;
}
&.disconnection {
color: #D50000;
&:hover {
background-color: #E53935;
color: white;
}
}
}
}

View File

@@ -1,14 +1,15 @@
import { CommonModule } from '@angular/common';
import { Component, inject } from '@angular/core';
import { MatIconModule } from '@angular/material/icon';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatRippleModule } from '@angular/material/core';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatTooltipModule } from '@angular/material/tooltip';
import { RouterModule } from '@angular/router';
import { AuthenticationService } from '../../core/service/authentication.service';
import { CommonModule } from '@angular/common';
import { SideMenuComponent } from '../side-menu/side-menu.component';
import { MatRippleModule } from '@angular/material/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { PublicationsSearchBarComponent } from '../publications-search-bar/publications-search-bar.component';
import { MatTooltipModule } from '@angular/material/tooltip';
import { SideMenuComponent } from '../side-menu/side-menu.component';
@Component({
selector: 'app-header',
@@ -17,12 +18,13 @@ import { MatTooltipModule } from '@angular/material/tooltip';
CommonModule,
MatButtonModule,
MatIconModule,
MatMenuModule,
MatRippleModule,
MatTooltipModule,
PublicationsSearchBarComponent,
ReactiveFormsModule,
RouterModule,
SideMenuComponent,
MatRippleModule,
ReactiveFormsModule,
PublicationsSearchBarComponent,
MatTooltipModule
],
templateUrl: './header.component.html',
styleUrl: './header.component.scss',
@@ -34,8 +36,4 @@ export class HeaderComponent {
get isAuthenticated(): boolean {
return this.authenticationService.isAuthenticated();
}
searchPublications(): void {
}
}

View File

@@ -0,0 +1,37 @@
<button type="button"
(click)="closeDialog()"
class="cod-button icon secondary close"
matTooltip="Close"
matRipple
i18n-matTooltip>
<mat-icon>close</mat-icon>
</button>
<header>
<h1 i18n>Add a code block</h1>
</header>
<form [formGroup]="formGroup" (submit)="closeAndValidate()" class="cod-form" ngNativeValidate>
<div class="form-content">
<mat-form-field>
<mat-label i18n>Programming language</mat-label>
<mat-select #programmingLanguageSelect formControlName="programmingLanguage">
@for(programmingLanguage of programmingLanguages; track programmingLanguage) {
<mat-option [value]="programmingLanguage.code">
{{programmingLanguage.label}}
</mat-option>
}
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-label i18n>Code block</mat-label>
<textarea matInput formControlName="codeBlock"></textarea>
</mat-form-field>
</div>
<div class="actions reversed">
<button type="submit" class="cod-button" matRipple i18n>
Validate
</button>
<button type="button" (click)="closeDialog()" class="cod-button secondary" matRipple i18n>
Cancel
</button>
</div>
</form>

View File

@@ -0,0 +1,30 @@
:host {
display: flex;
flex-direction: column;
padding: 1em;
gap: 1em;
position: relative;
max-height: 90vh;
header {
flex: 1;
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
form {
div {
&.form-content {
mat-form-field {
width: 100%;
textarea {
height: 30vh;
}
}
}
}
}
}

View File

@@ -0,0 +1,120 @@
import { Component, inject } from "@angular/core";
import { FormBuilder, FormControl, ReactiveFormsModule, Validators } from "@angular/forms";
import { MatRippleModule } from "@angular/material/core";
import { MatDialogRef } from "@angular/material/dialog";
import { MatFormFieldModule } from "@angular/material/form-field";
import { MatIcon } from "@angular/material/icon";
import { MatInputModule } from "@angular/material/input";
import { MatSelectModule } from '@angular/material/select';
import { MatTooltip } from "@angular/material/tooltip";
export interface ProgramingLanguage {
code: string;
label: string;
}
export const PROGRAMMING_LANGUAGES: ProgramingLanguage[] = [
{
code: 'bash',
label: 'Bash'
},
{
code: 'c',
label: 'C'
},
{
code: 'cpp',
label: 'C++'
},
{
code: 'cs',
label: 'C#'
},
{
code: 'lua',
label: 'Lua'
},
{
code: 'java',
label: 'Java'
},
{
code: 'json5',
label: 'JSON'
},
{
code: 'kt',
label: 'Kotlin'
},
{
code: 'markup',
label: 'html/xml'
},
{
code: 'php',
label: 'PHP'
},
{
code: 'plsql',
label: 'PL/SQL'
},
{
code: 'python',
label: 'Python'
},
{
code: 'powershell',
label: 'PowerShell'
},
{
code: 'rust',
label: 'Rust'
},
{
code: 'sql',
label: 'SQL'
},
{
code: 'ts',
label: 'Typescript'
},
{
code: 'yml',
label: 'YAML'
},
];
@Component({
selector: 'app-code-block-dialog',
standalone: true,
templateUrl: './code-block-dialog.component.html',
styleUrl: './code-block-dialog.component.scss',
imports: [
MatFormFieldModule,
MatIcon,
MatInputModule,
MatRippleModule,
MatSelectModule,
MatTooltip,
ReactiveFormsModule,
]
})
export class CodeBlockDialog {
private readonly dialogRef = inject(MatDialogRef<CodeBlockDialog>);
private formBuilder = inject(FormBuilder);
programmingLanguages = PROGRAMMING_LANGUAGES;
formGroup = this.formBuilder.group({
programmingLanguage: new FormControl('', Validators.required),
codeBlock: new FormControl('', Validators.required)
});
closeAndValidate(): void {
if (this.formGroup.valid) {
this.dialogRef.close(this.formGroup.value);
}
}
closeDialog(): void {
this.dialogRef.close();
}
}

View File

@@ -0,0 +1,43 @@
<button type="button"
(click)="closeDialog()"
class="cod-button icon secondary close"
matTooltip="Close"
matRipple
i18n-matTooltip>
<mat-icon>close</mat-icon>
</button>
<header>
<h1 i18n>Select an illustration</h1>
</header>
<div class="picture-container">
@if (isLoading) {
<h2 i18n>Pictures loading...</h2>
<mat-spinner></mat-spinner>
} @else {
@if (pictures.length) {
@for(picture of pictures; track picture) {
<img src="/api/pictures/{{picture.id}}" (click)="selectPicture(picture)" matTooltip="Choose this illustration" i18n-matTooltip/>
}
} @else {
<h2 i18n>There is no any picture.</h2>
}
}
</div>
<footer>
<button type="button"
(click)="closeDialog()"
class="cod-button secondary"
matRipple
i18n>
Cancel
</button>
<button type="button"
(click)="fileUpload.click()"
class="cod-button"
matRipple
i18n>
<mat-icon>upload_file</mat-icon>
Add new picture
</button>
<input type="file" (change)="uploadPicture($event)" #fileUpload/>
</footer>

View File

@@ -6,20 +6,6 @@
position: relative;
max-height: 90vh;
.close {
position: absolute;
top: 1em;
right: 1em;
width: 2.5em;
height: 2.5em;
border-radius: 10em;
border: none;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
header {
flex: 1;
display: flex;

View File

@@ -11,9 +11,14 @@ import { MatTooltip } from "@angular/material/tooltip";
@Component({
selector: 'app-picture-selection',
standalone: true,
imports: [MatProgressSpinnerModule, MatIcon, MatRippleModule, MatTooltip],
templateUrl: './picture-selection-dialog.component.html',
styleUrl: './picture-selection-dialog.component.scss',
imports: [
MatIcon,
MatRippleModule,
MatProgressSpinnerModule,
MatTooltip
],
})
export class PictureSelectionDialog implements OnInit {
private readonly pictureRestService = inject(PictureRestService);
@@ -31,9 +36,13 @@ export class PictureSelectionDialog implements OnInit {
this.pictures = pictures;
})
.catch(error => {
const errorMessage = 'An error occured while loading pictures.';
console.error(errorMessage, error);
this.snackBar.open(errorMessage, 'Close', { duration: 5000 });
if (error.status === 401) {
this.dialogRef.close();
} else {
const errorMessage = $localize`An error occured while loading pictures.`;
console.error(errorMessage, error);
this.snackBar.open(errorMessage, $localize`Close`, { duration: 5000 });
}
})
.finally(() => {
this.isLoading = false;
@@ -49,7 +58,18 @@ export class PictureSelectionDialog implements OnInit {
this.dialogRef.close();
}
uploadPicture(file: any): void {
console.log("uploadFile", file);
uploadPicture(fileSelectionEvent: any): void {
const pictureFile = fileSelectionEvent.target.files[0];
if (pictureFile) {
this.pictureRestService.uploadPicture(pictureFile)
.then(pictureId => {
this.dialogRef.close(pictureId);
})
.catch(error => {
const errorMessage = $localize`A technical error occured while uploading your picture.`;
console.error(errorMessage, error);
this.snackBar.open(errorMessage, $localize`Close`, { duration: 5000 });
});
}
}
}

View File

@@ -16,9 +16,9 @@ export class PictureSelectionDialogService {
this.dialogRef.close(pictureId);
})
.catch(error => {
const errorMessage = 'An error occured while uploading a picture...';
const errorMessage = $localize`An error occured while uploading a picture...`;
console.error(errorMessage, error);
this.snackBar.open(errorMessage, 'Close', { duration: 5000 });
this.snackBar.open(errorMessage, $localize`Close`, { duration: 5000 });
});
}
}

View File

@@ -0,0 +1,132 @@
<form [formGroup]="publicationEditionForm" (submit)="save()" ngNativeValidate>
<header>
<h1>{{title}}</h1>
</header>
<mat-tab-group dynamicHeight (selectedIndexChange)="onTabChange($event)">
<mat-tab label="Edition" i18n-label>
<div class="form-content">
<div class="first-part">
<div>
<mat-form-field>
<mat-label i18n>Title</mat-label>
<input matInput type="text" formControlName="title" />
</mat-form-field>
<mat-form-field>
<mat-label i18n>Description</mat-label>
<input matInput type="text" formControlName="description" />
</mat-form-field>
<mat-form-field>
<mat-label i18n>Category</mat-label>
<mat-select formControlName="categoryId">
@for (category of categories$ | async; track category) {
<mat-option [value]="category.id">
{{ category.name }}
</mat-option>
}
</mat-select>
</mat-form-field>
</div>
<div class="picture-container">
<img [src]="publication.illustrationId.length ? '/api/pictures/' + publication.illustrationId : '/assets/images/default-picture.png'"
(click)="displayPictureSectionDialog()"
matTooltip="Click to change illustration"
i18n-matTooltip/>
</div>
</div>
<div class="actions">
<button type="button"
(click)="insertTitle(1)"
matTooltip="Click to insert a title 1 section"
matRipple
i18n-matTooltip>
H1
</button>
<button type="button"
(click)="insertTitle(2)"
matTooltip="Click to insert a title 2 section"
matRipple
i18n-matTooltip>
H2
</button>
<button type="button"
(click)="insertTitle(3)"
matTooltip="Click to insert a title 3 section"
matRipple
i18n-matTooltip>
H3
</button>
<button type="button"
(click)="insertLink()"
matTooltip="Click to insert a link"
matRipple
i18n-matTooltip>
<mat-icon>link</mat-icon>
</button>
<button type="button"
(click)="selectAPicture()"
matTooltip="Click to insert a picture"
matRipple
i18n-matTooltip>
<mat-icon>image</mat-icon>
</button>
<button type="button"
(click)="displayCodeBlockDialog()"
matTooltip="Click to insert a code block"
matRipple
i18n-matTooltip>
<mat-icon>code</mat-icon>
</button>
<button type="button"
matTooltip="Click to display editor help"
disabled
matRipple
i18n-matTooltip>
<mat-icon>help</mat-icon>
</button>
</div>
<mat-form-field>
<mat-label i18n>Content</mat-label>
<textarea
#textArea
matInput
formControlName="text"
class="text-input"
(keyup)="updateCursorPosition($event)"
(click)="updateCursorPosition($event)">
</textarea>
</mat-form-field>
</div>
</mat-tab>
<mat-tab label="Previewing" i18n-label>
<div class="preview">
@if ((isPreviewing$ | async) === true) {
<div class="preview-loading">
<h2 i18n>Preview is loading...</h2>
<mat-spinner></mat-spinner>
</div>
} @else {
<img class="illustration" src="/api/pictures/{{ publication.illustrationId }}" />
<header>
<h1>{{ publication.title }}</h1>
<h2>{{ publication.description }}</h2>
</header>
<main [innerHTML]="publicationInEdition.parsedText"></main>
}
</div>
</mat-tab>
</mat-tab-group>
<footer>
<app-submit-button [requestPending]="!!(isSaving$ | async)" i18n>Save</app-submit-button>
<button type="button"
class="cod-button secondary"
(click)="goPreviousLocation()"
matRipple
i18n>
Cancel
</button>
</footer>
</form>

View File

@@ -8,10 +8,10 @@
margin: 1em;
max-width: 80em;
width: 90%;
border-radius: .5em;
border-radius: .5em;
box-shadow: 0 2px 5px 0 rgba(0,0,0,.16),0 2px 10px 0 rgba(0,0,0,.12);
header {
& > header {
padding: 2em;
background-color: #3f51b5;
color: white;
@@ -102,6 +102,11 @@
button {
padding: 0;
border-radius: 10em;
border: none;
background-color: #3f51b5;
color: white;
transition: background-color .2s ease-in-out;
display: flex;
justify-content: center;
align-items: center;
@@ -109,39 +114,57 @@
height: 3em;
box-shadow: 0 2px 5px 0 rgba(0,0,0,.16),0 2px 10px 0 rgba(0,0,0,.12);
font-weight: bold;
&:hover {
background-color: #5b6ed8;
cursor: pointer;
}
&:disabled {
background-color: #5f6aa6;
cursor: not-allowed;
}
}
}
}
:host ::ng-deep .test circle {
stroke: white;
}
.preview {
display: flex;
flex-direction: column;
max-height: 80vh;
overflow-y: auto;
button, a.button {
padding: .8em 1.2em;
border-radius: 10em;
border: none;
background-color: #3f51b5;
color: white;
transition: background-color .2s ease-in-out;
&:hover {
background-color: #5b6ed8;
cursor: pointer;
.preview-loading {
display: flex;
flex-direction: column;
align-items: center;
}
&:disabled {
background-color: #5f6aa6;
cursor: not-allowed;
}
.illustration {
flex: 1;
height: 12em;
object-fit: cover;
transition: height .2s ease-in-out;
&.secondary {
color: #3f51b5;
background-color: white;
&:hover {
background-color: #f2f4ff;
cursor: pointer;
@media screen and (min-width: 450px) {
height: 15em;
}
@media screen and (min-width: 600px) {
height: 20em;
}
@media screen and (min-width: 750px) {
height: 25em;
}
}
header {
padding: 2em;
}
main {
padding: 2em;
text-align: justify;
}
}

View File

@@ -0,0 +1,150 @@
import { CommonModule, Location } from "@angular/common";
import { Component, EventEmitter, inject, Input, OnChanges, OnDestroy, Output } from "@angular/core";
import { FormGroup, ReactiveFormsModule } from "@angular/forms";
import { MatDialogModule } from "@angular/material/dialog";
import { MatIconModule } from "@angular/material/icon";
import { MatInputModule } from "@angular/material/input";
import { MatProgressSpinnerModule } from "@angular/material/progress-spinner";
import { MatSelectModule } from "@angular/material/select";
import { MatTabsModule } from "@angular/material/tabs";
import { MatTooltipModule } from "@angular/material/tooltip";
import { map, Observable, of, Subscription } from "rxjs";
import { Category } from "../../core/rest-services/category/model/category";
import { Publication } from "../../core/rest-services/publications/model/publication";
import { CategoryService } from "../../core/service/category.service";
import { SubmitButtonComponent } from "../submit-button/submit-button.component";
import { PictureSelectionDialog } from "./picture-selection-dialog/picture-selection-dialog.component";
import { PublicationEditionService } from "./publication-edition.service";
import { MatRippleModule } from "@angular/material/core";
@Component({
selector: 'app-publication-edition',
standalone: true,
templateUrl: './publication-edition.component.html',
styleUrl: './publication-edition.component.scss',
imports: [
CommonModule,
MatDialogModule,
MatIconModule,
MatInputModule,
MatRippleModule,
MatProgressSpinnerModule,
MatSelectModule,
MatTabsModule,
MatTooltipModule,
PictureSelectionDialog,
ReactiveFormsModule,
SubmitButtonComponent
],
providers: [PublicationEditionService]
})
export class PublicationEditionComponent implements OnChanges, OnDestroy {
@Input()
publication!: Publication;
@Input()
title!: string;
@Input()
isSaving$: Observable<boolean> = of(false);
@Output()
publicationSave = new EventEmitter<Publication>();
publicationInEdition!: Publication;
private readonly categoryService = inject(CategoryService);
private readonly location = inject(Location);
private readonly publicationEditionService = inject(PublicationEditionService);
private subscriptions: Subscription[] = [];
get publicationEditionForm(): FormGroup {
return this.publicationEditionService.publicationEditionForm;
}
get isLoading$(): Observable<boolean> {
return this.publicationEditionService.isLoading$;
}
get isPreviewing$(): Observable<boolean> {
return this.publicationEditionService.isPreviewing$;
}
get categories$(): Observable<Category[]> {
return this.categoryService.categories$
.pipe(
map(categories =>
categories.filter(category => category.subCategories.length == 0)
.sort(this.byNameAscComparator())
)
);
}
private byNameAscComparator(): (categoryA: Category, categoryB: Category) => number {
return (categoryA, categoryB) => this.compareStrings(categoryA.name, categoryB.name);
}
private compareStrings(stringA: string, stringB: string): number {
if (stringA < stringB) {
return -1;
}
if (stringA > stringB) {
return 1;
}
return 0;
}
ngOnChanges(): void {
this.ngOnDestroy();
if (!this.publicationInEdition || this.publicationInEdition !== this.publication) {
this.publicationInEdition = this.publication;
this.publicationEditionService.init(this.publicationInEdition);
}
}
ngOnDestroy(): void {
this.subscriptions.forEach(subscription => subscription?.unsubscribe());
}
goPreviousLocation(): void {
this.location.back();
}
insertTitle(titleNumber: number): void {
this.publicationEditionService.insertTitle(titleNumber);
}
selectAPicture(): void {
this.publicationEditionService.selectAPicture();
}
insertLink(): void {
this.publicationEditionService.insertLink();
}
displayCodeBlockDialog(): void {
this.publicationEditionService.displayCodeBlockDialog();
}
displayPictureSectionDialog(): void {
this.publicationEditionService.displayPictureSectionDialog();
}
updateCursorPosition(event: KeyboardEvent | MouseEvent): void {
if (event.target) {
const textarea = event.target as HTMLTextAreaElement;
const positionStart = textarea.selectionStart;
const positionEnd = textarea.selectionEnd;
this.publicationEditionService.editCursorPosition(positionStart, positionEnd);
}
}
save(): void {
this.publicationSave.emit(this.publicationEditionService.editedPublication);
}
onTabChange(tabSelectedIndex: number): void {
if (tabSelectedIndex === 1) {
this.publicationEditionService.loadPreview();
}
}
}

View File

@@ -0,0 +1,312 @@
import { Location } from "@angular/common";
import { inject, Injectable, OnDestroy } from "@angular/core";
import { MatDialog } from "@angular/material/dialog";
import { MatSnackBar } from "@angular/material/snack-bar";
import { ActivatedRoute } from "@angular/router";
import { BehaviorSubject, debounceTime, distinctUntilChanged, Observable, Subscription } from "rxjs";
import { Publication } from "../../core/rest-services/publications/model/publication";
import { PublicationRestService } from "../../core/rest-services/publications/publication.rest-service";
import { copy } from "../../core/utils/ObjectUtils";
import { CodeBlockDialog } from "./code-block-dialog/code-block-dialog.component";
import { PictureSelectionDialog } from "./picture-selection-dialog/picture-selection-dialog.component";
import { PreviewContentRequest } from "../../core/rest-services/publications/model/preview";
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
declare let Prism: any;
export class CursorPosition {
start: number;
end: number;
selectedCharacters: number;
constructor(start: number, end: number) {
this.start = start;
this.end = end;
this.selectedCharacters = end - start;
}
}
export interface PublicationEditionState {
publication: Publication;
cursorPosition: CursorPosition;
}
const DEFAULT_PUBLICATION: Publication = {
id: '',
key: '',
title: '',
text: '',
parsedText: '',
description: '',
creationDate: new Date(),
illustrationId: '',
categoryId: '',
author: {
id: '',
name: '',
image: ''
}
};
const DEFAULT_CURSOR_POSITION = new CursorPosition(0, 0);
const DEFAULT_STATE: PublicationEditionState = {
publication: DEFAULT_PUBLICATION,
cursorPosition: DEFAULT_CURSOR_POSITION
};
@Injectable()
export class PublicationEditionService implements OnDestroy {
private readonly activatedRoute = inject(ActivatedRoute);
private readonly dialog = inject(MatDialog);
private readonly formBuilder = inject(FormBuilder);
private readonly location = inject(Location);
private readonly publicationRestService = inject(PublicationRestService);
private readonly snackBar = inject(MatSnackBar);
private isLoadingSubject = new BehaviorSubject<boolean>(false);
private stateSubject = new BehaviorSubject<PublicationEditionState>(copy(DEFAULT_STATE));
private subscriptions: Subscription[] = [];
private isSavingSubject = new BehaviorSubject<boolean>(false);
private isPreviewingSubject = new BehaviorSubject<boolean>(false);
publicationEditionForm: FormGroup = this.formBuilder.group({
title: new FormControl<string | undefined>('', [Validators.required]),
description: new FormControl<string | undefined>('', [Validators.required]),
text: new FormControl<string | undefined>('', [Validators.required]),
illustrationId: new FormControl<string | undefined>('', [Validators.required]),
categoryId: new FormControl<string | undefined>('', [Validators.required])
});
ngOnDestroy(): void {
this.subscriptions.forEach(subscription => subscription.unsubscribe());
}
private get _state(): PublicationEditionState {
return this.stateSubject.value;
}
private _save(state: PublicationEditionState): void {
this.stateSubject.next(state);
}
private _updateForm(): void {
const state = this._state;
const publication = state.publication;
this.publicationEditionForm.controls['title'].setValue(publication.title);
this.publicationEditionForm.controls['description'].setValue(publication.description);
this.publicationEditionForm.controls['text'].setValue(publication.text);
this.publicationEditionForm.controls['illustrationId'].setValue(publication.illustrationId);
this.publicationEditionForm.controls['categoryId'].setValue(publication.categoryId);
}
get isLoading$(): Observable<boolean> {
return this.isLoadingSubject.asObservable();
}
get isSaving$(): Observable<boolean> {
return this.isSavingSubject.asObservable();
}
get isPreviewing$(): Observable<boolean> {
return this.isPreviewingSubject.asObservable();
}
get state$(): Observable<PublicationEditionState> {
return this.stateSubject.asObservable();
}
get editedPublication(): Publication {
return this._state.publication;
}
loadPublication(): void {
this.isLoadingSubject.next(true);
this.activatedRoute.paramMap.subscribe(params => {
const publicationId = params.get('publicationId');
if (publicationId == undefined) {
this.snackBar.open($localize`A technical error occurred while loading publication data.`, $localize`Close`, { duration: 5000 });
this.location.back();
} else {
this.publicationRestService.getById(publicationId)
.then(publication => {
const state = this._state;
state.publication = publication;
this.stateSubject.next(state);
})
.catch(error => {
const errorMessage = $localize`A technical error occurred while loading publication data.`;
this.snackBar.open(errorMessage, $localize`Close`, {duration: 5000});
console.error(errorMessage, error)
})
.finally(() => this.isLoadingSubject.next(false));
}
});
}
init(publication: Publication): void {
const state = this._state;
state.publication = publication;
this.stateSubject.next(state);
this._updateForm();
const formValueChangesSubscription = this.publicationEditionForm.valueChanges
.pipe(
debounceTime(200),
distinctUntilChanged()
)
.subscribe(formValue => {
const state = this._state;
const publication = state.publication;
publication.title = formValue.title;
publication.description = formValue.description;
publication.categoryId = formValue.categoryId;
publication.text = formValue.text;
this._save(state);
})
this.subscriptions.push(formValueChangesSubscription);
}
private editIllustrationId(pictureId: string): void {
const state = this._state;
state.publication.illustrationId = pictureId
this._save(state);
}
displayPictureSectionDialog(): void {
const dialogRef = this.dialog.open(PictureSelectionDialog);
const afterDialogCloseSubscription = dialogRef.afterClosed()
.subscribe(newPictureId => {
if (newPictureId) {
this.editIllustrationId(newPictureId);
}
});
this.subscriptions.push(afterDialogCloseSubscription);
}
displayCodeBlockDialog(): void {
const dialogRef = this.dialog.open(CodeBlockDialog, { width: '60em' });
const afterDialogCloseSubscription = dialogRef.afterClosed()
.subscribe(codeBlockWithLanguage => {
if (codeBlockWithLanguage) {
this.insertCodeBlock(codeBlockWithLanguage.programmingLanguage, codeBlockWithLanguage.codeBlock);
}
});
this.subscriptions.push(afterDialogCloseSubscription);
}
editCursorPosition(positionStart: number, positionEnd: number): void {
const state = this._state;
state.cursorPosition.start = positionStart;
state.cursorPosition.end = positionEnd;
this._save(state);
}
insertTitle(titleNumber: number): void {
if (titleNumber >= 1 && titleNumber <= 3) {
const state = this._state;
const publication = state.publication;
const publicationTextLeftPart = publication.text.substring(0, state.cursorPosition.start);
const publicationTextMiddlePart = publication.text.substring(state.cursorPosition.start, state.cursorPosition.end);
const publicationTextRightPart = publication.text.substring(state.cursorPosition.end);
const textWithTags = `${publicationTextLeftPart}[h${titleNumber}]${publicationTextMiddlePart}[/h${titleNumber}]${publicationTextRightPart}`;
publication.text = textWithTags;
this._save(state);
this._updateForm();
} else {
console.error(`Bad value for parameter of function 'insertTitle': '${titleNumber}'.`);
}
}
selectAPicture(): void {
const dialogRef = this.dialog.open(PictureSelectionDialog);
const afterDialogCloseSubscription = dialogRef.afterClosed()
.subscribe(newPictureId => {
if (newPictureId) {
this.insertPicture(newPictureId);
}
});
this.subscriptions.push(afterDialogCloseSubscription);
}
insertPicture(pictureId: string): void {
const state = this._state;
const publication = state.publication;
const publicationTextLeftPart = publication.text.substring(0, state.cursorPosition.start);
const publicationTextRightPart = publication.text.substring(state.cursorPosition.start);
const textWithTags = `${publicationTextLeftPart}[img src="/api/pictures/${pictureId}" /]${publicationTextRightPart}`;
publication.text = textWithTags;
this._save(state);
this._updateForm();
}
insertLink(): void {
const state = this._state;
const publication = state.publication;
const publicationTextLeftPart = publication.text.substring(0, state.cursorPosition.start);
const publicationTextMiddlePart = publication.text.substring(state.cursorPosition.start, state.cursorPosition.end);
const publicationTextRightPart = publication.text.substring(state.cursorPosition.end);
const textWithTags = `${publicationTextLeftPart}[link href="" txt="${publicationTextMiddlePart}" /]${publicationTextRightPart}`;
publication.text = textWithTags;
this._save(state);
this._updateForm();
}
private insertCodeBlock(programmingLanguage: string, codeBlock: string): void {
const state = this._state;
const publication = state.publication;
const publicationTextLeftPart = publication.text.substring(0, state.cursorPosition.start);
const publicationTextRightPart = publication.text.substring(state.cursorPosition.start);
const codeBlockInstruction = `\n[code lg="${programmingLanguage}"]\n${codeBlock}\n[/code]\n\n`;
const textWithTags = `${publicationTextLeftPart}${codeBlockInstruction}${publicationTextRightPart}`;
publication.text = textWithTags;
this._save(state);
this._updateForm();
}
loadPreview(): void {
const state = this._state;
this.isPreviewingSubject.next(true);
const request: PreviewContentRequest = {
text: state.publication.text
};
this.publicationRestService.preview(request)
.then(response => {
state.publication.parsedText = response.text;
this._save(state);
setTimeout(() => Prism.highlightAll(), 1000);
})
.catch(error => {
console.error(error);
})
.finally(() => {
this.isPreviewingSubject.next(false);
});
}
}

View File

@@ -1,15 +1,15 @@
@for(publication of publications$ | async; track publication) {
<a [routerLink]="['/publications/' + publication.id]" class="publication">
<img src="/pictures/{{ publication.illustrationId }}"/>
<img src="/api/pictures/{{ publication.illustrationId }}"/>
<div class="body">
<h1>{{publication.title}}</h1>
<h2>{{publication.description}}</h2>
</div>
<div class="footer">
<img src="/pictures/{{ publication.author.image }}" [matTooltip]="publication.author.name"/>
Publication posted by {{publication.author.name}}
<img src="/api/pictures/{{ publication.author.image }}" [matTooltip]="publication.author.name"/>
<span i18n>Publication posted by {{publication.author.name}}</span>
<span class="publication-date">
({{ publication.creationDate | date: 'short' : 'fr-Fr' }})
({{ publication.creationDate | date: 'short' }})
</span>
</div>
</a>

View File

@@ -1,6 +1,6 @@
<form [formGroup]="formGroup">
<input name="search-query" placeholder="Search something..." formControlName="criteria"/>
<button type="submit" (click)="searchPublications()">
<input name="search-query" placeholder="Search something..." formControlName="criteria" i18n-placeholder/>
<button type="submit" (click)="searchPublications()" matRipple>
<mat-icon>search</mat-icon>
</button>
</form>

View File

@@ -24,9 +24,10 @@
border-radius: $borderRadiusValue;
background-color: white;
border: none;
top: .4em;
top: 0;
right: 0;
color: #aaaaaa;
padding: .3em;
&:hover {
background-color: #eee;

View File

@@ -1,6 +1,6 @@
import { HttpParams } from "@angular/common/http";
import { Component, inject } from "@angular/core";
import { FormBuilder, FormControl, ReactiveFormsModule, Validators } from "@angular/forms";
import { MatRippleModule } from "@angular/material/core";
import { MatIconModule } from "@angular/material/icon";
import { Router } from "@angular/router";
@@ -11,8 +11,9 @@ import { Router } from "@angular/router";
styleUrl: './publications-search-bar.component.scss',
standalone: true,
imports: [
ReactiveFormsModule,
MatIconModule
MatIconModule,
MatRippleModule,
ReactiveFormsModule
],
providers: []
})
@@ -24,8 +25,13 @@ export class PublicationsSearchBarComponent {
});
searchPublications(): void {
let queryParams = new HttpParams();
queryParams = queryParams.set('query', this.formGroup.controls.criteria.value ?? '');
this.router.navigate(['/publications'], {queryParams});
const query = this.formGroup.controls.criteria.value
if (query?.trim()) {
const queryParams = { 'query' : this.formGroup.controls.criteria.value ?? '' }
this.router.navigate(['/publications'], { queryParams });
} else {
this.router.navigate(['/home']);
}
}
}

View File

@@ -1,18 +0,0 @@
import { HttpParams } from "@angular/common/http";
import { inject, Injectable } from "@angular/core";
import { Router } from "@angular/router";
import { BehaviorSubject } from "rxjs";
@Injectable()
export class PublicationsSearchBarService {
private router = inject(Router);
private criteriaSubject = new BehaviorSubject<string>('');
private cri
searchPublications(): void {
let queryParams = new HttpParams();
queryParams = queryParams.set('query', this.criteriaSubject.value);
this.router.navigate(['/publications'], {queryParams});
}
}

View File

@@ -6,7 +6,10 @@
</div>
<div class="sub-category-container {{category.isOpenned ? 'displayed' : ''}}">
@for(subCategory of category.subCategories; track subCategory) {
<a [routerLink]="['/publications']" [queryParams]="{'category-id': subCategory.id}" (click)="categoryClicked.emit()" class="sub-category">
<a [routerLink]="['/publications']"
[queryParams]="{'category-id': subCategory.id}"
(click)="categoryClicked.emit()"
class="sub-category">
{{subCategory.name}}
</a>
}

View File

@@ -8,8 +8,12 @@ import { RouterModule } from "@angular/router";
@Component({
selector: 'app-categories-menu',
standalone: true,
imports: [CommonModule, RouterModule, MatIconModule],
templateUrl: './categories-menu.component.html',
imports: [
CommonModule,
RouterModule,
MatIconModule
],
styleUrl: './categories-menu.component.scss'
})
export class CategoriesMenuComponent implements OnInit {

View File

@@ -4,11 +4,16 @@
<img src="assets/images/codiki.png" alt="logo"/>
Codiki
</a>
<button type="button" (click)="close()" matTooltip="Close the menu">
<button type="button"
(click)="close()"
class="cod-button icon"
matTooltip="Close the menu"
matRipple
i18n-matTooltip>
<mat-icon>close</mat-icon>
</button>
</h1>
<h2>Catégories</h2>
<h2 i18n>Categories</h2>
<app-categories-menu (categoryClicked)="close()"></app-categories-menu>
</div>
<div class="overlay {{ isOpenned ? 'displayed' : ''}}" (click)="close()"></div>

View File

@@ -12,7 +12,7 @@
bottom: 0;
transition: left .2s ease-in-out;
width: $categoriesMenuWidth;
z-index: 2;
z-index: 3;
padding: 1em 0;
&.displayed {
@@ -41,24 +41,6 @@
height: $imageSize;
}
}
button {
border-radius: 10em;
border: none;
display: flex;
justify-content: center;
align-items: center;
width: 2.5em;
height: 2.5em;
color: white;
background-color: #3f51b5;
transition: background-color .2s ease-in-out;
&:hover {
cursor: pointer;
background-color: #5c6bc0;
}
}
}
h2 {
@@ -77,6 +59,7 @@
height: 100%;
background-color: #000;
opacity: .2;
z-index: 2;
&.displayed {
display: block;

View File

@@ -3,13 +3,20 @@ import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { RouterModule } from '@angular/router';
import { CategoriesMenuComponent } from './categories-menu/categories-menu.component';
import { MatRippleModule } from '@angular/material/core';
@Component({
selector: 'app-side-menu',
standalone: true,
imports: [CategoriesMenuComponent, MatIconModule, MatTooltipModule, RouterModule],
templateUrl: './side-menu.component.html',
styleUrl: './side-menu.component.scss'
styleUrl: './side-menu.component.scss',
imports: [
CategoriesMenuComponent,
MatIconModule,
MatRippleModule,
MatTooltipModule,
RouterModule
]
})
export class SideMenuComponent {
isOpenned: boolean = false;

View File

@@ -1,9 +1,8 @@
import { Injectable, OnDestroy, inject } from '@angular/core';
import { CategoryService } from '../../core/service/category.service';
import { BehaviorSubject, Observable, Subscription, map } from 'rxjs';
import { Category } from '../../core/rest-services/category/model/category';
import { CategoryRestService } from '../../core/rest-services/category/category.rest-service';
import { Injectable, inject } from '@angular/core';
import { MatSnackBar } from '@angular/material/snack-bar';
import { BehaviorSubject, Observable } from 'rxjs';
import { CategoryRestService } from '../../core/rest-services/category/category.rest-service';
import { Category } from '../../core/rest-services/category/model/category';
export interface DisplayableCategory {
id: string;
@@ -20,31 +19,13 @@ export interface DisplayableSubCategory {
@Injectable({
providedIn: 'root'
})
export class SideMenuService implements OnDestroy {
export class SideMenuService {
private categoryRestService = inject(CategoryRestService);
private snackBar = inject(MatSnackBar);
private categoriesSubject = new BehaviorSubject<DisplayableCategory[]>([]);
private isLoadingSubject = new BehaviorSubject<boolean>(false);
private isLoadedSubject = new BehaviorSubject<boolean>(false);
constructor() {
// this.categoriesSubscription = this.categoryService.categories$
// .pipe(
// map(categories =>
// categories
// .filter(category => category.subCategories?.length)
// .map(category =>
// this.mapToDisplayableCategory(category)
// )
// )
// )
// .subscribe(categories => this.categoriesSubject.next(categories));
}
ngOnDestroy(): void {
// this.categoriesSubscription?.unsubscribe();
}
private mapToDisplayableCategory(category: Category): DisplayableCategory {
return {
id: category.id,
@@ -89,9 +70,9 @@ export class SideMenuService implements OnDestroy {
this.categoriesSubject.next(displayableCategories);
})
.catch(error => {
const errorMessage = "An error occured while loading categories.";
const errorMessage = $localize`An error occured while loading categories.`;
console.error(errorMessage, error);
this.snackBar.open(errorMessage, 'Close', { duration: 5000 });
this.snackBar.open(errorMessage, $localize`Close`, { duration: 5000 });
})
.finally(() => {
this.isLoadingSubject.next(false);

View File

@@ -1,8 +1,12 @@
<button type="submit" [class]="color" [disabled]="disabled || requestPending" (click)="click.emit()">
<button type="submit"
class="cod-button {{color}}"
[disabled]="disabled || requestPending"
(click)="click.emit()"
matRipple>
@if (requestPending) {
<mat-spinner class="spinner {{color}}" [diameter]="25"></mat-spinner>
}
<span>
{{ label }}
<ng-content/>
</span>
</button>

View File

@@ -1,14 +1,18 @@
import { CommonModule } from "@angular/common";
import { Component, EventEmitter, Input, Output } from "@angular/core";
import { MatRippleModule } from "@angular/material/core";
import { MatProgressSpinnerModule } from "@angular/material/progress-spinner";
@Component({
selector: 'app-submit-button',
standalone: true,
imports: [MatProgressSpinnerModule, CommonModule],
templateUrl: 'submit-button.component.html',
styleUrl: 'submit-button.component.scss'
styleUrl: 'submit-button.component.scss',
imports: [
CommonModule,
MatRippleModule,
MatProgressSpinnerModule
]
})
export class SubmitButtonComponent {
@Input() requestPending: boolean = false;

View File

@@ -0,0 +1,18 @@
import { inject } from "@angular/core";
import { CanActivateFn, Router } from "@angular/router";
import { AuthenticationService } from "../service/authentication.service";
import { MatSnackBar } from "@angular/material/snack-bar";
export const alreadyAuthenticatedGuard: CanActivateFn = () => {
const authenticationService = inject(AuthenticationService);
const router = inject(Router);
const snackBar = inject(MatSnackBar);
if (authenticationService.isAuthenticated()) {
router.navigate(['/home']);
snackBar.open($localize`You can't access to this page because you are already authenticated.`, $localize`Close`, { duration: 5000 });
return false;
} else {
return true;
}
}

View File

@@ -0,0 +1,20 @@
import { inject } from "@angular/core";
import { CanActivateFn, Router } from "@angular/router";
import { AuthenticationService } from "../service/authentication.service";
import { MatSnackBar } from "@angular/material/snack-bar";
export const authenticationGuard: CanActivateFn = async () => {
const authenticationService = inject(AuthenticationService);
const router = inject(Router);
const snackBar = inject(MatSnackBar);
await authenticationService.checkIsAuthenticated();
if (authenticationService.isAuthenticated()) {
return true;
} else {
router.navigate(['/login']);
snackBar.open($localize`You are unauthenticated. Please, log-in first.`, $localize`Close`, { duration: 5000 });
return false;
}
}

View File

@@ -1,23 +1,78 @@
import { Observable } from 'rxjs';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { catchError, filter, Observable, Subject, switchMap, take, throwError } from 'rxjs';
import { RefreshTokenRequest } from '../rest-services/user/model/refresh-token.model';
import { UserRestService } from '../rest-services/user/user.rest-service';
import { AuthenticationService } from '../service/authentication.service';
import { Router } from '@angular/router';
import { MatSnackBar } from '@angular/material/snack-bar';
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
private readonly authenticationService = inject(AuthenticationService);
private readonly router = inject(Router);
private readonly userRestService = inject(UserRestService);
private readonly snackBar = inject(MatSnackBar);
private isRefreshingToken = false;
private refreshTokenSubject = new Subject<string | undefined>();
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let requestWithAuthentication = request;
const jwt = this.authenticationService.getToken();
if (jwt) {
const cloned = request.clone({
headers: request.headers.set('Authorization', `Bearer ${jwt}`)
});
return next.handle(cloned);
requestWithAuthentication = this.addTokenInHeaders(request, jwt);
}
return next.handle(request);
return next.handle(requestWithAuthentication)
.pipe(
catchError(error => {
if (error instanceof HttpErrorResponse && error.status === 401) {
return this.handleAunauthorizedError(request, next, error);
}
return throwError(() => error);
})
);
}
private handleAunauthorizedError(request: HttpRequest<any>, next: HttpHandler, initialError: any): Observable<HttpEvent<any>> {
if (!this.isRefreshingToken) {
this.isRefreshingToken = true;
this.refreshTokenSubject.next(undefined);
this.authenticationService.refreshToken()
.then(refreshTokenResponse => {
this.refreshTokenSubject.next(refreshTokenResponse.accessToken);
})
.catch(() => this.handleNoRefreshToken(initialError))
.finally(() => this.isRefreshingToken = false);
}
return this.refreshTokenSubject.pipe(
filter(token => !!token),
take(1),
switchMap(token => {
let requestWithAuthentication = request;
if (token) {
requestWithAuthentication = this.addTokenInHeaders(request, token)
}
return next.handle(requestWithAuthentication);
})
);
}
private addTokenInHeaders(request: HttpRequest<any>, token: string): HttpRequest<any> {
return request.clone({
headers: request.headers.set('Authorization', `Bearer ${token}`)
});
}
private handleNoRefreshToken(initialError: any): Observable<HttpEvent<any>> {
this.router.navigate(['/login']);
this.refreshTokenSubject.next(undefined);
this.authenticationService.unauthenticate();
this.snackBar.open($localize`You are unauthenticated. Please, re-authenticate before retrying your action.`, $localize`Close`, { duration: 5000 });
return throwError(() => initialError);
}
}

View File

@@ -0,0 +1,7 @@
export interface PreviewContentRequest {
text: string;
}
export interface PreviewContentResponse {
text: string;
}

View File

@@ -1,7 +1,8 @@
import { HttpClient, HttpParams } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { lastValueFrom } from 'rxjs';
import { last, lastValueFrom } from 'rxjs';
import { Publication } from './model/publication';
import { PreviewContentRequest, PreviewContentResponse } from './model/preview';
@Injectable({
providedIn: 'root'
@@ -17,6 +18,10 @@ export class PublicationRestService {
return lastValueFrom(this.httpClient.get<Publication>(`/api/publications/${publicationId}`));
}
create(publication: Publication): Promise<void> {
return lastValueFrom(this.httpClient.post<void>('/api/publications', publication));
}
update(publication: Publication): Promise<void> {
return lastValueFrom(this.httpClient.put<void>(`/api/publications/${publication.id}`, publication));
}
@@ -26,4 +31,12 @@ export class PublicationRestService {
params = params.set('query', searchCriteria);
return lastValueFrom(this.httpClient.get<Publication[]>('/api/publications', { params }));
}
preview(request: PreviewContentRequest): Promise<PreviewContentResponse> {
return lastValueFrom(this.httpClient.post<PreviewContentResponse>('/api/publications/preview', request));
}
delete(publicationId: string): Promise<void> {
return lastValueFrom(this.httpClient.delete<void>(`/api/publications/${publicationId}`));
}
}

View File

@@ -0,0 +1,3 @@
export interface RefreshTokenRequest {
refreshTokenValue: string;
}

View File

@@ -3,6 +3,7 @@ import { Injectable, inject } from "@angular/core";
import { LoginRequest, LoginResponse } from "./model/login.model";
import { lastValueFrom } from "rxjs";
import { SigninRequest } from "./model/signin.model";
import { RefreshTokenRequest } from "./model/refresh-token.model";
@Injectable({
providedIn: 'root'
@@ -17,4 +18,8 @@ export class UserRestService {
signin(request: SigninRequest): Promise<void> {
return lastValueFrom(this.httpClient.post<void>('/api/users', request));
}
refreshToken(request: RefreshTokenRequest): Promise<LoginResponse> {
return lastValueFrom(this.httpClient.post<LoginResponse>('/api/users/refresh-token', request));
}
}

View File

@@ -1,7 +1,12 @@
import { Injectable } from "@angular/core";
import { inject, Injectable } from "@angular/core";
import { BehaviorSubject, interval } from "rxjs";
import { User } from "../model/User";
import { UserRestService } from "../rest-services/user/user.rest-service";
import { RefreshTokenRequest } from "../rest-services/user/model/refresh-token.model";
import { LoginResponse } from "../rest-services/user/model/login.model";
const JWT_PARAM = 'jwt';
const REFRESH_TOKEN_PARAM = 'refresh-token';
interface UserDetails {
sub: string;
@@ -15,25 +20,30 @@ interface UserDetails {
providedIn: 'root'
})
export class AuthenticationService {
authenticate(token: string): void {
private readonly AUTHENTICATION_CHECKING_PERIOD = 5 * 60 * 1000;
private isAuthenticatedSubject = new BehaviorSubject<boolean>(false);
private readonly userRestService = inject(UserRestService);
startAuthenticationCheckingProcess(): void {
this.checkIsAuthenticated();
interval(this.AUTHENTICATION_CHECKING_PERIOD)
.subscribe(() => this.checkIsAuthenticated());
}
authenticate(token: string, refreshToken: string): void {
localStorage.setItem(JWT_PARAM, token);
localStorage.setItem(REFRESH_TOKEN_PARAM, refreshToken);
this.isAuthenticatedSubject.next(true);
}
unauthenticate(): void {
localStorage.removeItem(JWT_PARAM);
localStorage.removeItem(REFRESH_TOKEN_PARAM);
this.isAuthenticatedSubject.next(false);
}
isAuthenticated(): boolean {
let result = false;
const userDetails = this.extractUserDetails();
if (userDetails) {
const authenticationExpiration = new Date(userDetails.exp * 1000);
result = authenticationExpiration > new Date();
}
return result;
return this.isAuthenticatedSubject.value;
}
getAuthenticatedUser(): User | undefined {
@@ -44,8 +54,62 @@ export class AuthenticationService {
return localStorage.getItem(JWT_PARAM) ?? undefined;
}
getRefreshToken(): string | undefined {
return localStorage.getItem(REFRESH_TOKEN_PARAM) ?? undefined;
}
isTokenExpired(): boolean {
let result = true;
const userDetails = this.extractUserDetails();
if (userDetails) {
const expirationDate = new Date(userDetails.exp * 1000);
const now = new Date();
result = expirationDate < now;
}
return result;
}
refreshToken(): Promise<LoginResponse> {
const refreshToken = this.getRefreshToken();
if (refreshToken) {
const refreshTokenRequest: RefreshTokenRequest = {
refreshTokenValue: refreshToken
};
return this.userRestService.refreshToken(refreshTokenRequest)
.then(refreshTokenResponse => {
this.authenticate(refreshTokenResponse.accessToken, refreshTokenResponse.refreshToken);
return refreshTokenResponse;
});
}
return Promise.reject('No any refresh token found.');
}
checkIsAuthenticated(): Promise<void> {
return new Promise((resolve, reject) => {
const isTokenExpired = this.isTokenExpired();
if (isTokenExpired) {
if (this.getRefreshToken()) {
this.refreshToken()
.then(() => resolve())
.catch(() => reject());
} else {
this.isAuthenticatedSubject.next(false);
}
} else {
this.isAuthenticatedSubject.next(true);
}
resolve();
});
}
private extractUserFromLocalStorage(): User | undefined {
let result: User | undefined = undefined;
let result: User | undefined;
const userDetails = this.extractUserDetails();
if (userDetails) {

View File

@@ -18,7 +18,7 @@ export class CategoryService {
if (!this.categories?.length) {
this.categoryRestService.getCategories()
.then(categories => this.categoriesSubject.next(categories))
.catch(error => console.error('An error occured while loading categories.', error));
.catch(error => console.error($localize`An error occured while loading categories.`, error));
}
return this.categoriesSubject.asObservable();
}

View File

@@ -1,2 +1,2 @@
<h1>Disconnection...</h1>
<h1 i18n>Disconnection...</h1>
<mat-spinner></mat-spinner>

View File

@@ -1,2 +1,11 @@
<h1>Last publications</h1>
<app-publication-list [publications$]="publications$"></app-publication-list>
<h1 i18n>Last publications</h1>
@if ((isLoading$ | async) === true) {
<h2 i18n>Publications loading...</h2>
<mat-spinner></mat-spinner>
} @else {
@if ((publications$ | async) != []) {
<app-publication-list [publications$]="publications$"></app-publication-list>
} @else {
<h2 i18n>No any publication.</h2>
}
}

View File

@@ -1,23 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HomeComponent]
})
.compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -1,16 +1,19 @@
import { Component, OnInit, inject } from '@angular/core';
import { HomeService } from './home.service';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { Observable } from 'rxjs';
import { Publication } from '../../core/rest-services/publications/model/publication';
import { RouterModule } from '@angular/router';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CommonModule } from '@angular/common';
import { PublicationListComponent } from '../../components/publication-list/publication-list.component';
import { Publication } from '../../core/rest-services/publications/model/publication';
import { HomeService } from './home.service';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-home',
standalone: true,
imports: [PublicationListComponent],
imports: [
CommonModule,
MatProgressSpinnerModule,
PublicationListComponent
],
templateUrl: './home.component.html',
styleUrl: './home.component.scss',
providers: [HomeService]

View File

@@ -26,8 +26,9 @@ export class HomeService {
this.publicationRestService.getLatest()
.then(publications => this.publicationsSubject.next(publications))
.catch(error => {
this.snackBar.open('An error occurred while retrieving latest publications...');
console.error('An error occurred while retrieving latest publications...', error);
const errorMessage = $localize`An error occurred while retrieving latest publications...`;
this.snackBar.open(errorMessage, $localize`Close`, { duration: 5000 });
console.error(errorMessage, error);
})
.finally(() => this.isLoadingSubject.next(false));
}

View File

@@ -1,23 +1,23 @@
<form [formGroup]="loginForm" (submit)="performLogin()" ngNativeValidate>
<h1>Login</h1>
<div>
<form [formGroup]="loginForm" (submit)="performLogin()" class="cod-form card" ngNativeValidate>
<h1 i18n>Login</h1>
<div class="form-field">
<mat-icon>mail</mat-icon>
<label for="email">
<label for="email" i18n>
Email address
<span class="required">*</span>
</label>
<input type="email" id="email" formControlName="email" autocomplete="email" required />
</div>
<div>
<div class="form-field">
<mat-icon>lock</mat-icon>
<label for="password">
<label for="password" i18n>
Password
<span class="required">*</span>
</label>
<input type="password" id="password" formControlName="password" required />
</div>
<div class="actions">
<button type="submit">Send</button>
<a [routerLink]="['/signin']">Create an account</a>
<div class="actions reversed">
<app-submit-button [requestPending]="false" [disabled]="false" i18n>Send</app-submit-button>
<a [routerLink]="['/signin']" class="cod-button secondary" matRipple i18n>Create an account</a>
</div>
</form>

View File

@@ -4,79 +4,4 @@
justify-content: center;
align-items: center;
padding: 1em;
form {
width: 80%;
max-width: 20em;
display: flex;
flex-direction: column;
justify-content: center;
gap: 1em;
box-shadow: 0 2px 5px 0 rgba(0,0,0,.16),0 2px 10px 0 rgba(0,0,0,.12);
border-radius: .5em;
padding: 1em 1.5em;
background-color: #ffffff;
h1 {
margin: 0;
}
div {
display: flex;
flex-direction: column;
position: relative;
gap: .1em;
mat-icon {
position: absolute;
top: 1.3em;
left: .5em;
color: #777;
}
&.actions {
flex-direction: row-reverse;
justify-content: space-between;
align-items: center;
a {
color: #3f51b5;
text-decoration: none;
}
button, a.button {
padding: .8em 1.2em;
border-radius: 10em;
border: none;
background-color: #3f51b5;
color: white;
transition: background-color .2s ease-in-out;
&:hover {
background-color: #5b6ed8;
cursor: pointer;
}
}
}
label {
flex: 1;
font-style: italic;
padding-left: 1em;
color: #777;
.required {
color: red;
}
}
input {
flex: 1;
background-color: #eeeeee;
border: none;
border-radius: 10em;
padding: 1em 1em 1em 3em;
}
}
}
}

View File

@@ -1,23 +0,0 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [LoginComponent]
})
.compileComponents();
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -5,13 +5,21 @@ import { Subscription, debounceTime, map } from 'rxjs';
import { LoginService } from './login.service';
import { MatIconModule } from '@angular/material/icon';
import { RouterModule } from '@angular/router';
import { SubmitButtonComponent } from "../../components/submit-button/submit-button.component";
import { MatRippleModule } from '@angular/material/core';
@Component({
selector: 'app-login',
standalone: true,
templateUrl: './login.component.html',
styleUrl: './login.component.scss',
imports: [ReactiveFormsModule, MatIconModule, RouterModule],
imports: [
MatIconModule,
MatRippleModule,
ReactiveFormsModule,
RouterModule,
SubmitButtonComponent
],
providers: [LoginService, MatSnackBarModule]
})
export class LoginComponent implements OnInit, OnDestroy {

View File

@@ -60,22 +60,24 @@ export class LoginService {
performLogin(): void {
const state = this.state;
// Check state is valid
if (this.isStateValid(state)) {
this.userRestService
.login(state.request)
.then((response) => {
this.authenticationService.authenticate(response.accessToken, response.refreshToken);
this.snackBar.open($localize`Authentication succeeded!`, $localize`Close`, { duration: 5000 });
this.router.navigate(['/home']);
})
.catch((error) => {
console.error(error);
this.snackBar.open($localize`Authentication failed.`, $localize`Close`, { duration: 5000 });
});
} else {
this.snackBar.open($localize`Please, fill the inputs before send.`, $localize`Close`, { duration: 5000 });
}
}
this.userRestService
.login(state.request)
.then((response) => {
this.authenticationService.authenticate(response.accessToken);
this.snackBar.open('Authentication succeeded!', 'Close', {
duration: 5000,
});
this.router.navigate(['/home']);
})
.catch((error) => {
console.error(error);
this.snackBar.open('Authentication failed.', 'Close', {
duration: 5000,
});
});
isStateValid(state: LoginState): boolean {
return !!state.request.email?.trim().length && !!state.request.password?.length;
}
}

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