DELETED .deepsource.toml Index: .deepsource.toml ================================================================== --- .deepsource.toml +++ /dev/null @@ -1,8 +0,0 @@ -version = 1 - -[[analyzers]] -name = "go" -enabled = true - - [analyzers.meta] -import_paths = ["github.com/zettelstore/zettelstore"] Index: LICENSE.txt ================================================================== --- LICENSE.txt +++ LICENSE.txt @@ -1,6 +1,6 @@ -Copyright (c) 2020-2022 Detlef Stern +Copyright (c) 2020-present Detlef Stern Licensed under the EUPL Zettelstore is licensed under the European Union Public License, version 1.2 or later (EUPL v. 1.2). The license is available in the official languages of the Index: Makefile ================================================================== --- Makefile +++ Makefile @@ -1,31 +1,31 @@ -## Copyright (c) 2020-2021 Detlef Stern +## Copyright (c) 2020-present Detlef Stern ## -## This file is part of zettelstore. +## This file is part of Zettelstore. ## ## Zettelstore is licensed under the latest version of the EUPL (European Union ## Public License). Please see file LICENSE.txt for your rights and obligations ## under this license. -.PHONY: check relcheck api build release clean +.PHONY: check relcheck api version build release clean check: - go run tools/build.go check + go run tools/check/check.go relcheck: - go run tools/build.go relcheck + go run tools/check/check.go -r api: - go run tools/build.go testapi + go run tools/testapi/testapi.go version: - @echo $(shell go run tools/build.go version) + @echo $(shell go run tools/build/build.go version) build: - go run tools/build.go build + go run tools/build/build.go build release: - go run tools/build.go release + go run tools/build/build.go release clean: - go run tools/build.go clean + go run tools/clean/clean.go Index: README.md ================================================================== --- README.md +++ README.md @@ -11,16 +11,16 @@ To get an initial impression, take a look at the [manual](https://zettelstore.de/manual/). It is a live example of the zettelstore software, running in read-only mode. -[Zettelstore Client](https://zettelstore.de/client) provides client -software to access Zettelstore via its API more easily, [Zettelstore +[Zettelstore Client](https://t73f.de/r/zsc) provides client software to access +Zettelstore via its API more easily, [Zettelstore Contrib](https://zettelstore.de/contrib) contains contributed software, which often connects to Zettelstore via its API. Some of the software packages may be experimental. The software, including the manual, is licensed under the [European Union Public License 1.2 (or later)](https://zettelstore.de/home/file?name=LICENSE.txt&ci=trunk). -[Stay tuned](https://twitter.com/zettelstore)… +[Stay tuned](https://mastodon.social/tags/Zettelstore) … Index: VERSION ================================================================== --- VERSION +++ VERSION @@ -1,1 +1,1 @@ -0.5.0 +0.22.0-dev DELETED ast/ast.go Index: ast/ast.go ================================================================== --- ast/ast.go +++ /dev/null @@ -1,88 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package ast provides the abstract syntax tree for parsed zettel content. -package ast - -import ( - "net/url" - - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -// ZettelNode is the root node of the abstract syntax tree. -// It is *not* part of the visitor pattern. -type ZettelNode struct { - Meta *meta.Meta // Original metadata - Content domain.Content // Original content - Zid id.Zid // Zettel identification. - InhMeta *meta.Meta // Metadata of the zettel, with inherited values. - Ast BlockSlice // Zettel abstract syntax tree is a sequence of block nodes. - Syntax string // Syntax / parser that produced the Ast -} - -// Node is the interface, all nodes must implement. -type Node interface { - WalkChildren(v Visitor) -} - -// BlockNode is the interface that all block nodes must implement. -type BlockNode interface { - Node - blockNode() -} - -// ItemNode is a node that can occur as a list item. -type ItemNode interface { - BlockNode - itemNode() -} - -// ItemSlice is a slice of ItemNodes. -type ItemSlice []ItemNode - -// DescriptionNode is a node that contains just textual description. -type DescriptionNode interface { - ItemNode - descriptionNode() -} - -// DescriptionSlice is a slice of DescriptionNodes. -type DescriptionSlice []DescriptionNode - -// InlineNode is the interface that all inline nodes must implement. -type InlineNode interface { - Node - inlineNode() -} - -// Reference is a reference to external or internal material. -type Reference struct { - URL *url.URL - Value string - State RefState -} - -// RefState indicates the state of the reference. -type RefState int - -// Constants for RefState -const ( - RefStateInvalid RefState = iota // Invalid Reference - RefStateZettel // Reference to an internal zettel - RefStateSelf // Reference to same zettel with a fragment - RefStateFound // Reference to an existing internal zettel, URL is ajusted - RefStateBroken // Reference to a non-existing internal zettel - RefStateHosted // Reference to local hosted non-Zettel, without URL change - RefStateBased // Reference to local non-Zettel, to be prefixed - RefStateExternal // Reference to external material -) DELETED ast/block.go Index: ast/block.go ================================================================== --- ast/block.go +++ /dev/null @@ -1,296 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package ast - -import "zettelstore.de/c/attrs" - -// Definition of Block nodes. - -// BlockSlice is a slice of BlockNodes. -type BlockSlice []BlockNode - -func (*BlockSlice) blockNode() { /* Just a marker */ } - -// WalkChildren walks down to the descriptions. -func (bs *BlockSlice) WalkChildren(v Visitor) { - if bs != nil { - for _, bn := range *bs { - Walk(v, bn) - } - } -} - -// FirstParagraphInlines returns the inline list of the first paragraph that -// contains a inline list. -func (bs BlockSlice) FirstParagraphInlines() InlineSlice { - for _, bn := range bs { - pn, ok := bn.(*ParaNode) - if !ok { - continue - } - if inl := pn.Inlines; len(inl) > 0 { - return inl - } - } - return nil -} - -//-------------------------------------------------------------------------- - -// ParaNode contains just a sequence of inline elements. -// Another name is "paragraph". -type ParaNode struct { - Inlines InlineSlice -} - -func (*ParaNode) blockNode() { /* Just a marker */ } -func (*ParaNode) itemNode() { /* Just a marker */ } -func (*ParaNode) descriptionNode() { /* Just a marker */ } - -// CreateParaNode creates a parameter block from inline nodes. -func CreateParaNode(nodes ...InlineNode) *ParaNode { return &ParaNode{Inlines: nodes} } - -// WalkChildren walks down the inline elements. -func (pn *ParaNode) WalkChildren(v Visitor) { Walk(v, &pn.Inlines) } - -//-------------------------------------------------------------------------- - -// VerbatimNode contains uninterpreted text -type VerbatimNode struct { - Kind VerbatimKind - Attrs attrs.Attributes - Content []byte -} - -// VerbatimKind specifies the format that is applied to code inline nodes. -type VerbatimKind int - -// Constants for VerbatimCode -const ( - _ VerbatimKind = iota - VerbatimZettel // Zettel content - VerbatimProg // Program code - VerbatimEval // Code to be externally interpreted. Syntax is stored in default attribute. - VerbatimComment // Block comment - VerbatimHTML // Block HTML, e.g. for Markdown - VerbatimMath // Block math mode -) - -func (*VerbatimNode) blockNode() { /* Just a marker */ } -func (*VerbatimNode) itemNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (*VerbatimNode) WalkChildren(Visitor) { /* No children*/ } - -// Supported syntax values for VerbatimEval. -const ( - VerbatimEvalSyntaxDraw = "draw" -) - -//-------------------------------------------------------------------------- - -// RegionNode encapsulates a region of block nodes. -type RegionNode struct { - Kind RegionKind - Attrs attrs.Attributes - Blocks BlockSlice - Inlines InlineSlice // Optional text at the end of the region -} - -// RegionKind specifies the actual region type. -type RegionKind int - -// Values for RegionCode -const ( - _ RegionKind = iota - RegionSpan // Just a span of blocks - RegionQuote // A longer quotation - RegionVerse // Line breaks matter -) - -func (*RegionNode) blockNode() { /* Just a marker */ } -func (*RegionNode) itemNode() { /* Just a marker */ } - -// WalkChildren walks down the blocks and the text. -func (rn *RegionNode) WalkChildren(v Visitor) { - Walk(v, &rn.Blocks) - Walk(v, &rn.Inlines) -} - -//-------------------------------------------------------------------------- - -// HeadingNode stores the heading text and level. -type HeadingNode struct { - Level int - Attrs attrs.Attributes - Slug string // Heading text, normalized - Fragment string // Heading text, suitable to be used as an unique URL fragment - Inlines InlineSlice // Heading text, possibly formatted -} - -func (*HeadingNode) blockNode() { /* Just a marker */ } -func (*HeadingNode) itemNode() { /* Just a marker */ } - -// WalkChildren walks the heading text. -func (hn *HeadingNode) WalkChildren(v Visitor) { Walk(v, &hn.Inlines) } - -//-------------------------------------------------------------------------- - -// HRuleNode specifies a horizontal rule. -type HRuleNode struct { - Attrs attrs.Attributes -} - -func (*HRuleNode) blockNode() { /* Just a marker */ } -func (*HRuleNode) itemNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (*HRuleNode) WalkChildren(Visitor) { /* No children*/ } - -//-------------------------------------------------------------------------- - -// NestedListNode specifies a nestable list, either ordered or unordered. -type NestedListNode struct { - Kind NestedListKind - Items []ItemSlice - Attrs attrs.Attributes -} - -// NestedListKind specifies the actual list type. -type NestedListKind uint8 - -// Values for ListCode -const ( - _ NestedListKind = iota - NestedListOrdered // Ordered list. - NestedListUnordered // Unordered list. - NestedListQuote // Quote list. -) - -func (*NestedListNode) blockNode() { /* Just a marker */ } -func (*NestedListNode) itemNode() { /* Just a marker */ } - -// WalkChildren walks down the items. -func (ln *NestedListNode) WalkChildren(v Visitor) { - if items := ln.Items; items != nil { - for _, item := range items { - WalkItemSlice(v, item) - } - } -} - -//-------------------------------------------------------------------------- - -// DescriptionListNode specifies a description list. -type DescriptionListNode struct { - Descriptions []Description -} - -// Description is one element of a description list. -type Description struct { - Term InlineSlice - Descriptions []DescriptionSlice -} - -func (*DescriptionListNode) blockNode() { /* Just a marker */ } - -// WalkChildren walks down to the descriptions. -func (dn *DescriptionListNode) WalkChildren(v Visitor) { - if descrs := dn.Descriptions; descrs != nil { - for i, desc := range descrs { - if len(desc.Term) > 0 { - Walk(v, &descrs[i].Term) // Otherwise, changes in desc.Term will not go back into AST - } - if dss := desc.Descriptions; dss != nil { - for _, dns := range dss { - WalkDescriptionSlice(v, dns) - } - } - } - } -} - -//-------------------------------------------------------------------------- - -// TableNode specifies a full table -type TableNode struct { - Header TableRow // The header row - Align []Alignment // Default column alignment - Rows []TableRow // The slice of cell rows -} - -// TableCell contains the data for one table cell -type TableCell struct { - Align Alignment // Cell alignment - Inlines InlineSlice // Cell content -} - -// TableRow is a slice of cells. -type TableRow []*TableCell - -// Alignment specifies text alignment. -// Currently only for tables. -type Alignment int - -// Constants for Alignment. -const ( - _ Alignment = iota - AlignDefault // Default alignment, inherited - AlignLeft // Left alignment - AlignCenter // Center the content - AlignRight // Right alignment -) - -func (*TableNode) blockNode() { /* Just a marker */ } - -// WalkChildren walks down to the cells. -func (tn *TableNode) WalkChildren(v Visitor) { - if header := tn.Header; header != nil { - for i := range header { - Walk(v, &header[i].Inlines) // Otherwise changes will not go back - } - } - if rows := tn.Rows; rows != nil { - for _, row := range rows { - for i := range row { - Walk(v, &row[i].Inlines) // Otherwise changes will not go back - } - } - } -} - -//-------------------------------------------------------------------------- - -// TranscludeNode specifies block content from other zettel to embedded in -// current zettel -type TranscludeNode struct { - Ref *Reference -} - -func (*TranscludeNode) blockNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (*TranscludeNode) WalkChildren(Visitor) { /* No children*/ } - -//-------------------------------------------------------------------------- - -// BLOBNode contains just binary data that must be interpreted according to -// a syntax. -type BLOBNode struct { - Title string - Syntax string - Blob []byte -} - -func (*BLOBNode) blockNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (*BLOBNode) WalkChildren(Visitor) { /* No children*/ } DELETED ast/inline.go Index: ast/inline.go ================================================================== --- ast/inline.go +++ /dev/null @@ -1,252 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package ast - -import ( - "unicode/utf8" - - "zettelstore.de/c/attrs" -) - -// Definitions of inline nodes. - -// InlineSlice is a list of BlockNodes. -type InlineSlice []InlineNode - -func (*InlineSlice) inlineNode() { /* Just a marker */ } - -// CreateInlineSliceFromWords makes a new inline list from words, -// that will be space-separated. -func CreateInlineSliceFromWords(words ...string) InlineSlice { - inl := make(InlineSlice, 0, 2*len(words)-1) - for i, word := range words { - if i > 0 { - inl = append(inl, &SpaceNode{Lexeme: " "}) - } - inl = append(inl, &TextNode{Text: word}) - } - return inl -} - -// WalkChildren walks down to the list. -func (is *InlineSlice) WalkChildren(v Visitor) { - for _, in := range *is { - Walk(v, in) - } -} - -// -------------------------------------------------------------------------- - -// TextNode just contains some text. -type TextNode struct { - Text string // The text itself. -} - -func (*TextNode) inlineNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (*TextNode) WalkChildren(Visitor) { /* No children*/ } - -// -------------------------------------------------------------------------- - -// TagNode contains a tag. -type TagNode struct { - Tag string // The text itself. -} - -func (*TagNode) inlineNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (*TagNode) WalkChildren(Visitor) { /* No children*/ } - -// -------------------------------------------------------------------------- - -// SpaceNode tracks inter-word space characters. -type SpaceNode struct { - Lexeme string -} - -func (*SpaceNode) inlineNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (*SpaceNode) WalkChildren(Visitor) { /* No children*/ } - -// Count returns the number of space runes. -func (sn *SpaceNode) Count() int { - return utf8.RuneCountInString(sn.Lexeme) -} - -// -------------------------------------------------------------------------- - -// BreakNode signals a new line that must / should be interpreted as a new line break. -type BreakNode struct { - Hard bool // Hard line break? -} - -func (*BreakNode) inlineNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (*BreakNode) WalkChildren(Visitor) { /* No children*/ } - -// -------------------------------------------------------------------------- - -// LinkNode contains the specified link. -type LinkNode struct { - Attrs attrs.Attributes // Optional attributes - Ref *Reference - Inlines InlineSlice // The text associated with the link. -} - -func (*LinkNode) inlineNode() { /* Just a marker */ } - -// WalkChildren walks to the link text. -func (ln *LinkNode) WalkChildren(v Visitor) { - if len(ln.Inlines) > 0 { - Walk(v, &ln.Inlines) - } -} - -// -------------------------------------------------------------------------- - -// EmbedRefNode contains the specified embedded reference material. -type EmbedRefNode struct { - Attrs attrs.Attributes // Optional attributes - Ref *Reference // The reference to be embedded. - Syntax string // Syntax of referenced material, if known - Inlines InlineSlice // Optional text associated with the image. -} - -func (*EmbedRefNode) inlineNode() { /* Just a marker */ } - -// WalkChildren walks to the text that describes the embedded material. -func (en *EmbedRefNode) WalkChildren(v Visitor) { Walk(v, &en.Inlines) } - -// -------------------------------------------------------------------------- - -// EmbedBLOBNode contains the specified embedded BLOB material. -type EmbedBLOBNode struct { - Attrs attrs.Attributes // Optional attributes - Syntax string // Syntax of Blob - Blob []byte // BLOB data itself. - Inlines InlineSlice // Optional text associated with the image. -} - -func (*EmbedBLOBNode) inlineNode() { /* Just a marker */ } - -// WalkChildren walks to the text that describes the embedded material. -func (en *EmbedBLOBNode) WalkChildren(v Visitor) { Walk(v, &en.Inlines) } - -// -------------------------------------------------------------------------- - -// CiteNode contains the specified citation. -type CiteNode struct { - Attrs attrs.Attributes // Optional attributes - Key string // The citation key - Inlines InlineSlice // Optional text associated with the citation. -} - -func (*CiteNode) inlineNode() { /* Just a marker */ } - -// WalkChildren walks to the cite text. -func (cn *CiteNode) WalkChildren(v Visitor) { Walk(v, &cn.Inlines) } - -// -------------------------------------------------------------------------- - -// MarkNode contains the specified merked position. -// It is a BlockNode too, because although it is typically parsed during inline -// mode, it is moved into block mode afterwards. -type MarkNode struct { - Mark string // The mark text itself - Slug string // Slugified form of Mark - Fragment string // Unique form of Slug - Inlines InlineSlice // Marked inline content -} - -func (*MarkNode) inlineNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (mn *MarkNode) WalkChildren(v Visitor) { - if len(mn.Inlines) > 0 { - Walk(v, &mn.Inlines) - } -} - -// -------------------------------------------------------------------------- - -// FootnoteNode contains the specified footnote. -type FootnoteNode struct { - Attrs attrs.Attributes // Optional attributes - Inlines InlineSlice // The footnote text. -} - -func (*FootnoteNode) inlineNode() { /* Just a marker */ } - -// WalkChildren walks to the footnote text. -func (fn *FootnoteNode) WalkChildren(v Visitor) { Walk(v, &fn.Inlines) } - -// -------------------------------------------------------------------------- - -// FormatNode specifies some inline formatting. -type FormatNode struct { - Kind FormatKind - Attrs attrs.Attributes // Optional attributes. - Inlines InlineSlice -} - -// FormatKind specifies the format that is applied to the inline nodes. -type FormatKind int - -// Constants for FormatCode -const ( - _ FormatKind = iota - FormatEmph // Emphasized text. - FormatStrong // Strongly emphasized text. - FormatInsert // Inserted text. - FormatDelete // Deleted text. - FormatSuper // Superscripted text. - FormatSub // SubscriptedText. - FormatQuote // Quoted text. - FormatSpan // Generic inline container. -) - -func (*FormatNode) inlineNode() { /* Just a marker */ } - -// WalkChildren walks to the formatted text. -func (fn *FormatNode) WalkChildren(v Visitor) { Walk(v, &fn.Inlines) } - -// -------------------------------------------------------------------------- - -// LiteralNode specifies some uninterpreted text. -type LiteralNode struct { - Kind LiteralKind - Attrs attrs.Attributes // Optional attributes. - Content []byte -} - -// LiteralKind specifies the format that is applied to code inline nodes. -type LiteralKind int - -// Constants for LiteralCode -const ( - _ LiteralKind = iota - LiteralZettel // Zettel content - LiteralProg // Inline program code - LiteralInput // Computer input, e.g. Keyboard strokes - LiteralOutput // Computer output - LiteralComment // Inline comment - LiteralHTML // Inline HTML, e.g. for Markdown - LiteralMath // Inline math mode -) - -func (*LiteralNode) inlineNode() { /* Just a marker */ } - -// WalkChildren does nothing. -func (*LiteralNode) WalkChildren(Visitor) { /* No children*/ } DELETED ast/ref.go Index: ast/ref.go ================================================================== --- ast/ref.go +++ /dev/null @@ -1,91 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package ast - -import ( - "net/url" - - "zettelstore.de/z/domain/id" -) - -// ParseReference parses a string and returns a reference. -func ParseReference(s string) *Reference { - switch s { - case "", "00000000000000": - return &Reference{URL: nil, Value: s, State: RefStateInvalid} - } - if state, ok := localState(s); ok { - if state == RefStateBased { - s = s[1:] - } - u, err := url.Parse(s) - if err == nil { - return &Reference{URL: u, Value: s, State: state} - } - } - u, err := url.Parse(s) - if err != nil { - return &Reference{URL: nil, Value: s, State: RefStateInvalid} - } - if len(u.Scheme)+len(u.Opaque)+len(u.Host) == 0 && u.User == nil { - if _, err = id.Parse(u.Path); err == nil { - return &Reference{URL: u, Value: s, State: RefStateZettel} - } - if u.Path == "" && u.Fragment != "" { - return &Reference{URL: u, Value: s, State: RefStateSelf} - } - } - return &Reference{URL: u, Value: s, State: RefStateExternal} -} - -func localState(path string) (RefState, bool) { - if len(path) > 0 && path[0] == '/' { - if len(path) > 1 && path[1] == '/' { - return RefStateBased, true - } - return RefStateHosted, true - } - if len(path) > 1 && path[0] == '.' { - if len(path) > 2 && path[1] == '.' && path[2] == '/' { - return RefStateHosted, true - } - return RefStateHosted, path[1] == '/' - } - return RefStateInvalid, false -} - -// String returns the string representation of a reference. -func (r Reference) String() string { - if r.URL != nil { - return r.URL.String() - } - return r.Value -} - -// IsValid returns true if reference is valid -func (r *Reference) IsValid() bool { return r.State != RefStateInvalid } - -// IsZettel returns true if it is a referencen to a local zettel. -func (r *Reference) IsZettel() bool { - switch r.State { - case RefStateZettel, RefStateSelf, RefStateFound, RefStateBroken: - return true - } - return false -} - -// IsLocal returns true if reference is local -func (r *Reference) IsLocal() bool { - return r.State == RefStateHosted || r.State == RefStateBased -} - -// IsExternal returns true if it is a referencen to external material. -func (r *Reference) IsExternal() bool { return r.State == RefStateExternal } DELETED ast/ref_test.go Index: ast/ref_test.go ================================================================== --- ast/ref_test.go +++ /dev/null @@ -1,95 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package ast_test - -import ( - "testing" - - "zettelstore.de/z/ast" -) - -func TestParseReference(t *testing.T) { - t.Parallel() - testcases := []struct { - link string - err bool - exp string - }{ - {"", true, ""}, - {"123", false, "123"}, - {",://", true, ""}, - } - - for i, tc := range testcases { - got := ast.ParseReference(tc.link) - if got.IsValid() == tc.err { - t.Errorf( - "TC=%d, expected parse error of %q: %v, but got %q", i, tc.link, tc.err, got) - } - if got.IsValid() && got.String() != tc.exp { - t.Errorf("TC=%d, Reference of %q is %q, but got %q", i, tc.link, tc.exp, got) - } - } -} - -func TestReferenceIsZettelMaterial(t *testing.T) { - t.Parallel() - testcases := []struct { - link string - isZettel bool - isExternal bool - isLocal bool - }{ - {"", false, false, false}, - {"00000000000000", false, false, false}, - {"http://zettelstore.de/z/ast", false, true, false}, - {"12345678901234", true, false, false}, - {"12345678901234#local", true, false, false}, - {"http://12345678901234", false, true, false}, - {"http://zettelstore.de/z/12345678901234", false, true, false}, - {"http://zettelstore.de/12345678901234", false, true, false}, - {"/12345678901234", false, false, true}, - {"//12345678901234", false, false, true}, - {"./12345678901234", false, false, true}, - {"../12345678901234", false, false, true}, - {".../12345678901234", false, true, false}, - } - - for i, tc := range testcases { - ref := ast.ParseReference(tc.link) - isZettel := ref.IsZettel() - if isZettel != tc.isZettel { - t.Errorf( - "TC=%d, Reference %q isZettel=%v expected, but got %v", - i, - tc.link, - tc.isZettel, - isZettel) - } - isLocal := ref.IsLocal() - if isLocal != tc.isLocal { - t.Errorf( - "TC=%d, Reference %q isLocal=%v expected, but got %v", - i, - tc.link, - tc.isLocal, isLocal) - } - isExternal := ref.IsExternal() - if isExternal != tc.isExternal { - t.Errorf( - "TC=%d, Reference %q isExternal=%v expected, but got %v", - i, - tc.link, - tc.isExternal, - isExternal) - } - } -} DELETED ast/walk.go Index: ast/walk.go ================================================================== --- ast/walk.go +++ /dev/null @@ -1,45 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package ast - -// Visitor is a visitor for walking the AST. -type Visitor interface { - Visit(node Node) Visitor -} - -// Walk traverses the AST. -func Walk(v Visitor, node Node) { - if v = v.Visit(node); v == nil { - return - } - - // Implementation note: - // It is much faster to use interface dispatching than to use a switch statement. - // On my "cpu: Intel(R) Core(TM) i7-6820HQ CPU @ 2.70GHz", a switch statement - // implementation tooks approx 940-980 ns/op. Interface dispatching is in the - // range of 900-930 ns/op. - node.WalkChildren(v) - v.Visit(nil) -} - -// WalkItemSlice traverses an item slice. -func WalkItemSlice(v Visitor, ins ItemSlice) { - for _, in := range ins { - Walk(v, in) - } -} - -// WalkDescriptionSlice traverses an item slice. -func WalkDescriptionSlice(v Visitor, dns DescriptionSlice) { - for _, dn := range dns { - Walk(v, dn) - } -} DELETED ast/walk_test.go Index: ast/walk_test.go ================================================================== --- ast/walk_test.go +++ /dev/null @@ -1,71 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package ast_test - -import ( - "testing" - - "zettelstore.de/c/attrs" - "zettelstore.de/z/ast" -) - -func BenchmarkWalk(b *testing.B) { - root := ast.BlockSlice{ - &ast.HeadingNode{ - Inlines: ast.CreateInlineSliceFromWords("A", "Simple", "Heading"), - }, - &ast.ParaNode{ - Inlines: ast.CreateInlineSliceFromWords("This", "is", "the", "introduction."), - }, - &ast.NestedListNode{ - Kind: ast.NestedListUnordered, - Items: []ast.ItemSlice{ - []ast.ItemNode{ - &ast.ParaNode{ - Inlines: ast.CreateInlineSliceFromWords("Item", "1"), - }, - }, - []ast.ItemNode{ - &ast.ParaNode{ - Inlines: ast.CreateInlineSliceFromWords("Item", "2"), - }, - }, - }, - }, - &ast.ParaNode{ - Inlines: ast.CreateInlineSliceFromWords("This", "is", "some", "intermediate", "text."), - }, - ast.CreateParaNode( - &ast.FormatNode{ - Kind: ast.FormatEmph, - Attrs: attrs.Attributes(map[string]string{ - "": "class", - "color": "green", - }), - Inlines: ast.CreateInlineSliceFromWords("This", "is", "some", "emphasized", "text."), - }, - &ast.SpaceNode{Lexeme: " "}, - &ast.LinkNode{ - Ref: &ast.Reference{Value: "http://zettelstore.de"}, - Inlines: ast.CreateInlineSliceFromWords("URL", "text."), - }, - ), - } - v := benchVisitor{} - b.ResetTimer() - for n := 0; n < b.N; n++ { - ast.Walk(&v, &root) - } -} - -type benchVisitor struct{} - -func (bv *benchVisitor) Visit(ast.Node) ast.Visitor { return bv } DELETED auth/auth.go Index: auth/auth.go ================================================================== --- auth/auth.go +++ /dev/null @@ -1,104 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package auth provides services for authentification / authorization. -package auth - -import ( - "time" - - "zettelstore.de/z/box" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/web/server" -) - -// BaseManager allows to check some base auth modes. -type BaseManager interface { - // IsReadonly returns true, if the systems is configured to run in read-only-mode. - IsReadonly() bool -} - -// TokenManager provides methods to create authentication -type TokenManager interface { - - // GetToken produces a authentication token. - GetToken(ident *meta.Meta, d time.Duration, kind TokenKind) ([]byte, error) - - // CheckToken checks the validity of the token and returns relevant data. - CheckToken(token []byte, k TokenKind) (TokenData, error) -} - -// TokenKind specifies for which application / usage a token is/was requested. -type TokenKind int - -// Allowed values of token kind -const ( - _ TokenKind = iota - KindJSON - KindHTML -) - -// TokenData contains some important elements from a token. -type TokenData struct { - Token []byte - Now time.Time - Issued time.Time - Expires time.Time - Ident string - Zid id.Zid -} - -// AuthzManager provides methods for authorization. -type AuthzManager interface { - BaseManager - - // Owner returns the zettel identifier of the owner. - Owner() id.Zid - - // IsOwner returns true, if the given zettel identifier is that of the owner. - IsOwner(zid id.Zid) bool - - // Returns true if authentication is enabled. - WithAuth() bool - - // GetUserRole role returns the user role of the given user zettel. - GetUserRole(user *meta.Meta) meta.UserRole -} - -// Manager is the main interface for providing the service. -type Manager interface { - TokenManager - AuthzManager - - BoxWithPolicy(auth server.Auth, unprotectedBox box.Box, rtConfig config.Config) (box.Box, Policy) -} - -// Policy is an interface for checking access authorization. -type Policy interface { - // User is allowed to create a new zettel. - CanCreate(user, newMeta *meta.Meta) bool - - // User is allowed to read zettel - CanRead(user, m *meta.Meta) bool - - // User is allowed to write zettel. - CanWrite(user, oldMeta, newMeta *meta.Meta) bool - - // User is allowed to rename zettel - CanRename(user, m *meta.Meta) bool - - // User is allowed to delete zettel. - CanDelete(user, m *meta.Meta) bool - - // User is allowed to refresh box data. - CanRefresh(user *meta.Meta) bool -} DELETED auth/cred/cred.go Index: auth/cred/cred.go ================================================================== --- auth/cred/cred.go +++ /dev/null @@ -1,53 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package cred provides some function for handling credentials. -package cred - -import ( - "bytes" - - "golang.org/x/crypto/bcrypt" - "zettelstore.de/z/domain/id" -) - -// HashCredential returns a hashed vesion of the given credential -func HashCredential(zid id.Zid, ident, credential string) (string, error) { - fullCredential := createFullCredential(zid, ident, credential) - res, err := bcrypt.GenerateFromPassword(fullCredential, bcrypt.DefaultCost) - if err != nil { - return "", err - } - return string(res), nil -} - -// CompareHashAndCredential checks, whether the hashed credential is a possible -// value when hashing the credential. -func CompareHashAndCredential(hashed string, zid id.Zid, ident, credential string) (bool, error) { - fullCredential := createFullCredential(zid, ident, credential) - err := bcrypt.CompareHashAndPassword([]byte(hashed), fullCredential) - if err == nil { - return true, nil - } - if err == bcrypt.ErrMismatchedHashAndPassword { - return false, nil - } - return false, err -} - -func createFullCredential(zid id.Zid, ident, credential string) []byte { - var buf bytes.Buffer - buf.WriteString(zid.String()) - buf.WriteByte(' ') - buf.WriteString(ident) - buf.WriteByte(' ') - buf.WriteString(credential) - return buf.Bytes() -} DELETED auth/impl/impl.go Index: auth/impl/impl.go ================================================================== --- auth/impl/impl.go +++ /dev/null @@ -1,179 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package impl provides services for authentification / authorization. -package impl - -import ( - "errors" - "hash/fnv" - "io" - "time" - - "github.com/pascaldekloe/jwt" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/auth/policy" - "zettelstore.de/z/box" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" - "zettelstore.de/z/web/server" -) - -type myAuth struct { - readonly bool - owner id.Zid - secret []byte -} - -// New creates a new auth object. -func New(readonly bool, owner id.Zid, extSecret string) auth.Manager { - return &myAuth{ - readonly: readonly, - owner: owner, - secret: calcSecret(extSecret), - } -} - -var configKeys = []string{ - kernel.CoreProgname, - kernel.CoreGoVersion, - kernel.CoreHostname, - kernel.CoreGoOS, - kernel.CoreGoArch, - kernel.CoreVersion, -} - -func calcSecret(extSecret string) []byte { - h := fnv.New128() - if extSecret != "" { - io.WriteString(h, extSecret) - } - for _, key := range configKeys { - io.WriteString(h, kernel.Main.GetConfig(kernel.CoreService, key).(string)) - } - return h.Sum(nil) -} - -// IsReadonly returns true, if the systems is configured to run in read-only-mode. -func (a *myAuth) IsReadonly() bool { return a.readonly } - -const reqHash = jwt.HS512 - -// ErrNoIdent signals that the 'ident' key is missing. -var ErrNoIdent = errors.New("auth: missing ident") - -// ErrOtherKind signals that the token was defined for another token kind. -var ErrOtherKind = errors.New("auth: wrong token kind") - -// ErrNoZid signals that the 'zid' key is missing. -var ErrNoZid = errors.New("auth: missing zettel id") - -// GetToken returns a token to be used for authentification. -func (a *myAuth) GetToken(ident *meta.Meta, d time.Duration, kind auth.TokenKind) ([]byte, error) { - subject, ok := ident.Get(api.KeyUserID) - if !ok || subject == "" { - return nil, ErrNoIdent - } - - now := time.Now().Round(time.Second) - claims := jwt.Claims{ - Registered: jwt.Registered{ - Subject: subject, - Expires: jwt.NewNumericTime(now.Add(d)), - Issued: jwt.NewNumericTime(now), - }, - Set: map[string]interface{}{ - "zid": ident.Zid.String(), - "_tk": int(kind), - }, - } - token, err := claims.HMACSign(reqHash, a.secret) - if err != nil { - return nil, err - } - return token, nil -} - -// ErrTokenExpired signals an exired token -var ErrTokenExpired = errors.New("auth: token expired") - -// CheckToken checks the validity of the token and returns relevant data. -func (a *myAuth) CheckToken(token []byte, k auth.TokenKind) (auth.TokenData, error) { - h, err := jwt.NewHMAC(reqHash, a.secret) - if err != nil { - return auth.TokenData{}, err - } - claims, err := h.Check(token) - if err != nil { - return auth.TokenData{}, err - } - now := time.Now().Round(time.Second) - expires := claims.Expires.Time() - if expires.Before(now) { - return auth.TokenData{}, ErrTokenExpired - } - ident := claims.Subject - if ident == "" { - return auth.TokenData{}, ErrNoIdent - } - if zidS, ok := claims.Set["zid"].(string); ok { - if zid, err2 := id.Parse(zidS); err2 == nil { - if kind, ok2 := claims.Set["_tk"].(float64); ok2 { - if auth.TokenKind(kind) == k { - return auth.TokenData{ - Token: token, - Now: now, - Issued: claims.Issued.Time(), - Expires: expires, - Ident: ident, - Zid: zid, - }, nil - } - } - return auth.TokenData{}, ErrOtherKind - } - } - return auth.TokenData{}, ErrNoZid -} - -func (a *myAuth) Owner() id.Zid { return a.owner } - -func (a *myAuth) IsOwner(zid id.Zid) bool { - return zid.IsValid() && zid == a.owner -} - -func (a *myAuth) WithAuth() bool { return a.owner != id.Invalid } - -// GetUserRole role returns the user role of the given user zettel. -func (a *myAuth) GetUserRole(user *meta.Meta) meta.UserRole { - if user == nil { - if a.WithAuth() { - return meta.UserRoleUnknown - } - return meta.UserRoleOwner - } - if a.IsOwner(user.Zid) { - return meta.UserRoleOwner - } - if val, ok := user.Get(api.KeyUserRole); ok { - if ur := meta.GetUserRole(val); ur != meta.UserRoleUnknown { - return ur - } - } - return meta.UserRoleReader -} - -func (a *myAuth) BoxWithPolicy(auth server.Auth, unprotectedBox box.Box, rtConfig config.Config) (box.Box, auth.Policy) { - return policy.BoxWithPolicy(auth, a, unprotectedBox, rtConfig) -} DELETED auth/policy/anon.go Index: auth/policy/anon.go ================================================================== --- auth/policy/anon.go +++ /dev/null @@ -1,56 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package policy - -import ( - "zettelstore.de/z/auth" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/meta" -) - -type anonPolicy struct { - authConfig config.AuthConfig - pre auth.Policy -} - -func (ap *anonPolicy) CanCreate(user, newMeta *meta.Meta) bool { - return ap.pre.CanCreate(user, newMeta) -} - -func (ap *anonPolicy) CanRead(user, m *meta.Meta) bool { - return ap.pre.CanRead(user, m) && ap.checkVisibility(m) -} - -func (ap *anonPolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool { - return ap.pre.CanWrite(user, oldMeta, newMeta) && ap.checkVisibility(oldMeta) -} - -func (ap *anonPolicy) CanRename(user, m *meta.Meta) bool { - return ap.pre.CanRename(user, m) && ap.checkVisibility(m) -} - -func (ap *anonPolicy) CanDelete(user, m *meta.Meta) bool { - return ap.pre.CanDelete(user, m) && ap.checkVisibility(m) -} - -func (ap *anonPolicy) CanRefresh(user *meta.Meta) bool { - if ap.authConfig.GetExpertMode() || ap.authConfig.GetSimpleMode() { - return true - } - return ap.pre.CanRefresh(user) -} - -func (ap *anonPolicy) checkVisibility(m *meta.Meta) bool { - if ap.authConfig.GetVisibility(m) == meta.VisibilityExpert { - return ap.authConfig.GetExpertMode() - } - return true -} DELETED auth/policy/box.go Index: auth/policy/box.go ================================================================== --- auth/policy/box.go +++ /dev/null @@ -1,171 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package policy - -import ( - "context" - - "zettelstore.de/z/auth" - "zettelstore.de/z/box" - "zettelstore.de/z/config" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/search" - "zettelstore.de/z/web/server" -) - -// BoxWithPolicy wraps the given box inside a policy box. -func BoxWithPolicy( - auth server.Auth, - manager auth.AuthzManager, - box box.Box, - authConfig config.AuthConfig, -) (box.Box, auth.Policy) { - pol := newPolicy(manager, authConfig) - return newBox(auth, box, pol), pol -} - -// polBox implements a policy box. -type polBox struct { - auth server.Auth - box box.Box - policy auth.Policy -} - -// newBox creates a new policy box. -func newBox(auth server.Auth, box box.Box, policy auth.Policy) box.Box { - return &polBox{ - auth: auth, - box: box, - policy: policy, - } -} - -func (pp *polBox) Location() string { - return pp.box.Location() -} - -func (pp *polBox) CanCreateZettel(ctx context.Context) bool { - return pp.box.CanCreateZettel(ctx) -} - -func (pp *polBox) CreateZettel(ctx context.Context, zettel domain.Zettel) (id.Zid, error) { - user := pp.auth.GetUser(ctx) - if pp.policy.CanCreate(user, zettel.Meta) { - return pp.box.CreateZettel(ctx, zettel) - } - return id.Invalid, box.NewErrNotAllowed("Create", user, id.Invalid) -} - -func (pp *polBox) GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) { - zettel, err := pp.box.GetZettel(ctx, zid) - if err != nil { - return domain.Zettel{}, err - } - user := pp.auth.GetUser(ctx) - if pp.policy.CanRead(user, zettel.Meta) { - return zettel, nil - } - return domain.Zettel{}, box.NewErrNotAllowed("GetZettel", user, zid) -} - -func (pp *polBox) GetAllZettel(ctx context.Context, zid id.Zid) ([]domain.Zettel, error) { - return pp.box.GetAllZettel(ctx, zid) -} - -func (pp *polBox) GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) { - m, err := pp.box.GetMeta(ctx, zid) - if err != nil { - return nil, err - } - user := pp.auth.GetUser(ctx) - if pp.policy.CanRead(user, m) { - return m, nil - } - return nil, box.NewErrNotAllowed("GetMeta", user, zid) -} - -func (pp *polBox) GetAllMeta(ctx context.Context, zid id.Zid) ([]*meta.Meta, error) { - return pp.box.GetAllMeta(ctx, zid) -} - -func (pp *polBox) FetchZids(ctx context.Context) (id.Set, error) { - return nil, box.NewErrNotAllowed("fetch-zids", pp.auth.GetUser(ctx), id.Invalid) -} - -func (pp *polBox) SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) { - user := pp.auth.GetUser(ctx) - canRead := pp.policy.CanRead - s = s.AddPreMatch(func(m *meta.Meta) bool { return canRead(user, m) }) - return pp.box.SelectMeta(ctx, s) -} - -func (pp *polBox) CanUpdateZettel(ctx context.Context, zettel domain.Zettel) bool { - return pp.box.CanUpdateZettel(ctx, zettel) -} - -func (pp *polBox) UpdateZettel(ctx context.Context, zettel domain.Zettel) error { - zid := zettel.Meta.Zid - user := pp.auth.GetUser(ctx) - if !zid.IsValid() { - return &box.ErrInvalidID{Zid: zid} - } - // Write existing zettel - oldMeta, err := pp.box.GetMeta(ctx, zid) - if err != nil { - return err - } - if pp.policy.CanWrite(user, oldMeta, zettel.Meta) { - return pp.box.UpdateZettel(ctx, zettel) - } - return box.NewErrNotAllowed("Write", user, zid) -} - -func (pp *polBox) AllowRenameZettel(ctx context.Context, zid id.Zid) bool { - return pp.box.AllowRenameZettel(ctx, zid) -} - -func (pp *polBox) RenameZettel(ctx context.Context, curZid, newZid id.Zid) error { - meta, err := pp.box.GetMeta(ctx, curZid) - if err != nil { - return err - } - user := pp.auth.GetUser(ctx) - if pp.policy.CanRename(user, meta) { - return pp.box.RenameZettel(ctx, curZid, newZid) - } - return box.NewErrNotAllowed("Rename", user, curZid) -} - -func (pp *polBox) CanDeleteZettel(ctx context.Context, zid id.Zid) bool { - return pp.box.CanDeleteZettel(ctx, zid) -} - -func (pp *polBox) DeleteZettel(ctx context.Context, zid id.Zid) error { - meta, err := pp.box.GetMeta(ctx, zid) - if err != nil { - return err - } - user := pp.auth.GetUser(ctx) - if pp.policy.CanDelete(user, meta) { - return pp.box.DeleteZettel(ctx, zid) - } - return box.NewErrNotAllowed("Delete", user, zid) -} - -func (pp *polBox) Refresh(ctx context.Context) error { - user := pp.auth.GetUser(ctx) - if pp.policy.CanRefresh(user) { - return pp.box.Refresh(ctx) - } - return box.NewErrNotAllowed("Refresh", user, id.Invalid) -} DELETED auth/policy/default.go Index: auth/policy/default.go ================================================================== --- auth/policy/default.go +++ /dev/null @@ -1,57 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package policy - -import ( - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/domain/meta" -) - -type defaultPolicy struct { - manager auth.AuthzManager -} - -func (*defaultPolicy) CanCreate(_, _ *meta.Meta) bool { return true } -func (*defaultPolicy) CanRead(_, _ *meta.Meta) bool { return true } -func (d *defaultPolicy) CanWrite(user, oldMeta, _ *meta.Meta) bool { - return d.canChange(user, oldMeta) -} -func (d *defaultPolicy) CanRename(user, m *meta.Meta) bool { return d.canChange(user, m) } -func (d *defaultPolicy) CanDelete(user, m *meta.Meta) bool { return d.canChange(user, m) } - -func (*defaultPolicy) CanRefresh(user *meta.Meta) bool { return user != nil } - -func (d *defaultPolicy) canChange(user, m *meta.Meta) bool { - metaRo, ok := m.Get(api.KeyReadOnly) - if !ok { - return true - } - if user == nil { - // If we are here, there is no authentication. - // See owner.go:CanWrite. - - // No authentication: check for owner-like restriction, because the user - // acts as an owner - return metaRo != api.ValueUserRoleOwner && !meta.BoolValue(metaRo) - } - - userRole := d.manager.GetUserRole(user) - switch metaRo { - case api.ValueUserRoleReader: - return userRole > meta.UserRoleReader - case api.ValueUserRoleWriter: - return userRole > meta.UserRoleWriter - case api.ValueUserRoleOwner: - return userRole > meta.UserRoleOwner - } - return !meta.BoolValue(metaRo) -} DELETED auth/policy/owner.go Index: auth/policy/owner.go ================================================================== --- auth/policy/owner.go +++ /dev/null @@ -1,163 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package policy - -import ( - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/meta" -) - -type ownerPolicy struct { - manager auth.AuthzManager - authConfig config.AuthConfig - pre auth.Policy -} - -func (o *ownerPolicy) CanCreate(user, newMeta *meta.Meta) bool { - if user == nil || !o.pre.CanCreate(user, newMeta) { - return false - } - return o.userIsOwner(user) || o.userCanCreate(user, newMeta) -} - -func (o *ownerPolicy) userCanCreate(user, newMeta *meta.Meta) bool { - if o.manager.GetUserRole(user) == meta.UserRoleReader { - return false - } - if _, ok := newMeta.Get(api.KeyUserID); ok { - return false - } - return true -} - -func (o *ownerPolicy) CanRead(user, m *meta.Meta) bool { - // No need to call o.pre.CanRead(user, meta), because it will always return true. - // Both the default and the readonly policy allow to read a zettel. - vis := o.authConfig.GetVisibility(m) - if res, ok := o.checkVisibility(user, vis); ok { - return res - } - return o.userIsOwner(user) || o.userCanRead(user, m, vis) -} - -func (o *ownerPolicy) userCanRead(user, m *meta.Meta, vis meta.Visibility) bool { - switch vis { - case meta.VisibilityOwner, meta.VisibilityExpert: - return false - case meta.VisibilityPublic: - return true - } - if user == nil { - return false - } - if _, ok := m.Get(api.KeyUserID); ok { - // Only the user can read its own zettel - return user.Zid == m.Zid - } - switch o.manager.GetUserRole(user) { - case meta.UserRoleReader, meta.UserRoleWriter, meta.UserRoleOwner: - return true - case meta.UserRoleCreator: - return vis == meta.VisibilityCreator - default: - return false - } -} - -var noChangeUser = []string{ - api.KeyID, - api.KeyRole, - api.KeyUserID, - api.KeyUserRole, -} - -func (o *ownerPolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool { - if user == nil || !o.pre.CanWrite(user, oldMeta, newMeta) { - return false - } - vis := o.authConfig.GetVisibility(oldMeta) - if res, ok := o.checkVisibility(user, vis); ok { - return res - } - if o.userIsOwner(user) { - return true - } - if !o.userCanRead(user, oldMeta, vis) { - return false - } - if _, ok := oldMeta.Get(api.KeyUserID); ok { - // Here we know, that user.Zid == newMeta.Zid (because of userCanRead) and - // user.Zid == newMeta.Zid (because oldMeta.Zid == newMeta.Zid) - for _, key := range noChangeUser { - if oldMeta.GetDefault(key, "") != newMeta.GetDefault(key, "") { - return false - } - } - return true - } - switch userRole := o.manager.GetUserRole(user); userRole { - case meta.UserRoleReader, meta.UserRoleCreator: - return false - } - return o.userCanCreate(user, newMeta) -} - -func (o *ownerPolicy) CanRename(user, m *meta.Meta) bool { - if user == nil || !o.pre.CanRename(user, m) { - return false - } - if res, ok := o.checkVisibility(user, o.authConfig.GetVisibility(m)); ok { - return res - } - return o.userIsOwner(user) -} - -func (o *ownerPolicy) CanDelete(user, m *meta.Meta) bool { - if user == nil || !o.pre.CanDelete(user, m) { - return false - } - if res, ok := o.checkVisibility(user, o.authConfig.GetVisibility(m)); ok { - return res - } - return o.userIsOwner(user) -} - -func (o *ownerPolicy) CanRefresh(user *meta.Meta) bool { - switch userRole := o.manager.GetUserRole(user); userRole { - case meta.UserRoleUnknown: - return o.authConfig.GetSimpleMode() - case meta.UserRoleCreator: - return o.authConfig.GetExpertMode() || o.authConfig.GetSimpleMode() - } - return true -} - -func (o *ownerPolicy) checkVisibility(user *meta.Meta, vis meta.Visibility) (bool, bool) { - if vis == meta.VisibilityExpert { - return o.userIsOwner(user) && o.authConfig.GetExpertMode(), true - } - return false, false -} - -func (o *ownerPolicy) userIsOwner(user *meta.Meta) bool { - if user == nil { - return false - } - if o.manager.IsOwner(user.Zid) { - return true - } - if val, ok := user.Get(api.KeyUserRole); ok && val == api.ValueUserRoleOwner { - return true - } - return false -} DELETED auth/policy/policy.go Index: auth/policy/policy.go ================================================================== --- auth/policy/policy.go +++ /dev/null @@ -1,70 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package policy provides some interfaces and implementation for authorizsation policies. -package policy - -import ( - "zettelstore.de/z/auth" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/meta" -) - -// newPolicy creates a policy based on given constraints. -func newPolicy(manager auth.AuthzManager, authConfig config.AuthConfig) auth.Policy { - var pol auth.Policy - if manager.IsReadonly() { - pol = &roPolicy{} - } else { - pol = &defaultPolicy{manager} - } - if manager.WithAuth() { - pol = &ownerPolicy{ - manager: manager, - authConfig: authConfig, - pre: pol, - } - } else { - pol = &anonPolicy{ - authConfig: authConfig, - pre: pol, - } - } - return &prePolicy{pol} -} - -type prePolicy struct { - post auth.Policy -} - -func (p *prePolicy) CanCreate(user, newMeta *meta.Meta) bool { - return newMeta != nil && p.post.CanCreate(user, newMeta) -} - -func (p *prePolicy) CanRead(user, m *meta.Meta) bool { - return m != nil && p.post.CanRead(user, m) -} - -func (p *prePolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool { - return oldMeta != nil && newMeta != nil && oldMeta.Zid == newMeta.Zid && - p.post.CanWrite(user, oldMeta, newMeta) -} - -func (p *prePolicy) CanRename(user, m *meta.Meta) bool { - return m != nil && p.post.CanRename(user, m) -} - -func (p *prePolicy) CanDelete(user, m *meta.Meta) bool { - return m != nil && p.post.CanDelete(user, m) -} - -func (p *prePolicy) CanRefresh(user *meta.Meta) bool { - return p.post.CanRefresh(user) -} DELETED auth/policy/policy_test.go Index: auth/policy/policy_test.go ================================================================== --- auth/policy/policy_test.go +++ /dev/null @@ -1,717 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package policy - -import ( - "fmt" - "testing" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -func TestPolicies(t *testing.T) { - t.Parallel() - testScene := []struct { - readonly bool - withAuth bool - expert bool - simple bool - }{ - {true, true, true, true}, - {true, true, true, false}, - {true, true, false, true}, - {true, true, false, false}, - {true, false, true, true}, - {true, false, true, false}, - {true, false, false, true}, - {true, false, false, false}, - {false, true, true, true}, - {false, true, true, false}, - {false, true, false, true}, - {false, true, false, false}, - {false, false, true, true}, - {false, false, true, false}, - {false, false, false, true}, - {false, false, false, false}, - } - for _, ts := range testScene { - pol := newPolicy( - &testAuthzManager{readOnly: ts.readonly, withAuth: ts.withAuth}, - &authConfig{simple: ts.simple, expert: ts.expert}, - ) - name := fmt.Sprintf("readonly=%v/withauth=%v/expert=%v/simple=%v", - ts.readonly, ts.withAuth, ts.expert, ts.simple) - t.Run(name, func(tt *testing.T) { - testCreate(tt, pol, ts.withAuth, ts.readonly) - testRead(tt, pol, ts.withAuth, ts.expert) - testWrite(tt, pol, ts.withAuth, ts.readonly, ts.expert) - testRename(tt, pol, ts.withAuth, ts.readonly, ts.expert) - testDelete(tt, pol, ts.withAuth, ts.readonly, ts.expert) - testRefresh(tt, pol, ts.withAuth, ts.expert, ts.simple) - }) - } -} - -type testAuthzManager struct { - readOnly bool - withAuth bool -} - -func (a *testAuthzManager) IsReadonly() bool { return a.readOnly } -func (*testAuthzManager) Owner() id.Zid { return ownerZid } -func (*testAuthzManager) IsOwner(zid id.Zid) bool { return zid == ownerZid } - -func (a *testAuthzManager) WithAuth() bool { return a.withAuth } - -func (a *testAuthzManager) GetUserRole(user *meta.Meta) meta.UserRole { - if user == nil { - if a.WithAuth() { - return meta.UserRoleUnknown - } - return meta.UserRoleOwner - } - if a.IsOwner(user.Zid) { - return meta.UserRoleOwner - } - if val, ok := user.Get(api.KeyUserRole); ok { - if ur := meta.GetUserRole(val); ur != meta.UserRoleUnknown { - return ur - } - } - return meta.UserRoleReader -} - -type authConfig struct{ simple, expert bool } - -func (ac *authConfig) GetSimpleMode() bool { return ac.simple } -func (ac *authConfig) GetExpertMode() bool { return ac.expert } - -func (*authConfig) GetVisibility(m *meta.Meta) meta.Visibility { - if vis, ok := m.Get(api.KeyVisibility); ok { - return meta.GetVisibility(vis) - } - return meta.VisibilityLogin -} - -func testCreate(t *testing.T, pol auth.Policy, withAuth, readonly bool) { - t.Helper() - anonUser := newAnon() - creator := newCreator() - reader := newReader() - writer := newWriter() - owner := newOwner() - owner2 := newOwner2() - zettel := newZettel() - userZettel := newUserZettel() - testCases := []struct { - user *meta.Meta - meta *meta.Meta - exp bool - }{ - // No meta - {anonUser, nil, false}, - {creator, nil, false}, - {reader, nil, false}, - {writer, nil, false}, - {owner, nil, false}, - {owner2, nil, false}, - // Ordinary zettel - {anonUser, zettel, !withAuth && !readonly}, - {creator, zettel, !readonly}, - {reader, zettel, !withAuth && !readonly}, - {writer, zettel, !readonly}, - {owner, zettel, !readonly}, - {owner2, zettel, !readonly}, - // User zettel - {anonUser, userZettel, !withAuth && !readonly}, - {creator, userZettel, !withAuth && !readonly}, - {reader, userZettel, !withAuth && !readonly}, - {writer, userZettel, !withAuth && !readonly}, - {owner, userZettel, !readonly}, - {owner2, userZettel, !readonly}, - } - for _, tc := range testCases { - t.Run("Create", func(tt *testing.T) { - got := pol.CanCreate(tc.user, tc.meta) - if tc.exp != got { - tt.Errorf("exp=%v, but got=%v", tc.exp, got) - } - }) - } -} - -func testRead(t *testing.T, pol auth.Policy, withAuth, expert bool) { - t.Helper() - anonUser := newAnon() - creator := newCreator() - reader := newReader() - writer := newWriter() - owner := newOwner() - owner2 := newOwner2() - zettel := newZettel() - publicZettel := newPublicZettel() - creatorZettel := newCreatorZettel() - loginZettel := newLoginZettel() - ownerZettel := newOwnerZettel() - expertZettel := newExpertZettel() - userZettel := newUserZettel() - testCases := []struct { - user *meta.Meta - meta *meta.Meta - exp bool - }{ - // No meta - {anonUser, nil, false}, - {creator, nil, false}, - {reader, nil, false}, - {writer, nil, false}, - {owner, nil, false}, - {owner2, nil, false}, - // Ordinary zettel - {anonUser, zettel, !withAuth}, - {creator, zettel, !withAuth}, - {reader, zettel, true}, - {writer, zettel, true}, - {owner, zettel, true}, - {owner2, zettel, true}, - // Public zettel - {anonUser, publicZettel, true}, - {creator, publicZettel, true}, - {reader, publicZettel, true}, - {writer, publicZettel, true}, - {owner, publicZettel, true}, - {owner2, publicZettel, true}, - // Creator zettel - {anonUser, creatorZettel, !withAuth}, - {creator, creatorZettel, true}, - {reader, creatorZettel, true}, - {writer, creatorZettel, true}, - {owner, creatorZettel, true}, - {owner2, creatorZettel, true}, - // Login zettel - {anonUser, loginZettel, !withAuth}, - {creator, loginZettel, !withAuth}, - {reader, loginZettel, true}, - {writer, loginZettel, true}, - {owner, loginZettel, true}, - {owner2, loginZettel, true}, - // Owner zettel - {anonUser, ownerZettel, !withAuth}, - {creator, ownerZettel, !withAuth}, - {reader, ownerZettel, !withAuth}, - {writer, ownerZettel, !withAuth}, - {owner, ownerZettel, true}, - {owner2, ownerZettel, true}, - // Expert zettel - {anonUser, expertZettel, !withAuth && expert}, - {creator, expertZettel, !withAuth && expert}, - {reader, expertZettel, !withAuth && expert}, - {writer, expertZettel, !withAuth && expert}, - {owner, expertZettel, expert}, - {owner2, expertZettel, expert}, - // Other user zettel - {anonUser, userZettel, !withAuth}, - {creator, userZettel, !withAuth}, - {reader, userZettel, !withAuth}, - {writer, userZettel, !withAuth}, - {owner, userZettel, true}, - {owner2, userZettel, true}, - // Own user zettel - {creator, creator, true}, - {reader, reader, true}, - {writer, writer, true}, - {owner, owner, true}, - {owner, owner2, true}, - {owner2, owner, true}, - {owner2, owner2, true}, - } - for _, tc := range testCases { - t.Run("Read", func(tt *testing.T) { - got := pol.CanRead(tc.user, tc.meta) - if tc.exp != got { - tt.Errorf("exp=%v, but got=%v", tc.exp, got) - } - }) - } -} - -func testWrite(t *testing.T, pol auth.Policy, withAuth, readonly, expert bool) { - t.Helper() - anonUser := newAnon() - creator := newCreator() - reader := newReader() - writer := newWriter() - owner := newOwner() - owner2 := newOwner2() - zettel := newZettel() - publicZettel := newPublicZettel() - loginZettel := newLoginZettel() - ownerZettel := newOwnerZettel() - expertZettel := newExpertZettel() - userZettel := newUserZettel() - writerNew := writer.Clone() - writerNew.Set(api.KeyUserRole, owner.GetDefault(api.KeyUserRole, "")) - roFalse := newRoFalseZettel() - roTrue := newRoTrueZettel() - roReader := newRoReaderZettel() - roWriter := newRoWriterZettel() - roOwner := newRoOwnerZettel() - notAuthNotReadonly := !withAuth && !readonly - testCases := []struct { - user *meta.Meta - old *meta.Meta - new *meta.Meta - exp bool - }{ - // No old and new meta - {anonUser, nil, nil, false}, - {creator, nil, nil, false}, - {reader, nil, nil, false}, - {writer, nil, nil, false}, - {owner, nil, nil, false}, - {owner2, nil, nil, false}, - // No old meta - {anonUser, nil, zettel, false}, - {creator, nil, zettel, false}, - {reader, nil, zettel, false}, - {writer, nil, zettel, false}, - {owner, nil, zettel, false}, - {owner2, nil, zettel, false}, - // No new meta - {anonUser, zettel, nil, false}, - {creator, zettel, nil, false}, - {reader, zettel, nil, false}, - {writer, zettel, nil, false}, - {owner, zettel, nil, false}, - {owner2, zettel, nil, false}, - // Old an new zettel have different zettel identifier - {anonUser, zettel, publicZettel, false}, - {creator, zettel, publicZettel, false}, - {reader, zettel, publicZettel, false}, - {writer, zettel, publicZettel, false}, - {owner, zettel, publicZettel, false}, - {owner2, zettel, publicZettel, false}, - // Overwrite a normal zettel - {anonUser, zettel, zettel, notAuthNotReadonly}, - {creator, zettel, zettel, notAuthNotReadonly}, - {reader, zettel, zettel, notAuthNotReadonly}, - {writer, zettel, zettel, !readonly}, - {owner, zettel, zettel, !readonly}, - {owner2, zettel, zettel, !readonly}, - // Public zettel - {anonUser, publicZettel, publicZettel, notAuthNotReadonly}, - {creator, publicZettel, publicZettel, notAuthNotReadonly}, - {reader, publicZettel, publicZettel, notAuthNotReadonly}, - {writer, publicZettel, publicZettel, !readonly}, - {owner, publicZettel, publicZettel, !readonly}, - {owner2, publicZettel, publicZettel, !readonly}, - // Login zettel - {anonUser, loginZettel, loginZettel, notAuthNotReadonly}, - {creator, loginZettel, loginZettel, notAuthNotReadonly}, - {reader, loginZettel, loginZettel, notAuthNotReadonly}, - {writer, loginZettel, loginZettel, !readonly}, - {owner, loginZettel, loginZettel, !readonly}, - {owner2, loginZettel, loginZettel, !readonly}, - // Owner zettel - {anonUser, ownerZettel, ownerZettel, notAuthNotReadonly}, - {creator, ownerZettel, ownerZettel, notAuthNotReadonly}, - {reader, ownerZettel, ownerZettel, notAuthNotReadonly}, - {writer, ownerZettel, ownerZettel, notAuthNotReadonly}, - {owner, ownerZettel, ownerZettel, !readonly}, - {owner2, ownerZettel, ownerZettel, !readonly}, - // Expert zettel - {anonUser, expertZettel, expertZettel, notAuthNotReadonly && expert}, - {creator, expertZettel, expertZettel, notAuthNotReadonly && expert}, - {reader, expertZettel, expertZettel, notAuthNotReadonly && expert}, - {writer, expertZettel, expertZettel, notAuthNotReadonly && expert}, - {owner, expertZettel, expertZettel, !readonly && expert}, - {owner2, expertZettel, expertZettel, !readonly && expert}, - // Other user zettel - {anonUser, userZettel, userZettel, notAuthNotReadonly}, - {creator, userZettel, userZettel, notAuthNotReadonly}, - {reader, userZettel, userZettel, notAuthNotReadonly}, - {writer, userZettel, userZettel, notAuthNotReadonly}, - {owner, userZettel, userZettel, !readonly}, - {owner2, userZettel, userZettel, !readonly}, - // Own user zettel - {creator, creator, creator, !readonly}, - {reader, reader, reader, !readonly}, - {writer, writer, writer, !readonly}, - {owner, owner, owner, !readonly}, - {owner2, owner2, owner2, !readonly}, - // Writer cannot change importand metadata of its own user zettel - {writer, writer, writerNew, notAuthNotReadonly}, - // No r/o zettel - {anonUser, roFalse, roFalse, notAuthNotReadonly}, - {creator, roFalse, roFalse, notAuthNotReadonly}, - {reader, roFalse, roFalse, notAuthNotReadonly}, - {writer, roFalse, roFalse, !readonly}, - {owner, roFalse, roFalse, !readonly}, - {owner2, roFalse, roFalse, !readonly}, - // Reader r/o zettel - {anonUser, roReader, roReader, false}, - {creator, roReader, roReader, false}, - {reader, roReader, roReader, false}, - {writer, roReader, roReader, !readonly}, - {owner, roReader, roReader, !readonly}, - {owner2, roReader, roReader, !readonly}, - // Writer r/o zettel - {anonUser, roWriter, roWriter, false}, - {creator, roWriter, roWriter, false}, - {reader, roWriter, roWriter, false}, - {writer, roWriter, roWriter, false}, - {owner, roWriter, roWriter, !readonly}, - {owner2, roWriter, roWriter, !readonly}, - // Owner r/o zettel - {anonUser, roOwner, roOwner, false}, - {creator, roOwner, roOwner, false}, - {reader, roOwner, roOwner, false}, - {writer, roOwner, roOwner, false}, - {owner, roOwner, roOwner, false}, - {owner2, roOwner, roOwner, false}, - // r/o = true zettel - {anonUser, roTrue, roTrue, false}, - {creator, roTrue, roTrue, false}, - {reader, roTrue, roTrue, false}, - {writer, roTrue, roTrue, false}, - {owner, roTrue, roTrue, false}, - {owner2, roTrue, roTrue, false}, - } - for _, tc := range testCases { - t.Run("Write", func(tt *testing.T) { - got := pol.CanWrite(tc.user, tc.old, tc.new) - if tc.exp != got { - tt.Errorf("exp=%v, but got=%v", tc.exp, got) - } - }) - } -} - -func testRename(t *testing.T, pol auth.Policy, withAuth, readonly, expert bool) { - t.Helper() - anonUser := newAnon() - creator := newCreator() - reader := newReader() - writer := newWriter() - owner := newOwner() - owner2 := newOwner2() - zettel := newZettel() - expertZettel := newExpertZettel() - roFalse := newRoFalseZettel() - roTrue := newRoTrueZettel() - roReader := newRoReaderZettel() - roWriter := newRoWriterZettel() - roOwner := newRoOwnerZettel() - notAuthNotReadonly := !withAuth && !readonly - testCases := []struct { - user *meta.Meta - meta *meta.Meta - exp bool - }{ - // No meta - {anonUser, nil, false}, - {creator, nil, false}, - {reader, nil, false}, - {writer, nil, false}, - {owner, nil, false}, - {owner2, nil, false}, - // Any zettel - {anonUser, zettel, notAuthNotReadonly}, - {creator, zettel, notAuthNotReadonly}, - {reader, zettel, notAuthNotReadonly}, - {writer, zettel, notAuthNotReadonly}, - {owner, zettel, !readonly}, - {owner2, zettel, !readonly}, - // Expert zettel - {anonUser, expertZettel, notAuthNotReadonly && expert}, - {creator, expertZettel, notAuthNotReadonly && expert}, - {reader, expertZettel, notAuthNotReadonly && expert}, - {writer, expertZettel, notAuthNotReadonly && expert}, - {owner, expertZettel, !readonly && expert}, - {owner2, expertZettel, !readonly && expert}, - // No r/o zettel - {anonUser, roFalse, notAuthNotReadonly}, - {creator, roFalse, notAuthNotReadonly}, - {reader, roFalse, notAuthNotReadonly}, - {writer, roFalse, notAuthNotReadonly}, - {owner, roFalse, !readonly}, - {owner2, roFalse, !readonly}, - // Reader r/o zettel - {anonUser, roReader, false}, - {creator, roReader, false}, - {reader, roReader, false}, - {writer, roReader, notAuthNotReadonly}, - {owner, roReader, !readonly}, - {owner2, roReader, !readonly}, - // Writer r/o zettel - {anonUser, roWriter, false}, - {creator, roWriter, false}, - {reader, roWriter, false}, - {writer, roWriter, false}, - {owner, roWriter, !readonly}, - {owner2, roWriter, !readonly}, - // Owner r/o zettel - {anonUser, roOwner, false}, - {creator, roOwner, false}, - {reader, roOwner, false}, - {writer, roOwner, false}, - {owner, roOwner, false}, - {owner2, roOwner, false}, - // r/o = true zettel - {anonUser, roTrue, false}, - {creator, roTrue, false}, - {reader, roTrue, false}, - {writer, roTrue, false}, - {owner, roTrue, false}, - {owner2, roTrue, false}, - } - for _, tc := range testCases { - t.Run("Rename", func(tt *testing.T) { - got := pol.CanRename(tc.user, tc.meta) - if tc.exp != got { - tt.Errorf("exp=%v, but got=%v", tc.exp, got) - } - }) - } -} - -func testDelete(t *testing.T, pol auth.Policy, withAuth, readonly, expert bool) { - t.Helper() - anonUser := newAnon() - creator := newCreator() - reader := newReader() - writer := newWriter() - owner := newOwner() - owner2 := newOwner2() - zettel := newZettel() - expertZettel := newExpertZettel() - roFalse := newRoFalseZettel() - roTrue := newRoTrueZettel() - roReader := newRoReaderZettel() - roWriter := newRoWriterZettel() - roOwner := newRoOwnerZettel() - notAuthNotReadonly := !withAuth && !readonly - testCases := []struct { - user *meta.Meta - meta *meta.Meta - exp bool - }{ - // No meta - {anonUser, nil, false}, - {creator, nil, false}, - {reader, nil, false}, - {writer, nil, false}, - {owner, nil, false}, - {owner2, nil, false}, - // Any zettel - {anonUser, zettel, notAuthNotReadonly}, - {creator, zettel, notAuthNotReadonly}, - {reader, zettel, notAuthNotReadonly}, - {writer, zettel, notAuthNotReadonly}, - {owner, zettel, !readonly}, - {owner2, zettel, !readonly}, - // Expert zettel - {anonUser, expertZettel, notAuthNotReadonly && expert}, - {creator, expertZettel, notAuthNotReadonly && expert}, - {reader, expertZettel, notAuthNotReadonly && expert}, - {writer, expertZettel, notAuthNotReadonly && expert}, - {owner, expertZettel, !readonly && expert}, - {owner2, expertZettel, !readonly && expert}, - // No r/o zettel - {anonUser, roFalse, notAuthNotReadonly}, - {creator, roFalse, notAuthNotReadonly}, - {reader, roFalse, notAuthNotReadonly}, - {writer, roFalse, notAuthNotReadonly}, - {owner, roFalse, !readonly}, - {owner2, roFalse, !readonly}, - // Reader r/o zettel - {anonUser, roReader, false}, - {creator, roReader, false}, - {reader, roReader, false}, - {writer, roReader, notAuthNotReadonly}, - {owner, roReader, !readonly}, - {owner2, roReader, !readonly}, - // Writer r/o zettel - {anonUser, roWriter, false}, - {creator, roWriter, false}, - {reader, roWriter, false}, - {writer, roWriter, false}, - {owner, roWriter, !readonly}, - {owner2, roWriter, !readonly}, - // Owner r/o zettel - {anonUser, roOwner, false}, - {creator, roOwner, false}, - {reader, roOwner, false}, - {writer, roOwner, false}, - {owner, roOwner, false}, - {owner2, roOwner, false}, - // r/o = true zettel - {anonUser, roTrue, false}, - {creator, roTrue, false}, - {reader, roTrue, false}, - {writer, roTrue, false}, - {owner, roTrue, false}, - {owner2, roTrue, false}, - } - for _, tc := range testCases { - t.Run("Delete", func(tt *testing.T) { - got := pol.CanDelete(tc.user, tc.meta) - if tc.exp != got { - tt.Errorf("exp=%v, but got=%v", tc.exp, got) - } - }) - } -} - -func testRefresh(t *testing.T, pol auth.Policy, withAuth, expert, simple bool) { - t.Helper() - testCases := []struct { - user *meta.Meta - exp bool - }{ - {newAnon(), (!withAuth && expert) || simple}, - {newCreator(), !withAuth || expert || simple}, - {newReader(), true}, - {newWriter(), true}, - {newOwner(), true}, - {newOwner2(), true}, - } - for _, tc := range testCases { - t.Run("Refresh", func(tt *testing.T) { - got := pol.CanRefresh(tc.user) - if tc.exp != got { - tt.Errorf("exp=%v, but got=%v", tc.exp, got) - } - }) - } -} - -const ( - creatorZid = id.Zid(1013) - readerZid = id.Zid(1013) - writerZid = id.Zid(1015) - ownerZid = id.Zid(1017) - owner2Zid = id.Zid(1019) - zettelZid = id.Zid(1021) - visZid = id.Zid(1023) - userZid = id.Zid(1025) -) - -func newAnon() *meta.Meta { return nil } -func newCreator() *meta.Meta { - user := meta.New(creatorZid) - user.Set(api.KeyTitle, "Creator") - user.Set(api.KeyUserID, "ceator") - user.Set(api.KeyUserRole, api.ValueUserRoleCreator) - return user -} -func newReader() *meta.Meta { - user := meta.New(readerZid) - user.Set(api.KeyTitle, "Reader") - user.Set(api.KeyUserID, "reader") - user.Set(api.KeyUserRole, api.ValueUserRoleReader) - return user -} -func newWriter() *meta.Meta { - user := meta.New(writerZid) - user.Set(api.KeyTitle, "Writer") - user.Set(api.KeyUserID, "writer") - user.Set(api.KeyUserRole, api.ValueUserRoleWriter) - return user -} -func newOwner() *meta.Meta { - user := meta.New(ownerZid) - user.Set(api.KeyTitle, "Owner") - user.Set(api.KeyUserID, "owner") - user.Set(api.KeyUserRole, api.ValueUserRoleOwner) - return user -} -func newOwner2() *meta.Meta { - user := meta.New(owner2Zid) - user.Set(api.KeyTitle, "Owner 2") - user.Set(api.KeyUserID, "owner-2") - user.Set(api.KeyUserRole, api.ValueUserRoleOwner) - return user -} -func newZettel() *meta.Meta { - m := meta.New(zettelZid) - m.Set(api.KeyTitle, "Any Zettel") - return m -} -func newPublicZettel() *meta.Meta { - m := meta.New(visZid) - m.Set(api.KeyTitle, "Public Zettel") - m.Set(api.KeyVisibility, api.ValueVisibilityPublic) - return m -} -func newCreatorZettel() *meta.Meta { - m := meta.New(visZid) - m.Set(api.KeyTitle, "Creator Zettel") - m.Set(api.KeyVisibility, api.ValueVisibilityCreator) - return m -} -func newLoginZettel() *meta.Meta { - m := meta.New(visZid) - m.Set(api.KeyTitle, "Login Zettel") - m.Set(api.KeyVisibility, api.ValueVisibilityLogin) - return m -} -func newOwnerZettel() *meta.Meta { - m := meta.New(visZid) - m.Set(api.KeyTitle, "Owner Zettel") - m.Set(api.KeyVisibility, api.ValueVisibilityOwner) - return m -} -func newExpertZettel() *meta.Meta { - m := meta.New(visZid) - m.Set(api.KeyTitle, "Expert Zettel") - m.Set(api.KeyVisibility, api.ValueVisibilityExpert) - return m -} -func newRoFalseZettel() *meta.Meta { - m := meta.New(zettelZid) - m.Set(api.KeyTitle, "No r/o Zettel") - m.Set(api.KeyReadOnly, api.ValueFalse) - return m -} -func newRoTrueZettel() *meta.Meta { - m := meta.New(zettelZid) - m.Set(api.KeyTitle, "A r/o Zettel") - m.Set(api.KeyReadOnly, api.ValueTrue) - return m -} -func newRoReaderZettel() *meta.Meta { - m := meta.New(zettelZid) - m.Set(api.KeyTitle, "Reader r/o Zettel") - m.Set(api.KeyReadOnly, api.ValueUserRoleReader) - return m -} -func newRoWriterZettel() *meta.Meta { - m := meta.New(zettelZid) - m.Set(api.KeyTitle, "Writer r/o Zettel") - m.Set(api.KeyReadOnly, api.ValueUserRoleWriter) - return m -} -func newRoOwnerZettel() *meta.Meta { - m := meta.New(zettelZid) - m.Set(api.KeyTitle, "Owner r/o Zettel") - m.Set(api.KeyReadOnly, api.ValueUserRoleOwner) - return m -} -func newUserZettel() *meta.Meta { - m := meta.New(userZid) - m.Set(api.KeyTitle, "Any User") - m.Set(api.KeyUserID, "any") - return m -} DELETED auth/policy/readonly.go Index: auth/policy/readonly.go ================================================================== --- auth/policy/readonly.go +++ /dev/null @@ -1,22 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package policy - -import "zettelstore.de/z/domain/meta" - -type roPolicy struct{} - -func (*roPolicy) CanCreate(_, _ *meta.Meta) bool { return false } -func (*roPolicy) CanRead(_, _ *meta.Meta) bool { return true } -func (*roPolicy) CanWrite(_, _, _ *meta.Meta) bool { return false } -func (*roPolicy) CanRename(_, _ *meta.Meta) bool { return false } -func (*roPolicy) CanDelete(_, _ *meta.Meta) bool { return false } -func (*roPolicy) CanRefresh(user *meta.Meta) bool { return user != nil } DELETED box/box.go Index: box/box.go ================================================================== --- box/box.go +++ /dev/null @@ -1,323 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package box provides a generic interface to zettel boxes. -package box - -import ( - "context" - "errors" - "fmt" - "io" - "net/url" - "strconv" - "time" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/search" -) - -// BaseBox is implemented by all Zettel boxes. -type BaseBox interface { - // Location returns some information where the box is located. - // Format is dependent of the box. - Location() string - - // CanCreateZettel returns true, if box could possibly create a new zettel. - CanCreateZettel(ctx context.Context) bool - - // CreateZettel creates a new zettel. - // Returns the new zettel id (and an error indication). - CreateZettel(ctx context.Context, zettel domain.Zettel) (id.Zid, error) - - // GetZettel retrieves a specific zettel. - GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) - - // GetMeta retrieves just the meta data of a specific zettel. - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) - - // CanUpdateZettel returns true, if box could possibly update the given zettel. - CanUpdateZettel(ctx context.Context, zettel domain.Zettel) bool - - // UpdateZettel updates an existing zettel. - UpdateZettel(ctx context.Context, zettel domain.Zettel) error - - // AllowRenameZettel returns true, if box will not disallow renaming the zettel. - AllowRenameZettel(ctx context.Context, zid id.Zid) bool - - // RenameZettel changes the current Zid to a new Zid. - RenameZettel(ctx context.Context, curZid, newZid id.Zid) error - - // CanDeleteZettel returns true, if box could possibly delete the given zettel. - CanDeleteZettel(ctx context.Context, zid id.Zid) bool - - // DeleteZettel removes the zettel from the box. - DeleteZettel(ctx context.Context, zid id.Zid) error -} - -// ZidFunc is a function that processes identifier of a zettel. -type ZidFunc func(id.Zid) - -// MetaFunc is a function that processes metadata of a zettel. -type MetaFunc func(*meta.Meta) - -// ManagedBox is the interface of managed boxes. -type ManagedBox interface { - BaseBox - - // Apply identifier of every zettel to the given function, if predicate returns true. - ApplyZid(context.Context, ZidFunc, search.RetrievePredicate) error - - // Apply metadata of every zettel to the given function, if predicate returns true. - ApplyMeta(context.Context, MetaFunc, search.RetrievePredicate) error - - // ReadStats populates st with box statistics - ReadStats(st *ManagedBoxStats) -} - -// ManagedBoxStats records statistics about the box. -type ManagedBoxStats struct { - // ReadOnly indicates that the content of a box cannot change. - ReadOnly bool - - // Zettel is the number of zettel managed by the box. - Zettel int -} - -// StartStopper performs simple lifecycle management. -type StartStopper interface { - // Start the box. Now all other functions of the box are allowed. - // Starting an already started box is not allowed. - Start(ctx context.Context) error - - // Stop the started box. Now only the Start() function is allowed. - Stop(ctx context.Context) -} - -// Refresher allow to refresh their internal data. -type Refresher interface { - // Refresh the box data. - Refresh(context.Context) -} - -// Box is to be used outside the box package and its descendants. -type Box interface { - BaseBox - - // FetchZids returns the set of all zettel identifer managed by the box. - FetchZids(ctx context.Context) (id.Set, error) - - // SelectMeta returns a list of metadata that comply to the given selection criteria. - SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) - - // GetAllZettel retrieves a specific zettel from all managed boxes. - GetAllZettel(ctx context.Context, zid id.Zid) ([]domain.Zettel, error) - - // GetAllMeta retrieves the meta data of a specific zettel from all managed boxes. - GetAllMeta(ctx context.Context, zid id.Zid) ([]*meta.Meta, error) - - // Refresh the data from the box and from its managed sub-boxes. - Refresh(context.Context) error -} - -// Stats record stattistics about a box. -type Stats struct { - // ReadOnly indicates that boxes cannot be modified. - ReadOnly bool - - // NumManagedBoxes is the number of boxes managed. - NumManagedBoxes int - - // Zettel is the number of zettel managed by the box, including - // duplicates across managed boxes. - ZettelTotal int - - // LastReload stores the timestamp when a full re-index was done. - LastReload time.Time - - // DurLastReload is the duration of the last full re-index run. - DurLastReload time.Duration - - // IndexesSinceReload counts indexing a zettel since the full re-index. - IndexesSinceReload uint64 - - // ZettelIndexed is the number of zettel managed by the indexer. - ZettelIndexed int - - // IndexUpdates count the number of metadata updates. - IndexUpdates uint64 - - // IndexedWords count the different words indexed. - IndexedWords uint64 - - // IndexedUrls count the different URLs indexed. - IndexedUrls uint64 -} - -// Manager is a box-managing box. -type Manager interface { - Box - StartStopper - Subject - - // ReadStats populates st with box statistics - ReadStats(st *Stats) - - // Dump internal data to a Writer. - Dump(w io.Writer) -} - -// UpdateReason gives an indication, why the ObserverFunc was called. -type UpdateReason uint8 - -// Values for Reason -const ( - _ UpdateReason = iota - OnReload // Box was reloaded - OnUpdate // A zettel was created or changed - OnDelete // A zettel was removed -) - -// UpdateInfo contains all the data about a changed zettel. -type UpdateInfo struct { - Box Box - Reason UpdateReason - Zid id.Zid -} - -// UpdateFunc is a function to be called when a change is detected. -type UpdateFunc func(UpdateInfo) - -// Subject is a box that notifies observers about changes. -type Subject interface { - // RegisterObserver registers an observer that will be notified - // if one or all zettel are found to be changed. - RegisterObserver(UpdateFunc) -} - -// Enricher is used to update metadata by adding new properties. -type Enricher interface { - // Enrich computes additional properties and updates the given metadata. - // It is typically called by zettel reading methods. - Enrich(ctx context.Context, m *meta.Meta, boxNumber int) -} - -// NoEnrichContext will signal an enricher that nothing has to be done. -// This is useful for an Indexer, but also for some box.Box calls, when -// just the plain metadata is needed. -func NoEnrichContext(ctx context.Context) context.Context { - return context.WithValue(ctx, ctxNoEnrichKey, &ctxNoEnrichKey) -} - -type ctxNoEnrichType struct{} - -var ctxNoEnrichKey ctxNoEnrichType - -// DoNotEnrich determines if the context is marked to not enrich metadata. -func DoNotEnrich(ctx context.Context) bool { - _, ok := ctx.Value(ctxNoEnrichKey).(*ctxNoEnrichType) - return ok -} - -// ErrNotAllowed is returned if the caller is not allowed to perform the operation. -type ErrNotAllowed struct { - Op string - User *meta.Meta - Zid id.Zid -} - -// NewErrNotAllowed creates an new authorization error. -func NewErrNotAllowed(op string, user *meta.Meta, zid id.Zid) error { - return &ErrNotAllowed{ - Op: op, - User: user, - Zid: zid, - } -} - -func (err *ErrNotAllowed) Error() string { - if err.User == nil { - if err.Zid.IsValid() { - return fmt.Sprintf( - "operation %q on zettel %v not allowed for not authorized user", - err.Op, - err.Zid.String()) - } - return fmt.Sprintf("operation %q not allowed for not authorized user", err.Op) - } - if err.Zid.IsValid() { - return fmt.Sprintf( - "operation %q on zettel %v not allowed for user %v/%v", - err.Op, - err.Zid.String(), - err.User.GetDefault(api.KeyUserID, "?"), - err.User.Zid.String()) - } - return fmt.Sprintf( - "operation %q not allowed for user %v/%v", - err.Op, - err.User.GetDefault(api.KeyUserID, "?"), - err.User.Zid.String()) -} - -// Is return true, if the error is of type ErrNotAllowed. -func (*ErrNotAllowed) Is(error) bool { return true } - -// ErrStarted is returned when trying to start an already started box. -var ErrStarted = errors.New("box is already started") - -// ErrStopped is returned if calling methods on a box that was not started. -var ErrStopped = errors.New("box is stopped") - -// ErrReadOnly is returned if there is an attepmt to write to a read-only box. -var ErrReadOnly = errors.New("read-only box") - -// ErrNotFound is returned if a zettel was not found in the box. -var ErrNotFound = errors.New("zettel not found") - -// ErrConflict is returned if a box operation detected a conflict.. -// One example: if calculating a new zettel identifier takes too long. -var ErrConflict = errors.New("conflict") - -// ErrCapacity is returned if a box has reached its capacity. -var ErrCapacity = errors.New("capacity exceeded") - -// ErrInvalidID is returned if the zettel id is not appropriate for the box operation. -type ErrInvalidID struct{ Zid id.Zid } - -func (err *ErrInvalidID) Error() string { return "invalid Zettel id: " + err.Zid.String() } - -// GetQueryBool is a helper function to extract bool values from a box URI. -func GetQueryBool(u *url.URL, key string) bool { - _, ok := u.Query()[key] - return ok -} - -// GetQueryInt is a helper function to extract int values of a specified range from a box URI. -func GetQueryInt(u *url.URL, key string, min, def, max int) int { - sVal := u.Query().Get(key) - if sVal == "" { - return def - } - iVal, err := strconv.Atoi(sVal) - if err != nil { - return def - } - if iVal < min { - return min - } - if iVal > max { - return max - } - return iVal -} DELETED box/compbox/compbox.go Index: box/compbox/compbox.go ================================================================== --- box/compbox/compbox.go +++ /dev/null @@ -1,193 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package compbox provides zettel that have computed content. -package compbox - -import ( - "context" - "net/url" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/box/manager" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" - "zettelstore.de/z/search" -) - -func init() { - manager.Register( - " comp", - func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) { - return getCompBox(cdata.Number, cdata.Enricher), nil - }) -} - -type compBox struct { - log *logger.Logger - number int - enricher box.Enricher -} - -var myConfig *meta.Meta -var myZettel = map[id.Zid]struct { - meta func(id.Zid) *meta.Meta - content func(*meta.Meta) []byte -}{ - id.MustParse(api.ZidVersion): {genVersionBuildM, genVersionBuildC}, - id.MustParse(api.ZidHost): {genVersionHostM, genVersionHostC}, - id.MustParse(api.ZidOperatingSystem): {genVersionOSM, genVersionOSC}, - id.MustParse(api.ZidLog): {genLogM, genLogC}, - id.MustParse(api.ZidBoxManager): {genManagerM, genManagerC}, - id.MustParse(api.ZidMetadataKey): {genKeysM, genKeysC}, - id.MustParse(api.ZidParser): {genParserM, genParserC}, - id.MustParse(api.ZidStartupConfiguration): {genConfigZettelM, genConfigZettelC}, -} - -// Get returns the one program box. -func getCompBox(boxNumber int, mf box.Enricher) box.ManagedBox { - return &compBox{ - log: kernel.Main.GetLogger(kernel.BoxService).Clone(). - Str("box", "comp").Int("boxnum", int64(boxNumber)).Child(), - number: boxNumber, - enricher: mf, - } -} - -// Setup remembers important values. -func Setup(cfg *meta.Meta) { myConfig = cfg.Clone() } - -func (*compBox) Location() string { return "" } - -func (*compBox) CanCreateZettel(context.Context) bool { return false } - -func (cb *compBox) CreateZettel(context.Context, domain.Zettel) (id.Zid, error) { - cb.log.Trace().Err(box.ErrReadOnly).Msg("CreateZettel") - return id.Invalid, box.ErrReadOnly -} - -func (cb *compBox) GetZettel(_ context.Context, zid id.Zid) (domain.Zettel, error) { - if gen, ok := myZettel[zid]; ok && gen.meta != nil { - if m := gen.meta(zid); m != nil { - updateMeta(m) - if genContent := gen.content; genContent != nil { - cb.log.Trace().Msg("GetMeta/Content") - return domain.Zettel{ - Meta: m, - Content: domain.NewContent(genContent(m)), - }, nil - } - cb.log.Trace().Msg("GetMeta/NoContent") - return domain.Zettel{Meta: m}, nil - } - } - cb.log.Trace().Err(box.ErrNotFound).Msg("GetZettel/Err") - return domain.Zettel{}, box.ErrNotFound -} - -func (cb *compBox) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) { - if gen, ok := myZettel[zid]; ok { - if genMeta := gen.meta; genMeta != nil { - if m := genMeta(zid); m != nil { - updateMeta(m) - cb.log.Trace().Msg("GetMeta") - return m, nil - } - } - } - cb.log.Trace().Err(box.ErrNotFound).Msg("GetMeta/Err") - return nil, box.ErrNotFound -} - -func (cb *compBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint search.RetrievePredicate) error { - cb.log.Trace().Int("entries", int64(len(myZettel))).Msg("ApplyMeta") - for zid, gen := range myZettel { - if !constraint(zid) { - continue - } - if genMeta := gen.meta; genMeta != nil { - if genMeta(zid) != nil { - handle(zid) - } - } - } - return nil -} - -func (cb *compBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint search.RetrievePredicate) error { - cb.log.Trace().Int("entries", int64(len(myZettel))).Msg("ApplyMeta") - for zid, gen := range myZettel { - if !constraint(zid) { - continue - } - if genMeta := gen.meta; genMeta != nil { - if m := genMeta(zid); m != nil { - updateMeta(m) - cb.enricher.Enrich(ctx, m, cb.number) - handle(m) - } - } - } - return nil -} - -func (*compBox) CanUpdateZettel(context.Context, domain.Zettel) bool { return false } - -func (cb *compBox) UpdateZettel(context.Context, domain.Zettel) error { - cb.log.Trace().Err(box.ErrReadOnly).Msg("UpdateZettel") - return box.ErrReadOnly -} - -func (*compBox) AllowRenameZettel(_ context.Context, zid id.Zid) bool { - _, ok := myZettel[zid] - return !ok -} - -func (cb *compBox) RenameZettel(_ context.Context, curZid, _ id.Zid) error { - err := box.ErrNotFound - if _, ok := myZettel[curZid]; ok { - err = box.ErrReadOnly - } - cb.log.Trace().Err(err).Msg("RenameZettel") - return err -} - -func (*compBox) CanDeleteZettel(context.Context, id.Zid) bool { return false } - -func (cb *compBox) DeleteZettel(_ context.Context, zid id.Zid) error { - err := box.ErrNotFound - if _, ok := myZettel[zid]; ok { - err = box.ErrReadOnly - } - cb.log.Trace().Err(err).Msg("DeleteZettel") - return err -} - -func (cb *compBox) ReadStats(st *box.ManagedBoxStats) { - st.ReadOnly = true - st.Zettel = len(myZettel) - cb.log.Trace().Int("zettel", int64(st.Zettel)).Msg("ReadStats") -} - -func updateMeta(m *meta.Meta) { - if _, ok := m.Get(api.KeySyntax); !ok { - m.Set(api.KeySyntax, api.ValueSyntaxZmk) - } - m.Set(api.KeyRole, api.ValueRoleConfiguration) - m.Set(api.KeyLang, api.ValueLangEN) - m.Set(api.KeyReadOnly, api.ValueTrue) - if _, ok := m.Get(api.KeyVisibility); !ok { - m.Set(api.KeyVisibility, api.ValueVisibilityExpert) - } -} DELETED box/compbox/config.go Index: box/compbox/config.go ================================================================== --- box/compbox/config.go +++ /dev/null @@ -1,52 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package compbox - -import ( - "bytes" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -func genConfigZettelM(zid id.Zid) *meta.Meta { - if myConfig == nil { - return nil - } - m := meta.New(zid) - m.Set(api.KeyTitle, "Zettelstore Startup Configuration") - m.Set(api.KeyVisibility, api.ValueVisibilityExpert) - return m -} - -func genConfigZettelC(*meta.Meta) []byte { - var buf bytes.Buffer - for i, p := range myConfig.Pairs() { - if i > 0 { - buf.WriteByte('\n') - } - buf.WriteString("; ''") - buf.WriteString(p.Key) - buf.WriteString("''") - if p.Value != "" { - buf.WriteString("\n: ``") - for _, r := range p.Value { - if r == '`' { - buf.WriteByte('\\') - } - buf.WriteRune(r) - } - buf.WriteString("``") - } - } - return buf.Bytes() -} DELETED box/compbox/keys.go Index: box/compbox/keys.go ================================================================== --- box/compbox/keys.go +++ /dev/null @@ -1,38 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package compbox - -import ( - "bytes" - "fmt" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -func genKeysM(zid id.Zid) *meta.Meta { - m := meta.New(zid) - m.Set(api.KeyTitle, "Zettelstore Supported Metadata Keys") - m.Set(api.KeyVisibility, api.ValueVisibilityLogin) - return m -} - -func genKeysC(*meta.Meta) []byte { - keys := meta.GetSortedKeyDescriptions() - var buf bytes.Buffer - buf.WriteString("|=Name<|=Type<|=Computed?:|=Property?:\n") - for _, kd := range keys { - fmt.Fprintf(&buf, - "|%v|%v|%v|%v\n", kd.Name, kd.Type.Name, kd.IsComputed(), kd.IsProperty()) - } - return buf.Bytes() -} DELETED box/compbox/log.go Index: box/compbox/log.go ================================================================== --- box/compbox/log.go +++ /dev/null @@ -1,48 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package compbox - -import ( - "bytes" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" -) - -func genLogM(zid id.Zid) *meta.Meta { - m := meta.New(zid) - m.Set(api.KeyTitle, "Zettelstore Log") - m.Set(api.KeySyntax, api.ValueSyntaxText) - return m -} - -func genLogC(*meta.Meta) []byte { - const tsFormat = "2006-01-02 15:04:05.999999" - entries := kernel.Main.RetrieveLogEntries() - var buf bytes.Buffer - for _, entry := range entries { - ts := entry.TS.Format(tsFormat) - buf.WriteString(ts) - for j := len(ts); j < len(tsFormat); j++ { - buf.WriteByte('0') - } - buf.WriteByte(' ') - buf.WriteString(entry.Level.Format()) - buf.WriteByte(' ') - buf.WriteString(entry.Prefix) - buf.WriteByte(' ') - buf.WriteString(entry.Message) - buf.WriteByte('\n') - } - return buf.Bytes() -} DELETED box/compbox/manager.go Index: box/compbox/manager.go ================================================================== --- box/compbox/manager.go +++ /dev/null @@ -1,40 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package compbox - -import ( - "bytes" - "fmt" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" -) - -func genManagerM(zid id.Zid) *meta.Meta { - m := meta.New(zid) - m.Set(api.KeyTitle, "Zettelstore Box Manager") - return m -} - -func genManagerC(*meta.Meta) []byte { - kvl := kernel.Main.GetServiceStatistics(kernel.BoxService) - if len(kvl) == 0 { - return nil - } - var buf bytes.Buffer - buf.WriteString("|=Name|=Value>\n") - for _, kv := range kvl { - fmt.Fprintf(&buf, "| %v | %v\n", kv.Key, kv.Value) - } - return buf.Bytes() -} DELETED box/compbox/parser.go Index: box/compbox/parser.go ================================================================== --- box/compbox/parser.go +++ /dev/null @@ -1,49 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package compbox - -import ( - "bytes" - "fmt" - "sort" - "strings" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/parser" -) - -func genParserM(zid id.Zid) *meta.Meta { - m := meta.New(zid) - m.Set(api.KeyTitle, "Zettelstore Supported Parser") - m.Set(api.KeyVisibility, api.ValueVisibilityLogin) - return m -} - -func genParserC(*meta.Meta) []byte { - var buf bytes.Buffer - buf.WriteString("|=Syntax<|=Alt. Value(s):|=Text Parser?:|=Image Format?:\n") - syntaxes := parser.GetSyntaxes() - sort.Strings(syntaxes) - for _, syntax := range syntaxes { - info := parser.Get(syntax) - if info.Name != syntax { - continue - } - altNames := info.AltNames - sort.Strings(altNames) - fmt.Fprintf( - &buf, "|%v|%v|%v|%v\n", - syntax, strings.Join(altNames, ", "), info.IsTextParser, info.IsImageFormat) - } - return buf.Bytes() -} DELETED box/compbox/version.go Index: box/compbox/version.go ================================================================== --- box/compbox/version.go +++ /dev/null @@ -1,53 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package compbox - -import ( - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" -) - -func getVersionMeta(zid id.Zid, title string) *meta.Meta { - m := meta.New(zid) - m.Set(api.KeyTitle, title) - m.Set(api.KeyVisibility, api.ValueVisibilityExpert) - return m -} - -func genVersionBuildM(zid id.Zid) *meta.Meta { - m := getVersionMeta(zid, "Zettelstore Version") - m.Set(api.KeyVisibility, api.ValueVisibilityLogin) - return m -} -func genVersionBuildC(*meta.Meta) []byte { - return []byte(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreVersion).(string)) -} - -func genVersionHostM(zid id.Zid) *meta.Meta { - return getVersionMeta(zid, "Zettelstore Host") -} -func genVersionHostC(*meta.Meta) []byte { - return []byte(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreHostname).(string)) -} - -func genVersionOSM(zid id.Zid) *meta.Meta { - return getVersionMeta(zid, "Zettelstore Operating System") -} -func genVersionOSC(*meta.Meta) []byte { - goOS := kernel.Main.GetConfig(kernel.CoreService, kernel.CoreGoOS).(string) - goArch := kernel.Main.GetConfig(kernel.CoreService, kernel.CoreGoArch).(string) - result := make([]byte, 0, len(goOS)+len(goArch)+1) - result = append(result, goOS...) - result = append(result, '/') - return append(result, goArch...) -} DELETED box/constbox/base.css Index: box/constbox/base.css ================================================================== --- box/constbox/base.css +++ /dev/null @@ -1,238 +0,0 @@ -*,*::before,*::after { - box-sizing: border-box; - } - html { - font-size: 1rem; - font-family: serif; - scroll-behavior: smooth; - height: 100%; - } - body { - margin: 0; - min-height: 100vh; - line-height: 1.4; - background-color: #f8f8f8 ; - height: 100%; - } - nav.zs-menu { - background-color: hsl(210, 28%, 90%); - overflow: auto; - white-space: nowrap; - font-family: sans-serif; - padding-left: .5rem; - } - nav.zs-menu > a { - float:left; - display: block; - text-align: center; - padding:.41rem .5rem; - text-decoration: none; - color:black; - } - nav.zs-menu > a:hover, .zs-dropdown:hover button { background-color: hsl(210, 28%, 80%) } - nav.zs-menu form { float: right } - nav.zs-menu form input[type=text] { - padding: .12rem; - border: none; - margin-top: .25rem; - margin-right: .5rem; - } - .zs-dropdown { - float: left; - overflow: hidden; - } - .zs-dropdown > button { - font-size: 16px; - border: none; - outline: none; - color: black; - padding:.41rem .5rem; - background-color: inherit; - font-family: inherit; - margin: 0; - } - .zs-dropdown-content { - display: none; - position: absolute; - background-color: #f9f9f9; - min-width: 160px; - box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); - z-index: 1; - } - .zs-dropdown-content > a { - float: none; - color: black; - padding:.41rem .5rem; - text-decoration: none; - display: block; - text-align: left; - } - .zs-dropdown-content > a:hover { background-color: hsl(210, 28%, 75%) } - .zs-dropdown:hover > .zs-dropdown-content { display: block } - main { padding: 0 1rem } - article > * + * { margin-top: .5rem } - article header { - padding: 0; - margin: 0; - } - h1,h2,h3,h4,h5,h6 { font-family:sans-serif; font-weight:normal } - h1 { font-size:1.5rem; margin:.65rem 0 } - h2 { font-size:1.25rem; margin:.70rem 0 } - h3 { font-size:1.15rem; margin:.75rem 0 } - h4 { font-size:1.05rem; margin:.8rem 0; font-weight: bold } - h5 { font-size:1.05rem; margin:.8rem 0 } - h6 { font-size:1.05rem; margin:.8rem 0; font-weight: lighter } - p { margin: .5rem 0 0 0 } - ol,ul { padding-left: 1.1rem } - li,figure,figcaption,dl { margin: 0 } - dt { margin: .5rem 0 0 0 } - dt+dd { margin-top: 0 } - dd { margin: .5rem 0 0 2rem } - dd > p:first-child { margin: 0 0 0 0 } - blockquote { - border-left: 0.5rem solid lightgray; - padding-left: 1rem; - margin-left: 1rem; - margin-right: 2rem; - font-style: italic; - } - blockquote p { margin-bottom: .5rem } - blockquote cite { font-style: normal } - table { - border-collapse: collapse; - border-spacing: 0; - max-width: 100%; - } - th,td { - text-align: left; - padding: .25rem .5rem; - } - td { border-bottom: 1px solid hsl(0, 0%, 85%) } - thead th { border-bottom: 2px solid hsl(0, 0%, 70%) } - tfoot th { border-top: 2px solid hsl(0, 0%, 70%) } - main form { - padding: 0 .5em; - margin: .5em 0 0 0; - } - main form:after { - content: "."; - display: block; - height: 0; - clear: both; - visibility: hidden; - } - main form div { margin: .5em 0 0 0 } - input { font-family: monospace } - input[type="submit"],button,select { font: inherit } - label { font-family: sans-serif; font-size:.9rem } - textarea { - font-family: monospace; - resize: vertical; - width: 100%; - } - .zs-input { - padding: .5em; - display:block; - border:none; - border-bottom:1px solid #ccc; - width:100%; - } - input.zs-primary { float:right } - input.zs-secondary { float:left } - a:not([class]) { text-decoration-skip-ink: auto } - a.broken { text-decoration: line-through } - img { max-width: 100% } - img.right { float: right } - ol.zs-endnotes { - padding-top: .5rem; - border-top: 1px solid; - } - kbd { font-family:monospace } - code,pre { - font-family: monospace; - font-size: 85%; - } - code { - padding: .1rem .2rem; - background: #f0f0f0; - border: 1px solid #ccc; - border-radius: .25rem; - } - pre { - padding: .5rem .7rem; - max-width: 100%; - overflow: auto; - border: 1px solid #ccc; - border-radius: .5rem; - background: #f0f0f0; - } - pre code { - font-size: 95%; - position: relative; - padding: 0; - border: none; - } - div.zs-indication { - padding: .5rem .7rem; - max-width: 100%; - border-radius: .5rem; - border: 1px solid black; - } - div.zs-indication p:first-child { margin-top: 0 } - span.zs-indication { - border: 1px solid black; - border-radius: .25rem; - padding: .1rem .2rem; - font-size: 95%; - } - .zs-example { border-style: dotted !important } - .zs-info { - background-color: lightblue; - padding: .5rem 1rem; - } - .zs-warning { - background-color: lightyellow; - padding: .5rem 1rem; - } - .zs-error { - background-color: lightpink; - border-style: none !important; - font-weight: bold; - } - td.left,th.left { text-align:left } - td.center,th.center { text-align:center } - td.right,th.right { text-align:right } - .zs-font-size-0 { font-size:75% } - .zs-font-size-1 { font-size:83% } - .zs-font-size-2 { font-size:100% } - .zs-font-size-3 { font-size:117% } - .zs-font-size-4 { font-size:150% } - .zs-font-size-5 { font-size:200% } - .zs-deprecated { border-style: dashed; padding: .2rem } - .zs-meta { - font-size:.75rem; - color:#444; - margin-bottom:1rem; - } - .zs-meta a { color:#444 } - h1+.zs-meta { margin-top:-1rem } - nav > details { margin-top:1rem } - details > summary { - width: 100%; - background-color: #eee; - font-family:sans-serif; - } - details > ul { - margin-top:0; - padding-left:2rem; - background-color: #eee; - } - footer { padding: 0 1rem } - @media (prefers-reduced-motion: reduce) { - * { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - scroll-behavior: auto !important; - } - } DELETED box/constbox/base.mustache Index: box/constbox/base.mustache ================================================================== --- box/constbox/base.mustache +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - -{{{MetaHeader}}} - - -{{#CSSRoleURL}}{{/CSSRoleURL}} -{{Title}} - - - -
-{{{Content}}} -
-{{#FooterHTML}}{{/FooterHTML}} -{{#DebugMode}}
WARNING: Debug mode is enabled. DO NOT USE IN PRODUCTION!
{{/DebugMode}} - - DELETED box/constbox/constbox.go Index: box/constbox/constbox.go ================================================================== --- box/constbox/constbox.go +++ /dev/null @@ -1,408 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package constbox puts zettel inside the executable. -package constbox - -import ( - "context" - _ "embed" // Allow to embed file content - "net/url" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/box/manager" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" - "zettelstore.de/z/search" -) - -func init() { - manager.Register( - " const", - func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) { - return &constBox{ - log: kernel.Main.GetLogger(kernel.BoxService).Clone(). - Str("box", "const").Int("boxnum", int64(cdata.Number)).Child(), - number: cdata.Number, - zettel: constZettelMap, - enricher: cdata.Enricher, - }, nil - }) -} - -type constHeader map[string]string - -type constZettel struct { - header constHeader - content domain.Content -} - -type constBox struct { - log *logger.Logger - number int - zettel map[id.Zid]constZettel - enricher box.Enricher -} - -func (*constBox) Location() string { return "const:" } - -func (*constBox) CanCreateZettel(context.Context) bool { return false } - -func (cb *constBox) CreateZettel(context.Context, domain.Zettel) (id.Zid, error) { - cb.log.Trace().Err(box.ErrReadOnly).Msg("CreateZettel") - return id.Invalid, box.ErrReadOnly -} - -func (cb *constBox) GetZettel(_ context.Context, zid id.Zid) (domain.Zettel, error) { - if z, ok := cb.zettel[zid]; ok { - cb.log.Trace().Msg("GetZettel") - return domain.Zettel{Meta: meta.NewWithData(zid, z.header), Content: z.content}, nil - } - cb.log.Trace().Err(box.ErrNotFound).Msg("GetZettel") - return domain.Zettel{}, box.ErrNotFound -} - -func (cb *constBox) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) { - if z, ok := cb.zettel[zid]; ok { - cb.log.Trace().Msg("GetMeta") - return meta.NewWithData(zid, z.header), nil - } - cb.log.Trace().Err(box.ErrNotFound).Msg("GetMeta") - return nil, box.ErrNotFound -} - -func (cb *constBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint search.RetrievePredicate) error { - cb.log.Trace().Int("entries", int64(len(cb.zettel))).Msg("ApplyZid") - for zid := range cb.zettel { - if constraint(zid) { - handle(zid) - } - } - return nil -} - -func (cb *constBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint search.RetrievePredicate) error { - cb.log.Trace().Int("entries", int64(len(cb.zettel))).Msg("ApplyMeta") - for zid, zettel := range cb.zettel { - if constraint(zid) { - m := meta.NewWithData(zid, zettel.header) - cb.enricher.Enrich(ctx, m, cb.number) - handle(m) - } - } - return nil -} - -func (*constBox) CanUpdateZettel(context.Context, domain.Zettel) bool { return false } - -func (cb *constBox) UpdateZettel(context.Context, domain.Zettel) error { - cb.log.Trace().Err(box.ErrReadOnly).Msg("UpdateZettel") - return box.ErrReadOnly -} - -func (cb *constBox) AllowRenameZettel(_ context.Context, zid id.Zid) bool { - _, ok := cb.zettel[zid] - return !ok -} - -func (cb *constBox) RenameZettel(_ context.Context, curZid, _ id.Zid) error { - err := box.ErrNotFound - if _, ok := cb.zettel[curZid]; ok { - err = box.ErrReadOnly - } - cb.log.Trace().Err(err).Msg("RenameZettel") - return err -} - -func (*constBox) CanDeleteZettel(context.Context, id.Zid) bool { return false } - -func (cb *constBox) DeleteZettel(_ context.Context, zid id.Zid) error { - err := box.ErrNotFound - if _, ok := cb.zettel[zid]; ok { - err = box.ErrReadOnly - } - cb.log.Trace().Err(err).Msg("DeleteZettel") - return err -} - -func (cb *constBox) ReadStats(st *box.ManagedBoxStats) { - st.ReadOnly = true - st.Zettel = len(cb.zettel) - cb.log.Trace().Int("zettel", int64(st.Zettel)).Msg("ReadStats") -} - -const syntaxTemplate = "mustache" - -var constZettelMap = map[id.Zid]constZettel{ - id.ConfigurationZid: { - constHeader{ - api.KeyTitle: "Zettelstore Runtime Configuration", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: api.ValueSyntaxNone, - api.KeyVisibility: api.ValueVisibilityOwner, - }, - domain.NewContent(nil)}, - id.MustParse(api.ZidLicense): { - constHeader{ - api.KeyTitle: "Zettelstore License", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: api.ValueSyntaxText, - api.KeyLang: api.ValueLangEN, - api.KeyReadOnly: api.ValueTrue, - api.KeyVisibility: api.ValueVisibilityPublic, - }, - domain.NewContent(contentLicense)}, - id.MustParse(api.ZidAuthors): { - constHeader{ - api.KeyTitle: "Zettelstore Contributors", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: api.ValueSyntaxZmk, - api.KeyLang: api.ValueLangEN, - api.KeyReadOnly: api.ValueTrue, - api.KeyVisibility: api.ValueVisibilityLogin, - }, - domain.NewContent(contentContributors)}, - id.MustParse(api.ZidDependencies): { - constHeader{ - api.KeyTitle: "Zettelstore Dependencies", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: api.ValueSyntaxZmk, - api.KeyLang: api.ValueLangEN, - api.KeyReadOnly: api.ValueTrue, - api.KeyVisibility: api.ValueVisibilityLogin, - }, - domain.NewContent(contentDependencies)}, - id.BaseTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore Base HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentBaseMustache)}, - id.LoginTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore Login Form HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentLoginMustache)}, - id.ZettelTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore Zettel HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentZettelMustache)}, - id.InfoTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore Info HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentInfoMustache)}, - id.ContextTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore Context HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentContextMustache)}, - id.FormTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore Form HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentFormMustache)}, - id.RenameTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore Rename Form HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentRenameMustache)}, - id.DeleteTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore Delete HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentDeleteMustache)}, - id.ListTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore List Zettel HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentListZettelMustache)}, - id.RolesTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore List Roles HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentListRolesMustache)}, - id.TagsTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore List Tags HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentListTagsMustache)}, - id.ErrorTemplateZid: { - constHeader{ - api.KeyTitle: "Zettelstore Error HTML Template", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: syntaxTemplate, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(contentErrorMustache)}, - id.MustParse(api.ZidBaseCSS): { - constHeader{ - api.KeyTitle: "Zettelstore Base CSS", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: "css", - api.KeyVisibility: api.ValueVisibilityPublic, - }, - domain.NewContent(contentBaseCSS)}, - id.MustParse(api.ZidUserCSS): { - constHeader{ - api.KeyTitle: "Zettelstore User CSS", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: "css", - api.KeyVisibility: api.ValueVisibilityPublic, - }, - domain.NewContent([]byte("/* User-defined CSS */"))}, - id.RoleCSSMapZid: { - constHeader{ - api.KeyTitle: "Zettelstore Role to CSS Map", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: api.ValueSyntaxNone, - api.KeyVisibility: api.ValueVisibilityExpert, - }, - domain.NewContent(nil)}, - id.EmojiZid: { - constHeader{ - api.KeyTitle: "Zettelstore Generic Emoji", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: api.ValueSyntaxGif, - api.KeyReadOnly: api.ValueTrue, - api.KeyVisibility: api.ValueVisibilityPublic, - }, - domain.NewContent(contentEmoji)}, - id.TOCNewTemplateZid: { - constHeader{ - api.KeyTitle: "New Menu", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: api.ValueSyntaxZmk, - api.KeyLang: api.ValueLangEN, - api.KeyVisibility: api.ValueVisibilityCreator, - }, - domain.NewContent(contentNewTOCZettel)}, - id.MustParse(api.ZidTemplateNewZettel): { - constHeader{ - api.KeyTitle: "New Zettel", - api.KeyRole: api.ValueRoleZettel, - api.KeySyntax: api.ValueSyntaxZmk, - api.KeyVisibility: api.ValueVisibilityCreator, - }, - domain.NewContent(nil)}, - id.MustParse(api.ZidTemplateNewUser): { - constHeader{ - api.KeyTitle: "New User", - api.KeyRole: api.ValueRoleConfiguration, - api.KeySyntax: api.ValueSyntaxNone, - meta.NewPrefix + api.KeyCredential: "", - meta.NewPrefix + api.KeyUserID: "", - meta.NewPrefix + api.KeyUserRole: api.ValueUserRoleReader, - api.KeyVisibility: api.ValueVisibilityOwner, - }, - domain.NewContent(nil)}, - id.DefaultHomeZid: { - constHeader{ - api.KeyTitle: "Home", - api.KeyRole: api.ValueRoleZettel, - api.KeySyntax: api.ValueSyntaxZmk, - api.KeyLang: api.ValueLangEN, - }, - domain.NewContent(contentHomeZettel)}, -} - -//go:embed license.txt -var contentLicense []byte - -//go:embed contributors.zettel -var contentContributors []byte - -//go:embed dependencies.zettel -var contentDependencies []byte - -//go:embed base.mustache -var contentBaseMustache []byte - -//go:embed login.mustache -var contentLoginMustache []byte - -//go:embed zettel.mustache -var contentZettelMustache []byte - -//go:embed info.mustache -var contentInfoMustache []byte - -//go:embed context.mustache -var contentContextMustache []byte - -//go:embed form.mustache -var contentFormMustache []byte - -//go:embed rename.mustache -var contentRenameMustache []byte - -//go:embed delete.mustache -var contentDeleteMustache []byte - -//go:embed listzettel.mustache -var contentListZettelMustache []byte - -//go:embed listroles.mustache -var contentListRolesMustache []byte - -//go:embed listtags.mustache -var contentListTagsMustache []byte - -//go:embed error.mustache -var contentErrorMustache []byte - -//go:embed base.css -var contentBaseCSS []byte - -//go:embed emoji_spin.gif -var contentEmoji []byte - -//go:embed newtoc.zettel -var contentNewTOCZettel []byte - -//go:embed home.zettel -var contentHomeZettel []byte DELETED box/constbox/context.mustache Index: box/constbox/context.mustache ================================================================== --- box/constbox/context.mustache +++ /dev/null @@ -1,16 +0,0 @@ - DELETED box/constbox/contributors.zettel Index: box/constbox/contributors.zettel ================================================================== --- box/constbox/contributors.zettel +++ /dev/null @@ -1,8 +0,0 @@ -Zettelstore is a software for humans made from humans. - -=== Licensor(s) -* Detlef Stern [[mailto:ds@zettelstore.de]] -** Main author -** Maintainer - -=== Contributors DELETED box/constbox/delete.mustache Index: box/constbox/delete.mustache ================================================================== --- box/constbox/delete.mustache +++ /dev/null @@ -1,43 +0,0 @@ -
-
-

Delete Zettel {{Zid}}

-
-

Do you really want to delete this zettel?

-{{#HasShadows}} -
-

Infomation

-

If you delete this zettel, the previoulsy shadowed zettel from overlayed box {{ShadowedBox}} becomes available.

-
-{{/HasShadows}} -{{#HasIncoming}} -
-

Warning!

-

If you delete this zettel, incoming references from the following zettel will become invalid.

-
    -{{#Incoming}} -
  • {{Text}}
  • -{{/Incoming}} -
-
-{{/HasIncoming}} -{{#HasUselessFiles}} -
-

Warning!

-

Deleting this zettel will also delete the following files, so that they will not be interpreted as content for this zettel.

-
    -{{#UselessFiles}} -
  • {{{.}}}
  • -{{/UselessFiles}} -
-
-{{/HasUselessFiles}} -
-{{#MetaPairs}} -
{{Key}}:
{{Value}}
-{{/MetaPairs}} -
-
- -
-
-{{end}} DELETED box/constbox/dependencies.zettel Index: box/constbox/dependencies.zettel ================================================================== --- box/constbox/dependencies.zettel +++ /dev/null @@ -1,179 +0,0 @@ -Zettelstore is made with the help of other software and other artifacts. -Thank you very much! - -This zettel lists all of them, together with their licenses. - -=== Go runtime and associated libraries -; License -: BSD 3-Clause "New" or "Revised" License -``` -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -``` - -=== ASCIIToSVG -; URL -: [[https://github.com/asciitosvg/asciitosvg]] -; License -: MIT -; Remarks -: ASCIIToSVG was incorporated into the source code of Zettelstore, moving it into package ''zettelstore.de/z/parser/draw''. - Later, the source code was changed substantially to adapt it to the needs of Zettelstore. -``` -Copyright (c) 2015 The ASCIIToSVG Contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -``` - -=== Fsnotify -; URL -: [[https://fsnotify.org/]] -; License -: BSD 3-Clause "New" or "Revised" License -; Source -: [[https://github.com/fsnotify/fsnotify]] -``` -Copyright (c) 2012 The Go Authors. All rights reserved. -Copyright (c) 2012-2019 fsnotify Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -``` - -=== hoisie/mustache / cbroglie/mustache -; URL & Source -: [[https://github.com/hoisie/mustache]] / [[https://github.com/cbroglie/mustache]] -; License -: MIT License -; Remarks -: cbroglie/mustache is a fork from hoisie/mustache (starting with commit [f9b4cbf]). - cbroglie/mustache does not claim a copyright and includes just the license file from hoisie/mustache. - cbroglie/mustache obviously continues with the original license. - -``` -Copyright (c) 2009 Michael Hoisie - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -``` - -=== pascaldekloe/jwt -; URL & Source -: [[https://github.com/pascaldekloe/jwt]] -; License -: [[CC0 1.0 Universal|https://creativecommons.org/publicdomain/zero/1.0/legalcode]] -``` -To the extent possible under law, Pascal S. de Kloe has waived all -copyright and related or neighboring rights to JWT. This work is -published from The Netherlands. - -https://creativecommons.org/publicdomain/zero/1.0/legalcode -``` - -=== yuin/goldmark -; URL & Source -: [[https://github.com/yuin/goldmark]] -; License -: MIT License -``` -MIT License - -Copyright (c) 2019 Yusuke Inuzuka - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -``` DELETED box/constbox/emoji_spin.gif Index: box/constbox/emoji_spin.gif ================================================================== --- box/constbox/emoji_spin.gif +++ /dev/null cannot compute difference between binary files DELETED box/constbox/error.mustache Index: box/constbox/error.mustache ================================================================== --- box/constbox/error.mustache +++ /dev/null @@ -1,6 +0,0 @@ -
-
-

{{ErrorTitle}}

-
-{{ErrorText}} -
DELETED box/constbox/form.mustache Index: box/constbox/form.mustache ================================================================== --- box/constbox/form.mustache +++ /dev/null @@ -1,54 +0,0 @@ -
-
-

{{Heading}}

-
-
-
- - -
-
-
- - -{{#HasRoleData}} - -{{#RoleData}} - -{{/HasRoleData}} -
- - -
-
- - -
-
- - -{{#HasSyntaxData}} - -{{#SyntaxData}} - -{{/HasSyntaxData}}
-
-{{#IsTextContent}} - - -{{/IsTextContent}} -
-
- - -
-
-
DELETED box/constbox/home.zettel Index: box/constbox/home.zettel ================================================================== --- box/constbox/home.zettel +++ /dev/null @@ -1,43 +0,0 @@ -=== Thank you for using Zettelstore! - -You will find the lastest information about Zettelstore at [[https://zettelstore.de]]. -Check that website regulary for [[upgrades|https://zettelstore.de/home/doc/trunk/www/download.wiki]] to the latest version. -You should consult the [[change log|https://zettelstore.de/home/doc/trunk/www/changes.wiki]] before upgrading. -Sometimes, you have to edit some of your Zettelstore-related zettel before upgrading. -Since Zettelstore is currently in a development state, every upgrade might fix some of your problems. - -If you have problems concerning Zettelstore, -do not hesitate to get in [[contact with the main developer|mailto:ds@zettelstore.de]]. - -=== Reporting errors -If you have encountered an error, please include the content of the following zettel in your mail (if possible): -* [[Zettelstore Version|00000000000001]]: {{00000000000001}} -* [[Zettelstore Operating System|00000000000003]] -* [[Zettelstore Startup Configuration|00000000000096]] -* [[Zettelstore Runtime Configuration|00000000000100]] - -Additionally, you have to describe, what you have done before that error occurs -and what you have expected instead. -Please do not forget to include the error message, if there is one. - -Some of above Zettelstore zettel can only be retrieved if you enabled ""expert mode"". -Otherwise, only some zettel are linked. -To enable expert mode, edit the zettel [[Zettelstore Runtime Configuration|00000000000100]]: -please set the metadata value of the key ''expert-mode'' to true. -To do you, enter the string ''expert-mode:true'' inside the edit view of the metadata. - -=== Information about this zettel -This zettel is your home zettel. -It is part of the Zettelstore software itself. -Every time you click on the [[Home|//]] link in the menu bar, you will be redirected to this zettel. - -You can change the content of this zettel by clicking on ""Edit"" above. -This allows you to customize your home zettel. - -Alternatively, you can designate another zettel as your home zettel. -Edit the [[Zettelstore Runtime Configuration|00000000000100]] by adding the metadata key ''home-zettel''. -Its value is the identifier of the zettel that should act as the new home zettel. -You will find the identifier of each zettel between their ""Edit"" and the ""Info"" link above. -The identifier of this zettel is ''00010000000000''. -If you provide a wrong identifier, this zettel will be shown as the home zettel. -Take a look inside the manual for further details. DELETED box/constbox/info.mustache Index: box/constbox/info.mustache ================================================================== --- box/constbox/info.mustache +++ /dev/null @@ -1,67 +0,0 @@ -
-
-

Information for Zettel {{Zid}}

-WebContext -{{#CanWrite}} · Edit{{/CanWrite}} -{{#CanFolge}} · Folge{{/CanFolge}} -{{#CanCopy}} · Copy{{/CanCopy}} -{{#CanRename}}· Rename{{/CanRename}} -{{#CanDelete}}· Delete{{/CanDelete}} -
-

Interpreted Metadata

-{{#MetaData}}{{/MetaData}}
{{Key}}{{{Value}}}
-

References

-{{#HasLocLinks}} -

Local

- -{{/HasLocLinks}} -{{#HasExtLinks}} -

External

- -{{/HasExtLinks}} -

Unlinked

- -
- - -
-

Parts and encodings

- -{{#EvalMatrix}} - - -{{#Elements}} -{{/Elements}} - -{{/EvalMatrix}} -
{{Header}}{{Text}}
-

Parsed (not evaluated)

- -{{#ParseMatrix}} - - -{{#Elements}} -{{/Elements}} - -{{/ParseMatrix}} -
{{Header}}{{Text}}
-{{#HasShadowLinks}} -

Shadowed Boxes

- -{{/HasShadowLinks}} -{{#Endnotes}}{{{Endnotes}}}{{/Endnotes}} -
DELETED box/constbox/license.txt Index: box/constbox/license.txt ================================================================== --- box/constbox/license.txt +++ /dev/null @@ -1,295 +0,0 @@ -Copyright (c) 2020-2022 Detlef Stern - - Licensed under the EUPL - -Zettelstore is licensed under the European Union Public License, version 1.2 or -later (EUPL v. 1.2). The license is available in the official languages of the -EU. The English version is included here. Please see -https://joinup.ec.europa.eu/community/eupl/og_page/eupl for official -translations of the other languages. - - -------------------------------------------------------------------------------- - - -EUROPEAN UNION PUBLIC LICENCE v. 1.2 -EUPL © the European Union 2007, 2016 - -This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined -below) which is provided under the terms of this Licence. Any use of the Work, -other than as authorised under this Licence is prohibited (to the extent such -use is covered by a right of the copyright holder of the Work). - -The Work is provided under the terms of this Licence when the Licensor (as -defined below) has placed the following notice immediately following the -copyright notice for the Work: - - Licensed under the EUPL - -or has expressed by any other means his willingness to license under the EUPL. - -1. Definitions - -In this Licence, the following terms have the following meaning: - -— ‘The Licence’: this Licence. -— ‘The Original Work’: the work or software distributed or communicated by the - Licensor under this Licence, available as Source Code and also as Executable - Code as the case may be. -— ‘Derivative Works’: the works or software that could be created by the - Licensee, based upon the Original Work or modifications thereof. This Licence - does not define the extent of modification or dependence on the Original Work - required in order to classify a work as a Derivative Work; this extent is - determined by copyright law applicable in the country mentioned in Article - 15. -— ‘The Work’: the Original Work or its Derivative Works. -— ‘The Source Code’: the human-readable form of the Work which is the most - convenient for people to study and modify. -— ‘The Executable Code’: any code which has generally been compiled and which - is meant to be interpreted by a computer as a program. -— ‘The Licensor’: the natural or legal person that distributes or communicates - the Work under the Licence. -— ‘Contributor(s)’: any natural or legal person who modifies the Work under the - Licence, or otherwise contributes to the creation of a Derivative Work. -— ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of - the Work under the terms of the Licence. -— ‘Distribution’ or ‘Communication’: any act of selling, giving, lending, - renting, distributing, communicating, transmitting, or otherwise making - available, online or offline, copies of the Work or providing access to its - essential functionalities at the disposal of any other natural or legal - person. - -2. Scope of the rights granted by the Licence - -The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, -sublicensable licence to do the following, for the duration of copyright vested -in the Original Work: - -— use the Work in any circumstance and for all usage, -— reproduce the Work, -— modify the Work, and make Derivative Works based upon the Work, -— communicate to the public, including the right to make available or display - the Work or copies thereof to the public and perform publicly, as the case - may be, the Work, -— distribute the Work or copies thereof, -— lend and rent the Work or copies thereof, -— sublicense rights in the Work or copies thereof. - -Those rights can be exercised on any media, supports and formats, whether now -known or later invented, as far as the applicable law permits so. - -In the countries where moral rights apply, the Licensor waives his right to -exercise his moral right to the extent allowed by law in order to make -effective the licence of the economic rights here above listed. - -The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to -any patents held by the Licensor, to the extent necessary to make use of the -rights granted on the Work under this Licence. - -3. Communication of the Source Code - -The Licensor may provide the Work either in its Source Code form, or as -Executable Code. If the Work is provided as Executable Code, the Licensor -provides in addition a machine-readable copy of the Source Code of the Work -along with each copy of the Work that the Licensor distributes or indicates, in -a notice following the copyright notice attached to the Work, a repository -where the Source Code is easily and freely accessible for as long as the -Licensor continues to distribute or communicate the Work. - -4. Limitations on copyright - -Nothing in this Licence is intended to deprive the Licensee of the benefits -from any exception or limitation to the exclusive rights of the rights owners -in the Work, of the exhaustion of those rights or of other applicable -limitations thereto. - -5. Obligations of the Licensee - -The grant of the rights mentioned above is subject to some restrictions and -obligations imposed on the Licensee. Those obligations are the following: - -Attribution right: The Licensee shall keep intact all copyright, patent or -trademarks notices and all notices that refer to the Licence and to the -disclaimer of warranties. The Licensee must include a copy of such notices and -a copy of the Licence with every copy of the Work he/she distributes or -communicates. The Licensee must cause any Derivative Work to carry prominent -notices stating that the Work has been modified and the date of modification. - -Copyleft clause: If the Licensee distributes or communicates copies of the -Original Works or Derivative Works, this Distribution or Communication will be -done under the terms of this Licence or of a later version of this Licence -unless the Original Work is expressly distributed only under this version of -the Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee -(becoming Licensor) cannot offer or impose any additional terms or conditions -on the Work or Derivative Work that alter or restrict the terms of the Licence. - -Compatibility clause: If the Licensee Distributes or Communicates Derivative -Works or copies thereof based upon both the Work and another work licensed -under a Compatible Licence, this Distribution or Communication can be done -under the terms of this Compatible Licence. For the sake of this clause, -‘Compatible Licence’ refers to the licences listed in the appendix attached to -this Licence. Should the Licensee's obligations under the Compatible Licence -conflict with his/her obligations under this Licence, the obligations of the -Compatible Licence shall prevail. - -Provision of Source Code: When distributing or communicating copies of the -Work, the Licensee will provide a machine-readable copy of the Source Code or -indicate a repository where this Source will be easily and freely available for -as long as the Licensee continues to distribute or communicate the Work. - -Legal Protection: This Licence does not grant permission to use the trade -names, trademarks, service marks, or names of the Licensor, except as required -for reasonable and customary use in describing the origin of the Work and -reproducing the content of the copyright notice. - -6. Chain of Authorship - -The original Licensor warrants that the copyright in the Original Work granted -hereunder is owned by him/her or licensed to him/her and that he/she has the -power and authority to grant the Licence. - -Each Contributor warrants that the copyright in the modifications he/she brings -to the Work are owned by him/her or licensed to him/her and that he/she has the -power and authority to grant the Licence. - -Each time You accept the Licence, the original Licensor and subsequent -Contributors grant You a licence to their contributions to the Work, under the -terms of this Licence. - -7. Disclaimer of Warranty - -The Work is a work in progress, which is continuously improved by numerous -Contributors. It is not a finished work and may therefore contain defects or -‘bugs’ inherent to this type of development. - -For the above reason, the Work is provided under the Licence on an ‘as is’ -basis and without warranties of any kind concerning the Work, including without -limitation merchantability, fitness for a particular purpose, absence of -defects or errors, accuracy, non-infringement of intellectual property rights -other than copyright as stated in Article 6 of this Licence. - -This disclaimer of warranty is an essential part of the Licence and a condition -for the grant of any rights to the Work. - -8. Disclaimer of Liability - -Except in the cases of wilful misconduct or damages directly caused to natural -persons, the Licensor will in no event be liable for any direct or indirect, -material or moral, damages of any kind, arising out of the Licence or of the -use of the Work, including without limitation, damages for loss of goodwill, -work stoppage, computer failure or malfunction, loss of data or any commercial -damage, even if the Licensor has been advised of the possibility of such -damage. However, the Licensor will be liable under statutory product liability -laws as far such laws apply to the Work. - -9. Additional agreements - -While distributing the Work, You may choose to conclude an additional -agreement, defining obligations or services consistent with this Licence. -However, if accepting obligations, You may act only on your own behalf and on -your sole responsibility, not on behalf of the original Licensor or any other -Contributor, and only if You agree to indemnify, defend, and hold each -Contributor harmless for any liability incurred by, or claims asserted against -such Contributor by the fact You have accepted any warranty or additional -liability. - -10. Acceptance of the Licence - -The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ -placed under the bottom of a window displaying the text of this Licence or by -affirming consent in any other similar way, in accordance with the rules of -applicable law. Clicking on that icon indicates your clear and irrevocable -acceptance of this Licence and all of its terms and conditions. - -Similarly, you irrevocably accept this Licence and all of its terms and -conditions by exercising any rights granted to You by Article 2 of this -Licence, such as the use of the Work, the creation by You of a Derivative Work -or the Distribution or Communication by You of the Work or copies thereof. - -11. Information to the public - -In case of any Distribution or Communication of the Work by means of electronic -communication by You (for example, by offering to download the Work from -a remote location) the distribution channel or media (for example, a website) -must at least provide to the public the information requested by the applicable -law regarding the Licensor, the Licence and the way it may be accessible, -concluded, stored and reproduced by the Licensee. - -12. Termination of the Licence - -The Licence and the rights granted hereunder will terminate automatically upon -any breach by the Licensee of the terms of the Licence. - -Such a termination will not terminate the licences of any person who has -received the Work from the Licensee under the Licence, provided such persons -remain in full compliance with the Licence. - -13. Miscellaneous - -Without prejudice of Article 9 above, the Licence represents the complete -agreement between the Parties as to the Work. - -If any provision of the Licence is invalid or unenforceable under applicable -law, this will not affect the validity or enforceability of the Licence as -a whole. Such provision will be construed or reformed so as necessary to make -it valid and enforceable. - -The European Commission may publish other linguistic versions or new versions -of this Licence or updated versions of the Appendix, so far this is required -and reasonable, without reducing the scope of the rights granted by the -Licence. New versions of the Licence will be published with a unique version -number. - -All linguistic versions of this Licence, approved by the European Commission, -have identical value. Parties can take advantage of the linguistic version of -their choice. - -14. Jurisdiction - -Without prejudice to specific agreement between parties, - -— any litigation resulting from the interpretation of this License, arising - between the European Union institutions, bodies, offices or agencies, as - a Licensor, and any Licensee, will be subject to the jurisdiction of the - Court of Justice of the European Union, as laid down in article 272 of the - Treaty on the Functioning of the European Union, -— any litigation arising between other parties and resulting from the - interpretation of this License, will be subject to the exclusive jurisdiction - of the competent court where the Licensor resides or conducts its primary - business. - -15. Applicable Law - -Without prejudice to specific agreement between parties, - -— this Licence shall be governed by the law of the European Union Member State - where the Licensor has his seat, resides or has his registered office, -— this licence shall be governed by Belgian law if the Licensor has no seat, - residence or registered office inside a European Union Member State. - - - Appendix - - -‘Compatible Licences’ according to Article 5 EUPL are: - -— GNU General Public License (GPL) v. 2, v. 3 -— GNU Affero General Public License (AGPL) v. 3 -— Open Software License (OSL) v. 2.1, v. 3.0 -— Eclipse Public License (EPL) v. 1.0 -— CeCILL v. 2.0, v. 2.1 -— Mozilla Public Licence (MPL) v. 2 -— GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 -— Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for - works other than software -— European Union Public Licence (EUPL) v. 1.1, v. 1.2 -— Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong - Reciprocity (LiLiQ-R+) - -The European Commission may update this Appendix to later versions of the above -licences without producing a new version of the EUPL, as long as they provide -the rights granted in Article 2 of this Licence and protect the covered Source -Code from exclusive appropriation. - -All other changes or additions to this Appendix require the production of a new -EUPL version. DELETED box/constbox/listroles.mustache Index: box/constbox/listroles.mustache ================================================================== --- box/constbox/listroles.mustache +++ /dev/null @@ -1,8 +0,0 @@ - DELETED box/constbox/listtags.mustache Index: box/constbox/listtags.mustache ================================================================== --- box/constbox/listtags.mustache +++ /dev/null @@ -1,10 +0,0 @@ - DELETED box/constbox/listzettel.mustache Index: box/constbox/listzettel.mustache ================================================================== --- box/constbox/listzettel.mustache +++ /dev/null @@ -1,6 +0,0 @@ -
-

{{Title}}

-
- DELETED box/constbox/login.mustache Index: box/constbox/login.mustache ================================================================== --- box/constbox/login.mustache +++ /dev/null @@ -1,19 +0,0 @@ -
-
-

{{Title}}

-
-{{#Retry}} -
Wrong user name / password. Try again.
-{{/Retry}} -
-
- - -
-
- - -
-
-
-
DELETED box/constbox/newtoc.zettel Index: box/constbox/newtoc.zettel ================================================================== --- box/constbox/newtoc.zettel +++ /dev/null @@ -1,4 +0,0 @@ -This zettel lists all zettel that should act as a template for new zettel. -These zettel will be included in the ""New"" menu of the WebUI. -* [[New Zettel|00000000090001]] -* [[New User|00000000090002]] DELETED box/constbox/rename.mustache Index: box/constbox/rename.mustache ================================================================== --- box/constbox/rename.mustache +++ /dev/null @@ -1,41 +0,0 @@ -
-
-

Rename Zettel {{Zid}}

-
-

Do you really want to rename this zettel?

-{{#HasIncoming}} -
-

Warning!

-

If you rename this zettel, incoming references from the following zettel will become invalid.

-
    -{{#Incoming}} -
  • {{Text}}
  • -{{/Incoming}} -
-
-{{/HasIncoming}} -{{#HasUselessFiles}} -
-

Warning!

-

Renaming this zettel will also delete the following files, so that they will not be interpreted as content for a zettel with identifier {{Zid}}.

-
    -{{#UselessFiles}} -
  • {{{.}}}
  • -{{/UselessFiles}} -
-
-{{/HasUselessFiles}} -
-
- - -
- -
-
-
-{{#MetaPairs}} -
{{Key}}:
{{Value}}
-{{/MetaPairs}} -
-
DELETED box/constbox/zettel.mustache Index: box/constbox/zettel.mustache ================================================================== --- box/constbox/zettel.mustache +++ /dev/null @@ -1,41 +0,0 @@ -
-
-

{{{HTMLTitle}}}

-
-{{#CanWrite}}Edit ·{{/CanWrite}} -{{Zid}} · -Info · -({{RoleText}}) -{{#HasTags}}· {{#Tags}} {{Text}}{{/Tags}}{{/HasTags}} -{{#CanCopy}}· Copy{{/CanCopy}} -{{#CanFolge}}· Folge{{/CanFolge}} -{{#PrecursorRefs}}
Precursor: {{{PrecursorRefs}}}{{/PrecursorRefs}} -{{#HasExtURL}}
URL: {{ExtURL}}{{/HasExtURL}} -
-
-{{{Content}}} -
-{{#HasFolgeLinks}} - -{{/HasFolgeLinks}} -{{#HasBackLinks}} - -{{/HasBackLinks}} DELETED box/dirbox/dirbox.go Index: box/dirbox/dirbox.go ================================================================== --- box/dirbox/dirbox.go +++ /dev/null @@ -1,399 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package dirbox provides a directory-based zettel box. -package dirbox - -import ( - "context" - "errors" - "net/url" - "os" - "path/filepath" - "sync" - - "zettelstore.de/z/box" - "zettelstore.de/z/box/manager" - "zettelstore.de/z/box/notify" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" - "zettelstore.de/z/search" -) - -func init() { - manager.Register("dir", func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) { - var log *logger.Logger - if krnl := kernel.Main; krnl != nil { - log = krnl.GetLogger(kernel.BoxService).Clone().Str("box", "dir").Int("boxnum", int64(cdata.Number)).Child() - } - path := getDirPath(u) - if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { - return nil, err - } - dp := dirBox{ - log: log, - number: cdata.Number, - location: u.String(), - readonly: box.GetQueryBool(u, "readonly"), - cdata: *cdata, - dir: path, - notifySpec: getDirSrvInfo(log, u.Query().Get("type")), - fSrvs: makePrime(uint32(box.GetQueryInt(u, "worker", 1, 7, 1499))), - } - return &dp, nil - }) -} - -func makePrime(n uint32) uint32 { - for !isPrime(n) { - n++ - } - return n -} - -func isPrime(n uint32) bool { - if n == 0 { - return false - } - if n <= 3 { - return true - } - if n%2 == 0 { - return false - } - for i := uint32(3); i*i <= n; i += 2 { - if n%i == 0 { - return false - } - } - return true -} - -type notifyTypeSpec int - -const ( - _ notifyTypeSpec = iota - dirNotifyAny - dirNotifySimple - dirNotifyFS -) - -func getDirSrvInfo(log *logger.Logger, notifyType string) notifyTypeSpec { - for count := 0; count < 2; count++ { - switch notifyType { - case kernel.BoxDirTypeNotify: - return dirNotifyFS - case kernel.BoxDirTypeSimple: - return dirNotifySimple - default: - notifyType = kernel.Main.GetConfig(kernel.BoxService, kernel.BoxDefaultDirType).(string) - } - } - log.Error().Str("notifyType", notifyType).Msg("Unable to set notify type, using a default") - return dirNotifySimple -} - -func getDirPath(u *url.URL) string { - if u.Opaque != "" { - return filepath.Clean(u.Opaque) - } - return filepath.Clean(u.Path) -} - -// dirBox uses a directory to store zettel as files. -type dirBox struct { - log *logger.Logger - number int - location string - readonly bool - cdata manager.ConnectData - dir string - notifySpec notifyTypeSpec - dirSrv *notify.DirService - fSrvs uint32 - fCmds []chan fileCmd - mxCmds sync.RWMutex -} - -func (dp *dirBox) Location() string { - return dp.location -} - -func (dp *dirBox) Start(context.Context) error { - dp.mxCmds.Lock() - defer dp.mxCmds.Unlock() - dp.fCmds = make([]chan fileCmd, 0, dp.fSrvs) - for i := uint32(0); i < dp.fSrvs; i++ { - cc := make(chan fileCmd) - go fileService(i, dp.log.Clone().Str("sub", "file").Uint("fn", uint64(i)).Child(), dp.dir, cc) - dp.fCmds = append(dp.fCmds, cc) - } - - var notifier notify.Notifier - var err error - switch dp.notifySpec { - case dirNotifySimple: - notifier, err = notify.NewSimpleDirNotifier(dp.log.Clone().Str("notify", "simple").Child(), dp.dir) - default: - notifier, err = notify.NewFSDirNotifier(dp.log.Clone().Str("notify", "fs").Child(), dp.dir) - } - if err != nil { - dp.log.Fatal().Err(err).Msg("Unable to create directory supervisor") - dp.stopFileServices() - return err - } - dp.dirSrv = notify.NewDirService( - dp.log.Clone().Str("sub", "dirsrv").Child(), - notifier, - dp.cdata.Notify, - ) - dp.dirSrv.Start() - return nil -} - -func (dp *dirBox) Refresh(_ context.Context) { - dp.dirSrv.Refresh() - dp.log.Trace().Msg("Refresh") -} - -func (dp *dirBox) Stop(_ context.Context) { - dirSrv := dp.dirSrv - dp.dirSrv = nil - if dirSrv != nil { - dirSrv.Stop() - } - dp.stopFileServices() -} - -func (dp *dirBox) stopFileServices() { - for _, c := range dp.fCmds { - close(c) - } -} - -func (dp *dirBox) notifyChanged(reason box.UpdateReason, zid id.Zid) { - if chci := dp.cdata.Notify; chci != nil { - dp.log.Trace().Zid(zid).Uint("reason", uint64(reason)).Msg("notifyChanged") - chci <- box.UpdateInfo{Reason: reason, Zid: zid} - } -} - -func (dp *dirBox) getFileChan(zid id.Zid) chan fileCmd { - // Based on https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function - sum := 2166136261 ^ uint32(zid) - sum *= 16777619 - sum ^= uint32(zid >> 32) - sum *= 16777619 - - dp.mxCmds.RLock() - defer dp.mxCmds.RUnlock() - return dp.fCmds[sum%dp.fSrvs] -} - -func (dp *dirBox) CanCreateZettel(_ context.Context) bool { - return !dp.readonly -} - -func (dp *dirBox) CreateZettel(ctx context.Context, zettel domain.Zettel) (id.Zid, error) { - if dp.readonly { - return id.Invalid, box.ErrReadOnly - } - - newZid, err := dp.dirSrv.SetNewDirEntry() - if err != nil { - return id.Invalid, err - } - meta := zettel.Meta - meta.Zid = newZid - entry := notify.DirEntry{Zid: newZid} - dp.updateEntryFromMetaContent(&entry, meta, zettel.Content) - - err = dp.srvSetZettel(ctx, &entry, zettel) - if err == nil { - err = dp.dirSrv.UpdateDirEntry(&entry) - } - dp.notifyChanged(box.OnUpdate, meta.Zid) - dp.log.Trace().Err(err).Zid(meta.Zid).Msg("CreateZettel") - return meta.Zid, err -} - -func (dp *dirBox) GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) { - entry := dp.dirSrv.GetDirEntry(zid) - if !entry.IsValid() { - return domain.Zettel{}, box.ErrNotFound - } - m, c, err := dp.srvGetMetaContent(ctx, entry, zid) - if err != nil { - return domain.Zettel{}, err - } - zettel := domain.Zettel{Meta: m, Content: domain.NewContent(c)} - dp.log.Trace().Zid(zid).Msg("GetZettel") - return zettel, nil -} - -func (dp *dirBox) GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) { - m, err := dp.doGetMeta(ctx, zid) - dp.log.Trace().Zid(zid).Err(err).Msg("GetMeta") - return m, err -} -func (dp *dirBox) doGetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) { - entry := dp.dirSrv.GetDirEntry(zid) - if !entry.IsValid() { - return nil, box.ErrNotFound - } - m, err := dp.srvGetMeta(ctx, entry, zid) - if err != nil { - return nil, err - } - return m, nil -} - -func (dp *dirBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint search.RetrievePredicate) error { - entries := dp.dirSrv.GetDirEntries(constraint) - dp.log.Trace().Int("entries", int64(len(entries))).Msg("ApplyZid") - for _, entry := range entries { - handle(entry.Zid) - } - return nil -} - -func (dp *dirBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint search.RetrievePredicate) error { - entries := dp.dirSrv.GetDirEntries(constraint) - dp.log.Trace().Int("entries", int64(len(entries))).Msg("ApplyMeta") - - // The following loop could be parallelized if needed for performance. - for _, entry := range entries { - m, err := dp.srvGetMeta(ctx, entry, entry.Zid) - if err != nil { - dp.log.Trace().Err(err).Msg("ApplyMeta/getMeta") - return err - } - dp.cdata.Enricher.Enrich(ctx, m, dp.number) - handle(m) - } - return nil -} - -func (dp *dirBox) CanUpdateZettel(context.Context, domain.Zettel) bool { - return !dp.readonly -} - -func (dp *dirBox) UpdateZettel(ctx context.Context, zettel domain.Zettel) error { - if dp.readonly { - return box.ErrReadOnly - } - - meta := zettel.Meta - zid := meta.Zid - if !zid.IsValid() { - return &box.ErrInvalidID{Zid: zid} - } - entry := dp.dirSrv.GetDirEntry(zid) - if !entry.IsValid() { - // Existing zettel, but new in this box. - entry = ¬ify.DirEntry{Zid: zid} - } - dp.updateEntryFromMetaContent(entry, meta, zettel.Content) - dp.dirSrv.UpdateDirEntry(entry) - err := dp.srvSetZettel(ctx, entry, zettel) - if err == nil { - dp.notifyChanged(box.OnUpdate, zid) - } - dp.log.Trace().Zid(zid).Err(err).Msg("UpdateZettel") - return err -} - -func (dp *dirBox) updateEntryFromMetaContent(entry *notify.DirEntry, m *meta.Meta, content domain.Content) { - entry.SetupFromMetaContent(m, content, dp.cdata.Config.GetZettelFileSyntax) -} - -func (dp *dirBox) AllowRenameZettel(context.Context, id.Zid) bool { - return !dp.readonly -} - -func (dp *dirBox) RenameZettel(ctx context.Context, curZid, newZid id.Zid) error { - if curZid == newZid { - return nil - } - curEntry := dp.dirSrv.GetDirEntry(curZid) - if !curEntry.IsValid() { - return box.ErrNotFound - } - if dp.readonly { - return box.ErrReadOnly - } - - // Check whether zettel with new ID already exists in this box. - if _, err := dp.doGetMeta(ctx, newZid); err == nil { - return &box.ErrInvalidID{Zid: newZid} - } - - oldMeta, oldContent, err := dp.srvGetMetaContent(ctx, curEntry, curZid) - if err != nil { - return err - } - - newEntry, err := dp.dirSrv.RenameDirEntry(curEntry, newZid) - if err != nil { - return err - } - oldMeta.Zid = newZid - newZettel := domain.Zettel{Meta: oldMeta, Content: domain.NewContent(oldContent)} - if err = dp.srvSetZettel(ctx, &newEntry, newZettel); err != nil { - // "Rollback" rename. No error checking... - dp.dirSrv.RenameDirEntry(&newEntry, curZid) - return err - } - err = dp.srvDeleteZettel(ctx, curEntry, curZid) - if err == nil { - dp.notifyChanged(box.OnDelete, curZid) - dp.notifyChanged(box.OnUpdate, newZid) - } - dp.log.Trace().Zid(curZid).Zid(newZid).Err(err).Msg("RenameZettel") - return err -} - -func (dp *dirBox) CanDeleteZettel(_ context.Context, zid id.Zid) bool { - if dp.readonly { - return false - } - entry := dp.dirSrv.GetDirEntry(zid) - return entry.IsValid() -} - -func (dp *dirBox) DeleteZettel(ctx context.Context, zid id.Zid) error { - if dp.readonly { - return box.ErrReadOnly - } - - entry := dp.dirSrv.GetDirEntry(zid) - if !entry.IsValid() { - return box.ErrNotFound - } - err := dp.dirSrv.DeleteDirEntry(zid) - if err != nil { - return nil - } - err = dp.srvDeleteZettel(ctx, entry, zid) - if err == nil { - dp.notifyChanged(box.OnDelete, zid) - } - dp.log.Trace().Zid(zid).Err(err).Msg("DeleteZettel") - return err -} - -func (dp *dirBox) ReadStats(st *box.ManagedBoxStats) { - st.ReadOnly = dp.readonly - st.Zettel = dp.dirSrv.NumDirEntries() - dp.log.Trace().Int("zettel", int64(st.Zettel)).Msg("ReadStats") -} DELETED box/dirbox/dirbox_test.go Index: box/dirbox/dirbox_test.go ================================================================== --- box/dirbox/dirbox_test.go +++ /dev/null @@ -1,50 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package dirbox - -import "testing" - -func TestIsPrime(t *testing.T) { - testcases := []struct { - n uint32 - exp bool - }{ - {0, false}, {1, true}, {2, true}, {3, true}, {4, false}, {5, true}, - {6, false}, {7, true}, {8, false}, {9, false}, {10, false}, - {11, true}, {12, false}, {13, true}, {14, false}, {15, false}, - {17, true}, {19, true}, {21, false}, {23, true}, {25, false}, - {27, false}, {29, true}, {31, true}, {33, false}, {35, false}, - } - for _, tc := range testcases { - got := isPrime(tc.n) - if got != tc.exp { - t.Errorf("isPrime(%d)=%v, but got %v", tc.n, tc.exp, got) - } - } -} - -func TestMakePrime(t *testing.T) { - for i := uint32(0); i < 1500; i++ { - np := makePrime(i) - if np < i { - t.Errorf("makePrime(%d) < %d", i, np) - continue - } - if !isPrime(np) { - t.Errorf("makePrime(%d) == %d is not prime", i, np) - continue - } - if isPrime(i) && i != np { - t.Errorf("%d is already prime, but got %d as next prime", i, np) - continue - } - } -} DELETED box/dirbox/service.go Index: box/dirbox/service.go ================================================================== --- box/dirbox/service.go +++ /dev/null @@ -1,387 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package dirbox - -import ( - "context" - "io" - "os" - "path/filepath" - "time" - - "zettelstore.de/z/box/filebox" - "zettelstore.de/z/box/notify" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/input" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" -) - -func fileService(i uint32, log *logger.Logger, dirPath string, cmds <-chan fileCmd) { - // Something may panic. Ensure a running service. - defer func() { - if r := recover(); r != nil { - kernel.Main.LogRecover("FileService", r) - go fileService(i, log, dirPath, cmds) - } - }() - - log.Trace().Uint("i", uint64(i)).Str("dirpath", dirPath).Msg("File service started") - for cmd := range cmds { - cmd.run(log, dirPath) - } - log.Trace().Uint("i", uint64(i)).Str("dirpath", dirPath).Msg("File service stopped") -} - -type fileCmd interface { - run(*logger.Logger, string) -} - -const serviceTimeout = 5 * time.Second // must be shorter than the web servers timeout values for reading+writing. - -// COMMAND: srvGetMeta ---------------------------------------- -// -// Retrieves the meta data from a zettel. - -func (dp *dirBox) srvGetMeta(ctx context.Context, entry *notify.DirEntry, zid id.Zid) (*meta.Meta, error) { - rc := make(chan resGetMeta, 1) - dp.getFileChan(zid) <- &fileGetMeta{entry, rc} - ctx, cancel := context.WithTimeout(ctx, serviceTimeout) - defer cancel() - select { - case res := <-rc: - return res.meta, res.err - case <-ctx.Done(): - return nil, ctx.Err() - } -} - -type fileGetMeta struct { - entry *notify.DirEntry - rc chan<- resGetMeta -} -type resGetMeta struct { - meta *meta.Meta - err error -} - -func (cmd *fileGetMeta) run(log *logger.Logger, dirPath string) { - var m *meta.Meta - var err error - - entry := cmd.entry - zid := entry.Zid - if metaName := entry.MetaName; metaName == "" { - contentName := entry.ContentName - contentExt := entry.ContentExt - if contentName == "" || contentExt == "" { - log.Panic().Zid(zid).Msg("No meta, no content in getMeta") - } - if entry.HasMetaInContent() { - m, _, err = parseMetaContentFile(zid, filepath.Join(dirPath, contentName)) - } else { - m = filebox.CalcDefaultMeta(zid, contentExt) - } - } else { - m, err = parseMetaFile(zid, filepath.Join(dirPath, metaName)) - } - if err == nil { - cmdCleanupMeta(m, entry) - } - cmd.rc <- resGetMeta{m, err} -} - -// COMMAND: srvGetMetaContent ---------------------------------------- -// -// Retrieves the meta data and the content of a zettel. - -func (dp *dirBox) srvGetMetaContent(ctx context.Context, entry *notify.DirEntry, zid id.Zid) (*meta.Meta, []byte, error) { - rc := make(chan resGetMetaContent, 1) - dp.getFileChan(zid) <- &fileGetMetaContent{entry, rc} - ctx, cancel := context.WithTimeout(ctx, serviceTimeout) - defer cancel() - select { - case res := <-rc: - return res.meta, res.content, res.err - case <-ctx.Done(): - return nil, nil, ctx.Err() - } -} - -type fileGetMetaContent struct { - entry *notify.DirEntry - rc chan<- resGetMetaContent -} -type resGetMetaContent struct { - meta *meta.Meta - content []byte - err error -} - -func (cmd *fileGetMetaContent) run(log *logger.Logger, dirPath string) { - var m *meta.Meta - var content []byte - var err error - - entry := cmd.entry - zid := entry.Zid - contentName := entry.ContentName - contentExt := entry.ContentExt - contentPath := filepath.Join(dirPath, contentName) - if metaName := entry.MetaName; metaName == "" { - if contentName == "" || contentExt == "" { - log.Panic().Zid(zid).Msg("No meta, no content in getMetaContent") - } - if entry.HasMetaInContent() { - m, content, err = parseMetaContentFile(zid, contentPath) - } else { - m = filebox.CalcDefaultMeta(zid, contentExt) - content, err = os.ReadFile(contentPath) - } - } else { - m, err = parseMetaFile(zid, filepath.Join(dirPath, metaName)) - if contentName != "" { - var err1 error - content, err1 = os.ReadFile(contentPath) - if err == nil { - err = err1 - } - } - } - if err == nil { - cmdCleanupMeta(m, entry) - } - cmd.rc <- resGetMetaContent{m, content, err} -} - -// COMMAND: srvSetZettel ---------------------------------------- -// -// Writes a new or exsting zettel. - -func (dp *dirBox) srvSetZettel(ctx context.Context, entry *notify.DirEntry, zettel domain.Zettel) error { - rc := make(chan resSetZettel, 1) - dp.getFileChan(zettel.Meta.Zid) <- &fileSetZettel{entry, zettel, rc} - ctx, cancel := context.WithTimeout(ctx, serviceTimeout) - defer cancel() - select { - case err := <-rc: - return err - case <-ctx.Done(): - return ctx.Err() - } -} - -type fileSetZettel struct { - entry *notify.DirEntry - zettel domain.Zettel - rc chan<- resSetZettel -} -type resSetZettel = error - -func (cmd *fileSetZettel) run(log *logger.Logger, dirPath string) { - entry := cmd.entry - zid := entry.Zid - contentName := entry.ContentName - m := cmd.zettel.Meta - content := cmd.zettel.Content.AsBytes() - metaName := entry.MetaName - if metaName == "" { - if contentName == "" { - log.Panic().Zid(zid).Msg("No meta, no content in setZettel") - } - contentPath := filepath.Join(dirPath, contentName) - if entry.HasMetaInContent() { - err := writeZettelFile(contentPath, m, content) - cmd.rc <- err - return - } - err := writeFileContent(contentPath, content) - cmd.rc <- err - return - } - - err := writeMetaFile(filepath.Join(dirPath, metaName), m) - if err == nil && contentName != "" { - err = writeFileContent(filepath.Join(dirPath, contentName), content) - } - cmd.rc <- err -} - -func writeMetaFile(metaPath string, m *meta.Meta) error { - metaFile, err := openFileWrite(metaPath) - if err != nil { - return err - } - err = writeFileZid(metaFile, m.Zid) - if err == nil { - _, err = m.WriteComputed(metaFile) - } - if err1 := metaFile.Close(); err == nil { - err = err1 - } - return err -} - -func writeZettelFile(contentPath string, m *meta.Meta, content []byte) error { - zettelFile, err := openFileWrite(contentPath) - if err != nil { - return err - } - if err == nil { - err = writeMetaHeader(zettelFile, m) - } - if err == nil { - _, err = zettelFile.Write(content) - } - if err1 := zettelFile.Close(); err == nil { - err = err1 - } - return err -} - -var ( - newline = []byte{'\n'} - yamlSep = []byte{'-', '-', '-', '\n'} -) - -func writeMetaHeader(w io.Writer, m *meta.Meta) (err error) { - if m.YamlSep { - _, err = w.Write(yamlSep) - if err != nil { - return err - } - } - err = writeFileZid(w, m.Zid) - if err != nil { - return err - } - _, err = m.WriteComputed(w) - if err != nil { - return err - } - if m.YamlSep { - _, err = w.Write(yamlSep) - } else { - _, err = w.Write(newline) - } - return err -} - -// COMMAND: srvDeleteZettel ---------------------------------------- -// -// Deletes an existing zettel. - -func (dp *dirBox) srvDeleteZettel(ctx context.Context, entry *notify.DirEntry, zid id.Zid) error { - rc := make(chan resDeleteZettel, 1) - dp.getFileChan(zid) <- &fileDeleteZettel{entry, rc} - ctx, cancel := context.WithTimeout(ctx, serviceTimeout) - defer cancel() - select { - case err := <-rc: - return err - case <-ctx.Done(): - return ctx.Err() - } -} - -type fileDeleteZettel struct { - entry *notify.DirEntry - rc chan<- resDeleteZettel -} -type resDeleteZettel = error - -func (cmd *fileDeleteZettel) run(log *logger.Logger, dirPath string) { - var err error - - entry := cmd.entry - contentName := entry.ContentName - contentPath := filepath.Join(dirPath, contentName) - if metaName := entry.MetaName; metaName == "" { - if contentName == "" { - log.Panic().Zid(entry.Zid).Msg("No meta, no content in getMetaContent") - } - err = os.Remove(contentPath) - } else { - if contentName != "" { - err = os.Remove(contentPath) - } - err1 := os.Remove(filepath.Join(dirPath, metaName)) - if err == nil { - err = err1 - } - } - for _, dupName := range entry.UselessFiles { - err1 := os.Remove(filepath.Join(dirPath, dupName)) - if err == nil { - err = err1 - } - } - cmd.rc <- err -} - -// Utility functions ---------------------------------------- - -func parseMetaFile(zid id.Zid, path string) (*meta.Meta, error) { - src, err := os.ReadFile(path) - if err != nil { - return nil, err - } - inp := input.NewInput(src) - return meta.NewFromInput(zid, inp), nil -} - -func parseMetaContentFile(zid id.Zid, path string) (*meta.Meta, []byte, error) { - src, err := os.ReadFile(path) - if err != nil { - return nil, nil, err - } - inp := input.NewInput(src) - meta := meta.NewFromInput(zid, inp) - return meta, src[inp.Pos:], nil -} - -func cmdCleanupMeta(m *meta.Meta, entry *notify.DirEntry) { - filebox.CleanupMeta( - m, - entry.Zid, - entry.ContentExt, - entry.MetaName != "", - entry.UselessFiles, - ) -} - -func openFileWrite(path string) (*os.File, error) { - return os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) -} - -func writeFileZid(w io.Writer, zid id.Zid) error { - _, err := io.WriteString(w, "id: ") - if err == nil { - _, err = w.Write(zid.Bytes()) - if err == nil { - _, err = io.WriteString(w, "\n") - } - } - return err -} - -func writeFileContent(path string, content []byte) error { - f, err := openFileWrite(path) - if err == nil { - _, err = f.Write(content) - if err1 := f.Close(); err == nil { - err = err1 - } - } - return err -} DELETED box/filebox/filebox.go Index: box/filebox/filebox.go ================================================================== --- box/filebox/filebox.go +++ /dev/null @@ -1,94 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package filebox provides boxes that are stored in a file. -package filebox - -import ( - "errors" - "net/url" - "path/filepath" - "strings" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/box/manager" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" -) - -func init() { - manager.Register("file", func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) { - path := getFilepathFromURL(u) - ext := strings.ToLower(filepath.Ext(path)) - if ext != ".zip" { - return nil, errors.New("unknown extension '" + ext + "' in box URL: " + u.String()) - } - return &zipBox{ - log: kernel.Main.GetLogger(kernel.BoxService).Clone(). - Str("box", "zip").Int("boxnum", int64(cdata.Number)).Child(), - number: cdata.Number, - name: path, - enricher: cdata.Enricher, - notify: cdata.Notify, - }, nil - }) -} - -func getFilepathFromURL(u *url.URL) string { - name := u.Opaque - if name == "" { - name = u.Path - } - components := strings.Split(name, "/") - fileName := filepath.Join(components...) - if len(components) > 0 && components[0] == "" { - return "/" + fileName - } - return fileName -} - -var alternativeSyntax = map[string]string{ - "htm": "html", -} - -func calculateSyntax(ext string) string { - ext = strings.ToLower(ext) - if syntax, ok := alternativeSyntax[ext]; ok { - return syntax - } - return ext -} - -// CalcDefaultMeta returns metadata with default values for the given entry. -func CalcDefaultMeta(zid id.Zid, ext string) *meta.Meta { - m := meta.New(zid) - m.Set(api.KeySyntax, calculateSyntax(ext)) - return m -} - -// CleanupMeta enhances the given metadata. -func CleanupMeta(m *meta.Meta, zid id.Zid, ext string, inMeta bool, uselessFiles []string) { - if inMeta { - if syntax, ok := m.Get(api.KeySyntax); !ok || syntax == "" { - dm := CalcDefaultMeta(zid, ext) - syntax, ok = dm.Get(api.KeySyntax) - if !ok { - panic("Default meta must contain syntax") - } - m.Set(api.KeySyntax, syntax) - } - } - - if len(uselessFiles) > 0 { - m.Set(api.KeyUselessFiles, strings.Join(uselessFiles, " ")) - } -} DELETED box/filebox/zipbox.go Index: box/filebox/zipbox.go ================================================================== --- box/filebox/zipbox.go +++ /dev/null @@ -1,255 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package filebox - -import ( - "archive/zip" - "context" - "io" - "strings" - - "zettelstore.de/z/box" - "zettelstore.de/z/box/notify" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/input" - "zettelstore.de/z/logger" - "zettelstore.de/z/search" -) - -type zipBox struct { - log *logger.Logger - number int - name string - enricher box.Enricher - notify chan<- box.UpdateInfo - dirSrv *notify.DirService -} - -func (zb *zipBox) Location() string { - if strings.HasPrefix(zb.name, "/") { - return "file://" + zb.name - } - return "file:" + zb.name -} - -func (zb *zipBox) Start(context.Context) error { - reader, err := zip.OpenReader(zb.name) - if err != nil { - return err - } - reader.Close() - zipNotifier, err := notify.NewSimpleZipNotifier(zb.log, zb.name) - if err != nil { - return err - } - zb.dirSrv = notify.NewDirService(zb.log, zipNotifier, zb.notify) - zb.dirSrv.Start() - return nil -} - -func (zb *zipBox) Refresh(_ context.Context) { - zb.dirSrv.Refresh() - zb.log.Trace().Msg("Refresh") -} - -func (zb *zipBox) Stop(context.Context) { - zb.dirSrv.Stop() -} - -func (*zipBox) CanCreateZettel(context.Context) bool { return false } - -func (zb *zipBox) CreateZettel(context.Context, domain.Zettel) (id.Zid, error) { - err := box.ErrReadOnly - zb.log.Trace().Err(err).Msg("CreateZettel") - return id.Invalid, err -} - -func (zb *zipBox) GetZettel(_ context.Context, zid id.Zid) (domain.Zettel, error) { - entry := zb.dirSrv.GetDirEntry(zid) - if !entry.IsValid() { - return domain.Zettel{}, box.ErrNotFound - } - reader, err := zip.OpenReader(zb.name) - if err != nil { - return domain.Zettel{}, err - } - defer reader.Close() - - var m *meta.Meta - var src []byte - var inMeta bool - - contentName := entry.ContentName - if metaName := entry.MetaName; metaName == "" { - if contentName == "" { - zb.log.Panic().Zid(zid).Msg("No meta, no content in zipBox.GetZettel") - } - src, err = readZipFileContent(reader, entry.ContentName) - if err != nil { - return domain.Zettel{}, err - } - if entry.HasMetaInContent() { - inp := input.NewInput(src) - m = meta.NewFromInput(zid, inp) - src = src[inp.Pos:] - } else { - m = CalcDefaultMeta(zid, entry.ContentExt) - } - } else { - m, err = readZipMetaFile(reader, zid, metaName) - if err != nil { - return domain.Zettel{}, err - } - inMeta = true - if contentName != "" { - src, err = readZipFileContent(reader, entry.ContentName) - if err != nil { - return domain.Zettel{}, err - } - } - } - - CleanupMeta(m, zid, entry.ContentExt, inMeta, entry.UselessFiles) - zb.log.Trace().Zid(zid).Msg("GetZettel") - return domain.Zettel{Meta: m, Content: domain.NewContent(src)}, nil -} - -func (zb *zipBox) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) { - entry := zb.dirSrv.GetDirEntry(zid) - if !entry.IsValid() { - return nil, box.ErrNotFound - } - reader, err := zip.OpenReader(zb.name) - if err != nil { - return nil, err - } - defer reader.Close() - m, err := zb.readZipMeta(reader, zid, entry) - zb.log.Trace().Err(err).Zid(zid).Msg("GetMeta") - return m, err -} - -func (zb *zipBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint search.RetrievePredicate) error { - entries := zb.dirSrv.GetDirEntries(constraint) - zb.log.Trace().Int("entries", int64(len(entries))).Msg("ApplyZid") - for _, entry := range entries { - handle(entry.Zid) - } - return nil -} - -func (zb *zipBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint search.RetrievePredicate) error { - reader, err := zip.OpenReader(zb.name) - if err != nil { - return err - } - defer reader.Close() - entries := zb.dirSrv.GetDirEntries(constraint) - zb.log.Trace().Int("entries", int64(len(entries))).Msg("ApplyMeta") - for _, entry := range entries { - if !constraint(entry.Zid) { - continue - } - m, err2 := zb.readZipMeta(reader, entry.Zid, entry) - if err2 != nil { - continue - } - zb.enricher.Enrich(ctx, m, zb.number) - handle(m) - } - return nil -} - -func (*zipBox) CanUpdateZettel(context.Context, domain.Zettel) bool { return false } - -func (zb *zipBox) UpdateZettel(context.Context, domain.Zettel) error { - err := box.ErrReadOnly - zb.log.Trace().Err(err).Msg("UpdateZettel") - return err -} - -func (zb *zipBox) AllowRenameZettel(_ context.Context, zid id.Zid) bool { - entry := zb.dirSrv.GetDirEntry(zid) - return !entry.IsValid() -} - -func (zb *zipBox) RenameZettel(_ context.Context, curZid, newZid id.Zid) error { - err := box.ErrReadOnly - if curZid == newZid { - err = nil - } - curEntry := zb.dirSrv.GetDirEntry(curZid) - if !curEntry.IsValid() { - err = box.ErrNotFound - } - zb.log.Trace().Err(err).Msg("RenameZettel") - return err -} - -func (*zipBox) CanDeleteZettel(context.Context, id.Zid) bool { return false } - -func (zb *zipBox) DeleteZettel(_ context.Context, zid id.Zid) error { - err := box.ErrReadOnly - entry := zb.dirSrv.GetDirEntry(zid) - if !entry.IsValid() { - err = box.ErrNotFound - } - zb.log.Trace().Err(err).Msg("DeleteZettel") - return err -} - -func (zb *zipBox) ReadStats(st *box.ManagedBoxStats) { - st.ReadOnly = true - st.Zettel = zb.dirSrv.NumDirEntries() - zb.log.Trace().Int("zettel", int64(st.Zettel)).Msg("ReadStats") -} - -func (zb *zipBox) readZipMeta(reader *zip.ReadCloser, zid id.Zid, entry *notify.DirEntry) (m *meta.Meta, err error) { - var inMeta bool - if metaName := entry.MetaName; metaName == "" { - contentName := entry.ContentName - contentExt := entry.ContentExt - if contentName == "" || contentExt == "" { - zb.log.Panic().Zid(zid).Msg("No meta, no content in getMeta") - } - if entry.HasMetaInContent() { - m, err = readZipMetaFile(reader, zid, contentName) - } else { - m = CalcDefaultMeta(zid, contentExt) - } - } else { - m, err = readZipMetaFile(reader, zid, metaName) - } - if err == nil { - CleanupMeta(m, zid, entry.ContentExt, inMeta, entry.UselessFiles) - } - return m, err -} - -func readZipMetaFile(reader *zip.ReadCloser, zid id.Zid, name string) (*meta.Meta, error) { - src, err := readZipFileContent(reader, name) - if err != nil { - return nil, err - } - inp := input.NewInput(src) - return meta.NewFromInput(zid, inp), nil -} - -func readZipFileContent(reader *zip.ReadCloser, name string) ([]byte, error) { - f, err := reader.Open(name) - if err != nil { - return nil, err - } - defer f.Close() - return io.ReadAll(f) -} DELETED box/helper.go Index: box/helper.go ================================================================== --- box/helper.go +++ /dev/null @@ -1,36 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package box - -import ( - "time" - - "zettelstore.de/z/domain/id" -) - -// GetNewZid calculates a new and unused zettel identifier, based on the current date and time. -func GetNewZid(testZid func(id.Zid) (bool, error)) (id.Zid, error) { - withSeconds := false - for i := 0; i < 90; i++ { // Must be completed within 9 seconds (less than web/server.writeTimeout) - zid := id.New(withSeconds) - found, err := testZid(zid) - if err != nil { - return id.Invalid, err - } - if found { - return zid, nil - } - // TODO: do not wait here unconditionally. - time.Sleep(100 * time.Millisecond) - withSeconds = true - } - return id.Invalid, ErrConflict -} DELETED box/manager/anteroom.go Index: box/manager/anteroom.go ================================================================== --- box/manager/anteroom.go +++ /dev/null @@ -1,164 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package manager - -import ( - "sync" - - "zettelstore.de/z/domain/id" -) - -type arAction int - -const ( - arNothing arAction = iota - arReload - arUpdate - arDelete -) - -type anteroom struct { - num uint64 - next *anteroom - waiting map[id.Zid]arAction - curLoad int - reload bool -} - -type anterooms struct { - mx sync.Mutex - nextNum uint64 - first *anteroom - last *anteroom - maxLoad int -} - -func newAnterooms(maxLoad int) *anterooms { - return &anterooms{maxLoad: maxLoad} -} - -func (ar *anterooms) Enqueue(zid id.Zid, action arAction) { - if !zid.IsValid() || action == arNothing || action == arReload { - return - } - ar.mx.Lock() - defer ar.mx.Unlock() - if ar.first == nil { - ar.first = ar.makeAnteroom(zid, action) - ar.last = ar.first - return - } - for room := ar.first; room != nil; room = room.next { - if room.reload { - continue // Do not put zettel in reload room - } - a, ok := room.waiting[zid] - if !ok { - continue - } - switch action { - case a: - return - case arUpdate: - room.waiting[zid] = action - case arDelete: - room.waiting[zid] = action - } - return - } - if room := ar.last; !room.reload && (ar.maxLoad == 0 || room.curLoad < ar.maxLoad) { - room.waiting[zid] = action - room.curLoad++ - return - } - room := ar.makeAnteroom(zid, action) - ar.last.next = room - ar.last = room -} - -func (ar *anterooms) makeAnteroom(zid id.Zid, action arAction) *anteroom { - c := ar.maxLoad - if c == 0 { - c = 100 - } - waiting := make(map[id.Zid]arAction, c) - waiting[zid] = action - ar.nextNum++ - return &anteroom{num: ar.nextNum, next: nil, waiting: waiting, curLoad: 1, reload: false} -} - -func (ar *anterooms) Reset() { - ar.mx.Lock() - defer ar.mx.Unlock() - ar.first = ar.makeAnteroom(id.Invalid, arReload) - ar.last = ar.first -} - -func (ar *anterooms) Reload(newZids id.Set) uint64 { - ar.mx.Lock() - defer ar.mx.Unlock() - newWaiting := createWaitingSet(newZids, arUpdate) - ar.deleteReloadedRooms() - - if ns := len(newWaiting); ns > 0 { - ar.nextNum++ - ar.first = &anteroom{num: ar.nextNum, next: ar.first, waiting: newWaiting, curLoad: ns} - if ar.first.next == nil { - ar.last = ar.first - } - return ar.nextNum - } - - ar.first = nil - ar.last = nil - return 0 -} - -func createWaitingSet(zids id.Set, action arAction) map[id.Zid]arAction { - waitingSet := make(map[id.Zid]arAction, len(zids)) - for zid := range zids { - if zid.IsValid() { - waitingSet[zid] = action - } - } - return waitingSet -} - -func (ar *anterooms) deleteReloadedRooms() { - room := ar.first - for room != nil && room.reload { - room = room.next - } - ar.first = room - if room == nil { - ar.last = nil - } -} - -func (ar *anterooms) Dequeue() (arAction, id.Zid, uint64) { - ar.mx.Lock() - defer ar.mx.Unlock() - if ar.first == nil { - return arNothing, id.Invalid, 0 - } - for zid, action := range ar.first.waiting { - roomNo := ar.first.num - delete(ar.first.waiting, zid) - if len(ar.first.waiting) == 0 { - ar.first = ar.first.next - if ar.first == nil { - ar.last = nil - } - } - return action, zid, roomNo - } - return arNothing, id.Invalid, 0 -} DELETED box/manager/anteroom_test.go Index: box/manager/anteroom_test.go ================================================================== --- box/manager/anteroom_test.go +++ /dev/null @@ -1,108 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package manager - -import ( - "testing" - - "zettelstore.de/z/domain/id" -) - -func TestSimple(t *testing.T) { - t.Parallel() - ar := newAnterooms(2) - ar.Enqueue(id.Zid(1), arUpdate) - action, zid, rno := ar.Dequeue() - if zid != id.Zid(1) || action != arUpdate || rno != 1 { - t.Errorf("Expected arUpdate/1/1, but got %v/%v/%v", action, zid, rno) - } - action, zid, _ = ar.Dequeue() - if zid != id.Invalid && action != arDelete { - t.Errorf("Expected invalid Zid, but got %v", zid) - } - ar.Enqueue(id.Zid(1), arUpdate) - ar.Enqueue(id.Zid(2), arUpdate) - if ar.first != ar.last { - t.Errorf("Expected one room, but got more") - } - ar.Enqueue(id.Zid(3), arUpdate) - if ar.first == ar.last { - t.Errorf("Expected more than one room, but got only one") - } - - count := 0 - for ; count < 1000; count++ { - action, _, _ = ar.Dequeue() - if action == arNothing { - break - } - } - if count != 3 { - t.Errorf("Expected 3 dequeues, but got %v", count) - } -} - -func TestReset(t *testing.T) { - t.Parallel() - ar := newAnterooms(1) - ar.Enqueue(id.Zid(1), arUpdate) - ar.Reset() - action, zid, _ := ar.Dequeue() - if action != arReload || zid != id.Invalid { - t.Errorf("Expected reload & invalid Zid, but got %v/%v", action, zid) - } - ar.Reload(id.NewSet(3, 4)) - ar.Enqueue(id.Zid(5), arUpdate) - ar.Enqueue(id.Zid(5), arDelete) - ar.Enqueue(id.Zid(5), arDelete) - ar.Enqueue(id.Zid(5), arUpdate) - if ar.first == ar.last || ar.first.next != ar.last /*|| ar.first.next.next != ar.last*/ { - t.Errorf("Expected 2 rooms") - } - action, zid1, _ := ar.Dequeue() - if action != arUpdate { - t.Errorf("Expected arUpdate, but got %v", action) - } - action, zid2, _ := ar.Dequeue() - if action != arUpdate { - t.Errorf("Expected arUpdate, but got %v", action) - } - if !(zid1 == id.Zid(3) && zid2 == id.Zid(4) || zid1 == id.Zid(4) && zid2 == id.Zid(3)) { - t.Errorf("Zids must be 3 or 4, but got %v/%v", zid1, zid2) - } - action, zid, _ = ar.Dequeue() - if zid != id.Zid(5) || action != arUpdate { - t.Errorf("Expected 5/arUpdate, but got %v/%v", zid, action) - } - action, zid, _ = ar.Dequeue() - if action != arNothing || zid != id.Invalid { - t.Errorf("Expected nothing & invalid Zid, but got %v/%v", action, zid) - } - - ar = newAnterooms(1) - ar.Reload(id.NewSet(id.Zid(6))) - action, zid, _ = ar.Dequeue() - if zid != id.Zid(6) || action != arUpdate { - t.Errorf("Expected 6/arUpdate, but got %v/%v", zid, action) - } - action, zid, _ = ar.Dequeue() - if action != arNothing || zid != id.Invalid { - t.Errorf("Expected nothing & invalid Zid, but got %v/%v", action, zid) - } - - ar = newAnterooms(1) - ar.Enqueue(id.Zid(8), arUpdate) - ar.Reload(nil) - action, zid, _ = ar.Dequeue() - if action != arNothing || zid != id.Invalid { - t.Errorf("Expected nothing & invalid Zid, but got %v/%v", action, zid) - } -} DELETED box/manager/box.go Index: box/manager/box.go ================================================================== --- box/manager/box.go +++ /dev/null @@ -1,295 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package manager - -import ( - "bytes" - "context" - "errors" - - "zettelstore.de/z/box" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/search" -) - -// Conatains all box.Box related functions - -// Location returns some information where the box is located. -func (mgr *Manager) Location() string { - if len(mgr.boxes) <= 2 { - return "NONE" - } - var buf bytes.Buffer - for i := 0; i < len(mgr.boxes)-2; i++ { - if i > 0 { - buf.WriteString(", ") - } - buf.WriteString(mgr.boxes[i].Location()) - } - return buf.String() -} - -// CanCreateZettel returns true, if box could possibly create a new zettel. -func (mgr *Manager) CanCreateZettel(ctx context.Context) bool { - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - return mgr.started && mgr.boxes[0].CanCreateZettel(ctx) -} - -// CreateZettel creates a new zettel. -func (mgr *Manager) CreateZettel(ctx context.Context, zettel domain.Zettel) (id.Zid, error) { - mgr.mgrLog.Debug().Msg("CreateZettel") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return id.Invalid, box.ErrStopped - } - return mgr.boxes[0].CreateZettel(ctx, zettel) -} - -// GetZettel retrieves a specific zettel. -func (mgr *Manager) GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) { - mgr.mgrLog.Debug().Zid(zid).Msg("GetZettel") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return domain.Zettel{}, box.ErrStopped - } - for i, p := range mgr.boxes { - if z, err := p.GetZettel(ctx, zid); err != box.ErrNotFound { - if err == nil { - mgr.Enrich(ctx, z.Meta, i+1) - } - return z, err - } - } - return domain.Zettel{}, box.ErrNotFound -} - -// GetAllZettel retrieves a specific zettel from all managed boxes. -func (mgr *Manager) GetAllZettel(ctx context.Context, zid id.Zid) ([]domain.Zettel, error) { - mgr.mgrLog.Debug().Zid(zid).Msg("GetAllZettel") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return nil, box.ErrStopped - } - var result []domain.Zettel - for i, p := range mgr.boxes { - if z, err := p.GetZettel(ctx, zid); err == nil { - mgr.Enrich(ctx, z.Meta, i+1) - result = append(result, z) - } - } - return result, nil -} - -// GetMeta retrieves just the meta data of a specific zettel. -func (mgr *Manager) GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) { - mgr.mgrLog.Debug().Zid(zid).Msg("GetMeta") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return nil, box.ErrStopped - } - return mgr.doGetMeta(ctx, zid) -} - -func (mgr *Manager) doGetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) { - for i, p := range mgr.boxes { - if m, err := p.GetMeta(ctx, zid); err != box.ErrNotFound { - if err == nil { - mgr.Enrich(ctx, m, i+1) - } - return m, err - } - } - return nil, box.ErrNotFound -} - -// GetAllMeta retrieves the meta data of a specific zettel from all managed boxes. -func (mgr *Manager) GetAllMeta(ctx context.Context, zid id.Zid) ([]*meta.Meta, error) { - mgr.mgrLog.Debug().Zid(zid).Msg("GetAllMeta") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return nil, box.ErrStopped - } - var result []*meta.Meta - for i, p := range mgr.boxes { - if m, err := p.GetMeta(ctx, zid); err == nil { - mgr.Enrich(ctx, m, i+1) - result = append(result, m) - } - } - return result, nil -} - -// FetchZids returns the set of all zettel identifer managed by the box. -func (mgr *Manager) FetchZids(ctx context.Context) (id.Set, error) { - mgr.mgrLog.Debug().Msg("FetchZids") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return nil, box.ErrStopped - } - result := id.Set{} - for _, p := range mgr.boxes { - err := p.ApplyZid(ctx, func(zid id.Zid) { result.Zid(zid) }, func(id.Zid) bool { return true }) - if err != nil { - return nil, err - } - } - return result, nil -} - -type metaMap map[id.Zid]*meta.Meta - -// SelectMeta returns all zettel meta data that match the selection -// criteria. The result is ordered by descending zettel id. -func (mgr *Manager) SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) { - if msg := mgr.mgrLog.Debug(); msg.Enabled() { - msg.Str("query", s.String()).Msg("SelectMeta") - } - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return nil, box.ErrStopped - } - - searchPred, match := s.RetrieveAndCompileMatch(mgr) - selected, rejected := metaMap{}, id.Set{} - handleMeta := func(m *meta.Meta) { - zid := m.Zid - if rejected.Contains(zid) { - mgr.mgrLog.Trace().Zid(zid).Msg("SelectMeta/alreadyRejected") - return - } - if _, ok := selected[zid]; ok { - mgr.mgrLog.Trace().Zid(zid).Msg("SelectMeta/alreadySelected") - return - } - if match(m) { - selected[zid] = m - mgr.mgrLog.Trace().Zid(zid).Msg("SelectMeta/match") - } else { - rejected.Zid(zid) - mgr.mgrLog.Trace().Zid(zid).Msg("SelectMeta/reject") - } - } - for _, p := range mgr.boxes { - if err := p.ApplyMeta(ctx, handleMeta, searchPred); err != nil { - return nil, err - } - } - result := make([]*meta.Meta, 0, len(selected)) - for _, m := range selected { - result = append(result, m) - } - return s.Sort(result), nil -} - -// CanUpdateZettel returns true, if box could possibly update the given zettel. -func (mgr *Manager) CanUpdateZettel(ctx context.Context, zettel domain.Zettel) bool { - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - return mgr.started && mgr.boxes[0].CanUpdateZettel(ctx, zettel) -} - -// UpdateZettel updates an existing zettel. -func (mgr *Manager) UpdateZettel(ctx context.Context, zettel domain.Zettel) error { - mgr.mgrLog.Debug().Zid(zettel.Meta.Zid).Msg("UpdateZettel") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return box.ErrStopped - } - // Remove all (computed) properties from metadata before storing the zettel. - zettel.Meta = zettel.Meta.Clone() - for _, p := range zettel.Meta.ComputedPairsRest() { - if mgr.propertyKeys.Has(p.Key) { - zettel.Meta.Delete(p.Key) - } - } - return mgr.boxes[0].UpdateZettel(ctx, zettel) -} - -// AllowRenameZettel returns true, if box will not disallow renaming the zettel. -func (mgr *Manager) AllowRenameZettel(ctx context.Context, zid id.Zid) bool { - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return false - } - for _, p := range mgr.boxes { - if !p.AllowRenameZettel(ctx, zid) { - return false - } - } - return true -} - -// RenameZettel changes the current zid to a new zid. -func (mgr *Manager) RenameZettel(ctx context.Context, curZid, newZid id.Zid) error { - mgr.mgrLog.Debug().Zid(curZid).Zid(newZid).Msg("RenameZettel") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return box.ErrStopped - } - for i, p := range mgr.boxes { - err := p.RenameZettel(ctx, curZid, newZid) - if err != nil && !errors.Is(err, box.ErrNotFound) { - for j := 0; j < i; j++ { - mgr.boxes[j].RenameZettel(ctx, newZid, curZid) - } - return err - } - } - return nil -} - -// CanDeleteZettel returns true, if box could possibly delete the given zettel. -func (mgr *Manager) CanDeleteZettel(ctx context.Context, zid id.Zid) bool { - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return false - } - for _, p := range mgr.boxes { - if p.CanDeleteZettel(ctx, zid) { - return true - } - } - return false -} - -// DeleteZettel removes the zettel from the box. -func (mgr *Manager) DeleteZettel(ctx context.Context, zid id.Zid) error { - mgr.mgrLog.Debug().Zid(zid).Msg("DeleteZettel") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - if !mgr.started { - return box.ErrStopped - } - for _, p := range mgr.boxes { - err := p.DeleteZettel(ctx, zid) - if err == nil { - return nil - } - if !errors.Is(err, box.ErrNotFound) && !errors.Is(err, box.ErrReadOnly) { - return err - } - } - return box.ErrNotFound -} DELETED box/manager/collect.go Index: box/manager/collect.go ================================================================== --- box/manager/collect.go +++ /dev/null @@ -1,84 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package manager - -import ( - "strings" - - "zettelstore.de/z/ast" - "zettelstore.de/z/box/manager/store" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/strfun" -) - -type collectData struct { - refs id.Set - words store.WordSet - urls store.WordSet - itags store.WordSet -} - -func (data *collectData) initialize() { - data.refs = id.NewSet() - data.words = store.NewWordSet() - data.urls = store.NewWordSet() - data.itags = store.NewWordSet() -} - -func collectZettelIndexData(zn *ast.ZettelNode, data *collectData) { - ast.Walk(data, &zn.Ast) -} - -func collectInlineIndexData(is *ast.InlineSlice, data *collectData) { - ast.Walk(data, is) -} - -func (data *collectData) Visit(node ast.Node) ast.Visitor { - switch n := node.(type) { - case *ast.VerbatimNode: - data.addText(string(n.Content)) - case *ast.TranscludeNode: - data.addRef(n.Ref) - case *ast.TextNode: - data.addText(n.Text) - case *ast.TagNode: - data.addText(n.Tag) - data.itags.Add("#" + strings.ToLower(n.Tag)) - case *ast.LinkNode: - data.addRef(n.Ref) - case *ast.EmbedRefNode: - data.addRef(n.Ref) - case *ast.LiteralNode: - data.addText(string(n.Content)) - } - return data -} - -func (data *collectData) addText(s string) { - for _, word := range strfun.NormalizeWords(s) { - data.words.Add(word) - } -} - -func (data *collectData) addRef(ref *ast.Reference) { - if ref == nil { - return - } - if ref.IsExternal() { - data.urls.Add(strings.ToLower(ref.Value)) - } - if !ref.IsZettel() { - return - } - if zid, err := id.Parse(ref.URL.Path); err == nil { - data.refs.Zid(zid) - } -} DELETED box/manager/enrich.go Index: box/manager/enrich.go ================================================================== --- box/manager/enrich.go +++ /dev/null @@ -1,52 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package manager - -import ( - "context" - "strconv" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/domain/meta" -) - -// Enrich computes additional properties and updates the given metadata. -func (mgr *Manager) Enrich(ctx context.Context, m *meta.Meta, boxNumber int) { - if box.DoNotEnrich(ctx) { - // Enrich is called indirectly via indexer or enrichment is not requested - // because of other reasons -> ignore this call, do not update meta data - return - } - m.Set(api.KeyBoxNumber, strconv.Itoa(boxNumber)) - computePublished(m) - mgr.idxStore.Enrich(ctx, m) -} - -func computePublished(m *meta.Meta) { - if _, ok := m.Get(api.KeyPublished); ok { - return - } - if modified, ok := m.Get(api.KeyModified); ok { - if _, ok = meta.TimeValue(modified); ok { - m.Set(api.KeyPublished, modified) - return - } - } - zid := m.Zid.String() - if _, ok := meta.TimeValue(zid); ok { - m.Set(api.KeyPublished, zid) - return - } - - // Neither the zettel was modified nor the zettel identifer contains a valid - // timestamp. In this case do not set the "published" property. -} DELETED box/manager/indexer.go Index: box/manager/indexer.go ================================================================== --- box/manager/indexer.go +++ /dev/null @@ -1,247 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package manager - -import ( - "context" - "fmt" - "net/url" - "time" - - "zettelstore.de/z/box" - "zettelstore.de/z/box/manager/store" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" - "zettelstore.de/z/parser" - "zettelstore.de/z/strfun" -) - -// SearchEqual returns all zettel that contains the given exact word. -// The word must be normalized through Unicode NKFD, trimmed and not empty. -func (mgr *Manager) SearchEqual(word string) id.Set { - found := mgr.idxStore.SearchEqual(word) - mgr.idxLog.Debug().Str("word", word).Int("found", int64(len(found))).Msg("SearchEqual") - if msg := mgr.idxLog.Trace(); msg.Enabled() { - msg.Str("ids", fmt.Sprint(found)).Msg("IDs") - } - return found -} - -// SearchPrefix returns all zettel that have a word with the given prefix. -// The prefix must be normalized through Unicode NKFD, trimmed and not empty. -func (mgr *Manager) SearchPrefix(prefix string) id.Set { - found := mgr.idxStore.SearchPrefix(prefix) - mgr.idxLog.Debug().Str("prefix", prefix).Int("found", int64(len(found))).Msg("SearchPrefix") - if msg := mgr.idxLog.Trace(); msg.Enabled() { - msg.Str("ids", fmt.Sprint(found)).Msg("IDs") - } - return found -} - -// SearchSuffix returns all zettel that have a word with the given suffix. -// The suffix must be normalized through Unicode NKFD, trimmed and not empty. -func (mgr *Manager) SearchSuffix(suffix string) id.Set { - found := mgr.idxStore.SearchSuffix(suffix) - mgr.idxLog.Debug().Str("suffix", suffix).Int("found", int64(len(found))).Msg("SearchSuffix") - if msg := mgr.idxLog.Trace(); msg.Enabled() { - msg.Str("ids", fmt.Sprint(found)).Msg("IDs") - } - return found -} - -// SearchContains returns all zettel that contains the given string. -// The string must be normalized through Unicode NKFD, trimmed and not empty. -func (mgr *Manager) SearchContains(s string) id.Set { - found := mgr.idxStore.SearchContains(s) - mgr.idxLog.Debug().Str("s", s).Int("found", int64(len(found))).Msg("SearchContains") - if msg := mgr.idxLog.Trace(); msg.Enabled() { - msg.Str("ids", fmt.Sprint(found)).Msg("IDs") - } - return found -} - -// idxIndexer runs in the background and updates the index data structures. -// This is the main service of the idxIndexer. -func (mgr *Manager) idxIndexer() { - // Something may panic. Ensure a running indexer. - defer func() { - if r := recover(); r != nil { - kernel.Main.LogRecover("Indexer", r) - go mgr.idxIndexer() - } - }() - - timerDuration := 15 * time.Second - timer := time.NewTimer(timerDuration) - ctx := box.NoEnrichContext(context.Background()) - for { - mgr.idxWorkService(ctx) - if !mgr.idxSleepService(timer, timerDuration) { - return - } - } -} - -func (mgr *Manager) idxWorkService(ctx context.Context) { - var roomNum uint64 - var start time.Time - for { - switch action, zid, arRoomNum := mgr.idxAr.Dequeue(); action { - case arNothing: - return - case arReload: - mgr.idxLog.Debug().Msg("reload") - roomNum = 0 - zids, err := mgr.FetchZids(ctx) - if err == nil { - start = time.Now() - if rno := mgr.idxAr.Reload(zids); rno > 0 { - roomNum = rno - } - mgr.idxMx.Lock() - mgr.idxLastReload = time.Now() - mgr.idxSinceReload = 0 - mgr.idxMx.Unlock() - } - case arUpdate: - mgr.idxLog.Debug().Zid(zid).Msg("update") - zettel, err := mgr.GetZettel(ctx, zid) - if err != nil { - // TODO: on some errors put the zid into a "try later" set - continue - } - mgr.idxMx.Lock() - if arRoomNum == roomNum { - mgr.idxDurReload = time.Since(start) - } - mgr.idxSinceReload++ - mgr.idxMx.Unlock() - mgr.idxUpdateZettel(ctx, zettel) - case arDelete: - mgr.idxLog.Debug().Zid(zid).Msg("delete") - if _, err := mgr.GetMeta(ctx, zid); err == nil { - // Zettel was not deleted. This might occur, if zettel was - // deleted in secondary dirbox, but is still present in - // first dirbox (or vice versa). Re-index zettel in case - // a hidden zettel was recovered - mgr.idxLog.Debug().Zid(zid).Msg("not deleted") - mgr.idxAr.Enqueue(zid, arUpdate) - } - mgr.idxMx.Lock() - mgr.idxSinceReload++ - mgr.idxMx.Unlock() - mgr.idxDeleteZettel(zid) - } - } -} - -func (mgr *Manager) idxSleepService(timer *time.Timer, timerDuration time.Duration) bool { - select { - case _, ok := <-mgr.idxReady: - if !ok { - return false - } - case _, ok := <-timer.C: - if !ok { - return false - } - timer.Reset(timerDuration) - case <-mgr.done: - if !timer.Stop() { - <-timer.C - } - return false - } - return true -} - -func (mgr *Manager) idxUpdateZettel(ctx context.Context, zettel domain.Zettel) { - var cData collectData - cData.initialize() - collectZettelIndexData(parser.ParseZettel(zettel, "", mgr.rtConfig), &cData) - - m := zettel.Meta - zi := store.NewZettelIndex(m.Zid) - mgr.idxCollectFromMeta(ctx, m, zi, &cData) - mgr.idxProcessData(ctx, zi, &cData) - toCheck := mgr.idxStore.UpdateReferences(ctx, zi) - mgr.idxCheckZettel(toCheck) -} - -func (mgr *Manager) idxCollectFromMeta(ctx context.Context, m *meta.Meta, zi *store.ZettelIndex, cData *collectData) { - for _, pair := range m.Pairs() { - descr := meta.GetDescription(pair.Key) - if descr.IsComputed() { - continue - } - switch descr.Type { - case meta.TypeID: - mgr.idxUpdateValue(ctx, descr.Inverse, pair.Value, zi) - case meta.TypeIDSet: - for _, val := range meta.ListFromValue(pair.Value) { - mgr.idxUpdateValue(ctx, descr.Inverse, val, zi) - } - case meta.TypeZettelmarkup: - is := parser.ParseMetadata(pair.Value) - collectInlineIndexData(&is, cData) - case meta.TypeURL: - if _, err := url.Parse(pair.Value); err == nil { - cData.urls.Add(pair.Value) - } - default: - for _, word := range strfun.NormalizeWords(pair.Value) { - cData.words.Add(word) - } - } - } -} - -func (mgr *Manager) idxProcessData(ctx context.Context, zi *store.ZettelIndex, cData *collectData) { - for ref := range cData.refs { - if _, err := mgr.GetMeta(ctx, ref); err == nil { - zi.AddBackRef(ref) - } else { - zi.AddDeadRef(ref) - } - } - zi.SetWords(cData.words) - zi.SetUrls(cData.urls) - zi.SetITags(cData.itags) -} - -func (mgr *Manager) idxUpdateValue(ctx context.Context, inverseKey, value string, zi *store.ZettelIndex) { - zid, err := id.Parse(value) - if err != nil { - return - } - if _, err = mgr.GetMeta(ctx, zid); err != nil { - zi.AddDeadRef(zid) - return - } - if inverseKey == "" { - zi.AddBackRef(zid) - return - } - zi.AddMetaRef(inverseKey, zid) -} - -func (mgr *Manager) idxDeleteZettel(zid id.Zid) { - toCheck := mgr.idxStore.DeleteZettel(context.Background(), zid) - mgr.idxCheckZettel(toCheck) -} - -func (mgr *Manager) idxCheckZettel(s id.Set) { - for zid := range s { - mgr.idxAr.Enqueue(zid, arUpdate) - } -} DELETED box/manager/manager.go Index: box/manager/manager.go ================================================================== --- box/manager/manager.go +++ /dev/null @@ -1,361 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package manager coordinates the various boxes and indexes of a Zettelstore. -package manager - -import ( - "context" - "io" - "net/url" - "sync" - "time" - - "zettelstore.de/c/maps" - "zettelstore.de/z/auth" - "zettelstore.de/z/box" - "zettelstore.de/z/box/manager/memstore" - "zettelstore.de/z/box/manager/store" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" - "zettelstore.de/z/strfun" -) - -// ConnectData contains all administration related values. -type ConnectData struct { - Number int // number of the box, starting with 1. - Config config.Config - Enricher box.Enricher - Notify chan<- box.UpdateInfo -} - -// Connect returns a handle to the specified box. -func Connect(u *url.URL, authManager auth.BaseManager, cdata *ConnectData) (box.ManagedBox, error) { - if authManager.IsReadonly() { - rawURL := u.String() - // TODO: the following is wrong under some circumstances: - // 1. fragment is set - if q := u.Query(); len(q) == 0 { - rawURL += "?readonly" - } else if _, ok := q["readonly"]; !ok { - rawURL += "&readonly" - } - var err error - if u, err = url.Parse(rawURL); err != nil { - return nil, err - } - } - - if create, ok := registry[u.Scheme]; ok { - return create(u, cdata) - } - return nil, &ErrInvalidScheme{u.Scheme} -} - -// ErrInvalidScheme is returned if there is no box with the given scheme. -type ErrInvalidScheme struct{ Scheme string } - -func (err *ErrInvalidScheme) Error() string { return "Invalid scheme: " + err.Scheme } - -type createFunc func(*url.URL, *ConnectData) (box.ManagedBox, error) - -var registry = map[string]createFunc{} - -// Register the encoder for later retrieval. -func Register(scheme string, create createFunc) { - if _, ok := registry[scheme]; ok { - panic(scheme) - } - registry[scheme] = create -} - -// GetSchemes returns all registered scheme, ordered by scheme string. -func GetSchemes() []string { return maps.Keys(registry) } - -// Manager is a coordinating box. -type Manager struct { - mgrLog *logger.Logger - mgrMx sync.RWMutex - started bool - rtConfig config.Config - boxes []box.ManagedBox - observers []box.UpdateFunc - mxObserver sync.RWMutex - done chan struct{} - infos chan box.UpdateInfo - propertyKeys strfun.Set // Set of property key names - - // Indexer data - idxLog *logger.Logger - idxStore store.Store - idxAr *anterooms - idxReady chan struct{} // Signal a non-empty anteroom to background task - - // Indexer stats data - idxMx sync.RWMutex - idxLastReload time.Time - idxDurReload time.Duration - idxSinceReload uint64 -} - -// New creates a new managing box. -func New(boxURIs []*url.URL, authManager auth.BaseManager, rtConfig config.Config) (*Manager, error) { - descrs := meta.GetSortedKeyDescriptions() - propertyKeys := make(strfun.Set, len(descrs)) - for _, kd := range descrs { - if kd.IsProperty() { - propertyKeys.Set(kd.Name) - } - } - boxLog := kernel.Main.GetLogger(kernel.BoxService) - mgr := &Manager{ - mgrLog: boxLog.Clone().Str("box", "manager").Child(), - rtConfig: rtConfig, - infos: make(chan box.UpdateInfo, len(boxURIs)*10), - propertyKeys: propertyKeys, - - idxLog: boxLog.Clone().Str("box", "index").Child(), - idxStore: memstore.New(), - idxAr: newAnterooms(10), - idxReady: make(chan struct{}, 1), - } - cdata := ConnectData{Number: 1, Config: rtConfig, Enricher: mgr, Notify: mgr.infos} - boxes := make([]box.ManagedBox, 0, len(boxURIs)+2) - for _, uri := range boxURIs { - p, err := Connect(uri, authManager, &cdata) - if err != nil { - return nil, err - } - if p != nil { - boxes = append(boxes, p) - cdata.Number++ - } - } - constbox, err := registry[" const"](nil, &cdata) - if err != nil { - return nil, err - } - cdata.Number++ - compbox, err := registry[" comp"](nil, &cdata) - if err != nil { - return nil, err - } - cdata.Number++ - boxes = append(boxes, constbox, compbox) - mgr.boxes = boxes - return mgr, nil -} - -// RegisterObserver registers an observer that will be notified -// if a zettel was found to be changed. -func (mgr *Manager) RegisterObserver(f box.UpdateFunc) { - if f != nil { - mgr.mxObserver.Lock() - mgr.observers = append(mgr.observers, f) - mgr.mxObserver.Unlock() - } -} - -func (mgr *Manager) notifier() { - // The call to notify may panic. Ensure a running notifier. - defer func() { - if r := recover(); r != nil { - kernel.Main.LogRecover("Notifier", r) - go mgr.notifier() - } - }() - - tsLastEvent := time.Now() - cache := destutterCache{} - for { - select { - case ci, ok := <-mgr.infos: - if ok { - now := time.Now() - if len(cache) > 1 && tsLastEvent.Add(10*time.Second).Before(now) { - // Cache contains entries and is definitely outdated - mgr.mgrLog.Trace().Msg("clean destutter cache") - cache = destutterCache{} - } - tsLastEvent = now - - reason, zid := ci.Reason, ci.Zid - mgr.mgrLog.Debug().Uint("reason", uint64(reason)).Zid(zid).Msg("notifier") - if ignoreUpdate(cache, now, reason, zid) { - mgr.mgrLog.Trace().Uint("reason", uint64(reason)).Zid(zid).Msg("notifier ignored") - continue - } - mgr.idxEnqueue(reason, zid) - if ci.Box == nil { - ci.Box = mgr - } - mgr.notifyObserver(&ci) - } - case <-mgr.done: - return - } - } -} - -type destutterData struct { - deadAt time.Time - reason box.UpdateReason -} -type destutterCache = map[id.Zid]destutterData - -func ignoreUpdate(cache destutterCache, now time.Time, reason box.UpdateReason, zid id.Zid) bool { - if dsd, found := cache[zid]; found { - if dsd.reason == reason && dsd.deadAt.After(now) { - return true - } - } - cache[zid] = destutterData{ - deadAt: now.Add(500 * time.Millisecond), - reason: reason, - } - return false -} - -func (mgr *Manager) idxEnqueue(reason box.UpdateReason, zid id.Zid) { - switch reason { - case box.OnReload: - mgr.idxAr.Reset() - case box.OnUpdate: - mgr.idxAr.Enqueue(zid, arUpdate) - case box.OnDelete: - mgr.idxAr.Enqueue(zid, arDelete) - default: - return - } - select { - case mgr.idxReady <- struct{}{}: - default: - } -} - -func (mgr *Manager) notifyObserver(ci *box.UpdateInfo) { - mgr.mxObserver.RLock() - observers := mgr.observers - mgr.mxObserver.RUnlock() - for _, ob := range observers { - ob(*ci) - } -} - -// Start the box. Now all other functions of the box are allowed. -// Starting an already started box is not allowed. -func (mgr *Manager) Start(ctx context.Context) error { - mgr.mgrMx.Lock() - if mgr.started { - mgr.mgrMx.Unlock() - return box.ErrStarted - } - for i := len(mgr.boxes) - 1; i >= 0; i-- { - ssi, ok := mgr.boxes[i].(box.StartStopper) - if !ok { - continue - } - err := ssi.Start(ctx) - if err == nil { - continue - } - for j := i + 1; j < len(mgr.boxes); j++ { - if ssj, ok2 := mgr.boxes[j].(box.StartStopper); ok2 { - ssj.Stop(ctx) - } - } - mgr.mgrMx.Unlock() - return err - } - mgr.idxAr.Reset() // Ensure an initial index run - mgr.done = make(chan struct{}) - go mgr.notifier() - go mgr.idxIndexer() - - mgr.started = true - mgr.mgrMx.Unlock() - return nil -} - -// Stop the started box. Now only the Start() function is allowed. -func (mgr *Manager) Stop(ctx context.Context) { - mgr.mgrMx.Lock() - defer mgr.mgrMx.Unlock() - if !mgr.started { - return - } - close(mgr.done) - for _, p := range mgr.boxes { - if ss, ok := p.(box.StartStopper); ok { - ss.Stop(ctx) - } - } - mgr.started = false -} - -// Refresh internal box data. -func (mgr *Manager) Refresh(ctx context.Context) error { - mgr.mgrLog.Debug().Msg("Refresh") - mgr.mgrMx.Lock() - defer mgr.mgrMx.Unlock() - if !mgr.started { - return box.ErrStopped - } - mgr.infos <- box.UpdateInfo{Reason: box.OnReload, Zid: id.Invalid} - for _, bx := range mgr.boxes { - if rb, ok := bx.(box.Refresher); ok { - rb.Refresh(ctx) - } - } - return nil -} - -// ReadStats populates st with box statistics. -func (mgr *Manager) ReadStats(st *box.Stats) { - mgr.mgrLog.Debug().Msg("ReadStats") - mgr.mgrMx.RLock() - defer mgr.mgrMx.RUnlock() - subStats := make([]box.ManagedBoxStats, len(mgr.boxes)) - for i, p := range mgr.boxes { - p.ReadStats(&subStats[i]) - } - - st.ReadOnly = true - sumZettel := 0 - for _, sst := range subStats { - if !sst.ReadOnly { - st.ReadOnly = false - } - sumZettel += sst.Zettel - } - st.NumManagedBoxes = len(mgr.boxes) - st.ZettelTotal = sumZettel - - var storeSt store.Stats - mgr.idxMx.RLock() - defer mgr.idxMx.RUnlock() - mgr.idxStore.ReadStats(&storeSt) - - st.LastReload = mgr.idxLastReload - st.IndexesSinceReload = mgr.idxSinceReload - st.DurLastReload = mgr.idxDurReload - st.ZettelIndexed = storeSt.Zettel - st.IndexUpdates = storeSt.Updates - st.IndexedWords = storeSt.Words - st.IndexedUrls = storeSt.Urls -} - -// Dump internal data structures to a Writer. -func (mgr *Manager) Dump(w io.Writer) { - mgr.idxStore.Dump(w) -} DELETED box/manager/memstore/memstore.go Index: box/manager/memstore/memstore.go ================================================================== --- box/manager/memstore/memstore.go +++ /dev/null @@ -1,598 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package memstore stored the index in main memory. -package memstore - -import ( - "context" - "fmt" - "io" - "sort" - "strings" - "sync" - - "zettelstore.de/c/api" - "zettelstore.de/c/maps" - "zettelstore.de/z/box/manager/store" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -type metaRefs struct { - forward id.Slice - backward id.Slice -} - -type zettelIndex struct { - dead id.Slice - forward id.Slice - backward id.Slice - meta map[string]metaRefs - words []string - urls []string - itags string // Inline tags -} - -func (zi *zettelIndex) isEmpty() bool { - if len(zi.forward) > 0 || len(zi.backward) > 0 || len(zi.dead) > 0 || len(zi.words) > 0 { - return false - } - return len(zi.meta) == 0 -} - -type stringRefs map[string]id.Slice - -type memStore struct { - mx sync.RWMutex - idx map[id.Zid]*zettelIndex - dead map[id.Zid]id.Slice // map dead refs where they occur - words stringRefs - urls stringRefs - - // Stats - updates uint64 -} - -// New returns a new memory-based index store. -func New() store.Store { - return &memStore{ - idx: make(map[id.Zid]*zettelIndex), - dead: make(map[id.Zid]id.Slice), - words: make(stringRefs), - urls: make(stringRefs), - } -} - -func (ms *memStore) Enrich(_ context.Context, m *meta.Meta) { - if ms.doEnrich(m) { - ms.mx.Lock() - ms.updates++ - ms.mx.Unlock() - } -} - -func (ms *memStore) doEnrich(m *meta.Meta) bool { - ms.mx.RLock() - defer ms.mx.RUnlock() - zi, ok := ms.idx[m.Zid] - if !ok { - return false - } - var updated bool - if len(zi.dead) > 0 { - m.Set(api.KeyDead, zi.dead.String()) - updated = true - } - back := removeOtherMetaRefs(m, zi.backward.Copy()) - if len(zi.backward) > 0 { - m.Set(api.KeyBackward, zi.backward.String()) - updated = true - } - if len(zi.forward) > 0 { - m.Set(api.KeyForward, zi.forward.String()) - back = remRefs(back, zi.forward) - updated = true - } - for k, refs := range zi.meta { - if len(refs.backward) > 0 { - m.Set(k, refs.backward.String()) - back = remRefs(back, refs.backward) - updated = true - } - } - if len(back) > 0 { - m.Set(api.KeyBack, back.String()) - updated = true - } - if itags := zi.itags; itags != "" { - m.Set(api.KeyContentTags, itags) - if tags, ok2 := m.Get(api.KeyTags); ok2 { - m.Set(api.KeyAllTags, tags+" "+itags) - } else { - m.Set(api.KeyAllTags, itags) - } - updated = true - } else if tags, ok2 := m.Get(api.KeyTags); ok2 { - m.Set(api.KeyAllTags, tags) - updated = true - } - return updated -} - -// SearchEqual returns all zettel that contains the given exact word. -// The word must be normalized through Unicode NKFD, trimmed and not empty. -func (ms *memStore) SearchEqual(word string) id.Set { - ms.mx.RLock() - defer ms.mx.RUnlock() - result := id.NewSet() - if refs, ok := ms.words[word]; ok { - result.AddSlice(refs) - } - if refs, ok := ms.urls[word]; ok { - result.AddSlice(refs) - } - zid, err := id.Parse(word) - if err != nil { - return result - } - zi, ok := ms.idx[zid] - if !ok { - return result - } - - addBackwardZids(result, zid, zi) - return result -} - -// SearchPrefix returns all zettel that have a word with the given prefix. -// The prefix must be normalized through Unicode NKFD, trimmed and not empty. -func (ms *memStore) SearchPrefix(prefix string) id.Set { - ms.mx.RLock() - defer ms.mx.RUnlock() - result := ms.selectWithPred(prefix, strings.HasPrefix) - l := len(prefix) - if l > 14 { - return result - } - minZid, err := id.Parse(prefix + "00000000000000"[:14-l]) - if err != nil { - return result - } - maxZid, err := id.Parse(prefix + "99999999999999"[:14-l]) - if err != nil { - return result - } - for zid, zi := range ms.idx { - if minZid <= zid && zid <= maxZid { - addBackwardZids(result, zid, zi) - } - } - return result -} - -// SearchSuffix returns all zettel that have a word with the given suffix. -// The suffix must be normalized through Unicode NKFD, trimmed and not empty. -func (ms *memStore) SearchSuffix(suffix string) id.Set { - ms.mx.RLock() - defer ms.mx.RUnlock() - result := ms.selectWithPred(suffix, strings.HasSuffix) - l := len(suffix) - if l > 14 { - return result - } - val, err := id.ParseUint(suffix) - if err != nil { - return result - } - modulo := uint64(1) - for i := 0; i < l; i++ { - modulo *= 10 - } - for zid, zi := range ms.idx { - if uint64(zid)%modulo == val { - addBackwardZids(result, zid, zi) - } - } - return result -} - -// SearchContains returns all zettel that contains the given string. -// The string must be normalized through Unicode NKFD, trimmed and not empty. -func (ms *memStore) SearchContains(s string) id.Set { - ms.mx.RLock() - defer ms.mx.RUnlock() - result := ms.selectWithPred(s, strings.Contains) - if len(s) > 14 { - return result - } - if _, err := id.ParseUint(s); err != nil { - return result - } - for zid, zi := range ms.idx { - if strings.Contains(zid.String(), s) { - addBackwardZids(result, zid, zi) - } - } - return result -} - -func (ms *memStore) selectWithPred(s string, pred func(string, string) bool) id.Set { - // Must only be called if ms.mx is read-locked! - result := id.NewSet() - for word, refs := range ms.words { - if !pred(word, s) { - continue - } - result.AddSlice(refs) - } - for u, refs := range ms.urls { - if !pred(u, s) { - continue - } - result.AddSlice(refs) - } - return result -} - -func addBackwardZids(result id.Set, zid id.Zid, zi *zettelIndex) { - // Must only be called if ms.mx is read-locked! - result.Zid(zid) - result.AddSlice(zi.backward) - for _, mref := range zi.meta { - result.AddSlice(mref.backward) - } -} - -func removeOtherMetaRefs(m *meta.Meta, back id.Slice) id.Slice { - for _, p := range m.PairsRest() { - switch meta.Type(p.Key) { - case meta.TypeID: - if zid, err := id.Parse(p.Value); err == nil { - back = remRef(back, zid) - } - case meta.TypeIDSet: - for _, val := range meta.ListFromValue(p.Value) { - if zid, err := id.Parse(val); err == nil { - back = remRef(back, zid) - } - } - } - } - return back -} - -func (ms *memStore) UpdateReferences(_ context.Context, zidx *store.ZettelIndex) id.Set { - ms.mx.Lock() - defer ms.mx.Unlock() - zi, ziExist := ms.idx[zidx.Zid] - if !ziExist || zi == nil { - zi = &zettelIndex{} - ziExist = false - } - - // Is this zettel an old dead reference mentioned in other zettel? - var toCheck id.Set - if refs, ok := ms.dead[zidx.Zid]; ok { - // These must be checked later again - toCheck = id.NewSet(refs...) - delete(ms.dead, zidx.Zid) - } - - ms.updateDeadReferences(zidx, zi) - ms.updateForwardBackwardReferences(zidx, zi) - ms.updateMetadataReferences(zidx, zi) - zi.words = updateWordSet(zidx.Zid, ms.words, zi.words, zidx.GetWords()) - zi.urls = updateWordSet(zidx.Zid, ms.urls, zi.urls, zidx.GetUrls()) - zi.itags = setITags(zidx.GetITags()) - - // Check if zi must be inserted into ms.idx - if !ziExist && !zi.isEmpty() { - ms.idx[zidx.Zid] = zi - } - - return toCheck -} - -func (ms *memStore) updateDeadReferences(zidx *store.ZettelIndex, zi *zettelIndex) { - // Must only be called if ms.mx is write-locked! - drefs := zidx.GetDeadRefs() - newRefs, remRefs := refsDiff(drefs, zi.dead) - zi.dead = drefs - for _, ref := range remRefs { - ms.dead[ref] = remRef(ms.dead[ref], zidx.Zid) - } - for _, ref := range newRefs { - ms.dead[ref] = addRef(ms.dead[ref], zidx.Zid) - } -} - -func (ms *memStore) updateForwardBackwardReferences(zidx *store.ZettelIndex, zi *zettelIndex) { - // Must only be called if ms.mx is write-locked! - brefs := zidx.GetBackRefs() - newRefs, remRefs := refsDiff(brefs, zi.forward) - zi.forward = brefs - for _, ref := range remRefs { - bzi := ms.getEntry(ref) - bzi.backward = remRef(bzi.backward, zidx.Zid) - } - for _, ref := range newRefs { - bzi := ms.getEntry(ref) - bzi.backward = addRef(bzi.backward, zidx.Zid) - } -} - -func (ms *memStore) updateMetadataReferences(zidx *store.ZettelIndex, zi *zettelIndex) { - // Must only be called if ms.mx is write-locked! - metarefs := zidx.GetMetaRefs() - for key, mr := range zi.meta { - if _, ok := metarefs[key]; ok { - continue - } - ms.removeInverseMeta(zidx.Zid, key, mr.forward) - } - if zi.meta == nil { - zi.meta = make(map[string]metaRefs) - } - for key, mrefs := range metarefs { - mr := zi.meta[key] - newRefs, remRefs := refsDiff(mrefs, mr.forward) - mr.forward = mrefs - zi.meta[key] = mr - - for _, ref := range newRefs { - bzi := ms.getEntry(ref) - if bzi.meta == nil { - bzi.meta = make(map[string]metaRefs) - } - bmr := bzi.meta[key] - bmr.backward = addRef(bmr.backward, zidx.Zid) - bzi.meta[key] = bmr - } - ms.removeInverseMeta(zidx.Zid, key, remRefs) - } -} - -func updateWordSet(zid id.Zid, srefs stringRefs, prev []string, next store.WordSet) []string { - // Must only be called if ms.mx is write-locked! - newWords, removeWords := next.Diff(prev) - for _, word := range newWords { - if refs, ok := srefs[word]; ok { - srefs[word] = addRef(refs, zid) - continue - } - srefs[word] = id.Slice{zid} - } - for _, word := range removeWords { - refs, ok := srefs[word] - if !ok { - continue - } - refs2 := remRef(refs, zid) - if len(refs2) == 0 { - delete(srefs, word) - continue - } - srefs[word] = refs2 - } - return next.Words() -} - -func setITags(next store.WordSet) string { - itags := next.Words() - if len(itags) == 0 { - return "" - } - sort.Strings(itags) - return strings.Join(itags, " ") -} - -func (ms *memStore) getEntry(zid id.Zid) *zettelIndex { - // Must only be called if ms.mx is write-locked! - if zi, ok := ms.idx[zid]; ok { - return zi - } - zi := &zettelIndex{} - ms.idx[zid] = zi - return zi -} - -func (ms *memStore) DeleteZettel(_ context.Context, zid id.Zid) id.Set { - ms.mx.Lock() - defer ms.mx.Unlock() - - zi, ok := ms.idx[zid] - if !ok { - return nil - } - - ms.deleteDeadSources(zid, zi) - toCheck := ms.deleteForwardBackward(zid, zi) - if len(zi.meta) > 0 { - for key, mrefs := range zi.meta { - ms.removeInverseMeta(zid, key, mrefs.forward) - } - } - ms.deleteWords(zid, zi.words) - delete(ms.idx, zid) - return toCheck -} - -func (ms *memStore) deleteDeadSources(zid id.Zid, zi *zettelIndex) { - // Must only be called if ms.mx is write-locked! - for _, ref := range zi.dead { - if drefs, ok := ms.dead[ref]; ok { - drefs = remRef(drefs, zid) - if len(drefs) > 0 { - ms.dead[ref] = drefs - } else { - delete(ms.dead, ref) - } - } - } -} - -func (ms *memStore) deleteForwardBackward(zid id.Zid, zi *zettelIndex) id.Set { - // Must only be called if ms.mx is write-locked! - var toCheck id.Set - for _, ref := range zi.forward { - if fzi, ok := ms.idx[ref]; ok { - fzi.backward = remRef(fzi.backward, zid) - } - } - for _, ref := range zi.backward { - if bzi, ok := ms.idx[ref]; ok { - bzi.forward = remRef(bzi.forward, zid) - if toCheck == nil { - toCheck = id.NewSet() - } - toCheck.Zid(ref) - } - } - return toCheck -} - -func (ms *memStore) removeInverseMeta(zid id.Zid, key string, forward id.Slice) { - // Must only be called if ms.mx is write-locked! - for _, ref := range forward { - bzi, ok := ms.idx[ref] - if !ok || bzi.meta == nil { - continue - } - bmr, ok := bzi.meta[key] - if !ok { - continue - } - bmr.backward = remRef(bmr.backward, zid) - if len(bmr.backward) > 0 || len(bmr.forward) > 0 { - bzi.meta[key] = bmr - } else { - delete(bzi.meta, key) - if len(bzi.meta) == 0 { - bzi.meta = nil - } - } - } -} - -func (ms *memStore) deleteWords(zid id.Zid, words []string) { - // Must only be called if ms.mx is write-locked! - for _, word := range words { - refs, ok := ms.words[word] - if !ok { - continue - } - refs2 := remRef(refs, zid) - if len(refs2) == 0 { - delete(ms.words, word) - continue - } - ms.words[word] = refs2 - } -} - -func (ms *memStore) ReadStats(st *store.Stats) { - ms.mx.RLock() - st.Zettel = len(ms.idx) - st.Updates = ms.updates - st.Words = uint64(len(ms.words)) - st.Urls = uint64(len(ms.urls)) - ms.mx.RUnlock() -} - -func (ms *memStore) Dump(w io.Writer) { - ms.mx.RLock() - defer ms.mx.RUnlock() - - io.WriteString(w, "=== Dump\n") - ms.dumpIndex(w) - ms.dumpDead(w) - dumpStringRefs(w, "Words", "", "", ms.words) - dumpStringRefs(w, "URLs", "[[", "]]", ms.urls) -} - -func (ms *memStore) dumpIndex(w io.Writer) { - if len(ms.idx) == 0 { - return - } - io.WriteString(w, "==== Zettel Index\n") - zids := make(id.Slice, 0, len(ms.idx)) - for id := range ms.idx { - zids = append(zids, id) - } - zids.Sort() - for _, id := range zids { - fmt.Fprintln(w, "=====", id) - zi := ms.idx[id] - if len(zi.dead) > 0 { - fmt.Fprintln(w, "* Dead:", zi.dead) - } - dumpZids(w, "* Forward:", zi.forward) - dumpZids(w, "* Backward:", zi.backward) - for k, fb := range zi.meta { - fmt.Fprintln(w, "* Meta", k) - dumpZids(w, "** Forward:", fb.forward) - dumpZids(w, "** Backward:", fb.backward) - } - dumpStrings(w, "* Words", "", "", zi.words) - dumpStrings(w, "* URLs", "[[", "]]", zi.urls) - } -} - -func (ms *memStore) dumpDead(w io.Writer) { - if len(ms.dead) == 0 { - return - } - fmt.Fprintf(w, "==== Dead References\n") - zids := make(id.Slice, 0, len(ms.dead)) - for id := range ms.dead { - zids = append(zids, id) - } - zids.Sort() - for _, id := range zids { - fmt.Fprintln(w, ";", id) - fmt.Fprintln(w, ":", ms.dead[id]) - } -} - -func dumpZids(w io.Writer, prefix string, zids id.Slice) { - if len(zids) > 0 { - io.WriteString(w, prefix) - for _, zid := range zids { - io.WriteString(w, " ") - w.Write(zid.Bytes()) - } - fmt.Fprintln(w) - } -} - -func dumpStrings(w io.Writer, title, preString, postString string, slice []string) { - if len(slice) > 0 { - sl := make([]string, len(slice)) - copy(sl, slice) - sort.Strings(sl) - fmt.Fprintln(w, title) - for _, s := range sl { - fmt.Fprintf(w, "** %s%s%s\n", preString, s, postString) - } - } - -} - -func dumpStringRefs(w io.Writer, title, preString, postString string, srefs stringRefs) { - if len(srefs) == 0 { - return - } - fmt.Fprintln(w, "====", title) - for _, s := range maps.Keys(srefs) { - fmt.Fprintf(w, "; %s%s%s\n", preString, s, postString) - fmt.Fprintln(w, ":", srefs[s]) - } -} DELETED box/manager/memstore/refs.go Index: box/manager/memstore/refs.go ================================================================== --- box/manager/memstore/refs.go +++ /dev/null @@ -1,100 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package memstore - -import "zettelstore.de/z/domain/id" - -func refsDiff(refsN, refsO id.Slice) (newRefs, remRefs id.Slice) { - npos, opos := 0, 0 - for npos < len(refsN) && opos < len(refsO) { - rn, ro := refsN[npos], refsO[opos] - if rn == ro { - npos++ - opos++ - continue - } - if rn < ro { - newRefs = append(newRefs, rn) - npos++ - continue - } - remRefs = append(remRefs, ro) - opos++ - } - if npos < len(refsN) { - newRefs = append(newRefs, refsN[npos:]...) - } - if opos < len(refsO) { - remRefs = append(remRefs, refsO[opos:]...) - } - return newRefs, remRefs -} - -func addRef(refs id.Slice, ref id.Zid) id.Slice { - hi := len(refs) - for lo := 0; lo < hi; { - m := lo + (hi-lo)/2 - if r := refs[m]; r == ref { - return refs - } else if r < ref { - lo = m + 1 - } else { - hi = m - } - } - refs = append(refs, id.Invalid) - copy(refs[hi+1:], refs[hi:]) - refs[hi] = ref - return refs -} - -func remRefs(refs, rem id.Slice) id.Slice { - if len(refs) == 0 || len(rem) == 0 { - return refs - } - result := make(id.Slice, 0, len(refs)) - rpos, dpos := 0, 0 - for rpos < len(refs) && dpos < len(rem) { - rr, dr := refs[rpos], rem[dpos] - if rr < dr { - result = append(result, rr) - rpos++ - continue - } - if dr < rr { - dpos++ - continue - } - rpos++ - dpos++ - } - if rpos < len(refs) { - result = append(result, refs[rpos:]...) - } - return result -} - -func remRef(refs id.Slice, ref id.Zid) id.Slice { - hi := len(refs) - for lo := 0; lo < hi; { - m := lo + (hi-lo)/2 - if r := refs[m]; r == ref { - copy(refs[m:], refs[m+1:]) - refs = refs[:len(refs)-1] - return refs - } else if r < ref { - lo = m + 1 - } else { - hi = m - } - } - return refs -} DELETED box/manager/memstore/refs_test.go Index: box/manager/memstore/refs_test.go ================================================================== --- box/manager/memstore/refs_test.go +++ /dev/null @@ -1,137 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package memstore - -import ( - "testing" - - "zettelstore.de/z/domain/id" -) - -func assertRefs(t *testing.T, i int, got, exp id.Slice) { - t.Helper() - if got == nil && exp != nil { - t.Errorf("%d: got nil, but expected %v", i, exp) - return - } - if got != nil && exp == nil { - t.Errorf("%d: expected nil, but got %v", i, got) - return - } - if len(got) != len(exp) { - t.Errorf("%d: expected len(%v)==%d, but got len(%v)==%d", i, exp, len(exp), got, len(got)) - return - } - for p, n := range exp { - if got := got[p]; got != id.Zid(n) { - t.Errorf("%d: pos %d: expected %d, but got %d", i, p, n, got) - } - } -} - -func TestRefsDiff(t *testing.T) { - t.Parallel() - testcases := []struct { - in1, in2 id.Slice - exp1, exp2 id.Slice - }{ - {nil, nil, nil, nil}, - {id.Slice{1}, nil, id.Slice{1}, nil}, - {nil, id.Slice{1}, nil, id.Slice{1}}, - {id.Slice{1}, id.Slice{1}, nil, nil}, - {id.Slice{1, 2}, id.Slice{1}, id.Slice{2}, nil}, - {id.Slice{1, 2}, id.Slice{1, 3}, id.Slice{2}, id.Slice{3}}, - {id.Slice{1, 4}, id.Slice{1, 3}, id.Slice{4}, id.Slice{3}}, - } - for i, tc := range testcases { - got1, got2 := refsDiff(tc.in1, tc.in2) - assertRefs(t, i, got1, tc.exp1) - assertRefs(t, i, got2, tc.exp2) - } -} - -func TestAddRef(t *testing.T) { - t.Parallel() - testcases := []struct { - ref id.Slice - zid uint - exp id.Slice - }{ - {nil, 5, id.Slice{5}}, - {id.Slice{1}, 5, id.Slice{1, 5}}, - {id.Slice{10}, 5, id.Slice{5, 10}}, - {id.Slice{5}, 5, id.Slice{5}}, - {id.Slice{1, 10}, 5, id.Slice{1, 5, 10}}, - {id.Slice{1, 5, 10}, 5, id.Slice{1, 5, 10}}, - } - for i, tc := range testcases { - got := addRef(tc.ref, id.Zid(tc.zid)) - assertRefs(t, i, got, tc.exp) - } -} - -func TestRemRefs(t *testing.T) { - t.Parallel() - testcases := []struct { - in1, in2 id.Slice - exp id.Slice - }{ - {nil, nil, nil}, - {nil, id.Slice{}, nil}, - {id.Slice{}, nil, id.Slice{}}, - {id.Slice{}, id.Slice{}, id.Slice{}}, - {id.Slice{1}, id.Slice{5}, id.Slice{1}}, - {id.Slice{10}, id.Slice{5}, id.Slice{10}}, - {id.Slice{1, 5}, id.Slice{5}, id.Slice{1}}, - {id.Slice{5, 10}, id.Slice{5}, id.Slice{10}}, - {id.Slice{1, 10}, id.Slice{5}, id.Slice{1, 10}}, - {id.Slice{1}, id.Slice{2, 5}, id.Slice{1}}, - {id.Slice{10}, id.Slice{2, 5}, id.Slice{10}}, - {id.Slice{1, 5}, id.Slice{2, 5}, id.Slice{1}}, - {id.Slice{5, 10}, id.Slice{2, 5}, id.Slice{10}}, - {id.Slice{1, 2, 5}, id.Slice{2, 5}, id.Slice{1}}, - {id.Slice{2, 5, 10}, id.Slice{2, 5}, id.Slice{10}}, - {id.Slice{1, 10}, id.Slice{2, 5}, id.Slice{1, 10}}, - {id.Slice{1}, id.Slice{5, 9}, id.Slice{1}}, - {id.Slice{10}, id.Slice{5, 9}, id.Slice{10}}, - {id.Slice{1, 5}, id.Slice{5, 9}, id.Slice{1}}, - {id.Slice{5, 10}, id.Slice{5, 9}, id.Slice{10}}, - {id.Slice{1, 5, 9}, id.Slice{5, 9}, id.Slice{1}}, - {id.Slice{5, 9, 10}, id.Slice{5, 9}, id.Slice{10}}, - {id.Slice{1, 10}, id.Slice{5, 9}, id.Slice{1, 10}}, - } - for i, tc := range testcases { - got := remRefs(tc.in1, tc.in2) - assertRefs(t, i, got, tc.exp) - } -} - -func TestRemRef(t *testing.T) { - t.Parallel() - testcases := []struct { - ref id.Slice - zid uint - exp id.Slice - }{ - {nil, 5, nil}, - {id.Slice{}, 5, id.Slice{}}, - {id.Slice{5}, 5, id.Slice{}}, - {id.Slice{1}, 5, id.Slice{1}}, - {id.Slice{10}, 5, id.Slice{10}}, - {id.Slice{1, 5}, 5, id.Slice{1}}, - {id.Slice{5, 10}, 5, id.Slice{10}}, - {id.Slice{1, 5, 10}, 5, id.Slice{1, 10}}, - } - for i, tc := range testcases { - got := remRef(tc.ref, id.Zid(tc.zid)) - assertRefs(t, i, got, tc.exp) - } -} DELETED box/manager/store/store.go Index: box/manager/store/store.go ================================================================== --- box/manager/store/store.go +++ /dev/null @@ -1,59 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package store contains general index data for storing a zettel index. -package store - -import ( - "context" - "io" - - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/search" -) - -// Stats records statistics about the store. -type Stats struct { - // Zettel is the number of zettel managed by the indexer. - Zettel int - - // Updates count the number of metadata updates. - Updates uint64 - - // Words count the different words stored in the store. - Words uint64 - - // Urls count the different URLs stored in the store. - Urls uint64 -} - -// Store all relevant zettel data. There may be multiple implementations, i.e. -// memory-based, file-based, based on SQLite, ... -type Store interface { - search.Searcher - - // Entrich metadata with data from store. - Enrich(ctx context.Context, m *meta.Meta) - - // UpdateReferences for a specific zettel. - // Returns set of zettel identifier that must also be checked for changes. - UpdateReferences(context.Context, *ZettelIndex) id.Set - - // DeleteZettel removes index data for given zettel. - // Returns set of zettel identifier that must also be checked for changes. - DeleteZettel(context.Context, id.Zid) id.Set - - // ReadStats populates st with store statistics. - ReadStats(st *Stats) - - // Dump the content to a Writer. - Dump(io.Writer) -} DELETED box/manager/store/wordset.go Index: box/manager/store/wordset.go ================================================================== --- box/manager/store/wordset.go +++ /dev/null @@ -1,60 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package store - -// WordSet contains the set of all words, with the count of their occurrences. -type WordSet map[string]int - -// NewWordSet returns a new WordSet. -func NewWordSet() WordSet { return make(WordSet) } - -// Add one word to the set -func (ws WordSet) Add(s string) { - ws[s] = ws[s] + 1 -} - -// Words gives the slice of all words in the set. -func (ws WordSet) Words() []string { - if len(ws) == 0 { - return nil - } - words := make([]string, 0, len(ws)) - for w := range ws { - words = append(words, w) - } - return words -} - -// Diff calculates the word slice to be added and to be removed from oldWords -// to get the given word set. -func (ws WordSet) Diff(oldWords []string) (newWords, removeWords []string) { - if len(ws) == 0 { - return nil, oldWords - } - if len(oldWords) == 0 { - return ws.Words(), nil - } - oldSet := make(WordSet, len(oldWords)) - for _, ow := range oldWords { - if _, ok := ws[ow]; ok { - oldSet[ow] = 1 - continue - } - removeWords = append(removeWords, ow) - } - for w := range ws { - if _, ok := oldSet[w]; ok { - continue - } - newWords = append(newWords, w) - } - return newWords, removeWords -} DELETED box/manager/store/wordset_test.go Index: box/manager/store/wordset_test.go ================================================================== --- box/manager/store/wordset_test.go +++ /dev/null @@ -1,77 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package store_test - -import ( - "sort" - "testing" - - "zettelstore.de/z/box/manager/store" -) - -func equalWordList(exp, got []string) bool { - if len(exp) != len(got) { - return false - } - if len(got) == 0 { - return len(exp) == 0 - } - sort.Strings(got) - for i, w := range exp { - if w != got[i] { - return false - } - } - return true -} - -func TestWordsWords(t *testing.T) { - t.Parallel() - testcases := []struct { - words store.WordSet - exp []string - }{ - {nil, nil}, - {store.WordSet{}, nil}, - {store.WordSet{"a": 1, "b": 2}, []string{"a", "b"}}, - } - for i, tc := range testcases { - got := tc.words.Words() - if !equalWordList(tc.exp, got) { - t.Errorf("%d: %v.Words() == %v, but got %v", i, tc.words, tc.exp, got) - } - } -} - -func TestWordsDiff(t *testing.T) { - t.Parallel() - testcases := []struct { - cur store.WordSet - old []string - expN, expR []string - }{ - {nil, nil, nil, nil}, - {store.WordSet{}, []string{}, nil, nil}, - {store.WordSet{"a": 1}, []string{}, []string{"a"}, nil}, - {store.WordSet{"a": 1}, []string{"b"}, []string{"a"}, []string{"b"}}, - {store.WordSet{}, []string{"b"}, nil, []string{"b"}}, - {store.WordSet{"a": 1}, []string{"a"}, nil, nil}, - } - for i, tc := range testcases { - gotN, gotR := tc.cur.Diff(tc.old) - if !equalWordList(tc.expN, gotN) { - t.Errorf("%d: %v.Diff(%v)->new %v, but got %v", i, tc.cur, tc.old, tc.expN, gotN) - } - if !equalWordList(tc.expR, gotR) { - t.Errorf("%d: %v.Diff(%v)->rem %v, but got %v", i, tc.cur, tc.old, tc.expR, gotR) - } - } -} DELETED box/manager/store/zettel.go Index: box/manager/store/zettel.go ================================================================== --- box/manager/store/zettel.go +++ /dev/null @@ -1,95 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package store - -import "zettelstore.de/z/domain/id" - -// ZettelIndex contains all index data of a zettel. -type ZettelIndex struct { - Zid id.Zid // zid of the indexed zettel - backrefs id.Set // set of back references - metarefs map[string]id.Set // references to inverse keys - deadrefs id.Set // set of dead references - words WordSet - urls WordSet - itags WordSet -} - -// NewZettelIndex creates a new zettel index. -func NewZettelIndex(zid id.Zid) *ZettelIndex { - return &ZettelIndex{ - Zid: zid, - backrefs: id.NewSet(), - metarefs: make(map[string]id.Set), - deadrefs: id.NewSet(), - } -} - -// AddBackRef adds a reference to a zettel where the current zettel links to -// without any more information. -func (zi *ZettelIndex) AddBackRef(zid id.Zid) { - zi.backrefs.Zid(zid) -} - -// AddMetaRef adds a named reference to a zettel. On that zettel, the given -// metadata key should point back to the current zettel. -func (zi *ZettelIndex) AddMetaRef(key string, zid id.Zid) { - if zids, ok := zi.metarefs[key]; ok { - zids.Zid(zid) - return - } - zi.metarefs[key] = id.NewSet(zid) -} - -// AddDeadRef adds a dead reference to a zettel. -func (zi *ZettelIndex) AddDeadRef(zid id.Zid) { - zi.deadrefs.Zid(zid) -} - -// SetWords sets the words to the given value. -func (zi *ZettelIndex) SetWords(words WordSet) { zi.words = words } - -// SetUrls sets the words to the given value. -func (zi *ZettelIndex) SetUrls(urls WordSet) { zi.urls = urls } - -// SetITags sets the words to the given value. -func (zi *ZettelIndex) SetITags(itags WordSet) { zi.itags = itags } - -// GetDeadRefs returns all dead references as a sorted list. -func (zi *ZettelIndex) GetDeadRefs() id.Slice { - return zi.deadrefs.Sorted() -} - -// GetBackRefs returns all back references as a sorted list. -func (zi *ZettelIndex) GetBackRefs() id.Slice { - return zi.backrefs.Sorted() -} - -// GetMetaRefs returns all meta references as a map of strings to a sorted list of references -func (zi *ZettelIndex) GetMetaRefs() map[string]id.Slice { - if len(zi.metarefs) == 0 { - return nil - } - result := make(map[string]id.Slice, len(zi.metarefs)) - for key, refs := range zi.metarefs { - result[key] = refs.Sorted() - } - return result -} - -// GetWords returns a reference to the set of words. It must not be modified. -func (zi *ZettelIndex) GetWords() WordSet { return zi.words } - -// GetUrls returns a reference to the set of URLs. It must not be modified. -func (zi *ZettelIndex) GetUrls() WordSet { return zi.urls } - -// GetITags returns a reference to the set of internal tags. It must not be modified. -func (zi *ZettelIndex) GetITags() WordSet { return zi.itags } DELETED box/membox/membox.go Index: box/membox/membox.go ================================================================== --- box/membox/membox.go +++ /dev/null @@ -1,257 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package membox stores zettel volatile in main memory. -package membox - -import ( - "context" - "net/url" - "sync" - - "zettelstore.de/z/box" - "zettelstore.de/z/box/manager" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" - "zettelstore.de/z/search" -) - -func init() { - manager.Register( - "mem", - func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) { - return &memBox{ - log: kernel.Main.GetLogger(kernel.BoxService).Clone(). - Str("box", "mem").Int("boxnum", int64(cdata.Number)).Child(), - u: u, - cdata: *cdata, - maxZettel: box.GetQueryInt(u, "max-zettel", 0, 127, 65535), - maxBytes: box.GetQueryInt(u, "max-bytes", 0, 65535, (1024*1024*1024)-1), - }, nil - }) -} - -type memBox struct { - log *logger.Logger - u *url.URL - cdata manager.ConnectData - maxZettel int - maxBytes int - mx sync.RWMutex // Protects the following fields - zettel map[id.Zid]domain.Zettel - curBytes int -} - -func (mb *memBox) notifyChanged(reason box.UpdateReason, zid id.Zid) { - if chci := mb.cdata.Notify; chci != nil { - chci <- box.UpdateInfo{Reason: reason, Zid: zid} - } -} - -func (mb *memBox) Location() string { - return mb.u.String() -} - -func (mb *memBox) Start(context.Context) error { - mb.mx.Lock() - mb.zettel = make(map[id.Zid]domain.Zettel) - mb.curBytes = 0 - mb.mx.Unlock() - mb.log.Trace().Int("max-zettel", int64(mb.maxZettel)).Int("max-bytes", int64(mb.maxBytes)).Msg("Start Box") - return nil -} - -func (mb *memBox) Stop(context.Context) { - mb.mx.Lock() - mb.zettel = nil - mb.mx.Unlock() -} - -func (mb *memBox) CanCreateZettel(context.Context) bool { - mb.mx.RLock() - defer mb.mx.RUnlock() - return len(mb.zettel) < mb.maxZettel -} - -func (mb *memBox) CreateZettel(_ context.Context, zettel domain.Zettel) (id.Zid, error) { - mb.mx.Lock() - newBytes := mb.curBytes + zettel.Length() - if mb.maxZettel < len(mb.zettel) || mb.maxBytes < newBytes { - mb.mx.Unlock() - return id.Invalid, box.ErrCapacity - } - zid, err := box.GetNewZid(func(zid id.Zid) (bool, error) { - _, ok := mb.zettel[zid] - return !ok, nil - }) - if err != nil { - mb.mx.Unlock() - return id.Invalid, err - } - meta := zettel.Meta.Clone() - meta.Zid = zid - zettel.Meta = meta - mb.zettel[zid] = zettel - mb.curBytes = newBytes - mb.mx.Unlock() - mb.notifyChanged(box.OnUpdate, zid) - mb.log.Trace().Zid(zid).Msg("CreateZettel") - return zid, nil -} - -func (mb *memBox) GetZettel(_ context.Context, zid id.Zid) (domain.Zettel, error) { - mb.mx.RLock() - zettel, ok := mb.zettel[zid] - mb.mx.RUnlock() - if !ok { - return domain.Zettel{}, box.ErrNotFound - } - zettel.Meta = zettel.Meta.Clone() - mb.log.Trace().Msg("GetZettel") - return zettel, nil -} - -func (mb *memBox) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) { - mb.mx.RLock() - zettel, ok := mb.zettel[zid] - mb.mx.RUnlock() - if !ok { - return nil, box.ErrNotFound - } - mb.log.Trace().Msg("GetMeta") - return zettel.Meta.Clone(), nil -} - -func (mb *memBox) ApplyZid(_ context.Context, handle box.ZidFunc, constraint search.RetrievePredicate) error { - mb.mx.RLock() - defer mb.mx.RUnlock() - mb.log.Trace().Int("entries", int64(len(mb.zettel))).Msg("ApplyZid") - for zid := range mb.zettel { - if constraint(zid) { - handle(zid) - } - } - return nil -} - -func (mb *memBox) ApplyMeta(ctx context.Context, handle box.MetaFunc, constraint search.RetrievePredicate) error { - mb.mx.RLock() - defer mb.mx.RUnlock() - mb.log.Trace().Int("entries", int64(len(mb.zettel))).Msg("ApplyMeta") - for zid, zettel := range mb.zettel { - if constraint(zid) { - m := zettel.Meta.Clone() - mb.cdata.Enricher.Enrich(ctx, m, mb.cdata.Number) - handle(m) - } - } - return nil -} - -func (mb *memBox) CanUpdateZettel(_ context.Context, zettel domain.Zettel) bool { - mb.mx.RLock() - defer mb.mx.RUnlock() - zid := zettel.Meta.Zid - if !zid.IsValid() { - return false - } - - newBytes := mb.curBytes + zettel.Length() - if prevZettel, found := mb.zettel[zid]; found { - newBytes -= prevZettel.Length() - } - return newBytes < mb.maxBytes -} - -func (mb *memBox) UpdateZettel(_ context.Context, zettel domain.Zettel) error { - m := zettel.Meta.Clone() - if !m.Zid.IsValid() { - return &box.ErrInvalidID{Zid: m.Zid} - } - - mb.mx.Lock() - newBytes := mb.curBytes + zettel.Length() - if prevZettel, found := mb.zettel[m.Zid]; found { - newBytes -= prevZettel.Length() - } - if mb.maxBytes < newBytes { - mb.mx.Unlock() - return box.ErrCapacity - } - - zettel.Meta = m - mb.zettel[m.Zid] = zettel - mb.curBytes = newBytes - mb.mx.Unlock() - mb.notifyChanged(box.OnUpdate, m.Zid) - mb.log.Trace().Msg("UpdateZettel") - return nil -} - -func (*memBox) AllowRenameZettel(context.Context, id.Zid) bool { return true } - -func (mb *memBox) RenameZettel(_ context.Context, curZid, newZid id.Zid) error { - mb.mx.Lock() - zettel, ok := mb.zettel[curZid] - if !ok { - mb.mx.Unlock() - return box.ErrNotFound - } - - // Check that there is no zettel with newZid - if _, ok = mb.zettel[newZid]; ok { - mb.mx.Unlock() - return &box.ErrInvalidID{Zid: newZid} - } - - meta := zettel.Meta.Clone() - meta.Zid = newZid - zettel.Meta = meta - mb.zettel[newZid] = zettel - delete(mb.zettel, curZid) - mb.mx.Unlock() - mb.notifyChanged(box.OnDelete, curZid) - mb.notifyChanged(box.OnUpdate, newZid) - mb.log.Trace().Msg("RenameZettel") - return nil -} - -func (mb *memBox) CanDeleteZettel(_ context.Context, zid id.Zid) bool { - mb.mx.RLock() - _, ok := mb.zettel[zid] - mb.mx.RUnlock() - return ok -} - -func (mb *memBox) DeleteZettel(_ context.Context, zid id.Zid) error { - mb.mx.Lock() - oldZettel, found := mb.zettel[zid] - if !found { - mb.mx.Unlock() - return box.ErrNotFound - } - delete(mb.zettel, zid) - mb.curBytes -= oldZettel.Length() - mb.mx.Unlock() - mb.notifyChanged(box.OnDelete, zid) - mb.log.Trace().Msg("DeleteZettel") - return nil -} - -func (mb *memBox) ReadStats(st *box.ManagedBoxStats) { - st.ReadOnly = false - mb.mx.RLock() - st.Zettel = len(mb.zettel) - mb.mx.RUnlock() - mb.log.Trace().Int("zettel", int64(st.Zettel)).Msg("ReadStats") -} DELETED box/notify/directory.go Index: box/notify/directory.go ================================================================== --- box/notify/directory.go +++ /dev/null @@ -1,575 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package notify - -import ( - "errors" - "fmt" - "path/filepath" - "regexp" - "strings" - "sync" - - "zettelstore.de/z/box" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/logger" - "zettelstore.de/z/parser" - "zettelstore.de/z/search" - "zettelstore.de/z/strfun" -) - -type entrySet map[id.Zid]*DirEntry - -// directoryState signal the internal state of the service. -// -// The following state transitions are possible: -// --newDirService--> dsCreated -// dsCreated --Start--> dsStarting -// dsStarting --last list notification--> dsWorking -// dsWorking --directory missing--> dsMissing -// dsMissing --last list notification--> dsWorking -// --Stop--> dsStopping -type directoryState uint8 - -const ( - dsCreated directoryState = iota - dsStarting // Reading inital scan - dsWorking // Initial scan complete, fully operational - dsMissing // Directory is missing - dsStopping // Service is shut down -) - -// DirService specifies a directory service for file based zettel. -type DirService struct { - log *logger.Logger - dirPath string - notifier Notifier - infos chan<- box.UpdateInfo - mx sync.RWMutex // protects status, entries - state directoryState - entries entrySet -} - -// ErrNoDirectory signals missing directory data. -var ErrNoDirectory = errors.New("unable to retrieve zettel directory information") - -// NewDirService creates a new directory service. -func NewDirService(log *logger.Logger, notifier Notifier, chci chan<- box.UpdateInfo) *DirService { - return &DirService{ - log: log, - notifier: notifier, - infos: chci, - state: dsCreated, - } -} - -// Start the directory service. -func (ds *DirService) Start() { - ds.mx.Lock() - ds.state = dsStarting - ds.mx.Unlock() - go ds.updateEvents() -} - -// Refresh the directory entries. -func (ds *DirService) Refresh() { - ds.notifier.Refresh() -} - -// Stop the directory service. -func (ds *DirService) Stop() { - ds.mx.Lock() - ds.state = dsStopping - ds.mx.Unlock() - ds.notifier.Close() -} - -func (ds *DirService) logMissingEntry(action string) error { - err := ErrNoDirectory - ds.log.Info().Err(err).Str("action", action).Msg("Unable to get directory information") - return err -} - -// NumDirEntries returns the number of entries in the directory. -func (ds *DirService) NumDirEntries() int { - ds.mx.RLock() - defer ds.mx.RUnlock() - if ds.entries == nil { - return 0 - } - return len(ds.entries) -} - -// GetDirEntries returns a list of directory entries, which satisfy the given constraint. -func (ds *DirService) GetDirEntries(constraint search.RetrievePredicate) []*DirEntry { - ds.mx.RLock() - defer ds.mx.RUnlock() - if ds.entries == nil { - return nil - } - result := make([]*DirEntry, 0, len(ds.entries)) - for zid, entry := range ds.entries { - if constraint(zid) { - copiedEntry := *entry - result = append(result, &copiedEntry) - } - } - return result -} - -// GetDirEntry returns a directory entry with the given zid, or nil if not found. -func (ds *DirService) GetDirEntry(zid id.Zid) *DirEntry { - ds.mx.RLock() - defer ds.mx.RUnlock() - if ds.entries == nil { - return nil - } - foundEntry := ds.entries[zid] - if foundEntry == nil { - return nil - } - result := *foundEntry - return &result -} - -// SetNewDirEntry calculates an empty directory entry with an unused identifier and -// stores it in the directory. -func (ds *DirService) SetNewDirEntry() (id.Zid, error) { - ds.mx.Lock() - defer ds.mx.Unlock() - if ds.entries == nil { - return id.Invalid, ds.logMissingEntry("new") - } - zid, err := box.GetNewZid(func(zid id.Zid) (bool, error) { - _, found := ds.entries[zid] - return !found, nil - }) - if err != nil { - return id.Invalid, err - } - ds.entries[zid] = &DirEntry{Zid: zid} - return zid, nil -} - -// UpdateDirEntry updates an directory entry in place. -func (ds *DirService) UpdateDirEntry(updatedEntry *DirEntry) error { - entry := *updatedEntry - ds.mx.Lock() - defer ds.mx.Unlock() - if ds.entries == nil { - return ds.logMissingEntry("update") - } - ds.entries[entry.Zid] = &entry - return nil -} - -// RenameDirEntry replaces an existing directory entry with a new one. -func (ds *DirService) RenameDirEntry(oldEntry *DirEntry, newZid id.Zid) (DirEntry, error) { - ds.mx.Lock() - defer ds.mx.Unlock() - if ds.entries == nil { - return DirEntry{}, ds.logMissingEntry("rename") - } - if _, found := ds.entries[newZid]; found { - return DirEntry{}, &box.ErrInvalidID{Zid: newZid} - } - oldZid := oldEntry.Zid - newEntry := DirEntry{ - Zid: newZid, - MetaName: renameFilename(oldEntry.MetaName, oldZid, newZid), - ContentName: renameFilename(oldEntry.ContentName, oldZid, newZid), - ContentExt: oldEntry.ContentExt, - // Duplicates must not be set, because duplicates will be deleted - } - delete(ds.entries, oldZid) - ds.entries[newZid] = &newEntry - return newEntry, nil -} - -func renameFilename(name string, curID, newID id.Zid) string { - if cur := curID.String(); strings.HasPrefix(name, cur) { - name = newID.String() + name[len(cur):] - } - return name -} - -// DeleteDirEntry removes a entry from the directory. -func (ds *DirService) DeleteDirEntry(zid id.Zid) error { - ds.mx.Lock() - defer ds.mx.Unlock() - if ds.entries == nil { - return ds.logMissingEntry("delete") - } - delete(ds.entries, zid) - return nil -} - -func (ds *DirService) updateEvents() { - var newEntries entrySet - for ev := range ds.notifier.Events() { - ds.mx.RLock() - state := ds.state - ds.mx.RUnlock() - - if msg := ds.log.Trace(); msg.Enabled() { - msg.Uint("state", uint64(state)).Str("op", ev.Op.String()).Str("name", ev.Name).Msg("notifyEvent") - } - if state == dsStopping { - break - } - - switch ev.Op { - case Error: - newEntries = nil - if state != dsMissing { - ds.log.Warn().Err(ev.Err).Msg("Notifier confused") - } - case Make: - newEntries = make(entrySet) - case List: - if ev.Name == "" { - zids := getNewZids(newEntries) - ds.mx.Lock() - fromMissing := ds.state == dsMissing - prevEntries := ds.entries - ds.entries = newEntries - ds.state = dsWorking - ds.mx.Unlock() - newEntries = nil - ds.onCreateDirectory(zids, prevEntries) - if fromMissing { - ds.log.Info().Str("path", ds.dirPath).Msg("Zettel directory found") - } - } else if newEntries != nil { - ds.onUpdateFileEvent(newEntries, ev.Name) - } - case Destroy: - newEntries = nil - ds.onDestroyDirectory() - ds.log.Error().Str("path", ds.dirPath).Msg("Zettel directory missing") - case Update: - ds.mx.Lock() - zid := ds.onUpdateFileEvent(ds.entries, ev.Name) - ds.mx.Unlock() - if zid != id.Invalid { - ds.notifyChange(box.OnUpdate, zid) - } - case Delete: - ds.mx.Lock() - ds.onDeleteFileEvent(ds.entries, ev.Name) - ds.mx.Unlock() - default: - ds.log.Warn().Str("event", fmt.Sprintf("%v", ev)).Msg("Unknown zettel notification event") - } - } -} - -func getNewZids(entries entrySet) id.Slice { - zids := make(id.Slice, 0, len(entries)) - for zid := range entries { - zids = append(zids, zid) - } - return zids -} - -func (ds *DirService) onCreateDirectory(zids id.Slice, prevEntries entrySet) { - for _, zid := range zids { - ds.notifyChange(box.OnUpdate, zid) - delete(prevEntries, zid) - } - - // These were previously stored, by are not found now. - // Notify system that these were deleted, e.g. for updating the index. - for zid := range prevEntries { - ds.notifyChange(box.OnDelete, zid) - } -} - -func (ds *DirService) onDestroyDirectory() { - ds.mx.Lock() - entries := ds.entries - ds.entries = nil - ds.state = dsMissing - ds.mx.Unlock() - for zid := range entries { - ds.notifyChange(box.OnDelete, zid) - } -} - -var validFileName = regexp.MustCompile(`^(\d{14})`) - -func matchValidFileName(name string) []string { - return validFileName.FindStringSubmatch(name) -} - -func seekZid(name string) id.Zid { - match := matchValidFileName(name) - if len(match) == 0 { - return id.Invalid - } - zid, err := id.Parse(match[1]) - if err != nil { - return id.Invalid - } - return zid -} - -func fetchdirEntry(entries entrySet, zid id.Zid) *DirEntry { - if entry, found := entries[zid]; found { - return entry - } - entry := &DirEntry{Zid: zid} - entries[zid] = entry - return entry -} - -func (ds *DirService) onUpdateFileEvent(entries entrySet, name string) id.Zid { - if entries == nil { - return id.Invalid - } - zid := seekZid(name) - if zid == id.Invalid { - return id.Invalid - } - entry := fetchdirEntry(entries, zid) - dupName1, dupName2 := ds.updateEntry(entry, name) - if dupName1 != "" { - ds.log.Warn().Str("name", dupName1).Msg("Duplicate content (is ignored)") - if dupName2 != "" { - ds.log.Warn().Str("name", dupName2).Msg("Duplicate content (is ignored)") - } - } - return zid -} - -func (ds *DirService) onDeleteFileEvent(entries entrySet, name string) { - if entries == nil { - return - } - zid := seekZid(name) - if zid == id.Invalid { - return - } - entry, found := entries[zid] - if !found { - return - } - for i, dupName := range entry.UselessFiles { - if dupName == name { - removeDuplicate(entry, i) - return - } - } - if name == entry.ContentName { - entry.ContentName = "" - entry.ContentExt = "" - ds.replayUpdateUselessFiles(entry) - } else if name == entry.MetaName { - entry.MetaName = "" - ds.replayUpdateUselessFiles(entry) - } - if entry.ContentName == "" && entry.MetaName == "" { - delete(entries, zid) - ds.notifyChange(box.OnDelete, zid) - } -} - -func removeDuplicate(entry *DirEntry, i int) { - if len(entry.UselessFiles) == 1 { - entry.UselessFiles = nil - return - } - entry.UselessFiles = entry.UselessFiles[:i+copy(entry.UselessFiles[i:], entry.UselessFiles[i+1:])] -} - -func (ds *DirService) replayUpdateUselessFiles(entry *DirEntry) { - uselessFiles := entry.UselessFiles - if len(uselessFiles) == 0 { - return - } - entry.UselessFiles = make([]string, 0, len(uselessFiles)) - for _, name := range uselessFiles { - ds.updateEntry(entry, name) - } - if len(uselessFiles) == len(entry.UselessFiles) { - return - } -loop: - for _, prevName := range uselessFiles { - for _, newName := range entry.UselessFiles { - if prevName == newName { - continue loop - } - } - ds.log.Info().Str("name", prevName).Msg("Previous duplicate file becomes useful") - } -} - -func (ds *DirService) updateEntry(entry *DirEntry, name string) (string, string) { - ext := onlyExt(name) - if !extIsMetaAndContent(entry.ContentExt) { - if ext == "" { - return updateEntryMeta(entry, name), "" - } - if entry.MetaName == "" { - if nameWithoutExt(name, ext) == entry.ContentName { - // We have marked a file as content file, but it is a metadata file, - // because it is the same as the new file without extension. - entry.MetaName = entry.ContentName - entry.ContentName = "" - entry.ContentExt = "" - ds.replayUpdateUselessFiles(entry) - } else if entry.ContentName != "" && nameWithoutExt(entry.ContentName, entry.ContentExt) == name { - // We have already a valid content file, and new file should serve as metadata file, - // because it is the same as the content file without extension. - entry.MetaName = name - return "", "" - } - } - } - return updateEntryContent(entry, name, ext) -} - -func nameWithoutExt(name, ext string) string { - return name[0 : len(name)-len(ext)-1] -} - -func updateEntryMeta(entry *DirEntry, name string) string { - metaName := entry.MetaName - if metaName == "" { - entry.MetaName = name - return "" - } - if metaName == name { - return "" - } - if newNameIsBetter(metaName, name) { - entry.MetaName = name - return addUselessFile(entry, metaName) - } - return addUselessFile(entry, name) -} - -func updateEntryContent(entry *DirEntry, name, ext string) (string, string) { - contentName := entry.ContentName - if contentName == "" { - entry.ContentName = name - entry.ContentExt = ext - return "", "" - } - if contentName == name { - return "", "" - } - contentExt := entry.ContentExt - if contentExt == ext { - if newNameIsBetter(contentName, name) { - entry.ContentName = name - return addUselessFile(entry, contentName), "" - } - return addUselessFile(entry, name), "" - } - if contentExt == extZettel { - return addUselessFile(entry, name), "" - } - if ext == extZettel { - entry.ContentName = name - entry.ContentExt = ext - contentName = addUselessFile(entry, contentName) - if metaName := entry.MetaName; metaName != "" { - metaName = addUselessFile(entry, metaName) - entry.MetaName = "" - return contentName, metaName - } - return contentName, "" - } - if newExtIsBetter(contentExt, ext) { - entry.ContentName = name - entry.ContentExt = ext - return addUselessFile(entry, contentName), "" - } - return addUselessFile(entry, name), "" -} -func addUselessFile(entry *DirEntry, name string) string { - for _, dupName := range entry.UselessFiles { - if name == dupName { - return "" - } - } - entry.UselessFiles = append(entry.UselessFiles, name) - return name -} - -func onlyExt(name string) string { - ext := filepath.Ext(name) - if ext == "" || ext[0] != '.' { - return ext - } - return ext[1:] -} - -func newNameIsBetter(oldName, newName string) bool { - if len(oldName) < len(newName) { - return false - } - return oldName > newName -} - -var supportedSyntax, primarySyntax strfun.Set - -func init() { - syntaxList := parser.GetSyntaxes() - supportedSyntax = strfun.NewSet(syntaxList...) - primarySyntax = make(map[string]struct{}, len(syntaxList)) - for _, syntax := range syntaxList { - if parser.Get(syntax).Name == syntax { - primarySyntax.Set(syntax) - } - } -} -func newExtIsBetter(oldExt, newExt string) bool { - oldSyntax := supportedSyntax.Has(oldExt) - if oldSyntax != supportedSyntax.Has(newExt) { - return !oldSyntax - } - if oldSyntax { - if oldExt == "zmk" { - return false - } - if newExt == "zmk" { - return true - } - oldInfo := parser.Get(oldExt) - newInfo := parser.Get(newExt) - if oldTextParser := oldInfo.IsTextParser; oldTextParser != newInfo.IsTextParser { - return !oldTextParser - } - if oldImageFormat := oldInfo.IsImageFormat; oldImageFormat != newInfo.IsImageFormat { - return oldImageFormat - } - if oldPrimary := primarySyntax.Has(oldExt); oldPrimary != primarySyntax.Has(newExt) { - return !oldPrimary - } - } - - oldLen := len(oldExt) - newLen := len(newExt) - if oldLen != newLen { - return newLen < oldLen - } - return newExt < oldExt -} - -func (ds *DirService) notifyChange(reason box.UpdateReason, zid id.Zid) { - if chci := ds.infos; chci != nil { - ds.log.Trace().Zid(zid).Uint("reason", uint64(reason)).Msg("notifyChange") - chci <- box.UpdateInfo{Reason: reason, Zid: zid} - } -} DELETED box/notify/directory_test.go Index: box/notify/directory_test.go ================================================================== --- box/notify/directory_test.go +++ /dev/null @@ -1,72 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package notify - -import ( - "testing" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - _ "zettelstore.de/z/parser/blob" // Allow to use BLOB parser. - _ "zettelstore.de/z/parser/markdown" // Allow to use markdown parser. - _ "zettelstore.de/z/parser/none" // Allow to use none parser. - _ "zettelstore.de/z/parser/plain" // Allow to use plain parser. - _ "zettelstore.de/z/parser/zettelmark" // Allow to use zettelmark parser. -) - -func TestSeekZid(t *testing.T) { - testcases := []struct { - name string - zid id.Zid - }{ - {"", id.Invalid}, - {"1", id.Invalid}, - {"1234567890123", id.Invalid}, - {" 12345678901234", id.Invalid}, - {"12345678901234", id.Zid(12345678901234)}, - {"12345678901234.ext", id.Zid(12345678901234)}, - {"12345678901234 abc.ext", id.Zid(12345678901234)}, - {"12345678901234.abc.ext", id.Zid(12345678901234)}, - {"12345678901234 def", id.Zid(12345678901234)}, - } - for _, tc := range testcases { - gotZid := seekZid(tc.name) - if gotZid != tc.zid { - t.Errorf("seekZid(%q) == %v, but got %v", tc.name, tc.zid, gotZid) - } - } -} - -func TestNewExtIsBetter(t *testing.T) { - extVals := []string{ - // Main Formats - api.ValueSyntaxZmk, "markdown", "md", - // Other supported text formats - "css", "txt", api.ValueSyntaxHTML, api.ValueSyntaxNone, "mustache", api.ValueSyntaxText, "plain", - // Supported graphics formats - api.ValueSyntaxGif, "png", api.ValueSyntaxSVG, "jpeg", "jpg", - // Unsupported syntax values - "gz", "cpp", "tar", "cppc", - } - for oldI, oldExt := range extVals { - for newI, newExt := range extVals { - if oldI <= newI { - continue - } - if !newExtIsBetter(oldExt, newExt) { - t.Errorf("newExtIsBetter(%q, %q) == true, but got false", oldExt, newExt) - } - if newExtIsBetter(newExt, oldExt) { - t.Errorf("newExtIsBetter(%q, %q) == false, but got true", newExt, oldExt) - } - } - } -} DELETED box/notify/entry.go Index: box/notify/entry.go ================================================================== --- box/notify/entry.go +++ /dev/null @@ -1,120 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package notify - -import ( - "path/filepath" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/parser" -) - -const ( - extZettel = "zettel" // file contains metadata and content - extBin = "bin" // file contains binary content - extTxt = "txt" // file contains non-binary content -) - -func extIsMetaAndContent(ext string) bool { return ext == extZettel } - -// DirEntry stores everything for a directory entry. -type DirEntry struct { - Zid id.Zid - MetaName string // file name of meta information - ContentName string // file name of zettel content - ContentExt string // (normalized) file extension of zettel content - UselessFiles []string // list of other content files -} - -// IsValid checks whether the entry is valid. -func (e *DirEntry) IsValid() bool { - return e != nil && e.Zid.IsValid() -} - -// HasMetaInContent returns true, if metadata will be stored in the content file. -func (e *DirEntry) HasMetaInContent() bool { - return e.IsValid() && extIsMetaAndContent(e.ContentExt) -} - -// SetupFromMetaContent fills entry data based on metadata and zettel content. -func (e *DirEntry) SetupFromMetaContent(m *meta.Meta, content domain.Content, getZettelFileSyntax func() []string) { - if e.Zid != m.Zid { - panic("Zid differ") - } - if contentName := e.ContentName; contentName != "" { - if !extIsMetaAndContent(e.ContentExt) && e.MetaName == "" { - e.MetaName = e.calcBaseName(contentName) - } - return - } - - syntax := m.GetDefault(api.KeySyntax, "") - ext := calcContentExt(syntax, m.YamlSep, getZettelFileSyntax) - metaName := e.MetaName - eimc := extIsMetaAndContent(ext) - if eimc { - if metaName != "" { - ext = contentExtWithMeta(syntax, content) - } - e.ContentName = e.calcBaseName(metaName) + "." + ext - e.ContentExt = ext - } else { - if len(content.AsBytes()) > 0 { - e.ContentName = e.calcBaseName(metaName) + "." + ext - e.ContentExt = ext - } - if metaName == "" { - e.MetaName = e.calcBaseName(e.ContentName) - } - } -} - -func contentExtWithMeta(syntax string, content domain.Content) string { - p := parser.Get(syntax) - if content.IsBinary() { - if p.IsImageFormat { - return syntax - } - return extBin - } - if p.IsImageFormat { - return extTxt - } - return syntax -} - -func calcContentExt(syntax string, yamlSep bool, getZettelFileSyntax func() []string) string { - if yamlSep { - return extZettel - } - switch syntax { - case api.ValueSyntaxNone, api.ValueSyntaxZmk: - return extZettel - } - for _, s := range getZettelFileSyntax() { - if s == syntax { - return extZettel - } - } - return syntax - -} - -func (e *DirEntry) calcBaseName(name string) string { - if name == "" { - return e.Zid.String() - } - return name[0 : len(name)-len(filepath.Ext(name))] - -} DELETED box/notify/fsdir.go Index: box/notify/fsdir.go ================================================================== --- box/notify/fsdir.go +++ /dev/null @@ -1,198 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package notify - -import ( - "os" - "path/filepath" - "strings" - - "github.com/fsnotify/fsnotify" - "zettelstore.de/z/logger" -) - -type fsdirNotifier struct { - log *logger.Logger - events chan Event - done chan struct{} - refresh chan struct{} - base *fsnotify.Watcher - path string - fetcher EntryFetcher - parent string -} - -// NewFSDirNotifier creates a directory based notifier that receives notifications -// from the file system. -func NewFSDirNotifier(log *logger.Logger, path string) (Notifier, error) { - absPath, err := filepath.Abs(path) - if err != nil { - log.Debug().Err(err).Str("path", path).Msg("Unable to create absolute path") - return nil, err - } - watcher, err := fsnotify.NewWatcher() - if err != nil { - log.Debug().Err(err).Str("absPath", absPath).Msg("Unable to create watcher") - return nil, err - } - absParentDir := filepath.Dir(absPath) - errParent := watcher.Add(absParentDir) - err = watcher.Add(absPath) - if errParent != nil { - if err != nil { - log.Error(). - Str("parentDir", absParentDir).Err(errParent). - Str("path", absPath).Err(err). - Msg("Unable to access Zettel directory and its parent directory") - watcher.Close() - return nil, err - } - log.Warn(). - Str("parentDir", absParentDir).Err(errParent). - Msg("Parent of Zettel directory cannot be supervised") - log.Warn().Str("path", absPath). - Msg("Zettelstore might not detect a deletion or movement of the Zettel directory") - } else if err != nil { - // Not a problem, if container is not available. It might become available later. - log.Warn().Err(err).Str("path", absPath).Msg("Zettel directory not available") - } - - fsdn := &fsdirNotifier{ - log: log, - events: make(chan Event), - refresh: make(chan struct{}), - done: make(chan struct{}), - base: watcher, - path: absPath, - fetcher: newDirPathFetcher(absPath), - parent: absParentDir, - } - go fsdn.eventLoop() - return fsdn, nil -} - -func (fsdn *fsdirNotifier) Events() <-chan Event { - return fsdn.events -} - -func (fsdn *fsdirNotifier) Refresh() { - fsdn.refresh <- struct{}{} -} - -func (fsdn *fsdirNotifier) eventLoop() { - defer fsdn.base.Close() - defer close(fsdn.events) - defer close(fsdn.refresh) - if !listDirElements(fsdn.log, fsdn.fetcher, fsdn.events, fsdn.done) { - return - } - for fsdn.readAndProcessEvent() { - } -} - -func (fsdn *fsdirNotifier) readAndProcessEvent() bool { - select { - case <-fsdn.done: - return false - default: - } - select { - case <-fsdn.done: - return false - case <-fsdn.refresh: - listDirElements(fsdn.log, fsdn.fetcher, fsdn.events, fsdn.done) - case err, ok := <-fsdn.base.Errors: - if !ok { - return false - } - select { - case fsdn.events <- Event{Op: Error, Err: err}: - case <-fsdn.done: - return false - } - case ev, ok := <-fsdn.base.Events: - if !ok { - return false - } - if !fsdn.processEvent(&ev) { - return false - } - } - return true -} - -func (fsdn *fsdirNotifier) processEvent(ev *fsnotify.Event) bool { - if strings.HasPrefix(ev.Name, fsdn.path) { - if len(ev.Name) == len(fsdn.path) { - return fsdn.processDirEvent(ev) - } - return fsdn.processFileEvent(ev) - } - return true -} - -const deleteFsOps = fsnotify.Remove | fsnotify.Rename -const updateFsOps = fsnotify.Create | fsnotify.Write - -func (fsdn *fsdirNotifier) processDirEvent(ev *fsnotify.Event) bool { - if ev.Op&deleteFsOps != 0 { - fsdn.log.Debug().Str("name", fsdn.path).Msg("Directory removed") - fsdn.base.Remove(fsdn.path) - select { - case fsdn.events <- Event{Op: Destroy}: - case <-fsdn.done: - return false - } - return true - } - if ev.Op&fsnotify.Create != 0 { - err := fsdn.base.Add(fsdn.path) - if err != nil { - fsdn.log.IfErr(err).Str("name", fsdn.path).Msg("Unable to add directory") - select { - case fsdn.events <- Event{Op: Error, Err: err}: - case <-fsdn.done: - return false - } - } - fsdn.log.Debug().Str("name", fsdn.path).Msg("Directory added") - return listDirElements(fsdn.log, fsdn.fetcher, fsdn.events, fsdn.done) - } - return true -} - -func (fsdn *fsdirNotifier) processFileEvent(ev *fsnotify.Event) bool { - if ev.Op&deleteFsOps != 0 { - fsdn.log.Trace().Str("name", ev.Name).Uint("op", uint64(ev.Op)).Msg("File deleted") - select { - case fsdn.events <- Event{Op: Delete, Name: filepath.Base(ev.Name)}: - case <-fsdn.done: - return false - } - return true - } - if ev.Op&updateFsOps != 0 { - if fi, err := os.Lstat(ev.Name); err != nil || !fi.Mode().IsRegular() { - return true - } - fsdn.log.Trace().Str("name", ev.Name).Uint("op", uint64(ev.Op)).Msg("File updated") - select { - case fsdn.events <- Event{Op: Update, Name: filepath.Base(ev.Name)}: - case <-fsdn.done: - return false - } - } - return true -} - -func (fsdn *fsdirNotifier) Close() { - close(fsdn.done) -} DELETED box/notify/helper.go Index: box/notify/helper.go ================================================================== --- box/notify/helper.go +++ /dev/null @@ -1,100 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package notify - -import ( - "archive/zip" - "os" - - "zettelstore.de/z/logger" -) - -// MakeMetaFilename builds the name of the file containing metadata. -func MakeMetaFilename(basename string) string { - return basename //+ ".meta" -} - -// EntryFetcher return a list of (file) names of an directory. -type EntryFetcher interface { - Fetch() ([]string, error) -} - -type dirPathFetcher struct { - dirPath string -} - -func newDirPathFetcher(dirPath string) EntryFetcher { return &dirPathFetcher{dirPath} } - -func (dpf *dirPathFetcher) Fetch() ([]string, error) { - entries, err := os.ReadDir(dpf.dirPath) - if err != nil { - return nil, err - } - result := make([]string, 0, len(entries)) - for _, entry := range entries { - if info, err1 := entry.Info(); err1 != nil || !info.Mode().IsRegular() { - continue - } - result = append(result, entry.Name()) - } - return result, nil -} - -type zipPathFetcher struct { - zipPath string -} - -func newZipPathFetcher(zipPath string) EntryFetcher { return &zipPathFetcher{zipPath} } - -func (zpf *zipPathFetcher) Fetch() ([]string, error) { - reader, err := zip.OpenReader(zpf.zipPath) - if err != nil { - return nil, err - } - defer reader.Close() - result := make([]string, 0, len(reader.File)) - for _, f := range reader.File { - result = append(result, f.Name) - } - return result, nil -} - -// listDirElements write all files within the directory path as events. -func listDirElements(log *logger.Logger, fetcher EntryFetcher, events chan<- Event, done <-chan struct{}) bool { - select { - case events <- Event{Op: Make}: - case <-done: - return false - } - entries, err := fetcher.Fetch() - if err != nil { - select { - case events <- Event{Op: Error, Err: err}: - case <-done: - return false - } - } - for _, name := range entries { - log.Trace().Str("name", name).Msg("File listed") - select { - case events <- Event{Op: List, Name: name}: - case <-done: - return false - } - } - - select { - case events <- Event{Op: List}: - case <-done: - return false - } - return true -} DELETED box/notify/notify.go Index: box/notify/notify.go ================================================================== --- box/notify/notify.go +++ /dev/null @@ -1,82 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package notify provides some notification services to be used by box services. -package notify - -import "fmt" - -// Notifier send events about their container and content. -type Notifier interface { - // Return the channel - Events() <-chan Event - - // Signal a refresh of the container. This will result in some events. - Refresh() - - // Close the notifier (and eventually the channel) - Close() -} - -// EventOp describe a notification operation. -type EventOp uint8 - -// Valid constants for event operations. -// -// Error signals a detected error. Details are in Event.Err. -// -// Make signals that the container is detected. List events will follow. -// -// List signals a found file, if Event.Name is not empty. Otherwise it signals -// the end of files within the container. -// -// Destroy signals that the container is not there any more. It might me Make later again. -// -// Update signals that file Event.Name was created/updated. File name is relative -// to the container. -// -// Delete signals that file Event.Name was removed. File name is relative to -// the container's name. -const ( - _ EventOp = iota - Error // Error while operating - Make // Make container - List // List container - Destroy // Destroy container - Update // Update element - Delete // Delete element -) - -// String representation of operation code. -func (c EventOp) String() string { - switch c { - case Error: - return "ERROR" - case Make: - return "MAKE" - case List: - return "LIST" - case Destroy: - return "DESTROY" - case Update: - return "UPDATE" - case Delete: - return "DELETE" - default: - return fmt.Sprintf("UNKNOWN(%d)", c) - } -} - -// Event represents a single container / element event. -type Event struct { - Op EventOp - Name string - Err error // Valid iff Op == Error -} DELETED box/notify/simpledir.go Index: box/notify/simpledir.go ================================================================== --- box/notify/simpledir.go +++ /dev/null @@ -1,85 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package notify - -import ( - "path/filepath" - - "zettelstore.de/z/logger" -) - -type simpleDirNotifier struct { - log *logger.Logger - events chan Event - done chan struct{} - refresh chan struct{} - fetcher EntryFetcher -} - -// NewSimpleDirNotifier creates a directory based notifier that will not receive -// any notifications from the operating system. -func NewSimpleDirNotifier(log *logger.Logger, path string) (Notifier, error) { - absPath, err := filepath.Abs(path) - if err != nil { - return nil, err - } - sdn := &simpleDirNotifier{ - log: log, - events: make(chan Event), - done: make(chan struct{}), - refresh: make(chan struct{}), - fetcher: newDirPathFetcher(absPath), - } - go sdn.eventLoop() - return sdn, nil -} - -// NewSimpleZipNotifier creates a zip-file based notifier that will not receive -// any notifications from the operating system. -func NewSimpleZipNotifier(log *logger.Logger, zipPath string) (Notifier, error) { - sdn := &simpleDirNotifier{ - log: log, - events: make(chan Event), - done: make(chan struct{}), - refresh: make(chan struct{}), - fetcher: newZipPathFetcher(zipPath), - } - go sdn.eventLoop() - return sdn, nil -} - -func (sdn *simpleDirNotifier) Events() <-chan Event { - return sdn.events -} - -func (sdn *simpleDirNotifier) Refresh() { - sdn.refresh <- struct{}{} -} - -func (sdn *simpleDirNotifier) eventLoop() { - defer close(sdn.events) - defer close(sdn.refresh) - if !listDirElements(sdn.log, sdn.fetcher, sdn.events, sdn.done) { - return - } - for { - select { - case <-sdn.done: - return - case <-sdn.refresh: - listDirElements(sdn.log, sdn.fetcher, sdn.events, sdn.done) - } - } -} - -func (sdn *simpleDirNotifier) Close() { - close(sdn.done) -} Index: cmd/cmd_file.go ================================================================== --- cmd/cmd_file.go +++ cmd/cmd_file.go @@ -1,30 +1,35 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern +// Copyright (c) 2020-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- package cmd import ( + "context" "flag" "fmt" "io" "os" - "zettelstore.de/c/api" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/encoder" - "zettelstore.de/z/input" - "zettelstore.de/z/parser" + "t73f.de/r/zsc/api" + "t73f.de/r/zsc/domain/id" + "t73f.de/r/zsc/domain/meta" + "t73f.de/r/zsx/input" + + "zettelstore.de/z/internal/encoder" + "zettelstore.de/z/internal/parser" + "zettelstore.de/z/internal/zettel" ) // ---------- Subcommand: file ----------------------------------------------- func cmdFile(fs *flag.FlagSet) (int, error) { @@ -32,23 +37,26 @@ m, inp, err := getInput(fs.Args()) if m == nil { return 2, err } z := parser.ParseZettel( - domain.Zettel{ + context.Background(), + zettel.Zettel{ Meta: m, - Content: domain.NewContent(inp.Src[inp.Pos:]), + Content: zettel.NewContent(inp.Src[inp.Pos:]), }, - m.GetDefault(api.KeySyntax, api.ValueSyntaxZmk), + string(m.GetDefault(meta.KeySyntax, meta.DefaultSyntax)), nil, ) - encdr := encoder.Create(api.Encoder(enc)) + encdr := encoder.Create( + api.Encoder(enc), + &encoder.CreateParameter{Lang: string(m.GetDefault(meta.KeyLang, meta.ValueLangEN))}) if encdr == nil { fmt.Fprintf(os.Stderr, "Unknown format %q\n", enc) return 2, nil } - _, err = encdr.WriteZettel(os.Stdout, z, parser.ParseMetadata) + _, err = encdr.WriteZettel(os.Stdout, z) if err != nil { return 2, err } fmt.Println() Index: cmd/cmd_password.go ================================================================== --- cmd/cmd_password.go +++ cmd/cmd_password.go @@ -1,13 +1,16 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern +// Copyright (c) 2020-present Detlef Stern // -// This file is part of zettelstore. +// This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- package cmd import ( @@ -15,13 +18,14 @@ "fmt" "os" "golang.org/x/term" - "zettelstore.de/c/api" - "zettelstore.de/z/auth/cred" - "zettelstore.de/z/domain/id" + "t73f.de/r/zsc/domain/id" + "t73f.de/r/zsc/domain/meta" + + "zettelstore.de/z/internal/auth/cred" ) // ---------- Subcommand: password ------------------------------------------- func cmdPassword(fs *flag.FlagSet) (int, error) { @@ -58,12 +62,12 @@ hashedPassword, err := cred.HashCredential(zid, ident, password) if err != nil { return 2, err } fmt.Printf("%v: %s\n%v: %s\n", - api.KeyCredential, hashedPassword, - api.KeyUserID, ident, + meta.KeyCredential, hashedPassword, + meta.KeyUserID, ident, ) return 0, nil } func getPassword(prompt string) (string, error) { Index: cmd/cmd_run.go ================================================================== --- cmd/cmd_run.go +++ cmd/cmd_run.go @@ -1,28 +1,36 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern +// Copyright (c) 2020-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- package cmd import ( + "context" "flag" - - "zettelstore.de/z/auth" - "zettelstore.de/z/box" - "zettelstore.de/z/config" - "zettelstore.de/z/kernel" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter/api" - "zettelstore.de/z/web/adapter/webui" - "zettelstore.de/z/web/server" + "net/http" + + "t73f.de/r/zsc/domain/meta" + + "zettelstore.de/z/internal/auth" + "zettelstore.de/z/internal/auth/user" + "zettelstore.de/z/internal/box" + "zettelstore.de/z/internal/config" + "zettelstore.de/z/internal/kernel" + "zettelstore.de/z/internal/usecase" + "zettelstore.de/z/internal/web/adapter/api" + "zettelstore.de/z/internal/web/adapter/webui" + "zettelstore.de/z/internal/web/server" ) // ---------- Subcommand: run ------------------------------------------------ func flgRun(fs *flag.FlagSet) { @@ -44,98 +52,89 @@ kernel.Main.WaitForShutdown() return exitCode, err } func setupRouting(webSrv server.Server, boxManager box.Manager, authManager auth.Manager, rtConfig config.Config) { - protectedBoxManager, authPolicy := authManager.BoxWithPolicy(webSrv, boxManager, rtConfig) + protectedBoxManager, authPolicy := authManager.BoxWithPolicy(boxManager, rtConfig) kern := kernel.Main - webLog := kern.GetLogger(kernel.WebService) - a := api.New( - webLog.Clone().Str("adapter", "api").Child(), - webSrv, authManager, authManager, webSrv, rtConfig, authPolicy) - wui := webui.New( - webLog.Clone().Str("adapter", "wui").Child(), - webSrv, authManager, rtConfig, authManager, boxManager, authPolicy) - - authLog := kern.GetLogger(kernel.AuthService) - ucLog := kern.GetLogger(kernel.CoreService).WithUser(webSrv) - ucAuthenticate := usecase.NewAuthenticate(authLog, authManager, authManager, boxManager) - ucIsAuth := usecase.NewIsAuthenticated(ucLog, webSrv, authManager) - ucCreateZettel := usecase.NewCreateZettel(ucLog, rtConfig, protectedBoxManager) - ucGetMeta := usecase.NewGetMeta(protectedBoxManager) - ucGetAllMeta := usecase.NewGetAllMeta(protectedBoxManager) + webLogger := kern.GetLogger(kernel.WebService) + + var getUser getUserImpl + authLogger := kern.GetLogger(kernel.AuthService) + ucLogger := kern.GetLogger(kernel.CoreService) + ucGetUser := usecase.NewGetUser(authManager, boxManager) + ucAuthenticate := usecase.NewAuthenticate(authLogger, authManager, &ucGetUser) + ucIsAuth := usecase.NewIsAuthenticated(ucLogger, &getUser, authManager) + ucCreateZettel := usecase.NewCreateZettel(ucLogger, rtConfig, protectedBoxManager) + ucGetAllZettel := usecase.NewGetAllZettel(protectedBoxManager) ucGetZettel := usecase.NewGetZettel(protectedBoxManager) ucParseZettel := usecase.NewParseZettel(rtConfig, ucGetZettel) - ucEvaluate := usecase.NewEvaluate(rtConfig, ucGetZettel, ucGetMeta) - ucListMeta := usecase.NewListMeta(protectedBoxManager) + ucGetReferences := usecase.NewGetReferences() + ucQuery := usecase.NewQuery(protectedBoxManager) + ucEvaluate := usecase.NewEvaluate(rtConfig, &ucGetZettel, &ucQuery) + ucQuery.SetEvaluate(&ucEvaluate) + ucTagZettel := usecase.NewTagZettel(protectedBoxManager, &ucQuery) + ucRoleZettel := usecase.NewRoleZettel(protectedBoxManager, &ucQuery) ucListSyntax := usecase.NewListSyntax(protectedBoxManager) ucListRoles := usecase.NewListRoles(protectedBoxManager) - ucListTags := usecase.NewListTags(protectedBoxManager) - ucZettelContext := usecase.NewZettelContext(protectedBoxManager, rtConfig) - ucDelete := usecase.NewDeleteZettel(ucLog, protectedBoxManager) - ucUpdate := usecase.NewUpdateZettel(ucLog, protectedBoxManager) - ucRename := usecase.NewRenameZettel(ucLog, protectedBoxManager) - ucUnlinkedRefs := usecase.NewUnlinkedReferences(protectedBoxManager, rtConfig) - ucRefresh := usecase.NewRefresh(ucLog, protectedBoxManager) + ucDelete := usecase.NewDeleteZettel(ucLogger, protectedBoxManager) + ucUpdate := usecase.NewUpdateZettel(ucLogger, protectedBoxManager) + ucRefresh := usecase.NewRefresh(ucLogger, protectedBoxManager) + ucReIndex := usecase.NewReIndex(ucLogger, protectedBoxManager) ucVersion := usecase.NewVersion(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreVersion).(string)) + a := api.New( + webLogger.With("system", "WEBAPI"), + webSrv, authManager, authManager, rtConfig, authPolicy) + wui := webui.New( + webLogger.With("system", "WEBUI"), + webSrv, authManager, rtConfig, authManager, boxManager, authPolicy, &ucEvaluate) + webSrv.Handle("/", wui.MakeGetRootHandler(protectedBoxManager)) + if assetDir := kern.GetConfig(kernel.WebService, kernel.WebAssetDir).(string); assetDir != "" { + const assetPrefix = "/assets/" + webSrv.Handle(assetPrefix, http.StripPrefix(assetPrefix, http.FileServer(http.Dir(assetDir)))) + webSrv.Handle("/favicon.ico", wui.MakeFaviconHandler(assetDir)) + } // Web user interface if !authManager.IsReadonly() { - webSrv.AddZettelRoute('b', server.MethodGet, wui.MakeGetRenameZettelHandler( - ucGetMeta, &ucEvaluate)) - webSrv.AddZettelRoute('b', server.MethodPost, wui.MakePostRenameZettelHandler(&ucRename)) + webSrv.AddListRoute('c', server.MethodGet, wui.MakeGetZettelFromListHandler(&ucQuery, &ucEvaluate, ucListRoles, ucListSyntax)) + webSrv.AddListRoute('c', server.MethodPost, wui.MakePostCreateZettelHandler(&ucCreateZettel)) webSrv.AddZettelRoute('c', server.MethodGet, wui.MakeGetCreateZettelHandler( ucGetZettel, &ucCreateZettel, ucListRoles, ucListSyntax)) webSrv.AddZettelRoute('c', server.MethodPost, wui.MakePostCreateZettelHandler(&ucCreateZettel)) - webSrv.AddZettelRoute('d', server.MethodGet, wui.MakeGetDeleteZettelHandler( - ucGetMeta, ucGetAllMeta, &ucEvaluate)) + webSrv.AddZettelRoute('d', server.MethodGet, wui.MakeGetDeleteZettelHandler(ucGetZettel, ucGetAllZettel)) webSrv.AddZettelRoute('d', server.MethodPost, wui.MakePostDeleteZettelHandler(&ucDelete)) webSrv.AddZettelRoute('e', server.MethodGet, wui.MakeEditGetZettelHandler(ucGetZettel, ucListRoles, ucListSyntax)) webSrv.AddZettelRoute('e', server.MethodPost, wui.MakeEditSetZettelHandler(&ucUpdate)) } webSrv.AddListRoute('g', server.MethodGet, wui.MakeGetGoActionHandler(&ucRefresh)) - webSrv.AddListRoute('h', server.MethodGet, wui.MakeListHTMLMetaHandler( - ucListMeta, ucListRoles, ucListTags, &ucEvaluate)) - webSrv.AddZettelRoute('h', server.MethodGet, wui.MakeGetHTMLZettelHandler( - &ucEvaluate, ucGetMeta)) + webSrv.AddListRoute('h', server.MethodGet, wui.MakeListHTMLMetaHandler(&ucQuery, &ucTagZettel, &ucRoleZettel, &ucReIndex)) + webSrv.AddZettelRoute('h', server.MethodGet, wui.MakeGetHTMLZettelHandler(&ucEvaluate, ucGetZettel)) webSrv.AddListRoute('i', server.MethodGet, wui.MakeGetLoginOutHandler()) webSrv.AddListRoute('i', server.MethodPost, wui.MakePostLoginHandler(&ucAuthenticate)) webSrv.AddZettelRoute('i', server.MethodGet, wui.MakeGetInfoHandler( - ucParseZettel, &ucEvaluate, ucGetMeta, ucGetAllMeta, ucUnlinkedRefs)) - webSrv.AddZettelRoute('k', server.MethodGet, wui.MakeZettelContextHandler( - ucZettelContext, &ucEvaluate)) + ucParseZettel, ucGetReferences, &ucEvaluate, ucGetZettel, ucGetAllZettel, &ucQuery)) // API webSrv.AddListRoute('a', server.MethodPost, a.MakePostLoginHandler(&ucAuthenticate)) webSrv.AddListRoute('a', server.MethodPut, a.MakeRenewAuthHandler()) - webSrv.AddListRoute('j', server.MethodGet, a.MakeListMetaHandler(ucListMeta)) - webSrv.AddZettelRoute('j', server.MethodGet, a.MakeGetZettelHandler(ucGetZettel)) - webSrv.AddListRoute('m', server.MethodGet, a.MakeListMapMetaHandler(ucListRoles, ucListTags)) - webSrv.AddZettelRoute('m', server.MethodGet, a.MakeGetMetaHandler(ucGetMeta)) - webSrv.AddZettelRoute('o', server.MethodGet, a.MakeGetOrderHandler( - usecase.NewZettelOrder(protectedBoxManager, ucEvaluate))) - webSrv.AddZettelRoute('p', server.MethodGet, a.MakeGetParsedZettelHandler(ucParseZettel)) - webSrv.AddZettelRoute('u', server.MethodGet, a.MakeListUnlinkedMetaHandler( - ucGetMeta, ucUnlinkedRefs, &ucEvaluate)) - webSrv.AddZettelRoute('v', server.MethodGet, a.MakeGetEvalZettelHandler(ucEvaluate)) + webSrv.AddZettelRoute('r', server.MethodGet, a.MakeGetReferencesHandler(ucParseZettel, ucGetReferences)) webSrv.AddListRoute('x', server.MethodGet, a.MakeGetDataHandler(ucVersion)) webSrv.AddListRoute('x', server.MethodPost, a.MakePostCommandHandler(&ucIsAuth, &ucRefresh)) - webSrv.AddZettelRoute('x', server.MethodGet, a.MakeZettelContextHandler(ucZettelContext)) - webSrv.AddListRoute('z', server.MethodGet, a.MakeListPlainHandler(ucListMeta)) - webSrv.AddZettelRoute('z', server.MethodGet, a.MakeGetPlainZettelHandler(ucGetZettel)) + webSrv.AddListRoute('z', server.MethodGet, a.MakeQueryHandler(&ucQuery, &ucTagZettel, &ucRoleZettel, &ucReIndex)) + webSrv.AddZettelRoute('z', server.MethodGet, a.MakeGetZettelHandler(ucGetZettel, ucParseZettel, ucEvaluate)) if !authManager.IsReadonly() { - webSrv.AddListRoute('j', server.MethodPost, a.MakePostCreateZettelHandler(&ucCreateZettel)) - webSrv.AddZettelRoute('j', server.MethodPut, a.MakeUpdateZettelHandler(&ucUpdate)) - webSrv.AddZettelRoute('j', server.MethodDelete, a.MakeDeleteZettelHandler(&ucDelete)) - webSrv.AddZettelRoute('j', server.MethodMove, a.MakeRenameZettelHandler(&ucRename)) - webSrv.AddListRoute('z', server.MethodPost, a.MakePostCreatePlainZettelHandler(&ucCreateZettel)) - webSrv.AddZettelRoute('z', server.MethodPut, a.MakeUpdatePlainZettelHandler(&ucUpdate)) + webSrv.AddListRoute('z', server.MethodPost, a.MakePostCreateZettelHandler(&ucCreateZettel)) + webSrv.AddZettelRoute('z', server.MethodPut, a.MakeUpdateZettelHandler(&ucUpdate)) webSrv.AddZettelRoute('z', server.MethodDelete, a.MakeDeleteZettelHandler(&ucDelete)) - webSrv.AddZettelRoute('z', server.MethodMove, a.MakeRenameZettelHandler(&ucRename)) } if authManager.WithAuth() { webSrv.SetUserRetriever(usecase.NewGetUserByZid(boxManager)) } } + +type getUserImpl struct{} + +func (*getUserImpl) GetCurrentUser(ctx context.Context) *meta.Meta { return user.GetCurrentUser(ctx) } Index: cmd/command.go ================================================================== --- cmd/command.go +++ cmd/command.go @@ -1,22 +1,25 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern +// Copyright (c) 2020-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- package cmd import ( "flag" - - "zettelstore.de/c/maps" - "zettelstore.de/z/logger" + "log/slog" + "maps" + "slices" ) // Command stores information about commands / sub-commands. type Command struct { Name string // command name as it appears on the command line @@ -46,11 +49,11 @@ } if _, ok := commands[cmd.Name]; ok { panic("Command already registered: " + cmd.Name) } cmd.flags = flag.NewFlagSet(cmd.Name, flag.ExitOnError) - cmd.flags.String("l", logger.InfoLevel.String(), "global log level") + cmd.flags.String("l", slog.LevelInfo.String(), "log level specification") if cmd.SetFlags != nil { cmd.SetFlags(cmd.flags) } commands[cmd.Name] = cmd @@ -61,6 +64,6 @@ cmd, ok := commands[name] return cmd, ok } // List returns a sorted list of all registered command names. -func List() []string { return maps.Keys(commands) } +func List() []string { return slices.Sorted(maps.Keys(commands)) } DELETED cmd/fd_limit.go Index: cmd/fd_limit.go ================================================================== --- cmd/fd_limit.go +++ /dev/null @@ -1,16 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -//go:build !darwin -// +build !darwin - -package cmd - -func raiseFdLimit() error { return nil } DELETED cmd/fd_limit_raise.go Index: cmd/fd_limit_raise.go ================================================================== --- cmd/fd_limit_raise.go +++ /dev/null @@ -1,51 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -//go:build darwin -// +build darwin - -package cmd - -import ( - "fmt" - "syscall" - - "zettelstore.de/z/kernel" -) - -const minFiles = 1048576 - -func raiseFdLimit() error { - var rLimit syscall.Rlimit - err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) - if err != nil { - return err - } - if rLimit.Cur >= minFiles { - return nil - } - rLimit.Cur = minFiles - if rLimit.Cur > rLimit.Max { - rLimit.Cur = rLimit.Max - } - err = syscall.Setrlimit(syscall.RLIMIT_NOFILE, &rLimit) - if err != nil { - return err - } - err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) - if err != nil { - return err - } - if rLimit.Cur < minFiles { - msg := fmt.Sprintf("Make sure you have no more than %d files in all your boxes if you enabled notification\n", rLimit.Cur) - kernel.Main.GetKernelLogger().Mandatory().Msg(msg) - } - return nil -} Index: cmd/main.go ================================================================== --- cmd/main.go +++ cmd/main.go @@ -1,41 +1,48 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern +// Copyright (c) 2020-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- +// Package cmd provides the commands to call Zettelstore from the command line. package cmd import ( - "errors" + "crypto/sha256" "flag" "fmt" + "log/slog" "net" "net/url" "os" "runtime/debug" "strconv" "strings" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/auth/impl" - "zettelstore.de/z/box" - "zettelstore.de/z/box/compbox" - "zettelstore.de/z/box/manager" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/input" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" - "zettelstore.de/z/web/server" + "time" + + "t73f.de/r/zsc/api" + "t73f.de/r/zsc/domain/id" + "t73f.de/r/zsc/domain/meta" + "t73f.de/r/zsx/input" + + "zettelstore.de/z/internal/auth" + "zettelstore.de/z/internal/auth/impl" + "zettelstore.de/z/internal/box" + "zettelstore.de/z/internal/box/compbox" + "zettelstore.de/z/internal/box/manager" + "zettelstore.de/z/internal/config" + "zettelstore.de/z/internal/kernel" + "zettelstore.de/z/internal/logging" + "zettelstore.de/z/internal/web/server" ) const strRunSimple = "run-simple" func init() { @@ -85,19 +92,19 @@ Name: "password", Func: cmdPassword, }) } -func fetchStartupConfiguration(fs *flag.FlagSet) (cfg *meta.Meta) { +func fetchStartupConfiguration(fs *flag.FlagSet) (string, *meta.Meta) { if configFlag := fs.Lookup("c"); configFlag != nil { if filename := configFlag.Value.String(); filename != "" { content, err := readConfiguration(filename) - return createConfiguration(content, err) + return filename, createConfiguration(content, err) } } - content, err := searchAndReadConfiguration() - return createConfiguration(content, err) + filename, content, err := searchAndReadConfiguration() + return filename, createConfiguration(content, err) } func createConfiguration(content []byte, err error) *meta.Meta { if err != nil { return meta.New(id.Invalid) @@ -105,147 +112,152 @@ return meta.NewFromInput(id.Invalid, input.NewInput(content)) } func readConfiguration(filename string) ([]byte, error) { return os.ReadFile(filename) } -func searchAndReadConfiguration() ([]byte, error) { - for _, filename := range []string{"zettelstore.cfg", "zsconfig.txt", "zscfg.txt", "_zscfg"} { +func searchAndReadConfiguration() (string, []byte, error) { + for _, filename := range []string{"zettelstore.cfg", "zsconfig.txt", "zscfg.txt", "_zscfg", ".zscfg"} { if content, err := readConfiguration(filename); err == nil { - return content, nil + return filename, content, nil } } - return readConfiguration(".zscfg") + return "", nil, os.ErrNotExist } -func getConfig(fs *flag.FlagSet) *meta.Meta { - cfg := fetchStartupConfiguration(fs) +func getConfig(fs *flag.FlagSet) (string, *meta.Meta) { + filename, cfg := fetchStartupConfiguration(fs) fs.Visit(func(flg *flag.Flag) { switch flg.Name { case "p": - if portStr, err := parsePort(flg.Value.String()); err == nil { - cfg.Set(keyListenAddr, net.JoinHostPort("127.0.0.1", portStr)) - } + cfg.Set(keyListenAddr, meta.Value(net.JoinHostPort("127.0.0.1", flg.Value.String()))) case "a": - if portStr, err := parsePort(flg.Value.String()); err == nil { - cfg.Set(keyAdminPort, portStr) - } + cfg.Set(keyAdminPort, meta.Value(flg.Value.String())) case "d": val := flg.Value.String() if strings.HasPrefix(val, "/") { val = "dir://" + val } else { val = "dir:" + val } deleteConfiguredBoxes(cfg) - cfg.Set(keyBoxOneURI, val) + cfg.Set(keyBoxOneURI, meta.Value(val)) case "l": - cfg.Set(keyLogLevel, flg.Value.String()) + cfg.Set(keyLogLevel, meta.Value(flg.Value.String())) case "debug": - cfg.Set(keyDebug, flg.Value.String()) + cfg.Set(keyDebug, meta.Value(flg.Value.String())) case "r": - cfg.Set(keyReadOnly, flg.Value.String()) + cfg.Set(keyReadOnly, meta.Value(flg.Value.String())) case "v": - cfg.Set(keyVerbose, flg.Value.String()) + cfg.Set(keyVerbose, meta.Value(flg.Value.String())) } }) - return cfg -} - -func parsePort(s string) (string, error) { - port, err := net.LookupPort("tcp", s) - if err != nil { - fmt.Fprintf(os.Stderr, "Wrong port specification: %q", s) - return "", err - } - return strconv.Itoa(port), nil + return filename, cfg } func deleteConfiguredBoxes(cfg *meta.Meta) { - for _, p := range cfg.PairsRest() { - if key := p.Key; strings.HasPrefix(key, kernel.BoxURIs) { + for key := range cfg.Rest() { + if strings.HasPrefix(key, kernel.BoxURIs) { cfg.Delete(key) } } } const ( keyAdminPort = "admin-port" + keyAssetDir = "asset-dir" + keyBaseURL = "base-url" + keyBoxOneURI = kernel.BoxURIs + "1" keyDebug = "debug-mode" keyDefaultDirBoxType = "default-dir-box-type" keyInsecureCookie = "insecure-cookie" + keyInsecureHTML = "insecure-html" keyListenAddr = "listen-addr" keyLogLevel = "log-level" + keyLoopbackIdent = "loopback-ident" + keyLoopbackZid = "loopback-zid" keyMaxRequestSize = "max-request-size" keyOwner = "owner" keyPersistentCookie = "persistent-cookie" - keyBoxOneURI = kernel.BoxURIs + "1" keyReadOnly = "read-only-mode" + keyRuntimeProfiling = "runtime-profiling" + keySxNesting = "sx-max-nesting" keyTokenLifetimeHTML = "token-lifetime-html" keyTokenLifetimeAPI = "token-lifetime-api" keyURLPrefix = "url-prefix" keyVerbose = "verbose-mode" ) -func setServiceConfig(cfg *meta.Meta) error { +func setServiceConfig(cfg *meta.Meta) bool { debugMode := cfg.GetBool(keyDebug) - if debugMode && kernel.Main.GetKernelLogger().Level() > logger.DebugLevel { - kernel.Main.SetGlobalLogLevel(logger.DebugLevel) - } - if strLevel, found := cfg.Get(keyLogLevel); found { - if level := logger.ParseLevel(strLevel); level.IsValid() { - kernel.Main.SetGlobalLogLevel(level) - } - } - ok := setConfigValue(true, kernel.CoreService, kernel.CoreDebug, debugMode) - ok = setConfigValue(ok, kernel.CoreService, kernel.CoreVerbose, cfg.GetBool(keyVerbose)) + if debugMode && kernel.Main.GetKernelLogLevel() > slog.LevelDebug { + kernel.Main.SetLogLevel(logging.LevelString(slog.LevelDebug)) + } + if logLevel, found := cfg.Get(keyLogLevel); found { + kernel.Main.SetLogLevel(string(logLevel)) + } + err := setConfigValue(nil, kernel.CoreService, kernel.CoreDebug, debugMode) + err = setConfigValue(err, kernel.CoreService, kernel.CoreVerbose, cfg.GetBool(keyVerbose)) if val, found := cfg.Get(keyAdminPort); found { - ok = setConfigValue(ok, kernel.CoreService, kernel.CorePort, val) - } - - ok = setConfigValue(ok, kernel.AuthService, kernel.AuthOwner, cfg.GetDefault(keyOwner, "")) - ok = setConfigValue(ok, kernel.AuthService, kernel.AuthReadonly, cfg.GetBool(keyReadOnly)) - - ok = setConfigValue( - ok, kernel.BoxService, kernel.BoxDefaultDirType, + err = setConfigValue(err, kernel.CoreService, kernel.CorePort, val) + } + + err = setConfigValue(err, kernel.AuthService, kernel.AuthOwner, cfg.GetDefault(keyOwner, "")) + err = setConfigValue(err, kernel.AuthService, kernel.AuthReadonly, cfg.GetBool(keyReadOnly)) + + err = setConfigValue( + err, kernel.BoxService, kernel.BoxDefaultDirType, cfg.GetDefault(keyDefaultDirBoxType, kernel.BoxDirTypeNotify)) - ok = setConfigValue(ok, kernel.BoxService, kernel.BoxURIs+"1", "dir:./zettel") - format := kernel.BoxURIs + "%v" + err = setConfigValue(err, kernel.BoxService, kernel.BoxURIs+"1", "dir:./zettel") for i := 1; ; i++ { - key := fmt.Sprintf(format, i) + key := kernel.BoxURIs + strconv.Itoa(i) val, found := cfg.Get(key) if !found { break } - ok = setConfigValue(ok, kernel.BoxService, key, val) - } - - ok = setConfigValue( - ok, kernel.WebService, kernel.WebListenAddress, - cfg.GetDefault(keyListenAddr, "127.0.0.1:23123")) - ok = setConfigValue(ok, kernel.WebService, kernel.WebURLPrefix, cfg.GetDefault(keyURLPrefix, "/")) - ok = setConfigValue(ok, kernel.WebService, kernel.WebSecureCookie, !cfg.GetBool(keyInsecureCookie)) - ok = setConfigValue(ok, kernel.WebService, kernel.WebPersistentCookie, cfg.GetBool(keyPersistentCookie)) + err = setConfigValue(err, kernel.BoxService, key, val) + } + + err = setConfigValue( + err, kernel.ConfigService, kernel.ConfigInsecureHTML, cfg.GetDefault(keyInsecureHTML, kernel.ConfigSecureHTML)) + + err = setConfigValue( + err, kernel.WebService, kernel.WebListenAddress, cfg.GetDefault(keyListenAddr, "127.0.0.1:23123")) + err = setConfigValue(err, kernel.WebService, kernel.WebLoopbackIdent, cfg.GetDefault(keyLoopbackIdent, "")) + err = setConfigValue(err, kernel.WebService, kernel.WebLoopbackZid, cfg.GetDefault(keyLoopbackZid, "")) + if val, found := cfg.Get(keyBaseURL); found { + err = setConfigValue(err, kernel.WebService, kernel.WebBaseURL, val) + } + if val, found := cfg.Get(keyURLPrefix); found { + err = setConfigValue(err, kernel.WebService, kernel.WebURLPrefix, val) + } + err = setConfigValue(err, kernel.WebService, kernel.WebSecureCookie, !cfg.GetBool(keyInsecureCookie)) + err = setConfigValue(err, kernel.WebService, kernel.WebPersistentCookie, cfg.GetBool(keyPersistentCookie)) if val, found := cfg.Get(keyMaxRequestSize); found { - ok = setConfigValue(ok, kernel.WebService, kernel.WebMaxRequestSize, val) - } - ok = setConfigValue( - ok, kernel.WebService, kernel.WebTokenLifetimeAPI, cfg.GetDefault(keyTokenLifetimeAPI, "")) - ok = setConfigValue( - ok, kernel.WebService, kernel.WebTokenLifetimeHTML, cfg.GetDefault(keyTokenLifetimeHTML, "")) - - if !ok { - return errors.New("unable to set configuration") - } - return nil -} - -func setConfigValue(ok bool, subsys kernel.Service, key string, val interface{}) bool { - done := kernel.Main.SetConfig(subsys, key, fmt.Sprintf("%v", val)) - if !done { - kernel.Main.GetKernelLogger().Error().Str(key, fmt.Sprint(val)).Msg("Unable to set configuration") - } - return ok && done + err = setConfigValue(err, kernel.WebService, kernel.WebMaxRequestSize, val) + } + err = setConfigValue( + err, kernel.WebService, kernel.WebTokenLifetimeAPI, cfg.GetDefault(keyTokenLifetimeAPI, "")) + err = setConfigValue( + err, kernel.WebService, kernel.WebTokenLifetimeHTML, cfg.GetDefault(keyTokenLifetimeHTML, "")) + err = setConfigValue(err, kernel.WebService, kernel.WebProfiling, debugMode || cfg.GetBool(keyRuntimeProfiling)) + if val, found := cfg.Get(keyAssetDir); found { + err = setConfigValue(err, kernel.WebService, kernel.WebAssetDir, val) + } + if val, found := cfg.Get(keySxNesting); found { + err = setConfigValue(err, kernel.WebService, kernel.WebSxMaxNesting, val) + } + return err == nil +} + +func setConfigValue(err error, subsys kernel.Service, key string, val any) error { + if err == nil { + if err = kernel.Main.SetConfig(subsys, key, fmt.Sprint(val)); err != nil { + kernel.Main.GetKernelLogger().Error("Unable to set configuration", + "key", key, "value", val, "err", err) + } + } + return err } func executeCommand(name string, args ...string) int { command, ok := Get(name) if !ok { @@ -255,26 +267,19 @@ fs := command.GetFlags() if err := fs.Parse(args); err != nil { fmt.Fprintf(os.Stderr, "%s: unable to parse flags: %v %v\n", name, args, err) return 1 } - cfg := getConfig(fs) - if err := setServiceConfig(cfg); err != nil { - fmt.Fprintf(os.Stderr, "%s: %v\n", name, err) + filename, cfg := getConfig(fs) + if !setServiceConfig(cfg) { + fs.Usage() return 2 } kern := kernel.Main var createManager kernel.CreateBoxManagerFunc if command.Boxes { - err := raiseFdLimit() - if err != nil { - logger := kern.GetKernelLogger() - logger.IfErr(err).Msg("Raising some limitions did not work") - logger.Error().Msg("Prepare to encounter errors. Most of them can be mitigated. See the manual for details") - kern.SetConfig(kernel.BoxService, kernel.BoxDefaultDirType, kernel.BoxDirTypeSimple) - } createManager = func(boxURIs []*url.URL, authManager auth.Manager, rtConfig config.Config) (box.Manager, error) { compbox.Setup(cfg) return manager.New(boxURIs, authManager, rtConfig) } } else { @@ -284,38 +289,43 @@ secret := cfg.GetDefault("secret", "") if len(secret) < 16 && cfg.GetDefault(keyOwner, "") != "" { fmt.Fprintf(os.Stderr, "secret must have at least length 16 when authentication is enabled, but is %q\n", secret) return 2 } + cfg.Delete("secret") + secretHash := fmt.Sprintf("%x", sha256.Sum256([]byte(string(secret)))) kern.SetCreators( func(readonly bool, owner id.Zid) (auth.Manager, error) { - return impl.New(readonly, owner, secret), nil + return impl.New(readonly, owner, secretHash), nil }, createManager, func(srv server.Server, plMgr box.Manager, authMgr auth.Manager, rtConfig config.Config) error { setupRouting(srv, plMgr, authMgr, rtConfig) return nil }, ) if command.Simple { - kern.SetConfig(kernel.ConfigService, kernel.ConfigSimpleMode, "true") + if err := kern.SetConfig(kernel.ConfigService, kernel.ConfigSimpleMode, "true"); err != nil { + kern.GetKernelLogger().Error("unable to set simple-mode", "err", err) + return 1 + } } - kern.Start(command.Header, command.LineServer) + kern.Start(command.Header, command.LineServer, filename) exitCode, err := command.Func(fs) if err != nil { fmt.Fprintf(os.Stderr, "%s: %v\n", name, err) } kern.Shutdown(true) return exitCode } // runSimple is called, when the user just starts the software via a double click -// or via a simple call ``./zettelstore`` on the command line. +// or via a simple call “./zettelstore“ on the command line. func runSimple() int { - if _, err := searchAndReadConfiguration(); err == nil { + if _, _, err := searchAndReadConfiguration(); err == nil { return executeCommand(strRunSimple) } dir := "./zettel" if err := os.MkdirAll(dir, 0750); err != nil { fmt.Fprintf(os.Stderr, "Unable to create zettel directory %q (%s)\n", dir, err) @@ -327,45 +337,69 @@ var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`") var memprofile = flag.String("memprofile", "", "write memory profile to `file`") // Main is the real entrypoint of the zettelstore. func Main(progName, buildVersion string) int { - fullVersion := retrieveFullVersion(buildVersion) - kernel.Main.SetConfig(kernel.CoreService, kernel.CoreProgname, progName) - kernel.Main.SetConfig(kernel.CoreService, kernel.CoreVersion, fullVersion) + info := retrieveVCSInfo(buildVersion) + fullVersion := info.revision + if info.dirty { + fullVersion += "-dirty" + } + kernel.Main.Setup(progName, fullVersion, info.time) flag.Parse() if *cpuprofile != "" || *memprofile != "" { + var err error if *cpuprofile != "" { - kernel.Main.StartProfiling(kernel.ProfileCPU, *cpuprofile) + err = kernel.Main.StartProfiling(kernel.ProfileCPU, *cpuprofile) } else { - kernel.Main.StartProfiling(kernel.ProfileHead, *memprofile) + err = kernel.Main.StartProfiling(kernel.ProfileHead, *memprofile) + } + if err != nil { + kernel.Main.GetKernelLogger().Error("start profiling", "err", err) + return 1 } - defer kernel.Main.StopProfiling() + defer func() { + if err = kernel.Main.StopProfiling(); err != nil { + kernel.Main.GetKernelLogger().Error("stop profiling", "err", err) + } + }() } args := flag.Args() if len(args) == 0 { return runSimple() } return executeCommand(args[0], args[1:]...) } -func retrieveFullVersion(version string) string { +type vcsInfo struct { + revision string + dirty bool + time time.Time +} + +func retrieveVCSInfo(version string) vcsInfo { + buildTime := time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC) info, ok := debug.ReadBuildInfo() if !ok { - return version + return vcsInfo{revision: version, dirty: false, time: buildTime} } - var revision, dirty string + result := vcsInfo{time: buildTime} for _, kv := range info.Settings { switch kv.Key { case "vcs.revision": - revision = "+" + kv.Value + revision := "+" + kv.Value if len(revision) > 11 { revision = revision[:11] } + result.revision = version + revision case "vcs.modified": if kv.Value == "true" { - dirty = "-dirty" + result.dirty = true + } + case "vcs.time": + if t, err := time.Parse(time.RFC3339, kv.Value); err == nil { + result.time = t } } } - return version + revision + dirty + return result } Index: cmd/register.go ================================================================== --- cmd/register.go +++ cmd/register.go @@ -1,32 +1,23 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern +// Copyright (c) 2020-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- -// Package cmd provides command generic functions. package cmd -// Mention all needed encoders, parsers and stores to have them registered. +// Mention all needed boxes, encoders, and parsers to have them registered. import ( - _ "zettelstore.de/z/box/compbox" // Allow to use computed box. - _ "zettelstore.de/z/box/constbox" // Allow to use global internal box. - _ "zettelstore.de/z/box/dirbox" // Allow to use directory box. - _ "zettelstore.de/z/box/filebox" // Allow to use file box. - _ "zettelstore.de/z/box/membox" // Allow to use in-memory box. - _ "zettelstore.de/z/encoder/htmlenc" // Allow to use HTML encoder. - _ "zettelstore.de/z/encoder/sexprenc" // Allow to use sexpr encoder. - _ "zettelstore.de/z/encoder/textenc" // Allow to use text encoder. - _ "zettelstore.de/z/encoder/zjsonenc" // Allow to use ZJSON encoder. - _ "zettelstore.de/z/encoder/zmkenc" // Allow to use zmk encoder. - _ "zettelstore.de/z/kernel/impl" // Allow kernel implementation to create itself - _ "zettelstore.de/z/parser/blob" // Allow to use BLOB parser. - _ "zettelstore.de/z/parser/markdown" // Allow to use markdown parser. - _ "zettelstore.de/z/parser/none" // Allow to use none parser. - _ "zettelstore.de/z/parser/plain" // Allow to use plain parser. - _ "zettelstore.de/z/parser/zettelmark" // Allow to use zettelmark parser. + _ "zettelstore.de/z/internal/box/compbox" // Allow to use computed box. + _ "zettelstore.de/z/internal/box/constbox" // Allow to use global internal box. + _ "zettelstore.de/z/internal/box/dirbox" // Allow to use directory box. + _ "zettelstore.de/z/internal/box/filebox" // Allow to use file box. + _ "zettelstore.de/z/internal/box/membox" // Allow to use in-memory box. ) Index: cmd/zettelstore/main.go ================================================================== --- cmd/zettelstore/main.go +++ cmd/zettelstore/main.go @@ -1,13 +1,16 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern +// Copyright (c) 2020-present Detlef Stern // -// This file is part of zettelstore. +// This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- // Package main is the starting point for the zettelstore command. package main @@ -16,11 +19,11 @@ "zettelstore.de/z/cmd" ) // Version variable. Will be filled by build process. -var version string = "" +var version string func main() { exitCode := cmd.Main("Zettelstore", version) os.Exit(exitCode) } DELETED collect/collect.go Index: collect/collect.go ================================================================== --- collect/collect.go +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package collect provides functions to collect items from a syntax tree. -package collect - -import "zettelstore.de/z/ast" - -// Summary stores the relevant parts of the syntax tree -type Summary struct { - Links []*ast.Reference // list of all linked material - Embeds []*ast.Reference // list of all embedded material - Cites []*ast.CiteNode // list of all referenced citations -} - -// References returns all references mentioned in the given zettel. This also -// includes references to images. -func References(zn *ast.ZettelNode) (s Summary) { - ast.Walk(&s, &zn.Ast) - return s -} - -// Visit all node to collect data for the summary. -func (s *Summary) Visit(node ast.Node) ast.Visitor { - switch n := node.(type) { - case *ast.TranscludeNode: - s.Embeds = append(s.Embeds, n.Ref) - case *ast.LinkNode: - s.Links = append(s.Links, n.Ref) - case *ast.EmbedRefNode: - s.Embeds = append(s.Embeds, n.Ref) - case *ast.CiteNode: - s.Cites = append(s.Cites, n) - } - return s -} DELETED collect/collect_test.go Index: collect/collect_test.go ================================================================== --- collect/collect_test.go +++ /dev/null @@ -1,61 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package collect_test provides some unit test for collectors. -package collect_test - -import ( - "testing" - - "zettelstore.de/z/ast" - "zettelstore.de/z/collect" -) - -func parseRef(s string) *ast.Reference { - r := ast.ParseReference(s) - if !r.IsValid() { - panic(s) - } - return r -} - -func TestLinks(t *testing.T) { - t.Parallel() - zn := &ast.ZettelNode{} - summary := collect.References(zn) - if summary.Links != nil || summary.Embeds != nil { - t.Error("No links/images expected, but got:", summary.Links, "and", summary.Embeds) - } - - intNode := &ast.LinkNode{Ref: parseRef("01234567890123")} - para := ast.CreateParaNode(intNode, &ast.LinkNode{Ref: parseRef("https://zettelstore.de/z")}) - zn.Ast = ast.BlockSlice{para} - summary = collect.References(zn) - if summary.Links == nil || summary.Embeds != nil { - t.Error("Links expected, and no images, but got:", summary.Links, "and", summary.Embeds) - } - - para.Inlines = append(para.Inlines, intNode) - summary = collect.References(zn) - if cnt := len(summary.Links); cnt != 3 { - t.Error("Link count does not work. Expected: 3, got", summary.Links) - } -} - -func TestEmbed(t *testing.T) { - t.Parallel() - zn := &ast.ZettelNode{ - Ast: ast.BlockSlice{ast.CreateParaNode(&ast.EmbedRefNode{Ref: parseRef("12345678901234")})}, - } - summary := collect.References(zn) - if summary.Embeds == nil { - t.Error("Only image expected, but got: ", summary.Embeds) - } -} DELETED collect/order.go Index: collect/order.go ================================================================== --- collect/order.go +++ /dev/null @@ -1,73 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package collect provides functions to collect items from a syntax tree. -package collect - -import "zettelstore.de/z/ast" - -// Order of internal reference within the given zettel. -func Order(zn *ast.ZettelNode) (result []*ast.Reference) { - for _, bn := range zn.Ast { - ln, ok := bn.(*ast.NestedListNode) - if !ok { - continue - } - switch ln.Kind { - case ast.NestedListOrdered, ast.NestedListUnordered: - for _, is := range ln.Items { - if ref := firstItemZettelReference(is); ref != nil { - result = append(result, ref) - } - } - } - } - return result -} - -func firstItemZettelReference(is ast.ItemSlice) *ast.Reference { - for _, in := range is { - if pn, ok := in.(*ast.ParaNode); ok { - if ref := firstInlineZettelReference(pn.Inlines); ref != nil { - return ref - } - } - } - return nil -} - -func firstInlineZettelReference(is ast.InlineSlice) (result *ast.Reference) { - for _, inl := range is { - switch in := inl.(type) { - case *ast.LinkNode: - if ref := in.Ref; ref.IsZettel() { - return ref - } - result = firstInlineZettelReference(in.Inlines) - case *ast.EmbedRefNode: - result = firstInlineZettelReference(in.Inlines) - case *ast.EmbedBLOBNode: - result = firstInlineZettelReference(in.Inlines) - case *ast.CiteNode: - result = firstInlineZettelReference(in.Inlines) - case *ast.FootnoteNode: - // Ignore references in footnotes - continue - case *ast.FormatNode: - result = firstInlineZettelReference(in.Inlines) - default: - continue - } - if result != nil { - return result - } - } - return nil -} DELETED collect/split.go Index: collect/split.go ================================================================== --- collect/split.go +++ /dev/null @@ -1,50 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package collect provides functions to collect items from a syntax tree. -package collect - -import ( - "zettelstore.de/z/ast" - "zettelstore.de/z/strfun" -) - -// DivideReferences divides the given list of rederences into zettel, local, and external References. -func DivideReferences(all []*ast.Reference) (zettel, local, external []*ast.Reference) { - if len(all) == 0 { - return nil, nil, nil - } - - mapZettel := make(strfun.Set) - mapLocal := make(strfun.Set) - mapExternal := make(strfun.Set) - for _, ref := range all { - if ref.State == ast.RefStateSelf { - continue - } - if ref.IsZettel() { - zettel = appendRefToList(zettel, mapZettel, ref) - } else if ref.IsExternal() { - external = appendRefToList(external, mapExternal, ref) - } else { - local = appendRefToList(local, mapLocal, ref) - } - } - return zettel, local, external -} - -func appendRefToList(reflist []*ast.Reference, refSet strfun.Set, ref *ast.Reference) []*ast.Reference { - s := ref.String() - if !refSet.Has(s) { - reflist = append(reflist, ref) - refSet.Set(s) - } - return reflist -} DELETED config/config.go Index: config/config.go ================================================================== --- config/config.go +++ /dev/null @@ -1,72 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package config provides functions to retrieve runtime configuration data. -package config - -import ( - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -// Config allows to retrieve all defined configuration values that can be changed during runtime. -type Config interface { - AuthConfig - - // AddDefaultValues enriches the given meta data with its default values. - AddDefaultValues(m *meta.Meta) *meta.Meta - - // GetDefaultLang returns the current value of the "default-lang" key. - GetDefaultLang() string - - // GetSiteName returns the current value of the "site-name" key. - GetSiteName() string - - // GetHomeZettel returns the value of the "home-zettel" key. - GetHomeZettel() id.Zid - - // GetMaxTransclusions return the maximum number of indirect transclusions. - GetMaxTransclusions() int - - // GetYAMLHeader returns the current value of the "yaml-header" key. - GetYAMLHeader() bool - - // GetZettelFileSyntax returns the current value of the "zettel-file-syntax" key. - GetZettelFileSyntax() []string - - // GetMarkerExternal returns the current value of the "marker-external" key. - GetMarkerExternal() string - - // GetFooterHTML returns HTML code that should be embedded into the footer - // of each WebUI page. - GetFooterHTML() string -} - -// AuthConfig are relevant configuration values for authentication. -type AuthConfig interface { - // GetSimpleMode returns true if system tuns in simple-mode. - GetSimpleMode() bool - - // GetExpertMode returns the current value of the "expert-mode" key. - GetExpertMode() bool - - // GetVisibility returns the visibility value of the metadata. - GetVisibility(m *meta.Meta) meta.Visibility -} - -// GetLang returns the value of the "lang" key of the given meta. If there is -// no such value, GetDefaultLang is returned. -func GetLang(m *meta.Meta, cfg Config) string { - if val, ok := m.Get(api.KeyLang); ok { - return val - } - return cfg.GetDefaultLang() -} Index: docs/development/00010000000000.zettel ================================================================== --- docs/development/00010000000000.zettel +++ docs/development/00010000000000.zettel @@ -1,8 +1,11 @@ id: 00010000000000 title: Developments Notes role: zettel syntax: zmk -modified: 20210916194954 +created: 00010101000000 +modified: 20231218182020 * [[Required Software|20210916193200]] +* [[Fuzzing tests|20221026184300]] * [[Checklist for Release|20210916194900]] +* [[Development tools|20231218181900]] Index: docs/development/20210916193200.zettel ================================================================== --- docs/development/20210916193200.zettel +++ docs/development/20210916193200.zettel @@ -1,19 +1,29 @@ id: 20210916193200 title: Required Software role: zettel syntax: zmk -modified: 20211213190428 +created: 20210916193200 +modified: 20241213124936 The following software must be installed: -* A current, supported [[release of Go|https://golang.org/doc/devel/release.html]], -* [[shadow|https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/shadow]] via ``go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest``, -* [[staticcheck|https://staticcheck.io/]] via ``go install honnef.co/go/tools/cmd/staticcheck@latest``, -* [[unparam|https://mvdan.cc/unparam]][^[[GitHub|https://github.com/mvdan/unparam]]] via ``go install mvdan.cc/unparam@latest`` +* A current, supported [[release of Go|https://go.dev/doc/devel/release]], +* [[Fossil|https://fossil-scm.org/]], +* [[Git|https://git-scm.org/]] (most dependencies are accessible via Git only). Make sure that the software is in your path, e.g. via: - ```sh export PATH=$PATH:/usr/local/go/bin export PATH=$PATH:$(go env GOPATH)/bin ``` + +The internal build tool needs the following software tools. +They can be installed / updated via the build tool itself: ``go run tools/devtools/devtools.go``. + +Otherwise you can install the software by hand: + +* [[shadow|https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/shadow]] via ``go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest``, +* [[staticcheck|https://staticcheck.io/]] via ``go install honnef.co/go/tools/cmd/staticcheck@latest``, +* [[unparam|https://mvdan.cc/unparam]][^[[GitHub|https://github.com/mvdan/unparam]]] via ``go install mvdan.cc/unparam@latest``, +* [[revive|https://revive.run]] via ``go install github.com/mgechev/revive@vlatest``, +* [[govulncheck|https://golang.org/x/vuln/cmd/govulncheck]] via ``go install golang.org/x/vuln/cmd/govulncheck@latest``, Index: docs/development/20210916194900.zettel ================================================================== --- docs/development/20210916194900.zettel +++ docs/development/20210916194900.zettel @@ -1,54 +1,58 @@ id: 20210916194900 title: Checklist for Release role: zettel syntax: zmk -modified: 20220309105459 +created: 20210916194900 +modified: 20241213125640 -# Sync with the official repository +# Sync with the official repository: #* ``fossil sync -u`` -# Make sure that all dependencies are up-to-date. +# Make sure that there is no workspace defined: +#* ``ls ..`` must not have a file ''go.work'', in no parent folder. +# Make sure that all dependencies are up-to-date: #* ``cat go.mod`` # Clean up your Go workspace: -#* ``go run tools/build.go clean`` (alternatively: ``make clean``). +#* ``go run tools/clean/clean.go`` (alternatively: ``make clean``) # All internal tests must succeed: -#* ``go run tools/build.go relcheck`` (alternatively: ``make relcheck``). +#* ``go run tools/check/check.go -r`` (alternatively: ``make relcheck``) # The API tests must succeed on every development platform: -#* ``go run tools/build.go testapi`` (alternatively: ``make api``). +#* ``go run tools/testapi/testapi.go`` (alternatively: ``make api``) # Run [[linkchecker|https://linkchecker.github.io/linkchecker/]] with the manual: #* ``go run -race cmd/zettelstore/main.go run -d docs/manual`` #* ``linkchecker http://127.0.0.1:23123 2>&1 | tee lc.txt`` #* Check all ""Error: 404 Not Found"" -#* Check all ""Error: 403 Forbidden"": allowed for endpoint ''/p'' with encoding ''html'' for those zettel that are accessible only in ''expert-mode''. +#* Check all ""Error: 403 Forbidden"": allowed for endpoint ''/z'' for those zettel that are accessible only in ''expert-mode'' #* Try to resolve other error messages and warnings #* Warnings about empty content can be ignored # On every development platform, the box with 10.000 zettel must run, with ''-race'' enabled: -#* ``go run -race cmd/zettelstore/main.go run -d DIR``. +#* ``go run -race cmd/zettelstore/main.go run -d DIR`` # Create a development release: -#* ``go run tools/build.go release`` (alternatively: ``make release``). +#* ``go run tools/build.go release`` (alternatively: ``make release``) # On every platform (esp. macOS), the box with 10.000 zettel must run properly: #* ``./zettelstore -d DIR`` -# Update files in directory ''www'' -#* index.wiki -#* download.wiki -#* changes.wiki -#* plan.wiki -# Set file ''VERSION'' to the new release version +# Update files in directory ''www'': +#* ''index.wiki'' +#* ''download.wiki'' +#* ''changes.wiki'' +#* ''plan.wiki'' +# Set file ''VERSION'' to the new release version. + It **must** consists of three numbers: ''MAJOR.MINOR.PATCH'', even if ''PATCH'' is zero. # Disable Fossil autosync mode: #* ``fossil setting autosync off`` # Commit the new release version: #* ``fossil commit --tag release --tag vVERSION -m "Version VERSION"`` #* **Important:** the tag must follow the given pattern, e.g. ''v0.0.15''. - Otherwise client will not be able to import ''zettelkasten.de/z''. + Otherwise client software will not be able to import ''zettelstore.de/z''. # Clean up your Go workspace: -#* ``go run tools/build.go clean`` (alternatively: ``make clean``). +#* ``go run tools/clean/clean.go`` (alternatively: ``make clean``) # Create the release: -#* ``go run tools/build.go release`` (alternatively: ``make release``). +#* ``go run tools/build/build.go release`` (alternatively: ``make release``) # Remove previous executables: #* ``fossil uv remove --glob '*-PREVVERSION*'`` # Add executables for release: -#* ``cd release`` +#* ``cd releases`` #* ``fossil uv add *.zip`` #* ``cd ..`` #* Synchronize with main repository: #* ``fossil sync -u`` # Enable autosync: ADDED docs/development/20221026184300.zettel Index: docs/development/20221026184300.zettel ================================================================== --- /dev/null +++ docs/development/20221026184300.zettel @@ -0,0 +1,13 @@ +id: 20221026184300 +title: Fuzzing Tests +role: zettel +syntax: zmk +created: 20221026184320 +modified: 20221102140156 + +The source code contains some simple [[fuzzing tests|https://go.dev/security/fuzz/]]. +You should call them regularly to make sure that the software will cope with unusual input. + +```sh +go test -fuzz=FuzzParseZmk zettelstore.de/z/internal/parser/ +``` ADDED docs/development/20231218181900.zettel Index: docs/development/20231218181900.zettel ================================================================== --- /dev/null +++ docs/development/20231218181900.zettel @@ -0,0 +1,116 @@ +id: 20231218181900 +title: Development tools +role: zettel +syntax: zmk +created: 20231218181956 +modified: 20231218184500 + +The source code contains some tools to assist the development of Zettelstore. +These are located in the ''tools'' directory. + +Most tool support the generic option ``-v``, which log internal activities. + +Some of the tools can be called easier by using ``make``, that reads in a provided ''Makefile''. + +=== Check +The ""check"" tool automates some testing activities. +It is called via the command line: +``` +# go run tools/check/check.go +``` +There is an additional option ``-r`` to check in advance of a release. + +The following checks are executed: +* Execution of unit tests, like ``go test ./...`` +* Analyze the source code for general problems, as in ``go vet ./...`` +* Tries to find shadowed variable, via ``shadow ./...`` +* Performs some additional checks on the source code, via ``staticcheck ./...`` +* Checks the usage of function parameters and usage of return values, via ``unparam ./...``. + In case the option ''-r'' is set, the check includes exported functions and internal tests. +* In case option ''-r'' is set, the source code is checked against the vulnerability database, via ``govulncheck ./...`` + +Please note, that most of the tools above are not automatically installed in a standard Go distribution. +Use the command ""devtools"" to install them. + +=== Devtools +The following command installs all needed tools: +``` +# go run tooles/devtools/devtools.go +``` +It will also automatically update these tools. + +=== TestAPI +The following command will perform some high-level tests: +```sh +# go run tools/testapi/testapi.go +``` +Basically, a Zettelstore will be started and then API calls will be made to simulate some typical activities with the Zettelstore. + +If a Zettelstore is already running on port 23123, this Zettelstore will be used instead. +Even if the API test should clean up later, some zettel might stay created if a test fails. +This feature is used, if you want to have more control on the running Zettelstore. +You should start it with the following command: +```sh +# go run -race cmd/zettelstore/main.go run -c testdata/testbox/19700101000000.zettel +``` +This allows you to debug failing API tests. + +=== HTMLlint +The following command will check the generated HTML code for validity: +```sh +# go run tools/htmllint/htmllint.go +``` +In addition, you might specify the URL od a running Zettelstore. +Otherwise ''http://localhost:23123'' is used. + +This command fetches first the list of all zettel. +This list is used to check the generated HTML code (''ZID'' is the paceholder for the zettel identification): + +* Check all zettel HTML encodings, via the path ''/z/ZID?enc=html&part=zettel'' +* Check all zettel web views, via the path ''/h/ZID'' +* The info page of all zettel is checked, via path ''/i/ZID'' +* A subset of max. 100 zettel will be checked for the validity of their edit page, via ''/e/ZID'' +* 10 random zettel are checked for a valid create form, via ''/c/ZID'' +* A maximum of 200 random zettel are checked for a valid delete dialog, via ''/d/ZID'' + +Depending on the selected Zettelstore, the command might take a long time. + +You can shorten the time, if you disable any zettel query in the footer. + +=== Build +The ""build"" tool allows to build the software, either for tests or for a release. + +The following command will create a Zettelstore executable for the architecture of the current computer: +```sh +# go tools/build/build.go build +``` +You will find the executable in the ''bin'' directory. + +A full release will be build in the directory ''releases'', containing ZIP files for the computer architectures ""Linux/amd64"", ""Linux/arm"", ""MacOS/arm64"", ""MacOS/amd64"", and ""Windows/amd64"". +In addition, the manual is also build as a ZIP file: +```sh +# go run tools/build/build.go release +``` + +If you just want the ZIP file with the manual, please use: +```sh +# go run tools/build/build.go manual +``` + +In case you want to check the version of the Zettelstore to be build, use: +```sh +# go run tools/build/build.go version +``` + +=== Clean +To remove the directories ''bin'' and ''releases'', as well as all cached Go libraries used by Zettelstore, execute: +```sh +# go run tools/clean/clean.go +``` + +Internally, the following commands are executed +```sh +# rm -rf bin releases +# go clean ./... +# go clean -cache -modcache -testcache +``` Index: docs/manual/00000000000100.zettel ================================================================== --- docs/manual/00000000000100.zettel +++ docs/manual/00000000000100.zettel @@ -1,13 +1,14 @@ id: 00000000000100 title: Zettelstore Runtime Configuration role: configuration syntax: none -default-copyright: (c) 2020-2022 by Detlef Stern +created: 20210126175322 +default-copyright: (c) 2020-present by Detlef Stern default-license: EUPL-1.2-or-later default-visibility: public -footer-html:

Imprint / Privacy

+footer-zettel: 00001000000100 home-zettel: 00001000000000 -modified: 20220215171041 +modified: 20221205173642 site-name: Zettelstore Manual visibility: owner ADDED docs/manual/00000000025001 Index: docs/manual/00000000025001 ================================================================== --- /dev/null +++ docs/manual/00000000025001 @@ -0,0 +1,7 @@ +id: 00000000025001 +title: Zettelstore User CSS +role: configuration +syntax: css +created: 20210622110143 +modified: 20220926183101 +visibility: public ADDED docs/manual/00000000025001.css Index: docs/manual/00000000025001.css ================================================================== --- /dev/null +++ docs/manual/00000000025001.css @@ -0,0 +1,2 @@ +/* User-defined CSS */ +.example { border-style: dotted !important } Index: docs/manual/00001000000000.zettel ================================================================== --- docs/manual/00001000000000.zettel +++ docs/manual/00001000000000.zettel @@ -1,11 +1,13 @@ id: 00001000000000 title: Zettelstore Manual role: manual tags: #manual #zettelstore syntax: zmk -modified: 20211027121716 +created: 20210126175322 +modified: 20241128141924 +show-back-links: false * [[Introduction|00001001000000]] * [[Design goals|00001002000000]] * [[Installation|00001003000000]] * [[Configuration|00001004000000]] @@ -14,9 +16,12 @@ * [[Zettelmarkup|00001007000000]] * [[Other markup languages|00001008000000]] * [[Security|00001010000000]] * [[API|00001012000000]] * [[Web user interface|00001014000000]] +* [[Tips and Tricks|00001017000000]] * [[Troubleshooting|00001018000000]] * Frequently asked questions + +Version: {{00001000000001}} Licensed under the EUPL-1.2-or-later. ADDED docs/manual/00001000000001.zettel Index: docs/manual/00001000000001.zettel ================================================================== --- /dev/null +++ docs/manual/00001000000001.zettel @@ -0,0 +1,8 @@ +id: 00001000000001 +title: Manual Version +role: configuration +syntax: zmk +created: 20231002142915 +modified: 20231002142948 + +To be set by build tool. ADDED docs/manual/00001000000002.zettel Index: docs/manual/00001000000002.zettel ================================================================== --- /dev/null +++ docs/manual/00001000000002.zettel @@ -0,0 +1,7 @@ +id: 00001000000002 +title: manual +role: role +syntax: zmk +created: 20231128184200 + +Zettel with the role ""manual"" contain the manual of the zettelstore. ADDED docs/manual/00001000000100.zettel Index: docs/manual/00001000000100.zettel ================================================================== --- /dev/null +++ docs/manual/00001000000100.zettel @@ -0,0 +1,8 @@ +id: 00001000000100 +title: Footer Zettel +role: configuration +syntax: zmk +created: 20221205173520 +modified: 20221207175927 + +[[Imprint / Privacy|/home/doc/trunk/www/impri.wiki]] Index: docs/manual/00001001000000.zettel ================================================================== --- docs/manual/00001001000000.zettel +++ docs/manual/00001001000000.zettel @@ -1,25 +1,17 @@ id: 00001001000000 title: Introduction to the Zettelstore role: manual tags: #introduction #manual #zettelstore syntax: zmk - -[[Personal knowledge -management|https://en.wikipedia.org/wiki/Personal_knowledge_management]] is -about collecting, classifying, storing, searching, retrieving, assessing, -evaluating, and sharing knowledge as a daily activity. Personal knowledge -management is done by most people, not necessarily as part of their main -business. It is essential for knowledge workers, like students, researchers, -lecturers, software developers, scientists, engineers, architects, to name -a few. Many hobbyists build up a significant amount of knowledge, even if the -do not need to think for a living. Personal knowledge management can be seen as -a prerequisite for many kinds of collaboration. - -Zettelstore is a software that collects and relates your notes (""zettel"") -to represent and enhance your knowledge. It helps with many tasks of personal -knowledge management by explicitly supporting the ""[[Zettelkasten -method|https://en.wikipedia.org/wiki/Zettelkasten]]"". The method is based on -creating many individual notes, each with one idea or information, that are -related to each other. Since knowledge is typically build up gradually, one -major focus is a long-term store of these notes, hence the name -""Zettelstore"". +created: 20210126175322 +modified: 20250102181246 + +[[Personal knowledge management|https://en.wikipedia.org/wiki/Personal_knowledge_management]] involves collecting, classifying, storing, searching, retrieving, assessing, evaluating, and sharing knowledge as a daily activity. +It's done by most individuals, not necessarily as part of their main business. +It's essential for knowledge workers, such as students, researchers, lecturers, software developers, scientists, engineers, architects, etc. +Many hobbyists build up a significant amount of knowledge, even if they do not need to think for a living. +Personal knowledge management can be seen as a prerequisite for many kinds of collaboration. + +Zettelstore is software that collects and relates your notes (""zettel"") to represent and enhance your knowledge, supporting the ""[[Zettelkasten method|https://en.wikipedia.org/wiki/Zettelkasten]]"". +The method is based on creating many individual notes, each containing one idea or piece of information, which are related to each other. +Since knowledge is typically built up gradually, one major focus is a long-term store of these notes, hence the name ""Zettelstore"". Index: docs/manual/00001002000000.zettel ================================================================== --- docs/manual/00001002000000.zettel +++ docs/manual/00001002000000.zettel @@ -1,32 +1,43 @@ id: 00001002000000 title: Design goals for the Zettelstore role: manual tags: #design #goal #manual #zettelstore syntax: zmk -modified: 20211124131628 +created: 20210126175322 +modified: 20250602181324 Zettelstore supports the following design goals: ; Longevity of stored notes / zettel : Every zettel you create should be readable without the help of any tool, even without Zettelstore. -: It should be not hard to write other software that works with your zettel. +: It should not be hard to write other software that works with your zettel. +: Normal zettel should be stored in a single file. + If this is not possible: at most in two files: one for the metadata, one for the content. + The only exceptions are [[predefined zettel|00001005090000]] stored in the Zettelstore executable. +: There is no additional database. ; Single user : All zettel belong to you, only to you. Zettelstore provides its services only to one person: you. - If your device is securely configured, there should be no risk that others are able to read or update your zettel. + If the computer running Zettelstore is securely configured, there should be no risk that others are able to read or update your zettel. : If you want, you can customize Zettelstore in a way that some specific or all persons are able to read some of your zettel. ; Ease of installation : If you want to use the Zettelstore software, all you need is to copy the executable to an appropriate file directory and start working. : Upgrading the software is done just by replacing the executable with a newer one. ; Ease of operation : There is only one executable for Zettelstore and one directory, where your zettel are stored. : If you decide to use multiple directories, you are free to configure Zettelstore appropriately. ; Multiple modes of operation : You can use Zettelstore as a standalone software on your device, but you are not restricted to it. -: You can install the software on a central server, or you can install it on all your devices with no restrictions how to synchronize your zettel. +: You can install the software on a central server, or you can install it on all your devices with no restrictions on how to synchronize your zettel. ; Multiple user interfaces : Zettelstore provides a default [[web-based user interface|00001014000000]]. - Anybody can provide alternative user interfaces, e.g. for special purposes. + Anyone can provide alternative user interfaces, e.g. for special purposes. ; Simple service : The purpose of Zettelstore is to safely store your zettel and to provide some initial relations between them. : External software can be written to deeply analyze your zettel and the structures they form. +; Security by default +: Without any customization, Zettelstore provides its services in a safe and secure manner and does not expose you (or other users) to security risks. +: If you know what you are doing, Zettelstore allows you to relax some security-related preferences. + However, even in this case, the more secure way is chosen. +: Zettelstore features a minimal design and relies on external software only when absolutely necessary. +: There will be no plugin mechanism, which allows external software to control the inner workings of the Zettelstore software. Index: docs/manual/00001003000000.zettel ================================================================== --- docs/manual/00001003000000.zettel +++ docs/manual/00001003000000.zettel @@ -1,27 +1,29 @@ id: 00001003000000 title: Installation of the Zettelstore software role: manual tags: #installation #manual #zettelstore syntax: zmk -modified: 20220119145756 +created: 20210126175322 +modified: 20250415170240 === The curious user You just want to check out the Zettelstore software -* Grab the appropriate executable and copy it into any directory -* Start the Zettelstore software, e.g. with a double click[^On Windows and macOS, the operating system tries to protect you from possible malicious software. If you encounter problem, please take a look on the [[Troubleshooting|00001018000000]] page.] +* Grab the appropriate executable and copy it to any directory +* Start the Zettelstore software, e.g. with a double click[^On Windows and macOS, the operating system tries to protect you from possible malicious software. + If you encounter a problem, please refer to the [[Troubleshooting|00001018000000]] page.] * A sub-directory ""zettel"" will be created in the directory where you put the executable. It will contain your future zettel. -* Open the URI [[http://localhost:23123]] with your web browser. - It will present you a mostly empty Zettelstore. +* Open the URI [[http://localhost:23123/]] with your web browser. + A mostly empty Zettelstore is presented. There will be a zettel titled ""[[Home|00010000000000]]"" that contains some helpful information. * Please read the instructions for the [[web-based user interface|00001014000000]] and learn about the various ways to write zettel. * If you restart your device, please make sure to start your Zettelstore again. === The intermediate user -You already tried the Zettelstore software and now you want to use it permanently. +You have already tried the Zettelstore software and now you want to use it permanently. Zettelstore should start automatically when you log into your computer. Please follow [[these instructions|00001003300000]]. === The server administrator Index: docs/manual/00001003300000.zettel ================================================================== --- docs/manual/00001003300000.zettel +++ docs/manual/00001003300000.zettel @@ -1,13 +1,14 @@ id: 00001003300000 title: Zettelstore installation for the intermediate user role: manual tags: #installation #manual #zettelstore syntax: zmk -modified: 20220114175754 +created: 20211125191727 +modified: 20250627152419 -You already tried the Zettelstore software and now you want to use it permanently. +You have already tried the Zettelstore software and now you want to use it permanently. Zettelstore should start automatically when you log into your computer. * Grab the appropriate executable and copy it into the appropriate directory * If you want to place your zettel into another directory, or if you want more than one [[Zettelstore box|00001004011200]], or if you want to [[enable authentication|00001010040100]], or if you want to tweak your Zettelstore in some other way, create an appropriate [[startup configuration file|00001004010000]]. * If you created a startup configuration file, you need to test it: @@ -16,11 +17,17 @@ In most cases, this is done by the command ``cd DIR``, where ''DIR'' denotes the directory, where you placed the executable. ** Start the Zettelstore: *** On Windows execute the command ``zettelstore.exe run -c CONFIG_FILE`` *** On macOS execute the command ``./zettelstore run -c CONFIG_FILE`` *** On Linux execute the command ``./zettelstore run -c CONFIG_FILE`` -** In all cases ''CONFIG_FILE'' must be substituted by file name where you wrote the startup configuration. +** In all cases, ''CONFIG_FILE'' must be replaced with the name of the file where you wrote the startup configuration. ** If you encounter some error messages, update the startup configuration, and try again. * Depending on your operating system, there are different ways to register Zettelstore to start automatically: ** [[Windows|00001003305000]] ** [[macOS|00001003310000]] ** [[Linux|00001003315000]] + +A word of caution: Never expose Zettelstore directly to the Internet. +As a personal service, Zettelstore is not designed to handle all aspects of the open web. +For instance, it lacks support for certificate handling, which is necessary for encrypted HTTP connections. +To ensure security, [[install Zettelstore on a server|00001003600000]] and place it behind a proxy server designed for Internet exposure. +For more details, see: [[External server to encrypt message transport|00001010090100]]. Index: docs/manual/00001003305000.zettel ================================================================== --- docs/manual/00001003305000.zettel +++ docs/manual/00001003305000.zettel @@ -1,11 +1,12 @@ id: 00001003305000 title: Enable Zettelstore to start automatically on Windows role: manual tags: #installation #manual #zettelstore syntax: zmk -modified: 20220218125541 +created: 20211125191727 +modified: 20250627152603 Windows is a complicated beast. There are several ways to automatically start Zettelstore. === Startup folder @@ -28,15 +29,15 @@ You can modify the behavior by changing some properties of the shortcut file. === Task scheduler -The Windows Task scheduler allows you to start Zettelstore as an background task. +The Windows Task scheduler allows you to start Zettelstore as a background task. This is both an advantage and a disadvantage. -On the plus side, Zettelstore runs in the background, and it does not disturbs you. +On the plus side, Zettelstore runs in the background, and it does not disturb you. All you have to do is to open your web browser, enter the appropriate URL, and there you go. On the negative side, you will not be notified when you enter the wrong data in the Task scheduler and Zettelstore fails to start. This can be mitigated by first using the command line prompt to start Zettelstore with the appropriate options. Once everything works, you can register Zettelstore to be automatically started by the task scheduler. @@ -69,11 +70,11 @@ {{00001003305112}} The next steps are the trickiest. -If you did not created a startup configuration file, then create an action that starts a program. +If you did not create a startup configuration file, then create an action that starts a program. Enter the file path where you placed the Zettelstore executable. The ""Browse ..."" button helps you with that.[^I store my Zettelstore executable in the sub-directory ''bin'' of my home directory.] It is essential that you also enter a directory, which serves as the environment for your zettelstore. The (sub-) directory ''zettel'', which will contain your zettel, will be placed in this directory. @@ -110,10 +111,10 @@ As the last step, you could run the freshly created task manually. Open your browser, enter the appropriate URL and use your Zettelstore. In case of errors, the task will most likely stop immediately. Make sure that all data you have entered is valid. -To not forget to check the content of the startup configuration file. +Do not forget to check the content of the startup configuration file. Use the command prompt to debug your configuration. Sometimes, for example when your computer was in stand-by and it wakes up, these tasks are not started. In this case execute the task scheduler and run the task manually. Index: docs/manual/00001003310000.zettel ================================================================== --- docs/manual/00001003310000.zettel +++ docs/manual/00001003310000.zettel @@ -1,10 +1,11 @@ id: 00001003310000 title: Enable Zettelstore to start automatically on macOS role: manual tags: #installation #manual #zettelstore syntax: zmk +created: 20220114181521 modified: 20220119124635 There are several ways to automatically start Zettelstore. * [[Login Items|#login-items]] Index: docs/manual/00001003315000.zettel ================================================================== --- docs/manual/00001003315000.zettel +++ docs/manual/00001003315000.zettel @@ -1,26 +1,27 @@ id: 00001003315000 title: Enable Zettelstore to start automatically on Linux role: manual tags: #installation #manual #zettelstore syntax: zmk -modified: 20220307104944 +created: 20220114181521 +modified: 20250627153033 Since there is no such thing as the one Linux, there are too many different ways to automatically start Zettelstore. * One way is to interpret your Linux desktop system as a server and use the [[recipe to install Zettelstore on a server|00001003600000]]. ** See below for a lighter alternative. * If you are using the [[Gnome Desktop|https://www.gnome.org/]], you could use the tool [[Tweak|https://wiki.gnome.org/action/show/Apps/Tweaks]] (formerly known as ""GNOME Tweak Tool"" or just ""Tweak Tool""). - It allows to specify application that should run on startup / login. + It allows you to specify applications that should run on startup / login. * [[KDE|https://kde.org/]] provides a system setting to [[autostart|https://docs.kde.org/stable5/en/plasma-workspace/kcontrol/autostart/]] applications. * [[Xfce|https://xfce.org/]] allows to specify [[autostart applications|https://docs.xfce.org/xfce/xfce4-session/preferences#application_autostart]]. * [[LXDE|https://www.lxde.org/]] uses [[LXSession Edit|https://wiki.lxde.org/en/LXSession_Edit]] to allow users to specify autostart applications. -If you use a different desktop environment, it often helps to to provide its name and the string ""autostart"" to google for it with the search engine of your choice. +If you're using a different desktop environment, try searching for its name together with the word ""autostart"". Yet another way is to make use of the middleware that is provided. -Many Linux distributions make use of [[systemd|https://systemd.io/]], which allows to start processes on behalf of an user. +Many Linux distributions make use of [[systemd|https://systemd.io/]], which allows to start processes on behalf of a user. On the command line, adapt the following script to your own needs and execute it: ``` # mkdir -p "$HOME/.config/systemd/user" # cd "$HOME/.config/systemd/user" # cat <<__EOF__ > zettelstore.service Index: docs/manual/00001003600000.zettel ================================================================== --- docs/manual/00001003600000.zettel +++ docs/manual/00001003600000.zettel @@ -1,11 +1,12 @@ id: 00001003600000 title: Installation of Zettelstore on a server role: manual tags: #installation #manual #zettelstore syntax: zmk -modified: 20211125185833 +created: 20211125191727 +modified: 20250227220033 You want to provide a shared Zettelstore that can be used from your various devices. Installing Zettelstore as a Linux service is not that hard. Grab the appropriate executable and copy it into the appropriate directory: @@ -49,5 +50,11 @@ Use the commands ``systemctl``{=sh} and ``journalctl``{=sh} to manage the service, e.g.: ```sh # sudo systemctl status zettelstore # verify that it is running # sudo journalctl -u zettelstore # obtain the output of the running zettelstore ``` + +A word of caution: Never expose Zettelstore directly to the Internet. +As a personal service, Zettelstore is not designed to handle all aspects of the open web. +For instance, it lacks support for certificate handling, which is necessary for encrypted HTTP connections. +To ensure security, place Zettelstore behind a proxy server designed for Internet exposure. +For more details, see: [[External server to encrypt message transport|00001010090100]]. Index: docs/manual/00001004000000.zettel ================================================================== --- docs/manual/00001004000000.zettel +++ docs/manual/00001004000000.zettel @@ -1,13 +1,14 @@ id: 00001004000000 title: Configuration of Zettelstore role: manual tags: #configuration #manual #zettelstore syntax: zmk -modified: 20210510153233 +created: 20210126175322 +modified: 20250102181034 -There are some levels to change the behavior and/or the appearance of Zettelstore. +There are several levels to change the behavior and/or the appearance of Zettelstore. # The first level is the way to start Zettelstore services and to manage it via command line (and, in part, via a graphical user interface). #* [[Command line parameters|00001004050000]] # As an intermediate user, you usually want to have more control over how Zettelstore is started. This may include the URI under which your Zettelstore is accessible, or the directories in which your Zettel are stored. Index: docs/manual/00001004010000.zettel ================================================================== --- docs/manual/00001004010000.zettel +++ docs/manual/00001004010000.zettel @@ -1,113 +1,171 @@ id: 00001004010000 title: Zettelstore startup configuration role: manual tags: #configuration #manual #zettelstore syntax: zmk -modified: 20220419193611 +created: 20210126175322 +modified: 20250627155145 -The configuration file, as specified by the ''-c CONFIGFILE'' [[command line option|00001004051000]], allows you to specify some startup options. -These options cannot be stored in a [[configuration zettel|00001004020000]] because either they are needed before Zettelstore can start or because of security reasons. -For example, Zettelstore need to know in advance, on which network address is must listen or where zettel are stored. +The configuration file, specified by the ''-c CONFIGFILE'' [[command line option|00001004051000]], allows you to specify some startup options. +These cannot be stored in a [[configuration zettel|00001004020000]] because they are needed before Zettelstore can start or because of security reasons. +For example, Zettelstore needs to know in advance on which network address it must listen or where zettel are stored. An attacker that is able to change the owner can do anything. -Therefore only the owner of the computer on which Zettelstore runs can change this information. +Therefore, only the owner of the computer on which Zettelstore runs can change this information. The file for startup configuration must be created via a text editor in advance. The syntax of the configuration file is the same as for any zettel metadata. The following keys are supported: ; [!admin-port|''admin-port''] : Specifies the TCP port through which you can reach the [[administrator console|00001004100000]]. - A value of ""0"" (the default) disables the administrator console. + A value of ""0"" (the default) disables it. The administrator console will only be enabled if Zettelstore is started with the [[''run'' sub-command|00001004051000]]. On most operating systems, the value must be greater than ""1024"" unless you start Zettelstore with the full privileges of a system administrator (which is not recommended). Default: ""0"" +; [!asset-dir|''asset-dir''] +: Allows to specify a directory whose files are allowed to be transferred directly with the help of the web server. + The URL prefix for these files is ''/assets/''. + You can use this if you want to transfer files that are too large for a zettel, such as presentation, PDF, music or video files. + + Files within the given directory will not be managed by Zettelstore.[^They will be managed by Zettelstore just in the very special case that the directory is one of the configured [[boxes|#box-uri-x]].] + + If you specify only the URL prefix in your web client, the contents of the directory are listed. + To avoid this, create an empty file in the directory named ""index.html"". + + Default: """", no asset directory is set, the URL prefix ''/assets/'' is invalid. +; [!base-url|''base-url''] +: Sets the absolute base URL for the service. + + Note: [[''url-prefix''|#url-prefix]] must be the suffix of ''base-url'', otherwise the web service will not start. + + Default: ""http://127.0.0.1:23123/"". ; [!box-uri-x|''box-uri-X''], where __X__ is a number greater or equal to one : Specifies a [[box|00001004011200]] where zettel are stored. - During startup __X__ is counted up, starting with one, until no key is found. - This allows to configure more than one box. + During startup, __X__ is incremented, starting with one, until no key is found. + This allows you to configure than one box. If no ''box-uri-1'' key is given, the overall effect will be the same as if only ''box-uri-1'' was specified with the value ""dir://.zettel"". In this case, even a key ''box-uri-2'' will be ignored. ; [!debug-mode|''debug-mode''] -: Allows to debug the Zettelstore software (mostly used by the developers) if set to [[true|00001006030500]] +: If set to [[true|00001006030500]], allows to debug the Zettelstore software (mostly used by Zettelstore developers). Disables any timeout values of the internal web server and does not send some security-related data. Sets [[''log-level''|#log-level]] to ""debug"". + Enables [[''runtime-profiling''|#runtime-profiling]]. Do not enable it for a production server. Default: ""false"" ; [!default-dir-box-type|''default-dir-box-type''] -: Specifies the default value for the (sub-) type of [[directory boxes|00001004011400#type]]. - Zettel are typically stored in such boxes. +: Specifies the default value for the (sub-)type of [[directory boxes|00001004011400#type]], in which Zettel are typically stored. Default: ""notify"" ; [!insecure-cookie|''insecure-cookie''] -: Must be set to [[true|00001006030500]], if authentication is enabled and Zettelstore is not accessible not via HTTPS (but via HTTP). - Otherwise web browser are free to ignore the authentication cookie. +: Must be set to [[true|00001006030500]] if authentication is enabled and Zettelstore is not accessible via HTTPS (but via HTTP). + Otherwise web browsers are free to ignore the authentication cookie. Default: ""false"" +; [!insecure-html|''insecure-html''] +: Allows to use HTML, e.g. within supported markup languages, even if this might introduce security-related problems. + However, HTML containing the `` +<script>alert('1');</script> + + +"> +'> +> + +< / script >< script >alert(8)< / script > + onfocus=JaVaSCript:alert(9) autofocus +" onfocus=JaVaSCript:alert(10) autofocus +' onfocus=JaVaSCript:alert(11) autofocus +<script>alert(12)</script> +ript>alert(13)ript> +--> +";alert(15);t=" +';alert(16);t=' +JavaSCript:alert(17) +;alert(18); +src=JaVaSCript:prompt(19) +">javascript:alert(25); +javascript:alert(26); +javascript:alert(27); +javascript:alert(28); +javascript:alert(29); +javascript:alert(30); +javascript:alert(31); +'`"><\x3Cscript>javascript:alert(32) +'`"><\x00script>javascript:alert(33) +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +ABC
DEF +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +test +`"'> +`"'> +`"'> +`"'> +`"'> +`"'> +`"'> +`"'> +`"'> +`"'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> +"`'> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +XXX + + + +<a href=http://foo.bar/#x=`y></a><img alt="`><img src=x:x onerror=javascript:alert(203)></a>"> +<!--[if]><script>javascript:alert(204)</script --> +<!--[if<img src=x onerror=javascript:alert(205)//]> --> +<script src="/\%(jscript)s"></script> +<script src="\\%(jscript)s"></script> +<IMG """><SCRIPT>alert("206")</SCRIPT>"> +<IMG SRC=javascript:alert(String.fromCharCode(50,48,55))> +<IMG SRC=# onmouseover="alert('208')"> +<IMG SRC= onmouseover="alert('209')"> +<IMG onmouseover="alert('210')"> +<IMG SRC=javascript:alert('211')> +<IMG SRC=javascript:alert('212')> +<IMG SRC=javascript:alert('213')> +<IMG SRC="jav   ascript:alert('214');"> +<IMG SRC="jav ascript:alert('215');"> +<IMG SRC="jav ascript:alert('216');"> +<IMG SRC="jav ascript:alert('217');"> +perl -e 'print "<IMG SRC=java\0script:alert(\"218\")>";' > out +<IMG SRC="   javascript:alert('219');"> +<SCRIPT/XSS SRC="http://ha.ckers.org/xss.js"></SCRIPT> +<BODY onload!#$%&()*~+-_.,:;?@[/|\]^`=alert("220")> +<SCRIPT/SRC="http://ha.ckers.org/xss.js"></SCRIPT> +<<SCRIPT>alert("221");//<</SCRIPT> +<SCRIPT SRC=http://ha.ckers.org/xss.js?< B > +<SCRIPT SRC=//ha.ckers.org/.j> +<IMG SRC="javascript:alert('222')" +<iframe src=http://ha.ckers.org/scriptlet.html < +\";alert('223');// +<u oncopy=alert()> Copy me</u> +<i onwheel=alert(224)> Scroll over me </i> +<plaintext> +http://a/%%30%30 +</textarea><script>alert(225)</script> + +# SQL Injection +# +# Strings which can cause a SQL injection if inputs are not sanitized + +1;DROP TABLE users +1'; DROP TABLE users-- 1 +' OR 1=1 -- 1 +' OR '1'='1 +'; EXEC sp_MSForEachTable 'DROP TABLE ?'; -- + +% +_ + +# Server Code Injection +# +# Strings which can cause user to run code on server as a privileged user (c.f. https://news.ycombinator.com/item?id=7665153) + +- +-- +--version +--help +$USER +/dev/null; touch /tmp/blns.fail ; echo +`touch /tmp/blns.fail` +$(touch /tmp/blns.fail) +@{[system "touch /tmp/blns.fail"]} + +# Command Injection (Ruby) +# +# Strings which can call system commands within Ruby/Rails applications + +eval("puts 'hello world'") +System("ls -al /") +`ls -al /` +Kernel.exec("ls -al /") +Kernel.exit(1) +%x('ls -al /') + +# XXE Injection (XML) +# +# String which can reveal system files when parsed by a badly configured XML parser + +<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE foo [ <!ELEMENT foo ANY ><!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo> + +# Unwanted Interpolation +# +# Strings which can be accidentally expanded into different strings if evaluated in the wrong context, e.g. used as a printf format string or via Perl or shell eval. Might expose sensitive data from the program doing the interpolation, or might just represent the wrong string. + +$HOME +$ENV{'HOME'} +%d +%s%s%s%s%s +{0} +%*.*s +%@ +%n +File:/// + +# File Inclusion +# +# Strings which can cause user to pull in files that should not be a part of a web server + +../../../../../../../../../../../etc/passwd%00 +../../../../../../../../../../../etc/hosts + +# Known CVEs and Vulnerabilities +# +# Strings that test for known vulnerabilities + +() { 0; }; touch /tmp/blns.shellshock1.fail; +() { _; } >_[$($())] { touch /tmp/blns.shellshock2.fail; } +<<< %s(un='%s') = %u ++++ATH0 + +# MSDOS/Windows Special Filenames +# +# Strings which are reserved characters in MSDOS/Windows + +CON +PRN +AUX +CLOCK$ +NUL +A: +ZZ: +COM1 +LPT1 +LPT2 +LPT3 +COM2 +COM3 +COM4 + +# IRC specific strings +# +# Strings that may occur on IRC clients that make security products freak out + +DCC SEND STARTKEYLOGGER 0 0 0 + +# Scunthorpe Problem +# +# Innocuous strings which may be blocked by profanity filters (https://en.wikipedia.org/wiki/Scunthorpe_problem) + +Scunthorpe General Hospital +Penistone Community Church +Lightwater Country Park +Jimmy Clitheroe +Horniman Museum +shitake mushrooms +RomansInSussex.co.uk +http://www.cum.qc.ca/ +Craig Cockburn, Software Specialist +Linda Callahan +Dr. Herman I. Libshitz +magna cum laude +Super Bowl XXX +medieval erection of parapets +evaluate +mocha +expression +Arsenal canal +classic +Tyson Gay +Dick Van Dyke +basement + +# Human injection +# +# Strings which may cause human to reinterpret worldview + +If you're reading this, you've been in a coma for almost 20 years now. We're trying a new technique. We don't know where this message will end up in your dream, but we hope it works. Please wake up, we miss you. + +# Terminal escape codes +# +# Strings which punish the fools who use cat/type on this file + +Roses are red, violets are blue. Hope you enjoy terminal hue +But now...for my greatest trick... +The quick brown fox... [Beeeep] + +# iOS Vulnerabilities +# +# Strings which crashed iMessage in various versions of iOS + +Powerلُلُصّبُلُلصّبُررً ॣ ॣh ॣ ॣ冗 +🏳0🌈️ +జ్ఞ‌ా + +# Persian special characters +# +# This is a four characters string which includes Persian special characters (گچپژ) + +گچپژ + +# jinja2 injection +# +# first one is supposed to raise "MemoryError" exception +# second, obviously, prints contents of /etc/passwd + +{% print 'x' * 64 * 1024**3 %} +{{ "".__class__.__mro__[2].__subclasses__()[40]("/etc/passwd").read() }} ADDED testdata/testbox/00000999999999.zettel Index: testdata/testbox/00000999999999.zettel ================================================================== --- /dev/null +++ testdata/testbox/00000999999999.zettel @@ -0,0 +1,11 @@ +id: 00000999999999 +title: Zettelstore Application Directory +role: configuration +syntax: none +app-zid: 00000999999999 +created: 20240703235900 +lang: en +modified: 20240708125724 +nozid-zid: 9999999998 +noappzid: 00000999999999 +visibility: login ADDED testdata/testbox/20230929102100.zettel Index: testdata/testbox/20230929102100.zettel ================================================================== --- /dev/null +++ testdata/testbox/20230929102100.zettel @@ -0,0 +1,7 @@ +id: 20230929102100 +title: #test +role: tag +syntax: zmk +created: 20230929102125 + +Zettel with this tag are testing the Zettelstore. Index: tests/client/client_test.go ================================================================== --- tests/client/client_test.go +++ tests/client/client_test.go @@ -1,45 +1,46 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern +// Copyright (c) 2021-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore client is licensed under the latest version of the EUPL // (European Union Public License). Please see file LICENSE.txt for your rights // and obligations under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2021-present Detlef Stern //----------------------------------------------------------------------------- // Package client provides a client for accessing the Zettelstore via its API. package client_test import ( "context" "flag" "fmt" + "io" "net/http" "net/url" + "slices" "strconv" "testing" - "zettelstore.de/c/api" - "zettelstore.de/c/client" - "zettelstore.de/z/kernel" + "t73f.de/r/zsc/api" + "t73f.de/r/zsc/client" + "t73f.de/r/zsc/domain/id" + "t73f.de/r/zsc/domain/meta" + "zettelstore.de/z/internal/kernel" ) -func nextZid(zid api.ZettelID) api.ZettelID { - numVal, err := strconv.ParseUint(string(zid), 10, 64) - if err != nil { - panic(err) - } - return api.ZettelID(fmt.Sprintf("%014d", numVal+1)) -} +func nextZid(zid id.Zid) id.Zid { return zid + 1 } func TestNextZid(t *testing.T) { testCases := []struct { - zid, exp api.ZettelID + zid, exp id.Zid }{ - {api.ZettelID("00000000000000"), api.ZettelID("00000000000001")}, + {1, 2}, } for i, tc := range testCases { if got := nextZid(tc.zid); got != tc.exp { t.Errorf("%d: zid=%q, exp=%q, got=%q", i, tc.zid, tc.exp, got) } @@ -47,16 +48,16 @@ } } func TestListZettel(t *testing.T) { const ( - ownerZettel = 49 - configRoleZettel = 31 - writerZettel = ownerZettel - 25 - readerZettel = ownerZettel - 25 - creatorZettel = 7 - publicZettel = 4 + ownerZettel = 58 + configRoleZettel = 36 + writerZettel = ownerZettel - 24 + readerZettel = ownerZettel - 24 + creatorZettel = 11 + publicZettel = 6 ) testdata := []struct { user string exp int @@ -68,68 +69,76 @@ {"owner", ownerZettel}, } t.Parallel() c := getClient() - query := url.Values{api.QueryKeyEncoding: {api.EncodingHTML}} // Client must remove "html" for i, tc := range testdata { t.Run(fmt.Sprintf("User %d/%q", i, tc.user), func(tt *testing.T) { c.SetAuth(tc.user, tc.user) - q, l, err := c.ListZettelJSON(context.Background(), query) + q, h, l, err := c.QueryZettelData(context.Background(), "") if err != nil { tt.Error(err) return } if q != "" { tt.Errorf("Query should be empty, but is %q", q) } + if h != "" { + tt.Errorf("Human should be empty, but is %q", q) + } got := len(l) if got != tc.exp { tt.Errorf("List of length %d expected, but got %d\n%v", tc.exp, got, l) } }) } - q, l, err := c.ListZettelJSON(context.Background(), url.Values{api.KeyRole: {api.ValueRoleConfiguration}}) + search := meta.KeyRole + api.SearchOperatorHas + meta.ValueRoleConfiguration + " ORDER id" + q, h, l, err := c.QueryZettelData(context.Background(), search) if err != nil { t.Error(err) return } - expQ := "role MATCH configuration" + expQ := "role:configuration ORDER id" if q != expQ { t.Errorf("Query should be %q, but is %q", expQ, q) } + expH := "role HAS configuration ORDER id" + if h != expH { + t.Errorf("Human should be %q, but is %q", expH, h) + } got := len(l) if got != configRoleZettel { t.Errorf("List of length %d expected, but got %d\n%v", configRoleZettel, got, l) } - pl, err := c.ListZettel(context.Background(), url.Values{api.KeyRole: {api.ValueRoleConfiguration}}) + pl, err := c.QueryZettel(context.Background(), search) if err != nil { t.Error(err) return } compareZettelList(t, pl, l) } -func compareZettelList(t *testing.T, pl [][]byte, l []api.ZidMetaJSON) { +func compareZettelList(t *testing.T, pl [][]byte, l []api.ZidMetaRights) { t.Helper() if len(pl) != len(l) { - t.Errorf("Different list lenght: Plain=%d, JSON=%d", len(pl), len(l)) + t.Errorf("Different list lenght: Plain=%d, Data=%d", len(pl), len(l)) } else { for i, line := range pl { - if got := api.ZettelID(line[:14]); got != l[i].ID { - t.Errorf("%d: JSON=%q, got=%q", i, l[i].ID, got) + got, err := id.Parse(string(line[:14])) + if err == nil && got != l[i].ID { + t.Errorf("%d: Data=%q, got=%q", i, l[i].ID, got) } } } } -func TestGetZettelJSON(t *testing.T) { +func TestGetZettelData(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") - z, err := c.GetZettelJSON(context.Background(), api.ZidDefaultHome) + z, err := c.GetZettelData(context.Background(), id.ZidDefaultHome) if err != nil { t.Error(err) return } if m := z.Meta; len(m) == 0 { @@ -137,21 +146,24 @@ } if z.Content == "" || z.Encoding != "" { t.Errorf("Expect non-empty content, but empty encoding (got %q)", z.Encoding) } - m, err := c.GetMeta(context.Background(), api.ZidDefaultHome) + mr, err := c.GetMetaData(context.Background(), id.ZidDefaultHome) if err != nil { t.Error(err) return } - if len(m) != len(z.Meta) { - t.Errorf("Pure meta differs from zettel meta: %s vs %s", m, z.Meta) + if mr.Rights == api.ZettelCanNone { + t.Error("rights must be greater zero") + } + if len(mr.Meta) != len(z.Meta) { + t.Errorf("Pure meta differs from zettel meta: %s vs %s", mr.Meta, z.Meta) return } for k, v := range z.Meta { - got, ok := m[k] + got, ok := mr.Meta[k] if !ok { t.Errorf("Pure meta has no key %q", k) continue } if got != v { @@ -163,25 +175,24 @@ func TestGetParsedEvaluatedZettel(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") encodings := []api.EncodingEnum{ - api.EncoderZJSON, api.EncoderHTML, - api.EncoderSexpr, + api.EncoderSz, api.EncoderText, } for _, enc := range encodings { - content, err := c.GetParsedZettel(context.Background(), api.ZidDefaultHome, enc) + content, err := c.GetParsedZettel(context.Background(), id.ZidDefaultHome, enc) if err != nil { t.Error(err) continue } if len(content) == 0 { t.Errorf("Empty content for parsed encoding %v", enc) } - content, err = c.GetEvaluatedZettel(context.Background(), api.ZidDefaultHome, enc) + content, err = c.GetEvaluatedZettel(context.Background(), id.ZidDefaultHome, enc) if err != nil { t.Error(err) continue } if len(content) == 0 { @@ -188,127 +199,109 @@ t.Errorf("Empty content for evaluated encoding %v", enc) } } } -func checkZid(t *testing.T, expected, got api.ZettelID) bool { - t.Helper() - if expected != got { - t.Errorf("Expected a Zid %q, but got %q", expected, got) - return false - } - return true -} - -func checkListZid(t *testing.T, l []api.ZidMetaJSON, pos int, expected api.ZettelID) { - t.Helper() - if got := api.ZettelID(l[pos].ID); got != expected { +func checkListZid(t *testing.T, l []api.ZidMetaRights, pos int, expected id.Zid) { + t.Helper() + if got := l[pos].ID; got != expected { t.Errorf("Expected result[%d]=%v, but got %v", pos, expected, got) } } func TestGetZettelOrder(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") - rl, err := c.GetZettelOrder(context.Background(), api.ZidTOCNewTemplate) + _, _, metaSeq, err := c.QueryZettelData(context.Background(), id.ZidTOCNewTemplate.String()+" "+api.ItemsDirective) if err != nil { t.Error(err) return } - if !checkZid(t, api.ZidTOCNewTemplate, rl.ID) { + if got := len(metaSeq); got != 4 { + t.Errorf("Expected list of length 4, got %d", got) return } - l := rl.List - if got := len(l); got != 2 { - t.Errorf("Expected list of length 2, got %d", got) - return - } - checkListZid(t, l, 0, api.ZidTemplateNewZettel) - checkListZid(t, l, 1, api.ZidTemplateNewUser) + checkListZid(t, metaSeq, 0, id.ZidTemplateNewZettel) + checkListZid(t, metaSeq, 1, id.ZidTemplateNewRole) + checkListZid(t, metaSeq, 2, id.ZidTemplateNewTag) + checkListZid(t, metaSeq, 3, id.ZidTemplateNewUser) } func TestGetZettelContext(t *testing.T) { const ( - allUserZid = api.ZettelID("20211019200500") - ownerZid = api.ZettelID("20210629163300") - writerZid = api.ZettelID("20210629165000") - readerZid = api.ZettelID("20210629165024") - creatorZid = api.ZettelID("20210629165050") + allUserZid = id.Zid(20211019200500) + ownerZid = id.Zid(20210629163300) + writerZid = id.Zid(20210629165000) + readerZid = id.Zid(20210629165024) + creatorZid = id.Zid(20210629165050) limitAll = 3 ) t.Parallel() c := getClient() c.SetAuth("owner", "owner") - rl, err := c.GetZettelContext(context.Background(), ownerZid, client.DirBoth, 0, limitAll) - if err != nil { - t.Error(err) - return - } - if !checkZid(t, ownerZid, rl.ID) { - return - } - l := rl.List - if got := len(l); got != limitAll { - t.Errorf("Expected list of length %d, got %d", limitAll, got) - t.Error(rl) - return - } - checkListZid(t, l, 0, allUserZid) - checkListZid(t, l, 1, writerZid) - checkListZid(t, l, 2, readerZid) - // checkListZid(t, l, 3, creatorZid) - - rl, err = c.GetZettelContext(context.Background(), ownerZid, client.DirBackward, 0, 0) - if err != nil { - t.Error(err) - return - } - if !checkZid(t, ownerZid, rl.ID) { - return - } - l = rl.List - if got := len(l); got != 1 { - t.Errorf("Expected list of length 1, got %d", got) - return - } - checkListZid(t, l, 0, allUserZid) + rl, err := c.QueryZettel(context.Background(), ownerZid.String()+" CONTEXT LIMIT "+strconv.Itoa(limitAll)) + if err != nil { + t.Error(err) + return + } + checkZidList(t, []id.Zid{ownerZid, allUserZid, writerZid}, rl) + + rl, err = c.QueryZettel(context.Background(), ownerZid.String()+" CONTEXT BACKWARD") + if err != nil { + t.Error(err) + return + } + checkZidList(t, []id.Zid{ownerZid, allUserZid}, rl) +} +func checkZidList(t *testing.T, exp []id.Zid, got [][]byte) { + t.Helper() + if len(exp) != len(got) { + t.Errorf("expected a list fo length %d, but got %d", len(exp), len(got)) + return + } + for i, expZid := range exp { + gotZid, err := id.Parse(string(got[i][:14])) + if err != nil || expZid != gotZid { + t.Errorf("lists differ at pos %d: expected id %v, but got %v", i, expZid, gotZid) + } + } } func TestGetUnlinkedReferences(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") - zl, err := c.GetUnlinkedReferences(context.Background(), api.ZidDefaultHome, nil) - if err != nil { - t.Error(err) - return - } - if !checkZid(t, api.ZidDefaultHome, zl.ID) { - return - } - l := zl.List - if got := len(l); got != 1 { - t.Errorf("Expected list of length 1, got %d", got) - return - } -} - -func failNoErrorOrNoCode(t *testing.T, err error, goodCode int) bool { - if err != nil { - if cErr, ok := err.(*client.Error); ok { - if cErr.StatusCode == goodCode { - return false - } - t.Errorf("Expect status code %d, but got client error %v", goodCode, cErr) - } else { - t.Errorf("Expect status code %d, but got non-client error %v", goodCode, err) - } - } else { - t.Errorf("No error returned, but status code %d expected", goodCode) - } - return true + _, _, metaSeq, err := c.QueryZettelData(context.Background(), id.ZidDefaultHome.String()+" "+api.UnlinkedDirective) + if err != nil { + t.Error(err) + return + } + if got := len(metaSeq); got != 1 { + t.Errorf("Expected list of length 1, got %d:\n%v", got, metaSeq) + return + } +} + +func TestGetReferences(t *testing.T) { + t.Parallel() + c := getClient() + c.SetAuth("owner", "owner") + urls, err := c.GetReferences(context.Background(), id.ZidDefaultHome, "zettel") + if err != nil { + t.Error(err) + return + } + exp := []string{ + "https://zettelstore.de/", + "https://zettelstore.de/home/doc/trunk/www/download.wiki", + "https://zettelstore.de/home/doc/trunk/www/changes.wiki", + "mailto:ds@zettelstore.de", + } + if !slices.Equal(urls, exp) { + t.Errorf("wrong references of home zettel: expected\n%v, but got\n%v", exp, urls) + } } func TestExecuteCommand(t *testing.T) { c := getClient() err := c.ExecuteCommand(context.Background(), api.Command("xyz")) @@ -326,16 +319,30 @@ err = c.ExecuteCommand(context.Background(), api.CommandRefresh) if err != nil { t.Error(err) } } +func failNoErrorOrNoCode(t *testing.T, err error, goodCode int) { + if err != nil { + if cErr, ok := err.(*client.Error); ok { + if cErr.StatusCode == goodCode { + return + } + t.Errorf("Expect status code %d, but got client error %v", goodCode, cErr) + } else { + t.Errorf("Expect status code %d, but got non-client error %v", goodCode, err) + } + } else { + t.Errorf("No error returned, but status code %d expected", goodCode) + } +} func TestListTags(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") - tm, err := c.ListMapMeta(context.Background(), api.KeyTags) + agg, err := c.QueryAggregate(context.Background(), api.ActionSeparator+meta.KeyTags) if err != nil { t.Error(err) return } tags := []struct { @@ -344,59 +351,155 @@ }{ {"#invisible", 1}, {"#user", 4}, {"#test", 4}, } - if len(tm) != len(tags) { - t.Errorf("Expected %d different tags, but got only %d (%v)", len(tags), len(tm), tm) + if len(agg) != len(tags) { + t.Errorf("Expected %d different tags, but got %d (%v)", len(tags), len(agg), agg) } for _, tag := range tags { - if zl, ok := tm[tag.key]; !ok { - t.Errorf("No tag %v: %v", tag.key, tm) + if zl, ok := agg[tag.key]; !ok { + t.Errorf("No tag %v: %v", tag.key, agg) } else if len(zl) != tag.size { t.Errorf("Expected %d zettel with tag %v, but got %v", tag.size, tag.key, zl) } } - for i, id := range tm["#user"] { - if id != tm["#test"][i] { - t.Errorf("Tags #user and #test have different content: %v vs %v", tm["#user"], tm["#test"]) + for i, id := range agg["#user"] { + if id != agg["#test"][i] { + t.Errorf("Tags #user and #test have different content: %v vs %v", agg["#user"], agg["#test"]) } } } + +func TestTagZettel(t *testing.T) { + t.Parallel() + c := getClient() + c.AllowRedirect(true) + c.SetAuth("owner", "owner") + ctx := context.Background() + zid, err := c.TagZettel(ctx, "nosuchtag") + if err != nil { + t.Error(err) + } else if zid != id.Invalid { + t.Errorf("no zid expected, but got %q", zid) + } + zid, err = c.TagZettel(ctx, "#test") + exp := id.Zid(20230929102100) + if err != nil { + t.Error(err) + } else if zid != exp { + t.Errorf("tag zettel for #test should be %q, but got %q", exp, zid) + } +} func TestListRoles(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") - rl, err := c.ListMapMeta(context.Background(), api.KeyRole) + agg, err := c.QueryAggregate(context.Background(), api.ActionSeparator+meta.KeyRole) + if err != nil { + t.Error(err) + return + } + exp := []string{"configuration", "role", "user", "tag", "zettel"} + if len(agg) != len(exp) { + t.Errorf("Expected %d different roles, but got %d (%v)", len(exp), len(agg), agg) + } + for _, id := range exp { + if _, found := agg[id]; !found { + t.Errorf("Role map expected key %q", id) + } + } +} + +func TestRoleZettel(t *testing.T) { + t.Parallel() + c := getClient() + c.AllowRedirect(true) + c.SetAuth("owner", "owner") + ctx := context.Background() + zid, err := c.RoleZettel(ctx, "nosuchrole") + if err != nil { + t.Error("AAA", err) + } else if zid != id.Invalid { + t.Errorf("no zid expected, but got %q", zid) + } + zid, err = c.RoleZettel(ctx, "zettel") + exp := id.Zid(60010) + if err != nil { + t.Error(err) + } else if zid != exp { + t.Errorf("role zettel for zettel should be %q, but got %q", exp, zid) + } +} + +func TestRedirect(t *testing.T) { + t.Parallel() + c := getClient() + search := "emoji" + api.ActionSeparator + api.RedirectAction + ub := c.NewURLBuilder('z').AppendQuery(search) + respRedirect, err := http.Get(ub.String()) + if err != nil { + t.Error(err) + return + } + defer func() { _ = respRedirect.Body.Close() }() + bodyRedirect, err := io.ReadAll(respRedirect.Body) + if err != nil { + t.Error(err) + return + } + ub.ClearQuery().SetZid(id.ZidEmoji) + respEmoji, err := http.Get(ub.String()) + if err != nil { + t.Error(err) + return + } + defer func() { _ = respEmoji.Body.Close() }() + bodyEmoji, err := io.ReadAll(respEmoji.Body) if err != nil { t.Error(err) return } - exp := []string{"configuration", "user", "zettel"} - if len(rl) != len(exp) { - t.Errorf("Expected %d different tags, but got only %d (%v)", len(exp), len(rl), rl) - } - for _, id := range exp { - if _, found := rl[id]; !found { - t.Errorf("Role map expected key %q", id) - } + if !slices.Equal(bodyRedirect, bodyEmoji) { + t.Error("Wrong redirect") + t.Error("REDIRECT", respRedirect) + t.Error("EXPECTED", respEmoji) } } func TestVersion(t *testing.T) { t.Parallel() c := getClient() - ver, err := c.GetVersionJSON(context.Background()) + ver, err := c.GetVersionInfo(context.Background()) if err != nil { t.Error(err) return } if ver.Major != -1 || ver.Minor != -1 || ver.Patch != -1 || ver.Info != kernel.CoreDefaultVersion || ver.Hash != "" { t.Error(ver) } } + +func TestApplicationZid(t *testing.T) { + c := getClient() + c.SetAuth("reader", "reader") + zid, err := c.GetApplicationZid(context.Background(), "app") + if err != nil { + t.Error(err) + return + } + if zid != id.ZidAppDirectory { + t.Errorf("c.GetApplicationZid(\"app\") should result in %q, but got: %q", id.ZidAppDirectory, zid) + } + if zid, err = c.GetApplicationZid(context.Background(), "noappzid"); err == nil { + t.Errorf(`c.GetApplicationZid("nozid") should result in error, but got: %v`, zid) + } + if zid, err = c.GetApplicationZid(context.Background(), "nozid"); err == nil { + t.Errorf(`c.GetApplicationZid("nozid") should result in error, but got: %v`, zid) + } +} var baseURL string func init() { flag.StringVar(&baseURL, "base-url", "", "Base URL") Index: tests/client/crud_test.go ================================================================== --- tests/client/crud_test.go +++ tests/client/crud_test.go @@ -1,30 +1,35 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern +// Copyright (c) 2021-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore client is licensed under the latest version of the EUPL // (European Union Public License). Please see file LICENSE.txt for your rights // and obligations under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2021-present Detlef Stern //----------------------------------------------------------------------------- package client_test import ( "context" "strings" "testing" - "zettelstore.de/c/api" - "zettelstore.de/c/client" + "t73f.de/r/zsc/api" + "t73f.de/r/zsc/client" + "t73f.de/r/zsc/domain/id" + "t73f.de/r/zsc/domain/meta" ) // --------------------------------------------------------------------------- // Tests that change the Zettelstore must nor run parallel to other tests. -func TestCreateGetRenameDeleteZettel(t *testing.T) { +func TestCreateGetDeleteZettel(t *testing.T) { // Is not to be allowed to run in parallel with other tests. zettel := `title: A Test Example content.` c := getClient() @@ -47,25 +52,19 @@ Example content.` if string(data) != exp { t.Errorf("Expected zettel data: %q, but got %q", exp, data) } - newZid := nextZid(zid) - err = c.RenameZettel(context.Background(), zid, newZid) - if err != nil { - t.Error("Cannot rename", zid, ":", err) - newZid = zid - } - - doDelete(t, c, newZid) + + doDelete(t, c, zid) } -func TestCreateGetRenameDeleteZettelJSON(t *testing.T) { +func TestCreateGetDeleteZettelDataCreator(t *testing.T) { // Is not to be allowed to run in parallel with other tests. c := getClient() c.SetAuth("creator", "creator") - zid, err := c.CreateZettelJSON(context.Background(), &api.ZettelDataJSON{ + zid, err := c.CreateZettelData(context.Background(), api.ZettelData{ Meta: nil, Encoding: "", Content: "Example", }) if err != nil { @@ -74,56 +73,49 @@ } if !zid.IsValid() { t.Error("Invalid zettel ID", zid) return } - newZid := nextZid(zid) - c.SetAuth("owner", "owner") - err = c.RenameZettel(context.Background(), zid, newZid) - if err != nil { - t.Error("Cannot rename", zid, ":", err) - newZid = zid - } c.SetAuth("owner", "owner") - doDelete(t, c, newZid) + doDelete(t, c, zid) } -func TestCreateGetDeleteZettelJSON(t *testing.T) { +func TestCreateGetDeleteZettelData(t *testing.T) { // Is not to be allowed to run in parallel with other tests. c := getClient() c.SetAuth("owner", "owner") wrongModified := "19691231115959" - zid, err := c.CreateZettelJSON(context.Background(), &api.ZettelDataJSON{ + zid, err := c.CreateZettelData(context.Background(), api.ZettelData{ Meta: api.ZettelMeta{ - api.KeyTitle: "A\nTitle", // \n must be converted into a space - api.KeyModified: wrongModified, + meta.KeyTitle: "A\nTitle", // \n must be converted into a space + meta.KeyModified: wrongModified, }, }) if err != nil { t.Error("Cannot create zettel:", err) return } - z, err := c.GetZettelJSON(context.Background(), zid) + z, err := c.GetZettelData(context.Background(), zid) if err != nil { t.Error("Cannot get zettel:", zid, err) } else { exp := "A Title" - if got := z.Meta[api.KeyTitle]; got != exp { + if got := z.Meta[meta.KeyTitle]; got != exp { t.Errorf("Expected title %q, but got %q", exp, got) } - if got := z.Meta[api.KeyModified]; got != "" { + if got := z.Meta[meta.KeyModified]; got != "" { t.Errorf("Create allowed to set the modified key: %q", got) } } doDelete(t, c, zid) } func TestUpdateZettel(t *testing.T) { c := getClient() c.SetAuth("owner", "owner") - z, err := c.GetZettel(context.Background(), api.ZidDefaultHome, api.PartZettel) + z, err := c.GetZettel(context.Background(), id.ZidDefaultHome, api.PartZettel) if err != nil { t.Error(err) return } if !strings.HasPrefix(string(z), "title: Home\n") { @@ -133,67 +125,67 @@ newZettel := `title: Empty Home role: zettel syntax: zmk Empty` - err = c.UpdateZettel(context.Background(), api.ZidDefaultHome, []byte(newZettel)) + err = c.UpdateZettel(context.Background(), id.ZidDefaultHome, []byte(newZettel)) if err != nil { t.Error(err) return } - zt, err := c.GetZettel(context.Background(), api.ZidDefaultHome, api.PartZettel) + zt, err := c.GetZettel(context.Background(), id.ZidDefaultHome, api.PartZettel) if err != nil { t.Error(err) return } if string(zt) != newZettel { t.Errorf("Expected zettel %q, got %q", newZettel, zt) } // Must delete to clean up for next tests - doDelete(t, c, api.ZidDefaultHome) + doDelete(t, c, id.ZidDefaultHome) } -func TestUpdateZettelJSON(t *testing.T) { +func TestUpdateZettelData(t *testing.T) { c := getClient() c.SetAuth("writer", "writer") - z, err := c.GetZettelJSON(context.Background(), api.ZidDefaultHome) + z, err := c.GetZettelData(context.Background(), id.ZidDefaultHome) if err != nil { t.Error(err) return } - if got := z.Meta[api.KeyTitle]; got != "Home" { + if got := z.Meta[meta.KeyTitle]; got != "Home" { t.Errorf("Title of zettel is not \"Home\", but %q", got) return } newTitle := "New Home" - z.Meta[api.KeyTitle] = newTitle + z.Meta[meta.KeyTitle] = newTitle wrongModified := "19691231235959" - z.Meta[api.KeyModified] = wrongModified - err = c.UpdateZettelJSON(context.Background(), api.ZidDefaultHome, z) + z.Meta[meta.KeyModified] = wrongModified + err = c.UpdateZettelData(context.Background(), id.ZidDefaultHome, z) if err != nil { t.Error(err) return } - zt, err := c.GetZettelJSON(context.Background(), api.ZidDefaultHome) + zt, err := c.GetZettelData(context.Background(), id.ZidDefaultHome) if err != nil { t.Error(err) return } - if got := zt.Meta[api.KeyTitle]; got != newTitle { + if got := zt.Meta[meta.KeyTitle]; got != newTitle { t.Errorf("Title of zettel is not %q, but %q", newTitle, got) } - if got := zt.Meta[api.KeyModified]; got == wrongModified { + if got := zt.Meta[meta.KeyModified]; got == wrongModified { t.Errorf("Update did not change the modified key: %q", got) } // Must delete to clean up for next tests c.SetAuth("owner", "owner") - doDelete(t, c, api.ZidDefaultHome) + doDelete(t, c, id.ZidDefaultHome) } -func doDelete(t *testing.T, c *client.Client, zid api.ZettelID) { +func doDelete(t *testing.T, c *client.Client, zid id.Zid) { err := c.DeleteZettel(context.Background(), zid) if err != nil { t.Helper() t.Error("Cannot delete", zid, ":", err) } } Index: tests/client/embed_test.go ================================================================== --- tests/client/embed_test.go +++ tests/client/embed_test.go @@ -1,41 +1,45 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern +// Copyright (c) 2021-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2021-present Detlef Stern //----------------------------------------------------------------------------- package client_test import ( "context" "strings" "testing" - "zettelstore.de/c/api" + "t73f.de/r/zsc/api" + "t73f.de/r/zsc/domain/id" ) const ( - abcZid = api.ZettelID("20211020121000") - abc10Zid = api.ZettelID("20211020121100") + abcZid = id.Zid(20211020121000) + abc10Zid = id.Zid(20211020121100) ) func TestZettelTransclusion(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") - const abc10000Zid = api.ZettelID("20211020121400") - contentMap := map[api.ZettelID]int{ - abcZid: 1, - abc10Zid: 10, - api.ZettelID("20211020121145"): 100, - api.ZettelID("20211020121300"): 1000, + const abc10000Zid = id.Zid(20211020121400) + contentMap := map[id.Zid]int{ + abcZid: 1, + abc10Zid: 10, + id.Zid(20211020121145): 100, + id.Zid(20211020121300): 1000, } content, err := c.GetZettel(context.Background(), abcZid, api.PartContent) if err != nil { t.Error(err) return @@ -67,19 +71,19 @@ content, err = c.GetEvaluatedZettel(context.Background(), abc10000Zid, api.EncoderHTML) if err != nil { t.Error(err) return } - checkContentContains(t, abc10000Zid, string(content), "Too\u00a0many\u00a0transclusions") + checkContentContains(t, abc10000Zid, string(content), "Too many transclusions") } func TestZettelTransclusionNoPrivilegeEscalation(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("reader", "reader") - zettelData, err := c.GetZettelJSON(context.Background(), api.ZidEmoji) + zettelData, err := c.GetZettelData(context.Background(), id.ZidEmoji) if err != nil { t.Error(err) return } expectedEnc := "base64" @@ -90,11 +94,13 @@ content, err := c.GetEvaluatedZettel(context.Background(), abc10Zid, api.EncoderHTML) if err != nil { t.Error(err) return } - checkContentContains(t, abc10Zid, string(content), "Error placeholder") + if exp, got := "", string(content); exp != got { + t.Errorf("Zettel %q must contain %q, but got %q", abc10Zid, exp, got) + } } func stringHead(s string) string { const maxLen = 40 if len(s) <= maxLen { @@ -115,15 +121,15 @@ t.Parallel() c := getClient() c.SetAuth("owner", "owner") const ( - selfRecursiveZid = api.ZettelID("20211020182600") - indirectRecursive1Zid = api.ZettelID("20211020183700") - indirectRecursive2Zid = api.ZettelID("20211020183800") + selfRecursiveZid = id.Zid(20211020182600) + indirectRecursive1Zid = id.Zid(20211020183700) + indirectRecursive2Zid = id.Zid(20211020183800) ) - recursiveZettel := map[api.ZettelID]api.ZettelID{ + recursiveZettel := map[id.Zid]id.Zid{ selfRecursiveZid: selfRecursiveZid, indirectRecursive1Zid: indirectRecursive2Zid, indirectRecursive2Zid: indirectRecursive1Zid, } for zid, errZid := range recursiveZettel { @@ -131,48 +137,48 @@ if err != nil { t.Error(err) continue } sContent := string(content) - checkContentContains(t, zid, sContent, "Recursive\u00a0transclusion") - checkContentContains(t, zid, sContent, string(errZid)) + checkContentContains(t, zid, sContent, "Recursive transclusion") + checkContentContains(t, zid, sContent, errZid.String()) } } func TestNothingToTransclude(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") const ( - transZid = api.ZettelID("20211020184342") - emptyZid = api.ZettelID("20211020184300") + transZid = id.Zid(20211020184342) + emptyZid = id.Zid(20211020184300) ) content, err := c.GetEvaluatedZettel(context.Background(), transZid, api.EncoderHTML) if err != nil { t.Error(err) return } sContent := string(content) checkContentContains(t, transZid, sContent, "<!-- Nothing to transclude") - checkContentContains(t, transZid, sContent, string(emptyZid)) + checkContentContains(t, transZid, sContent, emptyZid.String()) } func TestSelfEmbedRef(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") - const selfEmbedZid = api.ZettelID("20211020185400") + const selfEmbedZid = id.Zid(20211020185400) content, err := c.GetEvaluatedZettel(context.Background(), selfEmbedZid, api.EncoderHTML) if err != nil { t.Error(err) return } - checkContentContains(t, selfEmbedZid, string(content), "Self\u00a0embed\u00a0reference") + checkContentContains(t, selfEmbedZid, string(content), "Self embed reference") } -func checkContentContains(t *testing.T, zid api.ZettelID, content, expected string) { +func checkContentContains(t *testing.T, zid id.Zid, content, expected string) { if !strings.Contains(content, expected) { t.Helper() t.Errorf("Zettel %q should contain %q, but does not: %q", zid, expected, content) } } Index: tests/markdown_test.go ================================================================== --- tests/markdown_test.go +++ tests/markdown_test.go @@ -1,37 +1,36 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern +// Copyright (c) 2020-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- -// Package tests provides some higher-level tests. package tests import ( "bytes" "encoding/json" "fmt" "os" + "strings" "testing" - "zettelstore.de/c/api" - "zettelstore.de/z/ast" - "zettelstore.de/z/encoder" - _ "zettelstore.de/z/encoder/htmlenc" - _ "zettelstore.de/z/encoder/sexprenc" - _ "zettelstore.de/z/encoder/textenc" - _ "zettelstore.de/z/encoder/zjsonenc" - _ "zettelstore.de/z/encoder/zmkenc" - "zettelstore.de/z/input" - "zettelstore.de/z/parser" - _ "zettelstore.de/z/parser/markdown" - _ "zettelstore.de/z/parser/zettelmark" + "t73f.de/r/zsc/api" + "t73f.de/r/zsc/domain/meta" + "t73f.de/r/zsx/input" + + "zettelstore.de/z/internal/ast" + "zettelstore.de/z/internal/config" + "zettelstore.de/z/internal/encoder" + "zettelstore.de/z/internal/parser" ) type markdownTestCase struct { Markdown string `json:"markdown"` HTML string `json:"html"` @@ -43,11 +42,11 @@ func TestEncoderAvailability(t *testing.T) { t.Parallel() encoderMissing := false for _, enc := range encodings { - enc := encoder.Create(enc) + enc := encoder.Create(enc, &encoder.CreateParameter{Lang: meta.ValueLangEN}) if enc == nil { t.Errorf("No encoder for %q found", enc) encoderMissing = true } } @@ -66,52 +65,76 @@ if err = json.Unmarshal(content, &testcases); err != nil { panic(err) } for _, tc := range testcases { - ast := parser.ParseBlocks(input.NewInput([]byte(tc.Markdown)), nil, "markdown") + ast := createMDBlockSlice(tc.Markdown, config.NoHTML) testAllEncodings(t, tc, &ast) testZmkEncoding(t, tc, &ast) } } + +func createMDBlockSlice(markdown string, hi config.HTMLInsecurity) ast.BlockSlice { + return parser.Parse(input.NewInput([]byte(markdown)), nil, meta.ValueSyntaxMarkdown, hi) +} func testAllEncodings(t *testing.T, tc markdownTestCase, ast *ast.BlockSlice) { - var buf bytes.Buffer + var sb strings.Builder testID := tc.Example*100 + 1 for _, enc := range encodings { - t.Run(fmt.Sprintf("Encode %v %v", enc, testID), func(st *testing.T) { - encoder.Create(enc).WriteBlocks(&buf, ast) - buf.Reset() + t.Run(fmt.Sprintf("Encode %v %v", enc, testID), func(*testing.T) { + _, _ = encoder.Create(enc, &encoder.CreateParameter{Lang: meta.ValueLangEN}).WriteBlocks(&sb, ast) + sb.Reset() }) } } func testZmkEncoding(t *testing.T, tc markdownTestCase, ast *ast.BlockSlice) { - zmkEncoder := encoder.Create(api.EncoderZmk) + zmkEncoder := encoder.Create(api.EncoderZmk, nil) var buf bytes.Buffer testID := tc.Example*100 + 1 t.Run(fmt.Sprintf("Encode zmk %14d", testID), func(st *testing.T) { buf.Reset() - zmkEncoder.WriteBlocks(&buf, ast) + _, _ = zmkEncoder.WriteBlocks(&buf, ast) // gotFirst := buf.String() testID = tc.Example*100 + 2 - secondAst := parser.ParseBlocks(input.NewInput(buf.Bytes()), nil, api.ValueSyntaxZmk) + secondAst := parser.Parse(input.NewInput(buf.Bytes()), nil, meta.ValueSyntaxZmk, config.NoHTML) buf.Reset() - zmkEncoder.WriteBlocks(&buf, &secondAst) + _, _ = zmkEncoder.WriteBlocks(&buf, &secondAst) gotSecond := buf.String() // if gotFirst != gotSecond { // st.Errorf("\nCMD: %q\n1st: %q\n2nd: %q", tc.Markdown, gotFirst, gotSecond) // } testID = tc.Example*100 + 3 - thirdAst := parser.ParseBlocks(input.NewInput(buf.Bytes()), nil, api.ValueSyntaxZmk) + thirdAst := parser.Parse(input.NewInput(buf.Bytes()), nil, meta.ValueSyntaxZmk, config.NoHTML) buf.Reset() - zmkEncoder.WriteBlocks(&buf, &thirdAst) + _, _ = zmkEncoder.WriteBlocks(&buf, &thirdAst) gotThird := buf.String() if gotSecond != gotThird { st.Errorf("\n1st: %q\n2nd: %q", gotSecond, gotThird) } }) } + +func TestAdditionalMarkdown(t *testing.T) { + testcases := []struct { + md string + exp string + }{ + {`abc<br>def`, "abc``<br>``{=\"html\"}def"}, + } + zmkEncoder := encoder.Create(api.EncoderZmk, nil) + var sb strings.Builder + for i, tc := range testcases { + ast := createMDBlockSlice(tc.md, config.MarkdownHTML) + sb.Reset() + _, _ = zmkEncoder.WriteBlocks(&sb, &ast) + got := sb.String() + if got != tc.exp { + t.Errorf("%d: %q -> %q, but got %q", i, tc.md, tc.exp, got) + } + } +} ADDED tests/naughtystrings_test.go Index: tests/naughtystrings_test.go ================================================================== --- /dev/null +++ tests/naughtystrings_test.go @@ -0,0 +1,97 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2020-present Detlef Stern +// +// This file is part of Zettelstore. +// +// Zettelstore is licensed under the latest version of the EUPL (European Union +// Public License). Please see file LICENSE.txt for your rights and obligations +// under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern +//----------------------------------------------------------------------------- + +package tests + +import ( + "bufio" + "io" + "os" + "path/filepath" + "testing" + + "t73f.de/r/zsc/domain/meta" + "t73f.de/r/zsx/input" + + "zettelstore.de/z/internal/config" + "zettelstore.de/z/internal/encoder" + "zettelstore.de/z/internal/parser" + + _ "zettelstore.de/z/cmd" +) + +// Test all parser / encoder with a list of "naughty strings", i.e. unusual strings +// that often crash software. + +func getNaughtyStrings() (result []string, err error) { + fpath := filepath.Join("..", "testdata", "naughty", "blns.txt") + file, err := os.Open(fpath) + if err != nil { + return nil, err + } + defer func() { _ = file.Close() }() + scanner := bufio.NewScanner(file) + for scanner.Scan() { + if text := scanner.Text(); text != "" && text[0] != '#' { + result = append(result, text) + } + } + return result, scanner.Err() +} + +func getAllParser() (result []*parser.Info) { + for _, pname := range parser.GetSyntaxes() { + pinfo := parser.Get(pname) + if pname == pinfo.Name { + result = append(result, pinfo) + } + } + return result +} + +func getAllEncoder() (result []encoder.Encoder) { + for _, enc := range encoder.GetEncodings() { + e := encoder.Create(enc, &encoder.CreateParameter{Lang: meta.ValueLangEN}) + result = append(result, e) + } + return result +} + +func TestNaughtyStringParser(t *testing.T) { + blns, err := getNaughtyStrings() + if err != nil { + t.Fatal(err) + } + if len(blns) == 0 { + t.Fatal("no naughty strings found") + } + pinfos := getAllParser() + if len(pinfos) == 0 { + t.Fatal("no parser found") + } + encs := getAllEncoder() + if len(encs) == 0 { + t.Fatal("no encoder found") + } + for _, s := range blns { + for _, pinfo := range pinfos { + bs := parser.Parse(input.NewInput([]byte(s)), &meta.Meta{}, pinfo.Name, config.NoHTML) + for _, enc := range encs { + _, err = enc.WriteBlocks(io.Discard, &bs) + if err != nil { + t.Error(err) + } + } + } + } +} Index: tests/regression_test.go ================================================================== --- tests/regression_test.go +++ tests/regression_test.go @@ -1,46 +1,50 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern +// Copyright (c) 2020-present Detlef Stern // // This file is part of Zettelstore. // // Zettelstore is licensed under the latest version of the EUPL (European Union // Public License). Please see file LICENSE.txt for your rights and obligations // under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- // Package tests provides some higher-level tests. package tests import ( - "bytes" "context" "fmt" "io" "net/url" "os" "path/filepath" + "strings" "testing" - "zettelstore.de/c/api" - "zettelstore.de/z/ast" - "zettelstore.de/z/box" - "zettelstore.de/z/box/manager" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/encoder" - "zettelstore.de/z/kernel" - "zettelstore.de/z/parser" - - _ "zettelstore.de/z/box/dirbox" + "t73f.de/r/zsc/api" + "t73f.de/r/zsc/domain/meta" + + "zettelstore.de/z/internal/ast" + "zettelstore.de/z/internal/box" + "zettelstore.de/z/internal/box/manager" + "zettelstore.de/z/internal/config" + "zettelstore.de/z/internal/encoder" + "zettelstore.de/z/internal/kernel" + "zettelstore.de/z/internal/parser" + "zettelstore.de/z/internal/query" + + _ "zettelstore.de/z/internal/box/dirbox" ) var encodings = []api.EncodingEnum{ api.EncoderHTML, - api.EncoderSexpr, + api.EncoderSz, api.EncoderText, - api.EncoderZJSON, } func getFileBoxes(wd, kind string) (root string, boxes []box.ManagedBox) { root = filepath.Clean(filepath.Join(wd, "..", "testdata", kind)) entries, err := os.ReadDir(root) @@ -89,12 +93,15 @@ func resultFile(file string) (data string, err error) { f, err := os.Open(file) if err != nil { return "", err } - defer f.Close() src, err := io.ReadAll(f) + err2 := f.Close() + if err == nil { + err = err2 + } return string(src), err } func checkFileContent(t *testing.T, filename, gotContent string) { t.Helper() @@ -119,14 +126,14 @@ } func checkMetaFile(t *testing.T, resultName string, zn *ast.ZettelNode, enc api.EncodingEnum) { t.Helper() - if enc := encoder.Create(enc); enc != nil { - var buf bytes.Buffer - enc.WriteMeta(&buf, zn.Meta, parser.ParseMetadata) - checkFileContent(t, resultName, buf.String()) + if enc := encoder.Create(enc, &encoder.CreateParameter{Lang: meta.ValueLangEN}); enc != nil { + var sf strings.Builder + _, _ = enc.WriteMeta(&sf, zn.Meta) + checkFileContent(t, resultName, sf.String()) return } panic(fmt.Sprintf("Unknown writer encoding %q", enc)) } @@ -134,20 +141,21 @@ ss := p.(box.StartStopper) if err := ss.Start(context.Background()); err != nil { panic(err) } metaList := []*meta.Meta{} - err := p.ApplyMeta(context.Background(), func(m *meta.Meta) { metaList = append(metaList, m) }, nil) - if err != nil { + if err := p.ApplyMeta(context.Background(), + func(m *meta.Meta) { metaList = append(metaList, m) }, + query.AlwaysIncluded); err != nil { panic(err) } for _, meta := range metaList { - zettel, err2 := p.GetZettel(context.Background(), meta.Zid) - if err2 != nil { - panic(err2) + zettel, err := p.GetZettel(context.Background(), meta.Zid) + if err != nil { + panic(err) } - z := parser.ParseZettel(zettel, "", testConfig) + z := parser.ParseZettel(context.Background(), zettel, "", testConfig) for _, enc := range encodings { t.Run(fmt.Sprintf("%s::%d(%s)", p.Location(), meta.Zid, enc), func(st *testing.T) { resultName := filepath.Join(wd, "result", "meta", boxName, z.Zid.String()+"."+enc.String()) checkMetaFile(st, resultName, z, enc) }) @@ -156,19 +164,19 @@ ss.Stop(context.Background()) } type myConfig struct{} -func (*myConfig) AddDefaultValues(m *meta.Meta) *meta.Meta { return m } -func (*myConfig) GetDefaultLang() string { return "" } -func (*myConfig) GetFooterHTML() string { return "" } -func (*myConfig) GetHomeZettel() id.Zid { return id.Invalid } +func (*myConfig) Get(context.Context, *meta.Meta, string) string { return "" } +func (*myConfig) AddDefaultValues(_ context.Context, m *meta.Meta) *meta.Meta { + return m +} +func (*myConfig) GetHTMLInsecurity() config.HTMLInsecurity { return config.NoHTML } func (*myConfig) GetListPageSize() int { return 0 } -func (*myConfig) GetMarkerExternal() string { return "" } func (*myConfig) GetSiteName() string { return "" } func (*myConfig) GetYAMLHeader() bool { return false } -func (*myConfig) GetZettelFileSyntax() []string { return nil } +func (*myConfig) GetZettelFileSyntax() []meta.Value { return nil } func (*myConfig) GetSimpleMode() bool { return false } func (*myConfig) GetExpertMode() bool { return false } func (*myConfig) GetVisibility(*meta.Meta) meta.Visibility { return meta.VisibilityPublic } func (*myConfig) GetMaxTransclusions() int { return 1024 } DELETED tools/build.go Index: tools/build.go ================================================================== --- tools/build.go +++ /dev/null @@ -1,560 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package main provides a command to build and run the software. -package main - -import ( - "archive/zip" - "bytes" - "errors" - "flag" - "fmt" - "io" - "io/fs" - "net" - "os" - "os/exec" - "path/filepath" - "strings" - "time" - - "zettelstore.de/z/strfun" -) - -var directProxy = []string{"GOPROXY=direct"} - -func executeCommand(env []string, name string, arg ...string) (string, error) { - logCommand("EXEC", env, name, arg) - var out bytes.Buffer - cmd := prepareCommand(env, name, arg, &out) - err := cmd.Run() - return out.String(), err -} - -func prepareCommand(env []string, name string, arg []string, out io.Writer) *exec.Cmd { - if len(env) > 0 { - env = append(env, os.Environ()...) - } - cmd := exec.Command(name, arg...) - cmd.Env = env - cmd.Stdin = nil - cmd.Stdout = out - cmd.Stderr = os.Stderr - return cmd -} - -func logCommand(exec string, env []string, name string, arg []string) { - if verbose { - if len(env) > 0 { - for i, e := range env { - fmt.Fprintf(os.Stderr, "ENV%d %v\n", i+1, e) - } - } - fmt.Fprintln(os.Stderr, exec, name, arg) - } -} - -func readVersionFile() (string, error) { - content, err := os.ReadFile("VERSION") - if err != nil { - return "", err - } - return strings.TrimFunc(string(content), func(r rune) bool { - return r <= ' ' - }), nil -} - -func getVersion() string { - base, err := readVersionFile() - if err != nil { - base = "dev" - } - return base -} - -var dirtyPrefixes = []string{ - "DELETED ", "ADDED ", "UPDATED ", "CONFLICT ", "EDITED ", "RENAMED ", "EXTRA "} - -const dirtySuffix = "-dirty" - -func readFossilDirty() (string, error) { - s, err := executeCommand(nil, "fossil", "status", "--differ") - if err != nil { - return "", err - } - for _, line := range strfun.SplitLines(s) { - for _, prefix := range dirtyPrefixes { - if strings.HasPrefix(line, prefix) { - return dirtySuffix, nil - } - } - } - return "", nil -} - -func getFossilDirty() string { - fossil, err := readFossilDirty() - if err != nil { - return "" - } - return fossil -} - -func findExec(cmd string) string { - if path, err := executeCommand(nil, "which", cmd); err == nil && path != "" { - return strings.TrimSpace(path) - } - return "" -} - -func cmdCheck(forRelease bool) error { - if err := checkGoTest("./..."); err != nil { - return err - } - if err := checkGoVet(); err != nil { - return err - } - if err := checkShadow(forRelease); err != nil { - return err - } - if err := checkStaticcheck(); err != nil { - return err - } - if err := checkUnparam(forRelease); err != nil { - return err - } - return checkFossilExtra() -} - -func checkGoTest(pkg string, testParams ...string) error { - args := []string{"test", pkg} - args = append(args, testParams...) - out, err := executeCommand(directProxy, "go", args...) - if err != nil { - for _, line := range strfun.SplitLines(out) { - if strings.HasPrefix(line, "ok") || strings.HasPrefix(line, "?") { - continue - } - fmt.Fprintln(os.Stderr, line) - } - } - return err -} - -func checkGoVet() error { - out, err := executeCommand(nil, "go", "vet", "./...") - if err != nil { - fmt.Fprintln(os.Stderr, "Some checks failed") - if len(out) > 0 { - fmt.Fprintln(os.Stderr, out) - } - } - return err -} - -func checkShadow(forRelease bool) error { - path, err := findExecStrict("shadow", forRelease) - if path == "" { - return err - } - out, err := executeCommand(nil, path, "-strict", "./...") - if err != nil { - fmt.Fprintln(os.Stderr, "Some shadowed variables found") - if len(out) > 0 { - fmt.Fprintln(os.Stderr, out) - } - } - return err -} - -func checkStaticcheck() error { - out, err := executeCommand(nil, "staticcheck", "./...") - if err != nil { - fmt.Fprintln(os.Stderr, "Some staticcheck problems found") - if len(out) > 0 { - fmt.Fprintln(os.Stderr, out) - } - } - return err -} - -func checkUnparam(forRelease bool) error { - path, err := findExecStrict("unparam", forRelease) - if path == "" { - return err - } - // out, err := executeCommand(nil, path, "./...") - // if err != nil { - // fmt.Fprintln(os.Stderr, "Some unparam problems found") - // if len(out) > 0 { - // fmt.Fprintln(os.Stderr, out) - // } - // } - // if forRelease { - // if out2, err2 := executeCommand(nil, path, "-exported", "-tests", "./..."); err2 != nil { - // fmt.Fprintln(os.Stderr, "Some optional unparam problems found") - // if len(out2) > 0 { - // fmt.Fprintln(os.Stderr, out2) - // } - // } - // } - return err -} - -func findExecStrict(cmd string, forRelease bool) (string, error) { - path := findExec(cmd) - if path != "" || !forRelease { - return path, nil - } - return "", errors.New("Command '" + cmd + "' not installed, but required for release") -} - -func checkFossilExtra() error { - out, err := executeCommand(nil, "fossil", "extra") - if err != nil { - fmt.Fprintln(os.Stderr, "Unable to execute 'fossil extra'") - return err - } - if len(out) > 0 { - fmt.Fprint(os.Stderr, "Warning: unversioned file(s):") - for i, extra := range strfun.SplitLines(out) { - if i > 0 { - fmt.Fprint(os.Stderr, ",") - } - fmt.Fprintf(os.Stderr, " %q", extra) - } - fmt.Fprintln(os.Stderr) - } - return nil -} - -type zsInfo struct { - cmd *exec.Cmd - out bytes.Buffer - adminAddress string -} - -func cmdTestAPI() error { - var err error - var info zsInfo - needServer := !addressInUse(":23123") - if needServer { - err = startZettelstore(&info) - } - if err != nil { - return err - } - err = checkGoTest("zettelstore.de/z/tests/client", "-base-url", "http://127.0.0.1:23123") - if needServer { - err1 := stopZettelstore(&info) - if err == nil { - err = err1 - } - } - return err -} - -func startZettelstore(info *zsInfo) error { - info.adminAddress = ":2323" - name, arg := "go", []string{ - "run", "cmd/zettelstore/main.go", "run", - "-c", "./testdata/testbox/19700101000000.zettel", "-a", info.adminAddress[1:]} - logCommand("FORK", nil, name, arg) - cmd := prepareCommand(nil, name, arg, &info.out) - if !verbose { - cmd.Stderr = nil - } - err := cmd.Start() - for i := 0; i < 100; i++ { - time.Sleep(time.Millisecond * 100) - if addressInUse(info.adminAddress) { - info.cmd = cmd - return err - } - } - return errors.New("zettelstore did not start") -} - -func stopZettelstore(i *zsInfo) error { - conn, err := net.Dial("tcp", i.adminAddress) - if err != nil { - fmt.Println("Unable to stop Zettelstore") - return err - } - io.WriteString(conn, "shutdown\n") - conn.Close() - err = i.cmd.Wait() - return err -} - -func addressInUse(address string) bool { - conn, err := net.Dial("tcp", address) - if err != nil { - return false - } - conn.Close() - return true -} - -func cmdBuild() error { - return doBuild(directProxy, getVersion(), "bin/zettelstore") -} - -func doBuild(env []string, version, target string) error { - out, err := executeCommand( - env, - "go", "build", - "-tags", "osusergo,netgo", - "-trimpath", - "-ldflags", fmt.Sprintf("-X main.version=%v -w", version), - "-o", target, - "zettelstore.de/z/cmd/zettelstore", - ) - if err != nil { - return err - } - if len(out) > 0 { - fmt.Println(out) - } - return nil -} - -func cmdManual() error { - base := getReleaseVersionData() - return createManualZip(".", base) -} - -func createManualZip(path, base string) error { - manualPath := filepath.Join("docs", "manual") - entries, err := os.ReadDir(manualPath) - if err != nil { - return err - } - zipName := filepath.Join(path, "manual-"+base+".zip") - zipFile, err := os.OpenFile(zipName, os.O_RDWR|os.O_CREATE, 0600) - if err != nil { - return err - } - defer zipFile.Close() - zipWriter := zip.NewWriter(zipFile) - defer zipWriter.Close() - - for _, entry := range entries { - if err = createManualZipEntry(manualPath, entry, zipWriter); err != nil { - return err - } - } - return nil -} - -func createManualZipEntry(path string, entry fs.DirEntry, zipWriter *zip.Writer) error { - info, err := entry.Info() - if err != nil { - return err - } - fh, err := zip.FileInfoHeader(info) - if err != nil { - return err - } - fh.Name = entry.Name() - fh.Method = zip.Deflate - w, err := zipWriter.CreateHeader(fh) - if err != nil { - return err - } - manualFile, err := os.Open(filepath.Join(path, entry.Name())) - if err != nil { - return err - } - defer manualFile.Close() - _, err = io.Copy(w, manualFile) - return err -} - -func getReleaseVersionData() string { - if fossil := getFossilDirty(); fossil != "" { - fmt.Fprintln(os.Stderr, "Warning: releasing a dirty version") - } - base := getVersion() - if strings.HasSuffix(base, "dev") { - return base[:len(base)-3] + "preview-" + time.Now().Format("20060102") - } - return base -} - -func cmdRelease() error { - if err := cmdCheck(true); err != nil { - return err - } - base := getReleaseVersionData() - releases := []struct { - arch string - os string - env []string - name string - }{ - {"amd64", "linux", nil, "zettelstore"}, - {"arm", "linux", []string{"GOARM=6"}, "zettelstore"}, - {"amd64", "darwin", nil, "zettelstore"}, - {"arm64", "darwin", nil, "zettelstore"}, - {"amd64", "windows", nil, "zettelstore.exe"}, - } - for _, rel := range releases { - env := append([]string{}, rel.env...) - env = append(env, "GOARCH="+rel.arch, "GOOS="+rel.os) - env = append(env, directProxy...) - zsName := filepath.Join("releases", rel.name) - if err := doBuild(env, base, zsName); err != nil { - return err - } - zipName := fmt.Sprintf("zettelstore-%v-%v-%v.zip", base, rel.os, rel.arch) - if err := createReleaseZip(zsName, zipName, rel.name); err != nil { - return err - } - if err := os.Remove(zsName); err != nil { - return err - } - } - return createManualZip("releases", base) -} - -func createReleaseZip(zsName, zipName, fileName string) error { - zipFile, err := os.OpenFile(filepath.Join("releases", zipName), os.O_RDWR|os.O_CREATE, 0600) - if err != nil { - return err - } - defer zipFile.Close() - zw := zip.NewWriter(zipFile) - defer zw.Close() - err = addFileToZip(zw, zsName, fileName) - if err != nil { - return err - } - err = addFileToZip(zw, "LICENSE.txt", "LICENSE.txt") - if err != nil { - return err - } - err = addFileToZip(zw, "docs/readmezip.txt", "README.txt") - return err -} - -func addFileToZip(zipFile *zip.Writer, filepath, filename string) error { - zsFile, err := os.Open(filepath) - if err != nil { - return err - } - defer zsFile.Close() - stat, err := zsFile.Stat() - if err != nil { - return err - } - fh, err := zip.FileInfoHeader(stat) - if err != nil { - return err - } - fh.Name = filename - fh.Method = zip.Deflate - w, err := zipFile.CreateHeader(fh) - if err != nil { - return err - } - _, err = io.Copy(w, zsFile) - return err -} - -func cmdClean() error { - for _, dir := range []string{"bin", "releases"} { - err := os.RemoveAll(dir) - if err != nil { - return err - } - } - out, err := executeCommand(nil, "go", "clean", "./...") - if err != nil { - return err - } - if len(out) > 0 { - fmt.Println(out) - } - out, err = executeCommand(nil, "go", "clean", "-cache", "-modcache", "-testcache") - if err != nil { - return err - } - if len(out) > 0 { - fmt.Println(out) - } - return nil -} - -func cmdHelp() { - fmt.Println(`Usage: go run tools/build.go [-v] COMMAND - -Options: - -v Verbose output. - -Commands: - build Build the software for local computer. - check Check current working state: execute tests, - static analysis tools, extra files, ... - Is automatically done when releasing the software. - clean Remove all build and release directories. - help Output this text. - manual Create a ZIP file with all manual zettel - relcheck Check current working state for release. - release Create the software for various platforms and put them in - appropriate named ZIP files. - testapi Start a Zettelstore and execute API tests. - version Print the current version of the software. - -All commands can be abbreviated as long as they remain unique.`) -} - -var ( - verbose bool -) - -func main() { - flag.BoolVar(&verbose, "v", false, "Verbose output") - flag.Parse() - var err error - args := flag.Args() - if len(args) < 1 { - cmdHelp() - } else { - switch args[0] { - case "b", "bu", "bui", "buil", "build": - err = cmdBuild() - case "m", "ma", "man", "manu", "manua", "manual": - err = cmdManual() - case "r", "re", "rel", "rele", "relea", "releas", "release": - err = cmdRelease() - case "cl", "cle", "clea", "clean": - err = cmdClean() - case "v", "ve", "ver", "vers", "versi", "versio", "version": - fmt.Print(getVersion()) - case "ch", "che", "chec", "check": - err = cmdCheck(false) - case "relc", "relch", "relche", "relchec", "relcheck": - err = cmdCheck(true) - case "t", "te", "tes", "test", "testa", "testap", "testapi": - cmdTestAPI() - case "h", "he", "hel", "help": - cmdHelp() - default: - fmt.Fprintf(os.Stderr, "Unknown command %q\n", args[0]) - cmdHelp() - os.Exit(1) - } - } - if err != nil { - fmt.Fprintln(os.Stderr, err) - } -} ADDED tools/build/build.go Index: tools/build/build.go ================================================================== --- /dev/null +++ tools/build/build.go @@ -0,0 +1,326 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2021-present Detlef Stern +// +// This file is part of Zettelstore. +// +// Zettelstore is licensed under the latest version of the EUPL (European Union +// Public License). Please see file LICENSE.txt for your rights and obligations +// under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2021-present Detlef Stern +//----------------------------------------------------------------------------- + +// Package main provides a command to build and run the software. +package main + +import ( + "archive/zip" + "bytes" + "flag" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "slices" + "strings" + "time" + + "t73f.de/r/zsc/domain/id" + "t73f.de/r/zsc/domain/meta" + "t73f.de/r/zsx/input" + "zettelstore.de/z/strfun" + "zettelstore.de/z/tools" +) + +func readVersionFile() (string, error) { + content, err := os.ReadFile("VERSION") + if err != nil { + return "", err + } + return strings.TrimFunc(string(content), func(r rune) bool { + return r <= ' ' + }), nil +} + +func getVersion() string { + base, err := readVersionFile() + if err != nil { + base = "dev" + } + return base +} + +var dirtyPrefixes = []string{ + "DELETED ", "ADDED ", "UPDATED ", "CONFLICT ", "EDITED ", "RENAMED ", "EXTRA "} + +const dirtySuffix = "-dirty" + +func readFossilDirty() (string, error) { + s, err := tools.ExecuteCommand(nil, "fossil", "status", "--differ") + if err != nil { + return "", err + } + for _, line := range strfun.SplitLines(s) { + for _, prefix := range dirtyPrefixes { + if strings.HasPrefix(line, prefix) { + return dirtySuffix, nil + } + } + } + return "", nil +} + +func getFossilDirty() string { + fossil, err := readFossilDirty() + if err != nil { + return "" + } + return fossil +} + +func cmdBuild() error { + return doBuild(tools.EnvDirectProxy, getVersion(), "bin/zettelstore") +} + +func doBuild(env []string, version, target string) error { + env = append(env, "CGO_ENABLED=0") + env = append(env, tools.EnvGoVCS...) + out, err := tools.ExecuteCommand( + env, + "go", "build", + "-tags", "osusergo,netgo", + "-trimpath", + "-ldflags", fmt.Sprintf("-X main.version=%v -w", version), + "-o", target, + "zettelstore.de/z/cmd/zettelstore", + ) + if err != nil { + return err + } + if len(out) > 0 { + fmt.Println(out) + } + return nil +} + +func cmdHelp() { + fmt.Println(`Usage: go run tools/build/build.go [-v] COMMAND + +Options: + -v Verbose output. + +Commands: + build Build the software for local computer. + help Output this text. + manual Create a ZIP file with all manual zettel + release Create the software for various platforms and put them in + appropriate named ZIP files. + version Print the current version of the software. + +All commands can be abbreviated as long as they remain unique.`) +} + +func main() { + flag.BoolVar(&tools.Verbose, "v", false, "Verbose output") + flag.Parse() + var err error + args := flag.Args() + if len(args) < 1 { + cmdHelp() + } else { + switch args[0] { + case "b", "bu", "bui", "buil", "build": + err = cmdBuild() + case "m", "ma", "man", "manu", "manua", "manual": + err = cmdManual() + case "r", "re", "rel", "rele", "relea", "releas", "release": + err = cmdRelease() + case "v", "ve", "ver", "vers", "versi", "versio", "version": + fmt.Print(getVersion()) + case "h", "he", "hel", "help": + cmdHelp() + default: + fmt.Fprintf(os.Stderr, "Unknown command %q\n", args[0]) + cmdHelp() + os.Exit(1) + } + } + if err != nil { + fmt.Fprintln(os.Stderr, err) + } +} + +// --- manual + +func cmdManual() error { + base := getReleaseVersionData() + return createManualZip(".", base) +} + +func createManualZip(path, base string) error { + manualPath := filepath.Join("docs", "manual") + entries, err := os.ReadDir(manualPath) + if err != nil { + return err + } + zipName := filepath.Join(path, "manual-"+base+".zip") + zipFile, err := os.OpenFile(zipName, os.O_RDWR|os.O_CREATE, 0600) + if err != nil { + return err + } + defer func() { _ = zipFile.Close() }() + zipWriter := zip.NewWriter(zipFile) + defer func() { _ = zipWriter.Close() }() + + for _, entry := range entries { + if err = createManualZipEntry(manualPath, entry, zipWriter); err != nil { + return err + } + } + return nil +} + +const versionZid = "00001000000001" + +func createManualZipEntry(path string, entry fs.DirEntry, zipWriter *zip.Writer) error { + info, err := entry.Info() + if err != nil { + return err + } + fh, err := zip.FileInfoHeader(info) + if err != nil { + return err + } + name := entry.Name() + fh.Name = name + fh.Method = zip.Deflate + w, err := zipWriter.CreateHeader(fh) + if err != nil { + return err + } + manualFile, err := os.Open(filepath.Join(path, name)) + if err != nil { + return err + } + defer func() { _ = manualFile.Close() }() + + if name != versionZid+".zettel" { + _, err = io.Copy(w, manualFile) + return err + } + + data, err := io.ReadAll(manualFile) + if err != nil { + return err + } + inp := input.NewInput(data) + m := meta.NewFromInput(id.MustParse(versionZid), inp) + m.SetNow(meta.KeyModified) + + var buf bytes.Buffer + if _, err = fmt.Fprintf(&buf, "id: %s\n", versionZid); err != nil { + return err + } + if _, err = m.WriteComputed(&buf); err != nil { + return err + } + if _, err = fmt.Fprintf(&buf, "\n%s", getVersion()); err != nil { + return err + } + _, err = io.Copy(w, &buf) + return err +} + +//--- release + +func cmdRelease() error { + if err := tools.Check(true); err != nil { + return err + } + base := getReleaseVersionData() + releases := []struct { + arch string + os string + env []string + name string + }{ + {"amd64", "linux", nil, "zettelstore"}, + {"arm", "linux", []string{"GOARM=6"}, "zettelstore"}, + {"arm64", "darwin", nil, "zettelstore"}, + {"amd64", "darwin", nil, "zettelstore"}, + {"amd64", "windows", nil, "zettelstore.exe"}, + {"arm64", "android", nil, "zettelstore"}, + } + for _, rel := range releases { + env := slices.Clone(rel.env) + env = append(env, "GOARCH="+rel.arch, "GOOS="+rel.os) + env = append(env, tools.EnvDirectProxy...) + env = append(env, tools.EnvGoVCS...) + zsName := filepath.Join("releases", rel.name) + if err := doBuild(env, base, zsName); err != nil { + return err + } + zipName := fmt.Sprintf("zettelstore-%v-%v-%v.zip", base, rel.os, rel.arch) + if err := createReleaseZip(zsName, zipName, rel.name); err != nil { + return err + } + if err := os.Remove(zsName); err != nil { + return err + } + } + return createManualZip("releases", base) +} + +func getReleaseVersionData() string { + if fossil := getFossilDirty(); fossil != "" { + fmt.Fprintln(os.Stderr, "Warning: releasing a dirty version") + } + base := getVersion() + if strings.HasSuffix(base, "dev") { + return base[:len(base)-3] + "preview-" + time.Now().Local().Format("20060102") + } + return base +} + +func createReleaseZip(zsName, zipName, fileName string) error { + zipFile, err := os.OpenFile(filepath.Join("releases", zipName), os.O_RDWR|os.O_CREATE, 0600) + if err != nil { + return err + } + defer func() { _ = zipFile.Close() }() + zw := zip.NewWriter(zipFile) + defer func() { _ = zw.Close() }() + if err = addFileToZip(zw, zsName, fileName); err != nil { + return err + } + if err = addFileToZip(zw, "LICENSE.txt", "LICENSE.txt"); err != nil { + return err + } + return addFileToZip(zw, "docs/readmezip.txt", "README.txt") +} + +func addFileToZip(zipFile *zip.Writer, filepath, filename string) error { + zsFile, err := os.Open(filepath) + if err != nil { + return err + } + defer func() { _ = zsFile.Close() }() + stat, err := zsFile.Stat() + if err != nil { + return err + } + fh, err := zip.FileInfoHeader(stat) + if err != nil { + return err + } + fh.Name = filename + fh.Method = zip.Deflate + w, err := zipFile.CreateHeader(fh) + if err != nil { + return err + } + _, err = io.Copy(w, zsFile) + return err +} ADDED tools/check/check.go Index: tools/check/check.go ================================================================== --- /dev/null +++ tools/check/check.go @@ -0,0 +1,35 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2023-present Detlef Stern +// +// This file is part of Zettelstore. +// +// Zettelstore is licensed under the latest version of the EUPL (European Union +// Public License). Please see file LICENSE.txt for your rights and obligations +// under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2023-present Detlef Stern +//----------------------------------------------------------------------------- + +// Package main provides a command to execute unit tests. +package main + +import ( + "flag" + "fmt" + "os" + + "zettelstore.de/z/tools" +) + +var release bool + +func main() { + flag.BoolVar(&release, "r", false, "Release check") + flag.BoolVar(&tools.Verbose, "v", false, "Verbose output") + flag.Parse() + + if err := tools.Check(release); err != nil { + fmt.Fprintln(os.Stderr, err) + } +} ADDED tools/clean/clean.go Index: tools/clean/clean.go ================================================================== --- /dev/null +++ tools/clean/clean.go @@ -0,0 +1,56 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2023-present Detlef Stern +// +// This file is part of Zettelstore. +// +// Zettelstore is licensed under the latest version of the EUPL (European Union +// Public License). Please see file LICENSE.txt for your rights and obligations +// under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2023-present Detlef Stern +//----------------------------------------------------------------------------- + +// Package main provides a command to clean / remove development artifacts. +package main + +import ( + "flag" + "fmt" + "os" + + "zettelstore.de/z/tools" +) + +func main() { + flag.BoolVar(&tools.Verbose, "v", false, "Verbose output") + flag.Parse() + + if err := cmdClean(); err != nil { + fmt.Fprintln(os.Stderr, err) + } +} + +func cmdClean() error { + for _, dir := range []string{"bin", "releases"} { + err := os.RemoveAll(dir) + if err != nil { + return err + } + } + out, err := tools.ExecuteCommand(nil, "go", "clean", "./...") + if err != nil { + return err + } + if len(out) > 0 { + fmt.Println(out) + } + out, err = tools.ExecuteCommand(nil, "go", "clean", "-cache", "-modcache", "-testcache") + if err != nil { + return err + } + if len(out) > 0 { + fmt.Println(out) + } + return nil +} ADDED tools/devtools/devtools.go Index: tools/devtools/devtools.go ================================================================== --- /dev/null +++ tools/devtools/devtools.go @@ -0,0 +1,61 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2023-present Detlef Stern +// +// This file is part of Zettelstore. +// +// Zettelstore is licensed under the latest version of the EUPL (European Union +// Public License). Please see file LICENSE.txt for your rights and obligations +// under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2023-present Detlef Stern +//----------------------------------------------------------------------------- + +// Package main provides a command to install development tools. +package main + +import ( + "flag" + "fmt" + "os" + + "zettelstore.de/z/tools" +) + +func main() { + flag.BoolVar(&tools.Verbose, "v", false, "Verbose output") + flag.Parse() + + if err := cmdTools(); err != nil { + fmt.Fprintln(os.Stderr, err) + } +} + +func cmdTools() error { + tools := []struct{ name, pack string }{ + {"shadow", "golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest"}, + {"unparam", "mvdan.cc/unparam@latest"}, + {"staticcheck", "honnef.co/go/tools/cmd/staticcheck@latest"}, + {"govulncheck", "golang.org/x/vuln/cmd/govulncheck@latest"}, + {"deadcode", "golang.org/x/tools/cmd/deadcode@latest"}, + {"errcheck", "github.com/kisielk/errcheck@latest"}, + {"revive", "github.com/mgechev/revive@latest"}, + } + for _, tool := range tools { + err := doGoInstall(tool.pack) + if err != nil { + return err + } + } + return nil +} +func doGoInstall(pack string) error { + out, err := tools.ExecuteCommand(nil, "go", "install", pack) + if err != nil { + fmt.Fprintln(os.Stderr, "Unable to install package", pack) + if len(out) > 0 { + fmt.Fprintln(os.Stderr, out) + } + } + return err +} ADDED tools/htmllint/htmllint.go Index: tools/htmllint/htmllint.go ================================================================== --- /dev/null +++ tools/htmllint/htmllint.go @@ -0,0 +1,206 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2023-present Detlef Stern +// +// This file is part of Zettelstore. +// +// Zettelstore is licensed under the latest version of the EUPL (European Union +// Public License). Please see file LICENSE.txt for your rights and obligations +// under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2023-present Detlef Stern +//----------------------------------------------------------------------------- + +// Package main provides a tool to check the validity of HTML zettel documents. +package main + +import ( + "context" + "flag" + "fmt" + "log" + "math/rand/v2" + "net/url" + "os" + "regexp" + "slices" + "strings" + + "t73f.de/r/zsc/api" + "t73f.de/r/zsc/client" + "t73f.de/r/zsc/domain/id" + "zettelstore.de/z/tools" +) + +func main() { + flag.BoolVar(&tools.Verbose, "v", false, "Verbose output") + flag.Parse() + + if err := cmdValidateHTML(flag.Args()); err != nil { + fmt.Fprintln(os.Stderr, err) + } +} +func cmdValidateHTML(args []string) error { + rawURL := "http://localhost:23123" + if len(args) > 0 { + rawURL = args[0] + } + u, err := url.Parse(rawURL) + if err != nil { + return err + } + client := client.NewClient(u) + _, _, metaList, err := client.QueryZettelData(context.Background(), "") + if err != nil { + return err + } + zids, perm := calculateZids(metaList) + for _, kd := range keyDescr { + msgCount := 0 + fmt.Fprintf(os.Stderr, "Now checking: %s\n", kd.text) + for _, zid := range zidsToUse(zids, perm, kd.sampleSize) { + var nmsgs int + nmsgs, err = validateHTML(client, kd.uc, zid) + if err != nil { + fmt.Fprintf(os.Stderr, "* error while validating zettel %v with: %v\n", zid, err) + msgCount++ + } else { + msgCount += nmsgs + } + } + if msgCount == 1 { + fmt.Fprintln(os.Stderr, "==> found 1 possible issue") + } else if msgCount > 1 { + fmt.Fprintf(os.Stderr, "==> found %v possible issues\n", msgCount) + } + } + return nil +} + +func calculateZids(metaList []api.ZidMetaRights) ([]id.Zid, []int) { + zids := make([]id.Zid, len(metaList)) + for i, m := range metaList { + zids[i] = m.ID + } + slices.Sort(zids) + return zids, rand.Perm(len(metaList)) +} + +func zidsToUse(zids []id.Zid, perm []int, sampleSize int) []id.Zid { + if sampleSize < 0 || len(perm) <= sampleSize { + return zids + } + if sampleSize == 0 { + return nil + } + result := make([]id.Zid, sampleSize) + for i := range sampleSize { + result[i] = zids[perm[i]] + } + slices.Sort(result) + return result +} + +var keyDescr = []struct { + uc urlCreator + text string + sampleSize int +}{ + {getHTMLZettel, "zettel HTML encoding", -1}, + {createJustKey('h'), "zettel web view", -1}, + {createJustKey('i'), "zettel info view", -1}, + {createJustKey('e'), "zettel edit form", 100}, + {createJustKey('c'), "zettel create form", 10}, + {createJustKey('d'), "zettel delete dialog", 200}, +} + +type urlCreator func(*client.Client, id.Zid) *api.URLBuilder + +func createJustKey(key byte) urlCreator { + return func(c *client.Client, zid id.Zid) *api.URLBuilder { + return c.NewURLBuilder(key).SetZid(zid) + } +} + +func getHTMLZettel(client *client.Client, zid id.Zid) *api.URLBuilder { + return client.NewURLBuilder('z').SetZid(zid). + AppendKVQuery(api.QueryKeyEncoding, api.EncodingHTML). + AppendKVQuery(api.QueryKeyPart, api.PartZettel) +} + +func validateHTML(client *client.Client, uc urlCreator, zid id.Zid) (int, error) { + ub := uc(client, zid) + if tools.Verbose { + fmt.Fprintf(os.Stderr, "GET %v\n", ub) + } + data, err := client.Get(context.Background(), ub) + if err != nil { + return 0, err + } + if len(data) == 0 { + return 0, nil + } + _, stderr, err := tools.ExecuteFilter(data, nil, "tidy", "-e", "-q", "-lang", "en") + if err != nil { + switch err.Error() { + case "exit status 1": + case "exit status 2": + default: + log.Println("SERR", stderr) + return 0, err + } + } + if stderr == "" { + return 0, nil + } + if msgs := filterTidyMessages(strings.Split(stderr, "\n")); len(msgs) > 0 { + fmt.Fprintln(os.Stderr, zid) + for _, msg := range msgs { + fmt.Fprintln(os.Stderr, "-", msg) + } + return len(msgs), nil + } + return 0, nil +} + +var reLine = regexp.MustCompile(`line \d+ column \d+ - (.+): (.+)`) + +func filterTidyMessages(lines []string) []string { + result := make([]string, 0, len(lines)) + for _, line := range lines { + line = strings.TrimSpace(line) + if line == "" { + continue + } + matches := reLine.FindStringSubmatch(line) + if len(matches) <= 1 { + if line == "This document has errors that must be fixed before" || + line == "using HTML Tidy to generate a tidied up version." { + continue + } + result = append(result, "!!!"+line) + continue + } + if matches[1] == "Error" { + if len(matches) > 2 { + if matches[2] == "<search> is not recognized!" { + continue + } + } + } + if matches[1] != "Warning" { + result = append(result, "???"+line) + continue + } + if len(matches) > 2 { + switch matches[2] { + case "discarding unexpected <search>", + "discarding unexpected </search>", + `<input> proprietary attribute "inputmode"`: + continue + } + } + result = append(result, line) + } + return result +} ADDED tools/testapi/testapi.go Index: tools/testapi/testapi.go ================================================================== --- /dev/null +++ tools/testapi/testapi.go @@ -0,0 +1,110 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2023-present Detlef Stern +// +// This file is part of Zettelstore. +// +// Zettelstore is licensed under the latest version of the EUPL (European Union +// Public License). Please see file LICENSE.txt for your rights and obligations +// under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2023-present Detlef Stern +//----------------------------------------------------------------------------- + +// Package main provides a command to test the API +package main + +import ( + "errors" + "flag" + "fmt" + "io" + "net" + "os" + "os/exec" + "strings" + "time" + + "zettelstore.de/z/tools" +) + +func main() { + flag.BoolVar(&tools.Verbose, "v", false, "Verbose output") + flag.Parse() + + if err := cmdTestAPI(); err != nil { + fmt.Fprintln(os.Stderr, err) + } +} + +type zsInfo struct { + cmd *exec.Cmd + out strings.Builder + adminAddress string +} + +func cmdTestAPI() error { + var err error + var info zsInfo + needServer := !addressInUse(":23123") + if needServer { + err = startZettelstore(&info) + } + if err != nil { + return err + } + err = tools.CheckGoTest("zettelstore.de/z/tests/client", "-base-url", "http://127.0.0.1:23123") + if needServer { + err1 := stopZettelstore(&info) + if err == nil { + err = err1 + } + } + return err +} + +func startZettelstore(info *zsInfo) error { + info.adminAddress = ":2323" + name, arg := "go", []string{ + "run", "cmd/zettelstore/main.go", "run", + "-c", "./testdata/testbox/19700101000000.zettel", "-a", info.adminAddress[1:]} + tools.LogCommand("FORK", nil, name, arg) + cmd := tools.PrepareCommand(tools.EnvGoVCS, name, arg, nil, &info.out, os.Stderr) + if !tools.Verbose { + cmd.Stderr = nil + } + err := cmd.Start() + time.Sleep(2 * time.Second) + for range 100 { + time.Sleep(time.Millisecond * 100) + if addressInUse(info.adminAddress) { + info.cmd = cmd + return err + } + } + time.Sleep(4 * time.Second) // Wait for all zettel to be indexed. + return errors.New("zettelstore did not start") +} + +func stopZettelstore(i *zsInfo) error { + conn, err := net.Dial("tcp", i.adminAddress) + if err != nil { + fmt.Println("Unable to stop Zettelstore") + return err + } + _, err = io.WriteString(conn, "shutdown\n") + _ = conn.Close() + if err == nil { + err = i.cmd.Wait() + } + return err +} + +func addressInUse(address string) bool { + conn, err := net.Dial("tcp", address) + if err != nil { + return false + } + _ = conn.Close() + return true +} ADDED tools/tools.go Index: tools/tools.go ================================================================== --- /dev/null +++ tools/tools.go @@ -0,0 +1,254 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2023-present Detlef Stern +// +// This file is part of Zettelstore. +// +// Zettelstore is licensed under the latest version of the EUPL (European Union +// Public License). Please see file LICENSE.txt for your rights and obligations +// under this license. +// +// SPDX-License-Identifier: EUPL-1.2 +// SPDX-FileCopyrightText: 2023-present Detlef Stern +//----------------------------------------------------------------------------- + +// Package tools provides a collection of functions to build needed tools. +package tools + +import ( + "bytes" + "errors" + "fmt" + "io" + "os" + "os/exec" + "strings" + + "zettelstore.de/z/strfun" +) + +// Some constants to make Go work with fossil. +var ( + EnvDirectProxy = []string{"GOPROXY=direct"} + EnvGoVCS = []string{"GOVCS=zettelstore.de:fossil,t73f.de:fossil"} +) + +// Verbose signals a verbose tool execution. +var Verbose bool + +// ExecuteCommand executes a specific command. +func ExecuteCommand(env []string, name string, arg ...string) (string, error) { + LogCommand("EXEC", env, name, arg) + var out strings.Builder + cmd := PrepareCommand(env, name, arg, nil, &out, os.Stderr) + err := cmd.Run() + return out.String(), err +} + +// ExecuteFilter executes an external program to be used as a filter. +func ExecuteFilter(data []byte, env []string, name string, arg ...string) (string, string, error) { + LogCommand("EXEC", env, name, arg) + var stdout, stderr strings.Builder + cmd := PrepareCommand(env, name, arg, bytes.NewReader(data), &stdout, &stderr) + err := cmd.Run() + return stdout.String(), stderr.String(), err +} + +// PrepareCommand creates a commands to be executed. +func PrepareCommand(env []string, name string, arg []string, in io.Reader, stdout, stderr io.Writer) *exec.Cmd { + if len(env) > 0 { + env = append(env, os.Environ()...) + } + cmd := exec.Command(name, arg...) + cmd.Env = env + cmd.Stdin = in + cmd.Stdout = stdout + cmd.Stderr = stderr + return cmd +} + +// LogCommand logs the execution of a command. +func LogCommand(exec string, env []string, name string, arg []string) { + if Verbose { + if len(env) > 0 { + for i, e := range env { + fmt.Fprintf(os.Stderr, "ENV%d %v\n", i+1, e) + } + } + fmt.Fprintln(os.Stderr, exec, name, arg) + } +} + +// Check the source with some linters. +func Check(forRelease bool) error { + if err := CheckGoTest("./..."); err != nil { + return err + } + if err := checkGoVet(); err != nil { + return err + } + if err := checkShadow(forRelease); err != nil { + return err + } + if err := checkStaticcheck(); err != nil { + return err + } + if err := checkUnparam(forRelease); err != nil { + return err + } + if err := checkRevive(); err != nil { + return err + } + if err := checkErrCheck(); err != nil { + return err + } + if forRelease { + if err := checkGoVulncheck(); err != nil { + return err + } + } + return checkFossilExtra() +} + +// CheckGoTest runs all internal unti tests. +func CheckGoTest(pkg string, testParams ...string) error { + var env []string + env = append(env, EnvDirectProxy...) + env = append(env, EnvGoVCS...) + args := []string{"test", pkg} + args = append(args, testParams...) + out, err := ExecuteCommand(env, "go", args...) + if err != nil { + for _, line := range strfun.SplitLines(out) { + if strings.HasPrefix(line, "ok") || strings.HasPrefix(line, "?") { + continue + } + fmt.Fprintln(os.Stderr, line) + } + } + return err +} +func checkGoVet() error { + out, err := ExecuteCommand(EnvGoVCS, "go", "vet", "./...") + if err != nil { + fmt.Fprintln(os.Stderr, "Some checks failed") + if len(out) > 0 { + fmt.Fprintln(os.Stderr, out) + } + } + return err +} + +func checkShadow(forRelease bool) error { + path, err := findExecStrict("shadow", forRelease) + if path == "" { + return err + } + out, err := ExecuteCommand(EnvGoVCS, path, "-strict", "./...") + if err != nil { + fmt.Fprintln(os.Stderr, "Some shadowed variables found") + if len(out) > 0 { + fmt.Fprintln(os.Stderr, out) + } + } + return err +} + +func checkStaticcheck() error { + out, err := ExecuteCommand(EnvGoVCS, "staticcheck", "./...") + if err != nil { + fmt.Fprintln(os.Stderr, "Some staticcheck problems found") + if len(out) > 0 { + fmt.Fprintln(os.Stderr, out) + } + } + return err +} + +func checkRevive() error { + out, err := ExecuteCommand(EnvGoVCS, "revive", "./...") + if err != nil || out != "" { + fmt.Fprintln(os.Stderr, "Some revive problems found") + if len(out) > 0 { + fmt.Fprintln(os.Stderr, out) + } + } + return err +} + +func checkErrCheck() error { + out, err := ExecuteCommand(EnvGoVCS, "errcheck", "./...") + if err != nil || out != "" { + fmt.Fprintln(os.Stderr, "Some errcheck problems found") + if len(out) > 0 { + fmt.Fprintln(os.Stderr, out) + } + } + return err +} + +func checkUnparam(forRelease bool) error { + path, err := findExecStrict("unparam", forRelease) + if path == "" { + return err + } + out, err := ExecuteCommand(EnvGoVCS, path, "./...") + if err != nil { + fmt.Fprintln(os.Stderr, "Some unparam problems found") + if len(out) > 0 { + fmt.Fprintln(os.Stderr, out) + } + } + if forRelease { + if out2, err2 := ExecuteCommand(nil, path, "-exported", "-tests", "./..."); err2 != nil { + fmt.Fprintln(os.Stderr, "Some optional unparam problems found") + if len(out2) > 0 { + fmt.Fprintln(os.Stderr, out2) + } + } + } + return err +} + +func checkGoVulncheck() error { + out, err := ExecuteCommand(EnvGoVCS, "govulncheck", "./...") + if err != nil { + fmt.Fprintln(os.Stderr, "Some checks failed") + if len(out) > 0 { + fmt.Fprintln(os.Stderr, out) + } + } + return err +} +func findExec(cmd string) string { + if path, err := ExecuteCommand(nil, "which", cmd); err == nil && path != "" { + return strings.TrimSpace(path) + } + return "" +} + +func findExecStrict(cmd string, forRelease bool) (string, error) { + path := findExec(cmd) + if path != "" || !forRelease { + return path, nil + } + return "", errors.New("Command '" + cmd + "' not installed, but required for release") +} + +func checkFossilExtra() error { + out, err := ExecuteCommand(nil, "fossil", "extra") + if err != nil { + fmt.Fprintln(os.Stderr, "Unable to execute 'fossil extra'") + return err + } + if len(out) > 0 { + fmt.Fprint(os.Stderr, "Warning: unversioned file(s):") + for i, extra := range strfun.SplitLines(out) { + if i > 0 { + fmt.Fprint(os.Stderr, ",") + } + fmt.Fprintf(os.Stderr, " %q", extra) + } + fmt.Fprintln(os.Stderr) + } + return nil +} DELETED usecase/authenticate.go Index: usecase/authenticate.go ================================================================== --- usecase/authenticate.go +++ /dev/null @@ -1,147 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - "math/rand" - "time" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/auth/cred" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/logger" - "zettelstore.de/z/search" -) - -// AuthenticatePort is the interface used by this use case. -type AuthenticatePort interface { - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) - SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) -} - -// Authenticate is the data for this use case. -type Authenticate struct { - log *logger.Logger - token auth.TokenManager - port AuthenticatePort - ucGetUser GetUser -} - -// NewAuthenticate creates a new use case. -func NewAuthenticate(log *logger.Logger, token auth.TokenManager, authz auth.AuthzManager, port AuthenticatePort) Authenticate { - return Authenticate{ - log: log, - token: token, - port: port, - ucGetUser: NewGetUser(authz, port), - } -} - -// Run executes the use case. -func (uc *Authenticate) Run(ctx context.Context, ident, credential string, d time.Duration, k auth.TokenKind) ([]byte, error) { - identMeta, err := uc.ucGetUser.Run(ctx, ident) - defer addDelay(time.Now(), 500*time.Millisecond, 100*time.Millisecond) - - if identMeta == nil || err != nil { - uc.log.Info().Str("ident", ident).Err(err).Msg("No user with given ident found") - compensateCompare() - return nil, err - } - - if hashCred, ok := identMeta.Get(api.KeyCredential); ok { - ok, err = cred.CompareHashAndCredential(hashCred, identMeta.Zid, ident, credential) - if err != nil { - uc.log.Info().Str("ident", ident).Err(err).Msg("Error while comparing credentials") - return nil, err - } - if ok { - token, err2 := uc.token.GetToken(identMeta, d, k) - if err2 != nil { - uc.log.Info().Str("ident", ident).Err(err).Msg("Unable to produce authentication token") - return nil, err2 - } - uc.log.Info().Str("user", ident).Msg("Successful") - return token, nil - } - uc.log.Info().Str("ident", ident).Msg("Credentials don't match") - return nil, nil - } - uc.log.Info().Str("ident", ident).Msg("No credential stored") - compensateCompare() - return nil, nil -} - -// compensateCompare if normal comapare is not possible, to avoid timing hints. -func compensateCompare() { - cred.CompareHashAndCredential( - "$2a$10$WHcSO3G9afJ3zlOYQR1suuf83bCXED2jmzjti/MH4YH4l2mivDuze", id.Invalid, "", "") -} - -// addDelay after credential checking to allow some CPU time for other tasks. -// durDelay is the normal delay, if time spend for checking is smaller than -// the minimum delay minDelay. In addition some jitter (+/- 50 ms) is added. -func addDelay(start time.Time, durDelay, minDelay time.Duration) { - jitter := time.Duration(rand.Intn(100)-50) * time.Millisecond - if elapsed := time.Since(start); elapsed+minDelay < durDelay { - time.Sleep(durDelay - elapsed + jitter) - } else { - time.Sleep(minDelay + jitter) - } -} - -// IsAuthenticatedPort contains method for this usecase. -type IsAuthenticatedPort interface { - GetUser(context.Context) *meta.Meta -} - -// IsAuthenticated cheks if the caller is alrwady authenticated. -type IsAuthenticated struct { - log *logger.Logger - port IsAuthenticatedPort - authz auth.AuthzManager -} - -// NewIsAuthenticated creates a new use case object. -func NewIsAuthenticated(log *logger.Logger, port IsAuthenticatedPort, authz auth.AuthzManager) IsAuthenticated { - return IsAuthenticated{ - log: log, - port: port, - authz: authz, - } -} - -// IsAuthenticatedResult is an enumeration. -type IsAuthenticatedResult uint8 - -// Values for IsAuthenticatedResult. -const ( - _ IsAuthenticatedResult = iota - IsAuthenticatedDisabled - IsAuthenticatedAndValid - IsAuthenticatedAndInvalid -) - -// Run executes the use case. -func (uc *IsAuthenticated) Run(ctx context.Context) IsAuthenticatedResult { - if !uc.authz.WithAuth() { - uc.log.Sense().Str("auth", "disabled").Msg("IsAuthenticated") - return IsAuthenticatedDisabled - } - if uc.port.GetUser(ctx) == nil { - uc.log.Sense().Msg("IsAuthenticated is false") - return IsAuthenticatedAndInvalid - } - uc.log.Sense().Msg("IsAuthenticated is true") - return IsAuthenticatedAndValid -} DELETED usecase/context.go Index: usecase/context.go ================================================================== --- usecase/context.go +++ /dev/null @@ -1,197 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -// ZettelContextPort is the interface used by this use case. -type ZettelContextPort interface { - // GetMeta retrieves just the meta data of a specific zettel. - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) -} - -// ZettelContextConfig is the interface to allow the usecase to read some config data. -type ZettelContextConfig interface { - // GetHomeZettel returns the value of the "home-zettel" key. - GetHomeZettel() id.Zid -} - -// ZettelContext is the data for this use case. -type ZettelContext struct { - port ZettelContextPort - config ZettelContextConfig -} - -// NewZettelContext creates a new use case. -func NewZettelContext(port ZettelContextPort, config ZettelContextConfig) ZettelContext { - return ZettelContext{port: port, config: config} -} - -// ZettelContextDirection determines the way, the context is calculated. -type ZettelContextDirection int - -// Constant values for ZettelContextDirection -const ( - _ ZettelContextDirection = iota - ZettelContextForward // Traverse all forwarding links - ZettelContextBackward // Traverse all backwaring links - ZettelContextBoth // Traverse both directions -) - -// Run executes the use case. -func (uc ZettelContext) Run(ctx context.Context, zid id.Zid, dir ZettelContextDirection, depth, limit int) (result []*meta.Meta, err error) { - start, err := uc.port.GetMeta(ctx, zid) - if err != nil { - return nil, err - } - tasks := newQueue(start, depth, limit, uc.config.GetHomeZettel()) - isBackward := dir == ZettelContextBoth || dir == ZettelContextBackward - isForward := dir == ZettelContextBoth || dir == ZettelContextForward - for { - m, curDepth, found := tasks.next() - if !found { - break - } - result = append(result, m) - - for _, p := range m.ComputedPairsRest() { - tasks.addPair(ctx, uc.port, p.Key, p.Value, curDepth+1, isBackward, isForward) - } - } - return result, nil -} - -type ztlCtxTask struct { - next *ztlCtxTask - meta *meta.Meta - depth int -} - -type contextQueue struct { - home id.Zid - seen id.Set - first *ztlCtxTask - last *ztlCtxTask - maxDepth int - limit int -} - -func newQueue(m *meta.Meta, maxDepth, limit int, home id.Zid) *contextQueue { - task := &ztlCtxTask{ - next: nil, - meta: m, - depth: 0, - } - result := &contextQueue{ - home: home, - seen: id.NewSet(), - first: task, - last: task, - maxDepth: maxDepth, - limit: limit, - } - return result -} - -func (zc *contextQueue) addPair( - ctx context.Context, port ZettelContextPort, - key, value string, - curDepth int, isBackward, isForward bool, -) { - if key == api.KeyBackward { - if isBackward { - zc.addIDSet(ctx, port, curDepth, value) - } - return - } - if key == api.KeyForward { - if isForward { - zc.addIDSet(ctx, port, curDepth, value) - } - return - } - if key == api.KeyBack { - return - } - hasInverse := meta.Inverse(key) != "" - if (!hasInverse || !isBackward) && (hasInverse || !isForward) { - return - } - if t := meta.Type(key); t == meta.TypeID { - zc.addID(ctx, port, curDepth, value) - } else if t == meta.TypeIDSet { - zc.addIDSet(ctx, port, curDepth, value) - } -} - -func (zc *contextQueue) addID(ctx context.Context, port ZettelContextPort, depth int, value string) { - if (zc.maxDepth > 0 && depth > zc.maxDepth) || zc.hasLimit() { - return - } - - zid, err := id.Parse(value) - if err != nil || zid == zc.home { - return - } - - m, err := port.GetMeta(ctx, zid) - if err != nil { - return - } - - task := &ztlCtxTask{next: nil, meta: m, depth: depth} - if zc.first == nil { - zc.first = task - zc.last = task - } else { - zc.last.next = task - zc.last = task - } -} - -func (zc *contextQueue) addIDSet(ctx context.Context, port ZettelContextPort, curDepth int, value string) { - for _, val := range meta.ListFromValue(value) { - zc.addID(ctx, port, curDepth, val) - } -} - -func (zc *contextQueue) next() (*meta.Meta, int, bool) { - if zc.hasLimit() { - return nil, -1, false - } - for zc.first != nil { - task := zc.first - zc.first = task.next - if zc.first == nil { - zc.last = nil - } - m := task.meta - zid := m.Zid - _, found := zc.seen[zid] - if found { - continue - } - zc.seen.Zid(zid) - return m, task.depth, true - } - return nil, -1, false -} - -func (zc *contextQueue) hasLimit() bool { - limit := zc.limit - return limit > 0 && len(zc.seen) > limit -} DELETED usecase/create_zettel.go Index: usecase/create_zettel.go ================================================================== --- usecase/create_zettel.go +++ /dev/null @@ -1,124 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/c/api" - "zettelstore.de/z/config" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/logger" -) - -// CreateZettelPort is the interface used by this use case. -type CreateZettelPort interface { - // CreateZettel creates a new zettel. - CreateZettel(ctx context.Context, zettel domain.Zettel) (id.Zid, error) -} - -// CreateZettel is the data for this use case. -type CreateZettel struct { - log *logger.Logger - rtConfig config.Config - port CreateZettelPort -} - -// NewCreateZettel creates a new use case. -func NewCreateZettel(log *logger.Logger, rtConfig config.Config, port CreateZettelPort) CreateZettel { - return CreateZettel{ - log: log, - rtConfig: rtConfig, - port: port, - } -} - -// PrepareCopy the zettel for further modification. -func (*CreateZettel) PrepareCopy(origZettel domain.Zettel) domain.Zettel { - m := origZettel.Meta.Clone() - if title, found := m.Get(api.KeyTitle); found { - m.Set(api.KeyTitle, prependTitle(title, "Copy", "Copy of ")) - } - if readonly, found := m.Get(api.KeyReadOnly); found { - m.Set(api.KeyReadOnly, copyReadonly(readonly)) - } - content := origZettel.Content - content.TrimSpace() - return domain.Zettel{Meta: m, Content: content} -} - -// PrepareFolge the zettel for further modification. -func (*CreateZettel) PrepareFolge(origZettel domain.Zettel) domain.Zettel { - origMeta := origZettel.Meta - m := meta.New(id.Invalid) - if title, found := origMeta.Get(api.KeyTitle); found { - m.Set(api.KeyTitle, prependTitle(title, "Folge", "Folge of ")) - } - m.SetNonEmpty(api.KeyRole, origMeta.GetDefault(api.KeyRole, "")) - m.SetNonEmpty(api.KeyTags, origMeta.GetDefault(api.KeyTags, "")) - m.SetNonEmpty(api.KeySyntax, origMeta.GetDefault(api.KeySyntax, "")) - m.Set(api.KeyPrecursor, origMeta.Zid.String()) - return domain.Zettel{Meta: m, Content: domain.NewContent(nil)} -} - -// PrepareNew the zettel for further modification. -func (*CreateZettel) PrepareNew(origZettel domain.Zettel) domain.Zettel { - m := meta.New(id.Invalid) - om := origZettel.Meta - m.SetNonEmpty(api.KeyTitle, om.GetDefault(api.KeyTitle, "")) - m.SetNonEmpty(api.KeyRole, om.GetDefault(api.KeyRole, "")) - m.SetNonEmpty(api.KeyTags, om.GetDefault(api.KeyTags, "")) - m.SetNonEmpty(api.KeySyntax, om.GetDefault(api.KeySyntax, "")) - - const prefixLen = len(meta.NewPrefix) - for _, pair := range om.PairsRest() { - if key := pair.Key; len(key) > prefixLen && key[0:prefixLen] == meta.NewPrefix { - m.Set(key[prefixLen:], pair.Value) - } - } - content := origZettel.Content - content.TrimSpace() - return domain.Zettel{Meta: m, Content: content} -} - -func prependTitle(title, s0, s1 string) string { - if len(title) > 0 { - return s1 + title - } - return s0 -} - -func copyReadonly(string) string { - // Currently, "false" is a safe value. - // - // If the current user and its role is known, a mor elaborative calculation - // could be done: set it to a value, so that the current user will be able - // to modify it later. - return api.ValueFalse -} - -// Run executes the use case. -func (uc *CreateZettel) Run(ctx context.Context, zettel domain.Zettel) (id.Zid, error) { - m := zettel.Meta - if m.Zid.IsValid() { - return m.Zid, nil // TODO: new error: already exists - } - - m.Delete(api.KeyModified) - m.YamlSep = uc.rtConfig.GetYAMLHeader() - - zettel.Content.TrimSpace() - zid, err := uc.port.CreateZettel(ctx, zettel) - uc.log.Info().User(ctx).Zid(zid).Err(err).Msg("Create zettel") - return zid, err -} DELETED usecase/delete_zettel.go Index: usecase/delete_zettel.go ================================================================== --- usecase/delete_zettel.go +++ /dev/null @@ -1,42 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/z/domain/id" - "zettelstore.de/z/logger" -) - -// DeleteZettelPort is the interface used by this use case. -type DeleteZettelPort interface { - // DeleteZettel removes the zettel from the box. - DeleteZettel(ctx context.Context, zid id.Zid) error -} - -// DeleteZettel is the data for this use case. -type DeleteZettel struct { - log *logger.Logger - port DeleteZettelPort -} - -// NewDeleteZettel creates a new use case. -func NewDeleteZettel(log *logger.Logger, port DeleteZettelPort) DeleteZettel { - return DeleteZettel{log: log, port: port} -} - -// Run executes the use case. -func (uc *DeleteZettel) Run(ctx context.Context, zid id.Zid) error { - err := uc.port.DeleteZettel(ctx, zid) - uc.log.Info().User(ctx).Zid(zid).Err(err).Msg("Delete zettel") - return err -} DELETED usecase/evaluate.go Index: usecase/evaluate.go ================================================================== --- usecase/evaluate.go +++ /dev/null @@ -1,71 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/z/ast" - "zettelstore.de/z/config" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/evaluator" - "zettelstore.de/z/parser" -) - -// Evaluate is the data for this use case. -type Evaluate struct { - rtConfig config.Config - getZettel GetZettel - getMeta GetMeta -} - -// NewEvaluate creates a new use case. -func NewEvaluate(rtConfig config.Config, getZettel GetZettel, getMeta GetMeta) Evaluate { - return Evaluate{ - rtConfig: rtConfig, - getZettel: getZettel, - getMeta: getMeta, - } -} - -// Run executes the use case. -func (uc *Evaluate) Run(ctx context.Context, zid id.Zid, syntax string) (*ast.ZettelNode, error) { - zettel, err := uc.getZettel.Run(ctx, zid) - if err != nil { - return nil, err - } - zn, err := parser.ParseZettel(zettel, syntax, uc.rtConfig), nil - if err != nil { - return nil, err - } - - evaluator.EvaluateZettel(ctx, uc, uc.rtConfig, zn) - return zn, nil -} - -// RunMetadata executes the use case for a metadata value. -func (uc *Evaluate) RunMetadata(ctx context.Context, value string) ast.InlineSlice { - is := parser.ParseMetadata(value) - evaluator.EvaluateInline(ctx, uc, uc.rtConfig, &is) - return is -} - -// GetMeta retrieves the metadata of a given zettel identifier. -func (uc *Evaluate) GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) { - return uc.getMeta.Run(ctx, zid) -} - -// GetZettel retrieves the full zettel of a given zettel identifier. -func (uc *Evaluate) GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) { - return uc.getZettel.Run(ctx, zid) -} DELETED usecase/get_all_meta.go Index: usecase/get_all_meta.go ================================================================== --- usecase/get_all_meta.go +++ /dev/null @@ -1,39 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -// GetAllMetaPort is the interface used by this use case. -type GetAllMetaPort interface { - // GetAllMeta retrieves just the meta data of a specific zettel. - GetAllMeta(ctx context.Context, zid id.Zid) ([]*meta.Meta, error) -} - -// GetAllMeta is the data for this use case. -type GetAllMeta struct { - port GetAllMetaPort -} - -// NewGetAllMeta creates a new use case. -func NewGetAllMeta(port GetAllMetaPort) GetAllMeta { - return GetAllMeta{port: port} -} - -// Run executes the use case. -func (uc GetAllMeta) Run(ctx context.Context, zid id.Zid) ([]*meta.Meta, error) { - return uc.port.GetAllMeta(ctx, zid) -} DELETED usecase/get_meta.go Index: usecase/get_meta.go ================================================================== --- usecase/get_meta.go +++ /dev/null @@ -1,39 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -// GetMetaPort is the interface used by this use case. -type GetMetaPort interface { - // GetMeta retrieves just the meta data of a specific zettel. - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) -} - -// GetMeta is the data for this use case. -type GetMeta struct { - port GetMetaPort -} - -// NewGetMeta creates a new use case. -func NewGetMeta(port GetMetaPort) GetMeta { - return GetMeta{port: port} -} - -// Run executes the use case. -func (uc GetMeta) Run(ctx context.Context, zid id.Zid) (*meta.Meta, error) { - return uc.port.GetMeta(ctx, zid) -} DELETED usecase/get_user.go Index: usecase/get_user.go ================================================================== --- usecase/get_user.go +++ /dev/null @@ -1,98 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/box" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/search" -) - -// Use case: return user identified by meta key ident. -// --------------------------------------------------- - -// GetUserPort is the interface used by this use case. -type GetUserPort interface { - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) - SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) -} - -// GetUser is the data for this use case. -type GetUser struct { - authz auth.AuthzManager - port GetUserPort -} - -// NewGetUser creates a new use case. -func NewGetUser(authz auth.AuthzManager, port GetUserPort) GetUser { - return GetUser{authz: authz, port: port} -} - -// Run executes the use case. -func (uc GetUser) Run(ctx context.Context, ident string) (*meta.Meta, error) { - ctx = box.NoEnrichContext(ctx) - - // It is important to try first with the owner. First, because another user - // could give herself the same ''ident''. Second, in most cases the owner - // will authenticate. - identMeta, err := uc.port.GetMeta(ctx, uc.authz.Owner()) - if err == nil && identMeta.GetDefault(api.KeyUserID, "") == ident { - return identMeta, nil - } - // Owner was not found or has another ident. Try via list search. - var s *search.Search - s = s.AddExpr("", "="+ident) - s = s.AddExpr(api.KeyUserID, ident) - metaList, err := uc.port.SelectMeta(ctx, s) - if err != nil { - return nil, err - } - if len(metaList) < 1 { - return nil, nil - } - return metaList[len(metaList)-1], nil -} - -// Use case: return an user identified by zettel id and assert given ident value. -// ------------------------------------------------------------------------------ - -// GetUserByZidPort is the interface used by this use case. -type GetUserByZidPort interface { - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) -} - -// GetUserByZid is the data for this use case. -type GetUserByZid struct { - port GetUserByZidPort -} - -// NewGetUserByZid creates a new use case. -func NewGetUserByZid(port GetUserByZidPort) GetUserByZid { - return GetUserByZid{port: port} -} - -// GetUser executes the use case. -func (uc GetUserByZid) GetUser(ctx context.Context, zid id.Zid, ident string) (*meta.Meta, error) { - userMeta, err := uc.port.GetMeta(box.NoEnrichContext(ctx), zid) - if err != nil { - return nil, err - } - - if val, ok := userMeta.Get(api.KeyUserID); !ok || val != ident { - return nil, nil - } - return userMeta, nil -} DELETED usecase/get_zettel.go Index: usecase/get_zettel.go ================================================================== --- usecase/get_zettel.go +++ /dev/null @@ -1,39 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" -) - -// GetZettelPort is the interface used by this use case. -type GetZettelPort interface { - // GetZettel retrieves a specific zettel. - GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) -} - -// GetZettel is the data for this use case. -type GetZettel struct { - port GetZettelPort -} - -// NewGetZettel creates a new use case. -func NewGetZettel(port GetZettelPort) GetZettel { - return GetZettel{port: port} -} - -// Run executes the use case. -func (uc GetZettel) Run(ctx context.Context, zid id.Zid) (domain.Zettel, error) { - return uc.port.GetZettel(ctx, zid) -} DELETED usecase/lists.go Index: usecase/lists.go ================================================================== --- usecase/lists.go +++ /dev/null @@ -1,143 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/parser" - "zettelstore.de/z/search" -) - -// ListMetaPort is the interface used by this use case. -type ListMetaPort interface { - // SelectMeta returns all zettel metadata that match the selection criteria. - SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) -} - -// ListMeta is the data for this use case. -type ListMeta struct { - port ListMetaPort -} - -// NewListMeta creates a new use case. -func NewListMeta(port ListMetaPort) ListMeta { - return ListMeta{port: port} -} - -// Run executes the use case. -func (uc ListMeta) Run(ctx context.Context, s *search.Search) ([]*meta.Meta, error) { - return uc.port.SelectMeta(ctx, s) -} - -// -------- List roles ------------------------------------------------------- - -// ListSyntaxPort is the interface used by this use case. -type ListSyntaxPort interface { - // SelectMeta returns all zettel metadata that match the selection criteria. - SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) -} - -// ListSyntax is the data for this use case. -type ListSyntax struct { - port ListSyntaxPort -} - -// NewListSyntax creates a new use case. -func NewListSyntax(port ListSyntaxPort) ListSyntax { - return ListSyntax{port: port} -} - -// Run executes the use case. -func (uc ListSyntax) Run(ctx context.Context) (meta.Arrangement, error) { - var s *search.Search - s = s.AddExpr(api.KeySyntax, "") // We look for all metadata with a syntax key - metas, err := uc.port.SelectMeta(box.NoEnrichContext(ctx), s) - if err != nil { - return nil, err - } - result := meta.CreateArrangement(metas, api.KeySyntax) - for _, syn := range parser.GetSyntaxes() { - if _, found := result[syn]; !found { - result[syn] = nil - } - } - return result, nil -} - -// -------- List roles ------------------------------------------------------- - -// ListRolesPort is the interface used by this use case. -type ListRolesPort interface { - // SelectMeta returns all zettel metadata that match the selection criteria. - SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) -} - -// ListRoles is the data for this use case. -type ListRoles struct { - port ListRolesPort -} - -// NewListRoles creates a new use case. -func NewListRoles(port ListRolesPort) ListRoles { - return ListRoles{port: port} -} - -// Run executes the use case. -func (uc ListRoles) Run(ctx context.Context) (meta.Arrangement, error) { - var s *search.Search - s = s.AddExpr(api.KeyRole, "") // We look for all metadata with a role key - metas, err := uc.port.SelectMeta(box.NoEnrichContext(ctx), s) - if err != nil { - return nil, err - } - return meta.CreateArrangement(metas, api.KeyRole), nil -} - -// -------- List tags -------------------------------------------------------- - -// ListTagsPort is the interface used by this use case. -type ListTagsPort interface { - // SelectMeta returns all zettel metadata that match the selection criteria. - SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) -} - -// ListTags is the data for this use case. -type ListTags struct { - port ListTagsPort -} - -// NewListTags creates a new use case. -func NewListTags(port ListTagsPort) ListTags { - return ListTags{port: port} -} - -// Run executes the use case. -func (uc ListTags) Run(ctx context.Context, minCount int) (meta.Arrangement, error) { - var s *search.Search - s = s.AddExpr(api.KeyTags, "") // We look for all metadata with a tag - metas, err := uc.port.SelectMeta(ctx, s) - if err != nil { - return nil, err - } - result := meta.CreateArrangement(metas, api.KeyAllTags) - if minCount > 1 { - for t, ms := range result { - if len(ms) < minCount { - delete(result, t) - } - } - } - return result, nil -} DELETED usecase/order.go Index: usecase/order.go ================================================================== --- usecase/order.go +++ /dev/null @@ -1,54 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/z/collect" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -// ZettelOrderPort is the interface used by this use case. -type ZettelOrderPort interface { - // GetMeta retrieves just the meta data of a specific zettel. - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) -} - -// ZettelOrder is the data for this use case. -type ZettelOrder struct { - port ZettelOrderPort - evaluate Evaluate -} - -// NewZettelOrder creates a new use case. -func NewZettelOrder(port ZettelOrderPort, evaluate Evaluate) ZettelOrder { - return ZettelOrder{port: port, evaluate: evaluate} -} - -// Run executes the use case. -func (uc ZettelOrder) Run(ctx context.Context, zid id.Zid, syntax string) ( - start *meta.Meta, result []*meta.Meta, err error, -) { - zn, err := uc.evaluate.Run(ctx, zid, syntax) - if err != nil { - return nil, nil, err - } - for _, ref := range collect.Order(zn) { - if collectedZid, err2 := id.Parse(ref.URL.Path); err2 == nil { - if m, err3 := uc.port.GetMeta(ctx, collectedZid); err3 == nil { - result = append(result, m) - } - } - } - return zn.Meta, result, nil -} DELETED usecase/parse_zettel.go Index: usecase/parse_zettel.go ================================================================== --- usecase/parse_zettel.go +++ /dev/null @@ -1,41 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/z/ast" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/parser" -) - -// ParseZettel is the data for this use case. -type ParseZettel struct { - rtConfig config.Config - getZettel GetZettel -} - -// NewParseZettel creates a new use case. -func NewParseZettel(rtConfig config.Config, getZettel GetZettel) ParseZettel { - return ParseZettel{rtConfig: rtConfig, getZettel: getZettel} -} - -// Run executes the use case. -func (uc ParseZettel) Run(ctx context.Context, zid id.Zid, syntax string) (*ast.ZettelNode, error) { - zettel, err := uc.getZettel.Run(ctx, zid) - if err != nil { - return nil, err - } - - return parser.ParseZettel(zettel, syntax, uc.rtConfig), nil -} DELETED usecase/refresh.go Index: usecase/refresh.go ================================================================== --- usecase/refresh.go +++ /dev/null @@ -1,40 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/z/logger" -) - -// RefreshPort is the interface used by this use case. -type RefreshPort interface { - Refresh(context.Context) error -} - -// Refresh is the data for this use case. -type Refresh struct { - log *logger.Logger - port RefreshPort -} - -// NewRefresh creates a new use case. -func NewRefresh(log *logger.Logger, port RefreshPort) Refresh { - return Refresh{log: log, port: port} -} - -// Run executes the use case. -func (uc *Refresh) Run(ctx context.Context) error { - err := uc.port.Refresh(ctx) - uc.log.Info().User(ctx).Err(err).Msg("Refresh internal data") - return err -} DELETED usecase/rename_zettel.go Index: usecase/rename_zettel.go ================================================================== --- usecase/rename_zettel.go +++ /dev/null @@ -1,65 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/z/box" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/logger" -) - -// RenameZettelPort is the interface used by this use case. -type RenameZettelPort interface { - // GetMeta retrieves just the meta data of a specific zettel. - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) - - // Rename changes the current id to a new id. - RenameZettel(ctx context.Context, curZid, newZid id.Zid) error -} - -// RenameZettel is the data for this use case. -type RenameZettel struct { - log *logger.Logger - port RenameZettelPort -} - -// ErrZidInUse is returned if the zettel id is not appropriate for the box operation. -type ErrZidInUse struct{ Zid id.Zid } - -func (err *ErrZidInUse) Error() string { - return "Zettel id already in use: " + err.Zid.String() -} - -// NewRenameZettel creates a new use case. -func NewRenameZettel(log *logger.Logger, port RenameZettelPort) RenameZettel { - return RenameZettel{log: log, port: port} -} - -// Run executes the use case. -func (uc *RenameZettel) Run(ctx context.Context, curZid, newZid id.Zid) error { - noEnrichCtx := box.NoEnrichContext(ctx) - if _, err := uc.port.GetMeta(noEnrichCtx, curZid); err != nil { - return err - } - if newZid == curZid { - // Nothing to do - return nil - } - if _, err := uc.port.GetMeta(noEnrichCtx, newZid); err == nil { - return &ErrZidInUse{Zid: newZid} - } - err := uc.port.RenameZettel(ctx, curZid, newZid) - uc.log.Info().User(ctx).Zid(curZid).Err(err).Zid(newZid).Msg("Rename zettel") - return err -} DELETED usecase/unlinked_refs.go Index: usecase/unlinked_refs.go ================================================================== --- usecase/unlinked_refs.go +++ /dev/null @@ -1,178 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - "strings" - "unicode" - - "zettelstore.de/c/api" - "zettelstore.de/z/ast" - "zettelstore.de/z/config" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/encoder/textenc" - "zettelstore.de/z/evaluator" - "zettelstore.de/z/parser" - "zettelstore.de/z/search" -) - -// UnlinkedReferencesPort is the interface used by this use case. -type UnlinkedReferencesPort interface { - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) - GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) - SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) -} - -// UnlinkedReferences is the data for this use case. -type UnlinkedReferences struct { - port UnlinkedReferencesPort - rtConfig config.Config - encText *textenc.Encoder -} - -// NewUnlinkedReferences creates a new use case. -func NewUnlinkedReferences(port UnlinkedReferencesPort, rtConfig config.Config) UnlinkedReferences { - return UnlinkedReferences{ - port: port, - rtConfig: rtConfig, - encText: textenc.Create(), - } -} - -// Run executes the usecase with already evaluated title value. -func (uc *UnlinkedReferences) Run(ctx context.Context, title string, s *search.Search) ([]*meta.Meta, error) { - words := makeWords(title) - if len(words) == 0 { - return nil, nil - } - for _, word := range words { - s = s.AddExpr("", "="+word) - } - - // Limit applies to the filtering process, not to SelectMeta - limit := s.GetLimit() - s = s.SetLimit(0) - - candidates, err := uc.port.SelectMeta(ctx, s) - if err != nil { - return nil, err - } - s = s.SetLimit(limit) // Restore limit - return s.Limit(uc.filterCandidates(ctx, candidates, words)), nil -} - -func makeWords(text string) []string { - return strings.FieldsFunc(text, func(r rune) bool { - return unicode.In(r, unicode.C, unicode.P, unicode.Z) - }) -} - -func (uc *UnlinkedReferences) filterCandidates(ctx context.Context, candidates []*meta.Meta, words []string) []*meta.Meta { - result := make([]*meta.Meta, 0, len(candidates)) -candLoop: - for _, cand := range candidates { - zettel, err := uc.port.GetZettel(ctx, cand.Zid) - if err != nil { - continue - } - v := unlinkedVisitor{ - words: words, - found: false, - } - v.text = v.joinWords(words) - - for _, pair := range zettel.Meta.Pairs() { - if meta.Type(pair.Key) != meta.TypeZettelmarkup { - continue - } - is := parser.ParseMetadata(pair.Value) - evaluator.EvaluateInline(ctx, uc.port, uc.rtConfig, &is) - ast.Walk(&v, &is) - if v.found { - result = append(result, cand) - continue candLoop - } - } - - syntax := zettel.Meta.GetDefault(api.KeySyntax, "") - if !parser.IsTextParser(syntax) { - continue - } - zn, err := parser.ParseZettel(zettel, syntax, nil), nil - if err != nil { - continue - } - evaluator.EvaluateZettel(ctx, uc.port, uc.rtConfig, zn) - ast.Walk(&v, &zn.Ast) - if v.found { - result = append(result, cand) - } - } - return result -} - -func (*unlinkedVisitor) joinWords(words []string) string { - return " " + strings.ToLower(strings.Join(words, " ")) + " " -} - -type unlinkedVisitor struct { - words []string - text string - found bool -} - -func (v *unlinkedVisitor) Visit(node ast.Node) ast.Visitor { - switch n := node.(type) { - case *ast.InlineSlice: - v.checkWords(n) - return nil - case *ast.HeadingNode: - return nil - case *ast.LinkNode, *ast.EmbedRefNode, *ast.EmbedBLOBNode, *ast.CiteNode: - return nil - } - return v -} - -func (v *unlinkedVisitor) checkWords(is *ast.InlineSlice) { - if len(*is) < 2*len(v.words)-1 { - return - } - for _, text := range v.splitInlineTextList(is) { - if strings.Contains(text, v.text) { - v.found = true - } - } -} - -func (v *unlinkedVisitor) splitInlineTextList(is *ast.InlineSlice) []string { - var result []string - var curList []string - for _, in := range *is { - switch n := in.(type) { - case *ast.TextNode: - curList = append(curList, makeWords(n.Text)...) - case *ast.SpaceNode: - default: - if curList != nil { - result = append(result, v.joinWords(curList)) - curList = nil - } - } - } - if curList != nil { - result = append(result, v.joinWords(curList)) - } - return result -} DELETED usecase/update_zettel.go Index: usecase/update_zettel.go ================================================================== --- usecase/update_zettel.go +++ /dev/null @@ -1,65 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "context" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/logger" -) - -// UpdateZettelPort is the interface used by this use case. -type UpdateZettelPort interface { - // GetZettel retrieves a specific zettel. - GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) - - // UpdateZettel updates an existing zettel. - UpdateZettel(ctx context.Context, zettel domain.Zettel) error -} - -// UpdateZettel is the data for this use case. -type UpdateZettel struct { - log *logger.Logger - port UpdateZettelPort -} - -// NewUpdateZettel creates a new use case. -func NewUpdateZettel(log *logger.Logger, port UpdateZettelPort) UpdateZettel { - return UpdateZettel{log: log, port: port} -} - -// Run executes the use case. -func (uc *UpdateZettel) Run(ctx context.Context, zettel domain.Zettel, hasContent bool) error { - m := zettel.Meta - oldZettel, err := uc.port.GetZettel(box.NoEnrichContext(ctx), m.Zid) - if err != nil { - return err - } - if zettel.Equal(oldZettel, false) { - return nil - } - m.SetNow(api.KeyModified) - m.YamlSep = oldZettel.Meta.YamlSep - if m.Zid == id.ConfigurationZid { - m.Set(api.KeySyntax, api.ValueSyntaxNone) - } - if !hasContent { - zettel.Content = oldZettel.Content - } - zettel.Content.TrimSpace() - err = uc.port.UpdateZettel(ctx, zettel) - uc.log.Sense().User(ctx).Zid(m.Zid).Err(err).Msg("Update zettel") - return err -} DELETED usecase/usecase.go Index: usecase/usecase.go ================================================================== --- usecase/usecase.go +++ /dev/null @@ -1,12 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package usecase provides (business) use cases for the zettelstore. -package usecase DELETED usecase/version.go Index: usecase/version.go ================================================================== --- usecase/version.go +++ /dev/null @@ -1,76 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package usecase - -import ( - "regexp" - "strconv" - - "zettelstore.de/z/kernel" -) - -// Version is the data for this use case. -type Version struct { - vr VersionResult -} - -// NewVersion creates a new use case. -func NewVersion(version string) Version { - return Version{calculateVersionResult(version)} -} - -// VersionResult is the data structure returned by this usecase. -type VersionResult struct { - Major int - Minor int - Patch int - Info string - Hash string -} - -var invalidVersion = VersionResult{ - Major: -1, - Minor: -1, - Patch: -1, - Info: kernel.CoreDefaultVersion, - Hash: "", -} - -var reVersion = regexp.MustCompile(`^(\d+)\.(\d+)(\.(\d+))?(-(([[:alnum:]]|-)+))?(\+(([[:alnum:]])+(-[[:alnum:]]+)?))?`) - -func calculateVersionResult(version string) VersionResult { - match := reVersion.FindStringSubmatch(version) - if len(match) < 12 { - return invalidVersion - } - major, err := strconv.Atoi(match[1]) - if err != nil { - return invalidVersion - } - minor, err := strconv.Atoi(match[2]) - if err != nil { - return invalidVersion - } - patch, err := strconv.Atoi(match[4]) - if err != nil { - patch = 0 - } - return VersionResult{ - Major: major, - Minor: minor, - Patch: patch, - Info: match[6], - Hash: match[9], - } -} - -// Run executes the use case. -func (uc Version) Run() VersionResult { return uc.vr } DELETED web/adapter/api/api.go Index: web/adapter/api/api.go ================================================================== --- web/adapter/api/api.go +++ /dev/null @@ -1,118 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import ( - "bytes" - "context" - "net/http" - "time" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" - "zettelstore.de/z/web/adapter" - "zettelstore.de/z/web/server" -) - -// API holds all data and methods for delivering API call results. -type API struct { - log *logger.Logger - b server.Builder - authz auth.AuthzManager - token auth.TokenManager - auth server.Auth - rtConfig config.Config - policy auth.Policy - - tokenLifetime time.Duration -} - -// New creates a new API object. -func New(log *logger.Logger, b server.Builder, authz auth.AuthzManager, token auth.TokenManager, - auth server.Auth, rtConfig config.Config, pol auth.Policy) *API { - a := &API{ - log: log, - b: b, - authz: authz, - token: token, - auth: auth, - rtConfig: rtConfig, - policy: pol, - - tokenLifetime: kernel.Main.GetConfig(kernel.WebService, kernel.WebTokenLifetimeAPI).(time.Duration), - } - return a -} - -// GetURLPrefix returns the configured URL prefix of the web server. -func (a *API) GetURLPrefix() string { return a.b.GetURLPrefix() } - -// NewURLBuilder creates a new URL builder object with the given key. -func (a *API) NewURLBuilder(key byte) *api.URLBuilder { return a.b.NewURLBuilder(key) } - -func (a *API) getAuthData(ctx context.Context) *server.AuthData { - return a.auth.GetAuthData(ctx) -} -func (a *API) withAuth() bool { return a.authz.WithAuth() } -func (a *API) getToken(ident *meta.Meta) ([]byte, error) { - return a.token.GetToken(ident, a.tokenLifetime, auth.KindJSON) -} - -func (a *API) reportUsecaseError(w http.ResponseWriter, err error) { - code, text := adapter.CodeMessageFromError(err) - if code == http.StatusInternalServerError { - a.log.IfErr(err).Msg(text) - http.Error(w, http.StatusText(code), code) - return - } - // TODO: must call PrepareHeader somehow - http.Error(w, text, code) -} - -func writeBuffer(w http.ResponseWriter, buf *bytes.Buffer, contentType string) error { - if buf.Len() == 0 { - w.WriteHeader(http.StatusNoContent) - return nil - } - adapter.PrepareHeader(w, contentType) - w.WriteHeader(http.StatusOK) - _, err := w.Write(buf.Bytes()) - return err -} - -func (a *API) getRights(ctx context.Context, m *meta.Meta) (result api.ZettelRights) { - pol := a.policy - user := a.auth.GetUser(ctx) - if pol.CanCreate(user, m) { - result |= api.ZettelCanCreate - } - if pol.CanRead(user, m) { - result |= api.ZettelCanRead - } - if pol.CanWrite(user, m, m) { - result |= api.ZettelCanWrite - } - if pol.CanRename(user, m) { - result |= api.ZettelCanRename - } - if pol.CanDelete(user, m) { - result |= api.ZettelCanDelete - } - if result == 0 { - return api.ZettelCanNone - } - return result -} DELETED web/adapter/api/command.go Index: web/adapter/api/command.go ================================================================== --- web/adapter/api/command.go +++ /dev/null @@ -1,58 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package api - -import ( - "context" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/usecase" -) - -// MakePostCommandHandler creates a new HTTP handler to execute certain commands. -func (a *API) MakePostCommandHandler( - ucIsAuth *usecase.IsAuthenticated, - ucRefresh *usecase.Refresh, -) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - q := r.URL.Query() - cmd := q.Get(api.QueryKeyCommand) - switch api.Command(cmd) { - case api.CommandAuthenticated: - handleIsAuthenticated(ctx, w, ucIsAuth) - return - case api.CommandRefresh: - err := ucRefresh.Run(ctx) - if err != nil { - a.reportUsecaseError(w, err) - return - } - w.WriteHeader(http.StatusNoContent) - return - } - http.Error(w, "Unknown command", http.StatusBadRequest) - } -} - -func handleIsAuthenticated(ctx context.Context, w http.ResponseWriter, ucIsAuth *usecase.IsAuthenticated) { - switch ucIsAuth.Run(ctx) { - case usecase.IsAuthenticatedDisabled: - w.WriteHeader(http.StatusOK) - case usecase.IsAuthenticatedAndValid: - w.WriteHeader(http.StatusNoContent) - case usecase.IsAuthenticatedAndInvalid: - w.WriteHeader(http.StatusUnauthorized) - default: - http.Error(w, "Unexpected result value", http.StatusInternalServerError) - } -} DELETED web/adapter/api/content_type.go Index: web/adapter/api/content_type.go ================================================================== --- web/adapter/api/content_type.go +++ /dev/null @@ -1,60 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import "zettelstore.de/c/api" - -const ( - ctHTML = "text/html; charset=utf-8" - ctJSON = "application/json" - ctPlainText = "text/plain; charset=utf-8" - ctSVG = "image/svg+xml" -) - -var mapEncoding2CT = map[api.EncodingEnum]string{ - api.EncoderHTML: ctHTML, - api.EncoderSexpr: ctPlainText, - api.EncoderText: ctPlainText, - api.EncoderZJSON: ctJSON, - api.EncoderZmk: ctPlainText, -} - -func encoding2ContentType(enc api.EncodingEnum) string { - if ct, ok := mapEncoding2CT[enc]; ok { - return ct - } - return "application/octet-stream" -} - -var mapSyntax2CT = map[string]string{ - "css": "text/css; charset=utf-8", - api.ValueSyntaxGif: "image/gif", - api.ValueSyntaxHTML: "text/html; charset=utf-8", - "jpeg": "image/jpeg", - "jpg": "image/jpeg", - "js": "text/javascript; charset=utf-8", - "pdf": "application/pdf", - "png": "image/png", - api.ValueSyntaxSVG: ctSVG, - "xml": "text/xml; charset=utf-8", - api.ValueSyntaxZmk: "text/x-zmk; charset=utf-8", - "plain": ctPlainText, - api.ValueSyntaxText: ctPlainText, - "markdown": "text/markdown; charset=utf-8", - "md": "text/markdown; charset=utf-8", - "mustache": ctPlainText, -} - -func syntax2contentType(syntax string) (string, bool) { - contentType, ok := mapSyntax2CT[syntax] - return contentType, ok -} DELETED web/adapter/api/create_zettel.go Index: web/adapter/api/create_zettel.go ================================================================== --- web/adapter/api/create_zettel.go +++ /dev/null @@ -1,78 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package api - -import ( - "bytes" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakePostCreatePlainZettelHandler creates a new HTTP handler to store content of -// an existing zettel. -func (a *API) MakePostCreatePlainZettelHandler(createZettel *usecase.CreateZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - zettel, err := buildZettelFromPlainData(r, id.Invalid) - if err != nil { - a.reportUsecaseError(w, adapter.NewErrBadRequest(err.Error())) - return - } - - newZid, err := createZettel.Run(ctx, zettel) - if err != nil { - a.reportUsecaseError(w, err) - return - } - u := a.NewURLBuilder('z').SetZid(api.ZettelID(newZid.String())).String() - h := adapter.PrepareHeader(w, ctPlainText) - h.Set(api.HeaderLocation, u) - w.WriteHeader(http.StatusCreated) - _, err = w.Write(newZid.Bytes()) - a.log.IfErr(err).Zid(newZid).Msg("Create Plain Zettel") - } -} - -// MakePostCreateZettelHandler creates a new HTTP handler to store content of -// an existing zettel. -func (a *API) MakePostCreateZettelHandler(createZettel *usecase.CreateZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - zettel, err := buildZettelFromJSONData(r, id.Invalid) - if err != nil { - a.reportUsecaseError(w, adapter.NewErrBadRequest(err.Error())) - return - } - - newZid, err := createZettel.Run(ctx, zettel) - if err != nil { - a.reportUsecaseError(w, err) - return - } - var buf bytes.Buffer - err = encodeJSONData(&buf, api.ZidJSON{ID: api.ZettelID(newZid.String())}) - if err != nil { - a.log.Fatal().Err(err).Zid(newZid).Msg("Unable to store new Zid in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - - h := adapter.PrepareHeader(w, ctJSON) - h.Set(api.HeaderLocation, a.NewURLBuilder('j').SetZid(api.ZettelID(newZid.String())).String()) - w.WriteHeader(http.StatusCreated) - _, err = w.Write(buf.Bytes()) - a.log.IfErr(err).Zid(newZid).Msg("Create JSON Zettel") - } -} DELETED web/adapter/api/delete_zettel.go Index: web/adapter/api/delete_zettel.go ================================================================== --- web/adapter/api/delete_zettel.go +++ /dev/null @@ -1,35 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package api - -import ( - "net/http" - - "zettelstore.de/z/domain/id" - "zettelstore.de/z/usecase" -) - -// MakeDeleteZettelHandler creates a new HTTP handler to delete a zettel. -func (a *API) MakeDeleteZettelHandler(deleteZettel *usecase.DeleteZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - - if err = deleteZettel.Run(r.Context(), zid); err != nil { - a.reportUsecaseError(w, err) - return - } - w.WriteHeader(http.StatusNoContent) - } -} DELETED web/adapter/api/get_data.go Index: web/adapter/api/get_data.go ================================================================== --- web/adapter/api/get_data.go +++ /dev/null @@ -1,43 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package api - -import ( - "bytes" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/usecase" -) - -// MakeGetDataHandler creates a new HTTP handler to return zettelstore data. -func (a *API) MakeGetDataHandler(ucVersion usecase.Version) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - version := ucVersion.Run() - result := api.VersionJSON{ - Major: version.Major, - Minor: version.Minor, - Patch: version.Patch, - Info: version.Info, - Hash: version.Hash, - } - var buf bytes.Buffer - err := encodeJSONData(&buf, result) - if err != nil { - a.log.Fatal().Err(err).Msg("Unable to version info in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - - err = writeBuffer(w, &buf, ctJSON) - a.log.IfErr(err).Msg("Write Version Info") - } -} DELETED web/adapter/api/get_eval_zettel.go Index: web/adapter/api/get_eval_zettel.go ================================================================== --- web/adapter/api/get_eval_zettel.go +++ /dev/null @@ -1,46 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package api - -import ( - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/ast" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/encoder" - "zettelstore.de/z/usecase" -) - -// MakeGetEvalZettelHandler creates a new HTTP handler to return a evaluated zettel. -func (a *API) MakeGetEvalZettelHandler(evaluate usecase.Evaluate) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - - ctx := r.Context() - q := r.URL.Query() - enc, encStr := getEncoding(r, q, encoder.GetDefaultEncoding()) - part := getPart(q, partContent) - zn, err := evaluate.Run(ctx, zid, q.Get(api.KeySyntax)) - if err != nil { - a.reportUsecaseError(w, err) - return - } - evalMeta := func(value string) ast.InlineSlice { - return evaluate.RunMetadata(ctx, value) - } - a.writeEncodedZettelPart(w, zn, evalMeta, enc, encStr, part) - } -} DELETED web/adapter/api/get_lists.go Index: web/adapter/api/get_lists.go ================================================================== --- web/adapter/api/get_lists.go +++ /dev/null @@ -1,72 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import ( - "bytes" - "net/http" - "strconv" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/usecase" -) - -// MakeListMapMetaHandler creates a new HTTP handler to retrieve mappings of -// metadata values of a specific key to the list of zettel IDs, which contain -// this value. -func (a *API) MakeListMapMetaHandler(listRole usecase.ListRoles, listTags usecase.ListTags) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - var ar meta.Arrangement - query := r.URL.Query() - iMinCount, err := strconv.Atoi(query.Get(api.QueryKeyMin)) - if err != nil || iMinCount < 0 { - iMinCount = 0 - } - ctx := r.Context() - key := query.Get(api.QueryKeyKey) - switch key { - case api.KeyRole: - ar, err = listRole.Run(ctx) - case api.KeyTags: - ar, err = listTags.Run(ctx, iMinCount) - default: - a.log.Info().Str("key", key).Msg("illegal key for retrieving meta map") - http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) - return - } - if err != nil { - a.reportUsecaseError(w, err) - return - } - - mm := make(api.MapMeta, len(ar)) - for tag, metaList := range ar { - zidList := make([]api.ZettelID, 0, len(metaList)) - for _, m := range metaList { - zidList = append(zidList, api.ZettelID(m.Zid.String())) - } - mm[tag] = zidList - } - - var buf bytes.Buffer - err = encodeJSONData(&buf, api.MapListJSON{Map: mm}) - if err != nil { - a.log.Fatal().Err(err).Msg("Unable to store map list in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - - err = writeBuffer(w, &buf, ctJSON) - a.log.IfErr(err).Str("key", key).Msg("write meta map") - } -} DELETED web/adapter/api/get_order.go Index: web/adapter/api/get_order.go ================================================================== --- web/adapter/api/get_order.go +++ /dev/null @@ -1,41 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import ( - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/usecase" -) - -// MakeGetOrderHandler creates a new API handler to return zettel references -// of a given zettel. -func (a *API) MakeGetOrderHandler(zettelOrder usecase.ZettelOrder) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - ctx := r.Context() - q := r.URL.Query() - start, metas, err := zettelOrder.Run(ctx, zid, q.Get(api.KeySyntax)) - if err != nil { - a.reportUsecaseError(w, err) - return - } - err = a.writeMetaList(ctx, w, start, metas) - a.log.IfErr(err).Zid(zid).Msg("Write Zettel Order") - } -} DELETED web/adapter/api/get_parsed_zettel.go Index: web/adapter/api/get_parsed_zettel.go ================================================================== --- web/adapter/api/get_parsed_zettel.go +++ /dev/null @@ -1,81 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import ( - "bytes" - "fmt" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/ast" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/encoder" - "zettelstore.de/z/parser" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeGetParsedZettelHandler creates a new HTTP handler to return a parsed zettel. -func (a *API) MakeGetParsedZettelHandler(parseZettel usecase.ParseZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - - q := r.URL.Query() - enc, encStr := getEncoding(r, q, encoder.GetDefaultEncoding()) - part := getPart(q, partContent) - zn, err := parseZettel.Run(r.Context(), zid, q.Get(api.KeySyntax)) - if err != nil { - a.reportUsecaseError(w, err) - return - } - a.writeEncodedZettelPart(w, zn, parser.ParseMetadata, enc, encStr, part) - } -} - -func (a *API) writeEncodedZettelPart( - w http.ResponseWriter, zn *ast.ZettelNode, - evalMeta encoder.EvalMetaFunc, - enc api.EncodingEnum, encStr string, part partType, -) { - encdr := encoder.Create(enc) - if encdr == nil { - adapter.BadRequest(w, fmt.Sprintf("Zettel %q not available in encoding %q", zn.Meta.Zid.String(), encStr)) - return - } - var err error - var buf bytes.Buffer - switch part { - case partZettel: - _, err = encdr.WriteZettel(&buf, zn, evalMeta) - case partMeta: - _, err = encdr.WriteMeta(&buf, zn.InhMeta, evalMeta) - case partContent: - _, err = encdr.WriteContent(&buf, zn) - } - if err != nil { - a.log.Fatal().Err(err).Zid(zn.Zid).Msg("Unable to store data in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - if buf.Len() == 0 { - w.WriteHeader(http.StatusNoContent) - return - } - - err = writeBuffer(w, &buf, encoding2ContentType(enc)) - a.log.IfErr(err).Zid(zn.Zid).Msg("Write Encoded Zettel") -} DELETED web/adapter/api/get_unlinked_refs.go Index: web/adapter/api/get_unlinked_refs.go ================================================================== --- web/adapter/api/get_unlinked_refs.go +++ /dev/null @@ -1,90 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package api - -import ( - "bytes" - "net/http" - "strings" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/encoder/textenc" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeListUnlinkedMetaHandler creates a new HTTP handler for the use case "list unlinked references". -func (a *API) MakeListUnlinkedMetaHandler( - getMeta usecase.GetMeta, - unlinkedRefs usecase.UnlinkedReferences, - evaluate *usecase.Evaluate, -) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - ctx := r.Context() - zm, err := getMeta.Run(ctx, zid) - if err != nil { - a.reportUsecaseError(w, err) - return - } - - q := r.URL.Query() - phrase := q.Get(api.QueryKeyPhrase) - if phrase == "" { - if zmkTitle, found := zm.Get(api.KeyTitle); found { - isTitle := evaluate.RunMetadata(ctx, zmkTitle) - encdr := textenc.Create() - var b strings.Builder - _, err = encdr.WriteInlines(&b, &isTitle) - if err == nil { - phrase = b.String() - } - } - } - - metaList, err := unlinkedRefs.Run( - ctx, phrase, adapter.AddUnlinkedRefsToSearch(adapter.GetSearch(q), zm)) - if err != nil { - a.reportUsecaseError(w, err) - return - } - - result := api.ZidMetaRelatedList{ - ID: api.ZettelID(zid.String()), - Meta: zm.Map(), - Rights: a.getRights(ctx, zm), - List: make([]api.ZidMetaJSON, 0, len(metaList)), - } - for _, m := range metaList { - result.List = append(result.List, api.ZidMetaJSON{ - ID: api.ZettelID(m.Zid.String()), - Meta: m.Map(), - Rights: a.getRights(ctx, m), - }) - } - - var buf bytes.Buffer - err = encodeJSONData(&buf, result) - if err != nil { - a.log.Fatal().Err(err).Zid(zid).Msg("Unable to store unlinked references in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - - err = writeBuffer(w, &buf, ctJSON) - a.log.IfErr(err).Zid(zid).Msg("Write Unlinked References") - } -} DELETED web/adapter/api/get_zettel.go Index: web/adapter/api/get_zettel.go ================================================================== --- web/adapter/api/get_zettel.go +++ /dev/null @@ -1,139 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import ( - "bytes" - "context" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/usecase" -) - -// MakeGetZettelHandler creates a new HTTP handler to return a zettel. -func (a *API) MakeGetZettelHandler(getZettel usecase.GetZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - z, err := a.getZettelFromPath(ctx, w, r, getZettel) - if err != nil { - return - } - m := z.Meta - - var buf bytes.Buffer - content, encoding := z.Content.Encode() - err = encodeJSONData(&buf, api.ZettelJSON{ - ID: api.ZettelID(m.Zid.String()), - Meta: m.Map(), - Encoding: encoding, - Content: content, - Rights: a.getRights(ctx, m), - }) - if err != nil { - a.log.Fatal().Err(err).Zid(m.Zid).Msg("Unable to store zettel in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - - err = writeBuffer(w, &buf, ctJSON) - a.log.IfErr(err).Zid(m.Zid).Msg("Write JSON Zettel") - } -} - -// MakeGetPlainZettelHandler creates a new HTTP handler to return a zettel in plain formar -func (a *API) MakeGetPlainZettelHandler(getZettel usecase.GetZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - z, err := a.getZettelFromPath(box.NoEnrichContext(r.Context()), w, r, getZettel) - if err != nil { - return - } - - var buf bytes.Buffer - var contentType string - switch getPart(r.URL.Query(), partContent) { - case partZettel: - _, err = z.Meta.Write(&buf) - if err == nil { - err = buf.WriteByte('\n') - } - if err == nil { - _, err = z.Content.Write(&buf) - } - case partMeta: - contentType = ctPlainText - _, err = z.Meta.Write(&buf) - case partContent: - if ct, ok := syntax2contentType(z.Meta.GetDefault(api.KeySyntax, "")); ok { - contentType = ct - } - _, err = z.Content.Write(&buf) - } - if err != nil { - a.log.Fatal().Err(err).Zid(z.Meta.Zid).Msg("Unable to store plain zettel/part in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - err = writeBuffer(w, &buf, contentType) - a.log.IfErr(err).Zid(z.Meta.Zid).Msg("Write Plain Zettel") - } -} - -func (a *API) getZettelFromPath(ctx context.Context, w http.ResponseWriter, r *http.Request, getZettel usecase.GetZettel) (domain.Zettel, error) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return domain.Zettel{}, err - } - - z, err := getZettel.Run(ctx, zid) - if err != nil { - a.reportUsecaseError(w, err) - return domain.Zettel{}, err - } - return z, nil -} - -// MakeGetMetaHandler creates a new HTTP handler to return metadata of a zettel. -func (a *API) MakeGetMetaHandler(getMeta usecase.GetMeta) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - - ctx := r.Context() - m, err := getMeta.Run(ctx, zid) - if err != nil { - a.reportUsecaseError(w, err) - return - } - - var buf bytes.Buffer - err = encodeJSONData(&buf, api.MetaJSON{ - Meta: m.Map(), - Rights: a.getRights(ctx, m), - }) - if err != nil { - a.log.Fatal().Err(err).Zid(zid).Msg("Unable to store metadata in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - - err = writeBuffer(w, &buf, ctJSON) - a.log.IfErr(err).Zid(zid).Msg("Write JSON Meta") - } -} DELETED web/adapter/api/get_zettel_context.go Index: web/adapter/api/get_zettel_context.go ================================================================== --- web/adapter/api/get_zettel_context.go +++ /dev/null @@ -1,51 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import ( - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeZettelContextHandler creates a new HTTP handler for the use case "zettel context". -func (a *API) MakeZettelContextHandler(getContext usecase.ZettelContext) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - q := r.URL.Query() - dir := adapter.GetZCDirection(q.Get(api.QueryKeyDir)) - depth, ok := adapter.GetInteger(q, api.QueryKeyDepth) - if !ok || depth < 0 { - depth = 5 - } - limit, ok := adapter.GetInteger(q, api.QueryKeyLimit) - if !ok || limit < 0 { - limit = 200 - } - ctx := r.Context() - metaList, err := getContext.Run(ctx, zid, dir, depth, limit) - if err != nil { - a.reportUsecaseError(w, err) - return - } - - err = a.writeMetaList(ctx, w, metaList[0], metaList[1:]) - a.log.IfErr(err).Zid(zid).Msg("Write Context") - } -} DELETED web/adapter/api/get_zettel_list.go Index: web/adapter/api/get_zettel_list.go ================================================================== --- web/adapter/api/get_zettel_list.go +++ /dev/null @@ -1,86 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import ( - "bytes" - "fmt" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeListMetaHandler creates a new HTTP handler for the use case "list some zettel". -func (a *API) MakeListMetaHandler(listMeta usecase.ListMeta) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - q := r.URL.Query() - s := adapter.GetSearch(q) - metaList, err := listMeta.Run(ctx, s) - if err != nil { - a.reportUsecaseError(w, err) - return - } - - result := make([]api.ZidMetaJSON, 0, len(metaList)) - for _, m := range metaList { - result = append(result, api.ZidMetaJSON{ - ID: api.ZettelID(m.Zid.String()), - Meta: m.Map(), - Rights: a.getRights(ctx, m), - }) - } - - var buf bytes.Buffer - err = encodeJSONData(&buf, api.ZettelListJSON{ - Query: s.String(), - List: result, - }) - if err != nil { - a.log.Fatal().Err(err).Msg("Unable to store meta list in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - - err = writeBuffer(w, &buf, ctJSON) - a.log.IfErr(err).Msg("Write JSON List") - } -} - -// MakeListPlainHandler creates a new HTTP handler for the use case "list some zettel". -func (a *API) MakeListPlainHandler(listMeta usecase.ListMeta) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - q := r.URL.Query() - s := adapter.GetSearch(q) - metaList, err := listMeta.Run(ctx, s) - if err != nil { - a.reportUsecaseError(w, err) - return - } - - var buf bytes.Buffer - for _, m := range metaList { - _, err = fmt.Fprintln(&buf, m.Zid.String(), m.GetTitle()) - if err != nil { - a.log.Fatal().Err(err).Msg("Unable to store plain list in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - } - - err = writeBuffer(w, &buf, ctPlainText) - a.log.IfErr(err).Msg("Write Plain List") - } -} DELETED web/adapter/api/json.go Index: web/adapter/api/json.go ================================================================== --- web/adapter/api/json.go +++ /dev/null @@ -1,73 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import ( - "bytes" - "context" - "encoding/json" - "io" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -func encodeJSONData(w io.Writer, data interface{}) error { - enc := json.NewEncoder(w) - enc.SetEscapeHTML(false) - return enc.Encode(data) -} - -func (a *API) writeMetaList(ctx context.Context, w http.ResponseWriter, m *meta.Meta, metaList []*meta.Meta) error { - outList := make([]api.ZidMetaJSON, len(metaList)) - for i, m := range metaList { - outList[i].ID = api.ZettelID(m.Zid.String()) - outList[i].Meta = m.Map() - outList[i].Rights = a.getRights(ctx, m) - } - - var buf bytes.Buffer - err := encodeJSONData(&buf, api.ZidMetaRelatedList{ - ID: api.ZettelID(m.Zid.String()), - Meta: m.Map(), - Rights: a.getRights(ctx, m), - List: outList, - }) - if err != nil { - a.log.Fatal().Err(err).Zid(m.Zid).Msg("Unable to store meta list in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return nil - } - - return writeBuffer(w, &buf, ctJSON) -} - -func buildZettelFromJSONData(r *http.Request, zid id.Zid) (domain.Zettel, error) { - var zettel domain.Zettel - dec := json.NewDecoder(r.Body) - var zettelData api.ZettelDataJSON - if err := dec.Decode(&zettelData); err != nil { - return zettel, err - } - m := meta.New(zid) - for k, v := range zettelData.Meta { - m.Set(meta.RemoveNonGraphic(k), meta.RemoveNonGraphic(v)) - } - zettel.Meta = m - if err := zettel.Content.SetDecoded(zettelData.Content, zettelData.Encoding); err != nil { - return zettel, err - } - return zettel, nil -} DELETED web/adapter/api/login.go Index: web/adapter/api/login.go ================================================================== --- web/adapter/api/login.go +++ /dev/null @@ -1,112 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package api - -import ( - "bytes" - "encoding/json" - "net/http" - "time" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakePostLoginHandler creates a new HTTP handler to authenticate the given user via API. -func (a *API) MakePostLoginHandler(ucAuth *usecase.Authenticate) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if !a.withAuth() { - err := a.writeJSONToken(w, "freeaccess", 24*366*10*time.Hour) - a.log.IfErr(err).Msg("Login/free") - return - } - var token []byte - if ident, cred := retrieveIdentCred(r); ident != "" { - var err error - token, err = ucAuth.Run(r.Context(), ident, cred, a.tokenLifetime, auth.KindJSON) - if err != nil { - a.reportUsecaseError(w, err) - return - } - } - if len(token) == 0 { - w.Header().Set("WWW-Authenticate", `Bearer realm="Default"`) - http.Error(w, "Authentication failed", http.StatusUnauthorized) - return - } - - err := a.writeJSONToken(w, string(token), a.tokenLifetime) - a.log.IfErr(err).Msg("Login") - } -} - -func retrieveIdentCred(r *http.Request) (string, string) { - if ident, cred, ok := adapter.GetCredentialsViaForm(r); ok { - return ident, cred - } - if ident, cred, ok := r.BasicAuth(); ok { - return ident, cred - } - return "", "" -} - -func (a *API) writeJSONToken(w http.ResponseWriter, token string, lifetime time.Duration) error { - var buf bytes.Buffer - je := json.NewEncoder(&buf) - err := je.Encode(api.AuthJSON{ - Token: token, - Type: "Bearer", - Expires: int(lifetime / time.Second), - }) - if err != nil { - a.log.Fatal().Err(err).Msg("Unable to store token in buffer") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return nil - } - - return writeBuffer(w, &buf, ctJSON) -} - -// MakeRenewAuthHandler creates a new HTTP handler to renew the authenticate of a user. -func (a *API) MakeRenewAuthHandler() http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - if !a.withAuth() { - err := a.writeJSONToken(w, "freeaccess", 24*366*10*time.Hour) - a.log.IfErr(err).Msg("Refresh/free") - return - } - authData := a.getAuthData(ctx) - if authData == nil || len(authData.Token) == 0 || authData.User == nil { - adapter.BadRequest(w, "Not authenticated") - return - } - totalLifetime := authData.Expires.Sub(authData.Issued) - currentLifetime := authData.Now.Sub(authData.Issued) - // If we are in the first quarter of the tokens lifetime, return the token - if currentLifetime*4 < totalLifetime { - err := a.writeJSONToken(w, string(authData.Token), totalLifetime-currentLifetime) - a.log.IfErr(err).Msg("Write old token") - return - } - - // Token is a little bit aged. Create a new one - token, err := a.getToken(authData.User) - if err != nil { - a.reportUsecaseError(w, err) - return - } - err = a.writeJSONToken(w, string(token), a.tokenLifetime) - a.log.IfErr(err).Msg("Write renewed token") - } -} DELETED web/adapter/api/rename_zettel.go Index: web/adapter/api/rename_zettel.go ================================================================== --- web/adapter/api/rename_zettel.go +++ /dev/null @@ -1,67 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package api - -import ( - "net/http" - "net/url" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/usecase" -) - -// MakeRenameZettelHandler creates a new HTTP handler to update a zettel. -func (a *API) MakeRenameZettelHandler(renameZettel *usecase.RenameZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - newZid, found := getDestinationZid(r) - if !found { - http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) - return - } - if err = renameZettel.Run(r.Context(), zid, newZid); err != nil { - a.reportUsecaseError(w, err) - return - } - w.WriteHeader(http.StatusNoContent) - } -} - -func getDestinationZid(r *http.Request) (id.Zid, bool) { - if values, ok := r.Header[api.HeaderDestination]; ok { - for _, value := range values { - if zid, ok2 := getZidFromURL(value); ok2 { - return zid, true - } - } - } - return id.Invalid, false -} - -func getZidFromURL(val string) (id.Zid, bool) { - u, err := url.Parse(val) - if err != nil { - return id.Invalid, false - } - if len(u.Path) < len(api.ZidVersion) { - return id.Invalid, false - } - zid, err := id.Parse(u.Path[len(u.Path)-len(api.ZidVersion):]) - if err != nil { - return id.Invalid, false - } - return zid, true -} DELETED web/adapter/api/request.go Index: web/adapter/api/request.go ================================================================== --- web/adapter/api/request.go +++ /dev/null @@ -1,116 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package api provides api handlers for web requests. -package api - -import ( - "io" - "net/http" - "net/url" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/input" -) - -// getEncoding returns the data encoding selected by the caller. -func getEncoding(r *http.Request, q url.Values, defEncoding api.EncodingEnum) (api.EncodingEnum, string) { - encoding := q.Get(api.QueryKeyEncoding) - if len(encoding) > 0 { - return api.Encoder(encoding), encoding - } - if enc, ok := getOneEncoding(r, api.HeaderAccept); ok { - return api.Encoder(enc), enc - } - if enc, ok := getOneEncoding(r, api.HeaderContentType); ok { - return api.Encoder(enc), enc - } - return defEncoding, defEncoding.String() -} - -func getOneEncoding(r *http.Request, key string) (string, bool) { - if values, ok := r.Header[key]; ok { - for _, value := range values { - if enc, ok2 := contentType2encoding(value); ok2 { - return enc, true - } - } - } - return "", false -} - -var mapCT2encoding = map[string]string{ - "application/json": "json", - "text/html": api.EncodingHTML, -} - -func contentType2encoding(contentType string) (string, bool) { - // TODO: only check before first ';' - enc, ok := mapCT2encoding[contentType] - return enc, ok -} - -type partType int - -const ( - _ partType = iota - partMeta - partContent - partZettel -) - -var partMap = map[string]partType{ - api.PartMeta: partMeta, - api.PartContent: partContent, - api.PartZettel: partZettel, -} - -func getPart(q url.Values, defPart partType) partType { - if part, ok := partMap[q.Get(api.QueryKeyPart)]; ok { - return part - } - return defPart -} - -func (p partType) String() string { - switch p { - case partMeta: - return "meta" - case partContent: - return "content" - case partZettel: - return "zettel" - } - return "" -} - -func (p partType) DefString(defPart partType) string { - if p == defPart { - return "" - } - return p.String() -} - -func buildZettelFromPlainData(r *http.Request, zid id.Zid) (domain.Zettel, error) { - b, err := io.ReadAll(r.Body) - if err != nil { - return domain.Zettel{}, err - } - inp := input.NewInput(b) - m := meta.NewFromInput(zid, inp) - return domain.Zettel{ - Meta: m, - Content: domain.NewContent(inp.Src[inp.Pos:]), - }, nil - -} DELETED web/adapter/api/update_zettel.go Index: web/adapter/api/update_zettel.go ================================================================== --- web/adapter/api/update_zettel.go +++ /dev/null @@ -1,61 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package api - -import ( - "net/http" - - "zettelstore.de/z/domain/id" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeUpdatePlainZettelHandler creates a new HTTP handler to update a zettel. -func (a *API) MakeUpdatePlainZettelHandler(updateZettel *usecase.UpdateZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - zettel, err := buildZettelFromPlainData(r, zid) - if err != nil { - a.reportUsecaseError(w, adapter.NewErrBadRequest(err.Error())) - return - } - if err = updateZettel.Run(r.Context(), zettel, true); err != nil { - a.reportUsecaseError(w, err) - return - } - w.WriteHeader(http.StatusNoContent) - } -} - -// MakeUpdateZettelHandler creates a new HTTP handler to update a zettel. -func (a *API) MakeUpdateZettelHandler(updateZettel *usecase.UpdateZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - http.NotFound(w, r) - return - } - zettel, err := buildZettelFromJSONData(r, zid) - if err != nil { - a.reportUsecaseError(w, adapter.NewErrBadRequest(err.Error())) - return - } - if err = updateZettel.Run(r.Context(), zettel, true); err != nil { - a.reportUsecaseError(w, err) - return - } - w.WriteHeader(http.StatusNoContent) - } -} DELETED web/adapter/errors.go Index: web/adapter/errors.go ================================================================== --- web/adapter/errors.go +++ /dev/null @@ -1,29 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package adapter provides handlers for web requests. -package adapter - -import "net/http" - -// BadRequest signals HTTP status code 400. -func BadRequest(w http.ResponseWriter, text string) { - http.Error(w, text, http.StatusBadRequest) -} - -// Forbidden signals HTTP status code 403. -func Forbidden(w http.ResponseWriter, text string) { - http.Error(w, text, http.StatusForbidden) -} - -// NotFound signals HTTP status code 404. -func NotFound(w http.ResponseWriter, text string) { - http.Error(w, text, http.StatusNotFound) -} DELETED web/adapter/request.go Index: web/adapter/request.go ================================================================== --- web/adapter/request.go +++ /dev/null @@ -1,142 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package adapter - -import ( - "net/http" - "net/url" - "strconv" - "strings" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/kernel" - "zettelstore.de/z/search" - "zettelstore.de/z/usecase" -) - -// GetCredentialsViaForm retrieves the authentication credentions from a form. -func GetCredentialsViaForm(r *http.Request) (ident, cred string, ok bool) { - err := r.ParseForm() - if err != nil { - kernel.Main.GetLogger(kernel.WebService).Info().Err(err).Msg("Unable to parse form") - return "", "", false - } - - ident = strings.TrimSpace(r.PostFormValue("username")) - cred = r.PostFormValue("password") - if ident == "" { - return "", "", false - } - return ident, cred, true -} - -// GetInteger returns the integer value of the named query key. -func GetInteger(q url.Values, key string) (int, bool) { - s := q.Get(key) - if s != "" { - if val, err := strconv.Atoi(s); err == nil { - return val, true - } - } - return 0, false -} - -// GetSearch retrieves the specified search and sorting options from a query. -func GetSearch(q url.Values) (s *search.Search) { - for key, values := range q { - switch key { - case api.QueryKeySort, api.QueryKeyOrder: - s = extractOrderFromQuery(values, s) - case api.QueryKeyOffset: - s = extractOffsetFromQuery(values, s) - case api.QueryKeyLimit: - s = extractLimitFromQuery(values, s) - case api.QueryKeyNegate: - s = s.SetNegate() - case api.QueryKeySearch: - s = setCleanedQueryValues(s, "", values) - default: - if meta.KeyIsValid(key) { - s = setCleanedQueryValues(s, key, values) - } - } - } - return s -} - -func extractOrderFromQuery(values []string, s *search.Search) *search.Search { - if len(values) > 0 { - descending := false - sortkey := values[0] - if strings.HasPrefix(sortkey, "-") { - descending = true - sortkey = sortkey[1:] - } - if meta.KeyIsValid(sortkey) || sortkey == search.RandomOrder { - s = s.AddOrder(sortkey, descending) - } - } - return s -} - -func extractOffsetFromQuery(values []string, s *search.Search) *search.Search { - if len(values) > 0 { - if offset, err := strconv.Atoi(values[0]); err == nil && offset > 0 { - s = s.SetOffset(offset) - } - } - return s -} - -func extractLimitFromQuery(values []string, s *search.Search) *search.Search { - if len(values) > 0 { - if limit, err := strconv.Atoi(values[0]); err == nil && limit > 0 { - s = s.SetLimit(limit) - } - } - return s -} - -func setCleanedQueryValues(s *search.Search, key string, values []string) *search.Search { - for _, val := range values { - s = s.AddExpr(key, val) - } - return s -} - -// GetZCDirection returns a direction value for a given string. -func GetZCDirection(s string) usecase.ZettelContextDirection { - switch s { - case api.DirBackward: - return usecase.ZettelContextBackward - case api.DirForward: - return usecase.ZettelContextForward - } - return usecase.ZettelContextBoth -} - -// AddUnlinkedRefsToSearch inspects metadata and enhances the given search to ignore -// some zettel identifier. -func AddUnlinkedRefsToSearch(s *search.Search, m *meta.Meta) *search.Search { - s = s.AddExpr(api.KeyID, "!="+m.Zid.String()) - for _, pair := range m.ComputedPairsRest() { - switch meta.Type(pair.Key) { - case meta.TypeID: - s = s.AddExpr(api.KeyID, "!="+pair.Value) - case meta.TypeIDSet: - for _, value := range meta.ListFromValue(pair.Value) { - s = s.AddExpr(api.KeyID, "!="+value) - } - } - } - return s -} DELETED web/adapter/response.go Index: web/adapter/response.go ================================================================== --- web/adapter/response.go +++ /dev/null @@ -1,70 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package adapter provides handlers for web requests. -package adapter - -import ( - "errors" - "fmt" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/usecase" -) - -// PrepareHeader sets the HTTP header to defined values. -func PrepareHeader(w http.ResponseWriter, contentType string) http.Header { - h := w.Header() - if contentType != "" { - h.Set(api.HeaderContentType, contentType) - } - return h -} - -// ErrBadRequest is returned if the caller made an invalid HTTP request. -type ErrBadRequest struct { - Text string -} - -// NewErrBadRequest creates an new bad request error. -func NewErrBadRequest(text string) error { return &ErrBadRequest{Text: text} } - -func (err *ErrBadRequest) Error() string { return err.Text } - -// CodeMessageFromError returns an appropriate HTTP status code and text from a given error. -func CodeMessageFromError(err error) (int, string) { - if err == box.ErrNotFound { - return http.StatusNotFound, http.StatusText(http.StatusNotFound) - } - if err1, ok := err.(*box.ErrNotAllowed); ok { - return http.StatusForbidden, err1.Error() - } - if err1, ok := err.(*box.ErrInvalidID); ok { - return http.StatusBadRequest, fmt.Sprintf("Zettel-ID %q not appropriate in this context", err1.Zid) - } - if err1, ok := err.(*usecase.ErrZidInUse); ok { - return http.StatusBadRequest, fmt.Sprintf("Zettel-ID %q already in use", err1.Zid) - } - if err1, ok := err.(*ErrBadRequest); ok { - return http.StatusBadRequest, err1.Text - } - if errors.Is(err, box.ErrStopped) { - return http.StatusInternalServerError, fmt.Sprintf("Zettelstore not operational: %v", err) - } - if errors.Is(err, box.ErrConflict) { - return http.StatusConflict, "Zettelstore operations conflicted" - } - if errors.Is(err, box.ErrCapacity) { - return http.StatusInsufficientStorage, "Zettelstore reached one of its storage limits" - } - return http.StatusInternalServerError, err.Error() -} DELETED web/adapter/webui/const.go Index: web/adapter/webui/const.go ================================================================== --- web/adapter/webui/const.go +++ /dev/null @@ -1,44 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -// WebUI related constants. - -const queryKeyAction = "action" - -// Values for queryKeyAction -const ( - valueActionCopy = "copy" - valueActionFolge = "folge" - valueActionNew = "new" -) - -// Enumeration for queryKeyAction -type createAction uint8 - -const ( - actionCopy createAction = iota - actionFolge - actionNew -) - -func getCreateAction(s string) createAction { - switch s { - case valueActionCopy: - return actionCopy - case valueActionFolge: - return actionFolge - case valueActionNew: - return actionNew - default: - return actionCopy - } -} DELETED web/adapter/webui/create_zettel.go Index: web/adapter/webui/create_zettel.go ================================================================== --- web/adapter/webui/create_zettel.go +++ /dev/null @@ -1,141 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "context" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/config" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/parser" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeGetCreateZettelHandler creates a new HTTP handler to display the -// HTML edit view for the various zettel creation methods. -func (wui *WebUI) MakeGetCreateZettelHandler( - getZettel usecase.GetZettel, createZettel *usecase.CreateZettel, - ucListRoles usecase.ListRoles, ucListSyntax usecase.ListSyntax) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - q := r.URL.Query() - op := getCreateAction(q.Get(queryKeyAction)) - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - origZettel, err := getZettel.Run(box.NoEnrichContext(ctx), zid) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - - roleData, syntaxData := retrieveDataLists(ctx, ucListRoles, ucListSyntax) - switch op { - case actionCopy: - wui.renderZettelForm(ctx, w, createZettel.PrepareCopy(origZettel), "Copy Zettel", "Copy Zettel", roleData, syntaxData) - case actionFolge: - wui.renderZettelForm(ctx, w, createZettel.PrepareFolge(origZettel), "Folge Zettel", "Folgezettel", roleData, syntaxData) - case actionNew: - m := origZettel.Meta - title := parser.ParseMetadata(m.GetTitle()) - textTitle, err2 := encodeInlinesText(&title, wui.gentext) - if err2 != nil { - wui.reportError(ctx, w, err2) - return - } - htmlTitle, err2 := wui.getSimpleHTMLEncoder().InlinesString(&title, false) - if err2 != nil { - wui.reportError(ctx, w, err2) - return - } - wui.renderZettelForm(ctx, w, createZettel.PrepareNew(origZettel), textTitle, htmlTitle, roleData, syntaxData) - } - } -} - -func retrieveDataLists(ctx context.Context, ucListRoles usecase.ListRoles, ucListSyntax usecase.ListSyntax) ([]string, []string) { - roleData := dataListFromArrangement(ucListRoles.Run(ctx)) - syntaxData := dataListFromArrangement(ucListSyntax.Run(ctx)) - return roleData, syntaxData -} - -func dataListFromArrangement(ar meta.Arrangement, err error) []string { - if err == nil { - l := ar.Counted() - l.SortByCount() - return l.Categories() - } - return nil -} - -func (wui *WebUI) renderZettelForm( - ctx context.Context, - w http.ResponseWriter, - zettel domain.Zettel, - title, heading string, - roleData []string, - syntaxData []string, -) { - user := wui.getUser(ctx) - m := zettel.Meta - var base baseData - wui.makeBaseData(ctx, config.GetLang(m, wui.rtConfig), title, "", user, &base) - wui.renderTemplate(ctx, w, id.FormTemplateZid, &base, formZettelData{ - Heading: heading, - MetaTitle: m.GetDefault(api.KeyTitle, ""), - MetaTags: m.GetDefault(api.KeyTags, ""), - MetaRole: m.GetDefault(api.KeyRole, ""), - HasRoleData: len(roleData) > 0, - RoleData: roleData, - HasSyntaxData: len(syntaxData) > 0, - SyntaxData: syntaxData, - MetaSyntax: m.GetDefault(api.KeySyntax, ""), - MetaPairsRest: m.PairsRest(), - IsTextContent: !zettel.Content.IsBinary(), - Content: zettel.Content.AsString(), - }) -} - -// MakePostCreateZettelHandler creates a new HTTP handler to store content of -// an existing zettel. -func (wui *WebUI) MakePostCreateZettelHandler(createZettel *usecase.CreateZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - reEdit, zettel, hasContent, err := parseZettelForm(r, id.Invalid) - if err != nil { - wui.reportError(ctx, w, adapter.NewErrBadRequest("Unable to read form data")) - return - } - if !hasContent { - wui.reportError(ctx, w, adapter.NewErrBadRequest("Content is missing")) - return - } - - newZid, err := createZettel.Run(ctx, zettel) - if err != nil { - wui.reportError(ctx, w, err) - return - } - if reEdit { - wui.redirectFound(w, r, wui.NewURLBuilder('e').SetZid(api.ZettelID(newZid.String()))) - } else { - wui.redirectFound(w, r, wui.NewURLBuilder('h').SetZid(api.ZettelID(newZid.String()))) - } - } -} DELETED web/adapter/webui/delete_zettel.go Index: web/adapter/webui/delete_zettel.go ================================================================== --- web/adapter/webui/delete_zettel.go +++ /dev/null @@ -1,135 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/c/maps" - "zettelstore.de/z/box" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/strfun" - "zettelstore.de/z/usecase" -) - -// MakeGetDeleteZettelHandler creates a new HTTP handler to display the -// HTML delete view of a zettel. -func (wui *WebUI) MakeGetDeleteZettelHandler( - getMeta usecase.GetMeta, - getAllMeta usecase.GetAllMeta, - evaluate *usecase.Evaluate, -) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - - ms, err := getAllMeta.Run(ctx, zid) - if err != nil { - wui.reportError(ctx, w, err) - return - } - m := ms[0] - - var shadowedBox string - var incomingLinks []simpleLink - if len(ms) > 1 { - shadowedBox = ms[1].GetDefault(api.KeyBoxNumber, "???") - } else { - getTextTitle := wui.makeGetTextTitle(ctx, getMeta, evaluate) - incomingLinks = wui.encodeIncoming(m, getTextTitle) - } - uselessFiles := retrieveUselessFiles(m) - - user := wui.getUser(ctx) - var base baseData - wui.makeBaseData(ctx, config.GetLang(m, wui.rtConfig), "Delete Zettel "+m.Zid.String(), "", user, &base) - wui.renderTemplate(ctx, w, id.DeleteTemplateZid, &base, struct { - Zid string - MetaPairs []meta.Pair - HasShadows bool - ShadowedBox string - HasIncoming bool - Incoming []simpleLink - HasUselessFiles bool - UselessFiles []string - }{ - Zid: zid.String(), - MetaPairs: m.ComputedPairs(), - HasShadows: shadowedBox != "", - ShadowedBox: shadowedBox, - HasIncoming: len(incomingLinks) > 0, - Incoming: incomingLinks, - HasUselessFiles: len(uselessFiles) > 0, - UselessFiles: uselessFiles, - }) - } -} - -func retrieveUselessFiles(m *meta.Meta) []string { - if val, found := m.Get(api.KeyUselessFiles); found { - return []string{val} - } - return nil -} - -// MakePostDeleteZettelHandler creates a new HTTP handler to delete a zettel. -func (wui *WebUI) MakePostDeleteZettelHandler(deleteZettel *usecase.DeleteZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - - if err = deleteZettel.Run(r.Context(), zid); err != nil { - wui.reportError(ctx, w, err) - return - } - wui.redirectFound(w, r, wui.NewURLBuilder('/')) - } -} - -func (wui *WebUI) encodeIncoming(m *meta.Meta, getTextTitle getTextTitleFunc) []simpleLink { - zidMap := make(strfun.Set) - addListValues(zidMap, m, api.KeyBackward) - for _, kd := range meta.GetSortedKeyDescriptions() { - inverseKey := kd.Inverse - if inverseKey == "" { - continue - } - ikd := meta.GetDescription(inverseKey) - switch ikd.Type { - case meta.TypeID: - if val, ok := m.Get(inverseKey); ok { - zidMap.Set(val) - } - case meta.TypeIDSet: - addListValues(zidMap, m, inverseKey) - } - } - return wui.encodeZidLinks(maps.Keys(zidMap), getTextTitle) -} - -func addListValues(zidMap strfun.Set, m *meta.Meta, key string) { - if values, ok := m.GetList(key); ok { - for _, val := range values { - zidMap.Set(val) - } - } -} DELETED web/adapter/webui/edit_zettel.go Index: web/adapter/webui/edit_zettel.go ================================================================== --- web/adapter/webui/edit_zettel.go +++ /dev/null @@ -1,73 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeEditGetZettelHandler creates a new HTTP handler to display the -// HTML edit view of a zettel. -func (wui *WebUI) MakeEditGetZettelHandler(getZettel usecase.GetZettel, ucListRoles usecase.ListRoles, ucListSyntax usecase.ListSyntax) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - - zettel, err := getZettel.Run(box.NoEnrichContext(ctx), zid) - if err != nil { - wui.reportError(ctx, w, err) - return - } - - roleData, syntaxData := retrieveDataLists(ctx, ucListRoles, ucListSyntax) - wui.renderZettelForm(ctx, w, zettel, "Edit Zettel", "Edit Zettel", roleData, syntaxData) - } -} - -// MakeEditSetZettelHandler creates a new HTTP handler to store content of -// an existing zettel. -func (wui *WebUI) MakeEditSetZettelHandler(updateZettel *usecase.UpdateZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - - reEdit, zettel, hasContent, err := parseZettelForm(r, zid) - if err != nil { - wui.reportError(ctx, w, adapter.NewErrBadRequest("Unable to read zettel form")) - return - } - - if err = updateZettel.Run(r.Context(), zettel, hasContent); err != nil { - wui.reportError(ctx, w, err) - return - } - - if reEdit { - wui.redirectFound(w, r, wui.NewURLBuilder('e').SetZid(api.ZettelID(zid.String()))) - } else { - wui.redirectFound(w, r, wui.NewURLBuilder('h').SetZid(api.ZettelID(zid.String()))) - } - } -} DELETED web/adapter/webui/forms.go Index: web/adapter/webui/forms.go ================================================================== --- web/adapter/webui/forms.go +++ /dev/null @@ -1,101 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "bytes" - "net/http" - "regexp" - "strings" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/input" -) - -type formZettelData struct { - Heading string - MetaTitle string - MetaRole string - HasRoleData bool - RoleData []string - HasSyntaxData bool - SyntaxData []string - MetaTags string - MetaSyntax string - MetaPairsRest []meta.Pair - IsTextContent bool - Content string -} - -var ( - bsCRLF = []byte{'\r', '\n'} - bsLF = []byte{'\n'} -) - -func parseZettelForm(r *http.Request, zid id.Zid) (bool, domain.Zettel, bool, error) { - err := r.ParseForm() - if err != nil { - return false, domain.Zettel{}, false, err - } - _, doSave := r.Form["save"] - - var m *meta.Meta - if postMeta, ok := trimmedFormValue(r, "meta"); ok { - m = meta.NewFromInput(zid, input.NewInput(removeEmptyLines([]byte(postMeta)))) - m.Sanitize() - } else { - m = meta.New(zid) - } - if postTitle, ok := trimmedFormValue(r, "title"); ok { - m.Set(api.KeyTitle, meta.RemoveNonGraphic(postTitle)) - } - if postTags, ok := trimmedFormValue(r, "tags"); ok { - if tags := strings.Fields(meta.RemoveNonGraphic(postTags)); len(tags) > 0 { - m.SetList(api.KeyTags, tags) - } - } - if postRole, ok := trimmedFormValue(r, "role"); ok { - m.Set(api.KeyRole, meta.RemoveNonGraphic(postRole)) - } - if postSyntax, ok := trimmedFormValue(r, "syntax"); ok { - m.Set(api.KeySyntax, meta.RemoveNonGraphic(postSyntax)) - } - if values, ok := r.PostForm["content"]; ok && len(values) > 0 { - return doSave, domain.Zettel{ - Meta: m, - Content: domain.NewContent(bytes.ReplaceAll([]byte(values[0]), bsCRLF, bsLF)), - }, true, nil - } - return doSave, domain.Zettel{ - Meta: m, - Content: domain.NewContent(nil), - }, false, nil -} - -func trimmedFormValue(r *http.Request, key string) (string, bool) { - if values, ok := r.PostForm[key]; ok && len(values) > 0 { - value := strings.TrimSpace(values[0]) - if len(value) > 0 { - return value, true - } - } - return "", false -} - -var reEmptyLines = regexp.MustCompile(`(\n|\r)+\s*(\n|\r)+`) - -func removeEmptyLines(s []byte) []byte { - b := bytes.TrimSpace(s) - return reEmptyLines.ReplaceAllLiteral(b, []byte{'\n'}) -} DELETED web/adapter/webui/forms_test.go Index: web/adapter/webui/forms_test.go ================================================================== --- web/adapter/webui/forms_test.go +++ /dev/null @@ -1,35 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import "testing" - -func TestRemoveEmptyLines(t *testing.T) { - t.Parallel() - testcases := []struct { - in string - exp string - }{ - {"", ""}, - {"a", "a"}, - {"\na", "a"}, - {"a\n", "a"}, - {"a\nb", "a\nb"}, - {"a\n\nb", "a\nb"}, - {"a\n \nb", "a\nb"}, - } - for i, tc := range testcases { - got := string(removeEmptyLines([]byte(tc.in))) - if got != tc.exp { - t.Errorf("%d/%q: expected=%q, got=%q", i, tc.in, tc.exp, got) - } - } -} DELETED web/adapter/webui/get_info.go Index: web/adapter/webui/get_info.go ================================================================== --- web/adapter/webui/get_info.go +++ /dev/null @@ -1,253 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "bytes" - "context" - "net/http" - "sort" - "strings" - - "zettelstore.de/c/api" - "zettelstore.de/z/ast" - "zettelstore.de/z/box" - "zettelstore.de/z/collect" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/encoder" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -type metaDataInfo struct { - Key string - Value string -} - -type matrixLine struct { - Header string - Elements []simpleLink -} - -// MakeGetInfoHandler creates a new HTTP handler for the use case "get zettel". -func (wui *WebUI) MakeGetInfoHandler( - parseZettel usecase.ParseZettel, - evaluate *usecase.Evaluate, - getMeta usecase.GetMeta, - getAllMeta usecase.GetAllMeta, - unlinkedRefs usecase.UnlinkedReferences, -) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - q := r.URL.Query() - - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - - zn, err := parseZettel.Run(ctx, zid, q.Get(api.KeySyntax)) - if err != nil { - wui.reportError(ctx, w, err) - return - } - - enc := wui.getSimpleHTMLEncoder() - pairs := zn.Meta.ComputedPairs() - metaData := make([]metaDataInfo, len(pairs)) - getTextTitle := wui.makeGetTextTitle(ctx, getMeta, evaluate) - for i, p := range pairs { - var buf bytes.Buffer - wui.writeHTMLMetaValue( - &buf, p.Key, p.Value, - getTextTitle, - func(val string) ast.InlineSlice { - return evaluate.RunMetadata(ctx, val) - }, - enc) - metaData[i] = metaDataInfo{p.Key, buf.String()} - } - summary := collect.References(zn) - locLinks, extLinks := splitLocExtLinks(append(summary.Links, summary.Embeds...)) - - textTitle := wui.encodeTitleAsText(ctx, zn.InhMeta, evaluate) - phrase := q.Get(api.QueryKeyPhrase) - if phrase == "" { - phrase = textTitle - } - phrase = strings.TrimSpace(phrase) - unlinkedMeta, err := unlinkedRefs.Run( - ctx, phrase, adapter.AddUnlinkedRefsToSearch(nil, zn.InhMeta)) - if err != nil { - wui.reportError(ctx, w, err) - return - } - unLinks := wui.buildHTMLMetaList(ctx, unlinkedMeta, evaluate) - - shadowLinks := getShadowLinks(ctx, zid, getAllMeta) - endnotes, err := enc.BlocksString(&ast.BlockSlice{}) - if err != nil { - endnotes = "" - } - - user := wui.getUser(ctx) - canCreate := wui.canCreate(ctx, user) - apiZid := api.ZettelID(zid.String()) - var base baseData - wui.makeBaseData(ctx, config.GetLang(zn.InhMeta, wui.rtConfig), textTitle, "", user, &base) - wui.renderTemplate(ctx, w, id.InfoTemplateZid, &base, struct { - Zid string - WebURL string - ContextURL string - CanWrite bool - EditURL string - CanFolge bool - FolgeURL string - CanCopy bool - CopyURL string - CanRename bool - RenameURL string - CanDelete bool - DeleteURL string - MetaData []metaDataInfo - HasLocLinks bool - LocLinks []localLink - HasExtLinks bool - ExtLinks []string - ExtNewWindow string - UnLinks []simpleLink - UnLinksPhrase string - QueryKeyPhrase string - EvalMatrix []matrixLine - ParseMatrix []matrixLine - HasShadowLinks bool - ShadowLinks []string - Endnotes string - }{ - Zid: zid.String(), - WebURL: wui.NewURLBuilder('h').SetZid(apiZid).String(), - ContextURL: wui.NewURLBuilder('k').SetZid(apiZid).String(), - CanWrite: wui.canWrite(ctx, user, zn.Meta, zn.Content), - EditURL: wui.NewURLBuilder('e').SetZid(apiZid).String(), - CanFolge: canCreate, - FolgeURL: wui.NewURLBuilder('c').SetZid(apiZid).AppendQuery(queryKeyAction, valueActionFolge).String(), - CanCopy: canCreate && !zn.Content.IsBinary(), - CopyURL: wui.NewURLBuilder('c').SetZid(apiZid).AppendQuery(queryKeyAction, valueActionCopy).String(), - CanRename: wui.canRename(ctx, user, zn.Meta), - RenameURL: wui.NewURLBuilder('b').SetZid(apiZid).String(), - CanDelete: wui.canDelete(ctx, user, zn.Meta), - DeleteURL: wui.NewURLBuilder('d').SetZid(apiZid).String(), - MetaData: metaData, - HasLocLinks: len(locLinks) > 0, - LocLinks: locLinks, - HasExtLinks: len(extLinks) > 0, - ExtLinks: extLinks, - ExtNewWindow: htmlAttrNewWindow(len(extLinks) > 0), - UnLinks: unLinks, - UnLinksPhrase: phrase, - QueryKeyPhrase: api.QueryKeyPhrase, - EvalMatrix: wui.infoAPIMatrix('v', zid), - ParseMatrix: wui.infoAPIMatrixPlain('p', zid), - HasShadowLinks: len(shadowLinks) > 0, - ShadowLinks: shadowLinks, - Endnotes: endnotes, - }) - } -} - -type localLink struct { - Valid bool - Zid string -} - -func splitLocExtLinks(links []*ast.Reference) (locLinks []localLink, extLinks []string) { - if len(links) == 0 { - return nil, nil - } - for _, ref := range links { - if ref.State == ast.RefStateSelf { - continue - } - if ref.IsZettel() { - continue - } - if ref.IsExternal() { - extLinks = append(extLinks, ref.String()) - continue - } - locLinks = append(locLinks, localLink{ref.IsValid(), ref.String()}) - } - return locLinks, extLinks -} - -func (wui *WebUI) infoAPIMatrix(key byte, zid id.Zid) []matrixLine { - encodings := encoder.GetEncodings() - encTexts := make([]string, 0, len(encodings)) - for _, f := range encodings { - encTexts = append(encTexts, f.String()) - } - sort.Strings(encTexts) - defEncoding := encoder.GetDefaultEncoding().String() - parts := getParts() - matrix := make([]matrixLine, 0, len(parts)) - u := wui.NewURLBuilder(key).SetZid(api.ZettelID(zid.String())) - for _, part := range parts { - row := make([]simpleLink, len(encTexts)) - for j, enc := range encTexts { - u.AppendQuery(api.QueryKeyPart, part) - if enc != defEncoding { - u.AppendQuery(api.QueryKeyEncoding, enc) - } - row[j] = simpleLink{enc, u.String()} - u.ClearQuery() - } - matrix = append(matrix, matrixLine{part, row}) - } - return matrix -} - -func (wui *WebUI) infoAPIMatrixPlain(key byte, zid id.Zid) []matrixLine { - matrix := wui.infoAPIMatrix(key, zid) - apiZid := api.ZettelID(zid.String()) - - // Append plain and JSON format - u := wui.NewURLBuilder('z').SetZid(apiZid) - for i, part := range getParts() { - u.AppendQuery(api.QueryKeyPart, part) - matrix[i].Elements = append(matrix[i].Elements, simpleLink{"plain", u.String()}) - u.ClearQuery() - } - u = wui.NewURLBuilder('j').SetZid(apiZid) - matrix[0].Elements = append(matrix[0].Elements, simpleLink{"json", u.String()}) - u = wui.NewURLBuilder('m').SetZid(apiZid) - matrix[1].Elements = append(matrix[1].Elements, simpleLink{"json", u.String()}) - return matrix -} - -func getParts() []string { - return []string{api.PartZettel, api.PartMeta, api.PartContent} -} - -func getShadowLinks(ctx context.Context, zid id.Zid, getAllMeta usecase.GetAllMeta) []string { - ml, err := getAllMeta.Run(ctx, zid) - if err != nil || len(ml) < 2 { - return nil - } - result := make([]string, 0, len(ml)-1) - for _, m := range ml[1:] { - if boxNo, ok := m.Get(api.KeyBoxNumber); ok { - result = append(result, boxNo) - } - } - return result -} DELETED web/adapter/webui/get_zettel.go Index: web/adapter/webui/get_zettel.go ================================================================== --- web/adapter/webui/get_zettel.go +++ /dev/null @@ -1,189 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "bytes" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/ast" - "zettelstore.de/z/box" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/encoder/textenc" - "zettelstore.de/z/usecase" -) - -// MakeGetHTMLZettelHandler creates a new HTTP handler for the use case "get zettel". -func (wui *WebUI) MakeGetHTMLZettelHandler(evaluate *usecase.Evaluate, getMeta usecase.GetMeta) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - - q := r.URL.Query() - zn, err := evaluate.Run(ctx, zid, q.Get(api.KeySyntax)) - - if err != nil { - wui.reportError(ctx, w, err) - return - } - - enc := wui.createZettelEncoder() - metaHeader := enc.MetaString(zn.InhMeta, func(value string) ast.InlineSlice { - return evaluate.RunMetadata(ctx, value) - }) - textTitle := wui.encodeTitleAsText(ctx, zn.InhMeta, evaluate) - htmlTitle := encodeTitleAsHTML(ctx, zn.InhMeta, evaluate, enc, false) - htmlContent, err := enc.BlocksString(&zn.Ast) - if err != nil { - wui.reportError(ctx, w, err) - return - } - var roleCSSURL string - cssZid, err := wui.retrieveCSSZidFromRole(ctx, *zn.InhMeta) - if err != nil { - wui.reportError(ctx, w, err) - return - } - if cssZid != id.Invalid { - roleCSSURL = wui.NewURLBuilder('z').SetZid(api.ZettelID(cssZid.String())).String() - } - user := wui.getUser(ctx) - roleText := zn.Meta.GetDefault(api.KeyRole, "*") - tags := wui.buildTagInfos(zn.Meta) - canCreate := wui.canCreate(ctx, user) - getTextTitle := wui.makeGetTextTitle(ctx, getMeta, evaluate) - extURL, hasExtURL := zn.Meta.Get(api.KeyURL) - folgeLinks := wui.encodeZettelLinks(zn.InhMeta, api.KeyFolge, getTextTitle) - backLinks := wui.encodeZettelLinks(zn.InhMeta, api.KeyBack, getTextTitle) - apiZid := api.ZettelID(zid.String()) - var base baseData - wui.makeBaseData(ctx, config.GetLang(zn.InhMeta, wui.rtConfig), textTitle, roleCSSURL, user, &base) - base.MetaHeader = metaHeader - wui.renderTemplate(ctx, w, id.ZettelTemplateZid, &base, struct { - HTMLTitle string - RoleCSS string - CanWrite bool - EditURL string - Zid string - InfoURL string - RoleText string - RoleURL string - HasTags bool - Tags []simpleLink - CanCopy bool - CopyURL string - CanFolge bool - FolgeURL string - PrecursorRefs string - HasExtURL bool - ExtURL string - ExtNewWindow string - Content string - HasFolgeLinks bool - FolgeLinks []simpleLink - HasBackLinks bool - BackLinks []simpleLink - }{ - HTMLTitle: htmlTitle, - RoleCSS: roleCSSURL, - CanWrite: wui.canWrite(ctx, user, zn.Meta, zn.Content), - EditURL: wui.NewURLBuilder('e').SetZid(apiZid).String(), - Zid: zid.String(), - InfoURL: wui.NewURLBuilder('i').SetZid(apiZid).String(), - RoleText: roleText, - RoleURL: wui.NewURLBuilder('h').AppendQuery("role", roleText).String(), - HasTags: len(tags) > 0, - Tags: tags, - CanCopy: canCreate && !zn.Content.IsBinary(), - CopyURL: wui.NewURLBuilder('c').SetZid(apiZid).AppendQuery(queryKeyAction, valueActionCopy).String(), - CanFolge: canCreate, - FolgeURL: wui.NewURLBuilder('c').SetZid(apiZid).AppendQuery(queryKeyAction, valueActionFolge).String(), - PrecursorRefs: wui.encodeIdentifierSet(zn.InhMeta, api.KeyPrecursor, getTextTitle), - ExtURL: extURL, - HasExtURL: hasExtURL, - ExtNewWindow: htmlAttrNewWindow(hasExtURL), - Content: htmlContent, - HasFolgeLinks: len(folgeLinks) > 0, - FolgeLinks: folgeLinks, - HasBackLinks: len(backLinks) > 0, - BackLinks: backLinks, - }) - } -} - -func encodeInlinesText(is *ast.InlineSlice, enc *textenc.Encoder) (string, error) { - if is == nil || len(*is) == 0 { - return "", nil - } - - var buf bytes.Buffer - _, err := enc.WriteInlines(&buf, is) - if err != nil { - return "", err - } - return buf.String(), nil -} - -func (wui *WebUI) buildTagInfos(m *meta.Meta) []simpleLink { - var tagInfos []simpleLink - if tags, ok := m.GetList(api.KeyTags); ok { - ub := wui.NewURLBuilder('h') - tagInfos = make([]simpleLink, len(tags)) - for i, tag := range tags { - tagInfos[i] = simpleLink{Text: tag, URL: ub.AppendQuery(api.KeyAllTags, tag).String()} - ub.ClearQuery() - } - } - return tagInfos -} - -func (wui *WebUI) encodeIdentifierSet(m *meta.Meta, key string, getTextTitle getTextTitleFunc) string { - if value, ok := m.Get(key); ok { - var buf bytes.Buffer - wui.writeIdentifierSet(&buf, meta.ListFromValue(value), getTextTitle) - return buf.String() - } - return "" -} - -func (wui *WebUI) encodeZettelLinks(m *meta.Meta, key string, getTextTitle getTextTitleFunc) []simpleLink { - values, ok := m.GetList(key) - if !ok || len(values) == 0 { - return nil - } - return wui.encodeZidLinks(values, getTextTitle) -} - -func (wui *WebUI) encodeZidLinks(values []string, getTextTitle getTextTitleFunc) []simpleLink { - result := make([]simpleLink, 0, len(values)) - for _, val := range values { - zid, err := id.Parse(val) - if err != nil { - continue - } - if title, found := getTextTitle(zid); found > 0 { - url := wui.NewURLBuilder('h').SetZid(api.ZettelID(zid.String())).String() - if title == "" { - result = append(result, simpleLink{Text: val, URL: url}) - } else { - result = append(result, simpleLink{Text: title, URL: url}) - } - } - } - return result -} DELETED web/adapter/webui/goaction.go Index: web/adapter/webui/goaction.go ================================================================== --- web/adapter/webui/goaction.go +++ /dev/null @@ -1,32 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "net/http" - - "zettelstore.de/z/usecase" -) - -// MakeGetGoActionHandler creates a new HTTP handler to execute certain commands. -func (wui *WebUI) MakeGetGoActionHandler(ucRefresh *usecase.Refresh) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - - // Currently, command "refresh" is the only command to be executed. - err := ucRefresh.Run(ctx) - if err != nil { - wui.reportError(ctx, w, err) - return - } - wui.redirectFound(w, r, wui.NewURLBuilder('/')) - } -} DELETED web/adapter/webui/home.go Index: web/adapter/webui/home.go ================================================================== --- web/adapter/webui/home.go +++ /dev/null @@ -1,57 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "context" - "errors" - "net/http" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -type getRootStore interface { - // GetMeta retrieves just the meta data of a specific zettel. - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) -} - -// MakeGetRootHandler creates a new HTTP handler to show the root URL. -func (wui *WebUI) MakeGetRootHandler(s getRootStore) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - if r.URL.Path != "/" { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - homeZid := wui.rtConfig.GetHomeZettel() - apiHomeZid := api.ZettelID(homeZid.String()) - if homeZid != id.DefaultHomeZid { - if _, err := s.GetMeta(ctx, homeZid); err == nil { - wui.redirectFound(w, r, wui.NewURLBuilder('h').SetZid(apiHomeZid)) - return - } - homeZid = id.DefaultHomeZid - } - _, err := s.GetMeta(ctx, homeZid) - if err == nil { - wui.redirectFound(w, r, wui.NewURLBuilder('h').SetZid(apiHomeZid)) - return - } - if errors.Is(err, &box.ErrNotAllowed{}) && wui.authz.WithAuth() && wui.getUser(ctx) == nil { - wui.redirectFound(w, r, wui.NewURLBuilder('i')) - return - } - wui.redirectFound(w, r, wui.NewURLBuilder('h')) - } -} DELETED web/adapter/webui/htmlgen.go Index: web/adapter/webui/htmlgen.go ================================================================== --- web/adapter/webui/htmlgen.go +++ /dev/null @@ -1,205 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "bytes" - "strings" - - "codeberg.org/t73fde/sxpf" - "zettelstore.de/c/api" - "zettelstore.de/c/html" - "zettelstore.de/c/sexpr" - "zettelstore.de/z/ast" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/encoder" - "zettelstore.de/z/encoder/sexprenc" - "zettelstore.de/z/encoder/textenc" - "zettelstore.de/z/strfun" -) - -// Builder allows to build new URLs for the web service. -type urlBuilder interface { - GetURLPrefix() string - NewURLBuilder(key byte) *api.URLBuilder -} - -type htmlGenerator struct { - builder urlBuilder - textEnc *textenc.Encoder - extMarker string - newWindow bool - env *html.EncEnvironment -} - -func createGenerator(builder urlBuilder, extMarker string, newWindow bool) *htmlGenerator { - env := html.NewEncEnvironment(nil, 1) - gen := &htmlGenerator{ - builder: builder, - textEnc: textenc.Create(), - extMarker: extMarker, - newWindow: newWindow, - env: env, - } - - env.Builtins.Set(sexpr.SymTag, sxpf.NewBuiltin("tag", true, 0, -1, gen.generateTag)) - env.Builtins.Set(sexpr.SymLinkZettel, sxpf.NewBuiltin("linkZ", true, 2, -1, gen.generateLinkZettel)) - env.Builtins.Set(sexpr.SymLinkFound, sxpf.NewBuiltin("linkZ", true, 2, -1, gen.generateLinkZettel)) - env.Builtins.Set(sexpr.SymLinkBased, sxpf.NewBuiltin("linkB", true, 2, -1, gen.generateLinkBased)) - env.Builtins.Set(sexpr.SymLinkExternal, sxpf.NewBuiltin("linkE", true, 2, -1, gen.generateLinkExternal)) - - f, err := env.Builtins.LookupForm(sexpr.SymEmbed) - if err != nil { - panic(err) - } - b := f.(*sxpf.Builtin) - env.Builtins.Set(sexpr.SymEmbed, sxpf.NewBuiltin(b.Name(), true, 3, -1, gen.makeGenerateEmbed(b.GetValue()))) - return gen -} - -var mapMetaKey = map[string]string{ - api.KeyCopyright: "copyright", - api.KeyLicense: "license", -} - -func (g *htmlGenerator) MetaString(m *meta.Meta, evalMeta encoder.EvalMetaFunc) string { - ignore := strfun.NewSet(api.KeyTitle, api.KeyLang) - var buf bytes.Buffer - - if tags, ok := m.Get(api.KeyAllTags); ok { - writeMetaTags(&buf, tags) - ignore.Set(api.KeyAllTags) - ignore.Set(api.KeyTags) - } else if tags, ok = m.Get(api.KeyTags); ok { - writeMetaTags(&buf, tags) - ignore.Set(api.KeyTags) - } - - for _, p := range m.ComputedPairs() { - key := p.Key - if ignore.Has(key) { - continue - } - if altKey, found := mapMetaKey[key]; found { - buf.WriteString(`<meta name="`) - buf.WriteString(altKey) - } else { - buf.WriteString(`<meta name="zs-`) - buf.WriteString(key) - } - buf.WriteString(`" content="`) - is := evalMeta(p.Value) - var sb strings.Builder - g.textEnc.WriteInlines(&sb, &is) - html.AttributeEscape(&buf, sb.String()) - buf.WriteString("\">\n") - } - return buf.String() -} -func writeMetaTags(buf *bytes.Buffer, tags string) { - buf.WriteString(`<meta name="keywords" content="`) - for i, val := range meta.ListFromValue(tags) { - if i > 0 { - buf.WriteString(", ") - } - html.AttributeEscape(buf, strings.TrimPrefix(val, "#")) - } - buf.WriteString("\">\n") -} - -// BlocksString encodes a block slice. -func (g *htmlGenerator) BlocksString(bs *ast.BlockSlice) (string, error) { - if bs == nil || len(*bs) == 0 { - return "", nil - } - lst := sexprenc.GetSexpr(bs) - var buf bytes.Buffer - g.env.ReplaceWriter(&buf) - sxpf.Eval(g.env, lst) - if g.env.GetError() == nil { - g.env.WriteEndnotes() - } - g.env.ReplaceWriter(nil) - return buf.String(), g.env.GetError() -} - -// InlinesString writes an inline slice to the writer -func (g *htmlGenerator) InlinesString(is *ast.InlineSlice, noLink bool) (string, error) { - if is == nil || len(*is) == 0 { - return "", nil - } - return html.EvaluateInline(g.env, sexprenc.GetSexpr(is), !noLink, noLink), nil -} - -func (g *htmlGenerator) generateTag(senv sxpf.Environment, args *sxpf.Pair, _ int) (sxpf.Value, error) { - if !sxpf.IsNil(args) { - env := senv.(*html.EncEnvironment) - s := env.GetString(args) - if env.IgnoreLinks() { - env.WriteEscaped(s) - } else { - u := g.builder.NewURLBuilder('h').AppendQuery(api.KeyAllTags, "#"+strings.ToLower(s)) - env.WriteStrings(`<a href="`, u.String(), `">#`) - env.WriteEscaped(s) - env.WriteString("</a>") - } - } - return nil, nil -} - -func (g *htmlGenerator) generateLinkZettel(senv sxpf.Environment, args *sxpf.Pair, _ int) (sxpf.Value, error) { - env := senv.(*html.EncEnvironment) - if a, refValue, ok := html.PrepareLink(env, args); ok { - zid, fragment, hasFragment := strings.Cut(refValue, "#") - u := g.builder.NewURLBuilder('h').SetZid(api.ZettelID(zid)) - if hasFragment { - u = u.SetFragment(fragment) - } - html.WriteLink(env, args, a.Set("href", u.String()), refValue, "") - } - return nil, nil -} - -func (g *htmlGenerator) generateLinkBased(senv sxpf.Environment, args *sxpf.Pair, _ int) (sxpf.Value, error) { - env := senv.(*html.EncEnvironment) - if a, refValue, ok := html.PrepareLink(env, args); ok { - u := g.builder.NewURLBuilder('/').SetRawLocal(refValue) - html.WriteLink(env, args, a.Set("href", u.String()), refValue, "") - } - return nil, nil -} - -func (g *htmlGenerator) generateLinkExternal(senv sxpf.Environment, args *sxpf.Pair, _ int) (sxpf.Value, error) { - env := senv.(*html.EncEnvironment) - if a, refValue, ok := html.PrepareLink(env, args); ok { - a = a.Set("href", refValue). - AddClass("external"). - Set("target", "_blank"). - Set("rel", "noopener noreferrer") - html.WriteLink(env, args, a, refValue, g.extMarker) - } - return nil, nil -} - -func (g *htmlGenerator) makeGenerateEmbed(oldFn sxpf.BuiltinFn) sxpf.BuiltinFn { - return func(senv sxpf.Environment, args *sxpf.Pair, arity int) (sxpf.Value, error) { - env := senv.(*html.EncEnvironment) - ref := env.GetPair(args.GetTail()) - refValue := env.GetString(ref.GetTail()) - zid := api.ZettelID(refValue) - if !zid.IsValid() { - return oldFn(senv, args, arity) - } - u := g.builder.NewURLBuilder('z').SetZid(zid) - env.WriteImageWithSource(args, u.String()) - return nil, nil - } -} DELETED web/adapter/webui/htmlmeta.go Index: web/adapter/webui/htmlmeta.go ================================================================== --- web/adapter/webui/htmlmeta.go +++ /dev/null @@ -1,204 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "context" - "errors" - "fmt" - "io" - "net/url" - "time" - - "zettelstore.de/c/api" - "zettelstore.de/c/html" - "zettelstore.de/z/ast" - "zettelstore.de/z/box" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/usecase" -) - -var space = []byte{' '} - -type evalMetadataFunc = func(string) ast.InlineSlice - -func (wui *WebUI) writeHTMLMetaValue( - w io.Writer, - key, value string, - getTextTitle getTextTitleFunc, - evalMetadata evalMetadataFunc, - gen *htmlGenerator, -) { - switch kt := meta.Type(key); kt { - case meta.TypeCredential: - writeCredential(w, value) - case meta.TypeEmpty: - writeEmpty(w, value) - case meta.TypeID: - wui.writeIdentifier(w, value, getTextTitle) - case meta.TypeIDSet: - wui.writeIdentifierSet(w, meta.ListFromValue(value), getTextTitle) - case meta.TypeNumber: - wui.writeNumber(w, key, value) - case meta.TypeString: - writeString(w, value) - case meta.TypeTagSet: - wui.writeTagSet(w, key, meta.ListFromValue(value)) - case meta.TypeTimestamp: - if ts, ok := meta.TimeValue(value); ok { - writeTimestamp(w, ts) - } - case meta.TypeURL: - writeURL(w, value) - case meta.TypeWord: - wui.writeWord(w, key, value) - case meta.TypeWordSet: - wui.writeWordSet(w, key, meta.ListFromValue(value)) - case meta.TypeZettelmarkup: - io.WriteString(w, encodeZmkMetadata(value, evalMetadata, gen, false)) - default: - html.Escape(w, value) - fmt.Fprintf(w, " <b>(Unhandled type: %v, key: %v)</b>", kt, key) - } -} - -func writeCredential(w io.Writer, val string) { html.Escape(w, val) } -func writeEmpty(w io.Writer, val string) { html.Escape(w, val) } - -func (wui *WebUI) writeIdentifier(w io.Writer, val string, getTextTitle getTextTitleFunc) { - zid, err := id.Parse(val) - if err != nil { - html.Escape(w, val) - return - } - title, found := getTextTitle(zid) - switch { - case found > 0: - ub := wui.NewURLBuilder('h').SetZid(api.ZettelID(zid.String())) - if title == "" { - fmt.Fprintf(w, "<a href=\"%v\">%v</a>", ub, zid) - } else { - fmt.Fprintf(w, "<a href=\"%v\" title=\"%v\">%v</a>", ub, title, zid) - } - case found == 0: - fmt.Fprintf(w, "<s>%v</s>", val) - case found < 0: - io.WriteString(w, val) - } -} - -func (wui *WebUI) writeIdentifierSet(w io.Writer, vals []string, getTextTitle getTextTitleFunc) { - for i, val := range vals { - if i > 0 { - w.Write(space) - } - wui.writeIdentifier(w, val, getTextTitle) - } -} - -func (wui *WebUI) writeNumber(w io.Writer, key, val string) { - wui.writeLink(w, key, val, val) -} - -func writeString(w io.Writer, val string) { html.Escape(w, val) } - -func (wui *WebUI) writeTagSet(w io.Writer, key string, tags []string) { - for i, tag := range tags { - if i > 0 { - w.Write(space) - } - wui.writeLink(w, key, tag, tag) - } -} - -func writeTimestamp(w io.Writer, ts time.Time) { - io.WriteString(w, ts.Format("2006-01-02 15:04:05")) -} - -func writeURL(w io.Writer, val string) { - u, err := url.Parse(val) - if err != nil { - html.Escape(w, val) - return - } - fmt.Fprintf(w, "<a href=\"%v\"%v>", u, htmlAttrNewWindow(true)) - html.Escape(w, val) - io.WriteString(w, "</a>") -} - -func (wui *WebUI) writeWord(w io.Writer, key, word string) { - wui.writeLink(w, key, word, word) -} - -func (wui *WebUI) writeWordSet(w io.Writer, key string, words []string) { - for i, word := range words { - if i > 0 { - w.Write(space) - } - wui.writeWord(w, key, word) - } -} - -func (wui *WebUI) writeLink(w io.Writer, key, value, text string) { - fmt.Fprintf(w, "<a href=\"%v?%v=%v\">", wui.NewURLBuilder('h'), url.QueryEscape(key), url.QueryEscape(value)) - html.Escape(w, text) - io.WriteString(w, "</a>") -} - -type getTextTitleFunc func(id.Zid) (string, int) - -func (wui *WebUI) makeGetTextTitle( - ctx context.Context, - getMeta usecase.GetMeta, evaluate *usecase.Evaluate, -) getTextTitleFunc { - return func(zid id.Zid) (string, int) { - m, err := getMeta.Run(box.NoEnrichContext(ctx), zid) - if err != nil { - if errors.Is(err, &box.ErrNotAllowed{}) { - return "", -1 - } - return "", 0 - } - return wui.encodeTitleAsText(ctx, m, evaluate), 1 - } -} - -func encodeTitleAsHTML( - ctx context.Context, m *meta.Meta, - evaluate *usecase.Evaluate, - gen *htmlGenerator, noLink bool, -) string { - plainTitle := m.GetTitle() - return encodeZmkMetadata( - plainTitle, - func(val string) ast.InlineSlice { return evaluate.RunMetadata(ctx, val) }, - gen, noLink) -} - -func (wui *WebUI) encodeTitleAsText(ctx context.Context, m *meta.Meta, evaluate *usecase.Evaluate) string { - plainTitle := m.GetTitle() - is := evaluate.RunMetadata(ctx, plainTitle) - result, err := encodeInlinesText(&is, wui.gentext) - if err != nil { - return err.Error() - } - return result -} - -func encodeZmkMetadata(value string, evalMetadata evalMetadataFunc, gen *htmlGenerator, noLink bool) string { - is := evalMetadata(value) - result, err := gen.InlinesString(&is, noLink) - if err != nil { - return err.Error() - } - return result -} DELETED web/adapter/webui/lists.go Index: web/adapter/webui/lists.go ================================================================== --- web/adapter/webui/lists.go +++ /dev/null @@ -1,267 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "bytes" - "context" - "net/http" - "net/url" - "sort" - "strconv" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/search" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeListHTMLMetaHandler creates a HTTP handler for rendering the list of -// zettel as HTML. -func (wui *WebUI) MakeListHTMLMetaHandler( - listMeta usecase.ListMeta, - listRole usecase.ListRoles, - listTags usecase.ListTags, - evaluate *usecase.Evaluate, -) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - query := r.URL.Query() - switch query.Get("_l") { - case "r": - wui.renderRolesList(w, r, listRole) - case "t": - wui.renderTagsList(w, r, listTags) - default: - wui.renderZettelList(w, r, listMeta, evaluate) - } - } -} - -func (wui *WebUI) renderZettelList( - w http.ResponseWriter, r *http.Request, - listMeta usecase.ListMeta, evaluate *usecase.Evaluate, -) { - query := r.URL.Query() - s := adapter.GetSearch(query) - ctx := r.Context() - title := wui.listTitleSearch(s) - - if !s.EnrichNeeded() { - ctx = box.NoEnrichContext(ctx) - } - metaList, err := listMeta.Run(ctx, s) - if err != nil { - wui.reportError(ctx, w, err) - return - } - user := wui.getUser(ctx) - metas := wui.buildHTMLMetaList(ctx, metaList, evaluate) - var base baseData - wui.makeBaseData(ctx, wui.rtConfig.GetDefaultLang(), wui.rtConfig.GetSiteName(), "", user, &base) - wui.renderTemplate(ctx, w, id.ListTemplateZid, &base, struct { - Title string - Metas []simpleLink - }{ - Title: title, - Metas: metas, - }) -} - -type roleInfo struct { - Text string - URL string -} - -func (wui *WebUI) renderRolesList(w http.ResponseWriter, r *http.Request, listRole usecase.ListRoles) { - ctx := r.Context() - roleArrangement, err := listRole.Run(ctx) - if err != nil { - wui.reportError(ctx, w, err) - return - } - roleList := roleArrangement.Counted() - roleList.SortByName() - - roleInfos := make([]roleInfo, len(roleList)) - for i, role := range roleList { - roleInfos[i] = roleInfo{role.Name, wui.NewURLBuilder('h').AppendQuery("role", role.Name).String()} - } - - user := wui.getUser(ctx) - var base baseData - wui.makeBaseData(ctx, wui.rtConfig.GetDefaultLang(), wui.rtConfig.GetSiteName(), "", user, &base) - wui.renderTemplate(ctx, w, id.RolesTemplateZid, &base, struct { - Roles []roleInfo - }{ - Roles: roleInfos, - }) -} - -type countInfo struct { - Count string - URL string -} - -type tagInfo struct { - Name string - URL string - iCount int - Count string - Size string -} - -const fontSizes = 6 // Must be the number of CSS classes zs-font-size-* in base.css - -func (wui *WebUI) renderTagsList(w http.ResponseWriter, r *http.Request, listTags usecase.ListTags) { - ctx := r.Context() - iMinCount, err := strconv.Atoi(r.URL.Query().Get("min")) - if err != nil || iMinCount < 0 { - iMinCount = 0 - } - tagData, err := listTags.Run(ctx, iMinCount) - if err != nil { - wui.reportError(ctx, w, err) - return - } - - user := wui.getUser(ctx) - tagsList := make([]tagInfo, 0, len(tagData)) - countMap := make(map[int]int) - baseTagListURL := wui.NewURLBuilder('h') - for tag, ml := range tagData { - count := len(ml) - countMap[count]++ - tagsList = append( - tagsList, - tagInfo{tag, baseTagListURL.AppendQuery(api.KeyAllTags, tag).String(), count, "", ""}) - baseTagListURL.ClearQuery() - } - sort.Slice(tagsList, func(i, j int) bool { return tagsList[i].Name < tagsList[j].Name }) - - countList := make([]int, 0, len(countMap)) - for count := range countMap { - countList = append(countList, count) - } - sort.Ints(countList) - for pos, count := range countList { - countMap[count] = (pos * fontSizes) / len(countList) - } - for i := 0; i < len(tagsList); i++ { - count := tagsList[i].iCount - tagsList[i].Count = strconv.Itoa(count) - tagsList[i].Size = strconv.Itoa(countMap[count]) - } - - var base baseData - wui.makeBaseData(ctx, wui.rtConfig.GetDefaultLang(), wui.rtConfig.GetSiteName(), "", user, &base) - minCounts := make([]countInfo, 0, len(countList)) - for _, c := range countList { - sCount := strconv.Itoa(c) - minCounts = append(minCounts, countInfo{sCount, base.ListTagsURL + "&min=" + sCount}) - } - - wui.renderTemplate(ctx, w, id.TagsTemplateZid, &base, struct { - ListTagsURL string - MinCounts []countInfo - Tags []tagInfo - }{ - ListTagsURL: base.ListTagsURL, - MinCounts: minCounts, - Tags: tagsList, - }) -} - -// MakeZettelContextHandler creates a new HTTP handler for the use case "zettel context". -func (wui *WebUI) MakeZettelContextHandler(getContext usecase.ZettelContext, evaluate *usecase.Evaluate) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - q := r.URL.Query() - dir := adapter.GetZCDirection(q.Get(api.QueryKeyDir)) - depth := getIntParameter(q, api.QueryKeyDepth, 5) - limit := getIntParameter(q, api.QueryKeyLimit, 200) - metaList, err := getContext.Run(ctx, zid, dir, depth, limit) - if err != nil { - wui.reportError(ctx, w, err) - return - } - apiZid := api.ZettelID(zid.String()) - metaLinks := wui.buildHTMLMetaList(ctx, metaList, evaluate) - depths := []string{"2", "3", "4", "5", "6", "7", "8", "9", "10"} - depthLinks := make([]simpleLink, len(depths)) - depthURL := wui.NewURLBuilder('k').SetZid(apiZid) - for i, depth := range depths { - depthURL.ClearQuery() - switch dir { - case usecase.ZettelContextBackward: - depthURL.AppendQuery(api.QueryKeyDir, api.DirBackward) - case usecase.ZettelContextForward: - depthURL.AppendQuery(api.QueryKeyDir, api.DirForward) - } - depthURL.AppendQuery(api.QueryKeyDepth, depth) - depthLinks[i].Text = depth - depthLinks[i].URL = depthURL.String() - } - var base baseData - user := wui.getUser(ctx) - wui.makeBaseData(ctx, wui.rtConfig.GetDefaultLang(), wui.rtConfig.GetSiteName(), "", user, &base) - wui.renderTemplate(ctx, w, id.ContextTemplateZid, &base, struct { - Title string - InfoURL string - Depths []simpleLink - Start simpleLink - Metas []simpleLink - }{ - Title: "Zettel Context", - InfoURL: wui.NewURLBuilder('i').SetZid(apiZid).String(), - Depths: depthLinks, - Start: metaLinks[0], - Metas: metaLinks[1:], - }) - } -} - -func getIntParameter(q url.Values, key string, minValue int) int { - val, ok := adapter.GetInteger(q, key) - if !ok || val < 0 { - return minValue - } - return val -} - -func (wui *WebUI) listTitleSearch(s *search.Search) string { - if s == nil { - return wui.rtConfig.GetSiteName() - } - var buf bytes.Buffer - s.Print(&buf) - return buf.String() -} - -// buildHTMLMetaList builds a zettel list based on a meta list for HTML rendering. -func (wui *WebUI) buildHTMLMetaList(ctx context.Context, metaList []*meta.Meta, evaluate *usecase.Evaluate) []simpleLink { - metas := make([]simpleLink, 0, len(metaList)) - encHTML := wui.getSimpleHTMLEncoder() - for _, m := range metaList { - metas = append(metas, simpleLink{ - Text: encodeTitleAsHTML(ctx, m, evaluate, encHTML, true), - URL: wui.NewURLBuilder('h').SetZid(api.ZettelID(m.Zid.String())).String(), - }) - } - return metas -} DELETED web/adapter/webui/login.go Index: web/adapter/webui/login.go ================================================================== --- web/adapter/webui/login.go +++ /dev/null @@ -1,75 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "context" - "net/http" - - "zettelstore.de/z/auth" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeGetLoginOutHandler creates a new HTTP handler to display the HTML login view, -// or to execute a logout. -func (wui *WebUI) MakeGetLoginOutHandler() http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - query := r.URL.Query() - if query.Has("logout") { - wui.clearToken(r.Context(), w) - wui.redirectFound(w, r, wui.NewURLBuilder('/')) - return - } - wui.renderLoginForm(wui.clearToken(r.Context(), w), w, false) - } -} - -func (wui *WebUI) renderLoginForm(ctx context.Context, w http.ResponseWriter, retry bool) { - var base baseData - wui.makeBaseData(ctx, wui.rtConfig.GetDefaultLang(), "Login", "", nil, &base) - wui.renderTemplate(ctx, w, id.LoginTemplateZid, &base, struct { - Title string - Retry bool - }{ - Title: base.Title, - Retry: retry, - }) -} - -// MakePostLoginHandler creates a new HTTP handler to authenticate the given user. -func (wui *WebUI) MakePostLoginHandler(ucAuth *usecase.Authenticate) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if !wui.authz.WithAuth() { - wui.redirectFound(w, r, wui.NewURLBuilder('/')) - return - } - ctx := r.Context() - ident, cred, ok := adapter.GetCredentialsViaForm(r) - if !ok { - wui.reportError(ctx, w, adapter.NewErrBadRequest("Unable to read login form")) - return - } - token, err := ucAuth.Run(ctx, ident, cred, wui.tokenLifetime, auth.KindHTML) - if err != nil { - wui.reportError(ctx, w, err) - return - } - if token == nil { - wui.renderLoginForm(wui.clearToken(ctx, w), w, true) - return - } - - wui.setToken(w, token) - wui.redirectFound(w, r, wui.NewURLBuilder('/')) - } -} DELETED web/adapter/webui/rename_zettel.go Index: web/adapter/webui/rename_zettel.go ================================================================== --- web/adapter/webui/rename_zettel.go +++ /dev/null @@ -1,102 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "fmt" - "net/http" - "strings" - - "zettelstore.de/c/api" - "zettelstore.de/z/box" - "zettelstore.de/z/config" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/usecase" - "zettelstore.de/z/web/adapter" -) - -// MakeGetRenameZettelHandler creates a new HTTP handler to display the -// HTML rename view of a zettel. -func (wui *WebUI) MakeGetRenameZettelHandler(getMeta usecase.GetMeta, evaluate *usecase.Evaluate) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - zid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - - m, err := getMeta.Run(ctx, zid) - if err != nil { - wui.reportError(ctx, w, err) - return - } - - getTextTitle := wui.makeGetTextTitle(ctx, getMeta, evaluate) - incomingLinks := wui.encodeIncoming(m, getTextTitle) - uselessFiles := retrieveUselessFiles(m) - - user := wui.getUser(ctx) - var base baseData - wui.makeBaseData(ctx, config.GetLang(m, wui.rtConfig), "Rename Zettel "+zid.String(), "", user, &base) - wui.renderTemplate(ctx, w, id.RenameTemplateZid, &base, struct { - Zid string - MetaPairs []meta.Pair - HasIncoming bool - Incoming []simpleLink - HasUselessFiles bool - UselessFiles []string - }{ - Zid: zid.String(), - MetaPairs: m.ComputedPairs(), - HasIncoming: len(incomingLinks) > 0, - Incoming: incomingLinks, - HasUselessFiles: len(uselessFiles) > 0, - UselessFiles: uselessFiles, - }) - } -} - -// MakePostRenameZettelHandler creates a new HTTP handler to rename an existing zettel. -func (wui *WebUI) MakePostRenameZettelHandler(renameZettel *usecase.RenameZettel) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - ctx := r.Context() - curZid, err := id.Parse(r.URL.Path[1:]) - if err != nil { - wui.reportError(ctx, w, box.ErrNotFound) - return - } - - if err = r.ParseForm(); err != nil { - wui.reportError(ctx, w, adapter.NewErrBadRequest("Unable to read rename zettel form")) - return - } - if formCurZid, err1 := id.Parse( - r.PostFormValue("curzid")); err1 != nil || formCurZid != curZid { - wui.reportError(ctx, w, adapter.NewErrBadRequest("Invalid value for current zettel id in form")) - return - } - formNewZid := strings.TrimSpace(r.PostFormValue("newzid")) - newZid, err := id.Parse(formNewZid) - if err != nil { - wui.reportError( - ctx, w, adapter.NewErrBadRequest(fmt.Sprintf("Invalid new zettel id %q", formNewZid))) - return - } - - if err = renameZettel.Run(r.Context(), curZid, newZid); err != nil { - wui.reportError(ctx, w, err) - return - } - wui.redirectFound(w, r, wui.NewURLBuilder('h').SetZid(api.ZettelID(newZid.String()))) - } -} DELETED web/adapter/webui/response.go Index: web/adapter/webui/response.go ================================================================== --- web/adapter/webui/response.go +++ /dev/null @@ -1,23 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -package webui - -import ( - "net/http" - - "zettelstore.de/c/api" -) - -func (wui *WebUI) redirectFound(w http.ResponseWriter, r *http.Request, ub *api.URLBuilder) { - us := ub.String() - wui.log.Debug().Str("uri", us).Msg("redirect") - http.Redirect(w, r, us, http.StatusFound) -} DELETED web/adapter/webui/webui.go Index: web/adapter/webui/webui.go ================================================================== --- web/adapter/webui/webui.go +++ /dev/null @@ -1,445 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package webui provides web-UI handlers for web requests. -package webui - -import ( - "bytes" - "context" - "net/http" - "strings" - "sync" - "time" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/box" - "zettelstore.de/z/collect" - "zettelstore.de/z/config" - "zettelstore.de/z/domain" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/encoder/textenc" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" - "zettelstore.de/z/parser" - "zettelstore.de/z/template" - "zettelstore.de/z/web/adapter" - "zettelstore.de/z/web/server" -) - -// WebUI holds all data for delivering the web ui. -type WebUI struct { - log *logger.Logger - debug bool - ab server.AuthBuilder - authz auth.AuthzManager - rtConfig config.Config - token auth.TokenManager - box webuiBox - policy auth.Policy - - gentext *textenc.Encoder - - mxCache sync.RWMutex - templateCache map[id.Zid]*template.Template - - mxRoleCSSMap sync.RWMutex - roleCSSMap map[string]id.Zid - - tokenLifetime time.Duration - cssBaseURL string - cssUserURL string - homeURL string - listZettelURL string - listRolesURL string - listTagsURL string - refreshURL string - withAuth bool - loginURL string - logoutURL string - searchURL string -} - -type webuiBox interface { - CanCreateZettel(ctx context.Context) bool - GetZettel(ctx context.Context, zid id.Zid) (domain.Zettel, error) - GetMeta(ctx context.Context, zid id.Zid) (*meta.Meta, error) - CanUpdateZettel(ctx context.Context, zettel domain.Zettel) bool - AllowRenameZettel(ctx context.Context, zid id.Zid) bool - CanDeleteZettel(ctx context.Context, zid id.Zid) bool -} - -// New creates a new WebUI struct. -func New(log *logger.Logger, ab server.AuthBuilder, authz auth.AuthzManager, rtConfig config.Config, token auth.TokenManager, - mgr box.Manager, pol auth.Policy) *WebUI { - loginoutBase := ab.NewURLBuilder('i') - wui := &WebUI{ - log: log, - debug: kernel.Main.GetConfig(kernel.CoreService, kernel.CoreDebug).(bool), - ab: ab, - rtConfig: rtConfig, - authz: authz, - token: token, - box: mgr, - policy: pol, - - gentext: textenc.Create(), - - tokenLifetime: kernel.Main.GetConfig(kernel.WebService, kernel.WebTokenLifetimeHTML).(time.Duration), - cssBaseURL: ab.NewURLBuilder('z').SetZid(api.ZidBaseCSS).String(), - cssUserURL: ab.NewURLBuilder('z').SetZid(api.ZidUserCSS).String(), - homeURL: ab.NewURLBuilder('/').String(), - listZettelURL: ab.NewURLBuilder('h').String(), - listRolesURL: ab.NewURLBuilder('h').AppendQuery("_l", "r").String(), - listTagsURL: ab.NewURLBuilder('h').AppendQuery("_l", "t").String(), - refreshURL: ab.NewURLBuilder('g').AppendQuery("_c", "r").String(), - withAuth: authz.WithAuth(), - loginURL: loginoutBase.String(), - logoutURL: loginoutBase.AppendQuery("logout", "").String(), - searchURL: ab.NewURLBuilder('h').String(), - } - wui.observe(box.UpdateInfo{Box: mgr, Reason: box.OnReload, Zid: id.Invalid}) - mgr.RegisterObserver(wui.observe) - return wui -} - -func (wui *WebUI) observe(ci box.UpdateInfo) { - wui.mxCache.Lock() - if ci.Reason == box.OnReload || ci.Zid == id.BaseTemplateZid { - wui.templateCache = make(map[id.Zid]*template.Template, len(wui.templateCache)) - } else { - delete(wui.templateCache, ci.Zid) - } - wui.mxCache.Unlock() - wui.mxRoleCSSMap.Lock() - if ci.Reason == box.OnReload || ci.Zid == id.RoleCSSMapZid { - wui.roleCSSMap = nil - } - wui.mxRoleCSSMap.Unlock() -} - -func (wui *WebUI) cacheSetTemplate(zid id.Zid, t *template.Template) { - wui.mxCache.Lock() - wui.templateCache[zid] = t - wui.mxCache.Unlock() -} - -func (wui *WebUI) cacheGetTemplate(zid id.Zid) (*template.Template, bool) { - wui.mxCache.RLock() - t, ok := wui.templateCache[zid] - wui.mxCache.RUnlock() - return t, ok -} - -func (wui *WebUI) retrieveCSSZidFromRole(ctx context.Context, m meta.Meta) (id.Zid, error) { - wui.mxRoleCSSMap.RLock() - if wui.roleCSSMap == nil { - wui.mxRoleCSSMap.RUnlock() - wui.mxRoleCSSMap.Lock() - mMap, err := wui.box.GetMeta(ctx, id.RoleCSSMapZid) - if err == nil { - wui.roleCSSMap = createRoleCSSMap(mMap) - } - wui.mxRoleCSSMap.Unlock() - if err != nil { - return id.Invalid, err - } - wui.mxRoleCSSMap.RLock() - } - - defer wui.mxRoleCSSMap.RUnlock() - if role, found := m.Get("css-role"); found { - if result, found2 := wui.roleCSSMap[role]; found2 { - return result, nil - } - } - if role, found := m.Get(api.KeyRole); found { - if result, found2 := wui.roleCSSMap[role]; found2 { - return result, nil - } - } - return id.Invalid, nil -} - -func createRoleCSSMap(mMap *meta.Meta) map[string]id.Zid { - result := make(map[string]id.Zid) - for _, p := range mMap.PairsRest() { - key := p.Key - if len(key) < 9 || !strings.HasPrefix(key, "css-") || !strings.HasSuffix(key, "-zid") { - continue - } - zid, err2 := id.Parse(p.Value) - if err2 != nil { - continue - } - result[key[4:len(key)-4]] = zid - } - return result -} - -func (wui *WebUI) canCreate(ctx context.Context, user *meta.Meta) bool { - m := meta.New(id.Invalid) - return wui.policy.CanCreate(user, m) && wui.box.CanCreateZettel(ctx) -} - -func (wui *WebUI) canWrite( - ctx context.Context, user, meta *meta.Meta, content domain.Content) bool { - return wui.policy.CanWrite(user, meta, meta) && - wui.box.CanUpdateZettel(ctx, domain.Zettel{Meta: meta, Content: content}) -} - -func (wui *WebUI) canRename(ctx context.Context, user, m *meta.Meta) bool { - return wui.policy.CanRename(user, m) && wui.box.AllowRenameZettel(ctx, m.Zid) -} - -func (wui *WebUI) canDelete(ctx context.Context, user, m *meta.Meta) bool { - return wui.policy.CanDelete(user, m) && wui.box.CanDeleteZettel(ctx, m.Zid) -} - -func (wui *WebUI) canRefresh(user *meta.Meta) bool { - return wui.policy.CanRefresh(user) -} - -func (wui *WebUI) getTemplate( - ctx context.Context, templateID id.Zid) (*template.Template, error) { - if t, ok := wui.cacheGetTemplate(templateID); ok { - return t, nil - } - realTemplateZettel, err := wui.box.GetZettel(ctx, templateID) - if err != nil { - return nil, err - } - t, err := template.ParseString(realTemplateZettel.Content.AsString(), nil) - if err == nil { - // t.SetErrorOnMissing() - wui.cacheSetTemplate(templateID, t) - } - return t, err -} - -type simpleLink struct { - Text string - URL string -} - -type baseData struct { - Lang string - MetaHeader string - CSSBaseURL string - CSSUserURL string - CSSRoleURL string - Title string - HomeURL string - WithUser bool - WithAuth bool - UserIsValid bool - UserZettelURL string - UserIdent string - LoginURL string - LogoutURL string - ListZettelURL string - ListRolesURL string - ListTagsURL string - CanRefresh bool - RefreshURL string - HasNewZettelLinks bool - NewZettelLinks []simpleLink - SearchURL string - QueryKeySearch string - Content string - FooterHTML string - DebugMode bool -} - -func (wui *WebUI) makeBaseData(ctx context.Context, lang, title, roleCSSURL string, user *meta.Meta, data *baseData) { - var userZettelURL string - var userIdent string - - userIsValid := user != nil - if userIsValid { - userZettelURL = wui.NewURLBuilder('h').SetZid(api.ZettelID(user.Zid.String())).String() - userIdent = user.GetDefault(api.KeyUserID, "") - } - newZettelLinks := wui.fetchNewTemplates(ctx, user) - - data.Lang = lang - data.CSSBaseURL = wui.cssBaseURL - data.CSSUserURL = wui.cssUserURL - data.CSSRoleURL = roleCSSURL - data.Title = title - data.HomeURL = wui.homeURL - data.WithAuth = wui.withAuth - data.WithUser = data.WithAuth - data.UserIsValid = userIsValid - data.UserZettelURL = userZettelURL - data.UserIdent = userIdent - data.LoginURL = wui.loginURL - data.LogoutURL = wui.logoutURL - data.ListZettelURL = wui.listZettelURL - data.ListRolesURL = wui.listRolesURL - data.ListTagsURL = wui.listTagsURL - data.CanRefresh = wui.canRefresh(user) - data.RefreshURL = wui.refreshURL - data.HasNewZettelLinks = len(newZettelLinks) > 0 - data.NewZettelLinks = newZettelLinks - data.SearchURL = wui.searchURL - data.QueryKeySearch = api.QueryKeySearch - data.FooterHTML = wui.rtConfig.GetFooterHTML() - data.DebugMode = wui.debug -} - -func (wui *WebUI) getSimpleHTMLEncoder() *htmlGenerator { - return createGenerator(wui, "", false) -} -func (wui *WebUI) createZettelEncoder() *htmlGenerator { - return createGenerator(wui, wui.rtConfig.GetMarkerExternal(), true) -} - -// htmlAttrNewWindow returns HTML attribute string for opening a link in a new window. -// If hasURL is false an empty string is returned. -func htmlAttrNewWindow(hasURL bool) string { - if hasURL { - return " target=\"_blank\" ref=\"noopener noreferrer\"" - } - return "" -} - -func (wui *WebUI) fetchNewTemplates(ctx context.Context, user *meta.Meta) (result []simpleLink) { - ctx = box.NoEnrichContext(ctx) - if !wui.canCreate(ctx, user) { - return nil - } - menu, err := wui.box.GetZettel(ctx, id.TOCNewTemplateZid) - if err != nil { - return nil - } - refs := collect.Order(parser.ParseZettel(menu, "", wui.rtConfig)) - for _, ref := range refs { - zid, err2 := id.Parse(ref.URL.Path) - if err2 != nil { - continue - } - m, err2 := wui.box.GetMeta(ctx, zid) - if err2 != nil { - continue - } - if !wui.policy.CanRead(user, m) { - continue - } - title := m.GetTitle() - astTitle := parser.ParseMetadata(title) - menuTitle, err2 := wui.getSimpleHTMLEncoder().InlinesString(&astTitle, false) - if err2 != nil { - menuTitle, err2 = encodeInlinesText(&astTitle, wui.gentext) - if err2 != nil { - menuTitle = title - } - } - result = append(result, simpleLink{ - Text: menuTitle, - URL: wui.NewURLBuilder('c').SetZid(api.ZettelID(m.Zid.String())). - AppendQuery(queryKeyAction, valueActionNew).String(), - }) - } - return result -} - -func (wui *WebUI) renderTemplate( - ctx context.Context, - w http.ResponseWriter, - templateID id.Zid, - base *baseData, - data interface{}) { - wui.renderTemplateStatus(ctx, w, http.StatusOK, templateID, base, data) -} - -func (wui *WebUI) reportError(ctx context.Context, w http.ResponseWriter, err error) { - code, text := adapter.CodeMessageFromError(err) - if code == http.StatusInternalServerError { - wui.log.Error().Msg(err.Error()) - } - user := wui.getUser(ctx) - var base baseData - wui.makeBaseData(ctx, api.ValueLangEN, "Error", "", user, &base) - wui.renderTemplateStatus(ctx, w, code, id.ErrorTemplateZid, &base, struct { - ErrorTitle string - ErrorText string - }{ - ErrorTitle: http.StatusText(code), - ErrorText: text, - }) -} - -func (wui *WebUI) renderTemplateStatus( - ctx context.Context, - w http.ResponseWriter, - code int, - templateID id.Zid, - base *baseData, - data interface{}) { - - bt, err := wui.getTemplate(ctx, id.BaseTemplateZid) - if err != nil { - wui.log.IfErr(err).Zid(id.BaseTemplateZid).Msg("Unable to get template") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - t, err := wui.getTemplate(ctx, templateID) - if err != nil { - wui.log.IfErr(err).Zid(templateID).Msg("Unable to get template") - http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) - return - } - if user := wui.getUser(ctx); user != nil { - if tok, err1 := wui.token.GetToken(user, wui.tokenLifetime, auth.KindHTML); err1 == nil { - wui.setToken(w, tok) - } - } - var content bytes.Buffer - err = t.Render(&content, data) - if err == nil { - wui.prepareAndWriteHeader(w, code) - base.Content = content.String() - err = bt.Render(w, base) - } - if err != nil { - wui.log.IfErr(err).Msg("Unable to write HTML via template") - } -} - -func (wui *WebUI) getUser(ctx context.Context) *meta.Meta { return wui.ab.GetUser(ctx) } - -// GetURLPrefix returns the configured URL prefix of the web server. -func (wui *WebUI) GetURLPrefix() string { return wui.ab.GetURLPrefix() } - -// NewURLBuilder creates a new URL builder object with the given key. -func (wui *WebUI) NewURLBuilder(key byte) *api.URLBuilder { return wui.ab.NewURLBuilder(key) } - -func (wui *WebUI) clearToken(ctx context.Context, w http.ResponseWriter) context.Context { - return wui.ab.ClearToken(ctx, w) -} - -func (wui *WebUI) setToken(w http.ResponseWriter, token []byte) { - wui.ab.SetToken(w, token, wui.tokenLifetime) -} - -func (wui *WebUI) prepareAndWriteHeader(w http.ResponseWriter, statusCode int) { - h := adapter.PrepareHeader(w, "text/html; charset=utf-8") - h.Set("Content-Security-Policy", "default-src 'self'; img-src * data:; style-src 'self' 'unsafe-inline'") - h.Set("Permissions-Policy", "payment=(), interest-cohort=()") - h.Set("Referrer-Policy", "no-referrer") - h.Set("X-Content-Type-Options", "nosniff") - if !wui.debug { - h.Set("X-Frame-Options", "sameorigin") - } - w.WriteHeader(statusCode) -} DELETED web/server/impl/http.go Index: web/server/impl/http.go ================================================================== --- web/server/impl/http.go +++ /dev/null @@ -1,78 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package impl provides the Zettelstore web service. -package impl - -import ( - "context" - "net" - "net/http" - "time" -) - -// Server timeout values -const ( - shutdownTimeout = 5 * time.Second - readTimeout = 5 * time.Second - writeTimeout = 10 * time.Second - idleTimeout = 120 * time.Second -) - -// httpServer is a HTTP server. -type httpServer struct { - http.Server - waitStop chan struct{} -} - -// initializeHTTPServer creates a new HTTP server object. -func (srv *httpServer) initializeHTTPServer(addr string, handler http.Handler) { - if addr == "" { - addr = ":http" - } - srv.Server = http.Server{ - Addr: addr, - Handler: handler, - - // See: https://blog.cloudflare.com/exposing-go-on-the-internet/ - ReadTimeout: readTimeout, - WriteTimeout: writeTimeout, - IdleTimeout: idleTimeout, - } - srv.waitStop = make(chan struct{}) -} - -// SetDebug enables debugging goroutines that are started by the server. -// Basically, just the timeout values are reset. This method should be called -// before running the server. -func (srv *httpServer) SetDebug() { - srv.ReadTimeout = 0 - srv.WriteTimeout = 0 - srv.IdleTimeout = 0 -} - -// Run starts the web server, but does not wait for its completion. -func (srv *httpServer) Run() error { - ln, err := net.Listen("tcp", srv.Addr) - if err != nil { - return err - } - - go func() { srv.Serve(ln) }() - return nil -} - -// Stop the web server. -func (srv *httpServer) Stop() { - ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) - defer cancel() - - srv.Shutdown(ctx) -} DELETED web/server/impl/impl.go Index: web/server/impl/impl.go ================================================================== --- web/server/impl/impl.go +++ /dev/null @@ -1,136 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2021-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package impl provides the Zettelstore web service. -package impl - -import ( - "context" - "net/http" - "time" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/domain/meta" - "zettelstore.de/z/logger" - "zettelstore.de/z/web/server" -) - -type myServer struct { - log *logger.Logger - server httpServer - router httpRouter - persistentCookie bool - secureCookie bool -} - -// New creates a new web server. -func New(log *logger.Logger, listenAddr, urlPrefix string, persistentCookie, secureCookie bool, maxRequestSize int64, auth auth.TokenManager) server.Server { - srv := myServer{ - log: log, - persistentCookie: persistentCookie, - secureCookie: secureCookie, - } - srv.router.initializeRouter(log, urlPrefix, maxRequestSize, auth) - srv.server.initializeHTTPServer(listenAddr, &srv.router) - return &srv -} - -func (srv *myServer) Handle(pattern string, handler http.Handler) { - srv.router.Handle(pattern, handler) -} -func (srv *myServer) AddListRoute(key byte, method server.Method, handler http.Handler) { - srv.router.addListRoute(key, method, handler) -} -func (srv *myServer) AddZettelRoute(key byte, method server.Method, handler http.Handler) { - srv.router.addZettelRoute(key, method, handler) -} -func (srv *myServer) SetUserRetriever(ur server.UserRetriever) { - srv.router.ur = ur -} -func (srv *myServer) GetUser(ctx context.Context) *meta.Meta { - if data := srv.GetAuthData(ctx); data != nil { - return data.User - } - return nil -} -func (srv *myServer) NewURLBuilder(key byte) *api.URLBuilder { - return api.NewURLBuilder(srv.GetURLPrefix(), key) -} -func (srv *myServer) GetURLPrefix() string { - return srv.router.urlPrefix -} - -const sessionName = "zsession" - -func (srv *myServer) SetToken(w http.ResponseWriter, token []byte, d time.Duration) { - cookie := http.Cookie{ - Name: sessionName, - Value: string(token), - Path: srv.GetURLPrefix(), - Secure: srv.secureCookie, - HttpOnly: true, - SameSite: http.SameSiteLaxMode, - } - if srv.persistentCookie && d > 0 { - cookie.Expires = time.Now().Add(d).Add(30 * time.Second).UTC() - } - srv.log.Debug().Bytes("token", token).Msg("SetToken") - if v := cookie.String(); v != "" { - w.Header().Add("Set-Cookie", v) - w.Header().Add("Cache-Control", `no-cache="Set-Cookie"`) - w.Header().Add("Vary", "Cookie") - } -} - -// ClearToken invalidates the session cookie by sending an empty one. -func (srv *myServer) ClearToken(ctx context.Context, w http.ResponseWriter) context.Context { - if authData := srv.GetAuthData(ctx); authData == nil { - // No authentication data stored in session, nothing to do. - return ctx - } - if w != nil { - srv.SetToken(w, nil, 0) - } - return updateContext(ctx, nil, nil) -} - -// GetAuthData returns the full authentication data from the context. -func (*myServer) GetAuthData(ctx context.Context) *server.AuthData { - data, ok := ctx.Value(ctxKeySession).(*server.AuthData) - if ok { - return data - } - return nil -} - -type ctxKeyTypeSession struct{} - -var ctxKeySession ctxKeyTypeSession - -func updateContext(ctx context.Context, user *meta.Meta, data *auth.TokenData) context.Context { - if data == nil { - return context.WithValue(ctx, ctxKeySession, &server.AuthData{User: user}) - } - return context.WithValue( - ctx, - ctxKeySession, - &server.AuthData{ - User: user, - Token: data.Token, - Now: data.Now, - Issued: data.Issued, - Expires: data.Expires, - }) -} - -func (srv *myServer) SetDebug() { srv.server.SetDebug() } -func (srv *myServer) Run() error { return srv.server.Run() } -func (srv *myServer) Stop() { srv.server.Stop() } DELETED web/server/impl/router.go Index: web/server/impl/router.go ================================================================== --- web/server/impl/router.go +++ /dev/null @@ -1,250 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2022 Detlef Stern -// -// This file is part of Zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package impl provides the Zettelstore web service. -package impl - -import ( - "io" - "net/http" - "regexp" - "strings" - - "zettelstore.de/c/api" - "zettelstore.de/z/auth" - "zettelstore.de/z/kernel" - "zettelstore.de/z/logger" - "zettelstore.de/z/web/server" -) - -type ( - methodHandler [server.MethodLAST]http.Handler - routingTable [256]*methodHandler -) - -var mapMethod = map[string]server.Method{ - http.MethodHead: server.MethodHead, - http.MethodGet: server.MethodGet, - http.MethodPost: server.MethodPost, - http.MethodPut: server.MethodPut, - http.MethodDelete: server.MethodDelete, - api.MethodMove: server.MethodMove, -} - -// httpRouter handles all routing for zettelstore. -type httpRouter struct { - log *logger.Logger - urlPrefix string - auth auth.TokenManager - minKey byte - maxKey byte - reURL *regexp.Regexp - listTable routingTable - zettelTable routingTable - ur server.UserRetriever - mux *http.ServeMux - maxReqSize int64 -} - -// initializeRouter creates a new, empty router with the given root handler. -func (rt *httpRouter) initializeRouter(log *logger.Logger, urlPrefix string, maxRequestSize int64, auth auth.TokenManager) { - rt.log = log - rt.urlPrefix = urlPrefix - rt.auth = auth - rt.minKey = 255 - rt.maxKey = 0 - rt.reURL = regexp.MustCompile("^$") - rt.mux = http.NewServeMux() - rt.maxReqSize = maxRequestSize -} - -func (rt *httpRouter) addRoute(key byte, method server.Method, handler http.Handler, table *routingTable) { - // Set minKey and maxKey; re-calculate regexp. - if key < rt.minKey || rt.maxKey < key { - if key < rt.minKey { - rt.minKey = key - } - if rt.maxKey < key { - rt.maxKey = key - } - rt.reURL = regexp.MustCompile( - "^/(?:([" + string(rt.minKey) + "-" + string(rt.maxKey) + "])(?:/(?:([0-9]{14})/?)?)?)$") - } - - mh := table[key] - if mh == nil { - mh = new(methodHandler) - table[key] = mh - } - mh[method] = handler - if method == server.MethodGet { - if prevHandler := mh[server.MethodHead]; prevHandler == nil { - mh[server.MethodHead] = handler - } - } -} - -// addListRoute adds a route for the given key and HTTP method to work with a list. -func (rt *httpRouter) addListRoute(key byte, method server.Method, handler http.Handler) { - rt.addRoute(key, method, handler, &rt.listTable) -} - -// addZettelRoute adds a route for the given key and HTTP method to work with a zettel. -func (rt *httpRouter) addZettelRoute(key byte, method server.Method, handler http.Handler) { - rt.addRoute(key, method, handler, &rt.zettelTable) -} - -// Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics. -func (rt *httpRouter) Handle(pattern string, handler http.Handler) { - rt.mux.Handle(pattern, handler) -} - -func (rt *httpRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) { - // Something may panic. Ensure a kernel log. - defer func() { - if reco := recover(); reco != nil { - rt.log.Error().Str("Method", r.Method).Str("URL", r.URL.String()).Str("ip", getCallerIP(r)).Msg("Recover context") - kernel.Main.LogRecover("Web", reco) - } - }() - - var withDebug bool - if msg := rt.log.Debug(); msg.Enabled() { - withDebug = true - w = &traceResponseWriter{original: w} - msg.Str("method", r.Method).Str("uri", r.RequestURI).Str("ip", getCallerIP(r)).Msg("ServeHTTP") - } - - if prefixLen := len(rt.urlPrefix); prefixLen > 1 { - if len(r.URL.Path) < prefixLen || r.URL.Path[:prefixLen] != rt.urlPrefix { - http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) - if withDebug { - rt.log.Debug().Int("sc", int64(w.(*traceResponseWriter).statusCode)).Msg("/ServeHTTP/prefix") - } - return - } - r.URL.Path = r.URL.Path[prefixLen-1:] - } - r.Body = http.MaxBytesReader(w, r.Body, rt.maxReqSize) - match := rt.reURL.FindStringSubmatch(r.URL.Path) - if len(match) != 3 { - rt.mux.ServeHTTP(w, rt.addUserContext(r)) - if withDebug { - rt.log.Debug().Int("sc", int64(w.(*traceResponseWriter).statusCode)).Msg("match other") - } - return - } - if withDebug { - rt.log.Debug().Str("key", match[1]).Str("zid", match[2]).Msg("path match") - } - - key := match[1][0] - var mh *methodHandler - if match[2] == "" { - mh = rt.listTable[key] - } else { - mh = rt.zettelTable[key] - } - method, ok := mapMethod[r.Method] - if ok && mh != nil { - if handler := mh[method]; handler != nil { - r.URL.Path = "/" + match[2] - handler.ServeHTTP(w, rt.addUserContext(r)) - if withDebug { - rt.log.Debug().Int("sc", int64(w.(*traceResponseWriter).statusCode)).Msg("/ServeHTTP") - } - return - } - } - http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) - if withDebug { - rt.log.Debug().Int("sc", int64(w.(*traceResponseWriter).statusCode)).Msg("no match") - } -} - -func (rt *httpRouter) addUserContext(r *http.Request) *http.Request { - if rt.ur == nil { - // No auth needed - return r - } - k := auth.KindJSON - t := getHeaderToken(r) - if len(t) == 0 { - rt.log.Debug().Str("ip", getCallerIP(r)).Msg("no jwt token found") - k = auth.KindHTML - t = getSessionToken(r) - } - if len(t) == 0 { - rt.log.Sense().Str("ip", getCallerIP(r)).Msg("no auth token found in request") - return r - } - tokenData, err := rt.auth.CheckToken(t, k) - if err != nil { - rt.log.Sense().Err(err).Str("ip", getCallerIP(r)).Msg("invalid auth token") - return r - } - ctx := r.Context() - user, err := rt.ur.GetUser(ctx, tokenData.Zid, tokenData.Ident) - if err != nil { - rt.log.Sense().Zid(tokenData.Zid).Str("ident", tokenData.Ident).Err(err).Str("ip", getCallerIP(r)).Msg("auth user not found") - return r - } - return r.WithContext(updateContext(ctx, user, &tokenData)) -} - -func getCallerIP(r *http.Request) string { - if from := r.Header.Get("X-Forwarded-For"); from != "" { - return from - } - return r.RemoteAddr -} - -func getSessionToken(r *http.Request) []byte { - cookie, err := r.Cookie(sessionName) - if err != nil { - return nil - } - return []byte(cookie.Value) -} - -func getHeaderToken(r *http.Request) []byte { - h := r.Header["Authorization"] - if h == nil { - return nil - } - - // “Multiple message-header fields with the same field-name MAY be - // present in a message if and only if the entire field-value for that - // header field is defined as a comma-separated list.” - // — “Hypertext Transfer Protocol” RFC 2616, subsection 4.2 - auth := strings.Join(h, ", ") - - const prefix = "Bearer " - // RFC 2617, subsection 1.2 defines the scheme token as case-insensitive. - if len(auth) < len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) { - return nil - } - return []byte(auth[len(prefix):]) -} - -type traceResponseWriter struct { - original http.ResponseWriter - statusCode int -} - -func (w *traceResponseWriter) Header() http.Header { return w.original.Header() } -func (w *traceResponseWriter) Write(p []byte) (int, error) { return w.original.Write(p) } -func (w *traceResponseWriter) WriteHeader(statusCode int) { - w.statusCode = statusCode - w.original.WriteHeader(statusCode) -} -func (w *traceResponseWriter) WriteString(s string) (int, error) { - return io.WriteString(w.original, s) -} DELETED web/server/server.go Index: web/server/server.go ================================================================== --- web/server/server.go +++ /dev/null @@ -1,93 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2020-2021 Detlef Stern -// -// This file is part of zettelstore. -// -// Zettelstore is licensed under the latest version of the EUPL (European Union -// Public License). Please see file LICENSE.txt for your rights and obligations -// under this license. -//----------------------------------------------------------------------------- - -// Package server provides the Zettelstore web service. -package server - -import ( - "context" - "net/http" - "time" - - "zettelstore.de/c/api" - "zettelstore.de/z/domain/id" - "zettelstore.de/z/domain/meta" -) - -// UserRetriever allows to retrieve user data based on a given zettel identifier. -type UserRetriever interface { - GetUser(ctx context.Context, zid id.Zid, ident string) (*meta.Meta, error) -} - -// Method enumerates the allowed HTTP methods. -type Method uint8 - -// Values for method type -const ( - MethodGet Method = iota - MethodHead - MethodPost - MethodPut - MethodMove - MethodDelete - MethodLAST // must always be the last one -) - -// Router allows to state routes for various URL paths. -type Router interface { - Handle(pattern string, handler http.Handler) - AddListRoute(key byte, method Method, handler http.Handler) - AddZettelRoute(key byte, method Method, handler http.Handler) - SetUserRetriever(ur UserRetriever) -} - -// Builder allows to build new URLs for the web service. -type Builder interface { - GetURLPrefix() string - NewURLBuilder(key byte) *api.URLBuilder -} - -// Auth is the authencation interface. -type Auth interface { - GetUser(context.Context) *meta.Meta - SetToken(w http.ResponseWriter, token []byte, d time.Duration) - - // ClearToken invalidates the session cookie by sending an empty one. - ClearToken(ctx context.Context, w http.ResponseWriter) context.Context - - // GetAuthData returns the full authentication data from the context. - GetAuthData(ctx context.Context) *AuthData -} - -// AuthData stores all relevant authentication data for a context. -type AuthData struct { - User *meta.Meta - Token []byte - Now time.Time - Issued time.Time - Expires time.Time -} - -// AuthBuilder is a Builder that also allows to execute authentication functions. -type AuthBuilder interface { - Auth - Builder -} - -// Server is the main web server for accessing Zettelstore via HTTP. -type Server interface { - Router - Auth - Builder - - SetDebug() - Run() error - Stop() -} Index: www/build.md ================================================================== --- www/build.md +++ www/build.md @@ -1,57 +1,94 @@ -# How to build the Zettelstore +# How to build Zettelstore + ## Prerequisites + You must install the following software: -* A current, supported [release of Go](https://golang.org/doc/devel/release.html), +* A current, supported [release of Go](https://go.dev/doc/devel/release), * [staticcheck](https://staticcheck.io/), +* [shadow](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/shadow), +* [unparam](https://mvdan.cc/unparam), +* [govulncheck](https://golang.org/x/vuln/cmd/govulncheck), +* [revive](https://revive.run/), * [Fossil](https://fossil-scm.org/), * [Git](https://git-scm.org) (so that Go can download some dependencies). +See folder `docs/development` (a zettel box) for details. + ## Clone the repository -Most of this is covered by the excellent Fossil [documentation](https://fossil-scm.org/home/doc/trunk/www/quickstart.wiki). +Most of this is covered by the excellent Fossil +[documentation](https://fossil-scm.org/home/doc/trunk/www/quickstart.wiki). 1. Create a directory to store your Fossil repositories. - Let's assume, you have created <tt>$HOME/fossils</tt>. + Let's assume, you have created `$HOME/fossils`. 1. Clone the repository: `fossil clone https://zettelstore.de/ $HOME/fossils/zettelstore.fossil`. 1. Create a working directory. - Let's assume, you have created <tt>$HOME/zettelstore</tt>. + Let's assume, you have created `$HOME/zettelstore`. 1. Change into this directory: `cd $HOME/zettelstore`. 1. Open development: `fossil open $HOME/fossils/zettelstore.fossil`. -(If you are not able to use Fossil, you could try the GitHub mirror -<https://github.com/zettelstore/zettelstore>.) - -## The build tool -In directory <tt>tools</tt> there is a Go file called <tt>build.go</tt>. -It automates most aspects, (hopefully) platform-independent. - -The script is called as: - -``` -go run tools/build.go [-v] COMMAND -``` +## Tools to build, test, and manage +In the directory `tools` there are some Go files to automate most aspects of +building and testing, (hopefully) platform-independent. + +The build script is called as: + + go run tools/build/build.go [-v] COMMAND The flag `-v` enables the verbose mode. It outputs all commands called by the tool. Some important `COMMAND`s are: * `build`: builds the software with correct version information and puts it - into a freshly created directory <tt>bin</tt>. + into a freshly created directory `bin`. * `check`: checks the current state of the working directory to be ready for release (or commit). -* `clean`: removes the build directories and cleans the Go cache. * `version`: prints the current version information. Therefore, the easiest way to build your own version of the Zettelstore software is to execute the command -``` -go run tools/build.go build -``` + go run tools/build/build.go build In case of errors, please send the output of the verbose execution: -``` -go run tools/build.go -v build -``` + go run tools/build/build.go -v build + +Other tools are: + +* `go run tools/clean/clean.go` cleans your Go development workspace. +* `go run tools/check/check.go` executes all linters and unit tests. + If you add the option `-r` linters are more strict, to be used for a + release version. +* `go run tools/devtools/devtools.go` install all needed software (see above). +* `go run tools/htmllint/htmllint.go [URL]` checks all generated HTML of a + Zettelstore accessible at the given URL (default: http://localhost:23123). +* `go run tools/testapi/testapi.go` tests the API against a running + Zettelstore, which is started automatically. + +## A note on the use of Fossil + +Zettelstore is managed by the Fossil version control system. Fossil is an +alternative to the ubiquitous Git version control system. However, Go seems to +prefer Git and popular platforms that just support Git. + +Some dependencies of Zettelstore, namely [Zettelstore +client](https://t73f.de/r/zsc), [webs](https://t73f.de/r/webs), +[sx](https://t73f.de/r/sx), [sxwebs](https://t73f.de/r/sxwebs), +[zero](https://t73f.de/r/zero), and [zsx](https://t73f.de/r/zsx/) are also +managed by Fossil. Depending on your development setup, some error messages +might occur. + +If the error message mentions an environment variable called `GOVCS` you should +set it to the value `GOVCS=zettelstore.de:fossil` (alternatively more generous +to `GOVCS=*:all`). Since the Go build system is coupled with Git and some +special platforms, you must allow Go to download a Fossil repository from the +host `zettelstore.de`. The build tool sets `GOVCS` to the right value, but you +may use other `go` commands that try to download a Fossil repository. + +On some operating systems, namely Termux on Android, an error message might +state that an user cannot be determined (`cannot determine user`). In this +case, Fossil is allowed to download the repository, but cannot associate it +with an user name. Set the environment variable `USER` to any user name, like: +`USER=nobody go run tools/build.go build`. Index: www/changes.wiki ================================================================== --- www/changes.wiki +++ www/changes.wiki @@ -1,11 +1,802 @@ <title>Change Log - -

Changes for Version 0.6.0 (pending)

+ +

Changes for Version 0.22.0 (pending)

+ * Sx builtin (bind-lookup ...) is replaced with + (resolve-symbol ...). If you maintain your own Sx code to + customize Zettelstore behaviour, you must update your code; otherwise it + will break. If your code use (ROLE-DEFAULT-action ...) + , infinite recursion might occur. This is now handled with the new startup + configuration sx-max-nesting. In such cases, you should omit + the call to ROLE-DEFAULT-action. For debugging purposes, use + the web:trace logging level, which logs all Sx computations. + (breaking: webui) + * Sx templates are changed: base.sxn, info.sxn, zettel.sxn. If you are using + a (self-) modified version, you should update your modifications. + (breaking: webui) + * Remove zettel for the Sx prelude. Fortunately, it was never documented, + so it was likely unused. The prelude is now a constant string whithin Sx's + code base. + (breaking: webui) + * Remove support for metadata keys predecessor and + successors. A Zettelstore is not a version control system. + Use precursor instead (if appropriate), use your own metadata + key (which should end with -zids, or get rid of manually + versioned zettel. In the WebUI, action “version” is removed. + (breaking) + * New query directives FOLGE, SEQUEL, and + THREAD support folge zettel and sequel zettel (and both). See + the manual for details. To make working with these directives a little bit + more easier, appropriate query links are placed on main zettel web user + interface and on info zettel page. + (major) + * If authentication is enabled, Zettelstore can now be accessed from the + loopback device without logging in or obtaining an access token. + (major: api, webui) + * Context directive allows DIRECTED. + (minor) + * Metadata with keys ending with -ref or -refs are + interpreted as zettel identifier. + (minor) + * The new startup configuration key sx-max-nesting allows + setting a limit on the nesting depth of Sx computations. This is primarily + useful to prevent unbounded recursion due to programming errors. + Previously, such issues would crash the Zettelstore. + (minor: webui) + * At logging level trace, the web user interface now logs all + Sx computations, mainly those used for rendering HTML templates. + (minor: webui) + * Move context link to zettel page. + (minor: webui) + + +

Changes for Version 0.21.0 (2025-04-17)

+ * Change zettel identifier for Zettelstore Log, Zettelstore Memory, and + Zettelstore Sx Engine. See manual for updated identifier values. + (breaking) + * Sz encodings of links were simplified into one LINK symbol. + Different link types are now specified by reference node. + (breaking: api) + * Sz encodings of lists, descriptions, tables, table cells, and block BLOBs + have now an additional attributes entry, directly after the initial + symbol. + (breaking: api) + * Sz encoding for table cell alignment (CELL-*) is now done via + table cell attribute (align . *), where * is the + alignment value ("center", "left", or + "right"). + (breaking: api) + * New API endpoint /r/{ZID} retrieves references of a zettel. + (major: api) + * New computed zettel Zettelstore Modules, which shows all Go modules + Zettelstore is dependent to. + (minor) + * Move most of the code to new internal package internal, to + make reuse by other software a little bit harder. + * Move some code to external packages, esp. to Zettelstore Client, webs. + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.20.0 (2025-03-07)

+ * Metadata with keys that have the suffix -title are no longer + interpreted as Zettelmarkup. This was a leftover from [#0_11|v0.11], when + type of metadata title was changed from Zettelmarkup to a + possibly empty string. + (breaking) + * Type of metadata key summary changed from Zettelmarkup to + plain text. You might need to update your zettel that contain this key. + (breaking) + * Remove support for metadata type Zettelmarkup. It made + implementation too complex, and it was seldom used (see above). + (breaking) + * Remove metadata key created-missing, which was used to + support the cancelled migration process into a four letter zettel + identifier format. + (breaking) + * Remove support for inline zettel snippets. Mostly used for some HTML + elements, which hinders portability and encoding in other formats. + (breaking: zettelmarkup) + * Remove support for inline HTML text within Markdown text. Such HTML code + (did I ever say that Markdown is just a super-set of HTML?) is now + translated into literal text. + (breaking: markdown/CommonMark) + * Query aggregates ATOM and RSS are removed, as + well as the accompanying TITLE query action (parameter). + Was announced as deprecated in version 0.19. + (breaking) + * Query data encoding and aggregate data encoding were changed to remove the + superfluous (list ...). Instead, the result list is now + spliced into the returned s-expression list. If you use the Zettelstore + Client, it will handle that for you. + (breaking: api) + * “Lists” menu is build by reading a zettel with menu items + (Default: 00000000080001) instead of being hard coded. Can be + customized with runtime and user configuration + lists-menu-zettel. + (major: webui) + * Show metadata values superior and subordinate + on WebUI (again). Partially reverses the removal of support for these + values in v0.19. However, creating child zettel is not supported. + (major: webui) + * Implement CONTEXT query more correctly, as stated in the + manual; add MIN directive. + (minor) + * Remove timeouts for API and WebUI. If faced to the public internet, + Zettelstore should run behind a full proxy, like Caddy server, Nginx, or + similar. + (minor: api, webui) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.19.0 (2024-12-13)

+ * Remove support for renaming zettel, i.e. changing zettel identifier. Was + announced as deprecated in version 0.18. + (breaking: api, webui) + * Format of zettel identifier will be not changed. The deprecation message + from version 0.18 is no longer valid. + (major) + * Zettel content for most predefined zettel (ID less or equal than + 0000099999899) is not indexed any more. If you search / query for zettel + content, these zettel will not be returned. However, their metadata is + still searchable. Content of predefined zettel with ID between + 00000999999900 and 00000999999999 will be indexed.. + (breaking: api, webui) + * Metadata keys superior and subordinate are not + supported on the WebUI any more. They are still typed as a set of zettel + identifier, but are treated as ordinary links. Zettel should not form a + hierarchy, in most cases. + (major: webui) + * Metadata keys sequel and prequel support a + sequence of zettel. They are supported through the WebUI also. + sequel is calculated based on prequel. While + folge zettel are a train of thought, zettel sequences form different train + of thoughts. + (major) + * Query aggregates ATOM and RSS will be removed in + the next version of Zettelstore. They were introduced in [#0_7|v0.7] and + [#0_8|v0.8]. Both are not needed for a digital zettelkasten. Their current + use is to transform Zettelstore into a blogging engine. RSS and Atom feed + can be provided by external software, much better than Zettelstore will + ever do. + (deprecation) + * Fix wrong quote translation for markdown encoder. + (minor) + * Generate <th> in table header (was: <td>). + Also applies to SHTML encoder. (minor: webui, api) + * External links are now generated in shtml and html with attribute + rel="external" (previously: class="external"). + (minor: webui, api) + * Allow to enable runtime profiling of the software, to be used by + developers. + (minor) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.18.0 (2024-07-11)

+ * Remove Sx macro defunconst. Use defun instead. + (breaking: webui) + * The sz encoding of zettel does not make use of (SPACE) + elements any more. Instead, space characters are encoded within the + (TEXT "...") element. This might affect any client that works + with the sz encoding to produce some output. + (breaking) + * Format of zettel identifier will be changed in the future to a new format, + instead of the current timestamp-based format. The usage of zettel + identifier that are before 1970-01-01T00:00:00 is not allowed any more + (with the exception of predefined identifier) + (deprecation) + * Due to the planned format of zettel identifier, the “rename” + operation is deprecated. It will be removed in version 0.19 or later. If + you have a significant use case for the rename operation, please contact + the maintainer immediate. + (deprecation) + * New zettel are now created with the permission for others to read/write + them. This is important especially for Unix-like systems. If you want the + previous behaviour, set umask accordingly, for example + umask 066. + (major: dirbox) + * Add expert-mode zettel “Zettelstore Warnings” to help + identifying zettel to upgrade for future migration to planned new zettel + identifier format. + (minor: webui) + * Add expert-mode zettel “Zettelstore Identifier Mapping” to + show a possible mapping from the old identifier format to the new one. + This should help users to possibly rename some zettel for a better + mapping. + (minor: webui) + * Add metadata key created-missing to list zettel without + stored metadata key created. Needed for migration to planned + new zettelstore identifier format, which is not based on timestamp of + zettel creation date. + (minor) + * Add zettel “Zettelstore Application Directory”, which contains + identifier for application specific zettel. Needed for planned new + identifier format. + (minor: webui) + * Update Sx prelude: make macros more robust / more general. This might + break your code in the future. + (minor: webui) + * Add computed expert-mode zettel “Zettelstore Memory” with + zettel identifier 00000000000008. It shows some statistics + about memory usage. + (minor: webui) + * Add computed expert-mode zettel “Zettelstore Sx Engine” with + zettel identifier 00000000000009. It shows some statistics + about the internal Sx engine. (Currently only the number of used symbols, + but this will change in the future.) + (minor: webui) + * Zettelstore client is now Go package t73f.de/r/zsc. + (minor) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.17.0 (2024-03-04)

+ * Context search operates only on explicit references. Add the directive + FULL to follow zettel tags additionally. + (breaking) + * Context cost calculation has been changed. Prepare to retrieve different + result. + (breaking) + * Remove metadata type WordSet. It was never implemented completely, and + nobody complained about this. + (breaking) + * Remove logging level “sense”, “warn”, + “fatal”, and “panic”. + (breaking) + * Add query action REDIRECT which redirects to zettel that is + the first in the query result list. + (minor: api, webui) + * Add link to CONTEXT FULL in the zettel info page. + (minor: webui) + * When generating HTML code to query set based metadata (esp. tags), also + generate a query that matches all values. + (minor: webui) + * Show all metadata with key ending “-url” on zettel view. + (minor: webui) + * Make WebUI form elements a little bit more accessible by using HTML + search tag and inputmode attribute. + (minor: webui) + * Add UI action for role zettel, similar to tag zettel. Obviously forgotten + in release 0.16.0, but thanks to the bug fix v0.16.1 detected. + (minor: webui) + * If an action, which is written in uppercase letters, results in an empty + list, the list of selected zettel is returned instead. This allows some + backward compatibility if a new action is introduced. + (minor) + * Only when query list is not empty, allow to show data and plain encoding, + an optionally show the “Save As Zettel” button. + (minor: webui) + * If query list is greater than three elements, show the number of elements + at bottom (before other encodings). + (minor: webui) + * Zettel with syntax “sxn” are pretty-printed during evaluation. + This allows to retrieve parsed zettel content, which checked for syntax, + but is not pretty-printed. + (minor) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.16.1 (2023-12-28)

+ * Fix some Sxn definitions to allow role-based UI customizations. + (minor: webui) + +

Changes for Version 0.16.0 (2023-11-30)

+ * Sx function define is removed, as announced for version + 0.15.0. Use defvar (to define variables) or + defun (to define functions) instead. In addition + defunconst defines a constant function, which ensures a fixed + binding of its name to its function body (performance optimization). + (breaking: webui) + * Allow to determine a role zettel for a given role. + (major: api, webui) + * Present user the option to create a (missing) role zettel (in list view). + Results in a new predefined zettel with identifier 00000000090004, which + is a template for new role zettel. + (minor: webui) + * Timestamp values can be abbreviated by omitting most of its components. + Previously, such values that are not in the format YYYYMMDDhhmmss were + ignored. Now the following formats are also allowed: YYYY, YYYYMM, + YYYYMMDD, YYYYMMDDhh, YYYYMMDDhhmm. Querying and sorting work accordingly. + Previously, only a sequences of zeroes were appended, resulting in illegal + timestamps, e.g. for YYYY or YYYYMM. + (minor) + * SHTML encoder fixed w.r.t inline quoting. Previously, an <q> tag was + used, which is inappropriate. Restored smart quotes from version 0.3, but + with new SxHTML infrastructure. This affect the html encoder and the WebUI + too. Now, an empty quote should not result in a warning by HTML linters. + (minor: api, webui) + * Add new zettelmarkup inline formatting: ##Text## will mark / + highlight the given Text. It is typically used to highlight some text, + which is important for you, but not for the original author. When rendered + as HTML, the <mark> tag is used. + (minor: zettelmarkup) + * Add configuration keys to show, not to show, or show the closed list of + referencing zettel in the web user interface. You can set these + configurations system-wide, per user, or per zettel. Often it is used to + ensure a “clean” home zettel. Affects the list of incoming + / back links, folge zettel, subordinate zettel, and successor zettel. + (minor: webui) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.15.0 (2023-10-26)

+ * Sx function define is now deprecated. It will be removed in + version 0.16. Use defvar or defun instead. + Otherwise the WebUI will not work in version 0.16. + (major: webui, deprecated) + * Zettel can be re-indexed via WebUI or API query action + REINDEX. The info page of a zettel contains a link to + re-index the zettel. In a query transclusion, this action is ignored. + (major: api, webui). + * Allow to determine a tag zettel for a given tag. + (major: api, webui) + * Present user the option to create a (missing) tag zettel (in list view). + Results in a new predefined zettel with identifier 00000000090003, which + is a template for new tag zettel. + (minor: webui) + * ZIP file with manual now contains a zettel 00001000000000 that contains + its build date (metadata key created) and version (in the + zettel content) + (minor) + * If an error page cannot be created due to template errors (or similar), a + plain text error page is delivered instead. It shows the original error + and the error that occurred during rendering the original error page. + (minor: webui) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.14.0 (2023-09-22)

+ * Remove support for JSON. This was marked deprecated in version 0.12.0. Use + the data encoding instead, a form of symbolic expressions. + (breaking: api; minor: webui) + * Remove deprecated syntax for a context list: CONTEXT zid. Use + zid CONTEXT instead. It was deprecated in version 0.13.0. + (breaking: api, webui, zettelmarkup) + * Replace CSS-role-map mechanism with a more general Sx-based one: user + specific code may generates parts of resulting HTML document. + (breaking: webui) + * Allow meta-tags, i.e. zettel for a specific tag. Meta-tags have the tag + name as a title and specify the role "tag". + (major: webui) + * Allow to load sx code from multiple zettel; dependencies are specified + using precursor metadata. + (major: webui) + * Allow sx code to change WebUI for zettel with specified role. + (major: webui) + * Some minor usability improvements. + (minor: webui) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.13.0 (2023-08-07)

+ * There are for new search operators: less, not less, greater, not greater. + These use the same syntax as the operators prefix, not prefix, suffix, not + suffix. The latter are now denoted as [, ![, + ], and !]. The first may operate numerically for + metadata like numbers, timestamps, and zettel identifier. They are not + supported for full-text search. + (breaking: api, webui) + * The API endpoint /o/{ID} (order of zettel ID) is no longer + available. Please use the query expression {ID} ITEMS + instead. + (breaking: api) + * The API endpoint /u/{ID} (unlinked references of zettel ID) + is no longer available. Please use the query expression {ID} + UNLINKED instead. + (breaking: api) + * All API endpoints allow to encode zettel data with the data + encodings, incl. creating, updating, retrieving, and querying zettel. + (major: api) + * Change syntax for context query to zid ... CONTEXT. This will + allow to add more directives that operate on zettel identifier. Old syntax + CONTEXT zid will be removed in 0.14. + (major, deprecated) + * Add query directive ITEMS that will produce a list of + metadata of all zettel that are referenced by the originating zettel in + a top-level list. It replaces the API endpoint /o/{ID} (and + makes it more useful). + (major: api, webui) + * Add query directive UNLINKED that will produce a list of + metadata of all zettel that are mentioning the originating zettel in + a top-level, but do not mention them. It replaces the API endpoint + /u/{ID} (and makes it more useful). + (major: api, webui) + * Add query directive IDENT to distinguish a search for + a zettel identifier (“{ID}”), that will list all metadata of + zettel containing that zettel identifier, and a request to just list the + metadata of given zettel (“{ID} IDENT”). The latter could be + filtered further. + (minor: api, webui) + * Add support for metadata key folge-role. + (minor) + * Allow to create a child from a given zettel. + (minor: webui) + * Make zettel entry/edit form a little friendlier: auto-prepend missing '#' + to tags; ensure that role and syntax receive just a word. + (minor: webui) + * Use a zettel that defines builtins for evaluating WebUI templates. + (minor: webui) + * Add links to retrieve result of a query in other formats. + (minor: webui) + * Always log the found configuration file. + (minor: server) + * The use of the json zettel encoding is deprecated (since + version 0.12.0). Support for this encoding will be removed in version + 0.14.0. Please use the new data encoding instead. + (deprecated: api) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.12.0 (2023-06-05)

+ * Syntax of templates for the web user interface are changed from Mustache + to Sxn (S-Expressions). Mustache is no longer supported, nowhere in the + software. Mustache was marked deprecated in version 0.11.0. If you + modified the template zettel, you must adapt to the new syntax. + (breaking: webui) + * Query expression is allowed to search for the "context" of a zettel. + Previously, this was a separate call, without adding a search expression + / action expression. + (breaking) + * "sexpr" encoding is renamed to "sz" encoding. This will affect mostly the + API. Additionally, all string "sexpr" are renamed to "sz" also. "Sz" is + the short form for "symbolic expression for zettel", similar to "shtml" + that is the short form for "symbolic expression for HTML". + (breaking) + * Render footer zettel on all WebUI pages. + (fix: webui) + * Query search operator "=" now compares for equality, ":" compares + depending on the value type. + (minor: api, webui) + * Search term PICK now respects the original sort order. This + makes it more useful and orthogonal to RANDOM and + LIMIT. As a side effect, zettel lists retrieved via the API + are no longer sorted. In case you want a specific order, you must specify + it explicit. + (minor: api, webui) + * New metadata key expire records a timestamp when a zettel + should be treated as, well, expired. + (minor) + * New metadata keys superior and subordinate + (calculated from superior) allow to specify a hierarchy + between zettel. + (minor) + * Metadata keys with suffix -date and -time are + treated as + timestamp values. + (minor) + * sexpr zettel encoding is now documented in the manual. + (minor: manual) + * Build tool allows to install / update external Go tools needed to build + the software. + (minor) + * Show only useful metadata on WebUI, not the internal metadata. + (minor: webui) + * The use of the json zettel encoding is deprecated. Support + for this encoding may be removed in future versions. Please use the new + data encoding instead. + (deprecated: api) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.11.2 (2023-04-16)

+ * Render footer zettel on all WebUI pages. Backported from 0.12.0. Many + thanks to HK for reporting it! + (fix: webui) + +

Changes for Version 0.11.1 (2023-03-28)

+ * Make PICK search term a little bit more deterministic so that + the “Save As Zettel” button produces the same list. + (fix: webui) + +

Changes for Version 0.11.0 (2023-03-27)

+ * Remove ZJSON encoding. It was announced in version 0.10.0. Use Sexpr + encoding instead. + (breaking) + * Title of a zettel is no longer interpreted as Zettelmarkup text. Now it is + just a plain string, possibly empty. Therefore, no inline formatting (like + bold text), no links, no footnotes, no citations (the latter made + rendering the title often questionable, in some contexts). If you used + special entities, please use the Unicode characters directly. However, as + a good practice, it is often the best to printable ASCII characters. + (breaking) + * Remove runtime configuration marker-external. It was added in + version [#0_0_6|0.0.6] and updated in [#0_0_10|0.0.10]. If you want to + change the marker for an external URL, you could modify zettel + 00000000020001 (Zettelstore Base CSS) or zettel 00000000025001 + (Zettelstore User CSS, preferred) by changing / adding a rule to add some + content after an external tag. + (breaking: webui) + * Add SHTML encoding. This allows to ensure the quality of generated HTML + code. In addition, clients might use it, because it is easier to parse and + manipulate than ordinary HTML. In the future, HTML template zettel will + probably also use SHTML, deprecating the current Mustache syntax (which + was added in [#0_0_9|0.0.9]). + (major) + * Search term PICK n, where n is an integer value + greater zero, will pick randomly n elements from the search + result list. Somehow similar (and faster) as RANDOM LIMIT n, + but allows also later ordering of the resulting list. + (minor) + * Changed cost model for zettel context: a zettel with more + outgoing/incoming references has higher cost than a zettel with less + references. Also added support for traversing tags, with a similar cost + model. As an effect, zettel hubs (in many cases your home zettel) will + less likely add its references. Same for often used tags. The cost model + might change in some details in the future, but the idea of a penalty + applied to zettel / tags with many references will hold. + (minor) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.10.1 (2023-01-30)

+ * Show button to save a query into a zettel only when the current user has + authorization to do it. + (fix: webui) + +

Changes for Version 0.10.0 (2023-01-24)

+ * Remove support for endpoints /j, /m, /q, /p, /v. Their + functions are merged into endpoint /z. This was announced in + version 0.9.0. Please use only client library with at least version 0.10.0 + too. + (breaking: api) + * Remove support for runtime configuration key footer-html. Use + footer-zettel instead. Deprecated in version 0.9.0. + (breaking: webui) + * Save a query into a zettel to freeze it. + (major: webui) + * Allow to show all used metadata keys, linked with their occurrences and + their values. + (minor: webui) + * Mark ZJSON encoding as deprecated for v0.11.0. Please use Sexpr encoding + instead. + (deprecated) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.9.0 (2022-12-12)

+ * Remove support syntax pikchr. Although it was a nice idea to + include it into Zettelstore, the implementation is too brittle (w.r.t. the + expected long lifetime of Zettelstore). There should be other ways to + support SVG front-ends. + (breaking) + * Allow to upload content when creating / updating a zettel. + (major: webui) + * Add syntax “draw” (again) + (minor: zettelmarkup) + * Allow to encode zettel in Markdown. Please note: not every aspect of + a zettel can be encoded in Markdown. Those aspects will be ignored. + (minor: api) + * Enhance zettel context by raising the importance of folge zettel (and + similar). + (minor: api, webui) + * Interpret zettel files with extension .webp as an binary + image file format. + (minor) + * Allow to specify service specific log level via startup configuration and + via command line. + (minor) + * Allow to specify a zettel to serve footer content via runtime + configuration footer-zettel. Can be overwritten by user + zettel. + (minor: webui) + * Footer data is automatically separated by a thematic break / horizontal + rule. If you do not like it, you have to update the base template. + (minor: webui) + * Allow to set runtime configuration home-zettel in the user + zettel to make it user-specific. + (minor: webui) + * Serve favicon.ico from the asset directory. + (minor: webui) + * Zettelmarkup cheat sheet + (minor: manual) + * Runtime configuration key footer-html will be removed in + Version 0.10.0. Please use footer-zettel instead. + (deprecated: webui) + * In the next version 0.10.0, the API endpoints for a zettel + (/j, /p, /v) will be merged with + endpoint /z. Basically, the previous endpoint will be + refactored as query parameter of endpoint /z. To reduce + errors, there will be no version, where the previous endpoint are still + available and the new functionality is still there. This is a warning to + prepare for some breaking changes in v0.10.0. This also affects the API + client implementation. + (warning: api) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.8.0 (2022-10-20)

+ * Remove support for tags within zettel content. Removes also property + metadata keys all-tags and computed-tags. + Deprecated in version 0.7.0. + (breaking: zettelmarkup, api, webui) + * Remove API endpoint /m, which retrieve aggregated (tags, + roles) zettel identifier. Deprecated in version 0.7.0. + (breaking: api) + * Remove support for URL query parameter starting with an underscore. + Deprecated in version 0.7.0. + (breaking: api, webui) + * Ignore HTML content by default, and allow HTML gradually by setting + startup value insecure-html. + (breaking: markup) + * Endpoint /q returns list of full metadata, if no query action + is specified. A HTTP call GET /z (retrieving metadata of all + or some zettel) is now an alias for GET /q. + (major: api) + * Allow to create a zettel that acts as the new version of an existing + zettel. Useful if you want to have access to older, outdated content. + (minor: webui) + * Allow transclusion to reference local image via URL. + (minor: zettelmarkup, webui) + * Add categories in RSS feed, based on zettel tags. + (minor: api, webui) + * Add support for creating an Atom 1.0 feed using a query action. + (minor: api, webui) + * Ignore entities with code point that is not allowed in HTML. + (minor: zettelmarkup) + * Enhance distribution of tag sizes when show a tag cloud. + (minor: webui) + * Warn user if zettelstore listens non-locally, but no authentication is + enabled. + (minor: server) + * Fix error that a manual zettel deletion was not always detected. + (bug: dirbox) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.7.1 (2022-09-18)

+ * Produce a RSS feed compatible to Miniflux. + (minor) + * Make sure to always produce a pubdata in RSS feed. + (bug) + * Prefix search for data that looks like a zettel identifier may end with a + 0. + (bug) + * Fix glitch on manual zettel. + (bug) + +

Changes for Version 0.7.0 (2022-09-17)

+ * Removes support for URL query parameter to search for metadata values, + sorting, offset, and limit a zettel list. Deprecated in version 0.6.0 + (breaking: api, webui) + * Allow to search for the existence / non-existence of a metadata key with + the "?" operator: key? and key!?. Previously, + the ":" operator was used for this by specifying an empty search value. + Now you can use the ":" operator to find empty / non-empty metadata + values. If you specify a search operator for metadata, the specified key + is assumed to exist. + (breaking: api, webui) + * Rename “search expression” into “query + expressions”. Similar, the reference prefix search: to + specify a query link or a query transclusion is renamed to + query: + (breaking: zettelmarkup) + * Rename query parameter for query expression from _s to + q. + (breaking: api, webui) + * Cleanup names for HTTP query parameters in WebUI. Update your bookmarks + if you used them. (For API: see below) + (breaking: webui) + * Allow search terms to be OR-ed. This allows to specify any search + expression in disjunctive normal form. Therefore, the NEGATE term is not + needed any more. + (breaking: api, webui) + * Replace runtime configuration default-lang with + lang. Additionally, lang set at the zettel of + the current user, will provide a default value for the current user, + overwriting the global default value. + (breaking) + * Add new syntax pikchr, a markup language for diagrams in + technical documentation. + (major) + * Add endpoint /q to query the zettelstore and aggregate + resulting values. This is done by extending the query syntax. + (major: api) + * Add support for query actions. Actions may aggregate w.r.t. some metadata + keys, or produce an RSS feed. + (major: api, webui) + * Query results can be ordered for more than one metadata key. Ordering by + zettel identifier is an implicit last order expression to produce stable + results. + (minor: api, webui) + * Add support for an asset directory, accessible via URL prefix + /assests/. + (minor: server) + * Add support for metadata key created, a time stamp when the + zettel was created. Since key published is now either + created or modified, it will now always contains + a valid time stamp. + (minor) + * Add support for metadata key author. It will be displayed on + a zettel, if set. + (minor: webui) + * Remove CSS for lists. The browsers default value for + padding-left will be used. + (minor: webui) + * Removed templates for rendering roles and tags lists. This is now done by + query actions. + (minor: webui) + * Tags within zettel content are deprecated in version 0.8. This affects the + computed metadata keys content-tags and + all-tags. They will be removed. The number sign of a content + tag introduces unintended tags, esp. in the English language; content tags + may occur within links → links within links, when rendered as HTML; + content tags may occur in the title of a zettel; naming of content tags, + zettel tags, and their union is confusing for many. Migration: use zettel + tags or replace content tag with a search. + (deprecated: zettelmarkup) + * Cleanup names for HTTP query parameter for API calls. Essentially, + underscore characters in front are removed. Please use new names, old + names will be deprecated in version 0.8. + (deprecated: api) + * Some smaller bug fixes and improvements, to the software and to the + documentation. + + +

Changes for Version 0.6.2 (2022-08-22)

+ * Recognize renaming of zettel file external to Zettelstore. + (bug) + +

Changes for Version 0.6.1 (2022-08-22)

+ * Ignore empty tags when reading metadata. + (bug) + +

Changes for Version 0.6.0 (2022-08-11)

+ * Translating of "..." into horizontal ellipsis is no longer supported. Use + &hellip; instead. + (breaking: zettelmarkup) + * Allow to specify search expressions, which allow to specify search + criteria by using a simple syntax. Can be specified in WebUI's search box + and via the API by using query parameter "_s". + (major: api, webui) + * A link reference is allowed to be a search expression. The WebUI will + render this as a link to a list of zettel that satisfy the search + expression. + (major: zettelmarkup, webui) + * A block transclusion is allowed to specify a search expression. When + evaluated, the transclusion is replaced by a list of zettel that satisfy + the search expression. + (major: zettelmarkup) + * When presenting a zettel list, allow to change the search expression. + (minor: webui) + * When evaluating a zettel, ignore transclusions if current user is not + allowed to read transcluded zettel. + (minor) + * Added a small tutorial for Zettelmarkup. + (minor: manual) + * Using URL query parameter to search for metadata values, specify an + ordering, an offset, and a limit for the resulting list, will be removed + in version 0.7. Replace these with the more useable search expressions. + Please be aware that the = search operator is also deprecated. It was only + introduced to help the migration. + (deprecated: api, webui) + * Some smaller bug fixes and improvements, to the software and to the + documentation. - + +

Changes for Version 0.5.1 (2022-08-02)

+ * Log missing authentication tokens in debug level (was: sense level) + (major) + * Allow to use empty metadata values of string and zmk types. + (minor) + * Add IP address to some log messages, esp. when authentication fails. + (minor) +

Changes for Version 0.5.0 (2022-07-29)

* Removed zettel syntax “draw”. The new default syntax for inline zettel is now “text”. A drawing can now be made by using the “evaluation block” syntax (see below) by setting the generic attribute to “draw”. @@ -15,14 +806,14 @@ (breaking) * “Sexpr” encoding replaces “Native” encoding. Sexpr encoding is much easier to parse, compared with native and ZJSON encoding. In most cases it is smaller than ZJSON. (breaking: api) - * Endpoint /r is changed to /m?_key=role and returns now - a map of role names to the list of zettel having this role. Endpoint - /t is changed to /m?_key=tags. It already returned - mapping described before. + * Endpoint /r is changed to /m?_key=role and + returns now a map of role names to the list of zettel having this role. + Endpoint /t is changed to /m?_key=tags. It + already returned mapping described before. (breaking: api) * Remove support for a default value for metadata key title, role, and syntax. Title and role are now allowed to be empty, an empty syntax value defaults to “plain”. (breaking) @@ -46,33 +837,33 @@ * A zettel can be saved while creating / editing it. There is no need to manually re-edit it by using the 'e' endpoint. (minor: webui) * Zettel role and zettel syntax are backed by a HTML5 data list element which lists supported and used values to help to enter a valid value. - (mirnor: webui) + (minor: webui) * Allow to use startup configuration, even if started in simple mode. (minor) * Log authentication issues in level "sense"; add caller IP address to some web server log messages. (minor: web server) * New startup configuration key max-request-size to limit a web request body to prevent client sending too large requests. (minor: web server) - * Many smaller bug fixes and inprovements, to the software and to the + * Many smaller bug fixes and improvements, to the software and to the documentation. - +

Changes for Version 0.4 (2022-03-08)

* Encoding “djson” renamed to “zjson” (zettel json). (breaking: api; minor: webui) - * Remove inline quotation syntax <<...<<. Now, - ""..."" generates the equivalent code. + * Remove inline quotation syntax <<...<<. Now, + ""..."" generates the equivalent code. Typographical quotes are generated by the browser, not by Zettelstore. (breaking: Zettelmarkup) - * Remove inline formatting for monospace. Its syntax is now used by the - similar syntax element of literal computer input. Monospace was just + * Remove inline formatting for mono space. Its syntax is now used by the + similar syntax element of literal computer input. Mono space was just a visual element with no semantic association. Now, the syntax ++...++ is obsolete. (breaking: Zettelmarkup). * Remove API call to parse Zettelmarkup texts and encode it as text and HTML. Was call “POST /v”. It was needed to separately encode @@ -95,33 +886,33 @@ identifier. (minor: api, webui) * Change generated URLs for zettel-creation forms. If you have bookmarked them, e.g. to create a new zettel, you should update. (minor: webui) - * Remove support for metadata key no-index to suppress indexing - selected zettel. It was introduced in v0.0.11, but - disallows some future optimizations for searching zettel. + * Remove support for metadata key no-index to suppress indexing + selected zettel. It was introduced in [#0_0_11|v0.0.11], but disallows + some future optimizations for searching zettel. (minor: api, webui) * Make some metadata-based searches a little bit faster by executing a (in-memory-based) full-text search first. Now only those zettel are - loaded from file that contain the metdata value. + loaded from file that contain the metadata value. (minor: api, webui) * Add an API call to retrieve the version of the Zettelstore. (minor: api) * Limit the amount of zettel and bytes to be stored in a memory box. Allows to use it with public access. (minor: box) * Disallow to cache the authentication cookie. Will remove most unexpected log-outs when using a mobile device. (minor: webui) - * Many smaller bug fixes and inprovements, to the software and to the + * Many smaller bug fixes and improvements, to the software and to the documentation. - +

Changes for Version 0.3 (2022-02-09)

- * Zettel files with extension .meta are now treated as content - files. Previoulsy, they were interpreted as metadata files. The + * Zettel files with extension .meta are now treated as content + files. Previously, they were interpreted as metadata files. The interpretation as metadata files was deprecated in version 0.2. (breaking: directory and file/zip box) * Add syntax “draw” to produce some graphical representations. (major) * Add Zettelmarkup syntax to specify full transclusion of other zettel. @@ -133,56 +924,57 @@ access rights for the given zettel. (minor: api) * A previously duplicate file that is now useful (because another file was deleted) is now logged as such. (minor: directory and file/zip box) - * Many smaller bug fixes and inprovements, to the software and to the + * Many smaller bug fixes and improvements, to the software and to the documentation. - +

Changes for Version 0.2 (2022-01-19)

* v0.2.1 (2021-02-01) updates the license year in some documents - * Remove support for ;;small text;; Zettelmarkup. + * Remove support for ;;small text;; Zettelmarkup. (breaking: Zettelmarkup) * On macOS, the downloadable executable program is now called “zettelstore”, as on all other Unix-like platforms. (possibly breaking: macOS) * External metadata (e.g. for zettel with file extension other than - .zettel) are stored in files without an extension. Metadata files - with extension .meta are still recognized, but result in - a warning message. In a future version (probably v0.3), .meta - files will be treated as ordinary content files, possibly resulting in - duplicate content. In other words: usage of .meta files for - storing metadata is deprecated. + .zettel) are stored in files without an extension. Metadata + files with extension .meta are still recognized, but result + in a warning message. In a future version (probably v0.3), + .meta files will be treated as ordinary content files, + possibly resulting in duplicate content. In other words: usage of + .meta files for storing metadata is deprecated. (possibly breaking: directory and file box) * Show unlinked references in info page of each zettel. Unlinked references are phrases within zettel content that might reference another zettel with the same title as the phase. (major: webui) - * Add endpoint /u/{ID} to retrieve unlinked references. + * Add endpoint /u/{ID} to retrieve unlinked references. (major: api) * Provide a logging facility. Log messages are written to standard output. Messages with level “information” are also written to a circular buffer (of length 8192) which can be retrieved via a computed zettel. There is a command - line flag -l LEVEL to specify an application global logging level - on startup (default: “information”). Logging level can also be - changed via the administrator console, even for specific (sub-) services. + line flag -l LEVEL to specify an application global logging + level on startup (default: “information”). Logging level can + also be changed via the administrator console, even for specific (sub-) + services. (major) * The internal handling of zettel files is rewritten. This allows less reloads ands detects when the directory containing the zettel files is removed. The API, WebUI, and the admin console allow to manually refresh the internal state on demand. (major: box, webui) - * .zettel files with YAML header are now correctly written. + * .zettel files with YAML header are now correctly written. (bug) * Selecting zettel based on their metadata allows the same syntax as searching for zettel content. For example, you can list all zettel that - have an identifier not ending with 00 by using the query - id=!<00. + have an identifier not ending with 00 by using the query + id=!<00. (minor: api, webui) - * Remove support for //deprecated emphasized// Zettelmarkup. + * Remove support for //deprecated emphasized// Zettelmarkup. (minor: Zettelmarkup) * Add options to profile the software. Profiling can be enabled at the command line or via the administrator console. (minor) * Add computed zettel that lists all supported parser / recognized zettel @@ -189,66 +981,67 @@ syntaxes. (minor) * Add API call to check for enabled authentication. (minor: api) * Renewing an API access token works even if authentication is not enabled. - This corresponds to the behaviour of optaining an access token. + This corresponds to the behaviour of obtaining an access token. (minor: api) * If there is nothing to return, use HTTP status code 204, instead of 200 + - Content-Length: 0. + Content-Length: 0. (minor: api) - * Metadata key duplicates stores the duplicate file names, instead - of just a boolean value that there were duplicate file names. + * Metadata key duplicates stores the duplicate file names, + instead of just a boolean value that there were duplicate file names. (minor) - * Document autostarting Zettelstore on Windows, macOS, and Linux. + * Document auto starting Zettelstore on Windows, macOS, and Linux. (minor) - * Many smaller bug fixes and inprovements, to the software and to the + * Many smaller bug fixes and improvements, to the software and to the documentation. - +

Changes for Version 0.1 (2021-11-11)

* v0.1.3 (2021-12-15) fixes a bug where the modification date could be set when a new zettel is created. * v0.1.2 (2021-11-18) fixes a bug when selecting zettel from a list when more than one comparison is negated. * v0.1.1 (2021-11-12) updates the documentation, mostly related to the - deprecation of the // markup. + deprecation of the // markup. * Remove visual Zettelmarkup (italic, underline). Semantic Zettelmarkup (emphasize, insert) is still allowed, but got a different syntax. The new - syntax for inserted text is >>inserted>>, - while its previous syntax now denotes emphasized text: - __emphasized__. The previous syntax for emphasized text is now - deprecated: //deprecated emphasized//. Starting with - Version 0.2.0, the deprecated syntax will not be supported. The - reason is the collision with URLs that also contain the characters - //. The ZMK encoding of a zettel may help with the transition - (/v/{ZettelID}?_part=zettel&_enc=zmk, on the Info page of + syntax for inserted text is + >>inserted>>, while its previous syntax now + denotes emphasized text: __emphasized__. The + previous syntax for emphasized text is now deprecated: //deprecated + emphasized//. Starting with Version 0.2.0, the deprecated + syntax will not be supported. The reason is the collision with URLs that + also contain the characters //. The ZMK encoding of a zettel + may help with the transition + (/v/{ZettelID}?_part=zettel&_enc=zmk, on the Info page of each zettel in the WebUI). Additionally, all deprecated uses of - // will be rendered with a dashed box within the WebUI. + // will be rendered with a dashed box within the WebUI. (breaking: Zettelmarkup). - * API client software is now a [https://zettelstore.de/client/|separate] - project. + * API client software is now a separate project. (breaking) * Initial support for HTTP security headers (Content-Security-Policy, Permissions-Policy, Referrer-Policy, X-Content-Type-Options, X-Frame-Options). Header values are currently some constant values. (possibly breaking: api, webui) - * Remove visual Zettelmarkup (bold, striketrough). Semantic Zettelmarkup + * Remove visual Zettelmarkup (bold, strike through). Semantic Zettelmarkup (strong, delete) is still allowed and replaces the visual elements syntactically. The visual appearance should not change (depends on your changes / additions to CSS zettel). (possibly breaking: Zettelmarkup). - * Add API endpoint POST /v to retrieve HTMl and text encoded + * Add API endpoint POST /v to retrieve HTMl and text encoded strings from given ZettelMarkup encoded values. This will be used to render a HTML page from a given zettel: in many cases the title of a zettel must be treated separately. (minor: api) - * Add API endpoint /m to retrieve only the metadata of a zettel. + * Add API endpoint /m to retrieve only the metadata of + a zettel. (minor: api) - * New metadata value content-tags contains the tags that were given - in the zettel content. To put it simply, all-tags = tags - + content-tags. + * New metadata value content-tags contains the tags that were + given in the zettel content. To put it simply, all-tags + = tags + content-tags. (minor) * Calculating the context of a zettel stops at the home zettel. (minor: api, webui) * When renaming or deleting a zettel, a warning will be given, if other zettel references the given zettel, or when “deleting” will @@ -264,104 +1057,105 @@ (minor: webui) * Separate repository for [https://zettelstore.de/contrib/|contributed] software. First entry is a software for creating a presentation by using zettel. (info) - * Many smaller bug fixes and inprovements, to the software and to the + * Many smaller bug fixes and improvements, to the software and to the documentation. - +

Changes for Version 0.0.15 (2021-09-17)

* Move again endpoint characters for authentication to make room for future - features. WebUI authentication moves from /a to /i - (login) and /i?logout (logout). API authentication moves from - /v to /a. JSON-based basic zettel handling moves from - /z to /j and /z/{ID} to /j/{ID}. Since - the API client is updated too, this should not be a breaking change for - most users. + features. WebUI authentication moves from /a to + /i (login) and /i?logout (logout). API + authentication moves from /v to /a. JSON-based + basic zettel handling moves from /z to /j and + /z/{ID} to /j/{ID}. Since the API client is + updated too, this should not be a breaking change for most users. (minor: api, webui; possibly breaking) - * Add API endpoint /v/{ID} to retrieve an evaluated zettel in - various encodings. Mostly replaces endpoint /z/{ID} for other + * Add API endpoint /v/{ID} to retrieve an evaluated zettel in + various encodings. Mostly replaces endpoint /z/{ID} for other encodings except “json” and “raw”. Endpoint - /j/{ID} now only returns JSON data, endpoint /z/{ID} is - used to retrieve plain zettel data (previously called “raw”). - See documentation for details. + /j/{ID} now only returns JSON data, endpoint + /z/{ID} is used to retrieve plain zettel data (previously + called “raw”). See documentation for details. (major: api; breaking) * Metadata values of type tag set (the metadata with key - tags is its most prominent example), are now compared in + tags is its most prominent example), are now compared in a case-insensitive manner. Tags that only differ in upper / lower case character are now treated identical. This might break your workflow, if you depend on case-sensitive comparison of tag values. Tag values are translated to their lower case equivalent before comparing them and when you edit a zettel through Zettelstore. If you just modify the zettel files, your tag values remain unchanged. (major; breaking) - * Endpoint /z/{ID} allows the same methods as endpoint - /j/{ID}: GET retrieves zettel (see above), PUT - updates a zettel, DELETE deletes a zettel, MOVE renames - a zettel. In addtion, POST /z will create a new zettel. When - zettel data must be given, the format is plain text, with metadata - separated from content by an empty line. See documentation for more - details. + * Endpoint /z/{ID} allows the same methods as endpoint + /j/{ID}: GET retrieves zettel (see above), + PUT updates a zettel, DELETE deletes a zettel, + MOVE renames a zettel. In addition, POST /z will + create a new zettel. When zettel data must be given, the format is plain + text, with metadata separated from content by an empty line. See + documentation for more details. (major: api (plus WebUI for some details)) * Allows to transclude / expand the content of another zettel into a target zettel when the zettel is rendered. By using the syntax of embedding an image (which is some kind of expansion too), the first top-level paragraph of a zettel may be transcluded into the target zettel. Endless recursion is checked, as well as a possible “transclusion bomb ” (similar to a XML bomb). See manual for details. (major: zettelmarkup) - * The endpoint /z allows to list zettel in a simpler format than - endpoint /j: one line per zettel, and only zettel identifier plus - zettel title. + * The endpoint /z allows to list zettel in a simpler format + than endpoint /j: one line per zettel, and only zettel + identifier plus zettel title. (minor: api) * Folgezettel are now displayed with full title at the bottom of a page. (minor: webui) - * Add API endpoint /p/{ID} to retrieve a parsed, but not evaluated - zettel in various encodings. + * Add API endpoint /p/{ID} to retrieve a parsed, but not + evaluated zettel in various encodings. (minor: api) * Fix: do not list a shadowed zettel that matches the select criteria. (minor) - * Many smaller bug fixes and inprovements, to the software and to the + * Many smaller bug fixes and improvements, to the software and to the documentation. - +

Changes for Version 0.0.14 (2021-07-23)

* Rename “place” into “box”. This also affects the - configuration keys to specify boxes box-uriX (previously - place-uri-X. Older changes documented here are renamed - too. + configuration keys to specify boxes box-uriX + (previously place-uri-X. Older changes documented + here are renamed too. (breaking) * Add API for creating, updating, renaming, and deleting zettel. (major: api) * Initial API client for Go. (major: api) * Remove support for paging of WebUI list. Runtime configuration key - list-page-size is removed. If you still specify it, it will be - ignored. + list-page-size is removed. If you still specify it, it will + be ignored. (major: webui) - * Use endpoint /v for user authentication via API. Endpoint - /a is now used for the web user interface only. Similar, endpoint - /y (“zettel context”) is renamed to /x. + * Use endpoint /v for user authentication via API. Endpoint + /a is now used for the web user interface only. Similar, + endpoint /y (“zettel context”) is renamed to + /x. (minor, possibly breaking) * Type of used-defined metadata is determined by suffix of key: - -number, -url, -zid will result the values to - be interpreted as a number, an URL, or a zettel identifier. + -number, -url, -zid will result the + values to be interpreted as a number, an URL, or a zettel identifier. (minor, but possibly breaking if you already used a metadata key with above suffixes, but as a string type) - * New user-role “creator”, which is only allowed to + * New user-role “creator”, which is only allowed to create new zettel (except user zettel). This role may only read and update public zettel or its own user zettel. Added to support future client software (e.g. on a mobile device) that automatically creates new zettel but, in case of a password loss, should not allow to read existing zettel. (minor, possibly breaking, because new zettel template zettel must always - prepend the string new- before metdata keys that should be + prepend the string new- before metadata keys that should be transferred to the new zettel) - * New suported metadata key box-number, which gives an indication - from which box the zettel was loaded. + * New supported metadata key box-number, which gives an + indication from which box the zettel was loaded. (minor) - * New supported syntax html. + * New supported syntax html. (minor) * New predefined zettel “User CSS” that can be used to redefine some predefined CSS (without modifying the base CSS zettel). (minor: webui) * When a user moves a zettel file with additional characters into the box @@ -368,21 +1162,21 @@ directory, these characters are preserved when zettel is updated. (bug) * The phase “filtering a zettel list” is more precise “selecting zettel” (documentation) - * Many smaller bug fixes and inprovements, to the software and to the + * Many smaller bug fixes and improvements, to the software and to the documentation. - +

Changes for Version 0.0.13 (2021-06-01)

- * Startup configuration box-X-uri (where X is a - number greater than zero) has been renamed to - box-uri-X. + * Startup configuration box-X-uri (where X is + a number greater than zero) has been renamed to + box-uri-X. (breaking) - * Web server processes startup configuration url-prefix. There is - no need for stripping the prefix by a front-end web server any more. + * Web server processes startup configuration url-prefix. There + is no need for stripping the prefix by a front-end web server any more. (breaking: webui, api) * Administrator console (only optional accessible locally). Enable it only on systems with a single user or with trusted users. It is disabled by default. (major: core) @@ -389,12 +1183,13 @@ * Remove visibility value “simple-expert” introduced in [#0_0_8|version 0.0.8]. It was too complicated, esp. authorization. There was a name collision with the “simple” directory box sub-type. (major) * For security reasons, HTML blocks are not encoded as HTML if they contain - certain snippets, such as <script or <iframe. - These may be caused by using CommonMark as a zettel syntax. + certain snippets, such as <script or + <iframe. These may be caused by using CommonMark as + a zettel syntax. (major) * Full-text search can be a prefix search or a search for equal words, in addition to the search whether a word just contains word of the search term. (minor: api, webui) @@ -409,17 +1204,17 @@ * Local images that cannot be read (not found or no access rights) are substituted with the new default image, a spinning emoji. See [/file?name=box/constbox/emoji_spin.gif]. (minor: webui) * Add zettelmarkup syntax for a table row that should be ignored: - |%. This allows to paste output of the administrator console into - a zettel. + |%. This allows to paste output of the administrator console + into a zettel. (minor: zmk) - * Many smaller bug fixes and inprovements, to the software and to the + * Many smaller bug fixes and improvements, to the software and to the documentation. - +

Changes for Version 0.0.12 (2021-04-16)

* Raise the per-process limit of open files on macOS to 1.048.576. This allows most macOS users to use at least 500.000 zettel. That should be enough for the near future. (major) @@ -427,18 +1222,18 @@ directory boxes. The original directory box type is now called "notify" (the default value). There is a new type called "simple". This new type does not notify Zettelstore when some of the underlying Zettel files change. (major) - * Add new startup configuration default-dir-box-type, which gives - the default value for specifying a directory box type. The default value - is “notify”. On macOS, the default value may be changed + * Add new startup configuration default-dir-box-type, which + gives the default value for specifying a directory box type. The default + value is “notify”. On macOS, the default value may be changed “simple” if some errors occur while raising the per-process limit of open files. (minor) - +

Changes for Version 0.0.11 (2021-04-05)

* New box schema "file" allows to read zettel from a ZIP file. A zettel collection can now be packaged and distributed easier. (major: server) * Non-restricted search is a full-text search. The search string will be @@ -446,11 +1241,11 @@ or a number will be ignored for the search. It is sufficient if the words to be searched are part of words inside a zettel, both content and metadata. (major: api, webui) * A zettel can be excluded from being indexed (and excluded from being found - in a search) if it contains the metadata no-index: true. + in a search) if it contains the metadata no-index: true. (minor: api, webui) * Menu bar is shown when displaying error messages. (minor: webui) * When selecting zettel, it can be specified that a given value should not match. Previously, only the whole select criteria could be @@ -466,106 +1261,118 @@ * Selecting zettel depending on tag values can be both by comparing only the prefix or the whole string. If a search value begins with '#', only zettel with the exact tag will be returned. Otherwise a zettel will be returned if the search string just matches the prefix of only one of its tags. (minor: api, webui) - * Many smaller bug fixes and inprovements, to the software and to the documentation. + * Many smaller bug fixes and improvements, to the software and to the + documentation. A note for users of macOS: in the current release and with macOS's default values, a zettel directory must not contain more than approx. 250 files. There are three options to mitigate this limitation temporarily: # You update the per-process limit of open files on macOS. - # You setup a virtualization environment to run Zettelstore on Linux or Windows. + # You setup a virtualisation environment to run Zettelstore on Linux or + Windows. # You wait for version 0.0.12 which addresses this issue. - +

Changes for Version 0.0.10 (2021-02-26)

* Menu item “Home” now redirects to a home zettel. - Its default identifier is 000100000000. - The identifier can be changed with configuration key home-zettel, which supersedes key start. - The default home zettel contains some welcoming information for the new user. + Its default identifier is 000100000000. The identifier can be + changed with configuration key home-zettel, which supersedes + key start. The default home zettel contains some welcoming + information for the new user. (major: webui) - * Show context of a zettel by following all backward and/or forward reference - up to a defined depth and list the resulting zettel. Additionally, some zettel - with similar tags as the initial zettel are also taken into account. + * Show context of a zettel by following all backward and/or forward + reference up to a defined depth and list the resulting zettel. + Additionally, some zettel with similar tags as the initial zettel are also + taken into account. (major: api, webui) - * A zettel that references other zettel within first-level list items, can act - as a “table of contents” zettel. - The API endpoint /o/{ID} allows to retrieve the referenced zettel in - the same order as they occur in the zettel. + * A zettel that references other zettel within first-level list items, can + act as a “table of contents” zettel. The API endpoint + /o/{ID} allows to retrieve the referenced zettel in the same + order as they occur in the zettel. (major: api) - * The zettel “New Menu” with identifier 00000000090000 contains - a list of all zettel that should act as a template for new zettel. - They are listed in the WebUIs ”New“ menu. - This is an application of the previous item. - It supersedes the usage of a role new-template introduced in [#0_0_6|version 0.0.6]. - Please update your zettel if you make use of the now deprecated feature. + * The zettel “New Menu” with identifier + 00000000090000 contains a list of all zettel that should act + as a template for new zettel. They are listed in the WebUIs + ”New“ menu. This is an application of the previous item. It + supersedes the usage of a role new-template introduced in + [#0_0_6|version 0.0.6]. Please update your zettel if you make use of + the now deprecated feature. (major: webui) - * A reference that starts with two slash characters (“//”) - it will be interpreted relative to the value of url-prefix. - For example, if url-prefix has the value /manual/, - the reference [[Zettel list|//h]] will render as - <a href="/manual/h">Zettel list</a>. (minor: syntax) + * A reference that starts with two slash characters + (“//”) it will be interpreted relative to the + value of url-prefix. For example, if url-prefix + has the value /manual/, the reference + [[Zettel list|//h]] will render as <a + href="/manual/h">Zettel list</a>. + (minor: syntax) * Searching/selecting ignores the leading '#' character of tags. (minor: api, webui) - * When result of selecting or searching is presented, the query is written as the page heading. + * When result of selecting or searching is presented, the query is written + as the page heading. (minor: webui) - * A reference to a zettel that contains a URL fragment, will now be processed by the indexer. + * A reference to a zettel that contains a URL fragment, will now be + processed by the indexer. (bug: server) - * Runtime configuration key marker-external now defaults to + * Runtime configuration key marker-external now defaults to “&#10138;” (“➚”). It is more beautiful than the previous “&#8599;&#xfe0e;” (“↗︎”), which also needed the additional - “&#xfe0e;” to disable the conversion to an emoji on iPadOS. + “&#xfe0e;” to disable the conversion to an emoji on + iPadOS. (minor: webui) - * A pre-build binary for macOS ARM64 (also known as Apple silicon) is available. + * A pre-build binary for macOS ARM64 (also known as Apple silicon) is + available. (minor: infrastructure) - * Many smaller bug fixes and inprovements, to the software and to the documentation. + * Many smaller bug fixes and improvements, to the software and to the + documentation. - +

Changes for Version 0.0.9 (2021-01-29)

This is the first version that is managed by [https://fossil-scm.org|Fossil] instead of GitHub. To access older versions, use the Git repository under [https://github.com/zettelstore/zettelstore-github|zettelstore-github].

Server / API

* (major) Support for property metadata. - Metadata key published is the first example of such + Metadata key published is the first example of such a property. * (major) A background activity (called indexer) continuously monitors zettel changes to establish the reverse direction of found internal links. This affects the new metadata keys - precursor and folge. A user specifies the - precursor of a zettel and the indexer computes the property + precursor and folge. A user specifies + the precursor of a zettel and the indexer computes the property metadata for [https://forum.zettelkasten.de/discussion/996/definition-folgezettel|Folgezettel]. Metadata keys with type “Identifier” or “IdentifierSet” that have no inverse key (like - precursor and folge with add to the key - forward that also collects all internal links within the - content. The computed inverse is backward, which provides - all backlinks. The key back is computed as the value of - backward, but without forward links. Therefore, - back is something like the list of “smart - backlinks”. + precursor and folge with add to the key + forward that also collects all internal links within + the content. The computed inverse is backward, which + provides all backlinks. The key back is computed as + the value of backward, but without forward links. + Therefore, back is something like the list of + “smart backlinks”. * (minor) If Zettelstore is being stopped, an appropriate message is written in the console log. * (minor) New computed zettel with environmental data, the list of supported meta data keys, and statistics about all configured zettel boxes. Some other computed zettel got a new identifier (to make room for other variant). - * (minor) Remove zettel 00000000000004, which contained the Go + * (minor) Remove zettel 00000000000004, which contained the Go version that produced the Zettelstore executable. It was too specific to the current implementation. This information is now - included in zettel 00000000000006 (Zettelstore + included in zettel 00000000000006 (Zettelstore Environment Values). * (minor) Predefined templates for new zettel do not contain any value for - attribute visibility any more. + attribute visibility any more. * (minor) Add a new metadata key type called “Zettelmarkup”. It is a non-empty string, that will be formatted with - Zettelmarkup. title and default-title have this - type. + Zettelmarkup. title and default-title + have this type. * (major) Rename zettel syntax “meta” to “none”. Please update the Zettelstore Runtime Configuration and all other zettel that previously used the value “meta”. Other zettel are typically user zettel, used for authentication. However, there is no real harm, if you do not update these zettel. @@ -572,12 +1379,13 @@ In this case, the metadata is just not presented when rendered. Zettelstore will still work. * (minor) Login will take at least 500 milliseconds to mitigate login attacks. This affects both the API and the WebUI. * (minor) Add a sort option “_random” to produce a zettel list - in random order. _order / order are now an - aliases for the query parameters _sort / sort. + in random order. _order / order are now + an aliases for the query parameters _sort + / sort.

WebUI

* (major) HTML template zettel for WebUI now use [https://mustache.github.io/|Mustache] syntax instead of previously used [https://golang.org/pkg/html/template/|Go @@ -591,70 +1399,72 @@ header of a rendered zettel. If a zettel has real backlinks, they are shown at the botton of the page (“Additional links to this zettel”). * (minor) All property metadata, even computed metadata is shown in the info page of a zettel. - * (minor) Rendering of metadata keys title and - default-title in info page changed to a full HTML output - for these Zettelmarkup encoded values. + * (minor) Rendering of metadata keys title and + default-title in info page changed to a full HTML + output for these Zettelmarkup encoded values. * (minor) Always show the zettel identifier on the zettel detail view. Previously, the identifier was not shown if the zettel was not editable. * (minor) Do not show computed metadata in edit forms anymore. - +

Changes for Version 0.0.8 (2020-12-23)

Server / API

- * (bug) Zettel files with extension .jpg and without metadata will - get a syntax value “jpg”. The internal data - structure got the same value internally, instead of + * (bug) Zettel files with extension .jpg and without metadata + will get a syntax value “jpg”. The internal + data structure got the same value internally, instead of “jpeg”. This has been fixed for all possible alternative syntax values. - * (bug) If a file, e.g. an image file like 20201130190200.jpg, is - added to the directory box, its metadata are just calculated from + * (bug) If a file, e.g. an image file like 20201130190200.jpg, + is added to the directory box, its metadata are just calculated from the information available. Updated metadata did not find its way - into the zettel box, because the .meta file was not + into the zettel box, because the .meta file was not written. - * (bug) If just the .meta file was deleted manually, the zettel was - assumed to be missing. A workaround is to restart the software. If - the .meta file is deleted, metadata is now calculated in - the same way when the .meta file is non-existing at the - start of the software. + * (bug) If just the .meta file was deleted manually, the zettel + was assumed to be missing. A workaround is to restart the software. + If the .meta file is deleted, metadata is now + calculated in the same way when the .meta file is + non-existing at the start of the software. * (bug) A link to the current zettel, only using a fragment (e.g. [[Title|#title]]) is now handled correctly as a zettel link (and not as a link to external material). * (minor) Allow zettel to be marked as “read only”. - This is done through the metadata key read-only. + This is done through the metadata key read-only. * (bug) When renaming a zettel, check all boxes for the new zettel identifier, not just the first one. Otherwise it will be possible to shadow a read-only zettel from a next box, effectively modifying it. * (minor) Add support for a configurable default value for metadata key - visibility. - * (bug) If list-page-size is set to a relatively small value and - the authenticated user is not the owner, some zettel were not - shown in the list of zettel or were not returned by the API. + visibility. + * (bug) If list-page-size is set to a relatively small value + and the authenticated user is not the owner, some zettel were + not shown in the list of zettel or were not returned by the API. * (minor) Add support for new visibility “expert”. An owner becomes an expert, if the runtime configuration key - expert-mode is set to true. + expert-mode is set to true. * (major) Add support for computed zettel. - These zettel have an identifier less than 0000000000100. - Most of them are only visible, if expert-mode is enabled. + These zettel have an identifier less than + 0000000000100. Most of them are only visible, if + expert-mode is enabled. * (bug) Fixes a memory leak that results in too many open files after approx. 125 reload operations. * (major) Predefined templates for new zettel got an explicit value for visibility: “login”. Please update these zettel if you modified them. - * (major) Rename key readonly of Zettelstore Startup - Configuration to read-only-mode. This was done to - avoid some confusion with the the zettel metadata key - read-only. Please adapt your startup configuration. - Otherwise your Zettelstore will be accidentally writable. + * (major) Rename key readonly of Zettelstore Startup + Configuration to read-only-mode. This was done to + avoid some confusion with the zettel metadata key + read-only. Please adapt your startup + configuration. Otherwise your Zettelstore will be accidentally + writable. * (minor) References starting with “./” and “../” are treated as a local reference. Previously, only the prefix “/” was treated as a local reference. - * (major) Metadata key modified will be set automatically to the - current local time if a zettel is updated through Zettelstore. + * (major) Metadata key modified will be set automatically to + the current local time if a zettel is updated through Zettelstore. If you used that key previously for your own, you should rename it before you upgrade. * (minor) The new visibility value “simple-expert” ensures that many computed zettel are shown for new users. This is to enable them to send useful bug reports. @@ -670,16 +1480,16 @@ * (minor) Move zettel field "role" above "tags" and move "syntax" more to "content". * (minor) Rename zettel operation “clone” to “copy”. * (major) All predefined HTML templates have now a visibility value “expert”. If you want to see them as an non-expert - owner, you must temporary enable expert-mode and change - the visibility metadata value. + owner, you must temporary enable expert-mode and + change the visibility metadata value. * (minor) Initial support for [https://zettelkasten.de/posts/tags/folgezettel/|Folgezettel]. If you click on “Folge” (detail view or info view), a new - zettel is created with a reference (precursor) to the + zettel is created with a reference (precursor) to the original zettel. Title, role, tags, and syntax are copied from the original zettel. * (major) Most predefined zettel have a title prefix of “Zettelstore”. * (minor) If started in simple mode, e.g. via double click or without any @@ -687,32 +1497,33 @@ terminal, there is a hint about opening the web browser and use a specific URL. A Welcome zettel is created, to give some more information. (This change also applies to the server itself, but it is more suited to the WebUI user.) - +

Changes for Version 0.0.7 (2020-11-24)

* With this version, Zettelstore and this manual got a new license, the [https://joinup.ec.europa.eu/collection/eupl|European Union Public Licence] (EUPL), version 1.2 or later. Nothing else changed. If you want to stay with the old licenses (AGPLv3+, CC BY-SA 4.0), you are free to fork from the previous version. - +

Changes for Version 0.0.6 (2020-11-23)

Server

* (major) Rename identifier of Zettelstore Runtime Configuration to - 00000000000100 (previously 00000000000001). This - is done to gain some free identifier with smaller number to be - used internally. If you customized this zettel, please make - sure to rename it to the new identifier. + 00000000000100 (previously + 00000000000001). This is done to gain some free + identifier with smaller number to be used internally. If you + customized this zettel, please make sure to rename it to the new + identifier. * (major) Rename the two essential metadata keys of a user zettel to - credential and user-id. The previous values were - cred and ident. If you enabled user - authentication and added some user zettel, make sure to change - them accordingly. Otherwise these users will not authenticated any - more. + credential and user-id. The previous + values were cred and ident. If you + enabled user authentication and added some user zettel, make sure + to change them accordingly. Otherwise these users will not + authenticated any more. * (minor) Rename the scheme of the box URL where predefined zettel are stored to “const”. The previous value was “globals”.

Zettelmarkup

@@ -725,11 +1536,11 @@ in valid JSON content. * (bug) All query parameters of selecting zettel must be true, regardless if a specific key occurs more than one or not. * (minor) Encode all inherited meta values in all formats except “raw”. A meta value is called inherited if - there is a key starting with default- in the + there is a key starting with default- in the Zettelstore Runtime Configuration. Applies to WebUI also. * (minor) Automatic calculated identifier for headings (only for “html”, “djson”, “native” format and for the Web user interface). You can use this to provide a zettel reference that links to the heading, without @@ -749,72 +1560,75 @@ references”). When a local reference is displayed as an URL on the WebUI, it will not opened in a new window/tab. They will receive a local marker, when encoded as “djson” or “native”. Local references are listed on the Info page of each zettel. - * (minor) Change the default value for some visual sugar putd after an - external URL to &\#8599;&\#xfe0e; + * (minor) Change the default value for some visual sugar put after an + external URL to &\#8599;&\#xfe0e; (“↗︎”). This affects the former key - icon-material of the Zettelstore Runtime - Configuration, which is renamed to marker-external. + icon-material of the Zettelstore Runtime + Configuration, which is renamed to + marker-external. * (major) Allow multiple zettel to act as templates for creating new zettel. All zettel with a role value “new-template” act as a template to create a new zettel. The WebUI menu item “New” changed to a drop-down list with all those zettel, ordered by their identifier. All metadata keys with the - prefix new- will be translated to a new or updated + prefix new- will be translated to a new or updated keys/value without that prefix. You can use this mechanism to specify a role for the new zettel, or a different title. The title of the template zettel is used in the drop-down list. The initial template zettel “New Zettel” has now a different - zettel identifier (now: 00000000091001, was: - 00000000040001). Please update it, if you changed that - zettel. + zettel identifier (now: 00000000091001, was: + 00000000040001). Please update it, if you changed + that zettel.
Note: this feature was superseded in [#0_0_10|version 0.0.10] by the “New Menu” zettel. * (minor) When a page should be opened in a new windows (e.g. for external references), the web browser is instructed to decouple the new page from the previous one for privacy and security reasons. In detail, the web browser is instructed to omit referrer information and to omit a JS object linking to the page that contained the external link. * (minor) If the value of the Zettelstore Runtime Configuration key - list-page-size is greater than zero, the number of WebUI - list elements will be restricted and it is possible to change to - the next/previous page to list more elements. + list-page-size is greater than zero, the number of + WebUI list elements will be restricted and it is possible to + change to the next/previous page to list more elements. * (minor) Change CSS to enhance reading: make line-height a little smaller (previous: 1.6, now 1.4) and move list items to the left. - +

Changes for Version 0.0.5 (2020-10-22)

* Application Programming Interface (API) to allow external software to retrieve zettel data from the Zettelstore. * Specify boxes, where zettel are stored, via an URL. * Add support for a custom footer. - +

Changes for Version 0.0.4 (2020-09-11)

* Optional user authentication/authorization. - * New sub-commands file (use Zettelstore as a command line filter), - password (for authentication), and config. + * New sub-commands file (use Zettelstore as a command line + filter), password (for authentication), and + config. - +

Changes for Version 0.0.3 (2020-08-31)

* Starting Zettelstore has been changed by introducing sub-commands. This change is also reflected on the server installation procedures. * Limitations on renaming zettel has been relaxed. - +

Changes for Version 0.0.2 (2020-08-28)

- * Configuration zettel now has ID 00000000000001 (previously: - 00000000000000). - * The zettel with ID 00000000000000 is no longer shown in any + * Configuration zettel now has ID 00000000000001 (previously: + 00000000000000). + * The zettel with ID 00000000000000 is no longer shown in any zettel list. If you changed the configuration zettel, you should rename it manually in its file directory. * Creating a new zettel is now done by cloning an existing zettel. - To mimic the previous behaviour, a zettel with ID 00000000040001 - is introduced. You can change it if you need a different template zettel. + To mimic the previous behaviour, a zettel with ID + 00000000040001 is introduced. You can change it if you need + a different template zettel. - +

Changes for Version 0.0.1 (2020-08-21)

* Initial public release. Index: www/download.wiki ================================================================== --- www/download.wiki +++ www/download.wiki @@ -1,26 +1,38 @@ Download

Download of Zettelstore Software

Foreword

- * Zettelstore is free/libre open source software, licensed under EUPL-1.2-or-later. - * The software is provided as-is. - * There is no guarantee that it will not damage your system. - * However, it is in use by the main developer since March 2020 without any damage. - * It may be useful for you. It is useful for me. - * Take a look at the [https://zettelstore.de/manual/|manual] to know how to start and use it. + +Zettelstore is free/libre open source software, licensed under the +[https://zettelstore.de/home/file?name=LICENSE.txt&ci=trunk|EUPL-1.2 or later]. + +The software is provided as is, without any warranty. While there's no +guarantee it won't cause issues, it has been in daily use by the main developer +since March 2020, without any damage or data loss. +Since 2021, others have also been using Zettelstore reliably, and my students +have used it since 2023, all without encountering any problems. + +It’s useful for me and many others. It might be useful for you too. + +Check out the [https://zettelstore.de/manual/|manual] to get started and learn +how to make the most of it. +

ZIP-ped Executables

-Build: v0.5.0 (2022-07-29). - - * [/uv/zettelstore-0.5.0-linux-amd64.zip|Linux] (amd64) - * [/uv/zettelstore-0.5.0-linux-arm.zip|Linux] (arm6, e.g. Raspberry Pi) - * [/uv/zettelstore-0.5.0-windows-amd64.zip|Windows] (amd64) - * [/uv/zettelstore-0.5.0-darwin-amd64.zip|macOS] (amd64) - * [/uv/zettelstore-0.5.0-darwin-arm64.zip|macOS] (arm64, aka Apple silicon) - -Unzip the appropriate file, install and execute Zettelstore according to the manual. +Build: v0.21.0 (2025-03-07). + + * [/uv/zettelstore-0.21.0-android-arm64.zip|Android] (arm64) + * [/uv/zettelstore-0.21.0-linux-amd64.zip|Linux] (amd64) + * [/uv/zettelstore-0.21.0-linux-arm.zip|Linux] (arm6, e.g. Raspberry Pi) + * [/uv/zettelstore-0.21.0-darwin-arm64.zip|macOS] (arm64) + * [/uv/zettelstore-0.21.0-darwin-amd64.zip|macOS] (amd64) + * [/uv/zettelstore-0.21.0-windows-amd64.zip|Windows] (amd64) + +Unzip the appropriate file, install and execute Zettelstore according to the +manual.

Zettel for the manual

As a starter, you can download the zettel for the manual -[/uv/manual-0.5.0.zip|here]. +[/uv/manual-0.21.0.zip|here]. + Just unzip the contained files and put them into your zettel folder or configure a file box to read the zettel directly from the ZIP file. Index: www/impri.wiki ================================================================== --- www/impri.wiki +++ www/impri.wiki @@ -6,13 +6,13 @@ Phone: +49 (15678) 386566
Mail: ds (at) zettelstore.de

Privacy

If you do not log into this site, or login as the user "anonymous", -the only personal data this web service will process is your IP adress. It will +the only personal data this web service will process is your IP address. It will be used to send the data of the website you requested to you and to mitigate possible attacks against this website. This website is hosted by [https://ionos.de|1&1 IONOS SE]. According to -[https://www.ionos.de/hilfe/datenschutz/datenverarbeitung-von-webseitenbesuchern-ihres-11-ionos-produktes/andere-11-ionos-produkte/|their information], +[https://www.ionos.de/hilfe/datenschutz/datenverarbeitung-von-webseitenbesuchern-ihres-ionos-produktes/andere-ionos-produkte/|their information], no processing of personal data is done by them. Index: www/index.wiki ================================================================== --- www/index.wiki +++ www/index.wiki @@ -3,42 +3,45 @@ Zettelstore is a software that collects and relates your notes (“zettel”) to represent and enhance your knowledge. It helps with many tasks of personal knowledge management by explicitly supporting the [https://en.wikipedia.org/wiki/Zettelkasten|Zettelkasten method]. The method is based on creating many individual notes, each with one idea or information, -that are related to each other. Since knowledge is typically build up -gradually, one major focus is a long-term store of these notes, hence the name -“Zettelstore”. +that are related to each other. Since knowledge is typically built up +gradually, one major focus is a long-term storage of these notes, hence the +name “Zettelstore”. To get an initial impression, take a look at the [https://zettelstore.de/manual/|manual]. It is a live example of the zettelstore software, running in read-only mode. The software, including the manual, is licensed under the [/file?name=LICENSE.txt&ci=trunk|European Union Public License 1.2 (or later)]. -[https://zettelstore.de/client|Zettelstore Client] provides client software to -access Zettelstore via its API more easily, -[https://zettelstore.de/contrib|Zettelstore Contrib] contains contributed -software, which often connects to Zettelstore via its API. Some of the software -packages may be experimental. + * [https://t73f.de/r/zsc|Zettelstore Client] provides client software to + access Zettelstore via its API more easily. + * [https://zettelstore.de/contrib|Zettelstore Contrib] contains contributed + software, which often connects to Zettelstore via its API. Some of the + software packages may be experimental. + * [https://t73f.de/r/sx|Sx] provides an evaluator for symbolic + expressions, which is used for HTML templates and more. -[https://twitter.com/zettelstore|Stay tuned]… +[https://mastodon.social/tags/Zettelstore|Stay tuned] …
-

Latest Release: 0.5.0 (2022-07-29)

+

Latest Release: 0.21.0 (2025-03-07)

* [./download.wiki|Download] - * [./changes.wiki#0_5_0|Change summary] - * [/timeline?p=v0.5.0&bt=v0.4&y=ci|Check-ins for version 0.5.0], - [/vdiff?to=v0.5.0&from=v0.4|content diff] - * [/timeline?df=v0.5.0&y=ci|Check-ins derived from the 0.5.0 release], - [/vdiff?from=v0.5.0&to=trunk|content diff] + * [./changes.wiki#0_21|Change summary] + * [/timeline?p=v0.21.0&bt=v0.20.0&y=ci|Check-ins for version 0.21], + [/vdiff?to=v0.21.0&from=v0.20.0|content diff] + * [/timeline?df=v0.21.0&y=ci|Check-ins derived from the 0.21 release], + [/vdiff?from=v0.21.0&to=trunk|content diff] * [./plan.wiki|Limitations and planned improvements] * [/timeline?t=release|Timeline of all past releases]

Build instructions

-Just install [https://golang.org/dl/|Go] and some Go-based tools. Please read + +Just install [https://go.dev/dl/|Go] and some Go-based tools. Please read the [./build.md|instructions] for details. * [/dir?ci=trunk|Source code] * [/download|Download the source code] as a tarball or a ZIP file (you must [/login|login] as user "anonymous"). Index: www/plan.wiki ================================================================== --- www/plan.wiki +++ www/plan.wiki @@ -1,23 +1,16 @@ Limitations and planned improvements Here is a list of some shortcomings of Zettelstore. They are planned to be solved. -

Serious limitations

- * Content with binary data (e.g. a GIF, PNG, or JPG file) cannot be created - nor modified via the standard web interface. As a workaround, you should - put your file into the directory where your zettel are stored. Make sure - that the file name starts with unique 14 digits that make up the zettel - identifier. - * Automatic lists are not supported in Zettelmarkup. - * … - -

Smaller limitations

+ * Zettelstore must have indexed all zettel to make use of queries. + Otherwise not all zettel may be returned. * Quoted attribute values are not yet supported in Zettelmarkup: {key="value with space"}. - * The horizontal tab character (U+0009) is not supported. + * The horizontal tab character (U+0009) is not fully supported by + the parser. * Missing support for citation keys. * Changing the content syntax is not reflected in file extension. * File names with additional text besides the zettel identifier are not always preserved. * Some file systems differentiate filenames with different cases (e.g. some