Compare commits
8 Commits
8b7c2d4a9b
...
wip-debug-
Author | SHA1 | Date | |
---|---|---|---|
571da52888 | |||
c462442221
|
|||
27d63f467c | |||
078523ebad | |||
ec1e147e91
|
|||
9c1e06915e
|
|||
7a22503bac
|
|||
5645f6ab71
|
@ -1,3 +1,2 @@
|
|||||||
SESAM_FSV_VERSION=1.40.13
|
SESAM_FSV_VERSION=1.40.13
|
||||||
SESAM_INI_PATH=/etc/opt/santesocial/fsv/${SESAM_FSV_VERSION}/conf/sesam.ini
|
SESAM_INI_PATH=/etc/opt/santesocial/fsv/${SESAM_FSV_VERSION}/conf/sesam.ini
|
||||||
DATABASE_URL=sqlite://p4pillon.sqlite?mode=rwc
|
|
||||||
|
@ -1,3 +1,2 @@
|
|||||||
SESAM_FSV_VERSION=1.40.13
|
SESAM_FSV_VERSION=1.40.13
|
||||||
SESAM_INI_PATH=${ALLUSERSPROFILE}\\santesocial\\fsv\\${SESAM_FSV_VERSION}\\conf\\sesam.ini
|
SESAM_INI_PATH=${ALLUSERSPROFILE}\\santesocial\\fsv\\${SESAM_FSV_VERSION}\\conf\\sesam.ini
|
||||||
DATABASE_URL=sqlite://p4pillon.sqlite?mode=rwc
|
|
||||||
|
@ -1,28 +0,0 @@
|
|||||||
name: Demande de fusion (Pull Request)
|
|
||||||
about: Créez une demande de fusion pour partager votre travail avec le reste de l'équipe
|
|
||||||
body:
|
|
||||||
- type: markdown
|
|
||||||
attributes:
|
|
||||||
value: |
|
|
||||||
Une demande de fusion (Pull Request) a pour objectif de
|
|
||||||
partager au reste de l'équipe un développement réalisé.
|
|
||||||
Décrire les modifications apportées, leur impact et le contexte
|
|
||||||
dans lequel elles ont été réalisées permettra aux relecteurices
|
|
||||||
de plus facilement comprendre et valider votre travail.
|
|
||||||
- type: textarea
|
|
||||||
id: details
|
|
||||||
attributes:
|
|
||||||
label: Détails
|
|
||||||
description: Décrivez le contenu de la PR, son impact concret
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: why
|
|
||||||
attributes:
|
|
||||||
label: Pourquoi ?
|
|
||||||
description: Pourquoi ces modifications sont elles nécessaires ? Dans quel contexte s'inscrivent-elles ?
|
|
||||||
- type: textarea
|
|
||||||
id: documentation
|
|
||||||
attributes:
|
|
||||||
label: Documentation
|
|
||||||
description: Précisez ici des références à des ressources que vous avez utilisées pour réaliser ces modifications
|
|
@ -1,33 +0,0 @@
|
|||||||
name: Rapport de bug
|
|
||||||
about: Remplissez un rapport d'erreur
|
|
||||||
title: "[Bug]: "
|
|
||||||
blank_issues_enabled: false
|
|
||||||
labels:
|
|
||||||
- bug
|
|
||||||
- to-triage
|
|
||||||
body:
|
|
||||||
- type: textarea
|
|
||||||
id: what-happened
|
|
||||||
attributes:
|
|
||||||
label: Que se passe-t-il ?
|
|
||||||
description: Décrivez la situation que vous rencontrez
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: environment-description
|
|
||||||
attributes:
|
|
||||||
label: Si le problème semble lié à votre environement, décrivez-le ici
|
|
||||||
placeholder: Windows 10, Firefox 89.0, etc.
|
|
||||||
- type: dropdown
|
|
||||||
id: module
|
|
||||||
attributes:
|
|
||||||
label: Ce problème est il relatif à un ou des modules en particulier ?
|
|
||||||
multiple: true
|
|
||||||
options:
|
|
||||||
- Interface utilisateur⋅ice (crates/app)
|
|
||||||
- Encapsulation Tauri (crates/desktop)
|
|
||||||
- Moteur SESAM-Vitale (crates/sesam-vitale)
|
|
||||||
- Librairie utilitaire (crates/utils)
|
|
||||||
- Documentation (docs)
|
|
||||||
- Scripts (scripts)
|
|
||||||
- Autre
|
|
@ -1,13 +0,0 @@
|
|||||||
name: Proposez une fonctionnalité / amélioration
|
|
||||||
about: Proposez vos idées de fonctionnalités ou d'améliorations
|
|
||||||
blank_issues_enabled: false
|
|
||||||
labels:
|
|
||||||
- feature
|
|
||||||
- to-triage
|
|
||||||
body:
|
|
||||||
- type: textarea
|
|
||||||
id: description
|
|
||||||
attributes:
|
|
||||||
label: Décrivez votre idée
|
|
||||||
validations:
|
|
||||||
required: true
|
|
@ -1,20 +0,0 @@
|
|||||||
name: Posez une question
|
|
||||||
about: Une interrogation, une difficulté ? Posez votre question
|
|
||||||
blank_issues_enabled: false
|
|
||||||
labels:
|
|
||||||
- question
|
|
||||||
- to-triage
|
|
||||||
body:
|
|
||||||
- type: textarea
|
|
||||||
id: question
|
|
||||||
attributes:
|
|
||||||
label: Que se passe-t-il ?
|
|
||||||
description: Décrivez la situation que vous rencontrez, posez votre question
|
|
||||||
validations:
|
|
||||||
required: true
|
|
||||||
- type: textarea
|
|
||||||
id: environment-description
|
|
||||||
attributes:
|
|
||||||
label: Précisez votre environnement
|
|
||||||
description: S'il vous semble pertinent de préciser votre environement, décrivez-le ici
|
|
||||||
placeholder: Windows 10, Firefox 89.0, etc.
|
|
28
.gitignore
vendored
@ -1,28 +1,6 @@
|
|||||||
# ---> Rust
|
# Ignore Rust target directory
|
||||||
# Generated by Cargo
|
/target
|
||||||
# will have compiled files and executables
|
|
||||||
debug/
|
|
||||||
target/
|
|
||||||
|
|
||||||
# These are backup files generated by rustfmt
|
|
||||||
**/*.rs.bk
|
|
||||||
|
|
||||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
|
||||||
*.pdb
|
|
||||||
|
|
||||||
# Editor directories and files
|
|
||||||
.vscode/*
|
|
||||||
!.vscode/extensions.json
|
|
||||||
.idea
|
|
||||||
.DS_Store
|
|
||||||
*.suo
|
|
||||||
*.ntvs*
|
|
||||||
*.njsproj
|
|
||||||
*.sln
|
|
||||||
*.sw?
|
|
||||||
|
|
||||||
# Ignore .env files
|
# Ignore .env files
|
||||||
.env
|
.env
|
||||||
|
.env.build
|
||||||
# Development Database
|
|
||||||
*.sqlite
|
|
5
.ignore
@ -1,5 +0,0 @@
|
|||||||
# Ignorer les fichiers dont ne dépent pas la compilation
|
|
||||||
*.md
|
|
||||||
tailwind.config.js
|
|
||||||
*.example
|
|
||||||
scripts
|
|
7600
Cargo.lock
generated
27
Cargo.toml
@ -1,19 +1,12 @@
|
|||||||
[workspace]
|
[package]
|
||||||
resolver = "2"
|
name = "utils-debug-c-lib"
|
||||||
members = [
|
version = "0.1.0"
|
||||||
"crates/backend",
|
edition = "2021"
|
||||||
"crates/desktop",
|
build = "build.rs"
|
||||||
"crates/sesam-vitale",
|
|
||||||
"crates/utils",
|
|
||||||
"migration",
|
|
||||||
"entity",
|
|
||||||
".",
|
|
||||||
]
|
|
||||||
|
|
||||||
[workspace.dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0"
|
dotenv = "0.15"
|
||||||
|
libc = "0.2"
|
||||||
|
|
||||||
|
[build-dependencies]
|
||||||
dotenv = "0.15"
|
dotenv = "0.15"
|
||||||
sea-orm-cli = "1.0.1"
|
|
||||||
sea-orm = "1.0.1"
|
|
||||||
serde = { version = "1.0.210", features = ["derive"] }
|
|
||||||
thiserror = "1.0"
|
|
||||||
|
135
README.md
@ -1,121 +1,46 @@
|
|||||||
# Krys4lide
|
## Requirements
|
||||||
|
|
||||||
Logiciel de Pharmacie libre et open-source.
|
- Installer le [package FSV](https://industriels.sesam-vitale.fr/group/fournitures-sesam-vitale)
|
||||||
|
- Les librairies dynamiques (.lib, .dll, ...) fournies ne sont pas installés dans les emplacements standard du système, il faudra donc configurer leur chemin d'installation dans le fichier de configuration `.env.build` (voir ci-dessous)
|
||||||
|
- Le détail des chemins d'installation est donné dans la documentation du package FSV `fsv-mi-004_pack-FSV1.40.14_V2.3.pdf`
|
||||||
|
- Linux - par défaut : `/opt/santesocial/fsv/1.40.13/lib`
|
||||||
|
- Windows - par défaut : `C:\Program Files\santesocial\santesocial\fsv\1.40.14\lib` (ou dans Program Files (x86) si c'est le package 32bits qui a été installé)
|
||||||
|
|
||||||
## Modules applicatifs
|
- Installer la [CryptolibCPS](https://industriels.sesam-vitale.fr/group/galss-cryptolib-cps)
|
||||||
|
- Ce package fourni également l'utilitaire "CPS Gestion" pour obtenir des informations sur le lecteur de carte, etc.
|
||||||
|
- Linux : `cpgeslux`
|
||||||
|
- Windows : `...`
|
||||||
|
|
||||||
- `crates`: Dossier racine des modules Rust
|
## Setup
|
||||||
- `crates/backend`: Serveur backend propulsé par Axum, exposant une API REST
|
|
||||||
- `crates/desktop`: Client desktop propulsé par Tauri, exposant le `frontend`
|
|
||||||
- `crates/sesam-vitale`: Bibliothèque de gestion des services SESAM-Vitale (Lecture des cartes CPS et Vitale, téléservices ...)
|
|
||||||
- `crates/utils`: Bibliothèque de fonctions utilitaires
|
|
||||||
- `frontend`: Interface web du logiciel, propulsée par Nuxt.js
|
|
||||||
|
|
||||||
## Installation
|
- Créer et éditer le fichier de configuration de build `.env.build` en s'inspirant d'un des fichiers d'exemple (`.env.build.linux.example`, `.env.build.win.example`...)
|
||||||
|
- Ce fichier est nécessaire pour le build du package Rust
|
||||||
### Fichiers de configuration
|
- Créer et éditer le fichier de configuration de l'exécution `.env` en s'inspirant d'un des fichiers d'exemple (`.env.linux.example`, `.env.win.example`...)
|
||||||
|
- Ce fichier est nécessaire pour l'exécution du package Rust compilé, et doit donc être présent aux côtés de l'exécutable généré, le cas échéant
|
||||||
Certaines librairies nécessitent de définir certaines paramètres de configuration pour fonctionner correctement, en particulier le moteur SESAM-Vitale.
|
|
||||||
|
|
||||||
Ces paramètres sont définis dans un fichier de configuration `.env` situé dans un des dossiers suivant (par ordre de priorité) :
|
|
||||||
- dans le dossier courant (`./.env`)
|
|
||||||
- dans le dossier du manifeste (par exemple `crates/sesam-vitale/.env`)
|
|
||||||
- dans le dossier de configuration standard de l'OS (par exemple, sur linux, `~/.config/krys4lide/.env` - [plus d'info](https://github.com/dirs-dev/directories-rs?tab=readme-ov-file#projectdirs))
|
|
||||||
|
|
||||||
Des exemples de fichiers de configuration sont disponibles à la racine du projet : `.env.linux.example` et `.env.win.example`.
|
|
||||||
|
|
||||||
## Development
|
|
||||||
|
|
||||||
### Pré-requis
|
|
||||||
|
|
||||||
#### Frontend (Nuxt + Typescript)
|
|
||||||
|
|
||||||
Le frontend est propulsé par Nuxt.js, un framework TypeScript pour Vue.js. Pour le développement, il est nécessaire d'installer les dépendances suivantes :
|
|
||||||
- [Bun](https://bun.sh/docs/installation), un gestionnaire de paquets, équivalent à `npm` en plus performant
|
|
||||||
|
|
||||||
#### Tauri CLI
|
|
||||||
|
|
||||||
TODO: Tauri CLI, réellement nécessaire ?
|
|
||||||
|
|
||||||
La CLI Tauri est nécessaire au lancement du client `desktop`. Elle peut être installée via Cargo :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cargo install tauri-cli --version "^2.0.0-rc"
|
|
||||||
```
|
|
||||||
|
|
||||||
#### SeaORM CLI
|
|
||||||
|
|
||||||
SeaORM est notre ORM. Le CLI SeaORM est nécessaire pour la génération des modèles de la base de données et des migrations associées. Elle peut être installée via Cargo :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cargo install sea-orm-cli
|
|
||||||
```
|
|
||||||
|
|
||||||
L'applicatif va chercher les informations de connexion à la base de données dans la variable `DATABASE_URL` importée depuis les [fichiers de configuration](#fichiers-de-configuration).
|
|
||||||
|
|
||||||
```.env
|
|
||||||
DATABASE_URL=sqlite://p4pillon.sqlite?mode=rwc
|
|
||||||
```
|
|
||||||
|
|
||||||
Toutefois, l'usage de la CLI de SeaORM nécessite de renseigner les informations de connexion à la base de données dans un fichier `.env` situé à la racine du projet.
|
|
||||||
|
|
||||||
> Astuce : utilisé un lien symbolique pour éviter de dupliquer le fichier `.env`.
|
|
||||||
|
|
||||||
#### SESAM-Vitale
|
|
||||||
|
|
||||||
La crate `sesam-vitale` nécessite la présence des librairies dynamiques fournies par le package FSV et la CryptolibCPS. Les instructions d'installation sont disponibles dans le [README](crates/sesam-vitale/README.md) de la crate `sesam-vitale`.
|
|
||||||
|
|
||||||
#### Backend Hot-reload
|
|
||||||
|
|
||||||
Voir le [README](crates/backend/README.md) de la crate `backend` pour les prérequis de développement du serveur backend.
|
|
||||||
|
|
||||||
### Lancement
|
|
||||||
|
|
||||||
Pour lancer l'application en mode développement, il est nécessaire d'exécuter plusieurs composants simultanément :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Lancement du serveur backend
|
|
||||||
systemfd --no-pid -s http::8080 -- cargo watch -w crates/backend -x 'run --bin backend'
|
|
||||||
```
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Lancement de l'interface utilisateur (frontend ou desktop)
|
|
||||||
# - frontend (serveur web, accessible via navigateur)
|
|
||||||
bun run --cwd frontend/ dev
|
|
||||||
# - desktop (client desktop, basé sur Tauri)
|
|
||||||
cargo tauri dev --no-watch
|
|
||||||
```
|
|
||||||
|
|
||||||
> Pour circonscrire les hot-reloads intempestifs mais peu utiles :
|
|
||||||
> - le `backend` n'est rechargé que si des modifications sont détectées dans le dossier précisé par `-w crates/backend`
|
|
||||||
> - le rechargement du `desktop` est désactivé par l'option `--no-watch` ; en effet, le rechargement du `frontend` est déjà pris en charge par `bun` et ne nécessite pas de rechargement du `desktop`
|
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
|
|
||||||
Pour packager le client `desktop`, il est nécessaire de faire appel à la CLI Tauri, qui se charge de gérer le build du `frontend` et son intégration au bundle :
|
### Compilation C
|
||||||
|
|
||||||
```bash
|
Ce package s'appuie sur deux librairies :
|
||||||
cargo tauri build
|
- Une librairie statique, compilée à partir des sources (`*.c`, `*.h`) fournies dans le dossier `./src`
|
||||||
```
|
- Une librairie dynamique, fournie par le package FSV
|
||||||
|
- Windows : on fournit les headers, non présents dans la `.dll` en compilant les fichiers `src/*.def` en leur version binaire `lib/*.lib`
|
||||||
|
|
||||||
## Gestion de la base de données
|
Pour compiler les fichiers de librairie :
|
||||||
|
|
||||||
### Création d'une migration
|
- Windows : `.\make.bat`
|
||||||
|
- Linux : `make`
|
||||||
|
|
||||||
```bash
|
Pour nettoyer le dossier `./lib` :
|
||||||
sea-orm-cli migrate generate <nom_de_la_migration>
|
|
||||||
```
|
|
||||||
|
|
||||||
Cette commande génère un fichier de migration à adapter dans le dossier `migration/src`.
|
- Windows : `.\make.bat /clean`
|
||||||
|
- Linux : `make clean`
|
||||||
|
|
||||||
### Appliquer les migrations
|
### Compilation Rust
|
||||||
|
|
||||||
```bash
|
`cargo build`
|
||||||
sea-orm-cli migrate up
|
|
||||||
```
|
|
||||||
|
|
||||||
### Génération des entitées
|
## Run
|
||||||
|
|
||||||
```bash
|
`cargo run`
|
||||||
sea-orm-cli generate entity -o entity/src/entities --with-serde both
|
|
||||||
```
|
|
||||||
|
26
build.rs
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
extern crate dotenv;
|
||||||
|
|
||||||
|
use std::env;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
dotenv::from_filename(".env.build").ok();
|
||||||
|
println!("cargo::rerun-if-changed=.env.build");
|
||||||
|
|
||||||
|
let manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap();
|
||||||
|
|
||||||
|
let static_lib_path = PathBuf::from(manifest_dir).join("lib");
|
||||||
|
println!("cargo::rustc-link-search=native={}", static_lib_path.display());
|
||||||
|
println!("cargo::rustc-link-lib=static=p4pillondebuglib");
|
||||||
|
|
||||||
|
let fsv_lib_path = PathBuf::from(env::var("SESAM_FSV_LIB_PATH").unwrap());
|
||||||
|
println!("cargo::rustc-link-search=native={}", fsv_lib_path.display());
|
||||||
|
println!("cargo::rustc-link-lib=dylib={}", env::var("SESAM_FSV_SSVLIB").unwrap());
|
||||||
|
|
||||||
|
if cfg!(target_os = "windows") {
|
||||||
|
let path = env::var("PATH").unwrap_or(String::new());
|
||||||
|
println!("cargo:rustc-env=PATH={};{}", fsv_lib_path.display(), path);
|
||||||
|
} else if cfg!(target_os = "linux") {
|
||||||
|
println!("cargo:rustc-env=LD_LIBRARY_PATH={}", fsv_lib_path.display());
|
||||||
|
}
|
||||||
|
}
|
@ -1,29 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "backend"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
anyhow = "1.0.89"
|
|
||||||
axum = { version = "0.7.6", features = ["macros"] }
|
|
||||||
listenfd = "1.0.1"
|
|
||||||
tokio = { version = "1.40.0", features = ["macros", "rt-multi-thread"] }
|
|
||||||
tower-http = { version = "0.6.1", features = ["cors"] }
|
|
||||||
|
|
||||||
sea-orm = { workspace = true, features = [
|
|
||||||
# Same `ASYNC_RUNTIME` and `DATABASE_DRIVER` as in the migration crate
|
|
||||||
"sqlx-sqlite",
|
|
||||||
"runtime-tokio-rustls",
|
|
||||||
"macros",
|
|
||||||
] }
|
|
||||||
serde.workspace = true
|
|
||||||
thiserror.workspace = true
|
|
||||||
|
|
||||||
entity = { path = "../../entity" }
|
|
||||||
migration = { path = "../../migration" }
|
|
||||||
utils = { path = "../utils" }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
cargo-watch = "8.5.2"
|
|
||||||
sea-orm-cli.workspace = true
|
|
||||||
systemfd = "0.4.3"
|
|
@ -1,28 +0,0 @@
|
|||||||
# Backend
|
|
||||||
|
|
||||||
Ceci est un serveur backend, basé sur axum, et permettant d'offrir une gestion centralisée des accès aux données.
|
|
||||||
|
|
||||||
## Prérequis
|
|
||||||
|
|
||||||
En développement, le mécanisme de hot-reload nécessite de disposer de `cargo-watch` et `systemfd`. Pour les installer, exécutez la commande suivante :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cargo install cargo-watch systemfd
|
|
||||||
```
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
> Astuce : lorsqu'on exécute directement la crate `backend` à des fins de développement, le système de configuration n'utilisera pas l'éventuel fichier `.env` situé à la racine du workspace Rust. Pour éviter de dupliquer le fichier `.env`, il est possible de créer un lien symbolique vers le fichier `.env` de la crate `backend` :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd crates/backend
|
|
||||||
ln -s ../../.env .env
|
|
||||||
```
|
|
||||||
|
|
||||||
## Développement
|
|
||||||
|
|
||||||
Pour lancer le serveur en mode développement, exécutez la commande suivante :
|
|
||||||
|
|
||||||
```bash
|
|
||||||
systemfd --no-pid -s http::8080 -- cargo watch -w crates/backend -x 'run --bin backend'
|
|
||||||
```
|
|
@ -1,48 +0,0 @@
|
|||||||
use axum::{extract::State, routing, Json};
|
|
||||||
use sea_orm::*;
|
|
||||||
use serde::Serialize;
|
|
||||||
|
|
||||||
use ::entity::{debug, debug::Entity as DebugEntity};
|
|
||||||
|
|
||||||
use crate::{AppError, AppState};
|
|
||||||
|
|
||||||
// DATABASE DEBUG CONTROLLERS
|
|
||||||
|
|
||||||
async fn get_debug_entries(db: &DatabaseConnection) -> Result<Vec<debug::Model>, DbErr> {
|
|
||||||
DebugEntity::find().all(db).await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn add_random_debug_entry(State(AppState { db_connection }): State<AppState>) {
|
|
||||||
let random_entry = debug::ActiveModel {
|
|
||||||
title: Set("Random title".to_string()),
|
|
||||||
text: Set("Random text".to_string()),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
random_entry.insert(&db_connection).await.unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
// API HANDLER
|
|
||||||
|
|
||||||
#[derive(Serialize, Debug)]
|
|
||||||
struct DebugResponse {
|
|
||||||
db_ping_status: bool,
|
|
||||||
entries: Vec<debug::Model>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[axum::debug_handler]
|
|
||||||
async fn debug(
|
|
||||||
State(AppState { db_connection }): State<AppState>,
|
|
||||||
) -> Result<Json<DebugResponse>, AppError> {
|
|
||||||
let db_ping_status = db_connection.ping().await.is_ok();
|
|
||||||
let debug_entries = get_debug_entries(&db_connection).await?;
|
|
||||||
Ok(Json(DebugResponse {
|
|
||||||
db_ping_status,
|
|
||||||
entries: debug_entries,
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_routes() -> axum::Router<crate::AppState> {
|
|
||||||
axum::Router::new()
|
|
||||||
.route("/", routing::get(debug))
|
|
||||||
.route("/add_random", routing::post(add_random_debug_entry))
|
|
||||||
}
|
|
@ -1,9 +0,0 @@
|
|||||||
use axum::Router;
|
|
||||||
|
|
||||||
use crate::AppState;
|
|
||||||
|
|
||||||
mod debug;
|
|
||||||
|
|
||||||
pub fn get_routes() -> Router<AppState> {
|
|
||||||
Router::new().nest("/debug", debug::get_routes())
|
|
||||||
}
|
|
@ -1,11 +0,0 @@
|
|||||||
use migration::{Migrator, MigratorTrait};
|
|
||||||
use sea_orm::{Database, DatabaseConnection, DbErr};
|
|
||||||
use std::env;
|
|
||||||
|
|
||||||
pub async fn get_connection() -> Result<DatabaseConnection, DbErr> {
|
|
||||||
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
|
||||||
|
|
||||||
let db_connection = Database::connect(database_url).await?;
|
|
||||||
Migrator::up(&db_connection, None).await?;
|
|
||||||
Ok(db_connection)
|
|
||||||
}
|
|
@ -1,72 +0,0 @@
|
|||||||
use anyhow::Error as AnyError;
|
|
||||||
use axum::http::{header, StatusCode, Uri};
|
|
||||||
use axum::response::{IntoResponse, Response};
|
|
||||||
use axum::{routing::get, Router};
|
|
||||||
use sea_orm::{DatabaseConnection, DbErr};
|
|
||||||
use thiserror::Error;
|
|
||||||
use tower_http::cors::{Any, CorsLayer};
|
|
||||||
|
|
||||||
use ::utils::config::{load_config, ConfigError};
|
|
||||||
|
|
||||||
mod api;
|
|
||||||
mod db;
|
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
|
||||||
pub enum InitError {
|
|
||||||
#[error(transparent)]
|
|
||||||
ConfigError(#[from] ConfigError),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn init() -> Result<(), InitError> {
|
|
||||||
load_config(None)?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct AppState {
|
|
||||||
db_connection: DatabaseConnection,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_router() -> Result<Router, DbErr> {
|
|
||||||
let db_connection = db::get_connection().await?;
|
|
||||||
let state: AppState = AppState { db_connection };
|
|
||||||
|
|
||||||
let cors = CorsLayer::new()
|
|
||||||
.allow_methods(Any)
|
|
||||||
.allow_origin(Any)
|
|
||||||
.allow_headers([header::CONTENT_TYPE]);
|
|
||||||
|
|
||||||
Ok(Router::new()
|
|
||||||
.route("/", get(|| async { "Hello, world!" }))
|
|
||||||
.merge(api::get_routes())
|
|
||||||
.fallback(fallback)
|
|
||||||
.with_state(state)
|
|
||||||
.layer(cors))
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn fallback(uri: Uri) -> (StatusCode, String) {
|
|
||||||
(StatusCode::NOT_FOUND, format!("No route for {uri}"))
|
|
||||||
}
|
|
||||||
|
|
||||||
struct AppError(AnyError);
|
|
||||||
|
|
||||||
// To automatically convert `AppError` into a response
|
|
||||||
impl IntoResponse for AppError {
|
|
||||||
fn into_response(self) -> Response {
|
|
||||||
(
|
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
|
||||||
format!("Internal Server Error: {}", self.0),
|
|
||||||
)
|
|
||||||
.into_response()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// To automatically convert `AnyError` into `AppError`
|
|
||||||
impl<E> From<E> for AppError
|
|
||||||
where
|
|
||||||
E: Into<AnyError>,
|
|
||||||
{
|
|
||||||
fn from(err: E) -> Self {
|
|
||||||
Self(err.into())
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,39 +0,0 @@
|
|||||||
use listenfd::ListenFd;
|
|
||||||
use thiserror::Error;
|
|
||||||
use tokio::net::TcpListener;
|
|
||||||
|
|
||||||
use backend::{get_router, init, InitError};
|
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
|
||||||
pub enum BackendError {
|
|
||||||
#[error("Error while setting up or serving the TCP listener")]
|
|
||||||
ServeTCPListener(#[from] std::io::Error),
|
|
||||||
#[error("Error while initialising the backend")]
|
|
||||||
InitError(#[from] InitError),
|
|
||||||
#[error("Error with the database connection")]
|
|
||||||
DatabaseConnection(#[from] sea_orm::DbErr),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::main]
|
|
||||||
async fn main() -> Result<(), BackendError> {
|
|
||||||
init()?;
|
|
||||||
|
|
||||||
let app = get_router().await?;
|
|
||||||
|
|
||||||
let mut listenfd = ListenFd::from_env();
|
|
||||||
let listener = match listenfd.take_tcp_listener(0)? {
|
|
||||||
// if we are given a tcp listener on listen fd 0, we use that one
|
|
||||||
Some(listener) => {
|
|
||||||
listener.set_nonblocking(true)?;
|
|
||||||
TcpListener::from_std(listener)?
|
|
||||||
}
|
|
||||||
// otherwise fall back to local listening
|
|
||||||
None => TcpListener::bind("0.0.0.0:8080").await?,
|
|
||||||
};
|
|
||||||
|
|
||||||
let local_addr = listener.local_addr()?;
|
|
||||||
println!("Listening on http://{}", local_addr);
|
|
||||||
axum::serve(listener, app).await?;
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
7
crates/desktop/.gitignore
vendored
@ -1,7 +0,0 @@
|
|||||||
# Generated by Cargo
|
|
||||||
# will have compiled files and executables
|
|
||||||
/target/
|
|
||||||
|
|
||||||
# Generated by Tauri
|
|
||||||
# will have schema files for capabilities auto-completion
|
|
||||||
/gen/schemas
|
|
@ -1,24 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "desktop"
|
|
||||||
version = "0.1.0"
|
|
||||||
description = "Un logiciel de pharmacie libre et open-source."
|
|
||||||
authors = ["p4pillon"]
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "desktop_lib"
|
|
||||||
crate-type = ["lib", "cdylib", "staticlib"]
|
|
||||||
|
|
||||||
[build-dependencies]
|
|
||||||
tauri-build = { version = "2.0.0-rc", features = [] }
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
bytes = "1.6.1"
|
|
||||||
http = "1.1.0"
|
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
serde_json = "1"
|
|
||||||
tauri = { version = "2.0.0-rc", features = [] }
|
|
||||||
tauri-plugin-shell = "2.0.0-rc"
|
|
||||||
tower = "0.4.13"
|
|
||||||
|
|
||||||
thiserror.workspace = true
|
|
@ -1,3 +0,0 @@
|
|||||||
fn main() {
|
|
||||||
tauri_build::build()
|
|
||||||
}
|
|
@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "../gen/schemas/desktop-schema.json",
|
|
||||||
"identifier": "default",
|
|
||||||
"description": "Capability for the main window",
|
|
||||||
"windows": ["main"],
|
|
||||||
"permissions": [
|
|
||||||
"core:default",
|
|
||||||
"shell:allow-open"
|
|
||||||
]
|
|
||||||
}
|
|
Before Width: | Height: | Size: 3.4 KiB |
Before Width: | Height: | Size: 6.8 KiB |
Before Width: | Height: | Size: 974 B |
Before Width: | Height: | Size: 2.8 KiB |
Before Width: | Height: | Size: 3.8 KiB |
Before Width: | Height: | Size: 3.9 KiB |
Before Width: | Height: | Size: 7.6 KiB |
Before Width: | Height: | Size: 903 B |
Before Width: | Height: | Size: 8.4 KiB |
Before Width: | Height: | Size: 1.3 KiB |
Before Width: | Height: | Size: 2.0 KiB |
Before Width: | Height: | Size: 2.4 KiB |
Before Width: | Height: | Size: 1.5 KiB |
Before Width: | Height: | Size: 85 KiB |
Before Width: | Height: | Size: 14 KiB |
@ -1,14 +0,0 @@
|
|||||||
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
|
|
||||||
#[tauri::command]
|
|
||||||
fn greet(name: &str) -> String {
|
|
||||||
format!("Hello, {}! You've been greeted from Rust!", name)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
|
||||||
pub fn run() {
|
|
||||||
tauri::Builder::default()
|
|
||||||
.plugin(tauri_plugin_shell::init())
|
|
||||||
.invoke_handler(tauri::generate_handler![greet])
|
|
||||||
.run(tauri::generate_context!())
|
|
||||||
.expect("error while running tauri application");
|
|
||||||
}
|
|
@ -1,6 +0,0 @@
|
|||||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
|
||||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
desktop_lib::run()
|
|
||||||
}
|
|
@ -1,41 +0,0 @@
|
|||||||
{
|
|
||||||
"$schema": "https://schema.tauri.app/config/2.0.0-rc",
|
|
||||||
"productName": "Chrys4lide LGO",
|
|
||||||
"version": "0.0.1",
|
|
||||||
"identifier": "org.p4pillon.chrys4lide.lgo",
|
|
||||||
"build": {
|
|
||||||
"beforeDevCommand": {
|
|
||||||
"cwd": "../../frontend",
|
|
||||||
"script": "bun run dev"
|
|
||||||
},
|
|
||||||
"devUrl": "http://localhost:1420",
|
|
||||||
"beforeBuildCommand": {
|
|
||||||
"cwd": "../../frontend",
|
|
||||||
"script": "bun run generate"
|
|
||||||
},
|
|
||||||
"frontendDist": "../../frontend/dist"
|
|
||||||
},
|
|
||||||
"app": {
|
|
||||||
"windows": [
|
|
||||||
{
|
|
||||||
"title": "Chrys4lide | LG0",
|
|
||||||
"width": 800,
|
|
||||||
"height": 600
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"security": {
|
|
||||||
"csp": null
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"bundle": {
|
|
||||||
"active": true,
|
|
||||||
"targets": "all",
|
|
||||||
"icon": [
|
|
||||||
"icons/32x32.png",
|
|
||||||
"icons/128x128.png",
|
|
||||||
"icons/128x128@2x.png",
|
|
||||||
"icons/icon.icns",
|
|
||||||
"icons/icon.ico"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
}
|
|
9
crates/sesam-vitale/.gitignore
vendored
@ -1,9 +0,0 @@
|
|||||||
# Ignore Rust target directory
|
|
||||||
/target
|
|
||||||
|
|
||||||
# Ignore .env files
|
|
||||||
.env
|
|
||||||
.env.build
|
|
||||||
|
|
||||||
# Ignore exploitation files - only usefull for local debugging on windows
|
|
||||||
lib/*.exp
|
|
@ -1,14 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "sesam-vitale"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
anyhow.workspace = true
|
|
||||||
libc = "0.2"
|
|
||||||
thiserror.workspace = true
|
|
||||||
|
|
||||||
utils = { path = "../utils" }
|
|
||||||
|
|
||||||
[build-dependencies]
|
|
||||||
dotenv.workspace = true
|
|
@ -1,34 +0,0 @@
|
|||||||
## Requirements
|
|
||||||
|
|
||||||
- Installer le [package FSV](https://industriels.sesam-vitale.fr/group/fournitures-sesam-vitale)
|
|
||||||
- Les librairies dynamiques (.lib, .dll, ...) fournies ne sont pas installés dans les emplacements standard du système, il faudra donc configurer leur chemin d'installation dans le fichier de configuration `.env.build` (voir ci-dessous)
|
|
||||||
- Le détail des chemins d'installation est donné dans la documentation du package FSV `fsv-mi-004_pack-FSV1.40.14_V2.3.pdf`
|
|
||||||
- Linux - par défaut : `/opt/santesocial/fsv/1.40.13/lib`
|
|
||||||
- Windows - par défaut : `C:\Program Files\santesocial\santesocial\fsv\1.40.14\lib` (ou dans Program Files (x86) si c'est le package 32bits qui a été installé)
|
|
||||||
|
|
||||||
- Installer la [CryptolibCPS](https://industriels.sesam-vitale.fr/group/galss-cryptolib-cps)
|
|
||||||
- Ce package fourni également l'utilitaire "CPS Gestion" pour obtenir des informations sur le lecteur de carte, etc.
|
|
||||||
- Linux : `cpgeslux`
|
|
||||||
- Windows : `...`
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
- Créer et éditer le fichier de configuration de build `.env.build` en s'inspirant d'un des fichiers d'exemple (`.env.build.linux.example`, `.env.build.win.example`...)
|
|
||||||
- Ce fichier est nécessaire pour le build du package Rust
|
|
||||||
- Créer et éditer le fichier de configuration de l'exécution `.env` en s'inspirant d'un des fichiers d'exemple (`.env.linux.example`, `.env.win.example`...)
|
|
||||||
- Ce fichier est nécessaire pour l'exécution du package Rust compilé, et doit donc être présent aux côtés de l'exécutable généré, le cas échéant
|
|
||||||
|
|
||||||
## Build
|
|
||||||
|
|
||||||
### Windows - Compilation des headers FSV
|
|
||||||
|
|
||||||
Sous windows, la librairie dynamique fournie par le package FSV nécessite des headers qui ne sont pas présents dans la `.dll`. Il est donc nécessaire de fournir ces headers, en les renseignant dans des fichiers `crates/sesam-vitale/src/win/fsv/*.def` qui seront compilés en leur version binaire `crates/sesam-vitale/lib/*.lib`.
|
|
||||||
|
|
||||||
En cas de modification des fichiers `.def`, pour re-compiler ces headers, faire appel au script `scripts/compile_win_headers.bat`.
|
|
||||||
|
|
||||||
| /!\ Attention, le script `compile_win_headers.bat` exécute, en interne, l'utilitaire `vcvarsall.bat` et le linker `lib.exe` de Visual Studio. Visual Studio doit donc être installé et le chemin vers l'intallation le script `vcvarsall.bat`, écrit en dur dans le script `compile_win_headers.bat` doit être adapté à votre installation.
|
|
||||||
|
|
||||||
## À creuser
|
|
||||||
|
|
||||||
- Compilation cross platform facilitée par du Docker : https://github.com/cross-rs/cross
|
|
||||||
- Pour éviter l'usage de dotenv pour la configuration, on peut utiliser https://direnv.net/
|
|
@ -1,43 +0,0 @@
|
|||||||
use std::env;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use dotenv::from_path;
|
|
||||||
|
|
||||||
fn main() {
|
|
||||||
// Load the .env.build file for build-time environment variables
|
|
||||||
let manifest_dir = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR must be set");
|
|
||||||
let manifest_path = PathBuf::from(manifest_dir);
|
|
||||||
from_path(manifest_path.join(".env.build")).ok();
|
|
||||||
|
|
||||||
println!("cargo::rerun-if-env-changed=SESAM_FSV_LIB_PATH");
|
|
||||||
println!("cargo::rerun-if-env-changed=SESAM_FSV_SSVLIB");
|
|
||||||
println!("cargo::rerun-if-changed=.env.build");
|
|
||||||
println!("cargo::rerun-if-changed=build.rs");
|
|
||||||
|
|
||||||
// Add local lib directory to the linker search path (for def files and static libs)
|
|
||||||
let static_lib_path = manifest_path.join("lib");
|
|
||||||
println!(
|
|
||||||
"cargo::rustc-link-search=native={}",
|
|
||||||
static_lib_path.display()
|
|
||||||
);
|
|
||||||
|
|
||||||
// Add the SESAM_FSV_LIB_PATH to the linker search path
|
|
||||||
let fsv_lib_path =
|
|
||||||
PathBuf::from(env::var("SESAM_FSV_LIB_PATH").expect("SESAM_FSV_LIB_PATH must be set"));
|
|
||||||
println!("cargo::rustc-link-search=native={}", fsv_lib_path.display());
|
|
||||||
|
|
||||||
// Add the SESAM_FSV_LIB_PATH to the PATH environment variable
|
|
||||||
if cfg!(target_os = "windows") {
|
|
||||||
let path = env::var("PATH").unwrap_or_default();
|
|
||||||
println!("cargo:rustc-env=PATH={};{}", fsv_lib_path.display(), path);
|
|
||||||
} else if cfg!(target_os = "linux") {
|
|
||||||
println!("cargo:rustc-env=LD_LIBRARY_PATH={}", fsv_lib_path.display());
|
|
||||||
}
|
|
||||||
|
|
||||||
// Link the SESAM_FSV_SSVLIB dynamic library
|
|
||||||
println!(
|
|
||||||
"cargo::rustc-link-lib=dylib={}",
|
|
||||||
env::var("SESAM_FSV_SSVLIB").expect("SESAM_FSV_SSVLIB must be set")
|
|
||||||
);
|
|
||||||
// TODO : try `raw-dylib` instead of `dylib` on Windows to avoid the need of the `lib` headers compiled from the `def`
|
|
||||||
}
|
|
@ -1,400 +0,0 @@
|
|||||||
use libc::{c_void, size_t};
|
|
||||||
use std::ffi::CString;
|
|
||||||
use std::ptr;
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
use crate::libssv::{self, SSV_LireCartePS};
|
|
||||||
use crate::ssv_memory::{decode_ssv_memory, Block, SSVMemoryError};
|
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
|
||||||
pub enum CartePSError {
|
|
||||||
#[error("Unknown (group, field) pair: ({group}, {field})")]
|
|
||||||
UnknownGroupFieldPair { group: u16, field: u16 },
|
|
||||||
#[error("CString creation error: {0}")]
|
|
||||||
CString(#[from] std::ffi::NulError),
|
|
||||||
#[error("Unable to get the last situation while parsing a CartePS")]
|
|
||||||
InvalidLastSituation,
|
|
||||||
#[error(transparent)]
|
|
||||||
SSVMemory(#[from] SSVMemoryError),
|
|
||||||
#[error(transparent)]
|
|
||||||
SSVLibErrorCode(#[from] libssv::LibSSVError),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
pub struct CartePS {
|
|
||||||
titulaire: TitulairePS,
|
|
||||||
situations: Vec<SituationPS>,
|
|
||||||
}
|
|
||||||
|
|
||||||
// 1. CB = Caractères Binaires »
|
|
||||||
// 2. CE = Caractères « Etendus » (ISO 8859-1)
|
|
||||||
// 3. CA = Caractères Alphanumériques (ASCII?)
|
|
||||||
// 4. CN = Caractères Numériques
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
struct TitulairePS {
|
|
||||||
type_de_carte_ps: String, // CN
|
|
||||||
type_d_identification_nationale: String, // CN
|
|
||||||
numero_d_identification_nationale: String, // CE - 8 -> 30
|
|
||||||
cle_du_numero_d_identification_nationale: String, // CN
|
|
||||||
code_civilite: String, // CN
|
|
||||||
nom_du_ps: String, // CE - 27
|
|
||||||
prenom_du_ps: String, // CE - 27
|
|
||||||
categorie_carte: char, // CA
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
struct SituationPS {
|
|
||||||
numero_logique_de_la_situation_de_facturation_du_ps: u8,
|
|
||||||
mode_d_exercice: String,
|
|
||||||
statut_d_exercice: String,
|
|
||||||
secteur_d_activite: String,
|
|
||||||
type_d_identification_structure: String,
|
|
||||||
numero_d_identification_structure: String,
|
|
||||||
cle_du_numero_d_identification_structure: String,
|
|
||||||
raison_sociale_structure: String,
|
|
||||||
numero_d_identification_de_facturation_du_ps: String,
|
|
||||||
cle_du_numero_d_identification_de_facturation_du_ps: String,
|
|
||||||
numero_d_identification_du_ps_remplaçant: String,
|
|
||||||
cle_du_numero_d_identification_du_ps_remplaçant: String,
|
|
||||||
code_conventionnel: String,
|
|
||||||
code_specialite: String,
|
|
||||||
code_zone_tarifaire: String,
|
|
||||||
code_zone_ik: String,
|
|
||||||
code_agrement_1: String,
|
|
||||||
code_agrement_2: String,
|
|
||||||
code_agrement_3: String,
|
|
||||||
habilitation_à_signer_une_facture: String,
|
|
||||||
habilitation_à_signer_un_lot: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn lire_carte(code_pin: &str, lecteur: &str) -> Result<CartePS, CartePSError> {
|
|
||||||
let resource_ps = CString::new(lecteur)?;
|
|
||||||
let resource_reader = CString::new("")?;
|
|
||||||
let card_number = CString::new(code_pin)?;
|
|
||||||
|
|
||||||
let mut buffer: *mut c_void = ptr::null_mut();
|
|
||||||
let mut size: size_t = 0;
|
|
||||||
let mut hex_values: &[u8] = &[];
|
|
||||||
unsafe {
|
|
||||||
let result = SSV_LireCartePS(
|
|
||||||
resource_ps.as_ptr(),
|
|
||||||
resource_reader.as_ptr(),
|
|
||||||
card_number.as_ptr(),
|
|
||||||
&mut buffer,
|
|
||||||
&mut size,
|
|
||||||
);
|
|
||||||
println!("SSV_LireCartePS result: {}", result);
|
|
||||||
if result != 0 {
|
|
||||||
return Err(libssv::LibSSVError::StandardErrorCode {
|
|
||||||
code: result,
|
|
||||||
function: "SSV_LireCartePS",
|
|
||||||
}
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if !buffer.is_null() {
|
|
||||||
hex_values = std::slice::from_raw_parts(buffer as *const u8, size);
|
|
||||||
libc::free(buffer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let groups =
|
|
||||||
decode_ssv_memory(hex_values, hex_values.len()).map_err(CartePSError::SSVMemory)?;
|
|
||||||
decode_carte_ps(groups)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_last_mut_situation(carte_ps: &mut CartePS) -> Result<&mut SituationPS, CartePSError> {
|
|
||||||
carte_ps
|
|
||||||
.situations
|
|
||||||
.last_mut()
|
|
||||||
.ok_or(CartePSError::InvalidLastSituation)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn decode_carte_ps(groups: Vec<Block>) -> Result<CartePS, CartePSError> {
|
|
||||||
let mut carte_ps = CartePS::default();
|
|
||||||
for group in groups {
|
|
||||||
for field in group.content {
|
|
||||||
match (group.id, field.id) {
|
|
||||||
(1, 1) => {
|
|
||||||
carte_ps.titulaire.type_de_carte_ps =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(1, 2) => {
|
|
||||||
carte_ps.titulaire.type_d_identification_nationale =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(1, 3) => {
|
|
||||||
carte_ps.titulaire.numero_d_identification_nationale =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(1, 4) => {
|
|
||||||
carte_ps.titulaire.cle_du_numero_d_identification_nationale =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(1, 5) => {
|
|
||||||
carte_ps.titulaire.code_civilite =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(1, 6) => {
|
|
||||||
carte_ps.titulaire.nom_du_ps =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(1, 7) => {
|
|
||||||
carte_ps.titulaire.prenom_du_ps =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(1, 8) => {
|
|
||||||
let byte = field.content[0];
|
|
||||||
carte_ps.titulaire.categorie_carte = byte as char;
|
|
||||||
}
|
|
||||||
(2..=16, 1) => {
|
|
||||||
carte_ps.situations.push(SituationPS::default());
|
|
||||||
get_last_mut_situation(&mut carte_ps)?
|
|
||||||
.numero_logique_de_la_situation_de_facturation_du_ps = field.content[0];
|
|
||||||
}
|
|
||||||
(2..=16, 2) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.mode_d_exercice =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 3) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.statut_d_exercice =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 4) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.secteur_d_activite =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 5) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.type_d_identification_structure =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 6) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.numero_d_identification_structure =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 7) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?
|
|
||||||
.cle_du_numero_d_identification_structure =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 8) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.raison_sociale_structure =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 9) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?
|
|
||||||
.numero_d_identification_de_facturation_du_ps =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 10) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?
|
|
||||||
.cle_du_numero_d_identification_de_facturation_du_ps =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 11) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?
|
|
||||||
.numero_d_identification_du_ps_remplaçant =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 12) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?
|
|
||||||
.cle_du_numero_d_identification_du_ps_remplaçant =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 13) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.code_conventionnel =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 14) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.code_specialite =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 15) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.code_zone_tarifaire =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 16) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.code_zone_ik =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 17) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.code_agrement_1 =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 18) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.code_agrement_2 =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 19) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.code_agrement_3 =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 20) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.habilitation_à_signer_une_facture =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
(2..=16, 21) => {
|
|
||||||
get_last_mut_situation(&mut carte_ps)?.habilitation_à_signer_un_lot =
|
|
||||||
String::from_utf8_lossy(field.content).to_string();
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
return Err(CartePSError::UnknownGroupFieldPair {
|
|
||||||
group: group.id,
|
|
||||||
field: field.id,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(carte_ps)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test_decode_carte_ps {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_francoise_pharmacien0052419() {
|
|
||||||
let bytes: &[u8] = &[
|
|
||||||
0, 1, 51, // Block 01, Content size 51
|
|
||||||
1, 48, // Field 01, Content size 1
|
|
||||||
1, 56, // Field 02, Content size 1
|
|
||||||
11, 57, 57, 55, 48, 48, 53, 50, 52, 49, 57, 52, // Field 03, Content size 11
|
|
||||||
1, 52, // Field 04, Content size 1
|
|
||||||
2, 50, 50, // Field 05, Content size 2
|
|
||||||
17, 80, 72, 65, 82, 77, 65, 67, 73, 69, 78, 48, 48, 53, 50, 52, 49,
|
|
||||||
57, // Field 06, Content size 17
|
|
||||||
9, 70, 82, 65, 78, 67, 79, 73, 83, 69, // Field 07, Content size 9
|
|
||||||
1, 84, // Field 08, Content size 1
|
|
||||||
0, 2, 83, // Block 02, Content size 83
|
|
||||||
1, 1, 1, 48, 1, 49, 2, 56, 54, 1, 49, 9, 48, 66, 48, 50, 50, 49, 57, 53, 56, 1, 56, 24,
|
|
||||||
80, 72, 65, 82, 77, 65, 67, 73, 69, 32, 68, 85, 32, 67, 69, 78, 84, 82, 69, 50, 50, 49,
|
|
||||||
57, 53, 8, 48, 48, 50, 48, 50, 52, 49, 57, 1, 56, 0, 1, 48, 1, 49, 2, 53, 48, 2, 49,
|
|
||||||
48, 2, 48, 48, 1, 48, 1, 48, 1, 48, 1, 49, 1, 49,
|
|
||||||
];
|
|
||||||
let blocks = decode_ssv_memory(bytes, bytes.len()).unwrap();
|
|
||||||
let carte_ps = decode_carte_ps(blocks).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(carte_ps.titulaire.type_de_carte_ps, "0");
|
|
||||||
assert_eq!(carte_ps.titulaire.type_d_identification_nationale, "8");
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.titulaire.numero_d_identification_nationale,
|
|
||||||
"99700524194"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.titulaire.cle_du_numero_d_identification_nationale,
|
|
||||||
"4"
|
|
||||||
);
|
|
||||||
assert_eq!(carte_ps.titulaire.code_civilite, "22");
|
|
||||||
assert_eq!(carte_ps.titulaire.nom_du_ps, "PHARMACIEN0052419");
|
|
||||||
assert_eq!(carte_ps.titulaire.prenom_du_ps, "FRANCOISE");
|
|
||||||
assert_eq!(carte_ps.titulaire.categorie_carte, 'T');
|
|
||||||
|
|
||||||
assert_eq!(carte_ps.situations.len(), 1);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].numero_logique_de_la_situation_de_facturation_du_ps,
|
|
||||||
1
|
|
||||||
);
|
|
||||||
assert_eq!(carte_ps.situations[0].mode_d_exercice, "0");
|
|
||||||
assert_eq!(carte_ps.situations[0].statut_d_exercice, "1");
|
|
||||||
assert_eq!(carte_ps.situations[0].secteur_d_activite, "86");
|
|
||||||
assert_eq!(carte_ps.situations[0].type_d_identification_structure, "1");
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].numero_d_identification_structure,
|
|
||||||
"0B0221958"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].cle_du_numero_d_identification_structure,
|
|
||||||
"8"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].raison_sociale_structure,
|
|
||||||
"PHARMACIE DU CENTRE22195"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].numero_d_identification_de_facturation_du_ps,
|
|
||||||
"00202419"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].cle_du_numero_d_identification_de_facturation_du_ps,
|
|
||||||
"8"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].numero_d_identification_du_ps_remplaçant,
|
|
||||||
""
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].cle_du_numero_d_identification_du_ps_remplaçant,
|
|
||||||
"0"
|
|
||||||
);
|
|
||||||
assert_eq!(carte_ps.situations[0].code_conventionnel, "1");
|
|
||||||
assert_eq!(carte_ps.situations[0].code_specialite, "50");
|
|
||||||
assert_eq!(carte_ps.situations[0].code_zone_tarifaire, "10");
|
|
||||||
assert_eq!(carte_ps.situations[0].code_zone_ik, "00");
|
|
||||||
assert_eq!(carte_ps.situations[0].code_agrement_1, "0");
|
|
||||||
assert_eq!(carte_ps.situations[0].code_agrement_2, "0");
|
|
||||||
assert_eq!(carte_ps.situations[0].code_agrement_3, "0");
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].habilitation_à_signer_une_facture,
|
|
||||||
"1"
|
|
||||||
);
|
|
||||||
assert_eq!(carte_ps.situations[0].habilitation_à_signer_un_lot, "1");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_multiple_situations() {
|
|
||||||
let bytes: &[u8] = &[
|
|
||||||
0, 1, 51, // Block 01, Content size 51
|
|
||||||
1, 48, 1, 56, 11, 57, 57, 55, 48, 48, 53, 50, 52, 49, 57, 52, 1, 52, 2, 50, 50, 17, 80,
|
|
||||||
72, 65, 82, 77, 65, 67, 73, 69, 78, 48, 48, 53, 50, 52, 49, 57, 9, 70, 82, 65, 78, 67,
|
|
||||||
79, 73, 83, 69, 1, 84, 0, 2, 83, // Block 02, Content size 83
|
|
||||||
1, 1, 1, 48, 1, 49, 2, 56, 54, 1, 49, 9, 48, 66, 48, 50, 50, 49, 57, 53, 56, 1, 56, 24,
|
|
||||||
80, 72, 65, 82, 77, 65, 67, 73, 69, 32, 68, 85, 32, 67, 69, 78, 84, 82, 69, 50, 50, 49,
|
|
||||||
57, 53, 8, 48, 48, 50, 48, 50, 52, 49, 57, 1, 56, 0, 1, 48, 1, 49, 2, 53, 48, 2, 49,
|
|
||||||
48, 2, 48, 48, 1, 48, 1, 48, 1, 48, 1, 49, 1, 49, 0, 3,
|
|
||||||
83, // Block 03, Content size 83
|
|
||||||
1, 1, 1, 48, 1, 49, 2, 56, 54, 1, 49, 9, 48, 66, 48, 50, 50, 49, 57, 53, 56, 1, 56, 24,
|
|
||||||
80, 72, 65, 82, 77, 65, 67, 73, 69, 32, 68, 85, 32, 67, 69, 78, 84, 82, 69, 50, 50, 49,
|
|
||||||
57, 53, 8, 48, 48, 50, 48, 50, 52, 49, 57, 1, 56, 0, 1, 48, 1, 49, 2, 53, 48, 2, 49,
|
|
||||||
48, 2, 48, 48, 1, 48, 1, 48, 1, 48, 1, 49, 1, 49, 0, 4,
|
|
||||||
83, // Block 04, Content size 83
|
|
||||||
1, 1, 1, 48, 1, 49, 2, 56, 54, 1, 49, 9, 48, 66, 48, 50, 50, 49, 57, 53, 56, 1, 56, 24,
|
|
||||||
80, 72, 65, 82, 77, 65, 67, 73, 69, 32, 68, 85, 32, 67, 69, 78, 84, 82, 69, 50, 50, 49,
|
|
||||||
57, 53, 8, 48, 48, 50, 48, 50, 52, 49, 57, 1, 56, 0, 1, 48, 1, 49, 2, 53, 48, 2, 49,
|
|
||||||
48, 2, 48, 48, 1, 48, 1, 48, 1, 48, 1, 49, 1, 49,
|
|
||||||
];
|
|
||||||
let blocks = decode_ssv_memory(bytes, bytes.len()).unwrap();
|
|
||||||
let carte_ps = decode_carte_ps(blocks).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(carte_ps.situations.len(), 3);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[0].raison_sociale_structure,
|
|
||||||
"PHARMACIE DU CENTRE22195"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[1].raison_sociale_structure,
|
|
||||||
"PHARMACIE DU CENTRE22195"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
carte_ps.situations[2].raison_sociale_structure,
|
|
||||||
"PHARMACIE DU CENTRE22195"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[should_panic]
|
|
||||||
fn test_missing_field() {
|
|
||||||
todo!();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[should_panic]
|
|
||||||
fn test_unknown_group_field_pair() {
|
|
||||||
todo!();
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
#[should_panic]
|
|
||||||
fn test_invalid_field_format() {
|
|
||||||
todo!();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,19 +0,0 @@
|
|||||||
pub mod cps;
|
|
||||||
pub mod libssv;
|
|
||||||
pub mod ssv_memory;
|
|
||||||
pub mod ssvlib_demo;
|
|
||||||
|
|
||||||
pub fn add(left: usize, right: usize) -> usize {
|
|
||||||
left + right
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn it_works() {
|
|
||||||
let result = add(2, 2);
|
|
||||||
assert_eq!(result, 4);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,30 +0,0 @@
|
|||||||
/// libssv.rs
|
|
||||||
///
|
|
||||||
/// Low level bindings to the SSVLIB dynamic library.
|
|
||||||
// TODO : look for creating a dedicated *-sys crate : https://kornel.ski/rust-sys-crate
|
|
||||||
use libc::{c_char, c_ushort, c_void, size_t};
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
|
||||||
pub enum LibSSVError {
|
|
||||||
#[error("SSV library error in {function}: {code}")]
|
|
||||||
StandardErrorCode { code: u16, function: &'static str },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(target_os = "linux", link(name = "ssvlux64"))]
|
|
||||||
#[cfg_attr(target_os = "windows", link(name = "ssvw64"))]
|
|
||||||
extern "C" {
|
|
||||||
pub fn SSV_InitLIB2(pcRepSesamIni: *const c_char) -> c_ushort;
|
|
||||||
pub fn SSV_LireCartePS(
|
|
||||||
NomRessourcePS: *const c_char,
|
|
||||||
NomRessourceLecteur: *const c_char,
|
|
||||||
CodePorteurPS: *const c_char,
|
|
||||||
ZDonneesSortie: *mut *mut c_void,
|
|
||||||
TTailleDonneesSortie: *mut size_t,
|
|
||||||
) -> c_ushort;
|
|
||||||
pub fn SSV_LireConfig(
|
|
||||||
ZDonneesSortie: *mut *mut c_void,
|
|
||||||
TTailleDonneesSortie: *mut size_t,
|
|
||||||
) -> c_ushort;
|
|
||||||
}
|
|
||||||
// TODO : replace void* by Rust struct : https://doc.rust-lang.org/nomicon/ffi.html#representing-opaque-structs
|
|
@ -1,10 +0,0 @@
|
|||||||
mod cps;
|
|
||||||
mod libssv;
|
|
||||||
mod ssv_memory;
|
|
||||||
mod ssvlib_demo;
|
|
||||||
|
|
||||||
use anyhow::{Context, Result};
|
|
||||||
|
|
||||||
fn main() -> Result<()> {
|
|
||||||
ssvlib_demo::demo().context("Error while running the SSV library demo")
|
|
||||||
}
|
|
@ -1,358 +0,0 @@
|
|||||||
/// # SSV Memory
|
|
||||||
/// Provide functions to manipulate raw memory from SSV library.
|
|
||||||
use std::convert::TryFrom;
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
|
||||||
pub enum BytesReadingError {
|
|
||||||
#[error("Empty bytes input")]
|
|
||||||
EmptyBytes,
|
|
||||||
#[error("Invalid memory: not enough bytes ({actual}) to read the expected size ({expected})")]
|
|
||||||
InvalidSize { expected: usize, actual: usize },
|
|
||||||
#[error("Invalid memory: size ({actual}) is expected to be less than {expected} bytes")]
|
|
||||||
SizeTooBig { expected: usize, actual: usize },
|
|
||||||
#[error("Invalid memory: not enough bytes to read the block id")]
|
|
||||||
InvalidBlockId(#[from] std::array::TryFromSliceError),
|
|
||||||
#[error("Error while reading field at offset {offset}")]
|
|
||||||
InvalidField {
|
|
||||||
source: Box<BytesReadingError>,
|
|
||||||
offset: usize,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
|
||||||
pub enum SSVMemoryError {
|
|
||||||
#[error("Error while parsing block at offset {offset}")]
|
|
||||||
BlockParsing {
|
|
||||||
source: BytesReadingError,
|
|
||||||
offset: usize,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(PartialEq, Debug)]
|
|
||||||
struct ElementSize {
|
|
||||||
pub size: usize,
|
|
||||||
pub pad: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO : Est-ce qu'on pourrait/devrait définir un type custom pour représenter les tableaux de bytes ?
|
|
||||||
impl TryFrom<&[u8]> for ElementSize {
|
|
||||||
type Error = BytesReadingError;
|
|
||||||
|
|
||||||
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
|
|
||||||
if bytes.is_empty() {
|
|
||||||
return Err(BytesReadingError::EmptyBytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut element_size = ElementSize { size: 0, pad: 1 };
|
|
||||||
// Longueur:
|
|
||||||
// - si le bit de poids fort du premier octet est à 0, la longueur est codée sur un octet
|
|
||||||
// - si le bit de poids fort du premier octet est à 1, les 7 bits de poids faible codent le nombre d'octets utilisés pour coder la longueur
|
|
||||||
if bytes[0] & 0b1000_0000 == 0 {
|
|
||||||
// Size coded on 1 byte
|
|
||||||
element_size.size = bytes[0] as usize;
|
|
||||||
} else {
|
|
||||||
// Size coded on N bytes
|
|
||||||
// N are the 7 lower bits of the first byte
|
|
||||||
let size_bytes_len = (bytes[0] & 0b0111_1111) as usize;
|
|
||||||
if size_bytes_len > bytes.len() - 1 {
|
|
||||||
return Err(BytesReadingError::InvalidSize {
|
|
||||||
expected: size_bytes_len,
|
|
||||||
actual: bytes.len() - 1,
|
|
||||||
});
|
|
||||||
} else if size_bytes_len > 4 {
|
|
||||||
return Err(BytesReadingError::SizeTooBig {
|
|
||||||
expected: 4,
|
|
||||||
actual: size_bytes_len,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let size_bytes = &bytes[1..1 + size_bytes_len];
|
|
||||||
|
|
||||||
// u32::from_be_bytes() requires a 4 bytes array
|
|
||||||
let mut padded_bytes = [0u8; 4];
|
|
||||||
padded_bytes[size_bytes_len..].copy_from_slice(size_bytes);
|
|
||||||
|
|
||||||
element_size.size = u32::from_be_bytes(padded_bytes) as usize;
|
|
||||||
element_size.pad += size_bytes_len;
|
|
||||||
}
|
|
||||||
Ok(element_size)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Block<'a> {
|
|
||||||
pub id: u16,
|
|
||||||
pub size: usize,
|
|
||||||
pub content: Vec<Field<'a>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TryFrom<&'a [u8]> for Block<'a> {
|
|
||||||
type Error = BytesReadingError;
|
|
||||||
|
|
||||||
fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
|
|
||||||
let mut offset = 0;
|
|
||||||
let id = u16::from_be_bytes(
|
|
||||||
bytes[..2]
|
|
||||||
.try_into()
|
|
||||||
.map_err(BytesReadingError::InvalidBlockId)?,
|
|
||||||
);
|
|
||||||
offset += 2;
|
|
||||||
let ElementSize {
|
|
||||||
size: block_size,
|
|
||||||
pad,
|
|
||||||
} = bytes[2..].try_into()?;
|
|
||||||
offset += pad;
|
|
||||||
let raw_content = &bytes[offset..];
|
|
||||||
let mut field_offset = 0;
|
|
||||||
// While there is still content to read, parse Fields
|
|
||||||
let mut content = Vec::new();
|
|
||||||
let mut field_id = 1;
|
|
||||||
while field_offset < block_size {
|
|
||||||
let mut field: Field<'a> = raw_content[field_offset..].try_into().map_err(|err| {
|
|
||||||
BytesReadingError::InvalidField {
|
|
||||||
source: Box::new(err),
|
|
||||||
offset: field_offset,
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
field.id = field_id;
|
|
||||||
field_offset += field.size;
|
|
||||||
field_id += 1;
|
|
||||||
content.push(field);
|
|
||||||
}
|
|
||||||
Ok(Block {
|
|
||||||
id,
|
|
||||||
size: offset + block_size,
|
|
||||||
content,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Field<'a> {
|
|
||||||
pub id: u16,
|
|
||||||
pub size: usize,
|
|
||||||
pub content: &'a [u8],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> TryFrom<&'a [u8]> for Field<'a> {
|
|
||||||
type Error = BytesReadingError;
|
|
||||||
|
|
||||||
fn try_from(bytes: &'a [u8]) -> Result<Self, Self::Error> {
|
|
||||||
let ElementSize { size, pad } = bytes.try_into()?;
|
|
||||||
let contenu = &bytes[pad..pad + size];
|
|
||||||
Ok(Field {
|
|
||||||
id: 0,
|
|
||||||
size: pad + size,
|
|
||||||
content: contenu,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn decode_ssv_memory(bytes: &[u8], size: usize) -> Result<Vec<Block>, SSVMemoryError> {
|
|
||||||
let mut blocks: Vec<Block> = Vec::new();
|
|
||||||
let mut offset = 0;
|
|
||||||
while offset < size {
|
|
||||||
let block: Block =
|
|
||||||
bytes[offset..]
|
|
||||||
.try_into()
|
|
||||||
.map_err(|err| SSVMemoryError::BlockParsing {
|
|
||||||
source: err,
|
|
||||||
offset,
|
|
||||||
})?;
|
|
||||||
offset += block.size;
|
|
||||||
blocks.push(block);
|
|
||||||
}
|
|
||||||
Ok(blocks)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test_element_size {
|
|
||||||
use std::any::Any;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn short_size() {
|
|
||||||
let bytes: &[u8] = &[0b_0000_0001_u8];
|
|
||||||
let element_size: ElementSize = bytes.try_into().unwrap();
|
|
||||||
assert_eq!(element_size.size, 1);
|
|
||||||
assert_eq!(element_size.pad, 1);
|
|
||||||
|
|
||||||
let bytes: &[u8] = &[0b_0100_0000_u8];
|
|
||||||
let element_size: ElementSize = bytes.try_into().unwrap();
|
|
||||||
assert_eq!(element_size.size, 64);
|
|
||||||
assert_eq!(element_size.pad, 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn long_size() {
|
|
||||||
let bytes: &[u8] = &[0b_1000_0010_u8, 0b_0000_0001_u8, 0b_0100_0000_u8];
|
|
||||||
let element_size: ElementSize = bytes.try_into().unwrap();
|
|
||||||
assert_eq!(element_size.size, 320);
|
|
||||||
assert_eq!(element_size.pad, 3);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn null_size() {
|
|
||||||
let bytes: &[u8] = &[];
|
|
||||||
let result: Result<ElementSize, BytesReadingError> = bytes.try_into();
|
|
||||||
assert!(result.is_err());
|
|
||||||
assert_eq!(
|
|
||||||
result.unwrap_err().type_id(),
|
|
||||||
BytesReadingError::EmptyBytes.type_id()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn invalid_memory() {
|
|
||||||
let bytes: &[u8] = &[0b_1000_0001_u8];
|
|
||||||
let result: Result<ElementSize, BytesReadingError> = bytes.try_into();
|
|
||||||
assert!(result.is_err());
|
|
||||||
assert_eq!(
|
|
||||||
result.unwrap_err().to_string(),
|
|
||||||
BytesReadingError::InvalidSize {
|
|
||||||
expected: 1,
|
|
||||||
actual: 0
|
|
||||||
}
|
|
||||||
.to_string()
|
|
||||||
);
|
|
||||||
|
|
||||||
let bytes: &[u8] = &[0b_1000_0010_u8, 1];
|
|
||||||
let result: Result<ElementSize, BytesReadingError> = bytes.try_into();
|
|
||||||
assert!(result.is_err());
|
|
||||||
assert_eq!(
|
|
||||||
result.unwrap_err().to_string(),
|
|
||||||
BytesReadingError::InvalidSize {
|
|
||||||
expected: 2,
|
|
||||||
actual: 1
|
|
||||||
}
|
|
||||||
.to_string()
|
|
||||||
);
|
|
||||||
|
|
||||||
let bytes: &[u8] = &[0b_1000_0101_u8, 1, 1, 1, 1, 1];
|
|
||||||
let result: Result<ElementSize, BytesReadingError> = bytes.try_into();
|
|
||||||
assert!(result.is_err());
|
|
||||||
assert_eq!(
|
|
||||||
result.unwrap_err().to_string(),
|
|
||||||
BytesReadingError::SizeTooBig {
|
|
||||||
expected: 4,
|
|
||||||
actual: 5
|
|
||||||
}
|
|
||||||
.to_string()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test_field {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn short_size() {
|
|
||||||
let bytes: &[u8] = &[
|
|
||||||
51, 1, 48, 1, 56, 11, 57, 57, 55, 48, 48, 53, 50, 52, 49, 57, 52, 1, 52, 2, 50, 50, 17,
|
|
||||||
80, 72, 65, 82, 77, 65, 67, 73, 69, 78, 48, 48, 53, 50, 52, 49, 57, 9, 70, 82, 65, 78,
|
|
||||||
67, 79, 73, 83, 69, 1, 84,
|
|
||||||
];
|
|
||||||
let element: Field = bytes.try_into().unwrap();
|
|
||||||
assert_eq!(element.size, 52);
|
|
||||||
assert_eq!(element.content[..5], [1, 48, 1, 56, 11]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn long_size() {
|
|
||||||
let mut bytes_vec = vec![
|
|
||||||
0b_1000_0010_u8,
|
|
||||||
0b_0000_0001_u8,
|
|
||||||
0b_0000_0000_u8, // size = 256
|
|
||||||
];
|
|
||||||
// Add 256 bytes to the content
|
|
||||||
bytes_vec.append(&mut vec![1; 256]);
|
|
||||||
let bytes: &[u8] = &bytes_vec;
|
|
||||||
let element: Field = bytes.try_into().unwrap();
|
|
||||||
assert_eq!(element.size, 259);
|
|
||||||
assert_eq!(element.content.len(), 256);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test_block {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_francoise_pharmacien0052419_partial_block_1() {
|
|
||||||
let bytes: &[u8] = &[1, 48, 1, 56, 11, 57, 57, 55, 48, 48, 53, 50, 52, 49, 57, 52];
|
|
||||||
|
|
||||||
let field1: Field = bytes.try_into().unwrap();
|
|
||||||
assert_eq!(field1.size, 2);
|
|
||||||
assert_eq!(field1.content, &[48]);
|
|
||||||
|
|
||||||
let field2: Field = bytes[field1.size..].try_into().unwrap();
|
|
||||||
assert_eq!(field2.size, 2);
|
|
||||||
assert_eq!(field2.content, &[56]);
|
|
||||||
|
|
||||||
let field3: Field = bytes[field1.size + field2.size..].try_into().unwrap();
|
|
||||||
assert_eq!(field3.size, 12);
|
|
||||||
assert_eq!(
|
|
||||||
field3.content,
|
|
||||||
&[57, 57, 55, 48, 48, 53, 50, 52, 49, 57, 52]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_francoise_pharmacien0052419() {
|
|
||||||
let bytes: &[u8] = &[
|
|
||||||
0, 1, 51, // 3
|
|
||||||
1, 48, // 2
|
|
||||||
1, 56, // 2
|
|
||||||
11, 57, 57, 55, 48, 48, 53, 50, 52, 49, 57, 52, // 12
|
|
||||||
1, 52, // 2
|
|
||||||
2, 50, 50, // 3
|
|
||||||
17, 80, 72, 65, 82, 77, 65, 67, 73, 69, 78, 48, 48, 53, 50, 52, 49, 57, // 18
|
|
||||||
9, 70, 82, 65, 78, 67, 79, 73, 83, 69, // 10
|
|
||||||
1, 84, // 2
|
|
||||||
// total: 54
|
|
||||||
0, 2, 83, 1, 1, 1, 48, 1, 49, 2, 56, 54, 1, 49, 9, 48, 66, 48, 50, 50, 49, 57, 53, 56,
|
|
||||||
1, 56, 24, 80, 72, 65, 82, 77, 65, 67, 73, 69, 32, 68, 85, 32, 67, 69, 78, 84, 82, 69,
|
|
||||||
50, 50, 49, 57, 53, 8, 48, 48, 50, 48, 50, 52, 49, 57, 1, 56, 0, 1, 48, 1, 49, 2, 53,
|
|
||||||
48, 2, 49, 48, 2, 48, 48, 1, 48, 1, 48, 1, 48, 1, 49, 1, 49,
|
|
||||||
];
|
|
||||||
|
|
||||||
let first_block: Block = bytes.try_into().unwrap();
|
|
||||||
assert_eq!(first_block.id, 1);
|
|
||||||
assert_eq!(first_block.size, 54);
|
|
||||||
assert_eq!(first_block.content.len(), 8);
|
|
||||||
|
|
||||||
let second_block: Block = bytes[first_block.size..].try_into().unwrap();
|
|
||||||
assert_eq!(second_block.id, 2);
|
|
||||||
assert_eq!(second_block.size, 86);
|
|
||||||
assert_eq!(second_block.content.len(), 21);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod test_decode_ssv_memory {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn test_francoise_pharmacien0052419() {
|
|
||||||
let bytes: &[u8] = &[
|
|
||||||
0, 1, 51, // 3
|
|
||||||
1, 48, // 2
|
|
||||||
1, 56, // 2
|
|
||||||
11, 57, 57, 55, 48, 48, 53, 50, 52, 49, 57, 52, // 12
|
|
||||||
1, 52, // 2
|
|
||||||
2, 50, 50, // 3
|
|
||||||
17, 80, 72, 65, 82, 77, 65, 67, 73, 69, 78, 48, 48, 53, 50, 52, 49, 57, // 18
|
|
||||||
9, 70, 82, 65, 78, 67, 79, 73, 83, 69, // 10
|
|
||||||
1, 84, // 2
|
|
||||||
// total: 54
|
|
||||||
0, 2, 83, 1, 1, 1, 48, 1, 49, 2, 56, 54, 1, 49, 9, 48, 66, 48, 50, 50, 49, 57, 53, 56,
|
|
||||||
1, 56, 24, 80, 72, 65, 82, 77, 65, 67, 73, 69, 32, 68, 85, 32, 67, 69, 78, 84, 82, 69,
|
|
||||||
50, 50, 49, 57, 53, 8, 48, 48, 50, 48, 50, 52, 49, 57, 1, 56, 0, 1, 48, 1, 49, 2, 53,
|
|
||||||
48, 2, 49, 48, 2, 48, 48, 1, 48, 1, 48, 1, 48, 1, 49, 1, 49,
|
|
||||||
];
|
|
||||||
let blocks = decode_ssv_memory(bytes, bytes.len()).unwrap();
|
|
||||||
assert_eq!(blocks.len(), 2);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,87 +0,0 @@
|
|||||||
/// High level API for the SSV library,
|
|
||||||
/// based on the low level bindings in libssv.rs.
|
|
||||||
use libc::{c_void, size_t};
|
|
||||||
use std::env;
|
|
||||||
use std::ffi::CString;
|
|
||||||
use std::ptr;
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
use crate::cps::lire_carte;
|
|
||||||
use crate::libssv::{SSV_InitLIB2, SSV_LireConfig};
|
|
||||||
|
|
||||||
use ::utils::config::{load_config, ConfigError};
|
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
|
||||||
pub enum SSVDemoError {
|
|
||||||
#[error(transparent)]
|
|
||||||
CartePSReading(#[from] crate::cps::CartePSError),
|
|
||||||
#[error(transparent)]
|
|
||||||
SSVLibErrorCode(#[from] crate::libssv::LibSSVError),
|
|
||||||
#[error(transparent)]
|
|
||||||
Configuration(#[from] ConfigError),
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ssv_init_lib_2() -> Result<(), SSVDemoError> {
|
|
||||||
let ini_str = env::var("SESAM_INI_PATH").expect("SESAM_INI_PATH must be set");
|
|
||||||
let ini = CString::new(ini_str).expect("CString::new failed");
|
|
||||||
unsafe {
|
|
||||||
let result = SSV_InitLIB2(ini.as_ptr());
|
|
||||||
println!("SSV_InitLIB2 result: {}", result);
|
|
||||||
if result != 0 {
|
|
||||||
return Err(crate::libssv::LibSSVError::StandardErrorCode {
|
|
||||||
code: result,
|
|
||||||
function: "SSV_InitLIB2",
|
|
||||||
}
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn ssv_lire_config() -> Result<(), SSVDemoError> {
|
|
||||||
let mut buffer: *mut c_void = ptr::null_mut();
|
|
||||||
let mut size: size_t = 0;
|
|
||||||
unsafe {
|
|
||||||
let result = SSV_LireConfig(&mut buffer, &mut size);
|
|
||||||
println!("SSV_LireConfig result: {}", result);
|
|
||||||
if result != 0 {
|
|
||||||
return Err(crate::libssv::LibSSVError::StandardErrorCode {
|
|
||||||
code: result,
|
|
||||||
function: "SSV_LireConfig",
|
|
||||||
}
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
if !buffer.is_null() {
|
|
||||||
let hex_values = std::slice::from_raw_parts(buffer as *const u8, size);
|
|
||||||
for &byte in hex_values {
|
|
||||||
print!("{:02X} ", byte);
|
|
||||||
}
|
|
||||||
println!();
|
|
||||||
|
|
||||||
libc::free(buffer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn demo() -> Result<(), SSVDemoError> {
|
|
||||||
// TODO : this is probably not working on release, because I'm not sure it exists a CARGO_MANIFEST_DIR and so it can find the `.env`
|
|
||||||
// Maybe we could use a system standard config path to store a config file
|
|
||||||
|
|
||||||
println!("------- Demo for the SSV library --------");
|
|
||||||
|
|
||||||
load_config(None)?;
|
|
||||||
|
|
||||||
ssv_init_lib_2()?;
|
|
||||||
|
|
||||||
let code_pin = "1234";
|
|
||||||
let lecteur = "HID Global OMNIKEY 3x21 Smart Card Reader 0";
|
|
||||||
let carte_ps = lire_carte(code_pin, lecteur)?;
|
|
||||||
println!("CartePS: {:#?}", carte_ps);
|
|
||||||
|
|
||||||
ssv_lire_config()?;
|
|
||||||
|
|
||||||
println!("-----------------------------------------");
|
|
||||||
Ok(())
|
|
||||||
}
|
|
@ -1,10 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "utils"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
anyhow.workspace = true
|
|
||||||
directories = "5.0"
|
|
||||||
dotenv.workspace = true
|
|
||||||
thiserror.workspace = true
|
|
@ -1,68 +0,0 @@
|
|||||||
use std::{env, path::PathBuf, sync::atomic::AtomicBool};
|
|
||||||
|
|
||||||
use directories::ProjectDirs;
|
|
||||||
use dotenv::from_path;
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
const CONFIG_FILE_NAME: &str = ".env";
|
|
||||||
|
|
||||||
static CONFIG_INITIALIZED: AtomicBool = AtomicBool::new(false);
|
|
||||||
|
|
||||||
#[derive(Debug, Error)]
|
|
||||||
pub enum ConfigError {
|
|
||||||
#[error("No config file {0} found in the following directories: {1:#?}")]
|
|
||||||
ConfigFileNotFound(String, Vec<PathBuf>),
|
|
||||||
#[error("Failed to load config file: {0}")]
|
|
||||||
LoadConfigError(#[from] dotenv::Error),
|
|
||||||
#[error("Environment variable error: {0}")]
|
|
||||||
EnvVarError(#[from] std::env::VarError),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_config_dirs() -> Vec<PathBuf> {
|
|
||||||
let mut config_dirs = vec![
|
|
||||||
PathBuf::from(""), // Current directory
|
|
||||||
];
|
|
||||||
if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") {
|
|
||||||
config_dirs.push(PathBuf::from(manifest_dir));
|
|
||||||
}
|
|
||||||
if let Some(proj_dirs) = ProjectDirs::from("org", "P4pillon", "Krys4lide") {
|
|
||||||
config_dirs.push(proj_dirs.config_dir().to_path_buf());
|
|
||||||
}
|
|
||||||
config_dirs
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_config_files() -> Result<Vec<PathBuf>, ConfigError> {
|
|
||||||
let config_dirs = get_config_dirs();
|
|
||||||
let mut config_files = Vec::new();
|
|
||||||
for config_dir in config_dirs.iter() {
|
|
||||||
let config_file = config_dir.join(CONFIG_FILE_NAME);
|
|
||||||
if config_file.exists() {
|
|
||||||
config_files.push(config_file);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if config_files.is_empty() {
|
|
||||||
return Err(ConfigError::ConfigFileNotFound(
|
|
||||||
CONFIG_FILE_NAME.to_string(),
|
|
||||||
config_dirs,
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Ok(config_files)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn load_config(force: Option<bool>) -> Result<(), ConfigError> {
|
|
||||||
let force = force.unwrap_or(false);
|
|
||||||
if CONFIG_INITIALIZED.load(std::sync::atomic::Ordering::Relaxed) && force {
|
|
||||||
println!("DEBUG: Config already initialized, skipping");
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
let config_files = get_config_files()?;
|
|
||||||
// Load the first config file found
|
|
||||||
// TODO: add a verbose log to list all config files found
|
|
||||||
println!(
|
|
||||||
"DEBUG: Config files found (1st loaded): {:#?}",
|
|
||||||
config_files
|
|
||||||
);
|
|
||||||
from_path(config_files[0].as_path()).map_err(ConfigError::LoadConfigError)?;
|
|
||||||
CONFIG_INITIALIZED.store(true, std::sync::atomic::Ordering::Relaxed);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
pub mod config;
|
|
@ -1,85 +0,0 @@
|
|||||||
# Gestion des erreurs
|
|
||||||
|
|
||||||
Ce document décrit comment les erreurs sont gérées dans le projet.
|
|
||||||
|
|
||||||
## Gestion native
|
|
||||||
|
|
||||||
Par principe, en Rust, on évite au maximum la gestion par exception, ne la réservant qu'aux situations où un crash du programme est la meilleure solution.
|
|
||||||
En temps normal, on renvoie des `Result<Valeur, Erreur>` (pour les situations réussite/erreur) ou des `Option<Valeur>` (pour les situations valeur non-nulle/nulle).
|
|
||||||
|
|
||||||
Quand on fait face à une situation d'erreur, on cherchera à la gérer de manière explicite (voir [Récupération des erreurs](#récupération-des-erreurs)) ou à la remonter à un niveau supérieur, généralement à l'aide de l'opérateur `?`.
|
|
||||||
|
|
||||||
On évitera, par contre, au maximum de générer des exceptions (appelées "panics" en Rust), que ce soit par l'usage de `panic!` ou par des appels à des fonctions qui paniquent en cas d'erreur (comme `unwrap` ou `expect`).
|
|
||||||
|
|
||||||
De nombreux exemples des idiomes natifs de gestion des erreurs en Rust sont disponibles dans la documentation [Rust by example](https://doc.rust-lang.org/rust-by-example/error.html).
|
|
||||||
|
|
||||||
## Librairies de gestion des erreurs
|
|
||||||
|
|
||||||
Deux librairies sont utilisées pour gérer les erreurs dans le projet :
|
|
||||||
- [`anyhow`](https://docs.rs/anyhow/latest/anyhow/) : qui permet de renvoyer des erreurs faiblement typées, mais très facile à enrichir avec des messages d'explication. On l'utilise pour communiquer facilement des erreurs de haut niveau avec un utilisateur final.
|
|
||||||
```rust
|
|
||||||
use anyhow::{anyhow, Result};
|
|
||||||
|
|
||||||
fn get_cluster_info() -> Result<ClusterInfo> {
|
|
||||||
let data = fs::read_to_string("cluster.json")
|
|
||||||
.with_context(|| "failed to read cluster config")?;
|
|
||||||
let info: ClusterInfo = serde_json::from_str(&data)
|
|
||||||
.with_context(|| "failed to parse cluster config")?;
|
|
||||||
Ok(info)
|
|
||||||
}
|
|
||||||
```
|
|
||||||
- [`thiserror`](https://docs.rs/thiserror/latest/thiserror/) : qui fournit des macros pour définir des erreurs fortement typées. On l'utilise pour définir des erreurs spécifiques à une partie du code, contextualisées avec des données structurées plutôt que de simples messages d'erreurs, afin de favoriser la "récupération" face aux erreurs.
|
|
||||||
```rust
|
|
||||||
use thiserror::Error;
|
|
||||||
|
|
||||||
#[derive(Error, Debug)]
|
|
||||||
pub enum DataStoreError {
|
|
||||||
#[error("data store disconnected")]
|
|
||||||
Disconnect(#[from] io::Error),
|
|
||||||
#[error("the data for key `{0}` is not available")]
|
|
||||||
Redaction(String),
|
|
||||||
#[error("invalid header (expected {expected:?}, found {found:?})")]
|
|
||||||
InvalidHeader {
|
|
||||||
expected: String,
|
|
||||||
found: String,
|
|
||||||
},
|
|
||||||
#[error("unknown data store error")]
|
|
||||||
Unknown,
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## Récupération des erreurs
|
|
||||||
|
|
||||||
Dans la mesure du possible, on essaie de privilégier la "récupération" face à une erreur plutôt que le "crash". Les stratégies de récupération sont :
|
|
||||||
- Réessayer l'opération, tel quel ou avec des paramètres différents
|
|
||||||
- Contourner l'opération, en la remplaçant par une autre
|
|
||||||
- À défaut, informer l'utilisateur de l'erreur et :
|
|
||||||
- arrêter / annuler l'opération en cours
|
|
||||||
- ignorer l'erreur et continuer l'exécution
|
|
||||||
|
|
||||||
Quand on ne peut pas récupérer une erreur, on la remonte à un niveau supérieur, si besoin en la convertissant dans un type d'erreur plus générique et approprié au niveau considéré.
|
|
||||||
|
|
||||||
## Conversion des erreurs
|
|
||||||
|
|
||||||
Quand on remonte une erreur à un niveau supérieur, on peut être amené à la convertir dans un type d'erreur plus générique et approprié au niveau considéré. Pour faciliter cette conversion, on implémente le trait `From`. Avec `thiserror`, on peut utiliser l'attribut `#[from]` ou le paramètre `source` pour automatiser l'implémentation de telles conversions.
|
|
||||||
|
|
||||||
On peut ensuite, lors de la gestion d'une erreur, on pourra :
|
|
||||||
- soit directement renvoyer l'erreur à l'aide de l'opérateur `?`, qui se chargera de la conversion ;
|
|
||||||
- soit convertir l'erreur explicitement, par exemple en utilisant la méthode `map_err` sur un `Result`, en particulier quand on veut enrichir l'erreur avec des informations supplémentaires.
|
|
||||||
|
|
||||||
## Usages exceptionnels de `unwrap` et `expect`
|
|
||||||
|
|
||||||
Provoquant des "panics" en cas d'erreur, les fonctions `unwrap` et `expect` ne doivent être utilisées que dans des cas exceptionnels :
|
|
||||||
- Dans les tests, pour signaler une erreur de test
|
|
||||||
- Au plus haut niveau de l'application, pour signaler une erreur fatale qui ne peut pas être récupérée
|
|
||||||
- Dans des situations où l'erreur ne peut pas se produire, par exemple après une vérification de préconditions
|
|
||||||
|
|
||||||
Dans l'idéal, on préférera l'usage de `expect` à `unwrap`, car il permet de donner un message d'erreur explicite.
|
|
||||||
|
|
||||||
## Ressources
|
|
||||||
|
|
||||||
- [The Rust Programming Language - Ch. 9: Error Handling](https://doc.rust-lang.org/book/ch09-00-error-handling.html)
|
|
||||||
- [The NRC Book - Error Handling in Rust](https://nrc.github.io/error-docs/intro.html)
|
|
||||||
- [The Error Design Patterns Book - by Project Error Handling WG](https://github.com/rust-lang/project-error-handling/blob/master/error-design-patterns-book/src/SUMMARY.md)
|
|
||||||
- [The Rust Cookbook - Error Handling](https://rust-lang-nursery.github.io/rust-cookbook/error-handling.html)
|
|
||||||
- [Le ticket initial de l'intégration de la gestion des erreurs dans le projet](https://forge.p4pillon.org/P4Pillon/Krys4lide/issues/34)
|
|
@ -1,15 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "entity"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "entity"
|
|
||||||
path = "src/lib.rs"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
sea-orm.workspace = true
|
|
||||||
serde.workspace = true
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
sea-orm-cli.workspace = true
|
|
@ -1,18 +0,0 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.1
|
|
||||||
|
|
||||||
use sea_orm::entity::prelude::*;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize, Deserialize)]
|
|
||||||
#[sea_orm(table_name = "debug")]
|
|
||||||
pub struct Model {
|
|
||||||
#[sea_orm(primary_key)]
|
|
||||||
pub id: i32,
|
|
||||||
pub title: String,
|
|
||||||
pub text: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
|
||||||
pub enum Relation {}
|
|
||||||
|
|
||||||
impl ActiveModelBehavior for ActiveModel {}
|
|
@ -1,5 +0,0 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.1
|
|
||||||
|
|
||||||
pub mod prelude;
|
|
||||||
|
|
||||||
pub mod debug;
|
|
@ -1,3 +0,0 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.1
|
|
||||||
|
|
||||||
pub use super::debug::Entity as Debug;
|
|
@ -1,2 +0,0 @@
|
|||||||
mod entities;
|
|
||||||
pub use entities::*;
|
|
24
frontend/.gitignore
vendored
@ -1,24 +0,0 @@
|
|||||||
# Nuxt dev/build outputs
|
|
||||||
.output
|
|
||||||
.data
|
|
||||||
.nuxt
|
|
||||||
.nitro
|
|
||||||
.cache
|
|
||||||
dist
|
|
||||||
|
|
||||||
# Node dependencies
|
|
||||||
node_modules
|
|
||||||
|
|
||||||
# Logs
|
|
||||||
logs
|
|
||||||
*.log
|
|
||||||
|
|
||||||
# Misc
|
|
||||||
.DS_Store
|
|
||||||
.fleet
|
|
||||||
.idea
|
|
||||||
|
|
||||||
# Local env files
|
|
||||||
.env
|
|
||||||
.env.*
|
|
||||||
!.env.example
|
|
@ -1,77 +0,0 @@
|
|||||||
# Nuxt 3 Minimal Starter
|
|
||||||
|
|
||||||
TODO : Faire un vrai README pour `frontend` (Nuxt 3)
|
|
||||||
|
|
||||||
Look at the [Nuxt 3 documentation](https://nuxt.com/docs/getting-started/introduction) to learn more.
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
Make sure to install the dependencies:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# npm
|
|
||||||
npm install
|
|
||||||
|
|
||||||
# pnpm
|
|
||||||
pnpm install
|
|
||||||
|
|
||||||
# yarn
|
|
||||||
yarn install
|
|
||||||
|
|
||||||
# bun
|
|
||||||
bun install
|
|
||||||
```
|
|
||||||
|
|
||||||
## Development Server
|
|
||||||
|
|
||||||
Start the development server on `http://localhost:3000`:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# npm
|
|
||||||
npm run dev
|
|
||||||
|
|
||||||
# pnpm
|
|
||||||
pnpm run dev
|
|
||||||
|
|
||||||
# yarn
|
|
||||||
yarn dev
|
|
||||||
|
|
||||||
# bun
|
|
||||||
bun run dev
|
|
||||||
```
|
|
||||||
|
|
||||||
## Production
|
|
||||||
|
|
||||||
Build the application for production:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# npm
|
|
||||||
npm run build
|
|
||||||
|
|
||||||
# pnpm
|
|
||||||
pnpm run build
|
|
||||||
|
|
||||||
# yarn
|
|
||||||
yarn build
|
|
||||||
|
|
||||||
# bun
|
|
||||||
bun run build
|
|
||||||
```
|
|
||||||
|
|
||||||
Locally preview production build:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# npm
|
|
||||||
npm run preview
|
|
||||||
|
|
||||||
# pnpm
|
|
||||||
pnpm run preview
|
|
||||||
|
|
||||||
# yarn
|
|
||||||
yarn preview
|
|
||||||
|
|
||||||
# bun
|
|
||||||
bun run preview
|
|
||||||
```
|
|
||||||
|
|
||||||
Check out the [deployment documentation](https://nuxt.com/docs/getting-started/deployment) for more information.
|
|
@ -1,8 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div>
|
|
||||||
<NuxtLoadingIndicator />
|
|
||||||
<NuxtRouteAnnouncer />
|
|
||||||
<NavBar />
|
|
||||||
<NuxtPage />
|
|
||||||
</div>
|
|
||||||
</template>
|
|
@ -1,43 +0,0 @@
|
|||||||
<!--
|
|
||||||
This component is used to show a loading spinner when the SPA is loading.
|
|
||||||
Source: https://github.com/barelyhuman/snips/blob/dev/pages/css-loader.md
|
|
||||||
-->
|
|
||||||
<div class="loader"></div>
|
|
||||||
<style>
|
|
||||||
.loader {
|
|
||||||
display: block;
|
|
||||||
position: fixed;
|
|
||||||
z-index: 1031;
|
|
||||||
top: 50%;
|
|
||||||
left: 50%;
|
|
||||||
transform: translate(-50%, -50%);
|
|
||||||
width: 18px;
|
|
||||||
height: 18px;
|
|
||||||
box-sizing: border-box;
|
|
||||||
border: solid 2px transparent;
|
|
||||||
border-top-color: #000;
|
|
||||||
border-left-color: #000;
|
|
||||||
border-bottom-color: #efefef;
|
|
||||||
border-right-color: #efefef;
|
|
||||||
border-radius: 50%;
|
|
||||||
-webkit-animation: loader 400ms linear infinite;
|
|
||||||
animation: loader 400ms linear infinite;
|
|
||||||
}
|
|
||||||
|
|
||||||
\@-webkit-keyframes loader {
|
|
||||||
0% {
|
|
||||||
-webkit-transform: translate(-50%, -50%) rotate(0deg);
|
|
||||||
}
|
|
||||||
100% {
|
|
||||||
-webkit-transform: translate(-50%, -50%) rotate(360deg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
\@keyframes loader {
|
|
||||||
0% {
|
|
||||||
transform: translate(-50%, -50%) rotate(0deg);
|
|
||||||
}
|
|
||||||
100% {
|
|
||||||
transform: translate(-50%, -50%) rotate(360deg);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
</style>
|
|
@ -1,22 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="avatar">
|
|
||||||
<div class="rounded-full">
|
|
||||||
<img :src="getAvatarUrl(user)" />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
import type { User } from '~/types/user';
|
|
||||||
|
|
||||||
const props = defineProps<{
|
|
||||||
user: User,
|
|
||||||
}>();
|
|
||||||
|
|
||||||
const getAvatarUrl = (user: User) => {
|
|
||||||
if (user.avatar) {
|
|
||||||
return user.avatar;
|
|
||||||
}
|
|
||||||
return 'https://i.pravatar.cc/150?u=' + user.name;
|
|
||||||
};
|
|
||||||
</script>
|
|
@ -1,71 +0,0 @@
|
|||||||
<template>
|
|
||||||
<dialog
|
|
||||||
id="login_modal"
|
|
||||||
ref="login_modal"
|
|
||||||
@cancel.prevent=""
|
|
||||||
@keyup="handleKeyPress"
|
|
||||||
class="modal"
|
|
||||||
>
|
|
||||||
<div class="modal-box">
|
|
||||||
<h3 class="text-3xl text-center mb-6">Connexion</h3>
|
|
||||||
<div class="flex flex-wrap gap-5 justify-center">
|
|
||||||
<template v-for="(user, index) in users" :key="user.id">
|
|
||||||
<LoginModalAvatar
|
|
||||||
:user="user"
|
|
||||||
:rank="index+1"
|
|
||||||
@selectUser="login"
|
|
||||||
/>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<form method="dialog" class="modal-backdrop">
|
|
||||||
<button class="cursor-default">close</button>
|
|
||||||
</form>
|
|
||||||
</dialog>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
import type { User } from '~/types/user';
|
|
||||||
|
|
||||||
const users: User[] = [
|
|
||||||
{ id: 1, name: 'John Doe', avatar: 'https://img.daisyui.com/images/stock/photo-1534528741775-53994a69daeb.webp' },
|
|
||||||
{ id: 2, name: 'Jane Doe', avatar: 'https://i.pravatar.cc/150?u=JANEDOE728' },
|
|
||||||
{ id: 3, name: 'Michel Moulin' },
|
|
||||||
{ id: 4, name: 'Jean Paris' },
|
|
||||||
{ id: 5, name: 'Marie Dupont' },
|
|
||||||
{ id: 6, name: 'Émilie Fournier' },
|
|
||||||
{ id: 7, name: 'Pierre Lefevre' },
|
|
||||||
{ id: 8, name: 'Sophie Lemoine' },
|
|
||||||
{ id: 9, name: 'Lucie Simon' },
|
|
||||||
{ id: 10, name: 'Kevin Boucher' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const loginModal = useTemplateRef('login_modal');
|
|
||||||
|
|
||||||
const current_user = useCurrentUser();
|
|
||||||
|
|
||||||
const login = (user: User) => {
|
|
||||||
console.log('login', user);
|
|
||||||
current_user.value = user;
|
|
||||||
loginModal.value?.close();
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleKeyPress = (event: KeyboardEvent) => {
|
|
||||||
// Extract the rank from the event.code : Digit7 -> 7
|
|
||||||
const rank = event.code.match(/\d/);
|
|
||||||
if (!rank) {
|
|
||||||
console.debug('Not handled key event', { event });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const user = getUserByRank(parseInt(rank[0]));
|
|
||||||
if (user) {
|
|
||||||
login(user);
|
|
||||||
} else {
|
|
||||||
console.debug('Not handled key event', { event });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const getUserByRank = (rank: number): User => {
|
|
||||||
return users[rank - 1];
|
|
||||||
};
|
|
||||||
</script>
|
|
@ -1,17 +0,0 @@
|
|||||||
<template>
|
|
||||||
<button class="relative" @click="$emit('selectUser', user)">
|
|
||||||
<Avatar class="w-24" :user="user" />
|
|
||||||
<div class="absolute w-fit mx-auto bottom-0 inset-x-0">
|
|
||||||
<kbd class="kbd kbd-sm">{{ rank }}</kbd>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
import type { User } from '~/types/user';
|
|
||||||
|
|
||||||
const props = defineProps<{
|
|
||||||
user: User,
|
|
||||||
rank: Number,
|
|
||||||
}>();
|
|
||||||
</script>
|
|
@ -1,36 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div class="navbar">
|
|
||||||
<div class="navbar-start">
|
|
||||||
<a class="btn btn-ghost text-xl" href="/">Chrys4lide</a>
|
|
||||||
</div>
|
|
||||||
<nav class="navbar-center">
|
|
||||||
<NuxtLink to="/" class="btn btn-ghost">Accueil</NuxtLink>
|
|
||||||
<NuxtLink to="/CPS" class="btn btn-ghost">Carte CPS</NuxtLink>
|
|
||||||
<NuxtLink to="/debug" class="btn btn-ghost">Debug</NuxtLink>
|
|
||||||
</nav>
|
|
||||||
<div class="navbar-end">
|
|
||||||
<template v-if="!current_user">
|
|
||||||
<button class="btn btn-ghost" type="button" onclick="login_modal.showModal()">
|
|
||||||
Connexion
|
|
||||||
</button>
|
|
||||||
</template>
|
|
||||||
<template v-else>
|
|
||||||
<details class="dropdown dropdown-end">
|
|
||||||
<summary class="block"><Avatar :user="current_user" class="w-12" role="button" /></summary>
|
|
||||||
<ul class="menu dropdown-content bg-base-100 rounded-box z-[1] w-52 p-2 shadow">
|
|
||||||
<li><a @click="logout">Déconnexion</a></li>
|
|
||||||
</ul>
|
|
||||||
</details>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<LoginModal />
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
const current_user = useCurrentUser();
|
|
||||||
|
|
||||||
const logout = () => {
|
|
||||||
current_user.value = null;
|
|
||||||
};
|
|
||||||
</script>
|
|
@ -1,3 +0,0 @@
|
|||||||
import type { User } from '@/types/user';
|
|
||||||
|
|
||||||
export const useCurrentUser = () => useState<User | null>('currentUser', () => null);
|
|
@ -1,39 +0,0 @@
|
|||||||
// https://nuxt.com/docs/api/configuration/nuxt-config
|
|
||||||
export default defineNuxtConfig({
|
|
||||||
compatibilityDate: '2024-04-03',
|
|
||||||
// Enables the development server to be discoverable by other devices for mobile development
|
|
||||||
devServer: { host: '0.0.0.0', port: 1420 },
|
|
||||||
devtools: { enabled: true },
|
|
||||||
modules: [
|
|
||||||
'@nuxtjs/tailwindcss',
|
|
||||||
'@nuxtjs/color-mode',
|
|
||||||
],
|
|
||||||
// Disable SSR for Tauri
|
|
||||||
ssr: false,
|
|
||||||
vite: {
|
|
||||||
// Better support for Tauri CLI output
|
|
||||||
clearScreen: false,
|
|
||||||
// Enable environment variables
|
|
||||||
// Additional environment variables can be found at
|
|
||||||
// https://v2.tauri.app/reference/environment-variables/
|
|
||||||
envPrefix: ['VITE_', 'TAURI_'],
|
|
||||||
server: {
|
|
||||||
// Tauri requires a consistent port
|
|
||||||
strictPort: true,
|
|
||||||
hmr: {
|
|
||||||
// Use websocket for mobile hot reloading
|
|
||||||
protocol: 'ws',
|
|
||||||
// Make sure it's available on the network
|
|
||||||
host: '0.0.0.0',
|
|
||||||
// Use a specific port for hmr
|
|
||||||
port: 5183,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
colorMode: {
|
|
||||||
// Add `data-theme` attribute to the `html` tag, allowing DaisyUI to handle dark mode automatically
|
|
||||||
dataValue: 'theme',
|
|
||||||
// Remove the default `-mode` suffix from the class name, letting have `dark` and `light` as class names, for DaisyUI compatibility
|
|
||||||
classSuffix: '',
|
|
||||||
},
|
|
||||||
})
|
|
@ -1,22 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "nuxt-app",
|
|
||||||
"private": true,
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"build": "nuxi build",
|
|
||||||
"dev": "nuxi dev",
|
|
||||||
"generate": "nuxi generate",
|
|
||||||
"preview": "nuxi preview",
|
|
||||||
"postinstall": "nuxi prepare"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@nuxtjs/color-mode": "^3.5.1",
|
|
||||||
"daisyui": "^4.12.10",
|
|
||||||
"nuxt": "^3.13.0",
|
|
||||||
"vue": "latest",
|
|
||||||
"vue-router": "latest"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@nuxtjs/tailwindcss": "^6.12.1"
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,8 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div>
|
|
||||||
<h1 class="text-xl">Carte CPS</h1>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup>
|
|
||||||
</script>
|
|
@ -1,67 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div>
|
|
||||||
<h1 class="text-3xl mb-8">Debug</h1>
|
|
||||||
<div class="stats shadow mb-8">
|
|
||||||
<div class="stat">
|
|
||||||
<div class="stat-title">DB Ping Status</div>
|
|
||||||
<div class="stat-value">{{ data?.db_ping_status || "?" }}</div>
|
|
||||||
</div>
|
|
||||||
<div class="stat">
|
|
||||||
<div class="stat-title">Entries Count</div>
|
|
||||||
<div class="stat-value">{{ data?.entries.length || "?" }}</div>
|
|
||||||
<div class="stat-actions">
|
|
||||||
<button class="btn btn-sm" @click="addRandomEntry">Add entry</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="stat">
|
|
||||||
<div class="stat-title">Network status</div>
|
|
||||||
<div class="stat-value">{{ status }}</div>
|
|
||||||
<div class="stat-description">{{ error }}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h2 class="text-2xl mb-4">Entries</h2>
|
|
||||||
<table class="table">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>Id</th>
|
|
||||||
<th>Title</th>
|
|
||||||
<th>Text</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<tr v-for="entry in data?.entries" :key="entry.id">
|
|
||||||
<td>{{ entry.id }}</td>
|
|
||||||
<td>{{ entry.title }}</td>
|
|
||||||
<td>{{ entry.text }}</td>
|
|
||||||
</tr>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
type Entry = {
|
|
||||||
id: number;
|
|
||||||
title: string;
|
|
||||||
text: string;
|
|
||||||
};
|
|
||||||
type DebugResponse = {
|
|
||||||
db_ping_status: string;
|
|
||||||
entries: Entry[];
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
// TODO : handle a default backend URL by building a custom `$fetch` and `useFetch` functions with a `baseURL` option : https://nuxt.com/docs/guide/recipes/custom-usefetch#custom-fetch
|
|
||||||
|
|
||||||
const { data, refresh, error, status } = await useFetch<DebugResponse>('http://127.0.0.1:8080/debug');
|
|
||||||
|
|
||||||
async function addRandomEntry() {
|
|
||||||
await $fetch('http://127.0.0.1:8080/debug/add_random', {
|
|
||||||
method: 'POST',
|
|
||||||
});
|
|
||||||
refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
</script>
|
|
@ -1,17 +0,0 @@
|
|||||||
<template>
|
|
||||||
<div>
|
|
||||||
<h1 class="text-xl">Welcome to your {{ appName }}!</h1>
|
|
||||||
<p v-if="current_user">Logged in as {{ current_user.name }}</p>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup lang="ts">
|
|
||||||
const current_user = useCurrentUser();
|
|
||||||
const appName = 'Nuxt App';
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
h1 {
|
|
||||||
color: #42b983;
|
|
||||||
}
|
|
||||||
</style>
|
|
Before Width: | Height: | Size: 4.2 KiB |
@ -1 +0,0 @@
|
|||||||
|
|
@ -1,3 +0,0 @@
|
|||||||
{
|
|
||||||
"extends": "../.nuxt/tsconfig.server.json"
|
|
||||||
}
|
|
@ -1,7 +0,0 @@
|
|||||||
import type { Config } from 'tailwindcss'
|
|
||||||
|
|
||||||
export default <Partial<Config>>{
|
|
||||||
plugins: [
|
|
||||||
require('daisyui'),
|
|
||||||
],
|
|
||||||
}
|
|
@ -1,4 +0,0 @@
|
|||||||
{
|
|
||||||
// https://nuxt.com/docs/guide/concepts/typescript
|
|
||||||
"extends": "./.nuxt/tsconfig.json"
|
|
||||||
}
|
|
@ -1,6 +0,0 @@
|
|||||||
export declare interface User {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
email?: string;
|
|
||||||
avatar?: string;
|
|
||||||
}
|
|
BIN
lib/libp4pillondebuglib.a
Normal file
BIN
lib/p4pillondebuglib.lib
Normal file
BIN
lib/p4pillondebuglib.o
Normal file
BIN
lib/p4pillondebuglib.obj
Normal file
BIN
lib/ssvw64.exp
Normal file
36
make.bat
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
@echo off
|
||||||
|
rem Set variables
|
||||||
|
set SRC_DIR=src
|
||||||
|
set LIB_DIR=lib
|
||||||
|
|
||||||
|
rem Create the %LIB_DIR% directory if it does not exist
|
||||||
|
if not exist %LIB_DIR% mkdir %LIB_DIR%
|
||||||
|
|
||||||
|
if "%1"=="/clean" (
|
||||||
|
goto clean
|
||||||
|
)
|
||||||
|
|
||||||
|
rem Configure the environment for Visual Studio
|
||||||
|
call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
|
||||||
|
|
||||||
|
rem Build %SRC_DIR%\*.c files
|
||||||
|
cl /c /Fd:%LIB_DIR%\ /Fo:%LIB_DIR%\ /Iinclude\ /I%SRC_DIR%\ %SRC_DIR%\*.c
|
||||||
|
|
||||||
|
rem Link the object files into a static library
|
||||||
|
lib %LIB_DIR%\*.obj
|
||||||
|
|
||||||
|
rem Create a ssvw64.lib file from a ssvw64.def file
|
||||||
|
lib /def:%SRC_DIR%\ssvw64.def /out:%LIB_DIR%\ssvw64.lib /machine:x64
|
||||||
|
|
||||||
|
rem Build complete
|
||||||
|
pause
|
||||||
|
exit /b 0
|
||||||
|
|
||||||
|
:clean
|
||||||
|
del %LIB_DIR%\*.obj
|
||||||
|
del %LIB_DIR%\*.lib
|
||||||
|
del %LIB_DIR%\*.exp
|
||||||
|
|
||||||
|
rem Clean complete
|
||||||
|
pause
|
||||||
|
exit /b 0
|
32
makefile
Normal file
@ -0,0 +1,32 @@
|
|||||||
|
# Detect the operating system
|
||||||
|
ifeq ($(OS),Windows_NT)
|
||||||
|
MKDIR = if not exist $(LIB_DIR) mkdir $(LIB_DIR)
|
||||||
|
RM = del
|
||||||
|
else
|
||||||
|
MKDIR = mkdir -p $(LIB_DIR)
|
||||||
|
RM = rm -f
|
||||||
|
endif
|
||||||
|
|
||||||
|
CC = gcc
|
||||||
|
AR = ar
|
||||||
|
CFLAGS = -Wall -fPIC
|
||||||
|
SRC_DIR = src
|
||||||
|
LIB_DIR = lib
|
||||||
|
SRC_FILES = $(wildcard $(SRC_DIR)/*.c)
|
||||||
|
OBJ_FILES = $(SRC_FILES:$(SRC_DIR)/%.c=$(LIB_DIR)/%.o)
|
||||||
|
STATIC_LIB = $(LIB_DIR)/libp4pillondebuglib.a
|
||||||
|
|
||||||
|
all: $(STATIC_LIB)
|
||||||
|
|
||||||
|
$(STATIC_LIB): $(OBJ_FILES)
|
||||||
|
$(MKDIR)
|
||||||
|
$(AR) rcs $@ $^
|
||||||
|
|
||||||
|
$(LIB_DIR)/%.o: $(SRC_DIR)/%.c
|
||||||
|
$(MKDIR)
|
||||||
|
$(CC) $(CFLAGS) -c $< -o $@
|
||||||
|
|
||||||
|
clean:
|
||||||
|
$(RM) $(OBJ_FILES) $(STATIC_LIB)
|
||||||
|
|
||||||
|
.PHONY: all clean
|
@ -1,24 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "migration"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2021"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "migration"
|
|
||||||
path = "src/lib.rs"
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
async-std = { version = "1", features = ["attributes", "tokio1"] }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
sea-orm-cli.workspace = true
|
|
||||||
|
|
||||||
[dependencies.sea-orm-migration]
|
|
||||||
version = "1.0.0"
|
|
||||||
features = [
|
|
||||||
# `ASYNC_RUNTIME` and `DATABASE_DRIVER` are required to run migration using the cli
|
|
||||||
# They must be the same as the features in the `sea-orm` dependency in the `app` crate
|
|
||||||
"sqlx-sqlite", # `DATABASE_DRIVER` feature
|
|
||||||
"runtime-tokio-rustls", # `ASYNC_RUNTIME` feature
|
|
||||||
]
|
|
@ -1,41 +0,0 @@
|
|||||||
# Running Migrator CLI
|
|
||||||
|
|
||||||
- Generate a new migration file
|
|
||||||
```sh
|
|
||||||
cargo run -- generate MIGRATION_NAME
|
|
||||||
```
|
|
||||||
- Apply all pending migrations
|
|
||||||
```sh
|
|
||||||
cargo run
|
|
||||||
```
|
|
||||||
```sh
|
|
||||||
cargo run -- up
|
|
||||||
```
|
|
||||||
- Apply first 10 pending migrations
|
|
||||||
```sh
|
|
||||||
cargo run -- up -n 10
|
|
||||||
```
|
|
||||||
- Rollback last applied migrations
|
|
||||||
```sh
|
|
||||||
cargo run -- down
|
|
||||||
```
|
|
||||||
- Rollback last 10 applied migrations
|
|
||||||
```sh
|
|
||||||
cargo run -- down -n 10
|
|
||||||
```
|
|
||||||
- Drop all tables from the database, then reapply all migrations
|
|
||||||
```sh
|
|
||||||
cargo run -- fresh
|
|
||||||
```
|
|
||||||
- Rollback all applied migrations, then reapply all migrations
|
|
||||||
```sh
|
|
||||||
cargo run -- refresh
|
|
||||||
```
|
|
||||||
- Rollback all applied migrations
|
|
||||||
```sh
|
|
||||||
cargo run -- reset
|
|
||||||
```
|
|
||||||
- Check the status of all migrations
|
|
||||||
```sh
|
|
||||||
cargo run -- status
|
|
||||||
```
|
|
@ -1,12 +0,0 @@
|
|||||||
pub use sea_orm_migration::prelude::*;
|
|
||||||
|
|
||||||
mod m20220101_000001_create_debug_table;
|
|
||||||
|
|
||||||
pub struct Migrator;
|
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
|
||||||
impl MigratorTrait for Migrator {
|
|
||||||
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
|
||||||
vec![Box::new(m20220101_000001_create_debug_table::Migration)]
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,35 +0,0 @@
|
|||||||
use sea_orm_migration::{prelude::*, schema::*};
|
|
||||||
|
|
||||||
#[derive(DeriveMigrationName)]
|
|
||||||
pub struct Migration;
|
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
|
||||||
impl MigrationTrait for Migration {
|
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.create_table(
|
|
||||||
Table::create()
|
|
||||||
.table(Debug::Table)
|
|
||||||
.if_not_exists()
|
|
||||||
.col(pk_auto(Debug::Id))
|
|
||||||
.col(string(Debug::Title))
|
|
||||||
.col(string(Debug::Text))
|
|
||||||
.to_owned(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.drop_table(Table::drop().table(Debug::Table).to_owned())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(DeriveIden)]
|
|
||||||
enum Debug {
|
|
||||||
Table,
|
|
||||||
Id,
|
|
||||||
Title,
|
|
||||||
Text,
|
|
||||||
}
|
|
@ -1,6 +0,0 @@
|
|||||||
use sea_orm_migration::prelude::*;
|
|
||||||
|
|
||||||
#[async_std::main]
|
|
||||||
async fn main() {
|
|
||||||
cli::run_cli(migration::Migrator).await;
|
|
||||||
}
|
|
@ -1,26 +0,0 @@
|
|||||||
@echo off
|
|
||||||
rem Set variables
|
|
||||||
set LIB_DIR=crates/sesam-vitale/lib
|
|
||||||
set DEF_DIR=crates/sesam-vitale/src/win/fsv
|
|
||||||
|
|
||||||
if "%1"=="/clean" (
|
|
||||||
goto clean
|
|
||||||
)
|
|
||||||
|
|
||||||
rem Set the environment for the x64 platform
|
|
||||||
call "C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvarsall.bat" x64
|
|
||||||
|
|
||||||
rem Create a ssvw64.lib file from the ssvw64.def file
|
|
||||||
lib /def:ssvw64.def /out:%LIB_DIR%\ssvw64.lib /machine:x64
|
|
||||||
|
|
||||||
rem Build complete
|
|
||||||
pause
|
|
||||||
exit /b 0
|
|
||||||
|
|
||||||
:clean
|
|
||||||
del %LIB_DIR%\*.lib
|
|
||||||
del %LIB_DIR%\*.exp
|
|
||||||
|
|
||||||
rem Clean complete
|
|
||||||
pause
|
|
||||||
exit /b 0
|
|