minimal documentation for development, api format and reference

* set editor config and geany project configuration
* closes https://codeberg.org/minenux/minenux-skindb-webdb/issues/2
* closes https://codeberg.org/minetest-stuffs/minetest-skindb-skindata/issues/1
main
mckaygerhard 2024-04-09 16:11:35 -04:00
parent be6445a6ae
commit 33847e2759
7 changed files with 407 additions and 312 deletions

View File

@ -6,7 +6,7 @@ root = true
indent_style = space
indent_size = 4
charset = utf-8
trim_trailing_whitespace = true
trim_trailing_whitespace = false
insert_final_newline = true
end_of_line = lf
max_line_length = off
@ -14,8 +14,5 @@ max_line_length = off
[*.md]
indent_size = false
[*.ini]
indent_size = 4
[*.sql]
indent_size = 4
indent_size = 2

View File

@ -1,216 +1,220 @@
# skindb/api/reference
# skindb-webdb API reference
## message format
Is based on now defunct skin database (http://minetest.fensta.bplaced.net),
that will be now at https://skindb.sourceforge.io/ but modernized!
The API os skindb is based on two artifacts:
* the "data api" defines the communication format for the data
* and "skin format" that defines the nature of data files to use
## player skin data api
For api, skin is a couple of two parts, one is the png skin texture file and
the other is the metadata information file.
The api will show the information of each skin in json format, each line of the
metadata information file and a last line with base64 skin dump.
#### api request format
* Old way, php site `/api/v2/get.json.php?getlist&page=%i&outformat=base64&per_page=%p` with `%i` as number page
* New way, astro site `/api/v1/content?client=mod&page=%i` with `%i` as number page, only base64 output
File public assets
* preview asset `/skins/%i/%r.png` with `%i` as id skin and `%r` as ramdom generation number
#### api message format
```
{
"sucess": true, //boolean
"message": "server message", //a message from the server
"page": 1, //curent page you are on
"pages": 18, //max number of pages
"per_page": 20, //how many results are per page
"skins": [ //array containing skin items
{ //skin item
"id": Int, // same id as original api, new ones has new format
"name": "String", // alpha numeric only
"author": "String", // alpha numeric only
"license": "String",
"type": "String",
"img": "String" //base64 encoded image content string
"sucess": true, // boolean : true | false
"message": "server message", // string(32) : a message from the server
"page": 1, // integer : curent page of result, 0 on errors
"pages": 18, // integer : max number of pages
"per_page": 10, // integer : how many results are per page
"skins": [ // array : data of the results, skin items on normal operation
{
"id": Int, // integer : same id as original api, new ones has new format
"name": "String", // string(16) : alpha numeric only
"author": "String", // string(16) : alpha numeric only
"license": "String", // string(16) : SPDX licence identifier as https://spdx.org/licenses/
"type": "String", // format of the data, if skin, image/png, either just binary
"img": "String" // base64 : encoded image content string of skin player, png file
}
]
}
```
## use cases
## player skin format
| flujo | tarea | caso de uso / actor | ANON USER | AUTH USER |
The two files of skin are one png and one txt, the txt format depends on api site,
the png is describes in next section.
* The metadata file correspond of the `name`, `author`, `license` fields of json data
* The skin image file correspond of the `img` field of json data
#### filename meta txt
The defunct skin database (http://minetest.fensta.bplaced.net), uses the
a unique format, each line is as of `key = "string",` with a comma at the end.
if no value is given will be `unknow+<id>` and for license will be `CC-BY-NC-3.0`
* filename must match the file skin png file
* filename must start with "character" string
* filename format must be `character_<id>.txt`
* filename skin must be `../textures/character_<id>.png`
* file contents must be as:
* name : must be alphanumeric
* author : must be alphanumeric
* description : must be alphanumeric and maximun of 46 chars
* comment : must be alphanumeric and maximun of 46 chars
* license : must be alphanumeric and format must be as https://spdx.org/licenses/
```
name = "<name>",
author = "<author>",
description = "<description>",
comment = "<comment>",
license = "<SPDX licence identifier>",
```
#### filename meta new
New sites simplifies the meta file with only lines to parse, this
format manage each line is as of `key` directly without a comma at the end
* filename must match the file skin png file
* filename must start with "character" string
* filename format must be `character_<id>.txt`
* **BUT filename skin is `character.<id>.png`**
* file contents must be as:
* line 1 : must be alphanumeric ans is assumed as the skin name only
* line 2 : must be alphanumeric and is assumed as the skin author only
* line 3 : must be alphanumeric and format must be as https://spdx.org/licenses/
```
<name>
<author>
<SPDX licence identifier>,
```
#### png texture character
The file follow the format of the template description provided by
AntumDeluge at the https://opengameart.org/content/minetest-character-template
![template_colormap.png](template_colormap.png)
![template.png](template.png)
In future api can implement a way to check this file!
## API use cases
| workf | issue | use case api refers | ANON USER | AUTH USER |
| ----- | ----- | ------------------- | --------- | ---------- |
| 1. | #4 | login | x | |
| 2. | #8 | load skin | x | x |
| 3. | #5 | list skin | x | x |
| 6. | #6 | mark skin | | x |
| 7. | #7 | delete skin | | x |
| 1. | #5 | list skin | x | x |
| 2. | #4 | login | x | |
| 3. | #8 | load skin | x | x |
| 4. | #6 | mark skin | | x |
| 5. | #7 | delete skin | | x |
### login
### api key
##### Condiciones y flujo
The api can receive a key used to retrieve much more data, if there is no apikey
then only 10 items will be offered by the api, so means that parameters
to have specific amount of items of skins will be ignored if no api key present.
* 1 send POST parameters
- `username` : REQUERIDO : usuario entre 6 y 20 caracters alfanumericos
- `userpass` : REQUERIDO : contraseña entre 6 y 20 caracteres alfanumericos
- `userkey` : REQUERIDO : palabra de 40 caracteres alfanumerica
* 2 check DB api parameters
### list skin
##### Post condiciones
List all skins or filtered skins, this is the default operation and the normal usage for non api key users.
* 3 response sucess
- mensaje json de datos correctos y permisos de usuarios
CAll `/api/v1/list.php?getlist&outformat=base64&page=1`
##### Pre condiciones
- anonimous user
- apikey present as optional
- OPTIONAL #4 [login](#login)
- only one ip can be at the same time per session per user, to avoid conflicts on git filesystem
1. if no filters are show, all the skins will be returned
2. if error happened, the result will be show in message key
3. if apikey is given, user can retrieve all skins at the same time
4. if apikey is missing only 10 skins per page are can retrieve at the same time
- parameters GET or POST
- `per_page` : OPTIONAL : integer - amount of skins/data items returned in json data/skin
- `page` : OPTIONAL : integer - the current page of the items to retrieve
- `apikey` : OPTIONAL : string - alphanumeric 64 chars key for api
##### workflow
* 1 get optional POST parameters
- `name` : OPTIONAL : String : skin name as filter, of the skin player, 12 chars maximun
- `author` : OPIONAL : String : skin author as filter, is `username` like, 12 chars maximun
- `description` : OPTIONAL : String : long details of the skin made, 64 chars maximun
- `comment` : OPTIONAL : String : short details of the skin made, 32 chars maximun
- `license` : OPTIONAL : String : SPDX licence identifier as https://spdx.org/licenses/
- `skin` : OPTIONAL : String : name of file as filter
- `apikey` : OPTIONAL : String
* 2 check and validations, then
- search the metadata file as [player skin format](#player-skin-format), use the cache in sqlite database
##### good workflow
* 3 response
- mensaje
- if no api key, message will be "skins found, only 10 results per page, no api key present"
- you must count al the json id found and report as numbered results found
```
{
"sucess": true,
"message": "auth success"
}
```
##### Flujos Alternativos
* 2 response fails
- mensaje json de datos incorrectos session invalida
```
{
"sucess": false,
"message": "auth fail"
"data": [
"message": "skins found",
"page": 1,
"pages": 2,
"per_page": 10,
"skins": [
{
".. invalid api key"
"id": Int,
"name": "String",
"author": "String",
"license": "String",
"type": "String",
"img": "String",
"comment": "String"
}
{
"id": Int,
"name": "String",
"author": "String",
"license": "String",
"type": "String",
"img": "String",
"comment": "String"
}
]
}
```
### load skin
##### Pre conditions
##### failed workflow
- #8 [login](#login)
* 3 failed response
- mensaje json skind data
- count al the json id found and report as numbered results found
- miessage will show any error or no skins found
##### Condiciones y flujo
* 1 el API recibe los parametros POST
- `rif_agente` : REQUERIDO : rif del comprador
- `rif_sujeto` : OPCIONAL : rif del vendedor
- `num_skin ` : OPCIONAL/REQUERIDO : si hay rif de vendedor, es requerido, es el numero de factura
- `num_control` : OPCIONAL/REQUERIDO : si hay rif de vendedor, requerido, es numero caja o numero linea MH
- `fecha_skin ` : REQUERIDO : fecha de la factura/nota indicada en el skin
- `fecha_compra` : OPCIONAL : se pone a la fecha actual (de no venir) o maximo DIASCARGA atras
- `monto_skin ` : REQUERIDO : base imponible monto total todo el skin , solo positivos sin cero
- `monto_excento` : REQUERIDO : monto de la compra que no se le aplica ningun impuesto, solo positivos incluye cero
- `tipo_skin ` : REQUERIDO : factura o nota
- `adjunto_skin ` : REQUERIDO : el skin de la factura o nota escaneado
* 2 El API valida los datos: PROCESA LOS DATOS
- el api guarda en base de datos los datos y tambien el skin en base64
- el api tambien guarda el skin en el sistema de archivos, tabla anual
- la ruta en el sistema de archivos es separada directorios por años
- mensaje json de el id del skin YYYYMMDDHHmmss, mensaje archivo subido correctamente
##### Post condiciones
* 3 El API valida los datos: RESPUESTA detalle del skin cargado
- mensaje json de la clasificacion de el skin y ruta del archivo adjuntado
- la respuesta de [CAso de uso #7 : detalle skin ]()
##### Flujos Alternativos
* 2 El API valida los datos: RESPUESTA error en el proceso
- mensaje json de datos correctos y el error del sistema si no puedo guardar o paso algo
* 3 El API valida los datos: RESPUESTA datos incompletos o incorrectos
- mensaje json de datos correctos y los campos que tienen los datos incorrectos
### Caso de Uso listar skin s
Listar resumido los skin s o documentos cargados en el sistema segun criterios de filtrado o busqueda
- Actores Principales COMPRADOR, GASTOS, CONTABILIDAD
- Actor Secundario: Base de datos, API receiptsapi
##### Pre condiciones
- #5 [Caso de uso iniciar sesion](#caso-de-uso-iniciar-sesión)
esta se verifica desde las cabeceras junto con su clave.
- DIASCARGA : cantidad de dias permitido para load skin s
##### Condiciones y flujo
* 1 el API recibe los parametros GET, solo llama el punto de entrada
- `rif_agente` : OPCIONAL : rif del comprador
- `rif_sujeto` : OPCIONAL : rif del vendedor
- `num_skin ` : OPCIONAL : numero de factura o nota de skin
- `num_control` : OPCIONAL : numero caja o numero linea MH
- `fecha_skin ` : OPCIONAL : fecha de la factura/nota indicada en el skin
- `fecha_compra` : OPCIONAL : se pone a la fecha actual (de no venir) o maximo DIASCARGA atras
- `monto_factura` : OPCIONAL : total toda la factura, solo positivos sin cero
- `tipo_skin ` : OPCIONAL : factura o nota
##### Post condiciones
* 2 El API lista paginado la primera pagina y en ella los ultimos 100 skin s segun los criterios filtrados
- Si el actor es COMPRADOR, solo se listan sus skin s, Caso contrario se listan todos los skin s
- mensaje json de exito segun el actor en sesion
- listado con estas colunmas:
- `cod_skin ` : mostrar : YYYYMMDDHHMMSS
- `rif_agente` : mostrar
- `rif_sujeto` : mostrar si existe sino vacio
- `fecha_compra` : mostrar, formato YYYYMMDD
- `monto_skin ` : mostrar o 0, si cero mostrar "error" al lado
##### Flujos Alternativos
* 2 El API no muestra skin s si no los hay o no pertenecen al actor GASTOS o CONTABILIDAD
- mensaje json con el estado en error y el mensaje
- devuelve una linea enla primera pagina todos los mismos campos pero con valores en 0 o vacios
* 2 El API no muestra skin s si los existentes son mas de un año o no pertenecen al actor GASTOS o CONTABILIDAD
- mensaje json con el estado en error y el mensaje que no se han realizado cargas recientes
- devuelve una linea enla primera pagina todos los mismos campos pero con valores en 0 o vacios
Realizar el cuarto punto de entrada del api:
### Caso de Uso detalle skin
Detalle completo de un skin o documento en el sistema ya cargado este anulado o no, tenga mas de un año o no!
- Actores Principales COMPRADOR, GASTOS, CONTABILIDAD
- Actor Secundario: Base de datos, API receiptsapi
##### Pre condiciones
- #5 [Caso de uso iniciar sesion](#caso-de-uso-iniciar-sesión)
esta se verifica desde las cabeceras junto con su clave.
- COMPRADOR: se mostrara el skin si este lo cargo dicho usuario
- GASTOS/CONTABILIDAD: puede ver cualquier skin
##### Condiciones y flujo
* 1 el API recibe los parametros GET, solo llama el punto de entrada
- `cod_skin ` : REQUERIDO : id de skin YYYYMMDDHHMMSS
##### Post condiciones
* 2 El API lista paginado la primera pagina y en ella EL DETALLE del skin segun el codigo de id dado
- Si el actor es COMPRADOR, solo se listan sus skin s, Caso contrario se listan todos los skin s
- mensaje json de exito segun el actor en sesion
- listado con estas colunmas:
- `cod_skin ` : mostrar : YYYYMMDDHHMMSS
- `rif_agente` : mostrar
- `rif_sujeto` : mostrar si existe sino vacio
- `num_skin ` : mostrar siempre
- `num_control` : mostrar si existe sino vacio
- `fecha_skin ` : mostrar, formato YYYYMMDD
- `fecha_compra` : mostrar, formato YYYYMMDD
- `monto_skin ` : mostrar o 0, si cero mostrar "error" al lado
- `monto_excento` : mostrar o 0
- `tipo_skin ` : FACTURA/NOTA
- `adjunto_skin ` :
- ruta en sistema de archivo, el api debe verificar si existe, ruta publica del server
- caso contrario usa el guardado en la DB base64 y lo vuelve colocar en el sistema de ficheros
##### Flujos Alternativos
* 2 El API no muestra skin s porque no existe el id
- mensaje json con el estado en error y el mensaje, EL ID skin NO EXISTE EN EL SISTEMA
- devuelve una linea enla primera pagina todos los mismos campos pero con valores en 0 o vacios
* 2 El API no muestra skin s porque el skin no le pertenece
- mensaje json con el estado en error y el mensaje, EL ID skin NO LE PERTENECE
- devuelve una linea enla primera pagina todos los mismos campos pero con valores en 0 o vacios
* 2 El API no muestra skin s porque el parametro es incorrecto o hay un problema en la db
- mensaje json con el estado en error y el mensaje, ERROR INTERNO O PARAMETRO INCORRECTO
- devuelve una linea enla primera pagina todos los mismos campos pero con valores en 0 o vacios
```
{
"sucess": false,
"message": "no skins found",
"page": 1,
"pages": 0,
"per_page": 10,
"skins": []
}
```

View File

@ -1,72 +1,44 @@
## Skindb development
Quick setup: [README.md](README.md)
### WORKFLOW
Contributor must know how to work with git, and also git-flow,
with GitFlow Simplified , contributor must create an extra development branch!
https://medium.com/goodtogoat/simplified-git-flow-5dc37ba76ea8
The developer, just fork with https://codeberg.org/repo/fork/204481 and
clones the repository to creates the extra development branch, he starts
working on it to later send git merge request to upstream.
### Prerequisites
* you must have your user as `/home/general`
* you must have `Devel` subpath for development as then `/home/general/Devel`
* you must not work as root never!
* you must not work as root! never! and we do not use `sudo` !
* all files must have LF as new line and good identation
* api is developed with PHP and CSS with only JS usage for dynamic things!
* our prefered IDE/editor is Geany! we support non big open source projects too!
### Formato de api request
### Framework
* Old way, php site `/api/v2/get.json.php?getlist&page=%i&outformat=base64` with `%i` as number page
* New way, astro site `/api/v1/content?client=mod&page=%i` with `%i` as number page, only base64 output
The base is made in GUACHI based framework https://gitlab.com/guachi/Guachi_Framework
but reduced as "miniapi" and only handles database and routing.
File public assets
Any JS and/or CSS must be used directly without any network dependant
tool neither remote based development tool, the development must be
fully local and cannot depends of external things.
* preview asset `/skins/1/%i.png` with `%i` as id skin
Our eyecandy framework is based on Bulma https://github.com/jgthms/bulma?tab=readme-ov-file
### Formato de api response
### Full API documentation
```
{
"sucess": true,
"message": "message",
"page": 1,
"pages": 18,
"per_page": 20,
"skins": [
{
"id": Int,
"name": "String",
"author": "String",
"license": "String",
"type": "String",
"img": "String",
"url": "string"
},
...
]
}
```
Please referes to [API.md](API.md) for all the skin api documentation, before
start to develop.
### Formato de metadata skins
* name : string | alphanumeric
* author : string | alphanumeric
* comment : string | alphanumeric, used in the old api for licensing
* license : string | https://spdx.org/licenses/ identifier
```
name = "Sam 0",
author = "Jordach",
comment = "CC BY-SA 3.0",
```
New format uses same order and types but removes the string of titles like `name`:
```
Sam 0
Jordach
CC BY-SA 3.0
```
Fourth line will be the new comment
### FLUJO DE SISTEMA
Simple request response .. con login para subir
### BASE DE DATOS
### DATABASE
Se intentara omitir la carga hacia DB, usando los archivos de metadatos de los skins
y la carga directamente en el git.

View File

@ -35,7 +35,10 @@ cd $HOME/Devel/minenux-skindb-webdb
## How to Deploy and develop
Start geany an browse the `Devel/minenux-skindb-webdb` directory for `skindb-webdb` proyect file!
Start geany an browse the `Devel/minenux-skindb-webdb` directory , look
for `skindb-webdb` proyect file, load into Geany!
Then read the [DEVEL.md](DEVEL.md) for some specific details.
#### Requisitos
@ -46,71 +49,6 @@ Start geany an browse the `Devel/minenux-skindb-webdb` directory for `skindb-web
* database
* sqlite3 / perconadb 5.7+
#### Despliegue
El servicio levantara en `localhost/minenux-skindb-webdb`, sin configuraciones al no ser
una plataforma "domain driven", pero las implementaciones a estas
deberan trabajar con CORS, por lo que el despliege para desarrollo
sera con vesel remoto o en su defecto simple pull en una copia git `git pull origin develop`
#### Desarrollo
Con **GitFlow simplificado**, esta una rama de desarrollo `develop` predeterminada,
y se realiza como la rama "principal" de inmediato (aqui `develop`).
La rama de preproducción es `main`, ambas ramas son protegidas
nadie puede hacer merge sin revision, y todos los merge son squases,
evitando mensajes vanales.
Cada merge debe cerrar uno o mas issue tipo Meta/Casos, ya que el proyecto
se basa en alcances. Este tipo de flujo se emplea en equipos pequeños sin
necesidad de conocimientos git, ya que ellos trabajan juntos en una "rama trabajo"
por cada tarea asignada. Esto no sirve para grupos grandes.
https://medium.com/goodtogoat/simplified-git-flow-5dc37ba76ea8
El desarrollador clona el repositorio y crea una rama, esta
la empieza a trabajar pero cada dia debe realizar un `git pull origin develop`
hacia la rama trabajada.
#### Casos de uso
Deben de cumplirse todos en cada rama de etapa de proyecto, use el dashboard de los issues!
Estos describen que se quiere y como deben cumplirse
#### Estructura del repositorio
TODO
- [ ] authentication system
- [ ] user roles and crud for admins
- [ ] debug error handler
- [ ] api documentation system
- [ ] proyect documentation system
#### Convenciones de codigo
El proyecto contiene una interfaz no usable, pero que encaminan
dos ejemplos de como construir el api:
- [ ] public upload example (Usar esto como ejemplo)
- [ ] local upload example : (usar esto como ejemplo)
Cada commit debe especificar que archivo modifica y
al menos en que funcionalidad se esta trabajando, de al menos 1 linea
de mas de 30 caracteres explicito.
TODO
#### pruebas de despliegue y documentacion
TODO
#### rutas definidas default api
TODO
## LICENSE
The Guachi Framework is open-source software under the MIT License, this downstream part is a reduced version for!

152
docs/TODO.md Normal file
View File

@ -0,0 +1,152 @@
# skindb-webdb API reference
Is based on now defunct skin database (http://minetest.fensta.bplaced.net),
that will be now at https://skindb.sourceforge.io/
This documents the proposals, may change or not to be made
### login
This case is still in proposal, cos we are thinking to use git only
#### pre conditions
* 1 send POST parameters
- `username` : REQUIRED : github/codeberg/gitlab it depends
- `userpass` : REQUIRED : contraseña entre 6 y 20 caracteres alfanumericos
- `userkey` : REQUIRED : palabra de 60 caracteres alfanumerica
##### workflow
* 2 check DB api parameters, the database is sqlite
##### good workflow
* 3 response sucess
- mensaje json user data
- id : internal id of the user
- name : human name if any
- username : must match the POST username
- userkey : must match the POST userkey, this is the api key
- type : 0 or 1, 1 is admin user
- apikey : same as userkey
```
{
"sucess": true,
"message": "auth success"
"data": [
{
"id": Int,
"name": "String",
"username": "String",
"userkey": "String",
"type": Int,
"apikey": "String"
}
]
}
```
* NOTE only one ip can be at the same time per session per user, to avoid conflicts in git filesystem
##### failed workflow
* 2 response fails
- mensaje json de datos incorrectos session invalida
```
{
"sucess": false,
"message": "auth fail"
"data": [
{
".. invalid api key"
}
]
}
```
### load skin
This case is still in proposal, cos we are thinking to use git only
##### Pre conditions
- #4 [login](#login)
- only one ip can be at the same time per session per user, to avoid conflicts on git filesystem
* 1 send POST parameters with data
- `name` : REQUIRED : String : skin name, of the skin player, 12 chars maximun
- `author` : REQUIRED : String : auto filled with `username` session, 12 chars maximun
- `description` : OPTIONAL : String : long details of the skin made, 64 chars maximun
- `comment` : OPTIONAL : String : short details of the skin made, 32 chars maximun
- `license` : REQUEIRED : String : SPDX licence identifier as https://spdx.org/licenses/
- `skin` : REQUIRED : Base64 : png file
- `apikey` : REQUIRED : string - alphanumeric 64 chars key for api
- `username` : REQUIRED : user session if login
##### workflow
* 2 check and validations, then
- create the metadata file as [player skin format](#player-skin-format)
- decode base64 png file and dump into temp filesystem
##### good workflow
* 3 create id skin and store into git
- create new id format YYYYMMDDHHmmss
- save the metadata file into filesystem git submodule as in [data files](#data-files)
- save the png dump file into filesystem git submodule as in [data files](#data-files)
- save the metadata into sqlite database for cache search as in [data files](#data-files)
- schedule commit to the git filesystem
* 4 Response
```
{
"sucess": true,
"message": "skin stored",
"page": 1,
"pages": 1,
"per_page": 10,
"skins": [
{
"id": Int,
"name": "String",
"author": "String",
"license": "String",
"type": "String",
"img": "String",
"comment": "String"
}
]
}
```
##### failed workflow
* 3 failed response
```
{
"sucess": false,
"message": "skin error data",
"page": 1,
"pages": 1,
"per_page": 10,
"skins": [
{
"id": Int,
"name": "String",
"author": "String",
"license": "String",
"type": "String",
"img": "String",
"comment": "String"
}
]
}
```

32
skindb-webdb.geany Normal file
View File

@ -0,0 +1,32 @@
[editor]
line_wrapping=false
line_break_column=80
auto_continue_multiline=true
[file_prefs]
final_new_line=true
ensure_convert_new_lines=true
strip_trailing_spaces=false
replace_tabs=true
[indentation]
indent_width=4
indent_type=0
indent_hard_tab_width=4
detect_indent=false
detect_indent_width=false
indent_mode=1
[project]
name=skindb-webdb
base_path=/home/general/Devel/minenux-skindb-webdb/
[long line marker]
long_line_behaviour=2
long_line_column=76
[files]
current_page=0
[VTE]
last_dir=/home/general/Devel/minenux-skindb-webdb/

0
skindb.sqlite Normal file
View File