Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b692fabed5 | |||
| 830e411d92 | |||
| b7995b7e4a | |||
| f043d38eb2 | |||
| 780f85de59 |
@@ -0,0 +1,67 @@
|
||||
# =============================================================================
|
||||
# Tanabata File Manager — .gitattributes
|
||||
# =============================================================================
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Line endings: normalize to LF in repo, native on checkout
|
||||
# ---------------------------------------------------------------------------
|
||||
* text=auto eol=lf
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Explicitly text
|
||||
# ---------------------------------------------------------------------------
|
||||
*.go text eol=lf
|
||||
*.mod text eol=lf
|
||||
*.sum text eol=lf
|
||||
*.sql text eol=lf
|
||||
*.ts text eol=lf
|
||||
*.js text eol=lf
|
||||
*.svelte text eol=lf
|
||||
*.html text eol=lf
|
||||
*.css text eol=lf
|
||||
*.json text eol=lf
|
||||
*.yaml text eol=lf
|
||||
*.yml text eol=lf
|
||||
*.md text eol=lf
|
||||
*.txt text eol=lf
|
||||
*.env* text eol=lf
|
||||
*.sh text eol=lf
|
||||
*.toml text eol=lf
|
||||
*.xml text eol=lf
|
||||
*.svg text eol=lf
|
||||
Dockerfile text eol=lf
|
||||
Makefile text eol=lf
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Explicitly binary
|
||||
# ---------------------------------------------------------------------------
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.webp binary
|
||||
*.ico binary
|
||||
*.ttf binary
|
||||
*.woff binary
|
||||
*.woff2 binary
|
||||
*.eot binary
|
||||
*.otf binary
|
||||
*.zip binary
|
||||
*.gz binary
|
||||
*.tar binary
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Diff behavior
|
||||
# ---------------------------------------------------------------------------
|
||||
*.sql diff=sql
|
||||
*.go diff=golang
|
||||
*.css diff=css
|
||||
*.html diff=html
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Linguist: set repo language stats correctly
|
||||
# ---------------------------------------------------------------------------
|
||||
docs/reference/** linguist-documentation
|
||||
frontend/static/** linguist-vendored
|
||||
*.min.js linguist-vendored
|
||||
*.min.css linguist-vendored
|
||||
@@ -1,3 +1,86 @@
|
||||
venv/
|
||||
*__pycache__/
|
||||
.st*
|
||||
# =============================================================================
|
||||
# Tanabata File Manager — .gitignore
|
||||
# =============================================================================
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Environment & secrets
|
||||
# ---------------------------------------------------------------------------
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
*.pem
|
||||
*.key
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OS
|
||||
# ---------------------------------------------------------------------------
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
Desktop.ini
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# IDE
|
||||
# ---------------------------------------------------------------------------
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
!.vscode/settings.json
|
||||
.idea/
|
||||
*.iml
|
||||
*.sublime-project
|
||||
*.sublime-workspace
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Backend (Go)
|
||||
# ---------------------------------------------------------------------------
|
||||
backend/tmp/
|
||||
backend/cmd/server/server
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
*.test
|
||||
*.out
|
||||
*.prof
|
||||
coverage.out
|
||||
coverage.html
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Frontend (SvelteKit / Node)
|
||||
# ---------------------------------------------------------------------------
|
||||
frontend/node_modules/
|
||||
frontend/.svelte-kit/
|
||||
frontend/build/
|
||||
frontend/dist/
|
||||
frontend/src/lib/api/schema.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Docker
|
||||
# ---------------------------------------------------------------------------
|
||||
docker-compose.override.yml
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Data directories (runtime, not in repo)
|
||||
# ---------------------------------------------------------------------------
|
||||
data/
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Misc
|
||||
# ---------------------------------------------------------------------------
|
||||
*.log
|
||||
*.pid
|
||||
*.seed
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Reference: exclude vendored libs, keep design sources
|
||||
# ---------------------------------------------------------------------------
|
||||
docs/reference/**/bootstrap.min.css
|
||||
docs/reference/**/bootstrap.min.css.map
|
||||
docs/reference/**/jquery-*.min.js
|
||||
docs/reference/**/__pycache__/
|
||||
docs/reference/**/*.pyc
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Tanabata File Manager
|
||||
|
||||
Multi-user, tag-based web file manager for images and video.
|
||||
|
||||
## Architecture
|
||||
|
||||
Monorepo: `backend/` (Go) + `frontend/` (SvelteKit).
|
||||
|
||||
- Backend: Go + Gin + pgx v5 + goose migrations. Clean Architecture.
|
||||
- Frontend: SvelteKit SPA + Tailwind CSS + CSS custom properties.
|
||||
- DB: PostgreSQL 14+.
|
||||
- Auth: JWT Bearer tokens.
|
||||
|
||||
## Key documents (read before coding)
|
||||
|
||||
- `openapi.yaml` — full REST API specification (36 paths, 58 operations)
|
||||
- `docs/GO_PROJECT_STRUCTURE.md` — backend architecture, layer rules, DI pattern
|
||||
- `docs/FRONTEND_STRUCTURE.md` — frontend architecture, CSS approach, API client
|
||||
- `docs/Описание.md` — product requirements in Russian
|
||||
- `backend/migrations/001_init.sql` — database schema (4 schemas, 16 tables)
|
||||
|
||||
## Design reference
|
||||
|
||||
The `docs/reference/` directory contains the previous Python/Flask version.
|
||||
Use its visual design as the basis for the new frontend:
|
||||
- Color palette: #312F45 (bg), #9592B5 (accent), #444455 (tag default), #111118 (elevated)
|
||||
- Font: Epilogue (variable weight)
|
||||
- Dark theme is primary
|
||||
- Mobile-first layout with bottom navbar
|
||||
- 160×160 thumbnail grid for files
|
||||
- Colored tag pills
|
||||
- Floating selection bar for multi-select
|
||||
|
||||
## Backend commands
|
||||
```bash
|
||||
cd backend
|
||||
go run ./cmd/server # run dev server
|
||||
go test ./... # run all tests
|
||||
```
|
||||
|
||||
## Frontend commands
|
||||
```bash
|
||||
cd frontend
|
||||
npm run dev # vite dev server
|
||||
npm run build # production build
|
||||
npm run generate:types # regenerate API types from openapi.yaml
|
||||
```
|
||||
|
||||
## Conventions
|
||||
|
||||
- Go: gofmt, no global state, context.Context as first param in all service methods
|
||||
- TypeScript: strict mode, named exports
|
||||
- SQL: snake_case, all migrations via goose
|
||||
- API errors: { code, message, details? }
|
||||
- Git: conventional commits (feat:, fix:, docs:, refactor:)
|
||||
@@ -1,22 +0,0 @@
|
||||
<h1 align="center">🎋 Tanabata File Manager 🎋</h1>
|
||||
|
||||
---
|
||||
|
||||
<!-- [![Release version][release-shield]][release-link] -->
|
||||
|
||||
## Contents
|
||||
|
||||
- [About](#about)
|
||||
|
||||
## About
|
||||
|
||||
Tanabata (_jp._ 七夕) is Japanese festival. People generally celebrate this day (July 7th) by writing wishes, sometimes in the form of poetry, on _tanzaku_ (_jp._ 短冊), small pieces of paper, and hanging them on _sasa_ (_jp._ 笹), bamboo. See [this Wikipedia page](https://en.wikipedia.org/wiki/Tanabata) for more information.
|
||||
|
||||
Tanabata File Manager is a software project that will let you enjoy the Tanabata festival. It allows you to store and organize your files as _sasa_ bamboos, on which you can hang almost any number of _tanzaku_, just like adding tags on it.
|
||||
|
||||
---
|
||||
|
||||
<h6 align="center"><i>© Masahiko AMANO aka H1K0, 2022—present</i></h6>
|
||||
|
||||
<!-- [release-shield]: https://img.shields.io/github/release/H1K0/tanabata/all.svg?style=for-the-badge
|
||||
[release-link]: https://github.com/H1K0/tanabata/releases -->
|
||||
@@ -1,5 +0,0 @@
|
||||
title: Tanabata FM
|
||||
description: Web file manager with tags!
|
||||
remote_theme: pages-themes/merlot@v0.2.0
|
||||
plugins:
|
||||
- jekyll-remote-theme
|
||||
@@ -0,0 +1,5 @@
|
||||
module tanabata/backend
|
||||
|
||||
go 1.21
|
||||
|
||||
require github.com/google/uuid v1.6.0
|
||||
@@ -0,0 +1,2 @@
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
@@ -0,0 +1,19 @@
|
||||
package domain
|
||||
|
||||
import "github.com/google/uuid"
|
||||
|
||||
// ObjectType is a reference entity (file, tag, category, pool).
|
||||
type ObjectType struct {
|
||||
ID int16
|
||||
Name string
|
||||
}
|
||||
|
||||
// Permission represents a per-object access entry for a user.
|
||||
type Permission struct {
|
||||
UserID int16
|
||||
UserName string // denormalized
|
||||
ObjectTypeID int16
|
||||
ObjectID uuid.UUID
|
||||
CanView bool
|
||||
CanEdit bool
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// ActionType is a reference entity for auditable user actions.
|
||||
type ActionType struct {
|
||||
ID int16
|
||||
Name string
|
||||
}
|
||||
|
||||
// AuditEntry is a single audit log record.
|
||||
type AuditEntry struct {
|
||||
ID int64
|
||||
UserID int16
|
||||
UserName string // denormalized
|
||||
Action string // action type name, e.g. "file_create"
|
||||
ObjectType *string
|
||||
ObjectID *uuid.UUID
|
||||
Details json.RawMessage
|
||||
PerformedAt time.Time
|
||||
}
|
||||
|
||||
// AuditPage is an offset-based page of audit log entries.
|
||||
type AuditPage struct {
|
||||
Items []AuditEntry
|
||||
Total int
|
||||
Offset int
|
||||
Limit int
|
||||
}
|
||||
|
||||
// AuditFilter holds filter parameters for querying the audit log.
|
||||
type AuditFilter struct {
|
||||
UserID *int16
|
||||
Action string
|
||||
ObjectType string
|
||||
ObjectID *uuid.UUID
|
||||
From *time.Time
|
||||
To *time.Time
|
||||
Offset int
|
||||
Limit int
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Category is a logical grouping of tags.
|
||||
type Category struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
Notes *string
|
||||
Color *string // 6-char hex
|
||||
Metadata json.RawMessage
|
||||
CreatorID int16
|
||||
CreatorName string // denormalized
|
||||
IsPublic bool
|
||||
CreatedAt time.Time // extracted from UUID v7
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package domain
|
||||
|
||||
import "context"
|
||||
|
||||
type ctxKey int
|
||||
|
||||
const userKey ctxKey = iota
|
||||
|
||||
type contextUser struct {
|
||||
ID int16
|
||||
IsAdmin bool
|
||||
}
|
||||
|
||||
func WithUser(ctx context.Context, userID int16, isAdmin bool) context.Context {
|
||||
return context.WithValue(ctx, userKey, contextUser{ID: userID, IsAdmin: isAdmin})
|
||||
}
|
||||
|
||||
func UserFromContext(ctx context.Context) (userID int16, isAdmin bool) {
|
||||
u, ok := ctx.Value(userKey).(contextUser)
|
||||
if !ok {
|
||||
return 0, false
|
||||
}
|
||||
return u.ID, u.IsAdmin
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package domain
|
||||
|
||||
import "errors"
|
||||
|
||||
// Sentinel domain errors. Handlers map these to HTTP status codes.
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrForbidden = errors.New("forbidden")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrValidation = errors.New("validation error")
|
||||
ErrUnsupportedMIME = errors.New("unsupported MIME type")
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// MIMEType holds MIME whitelist data.
|
||||
type MIMEType struct {
|
||||
ID int16
|
||||
Name string
|
||||
Extension string
|
||||
}
|
||||
|
||||
// File represents a managed file record.
|
||||
type File struct {
|
||||
ID uuid.UUID
|
||||
OriginalName *string
|
||||
MIMEType string // denormalized from core.mime_types
|
||||
MIMEExtension string // denormalized from core.mime_types
|
||||
ContentDatetime time.Time
|
||||
Notes *string
|
||||
Metadata json.RawMessage
|
||||
EXIF json.RawMessage
|
||||
PHash *int64
|
||||
CreatorID int16
|
||||
CreatorName string // denormalized from core.users
|
||||
IsPublic bool
|
||||
IsDeleted bool
|
||||
CreatedAt time.Time // extracted from UUID v7
|
||||
Tags []Tag // loaded with the file
|
||||
}
|
||||
|
||||
// FileListParams holds all parameters for listing/filtering files.
|
||||
type FileListParams struct {
|
||||
Filter string
|
||||
Sort string
|
||||
Order string
|
||||
Cursor string
|
||||
Anchor *uuid.UUID
|
||||
Direction string // "forward" or "backward"
|
||||
Limit int
|
||||
Trash bool
|
||||
Search string
|
||||
}
|
||||
|
||||
// FilePage is the result of a cursor-based file listing.
|
||||
type FilePage struct {
|
||||
Items []File
|
||||
NextCursor *string
|
||||
PrevCursor *string
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Pool is an ordered collection of files.
|
||||
type Pool struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
Notes *string
|
||||
Metadata json.RawMessage
|
||||
CreatorID int16
|
||||
CreatorName string // denormalized
|
||||
IsPublic bool
|
||||
FileCount int
|
||||
CreatedAt time.Time // extracted from UUID v7
|
||||
}
|
||||
|
||||
// PoolFile is a File with its ordering position within a pool.
|
||||
type PoolFile struct {
|
||||
File
|
||||
Position int
|
||||
}
|
||||
|
||||
// PoolFilePage is the result of a cursor-based pool file listing.
|
||||
type PoolFilePage struct {
|
||||
Items []PoolFile
|
||||
NextCursor *string
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Tag represents a file label.
|
||||
type Tag struct {
|
||||
ID uuid.UUID
|
||||
Name string
|
||||
Notes *string
|
||||
Color *string // 6-char hex, e.g. "5DCAA5"
|
||||
CategoryID *uuid.UUID
|
||||
CategoryName *string // denormalized
|
||||
CategoryColor *string // denormalized
|
||||
Metadata json.RawMessage
|
||||
CreatorID int16
|
||||
CreatorName string // denormalized
|
||||
IsPublic bool
|
||||
CreatedAt time.Time // extracted from UUID v7
|
||||
}
|
||||
|
||||
// TagRule defines an auto-tagging rule: when WhenTagID is applied,
|
||||
// ThenTagID is automatically applied as well.
|
||||
type TagRule struct {
|
||||
WhenTagID uuid.UUID
|
||||
ThenTagID uuid.UUID
|
||||
ThenTagName string // denormalized
|
||||
IsActive bool
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package domain
|
||||
|
||||
import "time"
|
||||
|
||||
// User is an application user.
|
||||
type User struct {
|
||||
ID int16
|
||||
Name string
|
||||
Password string // bcrypt hash; only populated when needed for auth
|
||||
IsAdmin bool
|
||||
CanCreate bool
|
||||
IsBlocked bool
|
||||
}
|
||||
|
||||
// Session is an active user session.
|
||||
type Session struct {
|
||||
ID int
|
||||
TokenHash string
|
||||
UserID int16
|
||||
UserAgent string
|
||||
StartedAt time.Time
|
||||
ExpiresAt *time.Time
|
||||
LastActivity time.Time
|
||||
IsCurrent bool // true when this session matches the caller's token
|
||||
}
|
||||
|
||||
// OffsetPage is a generic offset-based page of users.
|
||||
type UserPage struct {
|
||||
Items []User
|
||||
Total int
|
||||
Offset int
|
||||
Limit int
|
||||
}
|
||||
|
||||
// SessionList is a list of sessions with a total count.
|
||||
type SessionList struct {
|
||||
Items []Session
|
||||
Total int
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||
|
||||
CREATE SCHEMA IF NOT EXISTS core;
|
||||
CREATE SCHEMA IF NOT EXISTS data;
|
||||
CREATE SCHEMA IF NOT EXISTS acl;
|
||||
CREATE SCHEMA IF NOT EXISTS activity;
|
||||
|
||||
-- UUID v7 generator
|
||||
CREATE OR REPLACE FUNCTION public.uuid_v7(cts timestamptz DEFAULT clock_timestamp())
|
||||
RETURNS uuid LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
state text = current_setting('uuidv7.old_tp', true);
|
||||
old_tp text = split_part(state, ':', 1);
|
||||
base int = coalesce(nullif(split_part(state, ':', 4), '')::int, (random()*16777215/2-1)::int);
|
||||
tp text;
|
||||
entropy text;
|
||||
seq text = base;
|
||||
seqn int = split_part(state, ':', 2);
|
||||
ver text = coalesce(split_part(state, ':', 3), to_hex(8+(random()*3)::int));
|
||||
BEGIN
|
||||
base = (random()*16777215/2-1)::int;
|
||||
tp = lpad(to_hex(floor(extract(epoch from cts)*1000)::int8), 12, '0') || '7';
|
||||
IF tp IS DISTINCT FROM old_tp THEN
|
||||
old_tp = tp;
|
||||
ver = to_hex(8+(random()*3)::int);
|
||||
base = (random()*16777215/2-1)::int;
|
||||
seqn = base;
|
||||
ELSE
|
||||
seqn = seqn + (random()*1000)::int;
|
||||
END IF;
|
||||
PERFORM set_config('uuidv7.old_tp', old_tp||':'||seqn||':'||ver||':'||base, false);
|
||||
entropy = md5(gen_random_uuid()::text);
|
||||
seq = lpad(to_hex(seqn), 6, '0');
|
||||
RETURN (tp || substring(seq from 1 for 3) || ver || substring(seq from 4 for 3) ||
|
||||
substring(entropy from 1 for 12))::uuid;
|
||||
END;
|
||||
$$;
|
||||
|
||||
-- Extract timestamp from UUID v7
|
||||
CREATE OR REPLACE FUNCTION public.uuid_extract_timestamp(uuid_val uuid)
|
||||
RETURNS timestamptz LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $$
|
||||
SELECT to_timestamp(
|
||||
('x' || left(replace(uuid_val::text, '-', ''), 12))::bit(48)::bigint / 1000.0
|
||||
);
|
||||
$$;
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP FUNCTION IF EXISTS public.uuid_extract_timestamp(uuid);
|
||||
DROP FUNCTION IF EXISTS public.uuid_v7(timestamptz);
|
||||
|
||||
DROP SCHEMA IF EXISTS activity;
|
||||
DROP SCHEMA IF EXISTS acl;
|
||||
DROP SCHEMA IF EXISTS data;
|
||||
DROP SCHEMA IF EXISTS core;
|
||||
|
||||
DROP EXTENSION IF EXISTS "uuid-ossp";
|
||||
DROP EXTENSION IF EXISTS pgcrypto;
|
||||
@@ -0,0 +1,36 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE core.users (
|
||||
id smallint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
name varchar(32) NOT NULL,
|
||||
password text NOT NULL, -- bcrypt hash via pgcrypto
|
||||
is_admin boolean NOT NULL DEFAULT false,
|
||||
can_create boolean NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT uni__users__name UNIQUE (name)
|
||||
);
|
||||
|
||||
CREATE TABLE core.mime_types (
|
||||
id smallint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
name varchar(127) NOT NULL,
|
||||
extension varchar(16) NOT NULL,
|
||||
|
||||
CONSTRAINT uni__mime_types__name UNIQUE (name)
|
||||
);
|
||||
|
||||
CREATE TABLE core.object_types (
|
||||
id smallint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
name varchar(32) NOT NULL,
|
||||
|
||||
CONSTRAINT uni__object_types__name UNIQUE (name)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE core.users IS 'Application users';
|
||||
COMMENT ON TABLE core.mime_types IS 'Whitelist of supported MIME types';
|
||||
COMMENT ON TABLE core.object_types IS 'Reference: entity types for ACL and audit log';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS core.object_types;
|
||||
DROP TABLE IF EXISTS core.mime_types;
|
||||
DROP TABLE IF EXISTS core.users;
|
||||
@@ -0,0 +1,118 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE data.categories (
|
||||
id uuid NOT NULL DEFAULT public.uuid_v7() PRIMARY KEY,
|
||||
name varchar(256) NOT NULL,
|
||||
notes text,
|
||||
color char(6),
|
||||
metadata jsonb,
|
||||
creator_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
is_public boolean NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT uni__categories__name UNIQUE (name),
|
||||
CONSTRAINT chk__categories__color_hex
|
||||
CHECK (color IS NULL OR color ~* '^[A-Fa-f0-9]{6}$')
|
||||
);
|
||||
|
||||
CREATE TABLE data.tags (
|
||||
id uuid NOT NULL DEFAULT public.uuid_v7() PRIMARY KEY,
|
||||
name varchar(256) NOT NULL,
|
||||
notes text,
|
||||
color char(6),
|
||||
category_id uuid REFERENCES data.categories(id)
|
||||
ON UPDATE CASCADE ON DELETE SET NULL,
|
||||
metadata jsonb,
|
||||
creator_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
is_public boolean NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT uni__tags__name UNIQUE (name),
|
||||
CONSTRAINT chk__tags__color_hex
|
||||
CHECK (color IS NULL OR color ~* '^[A-Fa-f0-9]{6}$')
|
||||
);
|
||||
|
||||
CREATE TABLE data.tag_rules (
|
||||
when_tag_id uuid NOT NULL REFERENCES data.tags(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
then_tag_id uuid NOT NULL REFERENCES data.tags(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
is_active boolean NOT NULL DEFAULT true,
|
||||
|
||||
PRIMARY KEY (when_tag_id, then_tag_id)
|
||||
);
|
||||
|
||||
CREATE TABLE data.files (
|
||||
id uuid NOT NULL DEFAULT public.uuid_v7() PRIMARY KEY,
|
||||
original_name varchar(256), -- original filename at upload time
|
||||
mime_id smallint NOT NULL REFERENCES core.mime_types(id)
|
||||
ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
content_datetime timestamptz NOT NULL DEFAULT clock_timestamp(), -- content datetime (e.g. photo taken)
|
||||
notes text,
|
||||
metadata jsonb, -- user-editable key-value data
|
||||
exif jsonb NOT NULL DEFAULT '{}'::jsonb, -- EXIF data extracted at upload (immutable)
|
||||
phash bigint, -- perceptual hash for duplicate detection (future)
|
||||
creator_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
is_public boolean NOT NULL DEFAULT false,
|
||||
is_deleted boolean NOT NULL DEFAULT false -- soft delete (trash)
|
||||
);
|
||||
|
||||
CREATE TABLE data.file_tag (
|
||||
file_id uuid NOT NULL REFERENCES data.files(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
tag_id uuid NOT NULL REFERENCES data.tags(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
|
||||
PRIMARY KEY (file_id, tag_id)
|
||||
);
|
||||
|
||||
CREATE TABLE data.pools (
|
||||
id uuid NOT NULL DEFAULT public.uuid_v7() PRIMARY KEY,
|
||||
name varchar(256) NOT NULL,
|
||||
notes text,
|
||||
metadata jsonb,
|
||||
creator_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
is_public boolean NOT NULL DEFAULT false,
|
||||
|
||||
CONSTRAINT uni__pools__name UNIQUE (name)
|
||||
);
|
||||
|
||||
-- `position` uses integer with gaps (e.g. 1000, 2000, 3000) to allow
|
||||
-- insertions without renumbering. Compact when gaps get too small.
|
||||
CREATE TABLE data.file_pool (
|
||||
file_id uuid NOT NULL REFERENCES data.files(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
pool_id uuid NOT NULL REFERENCES data.pools(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
position integer NOT NULL DEFAULT 0,
|
||||
|
||||
PRIMARY KEY (file_id, pool_id)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE data.categories IS 'Logical grouping of tags';
|
||||
COMMENT ON TABLE data.tags IS 'File labels/tags';
|
||||
COMMENT ON TABLE data.tag_rules IS 'Auto-tagging rules: when when_tag is assigned, then_tag follows';
|
||||
COMMENT ON TABLE data.files IS 'Managed files; actual content stored on disk as {id}.{ext}';
|
||||
COMMENT ON TABLE data.file_tag IS 'Many-to-many: files <-> tags';
|
||||
COMMENT ON TABLE data.pools IS 'Ordered collections of files';
|
||||
COMMENT ON TABLE data.file_pool IS 'Many-to-many: files <-> pools, with ordering';
|
||||
|
||||
COMMENT ON COLUMN data.files.original_name IS 'Original filename at upload time';
|
||||
COMMENT ON COLUMN data.files.content_datetime IS 'Content datetime (e.g. when photo was taken); falls back to EXIF DateTimeOriginal';
|
||||
COMMENT ON COLUMN data.files.metadata IS 'User-editable key-value metadata';
|
||||
COMMENT ON COLUMN data.files.exif IS 'EXIF data extracted at upload time (immutable, system-managed)';
|
||||
COMMENT ON COLUMN data.files.phash IS 'Perceptual hash for image/video duplicate detection';
|
||||
COMMENT ON COLUMN data.files.is_deleted IS 'Soft-deleted files (trash); true = in recycle bin';
|
||||
COMMENT ON COLUMN data.file_pool.position IS 'Manual ordering within pool; uses gapped integers';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS data.file_pool;
|
||||
DROP TABLE IF EXISTS data.pools;
|
||||
DROP TABLE IF EXISTS data.file_tag;
|
||||
DROP TABLE IF EXISTS data.files;
|
||||
DROP TABLE IF EXISTS data.tag_rules;
|
||||
DROP TABLE IF EXISTS data.tags;
|
||||
DROP TABLE IF EXISTS data.categories;
|
||||
@@ -0,0 +1,22 @@
|
||||
-- +goose Up
|
||||
|
||||
-- If is_public=true on the object, it is accessible to everyone (ACL ignored).
|
||||
-- If is_public=false, only creator and users with can_view=true see it.
|
||||
-- Admins bypass all ACL checks.
|
||||
CREATE TABLE acl.permissions (
|
||||
user_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
object_type_id smallint NOT NULL REFERENCES core.object_types(id)
|
||||
ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
object_id uuid NOT NULL,
|
||||
can_view boolean NOT NULL DEFAULT true,
|
||||
can_edit boolean NOT NULL DEFAULT false,
|
||||
|
||||
PRIMARY KEY (user_id, object_type_id, object_id)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE acl.permissions IS 'Per-object permissions (used when is_public=false)';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS acl.permissions;
|
||||
@@ -0,0 +1,81 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE activity.action_types (
|
||||
id smallint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
name varchar(64) NOT NULL,
|
||||
|
||||
CONSTRAINT uni__action_types__name UNIQUE (name)
|
||||
);
|
||||
|
||||
CREATE TABLE activity.sessions (
|
||||
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
token_hash text NOT NULL, -- hashed session token
|
||||
user_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
user_agent varchar(256) NOT NULL,
|
||||
started_at timestamptz NOT NULL DEFAULT statement_timestamp(),
|
||||
expires_at timestamptz,
|
||||
last_activity timestamptz NOT NULL DEFAULT statement_timestamp(),
|
||||
|
||||
CONSTRAINT uni__sessions__token_hash UNIQUE (token_hash)
|
||||
);
|
||||
|
||||
CREATE TABLE activity.file_views (
|
||||
file_id uuid NOT NULL REFERENCES data.files(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
user_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
viewed_at timestamptz NOT NULL DEFAULT statement_timestamp(),
|
||||
|
||||
PRIMARY KEY (file_id, viewed_at, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE activity.pool_views (
|
||||
pool_id uuid NOT NULL REFERENCES data.pools(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
user_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
viewed_at timestamptz NOT NULL DEFAULT statement_timestamp(),
|
||||
|
||||
PRIMARY KEY (pool_id, viewed_at, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE activity.tag_uses (
|
||||
tag_id uuid NOT NULL REFERENCES data.tags(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
user_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE CASCADE,
|
||||
used_at timestamptz NOT NULL DEFAULT statement_timestamp(),
|
||||
is_included boolean NOT NULL, -- true=included in filter, false=excluded
|
||||
|
||||
PRIMARY KEY (tag_id, used_at, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE activity.audit_log (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
user_id smallint NOT NULL REFERENCES core.users(id)
|
||||
ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
action_type_id smallint NOT NULL REFERENCES activity.action_types(id)
|
||||
ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
object_type_id smallint REFERENCES core.object_types(id)
|
||||
ON UPDATE CASCADE ON DELETE RESTRICT,
|
||||
object_id uuid,
|
||||
details jsonb, -- action-specific payload
|
||||
performed_at timestamptz NOT NULL DEFAULT statement_timestamp()
|
||||
);
|
||||
|
||||
COMMENT ON TABLE activity.action_types IS 'Reference: types of auditable user actions';
|
||||
COMMENT ON TABLE activity.sessions IS 'Active user sessions';
|
||||
COMMENT ON TABLE activity.file_views IS 'File view history';
|
||||
COMMENT ON TABLE activity.pool_views IS 'Pool view history';
|
||||
COMMENT ON TABLE activity.tag_uses IS 'Tag usage in filters';
|
||||
COMMENT ON TABLE activity.audit_log IS 'Unified audit trail for all user actions';
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE IF EXISTS activity.audit_log;
|
||||
DROP TABLE IF EXISTS activity.tag_uses;
|
||||
DROP TABLE IF EXISTS activity.pool_views;
|
||||
DROP TABLE IF EXISTS activity.file_views;
|
||||
DROP TABLE IF EXISTS activity.sessions;
|
||||
DROP TABLE IF EXISTS activity.action_types;
|
||||
@@ -0,0 +1,87 @@
|
||||
-- +goose Up
|
||||
|
||||
-- core
|
||||
CREATE INDEX idx__users__name ON core.users USING hash (name);
|
||||
|
||||
-- data.categories
|
||||
CREATE INDEX idx__categories__creator_id ON data.categories USING hash (creator_id);
|
||||
|
||||
-- data.tags
|
||||
CREATE INDEX idx__tags__category_id ON data.tags USING hash (category_id);
|
||||
CREATE INDEX idx__tags__creator_id ON data.tags USING hash (creator_id);
|
||||
|
||||
-- data.tag_rules
|
||||
CREATE INDEX idx__tag_rules__when ON data.tag_rules USING hash (when_tag_id);
|
||||
CREATE INDEX idx__tag_rules__then ON data.tag_rules USING hash (then_tag_id);
|
||||
|
||||
-- data.files
|
||||
CREATE INDEX idx__files__mime_id ON data.files USING hash (mime_id);
|
||||
CREATE INDEX idx__files__creator_id ON data.files USING hash (creator_id);
|
||||
CREATE INDEX idx__files__content_datetime ON data.files USING btree (content_datetime DESC NULLS LAST);
|
||||
CREATE INDEX idx__files__is_deleted ON data.files USING btree (is_deleted) WHERE is_deleted = true;
|
||||
CREATE INDEX idx__files__phash ON data.files USING btree (phash) WHERE phash IS NOT NULL;
|
||||
|
||||
-- data.file_tag
|
||||
CREATE INDEX idx__file_tag__tag_id ON data.file_tag USING hash (tag_id);
|
||||
CREATE INDEX idx__file_tag__file_id ON data.file_tag USING hash (file_id);
|
||||
|
||||
-- data.pools
|
||||
CREATE INDEX idx__pools__creator_id ON data.pools USING hash (creator_id);
|
||||
|
||||
-- data.file_pool
|
||||
CREATE INDEX idx__file_pool__pool_id ON data.file_pool USING hash (pool_id);
|
||||
CREATE INDEX idx__file_pool__file_id ON data.file_pool USING hash (file_id);
|
||||
|
||||
-- acl.permissions
|
||||
CREATE INDEX idx__acl__object ON acl.permissions USING btree (object_type_id, object_id);
|
||||
CREATE INDEX idx__acl__user ON acl.permissions USING hash (user_id);
|
||||
|
||||
-- activity.sessions
|
||||
CREATE INDEX idx__sessions__user_id ON activity.sessions USING hash (user_id);
|
||||
CREATE INDEX idx__sessions__token_hash ON activity.sessions USING hash (token_hash);
|
||||
|
||||
-- activity.file_views
|
||||
CREATE INDEX idx__file_views__user_id ON activity.file_views USING hash (user_id);
|
||||
|
||||
-- activity.pool_views
|
||||
CREATE INDEX idx__pool_views__user_id ON activity.pool_views USING hash (user_id);
|
||||
|
||||
-- activity.tag_uses
|
||||
CREATE INDEX idx__tag_uses__user_id ON activity.tag_uses USING hash (user_id);
|
||||
|
||||
-- activity.audit_log
|
||||
CREATE INDEX idx__audit_log__user_id ON activity.audit_log USING hash (user_id);
|
||||
CREATE INDEX idx__audit_log__action_type_id ON activity.audit_log USING hash (action_type_id);
|
||||
CREATE INDEX idx__audit_log__object ON activity.audit_log USING btree (object_type_id, object_id)
|
||||
WHERE object_id IS NOT NULL;
|
||||
CREATE INDEX idx__audit_log__performed_at ON activity.audit_log USING btree (performed_at DESC);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP INDEX IF EXISTS activity.idx__audit_log__performed_at;
|
||||
DROP INDEX IF EXISTS activity.idx__audit_log__object;
|
||||
DROP INDEX IF EXISTS activity.idx__audit_log__action_type_id;
|
||||
DROP INDEX IF EXISTS activity.idx__audit_log__user_id;
|
||||
DROP INDEX IF EXISTS activity.idx__tag_uses__user_id;
|
||||
DROP INDEX IF EXISTS activity.idx__pool_views__user_id;
|
||||
DROP INDEX IF EXISTS activity.idx__file_views__user_id;
|
||||
DROP INDEX IF EXISTS activity.idx__sessions__token_hash;
|
||||
DROP INDEX IF EXISTS activity.idx__sessions__user_id;
|
||||
DROP INDEX IF EXISTS acl.idx__acl__user;
|
||||
DROP INDEX IF EXISTS acl.idx__acl__object;
|
||||
DROP INDEX IF EXISTS data.idx__file_pool__file_id;
|
||||
DROP INDEX IF EXISTS data.idx__file_pool__pool_id;
|
||||
DROP INDEX IF EXISTS data.idx__pools__creator_id;
|
||||
DROP INDEX IF EXISTS data.idx__file_tag__file_id;
|
||||
DROP INDEX IF EXISTS data.idx__file_tag__tag_id;
|
||||
DROP INDEX IF EXISTS data.idx__files__phash;
|
||||
DROP INDEX IF EXISTS data.idx__files__is_deleted;
|
||||
DROP INDEX IF EXISTS data.idx__files__content_datetime;
|
||||
DROP INDEX IF EXISTS data.idx__files__creator_id;
|
||||
DROP INDEX IF EXISTS data.idx__files__mime_id;
|
||||
DROP INDEX IF EXISTS data.idx__tag_rules__then;
|
||||
DROP INDEX IF EXISTS data.idx__tag_rules__when;
|
||||
DROP INDEX IF EXISTS data.idx__tags__creator_id;
|
||||
DROP INDEX IF EXISTS data.idx__tags__category_id;
|
||||
DROP INDEX IF EXISTS data.idx__categories__creator_id;
|
||||
DROP INDEX IF EXISTS core.idx__users__name;
|
||||
@@ -0,0 +1,32 @@
|
||||
-- +goose Up
|
||||
|
||||
INSERT INTO core.object_types (name) VALUES
|
||||
('file'), ('tag'), ('category'), ('pool');
|
||||
|
||||
INSERT INTO activity.action_types (name) VALUES
|
||||
-- Auth
|
||||
('user_login'), ('user_logout'),
|
||||
-- Files
|
||||
('file_create'), ('file_edit'), ('file_delete'), ('file_restore'),
|
||||
('file_permanent_delete'), ('file_replace'),
|
||||
-- Tags
|
||||
('tag_create'), ('tag_edit'), ('tag_delete'),
|
||||
-- Categories
|
||||
('category_create'), ('category_edit'), ('category_delete'),
|
||||
-- Pools
|
||||
('pool_create'), ('pool_edit'), ('pool_delete'),
|
||||
-- Relations
|
||||
('file_tag_add'), ('file_tag_remove'),
|
||||
('file_pool_add'), ('file_pool_remove'),
|
||||
-- ACL
|
||||
('acl_change'),
|
||||
-- Admin
|
||||
('user_create'), ('user_delete'), ('user_block'), ('user_unblock'),
|
||||
('user_role_change'),
|
||||
-- Sessions
|
||||
('session_terminate');
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DELETE FROM activity.action_types;
|
||||
DELETE FROM core.object_types;
|
||||
@@ -1,178 +0,0 @@
|
||||
#!../venv/bin/python3
|
||||
|
||||
import telebot
|
||||
import sys
|
||||
import os
|
||||
import atexit
|
||||
import signal
|
||||
from time import sleep
|
||||
from socket import getaddrinfo
|
||||
from requests import get
|
||||
from subprocess import check_output
|
||||
import logging as log
|
||||
from json import loads as ljson
|
||||
from datetime import datetime
|
||||
import pytz
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
import api.tfm_api as tfm_api
|
||||
|
||||
# set logger
|
||||
log.basicConfig(
|
||||
level=log.INFO,
|
||||
filename="/var/log/tfm/tfm-tb.log",
|
||||
filemode="a",
|
||||
format="%(asctime)s | %(threadName)s | %(levelname)s | %(message)s"
|
||||
)
|
||||
|
||||
# actions to do on exit
|
||||
exit_actions = []
|
||||
defer = exit_actions.append
|
||||
def finalize(*args):
|
||||
exec('\n'.join(exit_actions))
|
||||
os._exit(0)
|
||||
atexit.register(finalize)
|
||||
signal.signal(signal.SIGTERM, finalize)
|
||||
signal.signal(signal.SIGINT, finalize)
|
||||
|
||||
# initialize TFM API
|
||||
try:
|
||||
tfm_api.Initialize()
|
||||
tfm = tfm_api.TSession("af6dde9b-7be1-46f2-872e-9a06ce3d3358")
|
||||
except Exception as e:
|
||||
log.critical(f"failed to initialize TFM API: {str(e)}")
|
||||
exit(1)
|
||||
|
||||
# initialize bot
|
||||
tfm_tb = telebot.TeleBot(tfm_api.conf["Telebot"]["Token"])
|
||||
|
||||
TZ = pytz.timezone("Europe/Moscow")
|
||||
|
||||
|
||||
# check if user is authorized and if chat exists in db
|
||||
def check_chat(message):
|
||||
return message.from_user.id == 924090228
|
||||
|
||||
|
||||
# file handler
|
||||
@tfm_tb.message_handler(content_types=['document', 'photo', 'audio', 'video', 'voice', 'animation'])
|
||||
def file_handler(message):
|
||||
if not check_chat(message):
|
||||
return
|
||||
notes = None
|
||||
orig_name = None
|
||||
if message.forward_from_chat:
|
||||
notes = f"Telegram origin: \"{message.forward_from_chat.title}\" ({message.forward_from_chat.username})"
|
||||
if message.photo:
|
||||
fname = f"{message.photo[-1].file_unique_id}"
|
||||
log.info(f"got photo '{fname}'")
|
||||
file_info = tfm_tb.get_file(message.photo[-1].file_id)
|
||||
file_path = os.path.join(tfm_api.conf["Telebot"]["SaveFolder"], fname)
|
||||
with open(file_path, 'wb') as f:
|
||||
f.write(tfm_tb.download_file(file_info.file_path))
|
||||
elif message.video:
|
||||
fname = f"{message.video.file_unique_id}"
|
||||
log.info(f"got video '{fname}'")
|
||||
file_info = tfm_tb.get_file(message.video.file_id)
|
||||
file_path = os.path.join(tfm_api.conf["Telebot"]["SaveFolder"], fname)
|
||||
with open(file_path, 'wb') as f:
|
||||
f.write(tfm_tb.download_file(file_info.file_path))
|
||||
else:
|
||||
file = None
|
||||
if message.document:
|
||||
file = message.document
|
||||
elif message.animation:
|
||||
file = message.animation
|
||||
else:
|
||||
tfm_tb.reply_to(message, "Unsupported file type.")
|
||||
return
|
||||
log.info(f"got file '{file.file_name}'")
|
||||
orig_name = file.file_name
|
||||
file_info = tfm_tb.get_file(file.file_id)
|
||||
file_path = os.path.join(tfm_api.conf["Telebot"]["SaveFolder"], f"{file.file_unique_id}")
|
||||
try:
|
||||
with open(file_path, 'wb') as f:
|
||||
f.write(tfm_tb.download_file(file_info.file_path))
|
||||
log.info(f"downloaded file '{file_path}'")
|
||||
exif = ljson(os.popen(f"exiftool -json \"{file_path}\"").read())[0]
|
||||
dt = exif["FileModifyDate"]
|
||||
if "SubSecCreateDate" in exif.keys():
|
||||
dt = exif["SubSecCreateDate"]
|
||||
if '.' in dt:
|
||||
dt = datetime.strptime(dt, "%Y:%m:%d %H:%M:%S.%f%z")
|
||||
else:
|
||||
dt = datetime.strptime(dt, "%Y:%m:%d %H:%M:%S%z")
|
||||
file_id, ext = tfm.add_file(file_path, dt, notes, orig_name=orig_name)
|
||||
tfm.add_file_to_tag(file_id, "d6d8129a-984d-4451-8c83-d04523ced8a8")
|
||||
except Exception as e:
|
||||
tfm_tb.reply_to(message, "Error: %s" % str(e).split('\n')[0])
|
||||
log.info(f"Error: %s" % str(e).split('\n')[0])
|
||||
os.remove(file_path)
|
||||
log.info(f"removed file '{file_path}'")
|
||||
else:
|
||||
tfm_tb.reply_to(message, "File saved.")
|
||||
log.info(f"imported file '{file_path}'")
|
||||
|
||||
|
||||
# folder scanner
|
||||
@tfm_tb.message_handler(commands=['scan'])
|
||||
def scan(message):
|
||||
tfm_tb.reply_to(message, "Scanning...")
|
||||
log.info("Scanning...")
|
||||
scan_dir = "/srv/share/hfs/misc/tfm_temp/scan"
|
||||
files = []
|
||||
for file in os.listdir(scan_dir):
|
||||
new_file = {"name": file}
|
||||
file = os.path.join(scan_dir, file)
|
||||
if not os.path.isfile(file):
|
||||
continue
|
||||
new_file["path"] = file
|
||||
try:
|
||||
exif = ljson(os.popen(f"exiftool -json \"{file}\"").read())[0]
|
||||
except Exception as e:
|
||||
log.error("Error while parsing EXIF for file '%s': %s" % (file, e))
|
||||
continue
|
||||
dt = exif["FileModifyDate"]
|
||||
if "SubSecDateTimeOriginal" in exif.keys():
|
||||
dt = exif["SubSecDateTimeOriginal"]
|
||||
elif "DateTimeOriginal" in exif.keys():
|
||||
dt = exif["DateTimeOriginal"]
|
||||
if '.' in dt:
|
||||
try:
|
||||
dt = datetime.strptime(dt, "%Y:%m:%d %H:%M:%S.%f%z")
|
||||
except:
|
||||
dt = TZ.localize(datetime.strptime(dt, "%Y:%m:%d %H:%M:%S.%f"))
|
||||
else:
|
||||
try:
|
||||
try:
|
||||
dt = datetime.strptime(dt, "%Y:%m:%d %H:%M:%S%z")
|
||||
except:
|
||||
dt = TZ.localize(datetime.strptime(dt[:19], "%Y:%m:%d %H:%M:%S"))
|
||||
except:
|
||||
log.error("Broken date: %s\t%s" % (new_file, dt))
|
||||
continue
|
||||
new_file["datetime"] = dt
|
||||
files.append(new_file)
|
||||
tfm_tb.reply_to(message, f"{len(files)} files found.")
|
||||
log.info(f"{len(files)} files found.")
|
||||
files.sort(key=lambda f: f["datetime"])
|
||||
for file in files:
|
||||
try:
|
||||
file_id, ext = tfm.add_file(file["path"], file["datetime"])
|
||||
tfm.add_file_to_tag(file_id, "d6d8129a-984d-4451-8c83-d04523ced8a8")
|
||||
except Exception as e:
|
||||
tfm_tb.reply_to(message, f"Error adding file '{file['name']}': {str(e)}")
|
||||
log.error(f"Error adding file '{file['name']}': {str(e)}")
|
||||
tfm_tb.reply_to(message, "Files added.")
|
||||
log.info("Files added.")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
log.info("tfm-tb started")
|
||||
defer("log.info(\"tfm-tb stopped\")")
|
||||
while True:
|
||||
try:
|
||||
tfm_tb.polling(none_stop=True)
|
||||
except Exception as e:
|
||||
log.exception("exception on polling")
|
||||
sleep(1)
|
||||
@@ -0,0 +1,383 @@
|
||||
# Tanabata File Manager — Frontend Structure
|
||||
|
||||
## Stack
|
||||
|
||||
- **Framework**: SvelteKit (SPA mode, `ssr: false`)
|
||||
- **Language**: TypeScript
|
||||
- **CSS**: Tailwind CSS + CSS custom properties (hybrid)
|
||||
- **API types**: Auto-generated via openapi-typescript
|
||||
- **PWA**: Service worker + web manifest
|
||||
- **Font**: Epilogue (variable weight)
|
||||
- **Package manager**: npm
|
||||
|
||||
## Monorepo Layout
|
||||
|
||||
```
|
||||
tanabata/
|
||||
├── backend/ ← Go project (go.mod in here)
|
||||
│ ├── cmd/
|
||||
│ ├── internal/
|
||||
│ ├── migrations/
|
||||
│ ├── go.mod
|
||||
│ └── go.sum
|
||||
│
|
||||
├── frontend/ ← SvelteKit project (package.json in here)
|
||||
│ └── (see below)
|
||||
│
|
||||
├── openapi.yaml ← Shared API contract (root level)
|
||||
├── docker-compose.yml
|
||||
├── Dockerfile
|
||||
├── .env.example
|
||||
└── README.md
|
||||
```
|
||||
|
||||
`openapi.yaml` lives at repository root — both backend and frontend
|
||||
reference it. The frontend generates types from it; the backend
|
||||
validates its handlers against it.
|
||||
|
||||
## Frontend Directory Layout
|
||||
|
||||
```
|
||||
frontend/
|
||||
├── package.json
|
||||
├── svelte.config.js
|
||||
├── vite.config.ts
|
||||
├── tsconfig.json
|
||||
├── tailwind.config.ts
|
||||
├── postcss.config.js
|
||||
│
|
||||
├── src/
|
||||
│ ├── app.html # Shell HTML (PWA meta, font preload)
|
||||
│ ├── app.css # Tailwind directives + CSS custom properties
|
||||
│ ├── hooks.server.ts # Server hooks (not used in SPA mode)
|
||||
│ ├── hooks.client.ts # Client hooks (global error handling)
|
||||
│ │
|
||||
│ ├── lib/ # Shared code ($lib/ alias)
|
||||
│ │ │
|
||||
│ │ ├── api/ # API client layer
|
||||
│ │ │ ├── client.ts # Base fetch wrapper: auth headers, token refresh,
|
||||
│ │ │ │ # error parsing, base URL
|
||||
│ │ │ ├── files.ts # listFiles, getFile, uploadFile, deleteFile, etc.
|
||||
│ │ │ ├── tags.ts # listTags, createTag, getTag, updateTag, etc.
|
||||
│ │ │ ├── categories.ts # Category API functions
|
||||
│ │ │ ├── pools.ts # Pool API functions
|
||||
│ │ │ ├── auth.ts # login, logout, refresh, listSessions
|
||||
│ │ │ ├── acl.ts # getPermissions, setPermissions
|
||||
│ │ │ ├── users.ts # getMe, updateMe, admin user CRUD
|
||||
│ │ │ ├── audit.ts # queryAuditLog
|
||||
│ │ │ ├── schema.ts # AUTO-GENERATED from openapi.yaml (do not edit)
|
||||
│ │ │ └── types.ts # Friendly type aliases:
|
||||
│ │ │ # export type File = components["schemas"]["File"]
|
||||
│ │ │ # export type Tag = components["schemas"]["Tag"]
|
||||
│ │ │
|
||||
│ │ ├── components/ # Reusable UI components
|
||||
│ │ │ │
|
||||
│ │ │ ├── layout/ # App shell
|
||||
│ │ │ │ ├── Navbar.svelte # Bottom navigation bar (mobile-first)
|
||||
│ │ │ │ ├── Header.svelte # Section header with sorting controls
|
||||
│ │ │ │ ├── SelectionBar.svelte # Floating bar for multi-select actions
|
||||
│ │ │ │ └── Loader.svelte # Full-screen loading overlay
|
||||
│ │ │ │
|
||||
│ │ │ ├── file/ # File-related components
|
||||
│ │ │ │ ├── FileGrid.svelte # Thumbnail grid with infinite scroll
|
||||
│ │ │ │ ├── FileCard.svelte # Single thumbnail (160×160, selectable)
|
||||
│ │ │ │ ├── FileViewer.svelte # Full-screen preview with prev/next navigation
|
||||
│ │ │ │ ├── FileUpload.svelte # Upload form + drag-and-drop zone
|
||||
│ │ │ │ ├── FileDetail.svelte # Metadata editor (notes, datetime, tags)
|
||||
│ │ │ │ └── FilterBar.svelte # DSL filter builder UI
|
||||
│ │ │ │
|
||||
│ │ │ ├── tag/ # Tag-related components
|
||||
│ │ │ │ ├── TagBadge.svelte # Colored pill with tag name
|
||||
│ │ │ │ ├── TagPicker.svelte # Searchable tag selector (add/remove)
|
||||
│ │ │ │ ├── TagList.svelte # Tag grid for section view
|
||||
│ │ │ │ └── TagRuleEditor.svelte # Auto-tag rule management
|
||||
│ │ │ │
|
||||
│ │ │ ├── pool/ # Pool-related components
|
||||
│ │ │ │ ├── PoolCard.svelte # Pool preview card
|
||||
│ │ │ │ ├── PoolFileList.svelte # Ordered file list with drag reorder
|
||||
│ │ │ │ └── PoolDetail.svelte # Pool metadata editor
|
||||
│ │ │ │
|
||||
│ │ │ ├── acl/ # Access control components
|
||||
│ │ │ │ └── PermissionEditor.svelte # User permission grid
|
||||
│ │ │ │
|
||||
│ │ │ └── common/ # Shared primitives
|
||||
│ │ │ ├── Button.svelte
|
||||
│ │ │ ├── Modal.svelte
|
||||
│ │ │ ├── ConfirmDialog.svelte
|
||||
│ │ │ ├── Toast.svelte
|
||||
│ │ │ ├── InfiniteScroll.svelte
|
||||
│ │ │ ├── Pagination.svelte
|
||||
│ │ │ ├── SortDropdown.svelte
|
||||
│ │ │ ├── SearchInput.svelte
|
||||
│ │ │ ├── ColorPicker.svelte
|
||||
│ │ │ ├── Checkbox.svelte # Three-state: checked, unchecked, partial
|
||||
│ │ │ └── EmptyState.svelte
|
||||
│ │ │
|
||||
│ │ ├── stores/ # Svelte stores (global state)
|
||||
│ │ │ ├── auth.ts # Current user, JWT tokens, isAuthenticated
|
||||
│ │ │ ├── selection.ts # Selected item IDs, selection mode toggle
|
||||
│ │ │ ├── sorting.ts # Per-section sort key + order (persisted to localStorage)
|
||||
│ │ │ ├── theme.ts # Dark/light mode (persisted, respects prefers-color-scheme)
|
||||
│ │ │ └── toast.ts # Notification queue (success, error, info)
|
||||
│ │ │
|
||||
│ │ └── utils/ # Pure helper functions
|
||||
│ │ ├── format.ts # formatDate, formatFileSize, formatDuration
|
||||
│ │ ├── dsl.ts # Filter DSL builder: UI state → query string
|
||||
│ │ ├── pwa.ts # PWA reset, cache clear, update prompt
|
||||
│ │ └── keyboard.ts # Keyboard shortcut helpers (Ctrl+A, Escape, etc.)
|
||||
│ │
|
||||
│ ├── routes/ # SvelteKit file-based routing
|
||||
│ │ │
|
||||
│ │ ├── +layout.svelte # Root layout: Navbar, theme wrapper, toast container
|
||||
│ │ ├── +layout.ts # Root load: auth guard → redirect to /login if no token
|
||||
│ │ │
|
||||
│ │ ├── +page.svelte # / → redirect to /files
|
||||
│ │ │
|
||||
│ │ ├── login/
|
||||
│ │ │ └── +page.svelte # Login form (decorative Tanabata images)
|
||||
│ │ │
|
||||
│ │ ├── files/
|
||||
│ │ │ ├── +page.svelte # File grid: filter bar, sort, multi-select, upload
|
||||
│ │ │ ├── +page.ts # Load: initial file list (cursor page)
|
||||
│ │ │ ├── [id]/
|
||||
│ │ │ │ ├── +page.svelte # File view: preview, metadata, tags, ACL
|
||||
│ │ │ │ └── +page.ts # Load: file detail + tags
|
||||
│ │ │ └── trash/
|
||||
│ │ │ ├── +page.svelte # Trash: restore / permanent delete
|
||||
│ │ │ └── +page.ts
|
||||
│ │ │
|
||||
│ │ ├── tags/
|
||||
│ │ │ ├── +page.svelte # Tag list: search, sort, multi-select
|
||||
│ │ │ ├── +page.ts
|
||||
│ │ │ ├── new/
|
||||
│ │ │ │ └── +page.svelte # Create tag form
|
||||
│ │ │ └── [id]/
|
||||
│ │ │ ├── +page.svelte # Tag detail: edit, category, rules, parent tags
|
||||
│ │ │ └── +page.ts
|
||||
│ │ │
|
||||
│ │ ├── categories/
|
||||
│ │ │ ├── +page.svelte # Category list
|
||||
│ │ │ ├── +page.ts
|
||||
│ │ │ ├── new/
|
||||
│ │ │ │ └── +page.svelte
|
||||
│ │ │ └── [id]/
|
||||
│ │ │ ├── +page.svelte # Category detail: edit, view tags
|
||||
│ │ │ └── +page.ts
|
||||
│ │ │
|
||||
│ │ ├── pools/
|
||||
│ │ │ ├── +page.svelte # Pool list
|
||||
│ │ │ ├── +page.ts
|
||||
│ │ │ ├── new/
|
||||
│ │ │ │ └── +page.svelte
|
||||
│ │ │ └── [id]/
|
||||
│ │ │ ├── +page.svelte # Pool detail: files (reorderable), filter, edit
|
||||
│ │ │ └── +page.ts
|
||||
│ │ │
|
||||
│ │ ├── settings/
|
||||
│ │ │ ├── +page.svelte # Profile: name, password, active sessions
|
||||
│ │ │ └── +page.ts
|
||||
│ │ │
|
||||
│ │ └── admin/
|
||||
│ │ ├── +layout.svelte # Admin layout: restrict to is_admin
|
||||
│ │ ├── users/
|
||||
│ │ │ ├── +page.svelte # User management list
|
||||
│ │ │ ├── +page.ts
|
||||
│ │ │ └── [id]/
|
||||
│ │ │ ├── +page.svelte # User detail: role, block/unblock
|
||||
│ │ │ └── +page.ts
|
||||
│ │ └── audit/
|
||||
│ │ ├── +page.svelte # Audit log with filters
|
||||
│ │ └── +page.ts
|
||||
│ │
|
||||
│ └── service-worker.ts # PWA: offline cache for pinned files, app shell caching
|
||||
│
|
||||
└── static/
|
||||
├── favicon.png
|
||||
├── favicon.ico
|
||||
├── manifest.webmanifest # PWA manifest (name, icons, theme_color)
|
||||
├── images/
|
||||
│ ├── tanabata-left.png # Login page decorations (from current design)
|
||||
│ ├── tanabata-right.png
|
||||
│ └── icons/ # PWA icons (192×192, 512×512, etc.)
|
||||
└── fonts/
|
||||
└── Epilogue-VariableFont_wght.ttf
|
||||
```
|
||||
|
||||
## Key Architecture Decisions
|
||||
|
||||
### CSS Hybrid: Tailwind + Custom Properties
|
||||
|
||||
Theme colors defined as CSS custom properties in `app.css`:
|
||||
|
||||
```css
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
:root {
|
||||
--color-bg-primary: #312F45;
|
||||
--color-bg-secondary: #181721;
|
||||
--color-bg-elevated: #111118;
|
||||
--color-accent: #9592B5;
|
||||
--color-accent-hover: #7D7AA4;
|
||||
--color-text-primary: #f0f0f0;
|
||||
--color-text-muted: #9999AD;
|
||||
--color-danger: #DB6060;
|
||||
--color-info: #4DC7ED;
|
||||
--color-warning: #F5E872;
|
||||
--color-tag-default: #444455;
|
||||
}
|
||||
|
||||
:root[data-theme="light"] {
|
||||
--color-bg-primary: #f5f5f5;
|
||||
--color-bg-secondary: #ffffff;
|
||||
/* ... */
|
||||
}
|
||||
```
|
||||
|
||||
Tailwind references them in `tailwind.config.ts`:
|
||||
|
||||
```ts
|
||||
export default {
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
bg: {
|
||||
primary: 'var(--color-bg-primary)',
|
||||
secondary: 'var(--color-bg-secondary)',
|
||||
elevated: 'var(--color-bg-elevated)',
|
||||
},
|
||||
accent: {
|
||||
DEFAULT: 'var(--color-accent)',
|
||||
hover: 'var(--color-accent-hover)',
|
||||
},
|
||||
// ...
|
||||
},
|
||||
fontFamily: {
|
||||
sans: ['Epilogue', 'sans-serif'],
|
||||
},
|
||||
},
|
||||
},
|
||||
darkMode: 'class', // controlled via data-theme attribute
|
||||
};
|
||||
```
|
||||
|
||||
Usage in components: `<div class="bg-bg-primary text-text-primary rounded-xl p-4">`.
|
||||
Complex cases use scoped `<style>` inside `.svelte` files.
|
||||
|
||||
### API Client Pattern
|
||||
|
||||
`client.ts` — thin wrapper around fetch:
|
||||
|
||||
```ts
|
||||
// $lib/api/client.ts
|
||||
import { authStore } from '$lib/stores/auth';
|
||||
|
||||
const BASE = '/api/v1';
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const token = get(authStore).accessToken;
|
||||
const res = await fetch(BASE + path, {
|
||||
...init,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...(token && { Authorization: `Bearer ${token}` }),
|
||||
...init?.headers,
|
||||
},
|
||||
});
|
||||
if (res.status === 401) {
|
||||
// attempt refresh, retry once
|
||||
}
|
||||
if (!res.ok) {
|
||||
const err = await res.json();
|
||||
throw new ApiError(res.status, err.code, err.message, err.details);
|
||||
}
|
||||
if (res.status === 204) return undefined as T;
|
||||
return res.json();
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(path: string) => request<T>(path),
|
||||
post: <T>(path: string, body?: unknown) =>
|
||||
request<T>(path, { method: 'POST', body: JSON.stringify(body) }),
|
||||
patch: <T>(path: string, body?: unknown) =>
|
||||
request<T>(path, { method: 'PATCH', body: JSON.stringify(body) }),
|
||||
put: <T>(path: string, body?: unknown) =>
|
||||
request<T>(path, { method: 'PUT', body: JSON.stringify(body) }),
|
||||
delete: <T>(path: string) => request<T>(path, { method: 'DELETE' }),
|
||||
upload: <T>(path: string, formData: FormData) =>
|
||||
request<T>(path, { method: 'POST', body: formData, headers: {} }),
|
||||
};
|
||||
```
|
||||
|
||||
Domain-specific modules use it:
|
||||
|
||||
```ts
|
||||
// $lib/api/files.ts
|
||||
import { api } from './client';
|
||||
import type { File, FileCursorPage } from './types';
|
||||
|
||||
export function listFiles(params: Record<string, string>) {
|
||||
const qs = new URLSearchParams(params).toString();
|
||||
return api.get<FileCursorPage>(`/files?${qs}`);
|
||||
}
|
||||
|
||||
export function uploadFile(formData: FormData) {
|
||||
return api.upload<File>('/files', formData);
|
||||
}
|
||||
```
|
||||
|
||||
### Type Generation
|
||||
|
||||
Script in `package.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"generate:types": "openapi-typescript ../openapi.yaml -o src/lib/api/schema.ts",
|
||||
"dev": "npm run generate:types && vite dev",
|
||||
"build": "npm run generate:types && vite build"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Friendly aliases in `types.ts`:
|
||||
|
||||
```ts
|
||||
import type { components } from './schema';
|
||||
|
||||
export type File = components['schemas']['File'];
|
||||
export type Tag = components['schemas']['Tag'];
|
||||
export type Category = components['schemas']['Category'];
|
||||
export type Pool = components['schemas']['Pool'];
|
||||
export type FileCursorPage = components['schemas']['FileCursorPage'];
|
||||
export type TagOffsetPage = components['schemas']['TagOffsetPage'];
|
||||
export type Error = components['schemas']['Error'];
|
||||
// ...
|
||||
```
|
||||
|
||||
### SPA Mode
|
||||
|
||||
`svelte.config.js`:
|
||||
|
||||
```js
|
||||
import adapter from '@sveltejs/adapter-static';
|
||||
|
||||
export default {
|
||||
kit: {
|
||||
adapter: adapter({ fallback: 'index.html' }),
|
||||
// SPA: all routes handled client-side
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
The Go backend serves `index.html` for all non-API routes (SPA fallback).
|
||||
In development, Vite dev server proxies `/api` to the Go backend.
|
||||
|
||||
### PWA
|
||||
|
||||
`service-worker.ts` handles:
|
||||
- App shell caching (HTML, CSS, JS, fonts)
|
||||
- User-pinned file caching (explicit, via UI button)
|
||||
- Cache versioning and cleanup on update
|
||||
- Reset function (clear all caches except pinned files)
|
||||
@@ -0,0 +1,320 @@
|
||||
# Tanabata File Manager — Go Project Structure
|
||||
|
||||
## Stack
|
||||
|
||||
- **Router**: Gin
|
||||
- **Database**: pgx v5 (pgxpool)
|
||||
- **Migrations**: goose v3 + go:embed (auto-migrate on startup)
|
||||
- **Auth**: JWT (golang-jwt/jwt/v5)
|
||||
- **Config**: environment variables via .env (joho/godotenv)
|
||||
- **Logging**: slog (stdlib, Go 1.21+)
|
||||
- **Validation**: go-playground/validator/v10
|
||||
- **EXIF**: rwcarlsen/goexif or dsoprea/go-exif
|
||||
- **Image processing**: disintegration/imaging (thumbnails, previews)
|
||||
- **Architecture**: Clean Architecture (domain → service → repository/handler)
|
||||
|
||||
## Monorepo Layout
|
||||
|
||||
```
|
||||
tanabata/
|
||||
├── backend/ ← Go project
|
||||
├── frontend/ ← SvelteKit project
|
||||
├── openapi.yaml ← Shared API contract
|
||||
├── docker-compose.yml
|
||||
├── Dockerfile
|
||||
├── .env.example
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## Backend Directory Layout
|
||||
|
||||
```
|
||||
backend/
|
||||
├── cmd/
|
||||
│ └── server/
|
||||
│ └── main.go # Entrypoint: config → DB → migrate → wire → run
|
||||
│
|
||||
├── internal/
|
||||
│ │
|
||||
│ ├── domain/ # Pure business entities & value objects
|
||||
│ │ ├── file.go # File, FileFilter, FilePage
|
||||
│ │ ├── tag.go # Tag, TagRule
|
||||
│ │ ├── category.go # Category
|
||||
│ │ ├── pool.go # Pool, PoolFile
|
||||
│ │ ├── user.go # User, Session
|
||||
│ │ ├── acl.go # Permission, ObjectType
|
||||
│ │ ├── audit.go # AuditEntry, ActionType
|
||||
│ │ └── errors.go # Domain error types (ErrNotFound, ErrForbidden, etc.)
|
||||
│ │
|
||||
│ ├── port/ # Interfaces (ports) — contracts between layers
|
||||
│ │ ├── repository.go # FileRepo, TagRepo, CategoryRepo, PoolRepo,
|
||||
│ │ │ # UserRepo, SessionRepo, ACLRepo, AuditRepo,
|
||||
│ │ │ # MimeRepo, TagRuleRepo
|
||||
│ │ └── storage.go # FileStorage interface (disk operations)
|
||||
│ │
|
||||
│ ├── service/ # Business logic (use cases)
|
||||
│ │ ├── file_service.go # Upload, update, delete, trash/restore, replace,
|
||||
│ │ │ # import, filter/list, duplicate detection
|
||||
│ │ ├── tag_service.go # CRUD + auto-tag application logic
|
||||
│ │ ├── category_service.go # CRUD (thin, delegates to repo + ACL + audit)
|
||||
│ │ ├── pool_service.go # CRUD + file ordering, add/remove files
|
||||
│ │ ├── auth_service.go # Login, logout, JWT issue/refresh, session management
|
||||
│ │ ├── acl_service.go # Permission checks, grant/revoke
|
||||
│ │ ├── audit_service.go # Log actions, query audit log
|
||||
│ │ └── user_service.go # Profile update, admin CRUD, block/unblock
|
||||
│ │
|
||||
│ ├── handler/ # HTTP layer (Gin handlers)
|
||||
│ │ ├── router.go # Route registration, middleware wiring
|
||||
│ │ ├── middleware.go # Auth middleware (JWT extraction → context)
|
||||
│ │ ├── request.go # Common request parsing helpers
|
||||
│ │ ├── response.go # Error/success response builders
|
||||
│ │ ├── file_handler.go # /files endpoints
|
||||
│ │ ├── tag_handler.go # /tags endpoints
|
||||
│ │ ├── category_handler.go # /categories endpoints
|
||||
│ │ ├── pool_handler.go # /pools endpoints
|
||||
│ │ ├── auth_handler.go # /auth endpoints
|
||||
│ │ ├── acl_handler.go # /acl endpoints
|
||||
│ │ ├── user_handler.go # /users endpoints
|
||||
│ │ └── audit_handler.go # /audit endpoints
|
||||
│ │
|
||||
│ ├── db/ # Database adapters
|
||||
│ │ ├── db.go # Common helpers: pagination, repo factory, transactor base
|
||||
│ │ └── postgres/ # PostgreSQL implementation
|
||||
│ │ ├── postgres.go # pgxpool init, tx-from-context helpers
|
||||
│ │ ├── file_repo.go # FileRepo implementation
|
||||
│ │ ├── tag_repo.go # TagRepo + TagRuleRepo implementation
|
||||
│ │ ├── category_repo.go # CategoryRepo implementation
|
||||
│ │ ├── pool_repo.go # PoolRepo implementation
|
||||
│ │ ├── user_repo.go # UserRepo implementation
|
||||
│ │ ├── session_repo.go # SessionRepo implementation
|
||||
│ │ ├── acl_repo.go # ACLRepo implementation
|
||||
│ │ ├── audit_repo.go # AuditRepo implementation
|
||||
│ │ ├── mime_repo.go # MimeRepo implementation
|
||||
│ │ └── filter_parser.go # DSL → SQL WHERE clause builder
|
||||
│ │
|
||||
│ ├── storage/ # File storage adapter
|
||||
│ │ └── disk.go # FileStorage implementation (read/write/delete on disk)
|
||||
│ │
|
||||
│ └── config/ # Configuration
|
||||
│ └── config.go # Struct + loader from env vars
|
||||
│
|
||||
├── migrations/ # SQL migration files (goose format)
|
||||
│ ├── 001_init_schemas.sql
|
||||
│ ├── 002_core_tables.sql
|
||||
│ ├── 003_data_tables.sql
|
||||
│ ├── 004_acl_tables.sql
|
||||
│ ├── 005_activity_tables.sql
|
||||
│ ├── 006_indexes.sql
|
||||
│ └── 007_seed_data.sql
|
||||
│
|
||||
├── go.mod
|
||||
└── go.sum
|
||||
```
|
||||
|
||||
## Layer Dependency Rules
|
||||
|
||||
```
|
||||
handler → service → port (interfaces) ← db/postgres / storage
|
||||
↓
|
||||
domain (entities, value objects, errors)
|
||||
```
|
||||
|
||||
- **domain/**: zero imports from other internal packages. Only stdlib.
|
||||
- **port/**: imports only domain/. Defines interfaces.
|
||||
- **service/**: imports domain/ and port/. Never imports db/ or handler/.
|
||||
- **handler/**: imports domain/ and service/. Never imports db/.
|
||||
- **db/postgres/**: imports domain/, port/, and db/ (common helpers). Implements port interfaces.
|
||||
- **db/**: imports domain/ and port/. Shared utilities for all DB adapters.
|
||||
- **storage/**: imports domain/ and port/. Implements FileStorage.
|
||||
|
||||
No layer may import a layer above it. No circular dependencies.
|
||||
|
||||
## Key Design Decisions
|
||||
|
||||
### Dependency Injection (Wiring)
|
||||
|
||||
Manual wiring in `cmd/server/main.go`. No DI frameworks.
|
||||
|
||||
```go
|
||||
// Pseudocode
|
||||
pool := postgres.NewPool(cfg.DatabaseURL)
|
||||
goose.Up(pool, migrations)
|
||||
|
||||
// Repos (all from internal/db/postgres/)
|
||||
fileRepo := postgres.NewFileRepo(pool)
|
||||
tagRepo := postgres.NewTagRepo(pool)
|
||||
// ...
|
||||
|
||||
// Storage
|
||||
diskStore := storage.NewDiskStorage(cfg.FilesPath)
|
||||
|
||||
// Services
|
||||
aclSvc := service.NewACLService(aclRepo, objectTypeRepo)
|
||||
auditSvc := service.NewAuditService(auditRepo, actionTypeRepo)
|
||||
fileSvc := service.NewFileService(fileRepo, mimeRepo, tagRepo, diskStore, aclSvc, auditSvc)
|
||||
tagSvc := service.NewTagService(tagRepo, tagRuleRepo, aclSvc, auditSvc)
|
||||
// ...
|
||||
|
||||
// Handlers
|
||||
fileHandler := handler.NewFileHandler(fileSvc, tagSvc)
|
||||
// ...
|
||||
|
||||
router := handler.NewRouter(cfg, fileHandler, tagHandler, ...)
|
||||
router.Run(cfg.ListenAddr)
|
||||
```
|
||||
|
||||
### Context Propagation
|
||||
|
||||
Every service method receives `context.Context` as the first argument.
|
||||
The handler extracts user info from JWT (via middleware) and puts it
|
||||
into context. Services read the current user from context for ACL checks
|
||||
and audit logging.
|
||||
|
||||
```go
|
||||
// middleware.go
|
||||
func (m *AuthMiddleware) Handle(c *gin.Context) {
|
||||
claims := parseJWT(c.GetHeader("Authorization"))
|
||||
ctx := domain.WithUser(c.Request.Context(), claims.UserID, claims.IsAdmin)
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
c.Next()
|
||||
}
|
||||
|
||||
// domain/context.go
|
||||
type ctxKey int
|
||||
const userKey ctxKey = iota
|
||||
func WithUser(ctx context.Context, userID int16, isAdmin bool) context.Context { ... }
|
||||
func UserFromContext(ctx context.Context) (userID int16, isAdmin bool) { ... }
|
||||
```
|
||||
|
||||
### Transaction Management
|
||||
|
||||
Repository interfaces include a `Transactor`:
|
||||
|
||||
```go
|
||||
// port/repository.go
|
||||
type Transactor interface {
|
||||
WithTx(ctx context.Context, fn func(ctx context.Context) error) error
|
||||
}
|
||||
```
|
||||
|
||||
The postgres implementation wraps `pgxpool.Pool.BeginTx`. Inside `fn`,
|
||||
all repo calls use the transaction from context. This allows services
|
||||
to compose multiple repo calls in a single transaction:
|
||||
|
||||
```go
|
||||
// service/file_service.go
|
||||
func (s *FileService) Upload(ctx context.Context, input UploadInput) (*domain.File, error) {
|
||||
return s.tx.WithTx(ctx, func(ctx context.Context) error {
|
||||
file, err := s.fileRepo.Create(ctx, ...) // uses tx
|
||||
if err != nil { return err }
|
||||
for _, tagID := range input.TagIDs {
|
||||
s.tagRepo.AddFileTag(ctx, file.ID, tagID) // same tx
|
||||
}
|
||||
s.auditRepo.Log(ctx, ...) // same tx
|
||||
return nil
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### ACL Check Pattern
|
||||
|
||||
ACL logic is centralized in `ACLService`. Other services call it before
|
||||
any data mutation or retrieval:
|
||||
|
||||
```go
|
||||
// service/acl_service.go
|
||||
func (s *ACLService) CanView(ctx context.Context, objectType string, objectID uuid.UUID) error {
|
||||
userID, isAdmin := domain.UserFromContext(ctx)
|
||||
if isAdmin { return nil }
|
||||
// Check is_public on the object
|
||||
// If not public, check creator_id == userID
|
||||
// If not creator, check acl.permissions
|
||||
// Return domain.ErrForbidden if none match
|
||||
}
|
||||
```
|
||||
|
||||
### Error Mapping
|
||||
|
||||
Domain errors → HTTP status codes (handled in handler/response.go):
|
||||
|
||||
| Domain Error | HTTP Status | Error Code |
|
||||
|-----------------------|-------------|-------------------|
|
||||
| ErrNotFound | 404 | not_found |
|
||||
| ErrForbidden | 403 | forbidden |
|
||||
| ErrUnauthorized | 401 | unauthorized |
|
||||
| ErrConflict | 409 | conflict |
|
||||
| ErrValidation | 400 | validation_error |
|
||||
| ErrUnsupportedMIME | 415 | unsupported_mime |
|
||||
| (unexpected) | 500 | internal_error |
|
||||
|
||||
### Filter DSL
|
||||
|
||||
The DSL parser lives in `db/postgres/filter_parser.go` because it produces
|
||||
SQL WHERE clauses — it is a PostgreSQL-specific adapter concern.
|
||||
The service layer passes the raw DSL string to the repository; the
|
||||
repository parses it and builds the query.
|
||||
|
||||
For a different DBMS, a corresponding parser would live in
|
||||
`db/<dbms>/filter_parser.go`.
|
||||
|
||||
The interface:
|
||||
```go
|
||||
// port/repository.go
|
||||
type FileRepo interface {
|
||||
List(ctx context.Context, params FileListParams) (*domain.FilePage, error)
|
||||
// ...
|
||||
}
|
||||
|
||||
// domain/file.go
|
||||
type FileListParams struct {
|
||||
Filter string // raw DSL string
|
||||
Sort string
|
||||
Order string
|
||||
Cursor string
|
||||
Anchor *uuid.UUID
|
||||
Direction string // "forward" or "backward"
|
||||
Limit int
|
||||
Trash bool
|
||||
Search string
|
||||
}
|
||||
```
|
||||
|
||||
### JWT Structure
|
||||
|
||||
```go
|
||||
type Claims struct {
|
||||
jwt.RegisteredClaims
|
||||
UserID int16 `json:"uid"`
|
||||
IsAdmin bool `json:"adm"`
|
||||
SessionID int `json:"sid"`
|
||||
}
|
||||
```
|
||||
|
||||
Access token: short-lived (15 min). Refresh token: long-lived (30 days),
|
||||
stored as hash in `activity.sessions.token_hash`.
|
||||
|
||||
### Configuration (.env)
|
||||
|
||||
```env
|
||||
# Server
|
||||
LISTEN_ADDR=:8080
|
||||
JWT_SECRET=<random-32-bytes>
|
||||
JWT_ACCESS_TTL=15m
|
||||
JWT_REFRESH_TTL=720h
|
||||
|
||||
# Database
|
||||
DATABASE_URL=postgres://user:pass@host:5432/tanabata?sslmode=disable
|
||||
|
||||
# Storage
|
||||
FILES_PATH=/data/files
|
||||
THUMBS_CACHE_PATH=/data/thumbs
|
||||
|
||||
# Thumbnails
|
||||
THUMB_WIDTH=160
|
||||
THUMB_HEIGHT=160
|
||||
PREVIEW_WIDTH=1920
|
||||
PREVIEW_HEIGHT=1080
|
||||
|
||||
# Import
|
||||
IMPORT_PATH=/data/import
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"tanabata/internal/storage/postgres"
|
||||
)
|
||||
|
||||
func main() {
|
||||
postgres.InitDB("postgres://hiko:taikibansei@192.168.0.25/Tanabata_new?application_name=Tanabata%20testing")
|
||||
// test_json := json.RawMessage([]byte("{\"valery\": \"ponosoff\"}"))
|
||||
// data, statusCode, err := db.FileGetSlice(1, "", "+2", -2, 0)
|
||||
// data, statusCode, err := db.FileGet(1, "0197d056-cfb0-76b5-97e0-bd588826393c")
|
||||
// data, statusCode, err := db.FileAdd(1, "ABOBA.png", "image/png", time.Now(), "slkdfjsldkflsdkfj;sldkf", test_json)
|
||||
// statusCode, err := db.FileUpdate(2, "0197d159-bf3a-7617-a3a8-a4a9fc39eca6", map[string]interface{}{
|
||||
// "name": "ponos.png",
|
||||
// })
|
||||
// statusCode, err := db.FileDelete(1, "0197d155-848f-7221-ba4a-4660f257c7d5")
|
||||
// v, e, err := postgres.FileGetAccess(1, "0197d15a-57f9-712c-991e-c512290e774f")
|
||||
// fmt.Printf("V: %s, E: %s\n", v, e)
|
||||
// fmt.Printf("Status: %d\n", statusCode)
|
||||
// fmt.Printf("Error: %s\n", err)
|
||||
// fmt.Printf("%+v\n", data)
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"tanabata/db"
|
||||
)
|
||||
|
||||
func main() {
|
||||
db.InitDB("postgres://hiko:taikibansei@192.168.0.25/Tanabata_new?application_name=Tanabata%20testing")
|
||||
// test_json := json.RawMessage([]byte("{\"valery\": \"ponosoff\"}"))
|
||||
// data, statusCode, err := db.FileGetSlice(2, "", "+2", -2, 0)
|
||||
// data, statusCode, err := db.FileGet(1, "0197d056-cfb0-76b5-97e0-bd588826393c")
|
||||
// data, statusCode, err := db.FileAdd(1, "ABOBA.png", "image/png", time.Now(), "slkdfjsldkflsdkfj;sldkf", test_json)
|
||||
// statusCode, err := db.FileUpdate(2, "0197d159-bf3a-7617-a3a8-a4a9fc39eca6", map[string]interface{}{
|
||||
// "name": "ponos.png",
|
||||
// })
|
||||
statusCode, err := db.FileDelete(1, "0197d155-848f-7221-ba4a-4660f257c7d5")
|
||||
fmt.Printf("Status: %d\n", statusCode)
|
||||
fmt.Printf("Error: %s\n", err)
|
||||
// fmt.Printf("%+v\n", data)
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var connPool *pgxpool.Pool
|
||||
|
||||
func InitDB(connString string) error {
|
||||
poolConfig, err := pgxpool.ParseConfig(connString)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while parsing connection string: %w", err)
|
||||
}
|
||||
|
||||
poolConfig.MaxConns = 100
|
||||
poolConfig.MinConns = 0
|
||||
poolConfig.MaxConnLifetime = time.Hour
|
||||
poolConfig.HealthCheckPeriod = 30 * time.Second
|
||||
|
||||
connPool, err = pgxpool.NewWithConfig(context.Background(), poolConfig)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error while initializing DB connections pool: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func transaction(handler func(context.Context, pgx.Tx) (statusCode int, err error)) (statusCode int, err error) {
|
||||
ctx := context.Background()
|
||||
tx, err := connPool.Begin(ctx)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
return
|
||||
}
|
||||
statusCode, err = handler(ctx, tx)
|
||||
if err != nil {
|
||||
tx.Rollback(ctx)
|
||||
return
|
||||
}
|
||||
err = tx.Commit(ctx)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Handle database error
|
||||
func handleDBError(errIn error) (statusCode int, err error) {
|
||||
if errIn == nil {
|
||||
statusCode = http.StatusOK
|
||||
return
|
||||
}
|
||||
if errors.Is(errIn, pgx.ErrNoRows) {
|
||||
err = fmt.Errorf("not found")
|
||||
statusCode = http.StatusNotFound
|
||||
return
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(errIn, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "22P02", "22007": // Invalid data format
|
||||
err = fmt.Errorf("%s", pgErr.Message)
|
||||
statusCode = http.StatusBadRequest
|
||||
return
|
||||
case "23505": // Unique constraint violation
|
||||
err = fmt.Errorf("already exists")
|
||||
statusCode = http.StatusConflict
|
||||
return
|
||||
}
|
||||
}
|
||||
return http.StatusInternalServerError, errIn
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Convert "filter" URL param to SQL "WHERE" condition
|
||||
func filterToSQL(filter string) (sql string, statusCode int, err error) {
|
||||
// filterTokens := strings.Split(string(filter), ";")
|
||||
sql = "(true)"
|
||||
return
|
||||
}
|
||||
|
||||
// Convert "sort" URL param to SQL "ORDER BY"
|
||||
func sortToSQL(sort string) (sql string, statusCode int, err error) {
|
||||
if sort == "" {
|
||||
return
|
||||
}
|
||||
sortOptions := strings.Split(sort, ",")
|
||||
sql = " ORDER BY "
|
||||
for i, sortOption := range sortOptions {
|
||||
sortOrder := sortOption[:1]
|
||||
sortColumn := sortOption[1:]
|
||||
// parse sorting order marker
|
||||
switch sortOrder {
|
||||
case "+":
|
||||
sortOrder = "ASC"
|
||||
case "-":
|
||||
sortOrder = "DESC"
|
||||
default:
|
||||
err = fmt.Errorf("invalid sorting order mark: %q", sortOrder)
|
||||
statusCode = http.StatusBadRequest
|
||||
return
|
||||
}
|
||||
// validate sorting column
|
||||
var n int
|
||||
n, err = strconv.Atoi(sortColumn)
|
||||
if err != nil || n < 0 {
|
||||
err = fmt.Errorf("invalid sorting column: %q", sortColumn)
|
||||
statusCode = http.StatusBadRequest
|
||||
return
|
||||
}
|
||||
// add sorting option to query
|
||||
if i > 0 {
|
||||
sql += ","
|
||||
}
|
||||
sql += fmt.Sprintf("%s %s NULLS LAST", sortColumn, sortOrder)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
module tanabata
|
||||
|
||||
go 1.23.0
|
||||
|
||||
toolchain go1.23.10
|
||||
|
||||
require github.com/jackc/pgx/v5 v5.7.5
|
||||
|
||||
require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/pgx v3.6.2+incompatible // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/stretchr/testify v1.9.0 // indirect
|
||||
golang.org/x/crypto v0.37.0 // indirect
|
||||
golang.org/x/sync v0.13.0 // indirect
|
||||
golang.org/x/text v0.24.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,32 @@
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx v3.6.2+incompatible h1:2zP5OD7kiyR3xzRYMhOcXVvkDZsImVXfj+yIyTQf3/o=
|
||||
github.com/jackc/pgx v3.6.2+incompatible/go.mod h1:0ZGrqGqkRlliWnWB4zKnWtjbSWbGkVEFm4TeybAXq+I=
|
||||
github.com/jackc/pgx/v5 v5.7.5 h1:JHGfMnQY+IEtGM63d+NGMjoRpysB2JBwDr5fsngwmJs=
|
||||
github.com/jackc/pgx/v5 v5.7.5/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
|
||||
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
|
||||
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
|
||||
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,122 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Name string `json:"name"`
|
||||
IsAdmin bool `json:"isAdmin"`
|
||||
CanCreate bool `json:"canCreate"`
|
||||
}
|
||||
|
||||
type MIME struct {
|
||||
Name string `json:"name"`
|
||||
Extension string `json:"extension"`
|
||||
}
|
||||
|
||||
type (
|
||||
CategoryCore struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Color pgtype.Text `json:"color"`
|
||||
}
|
||||
CategoryItem struct {
|
||||
CategoryCore
|
||||
}
|
||||
CategoryFull struct {
|
||||
CategoryCore
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
Notes pgtype.Text `json:"notes"`
|
||||
}
|
||||
)
|
||||
|
||||
type (
|
||||
FileCore struct {
|
||||
ID string `json:"id"`
|
||||
Name pgtype.Text `json:"name"`
|
||||
MIME MIME `json:"mime"`
|
||||
}
|
||||
FileItem struct {
|
||||
FileCore
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
}
|
||||
FileFull struct {
|
||||
FileCore
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
Notes pgtype.Text `json:"notes"`
|
||||
Metadata json.RawMessage `json:"metadata"`
|
||||
Tags []TagCore `json:"tags"`
|
||||
Viewed int `json:"viewed"`
|
||||
}
|
||||
)
|
||||
|
||||
type (
|
||||
TagCore struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Color pgtype.Text `json:"color"`
|
||||
}
|
||||
TagItem struct {
|
||||
TagCore
|
||||
Category CategoryCore `json:"category"`
|
||||
}
|
||||
TagFull struct {
|
||||
TagCore
|
||||
Category CategoryCore `json:"category"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
Notes pgtype.Text `json:"notes"`
|
||||
UsedIncl int `json:"usedIncl"`
|
||||
UsedExcl int `json:"usedExcl"`
|
||||
}
|
||||
)
|
||||
|
||||
type Autotag struct {
|
||||
TriggerTag TagCore `json:"triggerTag"`
|
||||
AddTag TagCore `json:"addTag"`
|
||||
IsActive bool `json:"isActive"`
|
||||
}
|
||||
|
||||
type (
|
||||
PoolCore struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
PoolItem struct {
|
||||
PoolCore
|
||||
}
|
||||
PoolFull struct {
|
||||
PoolCore
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
Notes pgtype.Text `json:"notes"`
|
||||
Viewed int `json:"viewed"`
|
||||
}
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
ID int `json:"id"`
|
||||
UserAgent string `json:"userAgent"`
|
||||
StartedAt time.Time `json:"startedAt"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
LastActivity time.Time `json:"lastActivity"`
|
||||
}
|
||||
|
||||
type Pagination struct {
|
||||
Total int `json:"total"`
|
||||
Offset int `json:"offset"`
|
||||
Limit int `json:"limit"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Slice[T any] struct {
|
||||
Pagination Pagination `json:"pagination"`
|
||||
Data []T `json:"data"`
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package postgres
|
||||
|
||||
import "context"
|
||||
|
||||
func UserLogin(ctx context.Context, name, password string) (user_id int, err error) {
|
||||
row := connPool.QueryRow(ctx, "SELECT id FROM users WHERE name=$1 AND password=crypt($2, password)", name, password)
|
||||
err = row.Scan(&user_id)
|
||||
return
|
||||
}
|
||||
|
||||
func UserAuth(ctx context.Context, user_id int) (ok, isAdmin bool) {
|
||||
row := connPool.QueryRow(ctx, "SELECT is_admin FROM users WHERE id=$1", user_id)
|
||||
err := row.Scan(&isAdmin)
|
||||
ok = (err == nil)
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"tanabata/internal/domain"
|
||||
)
|
||||
|
||||
type FileStore struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewFileStore(db *pgxpool.Pool) *FileStore {
|
||||
return &FileStore{db: db}
|
||||
}
|
||||
|
||||
// Get user's access rights to file
|
||||
func (s *FileStore) getAccess(user_id int, file_id string) (canView, canEdit bool, err error) {
|
||||
ctx := context.Background()
|
||||
row := connPool.QueryRow(ctx, `
|
||||
SELECT
|
||||
COALESCE(a.view, FALSE) OR f.creator_id=$1 OR COALESCE(u.is_admin, FALSE),
|
||||
COALESCE(a.edit, FALSE) OR f.creator_id=$1 OR COALESCE(u.is_admin, FALSE)
|
||||
FROM data.files f
|
||||
LEFT JOIN acl.files a ON a.file_id=f.id AND a.user_id=$1
|
||||
LEFT JOIN system.users u ON u.id=$1
|
||||
WHERE f.id=$2
|
||||
`, user_id, file_id)
|
||||
err = row.Scan(&canView, &canEdit)
|
||||
return
|
||||
}
|
||||
|
||||
// Get a set of files
|
||||
func (s *FileStore) GetSlice(user_id int, filter, sort string, limit, offset int) (files domain.Slice[domain.FileItem], statusCode int, err error) {
|
||||
filterCond, statusCode, err := filterToSQL(filter)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
sortExpr, statusCode, err := sortToSQL(sort)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// prepare query
|
||||
query := `
|
||||
SELECT
|
||||
f.id,
|
||||
f.name,
|
||||
m.name,
|
||||
m.extension,
|
||||
uuid_extract_timestamp(f.id),
|
||||
u.name,
|
||||
u.is_admin
|
||||
FROM data.files f
|
||||
JOIN system.mime m ON m.id=f.mime_id
|
||||
JOIN system.users u ON u.id=f.creator_id
|
||||
WHERE NOT f.is_deleted AND (f.creator_id=$1 OR (SELECT view FROM acl.files WHERE file_id=f.id AND user_id=$1) OR (SELECT is_admin FROM system.users WHERE id=$1)) AND
|
||||
`
|
||||
query += filterCond
|
||||
queryCount := query
|
||||
query += sortExpr
|
||||
if limit >= 0 {
|
||||
query += fmt.Sprintf(" LIMIT %d", limit)
|
||||
}
|
||||
if offset > 0 {
|
||||
query += fmt.Sprintf(" OFFSET %d", offset)
|
||||
}
|
||||
// execute query
|
||||
statusCode, err = transaction(func(ctx context.Context, tx pgx.Tx) (statusCode int, err error) {
|
||||
rows, err := tx.Query(ctx, query, user_id)
|
||||
if err != nil {
|
||||
statusCode, err = handleDBError(err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
var file domain.FileItem
|
||||
err = rows.Scan(&file.ID, &file.Name, &file.MIME.Name, &file.MIME.Extension, &file.CreatedAt, &file.Creator.Name, &file.Creator.IsAdmin)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
return
|
||||
}
|
||||
files.Data = append(files.Data, file)
|
||||
count++
|
||||
}
|
||||
err = rows.Err()
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
return
|
||||
}
|
||||
files.Pagination.Limit = limit
|
||||
files.Pagination.Offset = offset
|
||||
files.Pagination.Count = count
|
||||
row := tx.QueryRow(ctx, fmt.Sprintf("SELECT COUNT(*) FROM (%s) tmp", queryCount), user_id)
|
||||
err = row.Scan(&files.Pagination.Total)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
}
|
||||
return
|
||||
})
|
||||
if err == nil {
|
||||
statusCode = http.StatusOK
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Get file
|
||||
func (s *FileStore) Get(user_id int, file_id string) (file domain.FileFull, statusCode int, err error) {
|
||||
ctx := context.Background()
|
||||
row := connPool.QueryRow(ctx, `
|
||||
SELECT
|
||||
f.id,
|
||||
f.name,
|
||||
m.name,
|
||||
m.extension,
|
||||
uuid_extract_timestamp(f.id),
|
||||
u.name,
|
||||
u.is_admin,
|
||||
f.notes,
|
||||
f.metadata,
|
||||
(SELECT COUNT(*) FROM activity.file_views fv WHERE fv.file_id=$2 AND fv.user_id=$1)
|
||||
FROM data.files f
|
||||
JOIN system.mime m ON m.id=f.mime_id
|
||||
JOIN system.users u ON u.id=f.creator_id
|
||||
WHERE NOT f.is_deleted AND f.id=$2 AND (f.creator_id=$1 OR (SELECT view FROM acl.files WHERE file_id=$2 AND user_id=$1) OR (SELECT is_admin FROM system.users WHERE id=$1))
|
||||
`, user_id, file_id)
|
||||
err = row.Scan(&file.ID, &file.Name, &file.MIME.Name, &file.MIME.Extension, &file.CreatedAt, &file.Creator.Name, &file.Creator.IsAdmin, &file.Notes, &file.Metadata, &file.Viewed)
|
||||
if err != nil {
|
||||
statusCode, err = handleDBError(err)
|
||||
return
|
||||
}
|
||||
rows, err := connPool.Query(ctx, `
|
||||
SELECT
|
||||
t.id,
|
||||
t.name,
|
||||
COALESCE(t.color, c.color)
|
||||
FROM data.tags t
|
||||
LEFT JOIN data.categories c ON c.id=t.category_id
|
||||
JOIN data.file_tag ft ON ft.tag_id=t.id
|
||||
WHERE ft.file_id=$1
|
||||
`, file_id)
|
||||
if err != nil {
|
||||
statusCode, err = handleDBError(err)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var tag domain.TagCore
|
||||
err = rows.Scan(&tag.ID, &tag.Name, &tag.Color)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
return
|
||||
}
|
||||
file.Tags = append(file.Tags, tag)
|
||||
}
|
||||
err = rows.Err()
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
return
|
||||
}
|
||||
statusCode = http.StatusOK
|
||||
return
|
||||
}
|
||||
|
||||
// Add file
|
||||
func (s *FileStore) Add(user_id int, name, mime string, datetime time.Time, notes string, metadata json.RawMessage) (file domain.FileCore, statusCode int, err error) {
|
||||
ctx := context.Background()
|
||||
var mime_id int
|
||||
var extension string
|
||||
row := connPool.QueryRow(ctx, "SELECT id, extension FROM system.mime WHERE name=$1", mime)
|
||||
err = row.Scan(&mime_id, &extension)
|
||||
if err != nil {
|
||||
if err == pgx.ErrNoRows {
|
||||
err = fmt.Errorf("unsupported file type: %q", mime)
|
||||
statusCode = http.StatusBadRequest
|
||||
} else {
|
||||
statusCode, err = handleDBError(err)
|
||||
}
|
||||
return
|
||||
}
|
||||
row = connPool.QueryRow(ctx, `
|
||||
INSERT INTO data.files (name, mime_id, datetime, creator_id, notes, metadata)
|
||||
VALUES (NULLIF($1, ''), $2, $3, $4, NULLIF($5 ,''), $6)
|
||||
RETURNING id
|
||||
`, name, mime_id, datetime, user_id, notes, metadata)
|
||||
err = row.Scan(&file.ID)
|
||||
if err != nil {
|
||||
statusCode, err = handleDBError(err)
|
||||
return
|
||||
}
|
||||
file.Name.String = name
|
||||
file.Name.Valid = (name != "")
|
||||
file.MIME.Name = mime
|
||||
file.MIME.Extension = extension
|
||||
statusCode = http.StatusOK
|
||||
return
|
||||
}
|
||||
|
||||
// Update file
|
||||
func (s *FileStore) Update(user_id int, file_id string, updates map[string]interface{}) (statusCode int, err error) {
|
||||
if len(updates) == 0 {
|
||||
err = fmt.Errorf("no fields provided for update")
|
||||
statusCode = http.StatusBadRequest
|
||||
return
|
||||
}
|
||||
writableFields := map[string]bool{
|
||||
"name": true,
|
||||
"datetime": true,
|
||||
"notes": true,
|
||||
"metadata": true,
|
||||
}
|
||||
query := "UPDATE data.files SET"
|
||||
newValues := []interface{}{user_id}
|
||||
count := 2
|
||||
for field, value := range updates {
|
||||
if !writableFields[field] {
|
||||
err = fmt.Errorf("invalid field: %q", field)
|
||||
statusCode = http.StatusBadRequest
|
||||
return
|
||||
}
|
||||
query += fmt.Sprintf(" %s=NULLIF($%d, '')", field, count)
|
||||
newValues = append(newValues, value)
|
||||
count++
|
||||
}
|
||||
query += fmt.Sprintf(
|
||||
" WHERE id=$%d AND (creator_id=$1 OR (SELECT edit FROM acl.files WHERE file_id=$%d AND user_id=$1) OR (SELECT is_admin FROM system.users WHERE id=$1))",
|
||||
count, count)
|
||||
newValues = append(newValues, file_id)
|
||||
ctx := context.Background()
|
||||
commandTag, err := connPool.Exec(ctx, query, newValues...)
|
||||
if err != nil {
|
||||
statusCode, err = handleDBError(err)
|
||||
return
|
||||
}
|
||||
if commandTag.RowsAffected() == 0 {
|
||||
err = fmt.Errorf("not found")
|
||||
statusCode = http.StatusNotFound
|
||||
return
|
||||
}
|
||||
statusCode = http.StatusNoContent
|
||||
return
|
||||
}
|
||||
|
||||
// Delete file
|
||||
func (s *FileStore) Delete(user_id int, file_id string) (statusCode int, err error) {
|
||||
ctx := context.Background()
|
||||
commandTag, err := connPool.Exec(ctx,
|
||||
"DELETE FROM data.files WHERE id=$2 AND (creator_id=$1 OR (SELECT edit FROM acl.files WHERE file_id=$2 AND user_id=$1) OR (SELECT is_admin FROM system.users WHERE id=$1))",
|
||||
user_id, file_id)
|
||||
if err != nil {
|
||||
statusCode, err = handleDBError(err)
|
||||
return
|
||||
}
|
||||
if commandTag.RowsAffected() == 0 {
|
||||
err = fmt.Errorf("not found")
|
||||
statusCode = http.StatusNotFound
|
||||
return
|
||||
}
|
||||
statusCode = http.StatusNoContent
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Storage struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
var connPool *pgxpool.Pool
|
||||
|
||||
// Initialize new database storage
|
||||
func New(dbURL string) (*Storage, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
config, err := pgxpool.ParseConfig(dbURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to parse DB URL: %w", err)
|
||||
}
|
||||
config.MaxConns = 10
|
||||
config.MinConns = 2
|
||||
config.HealthCheckPeriod = time.Minute
|
||||
db, err := pgxpool.NewWithConfig(ctx, config)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to connect to database: %w", err)
|
||||
}
|
||||
err = db.Ping(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("database ping failed: %w", err)
|
||||
}
|
||||
return &Storage{db: db}, nil
|
||||
}
|
||||
|
||||
// Close database storage
|
||||
func (s *Storage) Close() {
|
||||
s.db.Close()
|
||||
}
|
||||
|
||||
// Run handler inside transaction
|
||||
func (s *Storage) transaction(ctx context.Context, handler func(context.Context, pgx.Tx) (statusCode int, err error)) (statusCode int, err error) {
|
||||
tx, err := connPool.Begin(ctx)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
return
|
||||
}
|
||||
statusCode, err = handler(ctx, tx)
|
||||
if err != nil {
|
||||
tx.Rollback(ctx)
|
||||
return
|
||||
}
|
||||
err = tx.Commit(ctx)
|
||||
if err != nil {
|
||||
statusCode = http.StatusInternalServerError
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Handle database error
|
||||
func (s *Storage) handleDBError(errIn error) (statusCode int, err error) {
|
||||
if errIn == nil {
|
||||
statusCode = http.StatusOK
|
||||
return
|
||||
}
|
||||
if errors.Is(errIn, pgx.ErrNoRows) {
|
||||
err = fmt.Errorf("not found")
|
||||
statusCode = http.StatusNotFound
|
||||
return
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(errIn, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "22P02", "22007": // Invalid data format
|
||||
err = fmt.Errorf("%s", pgErr.Message)
|
||||
statusCode = http.StatusBadRequest
|
||||
return
|
||||
case "23505": // Unique constraint violation
|
||||
err = fmt.Errorf("already exists")
|
||||
statusCode = http.StatusConflict
|
||||
return
|
||||
}
|
||||
}
|
||||
return http.StatusInternalServerError, errIn
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Convert "filter" URL param to SQL "WHERE" condition
|
||||
func filterToSQL(filter string) (sql string, statusCode int, err error) {
|
||||
// filterTokens := strings.Split(string(filter), ";")
|
||||
sql = "(true)"
|
||||
return
|
||||
}
|
||||
|
||||
// Convert "sort" URL param to SQL "ORDER BY"
|
||||
func sortToSQL(sort string) (sql string, statusCode int, err error) {
|
||||
if sort == "" {
|
||||
return
|
||||
}
|
||||
sortOptions := strings.Split(sort, ",")
|
||||
sql = " ORDER BY "
|
||||
for i, sortOption := range sortOptions {
|
||||
sortOrder := sortOption[:1]
|
||||
sortColumn := sortOption[1:]
|
||||
// parse sorting order marker
|
||||
switch sortOrder {
|
||||
case "+":
|
||||
sortOrder = "ASC"
|
||||
case "-":
|
||||
sortOrder = "DESC"
|
||||
default:
|
||||
err = fmt.Errorf("invalid sorting order mark: %q", sortOrder)
|
||||
statusCode = http.StatusBadRequest
|
||||
return
|
||||
}
|
||||
// validate sorting column
|
||||
var n int
|
||||
n, err = strconv.Atoi(sortColumn)
|
||||
if err != nil || n < 0 {
|
||||
err = fmt.Errorf("invalid sorting column: %q", sortColumn)
|
||||
statusCode = http.StatusBadRequest
|
||||
return
|
||||
}
|
||||
// add sorting option to query
|
||||
if i > 0 {
|
||||
sql += ","
|
||||
}
|
||||
sql += fmt.Sprintf("%s %s NULLS LAST", sortColumn, sortOrder)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"tanabata/internal/domain"
|
||||
)
|
||||
|
||||
type Storage interface {
|
||||
FileRepository
|
||||
Close()
|
||||
}
|
||||
|
||||
type FileRepository interface {
|
||||
GetSlice(user_id int, filter, sort string, limit, offset int) (files domain.Slice[domain.FileItem], statusCode int, err error)
|
||||
Get(user_id int, file_id string) (file domain.FileFull, statusCode int, err error)
|
||||
Add(user_id int, name, mime string, datetime time.Time, notes string, metadata json.RawMessage) (file domain.FileCore, statusCode int, err error)
|
||||
Update(user_id int, file_id string, updates map[string]interface{}) (statusCode int, err error)
|
||||
Delete(user_id int, file_id string) (statusCode int, err error)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
Name string `json:"name"`
|
||||
IsAdmin bool `json:"isAdmin"`
|
||||
CanCreate bool `json:"canCreate"`
|
||||
}
|
||||
|
||||
type MIME struct {
|
||||
Name string `json:"name"`
|
||||
Extension string `json:"extension"`
|
||||
}
|
||||
|
||||
type (
|
||||
CategoryCore struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Color pgtype.Text `json:"color"`
|
||||
}
|
||||
CategoryItem struct {
|
||||
CategoryCore
|
||||
}
|
||||
CategoryFull struct {
|
||||
CategoryCore
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
Notes pgtype.Text `json:"notes"`
|
||||
}
|
||||
)
|
||||
|
||||
type (
|
||||
FileCore struct {
|
||||
ID string `json:"id"`
|
||||
Name pgtype.Text `json:"name"`
|
||||
MIME MIME `json:"mime"`
|
||||
}
|
||||
FileItem struct {
|
||||
FileCore
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
}
|
||||
FileFull struct {
|
||||
FileCore
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
Notes pgtype.Text `json:"notes"`
|
||||
Metadata json.RawMessage `json:"metadata"`
|
||||
Tags []TagCore `json:"tags"`
|
||||
Viewed int `json:"viewed"`
|
||||
}
|
||||
)
|
||||
|
||||
type (
|
||||
TagCore struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Color pgtype.Text `json:"color"`
|
||||
}
|
||||
TagItem struct {
|
||||
TagCore
|
||||
Category CategoryCore `json:"category"`
|
||||
}
|
||||
TagFull struct {
|
||||
TagCore
|
||||
Category CategoryCore `json:"category"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
Notes pgtype.Text `json:"notes"`
|
||||
}
|
||||
)
|
||||
|
||||
type Autotag struct {
|
||||
TriggerTag TagCore `json:"triggerTag"`
|
||||
AddTag TagCore `json:"addTag"`
|
||||
IsActive bool `json:"isActive"`
|
||||
}
|
||||
|
||||
type (
|
||||
PoolCore struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
PoolItem struct {
|
||||
PoolCore
|
||||
}
|
||||
PoolFull struct {
|
||||
PoolCore
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Creator User `json:"creator"`
|
||||
Notes pgtype.Text `json:"notes"`
|
||||
Viewed int `json:"viewed"`
|
||||
}
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
ID int `json:"id"`
|
||||
UserAgent string `json:"userAgent"`
|
||||
StartedAt time.Time `json:"startedAt"`
|
||||
ExpiresAt time.Time `json:"expiresAt"`
|
||||
LastActivity time.Time `json:"lastActivity"`
|
||||
}
|
||||
|
||||
type Pagination struct {
|
||||
Total int `json:"total"`
|
||||
Offset int `json:"offset"`
|
||||
Limit int `json:"limit"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type Slice[T any] struct {
|
||||
Pagination Pagination `json:"pagination"`
|
||||
Data []T `json:"data"`
|
||||
}
|
||||
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 2.6 KiB |
|
Before Width: | Height: | Size: 3.4 KiB After Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 5.0 KiB |
|
Before Width: | Height: | Size: 6.6 KiB After Width: | Height: | Size: 6.6 KiB |
|
Before Width: | Height: | Size: 7.8 KiB After Width: | Height: | Size: 7.8 KiB |
|
Before Width: | Height: | Size: 8.3 KiB After Width: | Height: | Size: 8.3 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 3.9 KiB After Width: | Height: | Size: 3.9 KiB |
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 4.2 KiB |
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 5.0 KiB |
|
Before Width: | Height: | Size: 5.2 KiB After Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 1.6 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 2.4 KiB |
|
Before Width: | Height: | Size: 7.0 KiB After Width: | Height: | Size: 7.0 KiB |
|
Before Width: | Height: | Size: 127 KiB After Width: | Height: | Size: 127 KiB |
|
Before Width: | Height: | Size: 158 KiB After Width: | Height: | Size: 158 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 985 B After Width: | Height: | Size: 985 B |
|
Before Width: | Height: | Size: 2.5 KiB After Width: | Height: | Size: 2.5 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
|
Before Width: | Height: | Size: 794 B After Width: | Height: | Size: 794 B |
|
Before Width: | Height: | Size: 3.3 KiB After Width: | Height: | Size: 3.3 KiB |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 626 B After Width: | Height: | Size: 626 B |
|
Before Width: | Height: | Size: 1.0 KiB After Width: | Height: | Size: 1.0 KiB |
|
Before Width: | Height: | Size: 972 KiB After Width: | Height: | Size: 972 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 11 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 5.0 KiB After Width: | Height: | Size: 5.0 KiB |
|
Before Width: | Height: | Size: 149 KiB After Width: | Height: | Size: 149 KiB |
|
Before Width: | Height: | Size: 110 KiB After Width: | Height: | Size: 110 KiB |
|
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |