10 Commits
Author SHA1 Message Date
konrad 29e82033ef Merge branch 'feature/exapp-ui-languages' 2026-10-19 15:30:39 +02:00
konradandCursor 623ada5f99 Resolve the page UI language once and let each ExApp fill its own Phrases.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-11 11:45:25 +02:00
konradandCursor afbd76445d Document every exported symbol and how callers use the library.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 19:25:44 +02:00
konrad d7768d44d6 Merge branch 'feature/mobile-app-navigation' 2026-09-29 18:57:08 +02:00
konradandCursor fad9806585 Hide App navigation on a narrow screen until the user opens it.
A width at or below Nextcloud's 1024px breakpoint keeps the tree off the page so the content stays usable, and the navigation button brings it back.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 18:56:44 +02:00
konrad 4e05fb1c6a Paint a destructive Dialog button with Nextcloud's error text color.
The theme's error background is a pale pink, so a white label looked disabled.
2026-09-29 02:53:59 +02:00
konrad 0a387815a0 Add a Dialog an ExApp page can open for a message, confirm, or prompt.
The page waits for the choice. App navigation includes the same piece.
2026-09-28 21:10:20 +02:00
konradandCursor d4c18e63bb Load the Nextcloud theme in App navigation and name its core icons.
The shell paints the instance wallpaper by default, and ExApps pick menu icons from NextcloudIcons instead of raw paths.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 20:12:02 +02:00
konradandCursor 7a915aee7b Add an optional App navigation shell for ExApp pages.
ExApps that mount it share one Files-style tree; an ExApp that never mounts it keeps its own page.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 19:31:36 +02:00
Konrad NeitzelandCursor 9e2005cfb3 Raise the module Go version to 1.27.0.
Match the Workspace pin so language and stdlib features through 1.27 are allowed.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 17:16:16 +02:00
27 changed files with 3790 additions and 107 deletions
+17 -1
View File
@@ -1,6 +1,6 @@
# go-nc-exapp # go-nc-exapp
Shared Go Library for Nextcloud ExApp Services: AppAPI authentication, OCS calls, per-user ExApp preferences, Notifications, Users and Groups, and optional Required Groups gating. ExApps import `gitea.neitzel.de/konrad/go-nc-exapp`. File storage and folder visits live in go-nc-files. Shared Go Library for Nextcloud ExApp Services: AppAPI authentication, OCS calls, per-user ExApp preferences, Notifications, Users and Groups, the Requesting user's UI language, and optional Required Groups gating. ExApps import `gitea.neitzel.de/konrad/go-nc-exapp`. File storage and folder visits live in go-nc-files.
## Language ## Language
@@ -12,6 +12,14 @@ _Avoid_: API key (generic), session token
The Nextcloud user on whose behalf the current ExApp request runs, taken from AppAPI authorization headers. WebDAV, preferences, and a Notification to that same user use this identity; there is no separate ExApp login. The Nextcloud user on whose behalf the current ExApp request runs, taken from AppAPI authorization headers. WebDAV, preferences, and a Notification to that same user use this identity; there is no separate ExApp login.
_Avoid_: service account (for per-request identity), anonymous _Avoid_: service account (for per-request identity), anonymous
**UI language**:
The Nextcloud language of the Requesting user, not the locale. A stored personal language is used. When none is stored, the browser language is used, then the instance default, then English. The Library resolves it once for a page. ExApp pages and the Library's own chrome use that same language for their Phrases. English and German are the languages the Library provides. A more specific code uses the broader language when that is the one provided. Any language the Library does not provide uses English. When the UI language cannot be read, it is English, and the page still renders.
_Avoid_: locale, Accept-Language, ExApp preference
**Phrase**:
A label or sentence on an ExApp page, identified by one stable name, not by the English text. English and German are two texts for that same Phrase. A Phrase is one text per language. A count is a hole, not a second form. English is the complete set. A Phrase with no text for the UI language shows the English text. An id with no English text shows the id. A Phrase may contain named holes for values the page inserts. English and German name the same holes and may place them differently. A hole with no value stays visible. Those values are not Phrases. The ExApp owns the Phrases of its pages and of its navigation items. The Library owns the Phrases of App navigation chrome and of Dialog buttons. A Library or an ExApp has one default set. A module keeps its own set with that module. The English text stays on the page, and the element names its Phrase, including a placeholder, a title, or an aria-label. The script shows the text for the UI language. A hole value is plain text. An error the page displays is the finished sentence for the UI language, not the id. The page and its script show the ExApp's default set and any module sets, as one map. A repeated id uses the text from the set added later. The Library writes its own Phrases into the chrome it renders, and that set is not in the map.
_Avoid_: Catalog, Message, user data, zone name, Notification subject
**Recipient**: **Recipient**:
The Nextcloud user a Notification is created for. May be the Requesting user or another user. AppAPI accepts one Recipient per call; sending to a group or to all admins is many Notifications. The Nextcloud user a Notification is created for. May be the Requesting user or another user. AppAPI accepts one Recipient per call; sending to a group or to all admins is many Notifications.
_Avoid_: destination, target (HTTP), addressee, treating a group as a Recipient _Avoid_: destination, target (HTTP), addressee, treating a group as a Recipient
@@ -40,6 +48,14 @@ _Avoid_: Group-API, Required Groups, AppAPI scopes, treating a group as a Recipi
The Library check that enforces Required Groups for the Requesting user on ExApp HTTP traffic (403 or denied UI when not a member; 401 without a user; 503 when membership cannot be determined). It reads the user's groups through Users and Groups. Lifecycle paths and top-menu script URLs under `/js/` stay ungated so Denied UI can load in the Nextcloud shell. The Library check that enforces Required Groups for the Requesting user on ExApp HTTP traffic (403 or denied UI when not a member; 401 without a user; 503 when membership cannot be determined). It reads the user's groups through Users and Groups. Lifecycle paths and top-menu script URLs under `/js/` stay ungated so Denied UI can load in the Nextcloud shell.
_Avoid_: Nextcloud middleware, HaRP ACL, admin bypass, gating the top-menu bootstrap script _Avoid_: Nextcloud middleware, HaRP ACL, admin bypass, gating the top-menu bootstrap script
**App navigation**:
The tree of named items along the left of an ExApp page. The ExApp supplies the tree. The selected item is the page on display. It plays the same role as the navigation in Nextcloud Files. On a screen at most 1024px wide the tree is hidden until the user opens it; choosing an item, pressing Escape, or clicking outside closes it again. An ExApp that does not use App navigation shows its own page instead. The Library's own phrases on that chrome follow the UI language. The names of the items are the ExApp's.
_Avoid_: Top Menu, sidebar, NcAppNavigation
**Dialog**:
A modal window on an ExApp page, in the same Nextcloud theme as that page. It does not require App navigation. The page waits for the user's choice; that choice is not a server request. The heading, the message, and the button word are plain text. The heading may be omitted. The fixed buttons follow the UI language. The Library provides them in English and German. One of three kinds: a Message (short text at info, warning, or error, dismissed with one button), a Confirm (yes or no; the agreeing button may be destructive), or a Prompt (one entered value, or cancelled). A Prompt with no value cannot be agreed. A successful Prompt value has no surrounding spaces. The caller may supply a starting value. A Prompt field has no label of its own; the message is the text above it.
_Avoid_: popup, browser alert/confirm/prompt, Notification, toast, HTML message
**Top Menu visibility**: **Top Menu visibility**:
Whether the ExApp app icon in the Nextcloud top menu is shown to all logged-in users or to Nextcloud admins only. Configured per deploy via env `TOP_MENU_ADMIN_REQUIRED` (`0` or `1`); the ExApp passes the value to AppAPI when registering the top-menu entry on enable. Independent of route `access_level` in info.xml and of Required Groups. Whether the ExApp app icon in the Nextcloud top menu is shown to all logged-in users or to Nextcloud admins only. Configured per deploy via env `TOP_MENU_ADMIN_REQUIRED` (`0` or `1`); the ExApp passes the value to AppAPI when registering the top-menu entry on enable. Independent of route `access_level` in info.xml and of Required Groups.
_Avoid_: route access_level, Required Groups, AppAPI group ACL _Avoid_: route access_level, Required Groups, AppAPI group ACL
+40 -81
View File
@@ -1,100 +1,59 @@
# go-nc-exapp # go-nc-exapp
Shared Go library for Nextcloud ExApp Services: AppAPI authentication, OCS JSON calls, per-user ExApp preferences, Notifications, Users and Groups, and an optional Required Groups Access Gate. Shared Go library for Nextcloud ExApp Services: AppAPI authentication, OCS JSON calls, per-user ExApp preferences, Notifications, Users and Groups, an optional Required Groups Access Gate, an optional App navigation shell, and a Dialog.
Import: `gitea.neitzel.de/konrad/go-nc-exapp` (package `gonexapp`). Import: `gitea.neitzel.de/konrad/go-nc-exapp` (package `gonexapp`).
## Scope ```bash
go get gitea.neitzel.de/konrad/go-nc-exapp
```
**Included** - [Guide](docs/guide.md) — how to call each capability
- [API](docs/api.md) — every exported symbol
- [Domain language](CONTEXT.md)
- **Credentials** — Nextcloud base URL, AppAPI secret, and requesting user identity ## Included
- **AuthHeaders** — outbound AppAPI authorization for OCS and other Nextcloud calls
- **WithUser** — credentials scoped to a specific requesting user
- **UserFromRequest** — extract the requesting user from inbound AppAPI-proxied requests
- **OCSClient** — authenticated OCS calls that always append `format=json`
- **AppAPIPreferences** — parameterized get/set of a string ExApp preference (caller supplies app id and key)
- **AppAPINotifications** — `Send` (Recipient = Credentials user) and `SendTo` (explicit Recipient); Subject required; Message, Link, and rich-object params optional. AppAPI’s notification OCS is limited (no actions, no custom icon)
- **Groups** — Users and Groups reads: `UserGroups`, `GroupMembers`, `ListGroups` (no search/paging). Directory calls (`GroupMembers` / `ListGroups`) run as the Credentials user and need an admin or subadmin
- **Access Gate** — optional Required Groups enforcement (`Wrap` + `Check`), English denied HTML for browsers (200 + `frame-ancestors 'self'`), positive membership cache; default skip for lifecycle paths and **`/js/`** top-menu scripts; env helpers for `REQUIRED_GROUPS` / `REQUIRED_GROUPS_CACHE_SECONDS`
- **Top Menu visibility** — `TopMenuAdminRequired` helper for deploy env `TOP_MENU_ADMIN_REQUIRED` (`0` / `1` for AppAPI top-menu OCS)
**Excluded** - [Credentials](docs/guide.md#credentials) — Nextcloud base URL, AppAPI secret, and requesting user
- [AuthHeaders](docs/guide.md#authheaders) — outbound AppAPI authorization
- [WithUser](docs/guide.md#withuser) — credentials scoped to one user
- [UserFromRequest](docs/guide.md#userfromrequest) — requesting user on an inbound request
- [OCSClient](docs/guide.md#ocsclient) — authenticated OCS calls with `format=json`
- [AppAPIPreferences](docs/guide.md#appapipreferences) — one string preference for the requesting user
- [AppAPINotifications](docs/guide.md#appapinotifications) — one bell notification
- [Groups](docs/guide.md#groups) — user groups, group members, and the group list
- [Access Gate](docs/guide.md#access-gate) — optional Required Groups check
- [Top Menu visibility](docs/guide.md#top-menu-visibility) — `TOP_MENU_ADMIN_REQUIRED`
- [App navigation](docs/guide.md#app-navigation) — optional Files-style shell
- [Dialog](docs/guide.md#dialog) — message, confirm, and prompt
- ExApp lifecycle HTTP routes (`/heartbeat`, `/enabled`, …) — the Gate *skips* these by default but does not implement them ## Excluded
- HaRP listen / `serve()` and unix-socket bootstrap
- ExApp lifecycle HTTP routes (`/heartbeat`, `/enabled`, and `/init`). The Access Gate skips these by default and does not implement them
- HaRP listen, `serve()`, and unix-socket bootstrap
- Top-menu, script, and iframe UI registration - Top-menu, script, and iframe UI registration
- WebDAV and file storage (see **go-nc-files**) - WebDAV and file storage (see **go-nc-files**)
- **Visit** folder resolution (see **go-nc-files**) - Visit folder resolution (see **go-nc-files**)
- Fan-out Notifications (`SendToGroup` / `SendToAdmins`) - Fan-out notifications (`SendToGroup`, `SendToAdmins`)
- A Library default privileged / admin user for directory OCS (callers who need that use `WithUser` themselves) - A library default admin user for directory OCS (callers pass that user with `WithUser`)
- CheckDNS (or any ExApp) wiring for Notifications or Groups — products opt in separately
## Usage
```go
cred := gonexapp.Credentials{
BaseURL: "https://nextcloud.example",
AppID: "myexapp",
AppVersion: "0.1.0",
AAVersion: "1.0.0",
AppSecret: os.Getenv("APP_SECRET"),
UserID: "alice",
}
prefs := gonexapp.NewAppAPIPreferences(cred, "myexapp", "savedDefault")
value, err := prefs.Get()
err = gonexapp.NewAppAPINotifications(cred).Send(gonexapp.Notification{Subject: "Job finished"})
members, err := gonexapp.NewGroups(cred).GroupMembers("CheckDNS")
groupsEnv, groupsSet := os.LookupEnv("REQUIRED_GROUPS")
groups := gonexapp.ResolveRequiredGroups(groupsEnv, groupsSet, nil)
ttl := gonexapp.ParseCacheSeconds(os.Getenv("REQUIRED_GROUPS_CACHE_SECONDS"), gonexapp.DefaultCacheSeconds)
handler := gonexapp.AccessGate{Cred: cred, Groups: groups, CacheTTL: ttl}.Wrap(inner)
```
Each ExApp chooses its own preference keys; this library does not hardcode product-specific names.
Declare `REQUIRED_GROUPS` and `REQUIRED_GROUPS_CACHE_SECONDS` in the ExApp `info.xml` so Deploy options can set them.
The Gate skips `/heartbeat`, `/enabled`, `/init`, and any path under **`/js/`** (AppAPI top-menu bootstrap). Serve the registered top-menu script under `/js/…` so a non-member still loads it and can show Denied UI in the Nextcloud shell. API routes stay gated.
Denied HTML is **200** with `Content-Security-Policy: … frame-ancestors 'self'`. Without that header AppAPI’s proxy defaults to `frame-ancestors 'none'` and a denied iframe stays blank. Non-HTML denials remain **403**.
### Top Menu visibility (`TOP_MENU_ADMIN_REQUIRED`)
Declare in `info.xml` under `<environment-variables>`. At enable time the ExApp reads the env and passes `"0"` or `"1"` to AppAPI’s top-menu OCS `adminRequired`. Only `0` and `1` are valid; anything else falls back to `DefaultTopMenuAdminRequired` (`true` → admins only).
```go
adminRequired := gonexapp.TopMenuAdminRequired(
os.Getenv(gonexapp.EnvTopMenuAdminRequired),
gonexapp.DefaultTopMenuAdminRequired,
)
// use adminRequired in POST …/ui/top-menu when registering the menu entry
```
**Applying a change:** AppAPI registers the top menu when the ExApp receives `PUT /enabled?enabled=1`. Changing the deploy env alone does not update the menu entry.
1. Set the new value in Deploy options (UI) or `occ app_api:app:register … --env TOP_MENU_ADMIN_REQUIRED=…` / update deploy config.
2. Recreate or restart the ExApp container so the new env is present.
3. Re-run lifecycle: disable then enable the ExApp (UI or `occ app_api:app:disable` / `app_api:app:enable`), or `occ app_api:app:update … -e` after an image/info update.
Route `access_level` in `info.xml` is separate and only changes when AppAPI re-reads `info.xml` on register/update — not via this env.
Runnable package examples: `go test -run Example`.
## Domain language
See [CONTEXT.md](./CONTEXT.md) for AppAPI credentials, Requesting user, Recipient, ExApp preference, Notification, OCS, Required Groups, Users and Groups, Access Gate, and Top Menu visibility terminology.
## Testing ## Testing
Unit tests use `httptest` fake OCS servers. No live Nextcloud is required for Library CI. Unit tests use `httptest` fake OCS servers. No live Nextcloud is required.
`go test ./...` fails when [`docs/api.md`](docs/api.md) does not match the exported API. Regenerate it with:
```bash
UPDATE_API_DOCS=1 go test -run TestAPIDoc -count=1
```
Runnable package examples: `go test -run Example`.
## Related ## Related
- **go-nc-files** — WebDAV, Working Folder, Saved Default, Visit resolution - **go-nc-files** — WebDAV, Working Folder, Saved Default, Visit resolution
- Workspace ADR 0013 — extraction from CheckDNS - Workspace ADR 0013 — extraction from CheckDNS
- Workspace ADR `docs/adr/go-nc-exapp/0001-required-groups-access-gate.md` — Access Gate decisions - Workspace ADR `docs/adr/go-nc-exapp/0001-required-groups-access-gate.md` — Access Gate
- Workspace ADR `docs/adr/go-nc-exapp/0002-users-and-groups-as-requesting-user.md` — directory OCS as Requesting user - Workspace ADR `docs/adr/go-nc-exapp/0002-users-and-groups-as-requesting-user.md` — directory OCS as the requesting user
- Workspace ADR `docs/adr/go-nc-exapp/0003-app-navigation-shell.md` — App navigation shell
- Workspace ADR `docs/adr/go-nc-exapp/0004-dialog-in-exapp-page.md` — Dialog
+10 -7
View File
@@ -2,6 +2,7 @@ package gonexapp
import ( import (
"net/http" "net/http"
"slices"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -39,7 +40,13 @@ const (
CheckUnavailable CheckUnavailable
) )
// Wrap returns a handler that applies the Access Gate before next. // Wrap returns a handler that runs Check before next.
// CheckAllowed calls next.
// CheckUnauthorized writes 401. CheckUnavailable writes 503.
// CheckDenied writes English HTML with status 200 and frame-ancestors 'self'
// when the request accepts text/html, and 403 otherwise.
// An empty Groups list allows every request. Paths /heartbeat, /enabled,
// /init, and /js/ are skipped, plus ExtraSkipPaths.
func (g AccessGate) Wrap(next http.Handler) http.Handler { func (g AccessGate) Wrap(next http.Handler) http.Handler {
gate := g.normalized() gate := g.normalized()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -93,15 +100,13 @@ func (g *AccessGate) memberOfRequired(userID string) (bool, error) {
return false, err return false, err
} }
for _, need := range g.Groups { for _, need := range g.Groups {
for _, have := range groups { if slices.Contains(groups, need) {
if have == need {
if g.CacheTTL > 0 { if g.CacheTTL > 0 {
g.storeAllowed(key) g.storeAllowed(key)
} }
return true, nil return true, nil
} }
} }
}
return false, nil return false, nil
} }
@@ -166,11 +171,9 @@ func (g *AccessGate) shouldSkip(path string) bool {
if isTopMenuScriptPath(path) { if isTopMenuScriptPath(path) {
return true return true
} }
for _, p := range defaultSkipPaths { if slices.Contains(defaultSkipPaths, path) {
if path == p {
return true return true
} }
}
for _, p := range g.ExtraSkipPaths { for _, p := range g.ExtraSkipPaths {
if path == normalizeGatePath(p) { if path == normalizeGatePath(p) {
return true return true
+2 -2
View File
@@ -226,7 +226,7 @@ func TestAccessGateCachesPositiveMembership(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/zones", nil) req := httptest.NewRequest(http.MethodGet, "/api/zones", nil)
req.Header.Set("AUTHORIZATION-APP-API", authHeader("alice")) req.Header.Set("AUTHORIZATION-APP-API", authHeader("alice"))
for i := 0; i < 2; i++ { for i := range 2 {
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
h.ServeHTTP(rec, req) h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK { if rec.Code != http.StatusOK {
@@ -314,7 +314,7 @@ func TestAccessGateZeroTTLDisablesCache(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/zones", nil) req := httptest.NewRequest(http.MethodGet, "/api/zones", nil)
req.Header.Set("AUTHORIZATION-APP-API", authHeader("alice")) req.Header.Set("AUTHORIZATION-APP-API", authHeader("alice"))
for i := 0; i < 2; i++ { for i := range 2 {
rec := httptest.NewRecorder() rec := httptest.NewRecorder()
h.ServeHTTP(rec, req) h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK { if rec.Code != http.StatusOK {
+278
View File
@@ -0,0 +1,278 @@
package gonexapp_test
import (
"bytes"
"fmt"
"go/ast"
"go/doc"
"go/doc/comment"
"go/parser"
"go/printer"
"go/token"
"os"
"strings"
"testing"
)
const apiModulePath = "gitea.neitzel.de/konrad/go-nc-exapp"
func TestAPIDoc(t *testing.T) {
got, err := renderAPIDoc(".", apiModulePath)
if err != nil {
t.Fatal(err)
}
const path = "docs/api.md"
if os.Getenv("UPDATE_API_DOCS") == "1" {
if err := os.MkdirAll("docs", 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
if string(want) != got {
t.Fatalf("docs/api.md is stale; regenerate with UPDATE_API_DOCS=1 go test -run TestAPIDoc -count=1\n%s", firstDiff(string(want), got))
}
}
func renderAPIDoc(dir, modulePath string) (string, error) {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool {
return !strings.HasSuffix(fi.Name(), "_test.go")
}, parser.ParseComments)
if err != nil {
return "", err
}
if len(pkgs) != 1 {
return "", fmt.Errorf("expected 1 package in %s, found %d", dir, len(pkgs))
}
var astPkg *ast.Package
for _, p := range pkgs {
astPkg = p
}
pkg := doc.New(astPkg, modulePath, 0)
lookup := symLookup(pkg)
var b strings.Builder
b.WriteString("# API\n\n")
b.WriteString("Generated from the package comment and every exported declaration. Do not edit.\n")
b.WriteString("Regenerate with `UPDATE_API_DOCS=1 go test -run TestAPIDoc -count=1`.\n\n")
fmt.Fprintf(&b, "## Package %s\n\n", pkg.Name)
writeDoc(&b, pkg.Doc, lookup)
writeValues(&b, fset, "Constants", pkg.Consts, "### ", lookup)
writeValues(&b, fset, "Variables", pkg.Vars, "### ", lookup)
writeFuncs(&b, fset, "Functions", pkg.Funcs, "### ", lookup)
if len(pkg.Types) > 0 {
b.WriteString("## Types\n\n")
for _, typ := range pkg.Types {
writeType(&b, fset, typ, lookup)
}
}
return b.String(), nil
}
func writeType(b *strings.Builder, fset *token.FileSet, typ *doc.Type, lookup func(string, string) bool) {
fmt.Fprintf(b, "### %s\n\n", typ.Name)
sig, err := formatGenDecl(fset, typ.Decl)
if err != nil {
fmt.Fprintf(b, "_(signature unavailable: %v)_\n\n", err)
} else {
writeCode(b, sig)
}
writeDoc(b, typ.Doc, lookup)
writeValues(b, fset, "", typ.Consts, "#### ", lookup)
writeValues(b, fset, "", typ.Vars, "#### ", lookup)
writeFuncs(b, fset, "", typ.Funcs, "#### ", lookup)
if !isInterface(typ) {
writeFuncs(b, fset, "", typ.Methods, "#### ", lookup)
}
}
func writeValues(b *strings.Builder, fset *token.FileSet, title string, vals []*doc.Value, heading string, lookup func(string, string) bool) {
if len(vals) == 0 {
return
}
if title != "" {
fmt.Fprintf(b, "## %s\n\n", title)
}
for _, v := range vals {
for _, name := range v.Names {
fmt.Fprintf(b, "%s%s\n\n", heading, name)
}
sig, err := formatGenDecl(fset, v.Decl)
if err != nil {
fmt.Fprintf(b, "_(signature unavailable: %v)_\n\n", err)
} else {
writeCode(b, sig)
}
writeDoc(b, v.Doc, lookup)
}
}
func writeFuncs(b *strings.Builder, fset *token.FileSet, title string, fns []*doc.Func, heading string, lookup func(string, string) bool) {
if len(fns) == 0 {
return
}
if title != "" {
fmt.Fprintf(b, "## %s\n\n", title)
}
for _, fn := range fns {
name := fn.Name
if fn.Recv != "" {
name = strings.TrimPrefix(fn.Recv, "*") + "." + fn.Name
}
fmt.Fprintf(b, "%s%s\n\n", heading, name)
sig, err := formatFunc(fset, fn.Decl)
if err != nil {
fmt.Fprintf(b, "_(signature unavailable: %v)_\n\n", err)
} else {
writeCode(b, sig)
}
writeDoc(b, fn.Doc, lookup)
}
}
func writeCode(b *strings.Builder, sig string) {
b.WriteString("```go\n")
b.WriteString(sig)
b.WriteString("\n```\n\n")
}
func writeDoc(b *strings.Builder, raw string, lookup func(string, string) bool) {
text := renderComment(raw, lookup)
if text == "" {
return
}
b.WriteString(text)
if !strings.HasSuffix(text, "\n") {
b.WriteByte('\n')
}
b.WriteByte('\n')
}
func symLookup(pkg *doc.Package) func(string, string) bool {
syms := map[string]bool{}
methods := map[string]bool{}
addNames := func(vals []*doc.Value) {
for _, v := range vals {
for _, name := range v.Names {
syms[name] = true
}
}
}
addFuncs := func(fns []*doc.Func) {
for _, fn := range fns {
syms[fn.Name] = true
if fn.Recv != "" {
recv := strings.TrimPrefix(fn.Recv, "*")
methods[recv+"."+fn.Name] = true
}
}
}
addNames(pkg.Consts)
addNames(pkg.Vars)
addFuncs(pkg.Funcs)
for _, typ := range pkg.Types {
syms[typ.Name] = true
addNames(typ.Consts)
addNames(typ.Vars)
addFuncs(typ.Funcs)
addFuncs(typ.Methods)
}
return func(recv, name string) bool {
if recv == "" {
return syms[name]
}
return methods[recv+"."+name]
}
}
func renderComment(raw string, lookup func(string, string) bool) string {
raw = strings.TrimSpace(raw)
if raw == "" {
return ""
}
var parser comment.Parser
parser.LookupSym = lookup
var printer comment.Printer
printer.HeadingLevel = 4
printer.DocLinkURL = func(link *comment.DocLink) string {
if link.ImportPath != "" {
return link.DefaultURL("https://pkg.go.dev")
}
name := link.Name
if link.Recv != "" {
name = link.Recv + "." + link.Name
}
return "#" + githubAnchor(name)
}
return strings.TrimSpace(string(printer.Markdown(parser.Parse(raw))))
}
// githubAnchor matches GitHub heading slugs: lowercase, drop punctuation, keep
// letters, digits, hyphens, and underscores. "Client.Chat" becomes "clientchat".
func githubAnchor(name string) string {
var b strings.Builder
for _, r := range strings.ToLower(name) {
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
b.WriteRune(r)
}
}
return b.String()
}
func formatGenDecl(fset *token.FileSet, decl *ast.GenDecl) (string, error) {
if decl == nil {
return "", fmt.Errorf("nil decl")
}
copyDecl := *decl
copyDecl.Doc = nil
return formatNode(fset, &copyDecl)
}
func formatFunc(fset *token.FileSet, decl *ast.FuncDecl) (string, error) {
if decl == nil {
return "", fmt.Errorf("nil decl")
}
copyDecl := *decl
copyDecl.Doc = nil
copyDecl.Body = nil
return formatNode(fset, &copyDecl)
}
func formatNode(fset *token.FileSet, node ast.Node) (string, error) {
var buf bytes.Buffer
if err := printer.Fprint(&buf, fset, node); err != nil {
return "", err
}
return strings.TrimSpace(buf.String()), nil
}
func isInterface(typ *doc.Type) bool {
if typ.Decl == nil || len(typ.Decl.Specs) != 1 {
return false
}
spec, ok := typ.Decl.Specs[0].(*ast.TypeSpec)
if !ok {
return false
}
_, ok = spec.Type.(*ast.InterfaceType)
return ok
}
func firstDiff(want, got string) string {
w := strings.Split(want, "\n")
g := strings.Split(got, "\n")
n := min(len(g), len(w))
for i := range n {
if w[i] != g[i] {
return fmt.Sprintf("line %d:\n got: %s\nwant: %s", i+1, g[i], w[i])
}
}
return fmt.Sprintf("length got %d lines, want %d lines", len(g), len(w))
}
+16 -5
View File
@@ -7,9 +7,13 @@ import (
"strings" "strings"
) )
// Credentials are what an ExApp needs to call Nextcloud as a user. // Credentials are what an ExApp needs to call Nextcloud as one user.
// BaseURL is the Nextcloud instance URL. A trailing slash is tolerated by
// callers in this package and is removed when they build a URL.
// AppID, AppVersion, and AAVersion are sent as EX-APP-ID, EX-APP-VERSION,
// and AA-VERSION. AppSecret and UserID form the AUTHORIZATION-APP-API token.
type Credentials struct { type Credentials struct {
BaseURL string // Nextcloud instance URL, no trailing slash BaseURL string
AppID string AppID string
AppVersion string AppVersion string
AAVersion string AAVersion string
@@ -17,7 +21,10 @@ type Credentials struct {
UserID string UserID string
} }
// AuthHeaders returns AppAPI auth headers for requests to Nextcloud. // AuthHeaders returns AppAPI headers for a request to Nextcloud.
// The set is AA-VERSION, EX-APP-ID, EX-APP-VERSION, AUTHORIZATION-APP-API,
// and OCS-APIRequest. AUTHORIZATION-APP-API is base64 of UserID, a colon,
// and AppSecret. The method does not return an error; empty fields are sent as empty.
func (c Credentials) AuthHeaders() http.Header { func (c Credentials) AuthHeaders() http.Header {
h := make(http.Header) h := make(http.Header)
h.Set("AA-VERSION", c.AAVersion) h.Set("AA-VERSION", c.AAVersion)
@@ -29,14 +36,18 @@ func (c Credentials) AuthHeaders() http.Header {
return h return h
} }
// WithUser returns a copy acting as userID. // WithUser returns a copy whose UserID is userID.
// The receiver is not modified.
func (c Credentials) WithUser(userID string) Credentials { func (c Credentials) WithUser(userID string) Credentials {
out := c out := c
out.UserID = userID out.UserID = userID
return out return out
} }
// UserFromRequest reads the requesting user from AUTHORIZATION-APP-API on an inbound ExApp request. // UserFromRequest reads the requesting user from AUTHORIZATION-APP-API
// on an inbound ExApp request.
// It returns an error when the header is missing, is not base64, or contains
// no user id before the colon.
func UserFromRequest(r *http.Request) (string, error) { func UserFromRequest(r *http.Request) (string, error) {
raw := r.Header.Get("AUTHORIZATION-APP-API") raw := r.Header.Get("AUTHORIZATION-APP-API")
if raw == "" { if raw == "" {
+112
View File
@@ -0,0 +1,112 @@
package gonexapp
import (
_ "embed"
"html"
"html/template"
"net/http"
)
//go:embed dialog.js
var dialogJS string
// DialogHTML is the Dialog markup and script for an ExApp page, in English.
// App navigation includes the same fragment in the UI language and does not
// take a language argument. A page the ExApp renders itself inserts this
// fragment, or Credentials.DialogHTML when that page has a request.
// The page then calls exappDialog.message, exappDialog.confirm,
// or exappDialog.prompt and waits for the user's choice.
func DialogHTML() template.HTML {
return dialogHTML("en")
}
// DialogHTML is the Dialog fragment in the UI language of r.
// A missing Requesting user or a failed read uses English.
// The caller does not pass a language.
func (c Credentials) DialogHTML(r *http.Request) template.HTML {
return dialogHTML(c.UILanguage(r))
}
func dialogHTML(lang string) template.HTML {
cancel := html.EscapeString(chromePhrase(lang, "dialog.cancel", nil))
agree := html.EscapeString(chromePhrase(lang, "dialog.ok", nil))
return template.HTML(dialogStyle + dialogButtons(cancel, agree) + "<script>" + dialogJS + "</script>")
}
func dialogButtons(cancel, agree string) string {
return `<dialog id="exapp-dialog" aria-modal="true">
<div id="exapp-dialog-panel">
<h2 id="exapp-dialog-heading" hidden></h2>
<p id="exapp-dialog-severity" hidden></p>
<p id="exapp-dialog-message"></p>
<input id="exapp-dialog-value" hidden autocomplete="off">
<div id="exapp-dialog-actions">
<button type="button" id="exapp-dialog-cancel">` + cancel + `</button>
<button type="button" id="exapp-dialog-agree">` + agree + `</button>
</div>
</div>
</dialog>`
}
const dialogStyle = `<style>
#exapp-dialog {
border: none;
padding: 0;
background: transparent;
max-width: calc(100% - 2rem);
}
#exapp-dialog::backdrop { background: rgba(0, 0, 0, 0.45); }
#exapp-dialog-panel {
box-sizing: border-box;
width: min(28rem, 100%);
padding: 1.1rem 1.25rem 1rem;
border-radius: var(--border-radius-element, 8px);
border-top: 4px solid var(--color-primary-element, #00679e);
background: var(--color-main-background, #fff);
color: var(--color-main-text, #222);
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.28);
}
#exapp-dialog[data-severity="warning"] #exapp-dialog-panel { border-top-color: var(--color-warning, #eca700); }
#exapp-dialog[data-severity="error"] #exapp-dialog-panel { border-top-color: var(--color-error, #e9322d); }
#exapp-dialog-heading { margin: 0 0 0.6rem; font-size: 1.15rem; }
#exapp-dialog-severity {
margin: 0 0 0.35rem;
font-size: 0.75rem;
font-weight: 700;
letter-spacing: 0.04em;
text-transform: uppercase;
}
#exapp-dialog-message { margin: 0; white-space: pre-wrap; }
#exapp-dialog-value {
box-sizing: border-box;
width: 100%;
margin-top: 0.8rem;
padding: 0.4rem 0.5rem;
border: 1px solid var(--color-border, #ccc);
border-radius: var(--border-radius-element, 8px);
background: var(--color-main-background, #fff);
color: inherit;
font: inherit;
}
#exapp-dialog-actions { display: flex; justify-content: flex-end; gap: 0.5rem; margin-top: 1.1rem; }
#exapp-dialog-actions button {
min-height: var(--default-clickable-area, 34px);
padding: 0 0.9rem;
border: 1px solid var(--color-border, #ccc);
border-radius: var(--border-radius-element, 8px);
background: var(--color-main-background, #fff);
color: inherit;
font: inherit;
cursor: pointer;
}
#exapp-dialog-actions button#exapp-dialog-agree {
border-color: transparent;
background: var(--color-primary-element, #00679e);
color: var(--color-primary-element-text, #fff);
}
#exapp-dialog-actions button#exapp-dialog-agree.destructive {
background: var(--color-error, #ffe7e7);
color: var(--color-error-text, #8a0000);
}
#exapp-dialog-actions button#exapp-dialog-agree:disabled { opacity: 0.45; cursor: default; }
</style>`
+129
View File
@@ -0,0 +1,129 @@
(function () {
var dialog = document.getElementById("exapp-dialog");
if (!dialog || dialog.getAttribute("data-ready") === "1") return;
dialog.setAttribute("data-ready", "1");
var panel = document.getElementById("exapp-dialog-panel");
var heading = document.getElementById("exapp-dialog-heading");
var severity = document.getElementById("exapp-dialog-severity");
var message = document.getElementById("exapp-dialog-message");
var field = document.getElementById("exapp-dialog-value");
var cancelBtn = document.getElementById("exapp-dialog-cancel");
var agreeBtn = document.getElementById("exapp-dialog-agree");
var defaultAgree = agreeBtn.textContent;
var queue = [];
var busy = false;
var finish = null;
function textOf(value) {
return value == null ? "" : String(value);
}
function trimmed() {
return field.value.trim();
}
function refreshAgree() {
agreeBtn.disabled = !field.hidden && trimmed() === "";
}
function settle(result) {
var done = finish;
finish = null;
if (dialog.open) dialog.close();
busy = false;
if (done) done(result);
pump();
}
function decline() {
if (!finish) return;
var kind = dialog.getAttribute("data-kind");
if (kind === "confirm") settle(false);
else if (kind === "prompt") settle(null);
else settle(undefined);
}
function agree() {
if (!finish || agreeBtn.disabled) return;
var kind = dialog.getAttribute("data-kind");
if (kind === "confirm") settle(true);
else if (kind === "prompt") settle(trimmed());
else settle(undefined);
}
cancelBtn.addEventListener("click", function (e) {
e.stopPropagation();
decline();
});
agreeBtn.addEventListener("click", function (e) {
e.stopPropagation();
agree();
});
field.addEventListener("input", refreshAgree);
dialog.addEventListener("cancel", function (e) {
e.preventDefault();
decline();
});
dialog.addEventListener("click", function (e) {
if (e.target === dialog) decline();
});
dialog.addEventListener("keydown", function (e) {
if (e.key !== "Enter") return;
e.preventDefault();
agree();
});
panel.addEventListener("click", function (e) {
e.stopPropagation();
});
function show(kind, opts, done) {
opts = opts || {};
finish = done;
dialog.setAttribute("data-kind", kind);
var head = textOf(opts.heading);
heading.textContent = head;
heading.hidden = head === "";
message.textContent = textOf(opts.text);
var sev = "";
if (kind === "message") {
sev = opts.severity === "warning" || opts.severity === "error" ? opts.severity : "info";
dialog.setAttribute("data-severity", sev);
} else {
dialog.removeAttribute("data-severity");
}
severity.textContent = sev;
severity.hidden = sev === "";
var isPrompt = kind === "prompt";
field.hidden = !isPrompt;
field.value = isPrompt ? textOf(opts.value) : "";
cancelBtn.hidden = kind === "message";
agreeBtn.textContent = kind !== "message" && opts.agree ? textOf(opts.agree) : defaultAgree;
agreeBtn.classList.toggle("destructive", kind === "confirm" && !!opts.destructive);
refreshAgree();
if (!dialog.open) dialog.showModal();
if (isPrompt) field.focus();
else if (!agreeBtn.disabled) agreeBtn.focus();
}
function pump() {
if (busy || queue.length === 0) return;
busy = true;
queue.shift()();
}
function enqueue(kind, opts) {
return new Promise(function (resolve) {
queue.push(function () {
show(kind, opts, resolve);
});
pump();
});
}
window.exappDialog = {
message: function (opts) { return enqueue("message", opts); },
confirm: function (opts) { return enqueue("confirm", opts); },
prompt: function (opts) { return enqueue("prompt", opts); }
};
})();
+519
View File
@@ -0,0 +1,519 @@
package gonexapp_test
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/chromedp/chromedp"
"github.com/chromedp/chromedp/kb"
"gitea.neitzel.de/konrad/go-nc-exapp"
)
func TestMain(m *testing.M) {
srv := httptest.NewServer(dialogFixture())
defer srv.Close()
fixtureURL = srv.URL
path := browserExecutable()
if path == "" {
fmt.Fprintln(os.Stderr, "dialog tests need Chrome, Edge, or Chromium (set EXAPP_BROWSER)")
os.Exit(1)
}
opts := append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.ExecPath(path),
chromedp.WindowSize(1200, 800),
)
var cancel context.CancelFunc
allocCtx, cancel = chromedp.NewExecAllocator(context.Background(), opts...)
code := m.Run()
cancel()
os.Exit(code)
}
var (
fixtureURL string
allocCtx context.Context
)
func dialogFixture() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /bare", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, "<!DOCTYPE html><html><head><meta charset=utf-8><title>Dialog</title></head><body>",
gonexapp.DialogHTML(), fixtureControls(), "</body></html>")
})
nav := gonexapp.AppNavigation{
DefaultID: "home",
Items: func(*http.Request) []gonexapp.Item {
return []gonexapp.Item{{ID: "home", Label: "Home"}}
},
Page: func(*http.Request, string) (string, bool) {
return fixtureControls(), true
},
}
mux.Handle("GET /shell", nav.Handler())
mux.Handle("GET /nav", sampleNavigation().Handler())
return mux
}
func fixtureControls() string {
return `<button type="button" id="open-info">Open info</button>
<button type="button" id="open-warning">Open warning</button>
<button type="button" id="open-error">Open error</button>
<button type="button" id="open-plain">Open plain</button>
<button type="button" id="open-confirm">Open confirm</button>
<button type="button" id="open-delete">Open delete</button>
<button type="button" id="open-html-button">Open html button</button>
<button type="button" id="open-prompt">Open prompt</button>
<button type="button" id="open-prefill">Open prefill</button>
<button type="button" id="open-blank">Open blank</button>
<button type="button" id="open-inner">Open inner</button>
<button type="button" id="open-three">Open three</button>
<pre id="log"></pre>
<script>
function log(line) { document.getElementById("log").textContent += line + "\n"; }
document.getElementById("open-info").onclick = function () {
exappDialog.message({ severity: "info", heading: "Notice", text: "Hello <b>x</b>", agree: "Nope" }).then(function () { log("dismissed"); });
};
document.getElementById("open-warning").onclick = function () {
exappDialog.message({ severity: "warning", text: "Careful" }).then(function () { log("dismissed"); });
};
document.getElementById("open-error").onclick = function () {
exappDialog.message({ severity: "error", heading: "<b>Nope</b>", text: "Failed" }).then(function () { log("dismissed"); });
};
document.getElementById("open-plain").onclick = function () {
exappDialog.message({ severity: "info", text: "Only the message" }).then(function () { log("dismissed"); });
};
document.getElementById("open-confirm").onclick = function () {
exappDialog.confirm({ text: "Proceed?" }).then(function (yes) { log(yes ? "yes" : "no"); });
};
document.getElementById("open-delete").onclick = function () {
exappDialog.confirm({ heading: "Remove domain", text: "Gone", agree: "Delete", destructive: true }).then(function (yes) { log(yes ? "yes" : "no"); });
};
document.getElementById("open-html-button").onclick = function () {
exappDialog.confirm({ text: "Go?", agree: "<i>Go</i>" }).then(function (yes) { log(yes ? "yes" : "no"); });
};
document.getElementById("open-prompt").onclick = function () {
exappDialog.prompt({ heading: "New folder", text: "Folder name" }).then(function (value) {
log(value === null ? "cancelled" : "value:" + JSON.stringify(value));
});
};
document.getElementById("open-prefill").onclick = function () {
exappDialog.prompt({ text: "Name", value: " hi " }).then(function (value) {
log(value === null ? "cancelled" : "value:" + JSON.stringify(value));
});
};
document.getElementById("open-blank").onclick = function () {
exappDialog.prompt({ text: "Name", value: " " }).then(function (value) {
log(value === null ? "cancelled" : "value:" + JSON.stringify(value));
});
};
document.getElementById("open-inner").onclick = function () {
exappDialog.prompt({ text: "Name", value: "a b" }).then(function (value) {
log(value === null ? "cancelled" : "value:" + JSON.stringify(value));
});
};
document.getElementById("open-three").onclick = function () {
exappDialog.message({ severity: "info", text: "First" }).then(function () { log("1"); });
exappDialog.message({ severity: "warning", text: "Second" }).then(function () { log("2"); });
exappDialog.message({ severity: "error", text: "Third" }).then(function () { log("3"); });
};
</script>`
}
func browserExecutable() string {
if p := os.Getenv("EXAPP_BROWSER"); p != "" {
return p
}
candidates := []string{
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
}
for _, c := range candidates {
if st, err := os.Stat(c); err == nil && !st.IsDir() {
return c
}
}
return ""
}
func drive(t *testing.T, path string, actions ...chromedp.Action) {
t.Helper()
ctx, cancel := chromedp.NewContext(allocCtx)
t.Cleanup(cancel)
ctx, cancel = context.WithTimeout(ctx, 25*time.Second)
t.Cleanup(cancel)
steps := append([]chromedp.Action{chromedp.Navigate(fixtureURL + path)}, actions...)
if err := chromedp.Run(ctx, steps...); err != nil {
t.Fatal(err)
}
}
func clickButton(label string) chromedp.Action {
expr := fmt.Sprintf(`(() => {
const btn = [...document.querySelectorAll("#exapp-dialog button")].find((b) => b.textContent.trim() === %q && !b.hidden);
if (!btn) return "missing";
btn.click();
return "clicked";
})()`, label)
return chromedp.ActionFunc(func(ctx context.Context) error {
var result string
if err := chromedp.Evaluate(expr, &result).Do(ctx); err != nil {
return err
}
if result != "clicked" {
return fmt.Errorf("button %q: %s", label, result)
}
return nil
})
}
func waitJS(expr, want string, contains bool) chromedp.Action {
return chromedp.ActionFunc(func(ctx context.Context) error {
deadline, ok := ctx.Deadline()
if !ok {
deadline = time.Now().Add(5 * time.Second)
}
var last string
for {
var got string
err := chromedp.Evaluate(expr, &got).Do(ctx)
if err == nil {
last = got
if contains && strings.Contains(got, want) {
return nil
}
if !contains && strings.TrimSpace(got) == want {
return nil
}
}
if time.Now().After(deadline) {
return fmt.Errorf("%s = %q, want %q", expr, last, want)
}
if err := chromedp.Sleep(40 * time.Millisecond).Do(ctx); err != nil {
return err
}
}
})
}
func waitDialogText(id, want string) chromedp.Action {
return waitJS(fmt.Sprintf(`document.getElementById("%s").textContent`, id), want, false)
}
func waitLog(want string) chromedp.Action {
return waitJS(`document.getElementById("log").textContent`, want, true)
}
func openShows(t *testing.T, path, button, severity, heading, message string) {
t.Helper()
drive(t, path,
chromedp.WaitVisible("#"+button, chromedp.ByQuery),
chromedp.Click("#"+button, chromedp.ByQuery),
waitDialogText("exapp-dialog-severity", severity),
waitDialogText("exapp-dialog-message", message),
chromedp.ActionFunc(func(ctx context.Context) error {
var head string
var hidden bool
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog-heading").textContent`, &head).Do(ctx); err != nil {
return err
}
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog-heading").hidden`, &hidden).Do(ctx); err != nil {
return err
}
if heading == "" {
if !hidden {
return fmt.Errorf("heading visible %q", head)
}
return nil
}
if hidden || strings.TrimSpace(head) != heading {
return fmt.Errorf("heading %q hidden %v, want %q", head, hidden, heading)
}
var bold int
if err := chromedp.Evaluate(`document.querySelectorAll("#exapp-dialog b, #exapp-dialog i").length`, &bold).Do(ctx); err != nil {
return err
}
if bold != 0 {
return fmt.Errorf("dialog interpreted HTML, %d elements", bold)
}
var label string
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog-agree").textContent`, &label).Do(ctx); err != nil {
return err
}
if strings.TrimSpace(label) != "OK" {
return fmt.Errorf("message button %q, want OK", label)
}
return nil
}),
)
}
func TestMessageOnBarePage(t *testing.T) {
openShows(t, "/bare", "open-info", "info", "Notice", "Hello <b>x</b>")
}
func TestMessageOnAppNavigation(t *testing.T) {
openShows(t, "/shell", "open-info", "info", "Notice", "Hello <b>x</b>")
}
func TestMessageSeveritiesAndDismiss(t *testing.T) {
cases := []struct {
button string
severity string
how string
}{
{"open-warning", "warning", "ok"},
{"open-error", "error", "enter"},
{"open-info", "info", "escape"},
{"open-plain", "info", "backdrop"},
}
for _, tc := range cases {
t.Run(tc.how, func(t *testing.T) {
var dismiss chromedp.Action
switch tc.how {
case "ok":
dismiss = clickButton("OK")
case "enter":
dismiss = chromedp.KeyEvent(kb.Enter)
case "escape":
dismiss = chromedp.KeyEvent(kb.Escape)
case "backdrop":
dismiss = chromedp.MouseClickXY(8, 8)
}
drive(t, "/bare",
chromedp.Click("#"+tc.button, chromedp.ByQuery),
waitDialogText("exapp-dialog-severity", tc.severity),
dismiss,
waitLog("dismissed"),
)
})
}
}
func TestMessageWithoutHeading(t *testing.T) {
openShows(t, "/bare", "open-plain", "info", "", "Only the message")
}
func TestConfirmYesNoAndDestructive(t *testing.T) {
t.Run("cancel", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-confirm", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Proceed?"),
clickButton("Cancel"),
waitLog("no"),
)
})
t.Run("escape", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-confirm", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Proceed?"),
chromedp.KeyEvent(kb.Escape),
waitLog("no"),
)
})
t.Run("backdrop", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-confirm", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Proceed?"),
chromedp.MouseClickXY(8, 8),
waitLog("no"),
)
})
t.Run("enter", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-confirm", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Proceed?"),
chromedp.KeyEvent(kb.Enter),
waitLog("yes"),
)
})
t.Run("delete", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-delete", chromedp.ByQuery),
waitDialogText("exapp-dialog-heading", "Remove domain"),
chromedp.ActionFunc(func(ctx context.Context) error {
var plain, destructive string
if err := chromedp.Evaluate(`getComputedStyle(document.getElementById("exapp-dialog-cancel")).backgroundColor`, &plain).Do(ctx); err != nil {
return err
}
if err := chromedp.Evaluate(`getComputedStyle(document.getElementById("exapp-dialog-agree")).backgroundColor`, &destructive).Do(ctx); err != nil {
return err
}
if plain == destructive {
return fmt.Errorf("destructive button color %q matches Cancel", destructive)
}
var text string
if err := chromedp.Evaluate(`getComputedStyle(document.getElementById("exapp-dialog-agree")).color`, &text).Do(ctx); err != nil {
return err
}
if text == "rgb(255, 255, 255)" || text == destructive {
return fmt.Errorf("destructive label color %q on background %q", text, destructive)
}
var label string
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog-agree").textContent`, &label).Do(ctx); err != nil {
return err
}
if strings.TrimSpace(label) != "Delete" {
return fmt.Errorf("agree label %q", label)
}
return nil
}),
clickButton("Delete"),
waitLog("yes"),
)
})
t.Run("button word is plain text", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-html-button", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Go?"),
chromedp.ActionFunc(func(ctx context.Context) error {
var n int
var label string
if err := chromedp.Evaluate(`document.querySelectorAll("#exapp-dialog i").length`, &n).Do(ctx); err != nil {
return err
}
if n != 0 {
return fmt.Errorf("button word was interpreted as HTML")
}
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog-agree").textContent`, &label).Do(ctx); err != nil {
return err
}
if strings.TrimSpace(label) != "<i>Go</i>" {
return fmt.Errorf("agree label %q", label)
}
return nil
}),
)
})
}
func TestPromptValueAndCancel(t *testing.T) {
t.Run("empty stays inactive", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-prompt", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Folder name"),
waitDialogText("exapp-dialog-heading", "New folder"),
chromedp.ActionFunc(func(ctx context.Context) error {
var disabled bool
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog-agree").disabled`, &disabled).Do(ctx); err != nil {
return err
}
if !disabled {
return fmt.Errorf("agree button active on an empty Prompt")
}
return chromedp.KeyEvent(kb.Enter).Do(ctx)
}),
chromedp.Sleep(200*time.Millisecond),
chromedp.ActionFunc(func(ctx context.Context) error {
var open bool
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog").open`, &open).Do(ctx); err != nil {
return err
}
if !open {
return fmt.Errorf("Enter closed an empty Prompt")
}
return nil
}),
clickButton("Cancel"),
waitLog("cancelled"),
)
})
t.Run("spaces only stay inactive", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-blank", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Name"),
chromedp.ActionFunc(func(ctx context.Context) error {
var disabled bool
var raw string
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog-agree").disabled`, &disabled).Do(ctx); err != nil {
return err
}
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog-value").value`, &raw).Do(ctx); err != nil {
return err
}
if raw != " " {
return fmt.Errorf("starting value %q", raw)
}
if !disabled {
return fmt.Errorf("agree button active for spaces")
}
return nil
}),
)
})
t.Run("prefill trims on agree", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-prefill", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Name"),
chromedp.ActionFunc(func(ctx context.Context) error {
var raw string
if err := chromedp.Evaluate(`document.getElementById("exapp-dialog-value").value`, &raw).Do(ctx); err != nil {
return err
}
if raw != " hi " {
return fmt.Errorf("starting value %q", raw)
}
return nil
}),
clickButton("OK"),
waitLog(`value:"hi"`),
)
})
t.Run("inner spaces stay", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-inner", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Name"),
clickButton("OK"),
waitLog(`value:"a b"`),
)
})
t.Run("escape cancels", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-prompt", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Folder name"),
chromedp.KeyEvent(kb.Escape),
waitLog("cancelled"),
)
})
t.Run("typed value", func(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-prompt", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "Folder name"),
chromedp.SendKeys("#exapp-dialog-value", " mail ", chromedp.ByQuery),
chromedp.KeyEvent(kb.Enter),
waitLog(`value:"mail"`),
)
})
}
func TestOneDialogAtATime(t *testing.T) {
drive(t, "/bare",
chromedp.Click("#open-three", chromedp.ByQuery),
waitDialogText("exapp-dialog-message", "First"),
chromedp.ActionFunc(func(ctx context.Context) error {
var n int
if err := chromedp.Evaluate(`document.querySelectorAll("dialog[open]").length`, &n).Do(ctx); err != nil {
return err
}
if n != 1 {
return fmt.Errorf("open dialogs %d, want 1", n)
}
return nil
}),
clickButton("OK"),
waitDialogText("exapp-dialog-message", "Second"),
clickButton("OK"),
waitDialogText("exapp-dialog-message", "Third"),
clickButton("OK"),
waitLog("1\n2\n3"),
)
}
+3 -1
View File
@@ -1,3 +1,5 @@
// Package gonexapp provides AppAPI credentials, OCS JSON calls, ExApp user // Package gonexapp provides AppAPI credentials, OCS JSON calls, ExApp user
// preferences, and an optional Required Groups Access Gate for Nextcloud ExApp Services. // preferences, Notifications, Users and Groups reads, an optional Required
// Groups Access Gate, an optional App navigation shell, and a Dialog for
// Nextcloud ExApp Services.
package gonexapp package gonexapp
+533
View File
@@ -0,0 +1,533 @@
# API
Generated from the package comment and every exported declaration. Do not edit.
Regenerate with `UPDATE_API_DOCS=1 go test -run TestAPIDoc -count=1`.
## Package gonexapp
Package gonexapp provides AppAPI credentials, OCS JSON calls, ExApp user preferences, Notifications, Users and Groups reads, an optional Required Groups Access Gate, an optional App navigation shell, and a Dialog for Nextcloud ExApp Services.
## Constants
### DefaultCacheSeconds
```go
const DefaultCacheSeconds = 60
```
DefaultCacheSeconds is used when REQUIRED\_GROUPS\_CACHE\_SECONDS is unset or invalid.
### DefaultTopMenuAdminRequired
```go
const DefaultTopMenuAdminRequired = true
```
DefaultTopMenuAdminRequired is used when TOP\_MENU\_ADMIN\_REQUIRED is unset or invalid.
### EnvRequiredGroups
```go
const EnvRequiredGroups = "REQUIRED_GROUPS"
```
EnvRequiredGroups is the conventional deploy env name for Required Groups.
### EnvRequiredGroupsCacheSeconds
```go
const EnvRequiredGroupsCacheSeconds = "REQUIRED_GROUPS_CACHE_SECONDS"
```
EnvRequiredGroupsCacheSeconds is the conventional deploy env name for Access Gate cache TTL.
### EnvTopMenuAdminRequired
```go
const EnvTopMenuAdminRequired = "TOP_MENU_ADMIN_REQUIRED"
```
EnvTopMenuAdminRequired is the conventional deploy env name for Top Menu visibility. Declare it in the ExApp info.xml environment-variables section.
## Variables
### NextcloudIcons
```go
var NextcloudIcons = nextcloudIcons{
Folder: "/core/img/filetypes/folder.svg",
FolderShared: "/core/img/filetypes/folder-shared.svg",
FolderPublic: "/core/img/filetypes/folder-public.svg",
FolderStarred: "/core/img/filetypes/folder-starred.svg",
FolderEncrypted: "/core/img/filetypes/folder-encrypted.svg",
File: "/core/img/filetypes/file.svg",
Text: "/core/img/filetypes/text.svg",
Image: "/core/img/filetypes/image.svg",
Audio: "/core/img/filetypes/audio.svg",
Video: "/core/img/filetypes/video.svg",
PDF: "/core/img/filetypes/application-pdf.svg",
Document: "/core/img/filetypes/x-office-document.svg",
Spreadsheet: "/core/img/filetypes/x-office-spreadsheet.svg",
Presentation: "/core/img/filetypes/x-office-presentation.svg",
Files: "/core/img/places/files.svg",
Home: "/core/img/places/home.svg",
Calendar: "/core/img/places/calendar.svg",
Contacts: "/core/img/places/contacts.svg",
Add: "/core/img/actions/add.svg",
Delete: "/core/img/actions/delete.svg",
Edit: "/core/img/actions/edit.svg",
Rename: "/core/img/actions/rename.svg",
Download: "/core/img/actions/download.svg",
Upload: "/core/img/actions/upload.svg",
Share: "/core/img/actions/share.svg",
Search: "/core/img/actions/search.svg",
Settings: "/core/img/actions/settings.svg",
Info: "/core/img/actions/info.svg",
History: "/core/img/actions/history.svg",
Password: "/core/img/actions/password.svg",
Confirm: "/core/img/actions/confirm.svg",
Close: "/core/img/actions/close.svg",
Star: "/core/img/actions/star.svg",
User: "/core/img/actions/user.svg",
Group: "/core/img/actions/group.svg",
Mail: "/core/img/actions/mail.svg",
Menu: "/core/img/actions/menu.svg",
External: "/core/img/actions/external.svg",
Filter: "/core/img/actions/filter.svg",
Recent: "/core/img/actions/recent.svg",
Tag: "/core/img/actions/tag.svg",
}
```
NextcloudIcons are SVG paths served by Nextcloud core under /core/img/. The library does not ship the files. Set Item.Icon to one of these. Dark mode inverts them with Nextcloud’s --background-invert-if-dark filter.
## Functions
### DialogHTML
```go
func DialogHTML() template.HTML
```
DialogHTML is the Dialog markup and script for an ExApp page, in English. App navigation includes the same fragment in the UI language and does not take a language argument. A page the ExApp renders itself inserts this fragment, or Credentials.DialogHTML when that page has a request. The page then calls exappDialog.message, exappDialog.confirm, or exappDialog.prompt and waits for the user's choice.
### FillScript
```go
func FillScript() template.HTML
```
FillScript replaces English source after load and refreshes Fold from the visible item name. It does not parse Phrase text as HTML. App navigation includes it. A page the ExApp renders itself places Script in the head and FillScript at the end of the body.
### ParseCacheSeconds
```go
func ParseCacheSeconds(s string, defaultSec int) time.Duration
```
ParseCacheSeconds parses REQUIRED\_GROUPS\_CACHE\_SECONDS. Unset or invalid → defaultSec seconds; "0" → no cache.
### ParseRequiredGroups
```go
func ParseRequiredGroups(s string) []string
```
ParseRequiredGroups splits a comma-separated Required Groups env value.
### ResolveRequiredGroups
```go
func ResolveRequiredGroups(envValue string, envSet bool, codeDefault []string) []string
```
ResolveRequiredGroups applies env override rules: unset uses codeDefault; set (including empty) replaces the default.
### TopMenuAdminRequired
```go
func TopMenuAdminRequired(envValue string, defaultAdminRequired bool) string
```
TopMenuAdminRequired returns "1" or "0" for the AppAPI top-menu OCS adminRequired field. Only "0" and "1" are accepted; any other value falls back to defaultAdminRequired. An empty envValue means unset and also uses defaultAdminRequired.
### UserFromRequest
```go
func UserFromRequest(r *http.Request) (string, error)
```
UserFromRequest reads the requesting user from AUTHORIZATION-APP-API on an inbound ExApp request. It returns an error when the header is missing, is not base64, or contains no user id before the colon.
## Types
### AccessGate
```go
type AccessGate struct {
Cred Credentials
Groups []string
CacheTTL time.Duration // 0 disables cache
ExtraSkipPaths []string
Client *http.Client
OCS OCSClient
Now func() time.Time
// contains filtered or unexported fields
}
```
AccessGate enforces Required Groups for the Requesting user on ExApp HTTP traffic.
#### AccessGate.Check
```go
func (g *AccessGate) Check(r *http.Request) CheckResult
```
Check reports whether r may proceed under Required Groups.
#### AccessGate.Wrap
```go
func (g AccessGate) Wrap(next http.Handler) http.Handler
```
Wrap returns a handler that runs Check before next. CheckAllowed calls next. CheckUnauthorized writes 401. CheckUnavailable writes 503. CheckDenied writes English HTML with status 200 and frame-ancestors 'self' when the request accepts text/html, and 403 otherwise. An empty Groups list allows every request. Paths /heartbeat, /enabled, /init, and /js/ are skipped, plus ExtraSkipPaths.
### AppAPINotifications
```go
type AppAPINotifications struct {
Cred Credentials
Client *http.Client
OCS OCSClient
}
```
AppAPINotifications creates Notifications via AppAPI OCS.
#### NewAppAPINotifications
```go
func NewAppAPINotifications(cred Credentials) AppAPINotifications
```
NewAppAPINotifications returns a sender using cred for AppAPI auth.
#### AppAPINotifications.Send
```go
func (n AppAPINotifications) Send(notif Notification) error
```
Send creates a Notification for Cred.UserID. It returns an error when UserID or Subject is empty, or when the OCS call fails. AppAPI notification OCS accepts Subject, Message, Link, and rich-object parameters. It does not accept actions or a custom icon.
#### AppAPINotifications.SendTo
```go
func (n AppAPINotifications) SendTo(userID string, notif Notification) error
```
SendTo creates a Notification for userID. The OCS call is authenticated as that user via WithUser. It returns an error when userID or Subject is empty, or when the OCS call fails.
### AppAPIPreferences
```go
type AppAPIPreferences struct {
Cred Credentials
AppID string
Key string
Client *http.Client
OCS OCSClient
}
```
AppAPIPreferences reads and writes one string ExApp preference for the requesting user.
#### NewAppAPIPreferences
```go
func NewAppAPIPreferences(cred Credentials, appID, key string) AppAPIPreferences
```
NewAppAPIPreferences returns a preference store for appID and key using cred for auth.
#### AppAPIPreferences.Get
```go
func (p AppAPIPreferences) Get() (string, error)
```
Get loads the configured preference key for the requesting user. A missing key returns an empty string and a nil error. It returns an error when the OCS call fails or the body cannot be decoded.
#### AppAPIPreferences.Set
```go
func (p AppAPIPreferences) Set(value string) error
```
Set stores value for the configured preference key. The value is stored as non-sensitive. It returns an error when the OCS call fails.
### AppNavigation
```go
type AppNavigation struct {
Items func(*http.Request) []Item
Page func(*http.Request, string) (string, bool)
Header func(*http.Request) string
DefaultID string
MissingMessage string
SelectKey string
// Title is the document title. Empty means "App navigation".
Title string
// DisableTheme skips the Nextcloud theme stylesheets. The zero value
// loads the active theme.
DisableTheme bool
// Cred reads the UI language for this page from Nextcloud.
// The zero value leaves the page in English.
// The caller does not pass a language.
Cred Credentials
// Phrases is the ExApp's set. The page script receives it.
// Library chrome is not included. The zero value leaves the page in English.
Phrases Phrases
// MissingPhrase names the ExApp Phrase for MissingMessage.
MissingPhrase string
}
```
AppNavigation is the Files-style shell an ExApp mounts. Items, Page, and DefaultID are required. Header and MissingMessage are optional. SelectKey defaults to "item". Every other query parameter, including the Visit folder, is copied onto the corrected address. An ExApp that never calls Handler keeps its own page.
#### AppNavigation.Handler
```go
func (n AppNavigation) Handler() http.Handler
```
Handler serves the shell. The selected item is the SelectKey query parameter. A missing item renders DefaultID, includes MissingMessage, and publishes the corrected query on data-address so the page can replace the address. Every parent starts expanded. Folding is client state for this document only.
### CheckResult
```go
type CheckResult int
```
CheckResult is the outcome of AccessGate.Check.
#### CheckAllowed
#### CheckDenied
#### CheckUnauthorized
#### CheckUnavailable
```go
const (
// CheckAllowed means the request may proceed (or the gate is inactive / skipped).
CheckAllowed CheckResult = iota
// CheckDenied means the Requesting user is not in Required Groups.
CheckDenied
// CheckUnauthorized means no Requesting user could be read from the request.
CheckUnauthorized
// CheckUnavailable means group membership could not be determined (e.g. OCS error).
CheckUnavailable
)
```
### Credentials
```go
type Credentials struct {
BaseURL string
AppID string
AppVersion string
AAVersion string
AppSecret string
UserID string
}
```
Credentials are what an ExApp needs to call Nextcloud as one user. BaseURL is the Nextcloud instance URL. A trailing slash is tolerated by callers in this package and is removed when they build a URL. AppID, AppVersion, and AAVersion are sent as EX-APP-ID, EX-APP-VERSION, and AA-VERSION. AppSecret and UserID form the AUTHORIZATION-APP-API token.
#### Credentials.AuthHeaders
```go
func (c Credentials) AuthHeaders() http.Header
```
AuthHeaders returns AppAPI headers for a request to Nextcloud. The set is AA-VERSION, EX-APP-ID, EX-APP-VERSION, AUTHORIZATION-APP-API, and OCS-APIRequest. AUTHORIZATION-APP-API is base64 of UserID, a colon, and AppSecret. The method does not return an error; empty fields are sent as empty.
#### Credentials.DialogHTML
```go
func (c Credentials) DialogHTML(r *http.Request) template.HTML
```
DialogHTML is the Dialog fragment in the UI language of r. A missing Requesting user or a failed read uses English. The caller does not pass a language.
#### Credentials.UILanguage
```go
func (c Credentials) UILanguage(r *http.Request) string
```
UILanguage is the language of the Phrases for this request, "en" or "de". It reads the Requesting user's language from the Provisioning OCS user record and forwards the request's Accept-Language on that read. The locale field is ignored. A more specific code uses the broader language when this Library provides that language. Any other code, a missing Requesting user, or a failed read is English, and the page still renders. A second call with the request returned from a page render reuses that result.
#### Credentials.WithUser
```go
func (c Credentials) WithUser(userID string) Credentials
```
WithUser returns a copy whose UserID is userID. The receiver is not modified.
### Groups
```go
type Groups struct {
Cred Credentials
Client *http.Client
OCS OCSClient
}
```
Groups reads Users and Groups from Provisioning OCS.
#### NewGroups
```go
func NewGroups(cred Credentials) Groups
```
NewGroups returns a directory reader using cred for AppAPI auth.
#### Groups.GroupMembers
```go
func (g Groups) GroupMembers(groupID string) ([]string, error)
```
GroupMembers returns the user ids in groupID. The OCS call uses Cred as-is. Nextcloud requires that user to be an admin or a subadmin of the group. It returns an error when the OCS call fails or the body cannot be decoded. There is no search or paging.
#### Groups.ListGroups
```go
func (g Groups) ListGroups() ([]string, error)
```
ListGroups returns instance group ids. The OCS call uses Cred as-is and needs an admin or subadmin. It returns an error when the OCS call fails or the body cannot be decoded. There is no search or paging.
#### Groups.UserGroups
```go
func (g Groups) UserGroups(userID string) ([]string, error)
```
UserGroups returns the Nextcloud group ids of userID. The OCS call is authenticated as userID. It returns an error when the OCS call fails or the body cannot be decoded.
### Item
```go
type Item struct {
ID string
Label string
Icon string
Phrase string
Children []Item
}
```
Item is one App navigation entry. The ExApp chooses the ids and labels. Children may nest. The shell does not interpret the ids. Icon is an optional same-origin image URL. NextcloudIcons names the core SVGs. Phrase names the ExApp Phrase for Label. The English label stays in the page until the script replaces it. Empty leaves the label as written.
### Notification
```go
type Notification struct {
Subject string
Message string
Link string
SubjectParams map[string]any
MessageParams map[string]any
}
```
Notification is one Nextcloud bell for a single Recipient.
### OCSClient
```go
type OCSClient struct {
Cred Credentials
Client *http.Client
Header http.Header
}
```
OCSClient performs AppAPI-authenticated OCS requests with format=json. Header is copied onto the outbound request after the AppAPI auth headers. The UI language read uses it to forward Accept-Language.
#### OCSClient.Call
```go
func (c OCSClient) Call(method, path string, body []byte) ([]byte, error)
```
Call performs method against path with an optional JSON body and returns the response body after verifying it is valid JSON. Non-2xx responses return an error including the status.
#### OCSClient.URL
```go
func (c OCSClient) URL(path string) string
```
URL builds an OCS URL under /ocs/v2.php with format=json.
### Phrases
```go
type Phrases struct {
// contains filtered or unexported fields
}
```
Phrases is one ExApp's merged Phrase set. English is the complete set. A module set is merged with Merge; a repeated id uses the set added later. The page script receives this set. Library chrome is not included.
#### Merge
```go
func Merge(sets ...Phrases) Phrases
```
Merge returns the sets combined in order. A repeated id uses the text from the set added later.
#### ParsePhrases
```go
func ParsePhrases(en, de []byte) (Phrases, error)
```
ParsePhrases reads an English object and a German object.
#### PhrasesFromFS
```go
func PhrasesFromFS(fsys fs.FS) (Phrases, error)
```
PhrasesFromFS reads i18n/en.json and i18n/de.json. Each file is one JSON object of id → text.
#### Phrases.Script
```go
func (p Phrases) Script(lang string) template.HTML
```
Script defines exappPhrase for the page, from this set only.
#### Phrases.Sentence
```go
func (p Phrases) Sentence(lang, id string, holes map[string]string) string
```
Sentence is the finished text for lang. A missing text for that language uses the English text. An id missing from English is the id. A hole with no value stays visible as {name}. The result is plain text; the caller escapes it when writing HTML.
+425
View File
@@ -0,0 +1,425 @@
# go-nc-exapp guide
How to use the library. Symbol signatures and doc comments are in [API](api.md). Words for the domain are in [CONTEXT.md](../CONTEXT.md).
## Credentials
### Purpose
`Credentials` is the set an ExApp needs to call Nextcloud as one user: the instance URL, the ExApp identity, the AppAPI secret, and the user id.
### When to use it
Fill one value at the edge of the service, from the environment HaRP injects, and pass it into preferences, notifications, groups, the Access Gate, and go-nc-files.
### Call sequence
1. Set `BaseURL`, `AppID`, `AppVersion`, `AAVersion`, `AppSecret`, and `UserID`.
2. Pass the value to `AuthHeaders`, `WithUser`, or a constructor such as `NewAppAPIPreferences`.
`BaseURL` may have a trailing slash. Callers in this package remove it when they build a URL.
### Errors
Constructing a `Credentials` value does not return an error. Empty fields are sent as empty headers. The Nextcloud call then fails.
### Example
```go
cred := gonexapp.Credentials{
BaseURL: "https://nextcloud.example",
AppID: "myexapp",
AppVersion: "0.1.0",
AAVersion: "1.0.0",
AppSecret: os.Getenv("APP_SECRET"),
UserID: "alice",
}
```
## AuthHeaders
### Purpose
`AuthHeaders` builds the AppAPI headers for a request from the ExApp to Nextcloud.
### When to use it
Use it for any Nextcloud HTTP call that is not going through `OCSClient`. `OCSClient` calls it for you. go-nc-files uses it on WebDAV.
### Call sequence
1. Fill `Credentials`.
2. Call `AuthHeaders`.
3. Copy the header onto the outbound request.
The set is `AA-VERSION`, `EX-APP-ID`, `EX-APP-VERSION`, `AUTHORIZATION-APP-API`, and `OCS-APIRequest`. `AUTHORIZATION-APP-API` is base64 of `UserID`, a colon, and `AppSecret`.
### Errors
`AuthHeaders` does not return an error.
### Example
```go
req.Header = cred.AuthHeaders()
```
## WithUser
### Purpose
`WithUser` returns a copy of the credentials whose `UserID` is the given user. The original value is unchanged.
### When to use it
Use it when one OCS call must run as a different user than the one on the service's credentials. `SendTo` and `UserGroups` do this themselves. Directory calls that must run as an admin use `WithUser` at the call site. This library does not pick an admin user.
### Call sequence
1. Start from the service credentials.
2. Call `WithUser` with the target user id.
3. Pass the copy to the client that should act as that user.
### Errors
`WithUser` does not return an error. An empty user id is stored as empty and fails later, when a call requires a recipient.
### Example
```go
asAdmin := cred.WithUser(adminID)
groups := gonexapp.NewGroups(asAdmin)
```
## UserFromRequest
### Purpose
`UserFromRequest` reads the requesting user from `AUTHORIZATION-APP-API` on a request HaRP proxied into the ExApp.
### When to use it
Use it on inbound ExApp routes when the handler needs the user id and does not already have it from the Access Gate. The Access Gate calls it before checking groups.
### Call sequence
1. Take the `*http.Request` the ExApp received.
2. Call `UserFromRequest`.
3. Use the returned user id as `Credentials.UserID` for outbound calls on behalf of that user.
### Errors
The function returns an error when the header is missing, is not base64, or has no user id before the colon.
### Example
```go
userID, err := gonexapp.UserFromRequest(r)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
cred.UserID = userID
```
## OCSClient
### Purpose
`OCSClient` performs an AppAPI-authenticated OCS request and requires a JSON body. Every URL gets `format=json`.
### When to use it
Use it for OCS routes that the typed helpers do not cover. Preferences, notifications, and groups are built on it. A nil `Client` uses `http.DefaultClient`.
### Call sequence
1. Set `OCSClient.Cred`.
2. Call `URL` when the caller only needs the address, or `Call` to perform the request.
3. `Call` takes an HTTP method, a path under `/ocs/v2.php/`, and an optional JSON body.
4. On success, decode the returned bytes. The client checks that the bytes are JSON and does not decode a particular OCS shape.
`URL` joins `BaseURL`, `/ocs/v2.php/`, the path, and `?format=json`.
### Errors
`Call` returns an error when the request cannot be built, the transport fails, the status is outside 2xx, or the body is not JSON. A non-2xx error includes the method, path, and HTTP status.
### Example
```go
ocs := gonexapp.OCSClient{Cred: cred}
raw, err := ocs.Call(http.MethodGet, "cloud/capabilities", nil)
if err != nil {
return err
}
_ = raw
```
## AppAPIPreferences
### Purpose
`AppAPIPreferences` reads and writes one string ExApp preference for the requesting user. The caller chooses the app id and the key. The library does not reserve product key names.
### When to use it
Use it for a per-user string such as a Saved Default path. Pair it with a go-nc-files `DefaultPathStore` in the ExApp if the product stores that path in preferences.
### Call sequence
1. Call `NewAppAPIPreferences` with credentials, the app id, and the key.
2. `Get` loads the value. A missing key returns an empty string.
3. `Set` stores a new string. The value is stored as non-sensitive.
Declare nothing extra for the preference itself. The AppAPI preference routes are fixed.
### Errors
`Get` and `Set` return the error from the OCS call. `Get` also returns an error when the body cannot be decoded. A missing key is an empty string and a nil error.
### Example
```go
prefs := gonexapp.NewAppAPIPreferences(cred, "myexapp", "savedDefault")
value, err := prefs.Get()
if err != nil {
return err
}
if err := prefs.Set("Zones"); err != nil {
return err
}
_ = value
```
## AppAPINotifications
### Purpose
`AppAPINotifications` creates one Nextcloud bell notification for one recipient. `Notification` carries a subject and, optionally, a message, a link, and rich-object parameter maps.
### When to use it
Use `Send` for the user on `Credentials`. Use `SendTo` for a different user. The library does not fan out to a group or to all admins.
### Call sequence
1. Call `NewAppAPINotifications` with credentials.
2. Fill a `Notification`. `Subject` is required. `Message`, `Link`, `SubjectParams`, and `MessageParams` are optional.
3. Call `Send` or `SendTo`.
`SendTo` authenticates the OCS call as that user via `WithUser`. AppAPI's notification route accepts this shape and does not accept actions or a custom icon.
### Errors
`Send` returns an error when `Cred.UserID` is empty. Both methods return an error when the subject is empty, the recipient user id is empty, or the OCS call fails.
### Example
```go
err := gonexapp.NewAppAPINotifications(cred).Send(gonexapp.Notification{
Subject: "Job finished",
Message: "The zone was updated.",
})
```
## Groups
### Purpose
`Groups` reads Users and Groups from the Provisioning API: the groups of one user, the members of one group, and the instance group list. There is no search and no paging.
### When to use it
Use `UserGroups` for the Access Gate's membership check, or whenever the product needs one user's groups. Use `GroupMembers` and `ListGroups` for directory listings. Those two call OCS as `Cred`'s user, who must be an admin or a subadmin.
### Call sequence
1. Call `NewGroups` with credentials.
2. `UserGroups(userID)` lists that user's group ids and authenticates as `userID`.
3. `GroupMembers(groupID)` lists user ids in the group, as the credentials user.
4. `ListGroups` lists instance group ids, as the credentials user.
### Errors
Each method returns an error when the OCS call fails or the body cannot be decoded. A forbidden directory call is the OCS error from `Call` (HTTP status in the message). This package does not wrap those as a sentinel.
### Example
```go
members, err := gonexapp.NewGroups(cred).GroupMembers("ops")
if err != nil {
return err
}
_ = members
```
## Access Gate
### Purpose
The Access Gate allows a request only when the requesting user is in one of the Required Groups. An empty group list turns the gate off.
### When to use it
Wrap the ExApp's HTTP handler when the product restricts who may open it. Leave `Groups` empty to allow everyone. Lifecycle routes stay reachable either way.
### Call sequence
1. Read the deploy environment. `EnvRequiredGroups` is `REQUIRED_GROUPS`. `EnvRequiredGroupsCacheSeconds` is `REQUIRED_GROUPS_CACHE_SECONDS`.
2. `ResolveRequiredGroups` uses the code default when the variable is unset, and replaces it when the variable is set, including set to empty.
3. `ParseCacheSeconds` turns the cache variable into a duration. Unset or invalid uses `DefaultCacheSeconds` (60). `"0"` disables the cache.
4. Put the credentials, the group list, and the cache TTL on an `AccessGate`.
5. `Wrap` the handler. Or call `Check` and branch on `CheckResult`.
`Wrap` calls `next` on `CheckAllowed`. `CheckUnauthorized` writes 401. `CheckUnavailable` writes 503. `CheckDenied` writes English HTML with status 200 and `frame-ancestors 'self'` when the request accepts `text/html`, and 403 otherwise. The 200 status and the CSP keep AppAPI from blanking the iframe.
Skipped paths are `/heartbeat`, `/enabled`, `/init`, anything under `/js/`, and `ExtraSkipPaths`. Top-menu scripts live under `/js/` so a non-member can still load them.
Positive membership is cached for `CacheTTL`. A denial is not cached. `CacheTTL` of zero disables the cache.
### Errors
`Check` does not return an error. It returns `CheckUnauthorized` when the requesting user cannot be read, and `CheckUnavailable` when the group lookup fails. `ParseRequiredGroups` and `ResolveRequiredGroups` do not return errors. They drop empty comma-separated fields.
### Example
```go
groupsEnv, groupsSet := os.LookupEnv(gonexapp.EnvRequiredGroups)
groups := gonexapp.ResolveRequiredGroups(groupsEnv, groupsSet, nil)
ttl := gonexapp.ParseCacheSeconds(os.Getenv(gonexapp.EnvRequiredGroupsCacheSeconds), gonexapp.DefaultCacheSeconds)
handler = gonexapp.AccessGate{Cred: cred, Groups: groups, CacheTTL: ttl}.Wrap(handler)
```
## Top Menu visibility
### Purpose
`TopMenuAdminRequired` turns the deploy environment into the `"0"` or `"1"` string AppAPI's top-menu OCS field `adminRequired` expects.
### When to use it
Use it when the ExApp registers its top-menu entry at enable time. The library does not register the menu. `"1"` means admins only. `"0"` means every user.
### Call sequence
1. Declare `TOP_MENU_ADMIN_REQUIRED` (`EnvTopMenuAdminRequired`) in `info.xml` under environment variables.
2. At enable time, call `TopMenuAdminRequired` with the env value and `DefaultTopMenuAdminRequired` (`true`).
3. Send the returned `"0"` or `"1"` in the top-menu registration request.
Only `"0"` and `"1"` are accepted. Any other value, including empty, uses the default. Changing the deploy env does not update an entry AppAPI already registered. Set the new value, recreate or restart the container so the env is present, then disable and enable the ExApp (or update it) so `PUT /enabled?enabled=1` runs again. Route `access_level` in `info.xml` is separate and changes only when AppAPI re-reads `info.xml`.
### Errors
`TopMenuAdminRequired` does not return an error. An invalid value falls back to the default.
### Example
```go
adminRequired := gonexapp.TopMenuAdminRequired(
os.Getenv(gonexapp.EnvTopMenuAdminRequired),
gonexapp.DefaultTopMenuAdminRequired,
)
```
## App navigation
### Purpose
App navigation is an optional Files-style shell. The ExApp supplies the tree and the page for each item. Mounting `Handler` replaces the ExApp's own page. Not mounting it leaves that page alone.
### When to use it
Use it when the ExApp wants Nextcloud's navigation column, theme background, and a selected item in the query string. Lifecycle routes, HaRP startup, and top-menu registration stay in the ExApp.
### Call sequence
1. Fill `AppNavigation`. `Items`, `Page`, and `DefaultID` are required. `Header` and `MissingMessage` are optional.
2. `Items` returns the tree for this request. An `Item` has an id, a label, optional children, an optional `Icon`, and an optional `Phrase` id. The label is the English source. When `Phrase` is set, the page script replaces it for the UI language.
3. Set `Icon` to a same-origin image URL, or to a field of `NextcloudIcons` (core SVGs Nextcloud already serves, such as `NextcloudIcons.Folder`).
4. `Page` returns the HTML body for the selected id and whether that id is known.
5. `SelectKey` defaults to `item`. Other query parameters, including a Visit folder, stay on the address.
6. Set `Cred` to the ExApp's Nextcloud credentials. The shell reads the UI language once from that. The zero value leaves the page in English. Do not pass a language.
7. Set `Phrases` to the ExApp's set. `MissingPhrase` names the Phrase for `MissingMessage`.
8. Mount `Handler` on the ExApp's page route.
A missing item renders `DefaultID`, shows `MissingMessage`, and publishes the corrected query on `data-address`. Every parent starts expanded. At 1024px and below, the tree stays hidden until the user opens it. Choosing an item, pressing Escape, or clicking outside closes it.
The zero value of `DisableTheme` loads the Nextcloud theme stylesheets, paints `--image-background`, and copies the surrounding page's `data-theme-*` markers. Set `DisableTheme` to skip the stylesheets. The shell includes the Dialog. The response sets `frame-ancestors 'self'` so AppAPI can show the iframe.
### Errors
`Handler` does not return an error to the caller. It writes HTML with status 200. A nil `Items` or `Page` yields an empty tree or an empty page.
### Example
```go
nav := gonexapp.AppNavigation{
DefaultID: "home",
Items: func(*http.Request) []gonexapp.Item {
return []gonexapp.Item{{
ID: "home", Label: "Home", Icon: gonexapp.NextcloudIcons.Home,
}}
},
Page: func(_ *http.Request, id string) (string, bool) {
if id != "home" {
return "", false
}
return "<p>Home</p>", true
},
}
http.Handle("/page", nav.Handler())
```
## UI language and Phrases
### Purpose
An ExApp page speaks the Requesting user's UI language. The Library resolves it once per page and writes its own chrome. The ExApp owns the Phrases of its pages and navigation items.
### Call sequence
1. `Credentials.UILanguage(r)` reads the Provisioning OCS user field `language` and forwards the page's `Accept-Language`. The field `locale` is ignored. `de` and `de_DE` use German. `en` and `en_GB` use English. Any other code, a missing user, or a failed read is English, and the page still renders. A later call on the same page request reuses that result.
2. Put `i18n/en.json` and `i18n/de.json` at the project root, or beside a module. Each file is one JSON object of stable dotted id → text. Embed the directory and load it with `PhrasesFromFS`. `Merge` combines sets; a repeated id uses the set added later. CheckDNS and StalwartAdmin use only the default set.
3. English is the complete set. A missing German text shows the English text. An unknown id shows the id. A hole is `{name}`. English and German name the same holes and may place them differently. A hole with no value stays as `{name}`. The value is plain text.
4. Leave the English sentence in the HTML. Name the Phrase with `data-phrase` on the text, `data-phrase-placeholder`, `data-phrase-title`, or `data-phrase-aria-label`. A hole value is JSON on `data-phrase-holes`. App navigation injects `Phrases.Script` and `FillScript`. A page the ExApp renders itself puts `Script(lang)` in the head and `FillScript()` at the end of the body.
5. A sentence the script creates calls `exappPhrase(id, holes)`. The map does not include Library chrome.
6. An error the page displays is `Phrases.Sentence(lang, id, holes)`, the finished sentence. Escape it when writing HTML. A log line the page does not show stays English.
### Errors
`UILanguage` does not return an error. A failed read is English. `PhrasesFromFS` and `ParsePhrases` return an error when a file is missing or is not a JSON object of strings.
## Dialog
### Purpose
The Dialog is a modal for a message, a confirm, or a prompt. The page calls it from JavaScript and waits for the user's choice.
### When to use it
App navigation already includes the dialog in the UI language. Insert `DialogHTML()` on a page the ExApp renders itself when that page stays in English, or `Credentials.DialogHTML(r)` so the same read supplies the language. OK stays OK. Cancel is Abbrechen in German. A renamed agreeing button is the exact text the caller passes. The choice stays in the page.
### Call sequence
1. Insert `DialogHTML()` into the page HTML once.
2. From the page script, call one of `exappDialog.message`, `exappDialog.confirm`, or `exappDialog.prompt`, and await the promise.
`message` takes `heading`, `text`, and `severity` (`info`, `warning`, or `error`). It shows no Cancel button. `confirm` takes `heading`, `text`, optional `agree`, and optional `destructive`. It resolves `true` or `false`. `prompt` takes `heading`, `text`, optional `value`, and optional `agree`. It resolves the trimmed string, or `null` when the user cancels. The agreeing button stays disabled until the field is non-empty. Calls are queued so only one dialog is open.
### Errors
`DialogHTML` does not return an error. It returns HTML that is safe to drop into a `template.HTML` context because the function's result type is already `template.HTML`. The page script is responsible for handling a dismissed dialog (`false`, `null`, or a resolved message).
### Example
```go
fmt.Fprint(w, gonexapp.DialogHTML())
```
```html
<script>
const ok = await exappDialog.confirm({heading: "Delete", text: "Delete this file?", agree: "Delete", destructive: true});
const name = await exappDialog.prompt({heading: "Name", text: "Folder name", value: "Zones"});
</script>
```
+12 -1
View File
@@ -1,3 +1,14 @@
module gitea.neitzel.de/konrad/go-nc-exapp module gitea.neitzel.de/konrad/go-nc-exapp
go 1.26.4 go 1.27.0
require (
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f // indirect
github.com/chromedp/chromedp v0.16.0 // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
github.com/gobwas/ws v1.4.0 // indirect
golang.org/x/sys v0.47.0 // indirect
)
+17
View File
@@ -0,0 +1,17 @@
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f h1:0Z1zcSLEmnj2c2CmJYBqewtS6pxhB39bNWUSEUAWjgk=
github.com/chromedp/cdproto v0.0.0-20260714215040-dc233986426f/go.mod h1:RwFsSODCtFExll+GhHM6R92SARHR3Z3oipaxLHj46C0=
github.com/chromedp/chromedp v0.16.0 h1:rOO4deOm4CbZgBCa8mD9g2rDyIoNs0BkgvNrlbp5ouk=
github.com/chromedp/chromedp v0.16.0/go.mod h1:rbuGKFT1vMcFcFqKfPIO1GpX/N+2s8onm2qMxZLbU5U=
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 h1:KZaTBSyshWX3MP5jukJcNSuXDQTO+rNpt0J564dX/eg=
github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+12 -3
View File
@@ -33,7 +33,9 @@ func (g Groups) ocsClient() OCSClient {
return c return c
} }
// UserGroups returns the Nextcloud group ids of userID, calling OCS as that user. // UserGroups returns the Nextcloud group ids of userID.
// The OCS call is authenticated as userID.
// It returns an error when the OCS call fails or the body cannot be decoded.
func (g Groups) UserGroups(userID string) ([]string, error) { func (g Groups) UserGroups(userID string) ([]string, error) {
ocs := g.ocsClient() ocs := g.ocsClient()
ocs.Cred = ocs.Cred.WithUser(userID) ocs.Cred = ocs.Cred.WithUser(userID)
@@ -45,7 +47,11 @@ func (g Groups) UserGroups(userID string) ([]string, error) {
return decodeUserGroups(raw) return decodeUserGroups(raw)
} }
// GroupMembers returns the user ids in groupID, calling OCS as the Requesting user. // GroupMembers returns the user ids in groupID.
// The OCS call uses Cred as-is. Nextcloud requires that user to be an admin
// or a subadmin of the group.
// It returns an error when the OCS call fails or the body cannot be decoded.
// There is no search or paging.
func (g Groups) GroupMembers(groupID string) ([]string, error) { func (g Groups) GroupMembers(groupID string) ([]string, error) {
ocs := g.ocsClient() ocs := g.ocsClient()
path := "cloud/groups/" + url.PathEscape(groupID) path := "cloud/groups/" + url.PathEscape(groupID)
@@ -70,7 +76,10 @@ func decodeGroupMembers(raw []byte) ([]string, error) {
return parsed.OCS.Data.Users, nil return parsed.OCS.Data.Users, nil
} }
// ListGroups returns instance group ids, calling OCS as the Requesting user. // ListGroups returns instance group ids.
// The OCS call uses Cred as-is and needs an admin or subadmin.
// It returns an error when the OCS call fails or the body cannot be decoded.
// There is no search or paging.
func (g Groups) ListGroups() ([]string, error) { func (g Groups) ListGroups() ([]string, error) {
ocs := g.ocsClient() ocs := g.ocsClient()
raw, err := ocs.Call(http.MethodGet, "cloud/groups", nil) raw, err := ocs.Call(http.MethodGet, "cloud/groups", nil)
+7
View File
@@ -0,0 +1,7 @@
{
"dialog.ok": "OK",
"dialog.cancel": "Abbrechen",
"nav.open": "Navigation öffnen",
"nav.close": "Navigation schließen",
"nav.fold": "{label} einklappen"
}
+7
View File
@@ -0,0 +1,7 @@
{
"dialog.ok": "OK",
"dialog.cancel": "Cancel",
"nav.open": "Open navigation",
"nav.close": "Close navigation",
"nav.fold": "Fold {label}"
}
+93
View File
@@ -0,0 +1,93 @@
package gonexapp
// NextcloudIcons are SVG paths served by Nextcloud core under /core/img/.
// The library does not ship the files. Set Item.Icon to one of these.
// Dark mode inverts them with Nextcloud’s --background-invert-if-dark filter.
var NextcloudIcons = nextcloudIcons{
Folder: "/core/img/filetypes/folder.svg",
FolderShared: "/core/img/filetypes/folder-shared.svg",
FolderPublic: "/core/img/filetypes/folder-public.svg",
FolderStarred: "/core/img/filetypes/folder-starred.svg",
FolderEncrypted: "/core/img/filetypes/folder-encrypted.svg",
File: "/core/img/filetypes/file.svg",
Text: "/core/img/filetypes/text.svg",
Image: "/core/img/filetypes/image.svg",
Audio: "/core/img/filetypes/audio.svg",
Video: "/core/img/filetypes/video.svg",
PDF: "/core/img/filetypes/application-pdf.svg",
Document: "/core/img/filetypes/x-office-document.svg",
Spreadsheet: "/core/img/filetypes/x-office-spreadsheet.svg",
Presentation: "/core/img/filetypes/x-office-presentation.svg",
Files: "/core/img/places/files.svg",
Home: "/core/img/places/home.svg",
Calendar: "/core/img/places/calendar.svg",
Contacts: "/core/img/places/contacts.svg",
Add: "/core/img/actions/add.svg",
Delete: "/core/img/actions/delete.svg",
Edit: "/core/img/actions/edit.svg",
Rename: "/core/img/actions/rename.svg",
Download: "/core/img/actions/download.svg",
Upload: "/core/img/actions/upload.svg",
Share: "/core/img/actions/share.svg",
Search: "/core/img/actions/search.svg",
Settings: "/core/img/actions/settings.svg",
Info: "/core/img/actions/info.svg",
History: "/core/img/actions/history.svg",
Password: "/core/img/actions/password.svg",
Confirm: "/core/img/actions/confirm.svg",
Close: "/core/img/actions/close.svg",
Star: "/core/img/actions/star.svg",
User: "/core/img/actions/user.svg",
Group: "/core/img/actions/group.svg",
Mail: "/core/img/actions/mail.svg",
Menu: "/core/img/actions/menu.svg",
External: "/core/img/actions/external.svg",
Filter: "/core/img/actions/filter.svg",
Recent: "/core/img/actions/recent.svg",
Tag: "/core/img/actions/tag.svg",
}
// nextcloudIcons is the named set of core SVGs. Fields are paths, not image bytes.
type nextcloudIcons struct {
Folder string
FolderShared string
FolderPublic string
FolderStarred string
FolderEncrypted string
File string
Text string
Image string
Audio string
Video string
PDF string
Document string
Spreadsheet string
Presentation string
Files string
Home string
Calendar string
Contacts string
Add string
Delete string
Edit string
Rename string
Download string
Upload string
Share string
Search string
Settings string
Info string
History string
Password string
Confirm string
Close string
Star string
User string
Group string
Mail string
Menu string
External string
Filter string
Recent string
Tag string
}
+163
View File
@@ -0,0 +1,163 @@
package gonexapp
import (
"context"
_ "embed"
"encoding/json"
"net/http"
"net/url"
"strings"
)
//go:embed i18n/en.json
var chromeENJSON []byte
//go:embed i18n/de.json
var chromeDEJSON []byte
// chromeSets is the Library's own chrome. It is not part of the map the page script sees.
var chromeSets = map[string]map[string]string{
"en": mustChrome(chromeENJSON),
"de": mustChrome(chromeDEJSON),
}
func mustChrome(raw []byte) map[string]string {
var m map[string]string
if err := json.Unmarshal(raw, &m); err != nil {
panic(err)
}
return m
}
type uiLanguageKey struct{}
// UILanguage is the language of the Phrases for this request, "en" or "de".
// It reads the Requesting user's language from the Provisioning OCS user
// record and forwards the request's Accept-Language on that read.
// The locale field is ignored. A more specific code uses the broader
// language when this Library provides that language. Any other code, a
// missing Requesting user, or a failed read is English, and the page still renders.
// A second call with the request returned from a page render reuses that result.
func (c Credentials) UILanguage(r *http.Request) string {
if r == nil {
return "en"
}
if lang, ok := r.Context().Value(uiLanguageKey{}).(string); ok {
return lang
}
return c.readUILanguage(r)
}
func (c Credentials) readUILanguage(r *http.Request) string {
if c.BaseURL == "" {
return "en"
}
userID, err := UserFromRequest(r)
if err != nil || userID == "" {
return "en"
}
ocs := OCSClient{Cred: c.WithUser(userID)}
if al := r.Header.Get("Accept-Language"); al != "" {
ocs.Header = http.Header{"Accept-Language": {al}}
}
raw, err := ocs.Call(http.MethodGet, "cloud/users/"+url.PathEscape(userID), nil)
if err != nil {
return "en"
}
return matchLanguage(userLanguage(raw), chromeHas)
}
func chromeHas(code string) bool {
_, ok := chromeSets[code]
return ok
}
// matchLanguage picks a Phrase set for the code Nextcloud returned.
// The code itself wins when that set exists. Otherwise the part before "_"
// wins when that set exists. Otherwise English.
func matchLanguage(code string, has func(string) bool) string {
code = strings.TrimSpace(code)
if code != "" && has(code) {
return code
}
if i := strings.IndexByte(code, '_'); i > 0 {
if base := code[:i]; has(base) {
return base
}
}
return "en"
}
func userLanguage(raw []byte) string {
var parsed struct {
OCS struct {
Data struct {
Language string `json:"language"`
} `json:"data"`
} `json:"ocs"`
}
if err := json.Unmarshal(raw, &parsed); err != nil {
return ""
}
return parsed.OCS.Data.Language
}
func chromePhrase(lang, id string, holes map[string]string) string {
if _, ok := chromeSets[lang]; !ok {
lang = "en"
}
text := chromeSets[lang][id]
if text == "" && lang != "en" {
text = chromeSets["en"][id]
}
if text == "" {
return id
}
return fillHoles(text, holes)
}
// fillHoles replaces {name} with the plain-text value.
// A hole with no value stays visible as {name}.
// A value is not scanned for further holes.
func fillHoles(text string, holes map[string]string) string {
if len(holes) == 0 || !strings.Contains(text, "{") {
return text
}
var b strings.Builder
b.Grow(len(text))
for i := 0; i < len(text); {
if text[i] != '{' {
b.WriteByte(text[i])
i++
continue
}
end := strings.IndexByte(text[i+1:], '}')
if end < 0 {
b.WriteByte(text[i])
i++
continue
}
name := text[i+1 : i+1+end]
value, ok := holes[name]
if !ok {
b.WriteByte(text[i])
i++
continue
}
b.WriteString(value)
i += end + 2
}
return b.String()
}
// rememberUILanguage returns r carrying lang so a later UILanguage call
// on this page does not read Nextcloud again.
func rememberUILanguage(r *http.Request, lang string) *http.Request {
if r == nil {
return nil
}
if _, ok := r.Context().Value(uiLanguageKey{}).(string); ok {
return r
}
return r.WithContext(context.WithValue(r.Context(), uiLanguageKey{}, lang))
}
+182
View File
@@ -0,0 +1,182 @@
package gonexapp_test
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
"gitea.neitzel.de/konrad/go-nc-exapp"
)
const browserLanguage = "de-DE,de;q=0.9"
func TestUILanguageChrome(t *testing.T) {
german := chromeSeen{
lang: "de", open: "Navigation öffnen", close: "Navigation schließen",
fold: "Domains einklappen", cancel: "Abbrechen", ok: "OK",
}
english := chromeSeen{
lang: "en", open: "Open navigation", close: "Close navigation",
fold: "Fold Domains", cancel: "Cancel", ok: "OK",
}
tests := []struct {
name string
user bool
status int
ncLang string
want chromeSeen
}{
{name: "german", user: true, status: http.StatusOK, ncLang: "de", want: german},
{name: "english", user: true, status: http.StatusOK, ncLang: "en", want: english},
{name: "formal german", user: true, status: http.StatusOK, ncLang: "de_DE", want: german},
{name: "british english", user: true, status: http.StatusOK, ncLang: "en_GB", want: english},
{name: "french", user: true, status: http.StatusOK, ncLang: "fr", want: english},
{name: "failed read", user: true, status: http.StatusInternalServerError, ncLang: "de", want: english},
{name: "missing user", user: false, status: http.StatusOK, ncLang: "de", want: english},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
nc := fakeLanguage(tt.status, tt.ncLang)
t.Cleanup(nc.Close)
page := languagePage(nc.URL)
t.Cleanup(page.Close)
headers := network.Headers{"Accept-Language": browserLanguage}
if tt.user {
headers["AUTHORIZATION-APP-API"] = base64.StdEncoding.EncodeToString([]byte("alice:secret"))
}
got := readChrome(t, page.URL+"/?item=domains", headers)
if !strings.Contains(got.page, "domains-page") {
t.Fatalf("page did not render: %+v", got)
}
if got.lang != tt.want.lang || got.open != tt.want.open || got.close != tt.want.close ||
got.fold != tt.want.fold || got.cancel != tt.want.cancel || got.ok != tt.want.ok || got.agree != "Remove" {
t.Fatalf("got %+v, want %+v with agree %q", got, tt.want, "Remove")
}
})
}
}
type chromeSeen struct {
lang string
open string
close string
fold string
cancel string
ok string
agree string
page string
}
func fakeLanguage(status int, language string) *httptest.Server {
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet || !strings.Contains(r.URL.Path, "/cloud/users/") {
http.NotFound(w, r)
return
}
if status != http.StatusOK {
http.Error(w, "language unavailable", status)
return
}
// A read that drops the browser language must not look like a hit.
lang := language
if r.Header.Get("Accept-Language") != browserLanguage {
lang = "en"
}
// locale differs from language so a read of the wrong field fails the page.
locale := "fr"
if language == "fr" || language == "en_GB" {
locale = "de"
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"ocs":{"meta":{"status":"ok","statuscode":200,"message":"OK"},"data":{"language":%q,"locale":%q}}}`, lang, locale)
}))
}
func languagePage(ncBase string) *httptest.Server {
nav := sampleNavigation()
nav.Cred = gonexapp.Credentials{
BaseURL: ncBase,
AppID: "exapp",
AppVersion: "1.0.0",
AAVersion: "1.0.0",
AppSecret: "secret",
}
nav.Page = func(_ *http.Request, id string) (string, bool) {
switch id {
case "domains":
return `<p>domains-page</p><button type="button" id="ask">Ask</button>
<script>
document.getElementById("ask").addEventListener("click", function () {
exappDialog.confirm({ text: "Sure?", agree: "Remove" });
});
</script>`, true
case "keys":
return "<p>keys-page</p>", true
case "example.com":
return "<p>zone-page</p>", true
default:
return "", false
}
}
return httptest.NewServer(nav.Handler())
}
func readChrome(t *testing.T, pageURL string, headers network.Headers) chromeSeen {
t.Helper()
ctx, cancel := chromedp.NewContext(allocCtx)
t.Cleanup(cancel)
ctx, cancel = context.WithTimeout(ctx, 25*time.Second)
t.Cleanup(cancel)
var raw, closeLabel, agree string
err := chromedp.Run(ctx,
network.Enable(),
network.SetExtraHTTPHeaders(headers),
chromedp.Navigate(pageURL),
chromedp.Evaluate(chromeProbeJS, &raw),
chromedp.Evaluate(`document.getElementById("nav-toggle").click()`, nil),
chromedp.Evaluate(`document.getElementById("nav-toggle").getAttribute("aria-label")`, &closeLabel),
chromedp.Evaluate(`document.getElementById("ask").click()`, nil),
chromedp.Evaluate(`document.getElementById("exapp-dialog-agree").textContent`, &agree),
)
if err != nil {
t.Fatal(err)
}
var probe struct {
Lang string `json:"lang"`
Open string `json:"open"`
Fold string `json:"fold"`
Cancel string `json:"cancel"`
OK string `json:"ok"`
Page string `json:"page"`
}
if err := json.Unmarshal([]byte(raw), &probe); err != nil {
t.Fatal(err)
}
return chromeSeen{
lang: probe.Lang, open: probe.Open, close: closeLabel, fold: probe.Fold,
cancel: probe.Cancel, ok: probe.OK, agree: agree, page: probe.Page,
}
}
const chromeProbeJS = `(() => {
const fold = document.querySelector("button.fold");
return JSON.stringify({
lang: document.documentElement.lang,
open: document.getElementById("nav-toggle").getAttribute("aria-label"),
fold: fold ? fold.getAttribute("aria-label") : "",
cancel: document.getElementById("exapp-dialog-cancel").textContent,
ok: document.getElementById("exapp-dialog-agree").textContent,
page: document.querySelector("main").textContent
});
})()`
+463
View File
@@ -0,0 +1,463 @@
package gonexapp
import (
"html/template"
"net/http"
)
// shellCSP lets the ExApp iframe render this document. AppAPI blanks a frame
// whose response omits frame-ancestors.
const shellCSP = "default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data:; font-src 'self' data:"
// Item is one App navigation entry. The ExApp chooses the ids and labels.
// Children may nest. The shell does not interpret the ids.
// Icon is an optional same-origin image URL. NextcloudIcons names the core SVGs.
// Phrase names the ExApp Phrase for Label. The English label stays in the
// page until the script replaces it. Empty leaves the label as written.
type Item struct {
ID string
Label string
Icon string
Phrase string
Children []Item
}
// AppNavigation is the Files-style shell an ExApp mounts.
// Items, Page, and DefaultID are required. Header and MissingMessage are
// optional. SelectKey defaults to "item". Every other query parameter,
// including the Visit folder, is copied onto the corrected address.
// An ExApp that never calls Handler keeps its own page.
type AppNavigation struct {
Items func(*http.Request) []Item
Page func(*http.Request, string) (string, bool)
Header func(*http.Request) string
DefaultID string
MissingMessage string
SelectKey string
// Title is the document title. Empty means "App navigation".
Title string
// DisableTheme skips the Nextcloud theme stylesheets. The zero value
// loads the active theme.
DisableTheme bool
// Cred reads the UI language for this page from Nextcloud.
// The zero value leaves the page in English.
// The caller does not pass a language.
Cred Credentials
// Phrases is the ExApp's set. The page script receives it.
// Library chrome is not included. The zero value leaves the page in English.
Phrases Phrases
// MissingPhrase names the ExApp Phrase for MissingMessage.
MissingPhrase string
}
// Handler serves the shell. The selected item is the SelectKey query parameter.
// A missing item renders DefaultID, includes MissingMessage, and publishes the
// corrected query on data-address so the page can replace the address.
// Every parent starts expanded. Folding is client state for this document only.
func (n AppNavigation) Handler() http.Handler {
return http.HandlerFunc(n.serve)
}
func (n AppNavigation) selectKey() string {
if n.SelectKey != "" {
return n.SelectKey
}
return "item"
}
func (n AppNavigation) serve(w http.ResponseWriter, r *http.Request) {
lang := n.Cred.UILanguage(r)
r = rememberUILanguage(r, lang)
var items []Item
if n.Items != nil {
items = n.Items(r)
}
asked := r.URL.Query().Get(n.selectKey())
selected := n.DefaultID
missing := false
if asked != "" {
if _, ok := findItem(items, asked); ok {
selected = asked
} else {
missing = true
}
}
page := ""
if n.Page != nil {
body, ok := n.Page(r, selected)
if !ok && selected != n.DefaultID {
missing = true
selected = n.DefaultID
body, ok = n.Page(r, selected)
}
if ok {
page = body
}
}
header := ""
if n.Header != nil {
header = n.Header(r)
}
msg := ""
if missing {
msg = n.MissingMessage
}
title := n.Title
if title == "" {
title = "App navigation"
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Content-Security-Policy", shellCSP)
w.WriteHeader(http.StatusOK)
// Status is already committed; a template error cannot change the response.
_ = shellTmpl.Execute(w, shellView{
Selected: selected,
Address: n.address(r, selected),
Header: template.HTML(header),
Items: viewItems(r, items, selected, n.address, lang),
Page: template.HTML(page),
Missing: msg,
Title: title,
Theme: !n.DisableTheme,
Dialog: n.Cred.DialogHTML(r),
Lang: lang,
OpenLabel: chromePhrase(lang, "nav.open", nil),
CloseLabel: chromePhrase(lang, "nav.close", nil),
PhraseScript: n.Phrases.Script(lang),
PhraseFill: FillScript(),
MissingPhrase: n.MissingPhrase,
})
}
func (n AppNavigation) address(r *http.Request, id string) string {
q := r.URL.Query()
q.Set(n.selectKey(), id)
return "?" + q.Encode()
}
func findItem(items []Item, id string) (Item, bool) {
for _, it := range items {
if it.ID == id {
return it, true
}
if child, ok := findItem(it.Children, id); ok {
return child, true
}
}
return Item{}, false
}
type shellView struct {
Selected string
Address string
Header template.HTML
Items []itemView
Page template.HTML
Missing string
Title string
Theme bool
Dialog template.HTML
Lang string
OpenLabel string
CloseLabel string
PhraseScript template.HTML
PhraseFill template.HTML
MissingPhrase string
}
type itemView struct {
ID string
Label string
Icon string
Href string
Current bool
HasChildren bool
Children []itemView
Fold string
FoldPattern string
Phrase string
}
func viewItems(r *http.Request, items []Item, selected string, href func(*http.Request, string) string, lang string) []itemView {
out := make([]itemView, 0, len(items))
for _, it := range items {
children := viewItems(r, it.Children, selected, href, lang)
fold := ""
pattern := ""
if len(children) > 0 {
fold = chromePhrase(lang, "nav.fold", map[string]string{"label": it.Label})
pattern = chromePhrase(lang, "nav.fold", nil)
}
out = append(out, itemView{
ID: it.ID,
Label: it.Label,
Icon: it.Icon,
Href: href(r, it.ID),
Current: it.ID == selected,
HasChildren: len(children) > 0,
Children: children,
Fold: fold,
FoldPattern: pattern,
Phrase: it.Phrase,
})
}
return out
}
var shellTmpl = template.Must(template.New("shell").Parse(`<!DOCTYPE html>
<html lang="{{.Lang}}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{.Title}}</title>
{{.PhraseScript}}
{{if .Theme}}
<link rel="stylesheet" href="/apps/theming/css/default.css">
<link rel="stylesheet" href="/index.php/apps/theming/theme/default.css">
<link rel="stylesheet" href="/index.php/apps/theming/theme/dark.css">
<script>
(function () {
var root = document.documentElement;
try {
var parent = window.parent && window.parent !== window ? window.parent.document.documentElement : null;
if (parent) {
for (var i = 0; i < parent.attributes.length; i++) {
var attr = parent.attributes[i];
if (attr.name.indexOf("data-theme") === 0) {
root.setAttribute(attr.name, attr.value);
}
}
}
} catch (e) {}
if (!root.hasAttribute("data-theme-default") && !root.hasAttribute("data-theme-dark") && !root.hasAttribute("data-theme-light")) {
var dark = window.matchMedia("(prefers-color-scheme: dark)").matches;
root.setAttribute(dark ? "data-theme-dark" : "data-theme-default", "");
}
})();
</script>
{{end}}
<style>
:root {
--color-main-background: #ffffff;
--color-main-text: #222222;
--color-background-hover: #f5f5f5;
--color-background-dark: #ededed;
--color-primary-element: #00679e;
--color-primary-element-light: #e5f0f8;
--color-border: #ededed;
--default-clickable-area: 34px;
--border-radius-element: 8px;
}
html, body {
min-height: 100%;
color: var(--color-main-text);
background-color: var(--color-background-plain, var(--color-main-background));
background-image: var(--image-background);
background-size: cover;
background-position: center;
background-attachment: fixed;
}
body { margin: 0; font: 15px/1.4 var(--font-face, system-ui, sans-serif); }
#app-nav { display: flex; flex-direction: column; min-height: 100vh; background: transparent; }
#nav-header {
display: flex;
align-items: center;
gap: 4px;
padding: 8px 12px;
border-bottom: 1px solid var(--color-border);
}
#nav-header-text { flex: 1; min-width: 0; }
#nav-toggle {
display: none;
align-items: center;
justify-content: center;
width: 44px;
height: 44px;
margin: 0;
padding: 0;
border: 0;
flex: none;
background: transparent;
color: inherit;
cursor: pointer;
border-radius: var(--border-radius-element);
}
#nav-toggle:hover { background: var(--color-background-hover); }
#nav-toggle svg { width: 20px; height: 20px; }
#nav-backdrop { display: none; }
#app-nav-body { display: flex; flex: 1; min-height: 0; }
nav.app-navigation {
width: var(--navigation-width, 300px);
flex: none;
background-color: var(--color-main-background-translucent, var(--color-main-background));
backdrop-filter: var(--filter-background-blur, none);
-webkit-backdrop-filter: var(--filter-background-blur, none);
border-inline-end: 1px solid var(--color-border);
padding: 8px;
overflow: auto;
}
main { flex: 1; padding: 16px; min-width: 0; background-color: var(--color-main-background); }
.app-navigation-list, .app-navigation-entry__children { list-style: none; margin: 0; padding: 0; }
.app-navigation-entry__children { padding-inline-start: 10px; }
.app-navigation-entry-wrapper { display: flex; flex-wrap: wrap; width: 100%; }
.app-navigation-entry {
display: flex;
align-items: stretch;
width: 100%;
min-height: var(--default-clickable-area);
border-radius: var(--border-radius-element);
position: relative;
}
.app-navigation-entry:hover { background: var(--color-background-hover); }
.app-navigation-entry.active { background: var(--color-primary-element-light); }
.app-navigation-entry.active::before {
content: "";
position: absolute;
inset-block: 8px;
inset-inline-start: 0;
width: 3px;
background: var(--color-primary-element);
border-radius: 999px;
}
.app-navigation-entry-link {
display: flex;
flex: 1 1 auto;
align-items: center;
min-width: 0;
min-height: var(--default-clickable-area);
padding: 0 8px 0 12px;
color: inherit;
text-decoration: none;
font-weight: 500;
}
.app-navigation-entry-icon {
width: 16px;
height: 16px;
margin-inline-end: 8px;
flex: none;
filter: var(--background-invert-if-dark, none);
}
.app-navigation-entry__name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.app-navigation-entry.active .app-navigation-entry__name { font-weight: 700; }
.app-navigation-entry__utils { display: flex; align-items: center; }
button.fold {
width: var(--default-clickable-area);
height: var(--default-clickable-area);
margin: 0;
padding: 0;
border: 0;
background: transparent;
color: inherit;
cursor: pointer;
border-radius: var(--border-radius-element);
display: flex;
align-items: center;
justify-content: center;
}
button.fold:hover { background: var(--color-background-dark); }
button.fold svg { width: 16px; height: 16px; transition: transform .15s ease; }
li[data-expanded="false"] > .app-navigation-entry__children { display: none; }
li[data-expanded="false"] button.fold svg { transform: rotate(-90deg); }
#nav-missing { margin: 0 0 1rem; }
@media (max-width: 1024px) {
#nav-header {
position: sticky;
top: 0;
z-index: 2100;
background-color: var(--color-main-background);
}
#nav-toggle { display: flex; }
nav.app-navigation {
display: none;
position: fixed;
z-index: 2000;
top: var(--nav-header-offset, 0px);
bottom: 0;
inset-inline-start: 0;
width: min(var(--navigation-width, 300px), 85vw);
}
body.nav-open nav.app-navigation { display: block; }
body.nav-open #nav-backdrop {
display: block;
position: fixed;
z-index: 1990;
top: var(--nav-header-offset, 0px);
right: 0;
bottom: 0;
left: 0;
background: rgba(0, 0, 0, 0.45);
}
}
</style>
</head>
<body data-selected="{{.Selected}}" data-address="{{.Address}}">
{{.Dialog}}
<div id="app-nav">
<div id="nav-header">
<button type="button" id="nav-toggle" aria-controls="app-navigation" aria-expanded="false" aria-label="{{.OpenLabel}}"><svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M3 6h18v2H3V6m0 5h18v2H3v-2m0 5h18v2H3v-2z"/></svg></button>
<div id="nav-header-text">{{.Header}}</div>
</div>
<div id="nav-backdrop"></div>
<div id="app-nav-body">
<nav id="app-navigation" class="app-navigation" aria-label="App navigation">
<ul class="app-navigation-list">{{template "items" .Items}}</ul>
</nav>
<main>
{{if .Missing}}<p id="nav-missing"{{if .MissingPhrase}} data-phrase="{{.MissingPhrase}}"{{end}}>{{.Missing}}</p>{{end}}
{{.Page}}
</main>
</div>
</div>
<script>
(function () {
var addr = document.body.getAttribute("data-address");
if (addr && addr !== location.search) {
history.replaceState(null, "", addr);
}
document.querySelectorAll("button.fold").forEach(function (btn) {
btn.addEventListener("click", function () {
var li = btn.closest("li");
var open = li.getAttribute("data-expanded") === "true";
li.setAttribute("data-expanded", open ? "false" : "true");
li.classList.toggle("app-navigation-entry--opened", !open);
btn.setAttribute("aria-expanded", open ? "false" : "true");
});
});
var toggle = document.getElementById("nav-toggle");
var backdrop = document.getElementById("nav-backdrop");
function placeNav() {
var header = document.getElementById("nav-header");
if (!header) return;
document.documentElement.style.setProperty("--nav-header-offset", header.offsetHeight + "px");
}
function setNavOpen(open) {
placeNav();
document.body.classList.toggle("nav-open", open);
if (!toggle) return;
toggle.setAttribute("aria-expanded", open ? "true" : "false");
toggle.setAttribute("aria-label", open ? {{.CloseLabel}} : {{.OpenLabel}});
}
placeNav();
window.addEventListener("resize", placeNav);
var narrow = window.matchMedia("(max-width: 1024px)");
if (narrow.addEventListener) narrow.addEventListener("change", placeNav);
if (toggle) {
toggle.addEventListener("click", function () {
setNavOpen(!document.body.classList.contains("nav-open"));
});
}
if (backdrop) backdrop.addEventListener("click", function () { setNavOpen(false); });
document.addEventListener("keydown", function (e) {
if (e.key !== "Escape") return;
var dialog = document.getElementById("exapp-dialog");
if (dialog && dialog.open) return;
setNavOpen(false);
});
})();
</script>
{{.PhraseFill}}
</body>
</html>
{{define "items"}}{{range .}}<li class="app-navigation-entry-wrapper{{if .HasChildren}} app-navigation-entry--collapsible app-navigation-entry--opened{{end}}" data-id="{{.ID}}"{{if .HasChildren}} data-expanded="true"{{end}}><div class="app-navigation-entry{{if .Current}} active{{end}}"><a class="app-navigation-entry-link" href="{{.Href}}"{{if .Current}} aria-current="page"{{end}}>{{if .Icon}}<img class="app-navigation-entry-icon" src="{{.Icon}}" alt="">{{end}}<span class="app-navigation-entry__name"{{if .Phrase}} data-phrase="{{.Phrase}}"{{end}}>{{.Label}}</span></a>{{if .HasChildren}}<div class="app-navigation-entry__utils"><button type="button" class="fold" aria-expanded="true" aria-label="{{.Fold}}" data-fold="{{.FoldPattern}}"><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4.5 6.5 8 10l3.5-3.5" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg></button></div>{{end}}</div>{{if .HasChildren}}<ul class="app-navigation-entry__children">{{template "items" .Children}}</ul>{{end}}</li>{{end}}{{end}}
`))
+270
View File
@@ -0,0 +1,270 @@
package gonexapp_test
import (
"html"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"github.com/chromedp/chromedp"
"github.com/chromedp/chromedp/kb"
"gitea.neitzel.de/konrad/go-nc-exapp"
)
func sampleNavigation() gonexapp.AppNavigation {
items := []gonexapp.Item{
{
ID: "domains", Label: "Domains",
Children: []gonexapp.Item{{ID: "example.com", Label: "example.com"}},
},
{ID: "keys", Label: "Keys"},
}
return gonexapp.AppNavigation{
Items: func(*http.Request) []gonexapp.Item { return items },
Page: func(_ *http.Request, id string) (string, bool) {
switch id {
case "domains":
return "<p>domains-page</p>", true
case "keys":
return "<p>keys-page</p>", true
case "example.com":
return "<p>zone-page</p>", true
default:
return "", false
}
},
Header: func(*http.Request) string { return `<p id="visit">folder-line</p>` },
DefaultID: "domains",
MissingMessage: "that item is not in this Visit",
}
}
func navBody(t *testing.T, rawURL string) string {
t.Helper()
rec := httptest.NewRecorder()
sampleNavigation().Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, rawURL, nil))
if rec.Code != http.StatusOK {
t.Fatalf("GET %s: got %d", rawURL, rec.Code)
}
return rec.Body.String()
}
func navAddress(t *testing.T, body string) url.Values {
t.Helper()
const key = `data-address="`
_, after, ok := strings.Cut(body, key)
if !ok {
t.Fatalf("no data-address in %s", body)
}
rest := after
end := strings.Index(rest, `"`)
if end < 0 {
t.Fatalf("unclosed data-address")
}
raw, err := url.QueryUnescape(html.UnescapeString(rest[:end]))
if err != nil {
t.Fatal(err)
}
q, err := url.ParseQuery(strings.TrimPrefix(raw, "?"))
if err != nil {
t.Fatal(err)
}
return q
}
func TestAppNavigationShowsSelectedPage(t *testing.T) {
body := navBody(t, "/?item=keys")
if !strings.Contains(body, "<p>keys-page</p>") {
t.Fatalf("got %s", body)
}
if !strings.Contains(body, `data-selected="keys"`) {
t.Fatalf("got %s", body)
}
if navAddress(t, body).Get("item") != "keys" {
t.Fatalf("address: %s", navAddress(t, body).Encode())
}
}
func TestAppNavigationDefaultsWhenItemMissingFromAddress(t *testing.T) {
body := navBody(t, "/")
if !strings.Contains(body, "<p>domains-page</p>") {
t.Fatalf("got %s", body)
}
if navAddress(t, body).Get("item") != "domains" {
t.Fatalf("address item = %q", navAddress(t, body).Get("item"))
}
if strings.Contains(body, "that item is not in this Visit") {
t.Fatalf("default open should not show the missing-item message: %s", body)
}
}
func TestAppNavigationMissingItemSelectsDefault(t *testing.T) {
body := navBody(t, "/?folder=share&item=gone")
if !strings.Contains(body, "<p>domains-page</p>") {
t.Fatalf("got %s", body)
}
if !strings.Contains(body, "that item is not in this Visit") {
t.Fatalf("got %s", body)
}
q := navAddress(t, body)
if q.Get("item") != "domains" || q.Get("folder") != "share" {
t.Fatalf("address = %s", q.Encode())
}
}
func TestAppNavigationPageRefusalSelectsDefault(t *testing.T) {
nav := sampleNavigation()
inner := nav.Page
nav.Page = func(r *http.Request, id string) (string, bool) {
if id == "keys" {
return "", false
}
return inner(r, id)
}
rec := httptest.NewRecorder()
nav.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/?folder=share&item=keys", nil))
if rec.Code != http.StatusOK {
t.Fatalf("got %d", rec.Code)
}
body := rec.Body.String()
if !strings.Contains(body, "<p>domains-page</p>") || !strings.Contains(body, "that item is not in this Visit") {
t.Fatalf("got %s", body)
}
q := navAddress(t, body)
if q.Get("item") != "domains" || q.Get("folder") != "share" {
t.Fatalf("address = %s", q.Encode())
}
}
func TestAppNavigationChildExpandsParents(t *testing.T) {
body := navBody(t, "/?item=example.com")
if !strings.Contains(body, "<p>zone-page</p>") {
t.Fatalf("got %s", body)
}
if !strings.Contains(body, `data-id="domains" data-expanded="true"`) {
t.Fatalf("got %s", body)
}
}
func TestAppNavigationLoadsNextcloudTheme(t *testing.T) {
body := navBody(t, "/")
for _, need := range []string{
"/apps/theming/css/default.css",
"/index.php/apps/theming/theme/default.css",
"/index.php/apps/theming/theme/dark.css",
} {
if !strings.Contains(body, need) {
t.Fatalf("missing %s in %s", need, body)
}
}
}
func TestAppNavigationThemeCanBeDisabled(t *testing.T) {
nav := sampleNavigation()
nav.DisableTheme = true
rec := httptest.NewRecorder()
nav.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
if strings.Contains(rec.Body.String(), "/apps/theming/css/default.css") {
t.Fatalf("theme stylesheet still present: %s", rec.Body.String())
}
}
func TestAppNavigationFoldControlFollowsLabel(t *testing.T) {
body := navBody(t, "/?item=domains")
name := strings.Index(body, ">Domains<")
fold := strings.Index(body, `aria-label="Fold Domains"`)
if name < 0 || fold < 0 || fold < name {
t.Fatalf("name %d fold %d", name, fold)
}
}
func TestAppNavigationRendersIconBeforeLabel(t *testing.T) {
nav := sampleNavigation()
nav.Items = func(*http.Request) []gonexapp.Item {
return []gonexapp.Item{{ID: "domains", Label: "Domains", Icon: gonexapp.NextcloudIcons.Folder}}
}
rec := httptest.NewRecorder()
nav.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/?item=domains", nil))
body := rec.Body.String()
icon := strings.Index(body, `src="/core/img/filetypes/folder.svg"`)
name := strings.Index(body, ">Domains<")
if icon < 0 || name < 0 || icon > name {
t.Fatalf("icon %d name %d", icon, name)
}
}
func TestAppNavigationHeaderPrecedesTree(t *testing.T) {
body := navBody(t, "/?item=domains")
header := strings.Index(body, "folder-line")
tree := strings.Index(body, ">Domains<")
if header < 0 || tree < 0 || header > tree {
t.Fatalf("header %d tree %d in %s", header, tree, body)
}
}
func TestAppNavigationOffersNarrowScreenToggle(t *testing.T) {
body := navBody(t, "/")
for _, need := range []string{
`<meta name="viewport" content="width=device-width, initial-scale=1">`,
`id="nav-toggle"`,
`aria-controls="app-navigation"`,
`aria-expanded="false"`,
`aria-label="Open navigation"`,
`id="nav-backdrop"`,
`id="app-navigation"`,
`max-width: 1024px`,
} {
if !strings.Contains(body, need) {
t.Errorf("missing %s", need)
}
}
}
// navLayoutJS reports how App navigation is laid out: "wide", "closed", or "open".
const navLayoutJS = `(() => {
const nav = document.querySelector("nav.app-navigation");
const btn = document.getElementById("nav-toggle");
const narrow = window.matchMedia("(max-width: 1024px)").matches;
const box = nav.getBoundingClientRect();
const navShown = getComputedStyle(nav).display !== "none" && box.width > 0 && box.left < window.innerWidth && box.right > 0;
const btnShown = getComputedStyle(btn).display !== "none";
const expanded = btn.getAttribute("aria-expanded") === "true";
if (!narrow && navShown && !btnShown && !expanded) return "wide";
if (narrow && !navShown && btnShown && !expanded) return "closed";
if (narrow && navShown && btnShown && expanded) return "open";
return "narrow=" + narrow + " nav=" + navShown + " btn=" + btnShown + " expanded=" + expanded + " width=" + window.innerWidth;
})()`
func TestAppNavigationWideScreenKeepsTheTreeVisible(t *testing.T) {
drive(t, "/nav",
chromedp.EmulateViewport(1280, 800),
waitJS(navLayoutJS, "wide", false),
)
}
func TestAppNavigationNarrowScreenOpensTheTreeOnDemand(t *testing.T) {
drive(t, "/nav",
chromedp.EmulateViewport(390, 800),
waitJS(navLayoutJS, "closed", false),
chromedp.Click("#nav-toggle", chromedp.ByQuery),
waitJS(navLayoutJS, "open", false),
chromedp.Click("#nav-toggle", chromedp.ByQuery),
waitJS(navLayoutJS, "closed", false),
chromedp.Click("#nav-toggle", chromedp.ByQuery),
waitJS(navLayoutJS, "open", false),
chromedp.MouseClickXY(370, 400),
waitJS(navLayoutJS, "closed", false),
chromedp.Click("#nav-toggle", chromedp.ByQuery),
waitJS(navLayoutJS, "open", false),
chromedp.KeyEvent(kb.Escape),
waitJS(navLayoutJS, "closed", false),
chromedp.Click("#nav-toggle", chromedp.ByQuery),
waitJS(navLayoutJS, "open", false),
chromedp.Click(`a.app-navigation-entry-link[href*="item=keys"]`, chromedp.ByQuery),
waitJS(`document.querySelector("main").textContent`, "keys-page", true),
waitJS(navLayoutJS, "closed", false),
)
}
+7 -2
View File
@@ -41,7 +41,10 @@ func (n AppAPINotifications) ocsClient() OCSClient {
return c return c
} }
// Send creates a Notification for the Requesting user on the Credentials. // Send creates a Notification for Cred.UserID.
// It returns an error when UserID or Subject is empty, or when the OCS call fails.
// AppAPI notification OCS accepts Subject, Message, Link, and rich-object
// parameters. It does not accept actions or a custom icon.
func (n AppAPINotifications) Send(notif Notification) error { func (n AppAPINotifications) Send(notif Notification) error {
if n.Cred.UserID == "" { if n.Cred.UserID == "" {
return fmt.Errorf("notification recipient user id is required") return fmt.Errorf("notification recipient user id is required")
@@ -49,7 +52,9 @@ func (n AppAPINotifications) Send(notif Notification) error {
return n.send(n.Cred.UserID, notif) return n.send(n.Cred.UserID, notif)
} }
// SendTo creates a Notification for userID, impersonating that Recipient. // SendTo creates a Notification for userID.
// The OCS call is authenticated as that user via WithUser.
// It returns an error when userID or Subject is empty, or when the OCS call fails.
func (n AppAPINotifications) SendTo(userID string, notif Notification) error { func (n AppAPINotifications) SendTo(userID string, notif Notification) error {
return n.send(userID, notif) return n.send(userID, notif)
} }
+8
View File
@@ -10,9 +10,12 @@ import (
) )
// OCSClient performs AppAPI-authenticated OCS requests with format=json. // OCSClient performs AppAPI-authenticated OCS requests with format=json.
// Header is copied onto the outbound request after the AppAPI auth headers.
// The UI language read uses it to forward Accept-Language.
type OCSClient struct { type OCSClient struct {
Cred Credentials Cred Credentials
Client *http.Client Client *http.Client
Header http.Header
} }
func (c OCSClient) httpClient() *http.Client { func (c OCSClient) httpClient() *http.Client {
@@ -48,6 +51,11 @@ func (c OCSClient) Call(method, path string, body []byte) ([]byte, error) {
req.Header.Set(k, v) req.Header.Set(k, v)
} }
} }
for k, vs := range c.Header {
for _, v := range vs {
req.Header.Add(k, v)
}
}
res, err := c.httpClient().Do(req) res, err := c.httpClient().Do(req)
if err != nil { if err != nil {
return nil, err return nil, err
+245
View File
@@ -0,0 +1,245 @@
package gonexapp_test
import (
"context"
"encoding/base64"
"encoding/json"
"html"
"net/http"
"net/http/httptest"
"testing"
"testing/fstest"
"time"
"github.com/chromedp/cdproto/network"
"github.com/chromedp/chromedp"
"gitea.neitzel.de/konrad/go-nc-exapp"
)
func TestExAppPhrasesOnThePage(t *testing.T) {
phrases := mergedPhrases(t)
tests := []struct {
name string
ncLang string
want phraseSeen
}{
{
name: "german",
ncLang: "de",
want: phraseSeen{
lang: "de", heading: "Spätere Überschrift", placeholder: "Platzhalter",
title: "Titel", aria: "Beschriftung", hole: "example.com fehlt",
openHole: "{zone} fehlt", fallback: "English only", unknown: "not.a.phrase",
htmlHole: "<b>x</b> fehlt", scripted: "Skript", chromeID: "dialog.cancel",
err: "<b>x</b> fehlt", nav: "Domänen", fold: "Domänen einklappen",
missing: "Dieser Eintrag fehlt",
},
},
{
name: "english",
ncLang: "en",
want: phraseSeen{
lang: "en", heading: "Later heading", placeholder: "Placeholder",
title: "Title", aria: "Aria", hole: "Zone example.com is missing",
openHole: "Zone {zone} is missing", fallback: "English only", unknown: "not.a.phrase",
htmlHole: "Zone <b>x</b> is missing", scripted: "Scripted", chromeID: "dialog.cancel",
err: "Missing <b>x</b>", nav: "Domains", fold: "Fold Domains",
missing: "that item is not in this Visit",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
nc := fakeLanguage(http.StatusOK, tt.ncLang)
t.Cleanup(nc.Close)
page := phrasePage(nc.URL, phrases)
t.Cleanup(page.Close)
got := readPhrases(t, page.URL+"/?item=missing", network.Headers{
"Accept-Language": browserLanguage,
"AUTHORIZATION-APP-API": base64.StdEncoding.EncodeToString([]byte("alice:secret")),
})
if got != tt.want {
t.Fatalf("got %+v, want %+v", got, tt.want)
}
})
}
}
type phraseSeen struct {
lang string
heading string
placeholder string
title string
aria string
hole string
openHole string
fallback string
unknown string
htmlHole string
scripted string
chromeID string
err string
nav string
fold string
missing string
}
func mergedPhrases(t *testing.T) gonexapp.Phrases {
t.Helper()
base, err := gonexapp.PhrasesFromFS(fstest.MapFS{
"i18n/en.json": {Data: []byte(phraseEN)},
"i18n/de.json": {Data: []byte(phraseDE)},
})
if err != nil {
t.Fatal(err)
}
mod, err := gonexapp.PhrasesFromFS(fstest.MapFS{
"i18n/en.json": {Data: []byte(`{"page.heading":"Later heading"}`)},
"i18n/de.json": {Data: []byte(`{"page.heading":"Spätere Überschrift"}`)},
})
if err != nil {
t.Fatal(err)
}
return gonexapp.Merge(base, mod)
}
const phraseEN = `{
"page.heading": "Heading",
"page.placeholder": "Placeholder",
"page.title": "Title",
"page.aria": "Aria",
"page.hole": "Zone {zone} is missing",
"page.english-only": "English only",
"page.scripted": "Scripted",
"page.error": "Missing {name}",
"nav.domains": "Domains",
"nav.missing": "that item is not in this Visit"
}`
const phraseDE = `{
"page.placeholder": "Platzhalter",
"page.title": "Titel",
"page.aria": "Beschriftung",
"page.hole": "{zone} fehlt",
"page.scripted": "Skript",
"page.error": "{name} fehlt",
"nav.domains": "Domänen",
"nav.missing": "Dieser Eintrag fehlt"
}`
func phrasePage(ncBase string, phrases gonexapp.Phrases) *httptest.Server {
nav := sampleNavigation()
nav.Cred = gonexapp.Credentials{
BaseURL: ncBase, AppID: "exapp", AppVersion: "1.0.0", AAVersion: "1.0.0", AppSecret: "secret",
}
nav.Phrases = phrases
nav.MissingMessage = "that item is not in this Visit"
nav.MissingPhrase = "nav.missing"
nav.Items = func(*http.Request) []gonexapp.Item {
return []gonexapp.Item{{
ID: "domains", Label: "Domains", Phrase: "nav.domains",
Children: []gonexapp.Item{{ID: "example.com", Label: "example.com"}},
}}
}
nav.Page = func(r *http.Request, id string) (string, bool) {
if id != "domains" {
return "", false
}
msg := phrases.Sentence(nav.Cred.UILanguage(r), "page.error", map[string]string{"name": "<b>x</b>"})
return `<h1 id="heading" data-phrase="page.heading">Heading</h1>
<input id="field" data-phrase-placeholder="page.placeholder" placeholder="Placeholder" data-phrase-title="page.title" title="Title" data-phrase-aria-label="page.aria" aria-label="Aria">
<p id="hole" data-phrase="page.hole" data-phrase-holes='{"zone":"example.com"}'>Zone {zone} is missing</p>
<p id="open-hole" data-phrase="page.hole">Zone {zone} is missing</p>
<p id="fallback" data-phrase="page.english-only">English only</p>
<p id="unknown" data-phrase="not.a.phrase">English source</p>
<p id="htmlhole" data-phrase="page.hole" data-phrase-holes='{"zone":"&lt;b&gt;x&lt;/b&gt;"}'>Zone {zone} is missing</p>
<p id="scripted"></p>
<p id="chrome-id"></p>
<p id="err">` + html.EscapeString(msg) + `</p>
<script>
document.getElementById("scripted").textContent = exappPhrase("page.scripted");
document.getElementById("chrome-id").textContent = exappPhrase("dialog.cancel");
</script>`, true
}
return httptest.NewServer(nav.Handler())
}
func readPhrases(t *testing.T, pageURL string, headers network.Headers) phraseSeen {
t.Helper()
ctx, cancel := chromedp.NewContext(allocCtx)
t.Cleanup(cancel)
ctx, cancel = context.WithTimeout(ctx, 25*time.Second)
t.Cleanup(cancel)
var raw string
if err := chromedp.Run(ctx,
network.Enable(),
network.SetExtraHTTPHeaders(headers),
chromedp.Navigate(pageURL),
chromedp.Evaluate(phraseProbeJS, &raw),
); err != nil {
t.Fatal(err)
}
var probe struct {
Lang string `json:"lang"`
Heading string `json:"heading"`
Placeholder string `json:"placeholder"`
Title string `json:"title"`
Aria string `json:"aria"`
Hole string `json:"hole"`
OpenHole string `json:"openHole"`
Fallback string `json:"fallback"`
Unknown string `json:"unknown"`
HTMLHole string `json:"htmlHole"`
HTMLHasB bool `json:"htmlHasB"`
Scripted string `json:"scripted"`
ChromeID string `json:"chromeId"`
Err string `json:"err"`
ErrHasB bool `json:"errHasB"`
Nav string `json:"nav"`
Fold string `json:"fold"`
Missing string `json:"missing"`
}
if err := json.Unmarshal([]byte(raw), &probe); err != nil {
t.Fatalf("probe %s: %v", raw, err)
}
if probe.HTMLHasB || probe.ErrHasB {
t.Fatalf("hole value was parsed as HTML: %+v", probe)
}
return phraseSeen{
lang: probe.Lang, heading: probe.Heading, placeholder: probe.Placeholder,
title: probe.Title, aria: probe.Aria, hole: probe.Hole, openHole: probe.OpenHole,
fallback: probe.Fallback, unknown: probe.Unknown, htmlHole: probe.HTMLHole,
scripted: probe.Scripted, chromeID: probe.ChromeID, err: probe.Err,
nav: probe.Nav, fold: probe.Fold, missing: probe.Missing,
}
}
const phraseProbeJS = `(() => {
const field = document.getElementById("field");
const htmlHole = document.getElementById("htmlhole");
const err = document.getElementById("err");
const name = document.querySelector('[data-id="domains"] > .app-navigation-entry .app-navigation-entry__name');
const fold = document.querySelector('[data-id="domains"] button.fold');
const missing = document.getElementById("nav-missing");
return JSON.stringify({
lang: document.documentElement.lang,
heading: document.getElementById("heading").textContent,
placeholder: field.placeholder,
title: field.title,
aria: field.getAttribute("aria-label"),
hole: document.getElementById("hole").textContent,
openHole: document.getElementById("open-hole").textContent,
fallback: document.getElementById("fallback").textContent,
unknown: document.getElementById("unknown").textContent,
htmlHole: htmlHole.textContent,
htmlHasB: !!htmlHole.querySelector("b"),
scripted: document.getElementById("scripted").textContent,
chromeId: document.getElementById("chrome-id").textContent,
err: err.textContent,
errHasB: !!err.querySelector("b"),
nav: name ? name.textContent : "",
fold: fold ? fold.getAttribute("aria-label") : "",
missing: missing ? missing.textContent : ""
});
})()`
+212
View File
@@ -0,0 +1,212 @@
package gonexapp
import (
"encoding/json"
"fmt"
"html/template"
"io/fs"
"maps"
"strings"
)
// Phrases is one ExApp's merged Phrase set.
// English is the complete set. A module set is merged with Merge;
// a repeated id uses the set added later.
// The page script receives this set. Library chrome is not included.
type Phrases struct {
en map[string]string
de map[string]string
}
// PhrasesFromFS reads i18n/en.json and i18n/de.json.
// Each file is one JSON object of id → text.
func PhrasesFromFS(fsys fs.FS) (Phrases, error) {
en, err := fs.ReadFile(fsys, "i18n/en.json")
if err != nil {
return Phrases{}, fmt.Errorf("read i18n/en.json: %w", err)
}
de, err := fs.ReadFile(fsys, "i18n/de.json")
if err != nil {
return Phrases{}, fmt.Errorf("read i18n/de.json: %w", err)
}
return ParsePhrases(en, de)
}
// ParsePhrases reads an English object and a German object.
func ParsePhrases(en, de []byte) (Phrases, error) {
enMap, err := decodePhraseFile(en)
if err != nil {
return Phrases{}, fmt.Errorf("en: %w", err)
}
deMap, err := decodePhraseFile(de)
if err != nil {
return Phrases{}, fmt.Errorf("de: %w", err)
}
return Phrases{en: enMap, de: deMap}, nil
}
func decodePhraseFile(raw []byte) (map[string]string, error) {
if len(strings.TrimSpace(string(raw))) == 0 {
return map[string]string{}, nil
}
var m map[string]string
if err := json.Unmarshal(raw, &m); err != nil {
return nil, err
}
if m == nil {
m = map[string]string{}
}
return m, nil
}
// Merge returns the sets combined in order.
// A repeated id uses the text from the set added later.
func Merge(sets ...Phrases) Phrases {
out := Phrases{en: map[string]string{}, de: map[string]string{}}
for _, set := range sets {
maps.Copy(out.en, set.en)
maps.Copy(out.de, set.de)
}
return out
}
func (p Phrases) has(code string) bool {
switch code {
case "en":
return p.en != nil
case "de":
return p.de != nil
default:
return false
}
}
func (p Phrases) texts(lang string) map[string]string {
if lang == "de" {
return p.de
}
return p.en
}
// Sentence is the finished text for lang.
// A missing text for that language uses the English text.
// An id missing from English is the id.
// A hole with no value stays visible as {name}.
// The result is plain text; the caller escapes it when writing HTML.
func (p Phrases) Sentence(lang, id string, holes map[string]string) string {
lang = matchLanguage(lang, p.has)
if text, ok := phraseText(p.texts(lang), id); ok {
return fillHoles(text, holes)
}
if lang != "en" {
if text, ok := phraseText(p.en, id); ok {
return fillHoles(text, holes)
}
}
return id
}
func phraseText(m map[string]string, id string) (string, bool) {
text, ok := m[id]
if !ok || text == "" {
return "", false
}
return text, true
}
// resolved is the map the page script sees: one text per id for lang,
// with English filling gaps. Ids missing from English are omitted.
func (p Phrases) resolved(lang string) map[string]string {
lang = matchLanguage(lang, p.has)
out := map[string]string{}
for id, text := range p.en {
if text == "" {
continue
}
out[id] = text
}
if lang == "en" {
return out
}
for id, text := range p.de {
if text == "" {
continue
}
if _, ok := phraseText(p.en, id); !ok {
continue
}
out[id] = text
}
return out
}
// Script defines exappPhrase for the page, from this set only.
func (p Phrases) Script(lang string) template.HTML {
raw, err := json.Marshal(p.resolved(lang))
if err != nil {
raw = []byte("{}")
}
return template.HTML("<script>\n" + phraseRuntimeJS + "\nwindow.exappPhrase = exappPhraseMap(" + string(raw) + ");\n</script>")
}
const phraseRuntimeJS = `function exappFill(text, holes) {
if (!holes || text.indexOf("{") < 0) return text;
var out = "";
for (var i = 0; i < text.length; i++) {
if (text.charAt(i) !== "{") { out += text.charAt(i); continue; }
var end = text.indexOf("}", i + 1);
if (end < 0) { out += text.charAt(i); continue; }
var name = text.slice(i + 1, end);
if (Object.prototype.hasOwnProperty.call(holes, name)) {
out += String(holes[name]);
i = end;
continue;
}
out += text.charAt(i);
}
return out;
}
function exappPhraseMap(map) {
return function (id, holes) {
var text = Object.prototype.hasOwnProperty.call(map, id) ? map[id] : String(id);
return exappFill(text, holes);
};
}`
// FillScript replaces English source after load and refreshes Fold from the
// visible item name. It does not parse Phrase text as HTML.
// App navigation includes it. A page the ExApp renders itself places Script
// in the head and FillScript at the end of the body.
func FillScript() template.HTML {
return phraseFillScript
}
// phraseFillScript replaces English source after load and refreshes Fold
// from the visible item name. It does not parse Phrase text as HTML.
const phraseFillScript = template.HTML(`<script>
(function () {
function holesOf(el) {
var raw = el.getAttribute("data-phrase-holes");
if (!raw) return null;
try { return JSON.parse(raw); } catch (e) { return null; }
}
function apply(el, attr, set) {
var id = el.getAttribute(attr);
if (!id || typeof exappPhrase !== "function") return;
set(exappPhrase(id, holesOf(el)));
}
document.querySelectorAll("[data-phrase],[data-phrase-placeholder],[data-phrase-title],[data-phrase-aria-label]").forEach(function (el) {
apply(el, "data-phrase", function (t) { el.textContent = t; });
apply(el, "data-phrase-placeholder", function (t) { el.placeholder = t; });
apply(el, "data-phrase-title", function (t) { el.title = t; });
apply(el, "data-phrase-aria-label", function (t) { el.setAttribute("aria-label", t); });
});
document.querySelectorAll("button.fold").forEach(function (btn) {
var pattern = btn.getAttribute("data-fold");
var entry = btn.closest(".app-navigation-entry");
var name = entry ? entry.querySelector(".app-navigation-entry__name") : null;
if (!pattern || !name || typeof exappFill !== "function") return;
btn.setAttribute("aria-label", exappFill(pattern, { label: name.textContent }));
});
})();
</script>`)
+4
View File
@@ -38,6 +38,8 @@ func (p AppAPIPreferences) ocsClient() OCSClient {
} }
// Get loads the configured preference key for the requesting user. // Get loads the configured preference key for the requesting user.
// A missing key returns an empty string and a nil error.
// It returns an error when the OCS call fails or the body cannot be decoded.
func (p AppAPIPreferences) Get() (string, error) { func (p AppAPIPreferences) Get() (string, error) {
ocs := p.ocsClient() ocs := p.ocsClient()
body, _ := json.Marshal(map[string]any{"configKeys": []string{p.Key}}) body, _ := json.Marshal(map[string]any{"configKeys": []string{p.Key}})
@@ -49,6 +51,8 @@ func (p AppAPIPreferences) Get() (string, error) {
} }
// Set stores value for the configured preference key. // Set stores value for the configured preference key.
// The value is stored as non-sensitive.
// It returns an error when the OCS call fails.
func (p AppAPIPreferences) Set(value string) error { func (p AppAPIPreferences) Set(value string) error {
ocs := p.ocsClient() ocs := p.ocsClient()
body, _ := json.Marshal(map[string]any{ body, _ := json.Marshal(map[string]any{