Skip to content

πŸ“š The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

Fix typo with resources

Smaug67396547e164b28d
diff --git a/backend/controllers/README.md b/backend/controllers/README.md
index 6b892ac6..e8f818ef 100644
--- a/backend/controllers/README.md
+++ b/backend/controllers/README.md
@@ -51,7 +51,7 @@ type Controller struct {
- **`users.controller.go`** - User profile management, updates
- **`nodes.controller.go`** - Document/note CRUD operations
- **`permissions.controller.go`** - Access control management
-- **`ressources.controller.go`** - File upload and media handling
+- **`resources.controller.go`** - File upload and media handling
## Usage Example
@@ -190,12 +190,12 @@ Example test structure:
func TestGetNodeById(t *testing.T) {
app := fiber.New()
controller := NewController(testApp)
-
+
app.Get("/nodes/:id", controller.GetNodeById)
-
+
req := httptest.NewRequest("GET", "/nodes/123", nil)
resp, err := app.Test(req)
-
+
assert.NoError(t, err)
assert.Equal(t, 200, resp.StatusCode)
}
diff --git a/backend/controllers/ressources.controller.go b/backend/controllers/resources.controller.go
similarity index 89%
rename from backend/controllers/ressources.controller.go
rename to backend/controllers/resources.controller.go
index 7582eaf7..72cad691 100644
--- a/backend/controllers/ressources.controller.go
+++ b/backend/controllers/resources.controller.go
@@ -11,13 +11,13 @@ import (
"github.com/gin-gonic/gin"
)
-type RessourceController interface {
+type ResourceController interface {
GetBackup(c *gin.Context) (int, any)
UploadFile(c *gin.Context) (int, any)
UploadAvatar(c *gin.Context) (int, any)
}
-func NewRessourceController(app *app.App) RessourceController {
+func NewResourceController(app *app.App) ResourceController {
return &Controller{
app: app,
authorizer: permissions.NewAuthorizer(app.Repos.Permission),
@@ -30,7 +30,7 @@ func (ctr *Controller) GetBackup(c *gin.Context) (int, any) {
return http.StatusBadRequest, err
}
- link, err := ctr.app.Services.Ressource.CreateBackup(userId, ctr.app.MinioClient)
+ link, err := ctr.app.Services.Resource.CreateBackup(userId, ctr.app.MinioClient)
if err != nil {
return http.StatusInternalServerError, err
}
@@ -62,7 +62,7 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
}
mimeType := header.Header.Get("Content-Type")
- node, err := ctr.app.Services.Ressource.UploadFile(
+ node, err := ctr.app.Services.Resource.UploadFile(
header.Filename,
header.Size,
fileContent,
@@ -104,7 +104,7 @@ func (ctr *Controller) UploadAvatar(c *gin.Context) (int, any) {
}
mimeType := header.Header.Get("Content-Type")
- err = ctr.app.Services.Ressource.UploadAvatar(
+ err = ctr.app.Services.Resource.UploadAvatar(
header.Filename,
header.Size,
fileContent,
diff --git a/backend/repositories/README.md b/backend/repositories/README.md
index 92dd70a4..0824895a 100644
--- a/backend/repositories/README.md
+++ b/backend/repositories/README.md
@@ -216,7 +216,7 @@ class nodes {
varchar(50) name
varchar(255) description
varchar(200) tags
- tinyint role /* 1=workspace, 2=category, 3=document, 4=ressource */
+ tinyint role /* 1=workspace, 2=category, 3=document, 4=resource */
int color
text icon
text thumbnail
diff --git a/backend/router/routes/ressources.go b/backend/router/routes/ressources.go
index 7ca8163e..a515d794 100644
--- a/backend/router/routes/ressources.go
+++ b/backend/router/routes/ressources.go
@@ -10,11 +10,11 @@ import (
)
func Uploads(app *app.App, router *gin.RouterGroup) {
- ressources := router.Group("/ressources")
- ressourcesCtrl := controllers.NewRessourceController(app)
+ resources := router.Group("/resources")
+ resourcesCtrl := controllers.NewResourceController(app)
- ressources.Use(middlewares.Auth())
- ressources.GET(("/backup"), utils.WP(ressourcesCtrl.GetBackup))
- ressources.POST("", utils.WP(ressourcesCtrl.UploadFile))
- ressources.POST("/avatar", utils.WP(ressourcesCtrl.UploadAvatar))
+ resources.Use(middlewares.Auth())
+ resources.GET(("/backup"), utils.WP(resourcesCtrl.GetBackup))
+ resources.POST("", utils.WP(resourcesCtrl.UploadFile))
+ resources.POST("/avatar", utils.WP(resourcesCtrl.UploadAvatar))
}
diff --git a/backend/services/README.md b/backend/services/README.md
index 3f8d0337..30ff8b42 100644
--- a/backend/services/README.md
+++ b/backend/services/README.md
@@ -49,7 +49,7 @@ if err != nil {
- **`session.service.go`** - User session lifecycle management
- **`log.service.go`** - Activity and connection logging
- **`minio.service.go`** - Object storage operations
-- **`ressource.service.go`** - File and media management
+- **`resource.service.go`** - File and media management
## Usage Example
diff --git a/backend/services/manager.go b/backend/services/manager.go
index 230d3e1a..2e318592 100644
--- a/backend/services/manager.go
+++ b/backend/services/manager.go
@@ -18,7 +18,7 @@ type ServiceManager struct {
Log LogService
Session SessionService
Minio MinioService
- Ressource RessourceService
+ Resource ResourceService
initialized bool
}
@@ -58,8 +58,8 @@ func (sm *ServiceManager) initializeServices(repos *repositories.RepositoryManag
// Initialize Session Service
sm.Session = NewSessionService(repos.Session)
- // Initialize Ressource Service
- sm.Ressource = NewRessourceService(repos.Node, snowflake)
+ // Initialize Resource Service
+ sm.Resource = NewResourceService(repos.Node, snowflake)
return nil
}
diff --git a/backend/services/ressource.service.go b/backend/services/resource.service.go
similarity index 82%
rename from backend/services/ressource.service.go
rename to backend/services/resource.service.go
index f5ba1e75..7ebe4e68 100644
--- a/backend/services/ressource.service.go
+++ b/backend/services/resource.service.go
@@ -19,25 +19,25 @@ import (
"github.com/minio/minio-go/v7"
)
-type RessourceService interface {
+type ResourceService interface {
CreateBackup(userId types.Snowflake, minioClient *minio.Client) (string, error)
UploadFile(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake, maxUploadsSize float64, supportedTypes []string, minioClient *minio.Client) (*models.Node, error)
UploadAvatar(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake, supportedTypes []string, minioClient *minio.Client) error
}
-type ressourceService struct {
+type resourceService struct {
nodeRepo repositories.NodeRepository
snowflake *snowflake.Snowflake
}
-func NewRessourceService(nodeRepo repositories.NodeRepository, snowflake *snowflake.Snowflake) RessourceService {
- return &ressourceService{
+func NewResourceService(nodeRepo repositories.NodeRepository, snowflake *snowflake.Snowflake) ResourceService {
+ return &resourceService{
nodeRepo: nodeRepo,
snowflake: snowflake,
}
}
-func (s *ressourceService) CreateBackup(userId types.Snowflake, minioClient *minio.Client) (string, error) {
+func (s *resourceService) CreateBackup(userId types.Snowflake, minioClient *minio.Client) (string, error) {
if minioClient == nil {
return "", errors.New("minio client not initialized")
}
@@ -64,7 +64,7 @@ func (s *ressourceService) CreateBackup(userId types.Snowflake, minioClient *min
return objectName, nil
}
-func (s *ressourceService) UploadFile(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake, maxUploadsSize float64, supportedTypes []string, minioClient *minio.Client) (*models.Node, error) {
+func (s *resourceService) UploadFile(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake, maxUploadsSize float64, supportedTypes []string, minioClient *minio.Client) (*models.Node, error) {
if minioClient == nil {
return nil, errors.New("minio client not initialized")
}
@@ -125,7 +125,7 @@ func (s *ressourceService) UploadFile(filename string, fileSize int64, fileConte
return node, nil
}
-func (s *ressourceService) UploadAvatar(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake, supportedTypes []string, minioClient *minio.Client) error {
+func (s *resourceService) UploadAvatar(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake, supportedTypes []string, minioClient *minio.Client) error {
if minioClient == nil {
return errors.New("minio client not initialized")
}
diff --git a/docs/README.md b/docs/README.md
index 2a698f18..5bf91cf5 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -35,20 +35,20 @@ Alexandrie is a modern, full-featured note-taking application designed for stude
### 1.3 Technology Stack
-| Layer | Technology | Version | Purpose |
-|-------|-----------|---------|---------|
-| **Backend** | Go (Golang) | 1.24.0 | High-performance API server |
-| **Web Framework** | Gin | 1.11.0 | HTTP routing and middleware |
-| **Frontend** | Nuxt | 4.2.1 | Vue.js meta-framework with SSR/SPA |
-| **UI Framework** | Vue.js | 3.5.24 | Reactive UI components |
-| **State Management** | Pinia | 3.0.4 | Centralized state management |
-| **Database** | MySQL | 8.0+ | Relational data storage |
-| **Object Storage** | MinIO/RustFS | - | S3-compatible file storage |
-| **Code Editor** | CodeMirror | 6.x | Markdown editing experience |
-| **Authentication** | JWT | golang-jwt/v5 | Stateless authentication |
-| **Email** | go-mail | 0.7.2 | SMTP email sending |
-| **Build Tool** | Bun | Latest | Fast package manager for frontend |
-| **Containerization** | Docker | - | Development and deployment |
+| Layer | Technology | Version | Purpose |
+| -------------------- | ------------ | ------------- | ---------------------------------- |
+| **Backend** | Go (Golang) | 1.24.0 | High-performance API server |
+| **Web Framework** | Gin | 1.11.0 | HTTP routing and middleware |
+| **Frontend** | Nuxt | 4.2.1 | Vue.js meta-framework with SSR/SPA |
+| **UI Framework** | Vue.js | 3.5.24 | Reactive UI components |
+| **State Management** | Pinia | 3.0.4 | Centralized state management |
+| **Database** | MySQL | 8.0+ | Relational data storage |
+| **Object Storage** | MinIO/RustFS | - | S3-compatible file storage |
+| **Code Editor** | CodeMirror | 6.x | Markdown editing experience |
+| **Authentication** | JWT | golang-jwt/v5 | Stateless authentication |
+| **Email** | go-mail | 0.7.2 | SMTP email sending |
+| **Build Tool** | Bun | Latest | Fast package manager for frontend |
+| **Containerization** | Docker | - | Development and deployment |
---
@@ -151,7 +151,7 @@ backend/
β”‚ β”œβ”€β”€ users.controller.go # User CRUD operations
β”‚ β”œβ”€β”€ nodes.controller.go # Nodes (document/category/wp) CRUD operations
β”‚ β”œβ”€β”€ permissions.controller.go # Permission management (for nodes, will be moved soon on /nodes/permissions and nodes.permissions.controller.go)
-β”‚ β”œβ”€β”€ ressources.controller.go # File upload/download (ressources)
+β”‚ β”œβ”€β”€ resources.controller.go # File upload/download (resources)
β”‚ └── index.go # Not implemented yey but healtcheck
β”‚
β”œβ”€β”€ services/ # Business logic layer
@@ -197,7 +197,7 @@ backend/
β”‚ β”œβ”€β”€ 000002_change_ids_to_bigints.up.sql
β”‚ β”œβ”€β”€ 000003_add_ip_indx.up.sql
β”‚ β”œβ”€β”€ 000004_add_category_color.up.sql
-β”‚ β”œβ”€β”€ 000005_ressource_parent.up.sql
+β”‚ β”œβ”€β”€ 000005_resource_parent.up.sql
β”‚ β”œβ”€β”€ 000006_file_parent_id_constraint_rmdoc.up.sql
β”‚ β”œβ”€β”€ 000007_pin_doc.up.sql
β”‚ β”œβ”€β”€ 000008_reset_pass.up.sql
@@ -249,55 +249,55 @@ backend/
#### Authentication Endpoints
-| Method | Endpoint | Description | Auth Required |
-|--------|----------|-------------|---------------|
-| POST | `/api/auth/register` | Create new user account | No |
-| POST | `/api/auth/login` | Login and get JWT tokens | No |
-| POST | `/api/auth/logout` | Logout and invalidate session | Yes |
-| POST | `/api/auth/refresh` | Refresh access token | Yes (Refresh Token) |
-| POST | `/api/auth/forgot-password` | Request password reset email | No |
-| POST | `/api/auth/reset-password` | Reset password with token | No |
+| Method | Endpoint | Description | Auth Required |
+| ------ | --------------------------- | ----------------------------- | ------------------- |
+| POST | `/api/auth/register` | Create new user account | No |
+| POST | `/api/auth/login` | Login and get JWT tokens | No |
+| POST | `/api/auth/logout` | Logout and invalidate session | Yes |
+| POST | `/api/auth/refresh` | Refresh access token | Yes (Refresh Token) |
+| POST | `/api/auth/forgot-password` | Request password reset email | No |
+| POST | `/api/auth/reset-password` | Reset password with token | No |
#### User Endpoints
-| Method | Endpoint | Description | Auth Required |
-|--------|----------|-------------|---------------|
-| GET | `/api/users/@me` | Get current user profile | Yes |
-| PATCH | `/api/users/@me` | Update current user | Yes |
-| DELETE | `/api/users/@me` | Delete current user account | Yes |
-| GET | `/api/users/:id` | Get user by ID (admin) | Yes (Admin) |
-| GET | `/api/users` | List all users (admin) | Yes (Admin) |
-| DELETE | `/api/users/:id` | Delete user (admin) | Yes (Admin) |
+| Method | Endpoint | Description | Auth Required |
+| ------ | ---------------- | --------------------------- | ------------- |
+| GET | `/api/users/@me` | Get current user profile | Yes |
+| PATCH | `/api/users/@me` | Update current user | Yes |
+| DELETE | `/api/users/@me` | Delete current user account | Yes |
+| GET | `/api/users/:id` | Get user by ID (admin) | Yes (Admin) |
+| GET | `/api/users` | List all users (admin) | Yes (Admin) |
+| DELETE | `/api/users/:id` | Delete user (admin) | Yes (Admin) |
#### Node Endpoints (Documents & Categories)
-| Method | Endpoint | Description | Auth Required |
-|--------|----------|-------------|---------------|
-| GET | `/api/nodes` | List user's nodes (with filters) | Yes |
-| GET | `/api/nodes/:id` | Get single node details | Yes (Permission) |
-| POST | `/api/nodes` | Create new node | Yes |
-| PATCH | `/api/nodes/:id` | Update node | Yes (Write Permission) |
-| DELETE | `/api/nodes/:id` | Delete node | Yes (Admin Permission) |
-| GET | `/api/nodes/:id/children` | Get child nodes | Yes (Permission) |
-| POST | `/api/nodes/:id/pin` | Pin/unpin node | Yes (Write Permission) |
+| Method | Endpoint | Description | Auth Required |
+| ------ | ------------------------- | -------------------------------- | ---------------------- |
+| GET | `/api/nodes` | List user's nodes (with filters) | Yes |
+| GET | `/api/nodes/:id` | Get single node details | Yes (Permission) |
+| POST | `/api/nodes` | Create new node | Yes |
+| PATCH | `/api/nodes/:id` | Update node | Yes (Write Permission) |
+| DELETE | `/api/nodes/:id` | Delete node | Yes (Admin Permission) |
+| GET | `/api/nodes/:id/children` | Get child nodes | Yes (Permission) |
+| POST | `/api/nodes/:id/pin` | Pin/unpin node | Yes (Write Permission) |
#### Permission Endpoints
-| Method | Endpoint | Description | Auth Required |
-|--------|----------|-------------|---------------|
-| GET | `/api/permissions/node/:nodeId` | Get node permissions | Yes (Owner) |
-| POST | `/api/permissions/node/:nodeId` | Grant permission to user | Yes (Owner) |
-| PATCH | `/api/permissions/:id` | Update permission level | Yes (Owner) |
-| DELETE | `/api/permissions/:id` | Revoke permission | Yes (Owner) |
+| Method | Endpoint | Description | Auth Required |
+| ------ | ------------------------------- | ------------------------ | ------------- |
+| GET | `/api/permissions/node/:nodeId` | Get node permissions | Yes (Owner) |
+| POST | `/api/permissions/node/:nodeId` | Grant permission to user | Yes (Owner) |
+| PATCH | `/api/permissions/:id` | Update permission level | Yes (Owner) |
+| DELETE | `/api/permissions/:id` | Revoke permission | Yes (Owner) |
#### File Upload Endpoints
-| Method | Endpoint | Description | Auth Required |
-|--------|----------|-------------|---------------|
-| POST | `/api/uploads` | Upload file to CDN | Yes |
-| GET | `/api/uploads` | List user's uploads | Yes |
-| GET | `/api/uploads/:id` | Get file metadata | Yes |
-| DELETE | `/api/uploads/:id` | Delete uploaded file | Yes |
+| Method | Endpoint | Description | Auth Required |
+| ------ | ------------------ | -------------------- | ------------- |
+| POST | `/api/uploads` | Upload file to CDN | Yes |
+| GET | `/api/uploads` | List user's uploads | Yes |
+| GET | `/api/uploads/:id` | Get file metadata | Yes |
+| DELETE | `/api/uploads/:id` | Delete uploaded file | Yes |
### 3.4 Service Layer Architecture
@@ -316,6 +316,7 @@ type NodeService interface {
```
**Service Layer Benefits:**
+
- Reusability across different controllers
- Easier unit testing (mock dependencies)
- Clear separation of concerns
@@ -478,7 +479,7 @@ frontend/
β”‚ β”‚ β”œβ”€β”€ importations.ts # Decoder for JSON Nodes format
β”‚ β”‚ β”œβ”€β”€ paginator.ts # Pagniation helper for datatable
β”‚ β”‚ β”œβ”€β”€ navigation.ts # Navigation constants
-β”‚ β”‚ β”œβ”€β”€ ressources.ts # Files management (file size, filetype, resolveUrl)
+β”‚ β”‚ β”œβ”€β”€ resources.ts # Files management (file size, filetype, resolveUrl)
β”‚ β”‚ └── utils.ts # General helpers
β”‚ β”‚
β”‚ β”œβ”€β”€ styles/ # Global styles
@@ -498,7 +499,6 @@ frontend/
└── Logo/ # Brand assets
```
-
### 4.2 State Management (Pinia Stores)
#### User Store (`user.store.ts`)
@@ -546,7 +546,7 @@ Getters:
- workspaces // Filter nodes with role=1
- categories // Filter nodes with role=2
- documents // Filter nodes with role=3
-- ressources // Filter nodes with role=4
+- resources // Filter nodes with role=4
```
#### Resources Store (`resources.store.ts`)
@@ -588,21 +588,21 @@ pages/dashboard/docs/edit/[id].vue β†’ /dashboard/docs/edit/:id (dynamic)
```typescript
// auth.ts - Protect authenticated routes
export default defineNuxtRouteMiddleware((to, from) => {
- const userStore = useUserStore()
-
+ const userStore = useUserStore();
+
if (!userStore.isAuthenticated) {
- return navigateTo('/auth/login')
+ return navigateTo('/auth/login');
}
-})
+});
// admin.ts - Protect admin routes
export default defineNuxtRouteMiddleware((to, from) => {
- const userStore = useUserStore()
-
+ const userStore = useUserStore();
+
if (!userStore.isAdmin) {
- return navigateTo('/dashboard')
+ return navigateTo('/dashboard');
}
-})
+});
```
### 4.4 Markdown Editor Implementation
@@ -612,29 +612,29 @@ Alexandrie uses **CodeMirror 6** for the Markdown editor:
```typescript
// Key CodeMirror extensions used:
-import { EditorView } from '@codemirror/view'
-import { EditorState } from '@codemirror/state'
-import { markdown } from '@codemirror/lang-markdown'
-import { autocompletion } from '@codemirror/autocomplete'
-import { search } from '@codemirror/search'
-import { highlightSelectionMatches } from '@codemirror/search'
+import { EditorView } from '@codemirror/view';
+import { EditorState } from '@codemirror/state';
+import { markdown } from '@codemirror/lang-markdown';
+import { autocompletion } from '@codemirror/autocomplete';
+import { search } from '@codemirror/search';
+import { highlightSelectionMatches } from '@codemirror/search';
// Editor configuration
const editorView = new EditorView({
state: EditorState.create({
doc: initialContent,
extensions: [
- markdown(), // Markdown syntax
- autocompletion(), // Autocomplete
- search(), // Search & replace
- highlightSelectionMatches(), // Highlight matches
+ markdown(), // Markdown syntax
+ autocompletion(), // Autocomplete
+ search(), // Search & replace
+ highlightSelectionMatches(), // Highlight matches
// Custom theme
// Keybindings
// Event handlers
- ]
+ ],
}),
- parent: editorElement
-})
+ parent: editorElement,
+});
```
#### Markdown Rendering
@@ -642,28 +642,30 @@ const editorView = new EditorView({
```typescript
// markdown-it configuration for rendering
-import MarkdownIt from 'markdown-it'
-import markdownItAnchor from 'markdown-it-anchor'
-import markdownItContainer from 'markdown-it-container'
-import markdownItHighlightjs from 'markdown-it-highlightjs'
-import markdownItMark from 'markdown-it-mark'
-import markdownItUnderline from 'markdown-it-underline'
+import MarkdownIt from 'markdown-it';
+import markdownItAnchor from 'markdown-it-anchor';
+import markdownItContainer from 'markdown-it-container';
+import markdownItHighlightjs from 'markdown-it-highlightjs';
+import markdownItMark from 'markdown-it-mark';
+import markdownItUnderline from 'markdown-it-underline';
const md = new MarkdownIt({
- html: true, // Enable HTML tags
- linkify: true, // Auto-convert URLs to links
- typographer: true, // Smart quotes, dashes
- breaks: false // Convert \n to <br>
+ html: true, // Enable HTML tags
+ linkify: true, // Auto-convert URLs to links
+ typographer: true, // Smart quotes, dashes
+ breaks: false, // Convert \n to <br>
})
- .use(markdownItAnchor, { /* heading anchors */ })
- .use(markdownItContainer, 'warning') // ::: warning blocks
- .use(markdownItContainer, 'info') // ::: info blocks
- .use(markdownItHighlightjs) // Code syntax highlighting
- .use(markdownItMark) // ==marked text==
- .use(markdownItUnderline) // ++underlined text++
+ .use(markdownItAnchor, {
+ /* heading anchors */
+ })
+ .use(markdownItContainer, 'warning') // ::: warning blocks
+ .use(markdownItContainer, 'info') // ::: info blocks
+ .use(markdownItHighlightjs) // Code syntax highlighting
+ .use(markdownItMark) // ==marked text==
+ .use(markdownItUnderline); // ++underlined text++
// Render markdown to HTML
-const html = md.render(markdownContent)
+const html = md.render(markdownContent);
```
#### KaTeX Math Rendering
@@ -671,7 +673,7 @@ const html = md.render(markdownContent)
```typescript
// Math formula rendering with KaTeX
-import katex from 'katex'
+import katex from 'katex';
// Inline math: $formula$
// Block math: $$formula$$
@@ -679,8 +681,8 @@ import katex from 'katex'
// Custom markdown-it plugin for math
md.use(markdownItMath, {
engine: katex,
- delimiters: 'dollars'
-})
+ delimiters: 'dollars',
+});
```
### 4.6 Component Architecture
@@ -694,12 +696,12 @@ md.use(markdownItMath, {
<Icon :name="node.icon" />
<h3>{{ node.name }}</h3>
</div>
-
+
<div class="document-meta">
<span>{{ formatDate(node.updated_timestamp) }}</span>
<Badge v-if="node.tags">{{ node.tags }}</Badge>
</div>
-
+
<div class="document-actions">
<AppButton @click.stop="shareDocument">Share</AppButton>
</div>
@@ -708,9 +710,7 @@ md.use(markdownItMath, {
<script setup lang="ts">
// NOTHING :) Nuxt automaticly import components from "app/components" folder
-import type { Node } from '~/stores'
-
-
+import type { Node } from '~/stores';
</script>
<style scoped lang="scss">
@@ -780,6 +780,7 @@ type User struct {
```
**Database Schema:**
+
```sql
CREATE TABLE `users` (
`id` varchar(50) NOT NULL PRIMARY KEY,
@@ -806,44 +807,46 @@ type Node struct {
Name string `json:"name"` // Display name (max 50 chars)
Description *string `json:"description"` // Optional description (max 250)
Tags *string `json:"tags"` // Comma-separated tags
-
+
// Node type and appearance
Role int `json:"role"` // 1: workspace, 2: category, 3: document
Color *int `json:"color"` // Color code for UI
Icon *string `json:"icon"` // Icon identifier
Thumbnail *string `json:"thumbnail"` // Thumbnail URL
Theme *string `json:"theme"` // Custom theme settings
-
+
// Access control
Accessibility *int `json:"accessibility"` // 0: Public, 1: Private, 2: Unlisted
Access int `json:"access"` // Bit field: 1=view, 2=edit
-
+
// Display and ordering
Display *int `json:"display"` // Display mode
Order *int `json:"order"` // Sort order (-1: pinned, -2: bookmark)
-
+
// Content (for document nodes)
Content *string `json:"content"` // Markdown content
ContentCompiled *string `json:"content_compiled"` // Rendered HTML
Size *int64 `json:"size"` // Content size in bytes
-
+
// Metadata
Metadata *JSONB `json:"metadata"` // Additional JSON data
CreatedTimestamp int64 `json:"created_timestamp"`
UpdatedTimestamp int64 `json:"updated_timestamp"`
-
+
// Relations
Permissions []*Permission `json:"permissions"` // Access permissions
}
```
**Node Roles:**
+
- `1` - Workspace: Top-level container
- `2` - Category: Organizational folder
- `3` - Document: Actual note/content
-- `4` - Ressource: An uploaded file
+- `4` - Resource: An uploaded file
**Accessibility Levels:**
+
- `0` - Public: Anyone can view
- `1` - Private: Only owner and permitted users
- `2` - Unlisted: Accessible via direct link
@@ -863,6 +866,7 @@ type Permission struct {
```
**Permission Levels:**
+
```go
const (
PermNone = 0 // No access
@@ -874,6 +878,7 @@ const (
```
**Permission Actions:**
+
```go
const (
ActionRead = 1 // Requires: PermRead
@@ -1083,27 +1088,27 @@ Workspace (role=1)
func (s *NodeService) GetNode(nodeId, userId Snowflake) (*Node, error) {
// 1. Load node from database
node := loadNodeFromDB(nodeId)
-
+
// 2. Check if user is owner
if node.UserId == userId {
return node, nil // Owner has full access
}
-
+
// 3. Load permissions for this node
permissions := loadPermissions(nodeId)
-
+
// 4. Check if user has permission
for _, perm := range permissions {
if perm.UserId == userId && perm.Level >= PermRead {
return node, nil
}
}
-
+
// 5. Check accessibility
if node.Accessibility == Public {
return node, nil // Public nodes are visible to all
}
-
+
return nil, ErrForbidden
}
```
@@ -1136,18 +1141,18 @@ Node owner shares document
func CanPerform(userId, nodeId Snowflake, action NodeAction) bool {
// 1. Load node
node := getNode(nodeId)
-
+
// 2. Owner always has full access
if node.UserId == userId {
return true
}
-
+
// 3. Get required permission level for action
requiredLevel := action.RequiredLevel()
-
+
// 4. Load user's permission for this node
permission := getPermission(nodeId, userId)
-
+
// 5. Compare levels
return permission.Level >= requiredLevel
}
@@ -1219,23 +1224,23 @@ To access the file, the request must be on the S3 server directly (minio, rustfs
```typescript
// Debounced search composable
-const searchQuery = ref('')
-const searchResults = ref<Node[]>([])
+const searchQuery = ref('');
+const searchResults = ref<Node[]>([]);
// Debounce to avoid excessive API calls
const debouncedSearch = useDebounceFn(async (query: string) => {
if (query.length < 2) {
- searchResults.value = []
- return
+ searchResults.value = [];
+ return;
}
-
- const results = await api(`/api/nodes?search=${query}`)
- searchResults.value = results
-}, 300)
-watch(searchQuery, (newQuery) => {
- debouncedSearch(newQuery)
-})
+ const results = await api(`/api/nodes?search=${query}`);
+ searchResults.value = results;
+}, 300);
+
+watch(searchQuery, newQuery => {
+ debouncedSearch(newQuery);
+});
```
### 6.6 Export Functionality
@@ -1246,17 +1251,17 @@ watch(searchQuery, (newQuery) => {
// Generate .md file from node content
const exportMarkdown = (node: Node) => {
- const content = `# ${node.name}\n\n${node.content}`
- const blob = new Blob([content], { type: 'text/markdown' })
- const url = URL.createObjectURL(blob)
-
- const link = document.createElement('a')
- link.href = url
- link.download = `${node.name}.md`
- link.click()
-
- URL.revokeObjectURL(url)
-}
+ const content = `# ${node.name}\n\n${node.content}`;
+ const blob = new Blob([content], { type: 'text/markdown' });
+ const url = URL.createObjectURL(blob);
+
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = `${node.name}.md`;
+ link.click();
+
+ URL.revokeObjectURL(url);
+};
```
#### PDF Export
@@ -1266,7 +1271,7 @@ const exportMarkdown = (node: Node) => {
const exportPDF = (node: Node) => {
// Render node content in printable format
- const printWindow = window.open('', '_blank')
+ const printWindow = window.open('', '_blank');
printWindow.document.write(`
<!DOCTYPE html>
<html>
@@ -1283,11 +1288,11 @@ const exportPDF = (node: Node) => {
${node.content_compiled}
</body>
</html>
- `)
-
- printWindow.document.close()
- printWindow.print()
-}
+ `);
+
+ printWindow.document.close();
+ printWindow.print();
+};
```
## 7. External Services Integration
@@ -1326,13 +1331,13 @@ db.SetConnMaxLifetime(5 * time.Minute)
// Run migrations on application start
func Migrate(config *Config) {
driver, _ := mysql.WithInstance(db, &mysql.Config{})
-
+
m, _ := migrate.NewWithDatabaseInstance(
"file://migrations",
"mysql",
driver,
)
-
+
// Apply all pending migrations
m.Up()
}
@@ -1351,16 +1356,16 @@ func CreateNodeWithPermissions(node *Node, permissions []*Permission) error {
if err != nil {
return err
}
-
+
// Defer rollback (no-op if commit succeeds)
defer tx.Rollback()
-
+
// Insert node
_, err = tx.Exec("INSERT INTO nodes (...) VALUES (...)", node)
if err != nil {
return err // Automatic rollback
}
-
+
// Insert permissions
for _, perm := range permissions {
_, err = tx.Exec("INSERT INTO permissions (...) VALUES (...)", perm)
@@ -1368,7 +1373,7 @@ func CreateNodeWithPermissions(node *Node, permissions []*Permission) error {
return err // Automatic rollback
}
}
-
+
// Commit transaction
return tx.Commit()
}
@@ -1409,7 +1414,7 @@ if !exists {
func (s *MinioService) UploadFile(file multipart.File, filename string) (string, error) {
// Generate object path
objectPath := fmt.Sprintf("uploads/%s/%s", userId, filename)
-
+
// Upload to MinIO
info, err := s.client.PutObject(
context.Background(),
@@ -1421,7 +1426,7 @@ func (s *MinioService) UploadFile(file multipart.File, filename string) (string,
ContentType: contentType,
},
)
-
+
return objectPath, err
}
@@ -1435,7 +1440,7 @@ func (s *MinioService) GetPresignedURL(objectPath string) (string, error) {
time.Hour, // Valid for 1 hour
nil,
)
-
+
return url.String(), err
}
@@ -1500,28 +1505,29 @@ mailClient, err := mail.NewClient(
func SendPasswordResetEmail(email, resetToken string) error {
m := mail.NewMsg()
-
+
m.From(smtpMail)
m.To(email)
m.Subject("Password Reset - Alexandrie")
-
- resetURL := fmt.Sprintf("%s/auth/reset-password?token=%s",
+
+ resetURL := fmt.Sprintf("%s/auth/reset-password?token=%s",
frontendURL, resetToken)
-
+
body := fmt.Sprintf(`
<h2>Password Reset Request</h2>
<p>Click the link below to reset your password:</p>
<a href="%s">Reset Password</a>
<p>This link expires in 1 hour.</p>
`, resetURL)
-
+
m.SetBodyString(mail.TypeTextHTML, body)
-
+
return mailClient.DialAndSend(m)
}
```
**Email Use Cases:**
+
- Password reset requests
- Collaboration invites (future)
@@ -1545,35 +1551,36 @@ city_ipv6_complete -- IPv6 address ranges
func GetLocationFromIP(ipAddress string) string {
// Parse IP
ip := net.ParseIP(ipAddress)
-
+
// Query appropriate table based on IP version
var geonameId int
if ip.To4() != nil {
// IPv4 query
query := `
- SELECT geoname_id
- FROM city_ipv4_complete
+ SELECT geoname_id
+ FROM city_ipv4_complete
WHERE INET_ATON(?) BETWEEN network_start_integer AND network_last_integer
`
db.QueryRow(query, ipAddress).Scan(&geonameId)
} else {
// IPv6 query (similar logic)
}
-
+
// Get city information
var city, country string
query := `
- SELECT city_name, country_name
- FROM city_locations_fr
+ SELECT city_name, country_name
+ FROM city_locations_fr
WHERE geoname_id = ?
`
db.QueryRow(query, geonameId).Scan(&city, &country)
-
+
return fmt.Sprintf("%s, %s", city, country)
}
```
**Usage:**
+
- Log user login locations
- Security monitoring
- Suspicious activity detection (not implemented yet)
@@ -1601,6 +1608,7 @@ func CheckPassword(password, hash string) bool {
```
**Security Features:**
+
- Bcrypt with cost factor 12 (secure against brute force)
- Salted hashing (built into bcrypt)
- Passwords never stored in plain text
@@ -1621,7 +1629,7 @@ func GenerateToken(userId Snowflake, role int, duration time.Duration) string {
"exp": time.Now().Add(duration).Unix(),
"iat": time.Now().Unix(),
}
-
+
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
signedToken, _ := token.SignedString([]byte(jwtSecret))
return signedToken
@@ -1640,6 +1648,7 @@ func ValidateToken(tokenString string) (*jwt.Token, error) {
```
**Token Expiration:**
+
- Access Token: 15 minutes (short-lived)
- Refresh Token: 7 days (stored in database)
@@ -1683,13 +1692,13 @@ const (
// Admin middleware
func AdminOnly(c *gin.Context) {
user := c.MustGet("user").(User)
-
+
if user.Role != RoleAdmin {
c.JSON(403, gin.H{"error": "Admin access required"})
c.Abort()
return
}
-
+
c.Next()
}
@@ -1711,23 +1720,23 @@ func RequireNodePermission(action NodeAction) gin.HandlerFunc {
return func(c *gin.Context) {
nodeId := c.Param("id")
user := c.MustGet("user").(User)
-
+
// Check if user can perform action
can := permissions.CanPerform(user.Id, nodeId, action)
-
+
if !can {
c.JSON(403, gin.H{"error": "Permission denied"})
c.Abort()
return
}
-
+
c.Next()
}
}
// Apply to routes
-router.PATCH("/api/nodes/:id",
- AuthMiddleware,
+router.PATCH("/api/nodes/:id",
+ AuthMiddleware,
RequireNodePermission(ActionUpdate),
controllers.UpdateNode)
```
@@ -1749,17 +1758,18 @@ type CreateNodeInput struct {
// Validate in controller
func CreateNode(c *gin.Context) {
var input CreateNodeInput
-
+
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(400, gin.H{"error": err.Error()})
return
}
-
+
// Input is valid, proceed...
}
```
**Validation Rules:**
+
- Required fields checked
- String length limits enforced
- Email format validation
@@ -1773,28 +1783,28 @@ func CreateNode(c *gin.Context) {
const validateNodeName = (name: string): boolean => {
if (!name || name.trim().length === 0) {
- return false
+ return false;
}
if (name.length > 50) {
- return false
+ return false;
}
- return true
-}
+ return true;
+};
// Usage in form
-const errors = ref<Record<string, string>>({})
+const errors = ref<Record<string, string>>({});
const submitForm = () => {
- errors.value = {}
-
+ errors.value = {};
+
if (!validateNodeName(form.name)) {
- errors.value.name = 'Name must be 1-50 characters'
- return
+ errors.value.name = 'Name must be 1-50 characters';
+ return;
}
-
+
// Submit if valid
- api.createNode(form)
-}
+ api.createNode(form);
+};
```
### 8.4 XSS Prevention
@@ -1815,9 +1825,11 @@ node.Content = SanitizeHTML(userInput)
```
**Frontend XSS Protection:**
+
```vue
<!-- Vue automatically escapes content -->
-<div>{{ userContent }}</div> <!-- Safe: content escaped -->
+<div>{{ userContent }}</div>
+<!-- Safe: content escaped -->
<!-- For rendering HTML, use v-html with sanitized content -->
<div v-html="sanitizedHTML"></div>
@@ -1841,6 +1853,7 @@ router.Use(cors.New(cors.Config{
```
**Production CORS:**
+
- Only allow specific frontend domain
- No wildcards in production
- Credentials enabled for cookies
@@ -1872,20 +1885,20 @@ var limiters = make(map[string]*rate.Limiter)
func RateLimitMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
ip := c.ClientIP()
-
+
limiter, exists := limiters[ip]
if !exists {
// 100 requests per minute
limiter = rate.NewLimiter(rate.Every(time.Minute/100), 100)
limiters[ip] = limiter
}
-
+
if !limiter.Allow() {
c.JSON(429, gin.H{"error": "Rate limit exceeded"})
c.Abort()
return
}
-
+
c.Next()
}
}
@@ -1910,6 +1923,7 @@ func HTTPSRedirect() gin.HandlerFunc {
```
**Production Security Checklist:**
+
- βœ… HTTPS enforced (TLS 1.2+)
- βœ… HSTS header enabled
- βœ… Secure cookie flags (httpOnly, secure, sameSite)
@@ -1928,6 +1942,7 @@ func HTTPSRedirect() gin.HandlerFunc {
### 9.1 Prerequisites
**Required Software:**
+
- [Bun](https://bun.sh/) v1.0+ - Fast JavaScript runtime & package manager
- [Go](https://go.dev/) v1.24+ - Backend language
- [MySQL](https://www.mysql.com/) 8.0+ - Database server
@@ -2112,7 +2127,7 @@ migrate create -ext sql -dir . -seq migration_name
# - 000012_migration_name.down.sql
```
-*Note: This tool is optional you can create manually the file but please follow the naming conventions*
+_Note: This tool is optional you can create manually the file but please follow the naming conventions_
#### Writing Migrations
@@ -2144,10 +2159,10 @@ migrate -database "..." -path migrations goto 10
# Check current version
migrate -database "..." -path migrations version
```
+
> [!WARNING]
> Migrations down are not fully implemented yet
-
### 9.5 Code Quality
#### Linting
@@ -2194,6 +2209,7 @@ git pull origin main
```
**Commit Message Convention:**
+
```
feat: Add new feature
fix: Fix bug in authentication
@@ -2230,8 +2246,8 @@ dlv debug main.go
```typescript
// Console logging
-console.log('Debug:', data)
-console.table(array)
+console.log('Debug:', data);
+console.table(array);
// Vue DevTools (browser extension)
// Inspect component state, Pinia stores, routing
@@ -2283,8 +2299,8 @@ go func() {
```typescript
// Performance API
-const perfData = performance.getEntriesByType('navigation')[0]
-console.log('Load time:', perfData.loadEventEnd - perfData.fetchStart)
+const perfData = performance.getEntriesByType('navigation')[0];
+console.log('Load time:', perfData.loadEventEnd - perfData.fetchStart);
// Lighthouse (Chrome DevTools)
// Run audit for performance, accessibility, SEO
@@ -2303,7 +2319,6 @@ For details please see [setup guide.md](./setup.md)
### 10.2 Performance Tuning
-
#### Caching Strategy
```go
@@ -2318,13 +2333,13 @@ func GetNodeWithCache(nodeId Snowflake) (*Node, error) {
if err == nil {
return unmarshalNode(cached), nil
}
-
+
// Cache miss, query database
node := getNodeFromDB(nodeId)
-
+
// Store in cache (expire in 5 minutes)
redis.Set(ctx, "node:"+nodeId, marshal(node), 5*time.Minute)
-
+
return node, nil
}
```
@@ -2333,7 +2348,7 @@ func GetNodeWithCache(nodeId Snowflake) (*Node, error) {
### A. Glossary
-- **Node**: Unified entity representing workspace, category, document or ressource
+- **Node**: Unified entity representing workspace, category, document or resource
- **Snowflake**: Distributed unique ID generation algorithm (inspired from https://discord.com/developers/docs/reference#snowflakes)
- **Permission Level**: Numeric access level (0-4) determining user capabilities
- **S3**: Simple Storage Service, object storage protocol
diff --git a/frontend/app/components/AppDrop.vue b/frontend/app/components/AppDrop.vue
index 33871341..e7298e5e 100644
--- a/frontend/app/components/AppDrop.vue
+++ b/frontend/app/components/AppDrop.vue
@@ -40,7 +40,7 @@
</div>
</template>
<script setup lang="ts">
-import { readableFileSize } from '~/helpers/ressources';
+import { readableFileSize } from '~/helpers/resources';
const props = withDefaults(
defineProps<{
diff --git a/frontend/app/components/MarkdownEditor/ImageSelectorModal.vue b/frontend/app/components/MarkdownEditor/ImageSelectorModal.vue
index 08d67fc1..83f3046f 100644
--- a/frontend/app/components/MarkdownEditor/ImageSelectorModal.vue
+++ b/frontend/app/components/MarkdownEditor/ImageSelectorModal.vue
@@ -27,10 +27,10 @@
<script setup lang="ts">
import EditorAppHeader from './EditorAppHeader.vue';
-import { readableFileSize, isImageFile, resolvePreviewUrl } from '~/helpers/ressources';
+import { readableFileSize, isImageFile, resolvePreviewUrl } from '~/helpers/resources';
import type { Node } from '~/stores';
-const ressourcesStore = useRessourcesStore();
+const resourcesStore = useResourcesStore();
const nodesStore = useNodesStore();
const props = defineProps<{ onImageSelect: (imageUrl: string, altText: string) => void }>();
@@ -48,7 +48,7 @@ const submitFile = (selectedFile: File) => {
const body = new FormData();
body.append('file', selectedFile);
dropComponent.value.reset(); // Reset drop component
- ressourcesStore
+ resourcesStore
.post(body)
.catch(e => (uploadError.value = e || 'An error occurred during upload.'))
.finally(() => (isLoading.value = false));
@@ -56,9 +56,9 @@ const submitFile = (selectedFile: File) => {
const filteredImages = computed(() => {
if (!searchQuery.value.trim()) {
- return nodesStore.ressources.filter(img => isImageFile(img.metadata?.filetype as string));
+ return nodesStore.resources.filter(img => isImageFile(img.metadata?.filetype as string));
}
- return nodesStore.ressources.filter(img => isImageFile(img.metadata?.filetype as string) && img.name.toLowerCase().includes(searchQuery.value.toLowerCase()));
+ return nodesStore.resources.filter(img => isImageFile(img.metadata?.filetype as string) && img.name.toLowerCase().includes(searchQuery.value.toLowerCase()));
});
const handleImageError = (event: Event) => {
diff --git a/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue b/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue
index be74b5fd..aec3cefd 100644
--- a/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue
+++ b/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue
@@ -43,7 +43,7 @@ import Toolbar from './Toolbar.vue';
import compile from '~/helpers/markdown';
import type { Node } from '~/stores';
-const resourcesStore = useRessourcesStore();
+const resourcesStore = useResourcesStore();
const preferences = usePreferences();
const props = defineProps<{ doc?: Partial<Node>; minimal?: boolean }>();
diff --git a/frontend/app/components/MarkdownEditor/modules/editorUploads.ts b/frontend/app/components/MarkdownEditor/modules/editorUploads.ts
index ab54702d..517d2cb2 100644
--- a/frontend/app/components/MarkdownEditor/modules/editorUploads.ts
+++ b/frontend/app/components/MarkdownEditor/modules/editorUploads.ts
@@ -2,7 +2,7 @@ import { EditorView } from '@codemirror/view';
import type { Node } from '~/stores';
interface UploadHandlersParams {
- resourcesStore: ReturnType<typeof import('~/stores').useRessourcesStore>;
+ resourcesStore: ReturnType<typeof import('~/stores').useResourcesStore>;
CDN: string;
insertText: (text: string) => void;
}
diff --git a/frontend/app/components/Sidebar/SidebarItem.vue b/frontend/app/components/Sidebar/SidebarItem.vue
index ad1af5b7..ad14dc02 100644
--- a/frontend/app/components/Sidebar/SidebarItem.vue
+++ b/frontend/app/components/Sidebar/SidebarItem.vue
@@ -88,9 +88,9 @@ const drop = async (event: DragEvent) => {
if (!draggedItem) return;
if (draggedItem.role === -1) return; // Prevent dropping nav items
- if (props.item.data.role === 4) return; // Prevent dropping on ressource items
+ if (props.item.data.role === 4) return; // Prevent dropping on resource items
if (draggedItem.id === props.item.id) return; // Prevent dropping on itself
- if (draggedItem.role <= 2 && props.item.data.role > 2) return; // Prevent dropping categories / workspaces on ressources / documents
+ if (draggedItem.role <= 2 && props.item.data.role > 2) return; // Prevent dropping categories / workspaces on resources / documents
// Move item to root
if (props.item.data.role === -1) {
return nodesStore.update({ ...(draggedItem as Node), parent_id: workspaceId.value });
diff --git a/frontend/app/composables/Preferences.ts b/frontend/app/composables/Preferences.ts
index 8c2ea74a..83e65031 100644
--- a/frontend/app/composables/Preferences.ts
+++ b/frontend/app/composables/Preferences.ts
@@ -5,9 +5,9 @@ export const DEFAULT_PREFERENCES = {
darkMode: false as boolean,
hideTOC: false as boolean,
compactMode: false as boolean,
- hideSidebarRessources: false as boolean,
+ hideSidebarResources: false as boolean,
normalizeFileIcons: false as boolean,
- displayUncategorizedRessources: true as boolean,
+ displayUncategorizedResources: true as boolean,
datatableItemsCount: 10 as number,
view_dock: true as boolean,
primaryColor: -2 as number, // -2 default primary; -1 unset; >= 0 app color index
diff --git a/frontend/app/composables/Sidebar.ts b/frontend/app/composables/Sidebar.ts
index 0f0bfce5..b512a3d9 100644
--- a/frontend/app/composables/Sidebar.ts
+++ b/frontend/app/composables/Sidebar.ts
@@ -21,7 +21,7 @@ const filtered = computed(() => {
if (found) return found.childrens || [];
if (workspaceId.value === 'shared') return tree.value.filter(i => i.data && i.data.shared);
- if (!usePreferences().get('displayUncategorizedRessources').value) return tree.value.filter(i => i.data && i.data.role != 4); // hide uncategorized
+ if (!usePreferences().get('displayUncategorizedResources').value) return tree.value.filter(i => i.data && i.data.role != 4); // hide uncategorized
return tree.value;
});
diff --git a/frontend/app/pages/dashboard/admin/users/[id]/documents/index.vue b/frontend/app/pages/dashboard/admin/users/[id]/documents/index.vue
index 9a30a89a..97ac764f 100644
--- a/frontend/app/pages/dashboard/admin/users/[id]/documents/index.vue
+++ b/frontend/app/pages/dashboard/admin/users/[id]/documents/index.vue
@@ -48,7 +48,7 @@ const rows = computed(() =>
badges = '<tag class="green">Document</tag>';
break;
case 4:
- badges = '<tag class="yellow">Ressource</tag>';
+ badges = '<tag class="yellow">Resource</tag>';
break;
}
if (doc.parent_id) badges += '<tag class="yellow">Child</tag>';
diff --git a/frontend/app/pages/dashboard/cdn/[id]/index.vue b/frontend/app/pages/dashboard/cdn/[id]/index.vue
index a41766aa..bb4495c0 100644
--- a/frontend/app/pages/dashboard/cdn/[id]/index.vue
+++ b/frontend/app/pages/dashboard/cdn/[id]/index.vue
@@ -1,34 +1,34 @@
<template>
<div class="card-component">
<header>
- <h3>Update ressource</h3>
+ <h3>Update resource</h3>
</header>
- <p>Manage ressources and files on the server. You can edit metadata and delete file from the server.</p>
- <form v-if="ressource" @submit.prevent>
+ <p>Manage resources and files on the server. You can edit metadata and delete file from the server.</p>
+ <form v-if="resource" @submit.prevent>
<div class="form-row">
<div class="form-column">
<label>ID</label>
- <input id="id" type="text" :value="ressource.id" disabled />
+ <input id="id" type="text" :value="resource.id" disabled />
</div>
<div class="form-column">
<label>Size</label>
- <input id="size" type="text" :value="readableFileSize(ressource.size ?? 0)" disabled />
+ <input id="size" type="text" :value="readableFileSize(resource.size ?? 0)" disabled />
</div>
</div>
<label>Name</label>
- <input id="name" v-model="ressource.name" type="text" required />
+ <input id="name" v-model="resource.name" type="text" required />
<label style="display: flex; align-items: center">Parent <AppHint text="To organize your uploads" /></label>
- <AppSelect v-model="ressource.parent_id" :items="tree" :disabled="(i) => (i as Item).data?.role !== 3" placeholder="Select a ressource parent" />
+ <AppSelect v-model="resource.parent_id" :items="tree" :disabled="(i) => (i as Item).data?.role !== 3" placeholder="Select a resource parent" />
<label>Type</label>
- <input id="id" type="text" :value="ressource.metadata?.filetype" disabled />
+ <input id="id" type="text" :value="resource.metadata?.filetype" disabled />
<label>Original path</label>
- <input id="content" type="text" :value="ressource.content" disabled />
+ <input id="content" type="text" :value="resource.content" disabled />
<label>Path</label>
- <input id="path" type="text" :value="ressource.metadata?.transformed_path" disabled />
+ <input id="path" type="text" :value="resource.metadata?.transformed_path" disabled />
<p style="overflow-wrap: break-word">
- Ressource:
- <a :href="`${CDN}/${ressource.user_id}/${ressource.metadata?.transformed_path || ressource.content}`" target="_blank">{{
- `${CDN}/${ressource.user_id}/${ressource.metadata?.transformed_path || ressource.content}`
+ Resource:
+ <a :href="`${CDN}/${resource.user_id}/${resource.metadata?.transformed_path || resource.content}`" target="_blank">{{
+ `${CDN}/${resource.user_id}/${resource.metadata?.transformed_path || resource.content}`
}}</a>
</p>
<div style="display: flex; justify-content: flex-end">
@@ -38,8 +38,8 @@
<h4>Preview</h4>
<div class="preview">
<img
- v-if="(ressource.metadata?.filetype as string)?.startsWith('image/')"
- :src="`${CDN}/${ressource.user_id}/${ressource.metadata?.transformed_path || ressource.content}`"
+ v-if="(resource.metadata?.filetype as string)?.startsWith('image/')"
+ :src="`${CDN}/${resource.user_id}/${resource.metadata?.transformed_path || resource.content}`"
alt="Preview"
/>
<p v-else>Preview not available for this file type.</p>
@@ -49,8 +49,8 @@
</template>
<script lang="ts" setup>
-import DeleteRessourceModal from '../_modals/DeleteRessourceModal.vue';
-import { readableFileSize } from '~/helpers/ressources';
+import DeleteResourceModal from '../_modals/DeleteResourceModal.vue';
+import { readableFileSize } from '~/helpers/resources';
definePageMeta({ breadcrumb: 'Edit' });
@@ -58,7 +58,7 @@ const nodeStore = useNodesStore();
const route = useRoute();
const { CDN } = useApi();
-const ressource = computed(() => nodeStore.getById(route.params.id as string));
+const resource = computed(() => nodeStore.getById(route.params.id as string));
const defaultItem: ANode = {
id: '',
@@ -69,17 +69,17 @@ const defaultItem: ANode = {
const tree = computed(() => [defaultItem, ...useSidebarTree().tree.value]);
const updateCategory = async () => {
- if (ressource.value)
+ if (resource.value)
nodeStore
- .update(ressource.value)
+ .update(resource.value)
.then(() => {
- useNotifications().add({ type: 'success', title: 'Ressource updated' });
+ useNotifications().add({ type: 'success', title: 'Resource updated' });
useRouter().push('/dashboard/cdn');
})
.catch(e => useNotifications().add({ type: 'error', title: 'Error', message: e }));
};
const showDeleteModal = () => {
- useModal().add(new Modal(shallowRef(DeleteRessourceModal), { props: { ressources: [ressource.value?.id] } }));
+ useModal().add(new Modal(shallowRef(DeleteResourceModal), { props: { resources: [resource.value?.id] } }));
};
</script>
diff --git a/frontend/app/pages/dashboard/cdn/[id]/preview.vue b/frontend/app/pages/dashboard/cdn/[id]/preview.vue
index dcf63fe3..0e1a72c8 100644
--- a/frontend/app/pages/dashboard/cdn/[id]/preview.vue
+++ b/frontend/app/pages/dashboard/cdn/[id]/preview.vue
@@ -1,29 +1,29 @@
<template>
<div class="card-component">
- <div v-if="ressource">
+ <div v-if="resource">
<header style="display: flex; align-items: center; justify-content: space-between">
<h1>Preview <tag blue>New</tag></h1>
<div style="display: flex">
- <NuxtLink :to="`/dashboard/cdn/${ressource.id}`"><AppButton type="primary">Edit</AppButton></NuxtLink>
+ <NuxtLink :to="`/dashboard/cdn/${resource.id}`"><AppButton type="primary">Edit</AppButton></NuxtLink>
<AppButton type="secondary" @click="copyLink">Copy link</AppButton>
</div>
</header>
- Name: <strong>{{ ressource.name }}</strong>
+ Name: <strong>{{ resource.name }}</strong>
<p>
- Type: <strong>{{ ressource.metadata?.filetype }}</strong>
+ Type: <strong>{{ resource.metadata?.filetype }}</strong>
</p>
<p>
- Size: <strong>{{ readableFileSize(ressource.size ?? 0) }}</strong>
+ Size: <strong>{{ readableFileSize(resource.size ?? 0) }}</strong>
</p>
<div class="preview">
<img
- v-if="(ressource?.metadata?.filetype as string)?.startsWith('image/')"
- :src="`${CDN}/${ressource!.user_id}/${ressource!.metadata?.transformed_path || ressource!.content}`"
+ v-if="(resource?.metadata?.filetype as string)?.startsWith('image/')"
+ :src="`${CDN}/${resource!.user_id}/${resource!.metadata?.transformed_path || resource!.content}`"
alt="Preview"
/>
<iframe
- v-else-if="(ressource?.metadata?.filetype as string)?.startsWith('application/pdf')"
- :src="`${CDN}/${ressource!.user_id}/${ressource!.metadata?.transformed_path || ressource!.content}`"
+ v-else-if="(resource?.metadata?.filetype as string)?.startsWith('application/pdf')"
+ :src="`${CDN}/${resource!.user_id}/${resource!.metadata?.transformed_path || resource!.content}`"
width="100%"
height="500px"
frameborder="0"
@@ -36,13 +36,13 @@
</template>
<script setup lang="ts">
-import { readableFileSize } from '~/helpers/ressources';
+import { readableFileSize } from '~/helpers/resources';
definePageMeta({ breadcrumb: 'Preview' });
-const ressource = computed(() => useNodesStore().getById(useRoute().params.id as string));
+const resource = computed(() => useNodesStore().getById(useRoute().params.id as string));
const { CDN } = useApi();
const copyLink = () => {
- const link = `${CDN}/${ressource.value?.user_id}/${ressource.value?.metadata?.transformed_path || ressource.value?.content}`;
+ const link = `${CDN}/${resource.value?.user_id}/${resource.value?.metadata?.transformed_path || resource.value?.content}`;
navigator.clipboard.writeText(link);
};
</script>
diff --git a/frontend/app/pages/dashboard/cdn/_modals/DeleteRessourceModal.vue b/frontend/app/pages/dashboard/cdn/_modals/DeleteRessourceModal.vue
index bb7b1205..0be44b7a 100644
--- a/frontend/app/pages/dashboard/cdn/_modals/DeleteRessourceModal.vue
+++ b/frontend/app/pages/dashboard/cdn/_modals/DeleteRessourceModal.vue
@@ -1,28 +1,28 @@
<template>
<div class="modal">
- <h3>Delete {{ ressources.length > 1 ? 'ressources' : 'ressource' }}</h3>
+ <h3>Delete {{ resources.length > 1 ? 'resources' : 'resource' }}</h3>
<p>
- Are you sure you want to delete the selected {{ ressources.length > 1 ? 'ressources' : 'ressource' }}? <br />
- <span v-if="ressources.length > 1"
- >This action will delete <strong>{{ ressources.length }}</strong> ressources.</span
+ Are you sure you want to delete the selected {{ resources.length > 1 ? 'resources' : 'resource' }}? <br />
+ <span v-if="resources.length > 1"
+ >This action will delete <strong>{{ resources.length }}</strong> resources.</span
>
</p>
<p style="opacity: 0.7">This action is irreversible</p>
<div class="footer">
<AppButton type="secondary" @click="emit('close')">Cancel</AppButton>
- <AppButton type="danger" @click="deleteRessource">Confirm</AppButton>
+ <AppButton type="danger" @click="deleteResource">Confirm</AppButton>
</div>
</div>
</template>
<script setup lang="ts">
-const props = defineProps<{ ressources: string[] }>();
+const props = defineProps<{ resources: string[] }>();
const emit = defineEmits(['close']);
-const deleteRessource = async () => {
+const deleteResource = async () => {
await useNodesStore()
- .bulkDelete(props.ressources)
+ .bulkDelete(props.resources)
.then(() => {
emit('close');
useRouter().push('/dashboard/cdn');
diff --git a/frontend/app/pages/dashboard/cdn/index.vue b/frontend/app/pages/dashboard/cdn/index.vue
index 41ff3dc9..fa99caf5 100644
--- a/frontend/app/pages/dashboard/cdn/index.vue
+++ b/frontend/app/pages/dashboard/cdn/index.vue
@@ -3,7 +3,7 @@
<header>
<h1>File manager</h1>
<div class="action-row">
- <NodeFilter v-show="!device.isMobile" :nodes="nodes" @update:nodes="filteredRessources = $event" />
+ <NodeFilter v-show="!device.isMobile" :nodes="nodes" @update:nodes="filteredResources = $event" />
<ViewSelection v-model="view" />
</div>
</header>
@@ -38,7 +38,7 @@
<AppButton type="secondary" @click="fileLinks = []">Clear</AppButton>
</div>
</div>
- <div v-if="filteredRessources.length" class="ressources-list">
+ <div v-if="filteredResources.length" class="resources-list">
<DataTable v-if="view === 'table'" :headers="headers" :rows="rows">
<template #bulk-actions="{ selected }">
<div class="bulk-actions">
@@ -50,38 +50,38 @@
<template #action="{ cell }">
<NuxtLink :href="`/dashboard/cdn/${(cell?.data as Node).id}/preview`" style="margin-right: 10px"><Icon name="view" /> </NuxtLink>
<NuxtLink :to="`/dashboard/cdn/${(cell?.data as Node).id}`"><Icon name="edit" style="margin-right: 10px" /></NuxtLink>
- <span @click="() => deleteRessource((cell?.data as Node).id)"><Icon name="delete" /></span>
+ <span @click="() => deleteResource((cell?.data as Node).id)"><Icon name="delete" /></span>
</template>
</DataTable>
<div v-else>
<hr />
<div class="images-grid">
- <div v-for="image in filteredRessources" :key="image.id" class="image-item" @click="router.push(`/dashboard/cdn/${image.id}/preview`)">
+ <div v-for="image in filteredResources" :key="image.id" class="image-item" @click="router.push(`/dashboard/cdn/${image.id}/preview`)">
<img :src="fileURL(image)" :alt="image.name" class="image-preview" />
<div class="image-info">
<span class="image-name">{{ image.name }}</span>
<span class="image-size">{{ readableFileSize(image.size ?? 0) }}</span>
</div>
</div>
- <div v-if="!filteredRessources.length" class="not-found">
+ <div v-if="!filteredResources.length" class="not-found">
<p>No result found for "{{ filter }}"</p>
</div>
</div>
</div>
</div>
- <NoContent v-else title="No ressource found"></NoContent>
+ <NoContent v-else title="No resource found"></NoContent>
</div>
</template>
<script setup lang="ts">
-import DeleteRessourceModal from './_modals/DeleteRessourceModal.vue';
-import { readableFileSize } from '~/helpers/ressources';
+import DeleteResourceModal from './_modals/DeleteResourceModal.vue';
+import { readableFileSize } from '~/helpers/resources';
import type { Field } from '~/components/DataTable.vue';
import type { Node } from '~/stores';
definePageMeta({ breadcrumb: 'Upload' });
const router = useRouter();
-const ressourcesStore = useRessourcesStore();
+const resourcesStore = useResourcesStore();
const nodesStore = useNodesStore();
const device = useDevice();
@@ -99,8 +99,8 @@ const { CDN } = useApi();
const MAX_STORAGE = 1024 * 1024 * 1024; // 1 GB in bytes
-const nodes = computed(() => nodesStore.ressources.toArray());
-const filteredRessources = ref(nodes.value);
+const nodes = computed(() => nodesStore.resources.toArray());
+const filteredResources = ref(nodes.value);
const totalUsedSpace = computed(() => nodes.value.reduce((acc, node) => acc + (node.size ?? 0), 0));
const storagePercentage = computed(() => Math.min((totalUsedSpace.value / MAX_STORAGE) * 100, 100));
@@ -130,7 +130,7 @@ const submitFiles = async () => {
const body = new FormData();
body.append('file', file);
try {
- const r = await ressourcesStore.post(body);
+ const r = await resourcesStore.post(body);
fileLinks.value.push(`${CDN}/${(r as Node).user_id}/${(r as Node).metadata?.transformed_path as string}`);
} catch (e) {
useNotifications().add({ type: 'error', title: 'Error', message: `Failed to upload ${file.name}: ${e}` });
@@ -144,8 +144,8 @@ const submitFiles = async () => {
}
};
-const fileURL = (ressource: Node) => {
- if ((ressource.metadata?.filetype as string)?.includes('image/')) return `${CDN}/${ressource.user_id}/${ressource.metadata?.transformed_path as string}`;
+const fileURL = (resource: Node) => {
+ if ((resource.metadata?.filetype as string)?.includes('image/')) return `${CDN}/${resource.user_id}/${resource.metadata?.transformed_path as string}`;
return '/file_placeholder.png';
};
const headers = [
@@ -159,7 +159,7 @@ const headers = [
const color = (type: string) => (type.includes('image') ? 'green' : type.includes('video') ? 'blue' : type.includes('pdf') ? 'yellow' : 'red');
const rows: ComputedRef<Field[]> = computed(() =>
- filteredRessources.value.map(res => {
+ filteredResources.value.map(res => {
const parent = res.parent_id ? nodesStore.getById(res.parent_id) : null;
const category = parent ? nodesStore.getById(parent.parent_id || '') : null;
return {
@@ -173,12 +173,12 @@ const rows: ComputedRef<Field[]> = computed(() =>
}),
);
-const deleteRessource = async (id: string) => {
- useModal().add(new Modal(shallowRef(DeleteRessourceModal), { props: { ressources: [id] }, size: 'small' }));
+const deleteResource = async (id: string) => {
+ useModal().add(new Modal(shallowRef(DeleteResourceModal), { props: { resources: [id] }, size: 'small' }));
};
const bulkDelete = async (lines: Field[]) => {
- const ressourcesIds = lines.map(line => (line.action?.data as Node | undefined)?.id).filter((id): id is string => !!id);
- useModal().add(new Modal(shallowRef(DeleteRessourceModal), { props: { ressources: ressourcesIds }, size: 'small' }));
+ const resourcesIds = lines.map(line => (line.action?.data as Node | undefined)?.id).filter((id): id is string => !!id);
+ useModal().add(new Modal(shallowRef(DeleteResourceModal), { props: { resources: resourcesIds }, size: 'small' }));
};
</script>
@@ -312,7 +312,7 @@ const bulkDelete = async (lines: Field[]) => {
justify-content: center;
}
-.ressources-list {
+.resources-list {
width: 100%;
}
diff --git a/frontend/app/pages/dashboard/home.vue b/frontend/app/pages/dashboard/home.vue
index 7be3606c..0e551137 100644
--- a/frontend/app/pages/dashboard/home.vue
+++ b/frontend/app/pages/dashboard/home.vue
@@ -162,7 +162,7 @@ const userName = computed(() => userStore.user?.firstname || userStore.user?.use
const documentsCount = computed(() => nodesStore.documents.size);
const workspacesCount = computed(() => nodesStore.getAll.filter(n => n.role === 1).size);
const tagsCount = computed(() => nodesStore.getAllTags.length);
-const resourcesCount = computed(() => nodesStore.ressources.size);
+const resourcesCount = computed(() => nodesStore.resources.size);
// Recently edited documents (last 5, sorted by update time)
const recentlyEdited = computed(() => {
diff --git a/frontend/app/pages/dashboard/settings/_views/backups.vue b/frontend/app/pages/dashboard/settings/_views/backups.vue
index d7616ab3..d1b926c3 100644
--- a/frontend/app/pages/dashboard/settings/_views/backups.vue
+++ b/frontend/app/pages/dashboard/settings/_views/backups.vue
@@ -30,7 +30,7 @@ const fileName = () => `backup-${new Date().toISOString().split('T')[0]}.json`;
async function submitFile() {
isLoading.value = true;
- const result = await makeRequest<{ link: string }>('ressources/backup', 'GET', {});
+ const result = await makeRequest<{ link: string }>('resources/backup', 'GET', {});
isLoading.value = false;
if (result.status != 'success') return useNotifications().add({ type: 'error', title: 'Error', message: result.message });
downloadLink.value = `${CDN}/${result.result?.link || ''}`;
diff --git a/frontend/app/pages/dashboard/settings/_views/preferences.vue b/frontend/app/pages/dashboard/settings/_views/preferences.vue
index c9084d29..297c5ba7 100644
--- a/frontend/app/pages/dashboard/settings/_views/preferences.vue
+++ b/frontend/app/pages/dashboard/settings/_views/preferences.vue
@@ -149,12 +149,12 @@ const options: Array<{ label: string; options: InterfaceOption[] }> = [
key: 'normalizeFileIcons',
},
{
- label: 'Display uncategorized ressources',
+ label: 'Display uncategorized resources',
description: 'Show resources (uploads from CDN) that are not categorized at the top of the sidebar.',
type: 'toggle',
- key: 'displayUncategorizedRessources',
+ key: 'displayUncategorizedResources',
},
- { label: 'Hide ressources', type: 'toggle', key: 'hideSidebarRessources' },
+ { label: 'Hide resources', type: 'toggle', key: 'hideSidebarResources' },
{
label: 'Show items in Sidebar',
type: 'groupCheckbox',
diff --git a/frontend/app/pages/dashboard/settings/_views/profile.vue b/frontend/app/pages/dashboard/settings/_views/profile.vue
index 6281e24e..49ae7d00 100644
--- a/frontend/app/pages/dashboard/settings/_views/profile.vue
+++ b/frontend/app/pages/dashboard/settings/_views/profile.vue
@@ -34,7 +34,7 @@
<script setup lang="ts">
const userStore = useUserStore();
-const ressourcesStore = useRessourcesStore();
+const resourcesStore = useResourcesStore();
const api = useApi();
const { shortDate } = useDateFormatters();
@@ -51,7 +51,7 @@ const uploadAvatar = async () => {
if (!file) return;
const body = new FormData();
body.append('file', file);
- const r = await ressourcesStore.postAvatar(body);
+ const r = await resourcesStore.postAvatar(body);
return r.content_compiled || r.original_path;
};
const previewAvatar = (event: Event) => {
diff --git a/frontend/app/stores/db_strustures.d.ts b/frontend/app/stores/db_strustures.d.ts
index b81cedfd..0d537fd2 100644
--- a/frontend/app/stores/db_strustures.d.ts
+++ b/frontend/app/stores/db_strustures.d.ts
@@ -5,7 +5,7 @@ export interface DB_Node {
name: string;
description?: string;
tags?: string;
- role: -1 | 1 | 2 | 3 | 4; // 1: Workspace; 2: Category; 3: Document; 4: Ressource; -1: Internal (frontend use only)
+ role: -1 | 1 | 2 | 3 | 4; // 1: Workspace; 2: Category; 3: Document; 4: Resource; -1: Internal (frontend use only)
color?: number; // -1: Default; 0: None; 1-7: App colors
icon?: string;
thumbnail?: string;
diff --git a/frontend/app/stores/nodes.store.ts b/frontend/app/stores/nodes.store.ts
index fdddcd2f..086a41a0 100644
--- a/frontend/app/stores/nodes.store.ts
+++ b/frontend/app/stores/nodes.store.ts
@@ -31,7 +31,7 @@ export const useNodesStore = defineStore('nodes', {
getChilds: state => (id: string) => state.nodes.filter(c => c.parent_id == id),
categories: state => state.nodes.filter(d => d.role === 1 || d.role === 2),
documents: state => state.nodes.filter(d => d.role === 3),
- ressources: state => state.nodes.filter(d => d.role === 4),
+ resources: state => state.nodes.filter(d => d.role === 4),
isDescendant:
state =>
(node: Node, descendantId: string): boolean => {
diff --git a/frontend/app/stores/resources.store.ts b/frontend/app/stores/resources.store.ts
index bdfdf637..544a7251 100644
--- a/frontend/app/stores/resources.store.ts
+++ b/frontend/app/stores/resources.store.ts
@@ -1,17 +1,17 @@
import { makeRequest } from './_utils';
import type { Node } from './db_strustures';
-export const useRessourcesStore = defineStore('ressources', {
+export const useResourcesStore = defineStore('resources', {
state: () => ({}),
actions: {
- async post(ressource: FormData): Promise<Node> {
- const request = await makeRequest(`ressources`, 'POST', ressource);
+ async post(resource: FormData): Promise<Node> {
+ const request = await makeRequest(`resources`, 'POST', resource);
if (request.status == 'success') {
useNodesStore().nodes.set((request.result as Node).id, request.result as Node);
return request.result as Node;
} else throw request.message;
},
- async postAvatar(ressource: FormData): Promise<{ original_path: string; content_compiled: string }> {
- const request = await makeRequest(`ressources/avatar`, 'POST', ressource);
+ async postAvatar(resource: FormData): Promise<{ original_path: string; content_compiled: string }> {
+ const request = await makeRequest(`resources/avatar`, 'POST', resource);
if (request.status == 'success') {
return request.result as { original_path: string; content_compiled: string };
} else throw request.message;