Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c8f39273c | ||
|
|
721311a643 | ||
|
|
7f1e8e572d | ||
|
|
02a0a36dc3 | ||
|
|
5a430c08f4 | ||
|
|
54e8fd5fed | ||
|
|
70460e4170 | ||
|
|
834493a4f5 | ||
|
|
a49eec909c | ||
|
|
e10a5e57e2 | ||
|
|
ff0854f331 | ||
|
|
b3793d5dbb | ||
|
|
008b0dfbb9 | ||
|
|
67d456baf6 | ||
|
|
0d99544579 | ||
|
|
95ae043d3e |
No files matched your search
@@ -14,3 +14,4 @@ CORS_ALLOWED_ORIGINS=
|
|||||||
AUTH_RATE_LIMIT_MAX_ATTEMPTS=5
|
AUTH_RATE_LIMIT_MAX_ATTEMPTS=5
|
||||||
AUTH_RATE_LIMIT_WINDOW_SECONDS=60
|
AUTH_RATE_LIMIT_WINDOW_SECONDS=60
|
||||||
TRUSTED_PROXIES=
|
TRUSTED_PROXIES=
|
||||||
|
UPDATE_FEED_URL=https://git.floriansylvain.fr
|
||||||
@@ -20,5 +20,10 @@ build-errors.log
|
|||||||
uploadedImages/
|
uploadedImages/
|
||||||
*.exe
|
*.exe
|
||||||
|
|
||||||
|
# AI fest
|
||||||
.claude/
|
.claude/
|
||||||
CLAUDE.md
|
CLAUDE.md
|
||||||
|
.codex/
|
||||||
|
.agents/
|
||||||
|
AGENTS.md
|
||||||
|
codex-workflow.md
|
||||||
@@ -15,6 +15,10 @@ cp .env.example .env # fill in PUBLIC_URL, JWT_SECRET and SMTP_*
|
|||||||
|
|
||||||
Data is stored in `./data/` by default. For a real server (systemd, HTTPS, backups), see **[docs/deployment.md](docs/deployment.md)**.
|
Data is stored in `./data/` by default. For a real server (systemd, HTTPS, backups), see **[docs/deployment.md](docs/deployment.md)**.
|
||||||
|
|
||||||
|
### Updates from the browser
|
||||||
|
|
||||||
|
On Linux with systemd, install v2.6.0-beta or newer manually, then follow [the browser-update setup guide](docs/deployment.md#browser-updates). It covers finding the actual database directory, installing the helper, testing a restart and troubleshooting. Other platforms use manual upgrades.
|
||||||
|
|
||||||
### Develop
|
### Develop
|
||||||
|
|
||||||
Requires Go 1.27+, Node.js 22, [Bun](https://bun.sh) and [Task](https://taskfile.dev).
|
Requires Go 1.27+, Node.js 22, [Bun](https://bun.sh) and [Task](https://taskfile.dev).
|
||||||
|
|||||||
+25
-2
@@ -122,14 +122,37 @@ tasks:
|
|||||||
- go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}{{exeExt}} ./cmd/server
|
- go build -trimpath -ldflags "{{.LDFLAGS}}" -o bin/{{.BINARY}}{{exeExt}} ./cmd/server
|
||||||
|
|
||||||
release:
|
release:
|
||||||
desc: Cross-compile production binaries for all release targets → bin/
|
desc: Cross-compile and sign production binaries for all release targets → bin/ (needs RELEASE_SIGNING_KEY)
|
||||||
deps: [build:web]
|
|
||||||
cmds:
|
cmds:
|
||||||
|
- task: release:check
|
||||||
|
- task: build:web
|
||||||
- for: { var: RELEASE_TARGETS }
|
- for: { var: RELEASE_TARGETS }
|
||||||
task: build:target
|
task: build:target
|
||||||
vars:
|
vars:
|
||||||
GOOS: '{{index (splitList "/" .ITEM) 0}}'
|
GOOS: '{{index (splitList "/" .ITEM) 0}}'
|
||||||
GOARCH: '{{index (splitList "/" .ITEM) 1}}'
|
GOARCH: '{{index (splitList "/" .ITEM) 1}}'
|
||||||
|
- go run ./cmd/releasesign checksums bin --match "{{.BINARY}}_{{.VERSION}}_*"
|
||||||
|
- go run ./cmd/releasesign sign bin/checksums.txt
|
||||||
|
- go run ./cmd/releasesign verify bin/checksums.txt
|
||||||
|
|
||||||
|
release:check:
|
||||||
|
internal: true
|
||||||
|
cmds:
|
||||||
|
- cmd: 'test -n "$RELEASE_SIGNING_KEY" || { echo "RELEASE_SIGNING_KEY is not set. Point it at the private release key file (see task release:keygen)." >&2; exit 1; }'
|
||||||
|
silent: true
|
||||||
|
- cmd: 'test -f "$RELEASE_SIGNING_KEY" || { echo "RELEASE_SIGNING_KEY points to a missing file: $RELEASE_SIGNING_KEY" >&2; exit 1; }'
|
||||||
|
silent: true
|
||||||
|
- mkdir -p tmp
|
||||||
|
- echo probe > tmp/release-probe.txt
|
||||||
|
- defer: rm -f tmp/release-probe.txt tmp/release-probe.txt.sig
|
||||||
|
- go run ./cmd/releasesign sign tmp/release-probe.txt
|
||||||
|
|
||||||
|
release:keygen:
|
||||||
|
desc: One-time release key pair. Usage, task release:keygen -- <private key path outside the repository>
|
||||||
|
cmds:
|
||||||
|
- cmd: 'test -n "{{.CLI_ARGS}}" || { echo "usage: task release:keygen -- <private key path outside the repository>" >&2; exit 1; }'
|
||||||
|
silent: true
|
||||||
|
- go run ./cmd/releasesign keygen {{.CLI_ARGS}}
|
||||||
|
|
||||||
build:target:
|
build:target:
|
||||||
internal: true
|
internal: true
|
||||||
|
|||||||
+132
-7
@@ -5,16 +5,22 @@ import (
|
|||||||
domainImage "RenewCMS/internal/domain/image"
|
domainImage "RenewCMS/internal/domain/image"
|
||||||
domainInvite "RenewCMS/internal/domain/invite"
|
domainInvite "RenewCMS/internal/domain/invite"
|
||||||
domainMail "RenewCMS/internal/domain/mail"
|
domainMail "RenewCMS/internal/domain/mail"
|
||||||
|
domainUpdate "RenewCMS/internal/domain/update"
|
||||||
domainUser "RenewCMS/internal/domain/user"
|
domainUser "RenewCMS/internal/domain/user"
|
||||||
"RenewCMS/internal/infrastructure/config"
|
"RenewCMS/internal/infrastructure/config"
|
||||||
"RenewCMS/internal/infrastructure/hashing"
|
"RenewCMS/internal/infrastructure/hashing"
|
||||||
"RenewCMS/internal/infrastructure/mailer"
|
"RenewCMS/internal/infrastructure/mailer"
|
||||||
"RenewCMS/internal/infrastructure/persistence/models"
|
"RenewCMS/internal/infrastructure/persistence/models"
|
||||||
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
persistence "RenewCMS/internal/infrastructure/persistence/repositories"
|
||||||
|
"RenewCMS/internal/infrastructure/update"
|
||||||
"RenewCMS/internal/infrastructure/useCases"
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"crypto/ed25519"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/glebarez/sqlite"
|
"github.com/glebarez/sqlite"
|
||||||
"github.com/go-chi/jwtauth/v5"
|
"github.com/go-chi/jwtauth/v5"
|
||||||
@@ -45,8 +51,17 @@ type UseCases struct {
|
|||||||
AcceptInviteUseCase *useCases.AcceptInviteUseCase
|
AcceptInviteUseCase *useCases.AcceptInviteUseCase
|
||||||
SendMailUseCase *useCases.SendMailUseCase
|
SendMailUseCase *useCases.SendMailUseCase
|
||||||
CreateImageUseCase *useCases.CreateImageUseCase
|
CreateImageUseCase *useCases.CreateImageUseCase
|
||||||
DeleteImageUseCase *useCases.DeleteImageUseCase
|
ListMediaUseCase *useCases.ListMediaUseCase
|
||||||
|
RenameMediaUseCase *useCases.RenameMediaUseCase
|
||||||
|
DeleteMediaUseCase *useCases.DeleteMediaUseCase
|
||||||
|
MergeMediaUseCase *useCases.MergeMediaUseCase
|
||||||
|
GetMediaUsageUseCase *useCases.GetMediaUsageUseCase
|
||||||
GetSettingsUseCase *useCases.GetSettingsUseCase
|
GetSettingsUseCase *useCases.GetSettingsUseCase
|
||||||
|
GetUpdateStatusUseCase *useCases.GetUpdateStatusUseCase
|
||||||
|
CheckForUpdateUseCase *useCases.CheckForUpdateUseCase
|
||||||
|
StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase
|
||||||
|
RequestRestartUseCase *useCases.RequestRestartUseCase
|
||||||
|
RecordRunningInfoUseCase *useCases.RecordRunningInfoUseCase
|
||||||
}
|
}
|
||||||
|
|
||||||
type Repositories struct {
|
type Repositories struct {
|
||||||
@@ -55,15 +70,33 @@ type Repositories struct {
|
|||||||
ImageRepo domainImage.Repository
|
ImageRepo domainImage.Repository
|
||||||
InviteRepo domainInvite.Repository
|
InviteRepo domainInvite.Repository
|
||||||
MailRepo domainMail.Repository
|
MailRepo domainMail.Repository
|
||||||
|
ReleaseFeed domainUpdate.ReleaseFeed
|
||||||
|
UpdateStore domainUpdate.StatusStore
|
||||||
|
UpdateJobs domainUpdate.JobStore
|
||||||
|
UpdateHelper domainUpdate.HelperDetector
|
||||||
|
AssetFetcher domainUpdate.AssetFetcher
|
||||||
|
SignatureVerifier domainUpdate.SignatureVerifier
|
||||||
|
StagedRunner domainUpdate.StagedBinaryRunner
|
||||||
|
DatabaseBackup domainUpdate.DatabaseBackup
|
||||||
|
UpdateResults domainUpdate.ResultStore
|
||||||
|
RestartRequests domainUpdate.RestartRequestStore
|
||||||
|
RunningInfo domainUpdate.RunningInfoStore
|
||||||
}
|
}
|
||||||
|
|
||||||
const sqliteBusyTimeoutMs = 5000
|
const (
|
||||||
|
sqliteBusyTimeoutMs = 5000
|
||||||
|
updateStatusFileName = "update-status.json"
|
||||||
|
updateJobFileName = "update-job.json"
|
||||||
|
updateHelperFileName = "update-helper.json"
|
||||||
|
updatesDirName = "updates"
|
||||||
|
backupsDirName = "backups"
|
||||||
|
)
|
||||||
|
|
||||||
func SQLiteDSN(dbName string) string {
|
func SQLiteDSN(dbName string) string {
|
||||||
return fmt.Sprintf("%s?_pragma=busy_timeout(%d)", dbName, sqliteBusyTimeoutMs)
|
return fmt.Sprintf("%s?_pragma=busy_timeout(%d)", dbName, sqliteBusyTimeoutMs)
|
||||||
}
|
}
|
||||||
|
|
||||||
func getDb(dbName string) *gorm.DB {
|
func getDb(dbName string, uploadDir string) *gorm.DB {
|
||||||
if err := os.MkdirAll(filepath.Dir(dbName), os.ModePerm); err != nil {
|
if err := os.MkdirAll(filepath.Dir(dbName), os.ModePerm); err != nil {
|
||||||
panic("Unable to create necessary subdirectories: " + err.Error())
|
panic("Unable to create necessary subdirectories: " + err.Error())
|
||||||
}
|
}
|
||||||
@@ -72,7 +105,7 @@ func getDb(dbName string) *gorm.DB {
|
|||||||
panic("Unable to open the database: " + err.Error())
|
panic("Unable to open the database: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := db.AutoMigrate(&models.Article{}, &models.User{}, &models.Invite{}); err != nil {
|
if err := db.AutoMigrate(&models.Article{}, &models.Image{}, &models.User{}, &models.Invite{}); err != nil {
|
||||||
panic("Failed to migrate database: " + err.Error())
|
panic("Failed to migrate database: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,16 +113,40 @@ func getDb(dbName string) *gorm.DB {
|
|||||||
panic("Failed to backfill user roles: " + err.Error())
|
panic("Failed to backfill user roles: " + err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := persistence.BackfillImageMetadata(db, uploadDir); err != nil {
|
||||||
|
panic("Failed to backfill image metadata: " + err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func releasePublicKey() ed25519.PublicKey {
|
||||||
|
key, err := update.EmbeddedPublicKey()
|
||||||
|
if err != nil {
|
||||||
|
panic("Unable to read the embedded release key: " + err.Error())
|
||||||
|
}
|
||||||
|
return key
|
||||||
|
}
|
||||||
|
|
||||||
func getRepositories(db *gorm.DB, settings config.Settings) *Repositories {
|
func getRepositories(db *gorm.DB, settings config.Settings) *Repositories {
|
||||||
|
dataDir := filepath.Dir(settings.DBFile)
|
||||||
return &Repositories{
|
return &Repositories{
|
||||||
ArticleRepo: persistence.NewArticleRepository(db),
|
ArticleRepo: persistence.NewArticleRepository(db),
|
||||||
UserRepo: persistence.NewUserRepository(db),
|
UserRepo: persistence.NewUserRepository(db),
|
||||||
ImageRepo: persistence.NewImageRepository(db, settings.UploadDir),
|
ImageRepo: persistence.NewImageRepository(db, settings.UploadDir),
|
||||||
InviteRepo: persistence.NewInviteRepository(db),
|
InviteRepo: persistence.NewInviteRepository(db),
|
||||||
MailRepo: mailer.NewMailRepository(settings.Smtp),
|
MailRepo: mailer.NewMailRepository(settings.Smtp),
|
||||||
|
ReleaseFeed: update.NewGiteaReleaseFeed(settings.UpdateFeedURL),
|
||||||
|
UpdateStore: update.NewJSONStatusStore(filepath.Join(dataDir, updateStatusFileName)),
|
||||||
|
UpdateJobs: update.NewJSONJobStore(filepath.Join(dataDir, updateJobFileName)),
|
||||||
|
UpdateHelper: update.NewFileHelperDetector(filepath.Join(dataDir, updateHelperFileName)),
|
||||||
|
AssetFetcher: update.NewHTTPAssetFetcher(settings.UpdateFeedURL),
|
||||||
|
SignatureVerifier: update.NewEd25519SignatureVerifier(releasePublicKey()),
|
||||||
|
StagedRunner: update.NewExecStagedBinaryRunner(),
|
||||||
|
DatabaseBackup: update.NewSQLiteDatabaseBackup(db, filepath.Join(dataDir, backupsDirName), time.Now),
|
||||||
|
UpdateResults: update.NewJSONResultStore(filepath.Join(dataDir, domainUpdate.ResultFileName)),
|
||||||
|
RestartRequests: update.NewJSONRestartRequestStore(filepath.Join(dataDir, domainUpdate.RestartRequestFileName)),
|
||||||
|
RunningInfo: update.NewJSONRunningInfoStore(filepath.Join(dataDir, domainUpdate.RunningInfoFileName)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,7 +159,7 @@ func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
|
|||||||
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo),
|
GetArticleUseCase: useCases.NewGetArticleUseCase(repos.ArticleRepo),
|
||||||
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo),
|
ListArticlesUseCase: useCases.NewListArticlesUseCase(repos.ArticleRepo),
|
||||||
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo),
|
UpdateArticleUseCase: useCases.NewUpdateArticleUseCase(repos.ArticleRepo),
|
||||||
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo, repos.ImageRepo),
|
DeleteArticleUseCase: useCases.NewDeleteArticleUseCase(repos.ArticleRepo),
|
||||||
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
|
GetUserUseCase: useCases.NewGetUserUseCase(repos.UserRepo),
|
||||||
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL),
|
CreateUserUseCase: useCases.NewCreateUserUseCase(repos.UserRepo, hasher, repos.MailRepo, settings.PublicURL),
|
||||||
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher),
|
AuthenticateUserUseCase: useCases.NewAuthenticateUserUseCase(repos.UserRepo, hasher),
|
||||||
@@ -120,13 +177,42 @@ func getUseCases(repos *Repositories, settings config.Settings) *UseCases {
|
|||||||
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher),
|
AcceptInviteUseCase: useCases.NewAcceptInviteUseCase(repos.UserRepo, repos.InviteRepo, hasher),
|
||||||
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
|
SendMailUseCase: useCases.NewSendMailUseCase(repos.MailRepo),
|
||||||
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo),
|
CreateImageUseCase: useCases.NewCreateImageUseCase(repos.ImageRepo),
|
||||||
DeleteImageUseCase: useCases.NewDeleteImageUseCase(repos.ImageRepo),
|
ListMediaUseCase: useCases.NewListMediaUseCase(repos.ImageRepo, repos.ArticleRepo, repos.UserRepo),
|
||||||
|
RenameMediaUseCase: useCases.NewRenameMediaUseCase(repos.ImageRepo),
|
||||||
|
DeleteMediaUseCase: useCases.NewDeleteMediaUseCase(repos.ImageRepo),
|
||||||
|
MergeMediaUseCase: useCases.NewMergeMediaUseCase(repos.ImageRepo, repos.ArticleRepo),
|
||||||
|
GetMediaUsageUseCase: useCases.NewGetMediaUsageUseCase(repos.ImageRepo, repos.ArticleRepo),
|
||||||
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
|
GetSettingsUseCase: useCases.NewGetSettingsUseCase(settings.Version),
|
||||||
|
GetUpdateStatusUseCase: useCases.NewGetUpdateStatusUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now),
|
||||||
|
CheckForUpdateUseCase: useCases.NewCheckForUpdateUseCase(repos.ReleaseFeed, repos.UpdateStore, settings.Version, time.Now),
|
||||||
|
StartUpdateDownloadUseCase: startUpdateDownloadUseCase(repos, settings),
|
||||||
|
RequestRestartUseCase: useCases.NewRequestRestartUseCase(repos.UpdateStore, repos.UpdateJobs, repos.UpdateHelper, repos.UpdateResults, repos.RestartRequests, settings.Version, time.Now),
|
||||||
|
RecordRunningInfoUseCase: useCases.NewRecordRunningInfoUseCase(repos.RunningInfo, settings.Version, os.Getpid(), time.Now),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func startUpdateDownloadUseCase(repos *Repositories, settings config.Settings) *useCases.StartUpdateDownloadUseCase {
|
||||||
|
return useCases.NewStartUpdateDownloadUseCase(useCases.StartUpdateDownloadDependencies{
|
||||||
|
Store: repos.UpdateStore,
|
||||||
|
Jobs: repos.UpdateJobs,
|
||||||
|
Helper: repos.UpdateHelper,
|
||||||
|
Results: repos.UpdateResults,
|
||||||
|
Requests: repos.RestartRequests,
|
||||||
|
Fetcher: repos.AssetFetcher,
|
||||||
|
Verifier: repos.SignatureVerifier,
|
||||||
|
Runner: repos.StagedRunner,
|
||||||
|
Backup: repos.DatabaseBackup,
|
||||||
|
Staging: update.NewOSStagingArea(filepath.Join(filepath.Dir(settings.DBFile), updatesDirName)),
|
||||||
|
Logger: log.Default(),
|
||||||
|
CurrentVersion: settings.Version,
|
||||||
|
Platform: domainUpdate.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH},
|
||||||
|
FeedURL: settings.UpdateFeedURL,
|
||||||
|
Now: time.Now,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func InitContainer(settings config.Settings) (*UseCases, func() error) {
|
func InitContainer(settings config.Settings) (*UseCases, func() error) {
|
||||||
db := getDb(settings.DBFile)
|
db := getDb(settings.DBFile, settings.UploadDir)
|
||||||
repos := getRepositories(db, settings)
|
repos := getRepositories(db, settings)
|
||||||
return getUseCases(repos, settings), closeDb(db)
|
return getUseCases(repos, settings), closeDb(db)
|
||||||
}
|
}
|
||||||
@@ -140,3 +226,42 @@ func closeDb(db *gorm.DB) func() error {
|
|||||||
return sqlDb.Close()
|
return sqlDb.Close()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type BrowserUpdateCommands struct {
|
||||||
|
Enable *useCases.EnableBrowserUpdatesUseCase
|
||||||
|
Disable *useCases.DisableBrowserUpdatesUseCase
|
||||||
|
}
|
||||||
|
|
||||||
|
func InitBrowserUpdateCommands() *BrowserUpdateCommands {
|
||||||
|
units := update.NewSystemdUnits()
|
||||||
|
dependencies := useCases.ManageBrowserUpdatesDependencies{
|
||||||
|
Probe: update.NewSystemMachineProbe(),
|
||||||
|
Locator: units,
|
||||||
|
Units: units,
|
||||||
|
Manager: update.NewSystemctlControl(domainUpdate.ServiceUnitName),
|
||||||
|
Status: update.NewJSONHelperStatusWriter(),
|
||||||
|
Now: time.Now,
|
||||||
|
}
|
||||||
|
return &BrowserUpdateCommands{
|
||||||
|
Enable: useCases.NewEnableBrowserUpdatesUseCase(dependencies),
|
||||||
|
Disable: useCases.NewDisableBrowserUpdatesUseCase(dependencies),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func InitApplyUpdateCommand(options domainUpdate.InstallOptions) *useCases.ApplyRestartRequestUseCase {
|
||||||
|
layout := domainUpdate.HelperLayout{DataDir: options.DataDir, BinaryPath: options.Binary}
|
||||||
|
files := update.NewNoFollowFilesystem()
|
||||||
|
return useCases.NewApplyRestartRequestUseCase(useCases.ApplyRestartRequestDependencies{
|
||||||
|
Requests: update.NewFSRestartRequestStore(files, layout.RestartRequestPath()),
|
||||||
|
Results: update.NewFSResultStore(files, layout.ResultPath()),
|
||||||
|
Running: update.NewJSONRunningInfoStore(filepath.Join(options.DataDir, domainUpdate.RunningInfoFileName)),
|
||||||
|
Files: files,
|
||||||
|
Service: update.NewSystemctlControl(options.Service),
|
||||||
|
Health: update.NewHTTPHealthChecker(options.Port),
|
||||||
|
Verifier: update.NewEd25519SignatureVerifier(releasePublicKey()),
|
||||||
|
Clock: update.NewSystemClock(),
|
||||||
|
Logger: log.Default(),
|
||||||
|
Layout: layout,
|
||||||
|
Platform: domainUpdate.Platform{OS: runtime.GOOS, Arch: runtime.GOARCH},
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,121 +0,0 @@
|
|||||||
package image
|
|
||||||
|
|
||||||
import (
|
|
||||||
"RenewCMS/api/pkg/apperr"
|
|
||||||
domainArticle "RenewCMS/internal/domain/article"
|
|
||||||
domainImage "RenewCMS/internal/domain/image"
|
|
||||||
"RenewCMS/internal/infrastructure/useCases"
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"github.com/go-chi/chi/v5"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Handler struct {
|
|
||||||
CreateUseCase *useCases.CreateImageUseCase
|
|
||||||
GetUseCase *useCases.GetArticleUseCase
|
|
||||||
UpdateUseCase *useCases.UpdateArticleUseCase
|
|
||||||
DeleteUseCase *useCases.DeleteImageUseCase
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewHandler(create *useCases.CreateImageUseCase, get *useCases.GetArticleUseCase, update *useCases.UpdateArticleUseCase, deleteUseCase *useCases.DeleteImageUseCase) *Handler {
|
|
||||||
return &Handler{
|
|
||||||
CreateUseCase: create,
|
|
||||||
GetUseCase: get,
|
|
||||||
UpdateUseCase: update,
|
|
||||||
DeleteUseCase: deleteUseCase,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeInternalServerError(w http.ResponseWriter) {
|
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
|
|
||||||
func writeArticleError(w http.ResponseWriter, err error) {
|
|
||||||
if errors.Is(err, domainArticle.ErrArticleNotFound) {
|
|
||||||
http.Error(w, apperr.ArticleNotFoundErrorMessage, http.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeInternalServerError(w)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) PostImage(w http.ResponseWriter, r *http.Request) {
|
|
||||||
articleId, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := h.GetUseCase.GetArticle(uint32(articleId)); err != nil {
|
|
||||||
writeArticleError(w, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
file, fileHeader, err := r.FormFile("file")
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
newImage, err := h.CreateUseCase.CreateImage(domainImage.ImageInput{
|
|
||||||
Content: file,
|
|
||||||
Filename: fileHeader.Filename,
|
|
||||||
Size: fileHeader.Size,
|
|
||||||
ContentType: fileHeader.Header.Get("Content-Type"),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, domainImage.ErrImageTypeNotAllowed) || errors.Is(err, domainImage.ErrImageTooLarge) {
|
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeInternalServerError(w)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.UpdateUseCase.AddImage(uint32(articleId), newImage.ID); err != nil {
|
|
||||||
writeArticleError(w, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
responseJson, err := json.Marshal(map[string]any{"id": newImage.ID, "location": newImage.Path})
|
|
||||||
if err != nil {
|
|
||||||
writeInternalServerError(w)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusCreated)
|
|
||||||
_, _ = w.Write(responseJson)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) DeleteImage(w http.ResponseWriter, r *http.Request) {
|
|
||||||
articleId, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
imageId, err := strconv.ParseUint(chi.URLParam(r, "imageId"), 10, 32)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err := h.GetUseCase.GetArticle(uint32(articleId)); err != nil {
|
|
||||||
writeArticleError(w, err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := h.DeleteUseCase.DeleteImage(uint32(imageId)); err != nil {
|
|
||||||
if errors.Is(err, domainImage.ErrImageNotFound) {
|
|
||||||
http.Error(w, apperr.ImageNotFoundErrorMessage, http.StatusNotFound)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
writeInternalServerError(w)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
package media
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/api/pkg/claims"
|
||||||
|
"RenewCMS/api/pkg/upload"
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
domainImage "RenewCMS/internal/domain/image"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
CreateUseCase *useCases.CreateImageUseCase
|
||||||
|
ListUseCase *useCases.ListMediaUseCase
|
||||||
|
RenameUseCase *useCases.RenameMediaUseCase
|
||||||
|
DeleteUseCase *useCases.DeleteMediaUseCase
|
||||||
|
MergeUseCase *useCases.MergeMediaUseCase
|
||||||
|
UsageUseCase *useCases.GetMediaUsageUseCase
|
||||||
|
}
|
||||||
|
|
||||||
|
type RenameRequest struct {
|
||||||
|
Filename string `json:"filename" validate:"required"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type MergeRequest struct {
|
||||||
|
KeepID uint32 `json:"keep_id" validate:"required,gt=0"`
|
||||||
|
MergeIDs []uint32 `json:"merge_ids" validate:"required,min=1,dive,gt=0"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type mediaItemResponse struct {
|
||||||
|
ID uint32 `json:"id"`
|
||||||
|
Filename string `json:"filename"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Width *int `json:"width"`
|
||||||
|
Height *int `json:"height"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
UploadedBy string `json:"uploaded_by"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UsedIn int `json:"used_in"`
|
||||||
|
Duplicate bool `json:"duplicate"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type countsResponse struct {
|
||||||
|
All int `json:"all"`
|
||||||
|
Unused int `json:"unused"`
|
||||||
|
Duplicates int `json:"duplicates"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type listResponse struct {
|
||||||
|
Items []mediaItemResponse `json:"items"`
|
||||||
|
NextCursor *string `json:"next_cursor"`
|
||||||
|
Counts countsResponse `json:"counts"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type usageResponse struct {
|
||||||
|
ID uint32 `json:"id"`
|
||||||
|
Title string `json:"title"`
|
||||||
|
Published bool `json:"published"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type mergeResponse struct {
|
||||||
|
ArticlesUpdated int `json:"articles_updated"`
|
||||||
|
Merged int `json:"merged"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(create *useCases.CreateImageUseCase, list *useCases.ListMediaUseCase, rename *useCases.RenameMediaUseCase, deleteUseCase *useCases.DeleteMediaUseCase, merge *useCases.MergeMediaUseCase, usage *useCases.GetMediaUsageUseCase) *Handler {
|
||||||
|
return &Handler{
|
||||||
|
CreateUseCase: create,
|
||||||
|
ListUseCase: list,
|
||||||
|
RenameUseCase: rename,
|
||||||
|
DeleteUseCase: deleteUseCase,
|
||||||
|
MergeUseCase: merge,
|
||||||
|
UsageUseCase: usage,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeInternalServerError(w http.ResponseWriter) {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||||
|
body, err := json.Marshal(payload)
|
||||||
|
if err != nil {
|
||||||
|
writeInternalServerError(w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(status)
|
||||||
|
_, _ = w.Write(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeImageError(w http.ResponseWriter, err error) {
|
||||||
|
if errors.Is(err, domainImage.ErrImageNotFound) {
|
||||||
|
http.Error(w, apperr.ImageNotFoundErrorMessage, http.StatusNotFound)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeInternalServerError(w)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseImageId(w http.ResponseWriter, r *http.Request) (uint32, bool) {
|
||||||
|
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
return uint32(id), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func dimension(value int) *int {
|
||||||
|
if value == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &value
|
||||||
|
}
|
||||||
|
|
||||||
|
func toResponse(item useCases.MediaItem) mediaItemResponse {
|
||||||
|
return mediaItemResponse{
|
||||||
|
ID: item.Image.ID,
|
||||||
|
Filename: item.Image.Filename,
|
||||||
|
URL: item.Image.Path,
|
||||||
|
Size: item.Image.Size,
|
||||||
|
ContentType: item.Image.ContentType,
|
||||||
|
Width: dimension(item.Image.Width),
|
||||||
|
Height: dimension(item.Image.Height),
|
||||||
|
SHA256: item.Image.SHA256,
|
||||||
|
UploadedBy: item.UploadedBy,
|
||||||
|
CreatedAt: item.Image.CreatedAt,
|
||||||
|
UsedIn: item.UsedIn,
|
||||||
|
Duplicate: item.Duplicate,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseListQuery(r *http.Request) (domainImage.ListQuery, error) {
|
||||||
|
values, err := url.ParseQuery(r.URL.RawQuery)
|
||||||
|
if err != nil {
|
||||||
|
return domainImage.ListQuery{}, domainImage.ErrInvalidQuery
|
||||||
|
}
|
||||||
|
|
||||||
|
query := domainImage.NewListQuery()
|
||||||
|
query.Search = values.Get("q")
|
||||||
|
query.Hash = strings.ToLower(values.Get("hash"))
|
||||||
|
query.Cursor = values.Get("cursor")
|
||||||
|
if values.Has("filter") {
|
||||||
|
query.Filter = domainImage.Filter(values.Get("filter"))
|
||||||
|
}
|
||||||
|
if values.Has("sort") {
|
||||||
|
query.Sort = domainImage.Sort(values.Get("sort"))
|
||||||
|
}
|
||||||
|
if values.Has("limit") {
|
||||||
|
limit, err := strconv.Atoi(values.Get("limit"))
|
||||||
|
if err != nil {
|
||||||
|
return domainImage.ListQuery{}, domainImage.ErrInvalidQuery
|
||||||
|
}
|
||||||
|
query.Limit = limit
|
||||||
|
}
|
||||||
|
return query, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) List(w http.ResponseWriter, r *http.Request) {
|
||||||
|
query, err := parseListQuery(r)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, apperr.MediaQueryErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
page, err := h.ListUseCase.List(query)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, domainImage.ErrInvalidQuery) {
|
||||||
|
http.Error(w, apperr.MediaQueryErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeInternalServerError(w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
items := make([]mediaItemResponse, 0, len(page.Items))
|
||||||
|
for _, item := range page.Items {
|
||||||
|
items = append(items, toResponse(item))
|
||||||
|
}
|
||||||
|
response := listResponse{
|
||||||
|
Items: items,
|
||||||
|
Counts: countsResponse{All: page.Counts.All, Unused: page.Counts.Unused, Duplicates: page.Counts.Duplicates},
|
||||||
|
}
|
||||||
|
if page.NextCursor != "" {
|
||||||
|
response.NextCursor = &page.NextCursor
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, response)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Upload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userId, _ := claims.UserId(r)
|
||||||
|
input, closeFile, ok := upload.ReadImageInput(w, r, userId)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer closeFile()
|
||||||
|
|
||||||
|
created, err := h.CreateUseCase.CreateImage(input)
|
||||||
|
if err != nil {
|
||||||
|
upload.WriteCreateError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.writeItem(w, http.StatusCreated, created)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) writeItem(w http.ResponseWriter, status int, img domainImage.Image) {
|
||||||
|
item, err := h.ListUseCase.Describe(img)
|
||||||
|
if err != nil {
|
||||||
|
writeInternalServerError(w)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, status, toResponse(item))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Rename(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := parseImageId(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var request RenameRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := validator.Validate.Struct(request); err != nil {
|
||||||
|
http.Error(w, apperr.MediaFilenameErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
renamed, err := h.RenameUseCase.Rename(id, request.Filename)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, domainImage.ErrInvalidFilename) {
|
||||||
|
http.Error(w, apperr.MediaFilenameErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeImageError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
h.writeItem(w, http.StatusOK, renamed)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Delete(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := parseImageId(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := h.DeleteUseCase.Delete(id); err != nil {
|
||||||
|
writeImageError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Usage(w http.ResponseWriter, r *http.Request) {
|
||||||
|
id, ok := parseImageId(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
articles, err := h.UsageUseCase.Usage(id)
|
||||||
|
if err != nil {
|
||||||
|
writeImageError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
response := make([]usageResponse, 0, len(articles))
|
||||||
|
for _, a := range articles {
|
||||||
|
response = append(response, usageResponse{ID: a.ID, Title: a.Title, Published: a.IsOnline})
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, response)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Merge(w http.ResponseWriter, r *http.Request) {
|
||||||
|
var request MergeRequest
|
||||||
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||||
|
http.Error(w, apperr.MediaMergeRequestErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := validator.Validate.Struct(request); err != nil {
|
||||||
|
http.Error(w, apperr.MediaMergeRequestErrorMessage, http.StatusBadRequest)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := h.MergeUseCase.Merge(request.KeepID, request.MergeIDs)
|
||||||
|
if err != nil {
|
||||||
|
writeMergeError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, mergeResponse{ArticlesUpdated: result.ArticlesUpdated, Merged: result.Merged})
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeMergeError(w http.ResponseWriter, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domainImage.ErrInvalidMergeRequest):
|
||||||
|
http.Error(w, apperr.MediaMergeRequestErrorMessage, http.StatusBadRequest)
|
||||||
|
case errors.Is(err, domainImage.ErrMergeCopyMissing), errors.Is(err, domainImage.ErrMergeHashMismatch):
|
||||||
|
http.Error(w, apperr.MediaMergeConflictErrorMessage, http.StatusConflict)
|
||||||
|
default:
|
||||||
|
writeImageError(w, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
const cacheControl = "public, max-age=31536000, immutable"
|
const cacheControl = "public, no-cache"
|
||||||
const svgContentSecurityPolicy = "default-src 'none'; style-src 'unsafe-inline'; sandbox"
|
const svgContentSecurityPolicy = "default-src 'none'; style-src 'unsafe-inline'; sandbox"
|
||||||
const fallbackContentType = "application/octet-stream"
|
const fallbackContentType = "application/octet-stream"
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/api/pkg/claims"
|
||||||
|
validator "RenewCMS/api/pkg/validator"
|
||||||
|
domain "RenewCMS/internal/domain/update"
|
||||||
|
"RenewCMS/internal/domain/user"
|
||||||
|
"RenewCMS/internal/infrastructure/useCases"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const restartBodyLimitBytes = 1024
|
||||||
|
|
||||||
|
type Handler struct {
|
||||||
|
GetUpdateStatusUseCase *useCases.GetUpdateStatusUseCase
|
||||||
|
CheckForUpdateUseCase *useCases.CheckForUpdateUseCase
|
||||||
|
StartUpdateDownloadUseCase *useCases.StartUpdateDownloadUseCase
|
||||||
|
RequestRestartUseCase *useCases.RequestRestartUseCase
|
||||||
|
GetUserUseCase *useCases.GetUserUseCase
|
||||||
|
}
|
||||||
|
|
||||||
|
type restartRequest struct {
|
||||||
|
Kind *string `json:"kind" validate:"omitempty,oneof=update restart"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(getStatus *useCases.GetUpdateStatusUseCase, checkForUpdate *useCases.CheckForUpdateUseCase, startDownload *useCases.StartUpdateDownloadUseCase, requestRestart *useCases.RequestRestartUseCase, getUser *useCases.GetUserUseCase) *Handler {
|
||||||
|
return &Handler{
|
||||||
|
GetUpdateStatusUseCase: getStatus,
|
||||||
|
CheckForUpdateUseCase: checkForUpdate,
|
||||||
|
StartUpdateDownloadUseCase: startDownload,
|
||||||
|
RequestRestartUseCase: requestRestart,
|
||||||
|
GetUserUseCase: getUser,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) GetStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
|
isOwner, ok := h.isOwner(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Check(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if _, err := h.CheckForUpdateUseCase.Check(); err != nil {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
isOwner, ok := h.isOwner(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeStatus(w, http.StatusOK, h.GetUpdateStatusUseCase.GetStatus(isOwner))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Download(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
status, err := h.StartUpdateDownloadUseCase.Start()
|
||||||
|
if err != nil {
|
||||||
|
writeDownloadError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeStatus(w, http.StatusAccepted, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) Restart(w http.ResponseWriter, r *http.Request) {
|
||||||
|
kind, ok := decodeRestartKind(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
userId, ok := claims.UserId(r)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
status, err := h.RequestRestartUseCase.Request(userId, kind)
|
||||||
|
if err != nil {
|
||||||
|
writeRestartError(w, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeStatus(w, http.StatusAccepted, status)
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeRestartKind(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||||
|
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, restartBodyLimitBytes))
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
if strings.TrimSpace(string(body)) == "" {
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
var request restartRequest
|
||||||
|
if err := json.Unmarshal(body, &request); err != nil || validator.Validate.Struct(request) != nil {
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
if request.Kind == nil {
|
||||||
|
return "", true
|
||||||
|
}
|
||||||
|
return *request.Kind, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) isOwner(w http.ResponseWriter, r *http.Request) (bool, bool) {
|
||||||
|
userId, ok := claims.UserId(r)
|
||||||
|
if !ok {
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
return false, false
|
||||||
|
}
|
||||||
|
currentUser, err := h.GetUserUseCase.GetUser(userId)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, user.ErrUserNotFound) {
|
||||||
|
http.Error(w, apperr.UnauthorizedErrorMessage, http.StatusUnauthorized)
|
||||||
|
return false, false
|
||||||
|
}
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return false, false
|
||||||
|
}
|
||||||
|
return currentUser.Role == user.RoleOwner, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeDownloadError(w http.ResponseWriter, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrNotPrepared):
|
||||||
|
http.Error(w, apperr.UpdateNotPreparedErrorMessage, http.StatusConflict)
|
||||||
|
case errors.Is(err, domain.ErrJobInProgress), errors.Is(err, domain.ErrRestartPending):
|
||||||
|
http.Error(w, apperr.UpdateAlreadyRunningErrorMessage, http.StatusConflict)
|
||||||
|
case errors.Is(err, domain.ErrNothingToUpdate):
|
||||||
|
http.Error(w, apperr.NothingToUpdateErrorMessage, http.StatusBadRequest)
|
||||||
|
case errors.Is(err, domain.ErrPreflightRefused):
|
||||||
|
http.Error(w, apperr.UpdateRefusedErrorMessage, http.StatusUnprocessableEntity)
|
||||||
|
default:
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeRestartError(w http.ResponseWriter, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, domain.ErrNotPrepared):
|
||||||
|
http.Error(w, apperr.UpdateNotPreparedErrorMessage, http.StatusConflict)
|
||||||
|
case errors.Is(err, domain.ErrJobInProgress), errors.Is(err, domain.ErrRestartPending):
|
||||||
|
http.Error(w, apperr.UpdateAlreadyRunningErrorMessage, http.StatusConflict)
|
||||||
|
case errors.Is(err, domain.ErrRestartKindMismatch):
|
||||||
|
http.Error(w, apperr.UpdateRestartMismatchErrorMessage, http.StatusConflict)
|
||||||
|
default:
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeStatus(w http.ResponseWriter, code int, status domain.UpdateStatus) {
|
||||||
|
body, err := json.Marshal(status)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(code)
|
||||||
|
_, _ = w.Write(body)
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package middleware
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"RenewCMS/api/pkg/apperr"
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/api/pkg/claims"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -14,12 +15,25 @@ type rateLimitWindow struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
func NewRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
||||||
|
return newKeyedRateLimiter(maxAttempts, window, func(r *http.Request) string { return r.RemoteAddr })
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUserRateLimiter(maxAttempts int, window time.Duration) func(http.Handler) http.Handler {
|
||||||
|
return newKeyedRateLimiter(maxAttempts, window, userRateLimitKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
func userRateLimitKey(r *http.Request) string {
|
||||||
|
userId, _ := claims.UserId(r)
|
||||||
|
return strconv.FormatUint(uint64(userId), 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newKeyedRateLimiter(maxAttempts int, window time.Duration, keyOf func(*http.Request) string) func(http.Handler) http.Handler {
|
||||||
var mu sync.Mutex
|
var mu sync.Mutex
|
||||||
windows := make(map[string]*rateLimitWindow)
|
windows := make(map[string]*rateLimitWindow)
|
||||||
|
|
||||||
return func(next http.Handler) http.Handler {
|
return func(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
retryAfter, allowed := recordAttempt(&mu, windows, r.RemoteAddr, maxAttempts, window)
|
retryAfter, allowed := recordAttempt(&mu, windows, keyOf(r), maxAttempts, window)
|
||||||
if !allowed {
|
if !allowed {
|
||||||
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
||||||
http.Error(w, apperr.TooManyRequestsErrorMessage, http.StatusTooManyRequests)
|
http.Error(w, apperr.TooManyRequestsErrorMessage, http.StatusTooManyRequests)
|
||||||
|
|||||||
@@ -25,3 +25,12 @@ const InviteInvalidErrorMessage = "This invite link doesn't work."
|
|||||||
const InviteExpiredErrorMessage = "This invite has expired."
|
const InviteExpiredErrorMessage = "This invite has expired."
|
||||||
const OwnerRequiredErrorMessage = "Only the owner can do this."
|
const OwnerRequiredErrorMessage = "Only the owner can do this."
|
||||||
const UsernameTakenErrorMessage = "That username is taken. Try another."
|
const UsernameTakenErrorMessage = "That username is taken. Try another."
|
||||||
|
const MediaQueryErrorMessage = "The media query is invalid."
|
||||||
|
const MediaFilenameErrorMessage = "Enter a filename."
|
||||||
|
const MediaMergeConflictErrorMessage = "Some of the images to merge changed. Refresh and try again."
|
||||||
|
const MediaMergeRequestErrorMessage = "Choose an image to keep and at least one other image to merge into it."
|
||||||
|
const UpdateNotPreparedErrorMessage = "This server cannot update itself yet."
|
||||||
|
const UpdateAlreadyRunningErrorMessage = "An update is already running or waiting to be installed."
|
||||||
|
const NothingToUpdateErrorMessage = "There is nothing to update."
|
||||||
|
const UpdateRefusedErrorMessage = "This update cannot be downloaded."
|
||||||
|
const UpdateRestartMismatchErrorMessage = "The update state changed. Reload the page and try again."
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package upload
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api/pkg/apperr"
|
||||||
|
"RenewCMS/internal/domain/image"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
const multipartOverheadAllowance = 1 << 20
|
||||||
|
|
||||||
|
const fileField = "file"
|
||||||
|
|
||||||
|
func ReadImageInput(w http.ResponseWriter, r *http.Request, uploadedById uint32) (image.ImageInput, func(), bool) {
|
||||||
|
r.Body = http.MaxBytesReader(w, r.Body, image.MaxImageSize+multipartOverheadAllowance)
|
||||||
|
|
||||||
|
file, header, err := r.FormFile(fileField)
|
||||||
|
if err != nil {
|
||||||
|
var tooLarge *http.MaxBytesError
|
||||||
|
if errors.As(err, &tooLarge) {
|
||||||
|
http.Error(w, image.ErrImageTooLarge.Error(), http.StatusRequestEntityTooLarge)
|
||||||
|
return image.ImageInput{}, nil, false
|
||||||
|
}
|
||||||
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
||||||
|
return image.ImageInput{}, nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
input := image.ImageInput{
|
||||||
|
Content: file,
|
||||||
|
Filename: header.Filename,
|
||||||
|
Size: header.Size,
|
||||||
|
ContentType: header.Header.Get("Content-Type"),
|
||||||
|
UploadedByID: uploadedById,
|
||||||
|
}
|
||||||
|
return input, func() { _ = file.Close() }, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func WriteCreateError(w http.ResponseWriter, err error) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, image.ErrImageTypeNotAllowed):
|
||||||
|
http.Error(w, err.Error(), http.StatusUnsupportedMediaType)
|
||||||
|
case errors.Is(err, image.ErrImageTooLarge):
|
||||||
|
http.Error(w, err.Error(), http.StatusRequestEntityTooLarge)
|
||||||
|
case errors.Is(err, image.ErrImageUnreadable):
|
||||||
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
|
default:
|
||||||
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
-4
@@ -4,14 +4,16 @@ import (
|
|||||||
"RenewCMS/api/handlers/article"
|
"RenewCMS/api/handlers/article"
|
||||||
"RenewCMS/api/handlers/auth"
|
"RenewCMS/api/handlers/auth"
|
||||||
"RenewCMS/api/handlers/frontend"
|
"RenewCMS/api/handlers/frontend"
|
||||||
"RenewCMS/api/handlers/image"
|
"RenewCMS/api/handlers/media"
|
||||||
"RenewCMS/api/handlers/settings"
|
"RenewCMS/api/handlers/settings"
|
||||||
"RenewCMS/api/handlers/staticimages"
|
"RenewCMS/api/handlers/staticimages"
|
||||||
|
"RenewCMS/api/handlers/update"
|
||||||
"RenewCMS/api/handlers/user"
|
"RenewCMS/api/handlers/user"
|
||||||
"RenewCMS/api/middleware"
|
"RenewCMS/api/middleware"
|
||||||
"RenewCMS/internal/infrastructure/config"
|
"RenewCMS/internal/infrastructure/config"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/MadAppGang/httplog"
|
"github.com/MadAppGang/httplog"
|
||||||
"github.com/go-chi/chi/v5"
|
"github.com/go-chi/chi/v5"
|
||||||
@@ -35,7 +37,6 @@ func NewArticleRouter(container *UseCases) http.Handler {
|
|||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
|
||||||
articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.GetUserUseCase)
|
articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase, container.UpdateArticleUseCase, container.GetUserUseCase)
|
||||||
imageHandler := image.NewHandler(container.CreateImageUseCase, container.GetArticleUseCase, container.UpdateArticleUseCase, container.DeleteImageUseCase)
|
|
||||||
|
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
r.Get("/", articleHandler.ListArticles)
|
r.Get("/", articleHandler.ListArticles)
|
||||||
@@ -50,8 +51,6 @@ func NewArticleRouter(container *UseCases) http.Handler {
|
|||||||
r.Patch("/{id}", articleHandler.UpdateArticleBody)
|
r.Patch("/{id}", articleHandler.UpdateArticleBody)
|
||||||
r.Patch("/{id}/publish", articleHandler.PublishArticle)
|
r.Patch("/{id}/publish", articleHandler.PublishArticle)
|
||||||
r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle)
|
r.Patch("/{id}/unpublish", articleHandler.UnpublishArticle)
|
||||||
r.Post("/{id}/image", imageHandler.PostImage)
|
|
||||||
r.Delete("/{id}/image/{imageId}", imageHandler.DeleteImage)
|
|
||||||
})
|
})
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
@@ -132,6 +131,58 @@ func NewSettingsRouter(container *UseCases) http.Handler {
|
|||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
updateCheckMaxAttempts = 5
|
||||||
|
updateCheckWindow = time.Minute
|
||||||
|
updateDownloadMaxAttempts = 5
|
||||||
|
updateDownloadWindow = time.Minute
|
||||||
|
)
|
||||||
|
|
||||||
|
func NewSystemRouter(container *UseCases) http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
|
||||||
|
updateHandler := update.NewHandler(container.GetUpdateStatusUseCase, container.CheckForUpdateUseCase, container.StartUpdateDownloadUseCase, container.RequestRestartUseCase, container.GetUserUseCase)
|
||||||
|
|
||||||
|
r.Use(jwtauth.Verifier(container.Token))
|
||||||
|
r.Use(jwtauth.Authenticator(container.Token))
|
||||||
|
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||||
|
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||||
|
r.Get("/update", updateHandler.GetStatus)
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||||
|
r.Use(middleware.NewUserRateLimiter(updateCheckMaxAttempts, updateCheckWindow))
|
||||||
|
r.Post("/update/check", updateHandler.Check)
|
||||||
|
})
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||||
|
r.Use(middleware.NewUserRateLimiter(updateDownloadMaxAttempts, updateDownloadWindow))
|
||||||
|
r.Post("/update/download", updateHandler.Download)
|
||||||
|
})
|
||||||
|
r.Group(func(r chi.Router) {
|
||||||
|
r.Use(middleware.RequireOwner(container.GetUserUseCase))
|
||||||
|
r.Post("/update/restart", updateHandler.Restart)
|
||||||
|
})
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMediaRouter(container *UseCases) http.Handler {
|
||||||
|
r := chi.NewRouter()
|
||||||
|
|
||||||
|
mediaHandler := media.NewHandler(container.CreateImageUseCase, container.ListMediaUseCase, container.RenameMediaUseCase, container.DeleteMediaUseCase, container.MergeMediaUseCase, container.GetMediaUsageUseCase)
|
||||||
|
|
||||||
|
r.Use(jwtauth.Verifier(container.Token))
|
||||||
|
r.Use(jwtauth.Authenticator(container.Token))
|
||||||
|
r.Use(middleware.RequireCurrentToken(container.GetUserUseCase))
|
||||||
|
r.Use(middleware.RequireVerifiedUser(container.GetUserUseCase))
|
||||||
|
r.Get("/", mediaHandler.List)
|
||||||
|
r.Post("/", mediaHandler.Upload)
|
||||||
|
r.Post("/merge", mediaHandler.Merge)
|
||||||
|
r.Patch("/{id}", mediaHandler.Rename)
|
||||||
|
r.Delete("/{id}", mediaHandler.Delete)
|
||||||
|
r.Get("/{id}/usage", mediaHandler.Usage)
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
||||||
r := chi.NewRouter()
|
r := chi.NewRouter()
|
||||||
|
|
||||||
@@ -146,6 +197,8 @@ func InitBackendRoutes(container *UseCases, settings config.Settings) *chi.Mux {
|
|||||||
})
|
})
|
||||||
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
r.Mount("/user", NewUserRouter(container, settings.AuthRateLimit, settings.TrustedProxies))
|
||||||
r.Mount("/settings", NewSettingsRouter(container))
|
r.Mount("/settings", NewSettingsRouter(container))
|
||||||
|
r.Mount("/media", NewMediaRouter(container))
|
||||||
|
r.Mount("/system", NewSystemRouter(container))
|
||||||
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
|
r.Mount("/auth", NewAuthRouter(container, settings.IsProduction(), settings.AuthRateLimit, settings.TrustedProxies))
|
||||||
|
|
||||||
return r
|
return r
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/internal/infrastructure/update/releasesign"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
os.Exit(releasesign.Run(os.Args[1:], os.Stdout, os.Stderr))
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"RenewCMS/api"
|
||||||
|
"RenewCMS/internal/domain/update"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
enableCommand = "enable-browser-updates"
|
||||||
|
disableCommand = "disable-browser-updates"
|
||||||
|
applyCommand = "apply-update"
|
||||||
|
|
||||||
|
exitOK = 0
|
||||||
|
exitError = 1
|
||||||
|
exitUsage = 2
|
||||||
|
|
||||||
|
usageText = "usage: renewcms [--version]\n" +
|
||||||
|
" renewcms enable-browser-updates [--service NAME] [--binary PATH] [--data-dir DIR] [--port PORT]\n" +
|
||||||
|
" renewcms disable-browser-updates [--service NAME] [--data-dir DIR]\n" +
|
||||||
|
" renewcms apply-update --binary PATH --data-dir DIR [--service NAME] [--port PORT]"
|
||||||
|
|
||||||
|
applyNeedsFlagsMessage = "apply-update needs --binary and --data-dir."
|
||||||
|
)
|
||||||
|
|
||||||
|
func runCommand(args []string, stdout io.Writer, stderr io.Writer) int {
|
||||||
|
name, rest := args[0], args[1:]
|
||||||
|
switch name {
|
||||||
|
case enableCommand:
|
||||||
|
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
|
||||||
|
message, err := api.InitBrowserUpdateCommands().Enable.Enable(options)
|
||||||
|
return printOutcome(stdout, stderr, message, err)
|
||||||
|
})
|
||||||
|
case disableCommand:
|
||||||
|
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
|
||||||
|
message, err := api.InitBrowserUpdateCommands().Disable.Disable(options)
|
||||||
|
return printOutcome(stdout, stderr, message, err)
|
||||||
|
})
|
||||||
|
case applyCommand:
|
||||||
|
return withOptions(name, rest, stderr, func(options update.InstallOptions) int {
|
||||||
|
return apply(options, stderr)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stderr, usageText)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
|
||||||
|
func withOptions(name string, args []string, stderr io.Writer, run func(update.InstallOptions) int) int {
|
||||||
|
flags := flag.NewFlagSet(name, flag.ContinueOnError)
|
||||||
|
flags.SetOutput(stderr)
|
||||||
|
var options update.InstallOptions
|
||||||
|
flags.StringVar(&options.Service, "service", "", "systemd service name of RenewCMS")
|
||||||
|
flags.StringVar(&options.Binary, "binary", "", "path of the RenewCMS binary")
|
||||||
|
flags.StringVar(&options.DataDir, "data-dir", "", "directory that holds DB_FILE")
|
||||||
|
flags.StringVar(&options.Port, "port", "", "port RenewCMS listens on")
|
||||||
|
if err := flags.Parse(args); err != nil {
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
return run(options)
|
||||||
|
}
|
||||||
|
|
||||||
|
func printOutcome(stdout io.Writer, stderr io.Writer, message string, err error) int {
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(stderr, err)
|
||||||
|
return exitError
|
||||||
|
}
|
||||||
|
fmt.Fprintln(stdout, message)
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
|
|
||||||
|
func apply(options update.InstallOptions, stderr io.Writer) int {
|
||||||
|
if options.Binary == "" || options.DataDir == "" {
|
||||||
|
fmt.Fprintln(stderr, applyNeedsFlagsMessage)
|
||||||
|
return exitUsage
|
||||||
|
}
|
||||||
|
if options.Service == "" {
|
||||||
|
options.Service = update.DefaultService
|
||||||
|
}
|
||||||
|
if options.Port == "" {
|
||||||
|
options.Port = update.DefaultPort
|
||||||
|
}
|
||||||
|
if err := api.InitApplyUpdateCommand(options).Apply(); err != nil {
|
||||||
|
log.Printf("apply-update failed: %v", err)
|
||||||
|
return exitError
|
||||||
|
}
|
||||||
|
return exitOK
|
||||||
|
}
|
||||||
+24
-5
@@ -8,6 +8,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
@@ -47,9 +48,19 @@ var envDefaults = map[string]string{
|
|||||||
"AUTH_RATE_LIMIT_MAX_ATTEMPTS": "5",
|
"AUTH_RATE_LIMIT_MAX_ATTEMPTS": "5",
|
||||||
"AUTH_RATE_LIMIT_WINDOW_SECONDS": "60",
|
"AUTH_RATE_LIMIT_WINDOW_SECONDS": "60",
|
||||||
"TRUSTED_PROXIES": "",
|
"TRUSTED_PROXIES": "",
|
||||||
|
"UPDATE_FEED_URL": "https://git.floriansylvain.fr",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const versionFlag = "--version"
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
if len(os.Args) == 2 && os.Args[1] == versionFlag {
|
||||||
|
fmt.Println(version)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
os.Exit(runCommand(os.Args[1:], os.Stdout, os.Stderr))
|
||||||
|
}
|
||||||
if err := run(); err != nil {
|
if err := run(); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -69,7 +80,7 @@ func run() error {
|
|||||||
validator.InitValidator()
|
validator.InitValidator()
|
||||||
|
|
||||||
server := newServer(api.InitRoutes(container, settings), settings)
|
server := newServer(api.InitRoutes(container, settings), settings)
|
||||||
return serveUntilStopped(server, settings)
|
return serveUntilStopped(server, settings, container.RecordRunningInfoUseCase.Record)
|
||||||
}
|
}
|
||||||
|
|
||||||
func initEnvVariables() {
|
func initEnvVariables() {
|
||||||
@@ -120,12 +131,12 @@ func newServer(handler http.Handler, settings config.Settings) *http.Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func serveUntilStopped(server *http.Server, settings config.Settings) error {
|
func serveUntilStopped(server *http.Server, settings config.Settings, recordRunning func() error) error {
|
||||||
stopSignal, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
stopSignal, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
defer stop()
|
defer stop()
|
||||||
|
|
||||||
serverErr := make(chan error, 1)
|
serverErr := make(chan error, 1)
|
||||||
go listen(server, serverErr, settings)
|
go listen(server, serverErr, settings, recordRunning)
|
||||||
|
|
||||||
select {
|
select {
|
||||||
case err := <-serverErr:
|
case err := <-serverErr:
|
||||||
@@ -135,9 +146,17 @@ func serveUntilStopped(server *http.Server, settings config.Settings) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func listen(server *http.Server, serverErr chan<- error, settings config.Settings) {
|
func listen(server *http.Server, serverErr chan<- error, settings config.Settings, recordRunning func() error) {
|
||||||
|
listener, err := net.Listen("tcp", server.Addr)
|
||||||
|
if err != nil {
|
||||||
|
serverErr <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := recordRunning(); err != nil {
|
||||||
|
log.Printf("WARNING: could not write the running-version file: %v", err)
|
||||||
|
}
|
||||||
log.Printf("RenewCMS %s (%s) listening on %s, public URL %s", version, settings.Environment, server.Addr, settings.PublicURL)
|
log.Printf("RenewCMS %s (%s) listening on %s, public URL %s", version, settings.Environment, server.Addr, settings.PublicURL)
|
||||||
err := server.ListenAndServe()
|
err = server.Serve(listener)
|
||||||
if errors.Is(err, http.ErrServerClosed) {
|
if errors.Is(err, http.ErrServerClosed) {
|
||||||
err = nil
|
err = nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,8 +26,14 @@ Nothing under `internal/` imports `api/`.
|
|||||||
| Package | Role |
|
| Package | Role |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `api/handlers/user` | Authenticated user endpoints: profile update (`UpdateMe`) and the users list with invitations (`CreateInvite`, `ListUsers`). |
|
| `api/handlers/user` | Authenticated user endpoints: profile update (`UpdateMe`) and the users list with invitations (`CreateInvite`, `ListUsers`). |
|
||||||
|
| `api/handlers/media` | The media library under `/v1/media` (list, upload, rename, delete, merge, usage). Images belong to the library, not to an article: deleting an article never deletes an image, and an image's "used in" is read from article bodies each time. |
|
||||||
|
| `api/pkg/upload` | Multipart `file` reading and the mapping of upload errors (415, 413, 400) shared by both upload routes. |
|
||||||
| `api/pkg/publicuser` | `PublicUser`, the JSON shape of a user with no password, codes or token version. `publicuser.New` converts a domain `user.User`, so handlers never serialise the domain struct directly. |
|
| `api/pkg/publicuser` | `PublicUser`, the JSON shape of a user with no password, codes or token version. `publicuser.New` converts a domain `user.User`, so handlers never serialise the domain struct directly. |
|
||||||
|
|
||||||
|
### Image metadata backfill
|
||||||
|
|
||||||
|
At boot, `BackfillImageMetadata` fills `filename`, `size`, `content_type`, `width`, `height` and `sha256` for image rows that lack them, reading the files in `UPLOAD_DIR`. It is idempotent, and a row whose file is missing or unreadable is left as it is without stopping the boot. The old `article_id` column and the `article_images` table are kept and never written.
|
||||||
|
|
||||||
## Frontend ↔ backend
|
## Frontend ↔ backend
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -30,9 +30,12 @@ Copy [`.env.example`](../.env.example) to `.env` to get started. When a required
|
|||||||
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. |
|
| `AUTH_RATE_LIMIT_MAX_ATTEMPTS` | `5` | Maximum number of requests a single client IP may send to `POST /v1/auth/login`, `POST /v1/auth/password-reset` or the invite-accept pair (`GET /v1/auth/invite` and `POST /v1/auth/invite/accept`, sharing one counter) within the window, tracked independently per route. |
|
||||||
| `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. |
|
| `AUTH_RATE_LIMIT_WINDOW_SECONDS` | `60` | Length, in seconds, of the fixed rate-limit window for the routes above. |
|
||||||
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). |
|
| `TRUSTED_PROXIES` | *(empty)* | Semicolon-separated list of exact IP addresses (no CIDR) of reverse proxies allowed to supply the client IP via `X-Real-IP` for the rate limiting of the routes above. When a request's connection address is not in this list, any `X-Real-IP` or `X-Forwarded-For` header it sends is ignored and the connection address is used instead. See [deployment.md](deployment.md). |
|
||||||
|
| `UPDATE_FEED_URL` | `https://git.floriansylvain.fr` | Base URL of the Gitea server that publishes RenewCMS releases. The Settings page asks `{UPDATE_FEED_URL}/api/v1/repos/fsylvain/RenewCMS/releases` when the owner checks for updates. The last result is kept in `update-status.json`, next to `DB_FILE`. |
|
||||||
|
|
||||||
Relative paths are resolved against the process's working directory. In production, use absolute paths (see [deployment.md](deployment.md)).
|
Relative paths are resolved against the process's working directory. In production, use absolute paths (see [deployment.md](deployment.md)).
|
||||||
|
|
||||||
|
For example, `WorkingDirectory=/var/lib/renewcms` with `DB_FILE=./data/renewcms.db` puts the database in `/var/lib/renewcms/data`. Browser-update `--data-dir` must name that directory, because the app reads helper status and update records beside the database. It is not necessarily `WorkingDirectory` or `ReadWritePaths`. Do not change an existing `DB_FILE` merely to match the helper: that could open a different, empty database. See [browser-update setup](deployment.md#browser-updates).
|
||||||
|
|
||||||
## Adding a variable
|
## Adding a variable
|
||||||
|
|
||||||
1. Read it in the code where it is needed (infrastructure or `api/`, never `internal/domain`).
|
1. Read it in the code where it is needed (infrastructure or `api/`, never `internal/domain`).
|
||||||
|
|||||||
+139
-1
@@ -8,7 +8,7 @@ RenewCMS ships as **one self-contained executable**. It serves:
|
|||||||
| `/healthz` | Liveness check, returns `200 ok` |
|
| `/healthz` | Liveness check, returns `200 ok` |
|
||||||
| `/*` | The Vue SPA (embedded), with fallback to `index.html` for client-side routes |
|
| `/*` | The Vue SPA (embedded), with fallback to `index.html` for client-side routes |
|
||||||
|
|
||||||
Its only runtime state is the SQLite database (`DB_FILE`) and the uploads directory (`UPLOAD_DIR`). Nothing else needs to be installed on the server.
|
Runtime state includes the SQLite database (`DB_FILE`), uploads (`UPLOAD_DIR`), and update records, staged binaries and backups beside the database. Running a release binary needs no Go, Bun or Node installation. Browser updates additionally require Linux with systemd and the helper setup below.
|
||||||
|
|
||||||
## 1. Build
|
## 1. Build
|
||||||
|
|
||||||
@@ -19,8 +19,146 @@ task build # this OS/arch → bin/renewcms[.exe]
|
|||||||
task release # all targets → bin/renewcms_<version>_<os>_<arch>[.exe]
|
task release # all targets → bin/renewcms_<version>_<os>_<arch>[.exe]
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`task release` also signs the release: it writes `bin/checksums.txt` (SHA-256 of the six binaries) and signs it into `bin/checksums.txt.sig` with an Ed25519 key. It refuses to start, before building anything, unless `RELEASE_SIGNING_KEY` points to the private key file and that key matches the public key committed as `internal/infrastructure/update/release.pub`. The one-time setup is below.
|
||||||
|
|
||||||
The frontend is built once and embedded into every binary. The binaries are static (`CGO_ENABLED=0`), so a Linux build runs on any distribution. The version comes from `git describe`: tag a release (`git tag v1.2.0`) before building, and the binary logs its version at startup.
|
The frontend is built once and embedded into every binary. The binaries are static (`CGO_ENABLED=0`), so a Linux build runs on any distribution. The version comes from `git describe`: tag a release (`git tag v1.2.0`) before building, and the binary logs its version at startup.
|
||||||
|
|
||||||
|
### Release signing key (maintainers, once)
|
||||||
|
|
||||||
|
1. Run `task release:keygen -- <path>` with a path outside the repository (for example `~/.renewcms/release.key`). The private key is written there and never leaves your machine; keygen refuses a path inside the work tree.
|
||||||
|
2. Commit the printed public key as `internal/infrastructure/update/release.pub`. A placeholder key (32 zero bytes) prevents signing. Official releases already embed the project's public key; this setup is for release maintainers, not site operators. Never copy the private signing key to a CMS server.
|
||||||
|
3. Export `RELEASE_SIGNING_KEY=<path to the private key>` before every `task release`.
|
||||||
|
|
||||||
|
To check a download by hand: `go run ./cmd/releasesign verify checksums.txt`, with `checksums.txt.sig` next to it, then compare the binary's hash with the matching line of `checksums.txt`.
|
||||||
|
|
||||||
|
### Update checks
|
||||||
|
|
||||||
|
The owner's Settings page asks the release feed for the newest release (see `UPDATE_FEED_URL` in [configuration.md](configuration.md)) and keeps the last result in `update-status.json`, next to `DB_FILE`. Back it up with the rest of the data directory if you like; it is rebuilt by the next check when missing. The Settings page reports a newer version. To install it from the browser, set up [Browser updates](#browser-updates) once on the server.
|
||||||
|
|
||||||
|
### Update downloads
|
||||||
|
|
||||||
|
Once the restart helper is installed (it writes `update-helper.json` next to `DB_FILE`), the owner's Update button downloads the new binary, `checksums.txt` and `checksums.txt.sig` from the release feed host over https only, checks the ed25519 signature and the SHA-256, runs the staged binary with `--version`, copies the database into `backups/` (the last 3 copies are kept) and stages everything under `updates/<tag>/`, all next to `DB_FILE`. The job record is `update-job.json`. Nothing running is replaced and the site is not restarted by the download: the owner's Restart button does that, as described in [Browser updates](#browser-updates). `renewcms --version` prints the build version and exits.
|
||||||
|
|
||||||
|
### Browser updates
|
||||||
|
|
||||||
|
The owner's Restart button installs a downloaded update, or just restarts the site, without touching the server by hand. The app itself stays unprivileged: the systemd unit below keeps `ProtectSystem=strict` and only the data directory (the directory that holds `DB_FILE`) is writable. The only privileged code is a small helper, the same binary started as `renewcms apply-update` by a systemd service that runs as root.
|
||||||
|
|
||||||
|
First install v2.6.0-beta or newer manually, back up the database, uploads and current binary, and confirm the app runs as an unprivileged service user. The binary and its parent directory should be controlled by root. Owners can start updates and restarts; admins have read-only update status.
|
||||||
|
|
||||||
|
#### Find the actual database directory
|
||||||
|
|
||||||
|
The helper's `--data-dir` must be the directory containing `DB_FILE`. Inspect the relevant settings without printing the configuration's secrets:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo systemctl show renewcms -p User -p WorkingDirectory
|
||||||
|
sudo grep '^DB_FILE=' /etc/renewcms/renewcms.env
|
||||||
|
```
|
||||||
|
|
||||||
|
| WorkingDirectory | DB_FILE | Correct --data-dir |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `/var/lib/renewcms` | `/var/lib/renewcms/renewcms.db` | `/var/lib/renewcms` |
|
||||||
|
| `/var/lib/renewcms` | `./data/renewcms.db` | `/var/lib/renewcms/data` |
|
||||||
|
|
||||||
|
Leave an existing `DB_FILE` unchanged: changing it can open a different, empty database. Configure the helper to match the existing database instead.
|
||||||
|
|
||||||
|
#### Enable the helper
|
||||||
|
|
||||||
|
For this guide's absolute database path and port 8080, run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo /opt/renewcms/renewcms enable-browser-updates \
|
||||||
|
--service renewcms \
|
||||||
|
--binary /opt/renewcms/renewcms \
|
||||||
|
--data-dir /var/lib/renewcms \
|
||||||
|
--port 8080
|
||||||
|
```
|
||||||
|
|
||||||
|
Replace these flags with your actual paths and port. For the relative database example above and port 8788, use `--data-dir /var/lib/renewcms/data --port 8788`. The absolute executable path works even when `/opt/renewcms` is absent from sudo's PATH.
|
||||||
|
|
||||||
|
Without explicit flags, discovery reads `/etc/systemd/system/renewcms.service` and takes its first `ReadWritePaths` entry as the data directory. It does not resolve `DB_FILE`, so explicit flags are necessary when these directories differ or the unit lives elsewhere. The port comes from `--port`, else `PORT` in the unit's `EnvironmentFile`, else 8080. The helper polls `/healthz` on `127.0.0.1` at that port. It then:
|
||||||
|
|
||||||
|
- writes `renewcms-update.path` and `renewcms-update.service` next to your other units in `/etc/systemd/system` (no secret and no environment value goes into them);
|
||||||
|
- runs `systemctl daemon-reload` and enables and starts the path unit;
|
||||||
|
- writes `update-helper.json` in the data directory last, so the Settings page only offers Update and Restart once everything else worked.
|
||||||
|
|
||||||
|
Running it again rewrites the units and the status file to the current values. If a step fails, the units it wrote are removed again and `update-helper.json` is not written.
|
||||||
|
|
||||||
|
#### Verify setup and test a plain restart
|
||||||
|
|
||||||
|
For the layout above, run these checks, substituting your service user and database directory if different:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl is-active renewcms-update.path
|
||||||
|
systemctl is-enabled renewcms-update.path
|
||||||
|
sudo systemctl cat renewcms-update.service
|
||||||
|
sudo -u renewcms cat /var/lib/renewcms/update-helper.json
|
||||||
|
```
|
||||||
|
|
||||||
|
Expect `active`, `enabled`, an `ExecStart` with the correct paths and port, and readable JSON. Reload Settings as owner. With no update waiting, Restart should appear. Press it, confirm the plain restart dialog, and expect the overlay followed by the site returning and a “Site restarted” message.
|
||||||
|
|
||||||
|
Then run:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
systemctl is-active renewcms
|
||||||
|
sudo cat /var/lib/renewcms/update-result.json
|
||||||
|
sudo cat /var/lib/renewcms/update-running.json
|
||||||
|
sudo journalctl -u renewcms-update.service -n 30 --no-pager
|
||||||
|
curl --retry 5 --retry-connrefused --retry-delay 2 -fsS http://127.0.0.1:8080/healthz
|
||||||
|
```
|
||||||
|
|
||||||
|
Expect an active app service, result `kind: restart` with `outcome: succeeded`, the installed version and a new process in `update-running.json`, and health response `ok`. Check `/healthz` through your public HTTPS hostname too. A brief connection refusal during startup can be transient. The oneshot helper normally becomes inactive after success; the path unit stays active.
|
||||||
|
|
||||||
|
#### Install a future update
|
||||||
|
|
||||||
|
When a newer signed release exists, check for updates in Settings, read its notes and click Update. The site stays online while the files are downloaded, verified and backed up. Wait for Ready to install, then click Restart and confirm installation. Afterwards, check the version in Settings, public health, the helper journal and `update-result.json`: expect `kind: update` and `outcome: succeeded`.
|
||||||
|
|
||||||
|
On the latest release you can test only a plain restart. Test installation, forced rollback and hostile-file cases on an isolated Linux/systemd machine with its own data and service. The helper unit names are fixed, so setting up another instance on the same machine replaces that machine's existing helper configuration.
|
||||||
|
|
||||||
|
#### Troubleshooting
|
||||||
|
|
||||||
|
- **Restart is missing:** reload Settings, confirm you are owner, and inspect `GET /v1/system/update` in the browser's Network panel. For an idle owner, `can_apply: false` means the app did not detect the helper. Check that `update-helper.json` is beside the actual database and readable by the service user.
|
||||||
|
- **Wrong helper directory:** disable the helper with the old `--data-dir`, then enable it with the correct directory and port. Do not change `DB_FILE` to compensate.
|
||||||
|
- **Overlay does not clear:** inspect the helper journal, `update-result.json` and `update-running.json` in the actual database directory. Check localhost health on the configured port, then public health through the proxy. Do not cache `/healthz` at the proxy.
|
||||||
|
- **Old binary panics on `--version`:** older releases may interpret it as normal startup and require server environment variables. v2.6.0-beta and newer print their version without loading configuration. A separately launched process failing this way does not stop the systemd service.
|
||||||
|
- **Download or verification fails:** inspect the app journal. All assets and redirects must use HTTPS on the configured feed host. The release must include the six binaries, `checksums.txt` and `checksums.txt.sig`.
|
||||||
|
- **Update rolls back:** check the previous version and helper journal. Automatic rollback restores the binary, not the database; schema changes still require a recovery plan.
|
||||||
|
|
||||||
|
#### Disable the helper
|
||||||
|
|
||||||
|
Use the same database directory you supplied when enabling it:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo /opt/renewcms/renewcms disable-browser-updates \
|
||||||
|
--service renewcms \
|
||||||
|
--data-dir /var/lib/renewcms
|
||||||
|
```
|
||||||
|
|
||||||
|
This stops and disables the path unit, removes both unit files and `update-helper.json`, and runs `systemctl daemon-reload`. The restart request, result, staged files and backups stay. `can_apply` becomes false: Settings shows “Not prepared” when an update is available, or “You're up to date” without Restart otherwise.
|
||||||
|
|
||||||
|
How it works: pressing Restart makes the app write `update-restart-request.json` in the data directory. The path unit notices it and starts the helper, which deletes the request, checks the staged files again, installs the update, restarts the service and waits up to 60 seconds for the site to answer `/healthz` and for the new process to write `update-running.json`. The helper writes its outcome to `update-result.json`; the Settings page reads it. The technical reason of a failure goes to the journal only (`journalctl -u renewcms-update`).
|
||||||
|
|
||||||
|
Files in the data directory:
|
||||||
|
|
||||||
|
| File | Written by | What |
|
||||||
|
|------|------------|------|
|
||||||
|
| `update-restart-request.json` | the app | The request: `kind` (`update` or `restart`), `tag` (updates only), `requested_at`, `requested_by`. The helper deletes it first. |
|
||||||
|
| `update-result.json` | the helper | The outcome: `running`, `succeeded`, `rolled_back` or `failed`, with `kind`, `tag`, `from_version`, `started_at`, `finished_at`. It stays until the next download or restart. |
|
||||||
|
| `update-helper.json` | `enable-browser-updates` | Marks browser updates as set up (`version`, `service`, `binary`, `data_dir`, `installed_at`). |
|
||||||
|
| `update-running.json` | the server, at every start | `version`, `pid` and `started_at` of the running process. The helper uses it to tell a new process from an old one. |
|
||||||
|
|
||||||
|
What is supported and what is not:
|
||||||
|
|
||||||
|
- Linux with systemd only. Not Windows, macOS, Docker or other init systems: there the command refuses with a clear message and the Settings page keeps showing "Not prepared".
|
||||||
|
- Before the swap the helper copies the staged files into a private temp directory, checks the signature and the SHA-256 on that copy and installs the copy. It refuses symbolic links under `updates/` and on the request file.
|
||||||
|
- The previous binary is kept as `<name>.previous` next to the binary, and the update download keeps a database backup in `backups/`.
|
||||||
|
- If the new version does not come up within 60 seconds, the helper puts `<name>.previous` back, restarts the service and records `rolled_back`. If even that fails the result is `failed` and the journal says so loudly.
|
||||||
|
- A plain restart (no update waiting) restarts the service the same way and records `succeeded` or `failed`; no binary is replaced.
|
||||||
|
- Only the owner can press Restart. The site is unavailable for about 10 seconds.
|
||||||
|
|
||||||
|
#### Verification status
|
||||||
|
|
||||||
|
A real v2.6.0-beta plain browser restart was confirmed on Linux/systemd on 2026-10-02: the path unit triggered the helper, a new server process started, the result was `succeeded`, and public health returned `ok`. Real signed installation, forced rollback and adversarial filesystem checks remain unverified. The manual cases are listed in [the restart QA procedure](../features/updates_restart_helper.qa.md).
|
||||||
|
|
||||||
## 2. Lay out the server
|
## 2. Lay out the server
|
||||||
|
|
||||||
The following is a suggested layout for Linux:
|
The following is a suggested layout for Linux:
|
||||||
|
|||||||
@@ -25,19 +25,22 @@ The visual spec of record for the back-office SPA and the transactional emails,
|
|||||||
| [Forgot password](screens/forgot-password.md) | `/register/reset/request` | 6 | `source/RenewCMS Screens Auth.dc.html` |
|
| [Forgot password](screens/forgot-password.md) | `/register/reset/request` | 6 | `source/RenewCMS Screens Auth.dc.html` |
|
||||||
| [Reset password](screens/reset-password.md) | `/register/reset/validate?c=CODE&email=EMAIL` | 7 | `source/RenewCMS Screens Auth.dc.html` |
|
| [Reset password](screens/reset-password.md) | `/register/reset/validate?c=CODE&email=EMAIL` | 7 | `source/RenewCMS Screens Auth.dc.html` |
|
||||||
| [Boot](screens/boot.md) | `any route, first load` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Boot](screens/boot.md) | `any route, first load` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Home](screens/home.md) | `/home` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Home](screens/home.md) | `/home` | 6 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Articles](screens/articles.md) | `/article` | 14 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Articles](screens/articles.md) | `/article` | 14 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [New article](screens/new-article.md) | `modal from anywhere · /article/new` | 5 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [New article](screens/new-article.md) | `modal from anywhere · /article/new` | 5 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Editor](screens/editor.md) | `/article/:id/edit` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Editor](screens/editor.md) | `/article/:id/edit` | 22 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
|
| [Media](screens/media.md) | `/media` | 41 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
|
| [Media picker](screens/media-picker.md) | `/article/:id/edit` (dialog) | 13 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Integration](screens/integration.md) | `/integration` | 2 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Users](screens/users.md) | `/users` | 17 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Users](screens/users.md) | `/users` | 17 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Settings](screens/settings.md) | `/settings` | 1 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Settings](screens/settings.md) | `/settings` | 25 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Profile](screens/profile.md) | `/profile` | 13 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Profile](screens/profile.md) | `/profile` | 13 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
| [Accept invite](screens/accept-invite.md) | `/invite/accept?c=CODE` | 9 | `source/RenewCMS Screens Auth.dc.html` |
|
| [Accept invite](screens/accept-invite.md) | `/invite/accept?c=CODE` | 9 | `source/RenewCMS Screens Auth.dc.html` |
|
||||||
| [Global](screens/global.md) | `any route` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
|
| [Global](screens/global.md) | `any route` | 4 | `source/RenewCMS Screens Back-office.dc.html` |
|
||||||
|
|
||||||
## Other boards
|
## Other boards
|
||||||
|
|
||||||
|
- `source/MediaFrame.dc.html`: the frame that draws the Media and Media picker states (the Back-office board imports it). Like `AppFrame.dc.html`, it holds the exact values.
|
||||||
- `source/RenewCMS Prototype.dc.html`: the clickable flows (first run, edit and publish, password reset, delete, session expiry mid-edit).
|
- `source/RenewCMS Prototype.dc.html`: the clickable flows (first run, edit and publish, password reset, delete, session expiry mid-edit).
|
||||||
- `source/RenewCMS Handoff.dc.html`: the handoff page the first markdown here was generated from. It predates the Users and Profile screens and the invitation email, so it does not list them. Those are written by hand from the Back-office board, `AppFrame.dc.html`, the Prototype and `emails/invitation.html`.
|
- `source/RenewCMS Handoff.dc.html`: the handoff page the first markdown here was generated from. It predates the Users and Profile screens and the invitation email, so it does not list them. Those are written by hand from the Back-office board, `AppFrame.dc.html`, the Prototype and `emails/invitation.html`.
|
||||||
- `source/RenewCMS Components Product.dc.html`: not regenerated for the new screens either. The matching component changes are in `components.md`, under "Added with the Users and Profile screens" and "Added with roles, invite actions and Settings".
|
- `source/RenewCMS Components Product.dc.html`: not regenerated for the new screens either. The matching component changes are in `components.md`, under "Added with the Users and Profile screens" and "Added with roles, invite actions and Settings".
|
||||||
|
|||||||
@@ -764,3 +764,38 @@ Cancel goes through `ConfirmDialog` with `tone: 'danger'`: title "Cancel this in
|
|||||||
### SettingsPage
|
### SettingsPage
|
||||||
|
|
||||||
A page header (title "Settings", subtitle "Workspace information."), then one card holding a "Version" row. See [screens/settings.md](screens/settings.md).
|
A page header (title "Settings", subtitle "Workspace information."), then one card holding a "Version" row. See [screens/settings.md](screens/settings.md).
|
||||||
|
|
||||||
|
## Added with Media
|
||||||
|
|
||||||
|
Exact values live in `source/MediaFrame.dc.html`. Copy and states are in [media](screens/media.md) and [media-picker](screens/media-picker.md).
|
||||||
|
|
||||||
|
| Component | Nuxt UI base | Props | Emits | Used in |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| MediaToolbar | UTabs, UInput, USelectMenu, UButtonGroup | tab, q, sort, view, counts | update:tab, update:q, update:sort, update:view | Media |
|
||||||
|
| MediaGrid | custom (buttons in a grid) | items, selected: Set, loading | open(id), toggle(id) | Media |
|
||||||
|
| MediaTable, MediaCardList | UTable, custom list | same as MediaGrid | same as MediaGrid | Media (md and up, below md) |
|
||||||
|
| MediaBulkBar | custom, UButton | count | delete, clear | Media |
|
||||||
|
| MediaDetailPanel | USlideover | id | close, rename, delete, copy-url, review-duplicates | Media |
|
||||||
|
| MediaUploadPanel | UProgress, UButton | rows | use-existing(row), upload-anyway(row), retry(row), cancel, dismiss | Media |
|
||||||
|
| DuplicateGroups | custom cards | groups | merge(group, keepId) | Media |
|
||||||
|
| MediaThumb | custom | item, size | none | Media, picker |
|
||||||
|
| MediaBadge | UBadge | kind: 'unused'\|'duplicate'\|'used'\|'online'\|'draft', label | none | Media, picker |
|
||||||
|
| RenameDialog, MergeDialog, DeleteMediaDialog | ConfirmDialog, UForm | item(s) | done | Media |
|
||||||
|
| MediaPicker | UTabs inside ImageUploader | articleId | picked(item, alt) | Editor |
|
||||||
|
|
||||||
|
ImageUploader (changed): it gains the Upload and Library tabs and the "Already in your library" card. The remove-image confirm becomes neutral and only detaches the image from the article.
|
||||||
|
|
||||||
|
## Added with Updates
|
||||||
|
|
||||||
|
Exact values live in `source/AppFrame.dc.html` (the Settings and Home states). Copy and states are in [settings](screens/settings.md) and [home](screens/home.md).
|
||||||
|
|
||||||
|
| Component | Nuxt UI base | Props | Emits | Used in |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| UpdatesCard | custom card, UProgress, UButton, UCollapsible | status: UpdateStatus, role | check, update, restart, copy-command | Settings |
|
||||||
|
| UpdateStatusBlock | custom (polite live region) | tone, icon, title, text, meta | none | UpdatesCard |
|
||||||
|
| UpdateProgress | UProgress | label, text, value or indeterminate | none | UpdatesCard |
|
||||||
|
| ReleaseNotes | UCollapsible | version, date, items | none | UpdatesCard |
|
||||||
|
| ServerCommand | UButton, code block | line | copy | UpdatesCard (Not prepared) |
|
||||||
|
| RestartOverlay | custom full-page `role="status"` | title, text, startedAt, slow | reload | App shell |
|
||||||
|
| UpdateBanner | UAlert | state: 'available'\|'ready' | go-to-settings, dismiss | Home (owner) |
|
||||||
|
| UpdatePill | UBadge | none | none | DashboardShell Settings item (dot on mobile) |
|
||||||
@@ -11,13 +11,14 @@ A global `router.beforeEach` guard reads `meta.auth`. On the first navigation it
|
|||||||
| `/register/validate` | AuthShell | public | VerifyPage | POST /v1/auth/verify (+ POST /login inline on 401) |
|
| `/register/validate` | AuthShell | public | VerifyPage | POST /v1/auth/verify (+ POST /login inline on 401) |
|
||||||
| `/register/reset/request` | AuthShell | public | ResetRequestPage | POST /v1/auth/password-reset |
|
| `/register/reset/request` | AuthShell | public | ResetRequestPage | POST /v1/auth/password-reset |
|
||||||
| `/register/reset/validate` | AuthShell | public | ResetConfirmPage | POST /v1/auth/password-reset/confirm |
|
| `/register/reset/validate` | AuthShell | public | ResetConfirmPage | POST /v1/auth/password-reset/confirm |
|
||||||
| `/home` | DashboardShell | verified | HomePage | GET /v1/article/ |
|
| `/home` | DashboardShell | verified | HomePage | GET /v1/article/ · GET /v1/system/update (owner, for the banner) |
|
||||||
| `/article` | DashboardShell | verified | ArticlesPage | GET /v1/article/ · PATCH /{id}/publish\|unpublish · DELETE /{id} |
|
| `/article` | DashboardShell | verified | ArticlesPage | GET /v1/article/ · PATCH /{id}/publish\|unpublish · DELETE /{id} |
|
||||||
| `/article/new` | DashboardShell | verified | ArticlesPage + NewArticleModal | POST /v1/article/ |
|
| `/article/new` | DashboardShell | verified | ArticlesPage + NewArticleModal | POST /v1/article/ |
|
||||||
| `/article/:id/edit` | DashboardShell | verified | EditorPage | GET /{id} · PATCH /{id} · PATCH /{id}/publish\|unpublish · POST /{id}/image · DELETE /{id} |
|
| `/article/:id/edit` | DashboardShell | verified | EditorPage | GET /{id} · PATCH /{id} · PATCH /{id}/publish\|unpublish · GET /v1/media/ · POST /v1/media/ · DELETE /{id} |
|
||||||
|
| `/media` | DashboardShell | verified | MediaPage | GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage |
|
||||||
| `/integration` | DashboardShell | verified | IntegrationPage | none |
|
| `/integration` | DashboardShell | verified | IntegrationPage | none |
|
||||||
| `/users` | DashboardShell | verified | UsersPage + InviteUserModal | GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id · POST /v1/user/invite/:id/renew |
|
| `/users` | DashboardShell | verified | UsersPage + InviteUserModal | GET /v1/user/ · POST /v1/user/invite · DELETE /v1/user/invite/:id · POST /v1/user/invite/:id/renew |
|
||||||
| `/settings` | DashboardShell | verified | SettingsPage | GET /v1/settings |
|
| `/settings` | DashboardShell | verified | SettingsPage | GET /v1/settings · GET /v1/system/update · POST /v1/system/update/check · POST /v1/system/update/download · POST /v1/system/update/restart |
|
||||||
| `/profile` | DashboardShell | verified | ProfilePage | GET /v1/auth/me · PATCH /v1/user/me · POST /v1/auth/password-reset |
|
| `/profile` | DashboardShell | verified | ProfilePage | GET /v1/auth/me · PATCH /v1/user/me · POST /v1/auth/password-reset |
|
||||||
| `/invite/accept` | AuthShell | public | AcceptInvitePage | GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept* |
|
| `/invite/accept` | AuthShell | public | AcceptInvitePage | GET /v1/auth/invite?c=* · POST /v1/auth/invite/accept* |
|
||||||
| `/:pathMatch(.*)*` | either | any | NotFoundPage | none |
|
| `/:pathMatch(.*)*` | either | any | NotFoundPage | none |
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
|
|||||||
|
|
||||||
- Breadcrumbs: Articles (mobile title "Articles")
|
- Breadcrumbs: Articles (mobile title "Articles")
|
||||||
- Modal: **Delete this article?**
|
- Modal: **Delete this article?**
|
||||||
- text ""Winter checklist for timber windows" and its 3 images will be deleted. This can't be undone."
|
- text ""Winter checklist for timber windows" will be deleted. Its images stay in your library. This can't be undone."
|
||||||
- cancel "Cancel"
|
- cancel "Cancel"
|
||||||
- confirm "Delete article" (danger)
|
- confirm "Delete article" (danger)
|
||||||
|
|
||||||
@@ -98,7 +98,7 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
|
|||||||
|
|
||||||
- Breadcrumbs: Articles (mobile title "Articles")
|
- Breadcrumbs: Articles (mobile title "Articles")
|
||||||
- Modal: **Delete this article?**
|
- Modal: **Delete this article?**
|
||||||
- text ""Winter checklist for timber windows" and its 3 images will be deleted. This can't be undone."
|
- text ""Winter checklist for timber windows" will be deleted. Its images stay in your library. This can't be undone."
|
||||||
- cancel "Cancel"
|
- cancel "Cancel"
|
||||||
- confirm "Deleting…" (danger), loading, not dismissible
|
- confirm "Deleting…" (danger), loading, not dismissible
|
||||||
|
|
||||||
@@ -108,7 +108,7 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
|
|||||||
|
|
||||||
- Breadcrumbs: Articles (mobile title "Articles")
|
- Breadcrumbs: Articles (mobile title "Articles")
|
||||||
- Modal: **Delete this article?**
|
- Modal: **Delete this article?**
|
||||||
- text ""Winter checklist for timber windows" and its 3 images will be deleted. This can't be undone."
|
- text ""Winter checklist for timber windows" will be deleted. Its images stay in your library. This can't be undone."
|
||||||
- Alert: "Couldn't delete the article, so it's still there. Try again in a moment."
|
- Alert: "Couldn't delete the article, so it's still there. Try again in a moment."
|
||||||
- cancel "Cancel"
|
- cancel "Cancel"
|
||||||
- confirm "Delete article" (danger)
|
- confirm "Delete article" (danger)
|
||||||
@@ -118,5 +118,5 @@ Rows update when the server responds, not optimistically. Search, tab and sort a
|
|||||||
**Trigger:** 204: the row is removed and focus moves to the next row. This is also where a delete from the editor ends up.
|
**Trigger:** 204: the row is removed and focus moves to the next row. This is also where a delete from the editor ends up.
|
||||||
|
|
||||||
- Breadcrumbs: Articles (mobile title "Articles")
|
- Breadcrumbs: Articles (mobile title "Articles")
|
||||||
- Toast (success, circle-check): **Article deleted** ""Winter checklist for timber windows" and its images are gone."
|
- Toast (success, circle-check): **Article deleted** ""Winter checklist for timber windows" is gone."
|
||||||
- Tab counts (All, Online, Drafts): 5, 4, 1
|
- Tab counts (All, Online, Drafts): 5, 4, 1
|
||||||
@@ -183,7 +183,7 @@ On mobile, Save and Publish sit in a sticky bottom bar and the details panel ope
|
|||||||
|
|
||||||
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
|
- Breadcrumbs: Articles › How we price a bathroom renovation (mobile title "Edit article")
|
||||||
- Modal: **Delete this article?**
|
- Modal: **Delete this article?**
|
||||||
- text ""How we price a bathroom renovation" and its 3 images will be deleted. This can't be undone."
|
- text ""How we price a bathroom renovation" will be deleted. Its images stay in your library. This can't be undone."
|
||||||
- cancel "Cancel"
|
- cancel "Cancel"
|
||||||
- confirm "Delete article" (danger)
|
- confirm "Delete article" (danger)
|
||||||
- Editor: status "draft", save "saved"
|
- Editor: status "draft", save "saved"
|
||||||
|
|||||||
@@ -40,3 +40,17 @@ The greeting reads "Good morning, {name}", where the name is the display name wh
|
|||||||
- Breadcrumbs: Home (mobile title "Home")
|
- Breadcrumbs: Home (mobile title "Home")
|
||||||
- Subtitle: "Here's where things stand on your site."
|
- Subtitle: "Here's where things stand on your site."
|
||||||
- Error state for the list request
|
- Error state for the list request
|
||||||
|
|
||||||
|
### Update available (owner)
|
||||||
|
|
||||||
|
**Trigger:** The owner only. A quiet banner above the content, and an "Update" pill on the Settings sidebar item (a dot on the menu icon on mobile, read as "Update available"). Dismissing hides the banner until the next version; the pill stays. Admins see neither.
|
||||||
|
|
||||||
|
- Breadcrumbs: Home (mobile title "Home")
|
||||||
|
- Subtitle: "Here's where things stand on your site."
|
||||||
|
- Banner: `role="region"` labelled "Update available", info tone, `circle-arrow-up` icon, title "Version 2.3.0 is available", text "Update it from Settings. It takes about 2 minutes and the site stays online.", button "Go to Settings", and a dismiss button
|
||||||
|
|
||||||
|
### Update ready to install (owner)
|
||||||
|
|
||||||
|
**Trigger:** The download is checked. The same banner changes its copy, and a dismiss comes back on the next visit because the update is waiting.
|
||||||
|
|
||||||
|
- Banner: success tone, `circle-check` icon, title "Version 2.3.0 is ready to install", text "Restart from Settings to finish. The site is unavailable for about 10 seconds.", button "Go to Settings"
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
# Media picker (editor)
|
||||||
|
|
||||||
|
- **Route:** `/article/:id/edit` (inside the editor's existing "Add an image" dialog)
|
||||||
|
- **API:** GET /v1/media/?q=&limit=&cursor= · POST /v1/media/ (same as the Media page)
|
||||||
|
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Media picker", drawn by `source/MediaFrame.dc.html`.
|
||||||
|
|
||||||
|
The existing "Add an image" dialog gains two tabs, Upload and Library. The Upload tab is the current flow unchanged, so it still offers crop and resize, and a new image lands in the library and is inserted as before. The Library tab opens on the Library tab when the library has images and on Upload when it is empty. Images load 24 at a time with "Load more". Newest first, and images already in this article carry "In this article". Alt text is set here and lives only in the article. The dialog is 640 px wide on desktop and a bottom sheet on mobile.
|
||||||
|
|
||||||
|
This supersedes the upload-only "Add an image" dialog described in [editor](editor.md), and the "Remove this image?" confirmation from `features/editor_image_removal.feature`.
|
||||||
|
|
||||||
|
## Dialog
|
||||||
|
|
||||||
|
Title "Add an image", `x` to close, 640 px wide on desktop (bottom sheet on mobile). Two tabs under the title: **Upload** (`upload` icon) and **Library** (`images` icon). The dialog opens on Library when the library has images and on Upload when it is empty; dropping a file onto the editor opens Upload with the file provided, as before. Footer: "Cancel", and on Library a primary "Insert image", disabled until an image is selected.
|
||||||
|
|
||||||
|
**Upload tab.** The current flow unchanged (drop zone "Drop an image here, or choose a file", help "PNG, JPEG, WEBP, SVG · max 10 MB", crop and resize, rejected, uploading and failed states). Two changes: the new image lands in the library and is inserted as before, and a chosen file whose content matches an existing image sends nothing and shows an info-bordered card: thumbnail, "Already in your library", `north-wall.jpg matches an image uploaded on 12 Sep 2026 by Marta Alves.`, with "Use existing" (primary) and "Upload anyway". "Use existing" goes to the alt text step for the existing image; "Upload anyway" continues to crop and upload.
|
||||||
|
|
||||||
|
**Library tab.** Search field ("Search by filename"), the line "Newest first · 48 images", a grid of square tiles (4 columns on desktop, 3 on mobile; scrolls inside the dialog) with the filename under each, and "Load more" below (24 images per page). Tiles are buttons labelled with filename, size and use; Enter or Space selects (single selection). A tile of an image already in this article carries a sand "In this article" tag. The selected tile gets a primary outline and a check. Once one is selected, the grid shrinks and a panel appears below it: 56 px thumbnail, filename, `dimensions · size`, and a field "Alt text (optional)" with placeholder "e.g. North wall of the kitchen before plastering" and help "Describes the image for people who use a screen reader, and shows if it doesn't load. Leave it empty if the image is only decoration." Alt text lives only in the article, never on the image.
|
||||||
|
|
||||||
|
| Library state | Copy |
|
||||||
|
|---|---|
|
||||||
|
| Empty | `images` icon, "Your library is empty" / "Images you upload appear here, ready to use in any article." / "Upload an image" (switches to Upload) |
|
||||||
|
| No results | `search` icon, `No images match "wall"` / "Check the spelling, or search for a shorter part of the filename." / "Clear search" |
|
||||||
|
| Failed | error alert "Couldn't load your library" / "Check your connection and try again." / "Try again" |
|
||||||
|
| Loading more | button reads "Loading…" with a loader, skeleton tiles at the end |
|
||||||
|
|
||||||
|
Insert (either tab): the image goes in at the cursor with the chosen alt text (empty alt means decorative), the draft becomes "Unsaved changes", and a toast appears: `circle-check`, "Image added" / "Save to keep it in the article." The dialog then closes.
|
||||||
|
|
||||||
|
## Removing an image from the article
|
||||||
|
|
||||||
|
The "Remove image" button on a selected image in the editor (and Backspace or Delete on it) now opens a neutral (not red) confirm, because nothing is deleted:
|
||||||
|
|
||||||
|
- Title: "Remove this image from the article?"
|
||||||
|
- Description: "It's removed from this article only. The file stays in your library and in any other article that uses it."
|
||||||
|
- Body: thumbnail, filename, "Stays in the library · 3.9 MB"
|
||||||
|
- Buttons: "Cancel" / "Remove image"
|
||||||
|
- Done: the image leaves the body, the draft becomes "Unsaved changes", and a toast appears: `circle-check`, "Image removed" / "It's still in your library."
|
||||||
|
|
||||||
|
No API call is made. Removing is a body edit only.
|
||||||
|
|
||||||
|
## States
|
||||||
|
|
||||||
|
| State | Trigger and behaviour |
|
||||||
|
|---|---|
|
||||||
|
| Upload tab | The image button in the toolbar. Identical to the current "Add an image" content; only the tabs are new. Rejected, uploading and failed states are unchanged. |
|
||||||
|
| Upload tab: already in your library | A chosen file has the same content as an existing image. Nothing is sent. "Use existing" inserts the existing image (the alt text step follows); "Upload anyway" continues to crop and upload as usual. |
|
||||||
|
| Library: loading | The Library tab was opened, or a search changed. Skeleton tiles after 150 ms. |
|
||||||
|
| Library: nothing selected | Newest first. Tiles are buttons labelled with filename, size and use, and Enter or Space selects. Images already in this article carry "In this article". "Insert image" is disabled. |
|
||||||
|
| Library: selected | One image selected (single selection). Below the grid: thumbnail, filename, dimensions and size, and an optional alt text field. "Insert image" turns on. |
|
||||||
|
| Library: alt text entered | Alt text is optional. Empty alt text is inserted as a decorative image. It is not saved on the image. |
|
||||||
|
| Library: loading more | "Load more" pressed. The button shows progress and new skeleton tiles appear at the end. Focus stays on the button until the new tiles arrive, then moves to the first new tile. |
|
||||||
|
| Library: empty | Zero images. "Upload an image" switches to the Upload tab. |
|
||||||
|
| Library: no results | Search matched nothing. "Clear search" resets it. |
|
||||||
|
| Library: failed to load | A 500 or network failure. The error shows in the dialog and Try again repeats the request. A 429 uses the same countdown alert as the Media page, and a 401 is handled globally. |
|
||||||
|
| Inserted | Insert image from either tab. The image goes in at the cursor with the chosen alt text, and the article now has unsaved changes. |
|
||||||
|
| Remove image: confirm | Remove image on an image in the article. It now only removes it from this article, and the copy says the file stays in the library. The confirm button is neutral, not red, because nothing is deleted. Title: "Remove this image from the article?" |
|
||||||
|
| Removed | Confirmed. The image leaves the article body, which now has unsaved changes. |
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
# Media
|
||||||
|
|
||||||
|
- **Route:** `/media` (verified users)
|
||||||
|
- **API:** GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage
|
||||||
|
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Media", drawn by `source/MediaFrame.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||||
|
|
||||||
|
The library of every uploaded image. It replaces "images belong to one article": an image belongs to the library and can be used in any number of articles. Deleting an article never deletes images. The sidebar gains **Media** (`images` icon) between Articles and Users, breadcrumb "Media".
|
||||||
|
|
||||||
|
New route for verified users, in the sidebar between Articles and Users with the images icon. Images belong to the library, not to an article: one image can be used in many articles, and deleting an article never deletes images. Uploads from this page are not cropped or resized, and the file is stored as chosen. "Used in" is read from article bodies each time the list loads. Duplicates are images with identical content, whatever their filenames. Alt text is not stored on the image; it is set when inserting into an article. Search, filter, sort and view are stored in the query string. Keyboard: grid items are buttons in one tab stop each; Enter opens the detail panel, Space toggles selection, and Escape closes the panel or clears the selection. Selection changes are announced ("north-wall.jpg selected, 1 selected").
|
||||||
|
|
||||||
|
## Layout
|
||||||
|
|
||||||
|
Header: title "Media", subtitle "Every image you've uploaded, ready to use in any article.", primary "Upload" button (`upload` icon) on the right. On mobile the button is a full-width 48 px button pinned to the bottom (it turns into "Try again in 0:42" while rate limited, and is replaced by the bulk bar while items are selected).
|
||||||
|
|
||||||
|
Toolbar: tabs **All**, **Unused** and **Duplicates** (count badge of duplicate groups, only while groups exist), then search ("Search by filename"), sort and the grid/list toggle. Sort options: Newest (default), Oldest, Name, Largest. Below md the toolbar stacks: search, tabs, then sort and toggle.
|
||||||
|
|
||||||
|
Grid (default): 5 columns on desktop, 2 on mobile, 16 px gap (10 px on mobile). Each card is one button: 4:3 thumbnail (checkerboard behind transparent PNG and SVG), filename (medium, ellipsis), `size · dimensions` (SVG dimensions read "Vector"), then badges. The accessible name reads "north-wall.jpg, 3.9 MB, used in 2 articles" or "…, unused". A "Select all" row with the image count sits above the grid.
|
||||||
|
|
||||||
|
| Badge | Look |
|
||||||
|
|---|---|
|
||||||
|
| Unused | warning-soft fill, `unlink` icon |
|
||||||
|
| Duplicate | info-soft fill, `copy` icon |
|
||||||
|
| Used in N | outline, toned text |
|
||||||
|
|
||||||
|
List view: table from md up, columns Filename (with 40 px thumbnail and Duplicate badge), Dimensions, Size, Type, Used in (underlined count, opens the detail panel), Uploaded by, Uploaded (sorted, `arrow-down`); 56 px rows, 36 px header, first column is the checkbox. Below md it is a card list with a 44 px checkbox column, a 56 px thumbnail, filename, `size · dimensions · type`, badges plus `uploader · date`, and a trailing `chevron-right`.
|
||||||
|
|
||||||
|
Selection: selected items take the sand fill (`--rc-sand`) with a primary outline. The checkbox shows on hover, on keyboard focus, on mobile, and whenever anything is selected. The bulk bar is sticky at the bottom (400 px wide on desktop, full width above the bottom edge on mobile): inverted fill, "3 selected", a danger "Delete" button (`trash-2`) and an inverted "Clear".
|
||||||
|
|
||||||
|
Detail panel: right-hand slideover 460 px wide on desktop (`x` to close), full screen on mobile with an `arrow-left`. Title is the filename. Body: 16:10 preview (4:3 on mobile), actions Copy URL (`link`), Rename (`pencil`), Delete (`trash-2`, error text), an info alert for duplicates, a metadata list (Type, Size, Dimensions, Uploaded, Uploaded by, URL in mono), then the "Used in" section.
|
||||||
|
|
||||||
|
Detail panel copy:
|
||||||
|
|
||||||
|
| Where | Copy |
|
||||||
|
|---|---|
|
||||||
|
| Duplicate alert | "Identical to 2 other images" / "floorboards-copy.jpg and IMG_2208.jpg have the same content." / action "Review duplicates" (`arrow-right`) |
|
||||||
|
| Used | "Used in 2 articles", then one row per article: title (underlined link to the editor), badge "Online" (`globe`, inverted) or "Draft" (`pencil-line`, outline), `arrow-up-right`. Footnote: "Counted from the text of your articles each time you open this page." |
|
||||||
|
| Not used | "Not used in any article" / "This image is safe to delete. No article shows it." |
|
||||||
|
|
||||||
|
## Dialogs
|
||||||
|
|
||||||
|
All dialogs use the existing ConfirmDialog look (`UModal`, `sm:max-w-md`, bottom sheet on mobile, cancel first). While a request runs the confirm button shows a `loader-circle`, both buttons are disabled and the dialog cannot be dismissed. A failure shows an error alert at the top of the dialog body and the dialog stays open.
|
||||||
|
|
||||||
|
| Dialog | Title | Description | Body | Cancel / Confirm (pending) |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| Rename | "Rename image" | "Only the filename changes. The URL stays the same, so articles that use this image keep working." | Field "Filename" with the extension fixed as a mono suffix (`.jpg`); help "Letters, numbers, dashes and underscores. The .jpg ending stays."; error "Enter a filename." on empty or only symbols | "Cancel" / "Rename" ("Renaming…") |
|
||||||
|
| Delete, unused | "Delete this image?" | ""window-frame.jpg" will be deleted from your library. No article uses it. This can't be undone." | none | "Cancel" / "Delete image" ("Deleting…"), danger |
|
||||||
|
| Delete, in use | "Delete an image that's in use?" | ""north-wall.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can't be undone." | list of affected articles with Online or Draft badges | "Cancel" / "Delete image" ("Deleting…"), danger |
|
||||||
|
| Bulk delete | "Delete 3 images?" | "2 of them are used in 4 articles, which will show a broken image. The other one isn't used anywhere. This can't be undone." | one row per image: filename and "Used in N" or "Unused" | "Cancel" / "Delete 3 images" ("Deleting…"), danger |
|
||||||
|
| Merge | "Merge into floorboards.jpg?" | "Articles that use the other 2 copies will be switched to floorboards.jpg, and the other 2 copies will be deleted. 5 articles will be updated. This can't be undone." | the kept image: thumbnail, filename, "Kept · used in 4 articles now" | "Cancel" / "Merge 2 copies" ("Merging…"), danger |
|
||||||
|
|
||||||
|
Dialog errors: rename "Couldn't rename the image. Your text is still here. Try again in a moment."; delete "Couldn't delete the image, so it's still there. Try again in a moment."; merge (500) "Couldn't merge the copies. Nothing was changed. Try again in a moment."; merge (409) "One of these images changed, so nothing was merged. The list is up to date now. Check it and try again."
|
||||||
|
|
||||||
|
## Upload panel
|
||||||
|
|
||||||
|
A panel above the images while files are in flight and until dismissed. Header: "Uploading 6 images" with "2 of 6 done" and "Cancel all" (after it settles: "Upload finished" / "5 images" and "Dismiss"; if nothing was added: "Nothing was uploaded"). Files upload two at a time, one row each: 40 px thumbnail, filename, size, then per status:
|
||||||
|
|
||||||
|
| Status | Row |
|
||||||
|
|---|---|
|
||||||
|
| Waiting | "Waiting" |
|
||||||
|
| Uploading | "Uploading 1.1 of 2.6 MB" with a 4 px progress bar and a cancel `x` |
|
||||||
|
| Added | `circle-check` "Added to your library" |
|
||||||
|
| Duplicate | "Already in your library" / `Same as "floorboards.jpg", uploaded 14 Jun 2026 by Inès Duarte.` / "Use existing" and "Upload anyway" |
|
||||||
|
| Rejected | `file-x` title, then "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image." Titles: `scan.tif is 14.2 MB` (too large), `notes.pdf isn't an image` (type), `broken.png couldn't be read` with "The server couldn't read this image. Save it again as a PNG or JPEG, then try again." (400) |
|
||||||
|
| Failed | `circle-x` "Upload failed" / "The server didn't accept the file. Nothing was added to your library." / "Try again" (`rotate-cw`) |
|
||||||
|
|
||||||
|
Summary line when settled: "2 uploaded · 1 already in your library · 2 need attention". Type and size are checked in the browser before anything is sent (PNG, JPEG, WEBP, SVG; 10 MB), by MIME type and by extension, exactly as the editor's uploader does. Dropping files onto the page shows a dashed primary-bordered area "Drop images to upload" / "PNG, JPEG, WEBP, SVG · max 10 MB each".
|
||||||
|
|
||||||
|
## Duplicates view
|
||||||
|
|
||||||
|
Groups stacked with 16 px gap. Each group is a bordered card: header "Group 1" and "3 identical images · 2.4 MB each · 3600 × 2400"; one column per copy (stacked on mobile) with thumbnail, filename, "Uploaded 14 Jun 2026 by Inès Duarte", underlined "Used in 4 articles", and a "Merge into this one" button (`merge` icon). The suggested copy has the sand fill, a primary outline, a "Suggested" tag and a primary button; the others are outline. Footer: "Suggested: the most used copy, then the oldest. Choosing another copy switches articles to it." Empty: `copy` icon, "No duplicates" / "Every image in your library is different." / "Back to all images".
|
||||||
|
|
||||||
|
## Other copy
|
||||||
|
|
||||||
|
| Where | Copy |
|
||||||
|
|---|---|
|
||||||
|
| Empty library | `images` icon, "No images yet" / "Upload your first image. You can use it in any article." / primary "Upload an image"; under it "PNG, JPEG, WEBP, SVG · max 10 MB each" |
|
||||||
|
| No results | `search` icon, `No images match "wall"` / "Nothing matches in Unused. Check the spelling, or clear the filters." / "Clear filters" |
|
||||||
|
| List error | error alert "Couldn't load your images" / "Check your connection and try again." / "Try again" |
|
||||||
|
| Rate limited | info alert `timer` "Too many uploads" / "For your security, wait a moment before uploading again."; the Upload button reads "Try again in 0:42" and is disabled |
|
||||||
|
| Offline banner | `wifi-off` "You're offline. You can look through the images that are loaded, but uploading, renaming and deleting need a connection." |
|
||||||
|
|
||||||
|
Toasts (success 5 s unless noted):
|
||||||
|
|
||||||
|
| Trigger | Icon, title, description |
|
||||||
|
|---|---|
|
||||||
|
| Copy URL | `circle-check` "URL copied" / "Paste it wherever you need the image address." |
|
||||||
|
| Rename | `circle-check` "Image renamed" / `It's now "north-wall-01.jpg". The URL is the same.` |
|
||||||
|
| Delete | `circle-check` "Image deleted" / `"window-frame.jpg" is gone from your library.` |
|
||||||
|
| Bulk delete | `circle-check` "3 images deleted" / "They're gone from your library." |
|
||||||
|
| Bulk delete, partial | error, stays until retried or dismissed: `circle-x` "Couldn't delete 1 image" / "2 images were deleted. window-frame.jpg is still in your library. Try again." / "Retry" |
|
||||||
|
| Merge | `circle-check` "Copies merged" / "2 copies merged. 5 articles updated." |
|
||||||
|
| 404 | info `info` "That image no longer exists" / "It was deleted somewhere else, so we removed it from the library." |
|
||||||
|
|
||||||
|
## Status to copy
|
||||||
|
|
||||||
|
| Status | Where | Copy |
|
||||||
|
|---|---|---|
|
||||||
|
| 200 / 201 | Upload, rename, merge | Upload: row reads "Added to your library". Rename and merge: toasts above. |
|
||||||
|
| 204 | Delete, bulk delete | Toasts above. |
|
||||||
|
| 400 | Upload row | "broken.png couldn't be read" / "The server couldn't read this image. Save it again as a PNG or JPEG, then try again." In a dialog: "Something in the form isn't valid. Check the highlighted fields." |
|
||||||
|
| 401 | any | Global: /login?redirect=/media&reason=expired. No local copy. |
|
||||||
|
| 403 | any, unverified | Global: /register/pending. |
|
||||||
|
| 404 | rename, delete, merge, panel | The info toast above; the panel or dialog closes. |
|
||||||
|
| 409 | merge | Dialog alert above. |
|
||||||
|
| 413 | upload row | "scan.tif is 14.2 MB" / "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image." |
|
||||||
|
| 415 | upload row | "notes.pdf isn't an image" / same description. |
|
||||||
|
| 429 | upload | Rate-limited alert above, counting down Retry-After. |
|
||||||
|
| 500 / network | list, upload row, rename, delete, merge | The copy for each place above. |
|
||||||
|
| Offline | whole page | Banner above. |
|
||||||
|
|
||||||
|
## Keyboard and accessibility
|
||||||
|
|
||||||
|
Grid items are buttons, one tab stop each. Enter opens the detail panel, Space toggles selection, arrow keys move focus across the grid, Escape closes the panel or clears the selection. Focus returns to the item when the panel closes, and moves to the next item after a delete. Selection changes are announced ("north-wall.jpg selected, 1 selected"), as are upload completion and the merge result. Search, filter, sort and view live in the query string.
|
||||||
|
|
||||||
|
## States
|
||||||
|
|
||||||
|
| State | Trigger and behaviour |
|
||||||
|
|---|---|
|
||||||
|
| Grid, many images | Default view. 12 images, newest first. Each item is a button labelled like "north-wall.jpg, 3.9 MB, used in 2 articles". Badges: "Unused" (warm), "Duplicate" (info), "Used in N" (outline). The Duplicates tab carries a count of groups only while duplicates exist. |
|
||||||
|
| Grid, few images | Three images. Cards keep their size instead of stretching. Checkerboard shows behind the SVG. |
|
||||||
|
| List view | The list icon in the toggle. A table from md up (Filename, Dimensions, Size, Type, Used in, Uploaded by, Uploaded) and a card list below md. The "Used in" count opens the article list in the detail panel. |
|
||||||
|
| Loading | The first load, a retry, or a change of search or filter. Skeleton cards appear after 150 ms. |
|
||||||
|
| Empty library, first run | Zero images. Toolbar and tabs are hidden; one call to action. Copy: "No images yet" / "Upload your first image. You can use it in any article." / "Upload an image". |
|
||||||
|
| No results | Search or filter matched nothing. "Clear filters" resets the search and goes back to All. |
|
||||||
|
| Hover, focus and keyboard | Hover (second item) darkens the border, adds the pop shadow and reveals the checkbox. Keyboard focus (third item) shows the 2 px primary ring with a 2 px offset and reveals the checkbox. Tab moves between items, Enter opens the detail panel, Space toggles selection, and arrow keys move focus across the grid. |
|
||||||
|
| Selection and bulk bar | Checkbox on any item, or Space. Selected items take the sand fill with a primary outline, and Select all shows a partial state. The bar is sticky at the bottom (above the bottom edge on mobile, replacing the Upload button). Announced: "3 selected". Escape or Clear empties it. |
|
||||||
|
| Bulk delete: confirm | Delete in the bulk bar. The dialog says how many of the selection are in use and lists them. The confirm button carries the count. |
|
||||||
|
| Bulk delete: in progress | Requests in flight. The dialog can't be dismissed. |
|
||||||
|
| Bulk delete: partly failed | Some requests failed. Deleted images leave the grid, failed ones stay selected, and the toast stays until retried or dismissed. |
|
||||||
|
| Bulk delete: done | 204 for all. Focus moves to the next item. |
|
||||||
|
| Detail panel: in use | Click or Enter on an item. Right-hand slideover on desktop, full screen on mobile with a back arrow. Actions: Copy URL, Rename, Delete. "Used in 2 articles" lists title, Online or Draft, and links to the editor. Focus returns to the item on close. |
|
||||||
|
| Detail panel: unused | Used in nothing. The section reads "Not used in any article" and says the image is safe to delete. |
|
||||||
|
| Detail panel: duplicate | The image has identical copies. An info alert links to the duplicates view. |
|
||||||
|
| Copy URL | Copy URL. Clipboard write succeeded. Success toasts last 5 s. |
|
||||||
|
| Rename: dialog | Rename in the panel. The field holds the name without its extension, and the .jpg ending is fixed. The description says the URL stays the same. |
|
||||||
|
| Rename: saving | PATCH in flight. Field and buttons disabled, dialog can't be dismissed. |
|
||||||
|
| Rename: validation | Empty or only symbols, on submit or blur. Nothing is sent. |
|
||||||
|
| Rename: failed | 500 or network failure. The error shows inside the dialog. |
|
||||||
|
| Rename: done | 200: the panel title and list update in place. |
|
||||||
|
| Delete: unused image | Delete in the panel. Plain confirm. Says what happens and that it can't be undone. |
|
||||||
|
| Delete: image in use | Stronger confirm. Lists the affected articles and states that they will show a broken image. |
|
||||||
|
| Delete: in progress | DELETE in flight. The dialog can't be dismissed. |
|
||||||
|
| Delete: failed | 500 or network failure. The error shows inside the dialog, as in the article delete. |
|
||||||
|
| Delete: done | 204: the panel closes, the item leaves the grid and focus moves to the next item. |
|
||||||
|
| Image already gone (404) | Any action on an image that was deleted elsewhere. The panel closes and the item leaves the list. |
|
||||||
|
| Upload: drag over the page | Files dragged onto the page. A dashed drop area covers the content. Dropping starts the upload straight away; there is no crop step on this page. |
|
||||||
|
| Upload: several files, mixed | Upload button or drop, several files. Each file has its own row and progress. Files upload two at a time. A row can end as added, "Already in your library", rejected in the browser, or failed. Rejected and failed rows stay until dismissed. |
|
||||||
|
| Upload: summary | All rows settled. The summary counts each outcome. "Use existing" selects the existing image and drops the row; "Upload anyway" stores a second copy, which then appears under Duplicates. "Try again" retries one file. Announced when it finishes. |
|
||||||
|
| Upload: rejected files (413, 400) | Type and size are checked in the browser first, so nothing is sent. A server 413 or 400 for a file that got through shows the same row with its own message. |
|
||||||
|
| Upload: too many requests (429) | Rate limited. Retry-After is counted down in the button. It re-enables at zero. Already-added files are kept. |
|
||||||
|
| Duplicates: groups | The Duplicates tab. Groups of identical images side by side, each with its uploader, upload date and "Used in N articles". The suggested copy to keep is the most used, then the oldest. |
|
||||||
|
| Duplicates: empty | No groups. The Duplicates tab loses its count badge. |
|
||||||
|
| Merge: confirm | "Merge into this one" on floorboards.jpg. The dialog says articles using the other copies will switch to this image and the other copies will be deleted, with the article count. |
|
||||||
|
| Merge: in progress | Request in flight. The dialog can't be dismissed. |
|
||||||
|
| Merge: failed | 500 or network failure. Nothing is switched or deleted. |
|
||||||
|
| Merge: conflict (409) | A copy was deleted, or a new copy appeared, since the page loaded. |
|
||||||
|
| Merge: done | 200: the group leaves the list. When it was the last one, "No duplicates" shows. |
|
||||||
|
| List failed to load | A 500 or network failure on the list request. The alert replaces the images; Try again repeats the request. |
|
||||||
|
| Offline | navigator.onLine is false. Loaded images stay browsable. Upload, Rename, Delete and Merge are disabled, and the banner says why. |
|
||||||
+111
-21
@@ -1,35 +1,125 @@
|
|||||||
# Settings
|
# Settings
|
||||||
|
|
||||||
- **Route:** `/settings`
|
- **Route:** `/settings`
|
||||||
- **API:** GET /v1/settings (not drawn, see the notes)
|
- **API:** GET /v1/settings (version) · GET /v1/system/update · POST /v1/system/update/check · POST /v1/system/update/download · POST /v1/system/update/restart
|
||||||
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Settings" (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
- **Visual reference:** `source/RenewCMS Screens Back-office.dc.html`, group "Settings", drawn by `source/AppFrame.dc.html` (open it in a browser; each state is drawn at desktop and mobile, with a light/dark toggle).
|
||||||
|
|
||||||
Opened from the sidebar (Settings, settings icon, after Integration) and from the mobile drawer. Every verified user sees it, owner and admins alike. For now it holds a single section, Version. Nothing on it can be edited.
|
Opened from the sidebar (Settings, settings icon, after Integration) and from the mobile drawer. Every verified user sees it. It holds two sections: Version (everyone) and Updates (the owner has the buttons, admins read the status).
|
||||||
|
|
||||||
|
The Updates card lets a non-technical owner update the site without a terminal. **Update** downloads the new version and checks it, and changes nothing. **Restart** installs it and restarts the site (about 10 seconds). "Restart later" is simply closing the dialog or leaving the page; the update waits. A plain **Restart** appears only when no update is waiting. The state lives on the server, so any owner on any device sees the same card, and the buttons are disabled while any step runs.
|
||||||
|
|
||||||
|
Out of scope: choosing versions, downgrades, automatic updates, update history.
|
||||||
|
|
||||||
## The page
|
## The page
|
||||||
|
|
||||||
Title "Settings" and the subtitle "Workspace information.", 720 px wide at most. Page padding 32 px on desktop and `20px 16px 88px` on mobile, 20 px between the header and the card.
|
Title "Settings", subtitle "Workspace information.", 720 px at most, 20 px between sections. Page padding 32 px on desktop and `20px 16px 88px` on mobile.
|
||||||
|
|
||||||
One card (`--ui-bg`, 1 px `--ui-border`, 20 px padding on desktop and 16 px on mobile), a single row with the label on the left and the value on the right, 16 px apart:
|
**Version card** (unchanged): label "Version" and the running build's version in IBM Plex Mono 14 px, shown exactly as the server reports it (for example `v2.2.0-beta`).
|
||||||
|
|
||||||
|
**Updates card**, under it: `--ui-bg`, 1 px `--ui-border`, 20 px padding (16 px on mobile), 16 px gap. A region labelled by its heading "Updates" (`id="updates-h"`, `tabindex="-1"`, focus ring `2px solid var(--ui-primary)` with 4 px offset when focus is moved there). Inside:
|
||||||
|
|
||||||
| Part | Content |
|
| Part | Content |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Label | "Version", 15 px semibold, `--ui-text-highlighted` |
|
| Status block | A polite live region (`aria-live="polite"`): 14 px padding, 12 px gap, an 18 px icon, a semibold title, the text, and a muted `meta` line. Background and icon color follow the tone: neutral `--ui-bg-muted`, success, info, warning, error (`--rc-<tone>-soft` fill, `--ui-<tone>` icon). |
|
||||||
| Value | The running build's version in IBM Plex Mono 14 px, `--ui-text-toned`. The board shows `v2.2.0-beta`. Shown exactly as the server reports it, so the SPA adds no `v` prefix. |
|
| Progress | A `progressbar` with a value (`aria-valuenow`) while downloading, labelled for example "Downloading version 2.3.0", with the text `42% · 11 of 26 MB`. Indeterminate while verifying (35 % wide moving bar), labelled "Checking the download", text "Almost there". Announced at 25 % steps and when the step changes, never on every tick. |
|
||||||
|
| Release notes | A button "What's new in 2.3.0" with `aria-expanded` and a chevron, collapsed by default. Open: "Released 24 Sep 2026" and a plain-text list. |
|
||||||
|
| Server command | Only in the "Not prepared" state: "For whoever manages the server", a one-line `code` block, a Copy button (reads "Copied" with a check for 2 s, announced), and the note "They run this once on the server. After that, Update and Restart appear here." The command shown is `renewcms enable-browser-updates` and is subject to the real one. |
|
||||||
|
| Buttons | 32 px high (44 px on mobile, stacked full width), 14 px side padding. One primary at most. Disabled buttons use 40 % opacity. |
|
||||||
|
| Hint | 12 px muted line under the buttons. |
|
||||||
|
| Link | Underlined, with an `arrow-up-right`: "How to update" or "Read the release notes". |
|
||||||
|
|
||||||
|
Buttons used: **Check for updates** (`refresh-cw`, secondary), **Update** (`download`, primary), **Restart** (`power`, primary when an update is ready, otherwise secondary), **Try again** (`rotate-cw`, primary), and the disabled "Checking…" and "Updating…" (`loader-circle`). Copy such as "Version 2.3.0" names the newer release. Decision for the spec: show the release tag without its leading `v` ("Version 2.3.0-beta" for tag `v2.3.0-beta`), while the Version card keeps the running build exactly as the server reports it.
|
||||||
|
|
||||||
|
## Copy
|
||||||
|
|
||||||
|
| Where | Copy |
|
||||||
|
|---|---|
|
||||||
|
| Up to date | `circle-check`, success: "You're up to date" / "You have the latest version of RenewCMS." / "Last checked today at 09:41"; buttons "Check for updates" and "Restart"; hint "Restart takes about 10 seconds. Your site is unavailable while it restarts." |
|
||||||
|
| Checking | `loader-circle`: "Checking for updates…" / "This usually takes a few seconds."; "Checking…" disabled |
|
||||||
|
| Check failed | `wifi-off`, warning: "Couldn't check for updates" / "RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected." / "Last checked yesterday at 18:12"; "Try again" (primary) and "Restart" |
|
||||||
|
| Available | `circle-arrow-up`, info: "Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."; "Update"; hint "Takes about 2 minutes. Your site stays online." |
|
||||||
|
| Downloading | `download`, info: "Downloading version 2.3.0…" / "You can leave this page. The download continues and your site stays online."; "Updating…" disabled |
|
||||||
|
| Verifying | `shield-check`, info: "Checking the download…" / "Making sure the file is complete and safe to install. This takes a few seconds." |
|
||||||
|
| Ready | `circle-check`, success: "Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds." / "Nothing has changed yet."; "Restart"; hint "Not now? Leave this page. The update waits here, and the banner on Home reminds you." |
|
||||||
|
| Done | "You're on version 2.3.0" / "The update is installed and your site is running again." / "Updated today at 09:52"; link "Read the release notes"; toast `circle-check` "Update installed" / "RenewCMS is now on version 2.3.0." |
|
||||||
|
| Rolled back | `triangle-alert`, warning: "The update didn't install" / "RenewCMS put the previous version back, so your site is running as before. Nothing was lost." / "What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update."; "Try again"; toast (error, stays) `circle-x` "The update didn't install" / "Your site is back on v2.2.0-beta." |
|
||||||
|
| Download failed | `circle-x`, error: "The download didn't finish" / "The connection dropped before the file was complete. Nothing was changed and your site is running as before."; "Try again" |
|
||||||
|
| Not trusted | `triangle-alert`, warning: "We didn't use this update" / "The file didn't pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support." Technical detail goes to the server log. |
|
||||||
|
| Rate limited | `info`: "Too many tries" / "Wait a moment before trying again."; button "Try again in 0:42" counting down Retry-After |
|
||||||
|
| Not prepared | `info`: "Version 2.3.0 is available" / "This site can't update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you." and a link "How to update". No buttons, not even Restart. |
|
||||||
|
| Admin | "Version 2.3.0 is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." No buttons. Up to date reads "You're up to date" and "Only the owner can update or restart the site." |
|
||||||
|
|
||||||
|
## Dialogs and overlays
|
||||||
|
|
||||||
|
Both dialogs use the ConfirmDialog behaviour: focus moves to the first button, Escape and the cancel button close it, and focus returns to the button that opened it. The confirm button is neutral, not red, because nothing is lost.
|
||||||
|
|
||||||
|
| Dialog | Title | Description | Cancel / Confirm |
|
||||||
|
|---|---|---|---|
|
||||||
|
| Install | "Restart to finish the update?" | "RenewCMS will install version 2.3.0 and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first." | "Restart later" / "Restart now" |
|
||||||
|
| Plain restart | "Restart the site?" | "Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first." | "Cancel" / "Restart site" |
|
||||||
|
|
||||||
|
Failure inside the install dialog: "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment."
|
||||||
|
|
||||||
|
Restart overlay: a full-page `role="status"` live region (`--ui-bg-muted`, 440 px card) that survives the server going away, with a moving bar. Copy: "Installing version 2.3.0" / "Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back." / "Started at 09:51". Announced once as "Installing version 2.3.0. Your site is restarting." After 60 seconds with no answer: "Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now." / "Started at 09:51 · 1 minute ago" and a "Reload page" button. Plain restart: "Restarting your site" / "This takes about 10 seconds. This page reloads on its own when the site is back." After the reload: focus lands on the "Updates" heading and a toast `circle-check` "Site restarted" / "Your site is running again."
|
||||||
|
|
||||||
|
## Elsewhere
|
||||||
|
|
||||||
|
For the owner only: an **Update** pill on the Settings sidebar item, and a dot on the menu icon on mobile (read as "Update available"). Admins see neither. The Home banner is described in [home](home.md).
|
||||||
|
|
||||||
|
## Status to copy
|
||||||
|
|
||||||
|
| Status | Where | Copy |
|
||||||
|
|---|---|---|
|
||||||
|
| 200 | Check, up to date | "You're up to date" and the last-checked line |
|
||||||
|
| 200 | Check, newer version | "Version 2.3.0 is available" and its text |
|
||||||
|
| 202 | Update, Restart | Accepted. The card switches to progress, announced as "Downloading version 2.3.0, 25 percent". |
|
||||||
|
| 200 | Update finished | "Version 2.3.0 is ready to install" |
|
||||||
|
| 200 | After restart | Toast "Update installed" or "Site restarted" |
|
||||||
|
| 400 | Update, nothing to install | Info toast "Nothing to update" / "You already have the latest version." The card refreshes. |
|
||||||
|
| 401 | any | Global: /login?redirect=/settings&reason=expired. No local copy. |
|
||||||
|
| 403 | any button, not the owner | Error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." The card reloads as the admin view. An unverified account is handled globally. |
|
||||||
|
| 409 | Update, Restart | Already running: info toast "An update is already running" / "Another owner started it. Progress shows here." Not prepared: the card shows the "Not prepared" state. |
|
||||||
|
| 422 | Update, file not trusted | The "Not trusted" card above |
|
||||||
|
| 429 | Check, Update | The rate-limited card above |
|
||||||
|
| 500 / network | Check | "Couldn't check for updates" with "Try again" |
|
||||||
|
| 500 / network | Update | "The download didn't finish" with "Try again" |
|
||||||
|
| 500 / network | Restart dialog | "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment." |
|
||||||
|
| Site back, old version | after restart | The rolled-back card above |
|
||||||
|
| No answer, 60 s | restart overlay | "Still restarting" |
|
||||||
|
| Offline | whole page | Existing banner. Check, Update and Restart are disabled. During a restart the overlay keeps polling and ignores the offline state. |
|
||||||
|
|
||||||
|
## Behaviour notes
|
||||||
|
|
||||||
|
- The page asks for `GET /v1/system/update` on open and, when a step is running, polls it every second. The server holds the state (idle, downloading, verifying, ready, restarting, succeeded, failed), so another device or owner sees the same card.
|
||||||
|
- A check runs on the first open after 24 hours and when "Check for updates" is pressed.
|
||||||
|
- Update takes no confirmation because it changes nothing. Restart always asks.
|
||||||
|
|
||||||
## States
|
## States
|
||||||
|
|
||||||
### Default
|
| State | Trigger and behaviour |
|
||||||
|
|---|---|
|
||||||
**Trigger:** Opened from the sidebar.
|
| Up to date | Opened with no newer version. Restart is available but not emphasised. |
|
||||||
|
| Checking | Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled. |
|
||||||
- Breadcrumbs: Settings (mobile title "Settings")
|
| Check failed | Offline, or the update server didn't answer (500, network). The last known result is kept. |
|
||||||
- Section: Version, `v2.2.0-beta`
|
| Update available | A newer version exists. Release notes are collapsed. Update is the one primary button. |
|
||||||
|
| Update available, notes open | "What's new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text. |
|
||||||
The board draws no loading or error state. Decide them in the spec (see the notes).
|
| Downloading | Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick. |
|
||||||
|
| Verifying | The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download". |
|
||||||
## Notes for implementation
|
| Ready to install | The file passed its checks. Restart becomes the primary action. "Restart later" is closing the dialog or leaving the page. |
|
||||||
|
| Restart: confirm | Restart pressed. Same dialog behaviour as the delete confirm: focus moves to the first button, Escape and "Restart later" close it, and focus returns to Restart. The confirm button is neutral, not red, because nothing is lost. |
|
||||||
- The board's API line says "none (static)", but the version lives in the Go binary (`main.version`, set with `-ldflags -X`, `dev` when unset), so the SPA has to ask for it. The recommendation is `GET /v1/settings` returning `{ "version": "..." }` inside the verified group, so later settings have a home. It is read once at startup and never from the environment at request time.
|
| Restart: request failed | 500 or network failure before the restart began. The site is still running. |
|
||||||
- Not drawn: loading (the recommendation is a skeleton for the value only, after 150 ms, like the other pages), and a failed request (an inline error in the card with "Try again", using the global copy "Couldn't reach RenewCMS. Check your connection and try again.").
|
| Restarting to install | Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting." |
|
||||||
- Keep the page free of actions, toggles and links until a later slice adds a real setting.
|
| Restarting, taking longer | No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back. |
|
||||||
|
| Update done | The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates. |
|
||||||
|
| Update failed, rolled back | The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation. |
|
||||||
|
| Download failed | A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download. |
|
||||||
|
| Verification failed | The downloaded file isn't trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen. |
|
||||||
|
| Too many requests (429) | Retry-After counted down in the button. It re-enables at zero. |
|
||||||
|
| Not prepared | The server can't update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one. |
|
||||||
|
| Not prepared: command copied | Copy pressed. The button reads "Copied" for 2 s and it is announced. |
|
||||||
|
| Plain restart: confirm | Restart with no update waiting. Nothing is installed. |
|
||||||
|
| Plain restart: restarting | Same overlay as the update restart with shorter copy. |
|
||||||
|
| Plain restart: done | The page reloaded. Focus lands on the "Updates" heading. |
|
||||||
|
| Admin view | Admins see the version and the note, with no buttons. Up to date: "You're up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill. |
|
||||||
|
| Role changed (403) | An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view. |
|
||||||
|
| Update already running (409) | Another owner started it. The card switches to that run's progress. |
|
||||||
@@ -12,7 +12,7 @@
|
|||||||
<div style="width:224px;flex-shrink:0;background:var(--ui-bg);border-right:1px solid var(--ui-border);display:flex;flex-direction:column;padding:12px;gap:2px">
|
<div style="width:224px;flex-shrink:0;background:var(--ui-bg);border-right:1px solid var(--ui-border);display:flex;flex-direction:column;padding:12px;gap:2px">
|
||||||
<div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div>
|
<div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><span style="font-weight:600;font-size:14px;color:var(--ui-text-highlighted)">RenewCMS</span></div>
|
||||||
<sc-for list="{{ nav }}" as="n" hint-placeholder-count="3">
|
<sc-for list="{{ nav }}" as="n" hint-placeholder-count="3">
|
||||||
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}</div>
|
<div data-act="nav-{{ n.key }}" style="display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:{{ n.bg }};color:{{ n.fg }};font-weight:{{ n.fw }}"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ n.icon }}.svg') center / contain no-repeat"></span>{{ n.t }}<sc-if value="{{ n.badge }}"><span style="margin-left:auto;height:18px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-info);color:var(--ui-bg);font:500 11px 'IBM Plex Sans',sans-serif">Update</span></sc-if></div>
|
||||||
</sc-for>
|
</sc-for>
|
||||||
<div style="flex:1"></div>
|
<div style="flex:1"></div>
|
||||||
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
<sc-if value="{{ s.boot }}"><div style="display:flex;align-items:center;gap:10px;height:40px;padding:0 6px"><span style="width:26px;height:26px;background:var(--ui-bg-accented)"></span><span style="width:80px;height:12px;background:var(--ui-bg-accented)"></span></div></sc-if>
|
||||||
@@ -25,7 +25,7 @@
|
|||||||
<div style="height:48px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 24px;gap:8px;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat"></span><span style="width:1px;height:16px;background:var(--ui-border);margin:0 6px"></span><sc-for list="{{ crumbs }}" as="c" hint-placeholder-count="1"><sc-if value="{{ c.sep }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></sc-if><span style="color:{{ c.fg }};font-weight:{{ c.fw }}">{{ c.t }}</span></sc-for></div>
|
<div style="height:48px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 24px;gap:8px;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/panel-left-close.svg') center / contain no-repeat"></span><span style="width:1px;height:16px;background:var(--ui-border);margin:0 6px"></span><sc-for list="{{ crumbs }}" as="c" hint-placeholder-count="1"><sc-if value="{{ c.sep }}"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/chevron-right.svg') center / contain no-repeat"></span></sc-if><span style="color:{{ c.fg }};font-weight:{{ c.fw }}">{{ c.t }}</span></sc-for></div>
|
||||||
</sc-if>
|
</sc-if>
|
||||||
<sc-if value="{{ mob }}">
|
<sc-if value="{{ mob }}">
|
||||||
<div style="height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)"><span data-act="m-lead" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat"></span></span><span style="flex:1;min-width:0;font-weight:600;font-size:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ s.mTitle }}</span><sc-if value="{{ s.mAction }}"><span data-act="m-action" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat"></span></span></sc-if></div>
|
<div style="height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)"><span data-act="m-lead" style="position:relative;width:44px;height:44px;display:flex;align-items:center;justify-content:center"><sc-if value="{{ s.navBadge }}"><span aria-label="Update available" style="position:absolute;top:9px;right:9px;width:10px;height:10px;background:var(--ui-info);border:2px solid var(--ui-bg)"></span></sc-if><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ mLead }}.svg') center / contain no-repeat"></span></span><span style="flex:1;min-width:0;font-weight:600;font-size:16px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap">{{ s.mTitle }}</span><sc-if value="{{ s.mAction }}"><span data-act="m-action" style="width:44px;height:44px;display:flex;align-items:center;justify-content:center"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:20px;height:20px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.mAction }}.svg') center / contain no-repeat"></span></span></sc-if></div>
|
||||||
</sc-if>
|
</sc-if>
|
||||||
<sc-if value="{{ s.offline }}"><div role="status" style="flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat"></span><span style="flex:1">You're offline. You can keep writing, but saving and publishing will wait until you're back online.</span></div></sc-if>
|
<sc-if value="{{ s.offline }}"><div role="status" style="flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/wifi-off.svg') center / contain no-repeat"></span><span style="flex:1">You're offline. You can keep writing, but saving and publishing will wait until you're back online.</span></div></sc-if>
|
||||||
|
|
||||||
@@ -43,6 +43,7 @@
|
|||||||
<sc-if value="{{ isHome }}">
|
<sc-if value="{{ isHome }}">
|
||||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:{{ gap }};max-width:1040px">
|
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:{{ gap }};max-width:1040px">
|
||||||
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:4px"><span style="font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Good morning, {{ who }}</span><span style="color:var(--ui-text-muted);font-size:14px">{{ s.home.sub }}</span></div><sc-if value="{{ desk }}"><span data-act="new" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat"></span>New article</span></sc-if></div>
|
<div style="display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap"><div style="flex:1;min-width:200px;display:flex;flex-direction:column;gap:4px"><span style="font:600 28px/36px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Good morning, {{ who }}</span><span style="color:var(--ui-text-muted);font-size:14px">{{ s.home.sub }}</span></div><sc-if value="{{ desk }}"><span data-act="new" style="height:32px;padding:0 12px;display:flex;align-items:center;gap:6px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/plus.svg') center / contain no-repeat"></span>New article</span></sc-if></div>
|
||||||
|
<sc-if value="{{ s.home.banner }}"><div role="region" aria-label="Update available" style="display:flex;flex-direction:{{ upBtnDir }};align-items:{{ upBannerAlign }};gap:12px;padding:12px 14px;background:{{ s.home.banner.bg }};border:1px solid var(--ui-border)"><div style="flex:1;display:flex;gap:10px;min-width:0"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:{{ s.home.banner.fg }};-webkit-mask:url('https://api.iconify.design/lucide/{{ s.home.banner.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.home.banner.icon }}.svg') center / contain no-repeat"></span></span><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600;color:var(--ui-text-highlighted)">{{ s.home.banner.title }}</span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ s.home.banner.text }}</span></div></div><div style="display:flex;align-items:center;gap:8px"><span style="flex:1;height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500">{{ s.home.banner.btn }}</span><span role="button" aria-label="Dismiss" style="width:{{ btnH }};height:{{ btnH }};display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/x.svg') center / contain no-repeat"></span></span></div></div></sc-if>
|
||||||
<sc-if value="{{ s.home.error }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load your articles</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
|
<sc-if value="{{ s.home.error }}"><div role="alert" style="display:flex;gap:10px;padding:12px 14px;background:var(--rc-error-soft);color:var(--ui-error)"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-x.svg') center / contain no-repeat"></span></span><div style="flex:1;display:flex;flex-direction:column;gap:8px"><div style="display:flex;flex-direction:column;gap:2px"><span style="font-weight:600">Couldn't load your articles</span><span style="color:var(--ui-text-toned)">Check your connection and try again.</span></div><span style="align-self:flex-start;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500;font-size:12px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/rotate-cw.svg') center / contain no-repeat"></span>Try again</span></div></div></sc-if>
|
||||||
<sc-if value="{{ s.home.stats }}">
|
<sc-if value="{{ s.home.stats }}">
|
||||||
<div style="display:grid;grid-template-columns:{{ cols3 }};gap:12px">
|
<div style="display:grid;grid-template-columns:{{ cols3 }};gap:12px">
|
||||||
@@ -229,7 +230,16 @@
|
|||||||
<sc-if value="{{ isSettings }}">
|
<sc-if value="{{ isSettings }}">
|
||||||
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
|
<div style="padding:{{ pad }};display:flex;flex-direction:column;gap:20px;max-width:720px;overflow:hidden">
|
||||||
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Settings</span><span style="color:var(--ui-text-muted)">Workspace information.</span></div>
|
<div style="display:flex;flex-direction:column;gap:2px"><span style="font:600 20px/28px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Settings</span><span style="color:var(--ui-text-muted)">Workspace information.</span></div>
|
||||||
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;align-items:center;justify-content:space-between;gap:16px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Version</span><span style="font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">v2.2.0-beta</span></div>
|
<div style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;align-items:center;justify-content:space-between;gap:16px"><span style="font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">Version</span><span style="font:400 14px/22px 'IBM Plex Mono',monospace;color:var(--ui-text-toned)">{{ s.upd.v }}</span></div>
|
||||||
|
<div role="region" aria-labelledby="updates-h" style="background:var(--ui-bg);border:1px solid var(--ui-border);padding:{{ cardPad }};display:flex;flex-direction:column;gap:16px">
|
||||||
|
<span id="updates-h" tabindex="-1" style="align-self:flex-start;font:600 15px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted);outline:{{ s.upd.focus }};outline-offset:4px">Updates</span>
|
||||||
|
<div aria-live="polite" style="display:flex;gap:12px;padding:14px;background:{{ s.upd.bg }}"><span style="display:flex;padding-top:2px"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:{{ s.upd.fg }};-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.icon }}.svg') center / contain no-repeat"></span></span><div style="flex:1;min-width:0;display:flex;flex-direction:column;gap:4px"><span style="font:600 14px/22px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.upd.title }}</span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ s.upd.text }}</span><sc-if value="{{ s.upd.bar }}"><div style="display:flex;flex-direction:column;gap:6px;padding-top:8px"><div role="progressbar" aria-label="{{ s.upd.barLabel }}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="{{ s.upd.pct }}" style="height:6px;background:var(--ui-bg-accented)"><div style="height:6px;width:{{ s.upd.barW }};margin-left:{{ s.upd.barL }};background:var(--ui-primary)"></div></div><span style="font:400 12px/16px 'IBM Plex Mono',monospace;color:var(--ui-text-muted)">{{ s.upd.barText }}</span></div></sc-if><sc-if value="{{ s.upd.meta }}"><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.meta }}</span></sc-if></div></div>
|
||||||
|
<sc-if value="{{ s.upd.notes }}"><div style="display:flex;flex-direction:column;gap:10px"><span role="button" aria-expanded="{{ s.upd.notes.open }}" style="align-self:flex-start;display:flex;align-items:center;gap:6px;min-height:{{ btnH }};font-weight:500;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.notes.chev }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.notes.chev }}.svg') center / contain no-repeat"></span>What's new in {{ s.upd.notes.ver }}</span><sc-if value="{{ s.upd.notes.open }}"><div style="display:flex;flex-direction:column;gap:8px;padding:0 0 0 20px"><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.notes.date }}</span><sc-for list="{{ s.upd.notes.items }}" as="it" hint-placeholder-count="3"><div style="display:flex;gap:8px"><span aria-hidden="true" style="flex-shrink:0;width:4px;height:4px;margin-top:8px;background:var(--ui-text-muted)"></span><span style="color:var(--ui-text-toned);text-wrap:pretty">{{ it.t }}</span></div></sc-for><span style="align-self:flex-start;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-weight:500">Read the full release notes</span></div></sc-if></div></sc-if>
|
||||||
|
<sc-if value="{{ s.upd.cmd }}"><div style="display:flex;flex-direction:column;gap:8px"><span style="font-weight:500;color:var(--ui-text-highlighted)">For whoever manages the server</span><div style="display:flex;flex-direction:{{ upCmdDir }};align-items:{{ upBtnAlign }};gap:8px"><code style="flex:1;min-width:0;padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;line-height:22px">{{ s.upd.cmd.line }}</code><span role="button" style="height:{{ btnH }};padding:0 12px;display:flex;align-items:center;justify-content:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:{{ s.upd.cmd.fg }};font-weight:500"><span aria-hidden="true" style="display:inline-block;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ s.upd.cmd.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ s.upd.cmd.icon }}.svg') center / contain no-repeat"></span>{{ s.upd.cmd.t }}</span></div><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.upd.cmd.note }}</span></div></sc-if>
|
||||||
|
<sc-if value="{{ s.upd.btns }}"><div style="display:flex;flex-direction:{{ upBtnDir }};align-items:{{ upBtnAlign }};gap:8px"><sc-for list="{{ s.upd.btns }}" as="b" hint-placeholder-count="1"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;justify-content:center;gap:6px;background:{{ b.bg }};color:{{ b.fg }};border:1px solid {{ b.bd }};opacity:{{ b.op }};font-weight:500"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:16px;height:16px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/{{ b.icon }}.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/{{ b.icon }}.svg') center / contain no-repeat"></span>{{ b.t }}</span></sc-for></div></sc-if>
|
||||||
|
<sc-if value="{{ s.upd.hint }}"><span style="font-size:12px;color:var(--ui-text-muted);text-wrap:pretty">{{ s.upd.hint }}</span></sc-if>
|
||||||
|
<sc-if value="{{ s.upd.link }}"><span style="align-self:flex-start;display:flex;align-items:center;gap:6px;color:var(--ui-text-highlighted);text-decoration:underline;text-underline-offset:3px;font-weight:500">{{ s.upd.link }}<span aria-hidden="true" style="display:inline-block;width:14px;height:14px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/external-link.svg') center / contain no-repeat"></span></span></sc-if>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</sc-if>
|
</sc-if>
|
||||||
|
|
||||||
@@ -272,6 +282,8 @@
|
|||||||
|
|
||||||
<sc-if value="{{ mobMenu }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="menu" aria-label="Account" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px"><div style="margin:0 auto 8px;width:36px;height:4px;background:var(--ui-bg-accented)"></div><div style="padding:8px 16px 14px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="width:36px;height:36px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 13px 'IBM Plex Sans',sans-serif">{{ ini }}</span><div style="display:flex;flex-direction:column;min-width:0"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ who }}</span><span style="color:var(--ui-text-muted)">marta@renew.example</span></div></div><div data-act="nav-profile" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:48px;padding:0 16px;display:flex;align-items:center;justify-content:space-between;font-size:15px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:18px;height:18px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></div></sc-if>
|
<sc-if value="{{ mobMenu }}"><div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:flex-end"><div role="menu" aria-label="Account" style="width:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);padding:8px 0 24px"><div style="margin:0 auto 8px;width:36px;height:4px;background:var(--ui-bg-accented)"></div><div style="padding:8px 16px 14px;display:flex;align-items:center;gap:12px;border-bottom:1px solid var(--ui-border);margin-bottom:4px"><span style="width:36px;height:36px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 13px 'IBM Plex Sans',sans-serif">{{ ini }}</span><div style="display:flex;flex-direction:column;min-width:0"><span style="font-weight:600;font-size:15px;color:var(--ui-text-highlighted)">{{ who }}</span><span style="color:var(--ui-text-muted)">marta@renew.example</span></div></div><div data-act="nav-profile" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;background:{{ pfItemBg }};color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/circle-user.svg') center / contain no-repeat"></span>Profile</div><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><sc-for list="{{ themeSeg }}" as="m" hint-placeholder-count="3"><div data-act="{{ m.act }}" role="menuitemradio" aria-checked="{{ m.on }}" style="height:48px;padding:0 16px;display:flex;align-items:center;justify-content:space-between;font-size:15px;color:var(--ui-text-highlighted)">{{ m.t }}<span aria-hidden="true" style="display:inline-block;width:18px;height:18px;background-color:currentColor;opacity:{{ m.op }};-webkit-mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/check.svg') center / contain no-repeat"></span></div></sc-for><div style="height:1px;background:var(--ui-border);margin:4px 0"></div><div data-act="logout" role="menuitem" style="height:48px;padding:0 16px;display:flex;align-items:center;gap:12px;font-size:15px;color:var(--ui-text-highlighted)"><span aria-hidden="true" style="display:inline-block;flex-shrink:0;width:18px;height:18px;background-color:currentColor;-webkit-mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat;mask:url('https://api.iconify.design/lucide/log-out.svg') center / contain no-repeat"></span>Log out</div></div></div></sc-if>
|
||||||
|
|
||||||
|
<sc-if value="{{ s.overlay }}"><div role="status" aria-live="polite" style="position:absolute;inset:0;z-index:70;background:var(--ui-bg-muted);display:flex;align-items:center;justify-content:center;padding:24px"><div style="width:100%;max-width:440px;display:flex;flex-direction:column;gap:16px;align-items:flex-start"><svg width="26" height="26" viewBox="0 0 16 16" shape-rendering="crispEdges" aria-hidden="true"><rect width="16" height="16" fill="#111"></rect><path fill="#fff" fill-rule="evenodd" d="M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z"></path></svg><div style="display:flex;flex-direction:column;gap:6px"><span style="font:600 22px/30px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ s.overlay.title }}</span><span style="font-size:14px;line-height:22px;color:var(--ui-text-toned);text-wrap:pretty">{{ s.overlay.text }}</span></div><div role="progressbar" aria-label="Restarting" style="width:100%;height:4px;background:var(--ui-bg-accented)"><div style="width:35%;height:4px;margin-left:{{ s.overlay.barL }};background:var(--ui-primary)"></div></div><span style="font-size:12px;color:var(--ui-text-muted)">{{ s.overlay.meta }}</span><sc-if value="{{ s.overlay.btn }}"><span role="button" style="height:{{ btnH }};padding:0 14px;display:flex;align-items:center;gap:6px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);font-weight:500">{{ s.overlay.btn }}</span></sc-if></div></div></sc-if>
|
||||||
|
|
||||||
<sc-if value="{{ s.modal }}">
|
<sc-if value="{{ s.modal }}">
|
||||||
<div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ modalAlign }};justify-content:center;padding:{{ modalPad }}">
|
<div style="position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:{{ modalAlign }};justify-content:center;padding:{{ modalPad }}">
|
||||||
<div role="dialog" aria-modal="true" style="width:{{ modalW }};background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column">
|
<div role="dialog" aria-modal="true" style="width:{{ modalW }};background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column">
|
||||||
@@ -343,8 +355,8 @@ class Component extends DCLogic {
|
|||||||
const s = this.props.s || {}
|
const s = this.props.s || {}
|
||||||
const m = !!this.props.mobile
|
const m = !!this.props.mobile
|
||||||
const k = s.kind || 'home'
|
const k = s.kind || 'home'
|
||||||
const navItems = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
const navItems = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
||||||
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 }))
|
const nav = navItems.map(([key, icon, t]) => ({ key, icon, t, bg: s.nav === key ? 'var(--rc-sand)' : 'transparent', badge: key === 'settings' && !!s.navBadge, fg: s.nav === key ? '#111111' : 'var(--ui-text-toned)', fw: s.nav === key ? 500 : 400 }))
|
||||||
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
|
const crumbs = (s.crumbs || []).map((t, i, a) => ({ t, sep: i > 0, fg: i === a.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)', fw: i === a.length - 1 ? 500 : 400 }))
|
||||||
const L = s.list || {}
|
const L = s.list || {}
|
||||||
const counts = L.counts || [6, 4, 2]
|
const counts = L.counts || [6, 4, 2]
|
||||||
@@ -426,14 +438,14 @@ class Component extends DCLogic {
|
|||||||
themeSeg: [['system','monitor','System'],['light','sun','Light'],['dark','moon','Dark']].map(([k,icon,tt])=>{const on=(s.mode||'light')===k;return {act:'theme-'+k,icon,t:tt,on,op:on?1:0}}), menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
|
themeSeg: [['system','monitor','System'],['light','sun','Light'],['dark','moon','Dark']].map(([k,icon,tt])=>{const on=(s.mode||'light')===k;return {act:'theme-'+k,icon,t:tt,on,op:on?1:0}}), menuOpen: !!s.userMenu, deskMenu: !m && !!s.userMenu, mobMenu: m && !!s.userMenu, pfItemBg: 'var(--ui-bg-elevated)',
|
||||||
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? '#111111' : 'var(--ui-text-highlighted)',
|
chipBg: s.userMenu || s.nav === 'profile' ? 'var(--rc-sand)' : 'transparent', chipFg: s.userMenu || s.nav === 'profile' ? '#111111' : 'var(--ui-text-highlighted)',
|
||||||
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
isSettings: k === 'settings', isProfile: k === 'profile', pfLoading: k === 'profile' && !!pf.loading, pfReady: k === 'profile' && !pf.loading,
|
||||||
cardPad: m ? '16px' : '20px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
upBtnDir: m ? 'column' : 'row', upBtnAlign: m ? 'stretch' : 'flex-start', cardPad: m ? '16px' : '20px', cardPadX: m ? '16px' : '20px', inH: m ? '44px' : '40px', pfCols: m ? 'minmax(0,1fr)' : 'minmax(0,1fr) minmax(0,1.4fr)', pwDir: m ? 'column' : 'row', pwAlign: m ? 'stretch' : 'flex-end', edTitle, edBody: e.body || '', sampleBody: !e.body, tabs, rows, save, counter, pub, mFields, up, toasts, endpoints, toolbar,
|
||||||
desk: !m, mob: m, notBoot: !s.boot,
|
desk: !m, mob: m, notBoot: !s.boot,
|
||||||
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
|
fw: m ? '390px' : '1440px', fh: m ? '844px' : '900px', dir: m ? 'column' : 'row',
|
||||||
mLead: s.mLead || 'menu',
|
mLead: s.mLead || 'menu',
|
||||||
isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isError: k === 'error', isUsers: k === 'users',
|
isBoot: !!s.boot, isHome: k === 'home' && !s.boot, isList: k === 'articles', isEditor: k === 'editor', isInteg: k === 'integration', isError: k === 'error', isUsers: k === 'users',
|
||||||
usRows, usError: !!US.error, usOnly: !!US.only && !US.error, usTable: !m && !US.error, usCards: m && !US.error,
|
usRows, usError: !!US.error, usOnly: !!US.only && !US.error, usTable: !m && !US.error, usCards: m && !US.error,
|
||||||
pad: m ? '20px 16px 88px' : '32px', gap: m ? '20px' : '28px', cols3: m ? 'repeat(3,minmax(0,1fr))' : 'repeat(3,minmax(0,1fr))',
|
pad: m ? '20px 16px 88px' : '32px', gap: m ? '20px' : '28px', cols3: m ? 'repeat(3,minmax(0,1fr))' : 'repeat(3,minmax(0,1fr))',
|
||||||
btnH: m ? '44px' : '32px', rowH: m ? '52px' : '44px', inF: m ? '16px' : '14px',
|
upBannerAlign: m ? 'stretch' : 'center', upCmdDir: m ? 'column' : 'row', btnH: m ? '44px' : '32px', rowH: m ? '52px' : '44px', inF: m ? '16px' : '14px',
|
||||||
tbDir: m ? 'column' : 'row', tbGap: m ? '12px' : '16px', tbBorder: m ? '0' : '1px solid var(--ui-border)', tabBorder: m ? '1px solid var(--ui-border)' : '0', tabH: m ? '44px' : '36px', tabF: m ? '14px' : '13px',
|
tbDir: m ? 'column' : 'row', tbGap: m ? '12px' : '16px', tbBorder: m ? '0' : '1px solid var(--ui-border)', tabBorder: m ? '1px solid var(--ui-border)' : '0', tabH: m ? '44px' : '36px', tabF: m ? '14px' : '13px',
|
||||||
qText: L.q ? L.q : 'Search by title', qFg: L.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)',
|
qText: L.q ? L.q : 'Search by title', qFg: L.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)',
|
||||||
showTable: !m && !L.empty, showCards: m && !L.empty, listFab: !s.modal,
|
showTable: !m && !L.empty, showCards: m && !L.empty, listFab: !s.modal,
|
||||||
|
|||||||
@@ -0,0 +1,276 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<script src="./support.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<x-dc>
|
||||||
|
<div style="display:contents">{{ view }}</div>
|
||||||
|
</x-dc>
|
||||||
|
<script type="text/x-dc" data-dc-script data-props="{"$preview":{"width":1440,"height":900},"s":{"editor":null,"tsType":"object"},"mobile":{"editor":null,"tsType":"boolean"}}">
|
||||||
|
class Component extends DCLogic {
|
||||||
|
renderVals() {
|
||||||
|
const s = this.props.s || {}, m = !!this.props.mobile, h = React.createElement
|
||||||
|
const P = t => Object.fromEntries(t.split(';').filter(x => x.trim()).map(x => { const i = x.indexOf(':'); const k = x.slice(0, i).trim(); return [k.startsWith('--') ? k : k.replace(/-([a-z])/g, (_, c) => c.toUpperCase()), x.slice(i + 1).trim()] }))
|
||||||
|
const D = (t, ...c) => h('div', { style: P(t) }, ...c)
|
||||||
|
const S = (t, ...c) => h('span', { style: P(t) }, ...c)
|
||||||
|
const I = (n, z = 16, t = '') => h('span', { 'aria-hidden': 'true', style: { display: 'inline-block', flexShrink: 0, width: z, height: z, backgroundColor: 'currentColor', WebkitMask: 'url(https://api.iconify.design/lucide/' + n + '.svg) center / contain no-repeat', mask: 'url(https://api.iconify.design/lucide/' + n + '.svg) center / contain no-repeat', ...(t ? P(t) : {}) } })
|
||||||
|
const bh = m ? 44 : 32
|
||||||
|
const B = (label, o = {}) => {
|
||||||
|
const k = o.k || 'outline'
|
||||||
|
const bg = k === 'primary' ? 'var(--ui-primary)' : k === 'danger' ? 'var(--ui-error)' : k === 'inv' ? 'transparent' : 'var(--ui-bg)'
|
||||||
|
const fg = k === 'primary' || k === 'danger' ? 'var(--ui-bg)' : k === 'del' ? 'var(--ui-error)' : k === 'inv' ? 'var(--ui-text-inverted)' : 'var(--ui-text-highlighted)'
|
||||||
|
const bd = k === 'primary' || k === 'danger' ? bg : k === 'inv' ? 'var(--ui-text-inverted)' : 'var(--ui-border-accented)'
|
||||||
|
return S('height:' + (o.h || bh) + 'px;padding:0 ' + (o.px || 12) + 'px;display:flex;align-items:center;justify-content:center;gap:6px;background:' + bg + ';color:' + fg + ';border:1px solid ' + bd + ';font-weight:500;font-size:' + (o.fs || 13) + 'px;white-space:nowrap;opacity:' + (o.dis ? 0.4 : 1) + ';' + (o.full ? 'flex:1;' : '') + (o.ring ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), o.icon && I(o.icon, o.z || 16), label)
|
||||||
|
}
|
||||||
|
const CHECK = 'conic-gradient(var(--ui-bg-accented) 25%, var(--ui-bg) 0 50%, var(--ui-bg-accented) 0 75%, var(--ui-bg) 0) 0 0/16px 16px'
|
||||||
|
const TONES = ['var(--rc-sand)', 'var(--ui-bg-accented)', 'color-mix(in srgb, var(--ui-border-accented) 35%, var(--ui-bg))', 'var(--ui-bg-elevated)']
|
||||||
|
const mark = h('svg', { width: 28, height: 28, viewBox: '0 0 16 16', shapeRendering: 'crispEdges' }, h('rect', { width: 16, height: 16, fill: '#111' }), h('path', { fill: '#fff', fillRule: 'evenodd', d: 'M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z' }))
|
||||||
|
const Th = (im, t = '', z = 24) => D('position:relative;overflow:hidden;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted);background:' + (im.alpha ? CHECK : 'repeating-linear-gradient(135deg, rgb(128 128 128 / 0.12) 0 1px, transparent 1px 12px), ' + TONES[im.tone % 4]) + ';' + t, im.svg ? mark : I('image', z, 'opacity:0.55'))
|
||||||
|
const BADGE = { unused: ['background:var(--rc-warning-soft);color:var(--ui-warning)', 'unlink'], dup: ['background:var(--rc-info-soft);color:var(--ui-info)', 'copy'], used: ['border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)'], on: ['background:var(--ui-bg-inverted);color:var(--ui-text-inverted)', 'globe'], draft: ['border:1px solid var(--ui-border-accented);color:var(--ui-text-toned)', 'pencil-line'] }
|
||||||
|
const Bd = (t, k, sz = 20) => S('height:' + sz + 'px;padding:0 6px;display:inline-flex;align-items:center;gap:4px;font-size:12px;font-weight:500;white-space:nowrap;' + BADGE[k][0], BADGE[k][1] && I(BADGE[k][1], 12), t)
|
||||||
|
const Cb = (on, z = 20, ind) => S('width:' + z + 'px;height:' + z + 'px;flex-shrink:0;display:flex;align-items:center;justify-content:center;border:1px solid ' + (on || ind ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';background:' + (on || ind ? 'var(--ui-primary)' : 'var(--ui-bg)') + ';color:var(--ui-bg)', (on || ind) && I(ind ? 'minus' : 'check', z - 6))
|
||||||
|
const Alert = (tone, icon, title, text, action, actionEl) => D('display:flex;gap:10px;padding:12px 14px;background:var(--rc-' + tone + '-soft);color:var(--ui-' + tone + ')', S('display:flex;padding-top:2px', I(icon)), D('flex:1;display:flex;flex-direction:column;gap:8px', D('display:flex;flex-direction:column;gap:2px', S('font-weight:600', title), S('color:var(--ui-text-toned)', text)), action && B(action, { icon: 'rotate-cw', h: m ? 44 : 28, fs: 12, z: 14, ...(actionEl || {}) })))
|
||||||
|
const Empty = (icon, title, text, action, primary, pad = 56) => D('background:var(--ui-bg);border:1px solid var(--ui-border);padding:' + pad + 'px 24px;display:flex;flex-direction:column;align-items:center;gap:12px;text-align:center', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center;background:var(--ui-bg-elevated);color:var(--ui-text-toned)', I(icon, 20)), S('font-weight:600;font-size:15px;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-muted);max-width:320px', text), action && B(action, { k: primary ? 'primary' : 'outline', icon: primary ? 'upload' : null, px: 16 }))
|
||||||
|
const Note = t => S('align-self:flex-start;height:20px;padding:0 6px;display:inline-flex;align-items:center;border:1px dashed var(--ui-border-accented);color:var(--ui-text-toned);font:500 11px \'IBM Plex Mono\',monospace', t)
|
||||||
|
|
||||||
|
const IM = [
|
||||||
|
{ id: 1, n: 'north-wall.jpg', sz: '3.9 MB', dim: '4032 × 3024', ty: 'JPEG', used: 2, by: 'Marta Alves', d: '12 Sep 2026', tone: 0 },
|
||||||
|
{ id: 2, n: 'kitchen-after.webp', sz: '1.2 MB', dim: '2400 × 1600', ty: 'WEBP', used: 3, by: 'Inès Duarte', d: '8 Sep 2026', tone: 1 },
|
||||||
|
{ id: 3, n: 'kitchen-before.webp', sz: '1.1 MB', dim: '2400 × 1600', ty: 'WEBP', used: 1, by: 'Inès Duarte', d: '8 Sep 2026', tone: 2 },
|
||||||
|
{ id: 4, n: 'logo-renew.svg', sz: '8 KB', dim: 'Vector', ty: 'SVG', used: 5, by: 'jonas', d: '5 Sep 2026', alpha: true, svg: true, tone: 3 },
|
||||||
|
{ id: 5, n: 'floorboards-copy.jpg', sz: '2.4 MB', dim: '3600 × 2400', ty: 'JPEG', used: 3, by: 'Marta Alves', d: '2 Sep 2026', dup: true, tone: 0 },
|
||||||
|
{ id: 6, n: 'IMG_2208.jpg', sz: '2.4 MB', dim: '3600 × 2400', ty: 'JPEG', used: 2, by: 'jonas', d: '30 Aug 2026', dup: true, tone: 0 },
|
||||||
|
{ id: 7, n: 'IMG_4471.jpg', sz: '3.1 MB', dim: '3600 × 2400', ty: 'JPEG', used: 2, by: 'Marta Alves', d: '29 Aug 2026', dup: true, tone: 2 },
|
||||||
|
{ id: 8, n: 'window-frame.jpg', sz: '1.8 MB', dim: '3000 × 2000', ty: 'JPEG', used: 0, by: 'Inès Duarte', d: '28 Aug 2026', tone: 3 },
|
||||||
|
{ id: 9, n: 'stone-wall-detail.jpg', sz: '3.1 MB', dim: '3600 × 2400', ty: 'JPEG', used: 1, by: 'jonas', d: '21 Aug 2026', dup: true, tone: 2 },
|
||||||
|
{ id: 10, n: 'bathroom-tiles.png', sz: '860 KB', dim: '1800 × 1200', ty: 'PNG', used: 0, by: 'Marta Alves', d: '4 Aug 2026', alpha: true, tone: 1 },
|
||||||
|
{ id: 11, n: 'lime-plaster.jpg', sz: '2.1 MB', dim: '3200 × 2133', ty: 'JPEG', used: 2, by: 'Inès Duarte', d: '19 Jul 2026', tone: 1 },
|
||||||
|
{ id: 12, n: 'floorboards.jpg', sz: '2.4 MB', dim: '3600 × 2400', ty: 'JPEG', used: 4, by: 'Inès Duarte', d: '14 Jun 2026', dup: true, tone: 0 }
|
||||||
|
]
|
||||||
|
const byId = id => IM.find(x => x.id === id)
|
||||||
|
const AR = [['How we price a bathroom renovation', 1], ['Winter checklist for timber windows', 0], ['Before and after: the Rue Verte kitchen', 1], ['Why we reuse original floorboards', 1], ['Choosing lime plaster for old stone walls', 0]]
|
||||||
|
const usedList = n => AR.slice(0, Math.min(n, 5))
|
||||||
|
const ids = s.ids || IM.map(x => x.id)
|
||||||
|
const imgs = ids.map(byId)
|
||||||
|
const sel = s.sel || []
|
||||||
|
const pl = n => n + (n === 1 ? ' article' : ' articles')
|
||||||
|
const label = im => im.n + ', ' + im.sz + ', ' + (im.used ? 'used in ' + pl(im.used) : 'unused')
|
||||||
|
const usedBadge = im => im.used ? Bd('Used in ' + im.used, 'used') : Bd('Unused', 'unused')
|
||||||
|
|
||||||
|
// ---------- Media page pieces
|
||||||
|
const Card = im => {
|
||||||
|
const on = sel.includes(im.id), hov = s.hover === im.id, foc = s.focus === im.id
|
||||||
|
const showCb = m || on || hov || foc || sel.length > 0
|
||||||
|
return D('position:relative;display:flex;flex-direction:column;background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? '#111111' : 'var(--ui-text)') + ';border:1px solid ' + (on ? 'var(--ui-primary)' : hov ? 'var(--ui-border-accented)' : 'var(--ui-border)') + ';' + (on ? 'box-shadow:inset 0 0 0 1px var(--ui-primary);' : hov ? 'box-shadow:var(--rc-shadow-pop);' : '') + (foc ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''),
|
||||||
|
Th(im, 'aspect-ratio:4/3;border-bottom:1px solid ' + (on ? 'var(--ui-primary)' : 'var(--ui-border)')),
|
||||||
|
showCb && S('position:absolute;top:0;left:0;width:' + (m ? 44 : 36) + 'px;height:' + (m ? 44 : 36) + 'px;display:flex;align-items:center;justify-content:center', Cb(on, m ? 22 : 20)),
|
||||||
|
D('padding:10px 12px;display:flex;flex-direction:column;gap:6px;min-width:0', D('display:flex;flex-direction:column;gap:2px;min-width:0', S('font-weight:500;color:' + (on ? '#111111' : 'var(--ui-text-highlighted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), S('font-size:12px;color:' + (on ? '#444444' : 'var(--ui-text-muted)') + ';white-space:nowrap;overflow:hidden;text-overflow:ellipsis', im.sz + ' · ' + im.dim)),
|
||||||
|
D('display:flex;flex-wrap:wrap;gap:4px', im.dup && Bd('Duplicate', 'dup'), usedBadge(im))))
|
||||||
|
}
|
||||||
|
const Grid = () => D('display:grid;grid-template-columns:repeat(' + (m ? 2 : 5) + ',minmax(0,1fr));gap:' + (m ? 10 : 16) + 'px', ...imgs.map(Card))
|
||||||
|
const Skel = () => D('display:grid;grid-template-columns:repeat(' + (m ? 2 : 5) + ',minmax(0,1fr));gap:' + (m ? 10 : 16) + 'px', ...Array.from({ length: m ? 6 : 10 }, () => D('background:var(--ui-bg);border:1px solid var(--ui-border)', S('display:block;aspect-ratio:4/3;background:var(--ui-bg-accented)'), D('padding:10px 12px;display:flex;flex-direction:column;gap:8px', S('display:block;width:70%;height:13px;background:var(--ui-bg-accented)'), S('display:block;width:45%;height:11px;background:var(--ui-bg-accented)'), S('display:block;width:60px;height:20px;background:var(--ui-bg-accented)')))))
|
||||||
|
const usedLink = im => im.used ? S('text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', pl(im.used)) : Bd('Unused', 'unused')
|
||||||
|
const Table = () => {
|
||||||
|
const cols = '36px minmax(0,1.7fr) 110px 76px 64px 120px 130px 100px'
|
||||||
|
const hd = D('display:grid;grid-template-columns:' + cols + ';height:36px;align-items:center;padding:0 12px 0 0;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500', S('display:flex;justify-content:center', Cb(false, 18, sel.length > 0 && sel.length < imgs.length)), S('', 'Filename'), S('', 'Dimensions'), S('', 'Size'), S('', 'Type'), S('', 'Used in'), S('', 'Uploaded by'), S('display:flex;align-items:center;gap:4px;color:var(--ui-text-highlighted)', 'Uploaded', I('arrow-down', 12)))
|
||||||
|
return D('background:var(--ui-bg);border:1px solid var(--ui-border)', hd, ...imgs.map(im => {
|
||||||
|
const on = sel.includes(im.id), hov = s.hover === im.id
|
||||||
|
return D('display:grid;grid-template-columns:' + cols + ';height:56px;align-items:center;padding:0 12px 0 0;border-top:1px solid var(--ui-border);background:' + (on ? 'var(--rc-sand)' : hov ? 'var(--ui-bg-elevated)' : 'var(--ui-bg)') + ';color:' + (on ? '#111111' : 'var(--ui-text-muted)'),
|
||||||
|
S('display:flex;justify-content:center', Cb(on, 18)),
|
||||||
|
D('display:flex;align-items:center;gap:12px;min-width:0;padding-right:12px', Th(im, 'width:40px;height:40px;flex-shrink:0;border:1px solid var(--ui-border)', 16), S('font-weight:500;color:' + (on ? '#111111' : 'var(--ui-text-highlighted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), im.dup && Bd('Duplicate', 'dup')),
|
||||||
|
S('', im.dim), S('', im.sz), S('', im.ty), S('', usedLink(im)), S('overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-right:8px', im.by), S('', im.d))
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
const Cards = () => D('background:var(--ui-bg);border:1px solid var(--ui-border);margin:0 -16px;border-left:0;border-right:0', ...imgs.map(im => {
|
||||||
|
const on = sel.includes(im.id)
|
||||||
|
return D('display:flex;align-items:center;gap:0;min-height:80px;padding:8px 12px 8px 0;border-bottom:1px solid var(--ui-border);background:' + (on ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (on ? '#444444' : 'var(--ui-text-muted)'),
|
||||||
|
S('width:44px;height:44px;flex-shrink:0;display:flex;align-items:center;justify-content:center', Cb(on, 22)),
|
||||||
|
Th(im, 'width:56px;height:56px;flex-shrink:0;border:1px solid var(--ui-border)', 20),
|
||||||
|
D('flex:1;min-width:0;display:flex;flex-direction:column;gap:3px;padding-left:12px', S('font-weight:500;font-size:15px;color:' + (on ? '#111111' : 'var(--ui-text-highlighted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), S('font-size:12px', im.sz + ' · ' + im.dim + ' · ' + im.ty), D('display:flex;flex-wrap:wrap;gap:4px;align-items:center;font-size:12px', im.dup && Bd('Duplicate', 'dup'), usedBadge(im), S('', im.by + ' · ' + im.d))),
|
||||||
|
I('chevron-right', 16, 'margin-left:8px'))
|
||||||
|
}))
|
||||||
|
|
||||||
|
const dg = s.dupEmpty ? 0 : s.dupGroups ?? 2
|
||||||
|
const tabs = [['all', 'All', String(imgs.length)], ['unused', 'Unused', String(imgs.filter(x => !x.used).length)], ['dups', 'Duplicates', String(dg)]]
|
||||||
|
const tab = s.tab || 'all'
|
||||||
|
const TabRow = () => D('display:flex;gap:20px;flex:1;' + (m ? 'border-bottom:1px solid var(--ui-border)' : ''), ...tabs.map(([k, t, n]) => S('height:' + (m ? 44 : 36) + 'px;display:flex;align-items:center;gap:6px;border-bottom:2px solid ' + (tab === k ? 'var(--ui-primary)' : 'transparent') + ';margin-bottom:-1px;font-weight:' + (tab === k ? 500 : 400) + ';color:' + (tab === k ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)') + ';font-size:' + (m ? 15 : 13) + 'px', t, k === 'dups' ? (dg > 0 && S('height:18px;min-width:18px;padding:0 5px;display:inline-flex;align-items:center;justify-content:center;background:var(--rc-info-soft);color:var(--ui-info);font:500 11px \'IBM Plex Mono\',monospace', n)) : S('font:500 11px \'IBM Plex Mono\',monospace;color:var(--ui-text-muted)', n))))
|
||||||
|
const Search = () => D('height:' + (m ? 44 : 32) + 'px;' + (m ? '' : 'width:240px;margin-bottom:0;') + 'padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:' + (s.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (m ? ';font-size:16px' : ''), I('search', 14), S('flex:1', s.q || 'Search by filename'), s.q && S('width:' + (m ? 36 : 24) + 'px;height:' + (m ? 36 : 24) + 'px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14)))
|
||||||
|
const Sort = () => D('height:' + (m ? 44 : 32) + 'px;padding:0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:var(--ui-text-highlighted);' + (m ? 'flex:1;' : 'width:128px;'), S('flex:1', s.sort || 'Newest'), I('chevron-down', 14, 'color:var(--ui-text-muted)'))
|
||||||
|
const view = s.view || 'grid'
|
||||||
|
const Toggle = () => D('display:flex;border:1px solid var(--ui-border-accented);flex-shrink:0', ...[['grid', 'layout-grid'], ['list', 'list']].map(([k, ic]) => S('width:' + (m ? 44 : 32) + 'px;height:' + (m ? 42 : 30) + 'px;display:flex;align-items:center;justify-content:center;background:' + (view === k ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (view === k ? '#111111' : 'var(--ui-text-toned)'), I(ic))))
|
||||||
|
const SelectAll = () => D('display:flex;align-items:center;gap:10px;color:var(--ui-text-muted)', m ? S('width:44px;height:44px;margin-left:-11px;display:flex;align-items:center;justify-content:center', Cb(false, 22, sel.length > 0)) : Cb(false, 18, sel.length > 0), S('color:var(--ui-text-highlighted);font-weight:500', 'Select all'), S('', imgs.length + ' images'))
|
||||||
|
|
||||||
|
const UP = s.upload
|
||||||
|
const upRow = r => {
|
||||||
|
const sc = { err: 'var(--ui-error)', dup: 'var(--ui-info)' }[r.st] || 'var(--ui-text-muted)'
|
||||||
|
const body = {
|
||||||
|
prog: [S('', 'Uploading ' + r.p), D('width:100%;height:4px;background:var(--ui-bg-accented)', D('width:' + r.pct + ';height:4px;background:var(--ui-primary)'))],
|
||||||
|
wait: [S('color:var(--ui-text-muted)', 'Waiting')],
|
||||||
|
ok: [S('display:flex;align-items:center;gap:6px;color:var(--ui-success)', I('circle-check', 14), 'Added to your library')],
|
||||||
|
dup: [S('font-weight:600;color:var(--ui-text-highlighted)', 'Already in your library'), S('color:var(--ui-text-toned);font-size:12px', r.msg), D('display:flex;gap:8px;flex-wrap:wrap', B('Use existing', { h: m ? 44 : 28, fs: 12, px: 10, full: m }), B('Upload anyway', { h: m ? 44 : 28, fs: 12, px: 10, full: m }))],
|
||||||
|
rej: [S('display:flex;gap:6px;align-items:center;font-weight:600;color:var(--ui-error)', I('file-x', 14), r.title), S('color:var(--ui-text-toned);font-size:12px', r.msg)],
|
||||||
|
fail: [S('display:flex;gap:6px;align-items:center;font-weight:600;color:var(--ui-error)', I('circle-x', 14), 'Upload failed'), S('color:var(--ui-text-toned);font-size:12px', 'The server didn\'t accept the file. Nothing was added to your library.'), D('display:flex', B('Try again', { icon: 'rotate-cw', z: 14, h: m ? 44 : 28, fs: 12, px: 10, full: m }))]
|
||||||
|
}[r.st]
|
||||||
|
return D('display:flex;gap:12px;align-items:flex-start;padding:12px 14px;border-top:1px solid var(--ui-border-muted)', Th(byId(r.im || 8), 'width:40px;height:40px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('flex:1;min-width:0;display:flex;flex-direction:column;gap:6px', D('display:flex;justify-content:space-between;gap:8px', S('font-weight:500;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', r.n), S('color:var(--ui-text-muted);white-space:nowrap', r.sz)), ...body), r.st === 'prog' && S('width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14)))
|
||||||
|
}
|
||||||
|
const UpPanel = () => D('background:var(--ui-bg);border:1px solid var(--ui-border);display:flex;flex-direction:column', D('display:flex;align-items:center;gap:12px;padding:12px 14px', D('flex:1;display:flex;flex-direction:column;gap:2px', S('font-weight:600;color:var(--ui-text-highlighted)', UP.title), S('color:var(--ui-text-muted)', UP.sub)), UP.done ? B('Dismiss', { h: m ? 44 : 28, fs: 12 }) : B('Cancel all', { h: m ? 44 : 28, fs: 12 })), ...UP.rows.map(upRow), UP.summary && D('padding:12px 14px;border-top:1px solid var(--ui-border);background:var(--ui-bg-elevated);color:var(--ui-text-toned);font-weight:500', UP.summary))
|
||||||
|
|
||||||
|
const Groups = () => {
|
||||||
|
const G = [
|
||||||
|
{ n: 'floorboards.jpg', sub: '3 identical images · 2.4 MB each · 3600 × 2400', c: [12, 5, 6], keep: 12 },
|
||||||
|
{ n: 'IMG_4471.jpg', sub: '2 identical images · 3.1 MB each · 3600 × 2400', c: [7, 9], keep: 7 }
|
||||||
|
]
|
||||||
|
return D('display:flex;flex-direction:column;gap:16px', ...G.slice(2 - dg).map((g, gi) => D('background:var(--ui-bg);border:1px solid var(--ui-border)', D('padding:12px 14px;border-bottom:1px solid var(--ui-border);display:flex;flex-direction:column;gap:2px', S('font-weight:600;color:var(--ui-text-highlighted)', 'Group ' + (gi + 1)), S('color:var(--ui-text-muted)', g.sub)),
|
||||||
|
D('display:grid;grid-template-columns:' + (m ? 'minmax(0,1fr)' : 'repeat(' + g.c.length + ',minmax(0,1fr))') + ';gap:' + (m ? 0 : 16) + 'px;padding:' + (m ? 0 : 16) + 'px', ...g.c.map(id => {
|
||||||
|
const im = byId(id), k = id === g.keep
|
||||||
|
const others = g.c.filter(x => x !== id).length
|
||||||
|
return D('display:flex;' + (m ? 'flex-direction:column;gap:12px;padding:14px;border-bottom:1px solid var(--ui-border-muted)' : 'flex-direction:column;gap:12px;padding:12px;border:1px solid ' + (k ? 'var(--ui-primary)' : 'var(--ui-border)')) + ';background:' + (k ? 'var(--rc-sand)' : 'var(--ui-bg)') + ';color:' + (k ? '#111111' : 'var(--ui-text)'),
|
||||||
|
D('display:flex;gap:12px;' + (m ? 'align-items:flex-start' : 'flex-direction:column'), Th(im, (m ? 'width:96px;height:72px;flex-shrink:0' : 'aspect-ratio:4/3') + ';border:1px solid var(--ui-border)'),
|
||||||
|
D('display:flex;flex-direction:column;gap:4px;min-width:0', D('display:flex;gap:6px;align-items:center;flex-wrap:wrap', S('font-weight:500;color:' + (k ? '#111111' : 'var(--ui-text-highlighted)') + ';overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), k && S('height:20px;padding:0 6px;display:inline-flex;align-items:center;background:var(--ui-primary);color:var(--ui-bg);font-size:12px;font-weight:500', 'Suggested')),
|
||||||
|
S('font-size:12px;color:' + (k ? '#444444' : 'var(--ui-text-muted)'), 'Uploaded ' + im.d + ' by ' + im.by),
|
||||||
|
S('font-weight:500;text-decoration:underline;text-underline-offset:3px', 'Used in ' + pl(im.used)))),
|
||||||
|
B('Merge into this one', { k: k ? 'primary' : 'outline', full: false, icon: 'merge', h: bh }))
|
||||||
|
})),
|
||||||
|
D('padding:10px 14px;border-top:1px solid var(--ui-border);color:var(--ui-text-muted);font-size:12px', 'Suggested: the most used copy, then the oldest. Choosing another copy switches articles to it.'))))
|
||||||
|
}
|
||||||
|
|
||||||
|
const Header = () => D('display:flex;align-items:flex-end;gap:16px;flex-wrap:wrap', D('flex:1;min-width:200px;display:flex;flex-direction:column;gap:2px', S('font:600 20px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'Media'), S('color:var(--ui-text-muted)', 'Every image you\'ve uploaded, ready to use in any article.')), !m && (s.limited ? B('Try again in 0:42', { k: 'primary', icon: 'timer', dis: true }) : B('Upload', { k: 'primary', icon: 'upload', dis: s.offline })))
|
||||||
|
|
||||||
|
const pageBody = () => {
|
||||||
|
const parts = []
|
||||||
|
if (s.empty === 'first') { parts.push(Empty('images', 'No images yet', 'Upload your first image. You can use it in any article.', 'Upload an image', true), S('align-self:center;color:var(--ui-text-muted);font-size:12px', 'PNG, JPEG, WEBP, SVG · max 10 MB each')); return parts }
|
||||||
|
if (s.limited) parts.push(Alert('info', 'timer', 'Too many uploads', 'For your security, wait a moment before uploading again.'))
|
||||||
|
if (s.error) parts.push(Alert('error', 'circle-x', 'Couldn\'t load your images', 'Check your connection and try again.', 'Try again'))
|
||||||
|
const tb = m
|
||||||
|
? D('display:flex;flex-direction:column;gap:12px', Search(), TabRow(), D('display:flex;gap:8px', Sort(), Toggle()))
|
||||||
|
: D('display:flex;align-items:flex-end;gap:12px;border-bottom:1px solid var(--ui-border)', TabRow(), S('display:flex;padding-bottom:6px;gap:8px', Search(), Sort(), Toggle()))
|
||||||
|
parts.push(tb)
|
||||||
|
if (UP) parts.push(UpPanel())
|
||||||
|
if (s.loading) parts.push(Skel())
|
||||||
|
else if (s.error) { }
|
||||||
|
else if (s.empty === 'search') parts.push(Empty('search', 'No images match "wall"', 'Nothing matches in Unused. Check the spelling, or clear the filters.', 'Clear filters', false))
|
||||||
|
else if (tab === 'dups') parts.push(s.dupEmpty ? Empty('copy', 'No duplicates', 'Every image in your library is different.', 'Back to all images', false) : Groups())
|
||||||
|
else {
|
||||||
|
if (view === 'grid') parts.push(SelectAll(), Grid()); else parts.push(m ? Cards() : Table())
|
||||||
|
}
|
||||||
|
return parts
|
||||||
|
}
|
||||||
|
const BulkBar = () => D('position:absolute;z-index:30;bottom:' + (m ? 16 : 24) + 'px;' + (m ? 'left:16px;right:16px' : 'left:calc(224px + (100% - 224px) / 2);transform:translateX(-50%);width:400px') + ';display:flex;align-items:center;gap:8px;padding:8px 8px 8px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted);box-shadow:var(--rc-shadow-pop)', S('flex:1;font-weight:500', sel.length + ' selected'), B('Delete', { k: 'danger', icon: 'trash-2' }), B('Clear', { k: 'inv' }))
|
||||||
|
|
||||||
|
// ---------- detail panel
|
||||||
|
const Panel = () => {
|
||||||
|
const im = byId(s.panel.id), list = usedList(im.used)
|
||||||
|
const meta = [['Type', im.ty], ['Size', im.sz], ['Dimensions', im.dim], ['Uploaded', im.d], ['Uploaded by', im.by]]
|
||||||
|
const w = m ? '100%' : '460px'
|
||||||
|
return D('position:absolute;inset:0;z-index:40;display:flex;justify-content:flex-end;background:' + (m ? 'var(--ui-bg)' : 'var(--rc-overlay)'),
|
||||||
|
D('width:' + w + ';height:100%;background:var(--ui-bg);display:flex;flex-direction:column;' + (m ? '' : 'box-shadow:var(--rc-shadow-modal)'),
|
||||||
|
D('height:' + (m ? 56 : 56) + 'px;flex-shrink:0;display:flex;align-items:center;gap:' + (m ? 4 : 12) + 'px;padding:0 ' + (m ? 6 : 20) + 'px;border-bottom:1px solid var(--ui-border)', m && S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I('arrow-left', 20)), S('flex:1;min-width:0;font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n), !m && S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
|
||||||
|
D('flex:1;min-height:0;overflow:hidden;padding:' + (m ? 16 : 20) + 'px;display:flex;flex-direction:column;gap:20px',
|
||||||
|
Th(im, 'aspect-ratio:' + (m ? '4/3' : '16/10') + ';border:1px solid var(--ui-border);flex-shrink:0', 40),
|
||||||
|
D('display:flex;gap:8px;' + (m ? 'flex-wrap:wrap' : ''), B('Copy URL', { icon: 'link', full: m }), B('Rename', { icon: 'pencil', full: m }), B('Delete', { k: 'del', icon: 'trash-2', full: m })),
|
||||||
|
im.dup && Alert('info', 'copy', 'Identical to 2 other images', 'floorboards-copy.jpg and IMG_2208.jpg have the same content.', 'Review duplicates', { icon: 'arrow-right' }),
|
||||||
|
D('display:grid;grid-template-columns:110px minmax(0,1fr);gap:8px 12px;color:var(--ui-text-toned)', ...meta.flatMap(([k, v]) => [S('color:var(--ui-text-muted)', k), S('color:var(--ui-text-highlighted)', v)]), S('color:var(--ui-text-muted)', 'URL'), S('font:400 12px/20px \'IBM Plex Mono\',monospace;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', 'cms.renew.example/media/' + im.n)),
|
||||||
|
D('display:flex;flex-direction:column;gap:8px', S('font:600 14px/22px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', im.used ? 'Used in ' + pl(im.used) : 'Not used in any article'),
|
||||||
|
im.used ? D('border:1px solid var(--ui-border)', ...list.map(([t, on], i) => D('display:flex;align-items:center;gap:8px;min-height:' + (m ? 48 : 40) + 'px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500;text-decoration:underline;text-underline-offset:3px;color:var(--ui-text-highlighted)', t), on ? Bd('Online', 'on', 22) : Bd('Draft', 'draft', 22), I('arrow-up-right', 14, 'color:var(--ui-text-muted)'))))
|
||||||
|
: S('color:var(--ui-text-muted)', 'This image is safe to delete. No article shows it.'),
|
||||||
|
im.used ? S('color:var(--ui-text-muted);font-size:12px', 'Counted from the text of your articles each time you open this page.') : null))))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- modal
|
||||||
|
const Field = (lab, val, o = {}) => D('display:flex;flex-direction:column;gap:6px', D('display:flex;justify-content:space-between', S('font-weight:500;color:var(--ui-text-highlighted)', lab), o.count && S('font:400 12px \'IBM Plex Mono\',monospace;color:var(--ui-text-muted)', o.count)), D('display:flex;align-items:center;min-height:' + (o.area ? 72 : m ? 44 : 40) + 'px;border:1px solid ' + (o.err ? 'var(--ui-error)' : o.focus ? 'var(--ui-primary)' : 'var(--ui-border-accented)') + ';' + (o.focus ? 'box-shadow:0 0 0 1px var(--ui-primary);' : '') + 'background:var(--ui-bg);font-size:' + (m ? 16 : 13) + 'px;' + (o.area ? 'align-items:flex-start;' : ''), S('flex:1;min-width:0;padding:' + (o.area ? '10px' : '0') + ' 12px;color:' + (o.val ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (o.dis ? ';opacity:.6' : ''), val), o.suffix && S('padding:0 12px;color:var(--ui-text-muted);font:400 13px \'IBM Plex Mono\',monospace', o.suffix)), o.err && S('display:flex;gap:6px;align-items:center;color:var(--ui-error);font-size:12px', I('circle-alert', 14), o.err), o.help && S('color:var(--ui-text-muted);font-size:12px', o.help))
|
||||||
|
const ArtBox = (list, more) => D('border:1px solid var(--ui-border)', ...list.map(([t, on], i) => D('display:flex;align-items:center;gap:8px;min-height:36px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--ui-text-highlighted)', t), on ? Bd('Online', 'on') : Bd('Draft', 'draft'))), more && D('padding:8px 12px;border-top:1px solid var(--ui-border-muted);color:var(--ui-text-muted)', more))
|
||||||
|
const modalCfg = () => {
|
||||||
|
const md = s.modal, k = md.k
|
||||||
|
if (k === 'rename') return { title: 'Rename image', desc: 'Only the filename changes. The URL stays the same, so articles that use this image keep working.', body: [Field('Filename', md.err ? '' : md.val || 'north-wall', { val: !md.err, suffix: '.jpg', focus: !md.loading, err: md.err, dis: md.loading, help: md.err ? '' : 'Letters, numbers, dashes and underscores. The .jpg ending stays.' })], cancel: 'Cancel', confirm: md.loading ? 'Renaming…' : 'Rename' }
|
||||||
|
if (k === 'del') return { title: 'Delete this image?', desc: '"window-frame.jpg" will be deleted from your library. No article uses it. This can\'t be undone.', cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' }
|
||||||
|
if (k === 'delUsed') return { title: 'Delete an image that\'s in use?', desc: '"north-wall.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can\'t be undone.', body: [ArtBox(usedList(2))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete image', tone: 'danger' }
|
||||||
|
if (k === 'bulk') return { title: 'Delete 3 images?', desc: '2 of them are used in 5 articles, which will show a broken image. The other one isn\'t used anywhere. This can\'t be undone.', body: [D('display:flex;flex-direction:column;border:1px solid var(--ui-border)', ...[['north-wall.jpg', 'Used in 2'], ['kitchen-after.webp', 'Used in 3'], ['window-frame.jpg', 'Unused']].map(([n, u], i) => D('display:flex;align-items:center;gap:8px;min-height:36px;padding:0 12px;border-top:' + (i ? '1px solid var(--ui-border-muted)' : '0'), S('flex:1;color:var(--ui-text-highlighted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', n), Bd(u === 'Unused' ? 'Unused' : u, u === 'Unused' ? 'unused' : 'used'))))], cancel: 'Cancel', confirm: md.loading ? 'Deleting…' : 'Delete 3 images', tone: 'danger' }
|
||||||
|
if (k === 'merge') return { title: 'Merge into floorboards.jpg?', desc: 'Articles that use the other 2 copies will be switched to floorboards.jpg, and the other 2 copies will be deleted. 5 articles will be updated. This can\'t be undone.', body: [D('display:flex;gap:12px;align-items:center;border:1px solid var(--ui-border);padding:10px 12px', Th(byId(12), 'width:56px;height:42px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'floorboards.jpg'), S('font-size:12px;color:var(--ui-text-muted)', 'Kept · used in 4 articles now')))], cancel: 'Cancel', confirm: md.loading ? 'Merging…' : 'Merge 2 copies', tone: 'danger' }
|
||||||
|
if (k === 'remove') return { title: 'Remove this image from the article?', desc: 'It\'s removed from this article only. The file stays in your library and in any other article that uses it.', body: [D('display:flex;gap:12px;align-items:center;border:1px solid var(--ui-border);padding:10px 12px', Th(byId(1), 'width:56px;height:42px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', 'north-wall.jpg'), S('font-size:12px;color:var(--ui-text-muted)', 'Stays in the library · 3.9 MB')))], cancel: 'Cancel', confirm: 'Remove image' }
|
||||||
|
}
|
||||||
|
const Shell = (o, body) => D('position:absolute;inset:0;z-index:50;background:var(--rc-overlay);display:flex;align-items:' + (m ? 'flex-end' : 'flex-start') + ';justify-content:center;padding:' + (m ? 16 : o.top || 140) + 'px 16px 16px',
|
||||||
|
D('width:' + (m ? '100%' : (o.w || 460) + 'px') + ';max-height:100%;background:var(--ui-bg);box-shadow:var(--rc-shadow-modal);display:flex;flex-direction:column',
|
||||||
|
D('padding:20px 24px 0;display:flex;align-items:flex-start;gap:12px', D('flex:1;display:flex;flex-direction:column;gap:4px', S('font:600 16px/24px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', o.title), o.desc && S('color:var(--ui-text-muted);text-wrap:pretty', o.desc)), o.close && S('width:28px;height:28px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x'))),
|
||||||
|
body,
|
||||||
|
D('padding:20px 24px;display:flex;flex-direction:' + (m ? 'column-reverse' : 'row') + ';justify-content:flex-end;gap:8px;flex-shrink:0', o.cancel && B(o.cancel, { dis: o.loading }), o.confirm && S('height:' + bh + 'px;padding:0 12px;display:flex;align-items:center;justify-content:center;gap:6px;background:' + (o.tone === 'danger' ? 'var(--ui-error)' : 'var(--ui-primary)') + ';color:var(--ui-bg);font-weight:500;opacity:' + (o.cdis ? 0.4 : 1), o.loading && I('loader-circle'), o.confirm))))
|
||||||
|
const Modal = () => {
|
||||||
|
const md = s.modal, c = modalCfg()
|
||||||
|
return Shell(c, D('padding:20px 24px 0;display:flex;flex-direction:column;gap:16px;min-height:0;overflow:hidden', md.notice && D('display:flex;gap:8px;padding:10px 12px;background:var(--rc-error-soft);color:var(--ui-error)', S('display:flex;padding-top:2px', I('circle-x')), S('color:var(--ui-text-toned)', md.notice)), ...(c.body || [])))
|
||||||
|
}
|
||||||
|
const Toasts = () => D('position:absolute;z-index:60;display:flex;flex-direction:column;gap:8px;' + (m ? 'left:16px;right:16px;bottom:' + (s.sel && s.sel.length ? 80 : 16) + 'px' : 'right:24px;bottom:24px;width:356px'), ...s.toasts.map(t => D('display:flex;gap:10px;padding:12px 14px;background:var(--ui-bg);border:1px solid var(--ui-border);box-shadow:var(--rc-shadow-pop)', S('margin-top:2px;display:flex;color:var(--ui-' + t[0] + ')', I(t[1])), D('flex:1;display:flex;flex-direction:column;gap:6px', D('display:flex;flex-direction:column;gap:2px', S('font-weight:600;color:var(--ui-text-highlighted)', t[2]), S('color:var(--ui-text-muted)', t[3])), t[4] && B(t[4], { icon: 'rotate-cw', z: 14, h: m ? 44 : 28, fs: 12, px: 10 })), I('x'))))
|
||||||
|
|
||||||
|
// ---------- picker (editor + dialog)
|
||||||
|
const Editor = () => D('flex:1;min-height:0;overflow:hidden;background:var(--ui-bg-muted);display:flex;flex-direction:column',
|
||||||
|
D('background:var(--ui-bg);border-bottom:1px solid var(--ui-border);padding:12px ' + (m ? 16 : 24) + 'px;display:flex;align-items:center;gap:12px', S('flex:1;font:600 ' + (m ? 16 : 20) + 'px/28px \'IBM Plex Sans\',sans-serif;color:var(--ui-text-highlighted)', 'How we price a bathroom renovation'), !m && B('Save', { dis: true }), !m && B('Publish', { k: 'primary' })),
|
||||||
|
D('flex:1;overflow:hidden;padding:' + (m ? '20px 16px' : '32px 0') + ';display:flex;justify-content:center', D('width:100%;max-width:680px;display:flex;flex-direction:column;gap:16px;font-family:\'Source Serif 4\',serif;font-size:' + (m ? 16 : 18) + 'px;line-height:1.66;color:var(--ui-text-toned)',
|
||||||
|
S('display:block', 'A bathroom is priced by what has to happen behind the walls before anything gets tiled.'),
|
||||||
|
s.inArticle && D('position:relative;aspect-ratio:16/9;border:1px solid var(--ui-border);overflow:hidden', Th(byId(1), 'position:absolute;inset:0', 40), S('position:absolute;top:8px;right:8px;height:28px;padding:0 10px;display:flex;align-items:center;gap:6px;background:var(--ui-bg);border:1px solid var(--ui-border-accented);color:var(--ui-text-highlighted);font:500 12px \'IBM Plex Sans\',sans-serif', I('trash-2', 14), 'Remove image')),
|
||||||
|
S('display:block', 'We don\'t add a margin on materials you choose yourself.'))))
|
||||||
|
const PT = s.pk || {}
|
||||||
|
const pImgs = (PT.ids || [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]).map(byId)
|
||||||
|
const inArt = [1, 4]
|
||||||
|
const cols = m ? 3 : 4
|
||||||
|
const PTile = im => {
|
||||||
|
const on = PT.sel === im.id
|
||||||
|
return D('display:flex;flex-direction:column;gap:6px;min-width:0', D('position:relative;' + (on ? 'outline:2px solid var(--ui-primary);outline-offset:2px;' : ''), Th(im, 'aspect-ratio:1/1;border:1px solid var(--ui-border)', 20),
|
||||||
|
inArt.includes(im.id) && S('position:absolute;left:4px;bottom:4px;height:18px;padding:0 5px;display:flex;align-items:center;background:var(--rc-sand);color:#111111;font-size:11px;font-weight:500', 'In this article'),
|
||||||
|
on && S('position:absolute;top:4px;right:4px;width:20px;height:20px;display:flex;align-items:center;justify-content:center;background:var(--ui-primary);color:var(--ui-bg)', I('check', 14))),
|
||||||
|
S('font-size:12px;color:var(--ui-text-toned);overflow:hidden;text-overflow:ellipsis;white-space:nowrap', im.n))
|
||||||
|
}
|
||||||
|
const PGrid = () => D('display:grid;grid-template-columns:repeat(' + cols + ',minmax(0,1fr));gap:12px ' + (m ? 8 : 12) + 'px', ...pImgs.map(PTile), ...(PT.more ? Array.from({ length: cols }, () => D('display:flex;flex-direction:column;gap:6px', S('display:block;aspect-ratio:1/1;background:var(--ui-bg-accented)'), S('display:block;width:70%;height:10px;background:var(--ui-bg-accented)'))) : []))
|
||||||
|
const PSkel = () => D('display:grid;grid-template-columns:repeat(' + cols + ',minmax(0,1fr));gap:12px ' + (m ? 8 : 12) + 'px', ...Array.from({ length: m ? 9 : 8 }, () => D('display:flex;flex-direction:column;gap:6px', S('display:block;aspect-ratio:1/1;background:var(--ui-bg-accented)'), S('display:block;width:70%;height:10px;background:var(--ui-bg-accented)'))))
|
||||||
|
const PTabs = () => D('display:flex;gap:20px;border-bottom:1px solid var(--ui-border);padding:0 24px;margin-top:16px', ...['Upload', 'Library'].map(t => S('height:' + (m ? 44 : 36) + 'px;display:flex;align-items:center;gap:6px;border-bottom:2px solid ' + (PT.tab === t ? 'var(--ui-primary)' : 'transparent') + ';margin-bottom:-1px;font-weight:' + (PT.tab === t ? 500 : 400) + ';color:' + (PT.tab === t ? 'var(--ui-text-highlighted)' : 'var(--ui-text-toned)'), I(t === 'Upload' ? 'upload' : 'images', 14), t)))
|
||||||
|
const drop = (icon, title, text, bd, ic) => D('height:180px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:16px;text-align:center;border:' + bd + ';background:var(--ui-bg)', I(icon, 24, 'color:' + (ic || 'var(--ui-text-toned)')), S('font-weight:500;color:var(--ui-text-highlighted)', title), S('color:var(--ui-text-toned);font-size:12px;max-width:300px', text))
|
||||||
|
const PBody = () => {
|
||||||
|
if (PT.tab === 'Upload') {
|
||||||
|
if (PT.dup) return D('display:flex;flex-direction:column;gap:12px;padding:16px;border:1px solid var(--ui-info);background:var(--ui-bg)', D('display:flex;gap:12px;align-items:center', Th(byId(1), 'width:72px;height:54px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;gap:2px;min-width:0', S('font-weight:600;color:var(--ui-text-highlighted)', 'Already in your library'), S('color:var(--ui-text-toned);font-size:12px', 'north-wall.jpg matches an image uploaded on 12 Sep 2026 by Marta Alves.'))), D('display:flex;gap:8px;' + (m ? 'flex-direction:column' : ''), B('Use existing', { k: 'primary', full: m }), B('Upload anyway', { full: m })))
|
||||||
|
return drop('image-plus', 'Drop an image here, or choose a file', 'PNG, JPEG, WEBP, SVG · max 10 MB', '1px dashed var(--ui-border-accented)')
|
||||||
|
}
|
||||||
|
const kids = []
|
||||||
|
kids.push(D('height:' + (m ? 44 : 32) + 'px;padding:0 4px 0 10px;display:flex;align-items:center;gap:8px;border:1px solid var(--ui-border-accented);background:var(--ui-bg);color:' + (PT.q ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + (m ? ';font-size:16px' : ''), I('search', 14), S('flex:1', PT.q || 'Search by filename'), PT.q && S('width:24px;height:24px;display:flex;align-items:center;justify-content:center;color:var(--ui-text-muted)', I('x', 14))))
|
||||||
|
if (PT.error) kids.push(Alert('error', 'circle-x', 'Couldn\'t load your library', 'Check your connection and try again.', 'Try again'))
|
||||||
|
else if (PT.empty === 'first') kids.push(Empty('images', 'Your library is empty', 'Images you upload appear here, ready to use in any article.', 'Upload an image', true, 32))
|
||||||
|
else if (PT.empty === 'search') kids.push(Empty('search', 'No images match "wall"', 'Check the spelling, or search for a shorter part of the filename.', 'Clear search', false, 32))
|
||||||
|
else if (PT.loading) kids.push(PSkel())
|
||||||
|
else {
|
||||||
|
kids.push(S('color:var(--ui-text-muted);font-size:12px', 'Newest first · 48 images'), D('min-height:0;overflow:hidden;' + (PT.sel ? 'max-height:' + (m ? 120 : 190) + 'px' : 'max-height:' + (m ? 300 : 300) + 'px'), PGrid()))
|
||||||
|
if (!PT.sel) kids.push(D('display:flex;justify-content:center', B(PT.more ? 'Loading…' : 'Load more', { icon: PT.more ? 'loader-circle' : null, dis: !!PT.more })))
|
||||||
|
}
|
||||||
|
if (PT.sel) { const im = byId(PT.sel); kids.push(D('display:flex;flex-direction:column;gap:12px;padding-top:12px;border-top:1px solid var(--ui-border)', D('display:flex;gap:12px;align-items:center', Th(im, 'width:56px;height:56px;flex-shrink:0;border:1px solid var(--ui-border)', 16), D('display:flex;flex-direction:column;min-width:0', S('font-weight:500;color:var(--ui-text-highlighted)', im.n), S('font-size:12px;color:var(--ui-text-muted)', im.dim + ' · ' + im.sz))), Field('Alt text (optional)', PT.alt || 'e.g. North wall of the kitchen before plastering', { val: !!PT.alt, focus: !!PT.alt, help: 'Describes the image for people who use a screen reader, and shows if it doesn\'t load. Leave it empty if the image is only decoration.' }))) }
|
||||||
|
return D('display:flex;flex-direction:column;gap:12px', ...kids)
|
||||||
|
}
|
||||||
|
const Picker = () => {
|
||||||
|
const ins = PT.tab === 'Library'
|
||||||
|
return Shell({ title: 'Add an image', close: true, w: 640, top: 40, cancel: 'Cancel', confirm: ins ? 'Insert image' : null, cdis: ins && !PT.sel }, D('display:flex;flex-direction:column;min-height:0;flex:1', PTabs(), D('padding:16px 24px 0;min-height:0;overflow:hidden;display:flex;flex-direction:column', PBody())))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- shell
|
||||||
|
const nav = [['home', 'house', 'Home'], ['articles', 'file-text', 'Articles'], ['media', 'images', 'Media'], ['users', 'users', 'Users'], ['integration', 'plug', 'Integration'], ['settings', 'settings', 'Settings']]
|
||||||
|
const isPicker = s.kind === 'picker'
|
||||||
|
const navKey = isPicker ? 'articles' : 'media'
|
||||||
|
const crumbs = isPicker ? ['Articles', 'How we price a bathroom renovation'] : ['Media']
|
||||||
|
const side = D('width:224px;flex-shrink:0;background:var(--ui-bg);border-right:1px solid var(--ui-border);display:flex;flex-direction:column;padding:12px;gap:2px',
|
||||||
|
D('display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;margin-bottom:10px', h('svg', { width: 26, height: 26, viewBox: '0 0 16 16', shapeRendering: 'crispEdges' }, h('rect', { width: 16, height: 16, fill: '#111' }), h('path', { fill: '#fff', fillRule: 'evenodd', d: 'M4 3h6v1h1v1h1v3h-1v1h-1v1h1v1h1v2h-2v-2h-1v-1H6v3H4zm2 2v3h4V5z' })), S('font-weight:600;font-size:14px;color:var(--ui-text-highlighted)', 'RenewCMS')),
|
||||||
|
...nav.map(([k, ic, t]) => D('display:flex;align-items:center;gap:10px;height:32px;padding:0 10px;background:' + (k === navKey ? 'var(--rc-sand)' : 'transparent') + ';color:' + (k === navKey ? '#111111' : 'var(--ui-text-toned)') + ';font-weight:' + (k === navKey ? 500 : 400), I(ic), t)),
|
||||||
|
D('flex:1'), D('display:flex;align-items:center;gap:10px;height:40px;padding:0 6px;color:var(--ui-text-highlighted)', S('width:26px;height:26px;flex-shrink:0;background:#d4c5b0;color:#111;display:flex;align-items:center;justify-content:center;font:600 11px \'IBM Plex Sans\',sans-serif', 'MA'), S('flex:1;font-weight:500', 'Marta Alves'), I('chevrons-up-down', 14)))
|
||||||
|
const topbar = m
|
||||||
|
? D('height:56px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 6px;gap:4px;color:var(--ui-text-highlighted)', S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I(isPicker ? 'arrow-left' : 'menu', 20)), S('flex:1;font-weight:600;font-size:16px', isPicker ? 'Edit article' : 'Media'), isPicker && S('width:44px;height:44px;display:flex;align-items:center;justify-content:center', I('ellipsis', 20)))
|
||||||
|
: D('height:48px;flex-shrink:0;border-bottom:1px solid var(--ui-border);background:var(--ui-bg);display:flex;align-items:center;padding:0 24px;gap:8px;color:var(--ui-text-muted)', I('panel-left-close'), S('width:1px;height:16px;background:var(--ui-border);margin:0 6px'), ...crumbs.flatMap((c, i) => [i > 0 && I('chevron-right', 14), S('color:' + (i === crumbs.length - 1 ? 'var(--ui-text-highlighted)' : 'var(--ui-text-muted)') + ';font-weight:' + (i === crumbs.length - 1 ? 500 : 400), c)]))
|
||||||
|
const offline = s.offline && D('flex-shrink:0;display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--ui-bg-inverted);color:var(--ui-text-inverted)', I('wifi-off'), S('flex:1', 'You\'re offline. You can look through the images that are loaded, but uploading, renaming and deleting need a connection.'))
|
||||||
|
const pad = m ? 16 : 24
|
||||||
|
const content = isPicker ? Editor() : D('flex:1;min-height:0;overflow:hidden;padding:' + pad + 'px;display:flex;flex-direction:column;gap:16px;position:relative', Header(), ...pageBody())
|
||||||
|
const dragOv = s.drag && D('position:absolute;z-index:35;inset:' + (m ? 8 : 12) + 'px;top:' + (m ? 64 : 60) + 'px;border:2px dashed var(--ui-primary);background:var(--rc-sand);color:#111111;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;text-align:center', I('upload', 28), S('font-weight:600;font-size:16px', 'Drop images to upload'), S('color:#444444', 'PNG, JPEG, WEBP, SVG · max 10 MB each'))
|
||||||
|
const fab = m && !isPicker && !(sel.length) && !s.panel && !s.modal && !s.error && s.empty !== 'first' && !s.drag && D('position:absolute;left:16px;right:16px;bottom:16px;height:48px;display:flex;align-items:center;justify-content:center;gap:8px;background:var(--ui-primary);color:var(--ui-bg);font-weight:500;font-size:15px;box-shadow:var(--rc-shadow-pop);opacity:' + (s.limited || s.offline ? 0.4 : 1), I(s.limited ? 'timer' : 'upload', 18), s.limited ? 'Try again in 0:42' : 'Upload')
|
||||||
|
const ann = s.ann && D('position:absolute;z-index:20;' + (m ? 'left:16px;bottom:24px' : 'left:248px;bottom:20px'), Note(s.ann))
|
||||||
|
const root = D('width:' + (m ? 390 : 1440) + 'px;height:' + (m ? 844 : 900) + 'px;position:relative;display:flex;flex-direction:' + (m ? 'column' : 'row') + ';background:var(--ui-bg-muted);color:var(--ui-text);font-family:\'IBM Plex Sans\',sans-serif;font-size:13px;line-height:20px;overflow:hidden',
|
||||||
|
!m && side, D('flex:1;min-width:0;min-height:0;display:flex;flex-direction:column', topbar, offline, content),
|
||||||
|
dragOv, fab, ann, sel.length > 0 && !s.panel && !s.modal && BulkBar(), s.panel && Panel(), isPicker && s.picker && Picker(), s.modal && Modal(), s.toasts && Toasts())
|
||||||
|
return { view: root }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -39,12 +39,13 @@
|
|||||||
<div style="display:flex;flex-direction:column;gap:12px">
|
<div style="display:flex;flex-direction:column;gap:12px">
|
||||||
<div style="display:flex;flex-direction:column;gap:2px;max-width:1040px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}</span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div>
|
<div style="display:flex;flex-direction:column;gap:2px;max-width:1040px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ st.name }}</span><span style="font-size:13px;color:var(--ui-text-muted)">{{ st.trigger }}</span></div>
|
||||||
<div style="display:flex;gap:24px;align-items:flex-start">
|
<div style="display:flex;gap:24px;align-items:flex-start">
|
||||||
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><dc-import name="AppFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></div></div>
|
<div style="width:720px;height:450px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:1440px;height:900px;zoom:0.5"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st }}" mobile="{{ false }}" hint-size="1440px,900px"></dc-import></sc-if></div></div>
|
||||||
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><dc-import name="AppFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></div></div>
|
<div style="width:293px;height:633px;overflow:hidden;border:1px solid var(--ui-border);flex-shrink:0"><div style="width:390px;height:844px;zoom:0.75"><sc-if value="{{ st.notMedia }}"><dc-import name="AppFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if><sc-if value="{{ st.isMedia }}"><dc-import name="MediaFrame" s="{{ st.m }}" mobile="{{ true }}" hint-size="390px,844px"></dc-import></sc-if></div></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</sc-for>
|
</sc-for>
|
||||||
</div>
|
</div>
|
||||||
|
<sc-if value="{{ g.table }}"><div style="display:flex;flex-direction:column;gap:8px;max-width:1240px"><span style="font:600 16px/24px 'IBM Plex Sans',sans-serif;color:var(--ui-text-highlighted)">{{ g.tableTitle }}</span><div style="background:var(--ui-bg);border:1px solid var(--ui-border)"><div style="display:grid;grid-template-columns:90px 240px minmax(0,1fr);padding:8px 12px;background:var(--ui-bg-elevated);color:var(--ui-text-muted);font-weight:500"><span>Status</span><span>Where</span><span>Copy</span></div><sc-for list="{{ g.table }}" as="r" hint-placeholder-count="3"><div style="display:grid;grid-template-columns:90px 240px minmax(0,1fr);gap:0;padding:10px 12px;border-top:1px solid var(--ui-border);line-height:20px"><span style="font:500 13px 'IBM Plex Mono',monospace;color:var(--ui-text-highlighted)">{{ r.a }}</span><span style="color:var(--ui-text-toned);padding-right:16px">{{ r.b }}</span><span style="color:var(--ui-text-highlighted);text-wrap:pretty">{{ r.c }}</span></div></sc-for></div></div></sc-if>
|
||||||
</section>
|
</section>
|
||||||
</sc-for>
|
</sc-for>
|
||||||
|
|
||||||
@@ -107,7 +108,29 @@ class Component extends DCLogic {
|
|||||||
const invF = (value, extra = {}) => [{ label: 'Email', value, ...extra }]
|
const invF = (value, extra = {}) => [{ label: 'Email', value, ...extra }]
|
||||||
const P = (pf = {}, o = {}) => withM({ kind: 'profile', nav: 'profile', crumbs: ['Profile'], mTitle: 'Profile', ...o, pf })
|
const P = (pf = {}, o = {}) => withM({ kind: 'profile', nav: 'profile', crumbs: ['Profile'], mTitle: 'Profile', ...o, pf })
|
||||||
const dname = 'Marta Alves'
|
const dname = 'Marta Alves'
|
||||||
return [
|
const MS = (o) => ({ frame: 'MediaFrame', isMedia: true, ...o, m: { frame: 'MediaFrame', isMedia: true, ...o } })
|
||||||
|
const Mp = (o) => MS({ kind: 'page', ...o })
|
||||||
|
const TT = (tone, icon, title, text, action) => [tone, icon, title, text, action]
|
||||||
|
const upT = (rows, o = {}) => ({ title: 'Uploading 6 images', sub: '2 of 6 done', rows, ...o })
|
||||||
|
const rowOk = (n, sz, im) => ({ n, sz, st: 'ok', im })
|
||||||
|
const rowDup = { n: 'floorboards-2.jpg', sz: '2.4 MB', st: 'dup', im: 12, msg: 'Same as "floorboards.jpg", uploaded 14 Jun 2026 by Inès Duarte.' }
|
||||||
|
const rowRej = { n: 'scan.tif', sz: '14.2 MB', st: 'rej', title: 'scan.tif is 14.2 MB', msg: 'Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image.' }
|
||||||
|
const rowFail = { n: 'roof.png', sz: '1.4 MB', st: 'fail', im: 10 }
|
||||||
|
const gone = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12]
|
||||||
|
const pk = (o = {}, x = {}) => MS({ kind: 'picker', picker: true, pk: { tab: 'Library', ...o }, ...x })
|
||||||
|
const TB = { neutral: 'var(--ui-bg-muted)', success: 'var(--rc-success-soft)', info: 'var(--rc-info-soft)', warning: 'var(--rc-warning-soft)', error: 'var(--rc-error-soft)' }
|
||||||
|
const B = (t, kind, icon, dis) => ({ t, icon, bg: kind === 'primary' ? 'var(--ui-primary)' : 'var(--ui-bg)', fg: kind === 'primary' ? 'var(--ui-bg)' : 'var(--ui-text-highlighted)', bd: kind === 'primary' ? 'var(--ui-primary)' : 'var(--ui-border-accented)', op: dis ? '0.4' : '1' })
|
||||||
|
const UPD = (o) => { const tone = o.tone || 'neutral'; return { v: 'v2.2.0-beta', focus: 'none', ...o, fg: tone === 'neutral' ? 'var(--ui-text-toned)' : 'var(--ui-' + tone + ')', bg: TB[tone], bar: o.pct !== undefined || !!o.indet, barW: o.indet ? '35%' : (o.pct || 0) + '%', barL: o.indet ? '30%' : '0', pct: o.indet ? undefined : o.pct } }
|
||||||
|
const NOTES = (open) => ({ open, chev: open ? 'chevron-down' : 'chevron-right', ver: '2.3.0', date: 'Released 24 Sep 2026', items: [{ t: 'Images upload faster, and large images no longer stall.' }, { t: 'Fixed a problem where a draft could show an old title after saving.' }, { t: 'Small improvements to the Users page.' }] })
|
||||||
|
const SU = (o, extra) => withM({ kind: 'settings', nav: 'settings', crumbs: ['Settings'], mTitle: 'Settings', ...extra, upd: UPD(o) })
|
||||||
|
const LAST = 'Last checked today at 09:41'
|
||||||
|
const RESTART_FOOT = 'Restart takes about 10 seconds. Your site is unavailable while it restarts.'
|
||||||
|
const bn = (icon, title, text) => ({ icon, title, text, btn: 'Go to Settings', fg: 'var(--ui-info)', bg: 'var(--rc-info-soft)' })
|
||||||
|
const cmdLine = 'renewcms enable-browser-updates'
|
||||||
|
const notPrep = (copied) => ({ icon: 'info', tone: 'info', title: 'Version 2.3.0 is available', text: 'This site can\'t update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you.', meta: LAST, cmd: { line: cmdLine, t: copied ? 'Copied' : 'Copy', icon: copied ? 'check' : 'copy', fg: copied ? 'var(--ui-success)' : 'var(--ui-text-highlighted)', note: 'They run this once on the server. After that, Update and Restart appear here.' }, link: 'How to update' })
|
||||||
|
const restartModal = (o) => ({ title: 'Restart the site?', desc: 'Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you\'re editing first.', cancel: 'Cancel', confirm: 'Restart site', ...o })
|
||||||
|
const installModal = (o) => ({ title: 'Restart to finish the update?', desc: 'RenewCMS will install version 2.3.0 and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you\'re editing first.', cancel: 'Restart later', confirm: 'Restart now', ...o })
|
||||||
|
return this.finish([
|
||||||
{ label: 'Boot', title: 'App boot', route: 'any route, first load', api: 'GET /v1/auth/me (pending)', note: 'While the session is checked, the shell renders with skeletons, never a spinner. The possible outcomes are: 200 with a verified user, which renders the route; 200 with an unverified user, which goes to /register/pending; and 401, which goes to /login?redirect=<path>. Public routes skip this check.', states: [
|
{ label: 'Boot', title: 'App boot', route: 'any route, first load', api: 'GET /v1/auth/me (pending)', note: 'While the session is checked, the shell renders with skeletons, never a spinner. The possible outcomes are: 200 with a verified user, which renders the route; 200 with an unverified user, which goes to /register/pending; and 401, which goes to /login?redirect=<path>. Public routes skip this check.', states: [
|
||||||
withM({ ...home, name: 'Checking session', trigger: 'The first paint on any back-office URL, and usually visible for well under a second.', boot: true })
|
withM({ ...home, name: 'Checking session', trigger: 'The first paint on any back-office URL, and usually visible for well under a second.', boot: true })
|
||||||
] },
|
] },
|
||||||
@@ -115,7 +138,9 @@ class Component extends DCLogic {
|
|||||||
withM({ ...home, name: 'Default', trigger: 'The articles loaded.', home: { sub: 'Here\'s where things stand on your site.', stats, recent } }),
|
withM({ ...home, name: 'Default', trigger: 'The articles loaded.', home: { sub: 'Here\'s where things stand on your site.', stats, recent } }),
|
||||||
withM({ ...home, name: 'Loading', trigger: 'The list request is in flight. Skeletons appear after 150 ms.', home: { sub: 'Here\'s where things stand on your site.', stats: stats.map(() => ({ skel: true })), recent: Array.from({ length: 5 }, () => ({ skel: true })) } }),
|
withM({ ...home, name: 'Loading', trigger: 'The list request is in flight. Skeletons appear after 150 ms.', home: { sub: 'Here\'s where things stand on your site.', stats: stats.map(() => ({ skel: true })), recent: Array.from({ length: 5 }, () => ({ skel: true })) } }),
|
||||||
withM({ ...home, name: 'Empty, first run', trigger: 'Zero articles: a single call to action, and no stats.', home: { sub: 'Welcome to RenewCMS.', empty: true } }),
|
withM({ ...home, name: 'Empty, first run', trigger: 'Zero articles: a single call to action, and no stats.', home: { sub: 'Welcome to RenewCMS.', empty: true } }),
|
||||||
withM({ ...home, name: 'Error', trigger: 'A 500 or network failure on the list request.', home: { sub: 'Here\'s where things stand on your site.', error: true } })
|
withM({ ...home, name: 'Error', trigger: 'A 500 or network failure on the list request.', home: { sub: 'Here\'s where things stand on your site.', error: true } }),
|
||||||
|
withM({ ...home, navBadge: true, name: 'Update available (owner)', trigger: 'The owner only. A quiet banner above the content, and an "Update" pill on the Settings item (a dot on the menu icon on mobile, read as "Update available"). Dismissing hides the banner until the next version; the pill stays. Admins see neither.', home: { sub: 'Here\'s where things stand on your site.', stats, recent, banner: bn('circle-arrow-up', 'Version 2.3.0 is available', 'Update it from Settings. It takes about 2 minutes and the site stays online.') } }),
|
||||||
|
withM({ ...home, navBadge: true, name: 'Update ready to install (owner)', trigger: 'The download is checked. The same banner changes its copy, and a dismiss comes back on the next visit because the update is waiting.', home: { sub: 'Here\'s where things stand on your site.', stats, recent, banner: bn('circle-check', 'Version 2.3.0 is ready to install', 'Restart from Settings to finish. The site is unavailable for about 10 seconds.') } })
|
||||||
] },
|
] },
|
||||||
{ label: 'Articles', title: 'Articles', route: '/article', api: 'GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id}', note: 'Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string.', states: [
|
{ label: 'Articles', title: 'Articles', route: '/article', api: 'GET /v1/article/ · PATCH …/publish · PATCH …/unpublish · DELETE /v1/article/{id}', note: 'Rows update when the server responds, not optimistically. Search, tab and sort are stored in the query string.', states: [
|
||||||
withM({ ...L(), name: 'Default', trigger: 'The list loaded, sorted by last updated.' }),
|
withM({ ...L(), name: 'Default', trigger: 'The list loaded, sorted by last updated.' }),
|
||||||
@@ -164,6 +189,82 @@ class Component extends DCLogic {
|
|||||||
E({ save: 'offline' }, { name: 'Offline', trigger: 'The connection dropped. Writing continues, and Save and Publish wait.', offline: true }),
|
E({ save: 'offline' }, { name: 'Offline', trigger: 'The connection dropped. Writing continues, and Save and Publish wait.', offline: true }),
|
||||||
E({ notfound: true }, { name: 'Not found (404)', trigger: 'Unknown id, or the article was deleted elsewhere.' })
|
E({ notfound: true }, { name: 'Not found (404)', trigger: 'Unknown id, or the article was deleted elsewhere.' })
|
||||||
] },
|
] },
|
||||||
|
{ label: 'Media', title: 'Media', route: '/media', api: 'GET /v1/media/ · POST /v1/media/ · PATCH /v1/media/{id} · DELETE /v1/media/{id} · POST /v1/media/merge · GET /v1/media/{id}/usage', note: 'New route for verified users, in the sidebar between Articles and Users with the images icon. Images belong to the library, not to an article: one image can be used in many articles, and deleting an article never deletes images. Uploads from this page are not cropped or resized, and the file is stored as chosen. "Used in" is read from article bodies each time the list loads. Duplicates are images with identical content, whatever their filenames. Alt text is not stored on the image; it is set when inserting into an article. Search, filter, sort and view are stored in the query string. Keyboard: grid items are buttons in one tab stop each; Enter opens the detail panel, Space toggles selection, and Escape closes the panel or clears the selection. Selection changes are announced ("north-wall.jpg selected, 1 selected").', states: [
|
||||||
|
Mp({ name: 'Grid, many images', trigger: 'Default view. 12 images, newest first. Each item is a button labelled like "north-wall.jpg, 3.9 MB, used in 2 articles". Badges: "Unused" (warm), "Duplicate" (info), "Used in N" (outline). The Duplicates tab carries a count of groups only while duplicates exist.' }),
|
||||||
|
Mp({ ids: [1, 4, 8], name: 'Grid, few images', trigger: 'Three images. Cards keep their size instead of stretching. Checkerboard shows behind the SVG.' }),
|
||||||
|
Mp({ view: 'list', name: 'List view', trigger: 'The list icon in the toggle. A table from md up (Filename, Dimensions, Size, Type, Used in, Uploaded by, Uploaded) and a card list below md. The "Used in" count opens the article list in the detail panel.' }),
|
||||||
|
Mp({ loading: true, name: 'Loading', trigger: 'The first load, a retry, or a change of search or filter. Skeleton cards appear after 150 ms.' }),
|
||||||
|
Mp({ empty: 'first', name: 'Empty library, first run', trigger: 'Zero images. Toolbar and tabs are hidden; one call to action. Copy: "No images yet" / "Upload your first image. You can use it in any article." / "Upload an image".' }),
|
||||||
|
Mp({ tab: 'unused', q: 'wall', empty: 'search', name: 'No results', trigger: 'Search or filter matched nothing. "Clear filters" resets the search and goes back to All.' }),
|
||||||
|
Mp({ hover: 2, focus: 3, ann: 'aria-label: kitchen-before.webp, 1.1 MB, used in 1 article', name: 'Hover, focus and keyboard', trigger: 'Hover (second item) darkens the border, adds the pop shadow and reveals the checkbox. Keyboard focus (third item) shows the 2 px primary ring with a 2 px offset and reveals the checkbox. Tab moves between items, Enter opens the detail panel, Space toggles selection, and arrow keys move focus across the grid.' }),
|
||||||
|
Mp({ sel: [1, 2, 8], name: 'Selection and bulk bar', trigger: 'Checkbox on any item, or Space. Selected items take the sand fill with a primary outline, and Select all shows a partial state. The bar is sticky at the bottom (above the bottom edge on mobile, replacing the Upload button). Announced: "3 selected". Escape or Clear empties it.' }),
|
||||||
|
Mp({ sel: [1, 2, 8], modal: { k: 'bulk' }, name: 'Bulk delete: confirm', trigger: 'Delete in the bulk bar. The dialog says how many of the selection are in use and lists them. The confirm button carries the count.' }),
|
||||||
|
Mp({ sel: [1, 2, 8], modal: { k: 'bulk', loading: true }, name: 'Bulk delete: in progress', trigger: 'Requests in flight. The dialog can\'t be dismissed.' }),
|
||||||
|
Mp({ ids: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12], sel: [8], toasts: [TT('error', 'circle-x', 'Couldn\'t delete 1 image', '2 images were deleted. window-frame.jpg is still in your library. Try again.', 'Retry')], name: 'Bulk delete: partly failed', trigger: 'Some requests failed. Deleted images leave the grid, failed ones stay selected, and the toast stays until retried or dismissed.' }),
|
||||||
|
Mp({ ids: [3, 4, 5, 6, 7, 9, 10, 11, 12], toasts: [TT('success', 'circle-check', '3 images deleted', 'They\'re gone from your library.')], name: 'Bulk delete: done', trigger: '204 for all. Focus moves to the next item.' }),
|
||||||
|
Mp({ panel: { id: 1 }, name: 'Detail panel: in use', trigger: 'Click or Enter on an item. Right-hand slideover on desktop, full screen on mobile with a back arrow. Actions: Copy URL, Rename, Delete. "Used in 2 articles" lists title, Online or Draft, and links to the editor. Focus returns to the item on close.' }),
|
||||||
|
Mp({ panel: { id: 8 }, name: 'Detail panel: unused', trigger: 'Used in nothing. The section reads "Not used in any article" and says the image is safe to delete.' }),
|
||||||
|
Mp({ panel: { id: 12 }, name: 'Detail panel: duplicate', trigger: 'The image has identical copies. An info alert links to the duplicates view.' }),
|
||||||
|
Mp({ panel: { id: 1 }, toasts: [TT('success', 'circle-check', 'URL copied', 'Paste it wherever you need the image address.')], name: 'Copy URL', trigger: 'Copy URL. Clipboard write succeeded. Success toasts last 5 s.' }),
|
||||||
|
Mp({ panel: { id: 1 }, modal: { k: 'rename', val: 'north-wall' }, name: 'Rename: dialog', trigger: 'Rename in the panel. The field holds the name without its extension, and the .jpg ending is fixed. The description says the URL stays the same.' }),
|
||||||
|
Mp({ panel: { id: 1 }, modal: { k: 'rename', val: 'north-wall-01', loading: true }, name: 'Rename: saving', trigger: 'PATCH in flight. Field and buttons disabled, dialog can\'t be dismissed.' }),
|
||||||
|
Mp({ panel: { id: 1 }, modal: { k: 'rename', err: 'Enter a filename.' }, name: 'Rename: validation', trigger: 'Empty or only symbols, on submit or blur. Nothing is sent.' }),
|
||||||
|
Mp({ panel: { id: 1 }, modal: { k: 'rename', val: 'north-wall-01', notice: 'Couldn\'t rename the image. Your text is still here. Try again in a moment.' }, name: 'Rename: failed', trigger: '500 or network failure. The error shows inside the dialog.' }),
|
||||||
|
Mp({ panel: { id: 1 }, toasts: [TT('success', 'circle-check', 'Image renamed', 'It\'s now "north-wall-01.jpg". The URL is the same.')], name: 'Rename: done', trigger: '200: the panel title and list update in place.' }),
|
||||||
|
Mp({ panel: { id: 8 }, modal: { k: 'del' }, name: 'Delete: unused image', trigger: 'Delete in the panel. Plain confirm. Says what happens and that it can\'t be undone.' }),
|
||||||
|
Mp({ panel: { id: 1 }, modal: { k: 'delUsed' }, name: 'Delete: image in use', trigger: 'Stronger confirm. Lists the affected articles and states that they will show a broken image.' }),
|
||||||
|
Mp({ panel: { id: 1 }, modal: { k: 'delUsed', loading: true }, name: 'Delete: in progress', trigger: 'DELETE in flight. The dialog can\'t be dismissed.' }),
|
||||||
|
Mp({ panel: { id: 8 }, modal: { k: 'del', notice: 'Couldn\'t delete the image, so it\'s still there. Try again in a moment.' }, name: 'Delete: failed', trigger: '500 or network failure. The error shows inside the dialog, as in the article delete.' }),
|
||||||
|
Mp({ ids: gone, toasts: [TT('success', 'circle-check', 'Image deleted', '"window-frame.jpg" is gone from your library.')], name: 'Delete: done', trigger: '204: the panel closes, the item leaves the grid and focus moves to the next item.' }),
|
||||||
|
Mp({ ids: gone, toasts: [TT('info', 'info', 'That image no longer exists', 'It was deleted somewhere else, so we removed it from the library.')], name: 'Image already gone (404)', trigger: 'Any action on an image that was deleted elsewhere. The panel closes and the item leaves the list.' }),
|
||||||
|
Mp({ drag: true, name: 'Upload: drag over the page', trigger: 'Files dragged onto the page. A dashed drop area covers the content. Dropping starts the upload straight away; there is no crop step on this page.' }),
|
||||||
|
Mp({ upload: upT([rowOk('kitchen-roof.jpg', '2.2 MB', 2), { n: 'porch-steps.jpg', sz: '2.6 MB', st: 'prog', p: '1.1 of 2.6 MB', pct: '42%', im: 11 }, rowDup, rowRej, rowFail, { n: 'attic.jpg', sz: '1.9 MB', st: 'wait', im: 3 }]), name: 'Upload: several files, mixed', trigger: 'Upload button or drop, several files. Each file has its own row and progress. Files upload two at a time. A row can end as added, "Already in your library", rejected in the browser, or failed. Rejected and failed rows stay until dismissed.' }),
|
||||||
|
Mp({ upload: upT([rowOk('kitchen-roof.jpg', '2.2 MB', 2), rowOk('porch-steps.jpg', '2.6 MB', 11), rowDup, rowRej, rowFail], { title: 'Upload finished', sub: '5 images', done: true, summary: '2 uploaded · 1 already in your library · 2 need attention' }), name: 'Upload: summary', trigger: 'All rows settled. The summary counts each outcome. "Use existing" selects the existing image and drops the row; "Upload anyway" stores a second copy, which then appears under Duplicates. "Try again" retries one file. Announced when it finishes.' }),
|
||||||
|
Mp({ upload: upT([rowRej, { n: 'notes.pdf', sz: '210 KB', st: 'rej', title: 'notes.pdf isn\'t an image', msg: 'Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image.' }, { n: 'broken.png', sz: '3.0 MB', st: 'rej', title: 'broken.png couldn\'t be read', msg: 'The server couldn\'t read this image. Save it again as a PNG or JPEG, then try again.' }], { title: 'Nothing was uploaded', sub: '3 files were rejected', done: true }), name: 'Upload: rejected files (413, 400)', trigger: 'Type and size are checked in the browser first, so nothing is sent. A server 413 or 400 for a file that got through shows the same row with its own message.' }),
|
||||||
|
Mp({ limited: true, name: 'Upload: too many requests (429)', trigger: 'Rate limited. Retry-After is counted down in the button. It re-enables at zero. Already-added files are kept.' }),
|
||||||
|
Mp({ tab: 'dups', name: 'Duplicates: groups', trigger: 'The Duplicates tab. Groups of identical images side by side, each with its uploader, upload date and "Used in N articles". The suggested copy to keep is the most used, then the oldest.' }),
|
||||||
|
Mp({ tab: 'dups', dupEmpty: true, name: 'Duplicates: empty', trigger: 'No groups. The Duplicates tab loses its count badge.' }),
|
||||||
|
Mp({ tab: 'dups', modal: { k: 'merge' }, name: 'Merge: confirm', trigger: '"Merge into this one" on floorboards.jpg. The dialog says articles using the other copies will switch to this image and the other copies will be deleted, with the article count.' }),
|
||||||
|
Mp({ tab: 'dups', modal: { k: 'merge', loading: true }, name: 'Merge: in progress', trigger: 'Request in flight. The dialog can\'t be dismissed.' }),
|
||||||
|
Mp({ tab: 'dups', modal: { k: 'merge', notice: 'Couldn\'t merge the copies. Nothing was changed. Try again in a moment.' }, name: 'Merge: failed', trigger: '500 or network failure. Nothing is switched or deleted.' }),
|
||||||
|
Mp({ tab: 'dups', modal: { k: 'merge', notice: 'One of these images changed, so nothing was merged. The list is up to date now. Check it and try again.' }, name: 'Merge: conflict (409)', trigger: 'A copy was deleted, or a new copy appeared, since the page loaded.' }),
|
||||||
|
Mp({ tab: 'dups', dupGroups: 1, ids: [1, 2, 3, 4, 7, 8, 9, 10, 11, 12], toasts: [TT('success', 'circle-check', 'Copies merged', '2 copies merged. 5 articles updated.')], name: 'Merge: done', trigger: '200: the group leaves the list. When it was the last one, "No duplicates" shows.' }),
|
||||||
|
Mp({ error: true, name: 'List failed to load', trigger: 'A 500 or network failure on the list request. The alert replaces the images; Try again repeats the request.' }),
|
||||||
|
Mp({ offline: true, name: 'Offline', trigger: 'navigator.onLine is false. Loaded images stay browsable. Upload, Rename, Delete and Merge are disabled, and the banner says why.' })
|
||||||
|
], tableTitle: 'Status to copy', table: [
|
||||||
|
{ a: '200 / 201', b: 'Upload, rename, merge', c: 'Upload: row reads "Added to your library". Rename: "Image renamed" / "It\'s now "north-wall-01.jpg". The URL is the same." Merge: "Copies merged" / "2 copies merged. 5 articles updated."' },
|
||||||
|
{ a: '204', b: 'Delete, bulk delete', c: '"Image deleted" / ""window-frame.jpg" is gone from your library." Bulk: "3 images deleted" / "They\'re gone from your library."' },
|
||||||
|
{ a: '400', b: 'Upload row', c: '"broken.png couldn\'t be read" / "The server couldn\'t read this image. Save it again as a PNG or JPEG, then try again." In a dialog: "Something in the form isn\'t valid. Check the highlighted fields."' },
|
||||||
|
{ a: '401', b: 'Any call', c: 'Handled globally: /login?redirect=/media&reason=expired. No local copy.' },
|
||||||
|
{ a: '403', b: 'Any call, unverified', c: 'Handled globally: /register/pending.' },
|
||||||
|
{ a: '404', b: 'Rename, delete, merge, panel', c: 'Toast (info): "That image no longer exists" / "It was deleted somewhere else, so we removed it from the library." The panel or dialog closes.' },
|
||||||
|
{ a: '409', b: 'Merge', c: 'Dialog alert: "One of these images changed, so nothing was merged. The list is up to date now. Check it and try again."' },
|
||||||
|
{ a: '413', b: 'Upload row', c: '"scan.tif is 14.2 MB" / "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image."' },
|
||||||
|
{ a: '415', b: 'Upload row', c: '"notes.pdf isn\'t an image" / "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image."' },
|
||||||
|
{ a: '429', b: 'Upload', c: 'Alert (info): "Too many uploads" / "For your security, wait a moment before uploading again." The button reads "Try again in 0:42" and counts down.' },
|
||||||
|
{ a: '500 / network', b: 'List', c: 'Alert: "Couldn\'t load your images" / "Check your connection and try again." with "Try again".' },
|
||||||
|
{ a: '500 / network', b: 'Upload row', c: '"Upload failed" / "The server didn\'t accept the file. Nothing was added to your library." with "Try again".' },
|
||||||
|
{ a: '500 / network', b: 'Rename dialog', c: '"Couldn\'t rename the image. Your text is still here. Try again in a moment."' },
|
||||||
|
{ a: '500 / network', b: 'Delete dialog', c: '"Couldn\'t delete the image, so it\'s still there. Try again in a moment."' },
|
||||||
|
{ a: '500 / network', b: 'Merge dialog', c: '"Couldn\'t merge the copies. Nothing was changed. Try again in a moment."' },
|
||||||
|
{ a: 'Partial', b: 'Bulk delete', c: 'Toast (error, stays): "Couldn\'t delete 1 image" / "2 images were deleted. window-frame.jpg is still in your library. Try again." with "Retry".' },
|
||||||
|
{ a: 'Offline', b: 'Whole page', c: 'Banner: "You\'re offline. You can look through the images that are loaded, but uploading, renaming and deleting need a connection."' }
|
||||||
|
] },
|
||||||
|
{ label: 'Media picker', title: 'Picker in the editor', route: '/article/:id/edit', api: 'GET /v1/media/?q=&limit=&cursor= · POST /v1/media/ (same as the Media page)', note: 'The existing "Add an image" dialog gains two tabs, Upload and Library. The Upload tab is the current flow unchanged, so it still offers crop and resize, and a new image lands in the library and is inserted as before. The Library tab opens on the Library tab when the library has images and on Upload when it is empty. Images load 24 at a time with "Load more". Newest first, and images already in this article carry "In this article". Alt text is set here and lives only in the article. The dialog is 640 px wide on desktop and a bottom sheet on mobile.', states: [
|
||||||
|
pk({ tab: 'Upload' }, { name: 'Upload tab', trigger: 'The image button in the toolbar. Identical to the current "Add an image" content; only the tabs are new. Rejected, uploading and failed states are unchanged.', inArticle: false }),
|
||||||
|
pk({ tab: 'Upload', dup: true }, { name: 'Upload tab: already in your library', trigger: 'A chosen file has the same content as an existing image. Nothing is sent. "Use existing" inserts the existing image (the alt text step follows); "Upload anyway" continues to crop and upload as usual.' }),
|
||||||
|
pk({ loading: true }, { name: 'Library: loading', trigger: 'The Library tab was opened, or a search changed. Skeleton tiles after 150 ms.' }),
|
||||||
|
pk({}, { name: 'Library: nothing selected', trigger: 'Newest first. Tiles are buttons labelled with filename, size and use, and Enter or Space selects. Images already in this article carry "In this article". "Insert image" is disabled.' }),
|
||||||
|
pk({ sel: 2, alt: '' }, { name: 'Library: selected', trigger: 'One image selected (single selection). Below the grid: thumbnail, filename, dimensions and size, and an optional alt text field. "Insert image" turns on.' }),
|
||||||
|
pk({ sel: 2, alt: 'A kitchen with new oak worktops and white tiles' }, { name: 'Library: alt text entered', trigger: 'Alt text is optional. Empty alt text is inserted as a decorative image. It is not saved on the image.' }),
|
||||||
|
pk({ more: true }, { name: 'Library: loading more', trigger: '"Load more" pressed. The button shows progress and new skeleton tiles appear at the end. Focus stays on the button until the new tiles arrive, then moves to the first new tile.' }),
|
||||||
|
pk({ empty: 'first' }, { name: 'Library: empty', trigger: 'Zero images. "Upload an image" switches to the Upload tab.' }),
|
||||||
|
pk({ q: 'wall', empty: 'search' }, { name: 'Library: no results', trigger: 'Search matched nothing. "Clear search" resets it.' }),
|
||||||
|
pk({ error: true }, { name: 'Library: failed to load', trigger: 'A 500 or network failure. The error shows in the dialog and Try again repeats the request. A 429 uses the same countdown alert as the Media page, and a 401 is handled globally.' }),
|
||||||
|
MS({ kind: 'picker', inArticle: true, name: 'Inserted', trigger: 'Insert image from either tab. The image goes in at the cursor with the chosen alt text, and the article now has unsaved changes.', toasts: [TT('success', 'circle-check', 'Image added', 'Save to keep it in the article.')] }),
|
||||||
|
MS({ kind: 'picker', inArticle: true, picker: false, modal: { k: 'remove' }, name: 'Remove image: confirm', trigger: 'Remove image on an image in the article. It now only removes it from this article, and the copy says the file stays in the library. The confirm button is neutral, not red, because nothing is deleted. Title: "Remove this image from the article?"' }),
|
||||||
|
MS({ kind: 'picker', name: 'Removed', trigger: 'Confirmed. The image leaves the article body, which now has unsaved changes.', toasts: [TT('success', 'circle-check', 'Image removed', 'It\'s still in your library.')] })
|
||||||
|
] },
|
||||||
{ label: 'Integration', title: 'Connect your website', route: '/integration', api: 'none (static)', note: 'Written for a developer. The base URL is window.location.origin.', states: [
|
{ label: 'Integration', title: 'Connect your website', route: '/integration', api: 'none (static)', note: 'Written for a developer. The base URL is window.location.origin.', states: [
|
||||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: 'Default', trigger: 'Opened from the sidebar or the Home card.' }),
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', name: 'Default', trigger: 'Opened from the sidebar or the Home card.' }),
|
||||||
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', copied: true, name: 'Copied', trigger: 'The base URL was copied. The button reads "Copied" for 2 s and this is announced.' })
|
withM({ kind: 'integration', nav: 'integration', crumbs: ['Integration'], mTitle: 'Integration', copied: true, name: 'Copied', trigger: 'The base URL was copied. The button reads "Copied" for 2 s and this is announced.' })
|
||||||
@@ -187,8 +288,50 @@ class Component extends DCLogic {
|
|||||||
withM({ ...U({ toasts: [T('error', 'circle-x', 'Couldn\'t renew the invite', 'Try again in a moment.')] }), name: 'Renew invite: failed', trigger: '500 or network failure. The row stays Expired and the button can be pressed again.' }),
|
withM({ ...U({ toasts: [T('error', 'circle-x', 'Couldn\'t renew the invite', 'Try again in a moment.')] }), name: 'Renew invite: failed', trigger: '500 or network failure. The row stays Expired and the button can be pressed again.' }),
|
||||||
withM({ ...U({ users: { rows: [{ email: 'lea.martin@renew.example', role: 'admin', st: 'pending', c: 'Today', hl: true }, ...people] } , toasts: [T('success', 'circle-check', 'Invite sent', 'lea.martin@renew.example has 3 days to accept.')] }), name: 'Invite sent', trigger: '201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms.' })
|
withM({ ...U({ users: { rows: [{ email: 'lea.martin@renew.example', role: 'admin', st: 'pending', c: 'Today', hl: true }, ...people] } , toasts: [T('success', 'circle-check', 'Invite sent', 'lea.martin@renew.example has 3 days to accept.')] }), name: 'Invite sent', trigger: '201: the dialog closes, the new invite appears at the top as Pending, and a toast confirms.' })
|
||||||
] },
|
] },
|
||||||
{ label: 'Settings', title: 'Settings', route: '/settings', api: 'none (static)', note: 'Opened from the sidebar. For now it holds only the Version section.', states: [
|
{ label: 'Settings', title: 'Settings: Updates', route: '/settings', api: 'GET /v1/system/update · POST …/check · POST …/download · POST …/restart (all pending)', note: 'New Updates card under Version, owner only. Update downloads and checks the new version and changes nothing. Restart installs it and restarts the site (about 10 seconds). "Restart later" is simply leaving the card or the dialog. A plain Restart shows only when no update is waiting. Admins see the version and a note. When the server isn\'t prepared, the card shows the notice and a "How to update" link with no buttons. Progress is a progressbar with a value, announced at 25% steps and when each step changes. The card is a polite live region. After the restart the page reloads, focus lands on the "Updates" heading, and a toast confirms. Buttons are disabled while any step runs, and any owner on any device sees the same state from the server. Cue elsewhere: see Home. Out of scope: choosing versions, downgrades, automatic updates, update history.', states: [
|
||||||
withM({ kind: 'settings', nav: 'settings', crumbs: ['Settings'], mTitle: 'Settings', name: 'Default', trigger: 'Opened from the sidebar.' })
|
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Up to date', trigger: 'Opened with no newer version. Restart is available but not emphasised.' }),
|
||||||
|
SU({ icon: 'loader-circle', title: 'Checking for updates…', text: 'This usually takes a few seconds.', btns: [B('Checking…', 'sec', 'loader-circle', true)] }, { name: 'Checking', trigger: 'Check for updates pressed, or the first open after 24 hours. Announced as "Checking for updates". Buttons are disabled.' }),
|
||||||
|
SU({ icon: 'wifi-off', tone: 'warning', title: 'Couldn\'t check for updates', text: 'RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected.', meta: 'Last checked yesterday at 18:12', btns: [B('Try again', 'primary', 'rotate-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Check failed', trigger: 'Offline, or the update server didn\'t answer (500, network). The last known result is kept.' }),
|
||||||
|
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(false), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available', trigger: 'A newer version exists. Release notes are collapsed. Update is the one primary button.', navBadge: true }),
|
||||||
|
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, notes: NOTES(true), btns: [B('Update', 'primary', 'download')], hint: 'Takes about 2 minutes. Your site stays online.' }, { name: 'Update available, notes open', trigger: '"What\'s new in 2.3.0" expanded. It is a button with aria-expanded, and the list is plain text.', navBadge: true }),
|
||||||
|
SU({ icon: 'download', tone: 'info', title: 'Downloading version 2.3.0…', text: 'You can leave this page. The download continues and your site stays online.', pct: 42, barLabel: 'Downloading version 2.3.0', barText: '42% · 11 of 26 MB', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Downloading', trigger: 'Update pressed (202). Progress polls every second. Announced as "Downloading, 25 percent" and so on, never every tick.', navBadge: true }),
|
||||||
|
SU({ icon: 'shield-check', tone: 'info', title: 'Checking the download…', text: 'Making sure the file is complete and safe to install. This takes a few seconds.', indet: true, barLabel: 'Checking the download', barText: 'Almost there', btns: [B('Updating…', 'sec', 'loader-circle', true)] }, { name: 'Verifying', trigger: 'The download finished. No percentage, so the bar is indeterminate. Announced as "Checking the download".', navBadge: true }),
|
||||||
|
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', notes: NOTES(false), btns: [B('Restart', 'primary', 'power')], hint: 'Not now? Leave this page. The update waits here, and the banner on Home reminds you.' }, { name: 'Ready to install', trigger: 'The file passed its checks. Restart becomes the primary action. "Restart later" is closing the dialog or leaving the page.', navBadge: true }),
|
||||||
|
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', btns: [B('Restart', 'primary', 'power')] }, { name: 'Restart: confirm', trigger: 'Restart pressed. Same dialog behaviour as the delete confirm: focus moves to the first button, Escape and "Restart later" close it, and focus returns to Restart. The confirm button is neutral, not red, because nothing is lost.', navBadge: true, modal: installModal() }),
|
||||||
|
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: 'The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds.', meta: 'Nothing has changed yet.', btns: [B('Restart', 'primary', 'power')] }, { name: 'Restart: request failed', trigger: '500 or network failure before the restart began. The site is still running.', navBadge: true, modal: installModal({ notice: 'Couldn\'t start the restart. Nothing was changed and your site is still running. Try again in a moment.' }) }),
|
||||||
|
SU({ icon: 'circle-check', tone: 'success', title: 'Version 2.3.0 is ready to install', text: '', btns: [] }, { name: 'Restarting to install', trigger: 'Full-page overlay, so it survives the server going away. The page polls until the site answers, then reloads. It is a live region announced once as "Installing version 2.3.0. Your site is restarting."', overlay: { title: 'Installing version 2.3.0', text: 'Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
|
||||||
|
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Restarting, taking longer', trigger: 'No answer after 60 seconds. The copy changes and a manual reload appears. The overlay stays until the site is back.', overlay: { title: 'Still restarting', text: 'This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now.', meta: 'Started at 09:51 · 1 minute ago', btn: 'Reload page', barL: '65%' } }),
|
||||||
|
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re on version 2.3.0', text: 'The update is installed and your site is running again.', meta: 'Updated today at 09:52', btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT, link: 'Read the release notes', v: 'v2.3.0', focus: '2px solid var(--ui-primary)', toasts: undefined }, { name: 'Update done', trigger: 'The page reloaded on the new version. Focus lands on the "Updates" heading (ring shown), the toast is announced, and the version updates.', toasts: [T('success', 'circle-check', 'Update installed', 'RenewCMS is now on version 2.3.0.')] }),
|
||||||
|
SU({ icon: 'triangle-alert', tone: 'warning', title: 'The update didn\'t install', text: 'RenewCMS put the previous version back, so your site is running as before. Nothing was lost.', meta: 'What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Update failed, rolled back', trigger: 'The site came back on v2.2.0-beta. The error toast stays until dismissed and the card keeps the explanation.', toasts: [T('error', 'circle-x', 'The update didn\'t install', 'Your site is back on v2.2.0-beta.')] }),
|
||||||
|
SU({ icon: 'circle-x', tone: 'error', title: 'The download didn\'t finish', text: 'The connection dropped before the file was complete. Nothing was changed and your site is running as before.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Download failed', trigger: 'A 500, or the connection dropped. Focus moves to the card heading. Try again restarts the download.', navBadge: true }),
|
||||||
|
SU({ icon: 'triangle-alert', tone: 'warning', title: 'We didn\'t use this update', text: 'The file didn\'t pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support.', btns: [B('Try again', 'primary', 'rotate-cw')] }, { name: 'Verification failed', trigger: 'The downloaded file isn\'t trusted. The tone is a warning, and the file is thrown away. Technical detail goes to the server log, not the screen.', navBadge: true }),
|
||||||
|
SU({ icon: 'info', tone: 'info', title: 'Too many tries', text: 'Wait a moment before trying again.', btns: [B('Try again in 0:42', 'sec', 'clock', true)] }, { name: 'Too many requests (429)', trigger: 'Retry-After counted down in the button. It re-enables at zero.' }),
|
||||||
|
SU(notPrep(false), { name: 'Not prepared', trigger: 'The server can\'t update from the browser. No buttons, not even Restart. The command is for the person who runs the server and is a single line. The placeholder command is subject to the real one.', navBadge: true }),
|
||||||
|
SU(notPrep(true), { name: 'Not prepared: command copied', trigger: 'Copy pressed. The button reads "Copied" for 2 s and it is announced.', navBadge: true }),
|
||||||
|
SU({ icon: 'circle-check', tone: 'success', title: 'You\'re up to date', text: 'You have the latest version of RenewCMS.', meta: LAST, btns: [B('Check for updates', 'sec', 'refresh-cw'), B('Restart', 'sec', 'power')], hint: RESTART_FOOT }, { name: 'Plain restart: confirm', trigger: 'Restart with no update waiting. Nothing is installed.', modal: restartModal() }),
|
||||||
|
SU({ icon: 'circle-check', tone: 'success', title: '', text: '', btns: [] }, { name: 'Plain restart: restarting', trigger: 'Same overlay as the update restart with shorter copy.', overlay: { title: 'Restarting your site', text: 'This takes about 10 seconds. This page reloads on its own when the site is back.', meta: 'Started at 09:51', barL: '30%' } }),
|
||||||
|
SU({ icon: 'circle-check', tone: 'success', title: 'Your site is back', text: '', btns: [] }, { name: 'Plain restart: done', trigger: 'The page reloaded. Focus lands on the "Updates" heading.', toasts: [T('success', 'circle-check', 'Site restarted', 'Your site is running again.')] }),
|
||||||
|
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { name: 'Admin view', trigger: 'Admins see the version and the note, with no buttons. Up to date: "You\'re up to date" and "Only the owner can update or restart the site." No Home banner or Settings pill.' }),
|
||||||
|
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.', meta: LAST }, { name: 'Role changed (403)', trigger: 'An owner was changed to admin while the page was open and pressed a button. The card reloads in the admin view.', toasts: [T('error', 'circle-x', 'Only the owner can do this', 'Ask the owner of this site to update RenewCMS.')] }),
|
||||||
|
SU({ icon: 'circle-arrow-up', tone: 'info', title: 'Version 2.3.0 is available', text: 'You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart.', meta: LAST, btns: [B('Update', 'primary', 'download', true)] }, { name: 'Update already running (409)', trigger: 'Another owner started it. The card switches to that run\'s progress.', navBadge: true, toasts: [T('info', 'info', 'An update is already running', 'Another owner started it. Progress shows here.')] })
|
||||||
|
], tableTitle: 'Status to copy', table: [
|
||||||
|
{ a: '200', b: 'Check, up to date', c: '"You\'re up to date" / "You have the latest version of RenewCMS." / "Last checked today at 09:41"' },
|
||||||
|
{ a: '200', b: 'Check, newer version', c: '"Version 2.3.0 is available" / "You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."' },
|
||||||
|
{ a: '202', b: 'Update, Restart', c: 'Accepted. The card switches to progress. Announced: "Downloading version 2.3.0, 25 percent".' },
|
||||||
|
{ a: '200', b: 'Update finished', c: '"Version 2.3.0 is ready to install" / "The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds."' },
|
||||||
|
{ a: '200', b: 'After restart', c: 'Toast: "Update installed" / "RenewCMS is now on version 2.3.0." Plain restart: "Site restarted" / "Your site is running again."' },
|
||||||
|
{ a: '400', b: 'Update, nothing to install', c: 'Toast (info): "Nothing to update" / "You already have the latest version." The card refreshes.' },
|
||||||
|
{ a: '401', b: 'Any call', c: 'Handled globally: /login?redirect=/settings&reason=expired. No local copy.' },
|
||||||
|
{ a: '403', b: 'Any button, not the owner', c: 'Toast (error): "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." The card reloads as the admin view. An unverified account is handled globally.' },
|
||||||
|
{ a: '409', b: 'Update, Restart', c: 'Already running: toast (info) "An update is already running" / "Another owner started it. Progress shows here." Not prepared: the card shows the "Not prepared" state and "How to update".' },
|
||||||
|
{ a: '422', b: 'Update, file not trusted', c: '"We didn\'t use this update" / "The file didn\'t pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support."' },
|
||||||
|
{ a: '429', b: 'Check, Update', c: 'Card alert (info): "Too many tries" / "Wait a moment before trying again." Button reads "Try again in 0:42" and counts down.' },
|
||||||
|
{ a: '500 / network', b: 'Check', c: '"Couldn\'t check for updates" / "RenewCMS couldn\'t reach the update server. Check your connection and try again. Your site isn\'t affected." with "Try again".' },
|
||||||
|
{ a: '500 / network', b: 'Update', c: '"The download didn\'t finish" / "The connection dropped before the file was complete. Nothing was changed and your site is running as before." with "Try again".' },
|
||||||
|
{ a: '500 / network', b: 'Restart dialog', c: '"Couldn\'t start the restart. Nothing was changed and your site is still running. Try again in a moment."' },
|
||||||
|
{ a: 'Site back, old version', b: 'After restart', c: '"The update didn\'t install" / "RenewCMS put the previous version back, so your site is running as before. Nothing was lost." Next step: "try again in a few minutes. If it fails again, ask whoever manages your server to check the update."' },
|
||||||
|
{ a: 'No answer, 60 s', b: 'Restart overlay', c: '"Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now."' },
|
||||||
|
{ a: 'Offline', b: 'Whole page', c: 'Existing banner. Check, Update and Restart are disabled. During a restart, the overlay keeps polling and ignores the offline state.' }
|
||||||
] },
|
] },
|
||||||
{ label: 'Profile', title: 'Profile', route: '/profile', api: 'GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset', note: 'Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters. Once saved it replaces the username everywhere a person is named: the sidebar, the account menu, the Home greeting, the Users list (with the username beside it) and the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS". Saving it empty goes back to the username. The reset link uses the same flow as "Forgot password" and ends on the auth board\'s "Choose a new password" screen.', states: [
|
{ label: 'Profile', title: 'Profile', route: '/profile', api: 'GET /v1/auth/me · PATCH /v1/user/me (pending) · POST /v1/auth/password-reset', note: 'Opened from the account menu at the bottom of the sidebar. Username, email and password are read-only. The display name is optional, trimmed, and up to 60 characters. Once saved it replaces the username everywhere a person is named: the sidebar, the account menu, the Home greeting, the Users list (with the username beside it) and the emails RenewCMS sends, such as "Marta Alves invited you to RenewCMS". Saving it empty goes back to the username. The reset link uses the same flow as "Forgot password" and ends on the auth board\'s "Choose a new password" screen.', states: [
|
||||||
withM({ ...home, home: { sub: 'Here\'s where things stand on your site.', stats, recent }, userMenu: true, name: 'Account menu', trigger: 'The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.' }),
|
withM({ ...home, home: { sub: 'Here\'s where things stand on your site.', stats, recent }, userMenu: true, name: 'Account menu', trigger: 'The account chip at the bottom of the sidebar. On mobile, the account row in the navigation drawer opens it as a sheet. Escape or a click outside closes it.' }),
|
||||||
@@ -211,8 +354,9 @@ class Component extends DCLogic {
|
|||||||
withM({ ...L({ offline: true }), name: 'Offline banner', trigger: 'navigator.onLine is false. The banner is shown on every back-office page.' }),
|
withM({ ...L({ offline: true }), name: 'Offline banner', trigger: 'navigator.onLine is false. The banner is shown on every back-office page.' }),
|
||||||
withM({ ...L({ toasts: [T('success', 'circle-check', 'Article published', '"Winter checklist for timber windows" is now online.'), T('info', 'info', 'That article no longer exists', 'It was deleted somewhere else, so we removed it from the list.'), T('error', 'circle-x', 'Couldn\'t unpublish', 'The server didn\'t respond. Nothing changed.', 'Retry')] }), name: 'Toast stack', trigger: 'Three at most, newest at the bottom. A fourth pushes out the oldest non-error toast.' })
|
withM({ ...L({ toasts: [T('success', 'circle-check', 'Article published', '"Winter checklist for timber windows" is now online.'), T('info', 'info', 'That article no longer exists', 'It was deleted somewhere else, so we removed it from the list.'), T('error', 'circle-x', 'Couldn\'t unpublish', 'The server didn\'t respond. Nothing changed.', 'Retry')] }), name: 'Toast stack', trigger: 'Three at most, newest at the bottom. A fourth pushes out the oldest non-error toast.' })
|
||||||
] }
|
] }
|
||||||
]
|
])
|
||||||
}
|
}
|
||||||
|
finish(gs) { return gs.map(g => ({ ...g, states: g.states.map(st => ({ notMedia: !st.isMedia, ...st, m: { ...st.m } })) })) }
|
||||||
renderVals() {
|
renderVals() {
|
||||||
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => {
|
const modes = [['system', 'System'], ['light', 'Light'], ['dark', 'Dark']].map(([k, label]) => {
|
||||||
const on = this.state.mode === k
|
const on = this.state.mode === k
|
||||||
|
|||||||
+100
-2
@@ -80,6 +80,60 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
|
|||||||
| Editor | `/article/:id/edit` | Offline | navigator.onLine is false | [editor](screens/editor.md) |
|
| Editor | `/article/:id/edit` | Offline | navigator.onLine is false | [editor](screens/editor.md) |
|
||||||
| Editor | `/article/:id/edit` | Deleted | 204: /article with toast | [editor](screens/editor.md) |
|
| Editor | `/article/:id/edit` | Deleted | 204: /article with toast | [editor](screens/editor.md) |
|
||||||
| Editor | `/article/:id/edit` | Session expired | 401: draft kept in sessionStorage, then /login | [editor](screens/editor.md) |
|
| Editor | `/article/:id/edit` | Session expired | 401: draft kept in sessionStorage, then /login | [editor](screens/editor.md) |
|
||||||
|
| Media | `/media` | Grid, many images | Default view | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Grid, few images | Three images | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | List view | The list icon in the toggle | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Loading | The first load, a retry, or a change of search or filter | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Empty library, first run | Zero images | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | No results | Search or filter matched nothing | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Hover, focus and keyboard | Hover (second item) darkens the border, adds the pop shadow and reveals the checkbox | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Selection and bulk bar | Checkbox on any item, or Space | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Bulk delete: confirm | Delete in the bulk bar | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Bulk delete: in progress | Requests in flight | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Bulk delete: partly failed | Some requests failed | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Bulk delete: done | 204 for all | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Detail panel: in use | Click or Enter on an item | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Detail panel: unused | Used in nothing | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Detail panel: duplicate | The image has identical copies | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Copy URL | Copy URL | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Rename: dialog | Rename in the panel | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Rename: saving | PATCH in flight | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Rename: validation | Empty or only symbols, on submit or blur | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Rename: failed | 500 or network failure | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Rename: done | 200: the panel title and list update in place | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Delete: unused image | Delete in the panel | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Delete: image in use | Stronger confirm | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Delete: in progress | DELETE in flight | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Delete: failed | 500 or network failure | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Delete: done | 204: the panel closes, the item leaves the grid and focus moves to the next item | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Image already gone (404) | Any action on an image that was deleted elsewhere | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Upload: drag over the page | Files dragged onto the page | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Upload: several files, mixed | Upload button or drop, several files | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Upload: summary | All rows settled | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Upload: rejected files (413, 400) | Type and size are checked in the browser first, so nothing is sent | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Upload: too many requests (429) | Rate limited | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Duplicates: groups | The Duplicates tab | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Duplicates: empty | No groups | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Merge: confirm | "Merge into this one" on floorboards.jpg | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Merge: in progress | Request in flight | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Merge: failed | 500 or network failure | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Merge: conflict (409) | A copy was deleted, or a new copy appeared, since the page loaded | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Merge: done | 200: the group leaves the list | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | List failed to load | A 500 or network failure on the list request | [media](screens/media.md) |
|
||||||
|
| Media | `/media` | Offline | navigator.onLine is false | [media](screens/media.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Upload tab | The image button in the toolbar | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Upload tab: already in your library | A chosen file has the same content as an existing image | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Library: loading | The Library tab was opened, or a search changed | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Library: nothing selected | Newest first | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Library: selected | One image selected (single selection) | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Library: alt text entered | Alt text is optional | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Library: loading more | "Load more" pressed | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Library: empty | Zero images | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Library: no results | Search matched nothing | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Library: failed to load | A 500 or network failure | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Inserted | Insert image from either tab | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Remove image: confirm | Remove image on an image in the article | [media-picker](screens/media-picker.md) |
|
||||||
|
| Media picker | `/article/:id/edit` | Removed | Confirmed | [media-picker](screens/media-picker.md) |
|
||||||
| Integration | `/integration` | Default | Page load | [integration](screens/integration.md) |
|
| Integration | `/integration` | Default | Page load | [integration](screens/integration.md) |
|
||||||
| Integration | `/integration` | Copied | Copy clicked (2 s) | [integration](screens/integration.md) |
|
| Integration | `/integration` | Copied | Copy clicked (2 s) | [integration](screens/integration.md) |
|
||||||
| Users | `/users` | Default | List loaded, newest first | [users](screens/users.md) |
|
| Users | `/users` | Default | List loaded, newest first | [users](screens/users.md) |
|
||||||
@@ -95,7 +149,33 @@ Every state is drawn at desktop and mobile on the screen boards, with final copy
|
|||||||
| Users | `/users` | Renew invite: sending | "Renew invite" on an Expired row; POST in flight | [users](screens/users.md) |
|
| Users | `/users` | Renew invite: sending | "Renew invite" on an Expired row; POST in flight | [users](screens/users.md) |
|
||||||
| Users | `/users` | Renew invite: done | 200: row Pending on top, toast | [users](screens/users.md) |
|
| Users | `/users` | Renew invite: done | 200: row Pending on top, toast | [users](screens/users.md) |
|
||||||
| Users | `/users` | Renew invite: failed | 500 or network: toast, row stays Expired | [users](screens/users.md) |
|
| Users | `/users` | Renew invite: failed | 500 or network: toast, row stays Expired | [users](screens/users.md) |
|
||||||
| Settings | `/settings` | Default | Opened from the sidebar | [settings](screens/settings.md) |
|
| Settings | `/settings` | Up to date | Opened with no newer version | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Checking | Check for updates pressed, or the first open after 24 hours | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Check failed | Offline, or the update server didn't answer (500, network) | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Update available | A newer version exists | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Update available, notes open | "What's new in 2.3.0" expanded | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Downloading | Update pressed (202) | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Verifying | The download finished | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Ready to install | The file passed its checks | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Restart: confirm | Restart pressed | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Restart: request failed | 500 or network failure before the restart began | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Restarting to install | Full-page overlay, so it survives the server going away | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Restarting, taking longer | No answer after 60 seconds | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Update done | The page reloaded on the new version | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Update failed, rolled back | The site came back on v2.2.0-beta | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Download failed | A 500, or the connection dropped | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Verification failed | The downloaded file isn't trusted | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Too many requests (429) | Retry-After counted down in the button | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Not prepared | The server can't update from the browser | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Not prepared: command copied | Copy pressed | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Plain restart: confirm | Restart with no update waiting | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Plain restart: restarting | Same overlay as the update restart with shorter copy | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Plain restart: done | The page reloaded | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Admin view | Admins see the version and the note, with no buttons | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Role changed (403) | An owner was changed to admin while the page was open and pressed a button | [settings](screens/settings.md) |
|
||||||
|
| Settings | `/settings` | Update already running (409) | Another owner started it | [settings](screens/settings.md) |
|
||||||
|
| Home | `/home` | Update available (owner) | Owner only: quiet banner and Settings pill | [home](screens/home.md) |
|
||||||
|
| Home | `/home` | Update ready to install (owner) | Download checked: banner copy changes | [home](screens/home.md) |
|
||||||
| Profile | `/profile` | Account menu | Account chip clicked | [profile](screens/profile.md) |
|
| Profile | `/profile` | Account menu | Account chip clicked | [profile](screens/profile.md) |
|
||||||
| Profile | `/profile` | Loading | Opened by URL before /auth/me returns | [profile](screens/profile.md) |
|
| Profile | `/profile` | Loading | Opened by URL before /auth/me returns | [profile](screens/profile.md) |
|
||||||
| Profile | `/profile` | Default, no display name | First visit | [profile](screens/profile.md) |
|
| Profile | `/profile` | Default, no display name | First visit | [profile](screens/profile.md) |
|
||||||
@@ -164,4 +244,22 @@ Added by the Users and Profile screens, none of which exist yet:
|
|||||||
|
|
||||||
Still not supported, so shown disabled or omitted:
|
Still not supported, so shown disabled or omitted:
|
||||||
|
|
||||||
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the email or username, listing or deleting individual images, removing users, promoting or demoting anyone, and any role other than owner and admin. Changing the password while logged in works only through the emailed reset link on the Profile page.
|
Renaming a title (shown read-only, with an explanation in Details), resending the verification email (the pending page explains how to start over), changing the email or username, removing users, promoting or demoting anyone, and any role other than owner and admin. Changing the password while logged in works only through the emailed reset link on the Profile page.
|
||||||
|
|
||||||
|
Added by the Updates card, none of which exists yet (owner only unless noted, see [settings](screens/settings.md)):
|
||||||
|
|
||||||
|
- `GET /v1/system/update` (any verified user): `{ current, latest, available, notes: { version, released_at, items }, checked_at, can_apply, state, progress, error, started_at }`. `state` is `idle`, `downloading`, `verifying`, `ready`, `restarting`, `succeeded` or `failed`. `can_apply` is false when the server hasn't been prepared, or for admins.
|
||||||
|
- `POST /v1/system/update/check`: asks the release feed. 200, 429 with `Retry-After`, 500 when the feed can't be reached.
|
||||||
|
- `POST /v1/system/update/download`: 202 starts the download and verification, 400 when there is nothing to update, 403, 409 when one is already running or the server isn't prepared, 422 when the file fails verification, 429.
|
||||||
|
- `POST /v1/system/update/restart`: 202 starts the install and restart (or only a restart when no update is ready), 403, 409, 500.
|
||||||
|
- A restart must survive the server going away: the SPA polls `/healthz` and `GET /v1/system/update` until they answer.
|
||||||
|
|
||||||
|
Added by the Media screens, none of which exist yet:
|
||||||
|
|
||||||
|
- `GET /v1/media/?q=&filter=&sort=&limit=&cursor=&hash=`: the library, newest first by default. `hash` (SHA-256 hex) returns only the images with that content, which is how the browser checks for a duplicate before uploading. Each item carries `id`, `filename`, `url`, `size`, `content_type`, `width`, `height` (null for SVG), `uploaded_by`, `created_at`, `used_in` (count) and `duplicate` (bool). The response also carries the counts for the Unused and Duplicates tabs.
|
||||||
|
- `POST /v1/media/`: multipart `file`, no article id. 201 with the item. It always stores the file: the duplicate check happens in the browser (hash with `crypto.subtle`, then `GET /v1/media/?hash=`), and when `crypto.subtle` is unavailable the check is skipped and any duplicate shows up under Duplicates. The server keeps each image's SHA-256. 413 for over 10 MB, 415 for another type, 400 for an unreadable image, 429 with `Retry-After`.
|
||||||
|
- `PATCH /v1/media/{id}`: `{ filename }`, the extension is kept and the URL does not change. 200, 404.
|
||||||
|
- `DELETE /v1/media/{id}`: 204, 404. Deleting an image that is in use is allowed.
|
||||||
|
- `POST /v1/media/merge`: `{ keep_id, merge_ids }`. Rewrites article bodies from the merged copies' URLs to the kept image's URL, then deletes the copies. 200 with `{ articles_updated, merged }`, 404, 409 when a listed copy is gone or the group changed.
|
||||||
|
- `GET /v1/media/{id}/usage`: `[{ id, title, published }]`, read from article bodies.
|
||||||
|
- Images no longer belong to an article, and deleting an article no longer deletes images. `POST /v1/article/{id}/image` and `DELETE /v1/article/{id}/image/{imageId}` are replaced by the endpoints above.
|
||||||
@@ -17,7 +17,7 @@ Rules: bullets are full sentences ending with a period; user-facing wording, no
|
|||||||
|
|
||||||
## Published releases
|
## Published releases
|
||||||
|
|
||||||
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<name>" --note-file docs/releases/<tag>.md --prerelease --asset <binary>` (one `--asset` per binary), after `task release`.
|
Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create --tag <tag> --title "<name>" --note-file docs/releases/<tag>.md --prerelease --asset <file>` after `task release`, with one `--asset` per file: the six binaries, `bin/checksums.txt` and `bin/checksums.txt.sig`. `task release` produces all eight and fails before building when the signing key is missing or wrong (see [deployment.md](deployment.md#release-signing-key-maintainers-once)). Never publish a release without the two checksum files.
|
||||||
|
|
||||||
| Tag | Name |
|
| Tag | Name |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
@@ -26,3 +26,6 @@ Each body lives in `docs/releases/<tag>.md`. Publish with `tea releases create -
|
|||||||
| `v2.2.0-beta` | v2.2.0-beta - Image crop, image removal & reset screens |
|
| `v2.2.0-beta` | v2.2.0-beta - Image crop, image removal & reset screens |
|
||||||
| `v2.3.0-beta` | v2.3.0-beta - Multi-user invitations, display names & profile page |
|
| `v2.3.0-beta` | v2.3.0-beta - Multi-user invitations, display names & profile page |
|
||||||
| `v2.4.0-beta` | v2.4.0-beta - Owner role, invite management & Settings page |
|
| `v2.4.0-beta` | v2.4.0-beta - Owner role, invite management & Settings page |
|
||||||
|
| `v2.5.0-beta` | v2.5.0-beta - Media library & image picker |
|
||||||
|
| `v2.6.0-beta` | v2.6.0-beta - Signed updates and browser restart |
|
||||||
|
| `v2.6.2-beta` | v2.6.2-beta - English and French interface |
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
RenewCMS now has a media library. Every uploaded image lives in one place where you can browse, rename, delete and clean up duplicates, and the article editor can reuse an image you already uploaded.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Media page**
|
||||||
|
- A new Media page at `/media` sits between Articles and Users in the sidebar and the mobile drawer.
|
||||||
|
- Browse the library as a grid or a list, with search by filename, sort by newest, oldest, name or largest, and Unused and Duplicates tabs with counts.
|
||||||
|
- Open an image to see its type, size, dimensions, uploader, upload date and URL, copy its URL, and see which articles use it.
|
||||||
|
- Rename an image. Only the filename changes, the URL stays the same, so articles keep working.
|
||||||
|
- Delete one image or many at once. Deleting an image that is still used asks for a stronger confirmation and lists the articles that will show a broken image.
|
||||||
|
- Upload several images at once, with a progress row for each one and a summary. Drop files anywhere on the page.
|
||||||
|
- When you upload a file that is already in the library, you are told so and can use the existing image instead.
|
||||||
|
- A Duplicates view groups identical images and merges them into one. Articles that used the other copies switch to the one you keep.
|
||||||
|
|
||||||
|
**Image picker in the editor**
|
||||||
|
- The editor's "Add an image" dialog now has Upload and Library tabs. Pick an image you already uploaded, set its alt text and insert it.
|
||||||
|
- Images already in the article are tagged "In this article".
|
||||||
|
- Removing an image from an article now only removes it from that article. The file stays in the library.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
- Deleting an article no longer deletes its images, and its confirmation says so.
|
||||||
|
- An image that no longer exists shows a "This image is no longer available" placeholder in the editor, with a way to remove it, instead of a collapsed pixel.
|
||||||
|
- Deleted images stop showing as soon as you open an article, not only after a refresh. Uploaded images are now revalidated by the browser instead of being cached for a year.
|
||||||
|
- The editor's Images row in the article details counts the images in the article body.
|
||||||
|
|
||||||
|
## API
|
||||||
|
- `GET /v1/media/` lists the library with `q`, `filter` (`all`, `unused`, `duplicates`), `sort`, `limit`, `cursor` and `hash` parameters. Each item carries its size, type, dimensions, uploader, `used_in` count and a `duplicate` flag, and the response carries the counts for each tab.
|
||||||
|
- `POST /v1/media/` uploads an image (multipart `file`). It returns 201, 400 for an unreadable image, 413 for a file over 10 MB and 415 for another type.
|
||||||
|
- `PATCH /v1/media/{id}` renames an image and keeps its extension and URL. It returns 200, or 404.
|
||||||
|
- `DELETE /v1/media/{id}` deletes an image, even when articles use it. It returns 204, or 404.
|
||||||
|
- `POST /v1/media/merge` takes `keep_id` and `merge_ids`, switches the articles that use the other copies to the kept image, deletes the copies and returns how many articles changed. It returns 409 when a copy is gone or the images are no longer identical.
|
||||||
|
- `GET /v1/media/{id}/usage` lists the articles that use an image, with their title and whether they are online.
|
||||||
|
- Changed: images no longer belong to an article. `GET /v1/article/{id}` no longer returns `images`, and deleting an article keeps its images.
|
||||||
|
- Changed: `DELETE /v1/article/{id}/image/{imageId}` and `POST /v1/article/{id}/image` are removed, replaced by the `/v1/media/` endpoints.
|
||||||
|
- Changed: `/static/uploadedImages/*` now sends `Cache-Control: public, no-cache` instead of a one-year `immutable` lifetime.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
- The image domain, repository, use cases and handlers were rebuilt around a library model, keeping the domain, use-case and infrastructure layering.
|
||||||
|
- WEBP dimensions are read with `golang.org/x/image`. `golang.org/x/sys` and `golang.org/x/text` were updated with it.
|
||||||
|
- New feature specs and tests cover the media API, the Media page, uploads, duplicates and the editor picker.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
- Replace the binary and restart. Your `.env`, SQLite file and uploads directory stay as they are, and there are no new environment variables.
|
||||||
|
- The database migrates itself on startup. It adds columns to the images table, and a one-time backfill reads each existing image file to fill in its size, type, dimensions and content hash. An image whose file is missing is left alone. Back up your SQLite file and uploads directory first as a precaution.
|
||||||
|
- Existing images become part of the library and are no longer tied to an article. The old article link is no longer used.
|
||||||
|
- Clients that call the removed article image endpoints, or read `images` from an article, must switch to `/v1/media/`.
|
||||||
|
- Browsers keep serving images they cached before the upgrade until they are reloaded once.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
- The Media page shows only the first 100 images.
|
||||||
|
- There is no rate limit on `/v1/media/` yet.
|
||||||
|
- The library list loads every article and image in memory, so very large libraries will be slow.
|
||||||
|
- A file whose extension doesn't match its content type, such as a JPEG labelled as PNG, is rejected.
|
||||||
|
- Searching filenames with non-ASCII letters is case-sensitive.
|
||||||
|
- Uploaded SVGs are served as they are. They are sandboxed with a restrictive content security policy, but not sanitised.
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
RenewCMS can now check for releases, download a signed update and install it from Settings. On Linux with systemd, the owner can restart the site from the browser, with automatic binary rollback if the new version fails to start.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**Updates in Settings**
|
||||||
|
- Owners can check for a newer release, read its release notes and download it while the site stays online.
|
||||||
|
- Downloads show progress, verify the release signature and binary checksum, check the staged version and back up the database before becoming ready to install.
|
||||||
|
- The Home page and Settings navigation show an owner-only update notification, and the Home banner can be dismissed for each version.
|
||||||
|
- Admins can read the update status without starting an update or restart.
|
||||||
|
|
||||||
|
**Browser restart and installation**
|
||||||
|
- Owners can confirm an update installation or a plain site restart from Settings.
|
||||||
|
- A restart overlay waits for the site to return and offers a reload action when the restart takes longer than expected.
|
||||||
|
- Linux installations with systemd can enable browser updates using `renewcms enable-browser-updates` and remove the helper using `renewcms disable-browser-updates`.
|
||||||
|
- The helper verifies the staged files again, keeps the previous binary and restores it if the new version does not start successfully.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
- Update status and download progress survive navigation and are shared between owners.
|
||||||
|
- Update checks and download starts have separate per-user rate limits with retry countdowns.
|
||||||
|
- Restart confirmations identify whether the action installs an update or only restarts the site, and refuse a request when another owner's action has changed that state.
|
||||||
|
- Completion messages are shown in the browser tab that requested the restart.
|
||||||
|
|
||||||
|
## API
|
||||||
|
- `GET /v1/system/update` returns the current and latest versions, release notes, release URL, helper availability, progress, state, error kind and operation timestamps for verified users, without changing state.
|
||||||
|
- `POST /v1/system/update/check` checks the release feed for owners and returns 200, 403 for insufficient permissions, 429 with `Retry-After`, or 500 when the feed cannot be reached.
|
||||||
|
- `POST /v1/system/update/download` starts an owner-only background download with 202, or returns 400 when nothing is available, 403, 409 for an unavailable helper or conflicting job, 422 for a pre-flight refusal, or 429.
|
||||||
|
- `POST /v1/system/update/restart` accepts an optional `kind` of `update` or `restart` and returns 202, 400 for invalid input, 403, 409 for an unavailable helper or conflicting state, or 500 when the request cannot be saved.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
- Releases include signed `checksums.txt` and `checksums.txt.sig` files alongside the six platform binaries.
|
||||||
|
- The update helper runs separately from the unprivileged app, copies staged files into a private directory and verifies the bytes it installs rather than trusting a mutable staged path.
|
||||||
|
- Feature specifications, fake-backed Go tests and SPA tests cover release checks, downloads, restart requests and rollback decisions.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
- Back up your SQLite database and uploads, then replace the binary and restart manually for this first release with browser-update support.
|
||||||
|
- No database schema change is introduced by the update features.
|
||||||
|
- `UPDATE_FEED_URL` is optional and defaults to the project's release feed; existing configuration remains usable.
|
||||||
|
- On Linux with systemd, run `sudo renewcms enable-browser-updates` after the manual upgrade to enable future updates and restarts from Settings.
|
||||||
|
- Keep the update status files, staged files and backups beside the database in the data directory, with the permissions described in `docs/deployment.md`.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
- The privileged update helper has automated coverage through fakes, but its first real Linux/systemd update and rollback checks are still pending.
|
||||||
|
- Browser installation and restart require Linux with systemd; Windows, macOS and other init systems remain manual upgrades.
|
||||||
|
- Updating or restarting briefly takes the site offline, and a reverse proxy may return errors during that interval.
|
||||||
|
- Automatic rollback restores the previous binary; it does not restore the database, so schema-changing upgrades still require a backup and a recovery plan.
|
||||||
|
- Update assets and redirects must use HTTPS on the configured feed host.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
This release adds English and French throughout the SPA, with an instant language switch and a preference remembered on this browser.
|
||||||
|
|
||||||
|
## New
|
||||||
|
|
||||||
|
**English and French interface**
|
||||||
|
|
||||||
|
- Choose English or Français from the Language control in the desktop or mobile profile submenu.
|
||||||
|
- Switch interface language immediately while keeping your current page and unsaved work.
|
||||||
|
- Keep your selected language after navigation, reload and logout, including on authentication screens.
|
||||||
|
- See translated forms, validation, notifications, dialogs and accessibility labels, with localized dates, numbers and counts.
|
||||||
|
|
||||||
|
## Improvements and fixes
|
||||||
|
|
||||||
|
- Keep partial bulk-delete failure notifications available after retrying, including when switching languages.
|
||||||
|
|
||||||
|
## Under the hood
|
||||||
|
|
||||||
|
- Add translation catalog parity, fallback, persistence and SPA interaction tests.
|
||||||
|
|
||||||
|
## Upgrading
|
||||||
|
|
||||||
|
- Install the signed update through Settings on a prepared Linux/systemd installation, or replace the binary and restart the service.
|
||||||
|
- No database migration or new environment variable is required.
|
||||||
|
- English remains the default until a language is selected; the preference is stored locally in the browser.
|
||||||
|
- User content, API data and transactional emails retain their existing language.
|
||||||
|
|
||||||
|
## Known limitations
|
||||||
|
|
||||||
|
- Visual parity checks for this feature were skipped under the accepted slice waiver.
|
||||||
@@ -59,9 +59,9 @@ Feature: Articles list screen
|
|||||||
remaining articles, and raises an info toast (icon info, id "article-not-found-{id}"): title
|
remaining articles, and raises an info toast (icon info, id "article-not-found-{id}"): title
|
||||||
"That article no longer exists" text "It was deleted somewhere else, so we removed it from
|
"That article no longer exists" text "It was deleted somewhere else, so we removed it from
|
||||||
the list."
|
the list."
|
||||||
And "Delete…" opens ConfirmDialog: title "Delete this article?" text "\"{title}\" and its
|
And "Delete…" opens ConfirmDialog: title "Delete this article?" text "\"{title}\" will be
|
||||||
{n} images will be deleted. This can't be undone." (a components.md convention: the row's
|
deleted. Its images stay in your library. This can't be undone." (the second sentence is
|
||||||
title plus its image count, "and its image" for exactly 1 and no image clause at all for 0),
|
present only when the article body holds at least one image),
|
||||||
"Cancel" and "Delete article" (danger); while the DELETE request is in flight the dialog
|
"Cancel" and "Delete article" (danger); while the DELETE request is in flight the dialog
|
||||||
cannot be dismissed by Cancel, Esc or a backdrop click, both buttons are disabled, the
|
cannot be dismissed by Cancel, Esc or a backdrop click, both buttons are disabled, the
|
||||||
confirm button reads "Deleting…" with a loading indicator, and aria-busy is set
|
confirm button reads "Deleting…" with a loading indicator, and aria-busy is set
|
||||||
@@ -72,7 +72,7 @@ Feature: Articles list screen
|
|||||||
And a successful delete (204) closes the dialog, removes the row, moves focus to the next row
|
And a successful delete (204) closes the dialog, removes the row, moves focus to the next row
|
||||||
(or the page heading if the deleted row was last), recomputes the tab counts, and raises a
|
(or the page heading if the deleted row was last), recomputes the tab counts, and raises a
|
||||||
success toast (icon circle-check, id "article-deleted-{id}"): title "Article deleted" text
|
success toast (icon circle-check, id "article-deleted-{id}"): title "Article deleted" text
|
||||||
"\"{title}\" and its images are gone."; this is also where a delete initiated from the editor
|
"\"{title}\" is gone."; this is also where a delete initiated from the editor
|
||||||
ends up
|
ends up
|
||||||
And the list, sorted by last updated with the most recently updated article first, holds
|
And the list, sorted by last updated with the most recently updated article first, holds
|
||||||
these 6 articles by default: id 1 "How we price a bathroom renovation" (online, updated "2
|
these 6 articles by default: id 1 "How we price a bathroom renovation" (online, updated "2
|
||||||
@@ -231,7 +231,7 @@ Feature: Articles list screen
|
|||||||
Given the Default state has loaded, and id 4 "Winter checklist for timber windows" has 3 images
|
Given the Default state has loaded, and id 4 "Winter checklist for timber windows" has 3 images
|
||||||
When the user chooses "Delete…" from id 4's row menu
|
When the user chooses "Delete…" from id 4's row menu
|
||||||
Then ConfirmDialog opens: title "Delete this article?" text "\"Winter checklist for timber
|
Then ConfirmDialog opens: title "Delete this article?" text "\"Winter checklist for timber
|
||||||
windows\" and its 3 images will be deleted. This can't be undone.", "Cancel" and "Delete
|
windows\" will be deleted. Its images stay in your library. This can't be undone.", "Cancel" and "Delete
|
||||||
article" (danger)
|
article" (danger)
|
||||||
|
|
||||||
Scenario: Delete in progress — the dialog cannot be dismissed while the request is in flight
|
Scenario: Delete in progress — the dialog cannot be dismissed while the request is in flight
|
||||||
@@ -256,4 +256,4 @@ Feature: Articles list screen
|
|||||||
Then the dialog closes, id 4's row is removed from the list, and focus moves to the next row
|
Then the dialog closes, id 4's row is removed from the list, and focus moves to the next row
|
||||||
And the tabs read "All 5" "Online 4" "Drafts 1"
|
And the tabs read "All 5" "Online 4" "Drafts 1"
|
||||||
And a success toast appears: icon circle-check, id "article-deleted-4", title "Article
|
And a success toast appears: icon circle-check, id "article-deleted-4", title "Article
|
||||||
deleted", text "\"Winter checklist for timber windows\" and its images are gone."
|
deleted", text "\"Winter checklist for timber windows\" is gone."
|
||||||
@@ -114,7 +114,7 @@ as listed), unless a scenario's Examples row substitutes a smaller fixture.
|
|||||||
18. **Deleted** — continuing from 16 (a fresh attempt), resolve the DELETE 204; assert the dialog
|
18. **Deleted** — continuing from 16 (a fresh attempt), resolve the DELETE 204; assert the dialog
|
||||||
closes, id 4's row is removed, focus moves to the next row; assert tabs read "All 5" "Online
|
closes, id 4's row is removed, focus moves to the next row; assert tabs read "All 5" "Online
|
||||||
4" "Drafts 1"; assert a toast with id "article-deleted-4", icon circle-check, title "Article
|
4" "Drafts 1"; assert a toast with id "article-deleted-4", icon circle-check, title "Article
|
||||||
deleted", text "\"Winter checklist for timber windows\" and its images are gone."
|
deleted", text "\"Winter checklist for timber windows\" is gone."
|
||||||
|
|
||||||
## Visual (manual verification — desktop and mobile, light and dark)
|
## Visual (manual verification — desktop and mobile, light and dark)
|
||||||
|
|
||||||
|
|||||||
@@ -1,84 +0,0 @@
|
|||||||
Feature: Deleting an article also deletes its images
|
|
||||||
|
|
||||||
As an authenticated RenewCMS user managing the CMS
|
|
||||||
I want deleting an article to also delete every image attached to it
|
|
||||||
So that removing an article doesn't leave orphaned image rows and files behind,
|
|
||||||
and so that an id that doesn't exist still answers 404 the same way every other
|
|
||||||
article write does
|
|
||||||
|
|
||||||
Background:
|
|
||||||
Given internal/domain/article.Article carries Images []*image.Image, populated by
|
|
||||||
ArticleRepository.Get via Preload("Images")
|
|
||||||
And internal/domain/image.Repository already exposes Delete(id uint32) error, which
|
|
||||||
on the real ImageRepository also removes the uploaded file from UPLOAD_DIR
|
|
||||||
And before this slice, DeleteArticleUseCase.DeleteArticle only called
|
|
||||||
articleRepository.Delete(id) and never touched image.Repository, so an article's
|
|
||||||
images were never deleted along with it
|
|
||||||
And this slice changes NewDeleteArticleUseCase to also take an image.Repository, and
|
|
||||||
changes DeleteArticleUseCase.DeleteArticle(id) to look up the article, delete every
|
|
||||||
image in its Images slice through image.Repository.Delete, and only then delete the
|
|
||||||
article itself through article.Repository.Delete
|
|
||||||
And this slice rewires api/dependecyInjection.go so
|
|
||||||
useCases.NewDeleteArticleUseCase(repos.ArticleRepo, repos.ImageRepo) supplies both
|
|
||||||
repositories
|
|
||||||
And DELETE /v1/article/{id} keeps sitting behind the jwtauth Verifier and
|
|
||||||
Authenticator group in api/router.go, unchanged from
|
|
||||||
features/write_not_found_errors.feature
|
|
||||||
And DELETE /v1/article/{id} keeps answering 204 with an empty body on success and 404
|
|
||||||
with body apperr.ArticleNotFoundErrorMessage for an id absent from the article
|
|
||||||
repository, backed by errors.Is(err, article.ErrArticleNotFound), unchanged from
|
|
||||||
features/write_not_found_errors.feature
|
|
||||||
And no image HTTP endpoint is mounted in api/router.go as of this slice, so cascading
|
|
||||||
image deletion is only observable through the image repository's state, not through
|
|
||||||
a separate HTTP call
|
|
||||||
And the use case deletes images in the order they appear in the article's Images
|
|
||||||
slice, and aborts on the first image.Repository.Delete error, leaving the article
|
|
||||||
and any not-yet-deleted images untouched, and answering the same generic 500 the
|
|
||||||
DeleteArticle handler already falls back to on any non-not-found error
|
|
||||||
|
|
||||||
Scenario: Deleting an article with images removes the article and every one of its images
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository contains an article with id 1 whose Images slice holds
|
|
||||||
image id 10 and image id 11
|
|
||||||
And the image repository contains images with id 10 and id 11
|
|
||||||
When the client sends DELETE /v1/article/1 with that cookie
|
|
||||||
Then the response status is 204
|
|
||||||
And the article repository no longer contains an article with id 1
|
|
||||||
And the image repository no longer contains an image with id 10 or id 11
|
|
||||||
|
|
||||||
Scenario: Deleting an article with no images still succeeds
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository contains an article with id 2 whose Images slice is empty
|
|
||||||
When the client sends DELETE /v1/article/2 with that cookie
|
|
||||||
Then the response status is 204
|
|
||||||
And the article repository no longer contains an article with id 2
|
|
||||||
And no call reaches the image repository's Delete method
|
|
||||||
|
|
||||||
Scenario: Deleting an unknown article still answers 404 and deletes no images
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository has no article with id 9999
|
|
||||||
When the client sends DELETE /v1/article/9999 with that cookie
|
|
||||||
Then the response status is 404
|
|
||||||
And the response body is the text "Article not found"
|
|
||||||
And no call reaches the image repository's Delete method
|
|
||||||
|
|
||||||
Scenario: Deleting an article still requires authentication
|
|
||||||
Given no jwt cookie is sent
|
|
||||||
And the article repository contains an article with id 1 whose Images slice holds
|
|
||||||
image id 10
|
|
||||||
When the client sends DELETE /v1/article/1 without a cookie
|
|
||||||
Then the response status is 401
|
|
||||||
And the article repository still contains the article with id 1
|
|
||||||
And the image repository still contains the image with id 10
|
|
||||||
|
|
||||||
Scenario: A failure deleting one of an article's images aborts the whole delete
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository contains an article with id 3 whose Images slice holds
|
|
||||||
image id 20 followed by image id 21
|
|
||||||
And the image repository contains images with id 20 and id 21
|
|
||||||
And the image repository's Delete fails for image id 20
|
|
||||||
When the client sends DELETE /v1/article/3 with that cookie
|
|
||||||
Then the response status is 500
|
|
||||||
And the response body is the text "Failed to delete article"
|
|
||||||
And the article repository still contains the article with id 3
|
|
||||||
And the image repository still contains the image with id 21
|
|
||||||
@@ -1,67 +0,0 @@
|
|||||||
# QA procedure: delete_article_cascades_images
|
|
||||||
|
|
||||||
Package: `test` (black-box, extending `article_test.go`).
|
|
||||||
|
|
||||||
## Setup shared by every case
|
|
||||||
1. Call `validator.InitValidator()` once.
|
|
||||||
2. Reuse `mockArticleRepo` (`test/article_test.go`) and `mockImageRepo`
|
|
||||||
(`test/image_test.go`) as-is. Extend `mockArticleRepo` seeding so a seeded article's
|
|
||||||
`Images []*image.Image` can hold pointers into the same `mockImageRepo.images` map used
|
|
||||||
by the test, so deleting through the article side and asserting through the image side
|
|
||||||
observe the same state.
|
|
||||||
3. Add a call counter (or reuse the existing `failSwitch`/call-tracking pattern already in
|
|
||||||
`test/`) on `mockImageRepo.Delete` so a scenario can assert it was never called, and reuse
|
|
||||||
`mockImageRepo.fail` (the existing `failSwitch`) to make `Delete` fail for a specific
|
|
||||||
image id.
|
|
||||||
4. Wire the real use cases over the fakes: `useCases.NewCreateArticleUseCase`,
|
|
||||||
`useCases.NewGetArticleUseCase`, `useCases.NewListArticlesUseCase`,
|
|
||||||
`useCases.NewUpdateArticleUseCase`, and the new two-argument
|
|
||||||
`useCases.NewDeleteArticleUseCase(articleRepo, imageRepo)`. Build `article.NewHandler(...)`
|
|
||||||
with the same constructor shape it already has (the use case's internal dependency count
|
|
||||||
changes, not the handler's).
|
|
||||||
5. Build a test `jwtauth.New("HS256", []byte("test-secret"), nil)`.
|
|
||||||
6. Mount the routes on a fresh `chi.NewRouter()` mirroring `api/router.go`'s current shape:
|
|
||||||
`GET /` under `jwtauth.Verifier` only; `GET /{id}`, `POST /`, `DELETE /{id}`,
|
|
||||||
`PATCH /{id}`, `PATCH /{id}/publish`, `PATCH /{id}/unpublish` under `jwtauth.Verifier` +
|
|
||||||
`jwtauth.Authenticator`.
|
|
||||||
7. Mint a valid jwt cookie for user id 1: `token.Encode(map[string]any{"user_id": uint32(1)})`,
|
|
||||||
set as the `jwt` cookie on the relevant `httptest.NewRequest`.
|
|
||||||
|
|
||||||
## HTTP checks
|
|
||||||
8. Seed `imageRepo.images[10]` and `imageRepo.images[11]`, then seed
|
|
||||||
`articleRepo.articles[1] = article.Article{ID: 1, Title: "Backyard Renovation Update",
|
|
||||||
Images: []*image.Image{imageRepo.images[10], imageRepo.images[11]}}` (pointers into the
|
|
||||||
same map). Send `DELETE /v1/article/1` with the valid cookie -> status `204`; assert
|
|
||||||
`articleRepo.articles` no longer has key `1`; assert `imageRepo.images` no longer has
|
|
||||||
keys `10` or `11`.
|
|
||||||
9. Seed `articleRepo.articles[2] = article.Article{ID: 2, Title: "Draft: Kitchen Remodel"}`
|
|
||||||
with a nil/empty `Images` slice. Send `DELETE /v1/article/2` with the valid cookie ->
|
|
||||||
status `204`; assert `articleRepo.articles` no longer has key `2`; assert the image-delete
|
|
||||||
call counter is `0`.
|
|
||||||
10. Empty `articleRepo`, empty `imageRepo`. Send `DELETE /v1/article/9999` with the valid
|
|
||||||
cookie -> status `404`, body `"Article not found\n"`; assert the image-delete call
|
|
||||||
counter is `0`.
|
|
||||||
11. Seed `imageRepo.images[10]` and `articleRepo.articles[1]` with `Images` holding image id
|
|
||||||
10, per step 8's pattern. Send `DELETE /v1/article/1` with **no** cookie -> status `401`;
|
|
||||||
assert `articleRepo.articles[1]` is still present and `imageRepo.images[10]` is still
|
|
||||||
present.
|
|
||||||
12. Seed `imageRepo.images[20]` and `imageRepo.images[21]`, then seed
|
|
||||||
`articleRepo.articles[3] = article.Article{ID: 3, Title: "Kitchen Progress Photos",
|
|
||||||
Images: []*image.Image{imageRepo.images[20], imageRepo.images[21]}}` (image 20 before
|
|
||||||
image 21 in the slice). Arm `imageRepo.fail` so `Delete` returns an error only when
|
|
||||||
called with id `20` (leave id `21` unarmed). Send `DELETE /v1/article/3` with the valid
|
|
||||||
cookie -> status `500`, body `"Failed to delete article\n"`; assert
|
|
||||||
`articleRepo.articles[3]` is still present; assert `imageRepo.images[21]` is still
|
|
||||||
present (never reached because the delete aborted on image `20` first).
|
|
||||||
|
|
||||||
## Manual verification (not exercised by the Go test)
|
|
||||||
- Real cascading delete against a real SQLite file and real `UPLOAD_DIR`: confirm that after
|
|
||||||
`DELETE /v1/article/{id}` on a real running instance, the uploaded image files under
|
|
||||||
`UPLOAD_DIR` for that article are gone from disk and the `images` table no longer holds
|
|
||||||
those rows, and that no orphaned rows are left behind in the `article_images` join table.
|
|
||||||
Not exercised by `task test` (fakes only); requires `task dev` or a built `task build`
|
|
||||||
binary with a scratch DB/upload dir.
|
|
||||||
- SPA-visible behaviour: confirm the back-office article deletion flow (if/when one exists)
|
|
||||||
reflects that any images shown for that article are gone too. No such UI exists yet as of
|
|
||||||
this slice.
|
|
||||||
- No SMTP involvement.
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
Feature: Deleting an article never deletes images
|
||||||
|
|
||||||
|
As an authenticated RenewCMS user
|
||||||
|
I want deleting an article to leave the media library alone
|
||||||
|
So that an image used by other articles, or waiting in the library, is never lost
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given images belong to the library and internal/domain/article.Article carries no Images
|
||||||
|
And DeleteArticleUseCase depends only on article.Repository and calls its Delete
|
||||||
|
And api/dependecyInjection.go builds useCases.NewDeleteArticleUseCase(repos.ArticleRepo)
|
||||||
|
And DELETE /v1/article/{id} stays behind the same jwtauth group, answering 204 with an
|
||||||
|
empty body, 404 with apperr.ArticleNotFoundErrorMessage for errors.Is(err,
|
||||||
|
article.ErrArticleNotFound), and the generic 500 "Failed to delete article" otherwise
|
||||||
|
|
||||||
|
Scenario: Deleting an article leaves every image it used
|
||||||
|
Given a valid jwt cookie for user 1
|
||||||
|
And article 1 whose body contains the urls of images 10 and 11
|
||||||
|
And the image repository contains images 10 and 11
|
||||||
|
When the client sends DELETE /v1/article/1
|
||||||
|
Then the response status is 204
|
||||||
|
And the article repository no longer contains article 1
|
||||||
|
And the image repository still contains images 10 and 11 and Delete was never called
|
||||||
|
|
||||||
|
Scenario: Deleting an unknown article is 404 and touches no image
|
||||||
|
Given a valid jwt cookie for user 1 and no article 9999
|
||||||
|
When the client sends DELETE /v1/article/9999
|
||||||
|
Then the response status is 404 and the body is "Article not found"
|
||||||
|
And the image repository is untouched
|
||||||
|
|
||||||
|
Scenario: Deleting still requires authentication
|
||||||
|
Given no jwt cookie
|
||||||
|
When the client sends DELETE /v1/article/1
|
||||||
|
Then the response status is 401 and article 1 and image 10 still exist
|
||||||
|
|
||||||
|
Scenario: An article repository failure is 500 and everything stays
|
||||||
|
Given the article repository's Delete fails
|
||||||
|
When the client sends DELETE /v1/article/1 with a valid cookie
|
||||||
|
Then the response status is 500 and the body is "Failed to delete article"
|
||||||
|
And the image repository is untouched
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# QA procedure: delete_article_keeps_images
|
||||||
|
|
||||||
|
Package: `test` (black-box). Wire `useCases.NewDeleteArticleUseCase(articleRepo)` (single argument) with the other article use cases and mount as in the retired `delete_article_cascades_images.qa.md`: `Verifier` plus `Authenticator`, `RequireCurrentToken`, `RequireVerifiedUser`, jwt cookie for user id 1. Seed images 10 and 11 in `mockImageRepo` and the article body with their urls. Call `validator.InitValidator()` first.
|
||||||
|
|
||||||
|
## HTTP checks
|
||||||
|
1. `DELETE /v1/article/1` with a valid cookie -> 204, `articleRepo` no longer holds article 1, `imageRepo.images` still holds 10 and 11 and `deleteCalls` is empty.
|
||||||
|
2. `DELETE /v1/article/9999` -> 404, body `"Article not found\n"`, image repo untouched.
|
||||||
|
3. `DELETE /v1/article/1` without cookie -> 401, article and images still present.
|
||||||
|
4. Article fake's `Delete` armed to fail -> 500, body `"Failed to delete article\n"`, image repo untouched.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
With a real SQLite file and `UPLOAD_DIR`, delete an article and confirm the image files and rows remain and still load. No SMTP.
|
||||||
@@ -9,8 +9,10 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Given ImageUploader inserts a crop-and-resize step between the idle file picker and the
|
Given ImageUploader inserts a crop-and-resize step between the idle file picker and the
|
||||||
upload, for any JPEG, PNG or WEBP that already passed the browser validation described in
|
upload, for any JPEG, PNG or WEBP that already passed the browser validation described in
|
||||||
features/editor_image_upload.feature; that feature's idle, dragging-over, rejected,
|
features/editor_image_upload.feature; that feature's idle, dragging-over, rejected,
|
||||||
uploading, inserted and failed states and its POST /v1/article/{articleId}/image contract
|
uploading, inserted and failed states and its POST /v1/media/ contract are unchanged and
|
||||||
are unchanged and out of scope here
|
out of scope here
|
||||||
|
And the hash lookup from features/editor_image_upload.feature runs before this step opens,
|
||||||
|
so the step only opens for a file with no match, or after "Upload anyway"
|
||||||
And an SVG file skips this step entirely and uploads immediately, as before
|
And an SVG file skips this step entirely and uploads immediately, as before
|
||||||
And opening the step retitles the modal from "Add an image" to "Crop and resize", with the
|
And opening the step retitles the modal from "Add an image" to "Crop and resize", with the
|
||||||
description "{filename} · {size}" (e.g. "north-wall.jpg · 3.9 MB")
|
description "{filename} · {size}" (e.g. "north-wall.jpg · 3.9 MB")
|
||||||
@@ -32,8 +34,8 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
crop is narrower than the chosen width, an info row reads "The crop is {crop width} px
|
crop is narrower than the chosen width, an info row reads "The crop is {crop width} px
|
||||||
wide, so it's uploaded at that size. Enlarging it would make it blurry."
|
wide, so it's uploaded at that size. Enlarging it would make it blurry."
|
||||||
And the footer offers "Choose another file" (discards this step and returns to the idle file
|
And the footer offers "Choose another file" (discards this step and returns to the idle file
|
||||||
picker with no adjustments carried over) and "Upload image" (uploads the cropped, resized
|
picker, with the tabs, with no adjustments carried over) and "Upload image" (uploads the cropped, resized
|
||||||
file through the unchanged POST /v1/article/{articleId}/image flow)
|
file through the unchanged POST /v1/media/ flow)
|
||||||
And "Rotate" turns the image 90° clockwise each activation, cycling 0°→90°→180°→270°→0°, and
|
And "Rotate" turns the image 90° clockwise each activation, cycling 0°→90°→180°→270°→0°, and
|
||||||
width presets apply to the post-rotation image
|
width presets apply to the post-rotation image
|
||||||
And "Reset" returns the ratio to Original, the width to 1600 px, the crop frame to the whole
|
And "Reset" returns the ratio to Original, the width to 1600 px, the crop frame to the whole
|
||||||
@@ -43,7 +45,7 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Given ImageUploader is open in the idle state for article 12
|
Given ImageUploader is open in the idle state for article 12
|
||||||
When the user chooses a file named "north-wall.jpg", content type "image/jpeg", size 3.9 MB,
|
When the user chooses a file named "north-wall.jpg", content type "image/jpeg", size 3.9 MB,
|
||||||
natural dimensions 4032 × 3024 px
|
natural dimensions 4032 × 3024 px
|
||||||
Then no request is sent to POST /v1/article/12/image
|
Then no request is sent to POST /v1/media/
|
||||||
And the modal retitles to "Crop and resize" with the description "north-wall.jpg · 3.9 MB"
|
And the modal retitles to "Crop and resize" with the description "north-wall.jpg · 3.9 MB"
|
||||||
And the crop frame starts as the whole image, ratio "Original" is selected, and width
|
And the crop frame starts as the whole image, ratio "Original" is selected, and width
|
||||||
"1600 px" is selected
|
"1600 px" is selected
|
||||||
@@ -53,7 +55,7 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Scenario: An SVG skips the crop step and uploads immediately
|
Scenario: An SVG skips the crop step and uploads immediately
|
||||||
Given ImageUploader is open in the idle state for article 12
|
Given ImageUploader is open in the idle state for article 12
|
||||||
When the user chooses a file named "diagram.svg", content type "image/svg+xml", size 40 KB
|
When the user chooses a file named "diagram.svg", content type "image/svg+xml", size 40 KB
|
||||||
Then POST /v1/article/12/image is sent immediately with that file
|
Then POST /v1/media/ is sent immediately with that file
|
||||||
And the crop-and-resize step is never shown
|
And the crop-and-resize step is never shown
|
||||||
|
|
||||||
Scenario Outline: Choosing an aspect ratio locks the frame to it
|
Scenario Outline: Choosing an aspect ratio locks the frame to it
|
||||||
@@ -108,7 +110,7 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Scenario: "Choose another file" returns to the file picker without uploading
|
Scenario: "Choose another file" returns to the file picker without uploading
|
||||||
Given the crop-and-resize step is open for "north-wall.jpg"
|
Given the crop-and-resize step is open for "north-wall.jpg"
|
||||||
When the user activates "Choose another file"
|
When the user activates "Choose another file"
|
||||||
Then no request is sent to POST /v1/article/12/image
|
Then no request is sent to POST /v1/media/
|
||||||
And the idle state is shown again, with the file picker available
|
And the idle state is shown again, with the file picker available
|
||||||
|
|
||||||
Scenario: A newly chosen file opens a fresh crop step, not the previous file's adjustments
|
Scenario: A newly chosen file opens a fresh crop step, not the previous file's adjustments
|
||||||
@@ -123,7 +125,7 @@ Feature: Crop and resize step in the editor's image uploader
|
|||||||
Given the crop-and-resize step is open for "north-wall.jpg" with ratio "Original", width
|
Given the crop-and-resize step is open for "north-wall.jpg" with ratio "Original", width
|
||||||
"1600 px" and the mono line "Uploads as 1600 × 1200 px · about 420 KB"
|
"1600 px" and the mono line "Uploads as 1600 × 1200 px · about 420 KB"
|
||||||
When the user activates "Upload image"
|
When the user activates "Upload image"
|
||||||
Then POST /v1/article/12/image is sent with a single file under the field name "file" whose
|
Then POST /v1/media/ is sent with a single file under the field name "file" whose
|
||||||
pixel dimensions are 1600 × 1200 and whose size is about 420 KB, not the original
|
pixel dimensions are 1600 × 1200 and whose size is about 420 KB, not the original
|
||||||
4032 × 3024, 3.9 MB file
|
4032 × 3024, 3.9 MB file
|
||||||
And the uploading state shows "Uploading 0.0 of 420 KB"
|
And the uploading state shows "Uploading 0.0 of 420 KB"
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ it renders internally (canvas/OffscreenCanvas is a coder implementation detail).
|
|||||||
"1600 px" selected, mono line "Uploads as 1600 × 1200 px · about 420 KB", footer "Choose
|
"1600 px" selected, mono line "Uploads as 1600 × 1200 px · about 420 KB", footer "Choose
|
||||||
another file" / "Upload image".
|
another file" / "Upload image".
|
||||||
2. **An SVG bypasses the step** — choose `diagram.svg` (image/svg+xml, 40 KB); assert an XHR to
|
2. **An SVG bypasses the step** — choose `diagram.svg` (image/svg+xml, 40 KB); assert an XHR to
|
||||||
`/v1/article/12/image` is created immediately and the crop step never renders.
|
`/v1/media/` is created immediately and the crop step never renders.
|
||||||
3. **Ratio presets lock the frame, Examples-driven (16:9 / 4:3 / 1:1)** — from the opened step,
|
3. **Ratio presets lock the frame, Examples-driven (16:9 / 4:3 / 1:1)** — from the opened step,
|
||||||
select each ratio pill; assert the frame's reported rect and the mono line's output size match
|
select each ratio pill; assert the frame's reported rect and the mono line's output size match
|
||||||
the feature's Examples table.
|
the feature's Examples table.
|
||||||
|
|||||||
@@ -1,148 +1,90 @@
|
|||||||
Feature: Removing an inline image from the editor
|
Feature: Removing an inline image from the article
|
||||||
|
|
||||||
As a verified RenewCMS owner writing an article
|
As a verified RenewCMS owner writing an article
|
||||||
I want to remove an image I've already inserted into the article body,
|
I want to take an image out of the article body, from a button or with Backspace or Delete
|
||||||
either through an explicit delete button or by pressing Backspace/Delete
|
So that an unwanted image leaves the article without deleting the file from my library
|
||||||
on the selected image, directly from the editor
|
|
||||||
So that a mistaken or unwanted image doesn't have to stay in the article
|
|
||||||
forever, and removing it behaves like every other destructive action in
|
|
||||||
RenewCMS: it asks for confirmation first, however the user starts it
|
|
||||||
|
|
||||||
Background:
|
Background:
|
||||||
Given docs/design/ has no board or state for removing an inline image;
|
Given this slice is SPA only for this file; the Go alias deletion is in
|
||||||
this feature was added at the user's explicit request ahead of design
|
features/remove_legacy_article_image_alias.feature
|
||||||
coverage, reusing the editor's existing visual language rather than
|
And docs/design/screens/media-picker.md now covers this flow ("Remove image: confirm" and
|
||||||
inventing new components: the trash icon and error color already used
|
"Removed"); it supersedes the earlier version of this feature, which had no design
|
||||||
by the article "Delete" button, and the ConfirmDialog component
|
coverage and used a red confirm that deleted through DELETE /v1/article/{id}/image/{imageId}
|
||||||
already used by "Delete this article?" (docs/design/screens/editor.md's
|
And removing an image is a body edit only: no API call of any kind is sent, before, during
|
||||||
"Delete: confirm" state)
|
or after the confirm, and the library and every other article are untouched
|
||||||
And this slice changes ArticleEditor's exposed insertImage(src, alt) to
|
And ArticleEditor keeps its exposed insertImage(src, alt, imageId) and removeImage(imageId),
|
||||||
insertImage(src, alt, imageId), stamping the inserted <img> node with
|
its "request-remove-image" event with the image id, and its Backspace and Delete handling,
|
||||||
the image's numeric id as a data-image-id attribute, persisted in the
|
which still intercepts the keys before Tiptap deletes the node
|
||||||
saved article body HTML; EditorView passes the id it now receives from
|
And an image already in a body from before data-image-id existed has no id, shows no
|
||||||
a successful upload (features/remove_article_image.feature's change to
|
"Remove image" button and is not intercepted by Backspace or Delete (unchanged)
|
||||||
POST .../image's 201 body) through to insertImage
|
And selecting an image node that carries data-image-id shows a button "Remove image" at the
|
||||||
And an image already present in an article's body from before this slice
|
image's top-right corner (8 px from the top and right): trash-2 icon at 14 px, neutral,
|
||||||
has no data-image-id attribute and so shows no delete affordance and
|
28 px high, 12 px medium text, a 1 px accented border and the page background; deselecting
|
||||||
is not intercepted by Backspace/Delete, until it is removed and
|
|
||||||
re-added
|
|
||||||
And selecting an image node that does carry a data-image-id attribute
|
|
||||||
shows a small delete button anchored to the image's top-right corner,
|
|
||||||
icon i-lucide-trash-2, color error, matching the article Delete
|
|
||||||
button's icon and color; deselecting the image (clicking elsewhere)
|
|
||||||
hides it
|
hides it
|
||||||
And there are two equivalent triggers for the same removal flow:
|
And EditorView reacts to "request-remove-image" by opening ConfirmDialog with tone "neutral",
|
||||||
activating that delete button, and pressing Backspace or Delete while
|
title "Remove this image from the article?", description "It's removed from this article
|
||||||
the image node is selected (a Tiptap NodeSelection on the image).
|
only. The file stays in your library and in any other article that uses it.", confirmLabel
|
||||||
Tiptap's native node deletion on Backspace/Delete is intercepted
|
"Remove image" and cancelLabel "Cancel"; the confirm button is primary, not red
|
||||||
before it reaches the document (e.g. via a keyboard-shortcut/keydown
|
And the body of the confirm is a bordered row with a 56 × 42 px thumbnail of the image, its
|
||||||
handler registered on the Image node or at the editor level, checked
|
filename, and "Stays in the library · {size}", for example "north-wall.jpg" and "Stays in
|
||||||
first while an image node is selected) so the key press never removes
|
the library · 3.9 MB"
|
||||||
the node directly; instead it triggers exactly the same flow as the
|
And the filename and size come from the images the SPA has seen this session, kept by image
|
||||||
button
|
id: those inserted from either tab and those loaded in the Library list
|
||||||
And either trigger emits ArticleEditor's new "request-remove-image"
|
And confirming runs removeImage(imageId), moves useArticleDraft to "dirty", closes the
|
||||||
event with the node's numeric image id; ArticleEditor does not call
|
dialog and shows the toast; the action cannot fail, so there is no inline error
|
||||||
the API or show any dialog itself, mirroring how "request-image"
|
And a thumbnail uses the image's src from the node
|
||||||
already only opens ImageUploader from EditorView
|
|
||||||
And EditorView reacts to "request-remove-image" by opening the existing
|
|
||||||
ConfirmDialog component with title "Remove this image?", description
|
|
||||||
"This image will be removed from the article. This can't be undone.",
|
|
||||||
confirmLabel "Remove image", cancelLabel "Cancel", pendingLabel
|
|
||||||
"Removing…", tone "danger" — the same component and tone already used
|
|
||||||
for "Delete this article?"
|
|
||||||
And ConfirmDialog's action calls DELETE /v1/article/{articleId}/image/
|
|
||||||
{imageId} through useApi (not the raw XMLHttpRequest used for upload,
|
|
||||||
since there is no progress to observe)
|
|
||||||
And on success (204) the action removes the image node from
|
|
||||||
ArticleEditor's content via a new exposed removeImage(imageId) method,
|
|
||||||
which moves useArticleDraft's state to "dirty" the same way any other
|
|
||||||
body edit does; ConfirmDialog then closes and a toast appears: color
|
|
||||||
success, icon i-lucide-circle-check, title "Image removed",
|
|
||||||
description "Save to keep this change."
|
|
||||||
And on any failure (404 for either the article or the image, 500, or a
|
|
||||||
network failure) the action throws, so ConfirmDialog shows its own
|
|
||||||
inline error "Couldn't remove the image, so it's still there. Try
|
|
||||||
again in a moment." and stays open; the image node is not removed and
|
|
||||||
the draft's dirty state is unchanged
|
|
||||||
And a 401 is handled entirely by useApi's global handling
|
|
||||||
(features/api_client_global_error_handling.feature) and is out of
|
|
||||||
scope for new scenarios here
|
|
||||||
And once the confirm dialog is open, its cancel/confirm/failure
|
|
||||||
behaviour (covered below) is identical regardless of which trigger
|
|
||||||
opened it, so those scenarios are written once, against the button
|
|
||||||
trigger, and are not duplicated per trigger
|
|
||||||
|
|
||||||
Scenario: Selecting an inserted image reveals its delete button
|
Scenario: Selecting an inserted image reveals "Remove image"
|
||||||
Given the user is on /article/12/edit with an image in the body carrying
|
Given the user is on /article/12/edit with an image in the body carrying data-image-id "1"
|
||||||
data-image-id "10"
|
|
||||||
When the user clicks that image
|
When the user clicks that image
|
||||||
Then a delete button (trash icon, error color) appears at the image's
|
Then a button "Remove image" with a trash-2 icon shows at the image's top-right corner
|
||||||
top-right corner
|
|
||||||
When the user clicks elsewhere in the editor
|
When the user clicks elsewhere in the editor
|
||||||
Then the delete button is no longer shown
|
Then the button is no longer shown
|
||||||
|
|
||||||
Scenario Outline: Either trigger opens the confirm dialog and sends no request yet, without letting Tiptap delete the node itself
|
Scenario: An image without data-image-id has no button
|
||||||
Given the image with data-image-id "10" is selected on /article/12/edit
|
Given the body has an image with no data-image-id
|
||||||
|
When the user clicks it
|
||||||
|
Then no "Remove image" button shows and Backspace does nothing special to it
|
||||||
|
|
||||||
|
Scenario Outline: Either trigger opens the neutral confirm and sends nothing
|
||||||
|
Given the image with data-image-id "1" ("north-wall.jpg", 3.9 MB, inserted this session) is selected on /article/12/edit
|
||||||
When the user <triggers-removal>
|
When the user <triggers-removal>
|
||||||
Then a dialog titled "Remove this image?" opens, with description "This
|
Then a dialog titled "Remove this image from the article?" opens, with the description "It's removed from this article only. The file stays in your library and in any other article that uses it."
|
||||||
image will be removed from the article. This can't be undone.",
|
And its body shows the thumbnail, "north-wall.jpg" and "Stays in the library · 3.9 MB"
|
||||||
cancel "Cancel" and confirm "Remove image"
|
And its buttons read "Cancel" and a primary "Remove image"
|
||||||
And no request has been sent to DELETE /v1/article/12/image/10
|
And no request has been sent
|
||||||
And the image node is still present in the editor's content (Tiptap's
|
And the image node is still in the editor's content (Tiptap's native deletion did not run)
|
||||||
native node deletion did not run)
|
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
| triggers-removal |
|
| triggers-removal |
|
||||||
| activates the image's delete button |
|
| activates the "Remove image" button |
|
||||||
| presses Backspace with the image node selected |
|
| presses Backspace with the image node selected |
|
||||||
| presses Delete with the image node selected |
|
| presses Delete with the image node selected |
|
||||||
|
|
||||||
Scenario: Cancelling the confirm dialog changes nothing
|
Scenario: The confirm for an image the session has not seen
|
||||||
Given the confirm dialog is open for image id 10 on /article/12/edit
|
Given the image with data-image-id "7" was in the saved body and is not in the session's record
|
||||||
|
When the user activates "Remove image"
|
||||||
|
Then the body row shows the thumbnail and "Stays in the library" with no filename and no size
|
||||||
|
|
||||||
|
Scenario: Cancelling changes nothing
|
||||||
|
Given the confirm is open for image id 1
|
||||||
When the user activates "Cancel"
|
When the user activates "Cancel"
|
||||||
Then the dialog closes
|
Then the dialog closes, no request has been sent, the image is still in the content, and the draft's dirty state is unchanged
|
||||||
And no request has been sent to DELETE /v1/article/12/image/10
|
|
||||||
And the image is still present in the editor's content
|
|
||||||
And the draft's dirty state is unchanged
|
|
||||||
|
|
||||||
Scenario: Confirming removes the image, marks the draft dirty, and shows a success toast
|
Scenario: Confirming removes the image from the body only
|
||||||
Given the confirm dialog is open for image id 10 on /article/12/edit,
|
Given the confirm is open for image id 1 on /article/12/edit, the draft in the Saved state
|
||||||
the draft in the Saved state
|
|
||||||
When the user activates "Remove image"
|
When the user activates "Remove image"
|
||||||
Then DELETE /v1/article/12/image/10 is sent
|
Then the dialog closes and the image leaves the editor's content
|
||||||
When that request resolves 204
|
And SaveStatus reads "Unsaved changes" and Save is enabled
|
||||||
Then the dialog closes
|
And a toast appears: color success, icon i-lucide-circle-check, title "Image removed", description "It's still in your library."
|
||||||
And the image is removed from the editor's content
|
And no request of any kind has been sent
|
||||||
And SaveStatus reads "Unsaved changes" and the Save button becomes
|
|
||||||
enabled
|
|
||||||
And a toast appears: color success, icon i-lucide-circle-check, title
|
|
||||||
"Image removed", description "Save to keep this change."
|
|
||||||
|
|
||||||
Scenario Outline: A failed removal keeps the image and shows the dialog's inline error
|
Scenario: A removal started by Backspace behaves like one started by the button
|
||||||
Given the confirm dialog is open for image id 10 on /article/12/edit
|
Given the confirm is open for image id 1, opened by Backspace, the draft in the Saved state
|
||||||
When the user activates "Remove image"
|
When the user activates "Remove image"
|
||||||
And DELETE /v1/article/12/image/10 <failure>
|
Then the outcome is the same as above
|
||||||
Then the dialog stays open, showing the inline error "Couldn't remove
|
|
||||||
the image, so it's still there. Try again in a moment."
|
|
||||||
And the image is still present in the editor's content
|
|
||||||
And the draft's dirty state is unchanged
|
|
||||||
|
|
||||||
Examples:
|
Scenario: The removed image can be picked again
|
||||||
| failure |
|
Given image id 1 was removed from the body this session
|
||||||
| resolves with a 404 response |
|
When the user opens the Library tab
|
||||||
| resolves with a 500 response |
|
Then "north-wall.jpg" no longer carries "In this article"
|
||||||
| never reaches the server |
|
|
||||||
|
|
||||||
Scenario: Confirming a removal started by Backspace/Delete behaves exactly like confirming one started by the button
|
|
||||||
Given the confirm dialog is open for image id 10 on /article/12/edit,
|
|
||||||
opened by pressing Backspace with the image node selected, the draft
|
|
||||||
in the Saved state
|
|
||||||
When the user activates "Remove image"
|
|
||||||
Then DELETE /v1/article/12/image/10 is sent
|
|
||||||
When that request resolves 204
|
|
||||||
Then the dialog closes
|
|
||||||
And the image is removed from the editor's content
|
|
||||||
And SaveStatus reads "Unsaved changes" and the Save button becomes
|
|
||||||
enabled
|
|
||||||
And a toast appears: color success, icon i-lucide-circle-check, title
|
|
||||||
"Image removed", description "Save to keep this change."
|
|
||||||
@@ -1,88 +1,25 @@
|
|||||||
# QA: Removing an inline image from the editor
|
# QA: Removing an inline image from the article
|
||||||
|
|
||||||
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
Mount EditorPage inside DashboardShell at `/article/12/edit` with the
|
Mount EditorPage at `/article/12/edit` with the `editor_core.qa.md` fixture article and a body of `<img src="/static/uploadedImages/1.jpg" data-image-id="1" alt="">`. Seed the session's image record with id 1 ("north-wall.jpg", 3.9 MB). Spy on `request` and on `XMLHttpRequest` and assert they are never called by any step below.
|
||||||
editor_core.qa.md fixture article (id 12, "How we price a bathroom
|
|
||||||
renovation", is_online false), GET already resolved 200, and a body
|
|
||||||
containing `<img src="/static/uploadedImages/before.png" data-image-id="10"
|
|
||||||
alt="">`. Mock `useApi`'s `request` for `DELETE /v1/article/12/image/10`
|
|
||||||
(fetch-based, not XHR — reuse whatever mock
|
|
||||||
`api_client_global_error_handling.qa.md` already sets up for `request`).
|
|
||||||
|
|
||||||
1. **Selecting the image reveals the delete button** — click the image
|
1. **Selecting reveals the button** - click the image; assert a button named "Remove image" with a trash-2 icon renders at the corner; click elsewhere; assert it is gone.
|
||||||
node; assert a delete button (trash icon, error color) renders anchored
|
2. **No id, no button** - an image without `data-image-id`: no button, and a Backspace keydown does not open the dialog.
|
||||||
to it; click elsewhere in the editor; assert the button is gone.
|
3. **Triggers, Examples-driven** - button click, Backspace keydown and Delete keydown each open the dialog with the exact title, description, "Cancel" and a primary (not error) "Remove image"; assert the body shows the thumbnail, "north-wall.jpg" and "Stays in the library · 3.9 MB"; assert no request; assert the node is still in the document.
|
||||||
2. **Activating the delete button opens the confirm dialog** — select the
|
4. **Unseen image** - id 7 not in the record; assert the row shows the thumbnail and "Stays in the library" only.
|
||||||
image, activate its delete button; assert a dialog titled "Remove this
|
5. **Cancel changes nothing.**
|
||||||
image?", description "This image will be removed from the article. This
|
6. **Confirm** - click "Remove image"; assert the dialog closes, the node is gone, SaveStatus "Unsaved changes", Save enabled, the toast (color success, icon `i-lucide-circle-check`, "Image removed" / "It's still in your library."), and zero requests.
|
||||||
can't be undone.", cancel "Cancel", confirm "Remove image"; assert no
|
7. **Backspace-opened confirm** gives the same outcome as 6.
|
||||||
request was sent yet; assert the image node is still present (Tiptap's
|
8. **Removed image loses its tag** - open the Library after step 6; assert "north-wall.jpg" has no "In this article" tag.
|
||||||
native deletion did not run).
|
|
||||||
3. **Backspace on the selected image opens the same confirm dialog instead
|
|
||||||
of deleting the node** — select the image node (NodeSelection), fire a
|
|
||||||
`keydown` for `Backspace`; assert the same dialog as step 2 opens;
|
|
||||||
assert no request was sent yet; assert the image node is still present
|
|
||||||
in the editor's document (i.e. the keydown was intercepted before
|
|
||||||
Tiptap's default node-deletion ran, not just undone afterwards).
|
|
||||||
4. **Delete on the selected image opens the same confirm dialog instead of
|
|
||||||
deleting the node** — same as step 3 but firing `keydown` for `Delete`.
|
|
||||||
5. **Cancelling changes nothing** — from the open dialog (opened via the
|
|
||||||
button), click "Cancel"; assert the dialog closes, no request was sent,
|
|
||||||
the image node is still in the editor's content, and SaveStatus/dirty
|
|
||||||
state is unchanged.
|
|
||||||
6. **Confirming removes the image, marks dirty, and toasts (button
|
|
||||||
trigger)** — from the open dialog (Saved state), click "Remove image";
|
|
||||||
assert a DELETE request to `/v1/article/12/image/10` was made; resolve
|
|
||||||
it 204; assert the dialog closes, the image node is gone from the
|
|
||||||
editor's content, SaveStatus reads "Unsaved changes" and Save is
|
|
||||||
enabled, and a toast appears with color success, icon
|
|
||||||
`i-lucide-circle-check`, title "Image removed", description "Save to
|
|
||||||
keep this change."
|
|
||||||
7. **Confirming removes the image the same way when opened via
|
|
||||||
Backspace/Delete** — repeat step 6's assertions, but open the dialog via
|
|
||||||
the Backspace keydown from step 3 instead of the button; assert the
|
|
||||||
outcome (request, node removal, dirty state, toast) is identical.
|
|
||||||
8. **A failed removal keeps the image and shows the inline error,
|
|
||||||
Examples-driven** — for a 404 response, a 500 response, and a rejected/
|
|
||||||
network-failure request: from the open dialog (button trigger), click
|
|
||||||
"Remove image"; resolve/reject accordingly; assert the dialog stays open
|
|
||||||
showing the inline error "Couldn't remove the image, so it's still
|
|
||||||
there. Try again in a moment."; assert the image node is still present
|
|
||||||
and the draft's dirty state is unchanged.
|
|
||||||
|
|
||||||
## Visual
|
## Visual: `task visual:check -- media-picker`
|
||||||
|
|
||||||
No `docs/design/` board or state exists for this trigger (see the feature's
|
The states "Remove image: confirm" and "Removed" are in the `media-picker` group; the setups are in `editor_media_picker.qa.md`. The sample data is north-wall.jpg, image id 1, 3.9 MB. The "Remove image" button is visible in "Remove image: confirm" and "Inserted", so the setup must select the image node. The confirm's confirm button must not be error-coloured.
|
||||||
Background). Per the user's explicit direction this slice ships the SPA
|
|
||||||
behaviour anyway, but `task visual:check -- editor` has nothing to compare
|
|
||||||
it against, so no visual capture is added for it — this is an intentional
|
|
||||||
gap, `skip: no-design-coverage` (distinct from `skip: clock-sensitive`), not
|
|
||||||
a QA oversight. If a board for this state is added to `docs/design/` later,
|
|
||||||
it needs its own follow-up slice to add the visual check.
|
|
||||||
|
|
||||||
- [ ] Keyboard/focus: once a delete button is shown, it is reachable by Tab
|
- [ ] Keyboard and focus: the button is reachable by Tab and activates with Enter or Space. Backspace or Delete with focus outside the editor does nothing. ConfirmDialog's focus trap and default focus on "Cancel" are unchanged.
|
||||||
and activates on Enter/Space; pressing Backspace/Delete with the
|
|
||||||
image node selected but focus elsewhere in the page does not trigger
|
|
||||||
removal (only an actual Tiptap NodeSelection on the image should);
|
|
||||||
ConfirmDialog's existing focus trap and cancel-button-default-focus
|
|
||||||
behaviour (already covered by the article-delete flow) applies
|
|
||||||
unchanged regardless of which trigger opened it.
|
|
||||||
|
|
||||||
## Manual verification
|
## Manual verification
|
||||||
|
|
||||||
- **Real DELETE round trip against a running server** — Vitest only mocks
|
- **Real keyboard behaviour** in a real browser, including an IME: Backspace or Delete on a selected image opens the confirm instead of deleting the node (jsdom doesn't exercise ProseMirror's keymap precedence).
|
||||||
`useApi`'s request; confirm a real removal (204/404/500) against
|
- **Save after removal** against `task dev`: remove an image, save, reload; the image is gone from the article and still listed in `/media`.
|
||||||
`task dev` with a live SQLite file and the real
|
|
||||||
`DELETE /v1/article/{id}/image/{imageId}` handler, since
|
|
||||||
`features/remove_article_image.feature`'s httptest suite covers the
|
|
||||||
handler in isolation but never through this SPA flow.
|
|
||||||
- **Real keyboard behaviour** — confirm in a real browser that selecting an
|
|
||||||
image (click) and pressing Backspace/Delete opens the confirm dialog
|
|
||||||
rather than deleting the node, including with an IME or on a platform
|
|
||||||
where Backspace/Delete semantics differ, since jsdom's `keydown`
|
|
||||||
simulation doesn't exercise Tiptap's real ProseMirror keymap precedence.
|
|
||||||
- **Design review of the delete-button/ConfirmDialog approach** — since
|
|
||||||
there is no board for this state, once a board is added, re-verify this
|
|
||||||
implementation still matches it (or update the implementation to match);
|
|
||||||
until then this is a best-effort, design-team-unreviewed UI.
|
|
||||||
@@ -1,58 +1,75 @@
|
|||||||
Feature: Wiring the editor's image upload flow
|
Feature: The editor's Upload tab uploads to the library
|
||||||
|
|
||||||
As a verified RenewCMS owner writing an article
|
As a verified RenewCMS owner writing an article
|
||||||
I want the editor's image button (and dropping a file onto the editor) to open an upload
|
I want the Upload tab of the "Add an image" dialog to check my file, spot duplicates,
|
||||||
modal that validates the file, shows progress, and inserts the result at my cursor
|
upload to my library and insert the result at my cursor
|
||||||
So that I can add images to an article's body without leaving the editor, with clear
|
So that I can add images to an article's body without leaving the editor, with clear
|
||||||
feedback when a file is rejected or the upload fails
|
feedback when a file is rejected or the upload fails
|
||||||
|
|
||||||
Background:
|
Background:
|
||||||
Given EditorView.vue listens for ArticleEditor's "request-image" event and, on it, opens
|
Given this slice is SPA only for this file: the API from the media library slice is used
|
||||||
ImageUploader (a UModal titled "Add an image") with the current article's id
|
unchanged
|
||||||
And dropping a file directly onto the editor surface also opens ImageUploader, with that
|
And EditorView listens for ArticleEditor's "request-image" event and opens ImageUploader
|
||||||
file already provided to it instead of an empty idle state
|
(a UModal titled "Add an image") with the picker tabs, whose Library tab is specified in
|
||||||
And ImageUploader validates a chosen or dropped file in the browser, checking both its MIME
|
features/editor_media_picker.feature
|
||||||
type and its file extension against png/jpeg/webp/svg, and that its size is at most
|
And dropping a file onto the editor surface opens ImageUploader on the Upload tab with that
|
||||||
10 × 1024 × 1024 bytes, before sending anything
|
file already provided, and no list request is sent until the Library tab is opened
|
||||||
And a file that passes validation is uploaded via a new useImageUpload composable, using
|
And this file supersedes these statements of the earlier version: the upload goes to
|
||||||
XMLHttpRequest (not useApi) so upload progress is observable, as multipart/form-data with
|
POST /v1/media/ and no longer to POST /v1/article/{articleId}/image; the 201 body is the
|
||||||
the file under the field name "file", to POST /v1/article/{articleId}/image, per
|
library item { id, filename, url, size, content_type, width, height, sha256, uploaded_by,
|
||||||
features/upload_article_image.feature's already-implemented and already-mounted contract
|
created_at, used_in, duplicate }; there is no article id in any upload request and no 404
|
||||||
And a 201 response's {"location": "..."} is inserted into ArticleEditor's content at the
|
for a deleted article on upload
|
||||||
current cursor position via an exposed insertImage(src, alt) method, with alt ""; this
|
And ImageUploader validates a chosen or dropped file in the browser with validateImageFile
|
||||||
moves useArticleDraft's state to "dirty" the same way any other body edit does
|
from web/src/lib/imageUpload.ts, size first (10485760 bytes allowed, one byte more is too
|
||||||
And closing the modal while an upload is in flight aborts the XMLHttpRequest
|
large), then MIME type and extension must both be allowed (png, jpeg, webp, svg), before
|
||||||
And a 401 response is handled entirely by useApi's global handling
|
hashing or sending anything
|
||||||
(features/api_client_global_error_handling.feature) and is out of scope for new scenarios
|
And a file that passes validation is hashed with hashFile from web/src/lib/fileHash.ts (the
|
||||||
here; the same is true of a 404 (the article was deleted elsewhere), which the editor's
|
lib shared with MediaPage), and GET /v1/media/?hash=<sha256 hex> is sent through useApi;
|
||||||
existing not-found handling already covers (features/editor_core.feature)
|
when hashFile resolves null, or the lookup fails with 500 or a network error, the check
|
||||||
|
is skipped and the flow continues as if nothing matched
|
||||||
|
And a file with no match continues exactly as in features/editor_image_crop_resize.feature:
|
||||||
|
a JPEG, PNG or WEBP opens the crop and resize step, an SVG is uploaded immediately
|
||||||
|
And the upload is sent with XMLHttpRequest (not useApi) so progress is observable, as
|
||||||
|
multipart/form-data with the file under the field name "file" to POST /v1/media/, with the
|
||||||
|
jwt cookie
|
||||||
|
And a 201 inserts the item's url at the cursor through insertImage(item.url, "", item.id),
|
||||||
|
so the node carries data-image-id, and useArticleDraft moves to "dirty"
|
||||||
|
And closing the dialog while an upload is in flight aborts the XMLHttpRequest
|
||||||
|
And the tabs show only on the choose step (idle, the duplicate card and the Library tab);
|
||||||
|
the crop, uploading, rejected and failed steps keep the earlier look without tabs
|
||||||
|
And the footer on the Upload tab holds only the step's own actions ("Cancel" in idle);
|
||||||
|
there is no "Insert image" button on it
|
||||||
|
|
||||||
Scenario: Opening the uploader from the toolbar's image button shows the idle state
|
Rule: Opening
|
||||||
|
|
||||||
|
Scenario: The toolbar's image button opens on Upload when the library is empty
|
||||||
Given the user is on /article/12/edit with the editor focused
|
Given the user is on /article/12/edit with the editor focused
|
||||||
|
And GET /v1/media/?limit=24 resolves 200 with no item
|
||||||
When the user activates the toolbar's "Image" button
|
When the user activates the toolbar's "Image" button
|
||||||
Then ImageUploader opens titled "Add an image"
|
Then ImageUploader opens titled "Add an image" with the tabs "Upload" (icon upload) and "Library" (icon images)
|
||||||
And it shows "Drop an image here", a "Choose file" action, and the help text
|
And the Upload tab is selected and shows the image-plus icon, "Drop an image here, or choose a file" and "PNG, JPEG, WEBP, SVG · max 10 MB"
|
||||||
"PNG, JPEG, WEBP, SVG · max 10 MB"
|
And its footer reads "Cancel" only
|
||||||
And its cancel action reads "Cancel"
|
And no POST has been sent
|
||||||
And no request has been sent
|
|
||||||
|
|
||||||
Scenario: Dragging a file over the editor surface shows the dragging-over state
|
Scenario: Dropping a file opens Upload with the file
|
||||||
Given ImageUploader is open in the idle state
|
Given the user is on /article/12/edit and ImageUploader is not open
|
||||||
|
When the user drops a file named "before.png", content type "image/png", size 3.9 MB, onto the editor surface
|
||||||
|
Then ImageUploader opens on the Upload tab
|
||||||
|
And GET /v1/media/?hash=<sha256 of the file> is sent, and no request to GET /v1/media/?limit=24 is sent
|
||||||
|
And when the lookup resolves 200 with no item the crop and resize step shows for "before.png"
|
||||||
|
And no POST /v1/media/ has been sent
|
||||||
|
|
||||||
|
Scenario: Dragging a file over the drop zone shows the dragging-over state
|
||||||
|
Given ImageUploader is open on the Upload tab in the idle state
|
||||||
When the user drags a file over the drop zone
|
When the user drags a file over the drop zone
|
||||||
Then the drop zone reads "Drop to upload"
|
Then the drop zone reads "Drop to upload"
|
||||||
|
|
||||||
Scenario: Dropping a valid file onto the editor opens the uploader already uploading it
|
Rule: Browser checks, nothing is sent
|
||||||
Given the user is on /article/12/edit with the editor focused and ImageUploader is not open
|
|
||||||
When the user drops a file named "before.png", content type "image/png", size 3.9 MB, onto
|
|
||||||
the editor surface
|
|
||||||
Then ImageUploader opens titled "Add an image"
|
|
||||||
And POST /v1/article/12/image is sent with that file under the field name "file"
|
|
||||||
And the uploading state is shown, not the idle state
|
|
||||||
|
|
||||||
Scenario Outline: Choosing a file the browser can reject never sends a request
|
Scenario Outline: Choosing a file the browser can reject sends nothing
|
||||||
Given ImageUploader is open in the idle state for article 12
|
Given ImageUploader is open in the idle state
|
||||||
When the user chooses a file named "<filename>", content type "<content_type>", size <size>
|
When the user chooses a file named "<filename>", content type "<content_type>", size <size>
|
||||||
Then no request is sent to POST /v1/article/12/image
|
Then no hash lookup and no POST /v1/media/ is sent
|
||||||
And the rejected state shows the title "\"<filename>\" can't be used"
|
And the rejected state shows the title "\"<filename>\" can't be used"
|
||||||
And its text reads "<description>"
|
And its text reads "<description>"
|
||||||
And its confirm action reads "Choose another file" and its cancel action reads "Cancel"
|
And its confirm action reads "Choose another file" and its cancel action reads "Cancel"
|
||||||
@@ -64,73 +81,111 @@ Feature: Wiring the editor's image upload flow
|
|||||||
| north-wall.tif | image/png | 14.2 MB | north-wall.tif is 14.2 MB. Images can be up to 10 MB. |
|
| north-wall.tif | image/png | 14.2 MB | north-wall.tif is 14.2 MB. Images can be up to 10 MB. |
|
||||||
|
|
||||||
Scenario: "Choose another file" from the rejected state returns to idle
|
Scenario: "Choose another file" from the rejected state returns to idle
|
||||||
Given ImageUploader is in the rejected state for a file named "plan.pdf"
|
Given ImageUploader is in the rejected state for "plan.pdf"
|
||||||
When the user activates "Choose another file"
|
When the user activates "Choose another file"
|
||||||
Then the idle state is shown again, with the file picker available
|
Then the idle state is shown again, with the tabs
|
||||||
|
|
||||||
Scenario: A valid upload shows progress and its cancel action reads "Cancel upload"
|
Rule: Already in your library
|
||||||
Given ImageUploader is open in the idle state for article 12
|
|
||||||
When the user chooses a file named "north-wall.jpg", content type "image/jpeg", size 3.9 MB
|
|
||||||
Then POST /v1/article/12/image is sent with that file under the field name "file"
|
|
||||||
And the uploading state shows "north-wall.jpg 0%" and "Uploading 0.0 of 3.9 MB"
|
|
||||||
And its cancel action reads "Cancel upload"
|
|
||||||
When the upload reports 2.4 MB sent of 3.9 MB
|
|
||||||
Then the uploading state shows "north-wall.jpg 62%" and "Uploading 2.4 of 3.9 MB"
|
|
||||||
|
|
||||||
Scenario: Closing the dialog during an upload cancels it
|
Scenario: A file whose content exists shows the duplicate card and sends nothing
|
||||||
Given ImageUploader is uploading a file named "north-wall.jpg" to article 12
|
Given ImageUploader is open in the idle state
|
||||||
When the user activates "Cancel upload" (or otherwise closes the modal)
|
And GET /v1/media/?hash=<sha256 of north-wall.jpg> resolves 200 with the image "north-wall.jpg" (id 1, 4032 × 3024, uploaded 12 Sep 2026 by Marta Alves)
|
||||||
Then the in-flight XMLHttpRequest is aborted
|
When the user chooses a valid file named "north-wall.jpg" of 3.9 MB
|
||||||
And the modal closes
|
Then the Upload tab shows a card with an info border: a 72 × 54 thumbnail of the existing image, the title "Already in your library" and the text "north-wall.jpg matches an image uploaded on 12 Sep 2026 by Marta Alves."
|
||||||
And the editor's body is unchanged and remains in its previous dirty/clean state
|
And the card has the buttons "Use existing" (primary) and "Upload anyway", stacked and full width below md
|
||||||
|
And no POST /v1/media/ has been sent and the crop step has not opened
|
||||||
|
|
||||||
Scenario: A successful upload inserts the image at the cursor and marks the draft dirty
|
Scenario: Several matches name the oldest one
|
||||||
Given the user is on /article/12/edit in the Saved state and ImageUploader is uploading a
|
Given the hash lookup resolves 200 with several images
|
||||||
file named "north-wall.jpg" to article 12
|
Then the card names the oldest match
|
||||||
When POST /v1/article/12/image resolves 201 with {"location": "/static/uploadedImages/north-wall.jpg"}
|
|
||||||
Then the uploading state briefly shows "Image added"
|
|
||||||
And the image at "/static/uploadedImages/north-wall.jpg" is inserted into the editor's
|
|
||||||
content at the cursor via insertImage
|
|
||||||
And SaveStatus reads "Unsaved changes" and the Save button becomes enabled
|
|
||||||
And a toast appears: color success, icon i-lucide-circle-check, title "Image added",
|
|
||||||
description "Save to keep it in the article."
|
|
||||||
And the modal closes 600 ms after the response resolves
|
|
||||||
|
|
||||||
Scenario Outline: A server-side upload failure keeps the article unchanged and offers a retry
|
Scenario: A match without a known uploader drops the "by" part
|
||||||
Given ImageUploader is uploading a file named "north-wall.jpg" to article 12
|
Given the matched image's uploaded_by is empty
|
||||||
When POST /v1/article/12/image <failure>
|
Then the text reads "north-wall.jpg matches an image uploaded on 12 Sep 2026."
|
||||||
Then the failed state shows the title "Upload failed"
|
|
||||||
And its text reads "The server didn't accept the file. Your article hasn't changed."
|
Scenario: "Use existing" goes to the alt text step for the existing image
|
||||||
And its confirm action reads "Try again"
|
Given the duplicate card is showing for image id 1
|
||||||
And the editor's body is unchanged, and no image is inserted
|
When the user activates "Use existing"
|
||||||
|
Then the Library tab is selected with "north-wall.jpg" selected, its panel visible with the empty "Alt text (optional)" field, and "Insert image" enabled
|
||||||
|
And no POST /v1/media/ has been sent
|
||||||
|
|
||||||
|
Scenario: "Upload anyway" continues to crop and upload
|
||||||
|
Given the duplicate card is showing for "north-wall.jpg" (4032 × 3024)
|
||||||
|
When the user activates "Upload anyway"
|
||||||
|
Then the crop and resize step opens for that file
|
||||||
|
And the hash lookup is not repeated
|
||||||
|
And uploading from that step sends POST /v1/media/ and follows the normal states
|
||||||
|
|
||||||
|
Scenario: "Upload anyway" for an SVG uploads immediately
|
||||||
|
Given the duplicate card is showing for "diagram.svg"
|
||||||
|
When the user activates "Upload anyway"
|
||||||
|
Then POST /v1/media/ is sent with that file
|
||||||
|
|
||||||
|
Scenario Outline: The duplicate check is skipped when it cannot run
|
||||||
|
Given ImageUploader is open in the idle state
|
||||||
|
When the user chooses a valid file and <condition>
|
||||||
|
Then the flow continues to the crop step (or the upload for an SVG) with no card
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
| failure |
|
| condition |
|
||||||
| resolves with a 500 response |
|
| crypto.subtle is undefined (an insecure context) |
|
||||||
| never reaches the server |
|
| GET /v1/media/?hash= resolves with a 500 response |
|
||||||
|
| GET /v1/media/?hash= never reaches the server |
|
||||||
|
|
||||||
|
Rule: Uploading
|
||||||
|
|
||||||
|
Scenario: A valid upload shows progress and its cancel action reads "Cancel upload"
|
||||||
|
Given the crop step was confirmed (or an SVG chosen) for "north-wall.jpg", 3.9 MB
|
||||||
|
Then POST /v1/media/ is sent with the file under the field name "file"
|
||||||
|
And the uploading state shows "north-wall.jpg 0%" and "Uploading 0.0 of 3.9 MB", and its cancel action reads "Cancel upload"
|
||||||
|
When the upload reports 2.4 MB sent of 3.9 MB
|
||||||
|
Then it shows "north-wall.jpg 62%" and "Uploading 2.4 of 3.9 MB"
|
||||||
|
|
||||||
|
Scenario: Closing the dialog during an upload cancels it
|
||||||
|
Given ImageUploader is uploading "north-wall.jpg"
|
||||||
|
When the user activates "Cancel upload" (or otherwise closes the dialog)
|
||||||
|
Then the in-flight XMLHttpRequest is aborted and the dialog closes
|
||||||
|
And the editor's body and its dirty or clean state are unchanged
|
||||||
|
|
||||||
|
Scenario: A successful upload inserts the image at the cursor and marks the draft dirty
|
||||||
|
Given the user is on /article/12/edit in the Saved state and "north-wall.jpg" is uploading
|
||||||
|
When POST /v1/media/ resolves 201 with the item { id: 13, url: "/static/uploadedImages/13.jpg", filename: "north-wall.jpg" }
|
||||||
|
Then the uploading state briefly shows "Image added"
|
||||||
|
And the image "/static/uploadedImages/13.jpg" is inserted at the cursor with alt "" and data-image-id 13
|
||||||
|
And SaveStatus reads "Unsaved changes" and Save is enabled
|
||||||
|
And a toast appears: color success, icon i-lucide-circle-check, title "Image added", description "Save to keep it in the article."
|
||||||
|
And the dialog closes 600 ms after the response
|
||||||
|
|
||||||
|
Scenario Outline: A server answer for a file that passed the browser checks
|
||||||
|
Given ImageUploader is uploading "<file>" of <size>
|
||||||
|
When POST /v1/media/ resolves <status>
|
||||||
|
Then the <state> state shows the title "<title>"
|
||||||
|
And its text reads "<text>"
|
||||||
|
And its confirm action reads "<confirm>"
|
||||||
|
And no image is inserted and the editor's body is unchanged
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| file | size | status | state | title | text | confirm |
|
||||||
|
| notes.pdf | 210 KB | 415 | rejected | "notes.pdf" can't be used | Use a PNG, JPEG, WEBP or SVG image, up to 10 MB. | Choose another file |
|
||||||
|
| north-wall.tif | 14.2 MB | 413 | rejected | "north-wall.tif" can't be used | north-wall.tif is 14.2 MB. Images can be up to 10 MB. | Choose another file |
|
||||||
|
| broken.png | 3.0 MB | 400 | rejected | "broken.png" can't be used | Use a PNG, JPEG, WEBP or SVG image, up to 10 MB. | Choose another file |
|
||||||
|
| north-wall.jpg | 3.9 MB | 500 | failed | Upload failed | The server didn't accept the file. Your article hasn't changed. | Try again |
|
||||||
|
| north-wall.jpg | 3.9 MB | 429 | failed | Upload failed | The server didn't accept the file. Your article hasn't changed. | Try again |
|
||||||
|
| north-wall.jpg | 3.9 MB | none (network) | failed | Upload failed | The server didn't accept the file. Your article hasn't changed. | Try again |
|
||||||
|
|
||||||
Scenario: "Try again" re-attempts the upload with the same file
|
Scenario: "Try again" re-attempts the upload with the same file
|
||||||
Given ImageUploader is in the failed state for a file named "north-wall.jpg", article 12,
|
Given ImageUploader is in the failed state for "north-wall.jpg" after a 500
|
||||||
after a 500 response
|
|
||||||
When the user activates "Try again"
|
When the user activates "Try again"
|
||||||
Then POST /v1/article/12/image is sent again with that same file under the field name "file"
|
Then POST /v1/media/ is sent again with that same file and no new hash lookup, and the uploading state shows
|
||||||
And the uploading state is shown
|
|
||||||
|
|
||||||
Scenario: A server 400 for a type the client should have caught shows the same rejected copy
|
Rule: Sessions
|
||||||
Given ImageUploader is uploading a file named "notes.pdf" to article 12 (a type that
|
|
||||||
defensively passed the browser's own check, e.g. a MIME type the browser misreported)
|
|
||||||
When POST /v1/article/12/image resolves 400
|
|
||||||
Then the rejected state shows the title "\"notes.pdf\" can't be used"
|
|
||||||
And its text reads "Use a PNG, JPEG, WEBP or SVG image, up to 10 MB."
|
|
||||||
And its confirm action reads "Choose another file"
|
|
||||||
And the editor's body is unchanged, and no image is inserted
|
|
||||||
|
|
||||||
Scenario: A server 400 for a size the client should have caught shows the same size-named copy
|
Scenario Outline: Session errors are global
|
||||||
Given ImageUploader is uploading a file named "north-wall.tif" to article 12 (a file that
|
When <call> resolves <status>
|
||||||
defensively passed the browser's own size check somehow, e.g. its reported size changed
|
Then the user is sent where useApi sends a <status> from /article/12/edit, and no local copy shows
|
||||||
between selection and send)
|
|
||||||
When POST /v1/article/12/image resolves 400
|
Examples:
|
||||||
Then the rejected state shows the title "\"north-wall.tif\" can't be used"
|
| call | status |
|
||||||
And its text reads "north-wall.tif is 14.2 MB. Images can be up to 10 MB."
|
| POST /v1/media/ (XHR) | 401 |
|
||||||
And its confirm action reads "Choose another file"
|
| POST /v1/media/ (XHR) | 403 |
|
||||||
And the editor's body is unchanged, and no image is inserted
|
| GET /v1/media/?hash= | 401 |
|
||||||
@@ -1,90 +1,33 @@
|
|||||||
# QA: Wiring the editor's image upload flow
|
# QA: The editor's Upload tab uploads to the library
|
||||||
|
|
||||||
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
Mock `XMLHttpRequest` (a fake implementing `open`/`setRequestHeader`/`send`/`abort` and firing
|
Mock `XMLHttpRequest` (a fake with `open`, `setRequestHeader`, `send`, `abort`, firing `upload.progress`, `load`, `error`) for `POST /v1/media/`. Mock useApi's `request` for `GET /v1/media/` (list and `?hash=`), reusing the mock from `api_client_global_error_handling.qa.md`. Stub `hashFile` where a hash is needed, and add one test with `crypto.subtle` deleted. Mount EditorPage inside DashboardShell at `/article/12/edit` with the `editor_core.qa.md` fixture article, GET already resolved 200. Assert URLs by parsing the query, not by string equality.
|
||||||
`upload.progress`, `load`, `error`) for `POST /v1/article/{id}/image`; useApi/fetch is not
|
|
||||||
involved in this slice. Mount EditorPage inside DashboardShell at `/article/12/edit` with the
|
|
||||||
editor_core.qa.md fixture article (id 12, title "How we price a bathroom renovation", is_online
|
|
||||||
false), GET already resolved 200.
|
|
||||||
|
|
||||||
1. **Toolbar button opens the idle state** — click the toolbar's "Image" button; assert
|
1. **Toolbar button, empty library** - `GET /v1/media/?limit=24` resolves `{items: [], next_cursor: null, counts: {all: 0, unused: 0, duplicates: 0}}`; click "Image"; assert the dialog "Add an image", both tabs, the Upload tab selected, the drop zone copy, footer "Cancel" only, no XHR.
|
||||||
ImageUploader opens titled "Add an image", showing "Drop an image here", "Choose file",
|
2. **Drop opens Upload with the file** - dispatch `drop` with `before.png` (image/png, 3.9 MB); assert the Upload tab, a `?hash=` request, no `?limit=24` list request, then the crop step after an empty lookup, and no XHR.
|
||||||
"PNG, JPEG, WEBP, SVG · max 10 MB", cancel "Cancel"; assert no XHR was created.
|
3. **Dragging over shows "Drop to upload"**.
|
||||||
2. **Dragging over shows "Drop to upload"** — with the uploader open idle, fire a `dragover` on
|
4. **Rejected, Examples-driven** - `plan.pdf`, `disguised.png`, `north-wall.tif`; assert no `?hash=` request and no XHR, plus the exact title, text, confirm and cancel.
|
||||||
the drop zone; assert the text changes to "Drop to upload".
|
5. **"Choose another file" returns to idle**, with the tabs back.
|
||||||
3. **Dropping a file on the editor opens the uploader already uploading** — with the uploader
|
6. **Duplicate card** - the hash lookup resolves one item (id 1, "north-wall.jpg", `created_at` 12 Sep 2026, `uploaded_by` "Marta Alves"); assert the card copy and buttons, no XHR, and no crop step.
|
||||||
closed, dispatch a `drop` event with a file `before.png` (image/png, 3.9 MB) on the editor
|
7. **Several matches name the oldest**, and **no uploader drops the "by" part**.
|
||||||
surface; assert ImageUploader opens and an XHR to `/v1/article/12/image` is created with that
|
8. **"Use existing"** - assert the Library tab is selected, image 1 selected, the alt field empty, "Insert image" enabled, and no XHR.
|
||||||
file, and the uploading state (not idle) is shown.
|
9. **"Upload anyway"** - assert the crop step opens (raster) with no second `?hash=` request; for an SVG assert the XHR is created at once.
|
||||||
4. **Rejected — Examples-driven on type, extension mismatch, and size** — for each of `plan.pdf`
|
10. **Check skipped** - Examples: `hashFile` resolves null, lookup 500, lookup rejects; assert the crop step opens with no card.
|
||||||
(application/pdf, 1.2 MB), `disguised.png` (application/pdf, 1.2 MB), and `north-wall.tif`
|
11. **Uploading and progress** - confirm the crop step; assert the XHR is `POST /v1/media/` with field `file`, cancel "Cancel upload", and `loaded: 2.4 * 1024 * 1024, total: 3.9 * 1024 * 1024` gives "north-wall.jpg 62%" and "Uploading 2.4 of 3.9 MB".
|
||||||
(image/png, 14.2 MB), choose the file via the `UFileUpload`; assert no XHR is created and the
|
12. **Closing during an upload aborts** - `abort` called, dialog closed, body and dirty state unchanged.
|
||||||
rejected state shows the exact title/text/confirm/cancel copy from the feature's Examples.
|
13. **201 inserts** - resolve the XHR with the item (id 13, url `/static/uploadedImages/13.jpg`); assert `insertImage` was called with (url, "", 13), SaveStatus "Unsaved changes", Save enabled, the toast (color success, icon `i-lucide-circle-check`, "Image added" / "Save to keep it in the article."), and after 600 ms of fake timers the dialog closes.
|
||||||
5. **"Choose another file" returns to idle** — from the rejected state, click "Choose another
|
14. **Server answers, Examples-driven** - 415, 413, 400 give the rejected copy; 500, 429 and a network `error` give "Upload failed"; assert no `insertImage` call and the body unchanged.
|
||||||
file"; assert the idle state re-renders.
|
15. **"Try again" resends the same file** with no new `?hash=` request.
|
||||||
6. **Uploading shows live progress and "Cancel upload"** — choose `north-wall.jpg` (image/jpeg,
|
16. **Sessions** - Examples from the feature; assert the same redirect `useApi` performs, with no local copy.
|
||||||
3.9 MB); assert the XHR is created with that file under field `file`; assert cancel reads
|
|
||||||
"Cancel upload"; fire an `upload.progress` event with `loaded: 2.4 * 1024 * 1024, total: 3.9 *
|
|
||||||
1024 * 1024`; assert the text reads "north-wall.jpg 62%" and "Uploading 2.4 of 3.9 MB".
|
|
||||||
7. **Closing during an upload aborts the XHR** — from the uploading state, click "Cancel
|
|
||||||
upload"; assert the fake XHR's `abort` was called, the modal closes, and the editor's body
|
|
||||||
and dirty state are unchanged from before the upload started.
|
|
||||||
8. **A 201 inserts at the cursor and marks the draft dirty** — from the uploading state, resolve
|
|
||||||
the fake XHR with status 201 and body `{"location": "/static/uploadedImages/north-wall.jpg"}`;
|
|
||||||
assert `insertImage` (or the editor's exposed method) was called with that location; assert
|
|
||||||
SaveStatus now reads "Unsaved changes" and Save is enabled; assert a toast appears with color
|
|
||||||
success, icon `i-lucide-circle-check`, title "Image added", description "Save to keep it in
|
|
||||||
the article."; advance fake timers 600 ms and assert the modal has closed.
|
|
||||||
9. **A 500 or network failure shows "Upload failed" and keeps the article unchanged, Examples-
|
|
||||||
driven** — for (a) the fake XHR firing `load` with status 500 and (b) firing `error`; assert
|
|
||||||
the failed state shows title "Upload failed", text "The server didn't accept the file. Your
|
|
||||||
article hasn't changed.", confirm "Try again"; assert no `insertImage` call and the editor's
|
|
||||||
body/dirty state is unchanged.
|
|
||||||
10. **"Try again" resends the same file** — from the failed state for `north-wall.jpg`, click
|
|
||||||
"Try again"; assert a new XHR is created for `/v1/article/12/image` with the same file, and
|
|
||||||
the uploading state is shown again.
|
|
||||||
11. **A server 400 for a type the client should have caught shows the rejected copy** — from an
|
|
||||||
uploading state for `notes.pdf`, resolve the fake XHR with status 400; assert the rejected
|
|
||||||
state shows title "\"notes.pdf\" can't be used", text "Use a PNG, JPEG, WEBP or SVG image,
|
|
||||||
up to 10 MB.", confirm "Choose another file"; assert no `insertImage` call.
|
|
||||||
12. **A server 400 for a size the client should have caught shows the size-named rejected copy**
|
|
||||||
— from an uploading state for `north-wall.tif`, resolve the fake XHR with status 400; assert
|
|
||||||
the rejected state shows title "\"north-wall.tif\" can't be used", text "north-wall.tif is
|
|
||||||
14.2 MB. Images can be up to 10 MB.", confirm "Choose another file"; assert no `insertImage`
|
|
||||||
call.
|
|
||||||
|
|
||||||
## Visual (manual verification — desktop and mobile, light and dark)
|
## Visual
|
||||||
|
|
||||||
Reference: `docs/design/screens/editor.md` states "Upload: choose", "Upload: in progress",
|
The Upload tab states are drawn in the `media-picker` group; see `editor_media_picker.qa.md`. The editor-group state 'Upload: choose' awaits the user's editor board update: the user refreshes the editor board themselves, and until then `task visual:check -- editor` is expected to fail on that state. The states "Upload: in progress" and "Upload: rejected" and the crop and resize states are unchanged. `web/visual/states.ts` line 2309 mocks `POST /v1/article/12/image` and must mock `POST /v1/media/` with the item shape, and every editor upload state needs a `GET /v1/media/?limit=24` mock.
|
||||||
"Upload: rejected", "Upload: inserted", and `docs/design/source/RenewCMS Screens Back-
|
|
||||||
office.dc.html`. Run `task visual:check -- editor` for each state below; add each state's mock
|
|
||||||
setup to `web/visual/states.ts` first, reusing editor_core.qa.md's fixture article (id 12, title
|
|
||||||
"How we price a bathroom renovation", draft, "Today, 11:02", 3 images) plus the sample file data
|
|
||||||
from the board: filename "north-wall.jpg", size 3.9 MB, progress 62% / 2.4 of 3.9 MB uploaded.
|
|
||||||
|
|
||||||
- [ ] Upload: choose — modal "Add an image", idle state, cancel "Cancel".
|
|
||||||
- [ ] Upload: in progress — modal "Add an image", uploading "north-wall.jpg 62%" / "Uploading
|
|
||||||
2.4 of 3.9 MB", cancel "Cancel upload".
|
|
||||||
- [ ] Upload: rejected — modal "Add an image", rejected state for a sample rejected file per the
|
|
||||||
board's script, cancel "Cancel", confirm "Choose another file".
|
|
||||||
- [ ] Upload: inserted — toast "Image added" / "Save to keep it in the article.", editor status
|
|
||||||
"draft", save "dirty".
|
|
||||||
- [ ] Mobile (all of the above at 390×844): same modal layout constraints as other editor
|
|
||||||
modals (leading arrow-left button, trailing ellipsis in the header behind it).
|
|
||||||
- [ ] Keyboard/focus: the drop zone is reachable by Tab and Enter opens the file picker; focus
|
|
||||||
moves into the modal on open and is trapped there; Esc during "Upload: in progress"
|
|
||||||
behaves like "Cancel upload" (aborts, closes); the progress bar's `role="progressbar"` /
|
|
||||||
`aria-valuenow` updates are announced without spamming on every progress tick.
|
|
||||||
- [ ] Motion: modal open/close follows the standard 240 ms timing; the success state's 600 ms
|
|
||||||
auto-close is not visually checked as a capture (it's a timing behavior, not a static
|
|
||||||
state) — cover only via the Vitest fake-timer assertion above.
|
|
||||||
|
|
||||||
## Manual verification
|
## Manual verification
|
||||||
|
|
||||||
- **Real POST round trip against a running server** — Vitest only mocks `XMLHttpRequest`;
|
- **Real round trip against `task dev`** with a live SQLite file: a real upload through the SPA (201, 413, 415, 400, 401), then the image shows in `/media`.
|
||||||
confirm a real upload (200/400/401/404/500) against `task dev` with a live SQLite file and the
|
- **Real OS drag and drop** of an image onto the editor in a real browser.
|
||||||
real `POST /v1/article/{id}/image` handler, since `features/upload_article_image.feature`'s
|
- **Real `crypto.subtle`** in a secure context (localhost or HTTPS), including the duplicate card for a file already in the library, and the skipped check on plain HTTP.
|
||||||
httptest suite covers the handler in isolation but never through this SPA flow.
|
- **Keyboard and focus**: the drop zone is reachable by Tab and opens the file chooser with Enter or Space. Focus moves into the dialog and is trapped. Esc during "Upload: in progress" aborts and closes. Tabs are reachable and arrow keys move between them.
|
||||||
- **Real drag-and-drop from the OS file picker** — jsdom's `drop` event is synthetic; confirm a
|
|
||||||
real OS-level drag of an image file onto the editor in a real browser.
|
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
Feature: The editor's Library tab, picking an image from the media library
|
||||||
|
|
||||||
|
As a verified RenewCMS owner writing an article
|
||||||
|
I want to browse my library from the "Add an image" dialog and insert an existing image
|
||||||
|
with alt text
|
||||||
|
So that I can reuse an image without uploading it again
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given this slice is SPA only for this feature: the API from the media library slice is used
|
||||||
|
unchanged, and the Go change to remove the legacy alias is specified in
|
||||||
|
features/remove_legacy_article_image_alias.feature
|
||||||
|
And the screen is docs/design/screens/media-picker.md, drawn by docs/design/source/MediaFrame.dc.html,
|
||||||
|
inside ImageUploader (UModal "Add an image") on /article/:id/edit
|
||||||
|
And the dialog has a title "Add an image", an x to close, and two tabs under the title,
|
||||||
|
"Upload" (icon upload) and "Library" (icon images), 36 px high on desktop and 44 px on
|
||||||
|
mobile with a 2 px primary underline on the selected one; it is 640 px wide on desktop and
|
||||||
|
a bottom sheet on mobile
|
||||||
|
And the footer reads "Cancel", and on the Library tab also a primary "Insert image" that is
|
||||||
|
disabled until an image is selected
|
||||||
|
And the Library tab calls GET /v1/media/ through useApi with limit=24, with q only while a
|
||||||
|
search is set and cursor only when loading more (no filter and no sort parameter), and the
|
||||||
|
Upload tab is specified in features/editor_image_upload.feature
|
||||||
|
And the response is { items, next_cursor, counts }, newest first; sizes read "8 KB" and
|
||||||
|
"3.9 MB", dimensions read "2400 × 1600" (an SVG reads "Vector"), dates are absolute
|
||||||
|
And the 12-image fixture, ids 1 to 12, is the one in features/media_browse.feature, and the
|
||||||
|
picker mocks use next_cursor "c24" and counts { all: 48, unused: 2, duplicates: 2 }
|
||||||
|
And an image is "in this article" when an image node with its id as data-image-id is in
|
||||||
|
the editor's current content, unsaved insertions included, when the dialog opens;
|
||||||
|
in the examples below images 1 (north-wall.jpg) and 4 (logo-renew.svg) are in the article
|
||||||
|
And the search field reads "Search by filename" (32 px high on desktop, 44 px with 16 px
|
||||||
|
text on mobile), with a search icon and, once it has text, an x that clears it
|
||||||
|
And the grid has 4 columns on desktop and 3 on mobile with a 12 px gap (8 px between
|
||||||
|
columns on mobile), square tiles with a 1 px border, and the filename under each tile in
|
||||||
|
12 px toned text with an ellipsis; it scrolls inside the dialog, 300 px high with nothing
|
||||||
|
selected, 190 px on desktop and 120 px on mobile with one selected
|
||||||
|
And every tile is one button whose accessible name reads like the Media page's, for example
|
||||||
|
"north-wall.jpg, 3.9 MB, used in 2 articles" or "window-frame.jpg, 1.8 MB, unused"
|
||||||
|
And skeleton tiles show only after 150 ms: 8 on desktop and 9 on mobile for a first load
|
||||||
|
or a search, one row (4 or 3) at the end for "Load more"
|
||||||
|
And a 401 or 403 on any of these calls is handled globally by useApi, with no local copy
|
||||||
|
|
||||||
|
Rule: Which tab opens
|
||||||
|
|
||||||
|
Scenario: The library has images, so Library opens
|
||||||
|
Given GET /v1/media/?limit=24 resolves 200 with the 12-image fixture
|
||||||
|
When the user activates the toolbar's "Image" button
|
||||||
|
Then the Library tab is selected and the footer reads "Cancel" and a disabled "Insert image"
|
||||||
|
And nothing is drawn in the grid for the first 150 ms, then 8 skeleton tiles show until the response arrives
|
||||||
|
|
||||||
|
Scenario: The library is empty, so Upload opens
|
||||||
|
Given GET /v1/media/?limit=24 resolves 200 with no item and no search set
|
||||||
|
When the dialog opens
|
||||||
|
Then the Upload tab is selected, in its idle state
|
||||||
|
When the user selects the Library tab
|
||||||
|
Then the empty panel shows
|
||||||
|
|
||||||
|
Scenario: A dropped file opens Upload and sends no list request
|
||||||
|
When the user drops "before.png" onto the editor
|
||||||
|
Then the Upload tab is selected and no GET /v1/media/?limit=24 is sent
|
||||||
|
When the user selects the Library tab
|
||||||
|
Then GET /v1/media/?limit=24 is sent
|
||||||
|
|
||||||
|
Rule: Browsing
|
||||||
|
|
||||||
|
Scenario: Library, nothing selected
|
||||||
|
Given the first page resolved with the 12-image fixture
|
||||||
|
Then the line "Newest first · 48 images" shows under the search field
|
||||||
|
And 12 tiles show in fixture order, 4 per row on desktop and 3 on mobile, each with its filename
|
||||||
|
And the tiles of "north-wall.jpg" and "logo-renew.svg" carry a sand "In this article" tag (bottom-left, 18 px high, 11 px text)
|
||||||
|
And no other tile carries it
|
||||||
|
And "Load more" shows below the grid, and "Insert image" is disabled
|
||||||
|
|
||||||
|
Scenario: A search is active, so the count is not shown
|
||||||
|
Given the user typed "wall" and the response resolved with 2 items
|
||||||
|
Then the line reads "Newest first"
|
||||||
|
|
||||||
|
Scenario: Load more is hidden on the last page
|
||||||
|
Given the response has next_cursor null
|
||||||
|
Then "Load more" is not shown
|
||||||
|
|
||||||
|
Scenario Outline: A tile's accessible name
|
||||||
|
Given the first page resolved with the 12-image fixture
|
||||||
|
Then the tile for "<filename>" is named "<name>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| filename | name |
|
||||||
|
| north-wall.jpg | north-wall.jpg, 3.9 MB, used in 2 articles |
|
||||||
|
| kitchen-before.webp | kitchen-before.webp, 1.1 MB, used in 1 article |
|
||||||
|
| window-frame.jpg | window-frame.jpg, 1.8 MB, unused |
|
||||||
|
|
||||||
|
Rule: Selection
|
||||||
|
|
||||||
|
Scenario Outline: A tile is selected by pointer or keyboard
|
||||||
|
Given the first page resolved with the 12-image fixture
|
||||||
|
When the user <action> on the tile of "kitchen-after.webp"
|
||||||
|
Then that tile has a 2 px primary outline (2 px offset) and a 20 px primary check at its top-right
|
||||||
|
And "Insert image" is enabled
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| action |
|
||||||
|
| clicks |
|
||||||
|
| presses Enter |
|
||||||
|
| presses Space |
|
||||||
|
|
||||||
|
Scenario: The selection panel
|
||||||
|
Given "kitchen-after.webp" is selected
|
||||||
|
Then the grid shrinks and a panel shows below it, under a 1 px top border
|
||||||
|
And the panel has a 56 px thumbnail, the filename "kitchen-after.webp", "2400 × 1600 · 1.2 MB", and a field "Alt text (optional)"
|
||||||
|
And the field's placeholder reads "e.g. North wall of the kitchen before plastering"
|
||||||
|
And its help reads "Describes the image for people who use a screen reader, and shows if it doesn't load. Leave it empty if the image is only decoration."
|
||||||
|
And "Load more" is hidden while an image is selected
|
||||||
|
|
||||||
|
Scenario: Selection is single
|
||||||
|
Given "kitchen-after.webp" is selected and the alt text reads "A kitchen"
|
||||||
|
When the user selects "window-frame.jpg"
|
||||||
|
Then only "window-frame.jpg" is selected and the alt text field is empty
|
||||||
|
|
||||||
|
Scenario: Activating the selected tile again keeps it selected
|
||||||
|
Given "kitchen-after.webp" is selected
|
||||||
|
When the user activates its tile
|
||||||
|
Then it stays selected
|
||||||
|
|
||||||
|
Scenario: An SVG's panel reads "Vector"
|
||||||
|
When the user selects "logo-renew.svg"
|
||||||
|
Then the panel reads "Vector · 8 KB"
|
||||||
|
|
||||||
|
Scenario: An image already in the article can be selected and inserted again
|
||||||
|
When the user selects "north-wall.jpg", which carries "In this article"
|
||||||
|
Then "Insert image" is enabled
|
||||||
|
|
||||||
|
Rule: Insert
|
||||||
|
|
||||||
|
Scenario: Insert with alt text
|
||||||
|
Given the user is on /article/12/edit in the Saved state with "kitchen-after.webp" (id 2, url "/static/uploadedImages/2.webp") selected
|
||||||
|
And the alt text reads "A kitchen with new oak worktops and white tiles"
|
||||||
|
When the user activates "Insert image"
|
||||||
|
Then insertImage is called with "/static/uploadedImages/2.webp", "A kitchen with new oak worktops and white tiles" and image id 2
|
||||||
|
And the image is in the editor's content at the cursor, with data-image-id 2
|
||||||
|
And SaveStatus reads "Unsaved changes" and Save is enabled
|
||||||
|
And a toast appears: color success, icon i-lucide-circle-check, title "Image added", description "Save to keep it in the article."
|
||||||
|
And the dialog closes at once
|
||||||
|
And no POST, PATCH or DELETE has been sent
|
||||||
|
|
||||||
|
Scenario: Empty alt text inserts a decorative image
|
||||||
|
Given "kitchen-after.webp" is selected and the alt text is empty
|
||||||
|
When the user activates "Insert image"
|
||||||
|
Then insertImage is called with alt ""
|
||||||
|
|
||||||
|
Scenario: Alt text lives only in the article
|
||||||
|
Given "kitchen-after.webp" is selected with alt text "A kitchen"
|
||||||
|
When the user activates "Insert image"
|
||||||
|
Then no request carries the alt text and the library item is unchanged
|
||||||
|
|
||||||
|
Scenario Outline: Leaving without inserting changes nothing
|
||||||
|
Given "kitchen-after.webp" is selected with alt text "A kitchen"
|
||||||
|
When the user <action>
|
||||||
|
Then the dialog closes, the editor's content and dirty state are unchanged, and no toast shows
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| action |
|
||||||
|
| activates "Cancel" |
|
||||||
|
| activates the x |
|
||||||
|
| presses Escape |
|
||||||
|
|
||||||
|
Rule: Search
|
||||||
|
|
||||||
|
Scenario: Typing searches after a debounce
|
||||||
|
Given the Library tab shows the 12-image fixture
|
||||||
|
When the user types "wall"
|
||||||
|
Then after a 120 ms debounce GET /v1/media/ is sent with q=wall and limit=24 and no cursor
|
||||||
|
And skeleton tiles show after 150 ms, and any selection is cleared
|
||||||
|
|
||||||
|
Scenario: The x in the field clears the search
|
||||||
|
Given the search field holds "wall" with results shown
|
||||||
|
When the user activates the x in the field
|
||||||
|
Then the field is empty and GET /v1/media/ is sent with limit=24 and no q
|
||||||
|
|
||||||
|
Scenario: No results
|
||||||
|
Given GET /v1/media/?q=wall&limit=24 resolves 200 with no item
|
||||||
|
Then the search icon shows with the title `No images match "wall"`, the text "Check the spelling, or search for a shorter part of the filename." and a "Clear search" button
|
||||||
|
And the search field still shows "wall" above it, and "Insert image" is disabled
|
||||||
|
When the user activates "Clear search"
|
||||||
|
Then the field is emptied and the list is requested again with no q
|
||||||
|
|
||||||
|
Rule: Load more
|
||||||
|
|
||||||
|
Scenario: Loading more shows progress and appends
|
||||||
|
Given the first page resolved with 12 images, next_cursor "c24"
|
||||||
|
When the user activates "Load more"
|
||||||
|
Then GET /v1/media/ is sent with limit=24 and cursor=c24
|
||||||
|
And the button reads "Loading…" with a loader-circle and is disabled, and one row of skeleton tiles shows at the end
|
||||||
|
And focus stays on the button
|
||||||
|
When the request resolves 200 with 12 more images
|
||||||
|
Then the new tiles are appended after the first 12, and focus moves to the first new tile
|
||||||
|
|
||||||
|
Scenario: The cursor and the search combine
|
||||||
|
Given the search "wall" is active and the page has next_cursor "c24"
|
||||||
|
When the user activates "Load more"
|
||||||
|
Then GET /v1/media/ is sent with q=wall, limit=24 and cursor=c24
|
||||||
|
|
||||||
|
Rule: Empty and failed
|
||||||
|
|
||||||
|
Scenario: Empty library
|
||||||
|
Given the Library tab is selected and GET /v1/media/?limit=24 resolved with no item
|
||||||
|
Then the images icon shows with "Your library is empty", "Images you upload appear here, ready to use in any article." and a primary "Upload an image"
|
||||||
|
And "Insert image" is disabled
|
||||||
|
When the user activates "Upload an image"
|
||||||
|
Then the Upload tab is selected
|
||||||
|
|
||||||
|
Scenario Outline: The library fails to load
|
||||||
|
Given GET /v1/media/ <failure>
|
||||||
|
When the Library tab loads
|
||||||
|
Then an error alert shows in the dialog: icon circle-x, title "Couldn't load your library", text "Check your connection and try again.", and a "Try again" button
|
||||||
|
And "Insert image" is disabled
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then the same request is sent again with a skeleton, and on 200 the tiles replace the alert
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| never reaches the server |
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# QA: The editor's Library tab
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `request` for `GET /v1/media/` by parsed query. Use the 12-image fixture from `media_browse.feature` as `items`, with `next_cursor: "c24"` and `counts: {all: 48, unused: 2, duplicates: 2}`. Mount EditorPage at `/article/12/edit` with a body containing `<img data-image-id="1">` and `<img data-image-id="4">`. Use fake timers for the 150 ms and 120 ms steps.
|
||||||
|
|
||||||
|
1. **Opens on Library with images** - first response has items; assert Library selected and skeleton tiles only after 150 ms.
|
||||||
|
2. **Opens on Upload when empty** - empty first response; assert Upload selected; then click Library and assert the empty panel.
|
||||||
|
3. **Drop sends no list request** - drop a file; assert no `?limit=24` request until Library is clicked.
|
||||||
|
4. **Nothing selected** - assert the line, 12 tiles in order, the "In this article" tag on exactly ids 1 and 4, "Load more", "Insert image" disabled.
|
||||||
|
5. **Active search hides the count** - the line reads "Newest first".
|
||||||
|
6. **Last page** - `next_cursor: null` hides "Load more".
|
||||||
|
7. **Accessible names** - the three Examples.
|
||||||
|
8. **Selection** - click, Enter and Space each select; check, outline, "Insert image" enabled.
|
||||||
|
9. **Panel copy** - kitchen-after.webp panel, placeholder and help text exact; "Load more" hidden; SVG reads "Vector · 8 KB".
|
||||||
|
10. **Single selection resets alt**; reactivating keeps it selected.
|
||||||
|
11. **Insert** - alt "A kitchen with new oak worktops and white tiles" gives `insertImage("/static/uploadedImages/2.webp", alt, 2)`, SaveStatus "Unsaved changes", the toast, the dialog closed, no non-GET request. Empty alt gives `""`.
|
||||||
|
12. **Cancel, x and Escape** change nothing.
|
||||||
|
13. **Search** - type "wall"; at 119 ms no request, at 120 ms the request has `q=wall&limit=24` and no cursor; the selection is cleared. The field's x and "Clear search" send a request with no `q`.
|
||||||
|
14. **No results** and **Empty** copy; "Upload an image" switches to the Upload tab.
|
||||||
|
15. **Load more** - request has `cursor=c24`; button "Loading…" and disabled; skeleton row of 4 (3 below md); focus on the button, then on the first new tile after resolve; combined `q` and `cursor`.
|
||||||
|
16. **Failed to load, Examples 500 and network** - alert copy; "Try again" repeats the request; success replaces the alert.
|
||||||
|
|
||||||
|
## Visual: `task visual:check -- media-picker`
|
||||||
|
|
||||||
|
Add a setup in `web/visual/states.ts` for each of the 13 states in `docs/design/screens/media-picker.md`, from the board's script (`RenewCMS Screens Back-office.dc.html` lines 239 to 253). Every capture must be within 10 % at 1440×900 and 390×844, light and dark. The sample data to reuse:
|
||||||
|
- Library mock: the 12-image fixture, `counts.all` 48, `next_cursor` non-null; images 1 and 4 in the article. The dialog is opened on the editor "How we price a bathroom renovation".
|
||||||
|
- "Upload tab": Upload selected, idle drop zone.
|
||||||
|
- "Upload tab: already in your library": a chosen file named `north-wall.jpg`; the hash lookup returns id 1 (12 Sep 2026, Marta Alves); the thumbnail is 72 × 54.
|
||||||
|
- "Library: loading": skeleton tiles.
|
||||||
|
- "Library: nothing selected": the 12 tiles, tags on ids 1 and 4, "Load more".
|
||||||
|
- "Library: selected": id 2 (kitchen-after.webp, 2400 × 1600 · 1.2 MB), empty alt.
|
||||||
|
- "Library: alt text entered": id 2 with alt "A kitchen with new oak worktops and white tiles".
|
||||||
|
- "Library: loading more": 12 tiles plus one skeleton row, button "Loading…".
|
||||||
|
- "Library: empty": a mock with zero items. "Library: no results": search "wall" and zero items.
|
||||||
|
- "Library: failed to load": a 500.
|
||||||
|
- "Inserted": the editor with an image (id 1 as the board draws it) and the toast "Image added" / "Save to keep it in the article.".
|
||||||
|
- "Remove image: confirm": the confirm over the editor, image id 1 (north-wall.jpg, 3.9 MB). See `editor_image_removal.qa.md`.
|
||||||
|
- "Removed": the editor without the image and the toast "Image removed" / "It's still in your library.".
|
||||||
|
|
||||||
|
Clock-sensitive: none. Dates are absolute. Nothing is skipped.
|
||||||
|
|
||||||
|
Layout facts the mocks must hit (from the frame): the dialog is 640 px at 40 px from the top; the tabs row has a 20 px gap and 24 px side padding; the body has 16 px top padding and 24 px side padding; the search field is 32 px (44 px on mobile); the grid gap is 12 px (8 px between columns on mobile).
|
||||||
|
|
||||||
|
Manual checks the screenshots can't cover:
|
||||||
|
- [ ] Focus order is tabs, search, tiles, "Load more", footer. Enter and Space select a tile. Focus returns to the toolbar's image button when the dialog closes.
|
||||||
|
- [ ] Hover on a tile and on "Load more", and the focus ring.
|
||||||
|
- [ ] Motion: the dialog follows the standard 240 ms timing.
|
||||||
|
- [ ] A real library of more than 24 images through `task dev`: "Load more" and the cursor.
|
||||||
|
- [ ] A screen reader reads the tile names and the alt text help.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
Real `GET /v1/media/` with `q` and `cursor` against `task dev` with a live SQLite file.
|
||||||
@@ -17,8 +17,8 @@ Feature: Allowed image types and the size limit are a domain rule
|
|||||||
the matching sentinel and calling the repository not at all when either check fails
|
the matching sentinel and calling the repository not at all when either check fails
|
||||||
And ImageRepository.Create no longer rejects an unrecognized content type itself; it
|
And ImageRepository.Create no longer rejects an unrecognized content type itself; it
|
||||||
only maps an already-allowed content type to a file extension
|
only maps an already-allowed content type to a file extension
|
||||||
And no image HTTP endpoint is mounted in api/router.go as of this slice, so this
|
And the HTTP mapping of these sentinels is 413, 415 and 400, specified in
|
||||||
behavior is observable only through CreateImageUseCase
|
features/media_library.feature
|
||||||
|
|
||||||
Scenario Outline: CreateImage accepts every allowed content type within the size limit
|
Scenario Outline: CreateImage accepts every allowed content type within the size limit
|
||||||
Given an empty image repository fake
|
Given an empty image repository fake
|
||||||
|
|||||||
@@ -0,0 +1,370 @@
|
|||||||
|
Feature: Media page, part 1: browse and manage
|
||||||
|
|
||||||
|
As a verified RenewCMS owner
|
||||||
|
I want /media to show every image in my library, let me search, filter, sort and switch view, and
|
||||||
|
let me inspect, copy, rename and delete one image at a time
|
||||||
|
So that I can manage the library from one place, with the page always reflecting what the
|
||||||
|
server actually holds
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given /media is a verified route (meta.auth "verified", meta.title "Media") rendered as
|
||||||
|
MediaPage inside DashboardShell, per docs/design/routes.md
|
||||||
|
And the sidebar gains the item "Media" (icon images) between "Articles" and "Users", in the
|
||||||
|
desktop sidebar and in the mobile drawer, it is the active item on /media, and the
|
||||||
|
breadcrumb reads "Media" (mobile title "Media")
|
||||||
|
And this slice is SPA only: the API from slice A already exists and is used unchanged, and
|
||||||
|
no Go code, use case or repository changes
|
||||||
|
And upload, multi-select, the bulk bar, the Duplicates tab content, duplicate merge,
|
||||||
|
drag-and-drop and the rate-limited state are specified in
|
||||||
|
features/media_upload_selection_duplicates.feature
|
||||||
|
And useMedia is a composable over useApi. It exposes the list state (items, counts, loading,
|
||||||
|
error), the request functions for list, usage, rename and delete, and the copy helper, and
|
||||||
|
it maps ApiError and NetworkError to the states below
|
||||||
|
And MediaPage calls GET /v1/media/ with the query built from the URL, always with limit=100,
|
||||||
|
and every request carries the jwt cookie through useApi
|
||||||
|
And search, tab, sort and view live in the URL query string so the view can be linked and
|
||||||
|
survives a reload: ?q= (search text), ?filter= ("unused" or "duplicates"; absent means
|
||||||
|
All), ?sort= ("oldest", "name" or "largest"; absent means Newest), ?view= ("list"; absent
|
||||||
|
means grid); a value outside these sets is dropped and the default applies; the names
|
||||||
|
mirror the API's own q, filter and sort parameters
|
||||||
|
And the header shows the title "Media", the subtitle "Every image you've uploaded, ready to
|
||||||
|
use in any article." and a primary "Upload" button (icon upload) on the right; on mobile it is
|
||||||
|
the full-width 48 px button pinned to the bottom
|
||||||
|
And the toolbar holds the tabs "All", "Unused" and "Duplicates" with a count each, then the
|
||||||
|
search field (placeholder "Search by filename"), the sort menu (options "Newest", "Oldest",
|
||||||
|
"Name", "Largest", sent as sort=newest, oldest, name, largest) and the grid/list toggle
|
||||||
|
(icons layout-grid and list); below md the toolbar stacks: search, tabs, then sort and toggle
|
||||||
|
And the tab counts come from the response's counts object (all, unused, duplicates). The
|
||||||
|
Duplicates count is a number of groups, drawn as an info-tinted badge only while it is
|
||||||
|
above 0. The All and Unused counts are drawn as plain muted mono numbers, as in the board
|
||||||
|
And the Duplicates tab selects the groups view and ?filter=duplicates is a valid value
|
||||||
|
And the grid is 5 columns on desktop and 2 on mobile, with a 16 px gap (10 px on mobile),
|
||||||
|
and each card is one button holding MediaThumb (4:3, a checkerboard behind PNG and SVG),
|
||||||
|
the filename (medium weight, ellipsis), "size · dimensions" and the MediaBadges; an SVG's
|
||||||
|
dimensions read "Vector"
|
||||||
|
And sizes read "8 KB" and "860 KB" (whole KB) below 1 MB and "3.9 MB" (one decimal, 1024
|
||||||
|
base) from 1 MB up; dimensions read "4032 × 3024"; dates read "12 Sep 2026" (absolute,
|
||||||
|
never relative); the Type column reads JPEG, PNG, WEBP or SVG from content_type
|
||||||
|
And the MediaBadges are: "Unused" (warning-soft fill, icon unlink) when used_in is 0,
|
||||||
|
"Duplicate" (info-soft fill, icon copy) when duplicate is true, and "Used in N"
|
||||||
|
(outline, toned text) when used_in is above 0; in the detail panel the article rows use
|
||||||
|
"Online" (icon globe, inverted fill) and "Draft" (icon pencil-line, outline)
|
||||||
|
And each card's accessible name reads "north-wall.jpg, 3.9 MB, used in 2 articles",
|
||||||
|
"kitchen-before.webp, 1.1 MB, used in 1 article" (singular for 1) or "window-frame.jpg,
|
||||||
|
1.8 MB, unused"
|
||||||
|
And list view is a table from md up (columns Filename with a 40 px thumbnail and the
|
||||||
|
Duplicate badge, Dimensions, Size, Type, Used in, Uploaded by, and Uploaded with an
|
||||||
|
arrow-down as the sorted column; 36 px header, 56 px rows) and a card list below md (56 px
|
||||||
|
thumbnail, filename, "size · dimensions · type", badges plus "uploader · date", and a
|
||||||
|
trailing chevron-right); in the table the "Used in" cell is an underlined count that
|
||||||
|
opens the detail panel, and reads the Unused badge when used_in is 0
|
||||||
|
And the checkbox column of the table (36 px), the 44 px checkbox column of the card list and
|
||||||
|
the "Select all" row above the grid are specified in
|
||||||
|
features/media_upload_selection_duplicates.feature
|
||||||
|
And the detail panel is a USlideover: 460 px on the right on desktop (a close button x),
|
||||||
|
full screen on mobile with an arrow-left back button; its title is the filename; the body
|
||||||
|
holds the 16:10 preview (4:3 on mobile), the actions "Copy URL" (icon link), "Rename"
|
||||||
|
(icon pencil) and "Delete" (icon trash-2, error-coloured text), the duplicate alert when
|
||||||
|
the image is a duplicate, the metadata list (Type, Size, Dimensions, Uploaded, Uploaded by,
|
||||||
|
and URL in mono) and the "Used in" section
|
||||||
|
And opening the panel for an image with used_in above 0 calls GET /v1/media/{id}/usage; for an
|
||||||
|
image with used_in 0 no usage call is sent
|
||||||
|
And the dialogs (Rename, Delete) are UModal with sm:max-w-md, a bottom sheet on mobile and
|
||||||
|
Cancel first; while a request runs the confirm button shows a loader-circle, both buttons
|
||||||
|
are disabled, and the dialog cannot be dismissed by Cancel, Escape or a backdrop click; a
|
||||||
|
failure shows an error alert at the top of the dialog body and the dialog stays open
|
||||||
|
And every success toast lasts 5 s; toast ids follow the action-plus-id convention:
|
||||||
|
"media-url-copied-{id}", "media-renamed-{id}", "media-deleted-{id}", "media-not-found-{id}"
|
||||||
|
And the library is this 12-image fixture, newest first (id, filename, size, dimensions, type,
|
||||||
|
used in, uploader, uploaded, flags), from the board's own script:
|
||||||
|
| id | filename | size | dimensions | type | used | uploaded by | uploaded | flags |
|
||||||
|
| 1 | north-wall.jpg | 3.9 MB | 4032 × 3024 | JPEG | 2 | Marta Alves | 12 Sep 2026 | |
|
||||||
|
| 2 | kitchen-after.webp | 1.2 MB | 2400 × 1600 | WEBP | 3 | Inès Duarte | 8 Sep 2026 | |
|
||||||
|
| 3 | kitchen-before.webp | 1.1 MB | 2400 × 1600 | WEBP | 1 | Inès Duarte | 8 Sep 2026 | |
|
||||||
|
| 4 | logo-renew.svg | 8 KB | Vector | SVG | 5 | jonas | 5 Sep 2026 | alpha |
|
||||||
|
| 5 | floorboards-copy.jpg | 2.4 MB | 3600 × 2400 | JPEG | 3 | Marta Alves | 2 Sep 2026 | duplicate |
|
||||||
|
| 6 | IMG_2208.jpg | 2.4 MB | 3600 × 2400 | JPEG | 2 | jonas | 30 Aug 2026 | duplicate |
|
||||||
|
| 7 | IMG_4471.jpg | 3.1 MB | 3600 × 2400 | JPEG | 2 | Marta Alves | 29 Aug 2026 | duplicate |
|
||||||
|
| 8 | window-frame.jpg | 1.8 MB | 3000 × 2000 | JPEG | 0 | Inès Duarte | 28 Aug 2026 | |
|
||||||
|
| 9 | stone-wall-detail.jpg | 3.1 MB | 3600 × 2400 | JPEG | 1 | jonas | 21 Aug 2026 | duplicate |
|
||||||
|
| 10 | bathroom-tiles.png | 860 KB | 1800 × 1200 | PNG | 0 | Marta Alves | 4 Aug 2026 | alpha |
|
||||||
|
| 11 | lime-plaster.jpg | 2.1 MB | 3200 × 2133 | JPEG | 2 | Inès Duarte | 19 Jul 2026 | |
|
||||||
|
| 12 | floorboards.jpg | 2.4 MB | 3600 × 2400 | JPEG | 4 | Inès Duarte | 14 Jun 2026 | duplicate |
|
||||||
|
with counts { all: 12, unused: 2, duplicates: 2 }, and next_cursor null
|
||||||
|
|
||||||
|
Scenario: Default, many images
|
||||||
|
Given GET /v1/media/?filter=all&sort=newest&limit=100 resolves 200 with the 12-image fixture
|
||||||
|
When the user navigates to /media
|
||||||
|
Then the breadcrumb reads "Media" (mobile title "Media")
|
||||||
|
And the tabs read "All 12", "Unused 2", "Duplicates 2", with "All" selected, and the
|
||||||
|
Duplicates count drawn as an info-tinted badge
|
||||||
|
And the grid shows the 12 images in exactly the fixture's order, 5 per row on desktop and 2
|
||||||
|
on mobile, each card with its thumbnail, filename, "size · dimensions" and badges
|
||||||
|
And the "Select all" row above the grid reads "Select all" and "12 images"
|
||||||
|
And the toolbar shows "Search by filename", the sort "Newest" and the grid toggle selected
|
||||||
|
|
||||||
|
Scenario Outline: Each card's badges and accessible name follow the image
|
||||||
|
Given the Default state has loaded
|
||||||
|
Then the card for "<filename>" has the accessible name "<name>" and the badges "<badges>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| filename | name | badges |
|
||||||
|
| north-wall.jpg | north-wall.jpg, 3.9 MB, used in 2 articles | Used in 2 |
|
||||||
|
| kitchen-before.webp | kitchen-before.webp, 1.1 MB, used in 1 article | Used in 1 |
|
||||||
|
| window-frame.jpg | window-frame.jpg, 1.8 MB, unused | Unused |
|
||||||
|
| floorboards.jpg | floorboards.jpg, 2.4 MB, used in 4 articles | Duplicate, Used in 4 |
|
||||||
|
| logo-renew.svg | logo-renew.svg, 8 KB, used in 5 articles | Used in 5 |
|
||||||
|
|
||||||
|
Scenario: Grid, few images, keeps card size
|
||||||
|
Given GET /v1/media/ resolves 200 with ids 1, 4 and 8 and counts { all: 3, unused: 1, duplicates: 0 }
|
||||||
|
When the user navigates to /media
|
||||||
|
Then three cards render at the same size as in the 12-image grid, not stretched
|
||||||
|
And a checkerboard shows behind the SVG thumbnail of "logo-renew.svg"
|
||||||
|
And the tabs read "All 3", "Unused 1" and "Duplicates" with no count badge
|
||||||
|
|
||||||
|
Scenario: List view, desktop, is a table
|
||||||
|
Given the Default state has loaded at md width or more
|
||||||
|
When the user activates the list icon in the toggle
|
||||||
|
Then the URL gains ?view=list
|
||||||
|
And a table shows the columns Filename, Dimensions, Size, Type, Used in, Uploaded by and
|
||||||
|
Uploaded (with an arrow-down), 12 rows of 56 px under a 36 px header, in fixture order
|
||||||
|
And each Filename cell shows a 40 px thumbnail, the filename and, for duplicates, the
|
||||||
|
Duplicate badge; the Used in cell shows an underlined count, or the Unused badge
|
||||||
|
for id 8 and id 10
|
||||||
|
And the Uploaded by cells read the uploader and the Uploaded cells read "12 Sep 2026"
|
||||||
|
|
||||||
|
Scenario: List view, mobile, is a card list
|
||||||
|
Given the Default state has loaded below md width with ?view=list
|
||||||
|
Then a card list replaces the grid; each row shows a 56 px thumbnail, the filename,
|
||||||
|
"3.9 MB · 4032 × 3024 · JPEG", the badges followed by "Marta Alves · 12 Sep 2026", and a
|
||||||
|
trailing chevron-right
|
||||||
|
When the user taps a row
|
||||||
|
Then the detail panel opens for that image
|
||||||
|
|
||||||
|
Scenario Outline: The query string is the source of truth for search, tab, sort and view
|
||||||
|
Given GET /v1/media/ is mocked
|
||||||
|
When the user opens /media<url>
|
||||||
|
Then GET /v1/media/ is sent with "<request>" and limit=100
|
||||||
|
And the control shows "<control>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| url | request | control |
|
||||||
|
| ?filter=unused | filter=unused&sort=newest | tab "Unused" selected |
|
||||||
|
| ?sort=largest | filter=all&sort=largest | sort "Largest" |
|
||||||
|
| ?sort=name | filter=all&sort=name | sort "Name" |
|
||||||
|
| ?sort=oldest | filter=all&sort=oldest | sort "Oldest" |
|
||||||
|
| ?q=wall | q=wall&filter=all | search field "wall" |
|
||||||
|
| ?view=list | filter=all&sort=newest | list icon selected |
|
||||||
|
| ?filter=bogus&sort=zzz | filter=all&sort=newest | tab "All" and sort "Newest", URL kept clean |
|
||||||
|
| ?filter=duplicates | filter=all&sort=newest | tab "All" selected |
|
||||||
|
|
||||||
|
Scenario: Changing a control writes the query string and reloads the list
|
||||||
|
Given the Default state has loaded
|
||||||
|
When the user types "wall" in the search field
|
||||||
|
Then after a 120 ms debounce the URL gains ?q=wall and GET /v1/media/?q=wall&filter=all&sort=newest&limit=100 is sent
|
||||||
|
When the user selects the "Unused" tab
|
||||||
|
Then the URL reads ?q=wall&filter=unused and the list is requested again
|
||||||
|
When the user picks "Largest" in the sort menu
|
||||||
|
Then the URL gains sort=largest and the list is requested again
|
||||||
|
And selecting "All" removes filter from the URL, "Newest" removes sort, and the grid icon removes view
|
||||||
|
|
||||||
|
Scenario: Loading, skeleton cards after 150 ms
|
||||||
|
Given GET /v1/media/ has not yet resolved
|
||||||
|
When the user navigates to /media
|
||||||
|
Then nothing is drawn for the first 150 ms
|
||||||
|
And after 150 ms 10 skeleton cards (6 on mobile) replace the images, the list container is
|
||||||
|
aria-busy="true", and the toolbar stays visible
|
||||||
|
When the request resolves 200 with the 12-image fixture
|
||||||
|
Then the skeleton cards are replaced by the Default state's cards
|
||||||
|
And the same skeleton appears on a retry and on a change of search, tab or sort, in grid and
|
||||||
|
list view alike
|
||||||
|
|
||||||
|
Scenario: Empty library, first run
|
||||||
|
Given GET /v1/media/ resolves 200 with zero items and counts { all: 0, unused: 0, duplicates: 0 } and no q
|
||||||
|
When the user navigates to /media
|
||||||
|
Then the toolbar and the tabs are hidden
|
||||||
|
And one panel shows the images icon, title "No images yet", text "Upload your first image. You can use it in any article.", a primary "Upload an image" button, and under it "PNG, JPEG, WEBP, SVG · max 10 MB each"
|
||||||
|
|
||||||
|
Scenario: No results, search and filter
|
||||||
|
Given the Default state has loaded
|
||||||
|
When the user selects "Unused" and types "wall" and GET /v1/media/?q=wall&filter=unused&sort=newest&limit=100 resolves 200 with zero items
|
||||||
|
Then a panel replaces the images with the search icon, title `No images match "wall"`, text "Nothing matches in Unused. Check the spelling, or clear the filters." and an outline "Clear filters" button
|
||||||
|
When the user activates "Clear filters"
|
||||||
|
Then the search field is emptied, the tab returns to "All", ?q and ?filter leave the URL, and the Default cards reappear
|
||||||
|
|
||||||
|
Scenario: Hover, focus and keyboard
|
||||||
|
Given the Default state has loaded on desktop
|
||||||
|
Then every card is one button and one tab stop
|
||||||
|
When the pointer rests on the second card ("kitchen-after.webp")
|
||||||
|
Then its border darkens (border-accented) and it gains the pop shadow
|
||||||
|
When the third card ("kitchen-before.webp") takes keyboard focus
|
||||||
|
Then it shows a 2 px primary ring with a 2 px offset and its accessible name reads "kitchen-before.webp, 1.1 MB, used in 1 article"
|
||||||
|
When the user presses an arrow key on a card
|
||||||
|
Then focus moves to the neighbouring card across the grid (left and right by one, up and down by one row, stopping at the edges)
|
||||||
|
When the user presses Enter on a card
|
||||||
|
Then the detail panel opens for that image
|
||||||
|
When the user presses Space on a card
|
||||||
|
Then the card's selection toggles and no panel opens
|
||||||
|
|
||||||
|
Scenario: Detail panel, in use
|
||||||
|
Given the Default state has loaded and GET /v1/media/1/usage resolves 200 with [{ id: 10, title: "How we price a bathroom renovation", published: true }, { id: 11, title: "Winter checklist for timber windows", published: false }]
|
||||||
|
When the user activates the "north-wall.jpg" card
|
||||||
|
Then the slideover opens with the title "north-wall.jpg", a 16:10 preview and the actions "Copy URL", "Rename" and "Delete" (Delete in error-coloured text)
|
||||||
|
And the metadata list reads Type "JPEG", Size "3.9 MB", Dimensions "4032 × 3024", Uploaded "12 Sep 2026", Uploaded by "Marta Alves" and URL in mono
|
||||||
|
And the "Used in" section reads "Used in 2 articles" over one bordered row per article: the title as an underlined link to /article/{id}/edit, a badge "Online" (icon globe, inverted) for "How we price a bathroom renovation" or "Draft" (icon pencil-line, outline) for "Winter checklist for timber windows", and an arrow-up-right
|
||||||
|
And the footnote reads "Counted from the text of your articles each time you open this page."
|
||||||
|
When the user closes the panel (x, the back arrow on mobile, or Escape)
|
||||||
|
Then the panel closes and focus returns to the "north-wall.jpg" card
|
||||||
|
|
||||||
|
Scenario: Detail panel, unused
|
||||||
|
Given the Default state has loaded
|
||||||
|
When the user activates the "window-frame.jpg" card
|
||||||
|
Then no usage request is sent
|
||||||
|
And the "Used in" section reads "Not used in any article" over the text "This image is safe to delete. No article shows it."
|
||||||
|
|
||||||
|
Scenario: Detail panel, duplicate
|
||||||
|
Given the Default state has loaded, GET /v1/media/?hash=<sha256 of id 12> resolves 200 with ids 12, 5 and 6, and GET /v1/media/12/usage resolves 200
|
||||||
|
When the user activates the "floorboards.jpg" card
|
||||||
|
Then an info alert reads "Identical to 2 other images" over "floorboards-copy.jpg and IMG_2208.jpg have the same content." with an action "Review duplicates" (icon arrow-right)
|
||||||
|
And the action is enabled and selects the Duplicates tab
|
||||||
|
|
||||||
|
Scenario: The Used in count in list view opens the panel
|
||||||
|
Given the Default state has loaded with ?view=list at md width or more
|
||||||
|
When the user activates the underlined "2" in the "north-wall.jpg" row
|
||||||
|
Then the detail panel opens for "north-wall.jpg" with its "Used in 2 articles" list
|
||||||
|
|
||||||
|
Scenario: Copy URL
|
||||||
|
Given the detail panel is open for "north-wall.jpg"
|
||||||
|
When the user activates "Copy URL"
|
||||||
|
Then "{origin}{url}" (the absolute address of the image) is written to the clipboard
|
||||||
|
And a success toast appears: icon circle-check, id "media-url-copied-1", title "URL copied", text "Paste it wherever you need the image address."
|
||||||
|
|
||||||
|
Scenario: Rename, dialog
|
||||||
|
Given the detail panel is open for "north-wall.jpg"
|
||||||
|
When the user activates "Rename"
|
||||||
|
Then a dialog opens: title "Rename image", description "Only the filename changes. The URL stays the same, so articles that use this image keep working."
|
||||||
|
And the field "Filename" holds "north-wall" with the mono suffix ".jpg" fixed after it and the help "Letters, numbers, dashes and underscores. The .jpg ending stays."
|
||||||
|
And the buttons read "Cancel" then "Rename"
|
||||||
|
|
||||||
|
Scenario Outline: Rename, validation, nothing is sent
|
||||||
|
Given the Rename dialog is open for "north-wall.jpg"
|
||||||
|
When the user enters "<value>" and submits or leaves the field
|
||||||
|
Then the field shows the error "Enter a filename." with a circle-alert icon and the help text is replaced
|
||||||
|
And no PATCH is sent
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| value |
|
||||||
|
| |
|
||||||
|
| --- |
|
||||||
|
| !!! |
|
||||||
|
|
||||||
|
Scenario: Rename, saving
|
||||||
|
Given the Rename dialog is open for "north-wall.jpg" with "north-wall-01" entered
|
||||||
|
When the user activates "Rename"
|
||||||
|
Then PATCH /v1/media/1 is sent with { "filename": "north-wall-01" }
|
||||||
|
And the field and both buttons are disabled, the confirm button reads "Renaming…" with a loader-circle, and Cancel, Escape and a backdrop click do not close the dialog
|
||||||
|
|
||||||
|
Scenario Outline: Rename, failed, the dialog stays and keeps the text
|
||||||
|
Given a rename is in flight for "north-wall.jpg" with "north-wall-01" entered
|
||||||
|
When PATCH /v1/media/1 <failure>
|
||||||
|
Then the dialog stays open with an error alert "Couldn't rename the image. Your text is still here. Try again in a moment." at the top of its body
|
||||||
|
And "north-wall-01" is still in the field and Cancel and Rename are enabled again
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| never reaches the server |
|
||||||
|
|
||||||
|
Scenario: Rename, done
|
||||||
|
Given a rename is in flight for "north-wall.jpg" with "north-wall-01" entered
|
||||||
|
When PATCH /v1/media/1 resolves 200 with the item, filename "north-wall-01.jpg"
|
||||||
|
Then the dialog closes, the panel title reads "north-wall-01.jpg", the card or row for id 1 reads "north-wall-01.jpg" in place (the list is not reordered), and the URL row is unchanged
|
||||||
|
And a success toast appears: icon circle-check, id "media-renamed-1", title "Image renamed", text `It's now "north-wall-01.jpg". The URL is the same.`
|
||||||
|
|
||||||
|
Scenario: Delete, unused image
|
||||||
|
Given the detail panel is open for "window-frame.jpg" (used in 0)
|
||||||
|
When the user activates "Delete"
|
||||||
|
Then a dialog opens: title "Delete this image?", description `"window-frame.jpg" will be deleted from your library. No article uses it. This can't be undone.`, no body, "Cancel" and a danger "Delete image"
|
||||||
|
|
||||||
|
Scenario: Delete, image in use
|
||||||
|
Given the detail panel is open for "north-wall.jpg" with its 2 articles loaded from GET /v1/media/1/usage
|
||||||
|
When the user activates "Delete"
|
||||||
|
Then a dialog opens: title "Delete an image that's in use?", description `"north-wall.jpg" is used in 2 articles. If you delete it, they will show a broken image. This can't be undone.`
|
||||||
|
And the body lists the two affected articles, each with its title and an "Online" or "Draft" badge, "Cancel" and a danger "Delete image"
|
||||||
|
|
||||||
|
Scenario: Delete, in progress
|
||||||
|
Given the Delete dialog is open for "window-frame.jpg"
|
||||||
|
When the user activates "Delete image"
|
||||||
|
Then DELETE /v1/media/8 is sent
|
||||||
|
And both buttons are disabled, the confirm button reads "Deleting…" with a loader-circle, aria-busy is set, and Cancel, Escape and a backdrop click do not close it
|
||||||
|
|
||||||
|
Scenario Outline: Delete, failed, the image stays
|
||||||
|
Given a delete is in flight for "window-frame.jpg"
|
||||||
|
When DELETE /v1/media/8 <failure>
|
||||||
|
Then the dialog stays open with an error alert "Couldn't delete the image, so it's still there. Try again in a moment." and both buttons enabled again
|
||||||
|
And the "window-frame.jpg" card is untouched behind the dialog
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| never reaches the server |
|
||||||
|
|
||||||
|
Scenario: Delete, done
|
||||||
|
Given a delete is in flight for "window-frame.jpg" (id 8, the 8th card)
|
||||||
|
When DELETE /v1/media/8 resolves 204
|
||||||
|
Then the dialog and the panel close and the card leaves the grid
|
||||||
|
And focus moves to the next card ("stone-wall-detail.jpg"); when the deleted card was the last, focus moves to the page heading
|
||||||
|
And a success toast appears: icon circle-check, id "media-deleted-8", title "Image deleted", text `"window-frame.jpg" is gone from your library.`
|
||||||
|
And the list is then requested again in the background, with no skeleton, to refresh the counts and the Duplicate flags
|
||||||
|
|
||||||
|
Scenario Outline: Image already gone, a 404 on any action removes it
|
||||||
|
Given the detail panel or a dialog is open for "window-frame.jpg"
|
||||||
|
When <trigger> resolves 404
|
||||||
|
Then the panel and any dialog close and the image leaves the list
|
||||||
|
And an info toast appears: icon info, id "media-not-found-8", title "That image no longer exists", text "It was deleted somewhere else, so we removed it from the library."
|
||||||
|
And the list is then requested again in the background to refresh the counts
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| trigger |
|
||||||
|
| DELETE /v1/media/8 |
|
||||||
|
| PATCH /v1/media/8 |
|
||||||
|
| GET /v1/media/8/usage (on open) |
|
||||||
|
|
||||||
|
Scenario Outline: List failed to load
|
||||||
|
Given GET /v1/media/ <failure>
|
||||||
|
When the user navigates to /media
|
||||||
|
Then an error alert replaces the images: icon circle-x, title "Couldn't load your images", text "Check your connection and try again.", and a "Try again" button (icon rotate-cw)
|
||||||
|
And the toolbar stays visible
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then the skeleton cards show and GET /v1/media/ is sent again, and on success the Default state replaces the alert
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure |
|
||||||
|
| resolves with a 500 response |
|
||||||
|
| never reaches the server |
|
||||||
|
|
||||||
|
Scenario: Offline
|
||||||
|
Given the Default state has loaded
|
||||||
|
When navigator.onLine becomes false
|
||||||
|
Then a banner with the wifi-off icon reads "You're offline. You can look through the images that are loaded, but uploading, renaming and deleting need a connection."
|
||||||
|
And the loaded cards stay browsable and the detail panel still opens and "Copy URL" still works
|
||||||
|
And "Upload", "Rename" and "Delete" are disabled
|
||||||
|
When navigator.onLine becomes true
|
||||||
|
Then the banner disappears and "Rename" and "Delete" are enabled again
|
||||||
|
|
||||||
|
Scenario Outline: Session errors are global
|
||||||
|
When any /v1/media call resolves <status>
|
||||||
|
Then the user is sent to <destination> by useApi, and no local media copy is shown
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| status | destination |
|
||||||
|
| 401 | /login?redirect=/media&reason=expired |
|
||||||
|
| 403 | /register/pending (unverified user) |
|
||||||
|
|
||||||
|
Scenario: The sidebar item and the mobile drawer
|
||||||
|
Given the user is signed in and verified
|
||||||
|
When the sidebar renders
|
||||||
|
Then it lists Home, Articles, Media (icon images), Users, Integration, Settings in that order
|
||||||
|
And on /media, "Media" is the active item, on desktop and in the mobile drawer
|
||||||
|
When the user activates "Media"
|
||||||
|
Then the router goes to /media
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
# QA: Media page, part 1 (browse and manage)
|
||||||
|
|
||||||
|
## Scope note (informational)
|
||||||
|
|
||||||
|
SPA only. The media API already exists (slice A), so there is no HTTP-level Go test in this slice
|
||||||
|
and no `test/` file. The Go suite is run only to confirm nothing regressed (`task test`).
|
||||||
|
|
||||||
|
Slice B2 (upload, multi-select, bulk bar, Duplicates content, merge, drag and drop, rate limit) is
|
||||||
|
specified in features/media_upload_selection_duplicates.feature and its .qa.md.
|
||||||
|
|
||||||
|
Toast ids: "media-url-copied-{id}", "media-renamed-{id}", "media-deleted-{id}", "media-not-found-{id}".
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `useApi`'s `request` (or the global fetch it wraps) per case for `GET /v1/media/`,
|
||||||
|
`GET /v1/media/{id}/usage`, `GET /v1/media/?hash=`, `PATCH /v1/media/{id}` and
|
||||||
|
`DELETE /v1/media/{id}`, plus `navigator.clipboard.writeText` and `navigator.onLine`. No real
|
||||||
|
backend. Mount MediaPage inside DashboardShell with a verified session and a test router at
|
||||||
|
/media. Sample data is the 12-image fixture in the .feature Background (same ids, filenames,
|
||||||
|
sizes, dimensions, used_in, uploaders and dates as the board's script), with counts { all: 12,
|
||||||
|
unused: 2, duplicates: 2 }. Use fake timers for the 150 ms skeleton delay and the 120 ms search
|
||||||
|
debounce.
|
||||||
|
|
||||||
|
Logic and copy:
|
||||||
|
|
||||||
|
1. **Formatting** (pure functions) - size: 8192 bytes to "8 KB", 880640 to "860 KB", 4089446 to
|
||||||
|
"3.9 MB"; dimensions "4032 × 3024"; null width and height to "Vector"; date "12 Sep 2026"
|
||||||
|
from `created_at`; type from content_type (image/jpeg "JPEG", image/png "PNG", image/webp
|
||||||
|
"WEBP", image/svg+xml "SVG"); accessible name for used_in 2, 1 and 0 ("used in 2 articles",
|
||||||
|
"used in 1 article", "unused").
|
||||||
|
2. **Query string mapping** - Examples-driven from the .feature: each URL produces the exact
|
||||||
|
request query and control state; unknown values fall back to defaults;
|
||||||
|
changing a control rewrites the URL and drops default values.
|
||||||
|
3. **Default** - 12 cards in fixture order, tabs "All 12" "Unused 2" "Duplicates 2", the
|
||||||
|
Duplicates badge only when duplicates > 0, "Select all" and "12 images" in the Select all row,
|
||||||
|
breadcrumb "Media".
|
||||||
|
4. **Badges and accessible names** - the 5 Examples rows (badges and aria-label / accessible name).
|
||||||
|
5. **Grid, few images** - 3 items; tabs "All 3" "Unused 1" "Duplicates" without a badge.
|
||||||
|
6. **List view** - desktop: table with the 7 column headers and 12 rows, the Used in cell
|
||||||
|
underlined count or Unused badge; mobile: card list with "3.9 MB · 4032 × 3024 · JPEG" and
|
||||||
|
"Marta Alves · 12 Sep 2026"; clicking the Used in count opens the panel.
|
||||||
|
7. **Duplicates tab** - covered by the B2 spec.
|
||||||
|
8. **Loading** - unresolved GET: nothing before 150 ms; after 150 ms the skeleton (10 cards,
|
||||||
|
6 below md) and aria-busy; resolve; cards replace it; same on retry and on search, tab and
|
||||||
|
sort change, in list view too.
|
||||||
|
9. **Empty library** - zero items and counts 0 with no q: toolbar and tabs absent, copy exact,
|
||||||
|
"Upload an image" enabled, the footnote "PNG, JPEG, WEBP, SVG · max 10 MB each".
|
||||||
|
10. **No results** - unused + "wall": title `No images match "wall"`, text "Nothing matches in
|
||||||
|
Unused. Check the spelling, or clear the filters."; "Clear filters" resets q and filter and
|
||||||
|
restores the cards.
|
||||||
|
11. **Keyboard** - each card is a button; Enter opens the panel; Space toggles selection and opens nothing; arrow keys
|
||||||
|
move focus (left, right, up, down by one row, stopping at the edges); Escape closes the panel
|
||||||
|
and focus returns to the card.
|
||||||
|
12. **Detail panel, in use** - usage called once for id 1, title, actions, metadata rows, article
|
||||||
|
rows with links to /article/{id}/edit and Online / Draft badges, footnote text.
|
||||||
|
13. **Detail panel, unused** - no usage request; "Not used in any article" and the safe-to-delete
|
||||||
|
text.
|
||||||
|
14. **Detail panel, duplicate** - hash query used; alert title "Identical to 2 other images" and
|
||||||
|
"floorboards-copy.jpg and IMG_2208.jpg have the same content." (the image itself is excluded);
|
||||||
|
the "Review duplicates" action is enabled and selects the Duplicates tab.
|
||||||
|
15. **Copy URL** - clipboard called with `{origin}{url}`; toast id "media-url-copied-1", icon
|
||||||
|
circle-check, title "URL copied", text "Paste it wherever you need the image address.".
|
||||||
|
16. **Rename dialog** - title, description, field "north-wall" with ".jpg" suffix, help text,
|
||||||
|
Cancel then Rename.
|
||||||
|
17. **Rename validation** - "", "---", "!!!": error "Enter a filename." on submit and on blur,
|
||||||
|
no PATCH.
|
||||||
|
18. **Rename saving** - PATCH /v1/media/1 body { filename: "north-wall-01" } (no extension); the
|
||||||
|
field and buttons disabled, "Renaming…", dialog not dismissible by Escape or backdrop.
|
||||||
|
19. **Rename failed** - 500 and network rejection: alert copy exact, text kept, buttons enabled.
|
||||||
|
20. **Rename done** - 200: panel title, card and row updated in place, order unchanged; toast id
|
||||||
|
"media-renamed-1", title "Image renamed", text `It's now "north-wall-01.jpg". The URL is the same.`
|
||||||
|
21. **Delete, unused** and **Delete, in use** - dialog titles, descriptions with the exact quotes
|
||||||
|
and counts, the article list with badges only in the in-use variant, "Delete image" danger.
|
||||||
|
22. **Delete in progress** - DELETE /v1/media/8; buttons disabled; "Deleting…"; not dismissible.
|
||||||
|
23. **Delete failed** - 500 and network rejection: alert copy exact, item untouched.
|
||||||
|
24. **Delete done** - 204: dialog and panel closed, card removed, focus on the next card (heading
|
||||||
|
when last), toast id "media-deleted-8", title "Image deleted", text `"window-frame.jpg" is gone from your library.`; a background list refresh
|
||||||
|
without skeleton follows and updates the counts.
|
||||||
|
25. **404 Examples-driven** - DELETE, PATCH, usage: everything closes, the item is removed,
|
||||||
|
toast id "media-not-found-8", icon info, title "That image no longer exists", text "It was
|
||||||
|
deleted somewhere else, so we removed it from the library.".
|
||||||
|
26. **List failed** - 500 and network rejection: alert copy exact, toolbar visible; "Try again"
|
||||||
|
re-requests, shows skeleton, then the list.
|
||||||
|
27. **Offline** - onLine false: banner copy exact, Upload, Rename and Delete disabled, Copy URL
|
||||||
|
and panel still work; back online restores them.
|
||||||
|
28. **401 / 403** - handled by useApi (redirect target strings asserted); no local media copy.
|
||||||
|
29. **Sidebar and drawer** - Media between Articles and Users with the images icon, active on
|
||||||
|
/media, in the desktop sidebar and the mobile drawer; the route has meta.auth "verified" and
|
||||||
|
meta.title "Media" (routerGuard spec extended).
|
||||||
|
30. **Header** - title, subtitle, and the Upload button (also the mobile pinned 48 px variant).
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- media`, desktop and mobile, light and dark)
|
||||||
|
|
||||||
|
Reference: docs/design/screens/media.md and `source/MediaFrame.dc.html` (group "Media" in the
|
||||||
|
back-office board). Add each setup to `web/visual/states.ts` first, mocking `/v1/media/`,
|
||||||
|
`/v1/media/{id}/usage` and `/v1/media/?hash=` from the board's own script: the 12 images (ids,
|
||||||
|
filenames, sizes, dimensions, used in, uploaders, absolute dates), and the article rows for
|
||||||
|
the panels ("How we price a bathroom renovation" Online, "Winter checklist for timber windows"
|
||||||
|
Draft for north-wall.jpg). None of the B1 states depends on the current date (all dates are
|
||||||
|
absolute), so none is `skip: 'clock-sensitive'`.
|
||||||
|
|
||||||
|
The board draws its thumbnails as placeholder tiles (a striped tone fill with an image
|
||||||
|
icon, the RenewCMS mark on the SVG, a checkerboard behind PNG and SVG), not photographs. The
|
||||||
|
mocked image URLs must render the same way, or the 10 % gate fails for a reason unrelated to
|
||||||
|
the code.
|
||||||
|
|
||||||
|
Harness note: the B2 states now have setups and no longer carry `skip: 'pending'`.
|
||||||
|
|
||||||
|
Setups for this slice (name in screens/media.md, then what must be drawn):
|
||||||
|
|
||||||
|
- [ ] Grid, many images: 12 cards, tabs 12 / 2 / 2, Select all row showing "12 images" only.
|
||||||
|
- [ ] Grid, few images: ids 1, 4, 8; checkerboard behind the SVG.
|
||||||
|
- [ ] List view: table at desktop, card list at mobile.
|
||||||
|
- [ ] Loading: skeleton cards (10 desktop, 6 mobile), toolbar visible.
|
||||||
|
- [ ] Empty library, first run: no toolbar, "No images yet" panel and the footnote.
|
||||||
|
- [ ] No results: unused + "wall".
|
||||||
|
- [ ] Hover, focus and keyboard: hover on id 2, focus ring on id 3 (the checkbox reveal is covered by B2).
|
||||||
|
- [ ] Detail panel: in use (id 1), unused (id 8), duplicate (id 12).
|
||||||
|
- [ ] Copy URL: id 1 panel plus the toast.
|
||||||
|
- [ ] Rename: dialog, saving, validation, failed, done (id 1, "north-wall-01").
|
||||||
|
- [ ] Delete: unused (id 8), in use (id 1), in progress (id 1), failed (id 8), done (grid without
|
||||||
|
id 8 plus toast).
|
||||||
|
- [ ] Image already gone (404): grid without id 8 plus the info toast.
|
||||||
|
- [ ] List failed to load: alert with "Try again".
|
||||||
|
- [ ] Offline: banner and disabled Upload.
|
||||||
|
|
||||||
|
The B2 states are listed in features/media_upload_selection_duplicates.qa.md.
|
||||||
|
|
||||||
|
Manual checks screenshots cannot cover:
|
||||||
|
|
||||||
|
- [ ] Keyboard and focus order: Tab visits the search, tabs, sort, toggle, then one stop per card;
|
||||||
|
arrow keys move across the grid; Enter opens the panel; focus is trapped in the panel and in
|
||||||
|
dialogs, starts on Cancel in dialogs, and returns to the card on close; after a delete focus
|
||||||
|
lands on the next card.
|
||||||
|
- [ ] Hover, motion and reduced motion: card hover shadow, skeleton pulse, panel and dialog
|
||||||
|
transitions stop under reduced motion.
|
||||||
|
- [ ] Screen reader: the card's accessible name reads correctly.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- **Real round trips against a running server** (`task dev`): list with real counts, sorting,
|
||||||
|
search, usage, rename (extension kept, URL unchanged), delete, a concurrent 404. Vitest only
|
||||||
|
mocks `useApi`.
|
||||||
|
- **Real image rendering**: the thumbnails and previews load from the real `url` and the
|
||||||
|
checkerboard shows behind real transparent PNG and SVG files.
|
||||||
|
- **Real clipboard write** in a real browser.
|
||||||
|
- **Toast placement and stacking** on a live app.
|
||||||
|
- **Counts after a delete** against a live server: the background refresh gives the true Unused
|
||||||
|
and Duplicates counts.
|
||||||
|
- **A library above 100 images**: B1 requests `limit=100` and ignores `next_cursor`, so only the
|
||||||
|
first 100 show.
|
||||||
@@ -0,0 +1,391 @@
|
|||||||
|
Feature: The media library holds every uploaded image as a library-level asset
|
||||||
|
|
||||||
|
As a verified RenewCMS user
|
||||||
|
I want to upload, browse, rename, delete, merge and inspect images that belong to the
|
||||||
|
library and not to any article
|
||||||
|
So that one image can be used in many articles, deleting an article never deletes an image,
|
||||||
|
and duplicates can be merged without leaving a broken image behind
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given internal/domain/image.Image carries ID, Path, Filename, Size, ContentType, Width,
|
||||||
|
Height (0 for SVG), SHA256, UploadedByID, CreatedAt and UpdatedAt, and no article id
|
||||||
|
And image.ImageInput gains Width, Height, SHA256 and UploadedByID
|
||||||
|
And internal/domain/image defines the sentinels ErrImageUnreadable, ErrInvalidFilename,
|
||||||
|
ErrMergeCopyMissing and ErrMergeHashMismatch, plus the existing ErrImageNotFound,
|
||||||
|
ErrImageTypeNotAllowed and ErrImageTooLarge, all asserted with errors.Is
|
||||||
|
And image.Repository exposes Create, Get, Delete, List(query), FindByHash, Rename,
|
||||||
|
ListByHash groups and Counts, and article.Repository exposes
|
||||||
|
FindByBodyContaining(filename) and the existing UpdateBody, and no longer AddImage
|
||||||
|
And CreateImageUseCase reads the bytes fully, rejects a type outside image/png, image/jpeg,
|
||||||
|
image/webp and image/svg+xml with ErrImageTypeNotAllowed, rejects more than 10485760
|
||||||
|
bytes actually read with ErrImageTooLarge, computes SHA-256 hex and, for raster images,
|
||||||
|
width and height from the bytes, and rejects bytes that cannot be decoded (or an SVG
|
||||||
|
without an svg root) with ErrImageUnreadable, all before image.Repository.Create is called
|
||||||
|
And an image's "used in" is the count of articles, online or draft, whose body contains
|
||||||
|
the image's url, read from article bodies each time
|
||||||
|
And /v1/media is mounted in api/router.go behind jwtauth.Verifier, jwtauth.Authenticator,
|
||||||
|
middleware.RequireCurrentToken and middleware.RequireVerifiedUser
|
||||||
|
And every media item is JSON with snake_case fields:
|
||||||
|
{"id","filename","url","size","content_type","width","height","sha256","uploaded_by",
|
||||||
|
"created_at","used_in","duplicate"}, where url is the stored path
|
||||||
|
"/static/uploadedImages/<uuid><ext>", width and height are null for SVG, uploaded_by is
|
||||||
|
the uploader's display name (username when empty, "" when unknown) and duplicate is true
|
||||||
|
when another image has the same sha256
|
||||||
|
And request bodies are validated with validate tags and validator.Validate.Struct, and
|
||||||
|
errors are plain text from http.Error
|
||||||
|
|
||||||
|
Scenario Outline: Every media route refuses callers that are not logged in and verified
|
||||||
|
When the client sends <method> <path> <credentials>
|
||||||
|
Then the response status is <status>
|
||||||
|
And no image or article is read or changed
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | path | credentials | status |
|
||||||
|
| GET | /v1/media/ | no cookie | 401 |
|
||||||
|
| POST | /v1/media/ | no cookie | 401 |
|
||||||
|
| PATCH | /v1/media/1 | no cookie | 401 |
|
||||||
|
| DELETE | /v1/media/1 | no cookie | 401 |
|
||||||
|
| POST | /v1/media/merge | no cookie | 401 |
|
||||||
|
| GET | /v1/media/1/usage | no cookie | 401 |
|
||||||
|
| GET | /v1/media/ | a stale token_version cookie | 401 |
|
||||||
|
| GET | /v1/media/ | cookie of an unverified user | 403 |
|
||||||
|
| DELETE | /v1/media/1 | cookie of an unverified user | 403 |
|
||||||
|
|
||||||
|
Rule: Listing
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given user 1 has display name "Inès Duarte" and user 2 has no display name and username "marta"
|
||||||
|
And the library holds, uploaded in this order (oldest first):
|
||||||
|
| id | filename | size | content_type | width | height | sha256 | uploaded by |
|
||||||
|
| 1 | north-wall.jpg | 4089446 | image/jpeg | 3600 | 2400 | A | 1 |
|
||||||
|
| 2 | floorboards.jpg | 2516582 | image/jpeg | 3600 | 2400 | B | 1 |
|
||||||
|
| 3 | floorboards-copy.jpg | 2516582 | image/jpeg | 3600 | 2400 | B | 2 |
|
||||||
|
| 4 | window-frame.jpg | 812345 | image/jpeg | 1200 | 800 | C | 2 |
|
||||||
|
| 5 | logo.svg | 1204 | image/svg+xml | 0 | 0 | D | 1 |
|
||||||
|
And article 1 "Kitchen Renovation" is online and its body contains the urls of images 1 and 2
|
||||||
|
And article 2 "Backyard Notes" is a draft and its body contains the url of image 1
|
||||||
|
And article 3 "Empty" has a body with no image url
|
||||||
|
|
||||||
|
Scenario: The default list is newest first with used_in, duplicate and tab counts
|
||||||
|
When the client sends GET /v1/media/ with a valid cookie
|
||||||
|
Then the response status is 200
|
||||||
|
And the "items" ids are 5, 4, 3, 2, 1 in that order
|
||||||
|
And item 1 has used_in 2, duplicate false and uploaded_by "Inès Duarte"
|
||||||
|
And items 2 and 3 have duplicate true, and item 3 has uploaded_by "marta"
|
||||||
|
And item 5 has width null, height null and used_in 0
|
||||||
|
And "next_cursor" is null
|
||||||
|
And "counts" is {"all": 5, "unused": 3, "duplicates": 1}
|
||||||
|
|
||||||
|
Scenario: An empty library answers an empty list, not null
|
||||||
|
Given the library holds no image
|
||||||
|
When the client sends GET /v1/media/ with a valid cookie
|
||||||
|
Then the response status is 200
|
||||||
|
And "items" is an empty array and "counts" is {"all": 0, "unused": 0, "duplicates": 0}
|
||||||
|
|
||||||
|
Scenario Outline: sort orders the list
|
||||||
|
When the client sends GET /v1/media/?sort=<sort> with a valid cookie
|
||||||
|
Then the "items" ids are <ids> in that order
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| sort | ids |
|
||||||
|
| newest | 5, 4, 3, 2, 1 |
|
||||||
|
| oldest | 1, 2, 3, 4, 5 |
|
||||||
|
| name | 2, 3, 5, 1, 4 |
|
||||||
|
| largest | 1, 2, 3, 4, 5 |
|
||||||
|
|
||||||
|
Scenario Outline: filter narrows the list and the counts stay library-wide
|
||||||
|
When the client sends GET /v1/media/?filter=<filter> with a valid cookie
|
||||||
|
Then the "items" ids, as a set, are <ids>
|
||||||
|
And "counts" is still {"all": 5, "unused": 3, "duplicates": 1}
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| filter | ids |
|
||||||
|
| all | 1,2,3,4,5 |
|
||||||
|
| unused | 3, 4, 5 |
|
||||||
|
| duplicates | 2, 3 |
|
||||||
|
|
||||||
|
Scenario Outline: q matches the filename case-insensitively
|
||||||
|
When the client sends GET /v1/media/?q=<q> with a valid cookie
|
||||||
|
Then the "items" ids are <ids> in that order
|
||||||
|
And "counts" is still {"all": 5, "unused": 3, "duplicates": 1}
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| q | ids |
|
||||||
|
| FLOORBOARD | 3, 2 |
|
||||||
|
| wall | 1 |
|
||||||
|
| zzz | |
|
||||||
|
|
||||||
|
Scenario: q, filter and sort combine
|
||||||
|
When the client sends GET /v1/media/?q=floorboards&filter=unused&sort=oldest with a valid cookie
|
||||||
|
Then the "items" ids are 3
|
||||||
|
|
||||||
|
Scenario: hash returns only the images with that content
|
||||||
|
When the client sends GET /v1/media/?hash=<sha256 of image 2's bytes> with a valid cookie
|
||||||
|
Then the "items" ids, as a set, are 2, 3
|
||||||
|
|
||||||
|
Scenario: hash of unknown content returns no item
|
||||||
|
When the client sends GET /v1/media/?hash=<64 hex zeros> with a valid cookie
|
||||||
|
Then the response status is 200 and "items" is empty
|
||||||
|
|
||||||
|
Scenario: limit and cursor page through the list
|
||||||
|
When the client sends GET /v1/media/?limit=2 with a valid cookie
|
||||||
|
Then the "items" ids are 5, 4 and "next_cursor" is a non-empty string
|
||||||
|
When the client sends GET /v1/media/?limit=2&cursor=<that next_cursor>
|
||||||
|
Then the "items" ids are 3, 2 and "next_cursor" is a non-empty string
|
||||||
|
When the client sends GET /v1/media/?limit=2&cursor=<that next_cursor>
|
||||||
|
Then the "items" ids are 1 and "next_cursor" is null
|
||||||
|
|
||||||
|
Scenario Outline: A malformed query answers 400
|
||||||
|
When the client sends GET /v1/media/?<query> with a valid cookie
|
||||||
|
Then the response status is 400
|
||||||
|
And the response body is the text apperr.MediaQueryErrorMessage
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| query |
|
||||||
|
| filter=bogus |
|
||||||
|
| sort=bogus |
|
||||||
|
| limit=0 |
|
||||||
|
| limit=101 |
|
||||||
|
| limit=abc |
|
||||||
|
| cursor=%%% |
|
||||||
|
| hash=notahash |
|
||||||
|
|
||||||
|
Rule: Uploading
|
||||||
|
|
||||||
|
Scenario Outline: An allowed image is always stored, with its metadata and hash
|
||||||
|
Given a valid cookie for user 1 whose display name is "Inès Duarte"
|
||||||
|
When the client sends POST /v1/media/ with multipart field "file" named <name>, content type <content_type> and real <content_type> bytes
|
||||||
|
Then the response status is 201
|
||||||
|
And the body is a media item whose filename is <name>, content_type is <content_type>, size is the byte count, width and height are <width> and <height>, sha256 is the SHA-256 hex of the bytes, uploaded_by is "Inès Duarte", used_in is 0 and duplicate is false
|
||||||
|
And the item's url matches "/static/uploadedImages/<uuid><ext>"
|
||||||
|
And the image repository holds one new image with UploadedByID 1
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| name | content_type | width | height |
|
||||||
|
| north-wall.png | image/png | 3 | 2 |
|
||||||
|
| IMG_2208.jpg | image/jpeg | 3 | 2 |
|
||||||
|
| hero.webp | image/webp | 1 | 1 |
|
||||||
|
| logo.svg | image/svg+xml | null | null |
|
||||||
|
|
||||||
|
Scenario: Uploading the same bytes twice stores both and marks both as duplicates
|
||||||
|
Given the library holds image 1 with the same bytes
|
||||||
|
When the client sends POST /v1/media/ with those bytes named "north-wall-again.png"
|
||||||
|
Then the response status is 201 and the item has duplicate true
|
||||||
|
And the library now holds two images with the same sha256 and different urls
|
||||||
|
And "counts".duplicates is 1 when listed
|
||||||
|
|
||||||
|
Scenario: A filename without extension gets the canonical one, a path is stripped
|
||||||
|
When the client uploads real PNG bytes named "C:\\photos\\north wall" with content type "image/png"
|
||||||
|
Then the item filename is "north wall.png"
|
||||||
|
|
||||||
|
Scenario: A file exactly at 10485760 bytes is accepted, one byte more is 413
|
||||||
|
When the client uploads a valid PNG padded to 10485760 bytes
|
||||||
|
Then the response status is 201
|
||||||
|
When the client uploads a valid PNG padded to 10485761 bytes
|
||||||
|
Then the response status is 413
|
||||||
|
And the response body is the text "the file exceeds the maximum upload size"
|
||||||
|
And the image repository's Create was called once in total
|
||||||
|
|
||||||
|
Scenario: A disallowed content type is 415
|
||||||
|
When the client uploads "notes.pdf" with content type "application/pdf"
|
||||||
|
Then the response status is 415
|
||||||
|
And the response body is the text "the file must be a PNG, JPEG, WEBP, or SVG image"
|
||||||
|
And the image repository's Create is never called
|
||||||
|
|
||||||
|
Scenario Outline: Bytes that cannot be read as the declared type are 400
|
||||||
|
When the client uploads <name> with content type <content_type> and the bytes "not an image"
|
||||||
|
Then the response status is 400
|
||||||
|
And the response body is the text "the image could not be read"
|
||||||
|
And the image repository's Create is never called
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| name | content_type |
|
||||||
|
| broken.png | image/png |
|
||||||
|
| broken.jpg | image/jpeg |
|
||||||
|
| broken.webp | image/webp |
|
||||||
|
| broken.svg | image/svg+xml |
|
||||||
|
|
||||||
|
Scenario: A request without the "file" part is 400
|
||||||
|
When the client sends POST /v1/media/ with a multipart body that has no "file" field
|
||||||
|
Then the response status is 400
|
||||||
|
And the image repository's Create is never called
|
||||||
|
|
||||||
|
Scenario: A repository failure is a generic 500
|
||||||
|
Given the image repository's next Create fails
|
||||||
|
When the client uploads a valid PNG
|
||||||
|
Then the response status is 500 and the body is "Internal server error"
|
||||||
|
|
||||||
|
Rule: Renaming
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given image 1 is "north-wall.jpg" with url "/static/uploadedImages/aaa.jpeg" and article 1 body contains that url
|
||||||
|
|
||||||
|
Scenario: Rename changes the display name, keeps the extension and the url
|
||||||
|
When the client sends PATCH /v1/media/1 with {"filename": "north-wall-01"}
|
||||||
|
Then the response status is 200
|
||||||
|
And the body is the media item with filename "north-wall-01.jpg" and url "/static/uploadedImages/aaa.jpeg"
|
||||||
|
And article 1's body is unchanged
|
||||||
|
And a following GET /v1/media/?q=north-wall-01 returns image 1
|
||||||
|
|
||||||
|
Scenario: Surrounding whitespace is trimmed and unicode letters are allowed
|
||||||
|
When the client sends PATCH /v1/media/1 with {"filename": " Été_2026-a "}
|
||||||
|
Then the response status is 200 and the filename is "Été_2026-a.jpg"
|
||||||
|
|
||||||
|
Scenario Outline: An invalid new name is 400 and nothing changes
|
||||||
|
When the client sends PATCH /v1/media/1 with <body>
|
||||||
|
Then the response status is 400
|
||||||
|
And the response body is the text "Enter a filename." for every row except "not json"
|
||||||
|
And the image's filename is still "north-wall.jpg"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| body |
|
||||||
|
| {"filename": ""} |
|
||||||
|
| {"filename": " "} |
|
||||||
|
| {"filename": "***"} |
|
||||||
|
| {"filename": "a.b"} |
|
||||||
|
| {"filename": "a b"} |
|
||||||
|
| {"filename": "<101 letters>"} |
|
||||||
|
| {} |
|
||||||
|
| not json |
|
||||||
|
|
||||||
|
Scenario: Renaming an unknown image is 404
|
||||||
|
When the client sends PATCH /v1/media/9999 with {"filename": "x"}
|
||||||
|
Then the response status is 404 and the body is "Image not found"
|
||||||
|
|
||||||
|
Scenario: A malformed id is 400
|
||||||
|
When the client sends PATCH /v1/media/abc with {"filename": "x"}
|
||||||
|
Then the response status is 400 and the body is apperr.IdUint32ErrorMessage
|
||||||
|
|
||||||
|
Rule: Deleting
|
||||||
|
|
||||||
|
Scenario: An image in use can be deleted and article bodies are left alone
|
||||||
|
Given image 1 is used in article 1's body
|
||||||
|
When the client sends DELETE /v1/media/1 with a valid cookie
|
||||||
|
Then the response status is 204 and the body is empty
|
||||||
|
And image 1 is gone from the repository and its file from UPLOAD_DIR
|
||||||
|
And article 1's body is byte-for-byte unchanged
|
||||||
|
|
||||||
|
Scenario: A file already missing from disk still deletes the row
|
||||||
|
Given image 4's file is not in UPLOAD_DIR
|
||||||
|
When the client sends DELETE /v1/media/4
|
||||||
|
Then the response status is 204 and image 4 is gone from the repository
|
||||||
|
|
||||||
|
Scenario: Deleting an unknown image is 404
|
||||||
|
When the client sends DELETE /v1/media/9999
|
||||||
|
Then the response status is 404 and the body is "Image not found"
|
||||||
|
|
||||||
|
Scenario: A malformed id is 400
|
||||||
|
When the client sends DELETE /v1/media/abc
|
||||||
|
Then the response status is 400 and the body is apperr.IdUint32ErrorMessage
|
||||||
|
|
||||||
|
Scenario: A repository failure is a generic 500 and the image stays
|
||||||
|
Given the image repository's Delete fails
|
||||||
|
When the client sends DELETE /v1/media/1
|
||||||
|
Then the response status is 500 and image 1 is still in the repository
|
||||||
|
|
||||||
|
Rule: Usage
|
||||||
|
|
||||||
|
Scenario: Usage lists the articles whose body contains the url
|
||||||
|
Given article 1 "Kitchen Renovation" is online and article 2 "Backyard Notes" is a draft, both containing image 1's url, and article 3 does not
|
||||||
|
When the client sends GET /v1/media/1/usage with a valid cookie
|
||||||
|
Then the response status is 200
|
||||||
|
And the body is [{"id": 1, "title": "Kitchen Renovation", "published": true}, {"id": 2, "title": "Backyard Notes", "published": false}]
|
||||||
|
|
||||||
|
Scenario: An unused image has an empty array, not null
|
||||||
|
When the client sends GET /v1/media/4/usage
|
||||||
|
Then the response status is 200 and the body is []
|
||||||
|
|
||||||
|
Scenario: An absolute url still counts as used
|
||||||
|
Given article 3's body contains "https://cms.example.com/static/uploadedImages/aaa.jpeg" for image 1
|
||||||
|
Then GET /v1/media/1/usage includes article 3
|
||||||
|
|
||||||
|
Scenario Outline: Unknown or malformed ids
|
||||||
|
When the client sends GET /v1/media/<id>/usage
|
||||||
|
Then the response status is <status> and the body is <body>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| id | status | body |
|
||||||
|
| 9999 | 404 | Image not found |
|
||||||
|
| abc | 400 | apperr.IdUint32ErrorMessage |
|
||||||
|
|
||||||
|
Rule: Merging
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given images 2, 3 and 6 share sha256 B, image 1 has sha256 A
|
||||||
|
And article 1 body contains the urls of images 2 and 3, article 2 body contains image 3's url twice, article 3 body contains image 2's url only, and article 4 has none of them
|
||||||
|
|
||||||
|
Scenario: Merge switches bodies to the kept url and deletes the copies
|
||||||
|
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3, 6]}
|
||||||
|
Then the response status is 200
|
||||||
|
And the body is {"articles_updated": 2, "merged": 2}
|
||||||
|
And article 1's body has image 3's url replaced by image 2's url
|
||||||
|
And article 2's body has both occurrences of image 3's url replaced by image 2's url
|
||||||
|
And article 3 and article 4 are unchanged
|
||||||
|
And images 3 and 6 are gone from the repository and from UPLOAD_DIR, and image 2 remains
|
||||||
|
|
||||||
|
Scenario: Merging copies that no article uses updates zero articles
|
||||||
|
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [6]}
|
||||||
|
Then the response status is 200 and the body is {"articles_updated": 0, "merged": 1}
|
||||||
|
|
||||||
|
Scenario: A copy that is gone answers 409 and changes nothing
|
||||||
|
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3, 9999]}
|
||||||
|
Then the response status is 409 and the body is apperr.MediaMergeConflictErrorMessage
|
||||||
|
And no article body changed and images 2 and 3 still exist
|
||||||
|
|
||||||
|
Scenario: A copy that does not share the hash answers 409 and changes nothing
|
||||||
|
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3, 1]}
|
||||||
|
Then the response status is 409
|
||||||
|
And no article body changed and images 1, 2 and 3 still exist
|
||||||
|
|
||||||
|
Scenario: A kept image that is gone answers 404
|
||||||
|
When the client sends POST /v1/media/merge with {"keep_id": 9999, "merge_ids": [3]}
|
||||||
|
Then the response status is 404 and the body is "Image not found"
|
||||||
|
And nothing changed
|
||||||
|
|
||||||
|
Scenario Outline: An invalid merge request is 400 and nothing changes
|
||||||
|
When the client sends POST /v1/media/merge with <body>
|
||||||
|
Then the response status is 400 and the body is apperr.MediaMergeRequestErrorMessage
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| body |
|
||||||
|
| {"keep_id": 2, "merge_ids": []} |
|
||||||
|
| {"keep_id": 2} |
|
||||||
|
| {"merge_ids": [3]} |
|
||||||
|
| {"keep_id": 2, "merge_ids": [2, 3]} |
|
||||||
|
| {"keep_id": 2, "merge_ids": [3, 3]} |
|
||||||
|
| {"keep_id": 0, "merge_ids": [3]} |
|
||||||
|
| not json |
|
||||||
|
|
||||||
|
Scenario: A failure rewriting a body restores the bodies already rewritten
|
||||||
|
Given the article repository's UpdateBody fails for article 2
|
||||||
|
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3]}
|
||||||
|
Then the response status is 500
|
||||||
|
And article 1's body is back to its original text, article 2 is unchanged
|
||||||
|
And images 2 and 3 still exist
|
||||||
|
|
||||||
|
Scenario: A failure deleting a copy after the rewrite is 500 and the bodies stay switched
|
||||||
|
Given the image repository's Delete fails for image 3
|
||||||
|
When the client sends POST /v1/media/merge with {"keep_id": 2, "merge_ids": [3]}
|
||||||
|
Then the response status is 500
|
||||||
|
And article 1's and article 2's bodies use image 2's url and image 3 still exists
|
||||||
|
|
||||||
|
@manual
|
||||||
|
Rule: Startup backfill and migration (persistence, verified by hand, see the qa.md)
|
||||||
|
|
||||||
|
Scenario: Existing rows get metadata and hash from the files on disk
|
||||||
|
Given the images table has rows created before this slice, with a path and no filename, size, content_type, width, height or sha256, and their files are in UPLOAD_DIR
|
||||||
|
When the server boots
|
||||||
|
Then each row gets filename equal to the stored file name, size, content_type, width and height (0 for SVG) and sha256 read from its file, and UploadedByID stays 0
|
||||||
|
And the old article_id column and the article_images table are kept and not written
|
||||||
|
|
||||||
|
Scenario: A row whose file is missing does not stop the boot
|
||||||
|
Given a row whose file is not in UPLOAD_DIR
|
||||||
|
When the server boots
|
||||||
|
Then the boot completes, the row is left without metadata, and the server serves requests
|
||||||
|
|
||||||
|
Scenario: The backfill is idempotent
|
||||||
|
When the server boots a second time
|
||||||
|
Then no row is changed again
|
||||||
|
|
||||||
|
Scenario: A row without metadata still lists
|
||||||
|
Then GET /v1/media/ returns it with size 0, width null, height null, sha256 "" and duplicate false
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
# QA procedure: media_library
|
||||||
|
|
||||||
|
Package: `test` (black-box). New file `test/media_library_http_test.go`. Fake type names must be unique in the package.
|
||||||
|
|
||||||
|
## Setup shared by every case
|
||||||
|
1. Call `validator.InitValidator()` once.
|
||||||
|
2. Rewrite `mockImageRepo` (`test/image_test.go`) to the new `image.Repository`: Create (stores the metadata from the ImageInput and derives a `/static/uploadedImages/<n>.<ext>` path), Get, Delete (records calls, honours `failDeleteFor`), List(query), FindByHash, Rename, ListByHash groups, Counts. Add fields for seeding `Filename`, `Size`, `ContentType`, `Width`, `Height`, `SHA256`, `UploadedByID`, `CreatedAt`.
|
||||||
|
3. Extend `mockArticleRepo` (`test/article_test.go`) with `FindByBodyContaining(filename)` (substring over `Body`) and a per-id failure switch for `UpdateBody`. Remove `AddImage` and the article `Images` field from the fake and from every test that uses them.
|
||||||
|
4. Use the existing user fake so `uploaded_by` resolves: user 1 display name "Inès Duarte", user 2 username "marta" with empty display name.
|
||||||
|
5. Wire the real use cases over the fakes: create, list, rename, delete, merge and usage media use cases, `NewCreateImageUseCase(imageRepo)`, `NewGetUserUseCase(userRepo)`. Build `media.NewHandler(...)` (`api/handlers/media`).
|
||||||
|
6. Build `jwtauth.New("HS256", []byte("test-secret"), nil)`. Mount on a fresh `chi.NewRouter()` mirroring `api/router.go`: `jwtauth.Verifier` at the top, then in the media group `Authenticator`, `RequireCurrentToken(getUser)`, `RequireVerifiedUser(getUser)`, with the six routes under `/v1/media`.
|
||||||
|
7. Mint cookies via `token.Encode(map[string]any{"user_id": uint32(n), ...})` as in the other HTTP tests. Build a stale-token cookie with a `token_version` lower than the user's, and use an unverified user for the 403 case.
|
||||||
|
8. Build multipart bodies with `mime/multipart.Writer`, using `CreatePart` with an explicit part `Content-Type` header. Generate real bytes in the test:
|
||||||
|
- PNG (3x2) with `image/png`;
|
||||||
|
- JPEG (3x2) with `image/jpeg`;
|
||||||
|
- a tiny valid WEBP fixture (1x1) as a byte constant;
|
||||||
|
- SVG `<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>`.
|
||||||
|
|
||||||
|
Compute expected sha256 in the test with `crypto/sha256`. For size limits, pad valid PNG bytes to 10485760 and 10485761 bytes.
|
||||||
|
9. Seed the Listing background exactly as in the feature (5 images, 3 articles, 2 users), with `created_at` strictly increasing by id.
|
||||||
|
|
||||||
|
## HTTP checks
|
||||||
|
10. Auth table: each method+path from the outline with no cookie -> 401, stale cookie -> 401 with `apperr.UnauthorizedErrorMessage`, unverified cookie -> 403 with `apperr.VerificationRequiredErrorMessage`. Assert no fake method beyond the middleware's user lookup was called.
|
||||||
|
11. List: decode `{items, next_cursor, counts}`. Assert each row of the sort, filter, `q` and `hash` tables, the combined query, the paging walk (limit 2 across three pages ending in `next_cursor == null`), the empty library (`items` is `[]` in the raw JSON, not `null`), SVG `width`/`height` are JSON `null` (assert on the raw body), and `counts` is unchanged by `q`/`filter`. Assert every 400 query row, body equals `apperr.MediaQueryErrorMessage + "\n"`.
|
||||||
|
12. Upload: for each allowed type assert 201, the item fields, `sha256` equals the test's own hash, `uploaded_by`, the url regex, and one repo entry with `UploadedByID == 1`. Upload identical bytes twice: both 201, second has `duplicate: true`, list `counts.duplicates == 1`. Assert filename rules (no extension gets `.png`, path stripped). Assert 413/415/400 statuses and bodies, that `Create` is never called on rejection, boundary 10485760 vs 10485761, a missing `file` part -> 400, and an armed `Create` failure -> 500 `"Internal server error\n"`.
|
||||||
|
13. Rename: assert 200 with the new filename, the same `url`, the article body unchanged, and every invalid row -> 400 with `"Enter a filename.\n"` for the filename rows; 404 for 9999; 400 with `apperr.IdUint32ErrorMessage` for `abc`. Assert the repository filename is unchanged after each 400.
|
||||||
|
14. Delete: in-use image -> 204 with an empty body, article bodies byte-identical, `deleteCalls == [1]`; 404, 400, 500 rows. The "file already gone" case is a persistence behaviour and is a manual item.
|
||||||
|
15. Usage: assert the exact JSON arrays (raw body compared as JSON), the empty `[]`, the absolute-url article, 404 and 400.
|
||||||
|
16. Merge: assert 200 `{articles_updated, merged}`, resulting bodies (both occurrences replaced), unchanged bodies for the other articles, and only image 2 left. Assert the 409 rows and 404 row, with no body change and no `Delete` calls (`deleteCalls` empty). Assert every 400 row with `apperr.MediaMergeRequestErrorMessage`. Assert the two failure rows: `UpdateBody` failing for article 2 leaves article 1 restored and no `Delete` call; `Delete` failing for image 3 leaves bodies switched and returns 500.
|
||||||
|
17. Unit-level asserts (same file, no HTTP) with `errors.Is` on the sentinels `ErrImageUnreadable`, `ErrMergeCopyMissing`, `ErrMergeHashMismatch`, `ErrInvalidFilename`.
|
||||||
|
18. Layering guard: `go list -deps` or a grep-style test that `api/handlers/media` imports no `persistence`, `mailer`, `models` or `gorm` package.
|
||||||
|
|
||||||
|
## Manual verification (not exercised by `task test`)
|
||||||
|
- Real upload, rename, delete, merge against a scratch SQLite file and `UPLOAD_DIR` via `task dev`: the files land on disk, `url` loads through `/static/uploadedImages/`, deleting an in-use image leaves the article body text untouched, and a merge removes the copy files.
|
||||||
|
- Delete when the file was already removed from `UPLOAD_DIR` still answers 204.
|
||||||
|
- Startup backfill: copy an old database (rows with only `path`), boot, and check that filename, size, content_type, width, height and sha256 are filled; check idempotency on a second boot; check that a row whose file is missing does not stop the boot; check that the `article_images` table and `article_id` column are still present and not written.
|
||||||
|
- `UploadedByID` 0 rows display an empty `uploaded_by`.
|
||||||
|
- WEBP dimensions with a real WEBP file (the fixture is minimal).
|
||||||
|
- No SMTP involvement. No real rate limit (out of scope for this slice).
|
||||||
@@ -0,0 +1,452 @@
|
|||||||
|
Feature: Media page, part 2: upload, selection and duplicates
|
||||||
|
|
||||||
|
As a verified RenewCMS owner
|
||||||
|
I want to upload images to the library from /media, select several images to delete them
|
||||||
|
together, and merge identical copies
|
||||||
|
So that I can keep the library complete and free of duplicates without leaving the page
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given /media is the verified route from slice B1, rendered as MediaPage inside
|
||||||
|
DashboardShell, per docs/design/routes.md and docs/design/screens/media.md
|
||||||
|
And this slice is SPA only: the API from slice A is used unchanged, and no Go code, use case
|
||||||
|
or repository changes
|
||||||
|
And this slice supersedes these B1 statements: the Upload button, the mobile pinned button and
|
||||||
|
"Upload an image" are enabled; the Duplicates tab is enabled and ?filter=duplicates is a
|
||||||
|
valid value; "Review duplicates" is enabled; Space on a card toggles selection; the checkbox,
|
||||||
|
the "Select all" text and the partial state exist; the B2 states no longer carry
|
||||||
|
skip 'pending' in web/visual/states.ts
|
||||||
|
And the calls used are POST /v1/media/ (multipart field "file", sent with XMLHttpRequest so
|
||||||
|
that upload progress is reported, with the jwt cookie), GET /v1/media/?hash=<sha256 hex>,
|
||||||
|
DELETE /v1/media/{id}, POST /v1/media/merge { keep_id, merge_ids } and the list call from
|
||||||
|
B1 with filter=duplicates; every other /v1 call goes through useApi
|
||||||
|
And 401 and 403 on any of these calls, including the XHR upload, send the user to
|
||||||
|
/login?redirect=/media&reason=expired and /register/pending as useApi does, with no local
|
||||||
|
copy
|
||||||
|
And the browser-side checks reuse validateImageFile from web/src/lib/imageUpload.ts: size is
|
||||||
|
checked first (10 MB = 10485760 bytes is allowed, one byte more is too large), then the
|
||||||
|
file's MIME type and its extension must both be allowed (PNG, JPEG, WEBP, SVG; .png, .jpg,
|
||||||
|
.jpeg, .webp, .svg); a rejected file is never hashed and never sent
|
||||||
|
And hashing lives in a shared module under web/src/lib that depends on nothing in the Media
|
||||||
|
page, so that the editor's media picker slice reuses it: it reads the file, computes the
|
||||||
|
SHA-256 with crypto.subtle and resolves the lowercase 64-character hex, or resolves null when
|
||||||
|
crypto.subtle is unavailable
|
||||||
|
And at most 2 uploads are in flight at once; files are processed in the order they were
|
||||||
|
chosen or dropped, and hashing runs inside the file's concurrency slot while its row reads
|
||||||
|
"Waiting"
|
||||||
|
And uploads from this page are not cropped or resized, and each file is sent as chosen
|
||||||
|
And toast ids are "media-bulk-deleted", "media-bulk-delete-failed", "media-merged-{keep_id}"
|
||||||
|
and "media-not-found-{id}", and success toasts last 5 s; the bulk-delete failure toast has
|
||||||
|
no duration and stays until retried or dismissed
|
||||||
|
And the 12-image fixture, its counts { all: 12, unused: 2, duplicates: 2 } and its sample
|
||||||
|
data are the ones in features/media_browse.feature; the duplicate groups are {12, 5, 6}
|
||||||
|
(floorboards.jpg, floorboards-copy.jpg, IMG_2208.jpg, 3600 × 2400, 2.4 MB each) and
|
||||||
|
{7, 9} (IMG_4471.jpg, stone-wall-detail.jpg, 3600 × 2400, 3.1 MB each)
|
||||||
|
And where a board frame contradicts the design prose or the fixture, this spec follows the
|
||||||
|
prose and the fixture, and the design is corrected by the user, with no visual exception
|
||||||
|
|
||||||
|
Rule: Upload entry points
|
||||||
|
|
||||||
|
Scenario Outline: The Upload controls open the file chooser
|
||||||
|
Given the Default state has loaded <context>
|
||||||
|
When the user activates "<control>"
|
||||||
|
Then the file chooser opens, accepts several files and offers image/png, image/jpeg, image/webp and image/svg+xml
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| context | control |
|
||||||
|
| at md width or more | Upload |
|
||||||
|
| below md width | Upload |
|
||||||
|
| and the library has no image | Upload an image |
|
||||||
|
|
||||||
|
Scenario: Dropping files anywhere on the page
|
||||||
|
Given the Default state has loaded at md width or more
|
||||||
|
When the user drags files over the page
|
||||||
|
Then a dashed primary-bordered area covers the content, with the upload icon, the title "Drop images to upload" and the text "PNG, JPEG, WEBP, SVG · max 10 MB each"
|
||||||
|
And the mobile pinned Upload button is hidden while the area shows
|
||||||
|
When the user drags the files away from the page
|
||||||
|
Then the area disappears and nothing is uploaded
|
||||||
|
When the user drops the files on the page
|
||||||
|
Then the area disappears and the upload of each file starts straight away, with no crop step
|
||||||
|
|
||||||
|
Scenario: Dragging something that is not a file does nothing
|
||||||
|
When the user drags selected text over the page
|
||||||
|
Then no drop area shows
|
||||||
|
|
||||||
|
Rule: Browser checks, nothing is sent
|
||||||
|
|
||||||
|
Scenario Outline: A file that fails the checks becomes a rejected row
|
||||||
|
Given the user chooses the file "<file>" of <size> with MIME type "<mime>"
|
||||||
|
Then one row is added with the file-x icon, the title "<title>" and the text "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image."
|
||||||
|
And no hash lookup and no POST /v1/media/ is sent for it
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| file | size | mime | title |
|
||||||
|
| scan.tif | 14.2 MB | image/tiff | scan.tif is 14.2 MB |
|
||||||
|
| notes.pdf | 210 KB | application/pdf | notes.pdf isn't an image |
|
||||||
|
| photo.png | 10.1 MB | image/png | photo.png is 10.1 MB |
|
||||||
|
| fake.jpg | 40 KB | text/plain | fake.jpg isn't an image |
|
||||||
|
| logo.gif | 40 KB | image/gif | logo.gif isn't an image |
|
||||||
|
| pic.jpg | 40 KB | image/png | pic.jpg isn't an image |
|
||||||
|
|
||||||
|
Scenario: Every rejected file leaves the panel with "Nothing was uploaded"
|
||||||
|
Given the user chooses scan.tif (14.2 MB), notes.pdf (210 KB) and broken.png (3.0 MB, rejected by the server with 400)
|
||||||
|
Then the panel header reads "Nothing was uploaded" with "3 files were rejected" and a "Dismiss" button
|
||||||
|
And the rows read "scan.tif is 14.2 MB", "notes.pdf isn't an image" and "broken.png couldn't be read" with "The server couldn't read this image. Save it again as a PNG or JPEG, then try again."
|
||||||
|
And no summary line shows
|
||||||
|
|
||||||
|
Scenario: Rejected and failed rows without an added image
|
||||||
|
Given the user chooses one rejected file and one file whose upload fails with 500
|
||||||
|
Then the panel header reads "Nothing was uploaded" with "2 files need attention"
|
||||||
|
And no summary line shows
|
||||||
|
|
||||||
|
Rule: The upload panel and its rows
|
||||||
|
|
||||||
|
Scenario: Files upload two at a time with progress
|
||||||
|
Given the user chooses 6 valid images and the duplicate lookup finds nothing
|
||||||
|
Then the panel shows above the images, below the toolbar, with the title "Uploading 6 images", "0 of 6 done" and a "Cancel all" button
|
||||||
|
And rows 1 and 2 read "Uploading", and rows 3 to 6 read "Waiting" (each row: 40 px thumbnail, filename, size)
|
||||||
|
When the first upload reports 1.1 MB sent of 2.6 MB
|
||||||
|
Then its row reads "Uploading 1.1 of 2.6 MB" over a 4 px progress bar filled to 42 % and shows a cancel x
|
||||||
|
When the first upload resolves 201
|
||||||
|
Then its row reads "Added to your library" with a circle-check icon, the header reads "1 of 6 done", and row 3 starts uploading
|
||||||
|
And at no time are more than 2 requests to POST /v1/media/ in flight
|
||||||
|
|
||||||
|
Scenario: The panel header counts settled rows
|
||||||
|
Given a panel with rows Added, Duplicate, Rejected, Failed, Uploading and Waiting
|
||||||
|
Then the header reads "4 of 6 done"
|
||||||
|
|
||||||
|
Scenario: Singular forms
|
||||||
|
Given the user chooses 1 valid image
|
||||||
|
Then the panel title reads "Uploading 1 image"
|
||||||
|
|
||||||
|
Scenario: New files added while the panel is open
|
||||||
|
Given the panel is showing rows
|
||||||
|
When the user chooses or drops more files
|
||||||
|
Then their rows are appended and the header counts cover all rows
|
||||||
|
|
||||||
|
Scenario: A new upload refreshes the list in the background
|
||||||
|
Given an upload resolves 201
|
||||||
|
Then the list is requested again with no skeleton, so the new image shows and the counts update
|
||||||
|
|
||||||
|
Scenario: A row whose content already exists
|
||||||
|
Given the user chooses "floorboards-2.jpg" (2.4 MB, valid)
|
||||||
|
When the SHA-256 of the file is computed
|
||||||
|
Then GET /v1/media/?hash=<that hex> is sent before any POST
|
||||||
|
And when it resolves 200 with the image "floorboards.jpg" (id 12, uploaded 14 Jun 2026 by Inès Duarte)
|
||||||
|
Then the row shows "Already in your library", the text `Same as "floorboards.jpg", uploaded 14 Jun 2026 by Inès Duarte.`, and the buttons "Use existing" and "Upload anyway"
|
||||||
|
And nothing is sent with POST /v1/media/ for it, and its concurrency slot is released
|
||||||
|
|
||||||
|
Scenario: Several existing matches name the oldest one
|
||||||
|
Given the lookup matches several images
|
||||||
|
Then the row names the oldest match
|
||||||
|
|
||||||
|
Scenario: Use existing selects the existing image
|
||||||
|
Given the row for "floorboards-2.jpg" is showing "Already in your library" for id 12
|
||||||
|
When the user activates "Use existing"
|
||||||
|
Then the row is dropped from the panel
|
||||||
|
And the image "floorboards.jpg" is selected, the bulk bar reads "1 selected", and the page announces "floorboards.jpg selected, 1 selected"
|
||||||
|
|
||||||
|
Scenario: Use existing when the image is not in the loaded list
|
||||||
|
Given the existing image is not in the loaded list because of the search, the tab or the 100 limit
|
||||||
|
When the user activates "Use existing"
|
||||||
|
Then the search and the tab reset to All and the image is selected
|
||||||
|
And if it is still not loaded the row is dropped without selecting
|
||||||
|
|
||||||
|
Scenario: Upload anyway stores a second copy
|
||||||
|
Given the row for "floorboards-2.jpg" is showing "Already in your library"
|
||||||
|
When the user activates "Upload anyway"
|
||||||
|
Then the file is sent with POST /v1/media/ and the row follows the normal upload states
|
||||||
|
And when it resolves 201 the list is reloaded and the Duplicates tab count reflects the new copy
|
||||||
|
|
||||||
|
Scenario Outline: The duplicate check is skipped when it cannot run
|
||||||
|
Given the user chooses a valid image and <condition>
|
||||||
|
Then the file is sent with POST /v1/media/ without waiting for the answer to a lookup
|
||||||
|
And any duplicate then shows up under Duplicates
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| condition |
|
||||||
|
| crypto.subtle is undefined (an insecure context) |
|
||||||
|
| GET /v1/media/?hash= fails with 500 or never reaches the server |
|
||||||
|
|
||||||
|
Scenario Outline: Server answers for an upload that passed the checks
|
||||||
|
Given a valid image "<file>" of <size> is uploading
|
||||||
|
When POST /v1/media/ resolves <status>
|
||||||
|
Then the row reads <row>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| file | size | status | row |
|
||||||
|
| roof.png | 1.4 MB | 201 | circle-check "Added to your library" |
|
||||||
|
| scan.png | 9.9 MB | 413 | file-x "scan.png is 9.9 MB" over "Images can be up to 10 MB. Use a PNG, JPEG, WEBP or SVG image." |
|
||||||
|
| notes.png | 210 KB | 415 | file-x "notes.png isn't an image" over the same text |
|
||||||
|
| broken.png | 3.0 MB | 400 | file-x "broken.png couldn't be read" over "The server couldn't read this image. Save it again as a PNG or JPEG, then try again." |
|
||||||
|
| roof.png | 1.4 MB | 500 | circle-x "Upload failed" over "The server didn't accept the file. Nothing was added to your library." and a "Try again" button (icon rotate-cw) |
|
||||||
|
| roof.png | 1.4 MB | no answer (network) | the same Failed row |
|
||||||
|
|
||||||
|
Scenario: Try again retries one file
|
||||||
|
Given a row is "Upload failed"
|
||||||
|
When the user activates "Try again"
|
||||||
|
Then only that file is sent again with POST /v1/media/ (no new duplicate lookup), and the row follows the normal upload states
|
||||||
|
|
||||||
|
Scenario: Cancelling one upload or all of them
|
||||||
|
Given several files are uploading or waiting
|
||||||
|
When the user activates the cancel x on an uploading row
|
||||||
|
Then that request is aborted and the row is removed, and the next waiting file starts
|
||||||
|
When the user activates "Cancel all"
|
||||||
|
Then every request in flight is aborted and every waiting row is removed, Added, rejected and failed rows stay, and when no row is left the panel closes
|
||||||
|
|
||||||
|
Scenario: The panel settles with a summary
|
||||||
|
Given 5 files settled as 2 Added, 1 Already in your library (still undecided), 1 rejected and 1 failed
|
||||||
|
Then the header reads "Upload finished" with "5 images" and a "Dismiss" button in place of "Cancel all"
|
||||||
|
And a summary line reads "2 uploaded · 1 already in your library · 2 need attention"
|
||||||
|
And the page announces the summary when the last row settles
|
||||||
|
When the user activates "Dismiss"
|
||||||
|
Then the panel and its rows disappear, including rejected and failed rows, which stay until then
|
||||||
|
|
||||||
|
Scenario Outline: The summary line counts each outcome and omits empty parts
|
||||||
|
Given the panel has settled with <uploaded> added, <dup> already in the library, <attention> rejected or failed
|
||||||
|
Then the summary line reads "<line>"
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| uploaded | dup | attention | line |
|
||||||
|
| 2 | 1 | 2 | 2 uploaded · 1 already in your library · 2 need attention |
|
||||||
|
| 3 | 0 | 0 | 3 uploaded |
|
||||||
|
| 0 | 1 | 0 | 1 already in your library |
|
||||||
|
| 1 | 0 | 1 | 1 uploaded · 1 need attention |
|
||||||
|
|
||||||
|
Rule: Too many uploads (429)
|
||||||
|
|
||||||
|
Scenario: The server rate limits an upload
|
||||||
|
Given a file is uploading and files are waiting
|
||||||
|
When POST /v1/media/ resolves 429 with the header Retry-After: 42
|
||||||
|
Then an info alert with the timer icon reads "Too many uploads" over "For your security, wait a moment before uploading again."
|
||||||
|
And the Upload button reads "Try again in 0:42" with the timer icon and is disabled, and so is the mobile pinned button
|
||||||
|
And Added rows stay in the panel
|
||||||
|
And the rate-limited file goes back to Waiting and the queue pauses
|
||||||
|
And the countdown is driven by useRetryAfter and ticks once per second
|
||||||
|
When the countdown reaches 0:00
|
||||||
|
Then the alert disappears, the Upload button reads "Upload" and is enabled again
|
||||||
|
And the paused file and the waiting files resume by themselves
|
||||||
|
|
||||||
|
Scenario: A missing Retry-After counts as 60 seconds
|
||||||
|
When POST /v1/media/ resolves 429 without a readable Retry-After header
|
||||||
|
Then the countdown starts at 1:00
|
||||||
|
|
||||||
|
Scenario: Dropping or choosing files while rate limited
|
||||||
|
Given the countdown is running
|
||||||
|
When the user drops files on the page
|
||||||
|
Then nothing is uploaded and the drop area does not show
|
||||||
|
|
||||||
|
Rule: Offline
|
||||||
|
|
||||||
|
Scenario: Upload, bulk delete and merge need a connection
|
||||||
|
Given the Default state has loaded and navigator.onLine becomes false
|
||||||
|
Then the offline banner from B1 shows
|
||||||
|
And "Upload" (header, mobile pinned button and "Upload an image"), "Delete" in the bulk bar and every "Merge into this one" are disabled, and dropping files does nothing
|
||||||
|
And browsing, selecting and "Clear" still work
|
||||||
|
When navigator.onLine becomes true
|
||||||
|
Then they are enabled again
|
||||||
|
|
||||||
|
Rule: Selection
|
||||||
|
|
||||||
|
Scenario: Selecting images
|
||||||
|
Given the Default state has loaded at md width or more
|
||||||
|
Then no checkbox is shown on the cards
|
||||||
|
When the pointer rests on a card, or a card takes keyboard focus
|
||||||
|
Then its checkbox shows at the top left (36 px)
|
||||||
|
When the user ticks the checkbox of "north-wall.jpg" (or presses Space on the card)
|
||||||
|
Then the card takes the sand fill (--rc-sand) with a primary outline, and every card now shows its checkbox
|
||||||
|
And the page announces "north-wall.jpg selected, 1 selected"
|
||||||
|
And the keyboard path is Space on the card: the checkbox itself is not an extra tab stop
|
||||||
|
And Enter still opens the detail panel, and ticking a checkbox does not
|
||||||
|
|
||||||
|
Scenario: Unselecting announces the new count
|
||||||
|
Given 3 images are selected
|
||||||
|
When the user unselects "north-wall.jpg"
|
||||||
|
Then the page announces "north-wall.jpg unselected, 2 selected"
|
||||||
|
And when the last one is unselected it announces "Selection cleared"
|
||||||
|
|
||||||
|
Scenario: Selection on mobile
|
||||||
|
Given the Default state has loaded below md width
|
||||||
|
Then every card shows a 44 px checkbox, and so does every row of the card list in list view
|
||||||
|
And tapping the checkbox toggles the selection, and tapping the card opens the detail panel
|
||||||
|
|
||||||
|
Scenario: Select all and the partial state
|
||||||
|
Given the Default state has loaded
|
||||||
|
Then the row above the grid reads "Select all" and "12 images", with an unchecked checkbox
|
||||||
|
When 3 images are selected
|
||||||
|
Then that checkbox shows the partial state
|
||||||
|
When the user activates it while it is partial
|
||||||
|
Then all 12 loaded images are selected and it shows checked
|
||||||
|
When the user activates it while it is checked
|
||||||
|
Then the selection is emptied
|
||||||
|
And in list view at md width or more the table header checkbox does the same; the mobile card list has no "Select all" row and is selected through its 44 px row checkboxes
|
||||||
|
|
||||||
|
Scenario: Escape and Clear empty the selection
|
||||||
|
Given 3 images are selected and the detail panel is closed
|
||||||
|
When the user presses Escape, or activates "Clear" in the bulk bar
|
||||||
|
Then the selection is emptied and the bulk bar disappears
|
||||||
|
Given the detail panel is open over a selection
|
||||||
|
When the user presses Escape
|
||||||
|
Then only the panel closes and the selection stays
|
||||||
|
|
||||||
|
Scenario: The selection follows the query
|
||||||
|
Given 3 images are selected
|
||||||
|
When the user changes the search text, the tab or the sort
|
||||||
|
Then the selection is cleared
|
||||||
|
When the user switches between grid and list
|
||||||
|
Then the selection is kept
|
||||||
|
|
||||||
|
Scenario: The bulk bar
|
||||||
|
Given the images "north-wall.jpg", "kitchen-after.webp" and "window-frame.jpg" are selected
|
||||||
|
Then a sticky bar sits at the bottom: 400 px wide and 24 px above the bottom edge, centred over the content area on desktop; full width with 16 px side margins and 16 px above the bottom edge on mobile
|
||||||
|
And it has the inverted fill, the text "3 selected", a danger "Delete" button (icon trash-2) and an inverted "Clear" button
|
||||||
|
And on mobile it replaces the pinned Upload button
|
||||||
|
And toasts sit above it on mobile
|
||||||
|
|
||||||
|
Rule: Bulk delete
|
||||||
|
|
||||||
|
Scenario: Bulk delete, confirm
|
||||||
|
Given "north-wall.jpg" (used in 2), "kitchen-after.webp" (used in 3) and "window-frame.jpg" (unused) are selected
|
||||||
|
When the user activates "Delete"
|
||||||
|
Then a dialog opens titled "Delete 3 images?" with the description "2 of them are used in 5 articles, which will show a broken image. The other one isn't used anywhere. This can't be undone."
|
||||||
|
And the body has one bordered row per selected image: the filename and the badge "Used in 2", "Used in 3" or "Unused"
|
||||||
|
And the buttons read "Cancel" first, then a danger "Delete 3 images"
|
||||||
|
And no usage request is sent
|
||||||
|
|
||||||
|
Scenario: Bulk delete, singular
|
||||||
|
Given one image is selected
|
||||||
|
When the user activates "Delete"
|
||||||
|
Then the dialog is titled "Delete 1 image?" and the confirm button reads "Delete 1 image"
|
||||||
|
|
||||||
|
Scenario: Bulk delete, in progress
|
||||||
|
Given the bulk delete dialog is open for 3 images
|
||||||
|
When the user activates "Delete 3 images"
|
||||||
|
Then one DELETE /v1/media/{id} is sent for each of the 3 images
|
||||||
|
And both buttons are disabled, the confirm button reads "Deleting…" with a loader-circle, and Cancel, Escape and a backdrop click do not close the dialog
|
||||||
|
|
||||||
|
Scenario: Bulk delete, done
|
||||||
|
Given a bulk delete of ids 1, 2 and 8 is in flight
|
||||||
|
When every DELETE resolves 204
|
||||||
|
Then the dialog closes, the 3 cards leave the grid and the selection is empty
|
||||||
|
And focus moves to the card now at the position of the first deleted card, or to the page heading when no card remains
|
||||||
|
And a success toast appears: icon circle-check, id "media-bulk-deleted", title "3 images deleted", text "They're gone from your library."
|
||||||
|
And the list is then requested again in the background, with no skeleton
|
||||||
|
|
||||||
|
Scenario: Bulk delete, partly failed
|
||||||
|
Given a bulk delete of ids 1, 2 and 8 is in flight
|
||||||
|
When DELETE /v1/media/1 and DELETE /v1/media/2 resolve 204 and DELETE /v1/media/8 resolves 500
|
||||||
|
Then the dialog closes, the cards for ids 1 and 2 leave the grid, and "window-frame.jpg" stays in the grid and stays selected, so the bulk bar reads "1 selected"
|
||||||
|
And an error toast appears and stays until retried or dismissed: icon circle-x, id "media-bulk-delete-failed", title "Couldn't delete 1 image", text "2 images were deleted. window-frame.jpg is still in your library. Try again." and a "Retry" button (icon rotate-cw)
|
||||||
|
When the user activates "Retry"
|
||||||
|
Then DELETE /v1/media/8 is sent again with no dialog, and on 204 the card leaves and the toast is replaced by a success toast
|
||||||
|
|
||||||
|
Scenario: Bulk delete, several failures
|
||||||
|
Given a bulk delete of 4 images in which two fail
|
||||||
|
Then the toast title reads "Couldn't delete 2 images" and the text names both files, "a.jpg and b.jpg are still in your library. Try again."
|
||||||
|
|
||||||
|
Scenario: Bulk delete, an image that no longer exists
|
||||||
|
Given a bulk delete of 3 images is in flight
|
||||||
|
When one DELETE resolves 404 and the others 204
|
||||||
|
Then the 404 image leaves the list and counts as deleted, and the success toast reads "3 images deleted"
|
||||||
|
|
||||||
|
Scenario: Bulk delete, every request fails
|
||||||
|
Given a bulk delete of 3 images is in flight
|
||||||
|
When every DELETE resolves 500 or never arrives
|
||||||
|
Then the dialog stays open with an error alert "Couldn't delete the images, so they're still there. Try again in a moment." and both buttons enabled
|
||||||
|
|
||||||
|
Rule: Duplicates
|
||||||
|
|
||||||
|
Scenario: The Duplicates tab is enabled
|
||||||
|
Given the Default state has loaded
|
||||||
|
When the user selects the "Duplicates 2" tab
|
||||||
|
Then the URL gains ?filter=duplicates and the list is requested with filter=duplicates and limit=100
|
||||||
|
And the tab is selected, and "Duplicates" carries the info-tinted count of groups
|
||||||
|
And opening /media?filter=duplicates lands on the same view, and "Review duplicates" in the detail panel of "floorboards.jpg" is enabled and selects this tab
|
||||||
|
And search applies, the sort menu and the view toggle show as on the other tabs, sort is sent with the request, and the view toggle has no effect on the groups view while the grid or list preference stays in the URL
|
||||||
|
|
||||||
|
Scenario: Duplicates, groups
|
||||||
|
Given GET /v1/media/?filter=duplicates&sort=newest&limit=100 resolves 200 with ids 5, 6, 7, 9 and 12
|
||||||
|
When the user opens the Duplicates tab
|
||||||
|
Then the images are grouped by sha256 into 2 bordered cards stacked with a 16 px gap, the group with the oldest suggested copy first
|
||||||
|
And group 1 has the header "Group 1" over "3 identical images · 2.4 MB each · 3600 × 2400", and group 2 has "Group 2" over "2 identical images · 3.1 MB each · 3600 × 2400"
|
||||||
|
And group 1 has one column per copy, in the order "floorboards.jpg", "floorboards-copy.jpg", "IMG_2208.jpg" (most used, then oldest, then lowest id), and group 2 has "IMG_4471.jpg" then "stone-wall-detail.jpg"; below md the columns stack
|
||||||
|
And each copy shows its thumbnail, filename, "Uploaded 14 Jun 2026 by Inès Duarte", an underlined "Used in 4 articles" that opens its detail panel, and a "Merge into this one" button (icon merge)
|
||||||
|
And "floorboards.jpg" and "IMG_4471.jpg" carry the sand fill, a primary outline, the "Suggested" tag and a primary button, and the other copies are outlined with outline buttons
|
||||||
|
And each group's footer reads "Suggested: the most used copy, then the oldest. Choosing another copy switches articles to it."
|
||||||
|
|
||||||
|
Scenario: Group header details
|
||||||
|
Given a group of SVG images whose uploader is unknown
|
||||||
|
Then the header reads "2 identical images · 8 KB each · Vector" and each copy reads "Uploaded 14 Jun 2026" without "by"
|
||||||
|
|
||||||
|
Scenario Outline: The suggested copy
|
||||||
|
Given a group of copies <copies>
|
||||||
|
Then the suggested copy is <suggested>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| copies | suggested |
|
||||||
|
| used in 4 (14 Jun), 3 (2 Sep) and 2 (30 Aug) | the copy used in 4 |
|
||||||
|
| used in 2 (29 Aug) and 2 (21 Aug) | the copy of 21 Aug (same use, oldest) |
|
||||||
|
| used in 0 (3 Sep) and 0 (1 Sep) | the copy of 1 Sep |
|
||||||
|
|
||||||
|
Scenario: Duplicates, empty
|
||||||
|
Given GET /v1/media/?filter=duplicates resolves 200 with no item and counts.duplicates 0
|
||||||
|
Then the Duplicates tab has no count badge
|
||||||
|
And a panel shows the copy icon, "No duplicates", "Every image in your library is different." and a "Back to all images" button
|
||||||
|
When the user activates "Back to all images"
|
||||||
|
Then the tab returns to All and ?filter leaves the URL
|
||||||
|
|
||||||
|
Rule: Merge
|
||||||
|
|
||||||
|
Scenario: Merge, confirm
|
||||||
|
Given the Duplicates tab shows group 1
|
||||||
|
When the user activates "Merge into this one" on "floorboards.jpg"
|
||||||
|
Then a dialog opens titled "Merge into floorboards.jpg?" with the description "Articles that use the other 2 copies will be switched to floorboards.jpg, and the other 2 copies will be deleted. 5 articles will be updated. This can't be undone."
|
||||||
|
And the body shows the kept image: its thumbnail, "floorboards.jpg" and "Kept · used in 4 articles now"
|
||||||
|
And the buttons read "Cancel" first, then a danger "Merge 2 copies"
|
||||||
|
|
||||||
|
Scenario: Choosing another copy keeps that one
|
||||||
|
When the user activates "Merge into this one" on "IMG_2208.jpg" in group 1
|
||||||
|
Then the dialog is titled "Merge into IMG_2208.jpg?" and its article count is the sum of the used_in of "floorboards.jpg" and "floorboards-copy.jpg"
|
||||||
|
|
||||||
|
Scenario: Merge, singular
|
||||||
|
Given a group of 2 copies
|
||||||
|
Then the description reads "Articles that use the other copy will be switched to …" and the confirm button reads "Merge 1 copy"
|
||||||
|
|
||||||
|
Scenario: Merge, in progress
|
||||||
|
Given the Merge dialog is open for group 1 with "floorboards.jpg" kept
|
||||||
|
When the user activates "Merge 2 copies"
|
||||||
|
Then POST /v1/media/merge is sent with { "keep_id": 12, "merge_ids": [5, 6] }
|
||||||
|
And both buttons are disabled, the confirm button reads "Merging…" with a loader-circle, and Cancel, Escape and a backdrop click do not close the dialog
|
||||||
|
|
||||||
|
Scenario: Merge, done
|
||||||
|
Given a merge for group 1 is in flight
|
||||||
|
When POST /v1/media/merge resolves 200 with { "articles_updated": 5, "merged": 2 }
|
||||||
|
Then the dialog closes and group 1 leaves the list
|
||||||
|
And a success toast appears: icon circle-check, id "media-merged-12", title "Copies merged", text "2 copies merged. 5 articles updated."
|
||||||
|
And the page announces the same text, and the list is requested again in the background so the counts and the Duplicate flags update
|
||||||
|
And when it was the last group, the "No duplicates" panel shows and the tab loses its count badge
|
||||||
|
|
||||||
|
Scenario Outline: Merge, errors keep the dialog open or remove the image
|
||||||
|
Given a merge for group 1 is in flight
|
||||||
|
When POST /v1/media/merge <failure>
|
||||||
|
Then <result>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| failure | result |
|
||||||
|
| resolves with a 500 response | the dialog stays open with the error alert "Couldn't merge the copies. Nothing was changed. Try again in a moment." and both buttons enabled again |
|
||||||
|
| never reaches the server | the same alert |
|
||||||
|
| resolves with a 409 response | the dialog stays open with "One of these images changed, so nothing was merged. The list is up to date now. Check it and try again.", and the list is reloaded |
|
||||||
|
| resolves with a 404 response | the dialog closes, the info toast "That image no longer exists" (id "media-not-found-12") shows, and the list is reloaded |
|
||||||
|
|
||||||
|
Rule: Sessions
|
||||||
|
|
||||||
|
Scenario Outline: Session errors are global for the new calls
|
||||||
|
When <call> resolves <status>
|
||||||
|
Then the user is sent to <destination> and no local copy shows
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| call | status | destination |
|
||||||
|
| POST /v1/media/ (XHR) | 401 | /login?redirect=/media&reason=expired |
|
||||||
|
| POST /v1/media/ (XHR) | 403 | /register/pending |
|
||||||
|
| POST /v1/media/merge | 401 | /login?redirect=/media&reason=expired |
|
||||||
|
| DELETE /v1/media/{id} | 403 | /register/pending |
|
||||||
|
| GET /v1/media/?hash= | 401 | /login?redirect=/media&reason=expired |
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
# QA: Media page, part 2 (upload, selection, duplicates)
|
||||||
|
|
||||||
|
## Scope note
|
||||||
|
|
||||||
|
SPA only. No Go test and no `test/` file; run the Go suite once (`task test`) to confirm nothing regressed. The server never returns 429 for POST /v1/media/ today (no rate limiter is mounted on the media router), so every 429 case is proven with a mock only.
|
||||||
|
|
||||||
|
## Automated (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mount MediaPage in DashboardShell with a verified session and a test router at /media, as in the B1 spec. Mock useApi's `request` for GET/DELETE/merge and the list; replace `XMLHttpRequest` with a controllable stub (per instance: `open`, `send`, `abort`, `upload.onprogress` with `loaded`/`total`, `status`, `responseText`, `getResponseHeader('Retry-After')`, `load`, `error`, `abort` events). Stub `crypto.subtle.digest` to a known hex per file with `vi.stubGlobal`, and to `undefined` for the unavailable case. Use fake timers for the 150 ms skeleton, the 120 ms search debounce and the 1 s Retry-After tick. Sample data is the 12-image fixture of media_browse.feature. Files are built with `new File([...], name, { type })` and a `size` override for over-limit sizes.
|
||||||
|
|
||||||
|
1. **Hashing lib** (pure): digest of a known byte array gives the expected lowercase 64-char hex; `crypto.subtle` undefined gives null; nothing in the lib imports from the Media page.
|
||||||
|
2. **Browser checks**: the six rows of the .feature, plus 10485760 bytes accepted and 10485761 rejected; size beats type; a rejected file triggers no hash call, no GET and no XHR; titles and text exact.
|
||||||
|
3. **Entry points**: Upload (desktop header), the mobile pinned button and "Upload an image" each click the hidden `input[type=file]` (multiple, exact accept list).
|
||||||
|
4. **Drop overlay**: dragenter with Files shows the copy exactly; dragleave hides; drop starts uploads; a drag without Files shows nothing; mobile pinned button hidden while shown.
|
||||||
|
5. **Queue**: 6 valid files give at most 2 XHRs open at once; order kept; header "Uploading 6 images" and "N of 6 done" counts settled rows; "Uploading 1 image" singular; progress 1.1 of 2.6 MB reads "Uploading 1.1 of 2.6 MB" with a 42 % bar; 201 gives "Added to your library"; a silent list reload follows; files added while open are appended.
|
||||||
|
6. **Duplicate check**: GET `?hash=` precedes POST; a match gives the Duplicate row with exact text (oldest match named); slot released; "Use existing" drops the row and selects the id (bulk bar "1 selected", live region text), including the reset-to-All path; "Upload anyway" sends POST; crypto undefined and lookup failure skip straight to POST.
|
||||||
|
7. **Server statuses**: 201, 413, 415, 400, 500, network error: row copy and icon exact; "Try again" re-sends only that file with no new GET `?hash=`.
|
||||||
|
8. **Cancel**: row x aborts that XHR and removes the row, the next file starts; "Cancel all" aborts all and removes waiting rows; panel closes when empty.
|
||||||
|
9. **Summary**: Examples-driven summary lines; "Upload finished" / "{n} images" and "Dismiss"; "Nothing was uploaded" with "3 files were rejected" and with "2 files need attention", no summary; live-region text; Dismiss removes every row.
|
||||||
|
10. **429**: `Retry-After: 42` gives the alert copy and "Try again in 0:42" (disabled, timer icon; mobile pinned button too); the 429'd file returns to Waiting; advancing 42 s re-enables, removes the alert and resumes the queue; Added rows kept; missing header gives 1:00; drops ignored while counting.
|
||||||
|
11. **Offline**: Upload, "Upload an image", bulk "Delete" and "Merge into this one" disabled; drops ignored; Clear and selection still work; back online re-enables.
|
||||||
|
12. **Selection**: checkbox visibility (hover, focus, any selection, always on mobile); tick and Space toggle; Enter opens the panel and ticking does not; live-region texts for select, unselect and "Selection cleared"; the checkbox is not a tab stop; select-all states (unchecked, partial, checked) in the grid row and the table header (no row in the mobile card list); Escape closes the panel first and clears the selection next; Clear; selection cleared on q/tab/sort change, kept on view change.
|
||||||
|
13. **Bulk bar**: copy, buttons, desktop and mobile placement classes, replaces the mobile pinned button.
|
||||||
|
14. **Bulk delete**: dialog copy exact (title, description with the summed count, rows "Used in 2", "Used in 3", "Unused"), singular form; no usage request; in progress (one DELETE per id, buttons disabled, not dismissible); done (cards leave, selection empty, focus target, toast id and text, silent reload); partly failed (two removed, failed one stays selected, bar "1 selected", toast with Retry and no auto-dismiss, Retry re-sends only the failed DELETE); several failures title; 404 counted as deleted; all failed gives the inline alert.
|
||||||
|
15. **Duplicates tab**: enabled, URL and request (`filter=duplicates`, limit=100), deep link, "Review duplicates" enabled and switching tab; sort and view toggle shown (sort sent with the request, toggle keeps the preference in the URL); grouping by sha256, group order, headers (including the SVG/unknown uploader case), column order, "Suggested" tag and footer, "Uploaded 14 Jun 2026 by Inès Duarte", "Used in 4 articles" opens the panel; suggested-copy Examples; empty state and "Back to all images"; badge absent at 0.
|
||||||
|
16. **Merge**: dialog copy exact for floorboards.jpg and another kept copy, singular form; POST body `{ keep_id: 12, merge_ids: [5, 6] }`; in progress not dismissible; 200 gives group removed, toast id "media-merged-12" and text, live-region text, silent reload, "No duplicates" when last; 500 and network give the alert; 409 gives the alert and a reload; 404 gives the info toast and closes.
|
||||||
|
17. **Global errors**: 401 and 403 from XHR upload, merge, delete and hash lookup call the same redirect handler as useApi; no local copy.
|
||||||
|
18. **B1 regression**: media_browse specs updated for the superseded statements and the rest still passes.
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- media`, desktop and mobile, light and dark)
|
||||||
|
|
||||||
|
Reference: docs/design/screens/media.md and `source/MediaFrame.dc.html`. The 20 B2 states lose `skip: 'pending'` and get a setup in `web/visual/states.ts`. None depends on the current date (dates are absolute), so none is `skip: 'clock-sensitive'`. Where a board frame contradicts the prose or fixture (bulk delete done / partly failed, "4 articles", tab badge at zero, "2 of 6 done", merge done with one group left), the user corrects the board; no exception is added.
|
||||||
|
|
||||||
|
Harness requirements:
|
||||||
|
- Upload states use an init-script XHR stub that holds a request at 1.1 of 2.6 MB (42 %); files come from `setInputFiles`; the duplicate state mocks `GET /v1/media/?hash=` by the hash of the file's bytes.
|
||||||
|
- The drag state dispatches a synthetic `dragenter` with `dataTransfer.types` = `['Files']`.
|
||||||
|
- The 429 state freezes timers with Playwright `page.clock` so the button reads "0:42".
|
||||||
|
|
||||||
|
Setups:
|
||||||
|
- [ ] Selection and bulk bar (ids 1, 2, 8; partial select-all)
|
||||||
|
- [ ] Bulk delete: confirm, in progress, partly failed, done
|
||||||
|
- [ ] Upload: drag over the page, several files mixed, summary, rejected files (413, 400), too many requests (429)
|
||||||
|
- [ ] Duplicates: groups, empty
|
||||||
|
- [ ] Merge: confirm, in progress, failed, conflict (409), done
|
||||||
|
|
||||||
|
Manual checks screenshots cannot cover:
|
||||||
|
- [ ] Keyboard and focus order: Space toggles selection, Enter opens the panel, Escape order (panel first, then selection); focus after a bulk delete; dialog focus starts on Cancel.
|
||||||
|
- [ ] Drag and drop with real files from the OS, including a folder and a non-image drop.
|
||||||
|
- [ ] Progress bar smoothness, hover and focus rings, reduced motion.
|
||||||
|
- [ ] Screen reader announcements for selection, upload completion and merge.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- Real upload round trip against a running server (`task dev`): progress on a large file, 413 at 10 MB + 1 byte, 415, 400 for a corrupt PNG, uploading the same bytes twice (duplicate row, "Upload anyway", Duplicates tab).
|
||||||
|
- Real SHA-256 over a 10 MB file, and the skip path on an insecure origin (plain http on a LAN address).
|
||||||
|
- Real merge: article bodies rewritten, counts after the refresh.
|
||||||
|
- Real 429 cannot be checked: the media router has no limiter.
|
||||||
|
- Real bulk delete of 20+ images with one deleted from another tab first (404 handling).
|
||||||
@@ -23,7 +23,7 @@ Feature: Single article read follows the same online/offline visibility rule as
|
|||||||
group that already holds GET /v1/article/ (features/public_article_listing.feature), so a
|
group that already holds GET /v1/article/ (features/public_article_listing.feature), so a
|
||||||
missing or invalid jwt cookie no longer blocks the request; POST /v1/article/,
|
missing or invalid jwt cookie no longer blocks the request; POST /v1/article/,
|
||||||
DELETE /v1/article/{id}, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish,
|
DELETE /v1/article/{id}, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish,
|
||||||
PATCH /v1/article/{id}/unpublish and POST /v1/article/{id}/image keep requiring
|
and PATCH /v1/article/{id}/unpublish keep requiring
|
||||||
Verifier + Authenticator + RequireVerifiedUser, unchanged
|
Verifier + Authenticator + RequireVerifiedUser, unchanged
|
||||||
And Handler.GetArticle reuses the existing Handler.callerIsVerified(r) helper already used by
|
And Handler.GetArticle reuses the existing Handler.callerIsVerified(r) helper already used by
|
||||||
Handler.ListArticles: when the request resolves to a verified account it calls
|
Handler.ListArticles: when the request resolves to a verified account it calls
|
||||||
|
|||||||
@@ -1,99 +0,0 @@
|
|||||||
Feature: Removing an image from an article
|
|
||||||
|
|
||||||
As an authenticated RenewCMS user managing the CMS
|
|
||||||
I want to delete an already-uploaded image by its id
|
|
||||||
So that a removed image's file and row are actually gone, and a delete on
|
|
||||||
an unknown article or an unknown image answers 404 the same way every
|
|
||||||
other article write does
|
|
||||||
|
|
||||||
Background:
|
|
||||||
Given internal/infrastructure/useCases.DeleteImageUseCase.DeleteImage(imageId)
|
|
||||||
already exists and calls image.Repository.Delete(imageId), which returns
|
|
||||||
image.ErrImageNotFound for an unknown id and, on the real ImageRepository,
|
|
||||||
also removes the uploaded file from UPLOAD_DIR, per
|
|
||||||
features/delete_article_cascades_images.feature
|
|
||||||
And this slice changes POST /v1/article/{id}/image's success response
|
|
||||||
(api/handlers/image.Handler.PostImage, features/upload_article_image.feature)
|
|
||||||
to also return the created image's numeric id, so the 201 body becomes
|
|
||||||
{"id": ..., "location": ...}; this lets a client address the image later
|
|
||||||
through this slice's DELETE route
|
|
||||||
And this slice mounts DELETE /v1/article/{articleId}/image/{imageId} in
|
|
||||||
api/router.go, in the same jwtauth Verifier + Authenticator group as
|
|
||||||
POST .../image
|
|
||||||
And this slice adds a DeleteImage method to api/handlers/image.Handler,
|
|
||||||
grows NewHandler's signature to also take DeleteImageUseCase, and wires
|
|
||||||
it in api/router.go
|
|
||||||
And DeleteImage parses articleId and imageId from the URL, answering 400
|
|
||||||
with apperr.IdUint32ErrorMessage if either isn't a valid uint32
|
|
||||||
And DeleteImage first calls GetArticleUseCase.GetArticle(articleId);
|
|
||||||
errors.Is(err, article.ErrArticleNotFound) answers 404 with
|
|
||||||
apperr.ArticleNotFoundErrorMessage; this only confirms the article id
|
|
||||||
in the URL names a real article, and does not verify that the image id
|
|
||||||
belongs to that article's Images slice (a shallow existence check on
|
|
||||||
both ids, not an ownership check)
|
|
||||||
And DeleteImage then calls DeleteImageUseCase.DeleteImage(imageId);
|
|
||||||
errors.Is(err, image.ErrImageNotFound) answers 404 with the new
|
|
||||||
apperr.ImageNotFoundErrorMessage = "Image not found"; any other error
|
|
||||||
falls back to the existing generic 500
|
|
||||||
And on success DeleteImage answers 204 with an empty body, the same shape
|
|
||||||
as DELETE /v1/article/{id}
|
|
||||||
|
|
||||||
Scenario: Removing an image from an article it belongs to succeeds
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository contains an article with id 1 titled
|
|
||||||
"Backyard Renovation Update" whose Images slice holds image id 10
|
|
||||||
And the image repository contains an image with id 10
|
|
||||||
When the client sends DELETE /v1/article/1/image/10 with that cookie
|
|
||||||
Then the response status is 204
|
|
||||||
And the response body is empty
|
|
||||||
And the image repository no longer contains an image with id 10
|
|
||||||
|
|
||||||
Scenario: Removing an image from an unknown article answers 404 and never touches the image repository
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository has no article with id 9999
|
|
||||||
And the image repository contains an image with id 10
|
|
||||||
When the client sends DELETE /v1/article/9999/image/10 with that cookie
|
|
||||||
Then the response status is 404
|
|
||||||
And the response body is the text "Article not found"
|
|
||||||
And the image repository's Delete is never called
|
|
||||||
And the image repository still contains the image with id 10
|
|
||||||
|
|
||||||
Scenario: Removing an unknown image from an existing article answers 404
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository contains an article with id 1 titled
|
|
||||||
"Backyard Renovation Update"
|
|
||||||
And the image repository has no image with id 9999
|
|
||||||
When the client sends DELETE /v1/article/1/image/9999 with that cookie
|
|
||||||
Then the response status is 404
|
|
||||||
And the response body is the text "Image not found"
|
|
||||||
|
|
||||||
Scenario: Removing an image id that belongs to a different article still succeeds, because the check is shallow
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository contains an article with id 1 titled
|
|
||||||
"Backyard Renovation Update" whose Images slice is empty
|
|
||||||
And the article repository contains a second article with id 2 whose
|
|
||||||
Images slice holds image id 10
|
|
||||||
And the image repository contains an image with id 10
|
|
||||||
When the client sends DELETE /v1/article/1/image/10 with that cookie
|
|
||||||
Then the response status is 204
|
|
||||||
And the image repository no longer contains an image with id 10
|
|
||||||
|
|
||||||
Scenario: Removing an image still requires authentication
|
|
||||||
Given no jwt cookie is sent
|
|
||||||
And the article repository contains an article with id 1 titled
|
|
||||||
"Backyard Renovation Update" whose Images slice holds image id 10
|
|
||||||
And the image repository contains an image with id 10
|
|
||||||
When the client sends DELETE /v1/article/1/image/10 without a cookie
|
|
||||||
Then the response status is 401
|
|
||||||
And the image repository still contains the image with id 10
|
|
||||||
|
|
||||||
Scenario Outline: A malformed id in the URL answers 400 before either repository is touched
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
When the client sends DELETE /v1/article/<article_id>/image/<image_id> with that cookie
|
|
||||||
Then the response status is 400
|
|
||||||
And the response body is the text "The server expects the ID to be in the format of an unsigned 32-bit integer (uint32)."
|
|
||||||
|
|
||||||
Examples:
|
|
||||||
| article_id | image_id |
|
|
||||||
| abc | 10 |
|
|
||||||
| 1 | abc |
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
# QA procedure: remove_article_image
|
|
||||||
|
|
||||||
Package: `test` (black-box, extending `article_test.go` / `image_test.go`).
|
|
||||||
|
|
||||||
## Setup shared by every case
|
|
||||||
1. Call `validator.InitValidator()` once.
|
|
||||||
2. Reuse `mockArticleRepo` and `mockImageRepo` as-is.
|
|
||||||
3. Wire `useCases.NewDeleteImageUseCase(imageRepo)` (already used by
|
|
||||||
`delete_article_cascades_images.qa.md`'s suite) alongside the existing
|
|
||||||
use cases.
|
|
||||||
4. Build `image.NewHandler(...)` with its grown constructor including the
|
|
||||||
delete use case, matching whatever parameter order the coder settles on.
|
|
||||||
5. Build a test `jwtauth.New("HS256", []byte("test-secret"), nil)`.
|
|
||||||
6. Mount `DELETE /{id}/image/{imageId}` alongside the existing article
|
|
||||||
routes under the authenticated group, mirroring `api/router.go` after
|
|
||||||
this slice.
|
|
||||||
7. Mint a valid jwt cookie for user id 1 as in `upload_article_image.qa.md`.
|
|
||||||
|
|
||||||
## HTTP checks
|
|
||||||
8. Seed `articleRepo.articles[1]` with `Images: []*image.Image{{ID: 10}}`
|
|
||||||
and `imageRepo.images[10] = image.Image{ID: 10}`. Send
|
|
||||||
`DELETE /v1/article/1/image/10` with the valid cookie. Assert status
|
|
||||||
204, empty body; assert `imageRepo.images` no longer has key 10.
|
|
||||||
9. Empty `articleRepo`; seed `imageRepo.images[10]`. Send
|
|
||||||
`DELETE /v1/article/9999/image/10`. Assert 404, body
|
|
||||||
`"Article not found\n"`; assert `imageRepo.images` still has key 10
|
|
||||||
(Delete never called — track via a call-count field on the fake, the
|
|
||||||
same way the existing fakes already track `Create`).
|
|
||||||
10. Seed `articleRepo.articles[1]`; empty `imageRepo`. Send
|
|
||||||
`DELETE /v1/article/1/image/9999`. Assert 404, body
|
|
||||||
`"Image not found\n"`.
|
|
||||||
11. Seed `articleRepo.articles[1]` (empty Images) and `articleRepo.articles[2]`
|
|
||||||
with `Images: []*image.Image{{ID: 10}}`; seed `imageRepo.images[10]`.
|
|
||||||
Send `DELETE /v1/article/1/image/10`. Assert 204; assert
|
|
||||||
`imageRepo.images` no longer has key 10 — asserts the shallow-check
|
|
||||||
contract from the feature's fourth scenario.
|
|
||||||
12. Seed as in step 8. Send `DELETE /v1/article/1/image/10` with **no**
|
|
||||||
cookie. Assert 401; assert `imageRepo.images` still has key 10.
|
|
||||||
13. Examples-driven: send `DELETE /v1/article/abc/image/10` and
|
|
||||||
`DELETE /v1/article/1/image/abc` with the valid cookie. Assert 400,
|
|
||||||
body `"The server expects the ID to be in the format of an unsigned
|
|
||||||
32-bit integer (uint32).\n"` for each.
|
|
||||||
|
|
||||||
## Also touched by this slice: upload_article_image's 201 body
|
|
||||||
14. Extend `upload_article_image.qa.md`'s existing 201-body assertion to
|
|
||||||
also decode and check the `id` field equals the newly created image's
|
|
||||||
`ID` in `imageRepo.images`.
|
|
||||||
|
|
||||||
## Manual verification (not exercised by the Go test)
|
|
||||||
- Real DELETE against a real SQLite file and real UPLOAD_DIR: confirm the
|
|
||||||
file is actually removed from disk and the `article_images` join row is
|
|
||||||
gone, the same way `upload_article_image.qa.md`'s manual item covers the
|
|
||||||
POST side.
|
|
||||||
- SPA-visible behaviour: covered separately by
|
|
||||||
`features/editor_image_removal.qa.md`.
|
|
||||||
- No SMTP involvement.
|
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
Feature: The legacy POST /v1/article/{id}/image alias is removed
|
||||||
|
|
||||||
|
As the maintainer of RenewCMS
|
||||||
|
I want the editor to upload through /v1/media only and the article alias deleted
|
||||||
|
So that there is one way to add an image and no dead route to keep
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given this is a Go API change in a slice that is otherwise SPA only, made at the user's request
|
||||||
|
And features/upload_article_image.feature and its .qa.md are deleted, with their tests
|
||||||
|
And api/router.go no longer mounts r.Post("/{id}/image", ...) in NewArticleRouter, and the
|
||||||
|
imageHandler variable and the api/handlers/image import are removed from it
|
||||||
|
And the package api/handlers/image (PostLegacyArticleImage, its NewHandler and its helpers) is deleted
|
||||||
|
And CreateImageUseCase and GetArticleUseCase stay: both are used by the media handler and
|
||||||
|
the article handler, and api/pkg/upload stays because the media handler uses it
|
||||||
|
And the rest of the protected article group is unchanged, still behind jwtauth.Authenticator,
|
||||||
|
RequireCurrentToken and RequireVerifiedUser
|
||||||
|
And docs/architecture.md no longer lists api/handlers/image
|
||||||
|
And POST /v1/media/ is the only upload route, and DELETE /v1/article/{id}/image/{imageId}
|
||||||
|
stays unmounted, as before
|
||||||
|
|
||||||
|
Scenario Outline: The removed routes are not found
|
||||||
|
Given a valid jwt cookie for verified user 1 and an article with id 1
|
||||||
|
When the client sends <method> <path> with a valid PNG as multipart field "file"
|
||||||
|
Then the response status is 404
|
||||||
|
And the image repository's Create is never called
|
||||||
|
And no image exists afterwards
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| method | path |
|
||||||
|
| POST | /v1/article/1/image |
|
||||||
|
| DELETE | /v1/article/1/image/10 |
|
||||||
|
|
||||||
|
Scenario: Uploading still works through the media route
|
||||||
|
Given a valid jwt cookie for verified user 1
|
||||||
|
When the client sends POST /v1/media/ with a real PNG named "before.png"
|
||||||
|
Then the response status is 201 and the body is the library item with a "url" and an "id"
|
||||||
|
And GET /v1/media/ lists it
|
||||||
|
|
||||||
|
Scenario: The rest of the article router is unchanged
|
||||||
|
Given a valid jwt cookie for verified user 1 and an article with id 1
|
||||||
|
When the client sends PATCH /v1/article/1/publish
|
||||||
|
Then the response is as before this slice
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# QA procedure: remove_legacy_article_image_alias
|
||||||
|
|
||||||
|
Package: `test` (black-box, httptest, in-memory fakes, no live server).
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
1. Call `validator.InitValidator()`.
|
||||||
|
2. Build the article router exactly as `NewArticleRouter` does after the change (no image handler), wrapped in `Verifier`, `Authenticator`, `RequireCurrentToken` and `RequireVerifiedUser`, over fake article, image and user repositories. Reuse `newMultipartFileRequest` and `pngBytes` from `test/media_fixtures_test.go`.
|
||||||
|
|
||||||
|
## HTTP checks
|
||||||
|
3. `POST /v1/article/1/image` with a valid PNG and a valid cookie -> 404, `Create` never called.
|
||||||
|
4. `DELETE /v1/article/1/image/10` with a valid cookie -> 404, image 10 still exists.
|
||||||
|
5. `POST /v1/media/` with a valid PNG -> 201 with `id` and `url` (this stays covered by `media_library_http_test.go`; confirm the case still passes after the deletions).
|
||||||
|
6. `PATCH /v1/article/1/publish` still answers as in `verified_account_required_http_test.go`.
|
||||||
|
|
||||||
|
## Cleanup (Go)
|
||||||
|
7. Delete `test/upload_article_image_http_test.go`.
|
||||||
|
8. In `test/verified_account_required_http_test.go`: remove the `api/handlers/image` import, the `imageHandler` construction (line 34), the route `r.Post("/{id}/image", ...)` (line 53) and the "unverified user is refused when attaching an image" case (around line 149).
|
||||||
|
9. Run `task test` and `task lint`; nothing else may reference `PostLegacyArticleImage` or `handlers/image`.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
With `task dev`, `curl -i -X POST /v1/article/1/image` with a valid cookie answers 404.
|
||||||
@@ -23,9 +23,11 @@ Feature: Serving uploaded images as static files
|
|||||||
"application/octet-stream"
|
"application/octet-stream"
|
||||||
And every response from this handler, success or 404, sets
|
And every response from this handler, success or 404, sets
|
||||||
"X-Content-Type-Options: nosniff"
|
"X-Content-Type-Options: nosniff"
|
||||||
And every successful response sets a long-lived, public Cache-Control
|
And every successful response sets the Cache-Control header
|
||||||
header, e.g. "public, max-age=31536000, immutable", because a stored
|
"public, no-cache", so a browser may store the file but must revalidate
|
||||||
filename is a UUID and its bytes never change
|
it before reusing it; a stored filename is a UUID and its bytes never
|
||||||
|
change, but the file can be deleted from the media library, and a
|
||||||
|
long-lived cache would keep showing it
|
||||||
And an "image/svg+xml" response additionally sets
|
And an "image/svg+xml" response additionally sets
|
||||||
"Content-Security-Policy: default-src 'none'; style-src
|
"Content-Security-Policy: default-src 'none'; style-src
|
||||||
'unsafe-inline'; sandbox", so a script embedded in an uploaded SVG
|
'unsafe-inline'; sandbox", so a script embedded in an uploaded SVG
|
||||||
@@ -42,7 +44,7 @@ Feature: Serving uploaded images as static files
|
|||||||
cookie
|
cookie
|
||||||
Then the response status is 200
|
Then the response status is 200
|
||||||
And the response Content-Type is <content_type>
|
And the response Content-Type is <content_type>
|
||||||
And the response Cache-Control is "public, max-age=31536000, immutable"
|
And the response Cache-Control is "public, no-cache"
|
||||||
And the response X-Content-Type-Options is "nosniff"
|
And the response X-Content-Type-Options is "nosniff"
|
||||||
And the response has no Content-Security-Policy header
|
And the response has no Content-Security-Policy header
|
||||||
And the response body is that file's exact content
|
And the response body is that file's exact content
|
||||||
@@ -61,7 +63,7 @@ Feature: Serving uploaded images as static files
|
|||||||
with no jwt cookie
|
with no jwt cookie
|
||||||
Then the response status is 200
|
Then the response status is 200
|
||||||
And the response Content-Type is "image/svg+xml"
|
And the response Content-Type is "image/svg+xml"
|
||||||
And the response Cache-Control is "public, max-age=31536000, immutable"
|
And the response Cache-Control is "public, no-cache"
|
||||||
And the response X-Content-Type-Options is "nosniff"
|
And the response X-Content-Type-Options is "nosniff"
|
||||||
And the response Content-Security-Policy is
|
And the response Content-Security-Policy is
|
||||||
"default-src 'none'; style-src 'unsafe-inline'; sandbox"
|
"default-src 'none'; style-src 'unsafe-inline'; sandbox"
|
||||||
@@ -128,7 +130,7 @@ Feature: Serving uploaded images as static files
|
|||||||
with no jwt cookie
|
with no jwt cookie
|
||||||
Then the response status is 200
|
Then the response status is 200
|
||||||
And the response Content-Type is "image/webp"
|
And the response Content-Type is "image/webp"
|
||||||
And the response Cache-Control is "public, max-age=31536000, immutable"
|
And the response Cache-Control is "public, no-cache"
|
||||||
And the response X-Content-Type-Options is "nosniff"
|
And the response X-Content-Type-Options is "nosniff"
|
||||||
And the response body is empty
|
And the response body is empty
|
||||||
|
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ Package: `test` (black-box, new file `test/serve_uploaded_images_test.go`).
|
|||||||
non-empty byte content. For each, `httptest.NewRequest("GET",
|
non-empty byte content. For each, `httptest.NewRequest("GET",
|
||||||
"/static/uploadedImages/"+name, nil)`, no cookie. Assert status `200`;
|
"/static/uploadedImages/"+name, nil)`, no cookie. Assert status `200`;
|
||||||
`Content-Type` equals the expected value; `Cache-Control` equals
|
`Content-Type` equals the expected value; `Cache-Control` equals
|
||||||
`"public, max-age=31536000, immutable"`; `X-Content-Type-Options` equals
|
`"public, no-cache"`; `X-Content-Type-Options` equals
|
||||||
`"nosniff"`; `Content-Security-Policy` header is absent; body bytes equal
|
`"nosniff"`; `Content-Security-Policy` header is absent; body bytes equal
|
||||||
what was written.
|
what was written.
|
||||||
7. Write a `.svg` file whose content contains an inline `onload` handler
|
7. Write a `.svg` file whose content contains an inline `onload` handler
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
Feature: English and French throughout the SPA
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given all existing SPA interface text supports English and French
|
||||||
|
And English preserves existing copy and French provides equivalent meaning
|
||||||
|
And user content, API data and transactional emails remain unchanged
|
||||||
|
And visual checks are waived by the user for this slice
|
||||||
|
And the language control uses existing design tokens
|
||||||
|
|
||||||
|
Scenario Outline: Resolve the language before rendering
|
||||||
|
Given the browser-local stored language is <stored>
|
||||||
|
When the SPA starts
|
||||||
|
Then the interface language and document lang are <locale>
|
||||||
|
And browser language does not override the choice
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| stored | locale |
|
||||||
|
| absent | en |
|
||||||
|
| en | en |
|
||||||
|
| fr | fr |
|
||||||
|
| unsupported | en |
|
||||||
|
| unreadable | en |
|
||||||
|
|
||||||
|
Scenario Outline: Open the language picker in the profile submenu
|
||||||
|
Given the user opens the <menu>
|
||||||
|
When they activate the localized Language control
|
||||||
|
Then a compact scrollable picker offers English and Français
|
||||||
|
And the selected language is visibly and accessibly identified
|
||||||
|
And the picker uses Nuxt UI and existing design tokens
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| menu |
|
||||||
|
| desktop UserMenu |
|
||||||
|
| mobile AccountMenuSheet |
|
||||||
|
|
||||||
|
Scenario: Switch language without losing work
|
||||||
|
Given the user is editing an unsaved display name on /profile
|
||||||
|
When they select Français
|
||||||
|
Then all SPA interface text immediately uses French
|
||||||
|
And the document lang is fr
|
||||||
|
And the route, session, theme and unsaved work remain unchanged
|
||||||
|
And no reload, navigation or API request is caused by switching
|
||||||
|
When they select English
|
||||||
|
Then the interface immediately restores English with the same preserved state
|
||||||
|
|
||||||
|
Scenario: Remember language on this browser
|
||||||
|
Given the user selected Français
|
||||||
|
When they navigate, reload, log out or return on this browser
|
||||||
|
Then French remains selected including on public authentication screens
|
||||||
|
And no language preference is sent to the server
|
||||||
|
|
||||||
|
Scenario: Storage failure does not prevent switching
|
||||||
|
Given preference storage cannot be written
|
||||||
|
When the user selects Français
|
||||||
|
Then French is used for the current session without an error
|
||||||
|
And a fresh load without a readable preference defaults to English
|
||||||
|
|
||||||
|
Scenario: Translate the entire interface
|
||||||
|
Given French is selected
|
||||||
|
When an existing SPA screen or shared component renders
|
||||||
|
Then navigation, forms, validation, notifications, dialogs and accessibility labels use French
|
||||||
|
And counts, human-readable dates and numbers use the selected locale
|
||||||
|
And Nuxt UI controls use the selected locale
|
||||||
|
And English and French catalogs have matching keys and interpolation parameters
|
||||||
|
And an unavailable French message falls back to English
|
||||||
|
And user content, account details, filenames, URLs, API data and emails remain unchanged
|
||||||
|
|
||||||
|
Scenario Outline: Operate the picker accessibly
|
||||||
|
Given the picker is open in the <menu>
|
||||||
|
When the user navigates its options with the keyboard and confirms a choice
|
||||||
|
Then the language changes and the picker closes
|
||||||
|
And focus returns to its language control
|
||||||
|
When they reopen it and press Escape or click outside
|
||||||
|
Then the picker closes without changing language
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| menu |
|
||||||
|
| desktop UserMenu |
|
||||||
|
| mobile AccountMenuSheet |
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# SPA internationalization QA
|
||||||
|
|
||||||
|
Accepted by the user on 2026-10-03 together with the slice specification.
|
||||||
|
|
||||||
|
## Automated
|
||||||
|
|
||||||
|
1. Verify absent, English, French, unsupported and unreadable stored preferences; English defaults independently of browser language and document lang follows selection.
|
||||||
|
2. Verify desktop UserMenu and mobile AccountMenuSheet offer a localized language entry and a compact bounded scrollable picker with English and Français, selected-state semantics, selection, dismissal and focus return. Preserve profile, theme and logout behavior.
|
||||||
|
3. Switch both ways while editing an unsaved profile display name. Verify translated UI and unchanged draft, route, session and theme without additional API requests.
|
||||||
|
4. Verify browser-local persistence across reload initialization, navigation and logout/public authentication. Verify storage write failure allows switching for the current session.
|
||||||
|
5. Preserve existing English tests and add French checks for login, validation, profile save failure, integration copy feedback, not-found, representative dialogs and notifications.
|
||||||
|
6. Audit every existing view, shared component, composable and library producing interface text, including editor, media, users, invitations, settings and updates. Verify Nuxt UI controls use the active locale.
|
||||||
|
7. Assert catalog key/interpolation parity, nonempty translations, pluralization, English fallback and locale-sensitive formatting. Use fixed input dates without freezing system time. Verify displayed alerts and dialogs react to language changes.
|
||||||
|
8. Verify user content, account details, filenames, URLs, API fields, integration protocol examples, server release notes and transactional emails remain unchanged.
|
||||||
|
9. Run task test:web, frontend type checks, applicable lint and final build checks. Inspect introduced comments and ensure application changes are SPA-only.
|
||||||
|
|
||||||
|
## Visual and manual
|
||||||
|
|
||||||
|
Visual checks are SKIPPED by explicit user waiver for this slice because the designer is unavailable. The user authorized a coherent language control using existing design tokens. Do not edit design sources or claim pixel parity.
|
||||||
|
|
||||||
|
Manual checklist: desktop/mobile and light/dark coherence, viewport containment, constrained scrolling, French text readability, touch and mouse selection, keyboard movement and confirmation, Escape/outside dismissal, focus return and visible focus. Confirm language retention after reload and logout. Do not freeze dates or investigate clock-sensitive states.
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
Feature: Updates part 2: the Update button (download, verify, stage)
|
||||||
|
|
||||||
|
As the owner of a RenewCMS site
|
||||||
|
I want one button that downloads the new release, proves it is genuine, backs up the database and stages it
|
||||||
|
So that the later Restart (slice 3) installs a file that was already checked, while the site stays online
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given slices 1 to 3 of Updates ship in one release
|
||||||
|
And this slice changes nothing that is running: it never replaces the running binary and never restarts the site
|
||||||
|
And the domain package internal/domain/update (stdlib only) gains these interfaces, each faked in tests:
|
||||||
|
AssetFetcher (downloads one asset to a path, reporting bytes done and total),
|
||||||
|
SignatureVerifier (ed25519 check of checksums.txt against checksums.txt.sig with the embedded release.pub),
|
||||||
|
StagedBinaryRunner (runs <path> --version and returns its output),
|
||||||
|
DatabaseBackup (consistent copy of the SQLite file with VACUUM INTO, prune to the last 3),
|
||||||
|
HelperDetector (reports whether the slice 3 helper is installed),
|
||||||
|
JobStore (persists the update job record)
|
||||||
|
And update.Release gains Assets (name, download URL, size) read by the Gitea adapter, and the stored CheckResult keeps
|
||||||
|
them, so POST /v1/system/update/download never contacts the feed
|
||||||
|
And the use cases depend only on domain interfaces; handlers in api/handlers/update receive them through NewHandler;
|
||||||
|
only api/dependecyInjection.go builds the adapters
|
||||||
|
And the job runs in one background goroutine owned by the use case; the HTTP handler returns as soon as it is started
|
||||||
|
And POST /v1/system/update/download is mounted in NewSystemRouter behind jwtauth.Verifier, jwtauth.Authenticator,
|
||||||
|
RequireCurrentToken, RequireVerifiedUser, RequireOwner and its own limiter of 5 starts per minute per user_id
|
||||||
|
(constants, separate from the check limiter and the auth limiter) answering 429 with an integer Retry-After
|
||||||
|
And the checks on POST run in this order: no cookie or stale token (401), unverified (403), not owner (403),
|
||||||
|
limiter (429), can_apply false (409), a job running or already ready (409), available false (400),
|
||||||
|
pre-flight refusal (422), then 202
|
||||||
|
And errors are plain text from http.Error
|
||||||
|
And the data directory is the directory that holds DB_FILE; no new env var is added
|
||||||
|
And the job record is update-job.json in the data directory, shared by all owners and surviving a restart
|
||||||
|
And a job record found as "downloading" or "verifying" at startup (no goroutine owns it) reads as failed with
|
||||||
|
error "download"; a record "ready" whose staged binary is gone reads as idle
|
||||||
|
And the staged files live in <data dir>/updates/<tag>/: the binary, checksums.txt and checksums.txt.sig
|
||||||
|
And the asset to download is named renewcms_<tag>_<runtime.GOOS>_<runtime.GOARCH>, plus ".exe" on windows
|
||||||
|
And the job runs these steps in order: download checksums.txt, checksums.txt.sig and the binary; verify the
|
||||||
|
ed25519 signature of checksums.txt; verify the SHA-256 of the binary against its checksums.txt line; run the
|
||||||
|
staged binary with --version and require the output to equal the tag; back up the database; mark "ready"
|
||||||
|
And state is "downloading" during the downloads and "verifying" from the signature check until "ready"
|
||||||
|
(the version run and the backup happen in "verifying")
|
||||||
|
And the download policy, enforced in the production adapter: the URL must be https, its host (with port) must equal
|
||||||
|
the host of UPDATE_FEED_URL, and every redirect must satisfy the same rule; there is a size cap per file
|
||||||
|
(binary 200 MiB, checksums.txt 64 KiB, checksums.txt.sig 1 KiB) and an overall timeout of 10 minutes (named constants)
|
||||||
|
And in tests the policy is relaxed only through the adapter constructor, which takes the allowed host, an
|
||||||
|
"allow insecure scheme" option, a smaller cap and a shorter timeout; there is no env var or build flag that relaxes it
|
||||||
|
And GET /v1/system/update keeps its 12 keys; state is one of idle, downloading, verifying, ready, failed;
|
||||||
|
progress is {percent, downloaded_bytes, total_bytes} while downloading and null otherwise;
|
||||||
|
error is null, "download" or "verification" (a kind only, never technical text); started_at is the job start
|
||||||
|
And can_apply is true only for the owner when HelperDetector reports the helper installed; it is false for admins
|
||||||
|
And the real HelperDetector reads <data dir>/update-helper.json (the status file the slice 3 helper writes); nothing
|
||||||
|
writes it in this slice, so can_apply is false on real builds until slice 3
|
||||||
|
And disk errors and database backup failures end the job as failed with error "download"
|
||||||
|
And on any failure the staged files are deleted, the technical reason is logged server side, and no response carries it
|
||||||
|
And a failed record stays until the next job starts; ready stays until slice 3 consumes it
|
||||||
|
And the SPA shows the newer release without its leading "v" ("Version 2.3.0-beta") and the running version exactly as reported
|
||||||
|
And the Restart button in "Ready to install" is rendered but disabled in this slice: the board frame draws it as the
|
||||||
|
primary action, it has no handler, and slice 3 enables it; plain Restart (no update waiting) stays not rendered until slice 3
|
||||||
|
|
||||||
|
Scenario: Start the update, happy path
|
||||||
|
Given the owner, can_apply true, a stored result with latest "v2.3.0-beta" (running "v2.2.0-beta", available true)
|
||||||
|
and assets for the host platform, all served by the fake fetcher and signed with a throwaway key
|
||||||
|
When the owner sends POST /v1/system/update/download
|
||||||
|
Then the status is 202 and the body is the status JSON with state "downloading" and started_at set
|
||||||
|
And GET /v1/system/update then reports downloading with progress.total_bytes equal to the asset size
|
||||||
|
And when the job finishes GET reports state "ready", error null, progress null, latest "v2.3.0-beta"
|
||||||
|
And the staged binary, checksums.txt and checksums.txt.sig are in <data dir>/updates/v2.3.0-beta/
|
||||||
|
And a database backup exists in <data dir>/backups/ before state became "ready"
|
||||||
|
And the running binary and the database are unchanged
|
||||||
|
|
||||||
|
Scenario Outline: The asset name follows the platform
|
||||||
|
Given the runtime is <os>/<arch> and the release lists all six binaries
|
||||||
|
When the update starts
|
||||||
|
Then the fetcher is asked for "<asset>", "checksums.txt" and "checksums.txt.sig" only
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| os | arch | asset |
|
||||||
|
| linux | amd64 | renewcms_v2.3.0-beta_linux_amd64 |
|
||||||
|
| linux | arm64 | renewcms_v2.3.0-beta_linux_arm64 |
|
||||||
|
| darwin | arm64 | renewcms_v2.3.0-beta_darwin_arm64 |
|
||||||
|
| windows | amd64 | renewcms_v2.3.0-beta_windows_amd64.exe |
|
||||||
|
|
||||||
|
Scenario: Progress is reported in bytes
|
||||||
|
Given the fake fetcher has delivered 11 of 26 MiB
|
||||||
|
When any verified user sends GET /v1/system/update
|
||||||
|
Then state is "downloading" and progress is {percent: 42, downloaded_bytes: 11534336, total_bytes: 27262976}
|
||||||
|
And percent is the floor of done * 100 / total
|
||||||
|
|
||||||
|
Scenario: Every owner sees the same job
|
||||||
|
Given owner A started the job
|
||||||
|
When owner B and an admin send GET /v1/system/update
|
||||||
|
Then both read state "downloading" with the same progress and started_at
|
||||||
|
And the owner's can_apply is true and the admin's can_apply is false
|
||||||
|
|
||||||
|
Scenario: The job record survives a restart
|
||||||
|
Given the job is "ready" for "v2.3.0-beta" with its staged binary present
|
||||||
|
When a new status use case is built over the same data directory
|
||||||
|
Then GET reports state "ready"
|
||||||
|
And a record "downloading" at startup reads as state "failed", error "download"
|
||||||
|
And a record "ready" with the staged binary deleted reads as "idle"
|
||||||
|
And a missing or corrupt job file reads as "idle" and is not fatal
|
||||||
|
|
||||||
|
Scenario: Only the owner
|
||||||
|
When an admin sends POST /v1/system/update/download
|
||||||
|
Then the status is 403 and the body is apperr.OwnerRequiredErrorMessage
|
||||||
|
And no job starts and the fetcher is not called
|
||||||
|
|
||||||
|
Scenario Outline: POST is guarded like the other system routes
|
||||||
|
When <caller> sends POST /v1/system/update/download
|
||||||
|
Then the status is <status>
|
||||||
|
And no job starts
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| caller | status |
|
||||||
|
| no jwt cookie | 401 |
|
||||||
|
| a stale token version | 401 |
|
||||||
|
| an unverified owner | 403 |
|
||||||
|
|
||||||
|
Scenario: Nothing to update
|
||||||
|
Given a stored result with available false, or no stored result
|
||||||
|
When the owner sends POST /v1/system/update/download
|
||||||
|
Then the status is 400 and no job starts and the fetcher is not called
|
||||||
|
|
||||||
|
Scenario: The server is not prepared
|
||||||
|
Given HelperDetector reports no helper
|
||||||
|
When the owner sends POST /v1/system/update/download
|
||||||
|
Then the status is 409 and no job starts
|
||||||
|
And GET reports can_apply false
|
||||||
|
And this holds even when available is false (409 before 400)
|
||||||
|
|
||||||
|
Scenario Outline: A second start while a job exists
|
||||||
|
Given the job state is <state>
|
||||||
|
When the owner sends POST /v1/system/update/download
|
||||||
|
Then the status is 409 and the existing job is untouched
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state |
|
||||||
|
| downloading |
|
||||||
|
| verifying |
|
||||||
|
| ready |
|
||||||
|
|
||||||
|
Scenario: Two starts at once run one job
|
||||||
|
When two owners send POST /v1/system/update/download concurrently
|
||||||
|
Then exactly one answers 202 and the other 409
|
||||||
|
And the fetcher downloads each asset once
|
||||||
|
|
||||||
|
Scenario: Try again after a failure
|
||||||
|
Given the job state is "failed"
|
||||||
|
When the owner sends POST /v1/system/update/download
|
||||||
|
Then the status is 202, error returns to null, started_at is new and the old staged files are replaced
|
||||||
|
|
||||||
|
Scenario: Start is rate limited per user
|
||||||
|
When the owner sends 6 starts within one minute
|
||||||
|
Then the first 5 are answered by the checks above and the 6th is 429 with apperr.TooManyRequestsErrorMessage
|
||||||
|
and an integer Retry-After of at least 1
|
||||||
|
And a different owner is not limited, and the check limiter and auth limiter counters are untouched
|
||||||
|
|
||||||
|
Scenario Outline: 422 is only a pre-flight refusal
|
||||||
|
Given a stored result where <condition>
|
||||||
|
When the owner sends POST /v1/system/update/download
|
||||||
|
Then the status is 422 and the body is plain text without technical detail
|
||||||
|
And no job starts, the fetcher is not called and the technical reason is logged
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| condition |
|
||||||
|
| no asset is named for the host platform |
|
||||||
|
| checksums.txt or checksums.txt.sig is missing from the assets |
|
||||||
|
| an asset URL is http, not https |
|
||||||
|
| an asset URL is on a host other than UPDATE_FEED_URL's host |
|
||||||
|
|
||||||
|
Scenario Outline: Verification failures end the job as failed, kind "verification"
|
||||||
|
Given a started job and <fault>
|
||||||
|
When the job reaches the check
|
||||||
|
Then GET reports state "failed", error "verification", progress null
|
||||||
|
And <data dir>/updates/<tag>/ is deleted
|
||||||
|
And the technical reason is logged and appears in no response body
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| fault |
|
||||||
|
| the binary was changed after signing (SHA-256 mismatch) |
|
||||||
|
| checksums.txt was changed after signing |
|
||||||
|
| the signature is from a different key |
|
||||||
|
| checksums.txt has no line for the asset |
|
||||||
|
| the staged binary prints "v2.2.9-beta" for --version |
|
||||||
|
| the staged binary cannot be run |
|
||||||
|
|
||||||
|
Scenario Outline: Download and disk failures end the job as failed, kind "download"
|
||||||
|
Given a started job and <fault>
|
||||||
|
Then GET reports state "failed", error "download"
|
||||||
|
And <data dir>/updates/<tag>/ is deleted and the technical reason is logged, not returned
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| fault |
|
||||||
|
| the connection drops after half the bytes (truncated download) |
|
||||||
|
| the bytes received differ from the size the release declares |
|
||||||
|
| a file exceeds its size cap |
|
||||||
|
| the download passes the overall timeout |
|
||||||
|
| the feed host answers 404 or 500 for an asset |
|
||||||
|
| the updates directory cannot be created or written (disk error) |
|
||||||
|
| the disk fills during the write |
|
||||||
|
| the database backup fails |
|
||||||
|
|
||||||
|
Scenario: The backup comes before ready, and the last 3 are kept
|
||||||
|
Given the backups directory holds 3 earlier backups
|
||||||
|
When a job completes
|
||||||
|
Then a new consistent copy exists (opened read-only it holds the same article rows as the live file)
|
||||||
|
And only the 3 newest backups remain, the oldest being deleted
|
||||||
|
And no job is "ready" until the new backup exists
|
||||||
|
And a failed backup leaves state "failed", error "download" and does not prune the earlier backups
|
||||||
|
|
||||||
|
Scenario: The production download policy
|
||||||
|
Given the production adapter with UPDATE_FEED_URL "https://git.example"
|
||||||
|
Then an http:// asset URL, an https URL on another host, and a redirect to another host or to http are refused
|
||||||
|
And an https URL on git.example is accepted
|
||||||
|
|
||||||
|
Scenario: A server --version flag
|
||||||
|
When the server binary is run with --version
|
||||||
|
Then it prints the build version and exits 0
|
||||||
|
And it does not read .env, open the database or start listening
|
||||||
|
And with no -ldflags version it prints "dev"
|
||||||
|
|
||||||
|
Scenario: Settings, owner, Update available with the helper detected (route /settings)
|
||||||
|
Given the owner and GET /v1/system/update resolves available true, can_apply true, state "idle", latest "v2.3.0-beta"
|
||||||
|
Then the block shows icon circle-arrow-up (info), "Version 2.3.0-beta is available" /
|
||||||
|
"You have v2.2.0-beta. Update downloads the new version and checks it. Nothing changes until you restart."
|
||||||
|
and the meta "Last checked ..."
|
||||||
|
And the notes button "What's new in 2.3.0-beta" is collapsed, and when open shows "Released 24 Sep 2026" and the list
|
||||||
|
And the one button is "Update" (download, primary) and the hint is "Takes about 2 minutes. Your site stays online."
|
||||||
|
And no server command, no "How to update" link, no Restart and no "Check for updates" is rendered
|
||||||
|
|
||||||
|
Scenario: Settings, owner, Downloading
|
||||||
|
When the owner presses "Update" and POST /v1/system/update/download answers 202
|
||||||
|
Then the block shows icon download (info), "Downloading version 2.3.0-beta…" /
|
||||||
|
"You can leave this page. The download continues and your site stays online."
|
||||||
|
And a progressbar labelled "Downloading version 2.3.0-beta" has aria-valuenow equal to progress.percent
|
||||||
|
and the text "42% · 11 of 26 MB"
|
||||||
|
And the button reads "Updating…" (loader-circle, secondary) and is disabled
|
||||||
|
And GET /v1/system/update is polled every second while state is downloading or verifying
|
||||||
|
|
||||||
|
Scenario: Settings, progress is announced at 25 percent steps only
|
||||||
|
Given the polled percent goes 3, 9, 24, 25, 26, 49, 50, 74, 75, 99, 100
|
||||||
|
Then the announcer text changes only at 25, 50, 75 and the step change, reading
|
||||||
|
"Downloading version 2.3.0-beta, 25 percent" and so on
|
||||||
|
And the visible text and aria-valuenow still update on every poll
|
||||||
|
And the live region does not announce the per-tick text
|
||||||
|
|
||||||
|
Scenario: Settings, owner, Verifying
|
||||||
|
Given the poll answers state "verifying"
|
||||||
|
Then the block shows icon shield-check (info), "Checking the download…" /
|
||||||
|
"Making sure the file is complete and safe to install. This takes a few seconds."
|
||||||
|
And the progressbar is indeterminate (no aria-valuenow, a 35% wide moving bar) labelled "Checking the download"
|
||||||
|
with the text "Almost there"
|
||||||
|
And the button reads "Updating…" and is disabled
|
||||||
|
And "Checking the download" is announced once, when the step changes
|
||||||
|
|
||||||
|
Scenario: Settings, owner, Ready to install
|
||||||
|
Given the poll answers state "ready"
|
||||||
|
Then polling stops
|
||||||
|
And the block shows icon circle-check (success), "Version 2.3.0-beta is ready to install" /
|
||||||
|
"The download is checked. Restart to install it. Your site will be unavailable for about 10 seconds." /
|
||||||
|
"Nothing has changed yet."
|
||||||
|
And the notes button is shown collapsed
|
||||||
|
And the Restart button (power, primary) is rendered with disabled set and 40% opacity, and activating it does nothing
|
||||||
|
And the hint is "Not now? Leave this page. The update waits here, and the banner on Home reminds you."
|
||||||
|
And no dialog, overlay or POST /v1/system/update/restart exists
|
||||||
|
|
||||||
|
Scenario: Settings, Download failed
|
||||||
|
Given the poll answers state "failed" with error "download", or POST download answers 500 or never reaches the server
|
||||||
|
Then focus moves to the "Updates" heading (id="updates-h")
|
||||||
|
And the block shows icon circle-x (error), "The download didn't finish" /
|
||||||
|
"The connection dropped before the file was complete. Nothing was changed and your site is running as before."
|
||||||
|
And the one button is "Try again" (rotate-cw, primary), which sends POST /v1/system/update/download
|
||||||
|
|
||||||
|
Scenario: Settings, Verification failed
|
||||||
|
Given the poll answers state "failed" with error "verification", or POST download answers 422
|
||||||
|
Then the block shows icon triangle-alert (warning), "We didn't use this update" /
|
||||||
|
"The file didn't pass our safety check, so it was not installed. Nothing was changed. Try downloading it again. If this keeps happening, contact RenewCMS support."
|
||||||
|
And the one button is "Try again" (rotate-cw, primary), as the board frame draws it
|
||||||
|
And focus does not move to the heading
|
||||||
|
And no technical detail is on screen
|
||||||
|
|
||||||
|
Scenario: Settings, 409 already running
|
||||||
|
Given POST /v1/system/update/download answers 409 and the reload answers state "downloading" or "verifying"
|
||||||
|
Then an info toast "An update is already running" / "Another owner started it. Progress shows here." shows
|
||||||
|
And the card switches to that run's progress and polls
|
||||||
|
When the reload instead answers can_apply false
|
||||||
|
Then the card shows the "Not prepared" state and no toast
|
||||||
|
When the reload instead answers state "ready"
|
||||||
|
Then the card shows "Ready to install" and no toast
|
||||||
|
|
||||||
|
Scenario: Settings, 400 nothing to update
|
||||||
|
Given POST /v1/system/update/download answers 400
|
||||||
|
Then an info toast "Nothing to update" / "You already have the latest version." shows
|
||||||
|
And the card reloads GET /v1/system/update
|
||||||
|
|
||||||
|
Scenario: Settings, 403 role changed on Update
|
||||||
|
Given POST /v1/system/update/download answers 403
|
||||||
|
Then an error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." shows
|
||||||
|
And the card reloads and renders the admin view
|
||||||
|
|
||||||
|
Scenario: Settings, 429 on Update
|
||||||
|
Given POST /v1/system/update/download answers 429 with Retry-After 42
|
||||||
|
Then the block shows icon info "Too many tries" / "Wait a moment before trying again."
|
||||||
|
And the button reads "Try again in 0:42" (clock, disabled) and counts down each second through useRetryAfter
|
||||||
|
And at zero it is re-enabled as "Try again" and pressing it sends POST /v1/system/update/download again
|
||||||
|
|
||||||
|
Scenario: Settings, reload keeps progress
|
||||||
|
Given a job is downloading and the owner leaves /settings
|
||||||
|
Then polling stops and the job continues on the server
|
||||||
|
When the owner opens /settings again, from this or another device
|
||||||
|
Then GET /v1/system/update is read on open and the card shows the job's current state and progress
|
||||||
|
And polling resumes while state is downloading or verifying
|
||||||
|
|
||||||
|
Scenario: Settings, a poll that fails keeps the card
|
||||||
|
Given a poll answers 500 or never reaches the server while downloading
|
||||||
|
Then the card keeps its last progress, no failure card shows, and polling continues each second
|
||||||
|
|
||||||
|
Scenario: Settings, admin view during a job
|
||||||
|
Given the session role is "admin" and state is "downloading"
|
||||||
|
Then the admin view of slice 1 shows ("Version 2.3.0-beta is available" / "You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site.")
|
||||||
|
And no button, progressbar or poll is rendered
|
||||||
|
|
||||||
|
Scenario: Home banner, ready to install (owner)
|
||||||
|
Given the owner is on /home and state is "ready"
|
||||||
|
Then a region labelled "Update available" shows above the content in info tone (as the board frame draws it)
|
||||||
|
with icon circle-check, title "Version 2.3.0-beta is ready to install",
|
||||||
|
text "Restart from Settings to finish. The site is unavailable for about 10 seconds.",
|
||||||
|
a "Go to Settings" button that navigates to /settings, and a Dismiss button
|
||||||
|
And it shows although the "available" banner for this version was dismissed earlier
|
||||||
|
When the owner dismisses it
|
||||||
|
Then it hides for this visit only and shows again on the next visit, and nothing is written to localStorage
|
||||||
|
And an admin sees no banner; with state "downloading" or "verifying" the "available" banner shows as before
|
||||||
|
|
||||||
|
Scenario: Pending states for slice 3
|
||||||
|
Then these remain pending in the visual gate, never passing: Restart confirm, Restart request failed, Restarting to install,
|
||||||
|
Restarting taking longer, Update done, Rolled back, Plain restart (confirm, restarting, done)
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
# QA: Updates part 2 (download, verify, stage)
|
||||||
|
|
||||||
|
## Automated Go (`task test`, package `test`, black-box, no live network, no real SMTP)
|
||||||
|
|
||||||
|
Files: `test/update_download_test.go` (domain, use case), `test/update_download_http_test.go` (HTTP),
|
||||||
|
`test/update_assets_test.go` (production download adapter against a local server). Fakes with unique names:
|
||||||
|
`fakeAssetFetcher` (serves bytes, can truncate, stall, fail, counts calls), `fakeHelperDetector`, `fakeJobStore`,
|
||||||
|
`fakeStagedRunner` (returns a configured --version output or error), `fakeDatabaseBackup`; reuse `fakeReleaseFeed`,
|
||||||
|
`fakeUpdateStore` and `mockUserRepo` from the slice 1 tests.
|
||||||
|
|
||||||
|
HTTP setup: `validator.InitValidator()`; `token := jwtauth.New("HS256", []byte("test-secret"), nil)`; a fresh `chi.NewRouter()` at
|
||||||
|
`/v1/system` mirroring `NewSystemRouter` (Verifier, Authenticator, RequireCurrentToken, RequireVerifiedUser; the download
|
||||||
|
route also RequireOwner and its limiter, 5 per minute); cookies as in `test/stale_token_invalidation_http_test.go`.
|
||||||
|
Job state, staged files and backups go in `t.TempDir()`. Wait for the job with a poll loop on GET (deadline 5 s), never a bare
|
||||||
|
`time.Sleep`. Use a throwaway ed25519 key generated in the test and sign `checksums.txt` with it; never read the committed
|
||||||
|
`release.pub`.
|
||||||
|
|
||||||
|
Local asset server: `httptest.NewServer` (plain HTTP) and `httptest.NewTLSServer` for the policy cases. The production adapter is
|
||||||
|
built through its constructor with the test's allowed host, allow-insecure true for the plain server, the TLS server's client for
|
||||||
|
the TLS cases, a small size cap and a short timeout. Never relax the policy by env var or build flag.
|
||||||
|
|
||||||
|
1. Happy path: owner POST gives 202 with state "downloading"; poll GET until "ready"; files in `updates/<tag>/`, one backup in
|
||||||
|
`backups/`; running binary unchanged; the fetcher was asked for exactly the three asset names.
|
||||||
|
2. Asset naming table over GOOS/GOARCH (including the `.exe` case). Inject the platform into the use case; never assert on the
|
||||||
|
test machine's own platform.
|
||||||
|
3. Progress: a fetcher paused at 11 of 26 MiB gives `{percent:42, downloaded_bytes, total_bytes}` on GET; `progress` is null in
|
||||||
|
verifying, ready and failed; `error` is null until a failure.
|
||||||
|
4. Shared state: GET as owner A, owner B and admin agree; admin `can_apply` false, owner true with the fake detector on.
|
||||||
|
5. Persistence: JSON job store round trip in a temp dir; "downloading" at startup reads failed/"download"; "ready" with the staged
|
||||||
|
binary deleted reads idle; a missing or corrupt file reads idle without error. The real helper detector reads
|
||||||
|
`<data dir>/update-helper.json`: absent file gives false, a present valid file gives true.
|
||||||
|
6. Guards: admin 403 with `apperr.OwnerRequiredErrorMessage+"\n"`; no cookie 401; stale token 401; unverified 403; none start a job.
|
||||||
|
7. Status codes: available false or nothing stored gives 400; detector off gives 409; state downloading, verifying, ready each give
|
||||||
|
409; after "failed" a new POST gives 202 with a new started_at. Order check: detector off and available false gives 409.
|
||||||
|
8. Concurrency: two simultaneous POSTs (goroutines) give one 202 and one 409; each asset fetched once (run with `-race`).
|
||||||
|
9. Rate limit: owner A sends 6 POSTs within a minute; the 6th is 429 with `apperr.TooManyRequestsErrorMessage+"\n"` and an integer
|
||||||
|
Retry-After >= 1; owner B is unaffected; the check limiter and a login limiter built in the test are untouched.
|
||||||
|
10. 422 pre-flight: each of the four conditions in the feature gives 422, the body is plain text with no URL, host or file name from
|
||||||
|
the fixture, no job record is created, fetcher count is 0, and the reason is captured from an injected logger.
|
||||||
|
11. Verification failures, one subtest per row, each ending with GET `state` "failed", `error` "verification", `updates/<tag>/`
|
||||||
|
removed, a body free of the fault text, and the fault text present in the injected logger: tampered binary, tampered
|
||||||
|
checksums.txt, signature from another key, no checksum line for the asset, wrong `--version` output, runner error.
|
||||||
|
12. Download failures, one subtest per row, each ending "failed", `error` "download", directory removed: truncated body, size
|
||||||
|
mismatch with the release, over the size cap, timeout (server stalls; adapter timeout shortened), 404/500, unwritable updates
|
||||||
|
directory (a file placed where the directory should be), disk full (a writer fake returning an error mid-write), backup failure
|
||||||
|
(earlier backups not pruned).
|
||||||
|
13. Backup: with the real SQLite backup adapter against a SQLite file created in `t.TempDir()` (pure-Go driver, `CGO_ENABLED=0`):
|
||||||
|
the copy opens and holds the same rows, four jobs leave only the 3 newest files, and a job is not "ready" before the copy exists.
|
||||||
|
14. Production policy: http URL, another host, redirect to another host and redirect to http are refused (no request reaches the
|
||||||
|
second server); the TLS server on the allowed host is accepted.
|
||||||
|
15. `--version`: build with `go build -tags nofrontend -ldflags "-X main.version=v9.9.9" ./cmd/server` into `t.TempDir()` and run
|
||||||
|
it with `--version` and an empty environment: stdout `v9.9.9`, exit 0, no `data/` created; without ldflags it prints `dev`.
|
||||||
|
16. Review items, not Go tests: `internal/domain/update` imports only the stdlib; use cases import no `net/http`, `os/exec`, `gorm`
|
||||||
|
or adapter; the handler imports no adapter; no secret value is in the repo; the helper detector reads only its status file.
|
||||||
|
|
||||||
|
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `useApi.request` for `GET /v1/system/update`, `POST /v1/system/update/check` and `POST /v1/system/update/download`. Fake timers
|
||||||
|
drive the 1 s poll and the countdown. No test freezes the system date and none asserts a relative date. Reuse the board's data:
|
||||||
|
running `v2.2.0-beta`, latest `v2.3.0-beta`, 26 MB total, 11 MB done (42 %), released 24 Sep 2026.
|
||||||
|
|
||||||
|
One test per state:
|
||||||
|
1. Update available, can_apply true: copy, notes collapsed, only "Update", hint; no command, no link, no Restart.
|
||||||
|
2. Update available, notes open (`aria-expanded`, "Released 24 Sep 2026").
|
||||||
|
3. Downloading: 202 then the card copy, progressbar label, `aria-valuenow` 42, "42% · 11 of 26 MB", "Updating…" disabled; GET called once per second.
|
||||||
|
4. Announcements: percents 3, 24, 25, 26, 49, 50, 75, 100; the announcer text changes only at 25, 50, 75 and the step change;
|
||||||
|
`aria-valuenow` changes on each tick.
|
||||||
|
5. Verifying: indeterminate bar (no `aria-valuenow`), "Almost there", announced once.
|
||||||
|
6. Ready: copy, meta, hint, Restart present with `disabled` and no request on click, notes button, polling stopped.
|
||||||
|
7. Download failed (state failed/download; a 500; a `NetworkError`): copy, focus on `#updates-h`, "Try again" posts download again.
|
||||||
|
8. Verification failed (state failed/verification; a 422): copy, "Try again", focus not moved, no technical text.
|
||||||
|
9. 409: reload downloading gives the info toast and progress; reload ready gives no toast and the Ready card; reload can_apply false
|
||||||
|
gives the Not prepared card.
|
||||||
|
10. 400: info toast "Nothing to update" and one GET.
|
||||||
|
11. 403: error toast and the admin view after reload.
|
||||||
|
12. 429: "Too many tries", "Try again in 0:42" counting down through `useRetryAfter`, re-enabled as "Try again" and it re-posts
|
||||||
|
download (not check).
|
||||||
|
13. Reload: unmount stops the poll; mount reads GET and resumes the poll for a running state; no poll for idle, ready or failed.
|
||||||
|
14. A failed poll keeps the last progress and keeps polling.
|
||||||
|
15. Admin with state downloading: admin copy, no button, no progressbar, no poll.
|
||||||
|
16. Home banner ready: info tone, copy, `role="region"` labelled "Update available", "Go to Settings" navigates, shows although the
|
||||||
|
available banner was dismissed, Dismiss hides until remount and writes nothing to localStorage; admin sees none.
|
||||||
|
17. Sidebar pill and mobile dot stay for ready, downloading and verifying (owner only, `available` true).
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- settings` and `-- home`; desktop and mobile, light and dark; every capture within 10 %)
|
||||||
|
|
||||||
|
Add the setups to `web/visual/states.ts` with the board's sample data (v2.2.0-beta, v2.3.0-beta, 42 % / "11 of 26 MB"). Exact values
|
||||||
|
from `docs/design/source/AppFrame.dc.html` and the "Settings" and "Home" groups of the Screens board; layout as drawn.
|
||||||
|
|
||||||
|
- [ ] Settings: Update available, Update available (notes open), Downloading (42 %), Verifying, Ready to install,
|
||||||
|
Download failed, Verification failed. The frame draws an enabled Restart; the disabled one (40 % opacity) must still be
|
||||||
|
within budget. If it is not, stop and report; do not widen the budget or add an exception without the user's approval.
|
||||||
|
- [ ] Home: Update ready to install (owner), with the sidebar pill and the mobile dot as drawn.
|
||||||
|
- [ ] Settings: Update already running (409): the frame shows the card in progress; set up with the mocked 409 then the
|
||||||
|
downloading reload (the toast only if the frame draws it; check the markup).
|
||||||
|
- [ ] `skip: 'clock-sensitive'`: any state whose meta line is relative ("Last checked today at 09:41"), as in slice 1.
|
||||||
|
- [ ] Pending, never passing (slice 3): Restart confirm, Restart request failed, Restarting, Restarting taking longer,
|
||||||
|
Update done, Rolled back, Plain restart (confirm, restarting, done).
|
||||||
|
- [ ] Not covered by screenshots: keyboard and focus order, the focus ring on `#updates-h` after Download failed, the 25 %
|
||||||
|
announcements (screen reader), hover and motion of the indeterminate bar.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- `can_apply` stays false on real builds until slice 3 writes `<data dir>/update-helper.json`: use the fake in tests, or place the
|
||||||
|
file by hand to see the Update button.
|
||||||
|
- Against a real signed release on the real feed host (needs `release.pub` replaced and `task release` signing): press Update, watch
|
||||||
|
progress, the Verifying step and the Ready card; check `<data dir>/updates/<tag>/` and one file in `<data dir>/backups/`.
|
||||||
|
- The real staged binary on the target OS runs `--version` and prints the tag.
|
||||||
|
- Flip one byte of a asset on a test mirror: the card shows "We didn't use this update" and the folder is gone.
|
||||||
|
- Kill the server mid-download and restart it: the card shows "The download didn't finish".
|
||||||
|
- Open the card in two browsers (two owners) and confirm the same progress; the second press shows the 409 toast.
|
||||||
|
- Embedded SPA build (no `-tags nofrontend`) serves /settings and /home with the new states.
|
||||||
|
- Confirm no secret or feed credential appears in logs, and that technical failure reasons are in the log only.
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
Feature: Updates part 1: signed releases, release feed and read-only update notification
|
||||||
|
|
||||||
|
As the owner of a RenewCMS site
|
||||||
|
I want to see when a newer signed release exists, and have admins see the same status read-only
|
||||||
|
So that I know when to update, while downloading and restarting arrive in later slices
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given slices 1 to 3 of Updates ship in one release, so no released build shows the command
|
||||||
|
"renewcms enable-browser-updates" before it exists (it is implemented in slice 3)
|
||||||
|
And every release is published as a Gitea prerelease with the six binaries, checksums.txt and checksums.txt.sig
|
||||||
|
And cmd/releasesign is a stdlib-only tool (crypto/ed25519, no new dependency) with the commands
|
||||||
|
keygen <private-key-path> [--pub-out <path>], sign <file> [--key <path>] [--pub <path>],
|
||||||
|
verify <file> [--pub <path>]
|
||||||
|
And keygen writes the private key to the path given and refuses a path inside the repository work tree
|
||||||
|
And sign and verify use the embedded public key unless --pub is given; tests always pass --pub with a throwaway key
|
||||||
|
And sign refuses to sign when the private key does not match the public key, naming the mismatch
|
||||||
|
And the public key is internal/infrastructure/update/release.pub, embedded with go:embed
|
||||||
|
And until the user runs task release:keygen and commits the real public key, release.pub holds the placeholder:
|
||||||
|
the base64 of 32 zero bytes (AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=); an all-zero key is recognised
|
||||||
|
as the placeholder, and sign and verify refuse it with a clear message
|
||||||
|
And the real private key is generated by the user outside the repo; the coder never generates or commits it
|
||||||
|
And task release writes checksums.txt (SHA-256 of every binary) next to the binaries and signs it into
|
||||||
|
checksums.txt.sig with the private key at the path in the env var RELEASE_SIGNING_KEY
|
||||||
|
And task release fails clearly, before building anything, when RELEASE_SIGNING_KEY is unset, the file is missing,
|
||||||
|
the embedded key is the placeholder, or the private key does not match the embedded public key
|
||||||
|
And task release:keygen creates the one-time key pair and prints where to commit the public key
|
||||||
|
And docs/release-notes.md gains the publish step (attach checksums.txt and checksums.txt.sig with the six binaries),
|
||||||
|
docs/deployment.md and docs/configuration.md are updated, and nothing is published
|
||||||
|
And the domain package internal/domain/update (stdlib only) holds Release, ReleaseNotes, version comparison,
|
||||||
|
UpdateStatus, the ReleaseFeed interface, the StatusStore interface and the Err sentinels
|
||||||
|
And the Gitea adapter lives under internal/infrastructure/update and implements update.ReleaseFeed with
|
||||||
|
var _ update.ReleaseFeed = &X{}; it requests GET {UPDATE_FEED_URL}/api/v1/repos/fsylvain/RenewCMS/releases
|
||||||
|
(the list, not "latest")
|
||||||
|
And UPDATE_FEED_URL is in requiredEnvVars/envDefaults, .env.example and docs/configuration.md, defaulting to the repo base URL
|
||||||
|
And a JSON file store implements update.StatusStore and keeps the last result and checked_at in update-status.json
|
||||||
|
beside DB_FILE, shared by all owners and surviving a restart; no new env var is added
|
||||||
|
And GetUpdateStatusUseCase and CheckForUpdateUseCase depend only on the domain interfaces; handlers in
|
||||||
|
api/handlers/update receive them through NewHandler; api/dependecyInjection.go builds the adapters
|
||||||
|
And NewSystemRouter is mounted at /v1/system behind jwtauth.Verifier, jwtauth.Authenticator, RequireCurrentToken
|
||||||
|
and RequireVerifiedUser; POST /update/check also sits behind RequireOwner and a limiter of 5 checks per minute
|
||||||
|
per user_id (constants, not env vars, separate from the auth limiter) that answers 429 with an integer Retry-After
|
||||||
|
And GET /v1/system/update returns 200 with JSON of exactly these snake_case keys: current, latest, available,
|
||||||
|
release_url, notes {version, released_at, items}, checked_at, can_apply, state, progress, error, started_at
|
||||||
|
And release_url is the release's html_url, null when never checked; in slice 3 the "How to update" link is
|
||||||
|
repointed at the "Browser updates" section of docs/deployment.md
|
||||||
|
And in this slice can_apply is always false and state is always "idle"; never-checked values are latest "",
|
||||||
|
available false, release_url null, notes null, checked_at null, progress null, error null, started_at null
|
||||||
|
And versions compare numerically per segment, a final release beats a beta of the same number, and the
|
||||||
|
running build "dev" never reports an update
|
||||||
|
And release notes are the release body converted to a plain-text list of items
|
||||||
|
And the API returns raw tags; the SPA shows the newer release without its leading "v" ("Version 2.3.0-beta")
|
||||||
|
and the running version exactly as reported
|
||||||
|
And the download and restart endpoints are not mounted; ReleaseFeed, StatusStore and UpdateStatus are shaped so
|
||||||
|
slices 2 and 3 only add use cases
|
||||||
|
And errors are plain text from http.Error
|
||||||
|
|
||||||
|
Scenario Outline: Version comparison
|
||||||
|
Given the running version is "<current>" and the newest feed release is "<latest>"
|
||||||
|
When the versions are compared
|
||||||
|
Then available is <available>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| current | latest | available |
|
||||||
|
| v2.2.0-beta | v2.3.0-beta | true |
|
||||||
|
| v2.5.0-beta | v2.5.0 | true |
|
||||||
|
| v2.5.0 | v2.5.0-beta | false |
|
||||||
|
| v2.9.0 | v2.10.0 | true |
|
||||||
|
| v2.5.0-beta | v2.5.0-beta | false |
|
||||||
|
| v2.5.0 | v2.4.9 | false |
|
||||||
|
| dev | v9.9.9 | false |
|
||||||
|
|
||||||
|
Scenario: The newest release is chosen from the list regardless of feed order
|
||||||
|
Given the feed list holds v2.4.0-beta, v2.5.0-beta and v2.3.0-beta, all marked prerelease
|
||||||
|
When the feed is read
|
||||||
|
Then the latest release is v2.5.0-beta
|
||||||
|
|
||||||
|
Scenario: Drafts are ignored
|
||||||
|
Given the feed list holds a draft release v9.0.0 and a published v2.5.0-beta
|
||||||
|
When the feed is read
|
||||||
|
Then the latest release is v2.5.0-beta
|
||||||
|
|
||||||
|
Scenario: Release notes become a plain-text list
|
||||||
|
Given a release body "## What's new\n- **Media** library\n- Fixed [caching](http://x) bug\n\n* Faster start"
|
||||||
|
When the notes are built
|
||||||
|
Then notes.items is ["Media library","Fixed caching bug","Faster start"]
|
||||||
|
And notes.released_at is the release's published date
|
||||||
|
|
||||||
|
Scenario: GET returns the idle shape, never applicable
|
||||||
|
Given a verified user, running version "v2.2.0-beta", and a stored result with latest "v2.3.0-beta",
|
||||||
|
html_url "https://git.example/fsylvain/RenewCMS/releases/tag/v2.3.0-beta" and checked_at 2026-09-30T09:41:00Z
|
||||||
|
When the client sends GET /v1/system/update
|
||||||
|
Then the status is 200 and the body has exactly the 12 keys
|
||||||
|
And current is "v2.2.0-beta", latest is "v2.3.0-beta", available is true, can_apply is false, state is "idle"
|
||||||
|
And release_url is the stored html_url and checked_at is "2026-09-30T09:41:00Z"
|
||||||
|
And the feed is not contacted
|
||||||
|
|
||||||
|
Scenario: GET before any check
|
||||||
|
Given no stored result
|
||||||
|
When a verified user sends GET /v1/system/update
|
||||||
|
Then the status is 200, available is false, latest is "", release_url, notes and checked_at are null, state is "idle"
|
||||||
|
|
||||||
|
Scenario Outline: GET is open to any verified user
|
||||||
|
Given the caller is <role> with a valid jwt cookie
|
||||||
|
When the client sends GET /v1/system/update
|
||||||
|
Then the status is 200
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| role |
|
||||||
|
| owner |
|
||||||
|
| admin |
|
||||||
|
|
||||||
|
Scenario: GET without a cookie
|
||||||
|
When the client sends GET /v1/system/update with no jwt cookie
|
||||||
|
Then the status is 401
|
||||||
|
|
||||||
|
Scenario: GET with a stale token
|
||||||
|
Given the jwt cookie was minted with a token version older than the account's
|
||||||
|
When the client sends GET /v1/system/update
|
||||||
|
Then the status is 401 and the body is apperr.UnauthorizedErrorMessage
|
||||||
|
|
||||||
|
Scenario: GET by an unverified account
|
||||||
|
When an unverified user with a valid cookie sends GET /v1/system/update
|
||||||
|
Then the status is 403 and the body is apperr.VerificationRequiredErrorMessage
|
||||||
|
|
||||||
|
Scenario: The owner checks and the result is stored
|
||||||
|
Given the fake feed returns v2.3.0-beta and the running version is "v2.2.0-beta"
|
||||||
|
When the owner sends POST /v1/system/update/check
|
||||||
|
Then the status is 200 with the same body shape as GET and available true
|
||||||
|
And the fake store holds latest "v2.3.0-beta" and checked_at at the check time
|
||||||
|
And a later GET returns the same result without contacting the feed
|
||||||
|
|
||||||
|
Scenario: A check with nothing newer
|
||||||
|
Given the feed returns v2.2.0-beta and the running version is "v2.2.0-beta"
|
||||||
|
When the owner sends POST /v1/system/update/check
|
||||||
|
Then the status is 200 and available is false
|
||||||
|
|
||||||
|
Scenario: A dev build never reports an update
|
||||||
|
Given the running version is "dev" and the feed returns v9.9.9
|
||||||
|
When the owner sends POST /v1/system/update/check
|
||||||
|
Then the status is 200 and available is false
|
||||||
|
|
||||||
|
Scenario: An admin cannot check
|
||||||
|
Given the caller is an admin
|
||||||
|
When the client sends POST /v1/system/update/check
|
||||||
|
Then the status is 403 and the body is apperr.OwnerRequiredErrorMessage
|
||||||
|
And the feed is not contacted
|
||||||
|
|
||||||
|
Scenario: Feed failure keeps the last result
|
||||||
|
Given the store holds latest "v2.3.0-beta" checked at 2026-09-30T09:41:00Z and the feed returns an error
|
||||||
|
When the owner sends POST /v1/system/update/check
|
||||||
|
Then the status is 500
|
||||||
|
And the store still holds the previous result and checked_at
|
||||||
|
And no feed error detail appears in the body
|
||||||
|
|
||||||
|
Scenario: Check is rate limited per user
|
||||||
|
When the owner sends 6 checks within one minute
|
||||||
|
Then the first 5 answer 200 and the 6th answers 429 with apperr.TooManyRequestsErrorMessage and an integer Retry-After
|
||||||
|
And the feed is contacted 5 times
|
||||||
|
And a different owner is not limited by the first owner's checks
|
||||||
|
And the auth limiter's counters are untouched
|
||||||
|
|
||||||
|
Scenario: The stored result survives a restart
|
||||||
|
Given the JSON file store saved a result
|
||||||
|
When a new store is opened on the same file
|
||||||
|
Then the same latest, release_url and checked_at are returned
|
||||||
|
And a missing or corrupt file reads as "no result" and is not fatal
|
||||||
|
|
||||||
|
Scenario: Release signing round trip with a throwaway key
|
||||||
|
Given a key pair made by keygen at a path outside the repo
|
||||||
|
When sign is run on checksums.txt with that key and verify with its public key
|
||||||
|
Then verify exits 0
|
||||||
|
And after one byte of checksums.txt changes, verify exits non-zero with a clear message
|
||||||
|
And verify with a different public key exits non-zero
|
||||||
|
|
||||||
|
Scenario: keygen refuses a path inside the repository
|
||||||
|
When keygen is given a path inside the work tree
|
||||||
|
Then it exits non-zero, writes nothing and says why
|
||||||
|
|
||||||
|
Scenario: The placeholder public key is refused
|
||||||
|
Given release.pub holds the placeholder (32 zero bytes, base64)
|
||||||
|
When sign or verify uses the embedded key
|
||||||
|
Then it exits non-zero with a message that the placeholder key has not been replaced
|
||||||
|
|
||||||
|
Scenario: sign refuses a private key that does not match the public key
|
||||||
|
Given a private key whose public half differs from the public key in use
|
||||||
|
When sign is run
|
||||||
|
Then it exits non-zero naming the mismatch and writes no .sig file
|
||||||
|
|
||||||
|
Scenario Outline: task release refuses to sign
|
||||||
|
Given <condition>
|
||||||
|
When task release is run
|
||||||
|
Then it fails before building any binary with a message naming <what>
|
||||||
|
And nothing is published
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| condition | what |
|
||||||
|
| RELEASE_SIGNING_KEY is unset | RELEASE_SIGNING_KEY |
|
||||||
|
| RELEASE_SIGNING_KEY points to a missing file | the missing path |
|
||||||
|
| the embedded public key is the placeholder | the placeholder key |
|
||||||
|
| the private key does not match the public key | the key mismatch |
|
||||||
|
|
||||||
|
Scenario: Settings, owner, Up to date (route /settings)
|
||||||
|
Given the session role is "owner" and GET /v1/system/update resolves available false with checked_at set
|
||||||
|
When the owner opens /settings
|
||||||
|
Then the Updates card shows the status block with icon circle-check (success), title "You're up to date",
|
||||||
|
text "You have the latest version of RenewCMS." and a meta line "Last checked ..." built from checked_at
|
||||||
|
And the only button is "Check for updates" (refresh-cw, secondary)
|
||||||
|
And no Restart button, hint or progress is rendered
|
||||||
|
|
||||||
|
Scenario: Settings, owner, Checking
|
||||||
|
When the owner presses "Check for updates"
|
||||||
|
Then the block shows icon loader-circle, "Checking for updates…" / "This usually takes a few seconds."
|
||||||
|
in a polite live region
|
||||||
|
And the button reads "Checking…" and is disabled
|
||||||
|
And POST /v1/system/update/check is sent once
|
||||||
|
|
||||||
|
Scenario: Settings, owner, Check failed
|
||||||
|
Given POST /v1/system/update/check answers 500 or never reaches the server
|
||||||
|
Then the block shows icon wifi-off (warning), "Couldn't check for updates" /
|
||||||
|
"RenewCMS couldn't reach the update server. Check your connection and try again. Your site isn't affected."
|
||||||
|
and the meta "Last checked ..." from the kept result
|
||||||
|
And the only button is "Try again" (rotate-cw, primary)
|
||||||
|
|
||||||
|
Scenario: Settings, owner, newer version, not prepared
|
||||||
|
Given the session role is "owner" and GET /v1/system/update resolves available true, can_apply false, latest "v2.3.0-beta"
|
||||||
|
When the owner opens /settings
|
||||||
|
Then the block shows icon info, "Version 2.3.0-beta is available" /
|
||||||
|
"This site can't update itself from the browser yet. Whoever manages your server can set it up once, or update RenewCMS for you."
|
||||||
|
And "For whoever manages the server" shows the one-line code "renewcms enable-browser-updates" with a Copy button
|
||||||
|
And the note "They run this once on the server. After that, Update and Restart appear here." shows
|
||||||
|
And the link "How to update" (arrow-up-right) opens release_url in a new tab
|
||||||
|
And no button other than Copy is rendered: not Update, not Restart, not even Check for updates
|
||||||
|
|
||||||
|
Scenario: Settings, owner, newer version, notes open
|
||||||
|
Given the same state with notes.items and notes.released_at 2026-09-24
|
||||||
|
When the owner activates "What's new in 2.3.0-beta" (a button with aria-expanded false then true)
|
||||||
|
Then "Released 24 Sep 2026" and the plain-text list show, and activating it again collapses them
|
||||||
|
And the notes are collapsed by default
|
||||||
|
|
||||||
|
Scenario: Settings, command copied
|
||||||
|
When the owner presses Copy
|
||||||
|
Then the button reads "Copied" with a check for 2 s, is announced, then reads "Copy" again
|
||||||
|
|
||||||
|
Scenario: Settings, admin view
|
||||||
|
Given the session role is "admin"
|
||||||
|
When GET /v1/system/update resolves available true with latest "v2.3.0-beta"
|
||||||
|
Then the card shows "Version 2.3.0-beta is available" /
|
||||||
|
"You have v2.2.0-beta. Only the owner can update RenewCMS. Ask the owner of this site." and no button
|
||||||
|
When it resolves available false
|
||||||
|
Then the card shows "You're up to date" / "Only the owner can update or restart the site." and no button
|
||||||
|
|
||||||
|
Scenario: Settings, Role changed (403)
|
||||||
|
Given an owner is on /settings and POST /v1/system/update/check answers 403
|
||||||
|
Then an error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." shows
|
||||||
|
And the card reloads GET /v1/system/update and renders the admin view
|
||||||
|
|
||||||
|
Scenario: Settings, Too many requests (429)
|
||||||
|
Given POST /v1/system/update/check answers 429 with Retry-After 42
|
||||||
|
Then the block shows icon info "Too many tries" / "Wait a moment before trying again."
|
||||||
|
And the button reads "Try again in 0:42", counts down each second and is re-enabled at zero
|
||||||
|
|
||||||
|
Scenario: A check runs on the first open after 24 hours, for the owner only
|
||||||
|
Given the owner opens /settings and checked_at is null or older than 24 hours
|
||||||
|
Then POST /v1/system/update/check is sent once automatically and the Checking state shows
|
||||||
|
When checked_at is under 24 hours old
|
||||||
|
Then no automatic check is sent
|
||||||
|
And an admin never sends one
|
||||||
|
|
||||||
|
Scenario: Home banner for the owner, update available
|
||||||
|
Given the owner is on /home and available is true with latest "v2.3.0-beta"
|
||||||
|
Then a region labelled "Update available" shows above the content in info tone with icon circle-arrow-up,
|
||||||
|
title "Version 2.3.0-beta is available",
|
||||||
|
text "Update it from Settings. It takes about 2 minutes and the site stays online.",
|
||||||
|
a "Go to Settings" button and a dismiss button
|
||||||
|
When the owner dismisses it
|
||||||
|
Then the banner is hidden and localStorage remembers the dismissed version
|
||||||
|
And it shows again when latest changes to a newer version
|
||||||
|
|
||||||
|
Scenario: Settings sidebar pill and mobile dot
|
||||||
|
Given the owner and available is true
|
||||||
|
Then the Settings sidebar item shows an "Update" pill, and on mobile the menu icon shows a dot read as "Update available"
|
||||||
|
And the pill stays after the banner is dismissed
|
||||||
|
|
||||||
|
Scenario: Admins and an up-to-date owner see no banner, pill or dot
|
||||||
|
Then an admin, or an owner with available false, sees no banner, pill or dot
|
||||||
|
|
||||||
|
Scenario: Pending states of slices 2 and 3
|
||||||
|
Then these states are listed as pending in the visual gate, never passing: Update available with its Update button
|
||||||
|
(and its notes-open frame), Downloading, Verifying, Ready to install, Restart confirm, Restart request failed,
|
||||||
|
Restarting, Restarting taking longer, Update done, Rolled back, Download failed, Verification failed,
|
||||||
|
Plain restart confirm, restarting and done, Update already running (409), and the Home "ready to install" banner
|
||||||
|
And the Update, Restart and progress elements are not rendered in any state of this slice
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
# QA: Updates part 1 (signed releases, release feed, notification)
|
||||||
|
|
||||||
|
## Automated Go (`task test`, package `test`, black-box)
|
||||||
|
|
||||||
|
Files: `test/update_test.go` (domain, use cases), `test/update_http_test.go` (HTTP), `test/update_feed_test.go`
|
||||||
|
(Gitea adapter, JSON store), `test/releasesign_test.go` (signing tool). Fakes with unique names: `fakeReleaseFeed`
|
||||||
|
(returns a list or an error, counts calls), `fakeUpdateStore`; reuse `mockUserRepo` from `test/user_test.go`.
|
||||||
|
|
||||||
|
HTTP setup: `validator.InitValidator()`; `token := jwtauth.New("HS256", []byte("test-secret"), nil)`; mount a fresh
|
||||||
|
`chi.NewRouter()` at `/v1/system` mirroring `NewSystemRouter` (Verifier, Authenticator, RequireCurrentToken,
|
||||||
|
RequireVerifiedUser; the check route also RequireOwner and the per-user limiter, 5 per minute); cookies via
|
||||||
|
`token.Encode({"user_id","token_version"})` as in `test/stale_token_invalidation_http_test.go`. `httptest` only: no live
|
||||||
|
server, no SQLite, no SMTP.
|
||||||
|
|
||||||
|
1. Version comparison, table-driven over the Examples in the feature (domain; `errors.Is` for sentinels).
|
||||||
|
2. Feed adapter against `httptest.NewServer` serving a Gitea JSON list: path is
|
||||||
|
`/api/v1/repos/fsylvain/RenewCMS/releases`; newest by numeric order regardless of order; drafts skipped; final beats
|
||||||
|
beta; notes markdown converted to items; `html_url` carried; a 500 and invalid JSON return an error.
|
||||||
|
3. `GET /v1/system/update` as owner and as admin: 200, exactly the 12 keys, `can_apply` false, `state` "idle", values
|
||||||
|
from the stored result, `release_url` from the stored `html_url`; the fake feed call count is 0.
|
||||||
|
4. GET before any check: `latest` "", `available` false, `release_url`, `notes`, `checked_at`, `progress`, `error`,
|
||||||
|
`started_at` null.
|
||||||
|
5. GET: no cookie 401; stale token 401 with `apperr.UnauthorizedErrorMessage`; unverified 403 with
|
||||||
|
`apperr.VerificationRequiredErrorMessage`.
|
||||||
|
6. `POST /v1/system/update/check` as owner: 200, store updated with latest, `release_url` and `checked_at`, feed called
|
||||||
|
once, a later GET equals it. Nothing newer: `available` false. Running version "dev": `available` false.
|
||||||
|
7. POST check as admin: 403, body `apperr.OwnerRequiredErrorMessage+"\n"`, feed not called.
|
||||||
|
8. Feed error: 500, store unchanged (latest and `checked_at` as before), body contains no feed error text.
|
||||||
|
9. Rate limit: owner A sends 6 checks: first 5 are 200, the 6th is 429 with `apperr.TooManyRequestsErrorMessage+"\n"`
|
||||||
|
and an integer `Retry-After` of at least 1; feed called 5 times; owner B's first check still 200; a login-limiter
|
||||||
|
instance built in the same test is unaffected.
|
||||||
|
10. JSON file store in `t.TempDir()`: save, reopen, same values; missing file and corrupt file read as empty without error.
|
||||||
|
11. Signing tool, run through `go run ./cmd/releasesign` (or its exported package) with a throwaway key pair generated
|
||||||
|
in `t.TempDir()` at test time, always with `--pub`; never read the committed `release.pub` key except in case 13:
|
||||||
|
keygen creates the key; sign then verify passes; one flipped byte fails verify; a different public key fails verify;
|
||||||
|
keygen into a path inside the repo tree is refused and writes nothing; sign with a private key that does not match
|
||||||
|
`--pub` fails, naming the mismatch, and writes no `.sig`.
|
||||||
|
12. Placeholder: a `--pub` file holding base64 of 32 zero bytes makes sign and verify fail with the placeholder message.
|
||||||
|
13. The committed `internal/infrastructure/update/release.pub` is checked only for shape: a valid base64 string that
|
||||||
|
decodes to 32 bytes. Do not assert that it is or is not the placeholder, since the user replaces it later.
|
||||||
|
14. Review items, not Go tests: `internal/domain/update` imports only the stdlib; use cases import no `net/http`,
|
||||||
|
`gorm`, adapter or `config`; the handler imports no adapter; `UPDATE_FEED_URL` is in `requiredEnvVars`/`envDefaults`,
|
||||||
|
`.env.example` and `docs/configuration.md`; no private key or secret value is in the repo.
|
||||||
|
|
||||||
|
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `useApi.request` for `GET /v1/system/update` and `POST /v1/system/update/check`. Fake timers for the countdown and
|
||||||
|
the 2 s "Copied". No test freezes the system date and none asserts a relative date or "Last checked today". Reuse the
|
||||||
|
board's sample data: running `v2.2.0-beta`, latest `v2.3.0-beta`, released 24 Sep 2026, items from the frame's script.
|
||||||
|
|
||||||
|
One test per state:
|
||||||
|
1. Up to date (owner): "You're up to date", only "Check for updates" rendered.
|
||||||
|
2. Checking: text, polite live region, "Checking…" disabled, one POST.
|
||||||
|
3. Check failed (500, then `NetworkError`): copy, only "Try again", last result kept.
|
||||||
|
4. Not prepared (available, `can_apply` false): copy, command line, note, "How to update" link with `href` equal to
|
||||||
|
`release_url` and an external target; no button other than Copy.
|
||||||
|
5. Notes open: collapsed by default, `aria-expanded` toggles, "Released 24 Sep 2026" and the plain-text list.
|
||||||
|
6. Command copied: Copy writes the command to the clipboard mock, reads "Copied" for 2 s, then "Copy".
|
||||||
|
7. Admin view: both texts, no button; no auto check.
|
||||||
|
8. Role changed (403): toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS.", then a
|
||||||
|
reload of the GET and the admin view.
|
||||||
|
9. 429: "Too many tries", button "Try again in 0:42" counting down to enabled.
|
||||||
|
10. Auto check: sent once when `checked_at` is null or older than 24 h, not when fresh, never for admin.
|
||||||
|
11. Home banner: shown for the owner when available, copy and "Go to Settings" navigates to /settings, dismiss writes
|
||||||
|
the version to localStorage and hides it, same version stays hidden after remount, a newer `latest` shows it again,
|
||||||
|
absent for admin and when not available.
|
||||||
|
12. Sidebar pill and mobile dot: owner and available only, pill remains after the banner is dismissed; absent for admin.
|
||||||
|
13. No Update, Restart or progressbar element exists in any of the states above; the shown version drops the leading
|
||||||
|
"v" ("Version 2.3.0-beta") while the Version card keeps `v2.2.0-beta`.
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- settings` and `-- home`; desktop and mobile, light and dark; every capture within 10 %)
|
||||||
|
|
||||||
|
Add the setups to `web/visual/states.ts` using the board's own sample data. Exact values from
|
||||||
|
`docs/design/source/AppFrame.dc.html` (Settings and Home blocks); layout as drawn, not from the prose.
|
||||||
|
|
||||||
|
- [ ] Settings: Checking (mock a never-resolving check after the click setup), Not prepared, Admin view (available),
|
||||||
|
Too many requests (429, Retry-After 42).
|
||||||
|
- [ ] Settings, `skip: 'clock-sensitive'` (the meta line is relative: "Last checked today at 09:41", "yesterday at 18:12"):
|
||||||
|
Up to date, Check failed, Admin view (up to date).
|
||||||
|
- [ ] Settings, Not prepared: command copied (the "Copied" state is time-bound; Vitest only), listed as not visual.
|
||||||
|
- [ ] Home: Update available (owner), with the sidebar pill and the mobile dot as drawn.
|
||||||
|
- [ ] Pending, never passing (slices 2 and 3): Update available with its Update button, Update available with notes
|
||||||
|
open (its frame draws the Update button), Downloading, Verifying, Ready to install, Restart confirm, Restart
|
||||||
|
request failed, Restarting, Restarting taking longer, Update done, Rolled back, Download failed, Verification
|
||||||
|
failed, Plain restart (confirm, restarting, done), Update already running (409), Home "ready to install" banner.
|
||||||
|
- [ ] Not covered by screenshots: keyboard and focus order, focus ring on the "Updates" heading (`id="updates-h"`),
|
||||||
|
hover and motion, the Copy announcement, the dismiss button focus.
|
||||||
|
|
||||||
|
## Manual verification
|
||||||
|
|
||||||
|
- Replace the placeholder key: run `task release:keygen`, store the private key outside the repo, set
|
||||||
|
`RELEASE_SIGNING_KEY` to its path, commit the printed public key as `internal/infrastructure/update/release.pub`, and
|
||||||
|
rebuild. Never commit or paste the private key. Until this is done, `task release` must fail with the placeholder message.
|
||||||
|
- Run `task release` with `RELEASE_SIGNING_KEY` unset, pointing to a missing file, and pointing to a key that does not
|
||||||
|
match `release.pub`: each fails before any binary is built, with a message naming the cause. With the correct key,
|
||||||
|
`checksums.txt` and `checksums.txt.sig` appear next to the six binaries and `cmd/releasesign verify` passes on them.
|
||||||
|
- Against the real Gitea feed (default `UPDATE_FEED_URL`), run a dev API with a lower fake version and press "Check for
|
||||||
|
updates" in the SPA: it reports the newest release; the "How to update" link opens that release's page.
|
||||||
|
- Real release notes (the markdown body) render as a sensible plain-text list.
|
||||||
|
- Restart the API and confirm the last result and `checked_at` survive, in `update-status.json` beside `DB_FILE`.
|
||||||
|
- Embedded SPA build (no `-tags nofrontend`) serves /settings and /home with the card, banner and pill.
|
||||||
|
- Confirm `docs/release-notes.md` (publish step: attach `checksums.txt` and `checksums.txt.sig` with the six binaries),
|
||||||
|
`docs/deployment.md` and `docs/configuration.md` are updated, and that nothing was published.
|
||||||
|
- Release gate: slices 1 to 3 ship together, so no released build shows `renewcms enable-browser-updates` before slice 3
|
||||||
|
implements it.
|
||||||
@@ -0,0 +1,508 @@
|
|||||||
|
Feature: Updates part 3: Restart, the privileged helper and rollback
|
||||||
|
|
||||||
|
As the owner of a RenewCMS site
|
||||||
|
I want one Restart button that installs the staged release, or just restarts the site, and puts the old version back if the new one does not come up
|
||||||
|
So that I can update from the browser while the app itself stays unprivileged and sandboxed
|
||||||
|
|
||||||
|
Background:
|
||||||
|
Given slices 1 to 3 of Updates ship in one release
|
||||||
|
And the app never gains privileges: the documented systemd unit keeps ProtectSystem=strict and only the data directory writable
|
||||||
|
And only the helper runs as root; it is the same binary, started as "renewcms apply-update" by a oneshot systemd service
|
||||||
|
And the data directory is the directory that holds DB_FILE; no new env var is added
|
||||||
|
And the files in the data directory are:
|
||||||
|
update-restart-request.json (marker, written by the app):
|
||||||
|
{"kind":"update"|"restart","tag" (update only),"requested_at" RFC3339 UTC,"requested_by" user_id};
|
||||||
|
update-result.json (written by the helper):
|
||||||
|
{"outcome":"running"|"succeeded"|"rolled_back"|"failed","kind","tag","from_version","started_at","finished_at"};
|
||||||
|
update-helper.json (status file, written by enable-browser-updates):
|
||||||
|
{"version":1,"service","binary","data_dir","installed_at"};
|
||||||
|
update-running.json (written by the server at every startup):
|
||||||
|
{"version","pid","started_at"}
|
||||||
|
And the marker is written atomically (temp file in the data directory, then rename) and deleted by the helper after reading it
|
||||||
|
And the technical reason of a failure goes to the log or journal only, never into a file the app serves or a response
|
||||||
|
And the domain package internal/domain/update (stdlib only) gains these interfaces, each faked in tests:
|
||||||
|
RestartRequestStore (write, read, delete the marker),
|
||||||
|
ResultStore (read, write and delete the result),
|
||||||
|
RunningInfoStore (the server writes update-running.json; the helper reads it),
|
||||||
|
HelperFilesystem (lstat, open with no-follow, read, create-exclusive, copy, rename, remove, chmod, make a fresh private
|
||||||
|
temp directory, all of them symlink-aware),
|
||||||
|
ServiceControl (restart and status of the systemd service),
|
||||||
|
HealthChecker (GET http://127.0.0.1:<port>/healthz, true on 200),
|
||||||
|
Clock
|
||||||
|
And the helper logic depends only on those interfaces and on update.SignatureVerifier from slice 2 with the embedded release.pub
|
||||||
|
And O_NOFOLLOW and lstat behaviour sit behind HelperFilesystem so the logic is tested on any OS; the real adapter is Linux-only
|
||||||
|
(build-tagged) and is covered by the manual systemd checklist
|
||||||
|
And RequestRestartUseCase and the extended GetUpdateStatusUseCase depend only on domain interfaces; handlers in
|
||||||
|
api/handlers/update receive them through NewHandler; only api/dependecyInjection.go builds the adapters
|
||||||
|
And POST /v1/system/update/restart is mounted in NewSystemRouter behind jwtauth.Verifier, jwtauth.Authenticator,
|
||||||
|
RequireCurrentToken, RequireVerifiedUser and RequireOwner; there is no limiter
|
||||||
|
And its optional JSON body is {"kind":"update"|"restart"}, bound to a request struct with
|
||||||
|
validate:"omitempty,oneof=update restart" and checked by validator.Validate.Struct; an empty body is allowed
|
||||||
|
And the checks on POST run in this order: no cookie or stale token (401), unverified (403), not owner (403),
|
||||||
|
malformed body or invalid kind (400), can_apply false (409), job downloading or verifying (409), a restart already pending
|
||||||
|
or running (409), kind that does not match the state (409), marker write error (500), then 202
|
||||||
|
And with no body the server picks by state: job "ready" gives kind "update", anything else kind "restart"
|
||||||
|
And the kind given must match: "update" needs a job "ready"; "restart" needs no job "ready"; otherwise 409 and nothing is written
|
||||||
|
And POST download and POST restart delete update-result.json before they start a new job or write a marker
|
||||||
|
And the 202 body is the status JSON with state "restarting" and started_at equal to the marker's requested_at (server clock)
|
||||||
|
And errors are plain text from http.Error and carry no path or technical detail
|
||||||
|
And GET /v1/system/update has no side effects; it keeps the 12 keys of slice 1 and gains exactly one key, "finished_at":
|
||||||
|
the result's finished_at (RFC3339 UTC) whenever a result file exists, otherwise null, whatever the state
|
||||||
|
And state is one of idle, downloading, verifying, ready, restarting, succeeded, failed, derived from the files by one rule:
|
||||||
|
marker present, or result "running" younger than 5 minutes: "restarting";
|
||||||
|
result "running" older than 5 minutes and no marker: "failed", error "install";
|
||||||
|
result "succeeded", kind "update", tag equal to the running version: "succeeded";
|
||||||
|
result "succeeded" for kind "restart", or kind "update" whose tag is no longer the running version: "idle";
|
||||||
|
result "rolled_back": "failed", error "rolled_back";
|
||||||
|
result "failed": "failed", error "install";
|
||||||
|
otherwise the slice 2 job state; a missing or corrupt result file counts as no result
|
||||||
|
And a result persists and is read the same on every GET until POST download or POST restart deletes it
|
||||||
|
And error is null, "download", "verification", "rolled_back" or "install"
|
||||||
|
And GET /healthz is unchanged: body "ok", no version header
|
||||||
|
And the server writes update-running.json at every startup, after the listener is bound and before it serves, atomically; a write error
|
||||||
|
is logged and is not fatal
|
||||||
|
And the helper judges a restart by two things: GET /healthz answers 200 AND update-running.json holds the expected version AND it is
|
||||||
|
NEW: its pid differs from the pid read before the restart, or its started_at is later than the instant the restart command
|
||||||
|
was issued; a stale file with the old pid or started_at never counts
|
||||||
|
And main gains a minimal dispatcher before the normal start: the subcommands enable-browser-updates, disable-browser-updates and
|
||||||
|
apply-update run their own code and never read .env, open the database or listen; "--version" and the normal start are unchanged
|
||||||
|
And the new subcommands never write a secret value or an env value into a unit file
|
||||||
|
|
||||||
|
Scenario: Request an update restart, happy path
|
||||||
|
Given the owner, can_apply true and a job "ready" for "v2.3.0-beta"
|
||||||
|
When the owner sends POST /v1/system/update/restart with no body, or with {"kind":"update"}
|
||||||
|
Then the status is 202 and the body is the status JSON with state "restarting"
|
||||||
|
And the marker holds kind "update", tag "v2.3.0-beta", requested_by the owner's user_id and requested_at
|
||||||
|
And update-result.json was deleted first
|
||||||
|
And the running binary, the staged files and the database are unchanged by the app
|
||||||
|
And GET reports state "restarting" for any verified user
|
||||||
|
|
||||||
|
Scenario: Request a plain restart
|
||||||
|
Given the owner, can_apply true and no job "ready"
|
||||||
|
When the owner sends POST /v1/system/update/restart with no body, or with {"kind":"restart"}
|
||||||
|
Then the status is 202, the marker holds kind "restart" and no tag, and GET reports state "restarting"
|
||||||
|
|
||||||
|
Scenario Outline: The kind must match the state
|
||||||
|
Given the owner, can_apply true and <state>
|
||||||
|
When the owner sends POST /v1/system/update/restart with {"kind":"<kind>"}
|
||||||
|
Then the status is 409, no marker is written, the result file and the job are untouched
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| state | kind |
|
||||||
|
| no job "ready" (idle) | update |
|
||||||
|
| a job "failed" | update |
|
||||||
|
| a job "ready" | restart |
|
||||||
|
|
||||||
|
Scenario: Restart site never installs an update another owner just made ready
|
||||||
|
Given owner A opened the Plain restart dialog while the job was idle
|
||||||
|
And owner B then made a job "ready"
|
||||||
|
When owner A confirms and the SPA sends {"kind":"restart"}
|
||||||
|
Then the status is 409, nothing is installed and the staged files are untouched
|
||||||
|
And the SPA reloads the card and shows "Ready to install"
|
||||||
|
|
||||||
|
Scenario Outline: A bad body is a 400
|
||||||
|
Given the owner and can_apply true
|
||||||
|
When the owner sends POST /v1/system/update/restart with <body>
|
||||||
|
Then the status is 400 with a plain text body and no marker is written
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| body |
|
||||||
|
| {"kind":"upgrade"} |
|
||||||
|
| {"kind":""} |
|
||||||
|
| {"kind":7} |
|
||||||
|
| {"kind":"update" |
|
||||||
|
| not json |
|
||||||
|
|
||||||
|
Scenario Outline: POST is guarded like the other system routes
|
||||||
|
When <caller> sends POST /v1/system/update/restart
|
||||||
|
Then the status is <status> and no marker is written and no result is deleted
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| caller | status | body |
|
||||||
|
| no jwt cookie | 401 | the existing 401 text |
|
||||||
|
| a stale token version | 401 | the existing 401 text |
|
||||||
|
| an unverified owner | 403 | the existing unverified text |
|
||||||
|
| an admin | 403 | apperr.OwnerRequiredErrorMessage |
|
||||||
|
|
||||||
|
Scenario Outline: Restart is refused with 409
|
||||||
|
Given the owner and <condition>
|
||||||
|
When the owner sends POST /v1/system/update/restart
|
||||||
|
Then the status is 409, the existing marker, result and job are untouched and no new marker is written
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| condition |
|
||||||
|
| can_apply is false (no update-helper.json) |
|
||||||
|
| the job state is downloading |
|
||||||
|
| the job state is verifying |
|
||||||
|
| a marker is already pending |
|
||||||
|
| the result file reads "running" (helper at work) |
|
||||||
|
|
||||||
|
Scenario: Two restarts at once write one marker
|
||||||
|
When two owners send POST /v1/system/update/restart concurrently
|
||||||
|
Then exactly one answers 202 and the other 409 and one marker exists
|
||||||
|
|
||||||
|
Scenario: The marker cannot be written
|
||||||
|
Given the data directory is not writable, or a directory sits where the marker file goes
|
||||||
|
When the owner sends POST /v1/system/update/restart
|
||||||
|
Then the status is 500 with a plain text body without paths, no marker exists and the job record is untouched
|
||||||
|
|
||||||
|
Scenario Outline: GET derives the state from the files and never changes them
|
||||||
|
Given <files>
|
||||||
|
When any verified user sends GET /v1/system/update twice
|
||||||
|
Then both answers are identical, state is <state>, error is <error> and finished_at is <finished>
|
||||||
|
And no file in the data directory changed
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| files | state | error | finished |
|
||||||
|
| a marker is present | restarting | null | null |
|
||||||
|
| result "running" written 30 s ago | restarting | null | null |
|
||||||
|
| result "running" written 6 minutes ago, no marker | failed | "install" | its value |
|
||||||
|
| result "succeeded", kind "update", tag equal to the running version | succeeded | null | its value |
|
||||||
|
| result "succeeded", kind "update", tag older than the running one | idle | null | its value |
|
||||||
|
| result "succeeded", kind "restart" | idle | null | its value |
|
||||||
|
| result "rolled_back" | failed | "rolled_back" | its value |
|
||||||
|
| result "failed" | failed | "install" | its value |
|
||||||
|
| no marker, no result | idle | null | null |
|
||||||
|
| a corrupt result file | idle | null | null |
|
||||||
|
|
||||||
|
Scenario: The result lives until the next job
|
||||||
|
Given a result "rolled_back"
|
||||||
|
When the owner sends POST /v1/system/update/download and the job reaches "ready"
|
||||||
|
Then the result file was deleted by the POST, GET reports state "ready", error null and finished_at null
|
||||||
|
And GET /v1/system/update still has exactly the 12 keys of slice 1 plus finished_at
|
||||||
|
|
||||||
|
Scenario: After a successful update the status is consistent
|
||||||
|
Given a result "succeeded" for "v2.3.0-beta" and the running version "v2.3.0-beta"
|
||||||
|
Then GET reports state "succeeded", available false, current "v2.3.0-beta" and finished_at set
|
||||||
|
|
||||||
|
Scenario: The server writes update-running.json at startup
|
||||||
|
When the server starts with version "v2.3.0-beta"
|
||||||
|
Then update-running.json holds {"version":"v2.3.0-beta","pid":<its pid>,"started_at":<now>} written atomically
|
||||||
|
And it is written after the listener is bound and before requests are served
|
||||||
|
And a write error is logged and the server still starts
|
||||||
|
And a second start replaces the file with the new pid and started_at
|
||||||
|
And the file is not served by any route
|
||||||
|
|
||||||
|
Scenario: Healthz is unchanged
|
||||||
|
When a client sends GET /healthz
|
||||||
|
Then the status is 200, the body is "ok" and there is no version header, and the route stays public
|
||||||
|
|
||||||
|
Scenario Outline: The command dispatcher
|
||||||
|
When the binary is run with "<args>" and an empty environment
|
||||||
|
Then <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| args | outcome |
|
||||||
|
| --version | it prints the version, exits 0 (unchanged from slice 2) |
|
||||||
|
| enable-browser-updates | it runs the installer, never reads .env or opens the database |
|
||||||
|
| disable-browser-updates | it runs the uninstaller, never reads .env or opens the database |
|
||||||
|
| apply-update | it runs the helper, never reads .env or opens the database |
|
||||||
|
| no arguments | the normal server start |
|
||||||
|
| an unknown subcommand | a usage message on stderr and a non-zero exit, the server is not started |
|
||||||
|
|
||||||
|
Scenario Outline: enable-browser-updates refuses when it cannot work
|
||||||
|
Given <situation>
|
||||||
|
When "renewcms enable-browser-updates" runs
|
||||||
|
Then it exits non-zero with the clear message "<message>" and writes nothing
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| situation | message |
|
||||||
|
| the OS is not Linux | Browser updates need Linux with systemd. |
|
||||||
|
| Linux without systemd (no /run/systemd/system) | Browser updates need systemd, which this machine is not running. |
|
||||||
|
| not run as root | Run this command as root, for example with sudo. |
|
||||||
|
| no unit for the service and no flags | Could not find the RenewCMS service. Pass --service, --binary and --data-dir. |
|
||||||
|
| the data directory cannot be resolved | Could not find the data directory. Pass --data-dir. |
|
||||||
|
|
||||||
|
Scenario: enable-browser-updates installs the units
|
||||||
|
Given systemd on Linux, root, and an existing renewcms.service with ExecStart=/opt/renewcms/renewcms and ReadWritePaths=/var/lib/renewcms
|
||||||
|
When "renewcms enable-browser-updates" runs
|
||||||
|
Then it reads the service name, binary path and data directory from the unit, with --service, --binary and --data-dir overriding them
|
||||||
|
And it writes renewcms-update.path (PathExists= the marker) and renewcms-update.service (Type=oneshot, User=root,
|
||||||
|
ExecStart=<binary> apply-update with the service, binary, data directory and port as flags)
|
||||||
|
And the port comes from --port, else from PORT in the service's environment file, else 8080
|
||||||
|
And it runs daemon-reload and enables and starts the path unit
|
||||||
|
And it writes update-helper.json last, so can_apply becomes true only when everything else worked
|
||||||
|
And no secret and no environment value is written into either unit
|
||||||
|
And it prints what it installed and how to undo it
|
||||||
|
|
||||||
|
Scenario: enable-browser-updates is idempotent
|
||||||
|
Given it ran once
|
||||||
|
When it runs again, including after the binary path or service name changed
|
||||||
|
Then the units and the status file are rewritten to the current values, no duplicate unit exists and the exit is 0
|
||||||
|
|
||||||
|
Scenario: enable-browser-updates undoes its own partial work
|
||||||
|
Given writing the second unit, daemon-reload or enable fails
|
||||||
|
Then the first unit is removed, update-helper.json is not written and the exit is non-zero with the reason
|
||||||
|
|
||||||
|
Scenario: disable-browser-updates
|
||||||
|
Given browser updates are enabled
|
||||||
|
When "renewcms disable-browser-updates" runs
|
||||||
|
Then the path unit is stopped and disabled, both unit files and update-helper.json are removed, daemon-reload runs
|
||||||
|
And the marker and result files, the staged files and backups are left in place
|
||||||
|
And running it again, or where it was never enabled, exits 0 with a message
|
||||||
|
And can_apply reads false afterwards
|
||||||
|
|
||||||
|
Scenario: apply-update, a plain restart
|
||||||
|
Given a marker of kind "restart" and update-running.json with pid 100 and started_at T0
|
||||||
|
When the helper runs
|
||||||
|
Then it reads the marker without following symlinks, deletes it, and writes the result "running" with started_at
|
||||||
|
And it records the current update-running.json, restarts the service once and polls until /healthz answers 200
|
||||||
|
and update-running.json is new (pid differs from 100, or started_at is later than the restart instant)
|
||||||
|
And it then writes "succeeded" with kind "restart" and finished_at
|
||||||
|
And the binary and the staged files are untouched
|
||||||
|
|
||||||
|
Scenario Outline: A stale running file never counts as success
|
||||||
|
Given a marker and update-running.json that <staleness> while /healthz answers 200
|
||||||
|
When the helper polls
|
||||||
|
Then it keeps polling and it is not declared succeeded or rolled back until a new file appears or 60 s pass
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| staleness |
|
||||||
|
| still holds the old pid and old started_at |
|
||||||
|
| holds the target version but the old pid and an old started_at |
|
||||||
|
| is missing |
|
||||||
|
| is corrupt |
|
||||||
|
| holds the old version with a new pid (for an update) |
|
||||||
|
|
||||||
|
Scenario: apply-update, an update, happy path
|
||||||
|
Given a marker of kind "update" for "v2.3.0-beta" and a staged binary, checksums.txt and checksums.txt.sig under updates/v2.3.0-beta/
|
||||||
|
When the helper runs
|
||||||
|
Then it creates a fresh root-owned temp directory with mode 0700 and copies the staged files into it, opening each original with no-follow
|
||||||
|
And it verifies the signature of the COPIED checksums.txt with the embedded public key
|
||||||
|
And it verifies the SHA-256 of the COPIED binary against its checksums.txt line, ignoring the earlier job record
|
||||||
|
And it copies the current binary to <name>.previous, replacing an older .previous
|
||||||
|
And it writes the verified copy to a temp file in the binary's directory (mode 0755), checks that it still hashes to the verified value,
|
||||||
|
and installs it with an atomic rename; the original staged path is never installed
|
||||||
|
And it restarts the service and polls /healthz and update-running.json for up to 60 s
|
||||||
|
And when /healthz answers 200 and update-running.json is new and holds "v2.3.0-beta" it writes "succeeded", success being declared on the
|
||||||
|
first matching poll
|
||||||
|
And it removes the temp directory and updates/v2.3.0-beta/
|
||||||
|
And the marker was deleted before any other step ran
|
||||||
|
|
||||||
|
Scenario Outline: apply-update refuses an untrusted staged binary
|
||||||
|
Given a marker of kind "update" and <fault>
|
||||||
|
When the helper runs
|
||||||
|
Then the current binary is not touched, no .previous is written and the service is not restarted
|
||||||
|
And it writes "failed", logs the technical reason only, and removes the temp directory and updates/<tag>/
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| fault |
|
||||||
|
| the binary was changed after the job verified it |
|
||||||
|
| checksums.txt was changed |
|
||||||
|
| the signature is from a different key or is missing |
|
||||||
|
| checksums.txt has no line for the asset |
|
||||||
|
| the staged binary is missing |
|
||||||
|
|
||||||
|
Scenario Outline: apply-update refuses symlinks
|
||||||
|
Given a marker of kind "update" and <symlink>
|
||||||
|
When the helper runs
|
||||||
|
Then it never reads through the link, the current binary is untouched, there is no .previous and no restart
|
||||||
|
And it writes "failed" and logs which path was a symlink
|
||||||
|
And whatever the link pointed to is not read, copied, written or removed
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| symlink |
|
||||||
|
| the marker itself is a symlink |
|
||||||
|
| <data>/updates is a symlink to another directory |
|
||||||
|
| <data>/updates/<tag> is a symlink to another directory |
|
||||||
|
| the staged binary is a symlink to /usr/bin/something |
|
||||||
|
| checksums.txt is a symlink |
|
||||||
|
| checksums.txt.sig is a symlink |
|
||||||
|
| a symlink is placed at the result path or at a temp file name |
|
||||||
|
|
||||||
|
Scenario: A symlinked marker is removed, not followed
|
||||||
|
Given the marker is a symlink to a file outside the data directory
|
||||||
|
When the helper runs
|
||||||
|
Then the link itself is unlinked, the target is untouched, and the result is "failed"
|
||||||
|
|
||||||
|
Scenario: A file swapped after verification is not installed
|
||||||
|
Given the staged binary is verified and a fake attacker replaces the original staged path with other bytes right after the copy step
|
||||||
|
When the helper installs
|
||||||
|
Then the installed bytes equal the verified copy's bytes and not the swapped bytes
|
||||||
|
And the same holds for a swap during the .previous copy and the final rename
|
||||||
|
And a swap of the temp file in the binary's directory before the rename is caught by the re-hash and ends as "failed" with the binary untouched
|
||||||
|
|
||||||
|
Scenario: Result and temp files are written without following links
|
||||||
|
Given the service user placed a symlink at update-result.json or at a predictable temp name in the data directory
|
||||||
|
When the helper writes its result
|
||||||
|
Then it creates a temp file with create-exclusive and no-follow, then renames it over the result, and the link target is untouched
|
||||||
|
|
||||||
|
Scenario Outline: apply-update distrusts the marker
|
||||||
|
Given a marker whose tag is <tag>
|
||||||
|
When the helper runs
|
||||||
|
Then it writes "failed", the binary is untouched, the service is not restarted and nothing outside <data>/updates is read
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| tag |
|
||||||
|
| ../../etc/passwd |
|
||||||
|
| v2.3.0-beta/../../x |
|
||||||
|
| an empty string |
|
||||||
|
| v2.1.0-beta (older than the running version) |
|
||||||
|
| not-a-version |
|
||||||
|
|
||||||
|
Scenario Outline: apply-update rolls back when the new version does not come up
|
||||||
|
Given an update marker and <fault> after the new binary was installed and the service restarted
|
||||||
|
When the helper runs
|
||||||
|
Then within the 60 s window it restores <name>.previous over the binary atomically and restarts the service again
|
||||||
|
And it polls until /healthz answers 200 and a NEW update-running.json holds the old version
|
||||||
|
And it writes "rolled_back" with from_version and tag and removes the temp directory and the staged files
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| fault |
|
||||||
|
| /healthz never answers within 60 s |
|
||||||
|
| /healthz answers but update-running.json stays old |
|
||||||
|
| update-running.json holds another version |
|
||||||
|
| the service restart command fails |
|
||||||
|
|
||||||
|
Scenario Outline: apply-update failures around the swap
|
||||||
|
Given an update marker and <fault>
|
||||||
|
Then <outcome>
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| fault | outcome |
|
||||||
|
| copying to .previous fails | the binary is untouched, the service not restarted, result "failed" |
|
||||||
|
| the atomic install fails | .previous and the old binary are intact, no restart, result "failed" |
|
||||||
|
| the rollback restore itself fails | result "failed", logged loudly, exit non-zero |
|
||||||
|
| the old version never returns after rollback | result "failed" (not "rolled_back"), exit non-zero |
|
||||||
|
|
||||||
|
Scenario: The result is always written
|
||||||
|
Given any marker and any outcome, including a panic in the helper
|
||||||
|
Then update-result.json holds outcome, kind, tag, from_version, started_at and finished_at, written atomically
|
||||||
|
And a "running" record exists from the moment the marker was read until the outcome replaces it
|
||||||
|
|
||||||
|
Scenario: Only the helper runs with privilege
|
||||||
|
Then the app has no code that execs systemctl, writes outside the data directory or reads the units
|
||||||
|
And the oneshot service and path unit contain no environment secrets
|
||||||
|
|
||||||
|
Scenario: Settings, owner, Restart buttons (route /settings)
|
||||||
|
Given the owner and can_apply true
|
||||||
|
Then with state "ready" the Restart button (power, primary) is enabled and opens the Install dialog
|
||||||
|
And with state "idle" (Up to date or Check failed) the Restart button (power, secondary) is enabled and opens the Plain restart dialog
|
||||||
|
And with state "downloading", "verifying" or "restarting" Restart is disabled or absent as the card draws it
|
||||||
|
And with can_apply false (Not prepared) or the admin view no Restart is rendered
|
||||||
|
And the slice 2 disabled Restart in Ready to install is now enabled and has a handler
|
||||||
|
And the SPA sends {"kind":"update"} from the Install dialog and {"kind":"restart"} from the Plain restart dialog, always
|
||||||
|
|
||||||
|
Scenario: Settings, Restart: confirm (Install dialog)
|
||||||
|
When the owner presses Restart in Ready to install
|
||||||
|
Then a dialog titled "Restart to finish the update?" shows "RenewCMS will install version 2.3.0-beta and restart. Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first."
|
||||||
|
And its buttons are "Restart later" and "Restart now", the confirm is neutral, not red
|
||||||
|
And focus moves to the first button, Escape and "Restart later" close it and focus returns to Restart
|
||||||
|
And no request is sent until "Restart now"
|
||||||
|
|
||||||
|
Scenario: Settings, Plain restart: confirm
|
||||||
|
When the owner presses Restart with no update waiting
|
||||||
|
Then a dialog titled "Restart the site?" shows "Your site will be unavailable for about 10 seconds. This page reloads on its own when the site is back. Save anything you're editing first."
|
||||||
|
And its buttons are "Cancel" and "Restart site", with the same focus and Escape behaviour
|
||||||
|
|
||||||
|
Scenario: Settings, Restart: request failed
|
||||||
|
Given the confirm button is pressed and POST /v1/system/update/restart answers 500 or never reaches the server
|
||||||
|
Then the dialog stays open (install or plain) with the error "Couldn't start the restart. Nothing was changed and your site is still running. Try again in a moment."
|
||||||
|
And the confirm button is enabled again, no overlay shows and nothing is stored in sessionStorage
|
||||||
|
|
||||||
|
Scenario: Settings, this tab remembers that it started the restart
|
||||||
|
Given POST /v1/system/update/restart answers 202 with started_at "S"
|
||||||
|
Then sessionStorage holds one entry with the kind and "S" (the server's started_at), and no other storage is written
|
||||||
|
And the overlay shows
|
||||||
|
|
||||||
|
Scenario: Settings, Restarting to install
|
||||||
|
Given POST /v1/system/update/restart answers 202 for an update
|
||||||
|
Then a full-page region with role "status" shows, titled "Installing version 2.3.0-beta" with
|
||||||
|
"Your site is restarting with the new version. This takes about 10 seconds. This page reloads on its own when the site is back." and a moving bar
|
||||||
|
And it is announced once as "Installing version 2.3.0-beta. Your site is restarting."
|
||||||
|
And the overlay survives failing requests and the Offline banner state is ignored while it shows
|
||||||
|
And it polls GET /healthz and GET /v1/system/update every second, tolerating network errors and non-200 answers
|
||||||
|
|
||||||
|
Scenario: Settings, Plain restart: restarting
|
||||||
|
Given POST /v1/system/update/restart answers 202 for a plain restart
|
||||||
|
Then the overlay shows "Restarting your site" / "This takes about 10 seconds. This page reloads on its own when the site is back."
|
||||||
|
And it polls the same way
|
||||||
|
|
||||||
|
Scenario: Settings, Restarting, taking longer
|
||||||
|
Given 60 seconds pass with no answer from /healthz or from GET /v1/system/update
|
||||||
|
Then the overlay shows "Still restarting" / "This is taking longer than usual. Keep this page open. It reloads on its own when the site is back, or you can reload it now." and a "Reload page" button
|
||||||
|
And the meta reads "Started at 09:51 · 1 minute ago" (clock-sensitive)
|
||||||
|
And "Reload page" reloads the page, the overlay stays until the site answers, and the polling continues
|
||||||
|
|
||||||
|
Scenario: Settings, the overlay ends when the site answers
|
||||||
|
Given the overlay shows and /healthz answers and GET /v1/system/update answers with a state other than "restarting"
|
||||||
|
and finished_at later than the stored started_at
|
||||||
|
Then the page reloads once
|
||||||
|
And a GET answering "restarting", a GET whose finished_at is null or not later than the stored started_at, a /healthz answer without a GET
|
||||||
|
answer, and a rejected GET all keep the overlay and do not reload
|
||||||
|
|
||||||
|
Scenario: Settings, Update done (the tab that started it)
|
||||||
|
Given the page reloaded, sessionStorage holds {kind "update", started_at "S"} and GET answers state "succeeded" with finished_at later than "S"
|
||||||
|
Then the entry is cleared, focus lands on the "Updates" heading (id="updates-h") with the ring shown
|
||||||
|
And a success toast "Update installed" / "RenewCMS is now on version 2.3.0-beta." is announced
|
||||||
|
And the Version card shows the new running version and the card reads "You're on version 2.3.0-beta" /
|
||||||
|
"The update is installed and your site is running again." / "Updated today at 09:52" with a "Read the release notes" link (arrow-up-right)
|
||||||
|
|
||||||
|
Scenario: Settings, Update failed, rolled back (the tab that started it)
|
||||||
|
Given the page reloaded, sessionStorage holds {kind "update", started_at "S"} and GET answers state "failed", error "rolled_back", finished_at later than "S", running "v2.2.0-beta"
|
||||||
|
Then the entry is cleared and focus lands on "Updates"
|
||||||
|
And an error toast (stays until dismissed) with icon circle-x "The update didn't install" / "Your site is back on v2.2.0-beta." shows
|
||||||
|
And the card shows icon triangle-alert (warning) "The update didn't install" /
|
||||||
|
"RenewCMS put the previous version back, so your site is running as before. Nothing was lost." /
|
||||||
|
"What to do next: try again in a few minutes. If it fails again, ask whoever manages your server to check the update." and a "Try again" button that sends POST /v1/system/update/download
|
||||||
|
And error "install" renders the same card and toast
|
||||||
|
|
||||||
|
Scenario: Settings, Plain restart: done (the tab that started it)
|
||||||
|
Given the page reloaded, sessionStorage holds {kind "restart", started_at "S"} and GET answers state "idle" with finished_at later than "S"
|
||||||
|
Then the entry is cleared, focus lands on "Updates" and a success toast "Site restarted" / "Your site is running again." is announced
|
||||||
|
And the card is the normal Up to date card
|
||||||
|
|
||||||
|
Scenario Outline: A later visit shows the card with no toast and no focus move
|
||||||
|
Given sessionStorage has no entry, or an entry whose started_at is not earlier than finished_at, and GET answers <result>
|
||||||
|
Then the card renders for that state, no toast shows and focus does not move to "Updates"
|
||||||
|
And nothing is written to sessionStorage
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
| result |
|
||||||
|
| state "succeeded", finished_at set |
|
||||||
|
| state "failed", error "rolled_back" |
|
||||||
|
| state "failed", error "install" |
|
||||||
|
| state "idle", finished_at set (plain restart) |
|
||||||
|
|
||||||
|
Scenario: Settings, another owner's tab never takes the toast
|
||||||
|
Given owner B has /settings open, with no sessionStorage entry, while GET answers "restarting" and later "succeeded"
|
||||||
|
Then owner B's page shows the overlay while "restarting" and the card afterwards, with no toast and no focus move
|
||||||
|
And owner A's tab, which holds the entry, still gets the toast and the focus
|
||||||
|
And an admin sees the admin view and no overlay
|
||||||
|
|
||||||
|
Scenario: Settings, a stale sessionStorage entry
|
||||||
|
Given an entry left behind by a restart that never finished in this tab (the tab was closed and reopened by hand)
|
||||||
|
When the page loads and GET answers a finished_at that is not later than the entry's started_at, or null
|
||||||
|
Then no toast shows, focus does not move, the entry stays until a later finished_at consumes it, and a new restart overwrites it
|
||||||
|
|
||||||
|
Scenario: Settings, 409 on Restart
|
||||||
|
Given POST /v1/system/update/restart answers 409
|
||||||
|
Then the dialog closes, nothing is stored in sessionStorage and the card reloads
|
||||||
|
And when the reload shows downloading, verifying or restarting an info toast "An update is already running" / "Another owner started it. Progress shows here." shows and the card or overlay switches to that run
|
||||||
|
And when the reload shows can_apply false the card shows "Not prepared" and no toast
|
||||||
|
And when the reload shows a different "Ready to install" or "idle" (the kind did not match) the card shows that state and no toast
|
||||||
|
|
||||||
|
Scenario: Settings, 400 on Restart
|
||||||
|
Given POST /v1/system/update/restart answers 400
|
||||||
|
Then the dialog shows the "Couldn't start the restart" text and nothing is stored in sessionStorage
|
||||||
|
|
||||||
|
Scenario: Settings, 403 role changed on Restart
|
||||||
|
Given POST /v1/system/update/restart answers 403
|
||||||
|
Then the dialog closes, an error toast "Only the owner can do this" / "Ask the owner of this site to update RenewCMS." shows and the card reloads in the admin view
|
||||||
|
|
||||||
|
Scenario: Settings, 401 on Restart
|
||||||
|
Given POST /v1/system/update/restart answers 401
|
||||||
|
Then the global handler goes to /login?redirect=/settings&reason=expired and no local copy shows
|
||||||
|
|
||||||
|
Scenario: Home banner while restarting
|
||||||
|
Given state "restarting"
|
||||||
|
Then Home shows no update banner and does not poll
|
||||||
|
|
||||||
|
Scenario: The docs gain a "Browser updates" section
|
||||||
|
Then docs/deployment.md has "Browser updates" with the one-time command "sudo renewcms enable-browser-updates", what it installs
|
||||||
|
(two units, update-helper.json), how to undo it ("sudo renewcms disable-browser-updates"), and what is and is not supported
|
||||||
|
And it lists: Linux with systemd only; not Windows, macOS, Docker or other init systems; the previous binary is kept as <name>.previous
|
||||||
|
and a database backup in backups/; an update whose new version does not come up within 60 s is rolled back automatically
|
||||||
|
And it names the files update-restart-request.json, update-result.json, update-helper.json and update-running.json
|
||||||
|
And the "How to update" link of the Not prepared card points at that section
|
||||||
|
And the sentence "the site does not update itself" in the "Update checks" section is replaced
|
||||||
@@ -0,0 +1,187 @@
|
|||||||
|
# QA: Updates part 3 (restart, helper, rollback)
|
||||||
|
|
||||||
|
## Automated Go (`task test`, package `test`, black-box, no live systemd, no real SMTP, no network)
|
||||||
|
|
||||||
|
Files: `test/update_restart_http_test.go` (HTTP), `test/update_restart_usecase_test.go` (request and status use cases),
|
||||||
|
`test/update_helper_test.go` (helper logic over fakes, including rollback and hardening), `test/update_helper_install_test.go`
|
||||||
|
(enable and disable over fakes), `test/update_helper_files_test.go` (real file adapters in `t.TempDir()`),
|
||||||
|
`test/update_dispatch_test.go` (built binary).
|
||||||
|
|
||||||
|
Fakes with unique names: `fakeRestartRequestStore`, `fakeResultStore`, `fakeRunningInfoStore` (scripted per poll: absent, corrupt, stale,
|
||||||
|
new), `fakeHelperFS`, `fakeServiceControl` (records restart calls with the clock instant; can fail), `fakeHealthChecker` (scripted per poll),
|
||||||
|
`fakeClock` (advances without sleeping), `fakeUnitWriter` (records unit contents, can fail the Nth write). Reuse `fakeJobStore`,
|
||||||
|
`fakeHelperDetector`, `fakeUpdateStore`, `mockUserRepo` and the throwaway ed25519 signer from slices 1 and 2. Never read the committed `release.pub`.
|
||||||
|
|
||||||
|
`fakeHelperFS`: an in-memory tree of files, directories and symlinks with owners and modes; `lstat`, no-follow open, create-exclusive, copy,
|
||||||
|
rename, remove and a fresh private temp directory are the only operations; every call is recorded in order with its path; an operation that
|
||||||
|
would traverse a symlink without the no-follow flag follows it (so a test fails if the code forgets to refuse); it can fail the Nth
|
||||||
|
call of an operation, and it has a hook `after(op, n, mutate)` that mutates the tree after a chosen call (used to swap the original
|
||||||
|
staged file after the copy step). Tests assert the paths the helper touched stay inside the data directory, the binary directory and
|
||||||
|
its own temp directory.
|
||||||
|
|
||||||
|
HTTP setup: `validator.InitValidator()`; `jwtauth.New("HS256", []byte("test-secret"), nil)`; a fresh `chi.NewRouter()` at `/v1/system`
|
||||||
|
mirroring `NewSystemRouter` (Verifier, Authenticator, RequireCurrentToken, RequireVerifiedUser; the restart route also RequireOwner);
|
||||||
|
cookies as in `test/stale_token_invalidation_http_test.go`. Marker, result and job files go in `t.TempDir()` through the real JSON adapters,
|
||||||
|
plus the fakes where noted. Helper time is driven by `fakeClock`: no `time.Sleep`, so the 60 s window runs instantly.
|
||||||
|
|
||||||
|
### Tests the coder must update (they exist from slices 1 and 2 and will break)
|
||||||
|
- Slice 1 tests that assert GET /v1/system/update has exactly 12 keys: now 13, with `finished_at` (null when no result file).
|
||||||
|
- Slice 2 tests and Vitest specs that assert the Restart button in "Ready to install" is disabled and has no handler, that no restart
|
||||||
|
endpoint, dialog or overlay exists, and that plain Restart is not rendered: replace them with the enabled behaviour below.
|
||||||
|
- Slice 2 "Pending states for slice 3" visual entries: they become real setups.
|
||||||
|
- Any slice 2 test that builds the status use case with a result store must accept the new `ResultStore` dependency.
|
||||||
|
|
||||||
|
### HTTP and use case (Go-testable)
|
||||||
|
1. Restart, update: ready job, can_apply on. POST with no body and POST `{"kind":"update"}` give 202 with state "restarting" and
|
||||||
|
`started_at` equal to the marker's `requested_at`; the marker has kind "update", the tag, requested_by equal to the owner id; the result file
|
||||||
|
was deleted first; no other file changed; GET as an admin also reads "restarting".
|
||||||
|
2. Plain restart: idle job. No body and `{"kind":"restart"}` give 202, marker kind "restart", empty tag. Also after a failed job and after a
|
||||||
|
rolled-back result.
|
||||||
|
3. Kind mismatch: `{"kind":"update"}` with no ready job (idle, failed) and `{"kind":"restart"}` with a ready job give 409; no marker, result and job untouched.
|
||||||
|
"Restart site never installs": owner A's body `{"kind":"restart"}` after the fake job store turned "ready" gives 409, no marker, staged files untouched.
|
||||||
|
4. Bad body: `{"kind":"upgrade"}`, `{"kind":""}`, `{"kind":7}`, truncated JSON, `not json` give 400 plain text, no marker. The struct uses
|
||||||
|
`validate:"omitempty,oneof=update restart"` and goes through `validator.Validate.Struct`; an empty body and `{}` are accepted.
|
||||||
|
5. Guards: admin 403 with `apperr.OwnerRequiredErrorMessage+"\n"`; no cookie 401; stale token 401; unverified 403; none writes a marker or deletes the result.
|
||||||
|
Order: an admin with a bad body gets 403, an owner with a bad body and can_apply off gets 400, can_apply off and a kind mismatch gives 409.
|
||||||
|
6. 409 table: can_apply off, downloading, verifying, marker pending, result "running": no second marker, existing files untouched.
|
||||||
|
7. Concurrency (`-race`): two simultaneous POSTs give one 202, one 409, one marker.
|
||||||
|
8. 500: a directory where the marker goes, and a read-only temp directory (`t.Skip` that one on Windows): 500, plain text without the path, no marker,
|
||||||
|
job record unchanged.
|
||||||
|
9. State derivation, one subtest per row of the feature table. Each row calls GET twice: the two bodies are byte-identical, `state`, `error` and
|
||||||
|
`finished_at` match, and a snapshot of every file in the data directory (names, bytes, mtimes) is unchanged by the GETs (GET has no side effects).
|
||||||
|
The 5-minute boundary uses `fakeClock`. Assert exactly the 12 slice 1 keys plus `finished_at`.
|
||||||
|
10. The result lives until the next job: a "rolled_back" result, then POST download and a job reaching "ready": the result is gone,
|
||||||
|
state "ready", error null, `finished_at` null. POST restart also deletes it before writing the marker.
|
||||||
|
11. After success: result "succeeded" for the running tag gives `available` false, `current` the new version, `finished_at` set.
|
||||||
|
12. Server startup file: with the real running-info adapter in `t.TempDir()` write twice; the file has `version`, `pid` and `started_at`, the second
|
||||||
|
write replaces the first, it is written by a temp file plus rename, and a write into a missing directory returns an error that the startup code logs
|
||||||
|
(use case or startup function returns it; it does not panic). The built binary (item 15) writes it before it answers `/healthz`.
|
||||||
|
13. `/healthz` is unchanged: body "ok", no `X-RenewCMS-Version` header, public.
|
||||||
|
14. A new download after "rolled_back" gives 202 and later a "ready" with error null.
|
||||||
|
15. Dispatcher: build with `go build -tags nofrontend -ldflags "-X main.version=v9.9.9" ./cmd/server` into `t.TempDir()`; with an empty environment
|
||||||
|
`--version` prints `v9.9.9`; an unknown subcommand exits non-zero with usage and does not listen; `apply-update` and `enable-browser-updates`
|
||||||
|
run without `.env` and create no `data/` (on a non-Linux machine the latter exits non-zero with the Linux/systemd message, which covers the Windows refusal).
|
||||||
|
|
||||||
|
### Helper logic over fakes (Go-testable, no systemd)
|
||||||
|
Fixture: fake FS with the binary `/opt/renewcms/renewcms` ("old"), staged `updates/v2.3.0-beta/` binary, `checksums.txt` and `checksums.txt.sig`
|
||||||
|
signed with a throwaway key injected through the verifier constructor, a marker, running version v2.2.0-beta, `update-running.json` with pid 100 and
|
||||||
|
started_at T0.
|
||||||
|
|
||||||
|
16. Plain restart: the marker is opened no-follow and deleted first, result "running" then "succeeded", one service restart, no write to the binary.
|
||||||
|
Success needs `/healthz` 200 AND a running file that is NEW.
|
||||||
|
17. Stale running info, one subtest per row: old pid and old started_at; target version but old pid and old started_at; absent; corrupt; old version with a new pid
|
||||||
|
(for an update). Health answers 200 throughout. The helper keeps polling and is not declared succeeded or rolled back until the file turns new or the
|
||||||
|
fake clock passes 60 s. Also: a file whose started_at is later than the restart instant counts as new even with the same pid.
|
||||||
|
18. Update happy path, asserting the ORDER of fake calls: no-follow read and delete of the marker, "running", fresh 0700 temp directory, no-follow copy of the
|
||||||
|
three staged files into it, signature check on the copy, SHA-256 of the copied binary, copy of the current binary to `.previous`, temp file in the
|
||||||
|
binary's directory written from the verified copy, re-hash of that temp file, atomic rename, mode 0755, record running info, restart, polls,
|
||||||
|
"succeeded", removal of the temp directory and `updates/<tag>/`. Final FS: binary equals the new bytes, `.previous` equals the old bytes.
|
||||||
|
Success is declared on the first matching poll, not at 60 s.
|
||||||
|
19. Re-verification, one subtest each: tampered binary, tampered checksums.txt, other-key signature, missing signature, no line for the asset, missing
|
||||||
|
binary. Each: binary unchanged, no `.previous`, zero restarts, result "failed", staged dir and temp dir removed, reason in the injected logger only.
|
||||||
|
20. Symlinks, one subtest each: marker; `updates`; `updates/<tag>`; the binary; checksums.txt; checksums.txt.sig; a link at the result path; a link at a
|
||||||
|
predictable temp file name. Each: the FS records no read, write, copy or removal through the link (the targets, placed outside the allowed
|
||||||
|
directories with sentinel bytes, are unchanged), binary untouched, no `.previous`, zero restarts, result "failed", the log names the link path.
|
||||||
|
The symlinked marker case: the link itself is unlinked and the target is intact.
|
||||||
|
21. TOCTOU: with the `after` hook, replace the original staged binary with other bytes immediately after the copy step; the installed bytes equal the
|
||||||
|
verified copy's bytes. Repeat with the swap after the signature check, after the hash check, and after the `.previous` copy. A swap of the temp file
|
||||||
|
in the binary's directory between write and rename is caught by the re-hash: result "failed", binary untouched.
|
||||||
|
22. Result and temp writes: create-exclusive and no-follow, then rename; a pre-planted symlink at the result path or a temp name leaves the target intact.
|
||||||
|
23. Hostile marker tags (traversal, traversal with valid prefix, empty, older version, malformed): result "failed", zero restarts, every touched path
|
||||||
|
under the allowed directories.
|
||||||
|
24. Rollback table: health never answers (60 s of fake clock, about 60 polls at 1 s), healthy but running file stays old, other version in the running file,
|
||||||
|
restart error. Each: binary restored to "old" through an atomic rename, second restart issued, polled until a NEW running file holds the old version,
|
||||||
|
result "rolled_back" with from_version and tag, temp directory and staged dir removed.
|
||||||
|
25. Swap failures: `.previous` copy fails (binary untouched, no restart, "failed"); atomic install fails (old binary and `.previous` intact, "failed");
|
||||||
|
restore fails ("failed", error returned, loud log); old version never returns after rollback ("failed", not "rolled_back").
|
||||||
|
26. Result always written: a panic in the fake service control still leaves outcome "failed" with `finished_at`; the "running" record exists before the
|
||||||
|
first service call; writes are atomic.
|
||||||
|
27. Timestamps come from `fakeClock`; finished is not before started.
|
||||||
|
28. Enable, over fake FS, unit writer and service control: refuses non-Linux, no systemd, not root, no unit and no flags, no data directory (exact
|
||||||
|
messages); on success writes both units containing the service, binary and data directory from the parsed unit, the `PathExists=` marker line and
|
||||||
|
the port flag (`--port` over `PORT` from the env file over 8080); the units never contain `JWT_SECRET` or any value from the env file (seed the
|
||||||
|
fixture env file with `JWT_SECRET=sentinel-secret` and search both units); flags override the unit; the status file is written LAST; running it
|
||||||
|
twice gives identical files and one unit pair; each failing step leaves no status file and removes the first unit.
|
||||||
|
29. Disable: removes units and the status file, keeps marker, result, staged files and backups; idempotent; a no-op where it was never enabled;
|
||||||
|
`can_apply` reads false afterwards through the real file detector.
|
||||||
|
30. Real adapters on `t.TempDir()`: the JSON marker, result, status and running-info stores round trip; the atomic write replaces an existing file.
|
||||||
|
The Linux-only no-follow adapter has a test file with `//go:build linux` (it runs on Linux CI machines and the user's WSL2, and is skipped on Windows).
|
||||||
|
31. Review items, not Go tests: the app (handlers, use cases, `api/`) execs no `systemctl` and writes only inside the data directory;
|
||||||
|
`internal/domain/update` imports only the stdlib; use cases import no `os/exec`, `net/http`, `gorm` or adapter; the handler imports no adapter;
|
||||||
|
the real filesystem adapter is the only code that calls `syscall.O_NOFOLLOW`; no secret in the repo; no new env var; `go vet -tags nofrontend`
|
||||||
|
and `gofmt` clean; no comments.
|
||||||
|
|
||||||
|
## Automated SPA (Vitest + Vue Test Utils, `task test:web`)
|
||||||
|
|
||||||
|
Mock `useApi.request` for `GET /v1/system/update`, `POST .../restart` and `POST .../download`; mock `fetch` for `GET /healthz`. Fake timers drive the
|
||||||
|
1 s polls and the 60 s switch. Stub `window.location.reload` and use a fresh `sessionStorage` per test. No test freezes the system date and none asserts a
|
||||||
|
relative date or "09:51". Sample data: running `v2.2.0-beta`, latest `v2.3.0-beta`, `started_at` and `finished_at` as plain strings.
|
||||||
|
|
||||||
|
One test per state:
|
||||||
|
1. Restart button: ready gives primary enabled; idle gives secondary enabled; downloading, verifying, restarting give disabled; can_apply false and admin give none.
|
||||||
|
2. Install dialog: exact title, text, buttons; focus on the first button; Escape and "Restart later" close it; focus returns to Restart; no request until
|
||||||
|
"Restart now"; the confirm is neutral; the request body is `{"kind":"update"}`.
|
||||||
|
3. Plain restart dialog: exact copy, "Cancel" / "Restart site", same behaviour; the request body is `{"kind":"restart"}`.
|
||||||
|
4. Restart request failed: 500 and `NetworkError`, in both dialogs: dialog stays, the exact error text, confirm enabled again, no overlay, nothing in sessionStorage. A 400 gives the same.
|
||||||
|
5. After 202, sessionStorage holds one entry with the kind and the response's `started_at`; no localStorage write.
|
||||||
|
6. Restarting to install: overlay `role="status"`, title and text, announced once; stays mounted when `fetch` rejects; the offline banner state is ignored; polls
|
||||||
|
/healthz and GET every second.
|
||||||
|
7. Plain restart: restarting: "Restarting your site" copy.
|
||||||
|
8. Taking longer: at 60 s "Still restarting", the text, "Reload page" present; pressing it calls reload; the overlay stays.
|
||||||
|
9. Overlay end: reload once when /healthz is ok and GET gives a non-"restarting" state with `finished_at` later than the stored `started_at`; no reload on
|
||||||
|
"restarting", on `finished_at` null, on `finished_at` not later, on a rejected GET, or without a GET answer; reload is not called twice.
|
||||||
|
10. Update done (entry present, state "succeeded", later `finished_at`): entry cleared, focus on `#updates-h`, success toast "Update installed" / "RenewCMS is now on version 2.3.0-beta.", card text and the "Read the release notes" link.
|
||||||
|
11. Rolled back (error "rolled_back" and "install"): entry cleared, focus on `#updates-h`, sticky error toast, card copy, "Try again" posts download.
|
||||||
|
12. Plain restart done (state "idle", later `finished_at`, kind "restart"): toast "Site restarted" / "Your site is running again.", focus, Up to date card, entry cleared.
|
||||||
|
13. No entry, or an entry not earlier than `finished_at`: for each of succeeded, rolled_back, install and plain-restart-idle results the card renders with no toast, no
|
||||||
|
focus move and no sessionStorage write.
|
||||||
|
14. Another owner's tab: no entry, GET "restarting" then "succeeded": overlay then card, no toast, no focus move. An owner tab with an entry still gets the toast. An admin sees the
|
||||||
|
admin view, no overlay and no poll.
|
||||||
|
15. Stale entry: `finished_at` null or earlier than the entry's `started_at` gives no toast and keeps the entry; a new restart overwrites it.
|
||||||
|
16. 409: reload downloading gives the info toast and progress; reload restarting gives the toast and overlay; reload can_apply false gives Not prepared and no toast; reload "ready"
|
||||||
|
or "idle" after a kind mismatch gives that card, no toast, nothing in sessionStorage.
|
||||||
|
17. 403: error toast and the admin view; 401 shows no local copy (the global handler is mocked).
|
||||||
|
18. Home: no banner or poll while "restarting".
|
||||||
|
19. Regression: slice 2's disabled-Restart assertions are replaced; Not prepared and the admin view still have no Restart.
|
||||||
|
|
||||||
|
## Visual (`task visual:check -- settings`; desktop and mobile, light and dark; every capture within 10 %)
|
||||||
|
|
||||||
|
`web/visual/states.ts` setups are added later by the coder, with the board's sample data (v2.2.0-beta, v2.3.0-beta). Exact values come from
|
||||||
|
`docs/design/source/AppFrame.dc.html` and the "Settings" group of the Screens board; describe layout as drawn (open the frame markup for the dialog, the overlay card
|
||||||
|
and its 440 px width before judging).
|
||||||
|
- [ ] Restart: confirm (install dialog)
|
||||||
|
- [ ] Plain restart: confirm
|
||||||
|
- [ ] Restart: request failed
|
||||||
|
- [ ] Restarting to install
|
||||||
|
- [ ] Plain restart: restarting
|
||||||
|
- [ ] Update failed, rolled back (the toast only if the frame draws it)
|
||||||
|
- [ ] `skip: 'clock-sensitive'`: Update done and Plain restart: done (meta "Updated today at 09:52"), Restarting, taking longer (meta "Started at 09:51 · 1 minute ago"); their copy is covered by Vitest
|
||||||
|
- [ ] Slice 2 pending states are now real: re-run the other Settings states and confirm Ready to install with an enabled Restart is within budget
|
||||||
|
- [ ] If a capture exceeds 10 %, stop and report; do not widen the budget or add an exception without the user's approval
|
||||||
|
- [ ] Not covered by screenshots: keyboard and focus order in both dialogs, the ring on `#updates-h` after the result states, the one-time overlay announcement, the motion of the bar, the Offline banner being ignored
|
||||||
|
|
||||||
|
## Manual only (real systemd Linux: WSL2 with systemd enabled, or a VPS): CANNOT be verified automatically
|
||||||
|
The user will run these. The helper's decision logic, ordering, symlink refusal, TOCTOU defence and rollback are unit-tested over fakes (items 16 to 27), but none of the following is covered:
|
||||||
|
- [ ] On Windows or macOS `renewcms enable-browser-updates` refuses with the clear message.
|
||||||
|
- [ ] On a VPS following docs/deployment.md (service user `renewcms`, `ProtectSystem=strict`, only `/var/lib/renewcms` writable): `sudo renewcms enable-browser-updates` reads the real unit, writes
|
||||||
|
`renewcms-update.path` and `renewcms-update.service`, enables the path unit (`systemctl status` active) and writes `update-helper.json`; a second run changes nothing.
|
||||||
|
- [ ] The Settings page shows the Update button (can_apply true) after a reload.
|
||||||
|
- [ ] The path unit fires when the sandboxed app writes the marker, and the app (as `renewcms`) can write the marker and cannot write the binary, the units or anything outside the data directory.
|
||||||
|
- [ ] The server writes `update-running.json` at startup (`cat` it: version, pid, started_at) and a restart replaces it.
|
||||||
|
- [ ] Real update from a real signed release (real `release.pub` committed, `task release` signing): Update, Ready, Restart, overlay, reload on the new version, toast on the tab that started it,
|
||||||
|
`.previous` next to the binary, `renewcms --version` equals the new tag, `journalctl -u renewcms-update` shows the helper log.
|
||||||
|
- [ ] Real rollback: stage a signed release whose binary prints the right `--version` but crashes at boot; the old binary is restored within about 60 s, the card reads "The update didn't install", the toast stays.
|
||||||
|
- [ ] Plain restart: overlay, about 10 s of downtime, reload with "Site restarted".
|
||||||
|
- [ ] The real no-follow adapter on Linux: as the service user, replace `updates/<tag>` with a symlink to `/etc`, replace the staged binary with a symlink, replace the marker with a symlink, and swap the staged file during
|
||||||
|
an update (a loop that rewrites it); the helper refuses or installs only verified bytes, and nothing outside the data directory is read or changed.
|
||||||
|
- [ ] Planted symlink at `update-result.json` pointing at a root-only file: the helper does not write through it.
|
||||||
|
- [ ] Binary directory ownership, SELinux and AppArmor do not block the atomic rename, and the temp file is on the same filesystem as the binary; the helper's private temp directory is root-owned 0700 and is removed.
|
||||||
|
- [ ] A hand-written marker with another tag, as the service user: refused, binary untouched.
|
||||||
|
- [ ] `sudo renewcms disable-browser-updates` removes the units and status file; the card returns to "Not prepared"; nothing else is deleted.
|
||||||
|
- [ ] A reverse proxy (nginx or Caddy) returns 502 during the restart and the overlay survives it; `/healthz` is not cached.
|
||||||
|
- [ ] Two owners in two browsers during a restart: both show the overlay; only the tab that started it gets the toast and focus.
|
||||||
|
- [ ] Embedded SPA build (no `-tags nofrontend`) serves `/settings` with the new dialogs and overlay.
|
||||||
|
- [ ] Journal and files contain no secret, and technical reasons are only in the journal.
|
||||||
|
|
||||||
|
## Final note
|
||||||
|
Not verifiable automatically: the whole privileged path on a real systemd Linux machine (generated units, path-unit trigger from the sandboxed app, real service restart, atomic swap on a real filesystem, real rollback, O_NOFOLLOW behaviour, permissions, SELinux or AppArmor, reverse-proxy behaviour). It needs the manual test on WSL2 with systemd or a VPS, which the user will do.
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
Feature: Uploading an image to an article
|
|
||||||
|
|
||||||
As an authenticated RenewCMS user managing the CMS
|
|
||||||
I want to attach an image file to an existing article and get back the
|
|
||||||
image's public location
|
|
||||||
So that an unknown article answers 404 the same way every other article
|
|
||||||
write does, without ever creating an orphaned image, and a disallowed
|
|
||||||
content type is rejected with 400 before it becomes part of the
|
|
||||||
article, without a maintainer needing to trust the client to send a
|
|
||||||
sane file
|
|
||||||
|
|
||||||
Background:
|
|
||||||
Given internal/infrastructure/useCases.CreateImageUseCase.CreateImage
|
|
||||||
already checks the uploaded content type against the allowed list
|
|
||||||
(image/png, image/jpeg, image/webp, image/svg+xml) and the size
|
|
||||||
against the 10485760-byte maximum before calling image.Repository.Create,
|
|
||||||
returning image.ErrImageTypeNotAllowed or image.ErrImageTooLarge and
|
|
||||||
calling the repository not at all when either check fails
|
|
||||||
And internal/infrastructure/persistence's ArticleRepository.AddImage
|
|
||||||
already returns article.ErrArticleNotFound when the article id doesn't
|
|
||||||
match any row, and image.ErrImageNotFound when the article exists but
|
|
||||||
the image id doesn't, both asserted with errors.Is
|
|
||||||
And before this slice, api/handlers/image.Handler.PostImage existed and
|
|
||||||
was wired to CreateImageUseCase and UpdateArticleUseCase.AddImage, but
|
|
||||||
no route called it, and every error it got back from either use case
|
|
||||||
fell through to a blanket 500
|
|
||||||
And this slice mounts POST /v1/article/{id}/image in api/router.go, in
|
|
||||||
the same jwtauth Verifier + Authenticator group as the other article
|
|
||||||
write routes, and changes the upload flow so that the article's
|
|
||||||
existence is confirmed before the image is created, so that an
|
|
||||||
unknown article id never leaves an orphaned image behind
|
|
||||||
And this slice changes PostImage's error handling so that errors.Is(err,
|
|
||||||
image.ErrImageTypeNotAllowed) or errors.Is(err, image.ErrImageTooLarge)
|
|
||||||
answers 400 with the sentinel's own message, errors.Is(err,
|
|
||||||
article.ErrArticleNotFound) answers 404 with body
|
|
||||||
apperr.ArticleNotFoundErrorMessage, and any other error still falls
|
|
||||||
back to a generic 500
|
|
||||||
And PostImage reads the uploaded file from the multipart form field
|
|
||||||
"file"
|
|
||||||
And on success PostImage answers 201 with a JSON body
|
|
||||||
{"id": ..., "location": ...} holding the created image's numeric id
|
|
||||||
and public path, e.g. "/static/uploadedImages/<stored-filename>"
|
|
||||||
And this slice (features/remove_article_image.feature) adds the "id"
|
|
||||||
field to that body; the id lets a client later address the image
|
|
||||||
through DELETE /v1/article/{id}/image/{imageId}
|
|
||||||
|
|
||||||
Scenario: Uploading an allowed image type to an existing article succeeds
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository contains an article with id 1 titled
|
|
||||||
"Backyard Renovation Update"
|
|
||||||
When the client sends POST /v1/article/1/image with that cookie and a
|
|
||||||
multipart form field "file" holding a file named "before.png" with
|
|
||||||
content type "image/png"
|
|
||||||
Then the response status is 201
|
|
||||||
And the response body is JSON with a "location" field whose value is
|
|
||||||
"/static/uploadedImages/before.png"
|
|
||||||
And the response body's "id" field equals the new image's id in the
|
|
||||||
image repository
|
|
||||||
And the image repository contains a new image whose Path is
|
|
||||||
"/static/uploadedImages/before.png"
|
|
||||||
And the article repository's article with id 1 has that new image's id
|
|
||||||
in its Images slice
|
|
||||||
|
|
||||||
Scenario: Uploading to an unknown article answers 404 and creates no image
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository has no article with id 9999
|
|
||||||
When the client sends POST /v1/article/9999/image with that cookie and a
|
|
||||||
multipart form field "file" holding a file named "before.png" with
|
|
||||||
content type "image/png"
|
|
||||||
Then the response status is 404
|
|
||||||
And the response body is the text "Article not found"
|
|
||||||
And the image repository's Create is never called
|
|
||||||
And no image exists in the image repository
|
|
||||||
|
|
||||||
Scenario: Uploading a disallowed content type answers 400 before the article is touched
|
|
||||||
Given a valid jwt cookie for a user with id 1
|
|
||||||
And the article repository contains an article with id 1 titled
|
|
||||||
"Backyard Renovation Update"
|
|
||||||
When the client sends POST /v1/article/1/image with that cookie and a
|
|
||||||
multipart form field "file" holding a file named "notes.pdf" with
|
|
||||||
content type "application/pdf"
|
|
||||||
Then the response status is 400
|
|
||||||
And the response body is the text
|
|
||||||
"the file must be a PNG, JPEG, WEBP, or SVG image"
|
|
||||||
And the image repository's Create is never called
|
|
||||||
And the article repository's article with id 1 still has an empty
|
|
||||||
Images slice
|
|
||||||
|
|
||||||
Scenario: Uploading an image still requires authentication
|
|
||||||
Given no jwt cookie is sent
|
|
||||||
And the article repository contains an article with id 1 titled
|
|
||||||
"Backyard Renovation Update"
|
|
||||||
When the client sends POST /v1/article/1/image without a cookie and a
|
|
||||||
multipart form field "file" holding a file named "before.png" with
|
|
||||||
content type "image/png"
|
|
||||||
Then the response status is 401
|
|
||||||
And the image repository's Create is never called
|
|
||||||
And the article repository's article with id 1 still has an empty
|
|
||||||
Images slice
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
# QA procedure: upload_article_image
|
|
||||||
|
|
||||||
Package: `test` (black-box, extending `article_test.go` / `image_test.go`).
|
|
||||||
|
|
||||||
## Setup shared by every case
|
|
||||||
1. Call `validator.InitValidator()` once.
|
|
||||||
2. Reuse `mockArticleRepo` (`test/article_test.go`) and `mockImageRepo`
|
|
||||||
(`test/image_test.go`) as-is; both already implement `AddImage` /
|
|
||||||
`Create` returning `article.ErrArticleNotFound` / `image.ErrImageNotFound`
|
|
||||||
for an unknown id, per `features/write_not_found_errors.feature`.
|
|
||||||
3. Wire the real use cases over the fakes: `useCases.NewCreateArticleUseCase`,
|
|
||||||
`useCases.NewGetArticleUseCase`, `useCases.NewListArticlesUseCase`,
|
|
||||||
`useCases.NewUpdateArticleUseCase(articleRepo)`,
|
|
||||||
`useCases.NewDeleteArticleUseCase(articleRepo, imageRepo)`,
|
|
||||||
`useCases.NewCreateImageUseCase(imageRepo)`.
|
|
||||||
4. Build `article.NewHandler(...)` with its existing constructor shape, and
|
|
||||||
`image.NewHandler(createImageUseCase, updateArticleUseCase)`
|
|
||||||
(`api/handlers/image`).
|
|
||||||
5. Build a test `jwtauth.New("HS256", []byte("test-secret"), nil)`.
|
|
||||||
6. Mount the routes on a fresh `chi.NewRouter()` mirroring `api/router.go`'s
|
|
||||||
shape after this slice: `GET /` under `jwtauth.Verifier` only;
|
|
||||||
`GET /{id}`, `POST /`, `DELETE /{id}`, `PATCH /{id}`,
|
|
||||||
`PATCH /{id}/publish`, `PATCH /{id}/unpublish` and the new
|
|
||||||
`POST /{id}/image` (routed to `imageHandler.PostImage`) under
|
|
||||||
`jwtauth.Verifier` + `jwtauth.Authenticator`.
|
|
||||||
7. Mint a valid jwt cookie for user id 1:
|
|
||||||
`token.Encode(map[string]any{"user_id": uint32(1)})`, set as the `jwt`
|
|
||||||
cookie on the relevant `httptest.NewRequest`.
|
|
||||||
8. Build multipart request bodies with `mime/multipart.Writer`, field name
|
|
||||||
`"file"`, setting the part's `Content-Type` header explicitly (Go's
|
|
||||||
multipart writer defaults to sniffing otherwise, so set it via
|
|
||||||
`CreatePart` with an explicit MIME header rather than
|
|
||||||
`CreateFormFile`), and set the request's `Content-Type` header to the
|
|
||||||
writer's `FormDataContentType()`.
|
|
||||||
|
|
||||||
## HTTP checks
|
|
||||||
9. Seed `articleRepo.articles[1] = article.Article{ID: 1, Title: "Backyard
|
|
||||||
Renovation Update"}`. Send `POST /v1/article/1/image` with the valid
|
|
||||||
cookie and a multipart `"file"` part named `"before.png"`,
|
|
||||||
content type `"image/png"`, some non-empty byte content. Assert status
|
|
||||||
`201`; decode the JSON body and assert `location` equals
|
|
||||||
`"/static/uploadedImages/before.png"`; assert `imageRepo.images` gained
|
|
||||||
exactly one entry whose `Path` matches that location; assert
|
|
||||||
`articleRepo.articles[1].Images` now contains that image's id.
|
|
||||||
10. Empty `articleRepo`, empty `imageRepo`. Send `POST /v1/article/9999/image`
|
|
||||||
with the valid cookie and the same `"before.png"` / `"image/png"` part.
|
|
||||||
Assert status `404`, body `"Article not found\n"`; assert
|
|
||||||
`imageRepo.images` is still empty (the article's existence is confirmed
|
|
||||||
before any image is created, so nothing is left orphaned).
|
|
||||||
11. Seed `articleRepo.articles[1] = article.Article{ID: 1, Title: "Backyard
|
|
||||||
Renovation Update"}` with an empty `Images` slice. Send
|
|
||||||
`POST /v1/article/1/image` with the valid cookie and a multipart
|
|
||||||
`"file"` part named `"notes.pdf"`, content type `"application/pdf"`.
|
|
||||||
Assert status `400`, body
|
|
||||||
`"the file must be a PNG, JPEG, WEBP, or SVG image\n"`; assert
|
|
||||||
`imageRepo.images` is still empty; assert
|
|
||||||
`articleRepo.articles[1].Images` is still empty.
|
|
||||||
12. Seed the same article id 1 as step 11. Send `POST /v1/article/1/image`
|
|
||||||
with **no** cookie and the `"before.png"` / `"image/png"` part. Assert
|
|
||||||
status `401`; assert `imageRepo.images` is still empty; assert
|
|
||||||
`articleRepo.articles[1].Images` is still empty.
|
|
||||||
|
|
||||||
## Manual verification (not exercised by the Go test)
|
|
||||||
- Real upload against a real SQLite file and real `UPLOAD_DIR`: confirm that
|
|
||||||
after `POST /v1/article/{id}/image` on a real running instance, the file
|
|
||||||
actually lands on disk under `UPLOAD_DIR`, the `images` row's `path`
|
|
||||||
resolves to a URL the SPA can load, and the `article_images` join table
|
|
||||||
gets the new row. Not exercised by `task test` (fakes only); requires
|
|
||||||
`task dev` or a built `task build` binary with a scratch DB/upload dir.
|
|
||||||
- SPA-visible behaviour: confirm the back-office article editor (if/when an
|
|
||||||
image-upload UI exists) shows the uploaded image at that location. No such
|
|
||||||
UI exists yet as of this slice.
|
|
||||||
- No SMTP involvement.
|
|
||||||
@@ -12,12 +12,12 @@ Feature: Protected article routes and the offline-inclusive listing require a ve
|
|||||||
Given before this slice, the protected group inside NewArticleRouter (api/router.go) applies
|
Given before this slice, the protected group inside NewArticleRouter (api/router.go) applies
|
||||||
only jwtauth.Verifier then jwtauth.Authenticator to GET /v1/article/{id}, POST /v1/article/,
|
only jwtauth.Verifier then jwtauth.Authenticator to GET /v1/article/{id}, POST /v1/article/,
|
||||||
DELETE /v1/article/{id}, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish,
|
DELETE /v1/article/{id}, PATCH /v1/article/{id}, PATCH /v1/article/{id}/publish,
|
||||||
PATCH /v1/article/{id}/unpublish and POST /v1/article/{id}/image, so any caller with a
|
PATCH /v1/article/{id}/unpublish, so any caller with a
|
||||||
validly signed, unexpired jwt cookie reaches the handler regardless of that account's
|
validly signed, unexpired jwt cookie reaches the handler regardless of that account's
|
||||||
is_verified status
|
is_verified status
|
||||||
And this slice adds a third middleware, api/middleware.RequireVerifiedUser(getUser
|
And this slice adds a third middleware, api/middleware.RequireVerifiedUser(getUser
|
||||||
*useCases.GetUserUseCase), mounted after jwtauth.Authenticator in that same group, so the
|
*useCases.GetUserUseCase), mounted after jwtauth.Authenticator in that same group, so the
|
||||||
order becomes Verifier, Authenticator, RequireVerifiedUser for all seven routes above
|
order becomes Verifier, Authenticator, RequireVerifiedUser for all six routes above
|
||||||
And RequireVerifiedUser reads user_id from the request's jwt claims using a new exported
|
And RequireVerifiedUser reads user_id from the request's jwt claims using a new exported
|
||||||
helper, api/pkg/claims.UserId(r *http.Request) (uint32, bool), which replaces the
|
helper, api/pkg/claims.UserId(r *http.Request) (uint32, bool), which replaces the
|
||||||
identical private userIdFromClaims method api/handlers/auth.Handler.Verify and
|
identical private userIdFromClaims method api/handlers/auth.Handler.Verify and
|
||||||
@@ -81,16 +81,6 @@ Feature: Protected article routes and the offline-inclusive listing require a ve
|
|||||||
| PATCH | /v1/article/1/publish |
|
| PATCH | /v1/article/1/publish |
|
||||||
| PATCH | /v1/article/1/unpublish |
|
| PATCH | /v1/article/1/unpublish |
|
||||||
|
|
||||||
Scenario: An unverified user is also refused when attaching an image
|
|
||||||
Given a user repository containing user id 1, is_verified false
|
|
||||||
And a valid jwt cookie for user id 1
|
|
||||||
And the article repository contains an article with id 1 titled "Backyard Renovation Update"
|
|
||||||
When the client sends POST /v1/article/1/image with that cookie and a multipart form field
|
|
||||||
"file" holding a file named "before.png" with content type "image/png"
|
|
||||||
Then the response status is 403
|
|
||||||
And the response body is the apperr.VerificationRequiredErrorMessage text
|
|
||||||
And the image repository's Create is never called
|
|
||||||
|
|
||||||
Scenario: A verified user still exercises the protected routes exactly as before
|
Scenario: A verified user still exercises the protected routes exactly as before
|
||||||
Given a user repository containing user id 1, is_verified true
|
Given a user repository containing user id 1, is_verified true
|
||||||
And a valid jwt cookie for user id 1
|
And a valid jwt cookie for user id 1
|
||||||
|
|||||||
@@ -29,8 +29,7 @@ routers, so the HTTP-level checks live in a new `test/verified_account_required_
|
|||||||
- a nested `r.Group` adding `jwtauth.Authenticator(token)` then
|
- a nested `r.Group` adding `jwtauth.Authenticator(token)` then
|
||||||
`middleware.RequireVerifiedUser(getUser)`, containing `r.Get("/{id}", ...)`,
|
`middleware.RequireVerifiedUser(getUser)`, containing `r.Get("/{id}", ...)`,
|
||||||
`r.Post("/", ...)`, `r.Delete("/{id}", ...)`, `r.Patch("/{id}", ...)`,
|
`r.Post("/", ...)`, `r.Delete("/{id}", ...)`, `r.Patch("/{id}", ...)`,
|
||||||
`r.Patch("/{id}/publish", ...)`, `r.Patch("/{id}/unpublish", ...)`,
|
`r.Patch("/{id}/publish", ...)`, `r.Patch("/{id}/unpublish", ...)`
|
||||||
`r.Post("/{id}/image", ...)`
|
|
||||||
No live server.
|
No live server.
|
||||||
8. Mint jwt cookies with `token.Encode(map[string]any{"user_id": uint32(1)})` for the valid-token
|
8. Mint jwt cookies with `token.Encode(map[string]any{"user_id": uint32(1)})` for the valid-token
|
||||||
cases, following the convention in `features/article_publishing.qa.md`.
|
cases, following the convention in `features/article_publishing.qa.md`.
|
||||||
@@ -45,10 +44,6 @@ routers, so the HTTP-level checks live in a new `test/verified_account_required_
|
|||||||
`PATCH /v1/article/1/unpublish`, each sent with the valid cookie from step 8 → assert status
|
`PATCH /v1/article/1/unpublish`, each sent with the valid cookie from step 8 → assert status
|
||||||
`403` and body exactly `apperr.VerificationRequiredErrorMessage`. Assert the article repository
|
`403` and body exactly `apperr.VerificationRequiredErrorMessage`. Assert the article repository
|
||||||
was not mutated by any of the write calls.
|
was not mutated by any of the write calls.
|
||||||
11. Same seed, `POST /v1/article/1/image` with the valid cookie and a multipart form field `"file"`
|
|
||||||
holding `before.png` / `image/png` → assert status `403`, body
|
|
||||||
`apperr.VerificationRequiredErrorMessage`, and the image repository's `Create` is never called
|
|
||||||
(mirroring the assertion style in `test/upload_article_image_test.go`).
|
|
||||||
|
|
||||||
## HTTP checks: a verified caller is unaffected
|
## HTTP checks: a verified caller is unaffected
|
||||||
|
|
||||||
@@ -127,7 +122,7 @@ routers, so the HTTP-level checks live in a new `test/verified_account_required_
|
|||||||
## Manual verification (not exercised by the Go test)
|
## Manual verification (not exercised by the Go test)
|
||||||
|
|
||||||
- The SPA-visible behaviour of an unverified, logged-in user landing on the back-office article
|
- The SPA-visible behaviour of an unverified, logged-in user landing on the back-office article
|
||||||
screens (create/edit/publish/image-upload) and seeing a 403 instead of the normal editing UI,
|
screens (create/edit/publish) and seeing a 403 instead of the normal editing UI,
|
||||||
and the front-office/back-office listing showing only published articles to that same unverified
|
and the front-office/back-office listing showing only published articles to that same unverified
|
||||||
session, is out of scope for this slice's automated test and should be checked by hand against a
|
session, is out of scope for this slice's automated test and should be checked by hand against a
|
||||||
running dev build with an unverified test account.
|
running dev build with an unverified test account.
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ require (
|
|||||||
github.com/google/uuid v1.6.0
|
github.com/google/uuid v1.6.0
|
||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
golang.org/x/crypto v0.44.0
|
golang.org/x/crypto v0.44.0
|
||||||
|
golang.org/x/image v0.46.0
|
||||||
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
|
||||||
gorm.io/gorm v1.31.1
|
gorm.io/gorm v1.31.1
|
||||||
)
|
)
|
||||||
@@ -41,8 +42,8 @@ require (
|
|||||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
github.com/segmentio/asm v1.2.1 // indirect
|
github.com/segmentio/asm v1.2.1 // indirect
|
||||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect
|
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 // indirect
|
||||||
golang.org/x/sys v0.38.0 // indirect
|
golang.org/x/sys v0.48.0 // indirect
|
||||||
golang.org/x/text v0.31.0 // indirect
|
golang.org/x/text v0.42.0 // indirect
|
||||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||||
modernc.org/libc v1.67.0 // indirect
|
modernc.org/libc v1.67.0 // indirect
|
||||||
modernc.org/mathutil v1.7.1 // indirect
|
modernc.org/mathutil v1.7.1 // indirect
|
||||||
|
|||||||
@@ -82,17 +82,19 @@ golang.org/x/crypto v0.44.0 h1:A97SsFvM3AIwEEmTBiaxPPTYpDC47w720rdiiUvgoAU=
|
|||||||
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
|
golang.org/x/crypto v0.44.0/go.mod h1:013i+Nw79BMiQiMsOPcVCB5ZIJbYkerPrGnOa00tvmc=
|
||||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0=
|
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6 h1:zfMcR1Cs4KNuomFFgGefv5N0czO2XZpUbxGUy8i8ug0=
|
||||||
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0=
|
golang.org/x/exp v0.0.0-20251113190631-e25ba8c21ef6/go.mod h1:46edojNIoXTNOhySWIWdix628clX9ODXwPsQuG6hsK0=
|
||||||
golang.org/x/mod v0.30.0 h1:fDEXFVZ/fmCKProc/yAXXUijritrDzahmwwefnjoPFk=
|
golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ=
|
||||||
golang.org/x/mod v0.30.0/go.mod h1:lAsf5O2EvJeSFMiBxXDki7sCgAxEUcZHXoXMKT4GJKc=
|
golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew=
|
||||||
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
|
golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=
|
||||||
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=
|
||||||
|
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||||
|
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
|
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||||
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
|
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||||
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
|
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||||
golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ=
|
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||||
golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ=
|
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
|
||||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package article
|
package article
|
||||||
|
|
||||||
import (
|
import (
|
||||||
domain "RenewCMS/internal/domain/image"
|
|
||||||
"errors"
|
"errors"
|
||||||
"time"
|
"time"
|
||||||
"unicode/utf8"
|
"unicode/utf8"
|
||||||
@@ -30,7 +29,6 @@ type Article struct {
|
|||||||
ID uint32 `json:"id"`
|
ID uint32 `json:"id"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Body string `json:"body"`
|
Body string `json:"body"`
|
||||||
Images []*domain.Image `json:"images"`
|
|
||||||
IsOnline bool `json:"is_online"`
|
IsOnline bool `json:"is_online"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
|||||||
@@ -13,5 +13,5 @@ type Repository interface {
|
|||||||
UpdateBody(id uint32, body string) (Article, error)
|
UpdateBody(id uint32, body string) (Article, error)
|
||||||
UpdateIsOnline(id uint32, isOnline bool) (Article, error)
|
UpdateIsOnline(id uint32, isOnline bool) (Article, error)
|
||||||
Delete(id uint32) error
|
Delete(id uint32) error
|
||||||
AddImage(postId uint32, imageId uint32) error
|
FindByBodyContaining(filename string) ([]Article, error)
|
||||||
}
|
}
|
||||||
@@ -3,16 +3,33 @@ package image
|
|||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
|
"path"
|
||||||
|
"regexp"
|
||||||
"sort"
|
"sort"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
)
|
)
|
||||||
|
|
||||||
var ErrImageNotFound = errors.New("image not found")
|
var ErrImageNotFound = errors.New("image not found")
|
||||||
var ErrImageTypeNotAllowed = errors.New("the file must be a PNG, JPEG, WEBP, or SVG image")
|
var ErrImageTypeNotAllowed = errors.New("the file must be a PNG, JPEG, WEBP, or SVG image")
|
||||||
var ErrImageTooLarge = errors.New("the file exceeds the maximum upload size")
|
var ErrImageTooLarge = errors.New("the file exceeds the maximum upload size")
|
||||||
|
var ErrImageUnreadable = errors.New("the image could not be read")
|
||||||
|
var ErrInvalidFilename = errors.New("invalid filename")
|
||||||
|
var ErrInvalidQuery = errors.New("invalid media query")
|
||||||
|
var ErrInvalidMergeRequest = errors.New("invalid merge request")
|
||||||
|
var ErrMergeCopyMissing = errors.New("a merged copy no longer exists")
|
||||||
|
var ErrMergeHashMismatch = errors.New("a merged copy does not share the kept image's content")
|
||||||
|
|
||||||
const MaxImageSize int64 = 10485760
|
const MaxImageSize int64 = 10485760
|
||||||
|
|
||||||
|
const (
|
||||||
|
MinFilenameRunes = 1
|
||||||
|
MaxFilenameRunes = 100
|
||||||
|
DefaultListLimit = 24
|
||||||
|
MaxListLimit = 100
|
||||||
|
)
|
||||||
|
|
||||||
var allowedContentTypes = map[string]bool{
|
var allowedContentTypes = map[string]bool{
|
||||||
"image/png": true,
|
"image/png": true,
|
||||||
"image/jpeg": true,
|
"image/jpeg": true,
|
||||||
@@ -20,6 +37,16 @@ var allowedContentTypes = map[string]bool{
|
|||||||
"image/svg+xml": true,
|
"image/svg+xml": true,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var canonicalExtensions = map[string]string{
|
||||||
|
"image/png": ".png",
|
||||||
|
"image/jpeg": ".jpg",
|
||||||
|
"image/webp": ".webp",
|
||||||
|
"image/svg+xml": ".svg",
|
||||||
|
}
|
||||||
|
|
||||||
|
var filenameStemPattern = regexp.MustCompile(`^[\p{L}\p{N}_-]+$`)
|
||||||
|
var sha256Pattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
||||||
|
|
||||||
func IsAllowedContentType(contentType string) bool {
|
func IsAllowedContentType(contentType string) bool {
|
||||||
return allowedContentTypes[contentType]
|
return allowedContentTypes[contentType]
|
||||||
}
|
}
|
||||||
@@ -33,17 +60,147 @@ func AllowedContentTypes() []string {
|
|||||||
return types
|
return types
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func NormalizeUploadFilename(original string, contentType string) string {
|
||||||
|
name := original[strings.LastIndexAny(original, `/\`)+1:]
|
||||||
|
name = strings.TrimSpace(name)
|
||||||
|
if name == "" || name == "." {
|
||||||
|
name = "image"
|
||||||
|
}
|
||||||
|
if path.Ext(name) == "" {
|
||||||
|
name += canonicalExtensions[contentType]
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExtensionOf(filename string) string {
|
||||||
|
return path.Ext(filename)
|
||||||
|
}
|
||||||
|
|
||||||
|
func StemOf(filename string) string {
|
||||||
|
return strings.TrimSuffix(filename, path.Ext(filename))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidateFilenameStem(stem string) (string, error) {
|
||||||
|
trimmed := strings.TrimSpace(stem)
|
||||||
|
runeCount := utf8.RuneCountInString(trimmed)
|
||||||
|
if runeCount < MinFilenameRunes || runeCount > MaxFilenameRunes {
|
||||||
|
return "", ErrInvalidFilename
|
||||||
|
}
|
||||||
|
if !filenameStemPattern.MatchString(trimmed) {
|
||||||
|
return "", ErrInvalidFilename
|
||||||
|
}
|
||||||
|
return trimmed, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func StoredName(imagePath string) string {
|
||||||
|
return path.Base(imagePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Sort string
|
||||||
|
|
||||||
|
const (
|
||||||
|
SortNewest Sort = "newest"
|
||||||
|
SortOldest Sort = "oldest"
|
||||||
|
SortName Sort = "name"
|
||||||
|
SortLargest Sort = "largest"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Filter string
|
||||||
|
|
||||||
|
const (
|
||||||
|
FilterAll Filter = "all"
|
||||||
|
FilterUnused Filter = "unused"
|
||||||
|
FilterDuplicates Filter = "duplicates"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ListQuery struct {
|
||||||
|
Search string
|
||||||
|
Hash string
|
||||||
|
Filter Filter
|
||||||
|
Sort Sort
|
||||||
|
Limit int
|
||||||
|
Cursor string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewListQuery() ListQuery {
|
||||||
|
return ListQuery{Filter: FilterAll, Sort: SortNewest, Limit: DefaultListLimit}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q ListQuery) Validate() error {
|
||||||
|
switch q.Filter {
|
||||||
|
case FilterAll, FilterUnused, FilterDuplicates:
|
||||||
|
default:
|
||||||
|
return ErrInvalidQuery
|
||||||
|
}
|
||||||
|
switch q.Sort {
|
||||||
|
case SortNewest, SortOldest, SortName, SortLargest:
|
||||||
|
default:
|
||||||
|
return ErrInvalidQuery
|
||||||
|
}
|
||||||
|
if q.Limit < 1 || q.Limit > MaxListLimit {
|
||||||
|
return ErrInvalidQuery
|
||||||
|
}
|
||||||
|
if q.Hash != "" && !sha256Pattern.MatchString(q.Hash) {
|
||||||
|
return ErrInvalidQuery
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func SortImages(images []Image, order Sort) {
|
||||||
|
sort.SliceStable(images, func(i, j int) bool {
|
||||||
|
a, b := images[i], images[j]
|
||||||
|
switch order {
|
||||||
|
case SortOldest:
|
||||||
|
if !a.CreatedAt.Equal(b.CreatedAt) {
|
||||||
|
return a.CreatedAt.Before(b.CreatedAt)
|
||||||
|
}
|
||||||
|
return a.ID < b.ID
|
||||||
|
case SortName:
|
||||||
|
nameA, nameB := strings.ToLower(StemOf(a.Filename)), strings.ToLower(StemOf(b.Filename))
|
||||||
|
if nameA != nameB {
|
||||||
|
return nameA < nameB
|
||||||
|
}
|
||||||
|
return a.ID < b.ID
|
||||||
|
case SortLargest:
|
||||||
|
if a.Size != b.Size {
|
||||||
|
return a.Size > b.Size
|
||||||
|
}
|
||||||
|
return a.ID < b.ID
|
||||||
|
default:
|
||||||
|
if !a.CreatedAt.Equal(b.CreatedAt) {
|
||||||
|
return a.CreatedAt.After(b.CreatedAt)
|
||||||
|
}
|
||||||
|
return a.ID > b.ID
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
type Counts struct {
|
||||||
|
All int
|
||||||
|
DuplicateGroups int
|
||||||
|
}
|
||||||
|
|
||||||
type ImageInput struct {
|
type ImageInput struct {
|
||||||
Content io.Reader
|
Content io.Reader
|
||||||
Filename string
|
Filename string
|
||||||
Size int64
|
Size int64
|
||||||
ContentType string
|
ContentType string
|
||||||
|
Width int
|
||||||
|
Height int
|
||||||
|
SHA256 string
|
||||||
|
UploadedByID uint32
|
||||||
}
|
}
|
||||||
|
|
||||||
type Image struct {
|
type Image struct {
|
||||||
ID uint32 `json:"id"`
|
ID uint32 `json:"id"`
|
||||||
Path string `json:"path"`
|
Path string `json:"path"`
|
||||||
ArticleID uint32 `json:"article_id"`
|
Filename string `json:"filename"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
ContentType string `json:"content_type"`
|
||||||
|
Width int `json:"width"`
|
||||||
|
Height int `json:"height"`
|
||||||
|
SHA256 string `json:"sha256"`
|
||||||
|
UploadedByID uint32 `json:"uploaded_by_id"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,17 @@
|
|||||||
package image
|
package image
|
||||||
|
|
||||||
|
type SearchQuery struct {
|
||||||
|
Search string
|
||||||
|
Hash string
|
||||||
|
}
|
||||||
|
|
||||||
type Repository interface {
|
type Repository interface {
|
||||||
Create(input ImageInput) (Image, error)
|
Create(input ImageInput) (Image, error)
|
||||||
|
Get(id uint32) (Image, error)
|
||||||
Delete(id uint32) error
|
Delete(id uint32) error
|
||||||
|
List(query SearchQuery) ([]Image, error)
|
||||||
|
FindByHash(hash string) ([]Image, error)
|
||||||
|
Rename(id uint32, filename string) (Image, error)
|
||||||
|
ListDuplicates() ([]Image, error)
|
||||||
|
Counts() (Counts, error)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const StateIdle = "idle"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrNoRelease = errors.New("no release found")
|
||||||
|
ErrInvalidVersion = errors.New("invalid version")
|
||||||
|
ErrFeedUnavailable = errors.New("release feed unavailable")
|
||||||
|
)
|
||||||
|
|
||||||
|
type ReleaseNotes struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
ReleasedAt time.Time `json:"released_at"`
|
||||||
|
Items []string `json:"items"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Asset struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
URL string `json:"url"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Release struct {
|
||||||
|
Tag string
|
||||||
|
URL string
|
||||||
|
PublishedAt time.Time
|
||||||
|
Notes ReleaseNotes
|
||||||
|
Assets []Asset
|
||||||
|
}
|
||||||
|
|
||||||
|
type CheckResult struct {
|
||||||
|
Latest string `json:"latest"`
|
||||||
|
ReleaseURL string `json:"release_url"`
|
||||||
|
Notes ReleaseNotes `json:"notes"`
|
||||||
|
Assets []Asset `json:"assets"`
|
||||||
|
CheckedAt time.Time `json:"checked_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Progress struct {
|
||||||
|
Percent int `json:"percent"`
|
||||||
|
DownloadedBytes int64 `json:"downloaded_bytes"`
|
||||||
|
TotalBytes int64 `json:"total_bytes"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateStatus struct {
|
||||||
|
Current string `json:"current"`
|
||||||
|
Latest string `json:"latest"`
|
||||||
|
Available bool `json:"available"`
|
||||||
|
ReleaseURL *string `json:"release_url"`
|
||||||
|
Notes *ReleaseNotes `json:"notes"`
|
||||||
|
CheckedAt *time.Time `json:"checked_at"`
|
||||||
|
CanApply bool `json:"can_apply"`
|
||||||
|
State string `json:"state"`
|
||||||
|
Progress *Progress `json:"progress"`
|
||||||
|
Error *string `json:"error"`
|
||||||
|
StartedAt *time.Time `json:"started_at"`
|
||||||
|
FinishedAt *time.Time `json:"finished_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewResult(release Release, checkedAt time.Time) CheckResult {
|
||||||
|
return CheckResult{
|
||||||
|
Latest: release.Tag,
|
||||||
|
ReleaseURL: release.URL,
|
||||||
|
Notes: release.Notes,
|
||||||
|
Assets: release.Assets,
|
||||||
|
CheckedAt: checkedAt.UTC(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStatus(current string, result *CheckResult) UpdateStatus {
|
||||||
|
status := UpdateStatus{Current: current, State: StateIdle}
|
||||||
|
if result == nil {
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
releaseURL := result.ReleaseURL
|
||||||
|
notes := result.Notes
|
||||||
|
notes.Items = nonNilItems(notes.Items)
|
||||||
|
checkedAt := result.CheckedAt
|
||||||
|
status.Latest = result.Latest
|
||||||
|
status.Available = IsNewer(current, result.Latest)
|
||||||
|
status.ReleaseURL = &releaseURL
|
||||||
|
status.Notes = ¬es
|
||||||
|
status.CheckedAt = &checkedAt
|
||||||
|
return status
|
||||||
|
}
|
||||||
|
|
||||||
|
func nonNilItems(items []string) []string {
|
||||||
|
if items == nil {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
return items
|
||||||
|
}
|
||||||
|
|
||||||
|
func Newest(releases []Release) (Release, error) {
|
||||||
|
var newest Release
|
||||||
|
found := false
|
||||||
|
for _, release := range releases {
|
||||||
|
if _, err := ParseVersion(release.Tag); err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !found || IsNewer(newest.Tag, release.Tag) {
|
||||||
|
newest = release
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
return Release{}, ErrNoRelease
|
||||||
|
}
|
||||||
|
return newest, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrNeedsLinux = errors.New("Browser updates need Linux with systemd.")
|
||||||
|
ErrNeedsSystemd = errors.New("Browser updates need systemd, which this machine is not running.")
|
||||||
|
ErrNeedsRoot = errors.New("Run this command as root, for example with sudo.")
|
||||||
|
ErrServiceNotFound = errors.New("Could not find the RenewCMS service. Pass --service, --binary and --data-dir.")
|
||||||
|
ErrDataDirNotFound = errors.New("Could not find the data directory. Pass --data-dir.")
|
||||||
|
ErrInvalidPort = errors.New("The port must be a number between 1 and 65535.")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
OSLinux = "linux"
|
||||||
|
pathUnitDescription = "Watch for a RenewCMS restart request"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ServiceDescription struct {
|
||||||
|
Name string
|
||||||
|
BinaryPath string
|
||||||
|
DataDir string
|
||||||
|
EnvironmentFile string
|
||||||
|
}
|
||||||
|
|
||||||
|
type InstallOptions struct {
|
||||||
|
Service string
|
||||||
|
Binary string
|
||||||
|
DataDir string
|
||||||
|
Port string
|
||||||
|
}
|
||||||
|
|
||||||
|
type MachineProbe interface {
|
||||||
|
OS() string
|
||||||
|
SystemdRunning() bool
|
||||||
|
IsRoot() bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServiceLocator interface {
|
||||||
|
Locate(name string) (ServiceDescription, bool)
|
||||||
|
PortFromEnvironmentFile(path string) (string, bool)
|
||||||
|
}
|
||||||
|
|
||||||
|
type UnitWriter interface {
|
||||||
|
Write(name string, content string) error
|
||||||
|
Remove(name string) (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type UnitManager interface {
|
||||||
|
DaemonReload() error
|
||||||
|
EnableNow(unit string) error
|
||||||
|
DisableNow(unit string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type HelperStatusWriter interface {
|
||||||
|
Write(dataDir string, status HelperStatus) error
|
||||||
|
Remove(dataDir string) (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func CheckInstallEnvironment(probe MachineProbe) error {
|
||||||
|
if probe.OS() != OSLinux {
|
||||||
|
return ErrNeedsLinux
|
||||||
|
}
|
||||||
|
if !probe.SystemdRunning() {
|
||||||
|
return ErrNeedsSystemd
|
||||||
|
}
|
||||||
|
if !probe.IsRoot() {
|
||||||
|
return ErrNeedsRoot
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidatePort(port string) error {
|
||||||
|
number, err := strconv.Atoi(port)
|
||||||
|
if err != nil || number < 1 || number > 65535 {
|
||||||
|
return ErrInvalidPort
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func RenderPathUnit(layout HelperLayout) string {
|
||||||
|
lines := []string{
|
||||||
|
"[Unit]",
|
||||||
|
"Description=" + pathUnitDescription,
|
||||||
|
"",
|
||||||
|
"[Path]",
|
||||||
|
"PathExists=" + layout.RestartRequestPath(),
|
||||||
|
"Unit=" + ServiceUnitName,
|
||||||
|
"",
|
||||||
|
"[Install]",
|
||||||
|
"WantedBy=multi-user.target",
|
||||||
|
"",
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
func RenderServiceUnit(options InstallOptions) string {
|
||||||
|
command := []string{
|
||||||
|
quoteUnitArgument(options.Binary),
|
||||||
|
"apply-update",
|
||||||
|
"--service", quoteUnitArgument(options.Service),
|
||||||
|
"--binary", quoteUnitArgument(options.Binary),
|
||||||
|
"--data-dir", quoteUnitArgument(options.DataDir),
|
||||||
|
"--port", options.Port,
|
||||||
|
}
|
||||||
|
lines := []string{
|
||||||
|
"[Unit]",
|
||||||
|
"Description=RenewCMS update helper",
|
||||||
|
"",
|
||||||
|
"[Service]",
|
||||||
|
"Type=oneshot",
|
||||||
|
"User=root",
|
||||||
|
"ExecStart=" + strings.Join(command, " "),
|
||||||
|
"",
|
||||||
|
}
|
||||||
|
return strings.Join(lines, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
var unitArgumentEscaper = strings.NewReplacer(
|
||||||
|
`\`, `\\`,
|
||||||
|
`"`, `\"`,
|
||||||
|
`%`, `%%`,
|
||||||
|
`$`, `$$`,
|
||||||
|
"\n", `\n`,
|
||||||
|
"\r", `\r`,
|
||||||
|
"\t", `\t`,
|
||||||
|
)
|
||||||
|
|
||||||
|
func quoteUnitArgument(value string) string {
|
||||||
|
if !strings.ContainsAny(value, " \t\r\n\"'\\%$;") {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return `"` + unitArgumentEscaper.Replace(value) + `"`
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
StateDownloading = "downloading"
|
||||||
|
StateVerifying = "verifying"
|
||||||
|
StateReady = "ready"
|
||||||
|
StateFailed = "failed"
|
||||||
|
|
||||||
|
ErrorKindDownload = "download"
|
||||||
|
ErrorKindVerification = "verification"
|
||||||
|
|
||||||
|
ChecksumsAssetName = "checksums.txt"
|
||||||
|
SignatureAssetName = "checksums.txt.sig"
|
||||||
|
|
||||||
|
windowsOS = "windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrNotPrepared = errors.New("this server cannot apply updates")
|
||||||
|
ErrJobInProgress = errors.New("an update job is already running or ready")
|
||||||
|
ErrNothingToUpdate = errors.New("there is nothing to update")
|
||||||
|
ErrPreflightRefused = errors.New("the update cannot be downloaded")
|
||||||
|
)
|
||||||
|
|
||||||
|
type Platform struct {
|
||||||
|
OS string
|
||||||
|
Arch string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Job struct {
|
||||||
|
Tag string `json:"tag"`
|
||||||
|
State string `json:"state"`
|
||||||
|
Error string `json:"error"`
|
||||||
|
StartedAt time.Time `json:"started_at"`
|
||||||
|
DownloadedBytes int64 `json:"downloaded_bytes"`
|
||||||
|
TotalBytes int64 `json:"total_bytes"`
|
||||||
|
StagedBinary string `json:"staged_binary"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type ProgressFunc func(done int64, total int64)
|
||||||
|
|
||||||
|
type AssetFetcher interface {
|
||||||
|
Fetch(asset Asset, destination string, report ProgressFunc) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type SignatureVerifier interface {
|
||||||
|
Verify(checksumsPath string, signaturePath string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type StagedBinaryRunner interface {
|
||||||
|
Version(binaryPath string) (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type DatabaseBackup interface {
|
||||||
|
Backup() (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type StagingArea interface {
|
||||||
|
Prepare(tag string) error
|
||||||
|
PathFor(tag string, name string) string
|
||||||
|
Size(path string) (int64, error)
|
||||||
|
ReadChecksums(path string) (string, error)
|
||||||
|
MakeExecutable(path string) error
|
||||||
|
Remove(tag string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type HelperDetector interface {
|
||||||
|
Installed() bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type JobStore interface {
|
||||||
|
Load() (Job, bool)
|
||||||
|
Save(job Job) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Logger interface {
|
||||||
|
Printf(format string, args ...any)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j Job) IsRunning() bool {
|
||||||
|
return j.State == StateDownloading || j.State == StateVerifying
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j Job) Occupies() bool {
|
||||||
|
return j.IsRunning() || j.State == StateReady
|
||||||
|
}
|
||||||
|
|
||||||
|
func (j Job) Progress() *Progress {
|
||||||
|
if j.State != StateDownloading || j.TotalBytes <= 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &Progress{
|
||||||
|
Percent: int(j.DownloadedBytes * 100 / j.TotalBytes),
|
||||||
|
DownloadedBytes: j.DownloadedBytes,
|
||||||
|
TotalBytes: j.TotalBytes,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s UpdateStatus) WithJob(job Job) UpdateStatus {
|
||||||
|
s.State = job.State
|
||||||
|
s.Progress = job.Progress()
|
||||||
|
s.Error = nil
|
||||||
|
if job.Error != "" {
|
||||||
|
kind := job.Error
|
||||||
|
s.Error = &kind
|
||||||
|
}
|
||||||
|
startedAt := job.StartedAt
|
||||||
|
s.StartedAt = &startedAt
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func AssetName(tag string, platform Platform) string {
|
||||||
|
name := "renewcms_" + tag + "_" + platform.OS + "_" + platform.Arch
|
||||||
|
if platform.OS == windowsOS {
|
||||||
|
name += ".exe"
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
func FindAsset(assets []Asset, name string) (Asset, bool) {
|
||||||
|
for _, asset := range assets {
|
||||||
|
if asset.Name == name {
|
||||||
|
return asset, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Asset{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func HostOf(rawURL string) string {
|
||||||
|
parsed, err := url.Parse(rawURL)
|
||||||
|
if err != nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return parsed.Host
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsAllowedAssetURL(rawURL string, allowedHost string) bool {
|
||||||
|
parsed, err := url.Parse(rawURL)
|
||||||
|
if err != nil || parsed.Scheme != "https" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return allowedHost != "" && parsed.Host == allowedHost
|
||||||
|
}
|
||||||
|
|
||||||
|
func ChecksumFor(checksums string, assetName string) (string, bool) {
|
||||||
|
for _, line := range strings.Split(checksums, "\n") {
|
||||||
|
fields := strings.Fields(line)
|
||||||
|
if len(fields) == 2 && strings.TrimPrefix(fields[1], "*") == assetName {
|
||||||
|
return strings.ToLower(fields[0]), true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
func FileSHA256(path string) (string, error) {
|
||||||
|
file, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
hash := sha256.New()
|
||||||
|
if _, err := io.Copy(hash, file); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return hex.EncodeToString(hash.Sum(nil)), nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"path"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
RestartRequestFileName = "update-restart-request.json"
|
||||||
|
ResultFileName = "update-result.json"
|
||||||
|
HelperStatusFileName = "update-helper.json"
|
||||||
|
RunningInfoFileName = "update-running.json"
|
||||||
|
UpdatesDirName = "updates"
|
||||||
|
HelperStatusVersion = 1
|
||||||
|
|
||||||
|
PathUnitName = "renewcms-update.path"
|
||||||
|
ServiceUnitName = "renewcms-update.service"
|
||||||
|
DefaultService = "renewcms"
|
||||||
|
DefaultPort = "8080"
|
||||||
|
|
||||||
|
PreviousSuffix = ".previous"
|
||||||
|
PreviousTempSuffix = ".previous.tmp"
|
||||||
|
InstallTempSuffix = ".new"
|
||||||
|
RestoreTempSuffix = ".restore"
|
||||||
|
ResultTempSuffix = ".tmp"
|
||||||
|
ExecutableMode = 0o755
|
||||||
|
PrivateFileMode = 0o600
|
||||||
|
)
|
||||||
|
|
||||||
|
type HelperLayout struct {
|
||||||
|
DataDir string
|
||||||
|
BinaryPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l HelperLayout) UpdatesDir() string {
|
||||||
|
return path.Join(l.DataDir, UpdatesDirName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l HelperLayout) StagedDir(tag string) string {
|
||||||
|
return path.Join(l.UpdatesDir(), tag)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l HelperLayout) ResultPath() string {
|
||||||
|
return path.Join(l.DataDir, ResultFileName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l HelperLayout) ResultTempPath() string {
|
||||||
|
return l.ResultPath() + ResultTempSuffix
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l HelperLayout) RestartRequestPath() string {
|
||||||
|
return path.Join(l.DataDir, RestartRequestFileName)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l HelperLayout) PreviousPath() string {
|
||||||
|
return l.BinaryPath + PreviousSuffix
|
||||||
|
}
|
||||||
|
|
||||||
|
func SHA256Hex(content []byte) string {
|
||||||
|
sum := sha256.Sum256(content)
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import (
|
||||||
|
"regexp"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
bulletLine = regexp.MustCompile(`^[-*+]\s+(.+)$`)
|
||||||
|
markdownLink = regexp.MustCompile(`!?\[([^\]]*)\]\([^)]*\)`)
|
||||||
|
boldText = regexp.MustCompile(`\*\*([^*]+)\*\*|__([^_]+)__`)
|
||||||
|
italicText = regexp.MustCompile(`\*([^*\s][^*]*)\*`)
|
||||||
|
inlineCode = regexp.MustCompile("`([^`]*)`")
|
||||||
|
)
|
||||||
|
|
||||||
|
func BuildNotes(tag string, publishedAt time.Time, body string) ReleaseNotes {
|
||||||
|
items := []string{}
|
||||||
|
for _, line := range strings.Split(body, "\n") {
|
||||||
|
match := bulletLine.FindStringSubmatch(strings.TrimSpace(line))
|
||||||
|
if match == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if item := plainText(match[1]); item != "" {
|
||||||
|
items = append(items, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ReleaseNotes{Version: tag, ReleasedAt: publishedAt, Items: items}
|
||||||
|
}
|
||||||
|
|
||||||
|
func plainText(markdown string) string {
|
||||||
|
text := markdownLink.ReplaceAllString(markdown, "$1")
|
||||||
|
text = boldText.ReplaceAllString(text, "$1$2")
|
||||||
|
text = italicText.ReplaceAllString(text, "$1")
|
||||||
|
text = inlineCode.ReplaceAllString(text, "$1")
|
||||||
|
return strings.TrimSpace(text)
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
type ReleaseFeed interface {
|
||||||
|
Latest() (Release, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type StatusStore interface {
|
||||||
|
Load() (CheckResult, bool)
|
||||||
|
Save(result CheckResult) error
|
||||||
|
}
|
||||||
@@ -0,0 +1,158 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"regexp"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
StateRestarting = "restarting"
|
||||||
|
StateSucceeded = "succeeded"
|
||||||
|
|
||||||
|
ErrorKindRolledBack = "rolled_back"
|
||||||
|
ErrorKindInstall = "install"
|
||||||
|
|
||||||
|
RestartKindUpdate = "update"
|
||||||
|
RestartKindRestart = "restart"
|
||||||
|
|
||||||
|
OutcomeRunning = "running"
|
||||||
|
OutcomeSucceeded = "succeeded"
|
||||||
|
OutcomeRolledBack = "rolled_back"
|
||||||
|
OutcomeFailed = "failed"
|
||||||
|
|
||||||
|
RunningResultMaxAge = 5 * time.Minute
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrRestartPending = errors.New("a restart is already pending or running")
|
||||||
|
ErrRestartKindMismatch = errors.New("the requested restart does not match the current state")
|
||||||
|
ErrNoRestartRequest = errors.New("there is no restart request")
|
||||||
|
ErrSymlinkRefused = errors.New("a symbolic link was found where a regular file is required")
|
||||||
|
ErrInvalidRestartTag = errors.New("the restart request names an invalid version")
|
||||||
|
ErrHelperUnsupported = errors.New("the privileged helper needs Linux")
|
||||||
|
)
|
||||||
|
|
||||||
|
var restartTagPattern = regexp.MustCompile(`^v[0-9]+(\.[0-9]+)*(-[0-9A-Za-z.]+)?$`)
|
||||||
|
|
||||||
|
type RestartRequest struct {
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Tag string `json:"tag,omitempty"`
|
||||||
|
RequestedAt time.Time `json:"requested_at"`
|
||||||
|
RequestedBy uint32 `json:"requested_by"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Result struct {
|
||||||
|
Outcome string `json:"outcome"`
|
||||||
|
Kind string `json:"kind"`
|
||||||
|
Tag string `json:"tag"`
|
||||||
|
FromVersion string `json:"from_version"`
|
||||||
|
StartedAt time.Time `json:"started_at"`
|
||||||
|
FinishedAt *time.Time `json:"finished_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunningInfo struct {
|
||||||
|
Version string `json:"version"`
|
||||||
|
Pid int `json:"pid"`
|
||||||
|
StartedAt time.Time `json:"started_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type HelperStatus struct {
|
||||||
|
Version int `json:"version"`
|
||||||
|
Service string `json:"service"`
|
||||||
|
Binary string `json:"binary"`
|
||||||
|
DataDir string `json:"data_dir"`
|
||||||
|
InstalledAt time.Time `json:"installed_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type FileInfo struct {
|
||||||
|
IsSymlink bool
|
||||||
|
IsDir bool
|
||||||
|
IsRegular bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type RestartRequestStore interface {
|
||||||
|
Write(request RestartRequest) error
|
||||||
|
Read() (RestartRequest, error)
|
||||||
|
Delete() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type ResultStore interface {
|
||||||
|
Read() (Result, bool)
|
||||||
|
Write(result Result) error
|
||||||
|
Delete() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type RunningInfoStore interface {
|
||||||
|
Write(info RunningInfo) error
|
||||||
|
Read() (RunningInfo, bool)
|
||||||
|
}
|
||||||
|
|
||||||
|
type HelperFilesystem interface {
|
||||||
|
Lstat(path string) (FileInfo, error)
|
||||||
|
ReadFile(path string) ([]byte, error)
|
||||||
|
CreateExclusive(path string, content []byte, mode uint32) error
|
||||||
|
Copy(source string, destination string, mode uint32) error
|
||||||
|
Rename(oldPath string, newPath string) error
|
||||||
|
Remove(path string) error
|
||||||
|
RemoveAll(path string) error
|
||||||
|
Chmod(path string, mode uint32) error
|
||||||
|
MakePrivateTempDir() (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type ServiceControl interface {
|
||||||
|
Restart() error
|
||||||
|
Status() (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type HealthChecker interface {
|
||||||
|
Healthy() bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type Clock interface {
|
||||||
|
Now() time.Time
|
||||||
|
Sleep(duration time.Duration)
|
||||||
|
}
|
||||||
|
|
||||||
|
func ValidateRestartTag(tag string, runningVersion string) error {
|
||||||
|
if !restartTagPattern.MatchString(tag) {
|
||||||
|
return ErrInvalidRestartTag
|
||||||
|
}
|
||||||
|
if _, err := ParseVersion(tag); err != nil || !IsNewer(runningVersion, tag) {
|
||||||
|
return ErrInvalidRestartTag
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Result) IsRunning() bool {
|
||||||
|
return r.Outcome == OutcomeRunning
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r Result) IsKnown() bool {
|
||||||
|
switch r.Outcome {
|
||||||
|
case OutcomeRunning, OutcomeSucceeded, OutcomeRolledBack, OutcomeFailed:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i RunningInfo) IsNewerThan(previous RunningInfo, restartedAt time.Time) bool {
|
||||||
|
return i.Pid != previous.Pid || i.StartedAt.After(restartedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
RestartWindow = 60 * time.Second
|
||||||
|
PollInterval = time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
type SymlinkError struct {
|
||||||
|
Path string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e SymlinkError) Error() string {
|
||||||
|
return e.Path + " is a symbolic link"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e SymlinkError) Is(target error) bool {
|
||||||
|
return target == ErrSymlinkRefused
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
func (s UpdateStatus) WithRestartRequest(request RestartRequest) UpdateStatus {
|
||||||
|
return s.settled(StateRestarting, "", request.RequestedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s UpdateStatus) WithResult(result Result, currentVersion string, now time.Time) UpdateStatus {
|
||||||
|
if result.IsRunning() && now.Sub(result.StartedAt) < RunningResultMaxAge {
|
||||||
|
return s.settled(StateRestarting, "", result.StartedAt)
|
||||||
|
}
|
||||||
|
if result.IsRunning() || result.Outcome == OutcomeFailed {
|
||||||
|
return s.settled(StateFailed, ErrorKindInstall, result.StartedAt)
|
||||||
|
}
|
||||||
|
if result.Outcome == OutcomeRolledBack {
|
||||||
|
return s.settled(StateFailed, ErrorKindRolledBack, result.StartedAt)
|
||||||
|
}
|
||||||
|
if result.Kind == RestartKindUpdate && result.Tag == currentVersion {
|
||||||
|
return s.settled(StateSucceeded, "", result.StartedAt)
|
||||||
|
}
|
||||||
|
s.State = StateIdle
|
||||||
|
s.Progress = nil
|
||||||
|
s.Error = nil
|
||||||
|
s.StartedAt = nil
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s UpdateStatus) settled(state string, errorKind string, startedAt time.Time) UpdateStatus {
|
||||||
|
s.State = state
|
||||||
|
s.Progress = nil
|
||||||
|
s.Error = nil
|
||||||
|
if errorKind != "" {
|
||||||
|
s.Error = &errorKind
|
||||||
|
}
|
||||||
|
s.StartedAt = &startedAt
|
||||||
|
return s
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import (
|
||||||
|
"cmp"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Version struct {
|
||||||
|
numbers []int
|
||||||
|
pre []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseVersion(raw string) (Version, error) {
|
||||||
|
trimmed := strings.TrimPrefix(strings.TrimSpace(raw), "v")
|
||||||
|
core, pre, hasPre := strings.Cut(trimmed, "-")
|
||||||
|
if core == "" || (hasPre && pre == "") {
|
||||||
|
return Version{}, ErrInvalidVersion
|
||||||
|
}
|
||||||
|
var version Version
|
||||||
|
for _, segment := range strings.Split(core, ".") {
|
||||||
|
number, err := strconv.Atoi(segment)
|
||||||
|
if err != nil || number < 0 {
|
||||||
|
return Version{}, ErrInvalidVersion
|
||||||
|
}
|
||||||
|
version.numbers = append(version.numbers, number)
|
||||||
|
}
|
||||||
|
if hasPre {
|
||||||
|
version.pre = strings.Split(pre, ".")
|
||||||
|
}
|
||||||
|
return version, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsNewer(current, latest string) bool {
|
||||||
|
currentVersion, err := ParseVersion(current)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
latestVersion, err := ParseVersion(latest)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return compareVersions(latestVersion, currentVersion) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareVersions(a, b Version) int {
|
||||||
|
if order := compareNumbers(a.numbers, b.numbers); order != 0 {
|
||||||
|
return order
|
||||||
|
}
|
||||||
|
return comparePreRelease(a.pre, b.pre)
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareNumbers(a, b []int) int {
|
||||||
|
for i := range max(len(a), len(b)) {
|
||||||
|
if order := cmp.Compare(segmentAt(a, i), segmentAt(b, i)); order != 0 {
|
||||||
|
return order
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func segmentAt(numbers []int, index int) int {
|
||||||
|
if index < len(numbers) {
|
||||||
|
return numbers[index]
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func comparePreRelease(a, b []string) int {
|
||||||
|
if len(a) == 0 && len(b) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
if len(a) == 0 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
if len(b) == 0 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
length := min(len(a), len(b))
|
||||||
|
for i := 0; i < length; i++ {
|
||||||
|
if order := compareIdentifiers(a[i], b[i]); order != 0 {
|
||||||
|
return order
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cmp.Compare(len(a), len(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareIdentifiers(a, b string) int {
|
||||||
|
numberA, errA := strconv.Atoi(a)
|
||||||
|
numberB, errB := strconv.Atoi(b)
|
||||||
|
if errA == nil && errB == nil {
|
||||||
|
return cmp.Compare(numberA, numberB)
|
||||||
|
}
|
||||||
|
if errA == nil {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
if errB == nil {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return strings.Compare(a, b)
|
||||||
|
}
|
||||||
@@ -32,6 +32,7 @@ type Settings struct {
|
|||||||
AuthRateLimit AuthRateLimitSettings
|
AuthRateLimit AuthRateLimitSettings
|
||||||
TrustedProxies []string
|
TrustedProxies []string
|
||||||
Version string
|
Version string
|
||||||
|
UpdateFeedURL string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Settings) IsProduction() bool {
|
func (s Settings) IsProduction() bool {
|
||||||
@@ -74,6 +75,7 @@ func NewSettingsFromEnv() (Settings, error) {
|
|||||||
Window: time.Duration(authRateLimitWindowSeconds) * time.Second,
|
Window: time.Duration(authRateLimitWindowSeconds) * time.Second,
|
||||||
},
|
},
|
||||||
TrustedProxies: parseSemicolonSeparatedList(os.Getenv("TRUSTED_PROXIES")),
|
TrustedProxies: parseSemicolonSeparatedList(os.Getenv("TRUSTED_PROXIES")),
|
||||||
|
UpdateFeedURL: os.Getenv("UPDATE_FEED_URL"),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,22 +2,14 @@ package mappers
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"RenewCMS/internal/domain/article"
|
"RenewCMS/internal/domain/article"
|
||||||
"RenewCMS/internal/domain/image"
|
|
||||||
"RenewCMS/internal/infrastructure/persistence/models"
|
"RenewCMS/internal/infrastructure/persistence/models"
|
||||||
)
|
)
|
||||||
|
|
||||||
func ArticleToDomain(m models.Article) article.Article {
|
func ArticleToDomain(m models.Article) article.Article {
|
||||||
domainImages := make([]*image.Image, len(m.Images))
|
|
||||||
for i, img := range m.Images {
|
|
||||||
domainImg := ImageToDomain(*img)
|
|
||||||
domainImages[i] = &domainImg
|
|
||||||
}
|
|
||||||
|
|
||||||
return article.Article{
|
return article.Article{
|
||||||
ID: m.ID,
|
ID: m.ID,
|
||||||
Title: m.Title,
|
Title: m.Title,
|
||||||
Body: m.Body,
|
Body: m.Body,
|
||||||
Images: domainImages,
|
|
||||||
IsOnline: m.IsOnline,
|
IsOnline: m.IsOnline,
|
||||||
CreatedAt: m.CreatedAt,
|
CreatedAt: m.CreatedAt,
|
||||||
UpdatedAt: m.UpdatedAt,
|
UpdatedAt: m.UpdatedAt,
|
||||||
@@ -25,16 +17,9 @@ func ArticleToDomain(m models.Article) article.Article {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ArticleToModel(a article.Article) models.Article {
|
func ArticleToModel(a article.Article) models.Article {
|
||||||
modelImages := make([]*models.Image, len(a.Images))
|
|
||||||
for i, img := range a.Images {
|
|
||||||
modelImage := ImageToModel(*img)
|
|
||||||
modelImages[i] = &modelImage
|
|
||||||
}
|
|
||||||
|
|
||||||
return models.Article{
|
return models.Article{
|
||||||
Title: a.Title,
|
Title: a.Title,
|
||||||
Body: a.Body,
|
Body: a.Body,
|
||||||
Images: modelImages,
|
|
||||||
IsOnline: a.IsOnline,
|
IsOnline: a.IsOnline,
|
||||||
CreatedAt: a.CreatedAt,
|
CreatedAt: a.CreatedAt,
|
||||||
UpdatedAt: a.UpdatedAt,
|
UpdatedAt: a.UpdatedAt,
|
||||||
|
|||||||
@@ -9,7 +9,13 @@ func ImageToDomain(imageModel models.Image) image.Image {
|
|||||||
return image.Image{
|
return image.Image{
|
||||||
ID: imageModel.ID,
|
ID: imageModel.ID,
|
||||||
Path: imageModel.Path,
|
Path: imageModel.Path,
|
||||||
ArticleID: imageModel.ArticleID,
|
Filename: imageModel.Filename,
|
||||||
|
Size: imageModel.Size,
|
||||||
|
ContentType: imageModel.ContentType,
|
||||||
|
Width: imageModel.Width,
|
||||||
|
Height: imageModel.Height,
|
||||||
|
SHA256: imageModel.SHA256,
|
||||||
|
UploadedByID: imageModel.UploadedByID,
|
||||||
CreatedAt: imageModel.CreatedAt,
|
CreatedAt: imageModel.CreatedAt,
|
||||||
UpdatedAt: imageModel.UpdatedAt,
|
UpdatedAt: imageModel.UpdatedAt,
|
||||||
}
|
}
|
||||||
@@ -17,8 +23,15 @@ func ImageToDomain(imageModel models.Image) image.Image {
|
|||||||
|
|
||||||
func ImageToModel(imageDomain image.Image) models.Image {
|
func ImageToModel(imageDomain image.Image) models.Image {
|
||||||
return models.Image{
|
return models.Image{
|
||||||
|
ID: imageDomain.ID,
|
||||||
Path: imageDomain.Path,
|
Path: imageDomain.Path,
|
||||||
ArticleID: imageDomain.ArticleID,
|
Filename: imageDomain.Filename,
|
||||||
|
Size: imageDomain.Size,
|
||||||
|
ContentType: imageDomain.ContentType,
|
||||||
|
Width: imageDomain.Width,
|
||||||
|
Height: imageDomain.Height,
|
||||||
|
SHA256: imageDomain.SHA256,
|
||||||
|
UploadedByID: imageDomain.UploadedByID,
|
||||||
CreatedAt: imageDomain.CreatedAt,
|
CreatedAt: imageDomain.CreatedAt,
|
||||||
UpdatedAt: imageDomain.UpdatedAt,
|
UpdatedAt: imageDomain.UpdatedAt,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ type Article struct {
|
|||||||
ID uint32 `gorm:"primary_key;auto_increment;not_null"`
|
ID uint32 `gorm:"primary_key;auto_increment;not_null"`
|
||||||
Title string
|
Title string
|
||||||
Body string
|
Body string
|
||||||
Images []*Image `gorm:"many2many:article_images;"`
|
|
||||||
IsOnline bool `gorm:"not_null;default:false"`
|
IsOnline bool `gorm:"not_null;default:false"`
|
||||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||||
|
|||||||
@@ -10,7 +10,13 @@ type Image struct {
|
|||||||
gorm.Model
|
gorm.Model
|
||||||
ID uint32 `gorm:"primary_key;auto_increment;not_null"`
|
ID uint32 `gorm:"primary_key;auto_increment;not_null"`
|
||||||
Path string
|
Path string
|
||||||
ArticleID uint32
|
Filename string
|
||||||
|
Size int64
|
||||||
|
ContentType string
|
||||||
|
Width int
|
||||||
|
Height int
|
||||||
|
SHA256 string `gorm:"column:sha256;index"`
|
||||||
|
UploadedByID uint32
|
||||||
CreatedAt time.Time `gorm:"autoCreateTime"`
|
CreatedAt time.Time `gorm:"autoCreateTime"`
|
||||||
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
UpdatedAt time.Time `gorm:"autoUpdateTime"`
|
||||||
}
|
}
|
||||||
@@ -2,7 +2,6 @@ package persistence
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
domain "RenewCMS/internal/domain/article"
|
domain "RenewCMS/internal/domain/article"
|
||||||
imageDomain "RenewCMS/internal/domain/image"
|
|
||||||
"RenewCMS/internal/infrastructure/persistence/mappers"
|
"RenewCMS/internal/infrastructure/persistence/mappers"
|
||||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||||
|
|
||||||
@@ -18,7 +17,7 @@ func NewArticleRepository(db *gorm.DB) *ArticleRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (a *ArticleRepository) FindByFilters(filters domain.Filters) ([]domain.Article, error) {
|
func (a *ArticleRepository) FindByFilters(filters domain.Filters) ([]domain.Article, error) {
|
||||||
query := a.db.Model(&entity.Article{}).Preload("Images")
|
query := a.db.Model(&entity.Article{})
|
||||||
|
|
||||||
if filters.IsOnline != nil {
|
if filters.IsOnline != nil {
|
||||||
query = query.Where("is_online = ?", *filters.IsOnline)
|
query = query.Where("is_online = ?", *filters.IsOnline)
|
||||||
@@ -37,7 +36,7 @@ func (a *ArticleRepository) FindByFilters(filters domain.Filters) ([]domain.Arti
|
|||||||
|
|
||||||
func (a *ArticleRepository) Get(id uint32) (domain.Article, error) {
|
func (a *ArticleRepository) Get(id uint32) (domain.Article, error) {
|
||||||
var article entity.Article
|
var article entity.Article
|
||||||
err := a.db.Model(&entity.Article{}).Preload("Images").First(&article, id).Error
|
err := a.db.Model(&entity.Article{}).First(&article, id).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return domain.Article{}, mapNotFoundErr(err, domain.ErrArticleNotFound)
|
return domain.Article{}, mapNotFoundErr(err, domain.ErrArticleNotFound)
|
||||||
}
|
}
|
||||||
@@ -125,25 +124,18 @@ func (a *ArticleRepository) Delete(id uint32) error {
|
|||||||
return deleteOrNotFound(result, domain.ErrArticleNotFound)
|
return deleteOrNotFound(result, domain.ErrArticleNotFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *ArticleRepository) AddImage(articleId uint32, imageId uint32) error {
|
func (a *ArticleRepository) FindByBodyContaining(filename string) ([]domain.Article, error) {
|
||||||
var localArticle entity.Article
|
var entityArticles []entity.Article
|
||||||
err := a.db.Model(&entity.Article{}).First(&localArticle, articleId).Error
|
err := a.db.Model(&entity.Article{}).Where("instr(body, ?) > 0", filename).Order("id asc").Find(&entityArticles).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return mapNotFoundErr(err, domain.ErrArticleNotFound)
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
var localImage entity.Image
|
domainArticles := make([]domain.Article, 0, len(entityArticles))
|
||||||
err = a.db.Model(&entity.Image{}).First(&localImage, imageId).Error
|
for _, entityArticle := range entityArticles {
|
||||||
if err != nil {
|
domainArticles = append(domainArticles, mappers.ArticleToDomain(entityArticle))
|
||||||
return mapNotFoundErr(err, imageDomain.ErrImageNotFound)
|
|
||||||
}
|
}
|
||||||
|
return domainArticles, nil
|
||||||
err = a.db.Model(&localArticle).Association("Images").Append(&localImage)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ domain.Repository = &ArticleRepository{}
|
var _ domain.Repository = &ArticleRepository{}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
package persistence
|
||||||
|
|
||||||
|
import (
|
||||||
|
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||||
|
"bytes"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
stdimage "image"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
_ "golang.org/x/image/webp"
|
||||||
|
_ "image/jpeg"
|
||||||
|
_ "image/png"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var extensionContentTypes = map[string]string{
|
||||||
|
".png": "image/png",
|
||||||
|
".jpg": "image/jpeg",
|
||||||
|
".jpeg": "image/jpeg",
|
||||||
|
".webp": "image/webp",
|
||||||
|
".svg": "image/svg+xml",
|
||||||
|
}
|
||||||
|
|
||||||
|
func BackfillImageMetadata(db *gorm.DB, uploadDir string) error {
|
||||||
|
var pending []entity.Image
|
||||||
|
err := db.Where("filename = '' OR filename IS NULL").Order("id asc").Find(&pending).Error
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, row := range pending {
|
||||||
|
metadata, ok := readStoredImage(uploadDir, row.Path)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
err := db.Model(&entity.Image{}).Where("id = ?", row.ID).UpdateColumns(metadata).Error
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func readStoredImage(uploadDir string, storedPath string) (map[string]any, bool) {
|
||||||
|
fileName := filepath.Base(storedPath)
|
||||||
|
contentType, known := extensionContentTypes[filepath.Ext(fileName)]
|
||||||
|
if !known {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := os.ReadFile(filepath.Join(uploadDir, fileName))
|
||||||
|
if err != nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
width, height := 0, 0
|
||||||
|
if contentType != "image/svg+xml" {
|
||||||
|
config, _, err := stdimage.DecodeConfig(bytes.NewReader(data))
|
||||||
|
if err != nil {
|
||||||
|
return nil, false
|
||||||
|
}
|
||||||
|
width, height = config.Width, config.Height
|
||||||
|
}
|
||||||
|
|
||||||
|
checksum := sha256.Sum256(data)
|
||||||
|
return map[string]any{
|
||||||
|
"filename": fileName,
|
||||||
|
"size": int64(len(data)),
|
||||||
|
"content_type": contentType,
|
||||||
|
"width": width,
|
||||||
|
"height": height,
|
||||||
|
"sha256": hex.EncodeToString(checksum[:]),
|
||||||
|
}, true
|
||||||
|
}
|
||||||
@@ -4,14 +4,18 @@ import (
|
|||||||
domain "RenewCMS/internal/domain/image"
|
domain "RenewCMS/internal/domain/image"
|
||||||
"RenewCMS/internal/infrastructure/persistence/mappers"
|
"RenewCMS/internal/infrastructure/persistence/mappers"
|
||||||
entity "RenewCMS/internal/infrastructure/persistence/models"
|
entity "RenewCMS/internal/infrastructure/persistence/models"
|
||||||
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const uploadedImagesURLPrefix = "/static/uploadedImages/"
|
||||||
|
|
||||||
type ImageRepository struct {
|
type ImageRepository struct {
|
||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
uploadDir string
|
uploadDir string
|
||||||
@@ -29,49 +33,142 @@ var contentTypeExtensions = map[string]string{
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (i ImageRepository) Create(input domain.ImageInput) (domain.Image, error) {
|
func (i ImageRepository) Create(input domain.ImageInput) (domain.Image, error) {
|
||||||
uploadDir := i.uploadDir
|
|
||||||
|
|
||||||
fileBytes, err := io.ReadAll(input.Content)
|
fileBytes, err := io.ReadAll(input.Content)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return domain.Image{}, err
|
return domain.Image{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
err = os.MkdirAll(uploadDir, 0755)
|
err = os.MkdirAll(i.uploadDir, 0755)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return domain.Image{}, err
|
return domain.Image{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
extension := contentTypeExtensions[input.ContentType]
|
newName := uuid.NewString() + contentTypeExtensions[input.ContentType]
|
||||||
|
finalPath := filepath.Join(i.uploadDir, newName)
|
||||||
newName := uuid.NewString() + extension
|
|
||||||
finalPath := filepath.Join(uploadDir, newName)
|
|
||||||
err = os.WriteFile(finalPath, fileBytes, 0666)
|
err = os.WriteFile(finalPath, fileBytes, 0666)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return domain.Image{}, err
|
return domain.Image{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
newImage := i.db.Create(&domain.Image{Path: "/static/uploadedImages/" + newName})
|
model := mappers.ImageToModel(domain.Image{
|
||||||
var createdImage entity.Image
|
Path: uploadedImagesURLPrefix + newName,
|
||||||
newImage.Scan(&createdImage)
|
Filename: input.Filename,
|
||||||
|
Size: input.Size,
|
||||||
|
ContentType: input.ContentType,
|
||||||
|
Width: input.Width,
|
||||||
|
Height: input.Height,
|
||||||
|
SHA256: input.SHA256,
|
||||||
|
UploadedByID: input.UploadedByID,
|
||||||
|
})
|
||||||
|
if err := i.db.Create(&model).Error; err != nil {
|
||||||
|
_ = os.Remove(finalPath)
|
||||||
|
return domain.Image{}, err
|
||||||
|
}
|
||||||
|
|
||||||
return mappers.ImageToDomain(createdImage), nil
|
return mappers.ImageToDomain(model), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i ImageRepository) Get(id uint32) (domain.Image, error) {
|
||||||
|
var model entity.Image
|
||||||
|
err := i.db.First(&model, id).Error
|
||||||
|
if err != nil {
|
||||||
|
return domain.Image{}, mapNotFoundErr(err, domain.ErrImageNotFound)
|
||||||
|
}
|
||||||
|
return mappers.ImageToDomain(model), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (i ImageRepository) Delete(id uint32) error {
|
func (i ImageRepository) Delete(id uint32) error {
|
||||||
uploadDir := i.uploadDir
|
var model entity.Image
|
||||||
var entityImage entity.Image
|
err := i.db.First(&model, id).Error
|
||||||
err := i.db.Model(&entity.Image{}).First(&entityImage, id).Error
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return mapNotFoundErr(err, domain.ErrImageNotFound)
|
return mapNotFoundErr(err, domain.ErrImageNotFound)
|
||||||
}
|
}
|
||||||
|
|
||||||
fileName := filepath.Base(entityImage.Path)
|
err = os.Remove(filepath.Join(i.uploadDir, filepath.Base(model.Path)))
|
||||||
err = os.Remove(filepath.Join(uploadDir, fileName))
|
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||||
if err != nil {
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return i.db.Delete(&entity.Image{}, id).Error
|
return i.db.Delete(&entity.Image{}, id).Error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (i ImageRepository) List(query domain.SearchQuery) ([]domain.Image, error) {
|
||||||
|
statement := i.db.Model(&entity.Image{})
|
||||||
|
if query.Search != "" {
|
||||||
|
statement = statement.Where("instr(lower(filename), ?) > 0", strings.ToLower(query.Search))
|
||||||
|
}
|
||||||
|
if query.Hash != "" {
|
||||||
|
statement = statement.Where("sha256 = ?", query.Hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
var models []entity.Image
|
||||||
|
if err := statement.Order("id asc").Find(&models).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return imagesToDomain(models), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i ImageRepository) FindByHash(hash string) ([]domain.Image, error) {
|
||||||
|
if hash == "" {
|
||||||
|
return []domain.Image{}, nil
|
||||||
|
}
|
||||||
|
var models []entity.Image
|
||||||
|
if err := i.db.Where("sha256 = ?", hash).Order("id asc").Find(&models).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return imagesToDomain(models), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i ImageRepository) Rename(id uint32, filename string) (domain.Image, error) {
|
||||||
|
var model entity.Image
|
||||||
|
err := i.db.First(&model, id).Error
|
||||||
|
if err != nil {
|
||||||
|
return domain.Image{}, mapNotFoundErr(err, domain.ErrImageNotFound)
|
||||||
|
}
|
||||||
|
|
||||||
|
model.Filename = filename
|
||||||
|
if err := i.db.Save(&model).Error; err != nil {
|
||||||
|
return domain.Image{}, err
|
||||||
|
}
|
||||||
|
return mappers.ImageToDomain(model), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i ImageRepository) ListDuplicates() ([]domain.Image, error) {
|
||||||
|
var models []entity.Image
|
||||||
|
err := i.db.Where("sha256 IN (?)", i.duplicatedHashes()).Order("sha256 asc, id asc").Find(&models).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return imagesToDomain(models), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i ImageRepository) Counts() (domain.Counts, error) {
|
||||||
|
var all int64
|
||||||
|
if err := i.db.Model(&entity.Image{}).Count(&all).Error; err != nil {
|
||||||
|
return domain.Counts{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var groups int64
|
||||||
|
if err := i.db.Table("(?) as duplicated", i.duplicatedHashes()).Count(&groups).Error; err != nil {
|
||||||
|
return domain.Counts{}, err
|
||||||
|
}
|
||||||
|
return domain.Counts{All: int(all), DuplicateGroups: int(groups)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (i ImageRepository) duplicatedHashes() *gorm.DB {
|
||||||
|
return i.db.Model(&entity.Image{}).
|
||||||
|
Select("sha256").
|
||||||
|
Where("sha256 <> ''").
|
||||||
|
Group("sha256").
|
||||||
|
Having("COUNT(*) > 1")
|
||||||
|
}
|
||||||
|
|
||||||
|
func imagesToDomain(models []entity.Image) []domain.Image {
|
||||||
|
images := make([]domain.Image, 0, len(models))
|
||||||
|
for _, model := range models {
|
||||||
|
images = append(images, mappers.ImageToDomain(model))
|
||||||
|
}
|
||||||
|
return images
|
||||||
|
}
|
||||||
|
|
||||||
var _ domain.Repository = &ImageRepository{}
|
var _ domain.Repository = &ImageRepository{}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package update
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io/fs"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
const readableFilePermissions = 0o644
|
||||||
|
|
||||||
|
func writeFileAtomically(path string, content []byte, permissions os.FileMode) error {
|
||||||
|
temporary := path + ".tmp"
|
||||||
|
if err := os.WriteFile(temporary, content, permissions); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.Rename(temporary, path); err != nil {
|
||||||
|
_ = os.Remove(temporary)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeJSONAtomically(path string, value any, permissions os.FileMode) error {
|
||||||
|
content, err := json.Marshal(value)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return writeFileAtomically(path, content, permissions)
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeFile(path string) (bool, error) {
|
||||||
|
err := os.Remove(path)
|
||||||
|
if err == nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, fs.ErrNotExist) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func removeIfPresent(path string) error {
|
||||||
|
_, err := removeFile(path)
|
||||||
|
return err
|
||||||
|
}
|
||||||
Loaded 100 of 342 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user