Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Difference From v0.2 To v0.1
2022-01-19
| ||
18:16 | Update license year ... (check-in: bdc4c01332 user: stern tags: release-0.2) | |
17:48 | Merge from release ... (check-in: 5e16f252b9 user: stern tags: trunk) | |
17:42 | Version 0.2 ... (check-in: f091916e1a user: stern tags: release, release-0.2, v0.2) | |
14:23 | Create new branch named "release-0.2" ... (check-in: fb7390fa25 user: stern tags: release-0.2) | |
2021-11-13
| ||
17:09 | Version 0.1.1 ... (check-in: 8d9dc27ae1 user: stern tags: trunk, release, v0.1.1) | |
2021-11-11
| ||
16:37 | Version 0.1 ... (check-in: 7c6fd9bcda user: stern tags: trunk, release, v0.1) | |
14:56 | Do not abort release build when unparam finds optional problems ... (check-in: 29e086118f user: stern tags: trunk) | |
Changes to LICENSE.txt.
|
| | | 1 2 3 4 5 6 7 8 | Copyright (c) 2020-2021 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 |
︙ | ︙ |
Changes to VERSION.
|
| | | 1 | 0.1 |
Changes to ast/ast.go.
1 2 3 4 5 6 7 8 9 10 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- | | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | //----------------------------------------------------------------------------- // 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 ast provides the abstract syntax tree. 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 *BlockListNode // Zettel abstract syntax tree is a sequence of block nodes. } // Node is the interface, all nodes must implement. type Node interface { WalkChildren(v Visitor) } |
︙ | ︙ |
Changes to ast/attr.go.
1 2 3 4 5 6 7 8 9 10 11 12 | //----------------------------------------------------------------------------- // 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 ast | > | > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //----------------------------------------------------------------------------- // 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 ast provides the abstract syntax tree. package ast import ( "strings" ) // Attributes store additional information about some node types. type Attributes struct { Attrs map[string]string } // IsEmpty returns true if there are no attributes. |
︙ | ︙ |
Changes to ast/attr_test.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ast_test import ( "testing" "zettelstore.de/z/ast" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 ast provides the abstract syntax tree. package ast_test import ( "testing" "zettelstore.de/z/ast" ) |
︙ | ︙ |
Changes to ast/block.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ast // Definition of Block nodes. // BlockListNode is a list of BlockNodes. type BlockListNode struct { List []BlockNode | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 ast provides the abstract syntax tree. package ast // Definition of Block nodes. // BlockListNode is a list of BlockNodes. type BlockListNode struct { List []BlockNode |
︙ | ︙ |
Changes to ast/inline.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ast // Definitions of inline nodes. // InlineListNode is a list of BlockNodes. type InlineListNode struct { List []InlineNode | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 ast provides the abstract syntax tree. package ast // Definitions of inline nodes. // InlineListNode is a list of BlockNodes. type InlineListNode struct { List []InlineNode |
︙ | ︙ | |||
33 34 35 36 37 38 39 | inl = append(inl, &SpaceNode{Lexeme: " "}) } inl = append(inl, &TextNode{Text: word}) } return &InlineListNode{List: inl} } | | | 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | inl = append(inl, &SpaceNode{Lexeme: " "}) } inl = append(inl, &TextNode{Text: word}) } return &InlineListNode{List: inl} } // WalkChildren walks down to the descriptions. func (iln *InlineListNode) WalkChildren(v Visitor) { for _, bn := range iln.List { Walk(v, bn) } } // IsEmpty returns true if the list has no elements. |
︙ | ︙ | |||
196 197 198 199 200 201 202 | } // FormatKind specifies the format that is applied to the inline nodes. type FormatKind uint8 // Constants for FormatCode const ( | | | | | | | | | | > | | > | 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | } // FormatKind specifies the format that is applied to the inline nodes. type FormatKind uint8 // 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. FormatQuotation // Quotation text. FormatSmall // Smaller text. FormatSpan // Generic inline container. FormatMonospace // Monospaced text. FormatEmphDeprecated // Deprecated kind of emphasized text. ) func (*FormatNode) inlineNode() { /* Just a marker */ } // WalkChildren walks to the formatted text. func (fn *FormatNode) WalkChildren(v Visitor) { Walk(v, fn.Inlines) |
︙ | ︙ |
Changes to ast/material.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ast // MaterialNode references the various types of zettel material. type MaterialNode interface { Node materialNode() } | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 ast provides the abstract syntax tree. package ast // MaterialNode references the various types of zettel material. type MaterialNode interface { Node materialNode() } |
︙ | ︙ |
Changes to ast/ref.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ast import ( "net/url" "zettelstore.de/z/domain/id" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 ast provides the abstract syntax tree. package ast import ( "net/url" "zettelstore.de/z/domain/id" ) |
︙ | ︙ |
Changes to ast/ref_test.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ast_test import ( "testing" "zettelstore.de/z/ast" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 ast_test provides the tests for the abstract syntax tree. package ast_test import ( "testing" "zettelstore.de/z/ast" ) |
︙ | ︙ |
Changes to ast/walk.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //----------------------------------------------------------------------------- // 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 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 } | > < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //----------------------------------------------------------------------------- // 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 ast provides the abstract syntax tree. 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 } node.WalkChildren(v) v.Visit(nil) } // WalkItemSlice traverses an item slice. func WalkItemSlice(v Visitor, ins ItemSlice) { for _, in := range ins { |
︙ | ︙ |
Deleted ast/walk_test.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to auth/auth.go.
︙ | ︙ | |||
92 93 94 95 96 97 98 | // 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 | | < < < | 92 93 94 95 96 97 98 99 100 101 | // 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 } |
Changes to auth/impl/impl.go.
︙ | ︙ | |||
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 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{ | > > > > > > | 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | 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 // ErrNoUser signals that the meta data has no role value 'user'. var ErrNoUser = errors.New("auth: meta is no user") // 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) { if role, ok := ident.Get(api.KeyRole); !ok || role != api.ValueRoleUser { return nil, ErrNoUser } subject, ok := ident.Get(api.KeyUserID) if !ok || subject == "" { return nil, ErrNoIdent } now := time.Now().Round(time.Second) claims := jwt.Claims{ |
︙ | ︙ |
Changes to auth/policy/anon.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 authorization policies. package policy import ( "zettelstore.de/z/auth" "zettelstore.de/z/config" "zettelstore.de/z/domain/meta" ) |
︙ | ︙ | |||
37 38 39 40 41 42 43 | 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) } | < < < < < < < | 38 39 40 41 42 43 44 45 46 47 48 49 50 | 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) checkVisibility(m *meta.Meta) bool { if ap.authConfig.GetVisibility(m) == meta.VisibilityExpert { return ap.authConfig.GetExpertMode() } return true } |
Changes to auth/policy/box.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 ( "context" "zettelstore.de/z/auth" "zettelstore.de/z/box" |
︙ | ︙ | |||
157 158 159 160 161 162 163 | } user := pp.auth.GetUser(ctx) if pp.policy.CanDelete(user, meta) { return pp.box.DeleteZettel(ctx, zid) } return box.NewErrNotAllowed("Delete", user, zid) } | < < < < < < < < | 158 159 160 161 162 163 164 | } user := pp.auth.GetUser(ctx) if pp.policy.CanDelete(user, meta) { return pp.box.DeleteZettel(ctx, zid) } return box.NewErrNotAllowed("Delete", user, zid) } |
Changes to auth/policy/default.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //----------------------------------------------------------------------------- // 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) } | > < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | //----------------------------------------------------------------------------- // 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/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 (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. |
︙ | ︙ |
Changes to auth/policy/owner.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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/c/api" "zettelstore.de/z/auth" "zettelstore.de/z/config" "zettelstore.de/z/domain/meta" |
︙ | ︙ | |||
30 31 32 33 34 35 36 | 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 } | | | 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 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 role, ok := newMeta.Get(api.KeyRole); ok && role == api.ValueRoleUser { 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. |
︙ | ︙ | |||
56 57 58 59 60 61 62 | return false case meta.VisibilityPublic: return true } if user == nil { return false } | | | 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | return false case meta.VisibilityPublic: return true } if user == nil { return false } if role, ok := m.Get(api.KeyRole); ok && role == api.ValueRoleUser { // 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: |
︙ | ︙ | |||
91 92 93 94 95 96 97 | } if o.userIsOwner(user) { return true } if !o.userCanRead(user, oldMeta, vis) { return false } | | | 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | } if o.userIsOwner(user) { return true } if !o.userCanRead(user, oldMeta, vis) { return false } if role, ok := oldMeta.Get(api.KeyRole); ok && role == api.ValueRoleUser { // 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 } } |
︙ | ︙ | |||
128 129 130 131 132 133 134 | } if res, ok := o.checkVisibility(user, o.authConfig.GetVisibility(m)); ok { return res } return o.userIsOwner(user) } | < < < < < < < < < < | 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | } if res, ok := o.checkVisibility(user, o.authConfig.GetVisibility(m)); ok { return res } return o.userIsOwner(user) } 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 } |
︙ | ︙ |
Changes to auth/policy/policy.go.
︙ | ︙ | |||
60 61 62 63 64 65 66 | 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) } | < < < < | 60 61 62 63 64 65 66 | 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) } |
Changes to auth/policy/policy_test.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //----------------------------------------------------------------------------- // 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 | > < | < | < | < | < | < | < | < | < | | > > | < | | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | //----------------------------------------------------------------------------- // 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 ( "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 }{ {true, true, true}, {true, true, false}, {true, false, true}, {true, false, false}, {false, true, true}, {false, true, false}, {false, false, true}, {false, false, false}, } for _, ts := range testScene { authzManager := &testAuthzManager{ readOnly: ts.readonly, withAuth: ts.withAuth, } pol := newPolicy(authzManager, &authConfig{ts.expert}) name := fmt.Sprintf("readonly=%v/withauth=%v/expert=%v", ts.readonly, ts.withAuth, ts.expert) 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) }) } } type testAuthzManager struct { readOnly bool withAuth bool |
︙ | ︙ | |||
88 89 90 91 92 93 94 | if ur := meta.GetUserRole(val); ur != meta.UserRoleUnknown { return ur } } return meta.UserRoleReader } | | < | 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | if ur := meta.GetUserRole(val); ur != meta.UserRoleUnknown { return ur } } return meta.UserRoleReader } type authConfig struct{ expert bool } 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 |
︙ | ︙ | |||
570 571 572 573 574 575 576 | if tc.exp != got { tt.Errorf("exp=%v, but got=%v", tc.exp, got) } }) } } | < < < < < < < < < < < < < < < < < < < < < < < | | | | | | 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 | 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.KeyRole, api.ValueRoleUser) user.Set(api.KeyUserRole, api.ValueUserRoleCreator) return user } func newReader() *meta.Meta { user := meta.New(readerZid) user.Set(api.KeyTitle, "Reader") user.Set(api.KeyRole, api.ValueRoleUser) user.Set(api.KeyUserRole, api.ValueUserRoleReader) return user } func newWriter() *meta.Meta { user := meta.New(writerZid) user.Set(api.KeyTitle, "Writer") user.Set(api.KeyRole, api.ValueRoleUser) user.Set(api.KeyUserRole, api.ValueUserRoleWriter) return user } func newOwner() *meta.Meta { user := meta.New(ownerZid) user.Set(api.KeyTitle, "Owner") user.Set(api.KeyRole, api.ValueRoleUser) 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.KeyRole, api.ValueRoleUser) user.Set(api.KeyUserRole, api.ValueUserRoleOwner) return user } func newZettel() *meta.Meta { m := meta.New(zettelZid) m.Set(api.KeyTitle, "Any Zettel") return m |
︙ | ︙ | |||
708 709 710 711 712 713 714 | 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") | | | 676 677 678 679 680 681 682 683 684 685 | 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.KeyRole, api.ValueRoleUser) return m } |
Changes to auth/policy/readonly.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //----------------------------------------------------------------------------- // 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{} | > | | | | | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //----------------------------------------------------------------------------- // 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 authorization policies. package policy import "zettelstore.de/z/domain/meta" type roPolicy struct{} func (p *roPolicy) CanCreate(user, newMeta *meta.Meta) bool { return false } func (p *roPolicy) CanRead(user, m *meta.Meta) bool { return true } func (p *roPolicy) CanWrite(user, oldMeta, newMeta *meta.Meta) bool { return false } func (p *roPolicy) CanRename(user, m *meta.Meta) bool { return false } func (p *roPolicy) CanDelete(user, m *meta.Meta) bool { return false } |
Changes to box/box.go.
︙ | ︙ | |||
69 70 71 72 73 74 75 | // 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 | | | | | | 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | // 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. ApplyZid(context.Context, ZidFunc) error // Apply metadata of every zettel to the given function. ApplyMeta(context.Context, MetaFunc) error // ReadStats populates st with box statistics ReadStats(st *ManagedBoxStats) } // ManagedBoxStats records statistics about the box. type ManagedBoxStats struct { |
︙ | ︙ | |||
95 96 97 98 99 100 101 | // 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. | | < < < < < < < < < | 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | // 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) error } // 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) } // Stats record stattistics about a box. type Stats struct { // ReadOnly indicates that boxes cannot be modified. ReadOnly bool |
︙ | ︙ |
Changes to box/compbox/compbox.go.
︙ | ︙ | |||
17 18 19 20 21 22 23 | "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" | < < < < < < | < < < < < | < | < < < | < < | < < < < | < < < < | | < < < | < | < | | < | < | | < < | < | 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | "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" ) 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 { 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.ZidBoxManager): {genManagerM, genManagerC}, id.MustParse(api.ZidMetadataKey): {genKeysM, genKeysC}, id.MustParse(api.ZidStartupConfiguration): {genConfigZettelM, genConfigZettelC}, } // Get returns the one program box. func getCompBox(boxNumber int, mf box.Enricher) box.ManagedBox { return &compBox{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 (*compBox) CreateZettel(context.Context, domain.Zettel) (id.Zid, error) { return id.Invalid, box.ErrReadOnly } func (*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 { return domain.Zettel{ Meta: m, Content: domain.NewContent(genContent(m)), }, nil } return domain.Zettel{Meta: m}, nil } } return domain.Zettel{}, box.ErrNotFound } func (*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) return m, nil } } } return nil, box.ErrNotFound } func (*compBox) ApplyZid(_ context.Context, handle box.ZidFunc) error { for zid, gen := range myZettel { if genMeta := gen.meta; genMeta != nil { if genMeta(zid) != nil { handle(zid) } } } return nil } func (pp *compBox) ApplyMeta(ctx context.Context, handle box.MetaFunc) error { for zid, gen := range myZettel { if genMeta := gen.meta; genMeta != nil { if m := genMeta(zid); m != nil { updateMeta(m) pp.enricher.Enrich(ctx, m, pp.number) handle(m) } } } return nil } func (*compBox) CanUpdateZettel(context.Context, domain.Zettel) bool { return false } func (*compBox) UpdateZettel(context.Context, domain.Zettel) error { return box.ErrReadOnly } func (*compBox) AllowRenameZettel(_ context.Context, zid id.Zid) bool { _, ok := myZettel[zid] return !ok } func (*compBox) RenameZettel(_ context.Context, curZid, _ id.Zid) error { if _, ok := myZettel[curZid]; ok { return box.ErrReadOnly } return box.ErrNotFound } func (*compBox) CanDeleteZettel(context.Context, id.Zid) bool { return false } func (*compBox) DeleteZettel(_ context.Context, zid id.Zid) error { if _, ok := myZettel[zid]; ok { return box.ErrReadOnly } return box.ErrNotFound } func (*compBox) ReadStats(st *box.ManagedBoxStats) { st.ReadOnly = true st.Zettel = len(myZettel) } func updateMeta(m *meta.Meta) { m.Set(api.KeyNoIndex, api.ValueTrue) 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) } } |
Changes to box/compbox/config.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides zettel that have computed content. package compbox import ( "bytes" "zettelstore.de/c/api" "zettelstore.de/z/domain/id" |
︙ | ︙ | |||
26 27 28 29 30 31 32 | m.Set(api.KeyTitle, "Zettelstore Startup Configuration") m.Set(api.KeyVisibility, api.ValueVisibilityExpert) return m } func genConfigZettelC(*meta.Meta) []byte { var buf bytes.Buffer | | | 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | 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(false) { if i > 0 { buf.WriteByte('\n') } buf.WriteString("; ''") buf.WriteString(p.Key) buf.WriteString("''") if p.Value != "" { |
︙ | ︙ |
Changes to box/compbox/keys.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides zettel that have computed content. package compbox import ( "bytes" "fmt" "zettelstore.de/c/api" |
︙ | ︙ |
Deleted box/compbox/log.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to box/compbox/manager.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides zettel that have computed content. package compbox import ( "bytes" "fmt" "zettelstore.de/c/api" |
︙ | ︙ |
Deleted box/compbox/parser.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to box/compbox/version.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //----------------------------------------------------------------------------- // 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") | > | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | //----------------------------------------------------------------------------- // 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 provides zettel that have computed content. 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.ValueVisibilityPublic) return m } func genVersionBuildC(*meta.Meta) []byte { return []byte(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreVersion).(string)) } func genVersionHostM(zid id.Zid) *meta.Meta { |
︙ | ︙ |
Changes to box/constbox/base.mustache.
︙ | ︙ | |||
30 31 32 33 34 35 36 | {{/WithUser}} <div class="zs-dropdown"> <button>Lists</button> <nav class="zs-dropdown-content"> <a href="{{{ListZettelURL}}}">List Zettel</a> <a href="{{{ListRolesURL}}}">List Roles</a> <a href="{{{ListTagsURL}}}">List Tags</a> | < < < | 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | {{/WithUser}} <div class="zs-dropdown"> <button>Lists</button> <nav class="zs-dropdown-content"> <a href="{{{ListZettelURL}}}">List Zettel</a> <a href="{{{ListRolesURL}}}">List Roles</a> <a href="{{{ListTagsURL}}}">List Tags</a> </nav> </div> {{#HasNewZettelLinks}} <div class="zs-dropdown"> <button>New</button> <nav class="zs-dropdown-content"> {{#NewZettelLinks}} |
︙ | ︙ |
Changes to box/constbox/constbox.go.
︙ | ︙ | |||
18 19 20 21 22 23 24 | "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" | < < < < < < | < | | < < | | < < | < | < | < | < | < | | | < | < < | < | | | < | | < | < | < | | < | | | < | 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | "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" ) func init() { manager.Register( " const", func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) { return &constBox{ 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 { 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 (*constBox) CreateZettel(context.Context, domain.Zettel) (id.Zid, error) { return id.Invalid, box.ErrReadOnly } func (cp *constBox) GetZettel(_ context.Context, zid id.Zid) (domain.Zettel, error) { if z, ok := cp.zettel[zid]; ok { return domain.Zettel{Meta: meta.NewWithData(zid, z.header), Content: z.content}, nil } return domain.Zettel{}, box.ErrNotFound } func (cp *constBox) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) { if z, ok := cp.zettel[zid]; ok { return meta.NewWithData(zid, z.header), nil } return nil, box.ErrNotFound } func (cp *constBox) ApplyZid(_ context.Context, handle box.ZidFunc) error { for zid := range cp.zettel { handle(zid) } return nil } func (cp *constBox) ApplyMeta(ctx context.Context, handle box.MetaFunc) error { for zid, zettel := range cp.zettel { m := meta.NewWithData(zid, zettel.header) cp.enricher.Enrich(ctx, m, cp.number) handle(m) } return nil } func (*constBox) CanUpdateZettel(context.Context, domain.Zettel) bool { return false } func (*constBox) UpdateZettel(context.Context, domain.Zettel) error { return box.ErrReadOnly } func (cp *constBox) AllowRenameZettel(_ context.Context, zid id.Zid) bool { _, ok := cp.zettel[zid] return !ok } func (cp *constBox) RenameZettel(_ context.Context, curZid, _ id.Zid) error { if _, ok := cp.zettel[curZid]; ok { return box.ErrReadOnly } return box.ErrNotFound } func (*constBox) CanDeleteZettel(context.Context, id.Zid) bool { return false } func (cp *constBox) DeleteZettel(_ context.Context, zid id.Zid) error { if _, ok := cp.zettel[zid]; ok { return box.ErrReadOnly } return box.ErrNotFound } func (cp *constBox) ReadStats(st *box.ManagedBoxStats) { st.ReadOnly = true st.Zettel = len(cp.zettel) } const syntaxTemplate = "mustache" var constZettelMap = map[id.Zid]constZettel{ id.ConfigurationZid: { constHeader{ |
︙ | ︙ | |||
167 168 169 170 171 172 173 | 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, | | | | 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | 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.ValueVisibilityPublic, }, 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.ValueVisibilityPublic, }, domain.NewContent(contentDependencies)}, id.BaseTemplateZid: { constHeader{ api.KeyTitle: "Zettelstore Base HTML Template", api.KeyRole: api.ValueRoleConfiguration, api.KeySyntax: syntaxTemplate, |
︙ | ︙ | |||
334 335 336 337 338 339 340 | api.KeySyntax: api.ValueSyntaxZmk, api.KeyVisibility: api.ValueVisibilityCreator, }, domain.NewContent(nil)}, id.MustParse(api.ZidTemplateNewUser): { constHeader{ api.KeyTitle: "New User", | | | 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | api.KeySyntax: api.ValueSyntaxZmk, api.KeyVisibility: api.ValueVisibilityCreator, }, domain.NewContent(nil)}, id.MustParse(api.ZidTemplateNewUser): { constHeader{ api.KeyTitle: "New User", api.KeyRole: api.ValueRoleUser, 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)}, |
︙ | ︙ |
Changes to box/constbox/delete.mustache.
︙ | ︙ | |||
16 17 18 19 20 21 22 | <ul> {{#Incoming}} <li><a href="{{{URL}}}">{{Text}}</a></li> {{/Incoming}} </ul> </div> {{/HasIncoming}} | < < < < < < < < < < < | 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <ul> {{#Incoming}} <li><a href="{{{URL}}}">{{Text}}</a></li> {{/Incoming}} </ul> </div> {{/HasIncoming}} <dl> {{#MetaPairs}} <dt>{{Key}}:</dt><dd>{{Value}}</dd> {{/MetaPairs}} </dl> <form method="POST"> <input class="zs-button" type="submit" value="Delete"> |
︙ | ︙ |
Changes to box/constbox/dependencies.zettel.
1 2 3 | Zettelstore is made with the help of other software and other artifacts. Thank you very much! | | | 1 2 3 4 5 6 7 8 9 10 11 | 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 license. === Go runtime and associated libraries ; License : BSD 3-Clause "New" or "Revised" License ``` Copyright (c) 2009 The Go Authors. All rights reserved. |
︙ | ︙ |
Changes to box/constbox/info.mustache.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <article> <header> <h1>Information for Zettel {{Zid}}</h1> <a href="{{{WebURL}}}">Web</a> · <a href="{{{ContextURL}}}">Context</a> {{#CanWrite}} · <a href="{{{EditURL}}}">Edit</a>{{/CanWrite}} {{#CanFolge}} · <a href="{{{FolgeURL}}}">Folge</a>{{/CanFolge}} {{#CanCopy}} · <a href="{{{CopyURL}}}">Copy</a>{{/CanCopy}} {{#CanRename}}· <a href="{{{RenameURL}}}">Rename</a>{{/CanRename}} {{#CanDelete}}· <a href="{{{DeleteURL}}}">Delete</a>{{/CanDelete}} </header> <h2>Interpreted Metadata</h2> <table>{{#MetaData}}<tr><td>{{Key}}</td><td>{{{Value}}}</td></tr>{{/MetaData}}</table> <h2>References</h2> {{#HasLocLinks}} <h3>Local</h3> <ul> {{#LocLinks}} {{#Valid}}<li><a href="{{{Zid}}}">{{Zid}}</a></li>{{/Valid}} {{^Valid}}<li>{{Zid}}</li>{{/Valid}} {{/LocLinks}} </ul> {{/HasLocLinks}} {{#HasExtLinks}} <h3>External</h3> <ul> {{#ExtLinks}} <li><a href="{{{.}}}"{{{ExtNewWindow}}}>{{.}}</a></li> {{/ExtLinks}} </ul> {{/HasExtLinks}} | > < < | < < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | <article> <header> <h1>Information for Zettel {{Zid}}</h1> <a href="{{{WebURL}}}">Web</a> · <a href="{{{ContextURL}}}">Context</a> {{#CanWrite}} · <a href="{{{EditURL}}}">Edit</a>{{/CanWrite}} {{#CanFolge}} · <a href="{{{FolgeURL}}}">Folge</a>{{/CanFolge}} {{#CanCopy}} · <a href="{{{CopyURL}}}">Copy</a>{{/CanCopy}} {{#CanRename}}· <a href="{{{RenameURL}}}">Rename</a>{{/CanRename}} {{#CanDelete}}· <a href="{{{DeleteURL}}}">Delete</a>{{/CanDelete}} </header> <h2>Interpreted Metadata</h2> <table>{{#MetaData}}<tr><td>{{Key}}</td><td>{{{Value}}}</td></tr>{{/MetaData}}</table> {{#HasLinks}} <h2>References</h2> {{#HasLocLinks}} <h3>Local</h3> <ul> {{#LocLinks}} {{#Valid}}<li><a href="{{{Zid}}}">{{Zid}}</a></li>{{/Valid}} {{^Valid}}<li>{{Zid}}</li>{{/Valid}} {{/LocLinks}} </ul> {{/HasLocLinks}} {{#HasExtLinks}} <h3>External</h3> <ul> {{#ExtLinks}} <li><a href="{{{.}}}"{{{ExtNewWindow}}}>{{.}}</a></li> {{/ExtLinks}} </ul> {{/HasExtLinks}} {{/HasLinks}} <h2>Parts and encodings</h2> <table> {{#EvalMatrix}} <tr> <th>{{Header}}</th> {{#Elements}}<td><a href="{{{URL}}}">{{Text}}</td> {{/Elements}} |
︙ | ︙ |
Changes to box/constbox/rename.mustache.
1 2 | <article> <header> | | < < < < < < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <article> <header> <h1>Rename Zettel {{.Zid}}</h1> </header> <p>Do you really want to rename this zettel?</p> {{#HasIncoming}} <div class="zs-warning"> <h2>Warning!</h2> <p>If you rename this zettel, incoming references from the following zettel will become invalid.</p> <ul> {{#Incoming}} <li><a href="{{{URL}}}">{{Text}}</a></li> {{/Incoming}} </ul> </div> {{/HasIncoming}} <form method="POST"> <div> <label for="newid">New zettel id</label> <input class="zs-input" type="text" id="newzid" name="newzid" placeholder="ZID.." value="{{Zid}}" autofocus> </div> <input type="hidden" id="curzid" name="curzid" value="{{Zid}}"> <input class="zs-button" type="submit" value="Rename"> |
︙ | ︙ |
Changes to box/constbox/zettel.mustache.
︙ | ︙ | |||
25 26 27 28 29 30 31 | {{/FolgeLinks}} </ul> </details> </nav> {{/HasFolgeLinks}} {{#HasBackLinks}} <nav> | | | | 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | {{/FolgeLinks}} </ul> </details> </nav> {{/HasFolgeLinks}} {{#HasBackLinks}} <nav> <details> <summary>Additional links to this zettel</summary> <ul> {{#BackLinks}} <li><a href="{{{URL}}}">{{Text}}</a></li> {{/BackLinks}} </ul> </details> </nav> |
︙ | ︙ |
Changes to box/dirbox/dirbox.go.
1 | //----------------------------------------------------------------------------- | | > > | | > < < < < < < < > < > | | < < < < < < | < < < | < < < < < < < < < < < < < < < < | | | | < < < < < < < < < < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | //----------------------------------------------------------------------------- // 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 dirbox provides a directory-based zettel box. package dirbox import ( "context" "errors" "net/url" "os" "path/filepath" "strconv" "strings" "sync" "time" "zettelstore.de/c/api" "zettelstore.de/z/box" "zettelstore.de/z/box/dirbox/directory" "zettelstore.de/z/box/filebox" "zettelstore.de/z/box/manager" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" ) func init() { manager.Register("dir", func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) { path := getDirPath(u) if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { return nil, err } dirSrvSpec, defWorker, maxWorker := getDirSrvInfo(u.Query().Get("type")) dp := dirBox{ number: cdata.Number, location: u.String(), readonly: getQueryBool(u, "readonly"), cdata: *cdata, dir: path, dirRescan: time.Duration(getQueryInt(u, "rescan", 60, 3600, 30*24*60*60)) * time.Second, dirSrvSpec: dirSrvSpec, fSrvs: uint32(getQueryInt(u, "worker", 1, defWorker, maxWorker)), } return &dp, nil }) } type directoryServiceSpec int const ( _ directoryServiceSpec = iota dirSrvAny dirSrvSimple dirSrvNotify ) func getDirPath(u *url.URL) string { if u.Opaque != "" { return filepath.Clean(u.Opaque) } return filepath.Clean(u.Path) } |
︙ | ︙ | |||
133 134 135 136 137 138 139 | return max } return iVal } // dirBox uses a directory to store zettel as files. type dirBox struct { | < > | | > < | | < < | < < < < < | | < < < < < < < | < < < < < < | < | < < < < < > > | < | > | | | < | | | < | | | | < | < < < < < | | | | | | > > | | | > | | | < | | < | | | > > > | < | > > > > | > > | | < | > > > > > > > > > > > > > > > > > > > > > > > > > > > | > > > > > | | | | | > > > > > > | > | | | < | | | | | | < < < | < | < > > > > > > > > > | 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 | return max } return iVal } // dirBox uses a directory to store zettel as files. type dirBox struct { number int location string readonly bool cdata manager.ConnectData dir string dirRescan time.Duration dirSrvSpec directoryServiceSpec dirSrv directory.Service mustNotify bool 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() dp.fCmds = make([]chan fileCmd, 0, dp.fSrvs) for i := uint32(0); i < dp.fSrvs; i++ { cc := make(chan fileCmd) go fileService(cc) dp.fCmds = append(dp.fCmds, cc) } dp.setupDirService() dp.mxCmds.Unlock() if dp.dirSrv == nil { panic("No directory service") } return dp.dirSrv.Start() } func (dp *dirBox) Stop(_ context.Context) error { dirSrv := dp.dirSrv dp.dirSrv = nil err := dirSrv.Stop() for _, c := range dp.fCmds { close(c) } return err } func (dp *dirBox) notifyChanged(reason box.UpdateReason, zid id.Zid) { if dp.mustNotify { if chci := dp.cdata.Notify; chci != nil { 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(_ context.Context, zettel domain.Zettel) (id.Zid, error) { if dp.readonly { return id.Invalid, box.ErrReadOnly } entry, err := dp.dirSrv.GetNew() if err != nil { return id.Invalid, err } meta := zettel.Meta meta.Zid = entry.Zid dp.updateEntryFromMeta(entry, meta) err = setZettel(dp, entry, zettel) if err == nil { dp.dirSrv.UpdateEntry(entry) } dp.notifyChanged(box.OnUpdate, meta.Zid) return meta.Zid, err } func (dp *dirBox) GetZettel(_ context.Context, zid id.Zid) (domain.Zettel, error) { entry, err := dp.dirSrv.GetEntry(zid) if err != nil || !entry.IsValid() { return domain.Zettel{}, box.ErrNotFound } m, c, err := getMetaContent(dp, entry, zid) if err != nil { return domain.Zettel{}, err } dp.cleanupMeta(m) zettel := domain.Zettel{Meta: m, Content: domain.NewContent(c)} return zettel, nil } func (dp *dirBox) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) { entry, err := dp.dirSrv.GetEntry(zid) if err != nil || !entry.IsValid() { return nil, box.ErrNotFound } m, err := getMeta(dp, entry, zid) if err != nil { return nil, err } dp.cleanupMeta(m) return m, nil } func (dp *dirBox) ApplyZid(_ context.Context, handle box.ZidFunc) error { entries, err := dp.dirSrv.GetEntries() if err != nil { return err } for _, entry := range entries { handle(entry.Zid) } return nil } func (dp *dirBox) ApplyMeta(ctx context.Context, handle box.MetaFunc) error { entries, err := dp.dirSrv.GetEntries() if err != nil { return err } // The following loop could be parallelized if needed for performance. for _, entry := range entries { m, err1 := getMeta(dp, entry, entry.Zid) if err1 != nil { return err1 } dp.cleanupMeta(m) 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(_ context.Context, zettel domain.Zettel) error { if dp.readonly { return box.ErrReadOnly } meta := zettel.Meta if !meta.Zid.IsValid() { return &box.ErrInvalidID{Zid: meta.Zid} } entry, err := dp.dirSrv.GetEntry(meta.Zid) if err != nil { return err } if !entry.IsValid() { // Existing zettel, but new in this box. entry = &directory.Entry{Zid: meta.Zid} dp.updateEntryFromMeta(entry, meta) } else if entry.MetaSpec == directory.MetaSpecNone { defaultMeta := filebox.CalcDefaultMeta(entry.Zid, entry.ContentExt) if !meta.Equal(defaultMeta, true) { dp.updateEntryFromMeta(entry, meta) dp.dirSrv.UpdateEntry(entry) } } err = setZettel(dp, entry, zettel) if err == nil { dp.notifyChanged(box.OnUpdate, meta.Zid) } return err } func (dp *dirBox) updateEntryFromMeta(entry *directory.Entry, meta *meta.Meta) { entry.MetaSpec, entry.ContentExt = dp.calcSpecExt(meta) basePath := dp.calcBasePath(entry) if entry.MetaSpec == directory.MetaSpecFile { entry.MetaPath = basePath + ".meta" } entry.ContentPath = basePath + "." + entry.ContentExt entry.Duplicates = false } func (dp *dirBox) calcBasePath(entry *directory.Entry) string { p := entry.ContentPath if p == "" { return filepath.Join(dp.dir, entry.Zid.String()) } // ContentPath w/o the file extension return p[0 : len(p)-len(filepath.Ext(p))] } func (dp *dirBox) calcSpecExt(m *meta.Meta) (directory.MetaSpec, string) { if m.YamlSep { return directory.MetaSpecHeader, "zettel" } syntax := m.GetDefault(api.KeySyntax, "bin") switch syntax { case api.ValueSyntaxNone, api.ValueSyntaxZmk: return directory.MetaSpecHeader, "zettel" } for _, s := range dp.cdata.Config.GetZettelFileSyntax() { if s == syntax { return directory.MetaSpecHeader, "zettel" } } return directory.MetaSpecFile, syntax } 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, err := dp.dirSrv.GetEntry(curZid) if err != nil || !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.GetMeta(ctx, newZid); err == nil { return &box.ErrInvalidID{Zid: newZid} } oldMeta, oldContent, err := getMetaContent(dp, curEntry, curZid) if err != nil { return err } newEntry := directory.Entry{ Zid: newZid, MetaSpec: curEntry.MetaSpec, MetaPath: renamePath(curEntry.MetaPath, curZid, newZid), ContentPath: renamePath(curEntry.ContentPath, curZid, newZid), ContentExt: curEntry.ContentExt, } if err = dp.dirSrv.RenameEntry(curEntry, &newEntry); err != nil { return err } oldMeta.Zid = newZid newZettel := domain.Zettel{Meta: oldMeta, Content: domain.NewContent(oldContent)} if err = setZettel(dp, &newEntry, newZettel); err != nil { // "Rollback" rename. No error checking... dp.dirSrv.RenameEntry(&newEntry, curEntry) return err } err = deleteZettel(dp, curEntry, curZid) if err == nil { dp.notifyChanged(box.OnDelete, curZid) dp.notifyChanged(box.OnUpdate, newZid) } return err } func (dp *dirBox) CanDeleteZettel(_ context.Context, zid id.Zid) bool { if dp.readonly { return false } entry, err := dp.dirSrv.GetEntry(zid) return err == nil && entry.IsValid() } func (dp *dirBox) DeleteZettel(_ context.Context, zid id.Zid) error { if dp.readonly { return box.ErrReadOnly } entry, err := dp.dirSrv.GetEntry(zid) if err != nil || !entry.IsValid() { return box.ErrNotFound } dp.dirSrv.DeleteEntry(zid) err = deleteZettel(dp, entry, zid) if err == nil { dp.notifyChanged(box.OnDelete, zid) } return err } func (dp *dirBox) ReadStats(st *box.ManagedBoxStats) { st.ReadOnly = dp.readonly st.Zettel, _ = dp.dirSrv.NumEntries() } func (dp *dirBox) cleanupMeta(m *meta.Meta) { if role, ok := m.Get(api.KeyRole); !ok || role == "" { m.Set(api.KeyRole, dp.cdata.Config.GetDefaultRole()) } if syntax, ok := m.Get(api.KeySyntax); !ok || syntax == "" { m.Set(api.KeySyntax, dp.cdata.Config.GetDefaultSyntax()) } } func renamePath(path string, curID, newID id.Zid) string { dir, file := filepath.Split(path) if cur := curID.String(); strings.HasPrefix(file, cur) { file = newID.String() + file[len(cur):] return filepath.Join(dir, file) } return path } |
Deleted box/dirbox/dirbox_test.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Added box/dirbox/directory/directory.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | //----------------------------------------------------------------------------- // 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 directory manages the directory interface of a dirstore. package directory import "zettelstore.de/z/domain/id" // Service is the interface of a directory service. type Service interface { Start() error Stop() error NumEntries() (int, error) GetEntries() ([]*Entry, error) GetEntry(zid id.Zid) (*Entry, error) GetNew() (*Entry, error) UpdateEntry(entry *Entry) error RenameEntry(curEntry, newEntry *Entry) error DeleteEntry(zid id.Zid) error } // MetaSpec defines all possibilities where meta data can be stored. type MetaSpec int // Constants for MetaSpec const ( _ MetaSpec = iota MetaSpecNone // no meta information MetaSpecFile // meta information is in meta file MetaSpecHeader // meta information is in header ) // Entry stores everything for a directory entry. type Entry struct { Zid id.Zid MetaSpec MetaSpec // location of meta information MetaPath string // file path of meta information ContentPath string // file path of zettel content ContentExt string // (normalized) file extension of zettel content Duplicates bool // multiple content files } // IsValid checks whether the entry is valid. func (e *Entry) IsValid() bool { return e != nil && e.Zid.IsValid() } |
Added box/dirbox/makedir.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | //----------------------------------------------------------------------------- // 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 provides a directory-based zettel box. package dirbox import ( "zettelstore.de/z/box/dirbox/notifydir" "zettelstore.de/z/box/dirbox/simpledir" "zettelstore.de/z/kernel" ) func getDirSrvInfo(dirType string) (directoryServiceSpec, int, int) { for count := 0; count < 2; count++ { switch dirType { case kernel.BoxDirTypeNotify: return dirSrvNotify, 7, 1499 case kernel.BoxDirTypeSimple: return dirSrvSimple, 1, 1 default: dirType = kernel.Main.GetConfig(kernel.BoxService, kernel.BoxDefaultDirType).(string) } } panic("unable to set default dir box type: " + dirType) } func (dp *dirBox) setupDirService() { switch dp.dirSrvSpec { case dirSrvSimple: dp.dirSrv = simpledir.NewService(dp.dir) dp.mustNotify = true default: dp.dirSrv = notifydir.NewService(dp.dir, dp.dirRescan, dp.cdata.Notify) dp.mustNotify = false } } |
Added box/dirbox/notifydir/notifydir.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | //----------------------------------------------------------------------------- // 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 notifydir manages the notified directory part of a dirstore. package notifydir import ( "time" "zettelstore.de/z/box" "zettelstore.de/z/box/dirbox/directory" "zettelstore.de/z/domain/id" ) // notifyService specifies a directory scan service. type notifyService struct { dirPath string rescanTime time.Duration done chan struct{} cmds chan dirCmd infos chan<- box.UpdateInfo } // NewService creates a new directory service. func NewService(directoryPath string, rescanTime time.Duration, chci chan<- box.UpdateInfo) directory.Service { srv := ¬ifyService{ dirPath: directoryPath, rescanTime: rescanTime, cmds: make(chan dirCmd), infos: chci, } return srv } // Start makes the directory service operational. func (srv *notifyService) Start() error { tick := make(chan struct{}) rawEvents := make(chan *fileEvent) events := make(chan *fileEvent) ready := make(chan int) go srv.directoryService(events, ready) go collectEvents(events, rawEvents) go watchDirectory(srv.dirPath, rawEvents, tick) if srv.done != nil { panic("src.done already set") } srv.done = make(chan struct{}) go ping(tick, srv.rescanTime, srv.done) <-ready return nil } // Stop stops the directory service. func (srv *notifyService) Stop() error { close(srv.done) srv.done = nil return nil } func (srv *notifyService) notifyChange(reason box.UpdateReason, zid id.Zid) { if chci := srv.infos; chci != nil { chci <- box.UpdateInfo{Reason: reason, Zid: zid} } } // NumEntries returns the number of managed zettel. func (srv *notifyService) NumEntries() (int, error) { resChan := make(chan resNumEntries) srv.cmds <- &cmdNumEntries{resChan} return <-resChan, nil } // GetEntries returns an unsorted list of all current directory entries. func (srv *notifyService) GetEntries() ([]*directory.Entry, error) { resChan := make(chan resGetEntries) srv.cmds <- &cmdGetEntries{resChan} return <-resChan, nil } // GetEntry returns the entry with the specified zettel id. If there is no such // zettel id, an empty entry is returned. func (srv *notifyService) GetEntry(zid id.Zid) (*directory.Entry, error) { resChan := make(chan resGetEntry) srv.cmds <- &cmdGetEntry{zid, resChan} return <-resChan, nil } // GetNew returns an entry with a new zettel id. func (srv *notifyService) GetNew() (*directory.Entry, error) { resChan := make(chan resNewEntry) srv.cmds <- &cmdNewEntry{resChan} result := <-resChan return result.entry, result.err } // UpdateEntry notifies the directory of an updated entry. func (srv *notifyService) UpdateEntry(entry *directory.Entry) error { resChan := make(chan struct{}) srv.cmds <- &cmdUpdateEntry{entry, resChan} <-resChan return nil } // RenameEntry notifies the directory of an renamed entry. func (srv *notifyService) RenameEntry(curEntry, newEntry *directory.Entry) error { resChan := make(chan resRenameEntry) srv.cmds <- &cmdRenameEntry{curEntry, newEntry, resChan} return <-resChan } // DeleteEntry removes a zettel id from the directory of entries. func (srv *notifyService) DeleteEntry(zid id.Zid) error { resChan := make(chan struct{}) srv.cmds <- &cmdDeleteEntry{zid, resChan} <-resChan return nil } |
Added box/dirbox/notifydir/service.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 | //----------------------------------------------------------------------------- // 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 notifydir manages the notified directory part of a dirstore. package notifydir import ( "log" "time" "zettelstore.de/z/box" "zettelstore.de/z/box/dirbox/directory" "zettelstore.de/z/domain/id" ) // ping sends every tick a signal to reload the directory list func ping(tick chan<- struct{}, rescanTime time.Duration, done <-chan struct{}) { ticker := time.NewTicker(rescanTime) defer close(tick) for { select { case _, ok := <-ticker.C: if !ok { return } tick <- struct{}{} case _, ok := <-done: if !ok { ticker.Stop() return } } } } func newEntry(ev *fileEvent) *directory.Entry { de := new(directory.Entry) de.Zid = ev.zid updateEntry(de, ev) return de } func updateEntry(de *directory.Entry, ev *fileEvent) { if ev.ext == "meta" { de.MetaSpec = directory.MetaSpecFile de.MetaPath = ev.path return } if de.ContentExt != "" && de.ContentExt != ev.ext { de.Duplicates = true return } if de.MetaSpec != directory.MetaSpecFile { if ev.ext == "zettel" { de.MetaSpec = directory.MetaSpecHeader } else { de.MetaSpec = directory.MetaSpecNone } } de.ContentPath = ev.path de.ContentExt = ev.ext } type dirMap map[id.Zid]*directory.Entry func dirMapUpdate(dm dirMap, ev *fileEvent) { de := dm[ev.zid] if de == nil { dm[ev.zid] = newEntry(ev) return } updateEntry(de, ev) } func deleteFromMap(dm dirMap, ev *fileEvent) { if ev.ext == "meta" { if entry, ok := dm[ev.zid]; ok { if entry.MetaSpec == directory.MetaSpecFile { entry.MetaSpec = directory.MetaSpecNone return } } } delete(dm, ev.zid) } // directoryService is the main service. func (srv *notifyService) directoryService(events <-chan *fileEvent, ready chan<- int) { curMap := make(dirMap) var newMap dirMap for { select { case ev, ok := <-events: if !ok { return } switch ev.status { case fileStatusReloadStart: newMap = make(dirMap) case fileStatusReloadEnd: curMap = newMap newMap = nil if ready != nil { ready <- len(curMap) close(ready) ready = nil } srv.notifyChange(box.OnReload, id.Invalid) case fileStatusError: log.Println("DIRBOX", "ERROR", ev.err) case fileStatusUpdate: srv.processFileUpdateEvent(ev, curMap, newMap) case fileStatusDelete: srv.processFileDeleteEvent(ev, curMap, newMap) } case cmd, ok := <-srv.cmds: if ok { cmd.run(curMap) } } } } func (srv *notifyService) processFileUpdateEvent(ev *fileEvent, curMap, newMap dirMap) { if newMap != nil { dirMapUpdate(newMap, ev) } else { dirMapUpdate(curMap, ev) srv.notifyChange(box.OnUpdate, ev.zid) } } func (srv *notifyService) processFileDeleteEvent(ev *fileEvent, curMap, newMap dirMap) { if newMap != nil { deleteFromMap(newMap, ev) } else { deleteFromMap(curMap, ev) srv.notifyChange(box.OnDelete, ev.zid) } } type dirCmd interface { run(m dirMap) } type cmdNumEntries struct { result chan<- resNumEntries } type resNumEntries = int func (cmd *cmdNumEntries) run(m dirMap) { cmd.result <- len(m) } type cmdGetEntries struct { result chan<- resGetEntries } type resGetEntries []*directory.Entry func (cmd *cmdGetEntries) run(m dirMap) { res := make([]*directory.Entry, len(m)) i := 0 for _, de := range m { entry := *de res[i] = &entry i++ } cmd.result <- res } type cmdGetEntry struct { zid id.Zid result chan<- resGetEntry } type resGetEntry = *directory.Entry func (cmd *cmdGetEntry) run(m dirMap) { entry := m[cmd.zid] if entry == nil { cmd.result <- nil } else { result := *entry cmd.result <- &result } } type cmdNewEntry struct { result chan<- resNewEntry } type resNewEntry struct { entry *directory.Entry err error } func (cmd *cmdNewEntry) run(m dirMap) { zid, err := box.GetNewZid(func(zid id.Zid) (bool, error) { _, ok := m[zid] return !ok, nil }) if err != nil { cmd.result <- resNewEntry{nil, err} return } entry := &directory.Entry{Zid: zid} m[zid] = entry cmd.result <- resNewEntry{&directory.Entry{Zid: zid}, nil} } type cmdUpdateEntry struct { entry *directory.Entry result chan<- struct{} } func (cmd *cmdUpdateEntry) run(m dirMap) { entry := *cmd.entry m[entry.Zid] = &entry cmd.result <- struct{}{} } type cmdRenameEntry struct { curEntry *directory.Entry newEntry *directory.Entry result chan<- resRenameEntry } type resRenameEntry = error func (cmd *cmdRenameEntry) run(m dirMap) { newEntry := *cmd.newEntry newZid := newEntry.Zid if _, found := m[newZid]; found { cmd.result <- &box.ErrInvalidID{Zid: newZid} return } delete(m, cmd.curEntry.Zid) m[newZid] = &newEntry cmd.result <- nil } type cmdDeleteEntry struct { zid id.Zid result chan<- struct{} } func (cmd *cmdDeleteEntry) run(m dirMap) { delete(m, cmd.zid) cmd.result <- struct{}{} } |
Added box/dirbox/notifydir/watch.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | //----------------------------------------------------------------------------- // 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 notifydir manages the notified directory part of a dirstore. package notifydir import ( "os" "path/filepath" "regexp" "time" "github.com/fsnotify/fsnotify" "zettelstore.de/z/domain/id" ) var validFileName = regexp.MustCompile(`^(\d{14}).*(\.(.+))$`) func matchValidFileName(name string) []string { return validFileName.FindStringSubmatch(name) } type fileStatus int const ( fileStatusNone fileStatus = iota fileStatusReloadStart fileStatusReloadEnd fileStatusError fileStatusUpdate fileStatusDelete ) type fileEvent struct { status fileStatus path string // Full file path zid id.Zid ext string // File extension err error // Error if Status == fileStatusError } type sendResult int const ( sendDone sendResult = iota sendReload sendExit ) func watchDirectory(directory string, events chan<- *fileEvent, tick <-chan struct{}) { defer close(events) var watcher *fsnotify.Watcher defer func() { if watcher != nil { watcher.Close() } }() sendEvent := func(ev *fileEvent) sendResult { select { case events <- ev: case _, ok := <-tick: if ok { return sendReload } return sendExit } return sendDone } sendError := func(err error) sendResult { return sendEvent(&fileEvent{status: fileStatusError, err: err}) } sendFileEvent := func(status fileStatus, path string, match []string) sendResult { zid, err := id.Parse(match[1]) if err != nil { return sendDone } event := &fileEvent{ status: status, path: path, zid: zid, ext: match[3], } return sendEvent(event) } reloadStartEvent := &fileEvent{status: fileStatusReloadStart} reloadEndEvent := &fileEvent{status: fileStatusReloadEnd} reloadFiles := func() bool { entries, err := os.ReadDir(directory) if err != nil { if res := sendError(err); res != sendDone { return res == sendReload } return true } if res := sendEvent(reloadStartEvent); res != sendDone { return res == sendReload } if watcher != nil { watcher.Close() } watcher, err = fsnotify.NewWatcher() if err != nil { if res := sendError(err); res != sendDone { return res == sendReload } } for _, entry := range entries { if entry.IsDir() { continue } if info, err1 := entry.Info(); err1 != nil || !info.Mode().IsRegular() { continue } name := entry.Name() match := matchValidFileName(name) if len(match) > 0 { path := filepath.Join(directory, name) if res := sendFileEvent(fileStatusUpdate, path, match); res != sendDone { return res == sendReload } } } if watcher != nil { err = watcher.Add(directory) if err != nil { if res := sendError(err); res != sendDone { return res == sendReload } } } if res := sendEvent(reloadEndEvent); res != sendDone { return res == sendReload } return true } handleEvents := func() bool { const createOps = fsnotify.Create | fsnotify.Write const deleteOps = fsnotify.Remove | fsnotify.Rename for { select { case wevent, ok := <-watcher.Events: if !ok { return false } path := filepath.Clean(wevent.Name) match := matchValidFileName(filepath.Base(path)) if len(match) == 0 { continue } if wevent.Op&createOps != 0 { if fi, err := os.Lstat(path); err != nil || !fi.Mode().IsRegular() { continue } if res := sendFileEvent( fileStatusUpdate, path, match); res != sendDone { return res == sendReload } } if wevent.Op&deleteOps != 0 { if res := sendFileEvent( fileStatusDelete, path, match); res != sendDone { return res == sendReload } } case err, ok := <-watcher.Errors: if !ok { return false } if res := sendError(err); res != sendDone { return res == sendReload } case _, ok := <-tick: return ok } } } for { if !reloadFiles() { return } if watcher == nil { if _, ok := <-tick; !ok { return } } else { if !handleEvents() { return } } } } func sendCollectedEvents(out chan<- *fileEvent, events []*fileEvent) { for _, ev := range events { if ev.status != fileStatusNone { out <- ev } } } func addEvent(events []*fileEvent, ev *fileEvent) []*fileEvent { switch ev.status { case fileStatusNone: return events case fileStatusReloadStart: events = events[0:0] case fileStatusUpdate, fileStatusDelete: if len(events) > 0 && mergeEvents(events, ev) { return events } } return append(events, ev) } func mergeEvents(events []*fileEvent, ev *fileEvent) bool { for i := len(events) - 1; i >= 0; i-- { oev := events[i] switch oev.status { case fileStatusReloadStart, fileStatusReloadEnd: return false case fileStatusUpdate, fileStatusDelete: if ev.path == oev.path { if ev.status == oev.status { return true } oev.status = fileStatusNone return false } } } return false } func collectEvents(out chan<- *fileEvent, in <-chan *fileEvent) { defer close(out) var sendTime time.Time sendTimeSet := false ticker := time.NewTicker(500 * time.Millisecond) defer ticker.Stop() events := make([]*fileEvent, 0, 32) buffer := false for { select { case ev, ok := <-in: if !ok { sendCollectedEvents(out, events) return } if ev.status == fileStatusReloadStart { buffer = false events = events[0:0] } if buffer { if !sendTimeSet { sendTime = time.Now().Add(1500 * time.Millisecond) sendTimeSet = true } events = addEvent(events, ev) if len(events) > 1024 { sendCollectedEvents(out, events) events = events[0:0] sendTimeSet = false } continue } out <- ev if ev.status == fileStatusReloadEnd { buffer = true } case now := <-ticker.C: if sendTimeSet && now.After(sendTime) { sendCollectedEvents(out, events) events = events[0:0] sendTimeSet = false } } } } |
Added box/dirbox/notifydir/watch_test.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | //----------------------------------------------------------------------------- // 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 notifydir manages the notified directory part of a dirstore. package notifydir import "testing" func sameStringSlices(sl1, sl2 []string) bool { if len(sl1) != len(sl2) { return false } for i := 0; i < len(sl1); i++ { if sl1[i] != sl2[i] { return false } } return true } func TestMatchValidFileName(t *testing.T) { t.Parallel() testcases := []struct { name string exp []string }{ {"", []string{}}, {".txt", []string{}}, {"12345678901234.txt", []string{"12345678901234", ".txt", "txt"}}, {"12345678901234abc.txt", []string{"12345678901234", ".txt", "txt"}}, {"12345678901234.abc.txt", []string{"12345678901234", ".txt", "txt"}}, } for i, tc := range testcases { got := matchValidFileName(tc.name) if len(got) == 0 { if len(tc.exp) > 0 { t.Errorf("TC=%d, name=%q, exp=%v, got=%v", i, tc.name, tc.exp, got) } } else { if got[0] != tc.name { t.Errorf("TC=%d, name=%q, got=%v", i, tc.name, got) } if !sameStringSlices(got[1:], tc.exp) { t.Errorf("TC=%d, name=%q, exp=%v, got=%v", i, tc.name, tc.exp, got) } } } } |
Changes to box/dirbox/service.go.
1 | //----------------------------------------------------------------------------- | | > < < < < | | < < | < < < < < < < < < | < | < < | | | < < < | > | < < < | | > < < | | < | < < < | | | | < < < | | | < < < | > | < < < | | | < | < | | | | | | | | < < < < < < < < < < | | | < < < | > | < < < | | > | | < | > | | | < < < < | < < < < | < | < | < < < < > | | < < | | | < | | | | > | | < < < > | | < < | > > | < | | < | < | < < < < | < < < < | | | < < < | < < < < < < < < | | | < < < | < | | | | < | | | < < | < < < | < < | < < < < > | < > | < > > > > > > | | | | < | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | //----------------------------------------------------------------------------- // 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 dirbox provides a directory-based zettel box. package dirbox import ( "os" "zettelstore.de/z/box/dirbox/directory" "zettelstore.de/z/box/filebox" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" "zettelstore.de/z/input" ) func fileService(cmds <-chan fileCmd) { for cmd := range cmds { cmd.run() } } type fileCmd interface { run() } // COMMAND: getMeta ---------------------------------------- // // Retrieves the meta data from a zettel. func getMeta(dp *dirBox, entry *directory.Entry, zid id.Zid) (*meta.Meta, error) { rc := make(chan resGetMeta) dp.getFileChan(zid) <- &fileGetMeta{entry, rc} res := <-rc close(rc) return res.meta, res.err } type fileGetMeta struct { entry *directory.Entry rc chan<- resGetMeta } type resGetMeta struct { meta *meta.Meta err error } func (cmd *fileGetMeta) run() { entry := cmd.entry var m *meta.Meta var err error switch entry.MetaSpec { case directory.MetaSpecFile: m, err = parseMetaFile(entry.Zid, entry.MetaPath) case directory.MetaSpecHeader: m, _, err = parseMetaContentFile(entry.Zid, entry.ContentPath) default: m = filebox.CalcDefaultMeta(entry.Zid, entry.ContentExt) } if err == nil { cmdCleanupMeta(m, entry) } cmd.rc <- resGetMeta{m, err} } // COMMAND: getMetaContent ---------------------------------------- // // Retrieves the meta data and the content of a zettel. func getMetaContent(dp *dirBox, entry *directory.Entry, zid id.Zid) (*meta.Meta, []byte, error) { rc := make(chan resGetMetaContent) dp.getFileChan(zid) <- &fileGetMetaContent{entry, rc} res := <-rc close(rc) return res.meta, res.content, res.err } type fileGetMetaContent struct { entry *directory.Entry rc chan<- resGetMetaContent } type resGetMetaContent struct { meta *meta.Meta content []byte err error } func (cmd *fileGetMetaContent) run() { var m *meta.Meta var content []byte var err error entry := cmd.entry switch entry.MetaSpec { case directory.MetaSpecFile: m, err = parseMetaFile(entry.Zid, entry.MetaPath) if err == nil { content, err = readFileContent(entry.ContentPath) } case directory.MetaSpecHeader: m, content, err = parseMetaContentFile(entry.Zid, entry.ContentPath) default: m = filebox.CalcDefaultMeta(entry.Zid, entry.ContentExt) content, err = readFileContent(entry.ContentPath) } if err == nil { cmdCleanupMeta(m, entry) } cmd.rc <- resGetMetaContent{m, content, err} } // COMMAND: setZettel ---------------------------------------- // // Writes a new or exsting zettel. func setZettel(dp *dirBox, entry *directory.Entry, zettel domain.Zettel) error { rc := make(chan resSetZettel) dp.getFileChan(zettel.Meta.Zid) <- &fileSetZettel{entry, zettel, rc} err := <-rc close(rc) return err } type fileSetZettel struct { entry *directory.Entry zettel domain.Zettel rc chan<- resSetZettel } type resSetZettel = error func (cmd *fileSetZettel) run() { var err error switch cmd.entry.MetaSpec { case directory.MetaSpecFile: err = cmd.runMetaSpecFile() case directory.MetaSpecHeader: err = cmd.runMetaSpecHeader() case directory.MetaSpecNone: // TODO: if meta has some additional infos: write meta to new .meta; // update entry in dir err = writeFileContent(cmd.entry.ContentPath, cmd.zettel.Content.AsString()) default: panic("TODO: ???") } cmd.rc <- err } func (cmd *fileSetZettel) runMetaSpecFile() error { f, err := openFileWrite(cmd.entry.MetaPath) if err == nil { err = writeFileZid(f, cmd.zettel.Meta.Zid) if err == nil { _, err = cmd.zettel.Meta.Write(f, true) if err1 := f.Close(); err == nil { err = err1 } if err == nil { err = writeFileContent(cmd.entry.ContentPath, cmd.zettel.Content.AsString()) } } } return err } func (cmd *fileSetZettel) runMetaSpecHeader() error { f, err := openFileWrite(cmd.entry.ContentPath) if err == nil { err = writeFileZid(f, cmd.zettel.Meta.Zid) if err == nil { _, err = cmd.zettel.Meta.WriteAsHeader(f, true) if err == nil { _, err = f.WriteString(cmd.zettel.Content.AsString()) if err1 := f.Close(); err == nil { err = err1 } } } } return err } // COMMAND: deleteZettel ---------------------------------------- // // Deletes an existing zettel. func deleteZettel(dp *dirBox, entry *directory.Entry, zid id.Zid) error { rc := make(chan resDeleteZettel) dp.getFileChan(zid) <- &fileDeleteZettel{entry, rc} err := <-rc close(rc) return err } type fileDeleteZettel struct { entry *directory.Entry rc chan<- resDeleteZettel } type resDeleteZettel = error func (cmd *fileDeleteZettel) run() { var err error switch cmd.entry.MetaSpec { case directory.MetaSpecFile: err1 := os.Remove(cmd.entry.MetaPath) err = os.Remove(cmd.entry.ContentPath) if err == nil { err = err1 } case directory.MetaSpecHeader: err = os.Remove(cmd.entry.ContentPath) case directory.MetaSpecNone: err = os.Remove(cmd.entry.ContentPath) default: panic("TODO: ???") } cmd.rc <- err } // Utility functions ---------------------------------------- func readFileContent(path string) ([]byte, error) { return os.ReadFile(path) } func parseMetaFile(zid id.Zid, path string) (*meta.Meta, error) { src, err := readFileContent(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 := readFileContent(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 *directory.Entry) { filebox.CleanupMeta( m, entry.Zid, entry.ContentExt, entry.MetaSpec == directory.MetaSpecFile, entry.Duplicates, ) } func openFileWrite(path string) (*os.File, error) { return os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) } func writeFileZid(f *os.File, zid id.Zid) error { _, err := f.WriteString("id: ") if err == nil { _, err = f.Write(zid.Bytes()) if err == nil { _, err = f.WriteString("\n") } } return err } func writeFileContent(path, content string) error { f, err := openFileWrite(path) if err == nil { _, err = f.WriteString(content) if err1 := f.Close(); err == nil { err = err1 } } return err } |
Added box/dirbox/simpledir/simpledir.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | //----------------------------------------------------------------------------- // 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 simpledir manages the directory part of a dirstore. package simpledir import ( "os" "path/filepath" "regexp" "sync" "zettelstore.de/z/box" "zettelstore.de/z/box/dirbox/directory" "zettelstore.de/z/domain/id" ) // simpleService specifies a directory service without scanning. type simpleService struct { dirPath string mx sync.Mutex } // NewService creates a new directory service. func NewService(directoryPath string) directory.Service { return &simpleService{ dirPath: directoryPath, } } func (ss *simpleService) Start() error { ss.mx.Lock() defer ss.mx.Unlock() _, err := os.ReadDir(ss.dirPath) return err } func (*simpleService) Stop() error { return nil } func (ss *simpleService) NumEntries() (int, error) { ss.mx.Lock() defer ss.mx.Unlock() entries, err := ss.doGetEntries() if err == nil { return len(entries), nil } return 0, err } func (ss *simpleService) GetEntries() ([]*directory.Entry, error) { ss.mx.Lock() defer ss.mx.Unlock() entrySet, err := ss.doGetEntries() if err != nil { return nil, err } result := make([]*directory.Entry, 0, len(entrySet)) for _, entry := range entrySet { result = append(result, entry) } return result, nil } func (ss *simpleService) doGetEntries() (map[id.Zid]*directory.Entry, error) { dirEntries, err := os.ReadDir(ss.dirPath) if err != nil { return nil, err } entrySet := make(map[id.Zid]*directory.Entry) for _, dirEntry := range dirEntries { if dirEntry.IsDir() { continue } if info, err1 := dirEntry.Info(); err1 != nil || !info.Mode().IsRegular() { continue } name := dirEntry.Name() match := matchValidFileName(name) if len(match) == 0 { continue } zid, err2 := id.Parse(match[1]) if err2 != nil { continue } var entry *directory.Entry if e, ok := entrySet[zid]; ok { entry = e } else { entry = &directory.Entry{Zid: zid} entrySet[zid] = entry } updateEntry(entry, filepath.Join(ss.dirPath, name), match[3]) } return entrySet, nil } var validFileName = regexp.MustCompile(`^(\d{14}).*(\.(.+))$`) func matchValidFileName(name string) []string { return validFileName.FindStringSubmatch(name) } func updateEntry(entry *directory.Entry, path, ext string) { if ext == "meta" { entry.MetaSpec = directory.MetaSpecFile entry.MetaPath = path } else if entry.ContentExt != "" && entry.ContentExt != ext { entry.Duplicates = true } else { if entry.MetaSpec != directory.MetaSpecFile { if ext == "zettel" { entry.MetaSpec = directory.MetaSpecHeader } else { entry.MetaSpec = directory.MetaSpecNone } } entry.ContentPath = path entry.ContentExt = ext } } func (ss *simpleService) GetEntry(zid id.Zid) (*directory.Entry, error) { ss.mx.Lock() defer ss.mx.Unlock() return ss.doGetEntry(zid) } func (ss *simpleService) doGetEntry(zid id.Zid) (*directory.Entry, error) { pattern := filepath.Join(ss.dirPath, zid.String()) + "*.*" paths, err := filepath.Glob(pattern) if err != nil { return nil, err } if len(paths) == 0 { return nil, nil } entry := &directory.Entry{Zid: zid} for _, path := range paths { ext := filepath.Ext(path) if len(ext) > 0 && ext[0] == '.' { ext = ext[1:] } updateEntry(entry, path, ext) } return entry, nil } func (ss *simpleService) GetNew() (*directory.Entry, error) { ss.mx.Lock() defer ss.mx.Unlock() zid, err := box.GetNewZid(func(zid id.Zid) (bool, error) { entry, err := ss.doGetEntry(zid) if err != nil { return false, nil } return !entry.IsValid(), nil }) if err != nil { return nil, err } return &directory.Entry{Zid: zid}, nil } func (*simpleService) UpdateEntry(*directory.Entry) error { // Nothing to to, since the actual file update is done by dirbox. return nil } func (*simpleService) RenameEntry(_, _ *directory.Entry) error { // Nothing to to, since the actual file rename is done by dirbox. return nil } func (*simpleService) DeleteEntry(id.Zid) error { // Nothing to to, since the actual file delete is done by dirbox. return nil } |
Changes to box/filebox/filebox.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
18 19 20 21 22 23 24 | "strings" "zettelstore.de/c/api" "zettelstore.de/z/box" "zettelstore.de/z/box/manager" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" | < < < < | 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | "strings" "zettelstore.de/c/api" "zettelstore.de/z/box" "zettelstore.de/z/box/manager" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" ) 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{ number: cdata.Number, name: path, enricher: cdata.Enricher, }, nil }) } func getFilepathFromURL(u *url.URL) string { name := u.Opaque if name == "" { |
︙ | ︙ | |||
73 74 75 76 77 78 79 | m := meta.New(zid) m.Set(api.KeyTitle, zid.String()) m.Set(api.KeySyntax, calculateSyntax(ext)) return m } // CleanupMeta enhances the given metadata. | | | | | 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | m := meta.New(zid) m.Set(api.KeyTitle, zid.String()) m.Set(api.KeySyntax, calculateSyntax(ext)) return m } // CleanupMeta enhances the given metadata. func CleanupMeta(m *meta.Meta, zid id.Zid, ext string, inMeta, duplicates bool) { if title, ok := m.Get(api.KeyTitle); !ok || title == "" { m.Set(api.KeyTitle, zid.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 duplicates { m.Set(api.KeyDuplicates, api.ValueTrue) } } |
Changes to box/filebox/zipbox.go.
1 | //----------------------------------------------------------------------------- | | > > < > | > | > > > | > > > > > | > < < < > | | | | > > > > > > > > > > > > | < | | > > > > | | | < > > | > > > | > > > > > | > | | > > > | | | < < < | < > > | < < | | | | | | | < | | > > > > | < < < < < < < < | | | < < | < < < | < | | | | | < < | < < | | | | < < | < < < | | | < < < | < | | | | > | < < < < | < < < | > | < < < < | | | < | | | | < < < < | > | | | < < < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | //----------------------------------------------------------------------------- // 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 filebox provides boxes that are stored in a file. package filebox import ( "archive/zip" "context" "io" "regexp" "strings" "zettelstore.de/z/box" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" "zettelstore.de/z/input" ) var validFileName = regexp.MustCompile(`^(\d{14}).*(\.(.+))$`) func matchValidFileName(name string) []string { return validFileName.FindStringSubmatch(name) } type zipEntry struct { metaName string contentName string contentExt string // (normalized) file extension of zettel content metaInHeader bool } type zipBox struct { number int name string enricher box.Enricher zettel map[id.Zid]*zipEntry // no lock needed, because read-only after creation } func (zp *zipBox) Location() string { if strings.HasPrefix(zp.name, "/") { return "file://" + zp.name } return "file:" + zp.name } func (zp *zipBox) Start(context.Context) error { reader, err := zip.OpenReader(zp.name) if err != nil { return err } defer reader.Close() zp.zettel = make(map[id.Zid]*zipEntry) for _, f := range reader.File { match := matchValidFileName(f.Name) if len(match) < 1 { continue } zid, err2 := id.Parse(match[1]) if err2 != nil { continue } zp.addFile(zid, f.Name, match[3]) } return nil } func (zp *zipBox) addFile(zid id.Zid, name, ext string) { entry := zp.zettel[zid] if entry == nil { entry = &zipEntry{} zp.zettel[zid] = entry } switch ext { case "zettel": if entry.contentExt == "" { entry.contentName = name entry.contentExt = ext entry.metaInHeader = true } case "meta": entry.metaName = name entry.metaInHeader = false default: if entry.contentExt == "" { entry.contentExt = ext entry.contentName = name } } } func (zp *zipBox) Stop(context.Context) error { zp.zettel = nil return nil } func (*zipBox) CanCreateZettel(context.Context) bool { return false } func (*zipBox) CreateZettel(context.Context, domain.Zettel) (id.Zid, error) { return id.Invalid, box.ErrReadOnly } func (zp *zipBox) GetZettel(_ context.Context, zid id.Zid) (domain.Zettel, error) { entry, ok := zp.zettel[zid] if !ok { return domain.Zettel{}, box.ErrNotFound } reader, err := zip.OpenReader(zp.name) if err != nil { return domain.Zettel{}, err } defer reader.Close() var m *meta.Meta var src []byte var inMeta bool if entry.metaInHeader { src, err = readZipFileContent(reader, entry.contentName) if err != nil { return domain.Zettel{}, err } inp := input.NewInput(src) m = meta.NewFromInput(zid, inp) src = src[inp.Pos:] } else if metaName := entry.metaName; metaName != "" { m, err = readZipMetaFile(reader, zid, metaName) if err != nil { return domain.Zettel{}, err } src, err = readZipFileContent(reader, entry.contentName) if err != nil { return domain.Zettel{}, err } inMeta = true } else { m = CalcDefaultMeta(zid, entry.contentExt) } CleanupMeta(m, zid, entry.contentExt, inMeta, false) return domain.Zettel{Meta: m, Content: domain.NewContent(src)}, nil } func (zp *zipBox) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) { entry, ok := zp.zettel[zid] if !ok { return nil, box.ErrNotFound } reader, err := zip.OpenReader(zp.name) if err != nil { return nil, err } defer reader.Close() return readZipMeta(reader, zid, entry) } func (zp *zipBox) ApplyZid(_ context.Context, handle box.ZidFunc) error { for zid := range zp.zettel { handle(zid) } return nil } func (zp *zipBox) ApplyMeta(ctx context.Context, handle box.MetaFunc) error { reader, err := zip.OpenReader(zp.name) if err != nil { return err } defer reader.Close() for zid, entry := range zp.zettel { m, err2 := readZipMeta(reader, zid, entry) if err2 != nil { continue } zp.enricher.Enrich(ctx, m, zp.number) handle(m) } return nil } func (*zipBox) CanUpdateZettel(context.Context, domain.Zettel) bool { return false } func (*zipBox) UpdateZettel(context.Context, domain.Zettel) error { return box.ErrReadOnly } func (zp *zipBox) AllowRenameZettel(_ context.Context, zid id.Zid) bool { _, ok := zp.zettel[zid] return !ok } func (zp *zipBox) RenameZettel(_ context.Context, curZid, _ id.Zid) error { if _, ok := zp.zettel[curZid]; ok { return box.ErrReadOnly } return box.ErrNotFound } func (*zipBox) CanDeleteZettel(context.Context, id.Zid) bool { return false } func (zp *zipBox) DeleteZettel(_ context.Context, zid id.Zid) error { if _, ok := zp.zettel[zid]; ok { return box.ErrReadOnly } return box.ErrNotFound } func (zp *zipBox) ReadStats(st *box.ManagedBoxStats) { st.ReadOnly = true st.Zettel = len(zp.zettel) } func readZipMeta(reader *zip.ReadCloser, zid id.Zid, entry *zipEntry) (m *meta.Meta, err error) { var inMeta bool if entry.metaInHeader { m, err = readZipMetaFile(reader, zid, entry.contentName) } else if metaName := entry.metaName; metaName != "" { m, err = readZipMetaFile(reader, zid, entry.metaName) inMeta = true } else { m = CalcDefaultMeta(zid, entry.contentExt) } if err == nil { CleanupMeta(m, zid, entry.contentExt, inMeta, false) } return m, err } func readZipMetaFile(reader *zip.ReadCloser, zid id.Zid, name string) (*meta.Meta, error) { src, err := readZipFileContent(reader, name) if err != nil { |
︙ | ︙ |
Changes to box/helper.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides a generic interface to zettel boxes. package box import ( "time" "zettelstore.de/z/domain/id" ) |
︙ | ︙ |
Changes to box/manager/anteroom.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 coordinates the various boxes and indexes of a Zettelstore. package manager import ( "sync" "zettelstore.de/z/domain/id" ) |
︙ | ︙ |
Changes to box/manager/anteroom_test.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 coordinates the various boxes and indexes of a Zettelstore. package manager import ( "testing" "zettelstore.de/z/domain/id" ) |
︙ | ︙ |
Changes to box/manager/box.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 coordinates the various boxes and indexes of a Zettelstore. package manager import ( "bytes" "context" "errors" |
︙ | ︙ | |||
44 45 46 47 48 49 50 | 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) { | < < < < < < < < < < | < < < < < | | < < < < < | < | | 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | 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.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.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.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.mgrMx.RLock() defer mgr.mgrMx.RUnlock() if !mgr.started { return nil, box.ErrStopped } 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.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.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] = true }) if err != nil { return nil, err } } return result, nil } // 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) { mgr.mgrMx.RLock() defer mgr.mgrMx.RUnlock() if !mgr.started { return nil, box.ErrStopped } selected, rejected := map[id.Zid]*meta.Meta{}, id.Set{} match := s.CompileMatch(mgr) handleMeta := func(m *meta.Meta) { zid := m.Zid if rejected[zid] { return } if _, ok := selected[zid]; ok { return } if match(m) { selected[zid] = m } else { rejected[zid] = true } } for _, p := range mgr.boxes { if err := p.ApplyMeta(ctx, handleMeta); 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.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.PairsRest(true) { if mgr.propertyKeys[p.Key] { zettel.Meta.Delete(p.Key) } } return mgr.boxes[0].UpdateZettel(ctx, zettel) } |
︙ | ︙ | |||
237 238 239 240 241 242 243 | } } return true } // RenameZettel changes the current zid to a new zid. func (mgr *Manager) RenameZettel(ctx context.Context, curZid, newZid id.Zid) error { | < | 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | } } return true } // RenameZettel changes the current zid to a new zid. func (mgr *Manager) RenameZettel(ctx context.Context, curZid, newZid id.Zid) error { 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) |
︙ | ︙ | |||
272 273 274 275 276 277 278 | } } return false } // DeleteZettel removes the zettel from the box. func (mgr *Manager) DeleteZettel(ctx context.Context, zid id.Zid) error { | < | 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | } } return false } // DeleteZettel removes the zettel from the box. func (mgr *Manager) DeleteZettel(ctx context.Context, zid id.Zid) error { mgr.mgrMx.RLock() defer mgr.mgrMx.RUnlock() if !mgr.started { return box.ErrStopped } for _, p := range mgr.boxes { err := p.DeleteZettel(ctx, zid) |
︙ | ︙ |
Changes to box/manager/collect.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ( "strings" "zettelstore.de/z/ast" "zettelstore.de/z/box/manager/store" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 coordinates the various boxes and indexes of a Zettelstore. package manager import ( "strings" "zettelstore.de/z/ast" "zettelstore.de/z/box/manager/store" |
︙ | ︙ |
Changes to box/manager/enrich.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 coordinates the various boxes and indexes of a Zettelstore. package manager import ( "context" "strconv" "zettelstore.de/c/api" |
︙ | ︙ |
Changes to box/manager/indexer.go.
1 | //----------------------------------------------------------------------------- | | > < | < < < < < | < < < < < | < < < < < | < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | //----------------------------------------------------------------------------- // 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 coordinates the various boxes and indexes of a Zettelstore. package manager import ( "context" "net/url" "time" "zettelstore.de/c/api" "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 { return mgr.idxStore.SearchEqual(word) } // 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 { return mgr.idxStore.SearchPrefix(prefix) } // 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 { return mgr.idxStore.SearchSuffix(suffix) } // 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 { return mgr.idxStore.SearchContains(s) } // 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() { |
︙ | ︙ | |||
97 98 99 100 101 102 103 | var roomNum uint64 var start time.Time for { switch action, zid, arRoomNum := mgr.idxAr.Dequeue(); action { case arNothing: return case arReload: | < < < < | 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 | var roomNum uint64 var start time.Time for { switch action, zid, arRoomNum := mgr.idxAr.Dequeue(); action { case arNothing: return case arReload: 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: 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: 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.idxAr.Enqueue(zid, arUpdate) } mgr.idxMx.Lock() mgr.idxSinceReload++ mgr.idxMx.Unlock() mgr.idxDeleteZettel(zid) } |
︙ | ︙ | |||
182 183 184 185 186 187 188 | 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) { | | | 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | 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(false) { descr := meta.GetDescription(pair.Key) if descr.IsComputed() { continue } switch descr.Type { case meta.TypeID: mgr.idxUpdateValue(ctx, descr.Inverse, pair.Value, zi) |
︙ | ︙ |
Changes to box/manager/manager.go.
︙ | ︙ | |||
23 24 25 26 27 28 29 | "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" | < | 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | "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" ) // ConnectData contains all administration related values. type ConnectData struct { Number int // number of the box, starting with 1. Config config.Config Enricher box.Enricher |
︙ | ︙ | |||
86 87 88 89 90 91 92 | } sort.Strings(result) return result } // Manager is a coordinating box. type Manager struct { | < < < < < | 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | } sort.Strings(result) return result } // Manager is a coordinating box. type Manager struct { 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 map[string]bool // Set of property key names // Indexer data 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) { propertyKeys := make(map[string]bool) for _, kd := range meta.GetSortedKeyDescriptions() { if kd.IsProperty() { propertyKeys[kd.Name] = true } } mgr := &Manager{ rtConfig: rtConfig, infos: make(chan box.UpdateInfo, len(boxURIs)*10), propertyKeys: propertyKeys, 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 { |
︙ | ︙ | |||
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | 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() } }() | > > > > > > > > > < < < < < < < < < < < < < < < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | 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) notifyObserver(ci *box.UpdateInfo) { mgr.mxObserver.RLock() observers := mgr.observers mgr.mxObserver.RUnlock() for _, ob := range observers { ob(*ci) } } 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() } }() for { select { case ci, ok := <-mgr.infos: if ok { mgr.idxEnqueue(ci.Reason, ci.Zid) if ci.Box == nil { ci.Box = mgr } mgr.notifyObserver(&ci) } case <-mgr.done: return } } } 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: } } // 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 |
︙ | ︙ | |||
283 284 285 286 287 288 289 290 291 292 293 294 295 | 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. | > > | < < < < < < < < < < < < < < < < < | > | | | > | | > > | < | 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | return err } mgr.idxAr.Reset() // Ensure an initial index run mgr.done = make(chan struct{}) go mgr.notifier() go mgr.idxIndexer() // mgr.startIndexer(mgr) mgr.started = true mgr.mgrMx.Unlock() mgr.infos <- box.UpdateInfo{Reason: box.OnReload, Zid: id.Invalid} return nil } // Stop the started box. Now only the Start() function is allowed. func (mgr *Manager) Stop(ctx context.Context) error { mgr.mgrMx.Lock() defer mgr.mgrMx.Unlock() if !mgr.started { return box.ErrStopped } close(mgr.done) var err error for _, p := range mgr.boxes { if ss, ok := p.(box.StartStopper); ok { if err1 := ss.Stop(ctx); err1 != nil && err == nil { err = err1 } } } mgr.started = false return err } // ReadStats populates st with box statistics. func (mgr *Manager) ReadStats(st *box.Stats) { mgr.mgrMx.RLock() defer mgr.mgrMx.RUnlock() subStats := make([]box.ManagedBoxStats, len(mgr.boxes)) for i, p := range mgr.boxes { p.ReadStats(&subStats[i]) } |
︙ | ︙ |
Changes to box/manager/memstore/memstore.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
247 248 249 250 251 252 253 | result.AddSlice(zi.backward) for _, mref := range zi.meta { result.AddSlice(mref.backward) } } func removeOtherMetaRefs(m *meta.Meta, back id.Slice) id.Slice { | | | 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | 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(false) { 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) { |
︙ | ︙ |
Changes to box/manager/memstore/refs.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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) { | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 stored the index in main memory. 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) { |
︙ | ︙ |
Changes to box/manager/memstore/refs_test.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 stored the index in main memory. package memstore import ( "testing" "zettelstore.de/z/domain/id" ) |
︙ | ︙ |
Changes to box/manager/store/wordset.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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) } | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 // 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) } |
︙ | ︙ |
Changes to box/manager/store/wordset_test.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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_test import ( "sort" "testing" "zettelstore.de/z/box/manager/store" |
︙ | ︙ |
Changes to box/manager/store/zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 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 | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 "zettelstore.de/z/domain/id" // ZettelIndex contains all index data of a zettel. type ZettelIndex struct { Zid id.Zid // zid of the indexed zettel |
︙ | ︙ |
Changes to box/membox/membox.go.
︙ | ︙ | |||
17 18 19 20 21 22 23 | "sync" "zettelstore.de/z/box" "zettelstore.de/z/box/manager" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" | < < < | < < < < < < | | | | | | | | | | | | > | | | | | | | < | | | | < | | | | < | | | < | < | < | | | < | < | | | < | | | | | < | | | | | | | | | | | < | | | | | | | | | | | < | | | | < | 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | "sync" "zettelstore.de/z/box" "zettelstore.de/z/box/manager" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" ) func init() { manager.Register( "mem", func(u *url.URL, cdata *manager.ConnectData) (box.ManagedBox, error) { return &memBox{u: u, cdata: *cdata}, nil }) } type memBox struct { u *url.URL cdata manager.ConnectData zettel map[id.Zid]domain.Zettel mx sync.RWMutex } func (mp *memBox) notifyChanged(reason box.UpdateReason, zid id.Zid) { if chci := mp.cdata.Notify; chci != nil { chci <- box.UpdateInfo{Reason: reason, Zid: zid} } } func (mp *memBox) Location() string { return mp.u.String() } func (mp *memBox) Start(context.Context) error { mp.mx.Lock() mp.zettel = make(map[id.Zid]domain.Zettel) mp.mx.Unlock() return nil } func (mp *memBox) Stop(context.Context) error { mp.mx.Lock() mp.zettel = nil mp.mx.Unlock() return nil } func (*memBox) CanCreateZettel(context.Context) bool { return true } func (mp *memBox) CreateZettel(_ context.Context, zettel domain.Zettel) (id.Zid, error) { mp.mx.Lock() zid, err := box.GetNewZid(func(zid id.Zid) (bool, error) { _, ok := mp.zettel[zid] return !ok, nil }) if err != nil { mp.mx.Unlock() return id.Invalid, err } meta := zettel.Meta.Clone() meta.Zid = zid zettel.Meta = meta mp.zettel[zid] = zettel mp.mx.Unlock() mp.notifyChanged(box.OnUpdate, zid) return zid, nil } func (mp *memBox) GetZettel(_ context.Context, zid id.Zid) (domain.Zettel, error) { mp.mx.RLock() zettel, ok := mp.zettel[zid] mp.mx.RUnlock() if !ok { return domain.Zettel{}, box.ErrNotFound } zettel.Meta = zettel.Meta.Clone() return zettel, nil } func (mp *memBox) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) { mp.mx.RLock() zettel, ok := mp.zettel[zid] mp.mx.RUnlock() if !ok { return nil, box.ErrNotFound } return zettel.Meta.Clone(), nil } func (mp *memBox) ApplyZid(_ context.Context, handle box.ZidFunc) error { mp.mx.RLock() defer mp.mx.RUnlock() for zid := range mp.zettel { handle(zid) } return nil } func (mp *memBox) ApplyMeta(ctx context.Context, handle box.MetaFunc) error { mp.mx.RLock() defer mp.mx.RUnlock() for _, zettel := range mp.zettel { m := zettel.Meta.Clone() mp.cdata.Enricher.Enrich(ctx, m, mp.cdata.Number) handle(m) } return nil } func (*memBox) CanUpdateZettel(context.Context, domain.Zettel) bool { return true } func (mp *memBox) UpdateZettel(_ context.Context, zettel domain.Zettel) error { mp.mx.Lock() meta := zettel.Meta.Clone() if !meta.Zid.IsValid() { return &box.ErrInvalidID{Zid: meta.Zid} } zettel.Meta = meta mp.zettel[meta.Zid] = zettel mp.mx.Unlock() mp.notifyChanged(box.OnUpdate, meta.Zid) return nil } func (*memBox) AllowRenameZettel(context.Context, id.Zid) bool { return true } func (mp *memBox) RenameZettel(_ context.Context, curZid, newZid id.Zid) error { mp.mx.Lock() zettel, ok := mp.zettel[curZid] if !ok { mp.mx.Unlock() return box.ErrNotFound } // Check that there is no zettel with newZid if _, ok = mp.zettel[newZid]; ok { mp.mx.Unlock() return &box.ErrInvalidID{Zid: newZid} } meta := zettel.Meta.Clone() meta.Zid = newZid zettel.Meta = meta mp.zettel[newZid] = zettel delete(mp.zettel, curZid) mp.mx.Unlock() mp.notifyChanged(box.OnDelete, curZid) mp.notifyChanged(box.OnUpdate, newZid) return nil } func (mp *memBox) CanDeleteZettel(_ context.Context, zid id.Zid) bool { mp.mx.RLock() _, ok := mp.zettel[zid] mp.mx.RUnlock() return ok } func (mp *memBox) DeleteZettel(_ context.Context, zid id.Zid) error { mp.mx.Lock() if _, ok := mp.zettel[zid]; !ok { mp.mx.Unlock() return box.ErrNotFound } delete(mp.zettel, zid) mp.mx.Unlock() mp.notifyChanged(box.OnDelete, zid) return nil } func (mp *memBox) ReadStats(st *box.ManagedBoxStats) { st.ReadOnly = false mp.mx.RLock() st.Zettel = len(mp.zettel) mp.mx.RUnlock() } |
Deleted box/notify/directory.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted box/notify/directory_test.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted box/notify/entry.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted box/notify/fsdir.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted box/notify/helper.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted box/notify/notify.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted box/notify/simpledir.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to cmd/cmd_run.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
32 33 34 35 36 37 38 | fs.String("d", "", "zettel directory") fs.Bool("r", false, "system-wide read-only mode") fs.Bool("v", false, "verbose mode") fs.Bool("debug", false, "debug mode") } func runFunc(*flag.FlagSet) (int, error) { | < < < | < > > > > > > > < < < < | < < | < < | < | | | | < < | | | | | | | > | | > | | | | | | | | < < < | | | | | | | | | | 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | fs.String("d", "", "zettel directory") fs.Bool("r", false, "system-wide read-only mode") fs.Bool("v", false, "verbose mode") fs.Bool("debug", false, "debug mode") } func runFunc(*flag.FlagSet) (int, error) { exitCode, err := doRun() kernel.Main.WaitForShutdown() return exitCode, err } func doRun() (int, error) { if err := kernel.Main.StartService(kernel.WebService); err != nil { return 1, err } return 0, nil } func setupRouting(webSrv server.Server, boxManager box.Manager, authManager auth.Manager, rtConfig config.Config) { protectedBoxManager, authPolicy := authManager.BoxWithPolicy(webSrv, boxManager, rtConfig) a := api.New(webSrv, authManager, authManager, webSrv, rtConfig) wui := webui.New(webSrv, authManager, rtConfig, authManager, boxManager, authPolicy) ucAuthenticate := usecase.NewAuthenticate(authManager, authManager, boxManager) ucCreateZettel := usecase.NewCreateZettel(rtConfig, protectedBoxManager) ucGetMeta := usecase.NewGetMeta(protectedBoxManager) ucGetAllMeta := usecase.NewGetAllMeta(protectedBoxManager) ucGetZettel := usecase.NewGetZettel(protectedBoxManager) ucParseZettel := usecase.NewParseZettel(rtConfig, ucGetZettel) ucEvaluate := usecase.NewEvaluate(rtConfig, ucGetZettel, ucGetMeta) ucListMeta := usecase.NewListMeta(protectedBoxManager) ucListRoles := usecase.NewListRole(protectedBoxManager) ucListTags := usecase.NewListTags(protectedBoxManager) ucZettelContext := usecase.NewZettelContext(protectedBoxManager, rtConfig) ucDelete := usecase.NewDeleteZettel(protectedBoxManager) ucUpdate := usecase.NewUpdateZettel(protectedBoxManager) ucRename := usecase.NewRenameZettel(protectedBoxManager) webSrv.Handle("/", wui.MakeGetRootHandler(protectedBoxManager)) // Web user interface if !authManager.IsReadonly() { webSrv.AddZettelRoute('b', server.MethodGet, wui.MakeGetRenameZettelHandler( ucGetMeta, &ucEvaluate)) webSrv.AddZettelRoute('b', server.MethodPost, wui.MakePostRenameZettelHandler(ucRename)) webSrv.AddZettelRoute('c', server.MethodGet, wui.MakeGetCopyZettelHandler( ucGetZettel, usecase.NewCopyZettel())) webSrv.AddZettelRoute('c', server.MethodPost, wui.MakePostCreateZettelHandler(ucCreateZettel)) webSrv.AddZettelRoute('d', server.MethodGet, wui.MakeGetDeleteZettelHandler( ucGetMeta, ucGetAllMeta, &ucEvaluate)) webSrv.AddZettelRoute('d', server.MethodPost, wui.MakePostDeleteZettelHandler(ucDelete)) webSrv.AddZettelRoute('e', server.MethodGet, wui.MakeEditGetZettelHandler(ucGetZettel)) webSrv.AddZettelRoute('e', server.MethodPost, wui.MakeEditSetZettelHandler(ucUpdate)) webSrv.AddZettelRoute('f', server.MethodGet, wui.MakeGetFolgeZettelHandler( ucGetZettel, usecase.NewFolgeZettel(rtConfig))) webSrv.AddZettelRoute('f', server.MethodPost, wui.MakePostCreateZettelHandler(ucCreateZettel)) webSrv.AddZettelRoute('g', server.MethodGet, wui.MakeGetNewZettelHandler( ucGetZettel, usecase.NewNewZettel())) webSrv.AddZettelRoute('g', server.MethodPost, wui.MakePostCreateZettelHandler(ucCreateZettel)) } webSrv.AddListRoute('f', server.MethodGet, wui.MakeSearchHandler( usecase.NewSearch(protectedBoxManager), &ucEvaluate)) webSrv.AddListRoute('h', server.MethodGet, wui.MakeListHTMLMetaHandler( ucListMeta, ucListRoles, ucListTags, &ucEvaluate)) webSrv.AddZettelRoute('h', server.MethodGet, wui.MakeGetHTMLZettelHandler( &ucEvaluate, ucGetMeta)) 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)) webSrv.AddListRoute('i', server.MethodGet, wui.MakeGetLoginOutHandler()) webSrv.AddZettelRoute('k', server.MethodGet, wui.MakeZettelContextHandler( ucZettelContext, &ucEvaluate)) // API webSrv.AddListRoute('a', server.MethodPost, a.MakePostLoginHandler(ucAuthenticate)) webSrv.AddListRoute('a', server.MethodPut, a.MakeRenewAuthHandler()) webSrv.AddListRoute('j', server.MethodGet, api.MakeListMetaHandler(ucListMeta)) webSrv.AddZettelRoute('j', server.MethodGet, api.MakeGetZettelHandler(ucGetZettel)) webSrv.AddZettelRoute('l', server.MethodGet, api.MakeGetLinksHandler(ucEvaluate)) webSrv.AddZettelRoute('m', server.MethodGet, api.MakeGetMetaHandler(ucGetMeta)) webSrv.AddZettelRoute('o', server.MethodGet, api.MakeGetOrderHandler( usecase.NewZettelOrder(protectedBoxManager, ucEvaluate))) webSrv.AddZettelRoute('p', server.MethodGet, a.MakeGetParsedZettelHandler(ucParseZettel)) webSrv.AddListRoute('r', server.MethodGet, api.MakeListRoleHandler(ucListRoles)) webSrv.AddListRoute('t', server.MethodGet, api.MakeListTagsHandler(ucListTags)) webSrv.AddListRoute('v', server.MethodPost, a.MakePostEncodeInlinesHandler(ucEvaluate)) webSrv.AddZettelRoute('v', server.MethodGet, a.MakeGetEvalZettelHandler(ucEvaluate)) webSrv.AddZettelRoute('x', server.MethodGet, api.MakeZettelContextHandler(ucZettelContext)) webSrv.AddListRoute('z', server.MethodGet, a.MakeListPlainHandler(ucListMeta)) webSrv.AddZettelRoute('z', server.MethodGet, a.MakeGetPlainZettelHandler(ucGetZettel)) if !authManager.IsReadonly() { webSrv.AddListRoute('j', server.MethodPost, a.MakePostCreateZettelHandler(ucCreateZettel)) webSrv.AddZettelRoute('j', server.MethodPut, api.MakeUpdateZettelHandler(ucUpdate)) webSrv.AddZettelRoute('j', server.MethodDelete, api.MakeDeleteZettelHandler(ucDelete)) webSrv.AddZettelRoute('j', server.MethodMove, api.MakeRenameZettelHandler(ucRename)) webSrv.AddListRoute('z', server.MethodPost, a.MakePostCreatePlainZettelHandler(ucCreateZettel)) webSrv.AddZettelRoute('z', server.MethodPut, api.MakeUpdatePlainZettelHandler(ucUpdate)) webSrv.AddZettelRoute('z', server.MethodDelete, api.MakeDeleteZettelHandler(ucDelete)) webSrv.AddZettelRoute('z', server.MethodMove, api.MakeRenameZettelHandler(ucRename)) } if authManager.WithAuth() { webSrv.SetUserRetriever(usecase.NewGetUserByZid(boxManager)) } } |
Added cmd/cmd_run_simple.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | //----------------------------------------------------------------------------- // 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 cmd import ( "flag" "fmt" "os" "strings" "zettelstore.de/z/kernel" ) func flgSimpleRun(fs *flag.FlagSet) { fs.String("d", "", "zettel directory") } func runSimpleFunc(*flag.FlagSet) (int, error) { kern := kernel.Main listenAddr := kern.GetConfig(kernel.WebService, kernel.WebListenAddress).(string) exitCode, err := doRun() if idx := strings.LastIndexByte(listenAddr, ':'); idx >= 0 { kern.Log() kern.Log("--------------------------") kern.Log("Open your browser and enter the following URL:") kern.Log() kern.Log(fmt.Sprintf(" http://localhost%v", listenAddr[idx:])) kern.Log() } kern.WaitForShutdown() return exitCode, err } // runSimple is called, when the user just starts the software via a double click // or via a simple call ``./zettelstore`` on the command line. func runSimple() int { dir := "./zettel" if err := os.MkdirAll(dir, 0750); err != nil { fmt.Fprintf(os.Stderr, "Unable to create zettel directory %q (%s)\n", dir, err) os.Exit(1) } return executeCommand("run-simple", "-d", dir) } |
Changes to cmd/command.go.
︙ | ︙ | |||
9 10 11 12 13 14 15 | //----------------------------------------------------------------------------- package cmd import ( "flag" "sort" | < < < | | 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | //----------------------------------------------------------------------------- package cmd import ( "flag" "sort" ) // Command stores information about commands / sub-commands. type Command struct { Name string // command name as it appears on the command line Func CommandFunc // function that executes a command Boxes bool // if true then boxes will be set up Header bool // Print a heading on startup LineServer bool // Start admin line server Flags func(*flag.FlagSet) // function to set up flag.FlagSet flags *flag.FlagSet // flags that belong to the command } // CommandFunc is the function that executes the command. // It accepts the parsed command line parameters. // It returns the exit code and an error. type CommandFunc func(*flag.FlagSet) (int, error) |
︙ | ︙ | |||
44 45 46 47 48 49 50 | if cmd.Name == "" || cmd.Func == nil { panic("Required command values missing") } if _, ok := commands[cmd.Name]; ok { panic("Command already registered: " + cmd.Name) } cmd.flags = flag.NewFlagSet(cmd.Name, flag.ExitOnError) | < < | | | 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | if cmd.Name == "" || cmd.Func == nil { panic("Required command values missing") } if _, ok := commands[cmd.Name]; ok { panic("Command already registered: " + cmd.Name) } cmd.flags = flag.NewFlagSet(cmd.Name, flag.ExitOnError) if cmd.Flags != nil { cmd.Flags(cmd.flags) } commands[cmd.Name] = cmd } // Get returns the command identified by the given name and a bool to signal success. func Get(name string) (Command, bool) { cmd, ok := commands[name] |
︙ | ︙ |
Changes to cmd/fd_limit_raise.go.
︙ | ︙ | |||
10 11 12 13 14 15 16 | //go:build darwin // +build darwin package cmd import ( | | < < | 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | //go:build darwin // +build darwin package cmd import ( "log" "syscall" ) const minFiles = 1048576 func raiseFdLimit() error { var rLimit syscall.Rlimit err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) |
︙ | ︙ | |||
40 41 42 43 44 45 46 | return err } err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) if err != nil { return err } if rLimit.Cur < minFiles { | | < | 38 39 40 41 42 43 44 45 46 47 48 | return err } err = syscall.Getrlimit(syscall.RLIMIT_NOFILE, &rLimit) if err != nil { return err } if rLimit.Cur < minFiles { log.Printf("Make sure you have no more than %d files in all your boxes if you enabled notification\n", rLimit.Cur) } return nil } |
Changes to cmd/main.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
27 28 29 30 31 32 33 | "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" | < | 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | "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/web/server" ) const ( defConfigfile = ".zscfg" ) |
︙ | ︙ | |||
57 58 59 60 61 62 63 | }) RegisterCommand(Command{ Name: "run", Func: runFunc, Boxes: true, Header: true, LineServer: true, | | | < < | < < < | | 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | }) RegisterCommand(Command{ Name: "run", Func: runFunc, Boxes: true, Header: true, LineServer: true, Flags: flgRun, }) RegisterCommand(Command{ Name: "run-simple", Func: runSimpleFunc, Boxes: true, Header: true, Flags: flgSimpleRun, }) RegisterCommand(Command{ Name: "file", Func: cmdFile, Flags: func(fs *flag.FlagSet) { fs.String("t", api.EncoderHTML.String(), "target output encoding") }, }) RegisterCommand(Command{ Name: "password", Func: cmdPassword, }) |
︙ | ︙ | |||
119 120 121 122 123 124 125 | if strings.HasPrefix(val, "/") { val = "dir://" + val } else { val = "dir:" + val } deleteConfiguredBoxes(cfg) cfg.Set(keyBoxOneURI, val) | < < | 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | if strings.HasPrefix(val, "/") { val = "dir://" + val } else { val = "dir:" + val } deleteConfiguredBoxes(cfg) cfg.Set(keyBoxOneURI, val) case "debug": cfg.Set(keyDebug, flg.Value.String()) case "r": cfg.Set(keyReadOnly, flg.Value.String()) case "v": cfg.Set(keyVerbose, flg.Value.String()) } |
︙ | ︙ | |||
142 143 144 145 146 147 148 | fmt.Fprintf(os.Stderr, "Wrong port specification: %q", s) return "", err } return strconv.Itoa(port), nil } func deleteConfiguredBoxes(cfg *meta.Meta) { | | < < < < < < < < < < | | 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | fmt.Fprintf(os.Stderr, "Wrong port specification: %q", s) return "", err } return strconv.Itoa(port), nil } func deleteConfiguredBoxes(cfg *meta.Meta) { for _, p := range cfg.PairsRest(false) { if key := p.Key; strings.HasPrefix(key, kernel.BoxURIs) { cfg.Delete(key) } } } const ( keyAdminPort = "admin-port" keyDebug = "debug-mode" keyDefaultDirBoxType = "default-dir-box-type" keyInsecureCookie = "insecure-cookie" keyListenAddr = "listen-addr" keyOwner = "owner" keyPersistentCookie = "persistent-cookie" keyBoxOneURI = kernel.BoxURIs + "1" keyReadOnly = "read-only-mode" keyTokenLifetimeHTML = "token-lifetime-html" keyTokenLifetimeAPI = "token-lifetime-api" keyURLPrefix = "url-prefix" keyVerbose = "verbose-mode" ) func setServiceConfig(cfg *meta.Meta) error { ok := setConfigValue(true, kernel.CoreService, kernel.CoreDebug, cfg.GetBool(keyDebug)) ok = setConfigValue(ok, 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)) |
︙ | ︙ | |||
219 220 221 222 223 224 225 | } 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 { | | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > < < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | | < < < < < < < < < < < < < < | | < | < > | < > | < < < | < > < | 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 | } 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.Log("unable to set configuration:", key, val) } return ok && done } func setupOperations(cfg *meta.Meta, withBoxes bool) { var createManager kernel.CreateBoxManagerFunc if withBoxes { err := raiseFdLimit() if err != nil { srvm := kernel.Main srvm.Log("Raising some limitions did not work:", err) srvm.Log("Prepare to encounter errors. Most of them can be mitigated. See the manual for details") srvm.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 { createManager = func([]*url.URL, auth.Manager, config.Config) (box.Manager, error) { return nil, nil } } kernel.Main.SetCreators( func(readonly bool, owner id.Zid) (auth.Manager, error) { return impl.New(readonly, owner, cfg.GetDefault("secret", "")), nil }, createManager, func(srv server.Server, plMgr box.Manager, authMgr auth.Manager, rtConfig config.Config) error { setupRouting(srv, plMgr, authMgr, rtConfig) return nil }, ) } func executeCommand(name string, args ...string) int { command, ok := Get(name) if !ok { fmt.Fprintf(os.Stderr, "Unknown command %q\n", name) return 1 } 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) return 2 } setupOperations(cfg, command.Boxes) kernel.Main.Start(command.Header, command.LineServer) exitCode, err := command.Func(fs) if err != nil { fmt.Fprintf(os.Stderr, "%s: %v\n", name, err) } kernel.Main.Shutdown(true) return exitCode } // Main is the real entrypoint of the zettelstore. func Main(progName, buildVersion string) { kernel.Main.SetConfig(kernel.CoreService, kernel.CoreProgname, progName) kernel.Main.SetConfig(kernel.CoreService, kernel.CoreVersion, buildVersion) var exitCode int if len(os.Args) <= 1 { exitCode = runSimple() } else { exitCode = executeCommand(os.Args[1], os.Args[2:]...) } if exitCode != 0 { os.Exit(exitCode) } } |
Changes to cmd/zettelstore/main.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 | //----------------------------------------------------------------------------- // 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 main is the starting point for the zettelstore command. package main | < < < | < | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //----------------------------------------------------------------------------- // 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 main is the starting point for the zettelstore command. package main import "zettelstore.de/z/cmd" // Version variable. Will be filled by build process. var version string = "" func main() { cmd.Main("Zettelstore", version) } |
Changes to config/config.go.
︙ | ︙ | |||
60 61 62 63 64 65 66 | // 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 { | < < < | | 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | // 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 { // 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 } // GetTitle returns the value of the "title" key of the given meta. If there |
︙ | ︙ |
Changes to docs/development/20210916193200.zettel.
1 2 3 4 | id: 20210916193200 title: Required Software role: zettel syntax: zmk | | > | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | id: 20210916193200 title: Required Software role: zettel syntax: zmk modified: 20211111143928 The following software must be installed: * A current, supported [[release of Go|https://golang.org/doc/devel/release.html]], * [[golint|https://github.com/golang/lint]], * [[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 get honnef.co/go/tools/cmd/staticcheck``, * [[unparam|https://mvdan.cc/unparam]][^[[GitHub|https://github.com/mvdan/unparam]]] via ``go install mvdan.cc/unparam@latest`` 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 |
︙ | ︙ |
Changes to docs/development/20210916194900.zettel.
1 2 3 4 | id: 20210916194900 title: Checklist for Release role: zettel syntax: zmk | | < < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | id: 20210916194900 title: Checklist for Release role: zettel syntax: zmk modified: 20211110193448 # Clean up your Go workspace: #* ``go run tools/build.go clean`` (alternatively: ``make clean``). # All internal tests must succeed: #* ``go run tools/build.go relcheck`` (alternatively: ``make relcheck``). # The API tests must succeed on every development platform: #* ``go run tools/build.go testapi`` (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''. #* 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``. # Create a development release: |
︙ | ︙ |
Changes to docs/manual/00000000000100.zettel.
1 2 3 4 | id: 00000000000100 title: Zettelstore Runtime Configuration role: configuration syntax: none | | | 1 2 3 4 5 6 7 8 9 10 11 12 | id: 00000000000100 title: Zettelstore Runtime Configuration role: configuration syntax: none default-copyright: (c) 2020-2021 by Detlef Stern <ds@zettelstore.de> default-license: EUPL-1.2-or-later default-visibility: public footer-html: <hr><p><a href="/home/doc/trunk/www/impri.wiki">Imprint / Privacy</a></p> home-zettel: 00001000000000 no-index: true site-name: Zettelstore Manual visibility: owner |
︙ | ︙ |
Changes to docs/manual/00001002000000.zettel.
1 2 | id: 00001002000000 title: Design goals for the Zettelstore | < | | 1 2 3 4 5 6 7 8 9 10 11 12 | id: 00001002000000 title: Design goals for the Zettelstore tags: #design #goal #manual #zettelstore syntax: zmk role: manual 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. ; Single user |
︙ | ︙ | |||
21 22 23 24 25 26 27 | ; 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. ; Multiple user interfaces | | | 20 21 22 23 24 25 26 27 28 29 30 31 | ; 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. ; Multiple user interfaces : Zettelstore provides a default web-based user interface. Anybody 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. |
Changes to docs/manual/00001003000000.zettel.
1 2 3 4 5 | id: 00001003000000 title: Installation of the Zettelstore software role: manual tags: #installation #manual #zettelstore syntax: zmk | < | | < > | > > > > > > > > > > > > > > > > > > > > > | > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | id: 00001003000000 title: Installation of the Zettelstore software role: manual tags: #installation #manual #zettelstore syntax: zmk === 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 * 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. There will be a zettel titled ""[[Home|00010000000000]]"" that contains some helpful information. * Please read the instructions for the web-based user interface 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. * Grab the appropriate executable and copy it into the appropriate directory * ... === The server administrator 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: ```sh # sudo mv zettelstore /usr/local/bin/zettelstore ``` Create a group named ''zettelstore'': ```sh # sudo groupadd --system zettelstore ``` Create a system user of that group, named ''zettelstore'', with a home folder: ```sh # sudo useradd --system --gid zettelstore \ --create-home --home-dir /var/lib/zettelstore \ --shell /usr/sbin/nologin \ --comment "Zettelstore server" \ zettelstore ``` Create a systemd service file and store it into ''/etc/systemd/system/zettelstore.service'': ```ini [Unit] Description=Zettelstore After=network.target [Service] Type=simple User=zettelstore Group=zettelstore ExecStart=/usr/local/bin/zettelstore run -d /var/lib/zettelstore WorkingDirectory=/var/lib/zettelstore [Install] WantedBy=multi-user.target ``` Double-check everything. Now you can enable and start the zettelstore as a service: ```sh # sudo systemctl daemon-reload # sudo systemctl enable zettelstore # sudo systemctl start zettelstore ``` 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 ``` |
Deleted docs/manual/00001003300000.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted docs/manual/00001003305000.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted docs/manual/00001003305102.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305104.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305106.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305108.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305110.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305112.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305114.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305116.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305118.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305120.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305122.png.
cannot compute difference between binary files
Deleted docs/manual/00001003305124.png.
cannot compute difference between binary files
Deleted docs/manual/00001003310000.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted docs/manual/00001003310104.png.
cannot compute difference between binary files
Deleted docs/manual/00001003310106.png.
cannot compute difference between binary files
Deleted docs/manual/00001003310108.png.
cannot compute difference between binary files
Deleted docs/manual/00001003310110.png.
cannot compute difference between binary files
Deleted docs/manual/00001003315000.zettel.
|
| < < < < < < < < < < < < < < < < < |
Deleted docs/manual/00001003600000.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to docs/manual/00001004010000.zettel.
1 2 3 4 5 | id: 00001004010000 title: Zettelstore startup configuration role: manual tags: #configuration #manual #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001004010000 title: Zettelstore startup configuration role: manual tags: #configuration #manual #zettelstore syntax: zmk modified: 20211109172143 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. 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. |
︙ | ︙ | |||
30 31 32 33 34 35 36 | This allows to configure more 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). Disables any timeout values of the internal web server and does not send some security-related data. | < | < < < < < < < | | | 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | This allows to configure more 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). Disables any timeout values of the internal web server and does not send some security-related data. 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. Default: ''notify'' ; [!insecure-cookie]''insecure-cookie'' : Must be set to ''true'', 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. Default: ''false'' ; [!listen-addr]''listen-addr'' : Configures the network address, where is zettel web service is listening for requests. Syntax is: ''[NETWORKIP]:PORT'', where ''NETWORKIP'' is the IP-address of the networking interface (or something like ''0.0.0.0'' if you want to listen on all network interfaces, and ''PORT'' is the TCP port. Default value: ''"127.0.0.1:23123"'' ; [!owner]''owner'' : [[Identifier|00001006050000]] of a zettel that contains data about the owner of the Zettelstore. The owner has full authorization for the Zettelstore. Only if owner is set to some value, user [[authentication|00001010000000]] is enabled. ; [!persistent-cookie]''persistent-cookie'' : A boolean value to make the access cookie persistent. This is helpful if you access the Zettelstore via a mobile device. On these devices, the operating system is free to stop the web browser and to remove temporary cookies. Therefore, an authenticated user will be logged off. If ''true'', a persistent cookie is used. Its lifetime exceeds the lifetime of the authentication token (see option ''token-lifetime-html'') by 30 seconds. Default: ''false'' ; [!read-only-mode]''read-only-mode'' : Puts the Zettelstore web service into a read-only mode. No changes are possible. Default: false. ; [!token-lifetime-api]''token-lifetime-api'', [!token-lifetime-html]''token-lifetime-html'' : Define lifetime of access tokens in minutes. Values are only valid if authentication is enabled, i.e. key ''owner'' is set. ''token-lifetime-api'' is for accessing Zettelstore via its API. Default: 10. ''token-lifetime-html'' specifies the lifetime for the HTML views. Default: 60. It is automatically extended, when a new HTML view is rendered. ; [!url-prefix]''url-prefix'' : Add the given string as a prefix to the local part of a Zettelstore local URL/URI when rendering zettel representations. |
︙ | ︙ |
Changes to docs/manual/00001004011400.zettel.
1 2 3 4 5 | id: 00001004011400 title: Configure file directory boxes role: manual tags: #configuration #manual #zettelstore syntax: zmk | | > | | | > > > > > > > > > > > > > > > > > > > > > > > > | < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | id: 00001004011400 title: Configure file directory boxes role: manual tags: #configuration #manual #zettelstore syntax: zmk modified: 20210525121232 Under certain circumstances, it is preferable to further configure a file directory box. This is done by appending query parameters after the base box URI ''dir:\//DIR''. The following parameters are supported: |= Parameter:|Description|Default value:| |type|(Sub-) Type of the directory service|(value of ''[[default-dir-box-type|00001004010000#default-dir-box-type]]'') |rescan|Time (in seconds) after which the directory should be scanned fully|600 |worker|Number of worker that can access the directory in parallel|(depends on type) |readonly|Allow only operations that do not change a zettel or create a new zettel|n/a === Type On some operating systems, Zettelstore tries to detect changes to zettel files outside of Zettelstore's control[^This includes Linux, Windows, and macOS.]. On other operating systems, this may be not possible, due to technical limitations. Automatic detection of external changes is also not possible, if zettel files are put on an external service, such as a file server accessed via SMD/CIFS or NFS. To cope with this uncertainty, Zettelstore provides various internal implementations of a directory box. The default values should match the needs of different users, as explained in the [[installation part|00001003000000]] of this manual. The following values are supported: ; simple : Is not able to detect external changes. Works on all platforms. Is a little slower than other implementations (up to three times slower). ; notify : Automatically detect external changes. Tries to optimize performance, at a little cost of main memory (RAM). === Rescan When the parameter ''type'' is set to ""notify"", Zettelstore automatically detects changes to zettel files that originates from other software. It is done on a ""best-effort"" basis. Under certain circumstances it is possible that Zettelstore does not detect a change done by another software. To cope with this unlikely, but still possible event, Zettelstore re-scans periodically the file directory. The time interval is configured by the ''rescan'' parameter, e.g. ``` box-uri-1: dir:///home/zettel?rescan=300 ``` This makes Zettelstore to re-scan the directory ''/home/zettel/'' every 300 seconds, i.e. 5 minutes. For a Zettelstore with many zettel, re-scanning the directory may take a while, especially if it is stored on a remote computer (e.g. via CIFS/SMB or NFS). In this case, you should adjust the parameter value. Please note that a directory re-scan invalidates all internal data of a Zettelstore. It might trigger a re-build of the backlink database (and other internal databases). Therefore a large value is preferred. This value is ignored for other directory box types, such as ""simple"". === Worker Internally, Zettelstore parallels concurrent requests for a zettel or its metadata. The number of parallel activities is configured by the ''worker'' parameter. A computer contains a limited number of internal processing units (CPU). Its number ranges from 1 to (currently) 128, e.g. in bigger server environments. Zettelstore typically runs on a system with 1 to 8 CPUs. Access to zettel file is ultimately managed by the underlying operating system. Depending on the hardware and on the type of the directory box, only a limited number of parallel accesses are desirable. On smaller hardware[^In comparison to a normal desktop or laptop computer], such as the [[Raspberry Zero|https://www.raspberrypi.org/products/raspberry-pi-zero/]], a smaller value might be appropriate. Every worker needs some amount of main memory (RAM) and some amount of processing power. On bigger hardware, with some fast file services, a bigger value could result in higher performance, if needed. For a directory box of type ""notify"", the default value is: 7. The directory box type ""simple"" limits the value to a maximum of 1, i.e. no concurrency is possible with this type of directory box. For various reasons, the value should be a prime number, with a maximum value of 1499. === Readonly Sometimes you may want to provide zettel from a file directory box, but you want to disallow any changes. If you provide the query parameter ''readonly'' (with or without a corresponding value), the box will disallow any changes. ``` box-uri-1: dir:///home/zettel?readonly ``` If you put the whole Zettelstore in [[read-only|00001004010000]] [[mode|00001004051000]], all configured file directory boxes will be in read-only mode too, even if not explicitly configured. |
Changes to docs/manual/00001004020000.zettel.
1 2 3 4 5 | id: 00001004020000 title: Configure the running Zettelstore role: manual tags: #configuration #manual #zettelstore syntax: zmk | | | | | > | | | | | | | | | | | | > > | > | > | | > | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | id: 00001004020000 title: Configure the running Zettelstore role: manual tags: #configuration #manual #zettelstore syntax: zmk modified: 20210810103936 You can configure a running Zettelstore by modifying the special zettel with the ID [[00000000000100]]. This zettel is called ""configuration zettel"". The following metadata keys change the appearance / behavior of Zettelstore: ; [!default-copyright]''default-copyright'' : Copyright value to be used when rendering content. Can be overwritten in a zettel with [[meta key|00001006020000]] ''copyright''. Default: (the empty string). ; [!default-lang]''default-lang'' : Default language to be used when displaying content. Can be overwritten in a zettel with [[meta key|00001006020000]] ''lang''. Default: ''en''. This value is also used to specify the language for all non-zettel content, e.g. lists or search results. Use values according to the language definition of [[RFC-5646|https://tools.ietf.org/html/rfc5646]]. ; [!default-license]''default-license'' : License value to be used when rendering content. Can be overwritten in a zettel with [[meta key|00001006020000]] ''license''. Default: (the empty string). ; [!default-role]''default-role'' : Role to be used, if a zettel specifies no ''role'' [[meta key|00001006020000]]. Default: ''zettel''. ; [!default-syntax]''default-syntax'' : Syntax to be used, if a zettel specifies no ''syntax'' [[meta key|00001006020000]]. Default: ''zmk'' (""Zettelmarkup""). ; [!default-title]''default-title'' : Title to be used, if a zettel specifies no ''title'' [[meta key|00001006020000]]. Default: ''Untitled''. You can use all [[inline-structured elements|00001007040000]] of Zettelmarkup. ; [!default-visibility]''default-visibility'' : Visibility to be used, if zettel does not specify a value for the [[''visibility''|00001006020000#visibility]] metadata key. Default: ''login''. ; [!expert-mode]''expert-mode'' : If set to a boolean true value, all zettel with [[visibility ""expert""|00001010070200]] will be shown (to the owner, if authentication is enabled; to all, otherwise). This affects most computed zettel. Default: False. ; [!footer-html]''footer-html'' : Contains some HTML code that will be included into the footer of each Zettelstore web page. It only affects the [[web user interface|00001014000000]]. Zettel content, delivered via the [[API|00001012000000]] as JSON, etc. is not affected. Default: (the empty string). ; [!home-zettel]''home-zettel'' : Specifies the identifier of the zettel, that should be presented for the default view / home view. If not given or if the identifier does not identify a zettel, the zettel with the identifier ''00010000000000'' is shown. ; [!marker-external]''marker-external'' : Some HTML code that is displayed after a reference to external material. Default: ''&\#10138;'', to display a ""➚"" sign. ; [!max-transclusions]''max-transclusions'' : Maximum number of indirect transclusion. This is used to avoid an exploding ""transclusion bomb"", a form of a [[billion laughs attack|https://en.wikipedia.org/wiki/Billion_laughs_attack]]. Default: 1024. ; [!site-name]''site-name'' : Name of the Zettelstore instance. Will be used when displaying some lists. Default: ''Zettelstore''. ; [!yaml-header]''yaml-header'' : If true, metadata and content will be separated by ''-\--\\n'' instead of an empty line (''\\n\\n''). Default: ''false''. You will probably use this key, if you are working with another software processing [[Markdown|https://daringfireball.net/projects/markdown/]] that uses a subset of [[YAML|https://yaml.org/]] to specify metadata. ; [!zettel-file-syntax]''zettel-file-syntax'' : If you create a new zettel with a syntax different to ""meta"" and ""zmk"", Zettelstore will store the zettel as two files: one for the metadata (file extension ''.meta'') and one for the content (file extension based on the syntax value). If you want to specify alternative syntax values, for which you want new zettel to be stored in one file (file extension ''.zettel''), you can use this key. All values are case-insensitive, duplicates are removed. For example, you could use this key if you're working with Markdown syntax and you want to store metadata and content in one ''.zettel'' file. If ''yaml-header'' evaluates to true, a zettel is always stored in one ''.zettel'' file. |
Changes to docs/manual/00001004050000.zettel.
1 2 3 4 5 | id: 00001004050000 title: Command line parameters role: manual tags: #command #configuration #manual #zettelstore syntax: zmk | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | id: 00001004050000 title: Command line parameters role: manual tags: #command #configuration #manual #zettelstore syntax: zmk modified: 20210511140731 Zettelstore is not just a web service that provides services of a zettelkasten. It allows to some tasks to be executed at the command line. Typically, the task (""sub-command"") will be given at the command line as the first parameter. If no parameter is given, the Zettelstore is called as ``` zettelstore ``` This is equivalent to call it this way: ```sh mkdir -p ./zettel zettelstore run -d ./zettel -c ./.zscfg ``` Typically this is done by starting Zettelstore via a graphical user interface by double-clicking to its file icon. === Sub-commands * [[``zettelstore help``|00001004050200]] lists all available sub-commands. * [[``zettelstore version``|00001004050400]] to display version information of Zettelstore. * [[``zettelstore run``|00001004051000]] to start the web-based Zettelstore service. * [[``zettelstore run-simple``|00001004051100]] is typically called, when you start Zettelstore by a double.click in your GUI. * [[``zettelstore file``|00001004051200]] to render files manually without activated/running Zettelstore services. * [[``zettelstore password``|00001004051400]] to calculate data for user authentication. |
Changes to docs/manual/00001004050400.zettel.
1 2 3 4 5 | id: 00001004050400 title: The ''version'' sub-command role: manual tags: #command #configuration #manual #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001004050400 title: The ''version'' sub-command role: manual tags: #command #configuration #manual #zettelstore syntax: zmk modified: 20210712234031 Emits some information about the Zettelstore's version. This allows you to check, whether your installed Zettelstore is The name of the software (""Zettelstore"") and the build version information is given, as well as the compiler version, and an indication about the operating system and the processor architecture of that computer. The build version information is a string like ''1.0.2+351ae138b4''. |
︙ | ︙ | |||
21 22 23 24 25 26 27 | ``` # zettelstore version Zettelstore 1.0.2+351ae138b4 (go1.16.5@linux/amd64) Licensed under the latest version of the EUPL (European Union Public License) ``` In this example, Zettelstore is running in the released version ""1.0.2"" and was compiled using [[Go, version 1.16.5|https://golang.org/doc/go1.16]]. The software was build for running under a Linux operating system with an ""amd64"" processor. | < < < | 21 22 23 24 25 26 27 | ``` # zettelstore version Zettelstore 1.0.2+351ae138b4 (go1.16.5@linux/amd64) Licensed under the latest version of the EUPL (European Union Public License) ``` In this example, Zettelstore is running in the released version ""1.0.2"" and was compiled using [[Go, version 1.16.5|https://golang.org/doc/go1.16]]. The software was build for running under a Linux operating system with an ""amd64"" processor. |
Changes to docs/manual/00001004051000.zettel.
1 2 3 4 5 | id: 00001004051000 title: The ''run'' sub-command role: manual tags: #command #configuration #manual #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001004051000 title: The ''run'' sub-command role: manual tags: #command #configuration #manual #zettelstore syntax: zmk modified: 20211109172046 === ``zettelstore run`` This starts the web service. ``` zettelstore run [-a PORT] [-c CONFIGFILE] [-d DIR] [-debug] [-p PORT] [-r] [-v] ``` |
︙ | ︙ | |||
35 36 37 38 39 40 41 | Default: 23123. Zettelstore listens only on ''127.0.0.1'', e.g. only requests from the current computer will be processed. If you want to listen on network card to process requests from other computer, please use [[''listen-addr''|00001004010000#listen-addr]] of the configuration file as described below. ; [!r]''-r'' : Puts the Zettelstore in read-only mode. | | | 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | Default: 23123. Zettelstore listens only on ''127.0.0.1'', e.g. only requests from the current computer will be processed. If you want to listen on network card to process requests from other computer, please use [[''listen-addr''|00001004010000#listen-addr]] of the configuration file as described below. ; [!r]''-r'' : Puts the Zettelstore in read-only mode. No changes are possible via the web interface / via the API. This allows to publish your content without any risks of unauthorized changes. ; [!v]''-v'' : Be more verbose when writing logs. Command line options take precedence over [[configuration file|00001004010000]] options. |
Deleted docs/manual/00001004059700.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted docs/manual/00001004059900.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to docs/manual/00001004101000.zettel.
1 2 3 4 5 | id: 00001004101000 title: List of supported commands of the administrator console role: manual tags: #configuration #manual #zettelstore syntax: zmk | | | < < | < < < < < < < < < < < < < < < < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | id: 00001004101000 title: List of supported commands of the administrator console role: manual tags: #configuration #manual #zettelstore syntax: zmk modified: 20211103161956 ; ''bye'' : Closes the connection to the administrator console. ; ''config SERVICE'' : Displays all valid configuration keys for the given service. If a key ends with the hyphen-minus character (""''-''"", ''U+002D''), the key denotes a list value. Keys of list elements are specified by appending a number greater than zero to the key. ; ''crlf'' : Toggles CRLF mode for console output. Changes end of line sequences between Windows mode (==\\r\\n==) and non-Windows mode (==\\n==, initial value). Often used on Windows telnet clients that otherwise scramble the output of commands. ; ''dump-index'' : Displays the content of the internal search index. ; ''dump-recover RECOVER'' : Displays data about the last given recovered internal activity. The value for ''RECOVER'' can be obtained via the command ``stat core``, which lists all overview data about all recoveries. ; ''echo'' : Toggles the echo mode, where each command is printed before execution ; ''env'' : Display environment values. ; ''help'' : Displays a list of all available commands. ; ''get-config'' : Displays current configuration data. ``get-config`` shows all current configuration data. ``get-config SERVICE`` shows only the current configuration data of the given service. ``get-config SERVICE KEY`` shows the current configuration data for the given service and key. ; ''header'' : Toggles the header mode, where each table is show with a header nor not. ; ''metrics'' : Displays some values that reflect the inner workings of Zettelstore. See [[here|https://golang.org/pkg/runtime/metrics/]] for a technical description of these values. ; ''next-config'' : Displays next configuration data. It will be the current configuration, if the corresponding services is restarted. ``next-config`` shows all next configuration data. ``next-config SERVICE`` shows only the next configuration data of the given service. ``next-config SERVICE KEY`` shows the next configuration data for the given service and key. ; ''restart SERVICE'' : Restart the given service and all other that depend on this. ; ''services'' : Displays s list of all available services and their current status. ; ''set-config SERVICE KEY VALUE'' : Sets a single configuration value for the next configuration of a given service. It will become effective if the service is restarted. |
︙ | ︙ |
Changes to docs/manual/00001005000000.zettel.
1 2 3 4 5 | id: 00001005000000 title: Structure of Zettelstore role: manual tags: #design #manual #zettelstore syntax: zmk | | | | | | > | < < < | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | id: 00001005000000 title: Structure of Zettelstore role: manual tags: #design #manual #zettelstore syntax: zmk modified: 20211103163918 Zettelstore is a software that manages your zettel. Since every zettel must be readable without any special tool, most zettel has to be stored as ordinary files within specific directories. Typically, file names and file content must comply to specific rules so that Zettelstore can manage them. If you add, delete, or change zettel files with other tools, e.g. a text editor, Zettelstore will monitor these actions. Zettelstore provides additional services to the user. Via a builtin web interface you can work with zettel in various ways. For example, you are able to list zettel, to create new zettel, to edit them, or to delete them. You can view zettel details and relations between zettel. In addition, Zettelstore provides an ""application programming interface"" (API) that allows other software to communicate with the Zettelstore. Zettelstore becomes extensible by external software. For example, a more sophisticated web interface could be build, or an application for your mobile device that allows you to send content to your Zettelstore as new zettel. === Where zettel are stored Your zettel are stored typically as files in a specific directory. If you have not explicitly specified the directory, a default directory will be used. The directory has to be specified at [[startup time|00001004010000]]. Nested directories are not supported (yet). Every file in this directory that should be monitored by Zettelstore must have a file name that begins with 14 digits (0-9), the [[zettel identifier|00001006050000]]. If you create a new zettel via the web interface or the API, the zettel identifier will be the timestamp of the current date and time (format is ''YYYYMMDDhhmmss''). This allows zettel to be sorted naturally by creation time. Since the only restriction on zettel identifiers are the 14 digits, you are free to use other digit sequences. The [[configuration zettel|00001004020000]] is one prominent example, as well as these manual zettel. You can create these special zettel identifiers either with the __rename__ function of Zettelstore or by manually renaming the underlying zettel files. It is allowed that the file name contains other characters after the 14 digits. These are ignored by Zettelstore. The file name must have an file extension. Two file extensions are used by Zettelstore: ''.meta'' and ''.zettel''. Other file extensions are used to determine the ""syntax"" of a zettel. This allows to use other content within the Zettelstore, e.g. images or HTML templates. For example, you want to store an important figure in the Zettelstore that is encoded as a ''.png'' file. Since each zettel contains some metadata, e.g. the title of the figure, the question arises where these data should be stores. The solution is a ''.meta'' file with the same zettel identifier. Zettelstore recognizes this situation and reads in both files for the one zettel containing the figure. It maintains this relationship as long as theses files exists. In case of some textual zettel content you do not want to store the metadata and the zettel content in two different files. Here the ''.zettel'' extension will signal that the metadata and the zettel content will be put in the same file, separated by an empty line or a line with three dashes (""''-\-\-''"", also known as ""YAML separator""). === Predefined zettel Zettelstore contains some [[predefined zettel|00001005090000]] to work properly. The [[configuration zettel|00001004020000]] is one example. To render the builtin web interface, some templates are used, as well as a layout specification in CSS. The icon that visualizes a broken image is a predefined GIF image. All of these are visible to the Zettelstore as zettel. One reason for this is to allow you to modify these zettel to adapt Zettelstore to your needs and visual preferences. Where are these zettel stored? They are stored within the Zettelstore software itself, because one design goal was to have just one executable file to use Zettelstore. But data stored within an executable programm cannot be changed later[^Well, it can, but it is a very bad idea to allow this. Mostly for security reasons.]. To allow changing predefined zettel, both the file store and the internal zettel store are internally chained together. If you change a zettel, it will be always stored as a file. If a zettel is requested, Zettelstore will first try to read that zettel from a file. If such a file was not found, the internal zettel store is searched secondly. Therefore, the file store ""shadows"" the internal zettel store. If you want to read the original zettel, you either have to delete the zettel (which removes it from the file directory), or you have to rename it to another zettel identifier. Now we have two places where zettel are stored: in the specific directory and within the Zettelstore software. * [[List of predefined zettel|00001005090000]] === Boxes: other ways to store zettel As described above, a zettel may be stored as a file inside a directory or inside the Zettelstore software itself. Zettelstore allows other ways to store zettel by providing an abstraction called __box__.[^Formerly, zettel were stored physically in boxes, often made of wood.] A file directory which stores zettel is called a ""directory box"". But zettel may be also stored in a ZIP file, which is called ""file box"". For testing purposes, zettel may be stored in volatile memory (called __RAM__). This way is called ""memory box"". |
︙ | ︙ |
Changes to docs/manual/00001005090000.zettel.
1 2 3 4 5 | id: 00001005090000 title: List of predefined zettel role: manual tags: #manual #reference #zettelstore syntax: zmk | | < < | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | id: 00001005090000 title: List of predefined zettel role: manual tags: #manual #reference #zettelstore syntax: zmk modified: 20210622124647 The following table lists all predefined zettel with their purpose. |= Identifier :|= Title | Purpose | [[00000000000001]] | Zettelstore Version | Contains the version string of the running Zettelstore | [[00000000000002]] | Zettelstore Host | Contains the name of the computer running the Zettelstore | [[00000000000003]] | Zettelstore Operating System | Contains the operating system and CPU architecture of the computer running the Zettelstore | [[00000000000004]] | Zettelstore License | Lists the license of Zettelstore | [[00000000000005]] | Zettelstore Contributors | Lists all contributors of Zettelstore | [[00000000000006]] | Zettelstore Dependencies | Lists all licensed content | [[00000000000020]] | Zettelstore Box Manager | Contains some statistics about zettel boxes and the the index process | [[00000000000090]] | Zettelstore Supported Metadata Keys | Contains all supported metadata keys, their [[types|00001006030000]], and more | [[00000000000096]] | Zettelstore Startup Configuration | Contains the effective values of the [[startup configuration|00001004010000]] | [[00000000000100]] | Zettelstore Runtime Configuration | Allows to [[configure Zettelstore at runtime|00001004020000]] | [[00000000010100]] | Zettelstore Base HTML Template | Contains the general layout of the HTML view | [[00000000010200]] | Zettelstore Login Form HTML Template | Layout of the login form, when authentication is [[enabled|00001010040100]] | [[00000000010300]] | Zettelstore List Meta HTML Template | Used when displaying a list of zettel | [[00000000010401]] | Zettelstore Detail HTML Template | Layout for the HTML detail view of one zettel | [[00000000010402]] | Zettelstore Info HTML Templöate | Layout for the information view of a specific zettel | [[00000000010403]] | Zettelstore Form HTML Template | Form that is used to create a new or to change an existing zettel that contains text | [[00000000010404]] | Zettelstore Rename Form HTML Template | View that is displayed to change the [[zettel identifier|00001006050000]] | [[00000000010405]] | Zettelstore Delete HTML Template | View to confirm the deletion of a zettel | [[00000000010500]] | Zettelstore List Roles HTML Template | Layout for listing all roles | [[00000000010600]] | Zettelstore List Tags HTML Template | Layout of tags lists | [[00000000020001]] | Zettelstore Base CSS | System-defined CSS file that is included by the [[Base HTML Template|00000000010100]] | [[00000000025001]] | Zettelstore User CSS | User-defined CSS file that is included by the [[Base HTML Template|00000000010100]] | [[00000000040001]] | Generic Emoji | Image that is shown if original image reference is invalid | [[00000000090000]] | New Menu | Contains items that should contain in the zettel template menu | [[00000000090001]] | New Zettel | Template for a new zettel with role ""[[zettel|00001006020100]]"" | [[00000000090002]] | New User | Template for a new zettel with role ""[[user|00001006020100#user]]"" | [[00010000000000]] | Home | Default home zettel, contains some welcome information If a zettel is not linked, it is not accessible for the current user. **Important:** All identifier may change until a stable version of the software is released. |
Changes to docs/manual/00001006000000.zettel.
1 2 3 4 5 | id: 00001006000000 title: Layout of a Zettel role: manual tags: #design #manual #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | id: 00001006000000 title: Layout of a Zettel role: manual tags: #design #manual #zettelstore syntax: zmk modified: 20210903210655 A zettel consists of two parts: the metadata and the zettel content. Metadata gives some information mostly about the zettel content, how it should be interpreted, how it is sorted within Zettelstore. The zettel content is, well, the actual content. In many cases, the content is in plain text form. Plain text is long-lasting. However, content in binary format is also possible. Metadata has to conform to a [[special syntax|00001006010000]]. It is effectively a collection of key/value pairs. Some keys have a [[special meaning|00001006020000]] and most of the predefined keys need values of a specific [[type|00001006030000]]. Each zettel is given a unique [[identifier|00001006050000]]. To some degree, the zettel identifier is part of the metadata.. The zettel content is your valuable content. Zettelstore contains some predefined parsers that interpret the zettel content to the syntax of the zettel. This includes markup languages, like [[Zettelmarkup|00001007000000]] and [[CommonMark|https://commonmark.org/]]. Other text formats are also supported, like CSS and HTML templates. Plain text content is always Unicode, encoded as UTF-8. Other character encodings are not supported and will never be[^This is not a real problem, since every modern software should support UTF-8 as an encoding.]. There is support for a graphical format with a text represenation: SVG. And there is support for some binary image formats, like GIF, PNG, and JPEG. |
Changes to docs/manual/00001006020000.zettel.
1 2 3 4 5 | id: 00001006020000 title: Supported Metadata Keys role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001006020000 title: Supported Metadata Keys role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk modified: 20211103163613 Although you are free to define your own metadata, by using any key (according to the [[syntax|00001006010000]]), some keys have a special meaning that is enforced by Zettelstore. See the [[computed list of supported metadata keys|00000000000090]] for details. Most keys conform to a [[type|00001006030000]]. ; [!all-tags]''all-tags'' |
︙ | ︙ | |||
27 28 29 30 31 32 33 34 35 36 37 38 39 40 | ; [!credential]''credential'' : Contains the hashed password, as it was emitted by [[``zettelstore password``|00001004051400]]. It is internally created by hashing the password, the [[zettel identifier|00001006050000]], and the value of the ''ident'' key. It is only used for zettel with a ''role'' value of ""user"". ; [!dead]''dead'' : Property that contains all references that does __not__ identify a zettel. ; [!folge]''folge'' : Is a property that contains identifier of all zettel that reference this zettel through the [[''precursor''|#precursor]] value. ; [!forward]''forward'' : Property that contains all references that identify another zettel within the content of the zettel. ; [!id]''id'' : Contains the [[zettel identifier|00001006050000]], as given by the Zettelstore. It cannot be set manually, because it is a computed value. | > > > | 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | ; [!credential]''credential'' : Contains the hashed password, as it was emitted by [[``zettelstore password``|00001004051400]]. It is internally created by hashing the password, the [[zettel identifier|00001006050000]], and the value of the ''ident'' key. It is only used for zettel with a ''role'' value of ""user"". ; [!dead]''dead'' : Property that contains all references that does __not__ identify a zettel. ; [!duplicates]''duplicates'' : Is set to the value ""true"" if there is more than one file that could contain the content of a zettel. Is used for [[directory boxes|00001004011400]] and [[file boxes|00001004011200#file]]. ; [!folge]''folge'' : Is a property that contains identifier of all zettel that reference this zettel through the [[''precursor''|#precursor]] value. ; [!forward]''forward'' : Property that contains all references that identify another zettel within the content of the zettel. ; [!id]''id'' : Contains the [[zettel identifier|00001006050000]], as given by the Zettelstore. It cannot be set manually, because it is a computed value. |
︙ | ︙ | |||
86 87 88 89 90 91 92 | : Specifies the title of the zettel. If not given, the value ''default-title'' from the [[configuration zettel|00001004020000#default-title]] will be used. You can use all [[inline-structured elements|00001007040000]] of Zettelmarkup. ; [!url]''url'' : Defines an URL / URI for this zettel that possibly references external material. One use case is to specify the document that the current zettel comments on. | | < < < < | | 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | : Specifies the title of the zettel. If not given, the value ''default-title'' from the [[configuration zettel|00001004020000#default-title]] will be used. You can use all [[inline-structured elements|00001007040000]] of Zettelmarkup. ; [!url]''url'' : Defines an URL / URI for this zettel that possibly references external material. One use case is to specify the document that the current zettel comments on. The URL will be rendered special on the web user interface if you use the default template. ; [!user-id]''user-id'' : Provides some unique user identification for a user zettel. It is used as a user name for authentication. It is only used for zettel with a ''role'' value of ""user"". ; [!user-role]''user-role'' : Defines the basic privileges of an authenticated user, e.g. reading / changing zettel. Is only valid in a user zettel. See [[User roles|00001010070300]] for more details. ; [!visibility]''visibility'' : When you work with authentication, you can give every zettel a value to decide, who can see the zettel. Its default value can be set with [[''default-visibility''|00001004020000#default-visibility]] of the configuration zettel. See [[visibility rules for zettel|00001010070200]] for more details. |
Changes to docs/manual/00001006020100.zettel.
1 2 3 4 5 | id: 00001006020100 title: Supported Zettel Roles role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk | | > > > > > | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | id: 00001006020100 title: Supported Zettel Roles role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk modified: 20210727120817 The [[''role'' key|00001006020000#role]] defines what kind of zettel you are writing. The following values are used internally by Zettelstore and must exist: ; [!user]''user'' : If you want to use [[authentication|00001010000000]], all zettel that identify users of the zettel store must have this role. Beside of this, you are free to define your own roles. The role ''zettel'' is predefined as the default role, but you can [[change this|00001004020000#default-role]]. Some roles are defined for technical reasons: ; [!configuration]''configuration'' : A zettel that contains some configuration data for the Zettelstore. Most prominent is [[00000000000100]], as described in [[00001004020000]]. ; [!manual]''manual'' : All zettel that document the inner workings of the Zettelstore software. This role is used in this specific Zettelstore. If you adhere to the process outlined by Niklas Luhmann, a zettel could have one of the following three roles: ; [!note]''note'' : A small note, to remember something. Notes are not real zettel, they just help to create a real zettel. Think of them as Post-it notes. |
︙ | ︙ |
Changes to docs/manual/00001006020400.zettel.
1 2 3 4 5 | id: 00001006020400 title: Supported values for metadata key ''read-only'' role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk | < | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | id: 00001006020400 title: Supported values for metadata key ''read-only'' role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk A zettel can be marked as read-only, if it contains a metadata value for key [[''read-only''|00001006020000#read-only]]. If user authentication is [[enabled|00001010040100]], it is possible to allow some users to change the zettel, depending on their [[user role|00001010070300]]. Otherwise, the read-only mark is just a binary value. === No authentication If there is no metadata value for key ''read-only'' or if its [[boolean value|00001006030500]] is interpreted as ""false"", anybody can modify the zettel. If the metadata value is something else (the value ""true"" is recommended), the user cannot modify the zettel through the web interface. However, if the zettel is stored as a file in a [[directory box|00001004011400]], the zettel could be modified using an external editor. === Authentication enabled If there is no metadata value for key ''read-only'' or if its [[boolean value|00001006030500]] is interpreted as ""false"", anybody can modify the zettel. If the metadata value is the same as an explicit [[user role|00001010070300]], users with that role (or a role with lower rights) are not allowed to modify the zettel. ; ""reader"" : Neither an unauthenticated user nor a user with role ""reader"" is allowed to modify the zettel. Users with role ""writer"" or the owner itself still can modify the zettel. ; ""writer"" : Neither an unauthenticated user, nor users with roles ""reader"" or ""writer"" are allowed to modify the zettel. Only the owner of the Zettelstore can modify the zettel. If the metadata value is something else (one of the values ""true"" or ""owner"" is recommended), no user is allowed modify the zettel through the web interface. However, if the zettel is accessible as a file in a [[directory box|00001004011400]], the zettel could be modified using an external editor. Typically the owner of a Zettelstore have such an access. |
Changes to docs/manual/00001006030000.zettel.
1 2 3 4 5 | id: 00001006030000 title: Supported Key Types role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk | | < < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | id: 00001006030000 title: Supported Key Types role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk modified: 20210830132855 All [[supported metadata keys|00001006020000]] conform to a type. User-defined metadata keys conform also to a type, based on the suffix of the key. |=Suffix|Type | ''-number'' | [[Number|00001006033000]] | ''-role'' | [[Word|00001006035500]] | ''-url'' | [[URL|00001006035000]] | ''-zid'' | [[Identifier|00001006032000]] | any other suffix | [[EString|00001006031500]] The name of the metadata key is bound to the key type Every key type has an associated validation rule to check values of the given type. There is also a rule how values are matched, e.g. against a search term when selecting some zettel. And there is a rule, how values compare for sorting. * [[Boolean|00001006030500]] * [[Credential|00001006031000]] * [[EString|00001006031500]] * [[Identifier|00001006032000]] * [[IdentifierSet|00001006032500]] * [[Number|00001006033000]] |
︙ | ︙ |
Changes to docs/manual/00001006032500.zettel.
1 2 3 4 5 | id: 00001006032500 title: IdentifierSet Key Type role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk | < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | id: 00001006032500 title: IdentifierSet Key Type role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk Values of this type denote a (sorted) set of [[zettel identifier|00001006050000]]. A set is different to a list, as no duplicates are allowed. === Allowed values Must be at least one sequence of 14 digits (""0""--""9""), separated by space characters. === Match operator A value matches an identifier set value, if the first value is a prefix of one of the identifier value. |
︙ | ︙ |
Changes to docs/manual/00001006034000.zettel.
1 2 3 4 5 | id: 00001006034000 title: TagSet Key Type role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | id: 00001006034000 title: TagSet Key Type role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk modified: 20210817201410 Values of this type denote a (sorted) set of tags. A set is different to a list, as no duplicates are allowed. === Allowed values Every tag must must begin with the number sign character (""''#''"", ''U+0023''), followed by at least one printable character. Tags are separated by space characters. All characters are mapped to their lower case values. |
︙ | ︙ |
Changes to docs/manual/00001006036000.zettel.
1 2 3 4 5 | id: 00001006036000 title: WordSet Key Type role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk | < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | id: 00001006036000 title: WordSet Key Type role: manual tags: #manual #meta #reference #zettel #zettelstore syntax: zmk Values of this type denote a (sorted) set of [[words|00001006035500]]. A set is different to a list, as no duplicates are allowed. === Allowed values Must be a sequence of at least one word, separated by space characters. === Match operator A value matches an wordset value, if the first value is equal to one of the word values in the word set. |
︙ | ︙ |
Changes to docs/manual/00001006055000.zettel.
1 2 3 4 5 | id: 00001006055000 title: Reserved zettel identifier role: manual tags: #design #manual #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001006055000 title: Reserved zettel identifier role: manual tags: #design #manual #zettelstore syntax: zmk modified: 20211001125243 [[Zettel identifier|00001006050000]] are typically created by examine the current date and time. By renaming a zettel, you are able to provide any sequence of 14 digits. If no other zettel has the same identifier, you are allowed to rename a zettel. To make things easier, you normally should not use zettel identifier that begin with four zeroes (''0000''). |
︙ | ︙ | |||
28 29 30 31 32 33 34 | If you need more than 10.000, your justification will contain more words. === Reserved Zettel Identifier |= From | To | Description | 00000000000000 | 0000000000000 | This is an invalid zettel identifier | 00000000000001 | 0000009999999 | [[Predefined zettel|00001005090000]] | | | 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | If you need more than 10.000, your justification will contain more words. === Reserved Zettel Identifier |= From | To | Description | 00000000000000 | 0000000000000 | This is an invalid zettel identifier | 00000000000001 | 0000009999999 | [[Predefined zettel|00001005090000]] | 00000100000000 | 0000019999999 | Zettelstore manual | 00000200000000 | 0000899999999 | Reserved for future use | 00009000000000 | 0000999999999 | Reserved for applications This list may change in the future. ==== External Applications |= From | To | Description | 00009000001000 | 00009000001999 | [[Zettel Presenter|https://zettelstore.de/contrib]], an application to display zettel as a HTML-based slideshow |
Changes to docs/manual/00001007000000.zettel.
1 2 3 4 5 | id: 00001007000000 title: Zettelmarkup role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | id: 00001007000000 title: Zettelmarkup role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20211103162744 Zettelmarkup is a rich plain-text based markup language for writing zettel content. Besides the zettel content, Zettelmarkup is also used for specifying the title of a zettel, regardless of the syntax of a zettel. Zettelmark supports the longevity of stored notes by providing a syntax that any person can easily read, as well as a computer. Zettelmark can be much easier parsed / consumed by a software compared to other markup languages. Writing a parser for [[Markdown|https://daringfireball.net/projects/markdown/syntax]] is quite challenging. [[CommonMark|https://commonmark.org/]] is an attempt to make it simpler by providing a comprehensive specification, combined with an extra chapter to give hints for the implementation. Zettelmark follows some simple principles that anybody who knows to ho write software should be able understand to create an implementation. Zettelmarkup is a markup language on its own. This is in contrast to Markdown, which is basically a superset of HTML. While HTML is a markup language that will probably last for a long time, it cannot be easily translated to other formats, such as PDF, JSON, or LaTeX. Additionally, it is allowed to embed other languages into HTML, such as CSS or even JavaScript. This could create problems with longevity as well as security problems. Zettelmarkup is a rich markup language, but it focusses on relatively short zettel content. It allows embedding other content, simple tables, quotations, description lists, and images. It provides a broad range of inline formatting, including __emphasized__, **strong**, ;;small;;, ~~deleted~~{-} and >>inserted>> text. Footnotes[^like this] are supported, links to other zettel and to external material, as well as citation keys. Zettelmarkup might be seen as a proprietary markup language. But if you want to use Markdown/CommonMark and you need support for footnotes, you'll end up with a proprietary extension. However, the Zettelstore supports CommonMark as a zettel syntax, so you can mix both Zettelmarkup zettel and CommonMark zettel in one store to get the best of both worlds. * [[General principles|00001007010000]] * [[Basic definitions|00001007020000]] * [[Block-structured elements|00001007030000]] * [[Inline-structured element|00001007040000]] * [[Attributes|00001007050000]] |
︙ | ︙ |
Changes to docs/manual/00001007010000.zettel.
1 2 | id: 00001007010000 title: Zettelmarkup: General Principles | < | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | id: 00001007010000 title: Zettelmarkup: General Principles tags: #manual #zettelmarkup #zettelstore syntax: zmk role: manual Any document can be thought as a sequence of paragraphs and other blocks-structural elements (""blocks""), such as headings, lists, quotations, and code blocks. Some of these blocks can contain other blocks, for example lists may contain other lists or paragraphs. Other blocks contain inline-structural elements (""inlines""), such as text, links, emphasized text, and images. With the exception of lists and tables, the markup for blocks always begins at the first position of a line with three or more identical characters. List blocks also begins at the first position of a line, but may need one or more character, plus a space character. Table blocks begins at the first position of a line with the character ""``|``"". Non-list blocks are either fully specified on that line or they span multiple lines and are delimited with the same three or more character. It depends on the block kind, whether blocks are specified on one line or on at least two lines. If a line does not begin with an explicit block element. the line is treated as a (implicit) paragraph block element that contains inline elements. This paragraph ends when a block element is detected at the beginning of a next line or when an empty line occurs. Some blocks may also contain inline elements, e.g. a heading. Inline elements mostly begins with two non-space, often identical characters. With some exceptions, two identical non-space characters begins a formatting range that is ended with the same two characters. Exceptions are: links, images, edits, comments, and both the ""en-dash"" and the ""horizontal ellipsis"". A link is given with ``[[...]]``{=zmk}, an images with ``{{...}}``{=zmk}, and an edit formatting with ``((...))``{=zmk}. An inline comment, beginning with the sequence ``%%``{=zmk}, always ends at the end of the line where it begins. The ""en-dash"" (""--"") is specified as ``--``{=zmk}, the ""horizontal ellipsis"" (""..."") as ``...``{=zmk}[^If put at the end of non-space text.]. Some inline elements do not follow the rule of two identical character, especially to specify footnotes, citation keys, and local marks. These elements begin with one opening square bracket (""``[``""), use a character for specifying the kind of the inline, typically allow to specify some content, and end with one closing square bracket (""``]``""). One inline element that does not begin with two characters is the ""entity"". It allows to specify any Unicode character. The specification of that character is put between an ampersand character and a semicolon: ``&...;``{=zmk}. For exmple, an ""n-dash"" could also be specified as ``–``{==zmk}. The backslash character (""``\\``"") possibly gives the next character a special meaning. This allows to resolve some left ambiguities. For example, a list of depth 2 will begin a line with ``** Item 2.2``{=zmk}. An inline element to strongly emphasize some text begin with a space will be specified as ``** Text**``{=zmk}. To force the inline element formatting at the beginning of a line, ``**\\ Text**``{=zmk} should better be specified. Many block and inline elements can be refined by additional attributes. Attributes resemble roughly HTML attributes and are put near the corresponding elements by using the syntax ``{...}``{=zmk}. One example is to make space characters visible inside a inline literal element: ``1 + 2 = 3``{-} was specified by using the default attribute: ``\`\`1 + 2 = 3\`\`{-}``. To summarize: * With some exceptions, blocks-structural elements begins at the for position of a line with three identical characters. * The most important exception to this rule is the specification of lists. |
︙ | ︙ |
Changes to docs/manual/00001007020000.zettel.
1 2 | id: 00001007020000 title: Zettelmarkup: Basic Definitions | < | < | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | id: 00001007020000 title: Zettelmarkup: Basic Definitions tags: #manual #zettelmarkup #zettelstore syntax: zmk role: manual Every zettelmark content consists of a sequence of Unicode codepoints. Unicode codepoints are called in the following as **character**s. Characters are encoded with UTF-8. A **line** is a sequence of characters, except newline (''U+000A'') and carraige return (''U+000D''), followed by a line ending sequence or the end of content. A **line ending** is either a newline not followed by a carriage return, a newline followed by a carriage return, or a carriage return. Different line can be finalized by different line endings. An **empty line** is an empty sequence of characters, followed by a line ending or the end of content. The **space** character is the Unicode codepoint ''U+0020''. |
Changes to docs/manual/00001007030000.zettel.
1 | id: 00001007030000 | | < | | 1 2 3 4 5 6 7 8 9 10 11 12 | id: 00001007030000 title: Zettelmarkup: Blocks-Structured Elements tags: #manual #zettelmarkup #zettelstore syntax: zmk role: manual Every markup for blocks-structured elements (""blocks"") begins at the very first position of a line. There are five kinds of blocks: lists, one-line blocks, line-range blocks, tables, and paragraphs. === Lists |
︙ | ︙ | |||
30 31 32 33 34 35 36 | To be useful, they encompass more lines. They begin with at least three identical characters at the first position of the beginning line. They end at the line, that contains at least the same number of these identical characters, beginning at the first position of that line. This allows line-range blocks to be nested. Additionally, all other blocks elements are allowed in line-range blocks. * [[Verbatim blocks|00001007030500]] do not interpret their content, | | | | | | 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | To be useful, they encompass more lines. They begin with at least three identical characters at the first position of the beginning line. They end at the line, that contains at least the same number of these identical characters, beginning at the first position of that line. This allows line-range blocks to be nested. Additionally, all other blocks elements are allowed in line-range blocks. * [[Verbatim blocks|00001007030500]] do not interpret their content, * [[Quotation blocks|00001007030600]] specify a block-length quotation, * [[Verse blocks|00001007030700]] allow to enter poetry, lyrics and similar text, where line endings are important * [[Region blocks|00001007030800]] just mark a region, e.g. for common formatting * [[Comment blocks|00001007030900]] allow to enter text that will be ignored when rendered === Tables Similar to lists are tables not specified explicitly. A sequence of table rows is considered a [[table|00001007031000]]. A table row itself is a sequence of table cells. |
︙ | ︙ |
Changes to docs/manual/00001007030100.zettel.
1 2 3 4 5 | id: 00001007030100 title: Zettelmarkup: Description Lists role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | id: 00001007030100 title: Zettelmarkup: Description Lists role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20211103163447 A description list is a sequence of terms to be described together with the descriptions of each term. Every term can described in multiple ways. A description term (short: __term__) is specified with one semicolon (""'';''"", ''U+003B'') at the first position, followed by a space character and the described term, specified as a sequence of line elements. If the following lines should also be part of the term, exactly two spaces must be given at the beginning of each following line. The description of a term is given with one colon (""'':''"", ''U+003A'') at the first position, followed by a space character and the description itself, specified as a sequence of inline elements. Similar to terms, following lines can also be part of the actual description, if they begin at each line with exactly two space characters. In contrast to terms, the actual descriptions are merged into a paragraph. This is because, an actual description can contain more than one paragraph. As usual, paragraphs are separated by an empty line. Every following paragraph of an actual description must be indented by two space characters. |
︙ | ︙ |
Changes to docs/manual/00001007030200.zettel.
1 2 3 4 5 | id: 00001007030200 title: Zettelmarkup: Nested Lists role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | id: 00001007030200 title: Zettelmarkup: Nested Lists role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20211103162835 There are thee kinds of lists that can be nested: ordered lists, unordered lists, and quotation lists. Ordered lists are specified with the number sign (""''#''"", ''U+0023''), unordered lists use the asterisk (""''*''"", ''U+002A''), and quotation lists are specified with the greater-than sing (""''>''"", ''U+003E''). Let's call these three characters __list characters__. Any nested list item is specified by a non-empty sequence of list characters, followed by a space character and a sequence of inline elements. In case of a quotation list as the last list character, the space character followed by a sequence of inline elements is optional. The number / count of list characters gives the nesting of the lists. If the following lines should also be part of the list item, exactly the same number of spaces must be given at the beginning of each of the following lines as it is the lists are nested, plus one additional space character. In other words: the inline elements must begin at the same column as it was on the previous line. The resulting sequence on inline elements is merged into a paragraph. Appropriately indented paragraphs can specified after the first one. |
︙ | ︙ | |||
88 89 90 91 92 93 94 | * B * C ::: Please note that two lists cannot be separated by an empty line. Instead you should put a horizonal rule (""thematic break"") between them. | | | 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | * B * C ::: Please note that two lists cannot be separated by an empty line. Instead you should put a horizonal rule (""thematic break"") between them. You could also use a mark element or a hard line break to separate the two lists: ```zmk # One # Two [!sep] # Uno # Due --- |
︙ | ︙ |
Changes to docs/manual/00001007030300.zettel.
1 2 3 4 5 | id: 00001007030300 title: Zettelmarkup: Headings role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | id: 00001007030300 title: Zettelmarkup: Headings role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20211103163105 To specify a (sub-) section of a zettel, you should use the headings syntax: at the beginning of a new line type at least three equal signs (""''=''"", ''U+003D''), plus at least one space and enter the text of the heading as inline elements. ```zmk === Level 1 Heading ==== Level 2 Heading ===== Level 3 Heading ====== Level 4 Heading ======= Level 5 Heading |
︙ | ︙ |
Changes to docs/manual/00001007030400.zettel.
1 | id: 00001007030400 | | < | | 1 2 3 4 5 6 7 8 9 10 11 12 | id: 00001007030400 title: Zettelmarkup: Horizontal Rule tags: #manual #zettelmarkup #zettelstore syntax: zmk role: manual To signal a thematic break, you can specify a horizonal rule. This is done by entering at least three hyphen-minus characters (""''-''"", ''U+002D'') at the first position of a line. You can add some [[attributes|00001007050000]], although the horizontal rule does not support the default attribute. Any other character in this line will be ignored If you do not enter the three hyphen-minus charachter at the very first position of a line, the are interpreted as [[inline elements|00001007040000]], typically as an ""en-dash" followed by a hyphen-minus. |
︙ | ︙ |
Changes to docs/manual/00001007030500.zettel.
1 2 | id: 00001007030500 title: Zettelmarkup: Verbatim Blocks | < | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | id: 00001007030500 title: Zettelmarkup: Verbatim Blocks tags: #manual #zettelmarkup #zettelstore syntax: zmk role: manual Verbatim blocks are used to enter text that should not be interpreted. They begin with at least three grave accent characters (""''`''"", ''U+0060'') at the first position of a line. Alternatively, a modifier letter grave accent (""''ˋ''"", ''U+02CB'') is also allowed[^On some devices, such as an iPhone / iPad, a grave accent character is harder to enter and is often confused with a modifier letter grave accent.]. You can add some [[attributes|00001007050000]] on the beginning line of a verbatim block, following the initiating characters. The verbatim block supports the default attribute: when given, all spaces in the text are rendered in HTML as open box characters (""''␣''"", ''U+2423''). If you want to give only one attribute and this attribute is the generic attribute, you can omit the most of the attribute syntax and just specify the value. It will be interpreted as a (programming) language to support colourizing the text when rendered in HTML. Any other character in this line will be ignored Text following the beginning line will not be interpreted, until a line begins with at least the same number of the same characters given at the beginning line. This allows to enter some grave accent characters in the text that should not be interpreted. For example: |
︙ | ︙ |
Changes to docs/manual/00001007030600.zettel.
1 2 | id: 00001007030600 title: Zettelmarkup: Quotation Blocks | < | | 1 2 3 4 5 6 7 8 9 10 11 12 | id: 00001007030600 title: Zettelmarkup: Quotation Blocks tags: #manual #zettelmarkup #zettelstore syntax: zmk role: manual A simple way to enter a quotation is to use the [[quotation list|00001007030200]]. A quotation list loosely follows the convention of quoting text within emails. However, if you want to attribute the quotation to seomeone, a quotation block is more appropriately. This kind of line-range block begins with at least three less-than characters (""''<''"", ''U+003C'') at the first position of a line. You can add some [[attributes|00001007050000]] on the beginning line of a quotation block, following the initiating characters. |
︙ | ︙ | |||
24 25 26 27 28 29 30 | ```zmk <<<< A quotation with an embedded quotation <<<{style=color:green} Embedded <<< Embedded Author | | | 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | ```zmk <<<< A quotation with an embedded quotation <<<{style=color:green} Embedded <<< Embedded Author <<<< ``` will be rendered in HTML as: :::example <<<< A quotation with an embedded quotation <<<{style=color:green} Embedded <<< Embedded Author <<<< Quotation Author ::: |
Changes to docs/manual/00001007030800.zettel.
1 2 | id: 00001007030800 title: Zettelmarkup: Region Blocks | < | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | id: 00001007030800 title: Zettelmarkup: Region Blocks tags: #manual #zettelmarkup #zettelstore syntax: zmk role: manual Region blocks does not directly have a visual representation. They just group a range of lines. You can use region blocks to enter [[attributes|00001007050000]] that apply only to this range of lines. One example is to enter a multi-line warning that should be visible. This kind of line-range block begins with at least three colon characters (""'':''"", ''U+003A'') at the first position of a line[^Since a [[description text|00001007030100]] only use exactly one colon character at the first position of a line, there is no possible ambiguity between these elements.]. You can add some [[attributes|00001007050000]] on the beginning line of a verse block, following the initiating characters. The region block does not support the default attribute, but it supports the generic attribute. Some generic attributes, like ``=note``, ``=warning`` will be rendered special. Attributes are interpreted on HTML rendering. Any other character in this line will be ignored. Text following the beginning line will be interpreted, until a line begins with at least the same number of the same characters given at the beginning line. This allows to enter a region block within a region block. |
︙ | ︙ |
Changes to docs/manual/00001007031000.zettel.
1 2 3 4 5 | id: 00001007031000 title: Zettelmarkup: Tables role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001007031000 title: Zettelmarkup: Tables role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20211103161859 Tables are used to show some data in a two-dimenensional fashion. In zettelmarkup, table are not specified explicitly, but by entering __table rows__. Therefore, a table can be seen as a sequence of table rows. A table row is nothing as a sequence of __table cells__. The length of a table is the number of table rows, the width of a table is the maximum length of its rows. |
︙ | ︙ | |||
87 88 89 90 91 92 93 | |>R|:C|<L |123456|123456|123456|123456| |123|123|123|123 ::: === Rows to be ignored A line that begins with the sequence ''|%'' (vertical bar character (""''|''"", ''U+007C''), followed by a percent sign character (“%”, U+0025)) will be ignored. | | | | 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | |>R|:C|<L |123456|123456|123456|123456| |123|123|123|123 ::: === Rows to be ignored A line that begins with the sequence ''|%'' (vertical bar character (""''|''"", ''U+007C''), followed by a percent sign character (“%”, U+0025)) will be ignored. This allows to specify a horizontal rule that is not rendered. Such tables are emitted by some commands of the [[administrator console|00001004100000]]. For example, the command ``get-config box`` will emit ``` |=Key | Value | Description |%-----------+--------+--------------------------- | defdirtype | notify | Default directory box type ``` This is rendered in HTML as: :::example |=Key | Value | Description |%-----------+--------+--------------------------- | defdirtype | notify | Default directory box type ::: |
Changes to docs/manual/00001007040000.zettel.
1 2 3 4 5 | id: 00001007040000 title: Zettelmarkup: Inline-Structured Elements role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001007040000 title: Zettelmarkup: Inline-Structured Elements role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20211103162150 Most characters you type is concerned with inline-structured elements. The content of a zettel contains is many cases just ordinary text, lightly formatted. Inline-structured elements allow to format your text and add some helpful links or images. Sometimes, you want to enter characters that have no representation on your keyboard. ; Text formatting |
︙ | ︙ | |||
33 34 35 36 37 38 39 | It ends at the end of the line where it begins. ==== Backslash The backslash character (""''\\''"", ''U+005C'') gives the next character another meaning. * If a space character follows, it is converted in a non-breaking space (''U+00A0''). * If a line ending follows the backslash character, the line break is converted from a __soft break__ into a __hard break__. * Every other character is taken as itself, but without the interpretation of a Zettelmarkup element. | | | 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | It ends at the end of the line where it begins. ==== Backslash The backslash character (""''\\''"", ''U+005C'') gives the next character another meaning. * If a space character follows, it is converted in a non-breaking space (''U+00A0''). * If a line ending follows the backslash character, the line break is converted from a __soft break__ into a __hard break__. * Every other character is taken as itself, but without the interpretation of a Zettelmarkup element. For example, if you want to enter a ""'']''"" into a footnote text, you should escape it with a backslash. ==== Tag Any text that begins with a number sign character (""''#''"", ''U+0023''), followed by a non-empty sequence of Unicode letters, Unicode digits, the hyphen-minus character (""''-''"", ''U+002D''), or the low line character (""''_''"", ''U+005F'') is interpreted as an __inline tag__. They are be considered equivalent to tags in metadata. ==== Entities & more Sometimes it is not easy to enter special characters. |
︙ | ︙ |
Changes to docs/manual/00001007040100.zettel.
1 2 3 4 5 | id: 00001007040100 title: Zettelmarkup: Text Formatting role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | > > > | | > > | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | id: 00001007040100 title: Zettelmarkup: Text Formatting role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20211103161716 Text formatting is the way to make your text visually different. Every text formatting element begins with two same characters. It ends when these two same characters occur the second time. It is possible that some [[attributes|00001007050000]] follow immediately, without any separating character. Text formatting can be nested, up to a reasonable limit. The following characters begin a text formatting: * The low line character (""''_''"", ''U+005F'') emphasizes its text. ** Example: ``abc __def__ ghi`` is rendered in HTML as: ::abc __def__ ghi::{=example}. ** The slash character (""''/''"", ''U+002F'') is still allowed to emphasize text, but its use is deprecated. With version 0.0.17 it will no longer be supported. *** Example: ``abc //def// ghi`` is rendered in HTML as: ::abc //def// ghi::{=example}. * The asterisk character (""''*''"", ''U+002A'') strongly emphasized its enclosed text. ** Example: ``abc **def** ghi`` is rendered in HTML as: ::abc **def** ghi::{=example}. * The low line character (""''_''"", ''U+005F'') marks text as inserted. ** Example: ``abc __def__ ghi`` is rendered in HTML as: ::abc __def__ ghi::{=example}. * Similar, the tilde character (""''~''"", ''U+007E'') marks deleted text. ** Example: ``abc ~~def~~ ghi`` is rendered in HTML as: ::abc ~~def~~ ghi::{=example}. * The apostrophe character (""''\'''"", ''U+0027'') renders text in mono-space / fixed font width. ** Example: ``abc ''def'' ghi`` is rendered in HTML as: ::abc ''def'' ghi::{=example}. * The circumflex accent character (""''^''"", ''U+005E'') allows to enter superscripted text. ** Example: ``e=mc^^2^^`` is rendered in HTML as: ::e=mc^^2^^::{=example}. * The comma character (""'',''"", ''U+002C'') produces subscripted text. ** Example: ``H,,2,,O`` is rendered in HTML as: ::H,,2,,O::{=example}. * The less-than sign character (""''<''"", ''U+003C'') marks an inline quotation. ** Example: ``<<To be or not<<`` is rendered in HTML as: ::<<To be or not<<::{=example}. * The quotation mark character (""''"''"", ''U+0022'') produces the right typographic quotation marks according to the [[specified language|00001007050100]]. ** Example: ``""To be or not""`` is rendered in HTML as: ::""To be or not""::{=example}. ** Example: ``""Sein oder nicht""{lang=de}`` is rendered in HTML as: ::""Sein oder nicht""{lang=de}::{=example}. * The semicolon character (""'';''"", ''U+003B'') specifies text that should be rendered with small characters. ** Example: ``abc ;;def;; ghi`` is rendered in HTML as: ::abc ;;def;; ghi::{=example}. * The colon character (""'':''"", ''U+003A'') mark some text that should belong together. It fills a similar role as [[region blocks|00001007030800]], but just for inline elements. ** Example: ``abc ::def::{style=color:green} ghi`` is rendered in HTML as: abc ::def::{style=color:green} ghi. |
Changes to docs/manual/00001007040200.zettel.
1 2 3 4 5 | id: 00001007040200 title: Zettelmarkup: Literal-like formatting role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | id: 00001007040200 title: Zettelmarkup: Literal-like formatting role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20210525121114 There are some reasons to mark text that should be rendered as uninterpreted: * Mark text as literal, sometimes as part of a program. * Mark text as input you give into a computer via a keyboard. * Mark text as output from some computer, e.g. shown at the command line. === Literal text Literal text somehow relates to [[verbatim blocks|00001007030500]]: their content should not be interpreted further, but may be rendered special. It is specified by two grave accent characters (""''`''"", ''U+0060''), followed by the text, followed by again two grave accent characters, optionally followed by an [[attribute|00001007050000]] specification. Similar to the verbatim block, the literal element allows also a modifier letter grave accent (""''ˋ''"", ''U+02CB'') as an alternative to the grave accent character[^On some devices, such as an iPhone / iPad, a grave accent character is harder to enter and is often confused with a modifier letter grave accent.]. However, all four characters must be the same. The literal element supports the default attribute: when given, all spaces in the text are rendered in HTML as open box characters (""''␣''"", ''U+2423''). The use of a generic attribute allwos to specify a (programming) language that controls syntax colouring when rendered in HTML. If you want to specify a grave accent character in the text, either use modifier grave accent characters as delimiters for the element, or put a backslash character before the grave accent character you want to use inside the element. If you want to enter a backslash character, you need to enter two of these. Examples: * ``\`\`abc def\`\``` is rendered in HTML as ::``abc def``::{=example}. * ``\`\`abc def\`\`{-}`` is rendered in HTML as ::``abc def``{-}::{=example}. |
︙ | ︙ |
Changes to docs/manual/00001007040310.zettel.
1 2 3 4 5 | id: 00001007040310 title: Zettelmarkup: Links role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | id: 00001007040310 title: Zettelmarkup: Links role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk There are two kinds of links, regardless of links to (internal) other zettel or to (external) material. Both kinds begin with two consecutive left square bracket characters (""''[''"", ''U+005B'') and ends with two consecutive right square bracket characters (""'']''"", ''U+005D''). The first form provides some text plus the link specification, delimited by a vertical bar character (""''|''"", ''U+007C''): ``[[text|linkspecification]]``. The second form just provides a link specification between the square brackets. Its text is derived from the link specification, e.g. by interpreting the link specification as text: ``[[linkspecification]]``. The link specification for another zettel within the same Zettelstore is just the [[zettel identifier|00001006050000]]. To reference some content within a zettel, you can append a number sign character (""''#''"", ''U+0023'') and the name of the mark to the zettel identifier. The resulting reference is called ""zettel reference"". To specify some material outside the Zettelstore, just use an normal Uniform Resource Identifier (URI) as defined by [[RFC\ 3986|https://tools.ietf.org/html/rfc3986]]. If the URL begins with the slash character (""/"", ''U+002F''), or if it begins with ""./"" or with ""../"", i.e. without scheme, user info, and host name, the reference will be treated as a ""local reference"", otherwise as an ""external reference"". If the URL begins with two slash characters, it will be interpreted relative to the value of [[''url-prefix''|00001004010000#url-prefix]]. The text in the second form is just a sequence of inline elements. |
Changes to docs/manual/00001007040320.zettel.
1 2 3 4 5 | id: 00001007040320 title: Zettelmarkup: Inline Embedding / Transclusion role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | id: 00001007040320 title: Zettelmarkup: Inline Embedding / Transclusion role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20210811162201 To some degree, an specification for embedded material is conceptually not too far away from a specification for [[linked material|00001007040310]]. Both contain a reference specification and optionally some text. In contrast to a link, the specification of embedded material must currently resolve to some kind of real content. This content replaces the embed specification. An image specification begins with two consecutive left curly bracket characters (""''{''"", ''U+007B'') and ends with two consecutive right curly bracket characters (""''}''"", ''U+007D''). The curly brackets delimits either a reference specification or some text, a vertical bar character and the link specification, similar to a link. One difference to a link: if the text was not given, an empty string is assumed. The reference must point to some content, either zettel content or URL-referenced content. If the referenced zettel does not exist, or is not readable, a spinning emoji is presented as a visual hint: Example: ``{{00000000000000}}`` will be rendered as ::{{00000000000000}}::{=example}. There are two kind of content: # [[image content|00001007040322]], # [[textual content|00001007040324]]. |
Changes to docs/manual/00001007040324.zettel.
1 2 3 4 5 | id: 00001007040324 title: Zettelmarkup: Inline Transclusion of Text role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | id: 00001007040324 title: Zettelmarkup: Inline Transclusion of Text role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20210811172440 Inline transclusion applies to all zettel that are parsed in an non-trivial way. For example, textual content is assumed if the [[syntax|00001006020000#syntax]] of a zettel is ''zmk'' ([[Zettelmarkup|00001007000000]]), or ''markdown'' / ''md'' ([[Markdown|00001008010000]]). Since the transclusion is at the level of [[inline-structured elements|00001007040000]], the transclude specification must be replaced with some inline-structured elements. First, the referenced zettel is read. If it contains inline transclusions, these will be expanded, recursively. When an endless recursion is detected, expansion does not take place. Instead an error message replaces the transclude specification. The result of this (indirect) transclusion is searched for inline-structured elements. * If only the zettel identifier was specified, the first top-level [[paragraph|00001007030000#paragraphs]] is used. Since a paragraph is basically a sequence of inline-structured elements, these elements will replace the transclude specification. Example: ``{{00010000000000}}`` (see [[00010000000000]]) is rendered as ::{{00010000000000}}::{=example}. * If a fragment identifier was additionally specified, the element with the given fragment is searched: ** If it specifies a [[heading|00001007030300]], the next top-level paragraph is used. |
︙ | ︙ |
Changes to docs/manual/00001007040340.zettel.
1 2 3 4 5 | id: 00001007040340 title: Zettelmarkup: Citation Key role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | id: 00001007040340 title: Zettelmarkup: Citation Key role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20210810172339 A citation key references some external material that is part of a bibliografical collection. Currently, Zettelstore implements this only partially, it is ""work in progress"". However, the syntax is: beginning with a left square bracket and followed by an at sign character (""''@''"", ''U+0040''), a the citation key is given. The key is typically a sequence of letters and digits. If a comma character (""'',''"", ''U+002C'') or a vertical bar character is given, the following is interpreted as inline elements. A right square bracket ends the text and the citation key element. |
Changes to docs/manual/00001007050000.zettel.
1 2 3 4 5 | id: 00001007050000 title: Zettelmarkup: Attributes role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001007050000 title: Zettelmarkup: Attributes role: manual tags: #manual #zettelmarkup #zettelstore syntax: zmk modified: 20211103162617 Attributes allows to modify the way how material is presented. Alternatively, they provide additional information to markup elements. To some degree, attributes are similar to [[HTML attributes|https://html.spec.whatwg.org/multipage/dom.html#global-attributes]]. Typical use cases for attributes are to specify the (natural) [[language|00001007050100]] for a text region, to specify the [[programming language|00001007050200]] for highlighting program code, or to make white space visible in plain text. |
︙ | ︙ | |||
50 51 52 53 54 55 56 | The key ""''-''"" (just hyphen-minus) is special. It is called __default attribute__ and has a markup specific meaning. For example, when used for plain text, it replaces the non-visible space with a visible representation: * ++``Hello, world``{-}++ produces ==Hello, world=={-}. * ++``Hello, world``++ produces ==Hello, world==. | | | 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | The key ""''-''"" (just hyphen-minus) is special. It is called __default attribute__ and has a markup specific meaning. For example, when used for plain text, it replaces the non-visible space with a visible representation: * ++``Hello, world``{-}++ produces ==Hello, world=={-}. * ++``Hello, world``++ produces ==Hello, world==. For some block elements, there is a syntax variant if you only want to specify a generic attribute. For all line-range blocks you can specify the generic attributes directly in the first line, after the three (or more) block characters. ``` :::attr ... ::: ``` |
︙ | ︙ | |||
85 86 87 88 89 90 91 | ``` is not allowed. Same for ``` === Heading {style=color:" green"} ```. | | | 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | ``` is not allowed. Same for ``` === Heading {style=color:" green"} ```. For inlines, the attributes must immediately follow the inline markup. However, the attributes may be continued on the next line when a space or line ending character is possible. ``::GREEN::{style=color:green}`` is allowed, but not ``::GREEN:: {style=color:green}``. ``` ::GREEN::{style=color:green background=grey} |
︙ | ︙ |
Changes to docs/manual/00001007060000.zettel.
1 2 3 4 5 | id: 00001007060000 title: Zettelmarkup: Summary of Formatting Characters role: manual tags: #manual #reference #zettelmarkup #zettelstore syntax: zmk | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | id: 00001007060000 title: Zettelmarkup: Summary of Formatting Characters role: manual tags: #manual #reference #zettelmarkup #zettelstore syntax: zmk modified: 20211103173317 The following table gives an overview about the use of all characters that begin a markup element. |= Character :|= Blocks <|= Inlines < | ''!'' | (free) | (free) | ''"'' | [[Verse block|00001007030700]] | [[Typographic quotation mark|00001007040100]] | ''#'' | [[Ordered list|00001007030200]] | [[Tag|00001007040000]] | ''$'' | (reserved) | (reserved) | ''%'' | [[Comment block|00001007030900]] | [[Comment|00001007040000]] | ''&'' | (free) | [[Entity|00001007040000]] | ''\''' | (free) | [[Monospace text|00001007040100]] | ''('' | (free) | (free) | '')'' | (free) | (free) | ''*'' | [[Unordered list|00001007030200]] | [[strongly emphasized text|00001007040100]] | ''+'' | (free) | [[Keyboard input|00001007040200]] | '','' | (free) | [[Subscripted text|00001007040100]] | ''-'' | [[Horizonal rule|00001007030400]] | ""[[en-dash|00001007040000]]"" | ''.'' | (free) | [[Horizontal ellipsis|00001007040000]] | ''/'' | (free) | [[//Emphasized text//|00001007040100]] (deprecated for v0.0.17) | '':'' | [[Region block|00001007030800]] / [[description text|00001007030100]] | [[Inline region|00001007040100]] | '';'' | [[Description term|00001007030100]] | [[Small text|00001007040100]] | ''<'' | [[Quotation block|00001007030600]] | [[Short inline quote|00001007040100]] | ''='' | [[Headings|00001007030300]] | [[Computer output|00001007040200]] | ''>'' | [[Quotation lists|00001007030200]] | [[Inserted text|00001007040100]] | ''?'' | (free) | (free) | ''@'' | (free) | (reserved) | ''['' | (reserved) | [[Linked material|00001007040300]], [[citation key|00001007040300]], [[footnote|00001007040300]], [[mark|00001007040300]] | ''\\'' | (blocked by inline meaning) | [[Escape character|00001007040000]] | '']'' | (reserved) | End of link, citation key, footnote, mark | ''^'' | (free) | [[Superscripted text|00001007040100]] | ''_'' | (free) | [[Emphasized text|00001007040100]] | ''`'' | [[Verbatim block|00001007030500]] | [[Literal text|00001007040200]] | ''{'' | (reserved) | [[Embedded material|00001007040300]], [[Attribute|00001007050000]] | ''|'' | [[Table row / table cell|00001007031000]] | Separator within link and embed formatting | ''}'' | (reserved) | End of embedded material, End of Attribute | ''~'' | (free) | [[Deleted text|00001007040100]] |
Changes to docs/manual/00001008000000.zettel.
1 2 3 4 5 | id: 00001008000000 title: Other Markup Languages role: manual tags: #manual #zettelstore syntax: zmk | | | | < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | id: 00001008000000 title: Other Markup Languages role: manual tags: #manual #zettelstore syntax: zmk modified: 20210705111758 [[Zettelmarkup|00001007000000]] is not the only markup language you can use to define your content. Zettelstore is quite agnostic with respect to markup languages. Of course, Zettelmarkup plays an important role. However, with the exception of zettel titles, you can use any (markup) language that is supported: * CSS * HTML template data * Image formats: GIF, PNG, JPEG, SVG * Markdown * Plain text, not further interpreted The [[metadata key|00001006020000#syntax]] ""''syntax''"" specifies which language should be used. If it is not given, the key ""''default-syntax''"" will be used (specified in the [[configuration zettel|00001004020000#default-syntax]]). The following syntax values are supported: ; [!css]''css'' : A [[Cascading Style Sheet|https://www.w3.org/Style/CSS/]], to be used when rendering a zettel as HTML. ; [!gif]''gif''; [!jpeg]''jpeg''; [!jpg]''jpg''; [!png]''png'' : The formats for pixel graphics. Typically the data is stored in a separate file and the syntax is given in the ''.meta'' file. ; [!html]''html'' : Hypertext Markup Language, will not be parsed further. Instead, it is treated as [[text|#text]], but will be encoded differently for [[HTML format|00001012920510]] (same for the [[web user interface|00001014000000]]). For security reasons, equivocal elements will not be encoded in the HTML format / web user interface, e.g. the ``<script ...`` tag. See [[security aspects of Markdown|00001008010000#security-aspects]] for some details. ; [!markdown]''markdown'', [!md]''md'' : For those who desperately need [[Markdown|https://daringfireball.net/projects/markdown/]]. Since the world of Markdown is so diverse, a [[CommonMark|https://commonmark.org/]] parser is used. See [[Use Markdown within Zettelstore|00001008010000]]. ; [!mustache]''mustache'' : A [[Mustache template|https://mustache.github.io/]], used when rendering a zettel as HTML for the [[web user interface|00001014000000]]. ; [!none]''none'' : Only the metadata of a zettel is ""parsed"". Useful for displaying the full metadata. The [[runtime configuration zettel|00000000000100]] uses this syntax. The zettel content is ignored. ; [!svg]''svg'' : A [[Scalable Vector Graphics|https://www.w3.org/TR/SVG2/]]. The icon for external material is an example. ; [!text]''text'', [!plain]''plain'', [!txt]''txt'' : Just plain text that must not be interpreted further. ; [!zmk]''zmk'' : [[Zettelmarkup|00001007000000]]. If you specify something else, your content will be interpreted as plain text. |
Changes to docs/manual/00001008010000.zettel.
1 2 3 4 5 | id: 00001008010000 title: Use Markdown within Zettelstore role: manual tags: #manual #markdown #zettelstore syntax: zmk | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | id: 00001008010000 title: Use Markdown within Zettelstore role: manual tags: #manual #markdown #zettelstore syntax: zmk modified: 20210726191610 If you are customized to use Markdown as your markup language, you can configure Zettelstore to support your decision. Zettelstore supports [[CommonMark|https://commonmark.org/]], an [[attempt|https://xkcd.com/927/]] to unify all the different, divergent dialects of Markdown. === Use Markdown as the default markup language of Zettelstore Add the key ''default-syntax'' with a value of ''md'' or ''markdown'' to the [[configuration zettel|00000000000100]]. Whether to use ''md'' or ''markdown'' is not just a matter to taste. It also depends on the value of [[''zettel-file-syntax''|00001004020000#zettel-file-syntax]] and, to some degree, on the value of [[''yaml-header''|00001004020000#yaml-header]]. If you set ''yaml-header'' to true, then new content is always stored in a file with the extension ''.zettel''. Otherwise ''zettel-file-syntax'' lists all syntax values, where its content should be stored in a file with the extension ''.zettel''. If neither ''yaml-header'' nor ''zettel-file-syntax'' is set, new content is stored in a file where its file name extension is the same as the syntax value of that zettel. In this case it makes a difference, whether you specify ''md'' or ''markdown''. If you specify the syntax ''md'', your content will be stored in a file with the ''.md'' extension. Similar for the syntax ''markdown''. If you want to process the files that store the zettel content, e.g. with some other Markdown tools, this may be important. Not every Markdown tool allows both file extensions. BTW, metadata is stored in a file with the extension ''.meta'', if neither ''yaml-header'' nor ''zettel-file-syntax'' is set. === Security aspects You should be aware that Markdown is a superset of HTML. Any HTML code is valid Markdown code. If you write your own zettel, this is probably not a problem. However, if you receive zettel from others, you should be careful. An attacker might include malicious HTML code in your zettel. For example, HTML allows to embed JavaScript, a full-sized programming language that drives many web sites. When a zettel is displayed, JavaScript code might be executed, sometimes with harmful results. Zettelstore mitigates this problem by ignoring suspicious text when it encodes a zettel as HTML. Any HTML text that might contain the ``<script>`` tag or the ``<iframe>`` tag is ignored. This may lead to unexpected results if you depend on these. Other [[encodings|00001012920500]] may still contain the full HTML text. Any external client of Zettelstore, which does not use Zettelstore's HTML encoding, must be programmed to take care of malicious code. |
Deleted docs/manual/00001008010500.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to docs/manual/00001010000000.zettel.
1 2 3 4 5 | id: 00001010000000 title: Security role: manual tags: #configuration #manual #security #zettelstore syntax: zmk | < | 1 2 3 4 5 6 7 8 9 10 11 12 | id: 00001010000000 title: Security role: manual tags: #configuration #manual #security #zettelstore syntax: zmk Your zettel could contain sensitive content. You probably want to ensure that only authorized person can read and/or modify them. Zettelstore ensures this in various ways. === Local first The Zettelstore is designed to run on your local computer. |
︙ | ︙ | |||
36 37 38 39 40 41 42 | Once you have enabled authentication, it is possible to allow others to access your Zettelstore. Maybe, others should be able to read some or all of your zettel. Or you want to allow them to create new zettel, or to change them. It is up to you. If someone is authenticated as the owner of the Zettelstore (hopefully you), no restrictions apply. But as an owner, you can create ""user zettel"" to allow others to access your Zettelstore in various ways. | | | 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | Once you have enabled authentication, it is possible to allow others to access your Zettelstore. Maybe, others should be able to read some or all of your zettel. Or you want to allow them to create new zettel, or to change them. It is up to you. If someone is authenticated as the owner of the Zettelstore (hopefully you), no restrictions apply. But as an owner, you can create ""user zettel"" to allow others to access your Zettelstore in various ways. Even if you do not want to share your Zettelstore with other persons, creating user zettel can be useful if you plan to access your Zettelstore via the API. Additionally, you can specify that a zettel is publicily visible. In this case no one has to authenticate itself to see the content of the zettel. Or you can specify that a zettel is visible only to the owner. In this case, no authenticated user will be able to read and change that protected zettel. * [[Visibility rules for zettel|00001010070200]] |
︙ | ︙ |
Changes to docs/manual/00001010040200.zettel.
1 2 | id: 00001010040200 title: Creating an user zettel | < | | > > < < < < < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | id: 00001010040200 title: Creating an user zettel tags: #authentication #configuration #manual #security #zettelstore syntax: zmk role: manual All data to be used for authenticating a user is store in a special zettel called ""user zettel"". A user zettel must have set the following three metadata fields: ; ''user-id'' (""user identification"") : The unique identification to be specified for authentication. ; ''credential'' : A hashed password as generated by the [[``zettelstore password``{=sh}|00001004051400]] command. ; ''role'' : Must contain the value ""user"". The title of the zettel typically specifies the real name of the user. A user zettel can only be created by the owner of the Zettelstore. The owner should execute the following steps to create a new user zettel: # Create a new zettel with the role ""user"". # Save the zettel to get a [[identifier|00001006050000]] for this zettel. # Choose a unique identification for the user. #* If the identifier is not unique, authentication will not work for this user. # Execute the [[``zettelstore password``|00001004051400]] command. #* You have to specify the user identification and the zettel identifier #* If you should not know the password of the new user, send her/him the user identification and the user zettel identifier, so that the person can create the hashed password herself. # Edit the user zettel and add the hashed password under the meta key ''credential'' and the user identification under the key ''user-id''. |
Changes to docs/manual/00001010040400.zettel.
1 2 | id: 00001010040400 title: Authentication process | < | > | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | id: 00001010040400 title: Authentication process tags: #authentication #configuration #manual #security #zettelstore syntax: zmk role: manual When someone tries to authenticate itself with an user identifier / ""user name"" and a password, the following process is executed: # If meta key ''owner'' of the configuration zettel does not have a valid [[zettel identifier|00001006050000]] as value, authentication fails. # Retrieve all zettel, where the meta key ''user-id'' has the same value as the given user identification. If the list is empty, authentication fails. # From above list, the zettel with the numerically smallest identifier is selected. Or in other words: the oldest zettel is selected[^This is done to prevent an attacker from creating a new note with the same user identification]. # If the zettel does not have role ''user'', authentication fails. # If the zettel does not have a value for the meta key ''credential'', authentication fails. # The value of the meta key ''credential'' is compared with the given password. If they do not match, authentication fails. The authentication is successful, because the Zettelstore has an owner, the identifier matches a user zettel, and the password conforms to the stored credential. |
Changes to docs/manual/00001010040700.zettel.
1 2 3 4 5 | id: 00001010040700 title: Access token role: manual tags: #authentication #configuration #manual #security #zettelstore syntax: zmk | < | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | id: 00001010040700 title: Access token role: manual tags: #authentication #configuration #manual #security #zettelstore syntax: zmk If an user is authenticated, an ""access token"" is created that must be sent with every request to prove the identity of the caller. Otherwise the user will not be recognized by Zettelstore. If the user was authenticated via the web interface, the access token is stored in a [[""session cookie""|https://en.wikipedia.org/wiki/HTTP_cookie#Session_cookie]]. When the web browser is closed, theses cookies are not saved. If you want web browser to store the cookie as long as lifetime of that token, the owner must set ''persistent-cookie'' of the [[startup configuration|00001004010000]] to ''true''. If the web browser remains inactive for a period, the user will be automatically logged off, because each access token has a limited lifetime. The maximum length of this period is specified by the ''token-lifetime-html'' value of the startup configuration. Every time a web page is displayed, a fresh token is created and stored inside the cookie. If the user was authenticated via the API, the access token will be returned as the content of the response. Typically, the lifetime of this token is more short term, e.g. 10 minutes. It is specified by the ''token-timeout-api'' value of the startup configuration. If you need more time, you can either [[re-authenticate|00001012050200]] the user or use an API call to [[renew the access token|00001012050400]]. If you remotely access your Zettelstore via HTTP (not via HTTPS, which allows encrypted communication), your must set the ''insecure-cookie'' value of the startup configuration to ''true''. In most cases, such a scenario is not recommended, because user name and password will be transferred as plain text. You could make use of such scenario if you know all parties that access the local network where you access the Zettelstore. |
Changes to docs/manual/00001010070200.zettel.
1 2 3 4 5 | id: 00001010070200 title: Visibility rules for zettel role: manual tags: #authorization #configuration #manual #security #zettelstore syntax: zmk | | < < | | | > | < < < < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | id: 00001010070200 title: Visibility rules for zettel role: manual tags: #authorization #configuration #manual #security #zettelstore syntax: zmk modified: 20210728162201 For every zettel you can specify under which condition the zettel is visible to others. This is controlled with the metadata key [[''visibility''|00001006020000#visibility]]. The following values are supported: ; [!public]""public"" : The zettel is visible to everybody, even if the user is not authenticated. ; [!login]""login"" : Only an authenticated user can access the zettel. This is the default value for [[''default-visibility''|00001004020000#default-visibility]]. ; [!owner]""owner"" : Only the owner of the Zettelstore can access the zettel. This is for zettel with sensitive content, e.g. the [[configuration zettel|00001004020000]] or the various zettel that contains the templates for rendering zettel in HTML. ; [!expert]""expert"" : Only the owner of the Zettelstore can access the zettel, if runtime configuration [[''expert-mode''|00001004020000#expert-mode]] is set to a boolean true value. This is for zettel with sensitive content that might irritate the owner. Computed zettel with internal runtime information are examples for such a zettel. When you install a Zettelstore, only some zettel have visibility ""public"". One is the zettel that contains CSS for displaying the web interface. This is to ensure that the web interface looks nice even for not authenticated users. Another is the zettel containing the [[version|00000000000001]] of the Zettelstore. Yet other zettel lists the Zettelstore [[license|00000000000004]], its [[contributors|00000000000005]], and external, licensed [[dependencies|00000000000006]], such as program code written by others or graphics designed by others. The [[default image|00000000040001]], used if an image reference is invalid, is also public visible. Please note: if authentication is not enabled, every user has the same rights as the owner of a Zettelstore. This is also true, if the Zettelstore runs additionally in [[read-only mode|00001004010000#read-only-mode]]. In this case, the [[runtime configuration zettel|00001004020000]] is shown (its visibility is ""owner""). The [[startup configuration|00001004010000]] is not shown, because the associated computed zettel with identifier ''00000000000096'' is stored with the visibility ""expert"". If you want to show such a zettel, you must set ''expert-mode'' to true. |
Changes to docs/manual/00001010070300.zettel.
1 2 3 4 5 | id: 00001010070300 title: User roles role: manual tags: #authorization #configuration #manual #security #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | id: 00001010070300 title: User roles role: manual tags: #authorization #configuration #manual #security #zettelstore syntax: zmk modified: 20210702165501 Every user is associated with some basic privileges. These are specified in the user zettel with the key ''user-role''. The following values are supported: ; [!reader]""reader"" : The user is allowed to read zettel. This is the default value for any user except the owner of the Zettelstore. ; [!writer]""writer"" : The user is allowed to create new zettel and to change existing zettel. |
︙ | ︙ |
Changes to docs/manual/00001010070600.zettel.
1 2 3 4 5 | id: 00001010070600 title: Access rules role: manual tags: #authorization #configuration #manual #security #zettelstore syntax: zmk | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | id: 00001010070600 title: Access rules role: manual tags: #authorization #configuration #manual #security #zettelstore syntax: zmk modified: 20210702165416 Whether an operation of the Zettelstore is allowed or rejected, depends on various factors. The following rules are checked first, in this order: # In read-only mode, every operation except the ""Read"" operation is rejected. # If there is no owner, authentication is disabled and every operation is allowed for everybody. # If the user is authenticated and it is the owner, then the operation is allowed. In the second step, when authentication is enabled and the requesting user is not the owner, everything depends on the requested operation. * Read a zettel: ** If the visibility is ""public"", the access is granted. ** If the visibility is ""owner"", the access is rejected. ** If the user is not authenticated, access is rejected. ** If the zettel requested is an user zettel, reject the access if the users identification is not the same as of the ''ident'' meta key in the zettel. In other words: only the requesting user is allowed to access its own user zettel. ** If the ''user-role'' of the user is ""creator"", reject the access. ** Otherwise the user is authenticated, no sensitive zettel is requested. Allow to read the zettel. * Create a new zettel ** If the user is not authenticated, reject the access. ** If the ''user-role'' of the user is ""reader"", reject the access. ** If the user tries to create an user zettel, the access is rejected. Only the owner is allowed to create user zettel. ** In all other cases allow to create the zettel. * Change an existing zettel ** If the user is not allowed to read the zettel (see above), reject the access. ** If the user is not authenticated, reject the access. ** If the zettel is the user zettel of the authenticated user, proceed as follows: *** If some sensitive meta values are changed (e.g. user identifier, zettel role, user role, but not hashed password), reject the access *** Since the user just updates some uncritical values, grant the access In other words: a user is allowed to change its user zettel, even if s/he has no writer privilege and if only uncritical data is changed. ** If the ''user-role'' of the user is ""reader"", reject the access. ** If the user is not allowed to create a new zettel, reject the access. ** Otherwise grant the access. * Rename a zettel |
︙ | ︙ |
Changes to docs/manual/00001012000000.zettel.
1 2 3 4 5 | id: 00001012000000 title: API role: manual tags: #api #manual #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001012000000 title: API role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20211004111103 The API (short for ""**A**pplication **P**rogramming **I**nterface"") is the primary way to communicate with a running Zettelstore. Most integration with other systems and services is done through the API. The [[web user interface|00001014000000]] is just an alternative, secondary way of interacting with a Zettelstore. === Background The API is HTTP-based and uses plain text and JSON as its main encoding format for exchanging messages between a Zettelstore and its client software. |
︙ | ︙ | |||
34 35 36 37 38 39 40 | * [[Create a new zettel|00001012053200]] * [[Retrieve metadata and content of an existing zettel|00001012053300]] * [[Retrieve metadata of an existing zettel|00001012053400]] * [[Retrieve evaluated metadata and content of an existing zettel in various encodings|00001012053500]] * [[Retrieve parsed metadata and content of an existing zettel in various encodings|00001012053600]] * [[Retrieve references of an existing zettel|00001012053700]] * [[Retrieve context of an existing zettel|00001012053800]] | < < < < | 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | * [[Create a new zettel|00001012053200]] * [[Retrieve metadata and content of an existing zettel|00001012053300]] * [[Retrieve metadata of an existing zettel|00001012053400]] * [[Retrieve evaluated metadata and content of an existing zettel in various encodings|00001012053500]] * [[Retrieve parsed metadata and content of an existing zettel in various encodings|00001012053600]] * [[Retrieve references of an existing zettel|00001012053700]] * [[Retrieve context of an existing zettel|00001012053800]] * [[Retrieve zettel order within an existing zettel|00001012054000]] * [[Update metadata and content of a zettel|00001012054200]] * [[Rename a zettel|00001012054400]] * [[Delete a zettel|00001012054600]] === Various helper method * [[Encode Zettelmarkup inline material as HTML/Text|00001012070500]] |
Changes to docs/manual/00001012050200.zettel.
1 2 3 4 5 | id: 00001012050200 title: API: Authenticate a client role: manual tags: #api #manual #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | id: 00001012050200 title: API: Authenticate a client role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20210726123709 Authentication for future API calls is done by sending a [[user identification|00001010040200]] and a password to the Zettelstore to obtain an [[access token|00001010040700]]. This token has to be used for other API calls. It is valid for a relatively short amount of time, as configured with the key ''token-timeout-api'' of the [[startup configuration|00001004010000]] (typically 10 minutes). The simplest way is to send user identification (''IDENT'') and password (''PASSWORD'') via [[HTTP Basic Authentication|https://tools.ietf.org/html/rfc7617]] and send them to the [[endpoint|00001012920000]] ''/a'' with a POST request: ```sh # curl -X POST -u IDENT:PASSWORD http://127.0.0.1:23123/a {"access_token":"eyJhbGciOiJIUzUxMiJ9.eyJfdGsiOjEsImV4cCI6MTYwMTczMTI3NSwiaWF0IjoxNjAxNzMwNjc1LCJzdWIiOiJhYmMiLCJ6aWQiOiIyMDIwMTAwMzE1MDEwMCJ9.ekhXkvn146P2bMKFQcU-bNlvgbeO6sS39hs6U5EKfjIqnSInkuHYjYAIfUqf_clYRfr6YBlX5izii8XfxV8jhg","token_type":"Bearer","expires_in":600} ``` |
︙ | ︙ | |||
29 30 31 32 33 34 35 | In all cases, you will receive an JSON object will all [[relevant data|00001012921000]] to be used for further API calls. **Important:** obtaining a token is a time-intensive process. Zettelstore will delay every request to obtain a token for a certain amount of time. Please take into account that this request will take approximately 500 milliseconds, under certain circumstances more. | < < < < < < < < < | 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | In all cases, you will receive an JSON object will all [[relevant data|00001012921000]] to be used for further API calls. **Important:** obtaining a token is a time-intensive process. Zettelstore will delay every request to obtain a token for a certain amount of time. Please take into account that this request will take approximately 500 milliseconds, under certain circumstances more. === HTTP Status codes In all cases of successful authentication, a JSON object is returned, which contains the token under the key ''"token"''. A successful authentication is signaled with the HTTP status code 200, as usual. Other status codes possibly send by the Zettelstore: ; ''400'' : Unable to process the request. In most cases the form data was invalid. ; ''401'' : Authentication failed. Either the user identification is invalid or you provided the wrong password. ; ''403'' : Authentication is not active. |
Changes to docs/manual/00001012050400.zettel.
1 2 3 4 5 | id: 00001012050400 title: API: Renew an access token role: manual tags: #api #manual #zettelstore syntax: zmk | | < < < < < < < < < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | id: 00001012050400 title: API: Renew an access token role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20210726123745 An access token is only valid for a certain duration. Since the [[authentication process|00001012050200]] will need some processing time, there is a way to renew the token without providing full authentication data. Send a HTTP PUT request to the [[endpoint|00001012920000]] ''/a'' and include the current access token in the ''Authorization'' header: ```sh # curl -X PUT -H 'Authorization: Bearer TOKEN' http://127.0.0.1:23123/a {"access_token":"eyJhbGciOiJIUzUxMiJ9.eyJfdGsiOjEsImV4cCI6MTYwMTczMTI3NSwiaWF0IjoxNjAxNzMwNjc1LCJzdWIiOiJhYmMiLCJ6aWQiOiIyMDIwMTAwMzE1MDEwMCJ9.ekhXkvn146P2bMKFQcU-bNlvgbeO6sS39hs6U5EKfjIqnSInkuHYjYAIfUqf_clYRfr6YBlX5izii8XfxV8jhg","token_type":"Bearer","expires_in":456} ``` You may receive a new access token, or the current one if it was obtained not a long time ago. However, the lifetime of the returned [[access token|00001012921000]] is accurate. === HTTP Status codes ; ''200'' : Renew process was successful, the body contains an [[appropriate JSON object|00001012921000]]. ; ''400'' : The renew process was not successful. There are several reasons for this. Maybe authorization was not [[enabled|00001010040100]], or the access bearer token was not valid. Probably you should [[authenticate|00001012050200]] again with user identification and password. |
Changes to docs/manual/00001012051200.zettel.
1 2 3 4 5 | id: 00001012051200 title: API: List metadata of all zettel role: manual tags: #api #manual #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | id: 00001012051200 title: API: List metadata of all zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20211004124401 To list the metadata of all zettel just send a HTTP GET request to the [[endpoint|00001012920000]] ''/j''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header]. If successful, the output is a JSON object: ```sh # curl http://127.0.0.1:23123/j {"query":"","list":[{"id":"00001012051200","meta":{"title":"API: Renew an access token","tags":"#api #manual #zettelstore","syntax":"zmk","role":"manual"}},{"id":"00001012050600","meta":{"title":"API: Provide an access token","tags":"#api #manual #zettelstore","syntax":"zmk","role":"manual"}},{"id":"00001012050400","meta":{"title":"API: Renew an access token","tags":"#api #manual #zettelstore","syntax":"zmk","role":"manual"}},{"id":"00001012050200","meta":{"title":"API: Authenticate a client","tags":"#api #manual #zettelstore","syntax":"zmk","role":"manual"}},{"id":"00001012000000","meta":{"title":"API","tags":"#api #manual #zettelstore","syntax":"zmk","role":"manual"}}]} ``` The JSON object contains a key ''"list"'' where its value is a list of zettel JSON objects. These zettel JSON objects themselves contains the keys ''"id"'' (value is a string containing the zettel identifier), , and ''"meta"'' (value as a JSON object). The value of key ''"meta"'' effectively contains all metadata of the identified zettel, where metadata keys are encoded as JSON object keys and metadata values encoded as JSON strings. Additionally, the JSON object contains a key ''"query"'' with a string value. It will contain a textual description of the underlying query if you [[select only some zettel|00001012051810]]. Without a selection, the value is the empty string. If you reformat the JSON output from the ''GET /j'' call, you'll see its structure better: |
︙ | ︙ | |||
75 76 77 78 79 80 81 | ] } ``` In this special case, the metadata of each zettel just contains the four default keys ''title'', ''tags'', ''syntax'', and ''role''. [!plain]Alternatively, you can retrieve the list of zettel in a simple, plain format using the [[endpoint|00001012920000]] ''/z''. In this case, a plain text document is returned, with one line per zettel. | | < < < < < < < | 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | ] } ``` In this special case, the metadata of each zettel just contains the four default keys ''title'', ''tags'', ''syntax'', and ''role''. [!plain]Alternatively, you can retrieve the list of zettel in a simple, plain format using the [[endpoint|00001012920000]] ''/z''. In this case, a plain text document is returned, with one line per zettel. Each line contains in the first 14 characters the zettel identifier. Separated by a space character, the title of the zettel follows: ```sh # curl http://127.0.0.1:23123/z 00001012051200 API: Renew an access token 00001012050600 API: Provide an access token 00001012050400 API: Renew an access token 00001012050200 API: Authenticate a client 00001012000000 API ``` === HTTP Status codes ; ''200'' : Retrieval was successful, the body contains an [[appropriate JSON object|00001012921000]]. ; ''400'' : Request was not valid. There are several reasons for this. Maybe the access bearer token was not valid. |
Changes to docs/manual/00001012051810.zettel.
1 2 3 4 5 | id: 00001012051810 title: API: Select zettel based on their metadata role: manual tags: #api #manual #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001012051810 title: API: Select zettel based on their metadata role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20211103164030 Every query parameter that does __not__ begin with the low line character (""_"", ''U+005F'') is treated as the name of a [[metadata|00001006010000]] key. According to the [[type|00001006030000]] of a metadata key, zettel are possibly selected. All [[supported|00001006020000]] metadata keys have a well-defined type. User-defined keys have the type ''e'' (string, possibly empty). For example, if you want to retrieve all zettel that contain the string ""API"" in its title, your request will be: |
︙ | ︙ | |||
30 31 32 33 34 35 36 | Both ``curl 'http://localhost:23123/j?url='`` and ``curl 'http://localhost:23123/j?url=!'`` may result in an empty list. The empty query parameter values matches all zettel that contain the given metadata key. Similar, if you specify just the exclamation mark character as a query parameter value, only those zettel match that does not contain the given metadata key. This is in contrast to above rule that the metadata value must exist before a match is done. For example ``curl 'http://localhost:23123/j?back=!&backward='`` returns all zettel that are reachable via other zettel, but also references these zettel. | < < < | 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | Both ``curl 'http://localhost:23123/j?url='`` and ``curl 'http://localhost:23123/j?url=!'`` may result in an empty list. The empty query parameter values matches all zettel that contain the given metadata key. Similar, if you specify just the exclamation mark character as a query parameter value, only those zettel match that does not contain the given metadata key. This is in contrast to above rule that the metadata value must exist before a match is done. For example ``curl 'http://localhost:23123/j?back=!&backward='`` returns all zettel that are reachable via other zettel, but also references these zettel. Above example shows that all sub-expressions of a select specification must be true so that no zettel is rejected from the final list. If you specify the query parameter ''_negate'', either with or without a value, the whole selection will be negated. Because of the precondition described above, ``curl 'http://127.0.0.1:23123/j?url=!com'`` and ``curl 'http://127.0.0.1:23123/j?url=com&_negate'`` may produce different lists. The first query produces a zettel list, where each zettel does have a ''url'' metadata value, which does not contain the characters ""com"". The second query produces a zettel list, that excludes any zettel containing a ''url'' metadata value that contains the characters ""com""; this also includes all zettel that do not contain the metadata key ''url''. |
︙ | ︙ |
Changes to docs/manual/00001012051840.zettel.
1 2 3 4 5 | id: 00001012051840 title: API: Shape the list of zettel metadata by searching the content role: manual tags: #api #manual #zettelstore syntax: zmk | < > | > > > | > > > > > > > > > > > > > > > > | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | id: 00001012051840 title: API: Shape the list of zettel metadata by searching the content role: manual tags: #api #manual #zettelstore syntax: zmk The query parameter ""''_s''"" allows to provide a string for a full-text search of all zettel. The search string will be normalized according to Unicode NKFD, ignoring everything except letters and numbers. If the search string starts with the character ""''!''"", it will be removed and the query matches all zettel that **do not match** the search string. In the next step, the first character of the search string will be inspected. If it contains one of the characters ""'':''"", ""''=''"", ""''>''"", or ""''~''"", this will modify how the search will be performed. The character will be removed from the start of the search string. For example, assume the search string is ""def"": ; ""'':''"", ""''~''"" (or none of these characters)[^""'':''"" is always the character for specifying the default comparison. In this case, it is equal to ""''~''"". If you omit a comparison character, the default comparison is used.] : The zettel must contain a word that contains the search string. ""def"", ""defghi"", and ""abcdefghi"" are matching the search string. ; ""''=''"" : The zettel must contain a word that is equal to the search string. Only the word ""def"" matches the search string. ; ""''>''"" : The zettel must contain a word with the search string as a prefix. A word like ""def"" or ""defghi"" matches the search string. If you want to include an initial ""''!''"" into the search string, you must prefix that with the escape character ""''\\''"". For example ""\\!abc"" will search for zettel that contains the string ""!abc"". A similar rule applies to the characters that specify the way how the search will be done. For example, ""!\\=abc"" will search for zettel that do not contains the string ""=abc"". You are allowed to specify this query parameter more than once. All results will be intersected, i.e. a zettel will be included into the list if all of the provided values match. This parameter loosely resembles the search box of the web user interface. |
Deleted docs/manual/00001012051890.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to docs/manual/00001012052000.zettel.
1 2 3 4 5 | id: 00001012052000 title: API: Sort the list of zettel metadata role: manual tags: #api #manual #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | id: 00001012052000 title: API: Sort the list of zettel metadata role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20210709162242 If not specified, the list of zettel is sorted descending by the value of the zettel identifier. The highest zettel identifier, which is a number, comes first. You change that with the ""''_sort''"" query parameter. Alternatively, you can also use the ""''_order''"" query parameter. It is an alias. Its value is the name of a metadata key, optionally prefixed with a hyphen-minus character (""-"", ''U+002D''). According to the [[type|00001006030000]] of a metadata key, the list of zettel is sorted. |
︙ | ︙ |
Changes to docs/manual/00001012053200.zettel.
1 2 3 4 5 | id: 00001012053200 title: API: Create a new zettel role: manual tags: #api #manual #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001012053200 title: API: Create a new zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20210905204325 A zettel is created by adding it to the [[list of zettel|00001012000000#zettel-lists]]. Therefore, the [[endpoint|00001012920000]] to create a new zettel is also ''/j'', but you must send the data of the new zettel via a HTTP POST request. The body of the POST request must contain a JSON object that specifies metadata and content of the zettel to be created. The following keys of the JSON object are used: ; ''"meta"'' |
︙ | ︙ | |||
31 32 33 34 35 36 37 | ``` # curl -X POST --data '{}' http://127.0.0.1:23123/j {"id":"20210713161000"} ``` If creating the zettel was successful, the HTTP response will contain a JSON object with one key: ; ''"id"'' | | | | 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | ``` # curl -X POST --data '{}' http://127.0.0.1:23123/j {"id":"20210713161000"} ``` If creating the zettel was successful, the HTTP response will contain a JSON object with one key: ; ''"id"'' : Contains the zettel identifier of the created zettel for further usage. In addition, the HTTP response header contains a key ''Location'' with a relative URL for the new zettel. A client must prepend the HTTP protocol scheme, the host name, and (optional, but often needed) the post number to make it an absolute URL. As an example, a zettel with title ""Note"" and content ""Important content."" can be created by issuing: ``` # curl -X POST --data '{"meta":{"title":"Note"},"content":"Important content."}' http://127.0.0.1:23123/j {"id":"20210713163100"} ``` [!plain]Alternatively, you can use the [[endpoint|00001012920000]] ''/z'' to create a new zettel. In this case, the zettel must be encoded in a [[plain|00001006000000]] format: first comes the [[metadata|00001006010000]] and the following content is separated by an empty line. This is the same format as used by storing zettel within a [[directory box|00001006010000]]. ``` # curl -X POST --data $'title: Note\n\nImportant content.' http://127.0.0.1:23123/z 20210903211500 ``` === HTTP Status codes ; ''201'' : Zettel creation was successful, the body contains a JSON object that contains its zettel identifier. ; ''400'' : Request was not valid. There are several reasons for this. Most likely, the JSON was not formed according to above rules. ; ''403'' : You are not allowed to create a new zettel. |
Changes to docs/manual/00001012053300.zettel.
1 | id: 00001012053300 | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | id: 00001012053300 title: Retrieve metadata and content of an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20211004111804 The [[endpoint|00001012920000]] to work with metadata and content of a specific zettel is ''/j/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits). For example, to retrieve some data about this zettel you are currently viewing, just send a HTTP GET request to the endpoint ''/j/00001012053300''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header]. If successful, the output is a JSON object: ```sh # curl http://127.0.0.1:23123/j/00001012053300 {"id":"00001012053300","meta":{"title":"API: Retrieve data for an exisiting zettel","tags":"#api #manual #zettelstore","syntax":"zmk","role":"manual","copyright":"(c) 2020 by Detlef Stern <ds@zettelstore.de>","lang":"en","license":"CC BY-SA 4.0"},"content":"The endpoint to work with a specific zettel is ''/j/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits).\n\nFor example, ... ``` Pretty-printed, this results in: ``` { "id": "00001012053300", "meta": { |
︙ | ︙ | |||
39 40 41 42 43 44 45 | Just change the [[endpoint|00001012920000]] to ''/z/{ID}'' Optionally, you may provide which parts of the zettel you are requesting. In this case, add an additional query parameter ''_part=[[PART|00001012920800]]''. Valid values are ""zettel"", ""[[meta|00001012053400]]"", and ""content"" (the default value). ````sh # curl 'http://127.0.0.1:23123/z/00001012053300' | | | | < < < | | 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | Just change the [[endpoint|00001012920000]] to ''/z/{ID}'' Optionally, you may provide which parts of the zettel you are requesting. In this case, add an additional query parameter ''_part=[[PART|00001012920800]]''. Valid values are ""zettel"", ""[[meta|00001012053400]]"", and ""content"" (the default value). ````sh # curl 'http://127.0.0.1:23123/z/00001012053300' The [[endpoint|00001012920000]] to work with metadata and content of a specific zettel is ''/j/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits). For example, to retrieve some data about this zettel you are currently viewing, just send a HTTP GET request to the endpoint ''/j/00001012053300''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header]. If successful, the output is a JSON object: ```sh ... ```` ````sh # curl 'http://127.0.0.1:23123/z/00001012053300?_part=zettel' title: API: Retrieve metadata and content of an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk The [[endpoint|00001012920000]] to work with metadata and content of a specific zettel is ''/j/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits). For example, to retrieve some data about this zettel you are currently viewing, just send a HTTP GET request to the endpoint ... ```` === HTTP Status codes ; ''200'' : Retrieval was successful, the body contains an appropriate JSON object. ; ''400'' : Request was not valid. There are several reasons for this. Maybe the zettel identifier did not consist of exactly 14 digits. ; ''403'' : You are not allowed to retrieve data of the given zettel. ; ''404'' : Zettel not found. You probably used a zettel identifier that is not used in the Zettelstore. |
Changes to docs/manual/00001012053400.zettel.
1 2 3 4 5 | id: 00001012053400 title: API: Retrieve metadata of an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | id: 00001012053400 title: API: Retrieve metadata of an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20211004112257 The [[endpoint|00001012920000]] to work with metadata of a specific zettel is ''/m/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits). For example, to retrieve some data about this zettel you are currently viewing, just send a HTTP GET request to the endpoint ''/j/00001012053400''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header]. If successful, the output is a JSON object: ```sh # curl http://127.0.0.1:23123/m/00001012053400 {"meta":{"all-tags":"#api #manual #zettelstore","back":"00001012000000 00001012053300","backward":"00001012000000 00001012053300 00001012920000","box-number":"1","forward":"00001010040100 00001012050200 00001012920000 00001012920800","modified":"20211004111240","published":"20211004111240","role":"manual","syntax":"zmk","tags":"#api #manual #zettelstore","title":"API: Retrieve metadata of an existing zettel"}} ``` |
︙ | ︙ |
Changes to docs/manual/00001012053500.zettel.
1 2 3 4 5 | id: 00001012053500 title: API: Retrieve evaluated metadata and content of an existing zettel in various encodings role: manual tags: #api #manual #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | id: 00001012053500 title: API: Retrieve evaluated metadata and content of an existing zettel in various encodings role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20211028191044 The [[endpoint|00001012920000]] to work with evaluated metadata and content of a specific zettel is ''/v/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits). For example, to retrieve some evaluated data about this zettel you are currently viewing, just send a HTTP GET request to the endpoint ''/v/00001012053500''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header]. If successful, the output is a JSON object: ```sh # curl http://127.0.0.1:23123/v/00001012053500 {"meta":{"title":[{"t":"Text","s":"API:"},{"t":"Space"},{"t":"Text","s":"Retrieve"},{"t":"Space"},{"t":"Text","s":"evaluated"},{"t":"Space"},{"t":"Text","s":"metadata"},{"t":"Space"},{"t":"Text","s":"and"},{"t":"Space"},{"t":"Text","s":"content"},{"t":"Space"},{"t":"Text","s":"of"},{"t":"Space"},{"t":"Text","s":"an"},{"t":"Space"},{"t":"Text","s":"existing"},{"t":"Space"},{"t":"Text","s":"zettel"},{"t":"Space"},{"t":"Text","s":"in"},{"t":"Space"}, ... ``` |
︙ | ︙ | |||
31 32 33 34 35 36 37 | <meta name="zs-backward" content="00001012000000"> <meta name="zs-box-number" content="1"> <meta name="copyright" content="(c) 2020-2021 by Detlef Stern <ds@zettelstore.de>"> <meta name="zs-forward" content="00001010040100 00001012050200 00001012920000 00001012920800"> <meta name="zs-published" content="00001012053500"> </head> <body> | | | 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <meta name="zs-backward" content="00001012000000"> <meta name="zs-box-number" content="1"> <meta name="copyright" content="(c) 2020-2021 by Detlef Stern <ds@zettelstore.de>"> <meta name="zs-forward" content="00001010040100 00001012050200 00001012920000 00001012920800"> <meta name="zs-published" content="00001012053500"> </head> <body> <p>The <a href="00001012920000">endpoint</a> to work with evaluated metadata and content of a specific zettel is <span class="zs-monospace">/v/{ID}</span>, where <span class="zs-monospace">{ID}</span> is a placeholder for the zettel identifier (14 digits).</p> ... ``` You also can use the query parameter ''_part=[[PART|00001012920800]]'' to specify which parts of a zettel must be encoded. In this case, its default value is ''content''. ```sh # curl 'http://127.0.0.1:23123/v/00001012053500?_enc=html&_part=meta' |
︙ | ︙ |
Changes to docs/manual/00001012053600.zettel.
1 2 3 4 5 | id: 00001012053600 title: API: Retrieve parsed metadata and content of an existing zettel in various encodings role: manual tags: #api #manual #zettelstore syntax: zmk | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | id: 00001012053600 title: API: Retrieve parsed metadata and content of an existing zettel in various encodings role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20211103164337 The [[endpoint|00001012920000]] to work with parsed metadata and content of a specific zettel is ''/p/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits). A __parsed__ zettel is basically an [[unevaluated|00001012053500]] zettel: the zettel is read and analyzed, but its content is not __evaluated__. By using this endpoint, you are able to retrieve the structure of a zettel before it is evaluated. For example, to retrieve some data about this zettel you are currently viewing, just send a HTTP GET request to the endpoint ''/v/00001012053600''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header]. If successful, the output is a JSON object: ```sh # curl http://127.0.0.1:23123/p/00001012053600 {"meta":{"title":[{"t":"Text","s":"Retrieve"},{"t":"Space"},{"t":"Text","s":"parsed"},{"t":"Space"},{"t":"Text","s":"metadata"},{"t":"Space"},{"t":"Text","s":"and"},{"t":"Space"},{"t":"Text","s":"content"},{"t":"Space"},{"t":"Text","s":"of"},{"t":"Space"},{"t":"Text","s":"an"},{"t":"Space"},{"t":"Text","s":"existing"},{"t":"Space"},{"t":"Text","s":"zettel"},{"t":"Space"},{"t":"Text","s":"in"},{"t":"Space"},{"t":"Text","s":"various"},{"t":"Space"},{"t":"Text","s":"encodings"}],"role":"manual","tags":["#api", ... ``` Similar to [[retrieving an encoded zettel|00001012053500]], you can specify an [[encoding|00001012920500]] and state which [[part|00001012920800]] of a zettel you are interested in. The same default values applies to this endpoint. === HTTP Status codes ; ''200'' |
︙ | ︙ |
Changes to docs/manual/00001012053700.zettel.
1 2 3 4 5 | id: 00001012053700 title: API: Retrieve references of an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001012053700 title: API: Retrieve references of an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20210825225643 The web of zettel is one important value of a Zettelstore. Many zettel references other zettel, embedded material, external/local material or, via citations, external literature. By using the [[endpoint|00001012920000]] ''/l/{ID}'' you are able to retrieve these references. ```` # curl http://127.0.0.1:23123/l/00001012053700 |
︙ | ︙ | |||
27 28 29 30 31 32 33 | }, "embedded": {} } ```` === Kind The following top-level JSON keys are returned: ; ''id'' | | | 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | }, "embedded": {} } ```` === Kind The following top-level JSON keys are returned: ; ''id'' : The zettel identifier for which the references were requested. ; ''linked'' : A JSON object that contains information about incoming and outgoing [[links|00001007040300#links]]. ; ''embedded'' : A JSON object that contains information about referenced [[embedded material|00001007040300#embedded-material]]. ; ''cite'' : A JSON list of [[citation keys|00001007040300#citation-key]] (as JSON strings). |
︙ | ︙ |
Changes to docs/manual/00001012053800.zettel.
1 2 3 4 5 | id: 00001012053800 title: API: Retrieve context of an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | id: 00001012053800 title: API: Retrieve context of an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20211103163027 The context of an origin zettel consists of those zettel that are somehow connected to the origin zettel. Direct connections of an origin zettel to other zettel are visible via [[metadata values|00001006020000]], such as ''backward'', ''forward'' or other values with type [[identifier|00001006032000]] or [[set of identifier|00001006032500]]. The context is defined by a __direction__, a __depth__, and a __limit__: * Direction: connections are directed. For example, the metadata value of ''backward'' lists all zettel that link to the current zettel, while ''formward'' list all zettel to which the current zettel links. When you are only interested in one direction, set the parameter ''dir'' either to the value ""backward"" or ""forward"". All other values, including a missing value, is interpreted as ""both"". * Depth: a direct connection has depth 1, an indirect connection is the length of the shortest path between two zettel. You should limit the depth by using the parameter ''depth''. Its default value is ""5"". A value of ""0"" does disable any depth check. * Limit: to set an upper bound for the returned context, you should use the parameter ''limit''. |
︙ | ︙ | |||
51 52 53 54 55 56 57 | } ] } ```` === Keys The following top-level JSON keys are returned: ; ''id'' | | | 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | } ] } ```` === Keys The following top-level JSON keys are returned: ; ''id'' : The zettel identifier for which the context was requested. ; ''meta'': : The metadata of the zettel, encoded as a JSON object. ; ''list'' : A list of JSON objects with keys ''id'' and ''meta'' that contains the zettel of the context. === HTTP Status codes ; ''200'' |
︙ | ︙ |
Deleted docs/manual/00001012053900.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to docs/manual/00001012054000.zettel.
1 2 3 4 5 | id: 00001012054000 title: API: Retrieve zettel order within an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001012054000 title: API: Retrieve zettel order within an existing zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20210825194515 Some zettel act as a ""table of contents"" for other zettel. The [[initial zettel|00001000000000]] of this manual is one example, the [[general API description|00001012000000]] is another. Every zettel with a certain internal structure can act as the ""table of contents"" for others. What is a ""table of contents""? Basically, it is just a list of references to other zettel. |
︙ | ︙ | |||
53 54 55 56 57 58 59 | } ] } ```` The following top-level JSON keys are returned: ; ''id'' | | | 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | } ] } ```` The following top-level JSON keys are returned: ; ''id'' : The zettel identifier for which the references were requested. ; ''meta'': : The metadata of the zettel, encoded as a JSON object. ; ''list'' : A list of JSON objects with keys ''id'' and ''meta'' that describe other zettel in the defined order. === HTTP Status codes ; ''200'' |
︙ | ︙ |
Changes to docs/manual/00001012054200.zettel.
1 2 3 4 5 | id: 00001012054200 title: API: Update a zettel role: manual tags: #api #manual #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | id: 00001012054200 title: API: Update a zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20210905204628 Updating metadata and content of a zettel is technically quite similar to [[creating a new zettel|00001012053200]]. In both cases you must provide the data for the new or updated zettel in the body of the HTTP request. One difference is the endpoint. The [[endpoint|00001012920000]] to update a zettel is ''/j/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits). You must send a HTTP PUT request to that endpoint: ``` # curl -X PUT --data '{}' http://127.0.0.1:23123/j/00001012054200 ``` This will put some empty content and metadata to the zettel you are currently reading. As usual, some metadata will be calculated if it is empty. |
︙ | ︙ |
Changes to docs/manual/00001012054400.zettel.
1 2 3 4 5 | id: 00001012054400 title: API: Rename a zettel role: manual tags: #api #manual #zettelstore syntax: zmk | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | id: 00001012054400 title: API: Rename a zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20211004111301 Renaming a zettel is effectively just specifying a new identifier for the zettel. Since more than one [[box|00001004011200]] might contain a zettel with the old identifier, the rename operation must success in every relevant box to be overall successful. If the rename operation fails in one box, Zettelstore tries to rollback previous successful operations. As a consequence, you cannot rename a zettel when its identifier is used in a read-only box. This applies to all predefined zettel, for example. The [[endpoint|00001012920000]] to rename a zettel is ''/j/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits). You must send a HTTP MOVE request to this endpoint, and you must specify the new zettel identifier as an URL, placed under the HTTP request header key ''Destination''. ``` # curl -X MOVE -H "Destination: 10000000000001" http://127.0.0.1:23123/j/00001000000000 ``` Only the last 14 characters of the value of ''Destination'' are taken into account and those must form an unused zettel identifier. If the value contains less than 14 characters that do not form an unused zettel identifier, the response will contain a HTTP status code ''400''. All other characters, besides those 14 digits, are effectively ignored. However, the value should form a valid URL that could be used later to [[read the content|00001012053300]] of the freshly renamed zettel. [!plain]Alternatively, you can also use the [[endpoint|00001012920000]] ''/z/{ID}''. Both endpoints behave identical. |
︙ | ︙ | |||
36 37 38 39 40 41 42 | : You are not allowed to delete the given zettel. In most cases you have either not enough [[access rights|00001010070600]] or at least one box containing the given identifier operates in read-only mode. ; ''404'' : Zettel not found. You probably used a zettel identifier that is not used in the Zettelstore. === Rationale for the MOVE method | | | 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | : You are not allowed to delete the given zettel. In most cases you have either not enough [[access rights|00001010070600]] or at least one box containing the given identifier operates in read-only mode. ; ''404'' : Zettel not found. You probably used a zettel identifier that is not used in the Zettelstore. === Rationale for the MOVE method HTTP [[standardizes|https://www.rfc-editor.org/rfc/rfc7231.txt]] seven methods. None of them is conceptually close to a rename operation. Everyone is free to ""invent"" some new method to be used in HTTP. To avoid a divergency, there is a [[methods registry|https://www.iana.org/assignments/http-methods/]] that tracks those extensions. The [[HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV)|https://www.rfc-editor.org/rfc/rfc4918.txt]] defines the method MOVE that is quite close to the desired rename operation. In fact, some command line tools use a ""move"" method for renaming files. Therefore, Zettelstore adopts somehow WebDAV's MOVE method and its use of the ''Destination'' HTTP header key. |
Changes to docs/manual/00001012054600.zettel.
1 2 3 4 5 | id: 00001012054600 title: API: Delete a zettel role: manual tags: #api #manual #zettelstore syntax: zmk | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | id: 00001012054600 title: API: Delete a zettel role: manual tags: #api #manual #zettelstore syntax: zmk modified: 20210905204749 Deleting a zettel within the Zettelstore is executed on the first [[box|00001004011200]] that contains that zettel. Zettel with the same identifier, but in subsequent boxes remain. If the first box containing the zettel is read-only, deleting that zettel will fail, as well for a Zettelstore in [[read-only mode|00001004010000#read-only-mode]] or if authentication is enabled and the user has no [[access right|00001010070600]] to do so. The [[endpoint|00001012920000]] to delete a zettel is ''/j/{ID}'', where ''{ID}'' is a placeholder for the zettel identifier (14 digits). You must send a HTTP DELETE request to this endpoint: ``` # curl -X DELETE http://127.0.0.1:23123/j/00001000000000 ``` [!plain]Alternatively, you can also use the [[endpoint|00001012920000]] ''/z/{ID}''. Both endpoints behave identical. |
︙ | ︙ |
Changes to docs/manual/00001012070500.zettel.
1 2 3 4 5 | id: 00001012070500 title: API: Encode Zettelmarkup inline material as HTML/Text role: zettel tags: #api #manual #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | id: 00001012070500 title: API: Encode Zettelmarkup inline material as HTML/Text role: zettel tags: #api #manual #zettelstore syntax: zmk modified: 20211111145202 To encode [[Zettelmarkup inline material|00001007040000]] send a HTTP POST request to the [[endpoint|00001012920000]] ''/v''. The POST body must contain a JSON encoded list of Zettelmarkup inline material to be encoded: ; ''first-zmk'' : Contains the first Zettelmarkup encoded material. This will be encoded as [[HTML|00001012920510]] and [[Text|00001012920519]]. ; ''other-zmk'' : Contain more material. The list can be empty. These will be encoded in HTML only. ; ''lang'' : Specifies the language for HTML encoding. |
︙ | ︙ | |||
30 31 32 33 34 35 36 | : HTML encoding of ''first-zmk'' ; ''first-text'' : Text encoding of ''first-zmk'' ; ''other_html'' : HTML encoding of the corresponding value in ''other-zmk''. Encoding takes place in the context of all other zettel in the Zettelstore. | | | 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | : HTML encoding of ''first-zmk'' ; ''first-text'' : Text encoding of ''first-zmk'' ; ''other_html'' : HTML encoding of the corresponding value in ''other-zmk''. Encoding takes place in the context of all other zettel in the Zettelstore. For example, links and images are evaluated according to this context. A simple example: ```sh # curl -X POST --data '{"first-zmk":"hallo [[00000000000001]]"}' http://127.0.0.1:23123/v {"first-html":"hallo <a href=\"00000000000001\">00000000000001</a>","first-text":"hallo ","other-html":null} # curl -X POST --data '{"first-zmk":"hallo [[00000000000001]]","no-links":true}' http://127.0.0.1:23123/v |
︙ | ︙ |
Deleted docs/manual/00001012080100.zettel.
|
| < < < < < < < < < < < < < < < < |
Deleted docs/manual/00001012080200.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted docs/manual/00001012080500.zettel.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to docs/manual/00001012920000.zettel.
1 2 3 4 5 | id: 00001012920000 title: Endpoints used by the API role: manual tags: #api #manual #reference #zettelstore syntax: zmk | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001012920000 title: Endpoints used by the API role: manual tags: #api #manual #reference #zettelstore syntax: zmk modified: 20211004111932 All API endpoints conform to the pattern ''[PREFIX]LETTER[/ZETTEL-ID]'', where: ; ''PREFIX'' : is the URL prefix (default: ''/''), configured via the ''url-prefix'' [[startup configuration|00001004010000]], ; ''LETTER'' : is a single letter that specifies the ressource type, ; ''ZETTEL-ID'' |
︙ | ︙ | |||
24 25 26 27 28 29 30 | | | | MOVE: [[rename the zettel|00001012054400]] | ''l'' | | GET: [[list references|00001012053700]] | **L**inks | ''m'' | | GET: [[retrieve metadata|00001012053400]] | **M**etadata | ''o'' | | GET: [[list zettel order|00001012054000]] | **O**rder | ''p'' | | GET: [[retrieve parsed zettel|00001012053600]]| **P**arsed | ''r'' | GET: [[list roles|00001012052600]] | | **R**oles | ''t'' | GET: [[list tags|00001012052400]] || **T**ags | < | | 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | | | | MOVE: [[rename the zettel|00001012054400]] | ''l'' | | GET: [[list references|00001012053700]] | **L**inks | ''m'' | | GET: [[retrieve metadata|00001012053400]] | **M**etadata | ''o'' | | GET: [[list zettel order|00001012054000]] | **O**rder | ''p'' | | GET: [[retrieve parsed zettel|00001012053600]]| **P**arsed | ''r'' | GET: [[list roles|00001012052600]] | | **R**oles | ''t'' | GET: [[list tags|00001012052400]] || **T**ags | ''v'' | POST: [[encode inlines|00001012070500]] | GET: [[retrieve evaluated zettel|00001012053500]] | E**v**aluated | ''x'' | | GET: [[list zettel context|00001012053800]] | Conte**x**t | ''z'' | GET: [[list zettel|00001012051200#plain]] | GET: [[retrieve zettel|00001012053300#plain]] | **Z**ettel | | POST: [[create new zettel|00001012053200#plain]] | PUT: [[update a zettel|00001012054200#plain]] | | | DELETE: [[delete zettel|00001012054600#plain]] | | | MOVE: [[rename zettel|00001012054400#plain]] The full URL will contain either the ''http'' oder ''https'' scheme, a host name, and an optional port number. The API examples will assume the ''http'' schema, the local host ''127.0.0.1'', the default port ''23123'', and the default empty ''PREFIX''. Therefore, all URLs in the API documentation will begin with ''http://127.0.0.1:23123''. |
Changes to docs/manual/00001012920500.zettel.
1 | id: 00001012920500 | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | id: 00001012920500 title: Encodings available by the API role: manual tags: #api #manual #reference #zettelstore syntax: zmk modified: 20210727120214 A zettel representation can be encoded in various formats for further processing. * [[djson|00001012920503]] (default) * [[html|00001012920510]] * [[native|00001012920513]] * [[text|00001012920519]] |
︙ | ︙ |
Changes to docs/manual/00001012920503.zettel.
1 2 3 4 5 | id: 00001012920503 title: DJSON Encoding role: manual tags: #api #manual #reference #zettelstore syntax: zmk | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | id: 00001012920503 title: DJSON Encoding role: manual tags: #api #manual #reference #zettelstore syntax: zmk modified: 20210727120128 A zettel representation that allows to process the syntactic structure of a zettel. It is a JSON-based encoding format, but different to the structures returned by [[endpoint|00001012920000]] ''/j/{ID}''. For an example, take a look at the JSON encoding of this page, which is available via the ""Info"" sub-page of this zettel: * [[//v/00001012920503?_enc=djson&_part=id]], * [[//v/00001012920503?_enc=djson&_part=zettel]], * [[//v/00001012920503?_enc=djson&_part=meta]], * [[//v/00001012920503?_enc=djson&_part=content]]. If transferred via HTTP, the content type will be ''application/json''. TODO: detailed description. |
Changes to docs/manual/00001012920522.zettel.
1 2 3 4 5 | id: 00001012920522 title: Zmk Encoding role: manual tags: #api #manual #reference #zettelstore syntax: zmk | | | | 1 2 3 4 5 6 7 8 9 10 11 | id: 00001012920522 title: Zmk Encoding role: manual tags: #api #manual #reference #zettelstore syntax: zmk modified: 20210726193136 A zettel representation that tries to recreate a [[Zettelmarkup|00001007000000]] representation of the zettel. Useful if you want to convert [[other markup languages|00001008000000]] to Zettelmarkup (e.g. Markdown). If transferred via HTTP, the content type will be ''text/plain''. |
Changes to docs/manual/00001018000000.zettel.
1 2 3 4 5 | id: 00001018000000 title: Troubleshooting role: zettel tags: #manual #zettelstore syntax: zmk | | < < < < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | id: 00001018000000 title: Troubleshooting role: zettel tags: #manual #zettelstore syntax: zmk modified: 20211027125603 This page lists some problems and their solutions that may occur when using your Zettelstore. === Authentication * **Problem:** [[Authentication is enabled|00001010040100]] for a local running Zettelstore and there is a valid [[user zettel|00001010040200]] for the owner. But entering user name and password at the [[web user interface|00001014000000]] seems to be ignored, while entering a wrong password will result in an error message. ** **Explanation:** A local running Zettelstore typically means, that you are accessing the Zettelstore using an URL with schema ''http:/\/'', and not ''http**s**:/\/'', for example ''http:/\/localhost:23123''. The difference between these two is the missing encryption of user name / password and for the answer of the Zettelstore if you use the ''http:/\/'' schema. To be secure by default, the Zettelstore will not work in an insecure environment. ** **Solution 1:** If you are sure that your communication medium is safe, even if you use the ''http:/\/'' schema (for example, you are running the Zettelstore on the same computer you are working on, or if the Zettelstore is running on a computer in your protected local network), then you could add the entry ''insecure-cookie: true'' in you [[startup configuration|00001004010000#insecure-cookie]] file. |
︙ | ︙ |
Changes to domain/id/id.go.
︙ | ︙ | |||
86 87 88 89 90 91 92 93 94 95 96 | func MustParse(s api.ZettelID) Zid { zid, err := Parse(string(s)) if err == nil { return zid } panic(err) } // String converts the zettel identification to a string of 14 digits. // Only defined for valid ids. func (zid Zid) String() string { | > > < < | > | > | | | | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | func MustParse(s api.ZettelID) Zid { zid, err := Parse(string(s)) if err == nil { return zid } panic(err) } const digits = "0123456789" // String converts the zettel identification to a string of 14 digits. // Only defined for valid ids. func (zid Zid) String() string { return string(zid.Bytes()) } // Bytes converts the zettel identification to a byte slice of 14 digits. // Only defined for valid ids. func (zid Zid) Bytes() []byte { n := uint64(zid) result := make([]byte, 14) for i := 13; i >= 0; i-- { result[i] = digits[n%10] n /= 10 } return result } // IsValid determines if zettel id is a valid one, e.g. consists of max. 14 digits. func (zid Zid) IsValid() bool { return 0 < zid && zid <= maxZid } // New returns a new zettel id based on the current time. func New(withSeconds bool) Zid { |
︙ | ︙ |
Changes to domain/id/id_test.go.
︙ | ︙ | |||
61 62 63 64 65 66 67 | for i, sid := range invalidIDs { if zid, err := id.Parse(sid); err == nil { t.Errorf("i=%d: sid=%q is valid (zid=%s), but should not be", i, sid, zid) } } } | < < < < < < < < < < < < < < < < < < < < | 61 62 63 64 65 66 67 | for i, sid := range invalidIDs { if zid, err := id.Parse(sid); err == nil { t.Errorf("i=%d: sid=%q is valid (zid=%s), but should not be", i, sid, zid) } } } |
Changes to domain/id/set.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 id // Set is a set of zettel identifier type Set map[Zid]bool // NewSet returns a new set of identifier with the given initial values. func NewSet(zids ...Zid) Set { | > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //----------------------------------------------------------------------------- // 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 id provides domain specific types, constants, and functions about // zettel identifier. package id // Set is a set of zettel identifier type Set map[Zid]bool // NewSet returns a new set of identifier with the given initial values. func NewSet(zids ...Zid) Set { |
︙ | ︙ | |||
34 35 36 37 38 39 40 | c = 8 } result := make(Set, c) result.AddSlice(zids) return result } | < < < < < < < < < < < < < < < < < < | | < < | < < < | 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | c = 8 } result := make(Set, c) result.AddSlice(zids) return result } // AddSlice adds all identifier of the given slice to the set. func (s Set) AddSlice(sl Slice) { for _, zid := range sl { s[zid] = true } } // Sorted returns the set as a sorted slice of zettel identifier. func (s Set) Sorted() Slice { if l := len(s); l > 0 { result := make(Slice, 0, l) for zid := range s { result = append(result, zid) } result.Sort() return result } return nil } // Intersect removes all zettel identifier that are not in the other set. // Both sets can be modified by this method. One of them is the set returned. // It contains the intersection of both. func (s Set) Intersect(other Set) Set { if len(s) > len(other) { s, other = other, s } for zid, inSet := range s { if !inSet { delete(s, zid) continue |
︙ | ︙ |
Changes to domain/id/set_test.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 id_test import ( "testing" "zettelstore.de/z/domain/id" ) | > > < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | < < < < | | > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | //----------------------------------------------------------------------------- // 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 id provides domain specific types, constants, and functions about // zettel identifier. package id_test import ( "testing" "zettelstore.de/z/domain/id" ) func TestSetSorted(t *testing.T) { t.Parallel() testcases := []struct { set id.Set exp id.Slice }{ {nil, nil}, {id.NewSet(), nil}, {id.NewSet(9, 4, 6, 1, 7), id.Slice{1, 4, 6, 7, 9}}, } for i, tc := range testcases { got := tc.set.Sorted() if !got.Equal(tc.exp) { t.Errorf("%d: %v.Sorted() should be %v, but got %v", i, tc.set, tc.exp, got) } } } func TestSetIntersection(t *testing.T) { t.Parallel() testcases := []struct { s1, s2 id.Set exp id.Slice }{ {nil, nil, nil}, {id.NewSet(), nil, nil}, {id.NewSet(), id.NewSet(), nil}, {id.NewSet(1), nil, nil}, {id.NewSet(1), id.NewSet(), nil}, {id.NewSet(1), id.NewSet(2), nil}, {id.NewSet(1), id.NewSet(1), id.Slice{1}}, } for i, tc := range testcases { sl1 := tc.s1.Sorted() sl2 := tc.s2.Sorted() got := tc.s1.Intersect(tc.s2).Sorted() if !got.Equal(tc.exp) { t.Errorf("%d: %v.Intersect(%v) should be %v, but got %v", i, sl1, sl2, tc.exp, got) } got = id.NewSet(sl2...).Intersect(id.NewSet(sl1...)).Sorted() if !got.Equal(tc.exp) { t.Errorf("%d: %v.Intersect(%v) should be %v, but got %v", i, sl2, sl1, tc.exp, got) } } } func TestSetRemove(t *testing.T) { t.Parallel() testcases := []struct { |
︙ | ︙ |
Changes to domain/meta/meta.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
75 76 77 78 79 80 81 | func IsComputed(name string) bool { if kd, ok := registeredKeys[name]; ok { return kd.IsComputed() } return false } | < < < < < < < < | 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | func IsComputed(name string) bool { if kd, ok := registeredKeys[name]; ok { return kd.IsComputed() } return false } // Inverse returns the name of the inverse key. func Inverse(name string) string { if kd, ok := registeredKeys[name]; ok { return kd.Inverse } return "" } |
︙ | ︙ | |||
120 121 122 123 124 125 126 | // Supported keys. func init() { registerKey(api.KeyID, TypeID, usageComputed, "") registerKey(api.KeyTitle, TypeZettelmarkup, usageUser, "") registerKey(api.KeyRole, TypeWord, usageUser, "") registerKey(api.KeyTags, TypeTagSet, usageUser, "") registerKey(api.KeySyntax, TypeWord, usageUser, "") | < | > < < > > > > > > > > > > > > > > > > > > | 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | // Supported keys. func init() { registerKey(api.KeyID, TypeID, usageComputed, "") registerKey(api.KeyTitle, TypeZettelmarkup, usageUser, "") registerKey(api.KeyRole, TypeWord, usageUser, "") registerKey(api.KeyTags, TypeTagSet, usageUser, "") registerKey(api.KeySyntax, TypeWord, usageUser, "") registerKey(api.KeyAllTags, TypeTagSet, usageProperty, "") registerKey(api.KeyBack, TypeIDSet, usageProperty, "") registerKey(api.KeyBackward, TypeIDSet, usageProperty, "") registerKey(api.KeyBoxNumber, TypeNumber, usageComputed, "") registerKey(api.KeyContentTags, TypeTagSet, usageProperty, "") registerKey(api.KeyCopyright, TypeString, usageUser, "") registerKey(api.KeyCredential, TypeCredential, usageUser, "") registerKey(api.KeyDead, TypeIDSet, usageProperty, "") registerKey(api.KeyDuplicates, TypeBool, usageProperty, "") registerKey(api.KeyFolge, TypeIDSet, usageProperty, "") registerKey(api.KeyForward, TypeIDSet, usageProperty, "") registerKey(api.KeyLang, TypeWord, usageUser, "") registerKey(api.KeyLicense, TypeEmpty, usageUser, "") registerKey(api.KeyModified, TypeTimestamp, usageComputed, "") registerKey(api.KeyNoIndex, TypeBool, usageUser, "") registerKey(api.KeyPrecursor, TypeIDSet, usageUser, api.KeyFolge) registerKey(api.KeyPublished, TypeTimestamp, usageProperty, "") registerKey(api.KeyReadOnly, TypeWord, usageUser, "") registerKey(api.KeyURL, TypeURL, usageUser, "") registerKey(api.KeyUserID, TypeWord, usageUser, "") registerKey(api.KeyUserRole, TypeWord, usageUser, "") registerKey(api.KeyVisibility, TypeWord, usageUser, "") // Keys for runtime configuration zettel // See: https://zettelstore.de/manual/h/00001004020000 registerKey(api.KeyDefaultCopyright, TypeString, usageUser, "") registerKey(api.KeyDefaultLang, TypeWord, usageUser, "") registerKey(api.KeyDefaultLicense, TypeEmpty, usageUser, "") registerKey(api.KeyDefaultRole, TypeWord, usageUser, "") registerKey(api.KeyDefaultSyntax, TypeWord, usageUser, "") registerKey(api.KeyDefaultTitle, TypeZettelmarkup, usageUser, "") registerKey(api.KeyDefaultVisibility, TypeWord, usageUser, "") registerKey(api.KeyExpertMode, TypeBool, usageUser, "") registerKey(api.KeyFooterHTML, TypeString, usageUser, "") registerKey(api.KeyHomeZettel, TypeID, usageUser, "") registerKey(api.KeyMarkerExternal, TypeEmpty, usageUser, "") registerKey(api.KeyMaxTransclusions, TypeNumber, usageUser, "") registerKey(api.KeySiteName, TypeString, usageUser, "") registerKey(api.KeyYAMLHeader, TypeBool, usageUser, "") registerKey(api.KeyZettelFileSyntax, TypeWordSet, usageUser, "") } // NewPrefix is the prefix for metadata key in template zettel for creating new zettel. const NewPrefix = "new-" // Meta contains all meta-data of a zettel. type Meta struct { |
︙ | ︙ | |||
241 242 243 244 245 246 247 | func (m *Meta) GetDefault(key, def string) string { if value, ok := m.Get(key); ok { return value } return def } | < < < < < < < | < < < < < < | < | | | < | < < < | < < < < < < < < > | | | | | < | < | | > > > > | | 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | func (m *Meta) GetDefault(key, def string) string { if value, ok := m.Get(key); ok { return value } return def } // Pairs returns all key/values pairs stored, in a specific order. First come // the pairs with predefined keys: MetaTitleKey, MetaTagsKey, MetaSyntaxKey, // MetaContextKey. Then all other pairs are append to the list, ordered by key. func (m *Meta) Pairs(allowComputed bool) []Pair { return m.doPairs(true, allowComputed) } // PairsRest returns all key/values pairs stored, except the values with // predefined keys. The pairs are ordered by key. func (m *Meta) PairsRest(allowComputed bool) []Pair { return m.doPairs(false, allowComputed) } func (m *Meta) doPairs(first, allowComputed bool) []Pair { result := make([]Pair, 0, len(m.pairs)) if first { for _, key := range firstKeys { if value, ok := m.pairs[key]; ok { result = append(result, Pair{key, value}) } } } keys := make([]string, 0, len(m.pairs)-len(result)) for k := range m.pairs { if !firstKeySet[k] && (allowComputed || !IsComputed(k)) { keys = append(keys, k) } } sort.Strings(keys) for _, k := range keys { result = append(result, Pair{k, m.pairs[k]}) } return result } // Delete removes a key from the data. func (m *Meta) Delete(key string) { if key != api.KeyID { delete(m.pairs, key) } |
︙ | ︙ |
Changes to domain/meta/meta_test.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
146 147 148 149 150 151 152 | func TestDefaultHeader(t *testing.T) { t.Parallel() m := New(testID) addToMeta(m, "h1", "d1") addToMeta(m, "H2", "D2") addToMeta(m, "H1", "D1.1") exp := map[string]string{"h1": "d1 D1.1", "h2": "D2"} | | | | | | | 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | func TestDefaultHeader(t *testing.T) { t.Parallel() m := New(testID) addToMeta(m, "h1", "d1") addToMeta(m, "H2", "D2") addToMeta(m, "H1", "D1.1") exp := map[string]string{"h1": "d1 D1.1", "h2": "D2"} checkHeader(t, exp, m.Pairs(true)) addToMeta(m, "", "d0") checkHeader(t, exp, m.Pairs(true)) addToMeta(m, "h3", "") exp["h3"] = "" checkHeader(t, exp, m.Pairs(true)) addToMeta(m, "h3", " ") checkHeader(t, exp, m.Pairs(true)) addToMeta(m, "h4", " ") exp["h4"] = "" checkHeader(t, exp, m.Pairs(true)) } func TestDelete(t *testing.T) { t.Parallel() m := New(testID) m.Set("key", "val") if got, ok := m.Get("key"); !ok || got != "val" { |
︙ | ︙ |
Changes to domain/meta/parse_test.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
78 79 80 81 82 83 84 | {"---\r\na:b\r\n", []meta.Pair{{"a", "b"}}}, {"---\r\na:b\r\n--\r\nc:d", []meta.Pair{{"a", "b"}, {"c", "d"}}}, {"---\r\na:b\r\n---\r\nc:d", []meta.Pair{{"a", "b"}}}, {"---\r\na:b\r\n----\r\nc:d", []meta.Pair{{"a", "b"}}}, } for i, tc := range testcases { meta := parseMetaStr(tc.input) | | | | 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | {"---\r\na:b\r\n", []meta.Pair{{"a", "b"}}}, {"---\r\na:b\r\n--\r\nc:d", []meta.Pair{{"a", "b"}, {"c", "d"}}}, {"---\r\na:b\r\n---\r\nc:d", []meta.Pair{{"a", "b"}}}, {"---\r\na:b\r\n----\r\nc:d", []meta.Pair{{"a", "b"}}}, } for i, tc := range testcases { meta := parseMetaStr(tc.input) if got := meta.Pairs(true); !equalPairs(tc.exp, got) { t.Errorf("TC=%d: expected=%v, got=%v", i, tc.exp, got) } } // Test, whether input position is correct. inp := input.NewInput([]byte("---\na:b\n---\nX")) m := meta.NewFromInput(testID, inp) exp := []meta.Pair{{"a", "b"}} if got := m.Pairs(true); !equalPairs(exp, got) { t.Errorf("Expected=%v, got=%v", exp, got) } expCh := 'X' if gotCh := inp.Ch; gotCh != expCh { t.Errorf("Expected=%v, got=%v", expCh, gotCh) } } |
︙ | ︙ |
Changes to domain/meta/type.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
66 67 68 69 70 71 72 | var ( cachedTypedKeys = make(map[string]*DescriptionType) mxTypedKey sync.RWMutex suffixTypes = map[string]*DescriptionType{ "-number": TypeNumber, "-role": TypeWord, "-url": TypeURL, | < | | 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | var ( cachedTypedKeys = make(map[string]*DescriptionType) mxTypedKey sync.RWMutex suffixTypes = map[string]*DescriptionType{ "-number": TypeNumber, "-role": TypeWord, "-url": TypeURL, "-zid": TypeID, } ) // Type returns a type hint for the given key. If no type hint is specified, // TypeUnknown is returned. func Type(key string) *DescriptionType { if k, ok := registeredKeys[key]; ok { return k.Type } mxTypedKey.RLock() k, ok := cachedTypedKeys[key] mxTypedKey.RUnlock() |
︙ | ︙ |
Changes to domain/meta/write.go.
1 | //----------------------------------------------------------------------------- | | | > > | < < < | | < < | < < | < | | < < < < < < < | < < < < < < | < < < | < | < | | | > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | //----------------------------------------------------------------------------- // Copyright (c) 2020 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 meta provides the domain specific type 'meta'. package meta import ( "bytes" "io" ) // Write writes a zettel meta to a writer. func (m *Meta) Write(w io.Writer, allowComputed bool) (int, error) { var buf bytes.Buffer for _, p := range m.Pairs(allowComputed) { buf.WriteString(p.Key) buf.WriteString(": ") buf.WriteString(p.Value) buf.WriteByte('\n') } return w.Write(buf.Bytes()) } var ( newline = []byte{'\n'} yamlSep = []byte{'-', '-', '-', '\n'} ) // WriteAsHeader writes the zettel meta to the writer, plus the separators func (m *Meta) WriteAsHeader(w io.Writer, allowComputed bool) (int, error) { var lb, lc, la int var err error if m.YamlSep { lb, err = w.Write(yamlSep) if err != nil { return lb, err } } lc, err = m.Write(w, allowComputed) if err != nil { return lb + lc, err } if m.YamlSep { la, err = w.Write(yamlSep) } else { la, err = w.Write(newline) } return lb + lc + la, err } |
Changes to domain/meta/write_test.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
35 36 37 38 39 40 41 | m.Set(api.KeySyntax, syntax) } return m } func assertWriteMeta(t *testing.T, m *meta.Meta, expected string) { t.Helper() var buf bytes.Buffer | | | 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | m.Set(api.KeySyntax, syntax) } return m } func assertWriteMeta(t *testing.T, m *meta.Meta, expected string) { t.Helper() var buf bytes.Buffer m.Write(&buf, true) if got := buf.String(); got != expected { t.Errorf("\nExp: %q\ngot: %q", expected, got) } } func TestWriteMeta(t *testing.T) { t.Parallel() |
︙ | ︙ |
Changes to encoder/djsonenc/djsonenc.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
382 383 384 385 386 387 388 | v.b.WriteByte('"') v.b.WriteString(fragment) v.b.WriteByte('"') } } var mapFormatKind = map[ast.FormatKind]string{ | > | | | | | | | | | > | | 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | v.b.WriteByte('"') v.b.WriteString(fragment) v.b.WriteByte('"') } } var mapFormatKind = map[ast.FormatKind]string{ ast.FormatEmphDeprecated: "EmphD", ast.FormatEmph: "Emph", ast.FormatStrong: "Strong", ast.FormatMonospace: "Mono", ast.FormatDelete: "Delete", ast.FormatInsert: "Insert", ast.FormatSuper: "Super", ast.FormatSub: "Sub", ast.FormatQuote: "Quote", ast.FormatQuotation: "Quotation", ast.FormatSmall: "Small", ast.FormatSpan: "Span", } var mapLiteralKind = map[ast.LiteralKind]string{ ast.LiteralProg: "Code", ast.LiteralKeyb: "Input", ast.LiteralOutput: "Output", ast.LiteralComment: "Comment", |
︙ | ︙ | |||
472 473 474 475 476 477 478 | v.b.Write(b) return } panic("Unknown content code " + strconv.Itoa(int(code))) } func (v *visitor) writeMeta(m *meta.Meta, evalMeta encoder.EvalMetaFunc) { | | | 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 | v.b.Write(b) return } panic("Unknown content code " + strconv.Itoa(int(code))) } func (v *visitor) writeMeta(m *meta.Meta, evalMeta encoder.EvalMetaFunc) { for i, p := range m.Pairs(true) { if i > 0 { v.b.WriteByte(',') } v.b.WriteByte('"') key := p.Key strfun.JSONEscape(&v.b, key) v.b.WriteString("\":") |
︙ | ︙ |
Changes to encoder/encoder_inline_test.go.
︙ | ︙ | |||
40 41 42 43 44 45 46 47 48 49 50 51 52 53 | encoderDJSON: `[{"t":"Emph","i":[{"t":"Text","s":"emph"}]}]`, encoderHTML: "<em>emph</em>", encoderNative: `Emph [Text "emph"]`, encoderText: "emph", encoderZmk: useZmk, }, }, { descr: "Strong formatting", zmk: "**strong**", expect: expectMap{ encoderDJSON: `[{"t":"Strong","i":[{"t":"Text","s":"strong"}]}]`, encoderHTML: "<strong>strong</strong>", encoderNative: `Strong [Text "strong"]`, | > > > > > > > > > > > | 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | encoderDJSON: `[{"t":"Emph","i":[{"t":"Text","s":"emph"}]}]`, encoderHTML: "<em>emph</em>", encoderNative: `Emph [Text "emph"]`, encoderText: "emph", encoderZmk: useZmk, }, }, { descr: "Emphasized formatting (deprecated)", zmk: "//emphd//", expect: expectMap{ encoderDJSON: `[{"t":"EmphD","i":[{"t":"Text","s":"emphd"}]}]`, encoderHTML: `<em class="zs-deprecated">emphd</em>`, encoderNative: `EmphD [Text "emphd"]`, encoderText: "emphd", encoderZmk: "__emphd__", }, }, { descr: "Strong formatting", zmk: "**strong**", expect: expectMap{ encoderDJSON: `[{"t":"Strong","i":[{"t":"Text","s":"strong"}]}]`, encoderHTML: "<strong>strong</strong>", encoderNative: `Strong [Text "strong"]`, |
︙ | ︙ | |||
150 151 152 153 154 155 156 157 158 159 160 161 162 163 | encoderDJSON: `[{"t":"Quotation","i":[{"t":"Text","s":"quotation"}]}]`, encoderHTML: `<q>quotation</q>`, encoderNative: `Quotation [Text "quotation"]`, encoderText: `quotation`, encoderZmk: useZmk, }, }, { descr: "Span formatting", zmk: `::span::`, expect: expectMap{ encoderDJSON: `[{"t":"Span","i":[{"t":"Text","s":"span"}]}]`, encoderHTML: `<span>span</span>`, encoderNative: `Span [Text "span"]`, | > > > > > > > > > > > | 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | encoderDJSON: `[{"t":"Quotation","i":[{"t":"Text","s":"quotation"}]}]`, encoderHTML: `<q>quotation</q>`, encoderNative: `Quotation [Text "quotation"]`, encoderText: `quotation`, encoderZmk: useZmk, }, }, { descr: "Small formatting", zmk: `;;small;;`, expect: expectMap{ encoderDJSON: `[{"t":"Small","i":[{"t":"Text","s":"small"}]}]`, encoderHTML: `<small>small</small>`, encoderNative: `Small [Text "small"]`, encoderText: `small`, encoderZmk: useZmk, }, }, { descr: "Span formatting", zmk: `::span::`, expect: expectMap{ encoderDJSON: `[{"t":"Span","i":[{"t":"Text","s":"span"}]}]`, encoderHTML: `<span>span</span>`, encoderNative: `Span [Text "span"]`, |
︙ | ︙ |
Changes to encoder/env.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //----------------------------------------------------------------------------- // 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 encoder import "zettelstore.de/z/ast" // Environment specifies all data and functions that affects encoding. type Environment struct { // Important for HTML encoder Lang string // default language Interactive bool // Encoded data will be placed in interactive content Xhtml bool // use XHTML syntax instead of HTML syntax MarkerExternal string // Marker after link to (external) material. NewWindow bool // open link in new window IgnoreMeta map[string]bool | > > | < < < < < < < | | | | | | | < | | < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | //----------------------------------------------------------------------------- // 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 encoder provides a generic interface to encode the abstract syntax // tree into some text form. package encoder import "zettelstore.de/z/ast" // Environment specifies all data and functions that affects encoding. type Environment struct { // Important for HTML encoder Lang string // default language Interactive bool // Encoded data will be placed in interactive content Xhtml bool // use XHTML syntax instead of HTML syntax MarkerExternal string // Marker after link to (external) material. NewWindow bool // open link in new window IgnoreMeta map[string]bool footnotes []*ast.FootnoteNode // Stores footnotes detected while encoding } // IsInteractive returns true, if Interactive is enabled and currently embedded // interactive encoding will take place. func (env *Environment) IsInteractive(inInteractive bool) bool { return inInteractive && env != nil && env.Interactive } // IsXHTML return true, if XHTML is enabled. func (env *Environment) IsXHTML() bool { return env != nil && env.Xhtml } // HasNewWindow retruns true, if a new browser windows should be opened. func (env *Environment) HasNewWindow() bool { return env != nil && env.NewWindow } // AddFootnote adds a footnote node to the environment and returns the number of that footnote. func (env *Environment) AddFootnote(fn *ast.FootnoteNode) int { if env == nil { return 0 } env.footnotes = append(env.footnotes, fn) return len(env.footnotes) } // GetCleanFootnotes returns the list of remembered footnote and forgets about them. func (env *Environment) GetCleanFootnotes() []*ast.FootnoteNode { if env == nil { return nil } result := env.footnotes env.footnotes = nil return result } |
Changes to encoder/htmlenc/inline.go.
︙ | ︙ | |||
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | func (v *visitor) visitFormat(fn *ast.FormatNode) { v.lang.push(fn.Attrs) defer v.lang.pop() var code string attrs := fn.Attrs.Clone() switch fn.Kind { case ast.FormatEmph: code = "em" case ast.FormatStrong: code = "strong" case ast.FormatInsert: code = "ins" case ast.FormatDelete: code = "del" case ast.FormatSuper: code = "sup" case ast.FormatSub: code = "sub" case ast.FormatQuotation: code = "q" case ast.FormatSpan: v.writeSpan(fn.Inlines, processSpanAttributes(attrs)) return case ast.FormatMonospace: code, attrs = "span", attrs.AddClass("zs-monospace") case ast.FormatQuote: v.visitQuotes(fn) | > > > > | 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 | func (v *visitor) visitFormat(fn *ast.FormatNode) { v.lang.push(fn.Attrs) defer v.lang.pop() var code string attrs := fn.Attrs.Clone() switch fn.Kind { case ast.FormatEmphDeprecated: code, attrs = "em", attrs.AddClass("zs-deprecated") case ast.FormatEmph: code = "em" case ast.FormatStrong: code = "strong" case ast.FormatInsert: code = "ins" case ast.FormatDelete: code = "del" case ast.FormatSuper: code = "sup" case ast.FormatSub: code = "sub" case ast.FormatQuotation: code = "q" case ast.FormatSmall: code = "small" case ast.FormatSpan: v.writeSpan(fn.Inlines, processSpanAttributes(attrs)) return case ast.FormatMonospace: code, attrs = "span", attrs.AddClass("zs-monospace") case ast.FormatQuote: v.visitQuotes(fn) |
︙ | ︙ |
Changes to encoder/htmlenc/visitor.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 htmlenc encodes the abstract syntax tree into HTML5. package htmlenc import ( "bytes" "io" "sort" "strconv" |
︙ | ︙ | |||
137 138 139 140 141 142 143 | ignore[api.KeyAllTags] = true ignore[api.KeyTags] = true } else if tags, ok = m.Get(api.KeyTags); ok { v.writeTags(tags) ignore[api.KeyTags] = true } | | | 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | ignore[api.KeyAllTags] = true ignore[api.KeyTags] = true } else if tags, ok = m.Get(api.KeyTags); ok { v.writeTags(tags) ignore[api.KeyTags] = true } for _, p := range m.Pairs(true) { key := p.Key if ignore[key] { continue } value := p.Value if m.Type(key) == meta.TypeZettelmarkup { if v := v.evalValue(value, evalMeta); v != "" { |
︙ | ︙ | |||
196 197 198 199 200 201 202 | func (v *visitor) writeMeta(prefix, key, value string) { v.b.WriteStrings("\n<meta name=\"", prefix, key, "\" content=\"") v.writeQuotedEscaped(value) v.b.WriteString("\">") } func (v *visitor) writeEndnotes() { | | | < < | > > > | | | | | | | | < | | > | 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | func (v *visitor) writeMeta(prefix, key, value string) { v.b.WriteStrings("\n<meta name=\"", prefix, key, "\" content=\"") v.writeQuotedEscaped(value) v.b.WriteString("\">") } func (v *visitor) writeEndnotes() { footnotes := v.env.GetCleanFootnotes() if len(footnotes) > 0 { v.b.WriteString("<ol class=\"zs-endnotes\">\n") for i := 0; i < len(footnotes); i++ { // Do not use a range loop above, because a footnote may contain // a footnote. Therefore v.enc.footnote may grow during the loop. fn := footnotes[i] n := strconv.Itoa(i + 1) v.b.WriteStrings("<li id=\"fn:", n, "\" role=\"doc-endnote\">") ast.Walk(v, fn.Inlines) v.b.WriteStrings( " <a href=\"#fnref:", n, "\" class=\"zs-footnote-backref\" role=\"doc-backlink\">↩︎</a></li>\n") } v.b.WriteString("</ol>\n") } } // visitAttributes write HTML attributes func (v *visitor) visitAttributes(a *ast.Attributes) { if a.IsEmpty() { return } |
︙ | ︙ | |||
242 243 244 245 246 247 248 | v.writeQuotedEscaped(vl) v.b.WriteByte('"') } } } func (v *visitor) writeHTMLEscaped(s string) { | < < < | < | 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | v.writeQuotedEscaped(vl) v.b.WriteByte('"') } } } func (v *visitor) writeHTMLEscaped(s string) { strfun.HTMLEscape(&v.b, s, v.visibleSpace) } func (v *visitor) writeQuotedEscaped(s string) { strfun.HTMLAttrEscape(&v.b, s) } func (v *visitor) writeReference(ref *ast.Reference) { if ref.URL == nil { v.writeHTMLEscaped(ref.Value) return } v.b.WriteString(ref.URL.String()) } |
Changes to encoder/nativeenc/nativeenc.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
188 189 190 191 192 193 194 | ) func (v *visitor) acceptMeta(m *meta.Meta, evalMeta encoder.EvalMetaFunc) { v.writeZettelmarkup("Title", m.GetDefault(api.KeyTitle, ""), evalMeta) v.writeMetaString(m, api.KeyRole, "Role") v.writeMetaList(m, api.KeyTags, "Tags") v.writeMetaString(m, api.KeySyntax, "Syntax") | | | 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | ) func (v *visitor) acceptMeta(m *meta.Meta, evalMeta encoder.EvalMetaFunc) { v.writeZettelmarkup("Title", m.GetDefault(api.KeyTitle, ""), evalMeta) v.writeMetaString(m, api.KeyRole, "Role") v.writeMetaList(m, api.KeyTags, "Tags") v.writeMetaString(m, api.KeySyntax, "Syntax") pairs := m.PairsRest(true) if len(pairs) == 0 { return } v.b.WriteString("\n[Header") v.level++ for i, p := range pairs { v.writeComma(i) |
︙ | ︙ | |||
477 478 479 480 481 482 483 | if fragment := mn.Fragment; fragment != "" { v.b.WriteString(" #") v.writeEscaped(fragment) } } var mapFormatKind = map[ast.FormatKind][]byte{ | > | | | | | | | | | > | | 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 | if fragment := mn.Fragment; fragment != "" { v.b.WriteString(" #") v.writeEscaped(fragment) } } var mapFormatKind = map[ast.FormatKind][]byte{ ast.FormatEmphDeprecated: []byte("EmphD"), ast.FormatEmph: []byte("Emph"), ast.FormatStrong: []byte("Strong"), ast.FormatInsert: []byte("Insert"), ast.FormatMonospace: []byte("Mono"), ast.FormatDelete: []byte("Delete"), ast.FormatSuper: []byte("Super"), ast.FormatSub: []byte("Sub"), ast.FormatQuote: []byte("Quote"), ast.FormatQuotation: []byte("Quotation"), ast.FormatSmall: []byte("Small"), ast.FormatSpan: []byte("Span"), } var mapLiteralKind = map[ast.LiteralKind][]byte{ ast.LiteralProg: []byte("Code"), ast.LiteralKeyb: []byte("Input"), ast.LiteralOutput: []byte("Output"), ast.LiteralComment: []byte("Comment"), |
︙ | ︙ |
Changes to encoder/textenc/textenc.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
36 37 38 39 40 41 42 | length, err := v.b.Flush() return length, err } // WriteMeta encodes metadata as text. func (te *textEncoder) WriteMeta(w io.Writer, m *meta.Meta, evalMeta encoder.EvalMetaFunc) (int, error) { buf := encoder.NewBufWriter(w) | | | 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | length, err := v.b.Flush() return length, err } // WriteMeta encodes metadata as text. func (te *textEncoder) WriteMeta(w io.Writer, m *meta.Meta, evalMeta encoder.EvalMetaFunc) (int, error) { buf := encoder.NewBufWriter(w) for _, pair := range m.Pairs(true) { switch meta.Type(pair.Key) { case meta.TypeBool: writeBool(&buf, pair.Value) case meta.TypeTagSet: writeTagSet(&buf, meta.ListFromValue(pair.Value)) case meta.TypeZettelmarkup: te.WriteInlines(&buf, evalMeta(pair.Value)) |
︙ | ︙ |
Changes to encoder/zmkenc/zmkenc.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- |
︙ | ︙ | |||
49 50 51 52 53 54 55 | v := newVisitor(w, ze) v.acceptMeta(m, evalMeta) length, err := v.b.Flush() return length, err } func (v *visitor) acceptMeta(m *meta.Meta, evalMeta encoder.EvalMetaFunc) { | | | 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | v := newVisitor(w, ze) v.acceptMeta(m, evalMeta) length, err := v.b.Flush() return length, err } func (v *visitor) acceptMeta(m *meta.Meta, evalMeta encoder.EvalMetaFunc) { for _, p := range m.Pairs(true) { key := p.Key v.b.WriteStrings(key, ": ") if meta.Type(key) == meta.TypeZettelmarkup { ast.Walk(v, evalMeta(p.Value)) } else { v.b.WriteString(p.Value) } |
︙ | ︙ | |||
308 309 310 311 312 313 314 | } ast.Walk(v, cell.Inlines) } } var escapeSeqs = map[string]bool{ "\\": true, | | > < > | 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | } ast.Walk(v, cell.Inlines) } } var escapeSeqs = map[string]bool{ "\\": true, "//": true, "**": true, "__": true, "~~": true, "^^": true, ",,": true, "<<": true, "\"\"": true, ";;": true, "::": true, "''": true, "``": true, "++": true, "==": true, } |
︙ | ︙ | |||
397 398 399 400 401 402 403 | ast.Walk(v, cn.Inlines) } v.b.WriteByte(']') v.visitAttributes(cn.Attrs) } var mapFormatKind = map[ast.FormatKind][]byte{ | > | | | | | | | | > | | | 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 | ast.Walk(v, cn.Inlines) } v.b.WriteByte(']') v.visitAttributes(cn.Attrs) } var mapFormatKind = map[ast.FormatKind][]byte{ ast.FormatEmphDeprecated: []byte("__"), ast.FormatEmph: []byte("__"), ast.FormatStrong: []byte("**"), ast.FormatInsert: []byte(">>"), ast.FormatDelete: []byte("~~"), ast.FormatSuper: []byte("^^"), ast.FormatSub: []byte(",,"), ast.FormatQuotation: []byte("<<"), ast.FormatQuote: []byte("\"\""), ast.FormatSmall: []byte(";;"), ast.FormatSpan: []byte("::"), ast.FormatMonospace: []byte("''"), } func (v *visitor) visitFormat(fn *ast.FormatNode) { kind, ok := mapFormatKind[fn.Kind] if !ok { panic(fmt.Sprintf("Unknown format kind %d", fn.Kind)) } |
︙ | ︙ |
Changes to evaluator/evaluator.go.
︙ | ︙ | |||
43 44 45 46 47 48 49 | } var emptyEnv Environment // EvaluateZettel evaluates the given zettel in the given context, with the // given ports, and the given environment. func EvaluateZettel(ctx context.Context, port Port, env *Environment, rtConfig config.Config, zn *ast.ZettelNode) { | < < < < < | 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | } var emptyEnv Environment // EvaluateZettel evaluates the given zettel in the given context, with the // given ports, and the given environment. func EvaluateZettel(ctx context.Context, port Port, env *Environment, rtConfig config.Config, zn *ast.ZettelNode) { evaluateNode(ctx, port, env, rtConfig, zn.Ast) cleaner.CleanBlockList(zn.Ast) } // EvaluateInline evaluates the given inline list in the given context, with // the given ports, and the given environment. func EvaluateInline(ctx context.Context, port Port, env *Environment, rtConfig config.Config, iln *ast.InlineListNode) { |
︙ | ︙ |
Deleted evaluator/metadata.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to go.mod.
1 2 3 4 5 6 7 | module zettelstore.de/z go 1.17 require ( github.com/fsnotify/fsnotify v1.5.1 github.com/pascaldekloe/jwt v1.10.0 | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | module zettelstore.de/z go 1.17 require ( github.com/fsnotify/fsnotify v1.5.1 github.com/pascaldekloe/jwt v1.10.0 github.com/yuin/goldmark v1.4.3 golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b golang.org/x/text v0.3.7 zettelstore.de/c v0.0.0-20211025140135-ccc3f543d0e9 ) require golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c // indirect |
Changes to go.sum.
1 2 3 4 | github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/pascaldekloe/jwt v1.10.0 h1:ktcIUV4TPvh404R5dIBEnPCsSwj0sqi3/0+XafE5gJs= github.com/pascaldekloe/jwt v1.10.0/go.mod h1:TKhllgThT7TOP5rGr2zMLKEDZRAgJfBbtKyVeRsNB9A= | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/pascaldekloe/jwt v1.10.0 h1:ktcIUV4TPvh404R5dIBEnPCsSwj0sqi3/0+XafE5gJs= github.com/pascaldekloe/jwt v1.10.0/go.mod h1:TKhllgThT7TOP5rGr2zMLKEDZRAgJfBbtKyVeRsNB9A= github.com/yuin/goldmark v1.4.3 h1:eTEYYWtQLjK7+WK45Tk81OTkp/0UvAyqUj8flU0nTO4= github.com/yuin/goldmark v1.4.3/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e h1:gsTQYXdTw2Gq7RBsWvlQ91b+aEQ6bXFUngBGuR8sPpI= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b h1:9zKuko04nR4gjZ4+DNjHqRlAJqbJETHwiNKDqTfOjfE= golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= zettelstore.de/c v0.0.0-20211025140135-ccc3f543d0e9 h1:X6Kb1JO0SEFxNrXiELXJeDxIMhjv0l0UaXUnRkAofjY= zettelstore.de/c v0.0.0-20211025140135-ccc3f543d0e9/go.mod h1:Hx/qzHCaQ8zzXEzBglBj/2aGkQpBQG81/4XztCIGJ84= |
Changes to kernel/impl/auth.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 impl import ( "sync" "zettelstore.de/z/auth" "zettelstore.de/z/domain/id" "zettelstore.de/z/kernel" | > < | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | //----------------------------------------------------------------------------- // 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 impl provides the kernel implementation. package impl import ( "sync" "zettelstore.de/z/auth" "zettelstore.de/z/domain/id" "zettelstore.de/z/kernel" ) type authService struct { srvConfig mxService sync.RWMutex manager auth.Manager createManager kernel.CreateAuthManagerFunc } func (as *authService) Initialize() { as.descr = descriptionMap{ kernel.AuthOwner: { "Owner's zettel id", func(val string) interface{} { if owner := as.cur[kernel.AuthOwner]; owner != nil && owner != id.Invalid { return nil } |
︙ | ︙ | |||
52 53 54 55 56 57 58 | } as.next = interfaceMap{ kernel.AuthOwner: id.Invalid, kernel.AuthReadonly: false, } } | < < | | | | | > < > | > > | 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | } as.next = interfaceMap{ kernel.AuthOwner: id.Invalid, kernel.AuthReadonly: false, } } func (as *authService) Start(kern *myKernel) error { as.mxService.Lock() defer as.mxService.Unlock() readonlyMode := as.GetNextConfig(kernel.AuthReadonly).(bool) owner := as.GetNextConfig(kernel.AuthOwner).(id.Zid) authMgr, err := as.createManager(readonlyMode, owner) if err != nil { kern.doLog("Unable to create auth manager:", err) return err } kern.doLog("Start Auth Manager") as.manager = authMgr return nil } func (as *authService) IsStarted() bool { as.mxService.RLock() defer as.mxService.RUnlock() return as.manager != nil } func (as *authService) Stop(kern *myKernel) error { kern.doLog("Stop Auth Manager") as.mxService.Lock() defer as.mxService.Unlock() as.manager = nil return nil } func (as *authService) GetStatistics() []kernel.KeyValue { return nil } |
Changes to kernel/impl/box.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //----------------------------------------------------------------------------- // 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 impl import ( "context" "fmt" "io" "net/url" "sync" "zettelstore.de/z/box" "zettelstore.de/z/kernel" | > < | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | //----------------------------------------------------------------------------- // 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 impl provides the kernel implementation. package impl import ( "context" "fmt" "io" "net/url" "sync" "zettelstore.de/z/box" "zettelstore.de/z/kernel" ) type boxService struct { srvConfig mxService sync.RWMutex manager box.Manager createManager kernel.CreateBoxManagerFunc } func (ps *boxService) Initialize() { ps.descr = descriptionMap{ kernel.BoxDefaultDirType: { "Default directory box type", ps.noFrozen(func(val string) interface{} { switch val { case kernel.BoxDirTypeNotify, kernel.BoxDirTypeSimple: return val |
︙ | ︙ | |||
59 60 61 62 63 64 65 | }, } ps.next = interfaceMap{ kernel.BoxDefaultDirType: kernel.BoxDirTypeNotify, } } | < < | | | < | | | > | 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | }, } ps.next = interfaceMap{ kernel.BoxDefaultDirType: kernel.BoxDirTypeNotify, } } func (ps *boxService) Start(kern *myKernel) error { boxURIs := make([]*url.URL, 0, 4) format := kernel.BoxURIs + "%d" for i := 1; ; i++ { u := ps.GetNextConfig(fmt.Sprintf(format, i)) if u == nil { break } boxURIs = append(boxURIs, u.(*url.URL)) } ps.mxService.Lock() defer ps.mxService.Unlock() mgr, err := ps.createManager(boxURIs, kern.auth.manager, kern.cfg.rtConfig) if err != nil { kern.doLog("Unable to create box manager:", err) return err } kern.doLog("Start Box Manager:", mgr.Location()) if err = mgr.Start(context.Background()); err != nil { kern.doLog("Unable to start box manager:", err) } kern.cfg.setBox(mgr) ps.manager = mgr return nil } func (ps *boxService) IsStarted() bool { ps.mxService.RLock() defer ps.mxService.RUnlock() return ps.manager != nil } func (ps *boxService) Stop(kern *myKernel) error { kern.doLog("Stop Box Manager") ps.mxService.RLock() mgr := ps.manager ps.mxService.RUnlock() err := mgr.Stop(context.Background()) ps.mxService.Lock() ps.manager = nil ps.mxService.Unlock() return err } func (ps *boxService) GetStatistics() []kernel.KeyValue { var st box.Stats ps.mxService.RLock() ps.manager.ReadStats(&st) ps.mxService.RUnlock() |
︙ | ︙ | |||
127 128 129 130 131 132 133 | {Key: "Zettel enrichments", Value: fmt.Sprintf("%v", st.IndexUpdates)}, } } func (ps *boxService) DumpIndex(w io.Writer) { ps.manager.Dump(w) } | < < < < < < < < < | 124 125 126 127 128 129 130 | {Key: "Zettel enrichments", Value: fmt.Sprintf("%v", st.IndexUpdates)}, } } func (ps *boxService) DumpIndex(w io.Writer) { ps.manager.Dump(w) } |
Changes to kernel/impl/cfg.go.
1 | //----------------------------------------------------------------------------- | | > < < < < < < < < < < < < < < < < < < < < < | < | | < | | | | | | | | | | | | < | | < | | | | | | | | | | | | < < | | | | | > < | < | < | | < < < | | | | | | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | //----------------------------------------------------------------------------- // 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 impl provides the kernel implementation. package impl import ( "context" "fmt" "strings" "sync" "zettelstore.de/c/api" "zettelstore.de/z/box" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" "zettelstore.de/z/kernel" ) type configService struct { srvConfig mxService sync.RWMutex rtConfig *myConfig } func (cs *configService) Initialize() { cs.descr = descriptionMap{ api.KeyDefaultCopyright: {"Default copyright", parseString, true}, api.KeyDefaultLang: {"Default language", parseString, true}, api.KeyDefaultRole: {"Default role", parseString, true}, api.KeyDefaultSyntax: {"Default syntax", parseString, true}, api.KeyDefaultTitle: {"Default title", parseString, true}, api.KeyDefaultVisibility: { "Default zettel visibility", func(val string) interface{} { vis := meta.GetVisibility(val) if vis == meta.VisibilityUnknown { return nil } return vis }, true, }, api.KeyExpertMode: {"Expert mode", parseBool, true}, api.KeyFooterHTML: {"Footer HTML", parseString, true}, api.KeyHomeZettel: {"Home zettel", parseZid, true}, api.KeyMarkerExternal: {"Marker external URL", parseString, true}, api.KeyMaxTransclusions: {"Maximum transclusions", parseInt, true}, api.KeySiteName: {"Site name", parseString, true}, api.KeyYAMLHeader: {"YAML header", parseBool, true}, api.KeyZettelFileSyntax: { "Zettel file syntax", func(val string) interface{} { return strings.Fields(val) }, true, }, } cs.next = interfaceMap{ api.KeyDefaultCopyright: "", api.KeyDefaultLang: api.ValueLangEN, api.KeyDefaultRole: api.ValueRoleZettel, api.KeyDefaultSyntax: api.ValueSyntaxZmk, api.KeyDefaultTitle: "Untitled", api.KeyDefaultVisibility: meta.VisibilityLogin, api.KeyExpertMode: false, api.KeyFooterHTML: "", api.KeyHomeZettel: id.DefaultHomeZid, api.KeyMarkerExternal: "➚", api.KeyMaxTransclusions: 1024, api.KeySiteName: "Zettelstore", api.KeyYAMLHeader: false, api.KeyZettelFileSyntax: nil, } } func (cs *configService) Start(kern *myKernel) error { kern.doLog("Start Config Service") data := meta.New(id.ConfigurationZid) for _, kv := range cs.GetNextConfigList() { data.Set(kv.Key, fmt.Sprintf("%v", kv.Value)) } cs.mxService.Lock() cs.rtConfig = newConfig(data) cs.mxService.Unlock() return nil } func (cs *configService) IsStarted() bool { cs.mxService.RLock() defer cs.mxService.RUnlock() return cs.rtConfig != nil } func (cs *configService) Stop(kern *myKernel) error { kern.doLog("Stop Config Service") cs.mxService.Lock() cs.rtConfig = nil cs.mxService.Unlock() return nil } func (*configService) GetStatistics() []kernel.KeyValue { return nil } func (cs *configService) setBox(mgr box.Manager) { cs.rtConfig.setBox(mgr) } // myConfig contains all runtime configuration data relevant for the software. type myConfig struct { mx sync.RWMutex orig *meta.Meta data *meta.Meta } // New creates a new Config value. func newConfig(orig *meta.Meta) *myConfig { cfg := myConfig{ orig: orig, data: orig.Clone(), } return &cfg } func (cfg *myConfig) setBox(mgr box.Manager) { mgr.RegisterObserver(cfg.observe) cfg.doUpdate(mgr) } func (cfg *myConfig) doUpdate(p box.Box) error { m, err := p.GetMeta(context.Background(), cfg.data.Zid) if err != nil { return err } cfg.mx.Lock() for _, pair := range cfg.data.Pairs(false) { if val, ok := m.Get(pair.Key); ok { cfg.data.Set(pair.Key, val) } } cfg.mx.Unlock() return nil } func (cfg *myConfig) observe(ci box.UpdateInfo) { if ci.Reason == box.OnReload || ci.Zid == id.ConfigurationZid { go func() { cfg.doUpdate(ci.Box) }() } } var defaultKeys = map[string]string{ api.KeyCopyright: api.KeyDefaultCopyright, api.KeyLang: api.KeyDefaultLang, api.KeyLicense: api.KeyDefaultLicense, api.KeyRole: api.KeyDefaultRole, api.KeySyntax: api.KeyDefaultSyntax, api.KeyTitle: api.KeyDefaultTitle, } // AddDefaultValues enriches the given meta data with its default values. func (cfg *myConfig) AddDefaultValues(m *meta.Meta) *meta.Meta { if cfg == nil { return m } |
︙ | ︙ | |||
226 227 228 229 230 231 232 | cfg.mx.RLock() val := cfg.data.GetBool(key) cfg.mx.RUnlock() return val } // GetDefaultTitle returns the current value of the "default-title" key. | | | | | | | | | | | | | | | < < < | | | 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | cfg.mx.RLock() val := cfg.data.GetBool(key) cfg.mx.RUnlock() return val } // GetDefaultTitle returns the current value of the "default-title" key. func (cfg *myConfig) GetDefaultTitle() string { return cfg.getString(api.KeyDefaultTitle) } // GetDefaultRole returns the current value of the "default-role" key. func (cfg *myConfig) GetDefaultRole() string { return cfg.getString(api.KeyDefaultRole) } // GetDefaultSyntax returns the current value of the "default-syntax" key. func (cfg *myConfig) GetDefaultSyntax() string { return cfg.getString(api.KeyDefaultSyntax) } // GetDefaultLang returns the current value of the "default-lang" key. func (cfg *myConfig) GetDefaultLang() string { return cfg.getString(api.KeyDefaultLang) } // GetSiteName returns the current value of the "site-name" key. func (cfg *myConfig) GetSiteName() string { return cfg.getString(api.KeySiteName) } // GetHomeZettel returns the value of the "home-zettel" key. func (cfg *myConfig) GetHomeZettel() id.Zid { val := cfg.getString(api.KeyHomeZettel) if homeZid, err := id.Parse(val); err == nil { return homeZid } cfg.mx.RLock() val, _ = cfg.orig.Get(api.KeyHomeZettel) homeZid, _ := id.Parse(val) cfg.mx.RUnlock() return homeZid } // GetDefaultVisibility returns the default value for zettel visibility. func (cfg *myConfig) GetDefaultVisibility() meta.Visibility { val := cfg.getString(api.KeyDefaultVisibility) if vis := meta.GetVisibility(val); vis != meta.VisibilityUnknown { return vis } cfg.mx.RLock() val, _ = cfg.orig.Get(api.KeyDefaultVisibility) vis := meta.GetVisibility(val) cfg.mx.RUnlock() return vis } // GetMaxTransclusions return the maximum number of indirect transclusions. func (cfg *myConfig) GetMaxTransclusions() int { cfg.mx.RLock() val, ok := cfg.data.GetNumber(api.KeyMaxTransclusions) cfg.mx.RUnlock() if ok && val > 0 { return val } return 1024 } // GetYAMLHeader returns the current value of the "yaml-header" key. func (cfg *myConfig) GetYAMLHeader() bool { return cfg.getBool(api.KeyYAMLHeader) } // GetMarkerExternal returns the current value of the "marker-external" key. func (cfg *myConfig) GetMarkerExternal() string { return cfg.getString(api.KeyMarkerExternal) } // GetFooterHTML returns HTML code that should be embedded into the footer // of each WebUI page. func (cfg *myConfig) GetFooterHTML() string { return cfg.getString(api.KeyFooterHTML) } // GetZettelFileSyntax returns the current value of the "zettel-file-syntax" key. func (cfg *myConfig) GetZettelFileSyntax() []string { cfg.mx.RLock() defer cfg.mx.RUnlock() return cfg.data.GetListOrNil(api.KeyZettelFileSyntax) } // --- AuthConfig // GetExpertMode returns the current value of the "expert-mode" key func (cfg *myConfig) GetExpertMode() bool { return cfg.getBool(api.KeyExpertMode) } // GetVisibility returns the visibility value, or "login" if none is given. func (cfg *myConfig) GetVisibility(m *meta.Meta) meta.Visibility { if val, ok := m.Get(api.KeyVisibility); ok { if vis := meta.GetVisibility(val); vis != meta.VisibilityUnknown { return vis } } return cfg.GetDefaultVisibility() } |
Changes to kernel/impl/cmd.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 impl import ( "fmt" "io" "os" "runtime/metrics" "sort" | > < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //----------------------------------------------------------------------------- // 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 impl provides the kernel implementation. package impl import ( "fmt" "io" "os" "runtime/metrics" "sort" "strings" "zettelstore.de/z/kernel" "zettelstore.de/z/strfun" ) type cmdSession struct { w io.Writer kern *myKernel echo bool |
︙ | ︙ | |||
161 162 163 164 165 166 167 | sess.println("echo is on") } else { sess.println("echo is off") } return true }, }, | < | | < < < | 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | sess.println("echo is on") } else { sess.println("echo is off") } return true }, }, "env": {"show environment values", cmdEnvironment}, "get-config": {"show current configuration data", cmdGetConfig}, "header": { "toggle table header", func(sess *cmdSession, cmd string, args []string) bool { sess.header = !sess.header if sess.header { sess.println("header are on") } else { sess.println("header are off") } return true }, }, "metrics": {"show Go runtime metrics", cmdMetrics}, "next-config": {"show next configuration data", cmdNextConfig}, "restart": {"restart service", cmdRestart}, "services": {"show available services", cmdServices}, "set-config": {"set next configuration data", cmdSetConfig}, "shutdown": { "shutdown Zettelstore", func(sess *cmdSession, cmd string, args []string) bool { sess.kern.Shutdown(false); return false }, }, |
︙ | ︙ | |||
253 254 255 256 257 258 259 | srvD := sess.kern.srvs[kernel.Service(k)] sess.println("%% Service", srvD.name) listConfig(sess, srvD.srv) } return } | | | > | 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | srvD := sess.kern.srvs[kernel.Service(k)] sess.println("%% Service", srvD.name) listConfig(sess, srvD.srv) } return } srvD, ok := sess.kern.srvNames[args[0]] if !ok { sess.println("Unknown service:", args[0]) return } if len(args) == 1 { listConfig(sess, srvD.srv) return } val := getConfig(srvD.srv, args[1]) |
︙ | ︙ | |||
288 289 290 291 292 293 294 | } func cmdSetConfig(sess *cmdSession, cmd string, args []string) bool { if len(args) < 3 { sess.usage(cmd, "SERVICE KEY VALUE") return true } | | | > < | < < > > > > > > | | 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 | } func cmdSetConfig(sess *cmdSession, cmd string, args []string) bool { if len(args) < 3 { sess.usage(cmd, "SERVICE KEY VALUE") return true } srvD, ok := sess.kern.srvNames[args[0]] if !ok { sess.println("Unknown service:", args[0]) return true } newValue := strings.Join(args[2:], " ") if !srvD.srv.SetConfig(args[1], newValue) { sess.println("Unable to set key", args[1], "to value", newValue) } return true } func cmdServices(sess *cmdSession, _ string, _ []string) bool { names := make([]string, 0, len(sess.kern.srvNames)) for name := range sess.kern.srvNames { names = append(names, name) } sort.Strings(names) table := [][]string{{"Service", "Status"}} for _, name := range names { if sess.kern.srvNames[name].srv.IsStarted() { table = append(table, []string{name, "started"}) } else { table = append(table, []string{name, "stopped"}) } } sess.printTable(table) |
︙ | ︙ | |||
356 357 358 359 360 361 362 | } func cmdStat(sess *cmdSession, cmd string, args []string) bool { if len(args) == 0 { sess.usage(cmd, "SERVICE") return true } | | > < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | > < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | } func cmdStat(sess *cmdSession, cmd string, args []string) bool { if len(args) == 0 { sess.usage(cmd, "SERVICE") return true } srvD, ok := sess.kern.srvNames[args[0]] if !ok { sess.println("Unknown service", args[0]) return true } kvl := srvD.srv.GetStatistics() if len(kvl) == 0 { return true } table := [][]string{{"Key", "Value"}} for _, kv := range kvl { table = append(table, []string{kv.Key, kv.Value}) } sess.printTable(table) return true } func lookupService(sess *cmdSession, cmd string, args []string) (kernel.Service, bool) { if len(args) == 0 { sess.usage(cmd, "SERVICE") return 0, false } srvD, ok := sess.kern.srvNames[args[0]] if !ok { sess.println("Unknown service", args[0]) return 0, false } return srvD.srvnum, true } func cmdMetrics(sess *cmdSession, _ string, _ []string) bool { var samples []metrics.Sample all := metrics.All() for _, d := range all { if d.Kind == metrics.KindFloat64Histogram { continue } |
︙ | ︙ | |||
510 511 512 513 514 515 516 | return true } func cmdDumpIndex(sess *cmdSession, _ string, _ []string) bool { sess.kern.DumpIndex(sess.w) return true } | < < < < < < < < | 432 433 434 435 436 437 438 439 440 441 442 443 444 445 | return true } func cmdDumpIndex(sess *cmdSession, _ string, _ []string) bool { sess.kern.DumpIndex(sess.w) return true } func cmdDumpRecover(sess *cmdSession, cmd string, args []string) bool { if len(args) == 0 { sess.usage(cmd, "RECOVER") sess.println("-- A valid value for RECOVER can be obtained via 'stat core'.") return true } lines := sess.kern.core.RecoverLines(args[0]) |
︙ | ︙ | |||
559 560 561 562 563 564 565 | if pos := strings.IndexByte(env, '='); pos >= 0 && pos < len(env) { table = append(table, []string{env[:pos], env[pos+1:]}) } } sess.printTable(table) return true } | < < < < < < < < < < < < < < < < < | 473 474 475 476 477 478 479 | if pos := strings.IndexByte(env, '='); pos >= 0 && pos < len(env) { table = append(table, []string{env[:pos], env[pos+1:]}) } } sess.printTable(table) return true } |
Changes to kernel/impl/config.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //----------------------------------------------------------------------------- // 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 impl import ( "fmt" "sort" "strconv" "strings" "sync" "zettelstore.de/z/domain/id" "zettelstore.de/z/kernel" | > < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //----------------------------------------------------------------------------- // 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 impl provides the kernel implementation. package impl import ( "fmt" "sort" "strconv" "strings" "sync" "zettelstore.de/z/domain/id" "zettelstore.de/z/kernel" ) type parseFunc func(string) interface{} type configDescription struct { text string parse parseFunc canList bool |
︙ | ︙ | |||
39 40 41 42 43 44 45 | for k, v := range m { result[k] = v } return result } type srvConfig struct { | < | 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | for k, v := range m { result[k] = v } return result } type srvConfig struct { mxConfig sync.RWMutex frozen bool descr descriptionMap cur interfaceMap next interfaceMap } |
︙ | ︙ | |||
146 147 148 149 150 151 152 | func (cfg *srvConfig) GetNextConfig(key string) interface{} { cfg.mxConfig.RLock() defer cfg.mxConfig.RUnlock() return cfg.next[key] } func (cfg *srvConfig) GetConfigList(all bool) []kernel.KeyDescrValue { | | | | | 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | func (cfg *srvConfig) GetNextConfig(key string) interface{} { cfg.mxConfig.RLock() defer cfg.mxConfig.RUnlock() return cfg.next[key] } func (cfg *srvConfig) GetConfigList(all bool) []kernel.KeyDescrValue { return cfg.getConfigList(all, cfg.GetConfig) } func (cfg *srvConfig) GetNextConfigList() []kernel.KeyDescrValue { return cfg.getConfigList(true, cfg.GetNextConfig) } func (cfg *srvConfig) getConfigList(all bool, getConfig func(string) interface{}) []kernel.KeyDescrValue { if len(cfg.descr) == 0 { return nil } keys := cfg.getSortedConfigKeys(all, getConfig) result := make([]kernel.KeyDescrValue, 0, len(keys)) for _, k := range keys { val := getConfig(k) |
︙ | ︙ |
Changes to kernel/impl/core.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //----------------------------------------------------------------------------- // 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 impl import ( "fmt" "net" "os" "runtime" "sort" "sync" "time" "zettelstore.de/z/kernel" | > < | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | //----------------------------------------------------------------------------- // 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 impl provides the kernel implementation. package impl import ( "fmt" "net" "os" "runtime" "sort" "sync" "time" "zettelstore.de/z/kernel" "zettelstore.de/z/strfun" ) type coreService struct { srvConfig started bool mxRecover sync.RWMutex mapRecover map[string]recoverInfo } type recoverInfo struct { count uint64 ts time.Time info interface{} stack []byte } func (cs *coreService) Initialize() { cs.mapRecover = make(map[string]recoverInfo) cs.descr = descriptionMap{ kernel.CoreDebug: {"Debug mode", parseBool, false}, kernel.CoreGoArch: {"Go processor architecture", nil, false}, kernel.CoreGoOS: {"Go Operating System", nil, false}, kernel.CoreGoVersion: {"Go Version", nil, false}, kernel.CoreHostname: {"Host name", nil, false}, |
︙ | ︙ | |||
81 82 83 84 85 86 87 | kernel.CoreVerbose: false, } if hn, err := os.Hostname(); err == nil { cs.next[kernel.CoreHostname] = hn } } | < < | > | 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | kernel.CoreVerbose: false, } if hn, err := os.Hostname(); err == nil { cs.next[kernel.CoreHostname] = hn } } func (cs *coreService) Start(*myKernel) error { cs.started = true return nil } func (cs *coreService) IsStarted() bool { return cs.started } func (cs *coreService) Stop(*myKernel) error { cs.started = false return nil } func (cs *coreService) GetStatistics() []kernel.KeyValue { cs.mxRecover.RLock() defer cs.mxRecover.RUnlock() names := make([]string, 0, len(cs.mapRecover)) for n := range cs.mapRecover { |
︙ | ︙ |
Changes to kernel/impl/impl.go.
︙ | ︙ | |||
8 9 10 11 12 13 14 | // under this license. //----------------------------------------------------------------------------- // Package impl provides the kernel implementation. package impl import ( | < > < < < < < | < < < < < | | < < < < < < | | | | < < < | | | | | | < | | 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | // under this license. //----------------------------------------------------------------------------- // Package impl provides the kernel implementation. package impl import ( "fmt" "io" "log" "net" "os" "os/signal" "runtime/debug" "strconv" "sync" "syscall" "zettelstore.de/z/kernel" ) // myKernel is the main internal kernel. type myKernel struct { // started bool wg sync.WaitGroup mx sync.RWMutex interrupt chan os.Signal core coreService cfg configService auth authService box boxService web webService srvs map[kernel.Service]serviceDescr srvNames map[string]serviceData depStart serviceDependency depStop serviceDependency // reverse of depStart } type serviceDescr struct { srv service name string } type serviceData struct { srv service srvnum kernel.Service } type serviceDependency map[kernel.Service][]kernel.Service // create and start a new kernel. func init() { kernel.Main = createAndStart() } // create and start a new kernel. func createAndStart() kernel.Kernel { kern := &myKernel{ interrupt: make(chan os.Signal, 5), } kern.srvs = map[kernel.Service]serviceDescr{ kernel.CoreService: {&kern.core, "core"}, kernel.ConfigService: {&kern.cfg, "config"}, kernel.AuthService: {&kern.auth, "auth"}, kernel.BoxService: {&kern.box, "box"}, kernel.WebService: {&kern.web, "web"}, } kern.srvNames = make(map[string]serviceData, len(kern.srvs)) for key, srvD := range kern.srvs { if _, ok := kern.srvNames[srvD.name]; ok { panic(fmt.Sprintf("Key %q already given for service %v", key, srvD.name)) } kern.srvNames[srvD.name] = serviceData{srvD.srv, key} srvD.srv.Initialize() } kern.depStart = serviceDependency{ kernel.CoreService: nil, kernel.ConfigService: {kernel.CoreService}, kernel.AuthService: {kernel.CoreService}, kernel.BoxService: {kernel.CoreService, kernel.ConfigService, kernel.AuthService}, kernel.WebService: {kernel.ConfigService, kernel.AuthService, kernel.BoxService}, |
︙ | ︙ | |||
116 117 118 119 120 121 122 | return kern } func (kern *myKernel) Start(headline, lineServer bool) { for _, srvD := range kern.srvs { srvD.srv.Freeze() } | < < < | < | | | | | | < | 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | return kern } func (kern *myKernel) Start(headline, lineServer bool) { for _, srvD := range kern.srvs { srvD.srv.Freeze() } kern.wg.Add(1) signal.Notify(kern.interrupt, os.Interrupt, syscall.SIGTERM) go func() { // Wait for interrupt. sig := <-kern.interrupt if strSig := sig.String(); strSig != "" { kern.doLog("Shut down Zettelstore:", strSig) } kern.doShutdown() kern.wg.Done() }() kern.StartService(kernel.CoreService) if headline { kern.doLog(fmt.Sprintf( "%v %v (%v@%v/%v)", kern.core.GetConfig(kernel.CoreProgname), kern.core.GetConfig(kernel.CoreVersion), kern.core.GetConfig(kernel.CoreGoVersion), kern.core.GetConfig(kernel.CoreGoOS), kern.core.GetConfig(kernel.CoreGoArch), )) kern.doLog("Licensed under the latest version of the EUPL (European Union Public License)") if kern.core.GetConfig(kernel.CoreDebug).(bool) { kern.doLog("-------------------------------------------------") kern.doLog("WARNING: DEBUG MODE, DO NO USE THIS IN PRODUCTION") kern.doLog("-------------------------------------------------") } if kern.auth.GetConfig(kernel.AuthReadonly).(bool) { kern.doLog("Read-only mode") } } if lineServer { port := kern.core.GetNextConfig(kernel.CorePort).(int) if port > 0 { listenAddr := net.JoinHostPort("127.0.0.1", strconv.Itoa(port)) startLineServer(kern, listenAddr) } } } func (kern *myKernel) doShutdown() { kern.StopService(kernel.CoreService) // Will stop all other services. } func (kern *myKernel) WaitForShutdown() { kern.wg.Wait() } // --- Shutdown operation ---------------------------------------------------- // Shutdown the service. Waits for all concurrent activity to stop. func (kern *myKernel) Shutdown(silent bool) { kern.interrupt <- &shutdownSignal{silent: silent} |
︙ | ︙ | |||
189 190 191 192 193 194 195 | } return "shutdown" } func (*shutdownSignal) Signal() { /* Just a signal */ } // --- Log operation --------------------------------------------------------- | < < < | | < | < | < < | | < | < | > < > < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | } return "shutdown" } func (*shutdownSignal) Signal() { /* Just a signal */ } // --- Log operation --------------------------------------------------------- // Log some activity. func (kern *myKernel) Log(args ...interface{}) { kern.mx.Lock() defer kern.mx.Unlock() kern.doLog(args...) } func (*myKernel) doLog(args ...interface{}) { log.Println(args...) } // LogRecover outputs some information about the previous panic. func (kern *myKernel) LogRecover(name string, recoverInfo interface{}) bool { return kern.doLogRecover(name, recoverInfo) } func (kern *myKernel) doLogRecover(name string, recoverInfo interface{}) bool { kern.Log(name, "recovered from:", recoverInfo) stack := debug.Stack() os.Stderr.Write(stack) kern.core.updateRecoverInfo(name, recoverInfo, stack) return true } // --- Service handling -------------------------------------------------- func (kern *myKernel) SetConfig(srvnum kernel.Service, key, value string) bool { kern.mx.Lock() defer kern.mx.Unlock() if srvD, ok := kern.srvs[srvnum]; ok { return srvD.srv.SetConfig(key, value) |
︙ | ︙ | |||
313 314 315 316 317 318 319 | kern.mx.RLock() defer kern.mx.RUnlock() if srvD, ok := kern.srvs[srvnum]; ok { return srvD.srv.GetConfigList(false) } return nil } | < < < < < < < < < < < < < < < < < < < < | 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 | kern.mx.RLock() defer kern.mx.RUnlock() if srvD, ok := kern.srvs[srvnum]; ok { return srvD.srv.GetConfigList(false) } return nil } func (kern *myKernel) GetServiceStatistics(srvnum kernel.Service) []kernel.KeyValue { kern.mx.RLock() defer kern.mx.RUnlock() if srvD, ok := kern.srvs[srvnum]; ok { return srvD.srv.GetStatistics() } return nil } func (kern *myKernel) StartService(srvnum kernel.Service) error { kern.mx.RLock() defer kern.mx.RUnlock() return kern.doStartService(srvnum) } func (kern *myKernel) doStartService(srvnum kernel.Service) error { for _, srv := range kern.sortDependency(srvnum, kern.depStart, true) { |
︙ | ︙ | |||
365 366 367 368 369 370 371 | kern.mx.RLock() defer kern.mx.RUnlock() return kern.doRestartService(srvnum) } func (kern *myKernel) doRestartService(srvnum kernel.Service) error { deps := kern.sortDependency(srvnum, kern.depStop, false) for _, srv := range deps { | | > > | | < | > > | 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | kern.mx.RLock() defer kern.mx.RUnlock() return kern.doRestartService(srvnum) } func (kern *myKernel) doRestartService(srvnum kernel.Service) error { deps := kern.sortDependency(srvnum, kern.depStop, false) for _, srv := range deps { if err := srv.Stop(kern); err != nil { return err } } for i := len(deps) - 1; i >= 0; i-- { srv := deps[i] if err := srv.Start(kern); err != nil { return err } srv.SwitchNextToCur() } return nil } func (kern *myKernel) StopService(srvnum kernel.Service) error { kern.mx.RLock() defer kern.mx.RUnlock() return kern.doStopService(srvnum) } func (kern *myKernel) doStopService(srvnum kernel.Service) error { for _, srv := range kern.sortDependency(srvnum, kern.depStop, false) { if err := srv.Stop(kern); err != nil { return err } } return nil } func (kern *myKernel) sortDependency( srvnum kernel.Service, srvdeps serviceDependency, |
︙ | ︙ | |||
416 417 418 419 420 421 422 | result = append(result, depSrv) found[depSrv] = true } } } return append(result, srvD.srv) } | < | < < < | 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 | result = append(result, depSrv) found[depSrv] = true } } } return append(result, srvD.srv) } func (kern *myKernel) DumpIndex(w io.Writer) { kern.box.DumpIndex(w) } type service interface { // Initialize the data for the service. Initialize() // ConfigDescriptions returns a sorted list of configuration descriptions. ConfigDescriptions() []serviceConfigDescription // SetConfig stores a configuration value. SetConfig(key, value string) bool |
︙ | ︙ | |||
462 463 464 465 466 467 468 | // SwitchNextToCur moves next config data to current. SwitchNextToCur() // IsStarted returns true if the service was started successfully. IsStarted() bool // Stop the service. | | | 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 | // SwitchNextToCur moves next config data to current. SwitchNextToCur() // IsStarted returns true if the service was started successfully. IsStarted() bool // Stop the service. Stop(*myKernel) error } type serviceConfigDescription struct{ Key, Descr string } func (kern *myKernel) SetCreators( createAuthManager kernel.CreateAuthManagerFunc, createBoxManager kernel.CreateBoxManagerFunc, setupWebServer kernel.SetupWebServerFunc, ) { kern.auth.createManager = createAuthManager kern.box.createManager = createBoxManager kern.web.setupServer = setupWebServer } |
Deleted kernel/impl/log.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to kernel/impl/server.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //----------------------------------------------------------------------------- // 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 impl import ( "bufio" "net" ) func startLineServer(kern *myKernel, listenAddr string) error { ln, err := net.Listen("tcp", listenAddr) if err != nil { | > | | | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | //----------------------------------------------------------------------------- // 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 impl provides the kernel implementation. package impl import ( "bufio" "net" ) func startLineServer(kern *myKernel, listenAddr string) error { ln, err := net.Listen("tcp", listenAddr) if err != nil { kern.doLog("Unable to start Line Command Server:", err) return err } kern.doLog("Start Line Command Server:", listenAddr) go func() { lineServer(ln, kern) }() return nil } func lineServer(ln net.Listener, kern *myKernel) { // Something may panic. Ensure a running line service. defer func() { if r := recover(); r != nil { kern.doLogRecover("Line", r) go lineServer(ln, kern) } }() for { conn, err := ln.Accept() if err != nil { // handle error kern.doLog("Unable to accept connection:", err) break } go handleLineConnection(conn, kern) } ln.Close() } func handleLineConnection(conn net.Conn, kern *myKernel) { // Something may panic. Ensure a running connection. defer func() { if r := recover(); r != nil { kern.doLogRecover("LineConn", r) go handleLineConnection(conn, kern) } }() cmds := cmdSession{} cmds.initialize(conn, kern) s := bufio.NewScanner(conn) for s.Scan() { line := s.Text() if !cmds.executeLine(line) { break } } conn.Close() } |
Changes to kernel/impl/web.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 | //----------------------------------------------------------------------------- // 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 impl import ( | > < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | //----------------------------------------------------------------------------- // 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 impl provides the kernel implementation. package impl import ( "net" "strconv" "sync" "time" "zettelstore.de/z/kernel" "zettelstore.de/z/web/server" "zettelstore.de/z/web/server/impl" ) type webService struct { srvConfig mxService sync.RWMutex |
︙ | ︙ | |||
37 38 39 40 41 42 43 | WebListenAddress = "listen" WebPersistentCookie = "persistent" WebTokenLifetimeAPI = "api-lifetime" WebTokenLifetimeHTML = "html-lifetime" WebURLPrefix = "prefix" ) | | < | 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | WebListenAddress = "listen" WebPersistentCookie = "persistent" WebTokenLifetimeAPI = "api-lifetime" WebTokenLifetimeHTML = "html-lifetime" WebURLPrefix = "prefix" ) func (ws *webService) Initialize() { ws.descr = descriptionMap{ kernel.WebListenAddress: { "Listen address", func(val string) interface{} { host, port, err := net.SplitHostPort(val) if err != nil { return nil |
︙ | ︙ | |||
102 103 104 105 106 107 108 | } return secs } return defDur } } | < < | | | | | < < < < < < < < < < | | | > | | 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | } return secs } return defDur } } func (ws *webService) Start(kern *myKernel) error { listenAddr := ws.GetNextConfig(kernel.WebListenAddress).(string) urlPrefix := ws.GetNextConfig(kernel.WebURLPrefix).(string) persistentCookie := ws.GetNextConfig(kernel.WebPersistentCookie).(bool) secureCookie := ws.GetNextConfig(kernel.WebSecureCookie).(bool) srvw := impl.New(listenAddr, urlPrefix, persistentCookie, secureCookie, kern.auth.manager) err := kern.web.setupServer(srvw, kern.box.manager, kern.auth.manager, kern.cfg.rtConfig) if err != nil { kern.doLog("Unable to create Web Server:", err) return err } if kern.core.GetConfig(kernel.CoreDebug).(bool) { srvw.SetDebug() } if err = srvw.Run(); err != nil { kern.doLog("Unable to start Web Service:", err) return err } kern.doLog("Start Web Service:", listenAddr) ws.mxService.Lock() ws.srvw = srvw ws.mxService.Unlock() return nil } func (ws *webService) IsStarted() bool { ws.mxService.RLock() defer ws.mxService.RUnlock() return ws.srvw != nil } func (ws *webService) Stop(kern *myKernel) error { kern.doLog("Stop Web Service") err := ws.srvw.Stop() ws.mxService.Lock() ws.srvw = nil ws.mxService.Unlock() return err } func (ws *webService) GetStatistics() []kernel.KeyValue { return nil } |
Changes to kernel/kernel.go.
︙ | ︙ | |||
10 11 12 13 14 15 16 | // Package kernel provides the main kernel service. package kernel import ( "io" "net/url" | < < < | | < < < < < < < < < < < < < < < < < < < < < < < < | 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | // Package kernel provides the main kernel service. package kernel import ( "io" "net/url" "zettelstore.de/z/auth" "zettelstore.de/z/box" "zettelstore.de/z/config" "zettelstore.de/z/domain/id" "zettelstore.de/z/web/server" ) // Kernel is the main internal service. type Kernel interface { // Start the service. Start(headline bool, lineServer bool) // WaitForShutdown blocks the call until Shutdown is called. WaitForShutdown() // Shutdown the service. Waits for all concurrent activities to stop. Shutdown(silent bool) // Log some activity. Log(args ...interface{}) // LogRecover outputs some information about the previous panic. LogRecover(name string, recoverInfo interface{}) bool // SetConfig stores a configuration value. SetConfig(srv Service, key, value string) bool // GetConfig returns a configuration value. GetConfig(srv Service, key string) interface{} // GetConfigList returns a sorted list of configuration data. GetConfigList(Service) []KeyDescrValue // StartService start the given service. StartService(Service) error // RestartService stops and restarts the given service, while maintaining service dependencies. RestartService(Service) error // StopService stop the given service. |
︙ | ︙ | |||
99 100 101 102 103 104 105 | // Unit is a type with just one value. type Unit struct{} // ShutdownChan is a channel used to signal a system shutdown. type ShutdownChan <-chan Unit | < < < < < < | 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | // Unit is a type with just one value. type Unit struct{} // ShutdownChan is a channel used to signal a system shutdown. type ShutdownChan <-chan Unit // Service specifies a service, e.g. web, ... type Service uint8 // Constants for type Service. const ( _ Service = iota CoreService |
︙ | ︙ | |||
131 132 133 134 135 136 137 | CoreHostname = "hostname" CorePort = "port" CoreProgname = "progname" CoreVerbose = "verbose" CoreVersion = "version" ) | < < < < < | 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | CoreHostname = "hostname" CorePort = "port" CoreProgname = "progname" CoreVerbose = "verbose" CoreVersion = "version" ) // Constants for authentication service keys. const ( AuthOwner = "owner" AuthReadonly = "readonly" ) // Constants for box service keys. |
︙ | ︙ | |||
170 171 172 173 174 175 176 | // KeyDescrValue is a triple of config data. type KeyDescrValue struct{ Key, Descr, Value string } // KeyValue is a pair of key and value. type KeyValue struct{ Key, Value string } | < < < < < < < < | 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | // KeyDescrValue is a triple of config data. type KeyDescrValue struct{ Key, Descr, Value string } // KeyValue is a pair of key and value. type KeyValue struct{ Key, Value string } // CreateAuthManagerFunc is called to create a new auth manager. type CreateAuthManagerFunc func(readonly bool, owner id.Zid) (auth.Manager, error) // CreateBoxManagerFunc is called to create a new box manager. type CreateBoxManagerFunc func( boxURIs []*url.URL, authManager auth.Manager, |
︙ | ︙ |
Deleted logger/logger.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted logger/logger_test.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Deleted logger/message.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to parser/none/none.go.
1 2 3 4 5 6 7 8 9 10 | //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- | | | > > > > > > | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | //----------------------------------------------------------------------------- // 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 none provides a none-parser for meta data. package none import ( "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/domain/meta" "zettelstore.de/z/input" "zettelstore.de/z/parser" ) func init() { parser.Register(&parser.Info{ Name: api.ValueSyntaxNone, AltNames: []string{}, IsTextParser: false, IsImageFormat: false, ParseBlocks: parseBlocks, ParseInlines: parseInlines, }) } func parseBlocks(_ *input.Input, m *meta.Meta, _ string) *ast.BlockListNode { descrlist := &ast.DescriptionListNode{} for _, p := range m.Pairs(true) { descrlist.Descriptions = append( descrlist.Descriptions, getDescription(p.Key, p.Value)) } return &ast.BlockListNode{List: []ast.BlockNode{descrlist}} } func getDescription(key, value string) ast.Description { return ast.Description{ Term: ast.CreateInlineListNode(&ast.TextNode{Text: key}), Descriptions: []ast.DescriptionSlice{{ &ast.ParaNode{ Inlines: convertToInlineList(value, meta.Type(key)), }}, }, } } func convertToInlineList(value string, dt *meta.DescriptionType) *ast.InlineListNode { var sliceData []string if dt.IsSet { sliceData = meta.ListFromValue(value) if len(sliceData) == 0 { return &ast.InlineListNode{} } } else { sliceData = []string{value} } var makeLink bool switch dt { case meta.TypeID, meta.TypeIDSet: makeLink = true } result := make([]ast.InlineNode, 0, 2*len(sliceData)-1) for i, val := range sliceData { if i > 0 { result = append(result, &ast.SpaceNode{Lexeme: " "}) } tn := &ast.TextNode{Text: val} if makeLink { result = append(result, &ast.LinkNode{ Ref: ast.ParseReference(val), Inlines: ast.CreateInlineListNode(tn), }) } else { result = append(result, tn) } } return ast.CreateInlineListNode(result...) } func parseInlines(inp *input.Input, _ string) *ast.InlineListNode { inp.SkipToEOL() return ast.CreateInlineListNode( &ast.FormatNode{ Kind: ast.FormatSpan, Attrs: &ast.Attributes{Attrs: map[string]string{"class": "warning"}}, Inlines: ast.CreateInlineListNodeFromWords( "parser.meta.ParseInlines:", "not", "possible", "("+string(inp.Src[0:inp.Pos])+")", ), }, ) } |
Changes to parser/parser.go.
︙ | ︙ | |||
9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //----------------------------------------------------------------------------- // Package parser provides a generic interface to a range of different parsers. package parser import ( "fmt" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/config" "zettelstore.de/z/domain" "zettelstore.de/z/domain/meta" "zettelstore.de/z/input" | > | 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | //----------------------------------------------------------------------------- // Package parser provides a generic interface to a range of different parsers. package parser import ( "fmt" "log" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/config" "zettelstore.de/z/domain" "zettelstore.de/z/domain/meta" "zettelstore.de/z/input" |
︙ | ︙ | |||
66 67 68 69 70 71 72 | func Get(name string) *Info { if pi := registry[name]; pi != nil { return pi } if pi := registry["plain"]; pi != nil { return pi } | | > | 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | func Get(name string) *Info { if pi := registry[name]; pi != nil { return pi } if pi := registry["plain"]; pi != nil { return pi } log.Printf("No parser for %q found", name) panic("No default parser registered") } // IsTextParser returns whether the given syntax parses text into an AST or not. func IsTextParser(syntax string) bool { pi, ok := registry[syntax] if !ok { return false |
︙ | ︙ | |||
125 126 127 128 129 130 131 | } return &ast.ZettelNode{ Meta: m, Content: zettel.Content, Zid: m.Zid, InhMeta: inhMeta, Ast: ParseBlocks(input.NewInput(zettel.Content.AsBytes()), parseMeta, syntax), | < | 127 128 129 130 131 132 133 134 135 | } return &ast.ZettelNode{ Meta: m, Content: zettel.Content, Zid: m.Zid, InhMeta: inhMeta, Ast: ParseBlocks(input.NewInput(zettel.Content.AsBytes()), parseMeta, syntax), } } |
Changes to parser/zettelmark/inline.go.
︙ | ︙ | |||
66 67 68 69 70 71 72 | if inp.Ch == '{' { in, success = cp.parseEmbed() } case '#': return cp.parseTag() case '%': in, success = cp.parseComment() | | | 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | if inp.Ch == '{' { in, success = cp.parseEmbed() } case '#': return cp.parseTag() case '%': in, success = cp.parseComment() case '/', '_', '*', '>', '~', '\'', '^', ',', '<', '"', ';', ':': in, success = cp.parseFormat() case '+', '`', '=', runeModGrave: in, success = cp.parseLiteral() case '\\': return cp.parseBackslash() case '-': in, success = cp.parseNdash() |
︙ | ︙ | |||
96 97 98 99 100 101 102 | return cp.parseTextBackslash() } for { inp.Next() switch inp.Ch { // The following case must contain all runes that occur in parseInline! // Plus the closing brackets ] and } and ) and the middle | | | | 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | return cp.parseTextBackslash() } for { inp.Next() switch inp.Ch { // The following case must contain all runes that occur in parseInline! // Plus the closing brackets ] and } and ) and the middle | case '/', input.EOS, '\n', '\r', ' ', '\t', '[', ']', '{', '}', '(', ')', '|', '#', '%', '_', '*', '>', '~', '\'', '^', ',', '<', '"', ';', ':', '+', '`', runeModGrave, '=', '\\', '-', '&': return &ast.TextNode{Text: string(inp.Src[pos:inp.Pos])} } } } func (cp *zmkP) parseTextBackslash() *ast.TextNode { cp.inp.Next() |
︙ | ︙ | |||
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 | return &ast.LiteralNode{Kind: ast.LiteralComment, Text: string(inp.Src[pos:inp.Pos])}, true } inp.Next() } } var mapRuneFormat = map[rune]ast.FormatKind{ '_': ast.FormatEmph, '*': ast.FormatStrong, '>': ast.FormatInsert, '~': ast.FormatDelete, '\'': ast.FormatMonospace, '^': ast.FormatSuper, ',': ast.FormatSub, '<': ast.FormatQuotation, '"': ast.FormatQuote, ':': ast.FormatSpan, } func (cp *zmkP) parseFormat() (res ast.InlineNode, success bool) { inp := cp.inp fch := inp.Ch kind, ok := mapRuneFormat[fch] | > > | 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | return &ast.LiteralNode{Kind: ast.LiteralComment, Text: string(inp.Src[pos:inp.Pos])}, true } inp.Next() } } var mapRuneFormat = map[rune]ast.FormatKind{ '/': ast.FormatEmphDeprecated, '_': ast.FormatEmph, '*': ast.FormatStrong, '>': ast.FormatInsert, '~': ast.FormatDelete, '\'': ast.FormatMonospace, '^': ast.FormatSuper, ',': ast.FormatSub, '<': ast.FormatQuotation, '"': ast.FormatQuote, ';': ast.FormatSmall, ':': ast.FormatSpan, } func (cp *zmkP) parseFormat() (res ast.InlineNode, success bool) { inp := cp.inp fch := inp.Ch kind, ok := mapRuneFormat[fch] |
︙ | ︙ |
Changes to parser/zettelmark/zettelmark_test.go.
︙ | ︙ | |||
300 301 302 303 304 305 306 | {"100%", "(PARA 100%)"}, }) } func TestFormat(t *testing.T) { t.Parallel() // Not for Insert / '>', because collision with quoted list | | | | 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | {"100%", "(PARA 100%)"}, }) } func TestFormat(t *testing.T) { t.Parallel() // Not for Insert / '>', because collision with quoted list for _, ch := range []string{"_", "*", "~", "'", "^", ",", "<", "\"", ";", ":"} { checkTcs(t, replace(ch, TestCases{ {"$", "(PARA $)"}, {"$$", "(PARA $$)"}, {"$$$", "(PARA $$$)"}, {"$$$$", "(PARA {$})"}, })) } for _, ch := range []string{"_", "*", ">", "~", "'", "^", ",", "<", "\"", ";", ":"} { checkTcs(t, replace(ch, TestCases{ {"$$a$$", "(PARA {$ a})"}, {"$$a$$$", "(PARA {$ a} $)"}, {"$$$a$$", "(PARA {$ $a})"}, {"$$$a$$$", "(PARA {$ $a} $)"}, {"$\\$", "(PARA $$)"}, {"$\\$$", "(PARA $$$)"}, |
︙ | ︙ | |||
901 902 903 904 905 906 907 908 909 910 911 912 913 914 | ast.FormatInsert: '>', ast.FormatDelete: '~', ast.FormatMonospace: '\'', ast.FormatSuper: '^', ast.FormatSub: ',', ast.FormatQuote: '"', ast.FormatQuotation: '<', ast.FormatSpan: ':', } var mapLiteralKind = map[ast.LiteralKind]rune{ ast.LiteralProg: '`', ast.LiteralKeyb: '+', ast.LiteralOutput: '=', | > | 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 | ast.FormatInsert: '>', ast.FormatDelete: '~', ast.FormatMonospace: '\'', ast.FormatSuper: '^', ast.FormatSub: ',', ast.FormatQuote: '"', ast.FormatQuotation: '<', ast.FormatSmall: ';', ast.FormatSpan: ':', } var mapLiteralKind = map[ast.LiteralKind]rune{ ast.LiteralProg: '`', ast.LiteralKeyb: '+', ast.LiteralOutput: '=', |
︙ | ︙ |
Added search/compile.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 | //----------------------------------------------------------------------------- // 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 search provides a zettel search. package search // This file is about "compiling" a search expression into a function. import ( "fmt" "strings" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" "zettelstore.de/z/strfun" ) func compileFullSearch(searcher Searcher, search []expValue) MetaMatchFunc { normSearch := compileNormalizedSearch(searcher, search) plainSearch := compilePlainSearch(searcher, search) if normSearch == nil { if plainSearch == nil { return nil } return plainSearch } if plainSearch == nil { return normSearch } return func(m *meta.Meta) bool { return normSearch(m) || plainSearch(m) } } func compileNormalizedSearch(searcher Searcher, search []expValue) MetaMatchFunc { var positives, negatives []expValue posSet := make(map[string]bool) negSet := make(map[string]bool) for _, val := range search { for _, word := range strfun.NormalizeWords(val.value) { if val.negate { if _, ok := negSet[word]; !ok { negSet[word] = true negatives = append(negatives, expValue{ value: word, op: val.op, negate: true, }) } } else { if _, ok := posSet[word]; !ok { posSet[word] = true positives = append(positives, expValue{ value: word, op: val.op, negate: false, }) } } } } return compileSearch(searcher, positives, negatives) } func compilePlainSearch(searcher Searcher, search []expValue) MetaMatchFunc { var positives, negatives []expValue for _, val := range search { if val.negate { negatives = append(negatives, expValue{ value: strings.ToLower(strings.TrimSpace(val.value)), op: val.op, negate: true, }) } else { positives = append(positives, expValue{ value: strings.ToLower(strings.TrimSpace(val.value)), op: val.op, negate: false, }) } } return compileSearch(searcher, positives, negatives) } func compileSearch(searcher Searcher, poss, negs []expValue) MetaMatchFunc { if len(poss) == 0 { if len(negs) == 0 { return nil } return makeNegOnlySearch(searcher, negs) } if len(negs) == 0 { return makePosOnlySearch(searcher, poss) } return makePosNegSearch(searcher, poss, negs) } func makePosOnlySearch(searcher Searcher, poss []expValue) MetaMatchFunc { retrievePos := compileRetrieveZids(searcher, poss) var ids id.Set return func(m *meta.Meta) bool { if ids == nil { ids = retrievePos() } _, ok := ids[m.Zid] return ok } } func makeNegOnlySearch(searcher Searcher, negs []expValue) MetaMatchFunc { retrieveNeg := compileRetrieveZids(searcher, negs) var ids id.Set return func(m *meta.Meta) bool { if ids == nil { ids = retrieveNeg() } _, ok := ids[m.Zid] return !ok } } func makePosNegSearch(searcher Searcher, poss, negs []expValue) MetaMatchFunc { retrievePos := compileRetrieveZids(searcher, poss) retrieveNeg := compileRetrieveZids(searcher, negs) var ids id.Set return func(m *meta.Meta) bool { if ids == nil { ids = retrievePos() ids.Remove(retrieveNeg()) } _, okPos := ids[m.Zid] return okPos } } func compileRetrieveZids(searcher Searcher, values []expValue) func() id.Set { selFuncs := make([]selectorFunc, 0, len(values)) stringVals := make([]string, 0, len(values)) for _, val := range values { selFuncs = append(selFuncs, compileSelectOp(searcher, val.op)) stringVals = append(stringVals, val.value) } if len(selFuncs) == 0 { return func() id.Set { return id.NewSet() } } if len(selFuncs) == 1 { return func() id.Set { return selFuncs[0](stringVals[0]) } } return func() id.Set { result := selFuncs[0](stringVals[0]) for i, f := range selFuncs[1:] { result = result.Intersect(f(stringVals[i+1])) } return result } } type selectorFunc func(string) id.Set func compileSelectOp(searcher Searcher, op compareOp) selectorFunc { switch op { case cmpDefault, cmpContains: return searcher.SearchContains case cmpEqual: return searcher.SearchEqual case cmpPrefix: return searcher.SearchPrefix case cmpSuffix: return searcher.SearchSuffix default: panic(fmt.Sprintf("Unexpected value of comparison operation: %v", op)) } } |
Changes to search/print.go.
︙ | ︙ | |||
11 12 13 14 15 16 17 | // Package search provides a zettel search. package search import ( "io" "sort" "strconv" | < < < < < < < < < < | 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | // Package search provides a zettel search. package search import ( "io" "sort" "strconv" "zettelstore.de/c/api" ) // Print the search to a writer. func (s *Search) Print(w io.Writer) { if s.negate { io.WriteString(w, "NOT (") } space := false if len(s.search) > 0 { io.WriteString(w, "ANY") printSelectExprValues(w, s.search) |
︙ | ︙ | |||
54 55 56 57 58 59 60 | space = true } if s.negate { io.WriteString(w, ")") space = true } | > > > > > > > > > > > | > > > > > | > > > > > | > > | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | | 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | space = true } if s.negate { io.WriteString(w, ")") space = true } if ord := s.order; len(ord) > 0 { switch ord { case api.KeyID: // Ignore case RandomOrder: space = printSpace(w, space) io.WriteString(w, "RANDOM") default: space = printSpace(w, space) io.WriteString(w, "SORT ") io.WriteString(w, ord) if s.descending { io.WriteString(w, " DESC") } } } if off := s.offset; off > 0 { space = printSpace(w, space) io.WriteString(w, "OFFSET ") io.WriteString(w, strconv.Itoa(off)) } if lim := s.limit; lim > 0 { _ = printSpace(w, space) io.WriteString(w, "LIMIT ") io.WriteString(w, strconv.Itoa(lim)) } } func printSelectExprValues(w io.Writer, values []expValue) { if len(values) == 0 { io.WriteString(w, " MATCH ANY") return } for j, val := range values { if j > 0 { io.WriteString(w, " AND") } if val.negate { io.WriteString(w, " NOT") } switch val.op { case cmpDefault: io.WriteString(w, " MATCH ") case cmpEqual: io.WriteString(w, " HAS ") case cmpPrefix: io.WriteString(w, " PREFIX ") case cmpSuffix: io.WriteString(w, " SUFFIX ") case cmpContains: io.WriteString(w, " CONTAINS ") default: io.WriteString(w, " MaTcH ") } if val.value == "" { io.WriteString(w, "ANY") } else { io.WriteString(w, val.value) } } } func printSpace(w io.Writer, space bool) bool { if space { io.WriteString(w, " ") } return true } |
Deleted search/retrieve.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to search/search.go.
︙ | ︙ | |||
40 41 42 43 44 45 46 | // The string must be normalized through Unicode NKFD, trimmed and not empty. SearchContains(s string) id.Set } // MetaMatchFunc is a function determine whethe some metadata should be selected or not. type MetaMatchFunc func(*meta.Meta) bool | < < < < < < | 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | // The string must be normalized through Unicode NKFD, trimmed and not empty. SearchContains(s string) id.Set } // MetaMatchFunc is a function determine whethe some metadata should be selected or not. type MetaMatchFunc func(*meta.Meta) bool // Search specifies a mechanism for selecting zettel. type Search struct { mx sync.RWMutex // Protects other attributes // Fields to be used for selecting preMatch MetaMatchFunc // Match that must be true tags expTagValues // Expected values for a tag |
︙ | ︙ | |||
71 72 73 74 75 76 77 | // RandomOrder is a pseudo metadata key that selects a random order. const RandomOrder = "_random" type compareOp uint8 const ( | < | < < < < < < < < < < < < < < < < < < < < < < < < | | | | < | 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | // RandomOrder is a pseudo metadata key that selects a random order. const RandomOrder = "_random" type compareOp uint8 const ( cmpDefault compareOp = iota cmpEqual cmpPrefix cmpSuffix cmpContains ) type expValue struct { value string op compareOp negate bool } // AddExpr adds a match expression to the search. func (s *Search) AddExpr(key, val string) *Search { val, negate, op := parseOp(strings.TrimSpace(val)) if s == nil { s = new(Search) } s.mx.Lock() defer s.mx.Unlock() if key == "" { s.search = append(s.search, expValue{value: val, op: op, negate: negate}) } else if s.tags == nil { s.tags = expTagValues{key: {{value: val, op: op, negate: negate}}} } else { s.tags[key] = append(s.tags[key], expValue{value: val, op: op, negate: negate}) } return s } func parseOp(s string) (r string, negate bool, op compareOp) { if s == "" { return s, false, cmpDefault |
︙ | ︙ | |||
252 253 254 255 256 257 258 | } s.mx.RLock() defer s.mx.RUnlock() return s.limit } // EnrichNeeded returns true, if the search references a metadata key that | | > | < < | < < < < | < < < < < < < < | | < | | < > | | > > | > > > > | > | | > | | > | | | < < | > | | < < < < < < | < | < < < | | < | < < < < | | | < < | | < | > | | | | | < | > > > > | | < > | | > | < < | 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | } s.mx.RLock() defer s.mx.RUnlock() return s.limit } // EnrichNeeded returns true, if the search references a metadata key that // is calculated via metadata enrichments. In most cases this is a computed // value. Metadata "tags" is an exception to this rule. func (s *Search) EnrichNeeded() bool { if s == nil { return false } s.mx.RLock() defer s.mx.RUnlock() for key := range s.tags { if meta.IsComputed(key) || key == api.KeyTags { return true } } if order := s.order; order != "" && (meta.IsComputed(order) || order == api.KeyTags) { return true } return false } // CompileMatch returns a function to match meta data based on select specification. func (s *Search) CompileMatch(searcher Searcher) MetaMatchFunc { if s == nil { return selectNone } s.mx.Lock() defer s.mx.Unlock() compMeta := compileSelect(s.tags) compSearch := compileFullSearch(searcher, s.search) if preMatch := s.preMatch; preMatch != nil { return compilePreMatch(preMatch, compMeta, compSearch, s.negate) } return compileNoPreMatch(compMeta, compSearch, s.negate) } func selectNone(*meta.Meta) bool { return true } func compilePreMatch(preMatch, compMeta, compSearch MetaMatchFunc, negate bool) MetaMatchFunc { if compMeta == nil { if compSearch == nil { return preMatch } if negate { return func(m *meta.Meta) bool { return preMatch(m) && !compSearch(m) } } return func(m *meta.Meta) bool { return preMatch(m) && compSearch(m) } } if compSearch == nil { if negate { return func(m *meta.Meta) bool { return preMatch(m) && !compMeta(m) } } return func(m *meta.Meta) bool { return preMatch(m) && compMeta(m) } } if negate { return func(m *meta.Meta) bool { return preMatch(m) && (!compMeta(m) || !compSearch(m)) } } return func(m *meta.Meta) bool { return preMatch(m) && compMeta(m) && compSearch(m) } } func compileNoPreMatch(compMeta, compSearch MetaMatchFunc, negate bool) MetaMatchFunc { if compMeta == nil { if compSearch == nil { if negate { return func(m *meta.Meta) bool { return false } } return selectNone } if negate { return func(m *meta.Meta) bool { return !compSearch(m) } } return compSearch } if compSearch == nil { if negate { return func(m *meta.Meta) bool { return !compMeta(m) } } return compMeta } if negate { return func(m *meta.Meta) bool { return !compMeta(m) || !compSearch(m) } } return func(m *meta.Meta) bool { return compMeta(m) && compSearch(m) } } // Sort applies the sorter to the slice of meta data. func (s *Search) Sort(metaList []*meta.Meta) []*meta.Meta { if len(metaList) == 0 { return metaList } |
︙ | ︙ | |||
384 385 386 387 388 389 390 | if s.offset > 0 { if s.offset > len(metaList) { return nil } metaList = metaList[s.offset:] } | < < < < < < < < | | 331 332 333 334 335 336 337 338 339 340 341 342 | if s.offset > 0 { if s.offset > len(metaList) { return nil } metaList = metaList[s.offset:] } if s.limit > 0 && s.limit < len(metaList) { metaList = metaList[:s.limit] } return metaList } |
Changes to search/select.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 | //----------------------------------------------------------------------------- // 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 search import ( | > < > | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | //----------------------------------------------------------------------------- // 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 search provides a zettel search. package search import ( "strings" "zettelstore.de/c/api" "zettelstore.de/z/domain/meta" ) type matchFunc func(value string) bool func matchNever(string) bool { return false } func matchAlways(string) bool { return true } type matchSpec struct { key string match matchFunc } // compileSelect calculates a selection func based on the given select criteria. func compileSelect(tags expTagValues) MetaMatchFunc { posSpecs, negSpecs, nomatch := createSelectSpecs(tags) if len(posSpecs) > 0 || len(negSpecs) > 0 || len(nomatch) > 0 { return makeSearchMetaMatchFunc(posSpecs, negSpecs, nomatch) } return nil } func createSelectSpecs(tags map[string][]expValue) (posSpecs, negSpecs []matchSpec, nomatch []string) { posSpecs = make([]matchSpec, 0, len(tags)) negSpecs = make([]matchSpec, 0, len(tags)) for key, values := range tags { if !meta.KeyIsValid(key) { continue } if always, never := countEmptyValues(values); always+never > 0 { if never == 0 { posSpecs = append(posSpecs, matchSpec{key, matchAlways}) continue } if always == 0 { negSpecs = append(negSpecs, matchSpec{key, nil}) continue } // value must match always AND never, at the same time. This results in a no-match. |
︙ | ︙ | |||
65 66 67 68 69 70 71 | } } return posSpecs, negSpecs, nomatch } func countEmptyValues(values []expValue) (always, never int) { for _, v := range values { | | > > | | | | < | | | | < < < < < | | | < < < < < < < < > | > | > | < | > > | | | > > < | | | | > | > | | > > > > > > > > > > | | | > | > > | > | | < | < < < < < < | < < | | < < < < < | | | | | > > > > > > > > > > > > > > > > > | | | > > > > > > > | > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > < < | < < < < < < < < < < < | < < < < < < | | < | < | 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | } } return posSpecs, negSpecs, nomatch } func countEmptyValues(values []expValue) (always, never int) { for _, v := range values { if v.value != "" { continue } if v.negate { never++ } else { always++ } } return always, never } func createPosNegMatchFunc(key string, values []expValue) (posMatch, negMatch matchFunc) { posValues := make([]opValue, 0, len(values)) negValues := make([]opValue, 0, len(values)) for _, val := range values { if val.negate { negValues = append(negValues, opValue{value: val.value, op: val.op}) } else { posValues = append(posValues, opValue{value: val.value, op: val.op}) } } return createMatchFunc(key, posValues), createMatchFunc(key, negValues) } // opValue is an expValue, but w/o the field "negate" type opValue struct { value string op compareOp } func createMatchFunc(key string, values []opValue) matchFunc { if len(values) == 0 { return nil } switch meta.Type(key) { case meta.TypeBool: return createMatchBoolFunc(values) case meta.TypeCredential: return matchNever case meta.TypeID, meta.TypeTimestamp: // ID and timestamp use the same layout return createMatchIDFunc(values) case meta.TypeIDSet: return createMatchIDSetFunc(values) case meta.TypeTagSet: return createMatchTagSetFunc(values) case meta.TypeWord: return createMatchWordFunc(values) case meta.TypeWordSet: return createMatchWordSetFunc(values) } return createMatchStringFunc(values) } func createMatchBoolFunc(values []opValue) matchFunc { preValues := make([]bool, 0, len(values)) for _, v := range values { preValues = append(preValues, meta.BoolValue(v.value)) } return func(value string) bool { bValue := meta.BoolValue(value) for _, v := range preValues { if bValue != v { return false } } return true } } func createMatchIDFunc(values []opValue) matchFunc { return func(value string) bool { for _, v := range values { if !strings.HasPrefix(value, v.value) { return false } } return true } } func createMatchIDSetFunc(values []opValue) matchFunc { idValues := preprocessSet(sliceToLower(values)) return func(value string) bool { ids := meta.ListFromValue(value) for _, neededIDs := range idValues { for _, neededID := range neededIDs { if !matchAllID(ids, neededID.value) { return false } } } return true } } func matchAllID(zettelIDs []string, neededID string) bool { for _, zt := range zettelIDs { if strings.HasPrefix(zt, neededID) { return true } } return false } func createMatchTagSetFunc(values []opValue) matchFunc { tagValues := processTagSet(preprocessSet(sliceToLower(values))) return func(value string) bool { tags := meta.ListFromValue(value) // Remove leading '#' from each tag for i, tag := range tags { tags[i] = meta.CleanTag(tag) } for _, neededTags := range tagValues { for _, neededTag := range neededTags { if !matchAllTag(tags, neededTag.value, neededTag.equal) { return false } } } return true } } type tagQueryValue struct { value string equal bool // not equal == prefix } func processTagSet(valueSet [][]opValue) [][]tagQueryValue { result := make([][]tagQueryValue, len(valueSet)) for i, values := range valueSet { tags := make([]tagQueryValue, len(values)) for j, val := range values { if tval := val.value; tval != "" && tval[0] == '#' { tval = meta.CleanTag(tval) tags[j] = tagQueryValue{value: tval, equal: true} } else { tags[j] = tagQueryValue{value: tval, equal: false} } } result[i] = tags } return result } func matchAllTag(zettelTags []string, neededTag string, equal bool) bool { if equal { for _, zt := range zettelTags { if zt == neededTag { return true } } } else { for _, zt := range zettelTags { if strings.HasPrefix(zt, neededTag) { return true } } } return false } func createMatchWordFunc(values []opValue) matchFunc { values = sliceToLower(values) return func(value string) bool { value = strings.ToLower(value) for _, v := range values { if value != v.value { return false } } return true } } func createMatchWordSetFunc(values []opValue) matchFunc { wordValues := preprocessSet(sliceToLower(values)) return func(value string) bool { words := meta.ListFromValue(value) for _, neededWords := range wordValues { for _, neededWord := range neededWords { if !matchAllWord(words, neededWord.value) { return false } } } return true } } func createMatchStringFunc(values []opValue) matchFunc { values = sliceToLower(values) return func(value string) bool { value = strings.ToLower(value) for _, v := range values { if !strings.Contains(value, v.value) { return false } } return true } } func makeSearchMetaMatchFunc(posSpecs, negSpecs []matchSpec, nomatch []string) MetaMatchFunc { return func(m *meta.Meta) bool { for _, key := range nomatch { if _, ok := getMeta(m, key); ok { return false } } for _, s := range posSpecs { if value, ok := getMeta(m, s.key); !ok || !s.match(value) { return false } } for _, s := range negSpecs { if s.match == nil { if _, ok := m.Get(s.key); ok { return false } } else if value, ok := getMeta(m, s.key); !ok || s.match(value) { return false } } return true } } func getMeta(m *meta.Meta, key string) (string, bool) { if key == api.KeyTags { return m.Get(api.KeyAllTags) } return m.Get(key) } func sliceToLower(sl []opValue) []opValue { result := make([]opValue, 0, len(sl)) for _, s := range sl { result = append(result, opValue{ value: strings.ToLower(s.value), |
︙ | ︙ | |||
286 287 288 289 290 291 292 | if len(valueElems) > 0 { result = append(result, valueElems) } } return result } | < | < < < < < < < < < < < < < < < < < < < < < < < < < < < | < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | | < < < < | < < < < < < < | | < < < < < < | 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | if len(valueElems) > 0 { result = append(result, valueElems) } } return result } func matchAllWord(zettelWords []string, neededWord string) bool { for _, zw := range zettelWords { if zw == neededWord { return true } } return false } |
Deleted search/select_test.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to strfun/escape.go.
1 | //----------------------------------------------------------------------------- | | | < < | < < < < < < < < | | | < | < < < < < | < < < | < < < > | > > > > > > > > > > > > | < > > > > > > > > > > > > | > > | > | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | //----------------------------------------------------------------------------- // Copyright (c) 2020 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 strfun provides some string functions. package strfun import "io" var ( htmlQuot = []byte(""") // shorter than "&39;", but often requested in standards htmlAmp = []byte("&") htmlLt = []byte("<") htmlGt = []byte(">") htmlNull = []byte("\uFFFD") htmlVisSpace = []byte("\u2423") ) // HTMLEscape writes to w the escaped HTML equivalent of the given string. // If visibleSpace is true, each space is written as U-2423. func HTMLEscape(w io.Writer, s string, visibleSpace bool) { last := 0 var html []byte lenS := len(s) for i := 0; i < lenS; i++ { switch s[i] { case '\000': html = htmlNull case ' ': if visibleSpace { html = htmlVisSpace } else { continue } case '"': html = htmlQuot case '&': html = htmlAmp case '<': html = htmlLt case '>': html = htmlGt default: continue } io.WriteString(w, s[last:i]) w.Write(html) last = i + 1 } io.WriteString(w, s[last:]) } // HTMLAttrEscape writes to w the escaped HTML equivalent of the given string to be used // in attributes. func HTMLAttrEscape(w io.Writer, s string) { last := 0 var html []byte lenS := len(s) for i := 0; i < lenS; i++ { switch s[i] { case '\000': html = htmlNull case '"': html = htmlQuot case '&': html = htmlAmp default: continue } io.WriteString(w, s[last:i]) w.Write(html) last = i + 1 } |
︙ | ︙ |
Changes to template/mustache.go.
1 | //----------------------------------------------------------------------------- | | | 1 2 3 4 5 6 7 8 9 | //----------------------------------------------------------------------------- // 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. // |
︙ | ︙ | |||
597 598 599 600 601 602 603 | if err != nil { return err } if val.IsValid() { if n.raw { fmt.Fprint(w, val.Interface()) } else { | > | | 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 | if err != nil { return err } if val.IsValid() { if n.raw { fmt.Fprint(w, val.Interface()) } else { s := fmt.Sprint(val.Interface()) strfun.HTMLEscape(w, s, false) } } case *sectionNode: if err := tmpl.renderSection(w, n, stack); err != nil { return err } case *partialNode: |
︙ | ︙ |
Changes to testdata/testbox/20210629163300.zettel.
1 | id: 20210629163300 | | | < | 1 2 3 4 5 6 7 8 | id: 20210629163300 title: owner role: user tags: #test #user syntax: none credential: $2a$10$gcKyVmQ50fwgpOjyiiCm4eba/ILrNXoxTUCopgTEnYTa4yuceHMC6 modified: 20210629173617 user-id: owner |
Changes to testdata/testbox/20210629165000.zettel.
1 | id: 20210629165000 | | | < | 1 2 3 4 5 6 7 8 9 | id: 20210629165000 title: writer role: user tags: #test #user syntax: none credential: $2a$10$VmHPyXa0Bm8DE4MJ.pQnbuuQmweWtyGya0L/bFA4nIuCn1EvPQflK modified: 20210629173536 user-id: writer user-role: writer |
Changes to testdata/testbox/20210629165024.zettel.
1 | id: 20210629165024 | | | < | 1 2 3 4 5 6 7 8 9 | id: 20210629165024 title: reader role: user tags: #test #user syntax: none credential: $2a$10$uC7LV2JdFhasw2HqSWZbSOihvFpwtaEXjXp98yzGfE3FHudq.vg.u modified: 20210629173459 user-id: reader user-role: reader |
Changes to testdata/testbox/20210629165050.zettel.
1 | id: 20210629165050 | | | < | 1 2 3 4 5 6 7 8 9 | id: 20210629165050 title: creator role: user tags: #test #user syntax: none credential: $2a$10$z85253tqhbHlXPZpt0hJpughLR4WXY8iYJbm1LlBhrKsL1YfkRy2q modified: 20210629173424 user-id: creator user-role: creator |
Changes to testdata/testbox/20211019200500.zettel.
1 2 3 4 | id: 20211019200500 title: Collection of all users role: zettel syntax: zmk | < | | | | | 1 2 3 4 5 6 7 8 9 | id: 20211019200500 title: Collection of all users role: zettel syntax: zmk * [[owner|20210629163300]] * [[writer|20210629165000]] * [[reader|20210629165024]] * [[creator|20210629165050]] |
Changes to testdata/testbox/20211020185400.zettel.
1 2 3 4 | id: 20211020185400 title: Self embed zettel role: zettel syntax: zmk | | | | 1 2 3 4 5 6 7 8 | id: 20211020185400 title: Self embed zettel role: zettel syntax: zmk modified: 20211020185512 {{#mark}} [!mark] ABC |
Changes to tests/client/client_test.go.
1 | //----------------------------------------------------------------------------- | | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | //----------------------------------------------------------------------------- // Copyright (c) 2021 Detlef Stern // // This file is part of zettelstore-client. // // 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. //----------------------------------------------------------------------------- // Package client provides a client for accessing the Zettelstore via its API. package client_test import ( "context" "flag" "fmt" "net/url" "strconv" "testing" "zettelstore.de/c/api" "zettelstore.de/c/client" ) |
︙ | ︙ | |||
44 45 46 47 48 49 50 | } } } func TestListZettel(t *testing.T) { const ( | | | | | | | | 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | } } } func TestListZettel(t *testing.T) { const ( ownerZettel = 46 configRoleZettel = 27 writerZettel = ownerZettel - 23 readerZettel = ownerZettel - 23 creatorZettel = 10 publicZettel = 7 ) testdata := []struct { user string exp int }{ {"", publicZettel}, |
︙ | ︙ | |||
93 94 95 96 97 98 99 | return } expQ := "role MATCH configuration" if q != expQ { t.Errorf("Query should be %q, but is %q", expQ, q) } got := len(l) | | | 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | return } expQ := "role MATCH configuration" if q != expQ { t.Errorf("Query should be %q, but is %q", expQ, q) } got := len(l) if got != 27 { 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}}) if err != nil { t.Error(err) return |
︙ | ︙ | |||
292 293 294 295 296 297 298 | t.Errorf("Expected 1 local link, got %d", got) } if got := len(zl.Linked.External); got != 4 { t.Errorf("Expected 4 external link, got %d", got) } } | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | t.Errorf("Expected 1 local link, got %d", got) } if got := len(zl.Linked.External); got != 4 { t.Errorf("Expected 4 external link, got %d", got) } } func TestListTags(t *testing.T) { t.Parallel() c := getClient() c.SetAuth("owner", "owner") tm, err := c.ListTags(context.Background()) if err != nil { t.Error(err) |
︙ | ︙ |
Changes to tests/client/crud_test.go.
︙ | ︙ | |||
90 91 92 93 94 95 96 | doDelete(t, c, newZid) } func TestCreateGetDeleteZettelJSON(t *testing.T) { // Is not to be allowed to run in parallel with other tests. c := getClient() c.SetAuth("owner", "owner") | < | < < < < | 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | doDelete(t, c, newZid) } func TestCreateGetDeleteZettelJSON(t *testing.T) { // Is not to be allowed to run in parallel with other tests. c := getClient() c.SetAuth("owner", "owner") zid, err := c.CreateZettelJSON(context.Background(), &api.ZettelDataJSON{ Meta: api.ZettelMeta{ api.KeyTitle: "A\nTitle", // \n must be converted into a space }, }) if err != nil { t.Error("Cannot create zettel:", err) return } z, err := c.GetZettelJSON(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 { t.Errorf("Expected title %q, but got %q", exp, got) } } doDelete(t, c, zid) } func TestUpdateZettel(t *testing.T) { c := getClient() c.SetAuth("owner", "owner") |
︙ | ︙ | |||
164 165 166 167 168 169 170 | } if got := z.Meta[api.KeyTitle]; got != "Home" { t.Errorf("Title of zettel is not \"Home\", but %q", got) return } newTitle := "New Home" z.Meta[api.KeyTitle] = newTitle | < < < < < | 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | } if got := z.Meta[api.KeyTitle]; got != "Home" { t.Errorf("Title of zettel is not \"Home\", but %q", got) return } newTitle := "New Home" z.Meta[api.KeyTitle] = newTitle err = c.UpdateZettelJSON(context.Background(), api.ZidDefaultHome, z) if err != nil { t.Error(err) return } zt, err := c.GetZettelJSON(context.Background(), api.ZidDefaultHome) if err != nil { t.Error(err) return } if got := zt.Meta[api.KeyTitle]; got != newTitle { t.Errorf("Title of zettel is not %q, but %q", newTitle, got) } // Must delete to clean up for next tests c.SetAuth("owner", "owner") doDelete(t, c, api.ZidDefaultHome) } func doDelete(t *testing.T, c *client.Client, zid api.ZettelID) { err := c.DeleteZettel(context.Background(), zid) if err != nil { t.Helper() t.Error("Cannot delete", zid, ":", err) } } |
Changes to tests/regression_test.go.
︙ | ︙ | |||
44 45 46 47 48 49 50 | func getFileBoxes(wd, kind string) (root string, boxes []box.ManagedBox) { root = filepath.Clean(filepath.Join(wd, "..", "testdata", kind)) entries, err := os.ReadDir(root) if err != nil { panic(err) } | | < < < < < | 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | func getFileBoxes(wd, kind string) (root string, boxes []box.ManagedBox) { root = filepath.Clean(filepath.Join(wd, "..", "testdata", kind)) entries, err := os.ReadDir(root) if err != nil { panic(err) } cdata := manager.ConnectData{Config: testConfig, Enricher: &noEnrich{}, Notify: nil} for _, entry := range entries { if entry.IsDir() { u, err2 := url.Parse("dir://" + filepath.Join(root, entry.Name()) + "?type=" + kernel.BoxDirTypeSimple) if err2 != nil { panic(err2) } box, err2 := manager.Connect(u, &noAuth{}, &cdata) |
︙ | ︙ | |||
132 133 134 135 136 137 138 | func checkMetaBox(t *testing.T, p box.ManagedBox, wd, boxName string) { ss := p.(box.StartStopper) if err := ss.Start(context.Background()); err != nil { panic(err) } metaList := []*meta.Meta{} | | | > > < | 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | func checkMetaBox(t *testing.T, p box.ManagedBox, wd, boxName string) { 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) }) if err != nil { panic(err) } for _, meta := range metaList { zettel, err2 := p.GetZettel(context.Background(), meta.Zid) if err2 != nil { panic(err2) } z := parser.ParseZettel(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) }) } } if err = ss.Stop(context.Background()); err != nil { panic(err) } } type myConfig struct{} func (*myConfig) AddDefaultValues(m *meta.Meta) *meta.Meta { return m } func (*myConfig) GetDefaultTitle() string { return "" } func (*myConfig) GetDefaultRole() string { return api.ValueRoleZettel } func (*myConfig) GetDefaultSyntax() string { return api.ValueSyntaxZmk } func (*myConfig) GetDefaultLang() string { return "" } func (*myConfig) GetDefaultVisibility() meta.Visibility { return meta.VisibilityPublic } func (*myConfig) GetFooterHTML() string { return "" } func (*myConfig) GetHomeZettel() id.Zid { return id.Invalid } 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) GetExpertMode() bool { return false } func (cfg *myConfig) GetVisibility(*meta.Meta) meta.Visibility { return cfg.GetDefaultVisibility() } func (*myConfig) GetMaxTransclusions() int { return 1024 } var testConfig = &myConfig{} func TestMetaRegression(t *testing.T) { |
︙ | ︙ |
Changes to tools/build.go.
︙ | ︙ | |||
138 139 140 141 142 143 144 145 146 147 148 | 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 } | > > > | | 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | func cmdCheck(forRelease bool) error { if err := checkGoTest("./..."); err != nil { return err } if err := checkGoVet(); err != nil { return err } if err := checkGoLint(); err != nil { return err } if err := checkShadow(forRelease); err != nil { return err } if err := checkStaticcheck(forRelease); err != nil { return err } if err := checkUnparam(forRelease); err != nil { return err } return checkFossilExtra() } |
︙ | ︙ | |||
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | 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 } | > > > > > > > > > | > > > > | | 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | fmt.Fprintln(os.Stderr, "Some checks failed") if len(out) > 0 { fmt.Fprintln(os.Stderr, out) } } return err } func checkGoLint() error { out, err := executeCommand(nil, "golint", "./...") if out != "" { fmt.Fprintln(os.Stderr, "Some lints failed") fmt.Fprint(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(forRelease bool) error { path, err := findExecStrict("staticcheck", forRelease) if path == "" { return err } out, err := executeCommand(nil, path, "./...") if err != nil { fmt.Fprintln(os.Stderr, "Some staticcheck problems found") if len(out) > 0 { fmt.Fprintln(os.Stderr, out) } } return err |
︙ | ︙ | |||
421 422 423 424 425 426 427 | arch string os string env []string name string }{ {"amd64", "linux", nil, "zettelstore"}, {"arm", "linux", []string{"GOARM=6"}, "zettelstore"}, | | | < | | 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 | arch string os string env []string name string }{ {"amd64", "linux", nil, "zettelstore"}, {"arm", "linux", []string{"GOARM=6"}, "zettelstore"}, {"amd64", "darwin", nil, "iZettelstore"}, {"arm64", "darwin", nil, "iZettelstore"}, {"amd64", "windows", nil, "zettelstore.exe"}, } for _, rel := range releases { env := append(rel.env, "GOARCH="+rel.arch, "GOOS="+rel.os) env = append(env, directProxy...) zsName := filepath.Join("releases", rel.name) if err := doBuild(env, calcVersion(base, fossil), 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 { |
︙ | ︙ | |||
524 525 526 527 528 529 530 | 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. | | | | 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 | 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 Outputs 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 Starts 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 |
︙ | ︙ |
Changes to usecase/authenticate.go.
1 | //----------------------------------------------------------------------------- | | > < < | < | < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. 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/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 { token auth.TokenManager port AuthenticatePort ucGetUser GetUser } // NewAuthenticate creates a new use case. func NewAuthenticate(token auth.TokenManager, authz auth.AuthzManager, port AuthenticatePort) Authenticate { return Authenticate{ 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 { compensateCompare() return nil, err } if hashCred, ok := identMeta.Get(api.KeyCredential); ok { ok, err = cred.CompareHashAndCredential(hashCred, identMeta.Zid, ident, credential) if err != nil { return nil, err } if ok { token, err2 := uc.token.GetToken(identMeta, d, k) if err2 != nil { return nil, err2 } return token, nil } return nil, nil } compensateCompare() return nil, nil } // compensateCompare if normal comapare is not possible, to avoid timing hints. func compensateCompare() { cred.CompareHashAndCredential( |
︙ | ︙ | |||
95 96 97 98 99 100 101 | 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) } } | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | 87 88 89 90 91 92 93 | 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) } } |
Changes to usecase/context.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 import ( "context" "zettelstore.de/c/api" "zettelstore.de/z/domain/id" |
︙ | ︙ | |||
64 65 66 67 68 69 70 | for { m, curDepth, found := tasks.next() if !found { break } result = append(result, m) | | | 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | for { m, curDepth, found := tasks.next() if !found { break } result = append(result, m) for _, p := range m.PairsRest(true) { tasks.addPair(ctx, uc.port, p.Key, p.Value, curDepth+1, isBackward, isForward) } } return result, nil } type ztlCtxTask struct { |
︙ | ︙ |
Changes to usecase/copy_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ( "zettelstore.de/c/api" "zettelstore.de/z/domain" ) | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "zettelstore.de/c/api" "zettelstore.de/z/domain" ) |
︙ | ︙ |
Changes to usecase/create_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //----------------------------------------------------------------------------- // 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/config" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" | > < < | < | < | < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "context" "zettelstore.de/c/api" "zettelstore.de/z/config" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" ) // 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 { rtConfig config.Config port CreateZettelPort } // NewCreateZettel creates a new use case. func NewCreateZettel(rtConfig config.Config, port CreateZettelPort) CreateZettel { return CreateZettel{ rtConfig: rtConfig, port: port, } } // 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 } if title, ok := m.Get(api.KeyTitle); !ok || title == "" { m.Set(api.KeyTitle, uc.rtConfig.GetDefaultTitle()) } if role, ok := m.Get(api.KeyRole); !ok || role == "" { m.Set(api.KeyRole, uc.rtConfig.GetDefaultRole()) } if syntax, ok := m.Get(api.KeySyntax); !ok || syntax == "" { m.Set(api.KeySyntax, uc.rtConfig.GetDefaultSyntax()) } m.YamlSep = uc.rtConfig.GetYAMLHeader() zettel.Content.TrimSpace() return uc.port.CreateZettel(ctx, zettel) } |
Changes to usecase/delete_zettel.go.
1 | //----------------------------------------------------------------------------- | | > < < | | | | < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | //----------------------------------------------------------------------------- // Copyright (c) 2020 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 import ( "context" "zettelstore.de/z/domain/id" ) // 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 { port DeleteZettelPort } // NewDeleteZettel creates a new use case. func NewDeleteZettel(port DeleteZettelPort) DeleteZettel { return DeleteZettel{port: port} } // Run executes the use case. func (uc DeleteZettel) Run(ctx context.Context, zid id.Zid) error { return uc.port.DeleteZettel(ctx, zid) } |
Changes to usecase/evaluate.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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/ast" "zettelstore.de/z/config" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 import ( "context" "zettelstore.de/z/ast" "zettelstore.de/z/config" |
︙ | ︙ |
Changes to usecase/folge_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ( "zettelstore.de/c/api" "zettelstore.de/z/config" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "zettelstore.de/c/api" "zettelstore.de/z/config" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" |
︙ | ︙ |
Changes to usecase/get_all_meta.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 import ( "context" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" |
︙ | ︙ |
Changes to usecase/get_meta.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // Copyright (c) 2020 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 import ( "context" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" |
︙ | ︙ |
Changes to usecase/get_user.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "context" "zettelstore.de/c/api" "zettelstore.de/z/auth" |
︙ | ︙ | |||
46 47 48 49 50 51 52 53 54 55 56 | 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 | > > > > | | 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | 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 { if role, ok := identMeta.Get(api.KeyRole); !ok || role != api.ValueRoleUser { return nil, nil } return identMeta, nil } // Owner was not found or has another ident. Try via list search. var s *search.Search s = s.AddExpr(api.KeyRole, api.ValueRoleUser) 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 |
︙ | ︙ |
Changes to usecase/get_zettel.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // Copyright (c) 2020 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 import ( "context" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" |
︙ | ︙ |
Changes to usecase/list_meta.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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/meta" "zettelstore.de/z/search" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "context" "zettelstore.de/z/domain/meta" "zettelstore.de/z/search" |
︙ | ︙ |
Changes to usecase/list_role.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" "sort" "zettelstore.de/c/api" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "context" "sort" "zettelstore.de/c/api" |
︙ | ︙ |
Changes to usecase/list_tags.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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/domain/meta" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "context" "zettelstore.de/c/api" "zettelstore.de/z/domain/meta" |
︙ | ︙ |
Changes to usecase/new_zettel.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "zettelstore.de/c/api" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" |
︙ | ︙ | |||
31 32 33 34 35 36 37 | om := origZettel.Meta m.Set(api.KeyTitle, om.GetDefault(api.KeyTitle, "")) m.Set(api.KeyRole, om.GetDefault(api.KeyRole, "")) m.Set(api.KeyTags, om.GetDefault(api.KeyTags, "")) m.Set(api.KeySyntax, om.GetDefault(api.KeySyntax, "")) const prefixLen = len(meta.NewPrefix) | | | 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | om := origZettel.Meta m.Set(api.KeyTitle, om.GetDefault(api.KeyTitle, "")) m.Set(api.KeyRole, om.GetDefault(api.KeyRole, "")) m.Set(api.KeyTags, om.GetDefault(api.KeyTags, "")) m.Set(api.KeySyntax, om.GetDefault(api.KeySyntax, "")) const prefixLen = len(meta.NewPrefix) for _, pair := range om.PairsRest(false) { 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} } |
Changes to usecase/order.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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/collect" "zettelstore.de/z/domain/id" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 import ( "context" "zettelstore.de/z/collect" "zettelstore.de/z/domain/id" |
︙ | ︙ |
Changes to usecase/parse_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "context" "zettelstore.de/z/ast" "zettelstore.de/z/config" |
︙ | ︙ |
Deleted usecase/refresh.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to usecase/rename_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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" | > < < | | | | < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "context" "zettelstore.de/z/box" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" ) // 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 { 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(port RenameZettelPort) RenameZettel { return RenameZettel{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} } return uc.port.RenameZettel(ctx, curZid, newZid) } |
Added usecase/search.go.
> > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "context" "zettelstore.de/z/box" "zettelstore.de/z/domain/meta" "zettelstore.de/z/search" ) // SearchPort is the interface used by this use case. type SearchPort interface { // SelectMeta returns all zettel meta data that match the selection criteria. SelectMeta(ctx context.Context, s *search.Search) ([]*meta.Meta, error) } // Search is the data for this use case. type Search struct { port SearchPort } // NewSearch creates a new use case. func NewSearch(port SearchPort) Search { return Search{port: port} } // Run executes the use case. func (uc Search) Run(ctx context.Context, s *search.Search) ([]*meta.Meta, error) { if !s.EnrichNeeded() { ctx = box.NoEnrichContext(ctx) } return uc.port.SelectMeta(ctx, s) } |
Deleted usecase/unlinked_refs.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to usecase/update_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //----------------------------------------------------------------------------- // 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" | > < < | | | | < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | //----------------------------------------------------------------------------- // 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 provides (business) use cases for the zettelstore. package usecase import ( "context" "zettelstore.de/c/api" "zettelstore.de/z/box" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" ) // 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 { port UpdateZettelPort } // NewUpdateZettel creates a new use case. func NewUpdateZettel(port UpdateZettelPort) UpdateZettel { return UpdateZettel{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() } return uc.port.UpdateZettel(ctx, zettel) } |
Deleted usecase/usecase.go.
|
| < < < < < < < < < < < < |
Changes to web/adapter/api/api.go.
︙ | ︙ | |||
8 9 10 11 12 13 14 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( | < < < < < | < | 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( "context" "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/web/server" ) // API holds all data and methods for delivering API call results. type API struct { b server.Builder rtConfig config.Config authz auth.AuthzManager token auth.TokenManager auth server.Auth tokenLifetime time.Duration } // New creates a new API object. func New(b server.Builder, authz auth.AuthzManager, token auth.TokenManager, auth server.Auth, rtConfig config.Config) *API { a := &API{ b: b, authz: authz, token: token, auth: auth, rtConfig: rtConfig, tokenLifetime: kernel.Main.GetConfig(kernel.WebService, kernel.WebTokenLifetimeAPI).(time.Duration), |
︙ | ︙ | |||
63 64 65 66 67 68 69 | 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) } | < < < < < < < < < < < < < < < < < < < < < < | 57 58 59 60 61 62 63 | 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) } |
Deleted web/adapter/api/command.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to web/adapter/api/create_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 | //----------------------------------------------------------------------------- // 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 ( | > < | | | | | > | | | < | < < < < < < | > | < > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | //----------------------------------------------------------------------------- // 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 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" ) // 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 { adapter.ReportUsecaseError(w, adapter.NewErrBadRequest(err.Error())) return } newZid, err := createZettel.Run(ctx, zettel) if err != nil { adapter.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) if _, err = w.Write(newZid.Bytes()); err != nil { adapter.InternalServerError(w, "Write Plain", err) } } } // 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 { adapter.ReportUsecaseError(w, adapter.NewErrBadRequest(err.Error())) return } newZid, err := createZettel.Run(ctx, zettel) if err != nil { adapter.ReportUsecaseError(w, err) return } u := a.NewURLBuilder('j').SetZid(api.ZettelID(newZid.String())).String() h := adapter.PrepareHeader(w, ctJSON) h.Set(api.HeaderLocation, u) w.WriteHeader(http.StatusCreated) if err = encodeJSONData(w, api.ZidJSON{ID: api.ZettelID(newZid.String())}); err != nil { adapter.InternalServerError(w, "Write JSON", err) } } } |
Changes to web/adapter/api/delete_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //----------------------------------------------------------------------------- // 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. | > > | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | //----------------------------------------------------------------------------- // 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 provides api handlers for web requests. package api import ( "net/http" "zettelstore.de/z/domain/id" "zettelstore.de/z/usecase" "zettelstore.de/z/web/adapter" ) // MakeDeleteZettelHandler creates a new HTTP handler to delete a zettel. func 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 { adapter.ReportUsecaseError(w, err) return } w.WriteHeader(http.StatusNoContent) } } |
Changes to web/adapter/api/encode_inlines.go.
︙ | ︙ | |||
17 18 19 20 21 22 23 24 25 26 27 28 29 30 | "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/encoder" "zettelstore.de/z/evaluator" "zettelstore.de/z/usecase" ) // MakePostEncodeInlinesHandler creates a new HTTP handler to encode given // Zettelmarkup inline material func (a *API) MakePostEncodeInlinesHandler(evaluate usecase.Evaluate) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { dec := json.NewDecoder(r.Body) | > | 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/encoder" "zettelstore.de/z/evaluator" "zettelstore.de/z/usecase" "zettelstore.de/z/web/adapter" ) // MakePostEncodeInlinesHandler creates a new HTTP handler to encode given // Zettelmarkup inline material func (a *API) MakePostEncodeInlinesHandler(evaluate usecase.Evaluate) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { dec := json.NewDecoder(r.Body) |
︙ | ︙ | |||
72 73 74 75 76 77 78 | http.Error(w, "Unable to encode other as HTML", http.StatusBadRequest) return } respJSON.OtherHTML[i] = s } } | | | < | < < < < | 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | http.Error(w, "Unable to encode other as HTML", http.StatusBadRequest) return } respJSON.OtherHTML[i] = s } } adapter.PrepareHeader(w, ctJSON) err := encodeJSONData(w, respJSON) if err != nil { adapter.InternalServerError(w, "Write JSON for encoded Zettelmarkup", err) } } } func encodeInlines(encdr encoder.Encoder, inl *ast.InlineListNode) (string, error) { var buf bytes.Buffer _, err := encdr.WriteInlines(&buf, inl) if err != nil { return "", err } return buf.String(), nil } |
Changes to web/adapter/api/get_eval_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 api import ( "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 api provides api handlers for web requests. package api import ( "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" |
︙ | ︙ | |||
43 44 45 46 47 48 49 | Blob: zettel.Content.AsBytes(), Syntax: syntax, } } } zn, err := evaluate.Run(ctx, zid, q.Get(api.KeySyntax), &env) if err != nil { | | | 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | Blob: zettel.Content.AsBytes(), Syntax: syntax, } } } zn, err := evaluate.Run(ctx, zid, q.Get(api.KeySyntax), &env) if err != nil { adapter.ReportUsecaseError(w, err) return } evalMeta := func(value string) *ast.InlineListNode { return evaluate.RunMetadata(ctx, value, &env) } a.writeEncodedZettelPart(w, zn, evalMeta, enc, encStr, part) } } |
Changes to web/adapter/api/get_links.go.
1 | //----------------------------------------------------------------------------- | | < > | | | | | < < < < < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | //----------------------------------------------------------------------------- // 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 api provides api handlers for web requests. package api import ( "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/collect" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" "zettelstore.de/z/usecase" "zettelstore.de/z/web/adapter" ) // MakeGetLinksHandler creates a new API handler to return links to other material. func MakeGetLinksHandler(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() zn, err := evaluate.Run(ctx, zid, q.Get(api.KeySyntax), nil) if err != nil { adapter.ReportUsecaseError(w, err) return } summary := collect.References(zn) outData := api.ZettelLinksJSON{ID: api.ZettelID(zid.String())} zetRefs, locRefs, extRefs := collect.DivideReferences(summary.Links) outData.Linked.Outgoing = idRefs(zetRefs) outData.Linked.Local = stringRefs(locRefs) outData.Linked.External = stringRefs(extRefs) for _, p := range zn.Meta.PairsRest(false) { if meta.Type(p.Key) == meta.TypeURL { outData.Linked.Meta = append(outData.Linked.Meta, p.Value) } } zetRefs, locRefs, extRefs = collect.DivideReferences(summary.Embeds) outData.Embedded.Outgoing = idRefs(zetRefs) outData.Embedded.Local = stringRefs(locRefs) outData.Embedded.External = stringRefs(extRefs) outData.Cites = stringCites(summary.Cites) adapter.PrepareHeader(w, ctJSON) encodeJSONData(w, outData) } } func idRefs(refs []*ast.Reference) []string { result := make([]string, len(refs)) for i, ref := range refs { path := ref.URL.Path |
︙ | ︙ |
Changes to web/adapter/api/get_order.go.
︙ | ︙ | |||
13 14 15 16 17 18 19 20 21 22 23 | 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. | > | | | < | 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | import ( "net/http" "zettelstore.de/c/api" "zettelstore.de/z/domain/id" "zettelstore.de/z/usecase" "zettelstore.de/z/web/adapter" ) // MakeGetOrderHandler creates a new API handler to return zettel references // of a given zettel. func 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 { adapter.ReportUsecaseError(w, err) return } writeMetaList(w, start, metas) } } |
Changes to web/adapter/api/get_parsed_zettel.go.
︙ | ︙ | |||
8 9 10 11 12 13 14 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( | < | 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( "fmt" "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/config" "zettelstore.de/z/domain/id" |
︙ | ︙ | |||
36 37 38 39 40 41 42 | } q := r.URL.Query() enc, encStr := adapter.GetEncoding(r, q, encoder.GetDefaultEncoding()) part := getPart(q, partContent) zn, err := parseZettel.Run(r.Context(), zid, q.Get(api.KeySyntax)) if err != nil { | | | 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | } q := r.URL.Query() enc, encStr := adapter.GetEncoding(r, q, encoder.GetDefaultEncoding()) part := getPart(q, partContent) zn, err := parseZettel.Run(r.Context(), zid, q.Get(api.KeySyntax)) if err != nil { adapter.ReportUsecaseError(w, err) return } a.writeEncodedZettelPart(w, zn, parser.ParseMetadata, enc, encStr, part) } } func (a *API) writeEncodedZettelPart( |
︙ | ︙ | |||
60 61 62 63 64 65 66 67 | IgnoreMeta: map[string]bool{api.KeyLang: true}, } encdr := encoder.Create(enc, &env) if encdr == nil { adapter.BadRequest(w, fmt.Sprintf("Zettel %q not available in encoding %q", zn.Meta.Zid.String(), encStr)) return } var err error | > < | | | < | < < < < | < < < < | 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | IgnoreMeta: map[string]bool{api.KeyLang: true}, } encdr := encoder.Create(enc, &env) if encdr == nil { adapter.BadRequest(w, fmt.Sprintf("Zettel %q not available in encoding %q", zn.Meta.Zid.String(), encStr)) return } adapter.PrepareHeader(w, encoding2ContentType(enc)) var err error switch part { case partZettel: _, err = encdr.WriteZettel(w, zn, evalMeta) case partMeta: _, err = encdr.WriteMeta(w, zn.InhMeta, evalMeta) case partContent: _, err = encdr.WriteContent(w, zn) } if err != nil { adapter.InternalServerError(w, "Write encoded zettel", err) } } |
Changes to web/adapter/api/get_role_list.go.
︙ | ︙ | |||
8 9 10 11 12 13 14 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( | < > | | | | | < < < < < < < < | 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( "net/http" "zettelstore.de/c/api" "zettelstore.de/z/usecase" "zettelstore.de/z/web/adapter" ) // MakeListRoleHandler creates a new HTTP handler for the use case "list some zettel". func MakeListRoleHandler(listRole usecase.ListRole) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { roleList, err := listRole.Run(r.Context()) if err != nil { adapter.ReportUsecaseError(w, err) return } adapter.PrepareHeader(w, ctJSON) encodeJSONData(w, api.RoleListJSON{Roles: roleList}) } } |
Changes to web/adapter/api/get_tags_list.go.
︙ | ︙ | |||
8 9 10 11 12 13 14 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( | < > | | | < | < < < < < < < < | 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( "net/http" "strconv" "zettelstore.de/c/api" "zettelstore.de/z/usecase" "zettelstore.de/z/web/adapter" ) // MakeListTagsHandler creates a new HTTP handler for the use case "list some zettel". func MakeListTagsHandler(listTags usecase.ListTags) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { iMinCount, _ := strconv.Atoi(r.URL.Query().Get("min")) tagData, err := listTags.Run(r.Context(), iMinCount) if err != nil { adapter.ReportUsecaseError(w, err) return } tagMap := make(map[string][]api.ZettelID, len(tagData)) for tag, metaList := range tagData { zidList := make([]api.ZettelID, 0, len(metaList)) for _, m := range metaList { zidList = append(zidList, api.ZettelID(m.Zid.String())) } tagMap[tag] = zidList } adapter.PrepareHeader(w, ctJSON) encodeJSONData(w, api.TagListJSON{Tags: tagMap}) } } |
Deleted web/adapter/api/get_unlinked_refs.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to web/adapter/api/get_zettel.go.
1 | //----------------------------------------------------------------------------- | | < > | | | | < | < < < < | < < | | | | | | | < | < < < | | | | | | < | < < < < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | //----------------------------------------------------------------------------- // 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 api provides api handlers for web requests. package api 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/usecase" "zettelstore.de/z/web/adapter" ) // MakeGetZettelHandler creates a new HTTP handler to return a zettel. func MakeGetZettelHandler(getZettel usecase.GetZettel) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { z, err := getZettelFromPath(r.Context(), w, r, getZettel) if err != nil { return } adapter.PrepareHeader(w, ctJSON) content, encoding := z.Content.Encode() err = encodeJSONData(w, api.ZettelJSON{ ID: api.ZettelID(z.Meta.Zid.String()), Meta: z.Meta.Map(), Encoding: encoding, Content: content, }) if err != nil { adapter.InternalServerError(w, "Write Zettel JSON", err) } } } // 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 := getZettelFromPath(box.NoEnrichContext(r.Context()), w, r, getZettel) if err != nil { return } switch getPart(r.URL.Query(), partContent) { case partZettel: _, err = z.Meta.Write(w, false) if err == nil { _, err = w.Write([]byte{'\n'}) } if err == nil { _, err = z.Content.Write(w) } case partMeta: adapter.PrepareHeader(w, ctPlainText) _, err = z.Meta.Write(w, false) case partContent: if ct, ok := syntax2contentType(config.GetSyntax(z.Meta, a.rtConfig)); ok { adapter.PrepareHeader(w, ct) } _, err = z.Content.Write(w) } if err != nil { adapter.InternalServerError(w, "Write plain zettel", err) } } } func 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 { adapter.ReportUsecaseError(w, err) return domain.Zettel{}, err } return z, nil } // MakeGetMetaHandler creates a new HTTP handler to return metadata of a zettel. func 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 } m, err := getMeta.Run(r.Context(), zid) if err != nil { adapter.ReportUsecaseError(w, err) return } adapter.PrepareHeader(w, ctJSON) err = encodeJSONData(w, api.MetaJSON{ Meta: m.Map(), }) if err != nil { adapter.InternalServerError(w, "Write Meta JSON", err) } } } |
Changes to web/adapter/api/get_zettel_context.go.
︙ | ︙ | |||
17 18 19 20 21 22 23 | "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". | | | < | < | 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | "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 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 { adapter.ReportUsecaseError(w, err) return } writeMetaList(w, metaList[0], metaList[1:]) } } |
Changes to web/adapter/api/get_zettel_list.go.
︙ | ︙ | |||
19 20 21 22 23 24 25 | "zettelstore.de/c/api" "zettelstore.de/z/config" "zettelstore.de/z/usecase" "zettelstore.de/z/web/adapter" ) // MakeListMetaHandler creates a new HTTP handler for the use case "list some zettel". | | | > > > > > | | | < | < < < < | | | < < | > > | < < | 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | "zettelstore.de/c/api" "zettelstore.de/z/config" "zettelstore.de/z/usecase" "zettelstore.de/z/web/adapter" ) // MakeListMetaHandler creates a new HTTP handler for the use case "list some zettel". func 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 { adapter.ReportUsecaseError(w, err) return } var queryText bytes.Buffer if s != nil { s.Print(&queryText) } 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(), }) } adapter.PrepareHeader(w, ctJSON) err = encodeJSONData(w, api.ZettelListJSON{ Query: queryText.String(), List: result, }) if err != nil { adapter.InternalServerError(w, "Write Zettel list JSON", err) } } } // 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 { adapter.ReportUsecaseError(w, err) return } adapter.PrepareHeader(w, ctPlainText) for _, m := range metaList { _, err = fmt.Fprintln(w, m.Zid.String(), config.GetTitle(m, a.rtConfig)) if err != nil { break } } if err != nil { adapter.InternalServerError(w, "Write Zettel list plain", err) } } } |
Changes to web/adapter/api/json.go.
︙ | ︙ | |||
8 9 10 11 12 13 14 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( | < > | | < | < < < < < < < | 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | // under this license. //----------------------------------------------------------------------------- // Package api provides api handlers for web requests. package api import ( "encoding/json" "io" "net/http" "zettelstore.de/c/api" "zettelstore.de/z/domain" "zettelstore.de/z/domain/id" "zettelstore.de/z/domain/meta" "zettelstore.de/z/web/adapter" ) func encodeJSONData(w io.Writer, data interface{}) error { enc := json.NewEncoder(w) enc.SetEscapeHTML(false) return enc.Encode(data) } func writeMetaList(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() } adapter.PrepareHeader(w, ctJSON) return encodeJSONData(w, api.ZidMetaRelatedList{ ID: api.ZettelID(m.Zid.String()), Meta: m.Map(), List: outList, }) } 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 { |
︙ | ︙ |
Changes to web/adapter/api/login.go.
1 | //----------------------------------------------------------------------------- | | > < | > | < | > | < | < | | < < < < < < < < < < < < > | < | > | < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | //----------------------------------------------------------------------------- // 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 api provides api handlers for web requests. package api import ( "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() { adapter.PrepareHeader(w, ctJSON) writeJSONToken(w, "freeaccess", 24*366*10*time.Hour) 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 { adapter.ReportUsecaseError(w, err) return } } if len(token) == 0 { w.Header().Set("WWW-Authenticate", `Bearer realm="Default"`) http.Error(w, "Authentication failed", http.StatusUnauthorized) return } adapter.PrepareHeader(w, ctJSON) writeJSONToken(w, string(token), a.tokenLifetime) } } 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 writeJSONToken(w http.ResponseWriter, token string, lifetime time.Duration) { je := json.NewEncoder(w) je.Encode(api.AuthJSON{ Token: token, Type: "Bearer", Expires: int(lifetime / time.Second), }) } // 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() 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 { adapter.PrepareHeader(w, ctJSON) writeJSONToken(w, string(authData.Token), totalLifetime-currentLifetime) return } // Token is a little bit aged. Create a new one token, err := a.getToken(authData.User) if err != nil { adapter.ReportUsecaseError(w, err) return } adapter.PrepareHeader(w, ctJSON) writeJSONToken(w, string(token), a.tokenLifetime) } } |
Changes to web/adapter/api/rename_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //----------------------------------------------------------------------------- // 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. | > > | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | //----------------------------------------------------------------------------- // 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 provides api handlers for web requests. package api import ( "net/http" "net/url" "zettelstore.de/c/api" "zettelstore.de/z/domain/id" "zettelstore.de/z/usecase" "zettelstore.de/z/web/adapter" ) // MakeRenameZettelHandler creates a new HTTP handler to update a zettel. func 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 { adapter.ReportUsecaseError(w, err) return } w.WriteHeader(http.StatusNoContent) } } func getDestinationZid(r *http.Request) (id.Zid, bool) { |
︙ | ︙ |
Changes to web/adapter/api/update_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //----------------------------------------------------------------------------- // 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. | > | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | //----------------------------------------------------------------------------- // 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 provides api handlers for web requests. 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 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 { adapter.ReportUsecaseError(w, adapter.NewErrBadRequest(err.Error())) return } if err = updateZettel.Run(r.Context(), zettel, true); err != nil { adapter.ReportUsecaseError(w, err) return } w.WriteHeader(http.StatusNoContent) } } // MakeUpdateZettelHandler creates a new HTTP handler to update a zettel. func 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 { adapter.ReportUsecaseError(w, adapter.NewErrBadRequest(err.Error())) return } if err = updateZettel.Run(r.Context(), zettel, true); err != nil { adapter.ReportUsecaseError(w, err) return } w.WriteHeader(http.StatusNoContent) } } |
Changes to web/adapter/errors.go.
1 | //----------------------------------------------------------------------------- | | | > > > > > > > > > > > > > > > > > > > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | //----------------------------------------------------------------------------- // Copyright (c) 2020 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 ( "log" "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) } // InternalServerError signals HTTP status code 500. func InternalServerError(w http.ResponseWriter, text string, err error) { http.Error(w, "Internal Server Error", http.StatusInternalServerError) if text == "" { log.Println(err) } else { log.Printf("%v: %v", text, err) } } // NotImplemented signals HTTP status code 501 func NotImplemented(w http.ResponseWriter, text string) { http.Error(w, text, http.StatusNotImplemented) log.Println(text) } |
Changes to web/adapter/request.go.
1 | //----------------------------------------------------------------------------- | | > > < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | //----------------------------------------------------------------------------- // 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 ( "log" "net/http" "net/url" "strconv" "strings" "zettelstore.de/c/api" "zettelstore.de/z/domain/meta" "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 { log.Println(err) return "", "", false } ident = strings.TrimSpace(r.PostFormValue("username")) cred = r.PostFormValue("password") if ident == "" { return "", "", false |
︙ | ︙ | |||
156 157 158 159 160 161 162 | case api.DirBackward: return usecase.ZettelContextBackward case api.DirForward: return usecase.ZettelContextForward } return usecase.ZettelContextBoth } | < < < < < < < < < < < < < < < < < | 157 158 159 160 161 162 163 | case api.DirBackward: return usecase.ZettelContextBackward case api.DirForward: return usecase.ZettelContextForward } return usecase.ZettelContextBoth } |
Changes to web/adapter/response.go.
︙ | ︙ | |||
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | // Package adapter provides handlers for web requests. package adapter import ( "errors" "fmt" "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/box" "zettelstore.de/z/domain/id" "zettelstore.de/z/usecase" "zettelstore.de/z/web/server" ) // 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. | > > > > > > > > > > > | 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | // Package adapter provides handlers for web requests. package adapter import ( "errors" "fmt" "log" "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/box" "zettelstore.de/z/domain/id" "zettelstore.de/z/usecase" "zettelstore.de/z/web/server" ) // 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 } // ReportUsecaseError returns an appropriate HTTP status code for errors in use cases. func ReportUsecaseError(w http.ResponseWriter, err error) { code, text := CodeMessageFromError(err) if code == http.StatusInternalServerError { log.Printf("%v: %v", text, err) } // TODO: must call PrepareHeader somehow http.Error(w, text, code) } // ErrBadRequest is returned if the caller made an invalid HTTP request. type ErrBadRequest struct { Text string } // NewErrBadRequest creates an new bad request error. |
︙ | ︙ | |||
67 68 69 70 71 72 73 | return http.StatusConflict, "Zettelstore operations conflicted" } return http.StatusInternalServerError, err.Error() } // CreateTagReference builds a reference to list all tags. func CreateTagReference(b server.Builder, key byte, enc, s string) *ast.Reference { | | | 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | return http.StatusConflict, "Zettelstore operations conflicted" } return http.StatusInternalServerError, err.Error() } // CreateTagReference builds a reference to list all tags. func CreateTagReference(b server.Builder, key byte, enc, s string) *ast.Reference { u := b.NewURLBuilder(key).AppendQuery(api.QueryKeyEncoding, enc).AppendQuery(api.KeyTags, s) ref := ast.ParseReference(u.String()) ref.State = ast.RefStateHosted return ref } // CreateHostedReference builds a reference with state "hosted". func CreateHostedReference(b server.Builder, s string) *ast.Reference { |
︙ | ︙ |
Changes to web/adapter/webui/create_zettel.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "context" "fmt" "net/http" |
︙ | ︙ | |||
115 116 117 118 119 120 121 | 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: config.GetRole(m, wui.rtConfig), MetaSyntax: config.GetSyntax(m, wui.rtConfig), | | | | | 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | 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: config.GetRole(m, wui.rtConfig), MetaSyntax: config.GetSyntax(m, wui.rtConfig), MetaPairsRest: m.PairsRest(false), 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() 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 } redirectFound(w, r, wui.NewURLBuilder('h').SetZid(api.ZettelID(newZid.String()))) } } |
Changes to web/adapter/webui/delete_zettel.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "fmt" "net/http" "sort" |
︙ | ︙ | |||
56 57 58 59 60 61 62 | 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) } | < | | | | | | < < | | | | | | < < < < < < < < < | | | 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | 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) } 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 }{ Zid: zid.String(), MetaPairs: m.Pairs(true), HasShadows: shadowedBox != "", ShadowedBox: shadowedBox, HasIncoming: len(incomingLinks) > 0, Incoming: incomingLinks, }) } } // 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 } redirectFound(w, r, wui.NewURLBuilder('/')) } } func (wui *WebUI) encodeIncoming(m *meta.Meta, getTextTitle getTextTitleFunc) []simpleLink { zidMap := make(map[string]bool) addListValues(zidMap, m, api.KeyBackward) for _, kd := range meta.GetSortedKeyDescriptions() { |
︙ | ︙ |
Changes to web/adapter/webui/edit_zettel.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "fmt" "net/http" "zettelstore.de/c/api" |
︙ | ︙ | |||
51 52 53 54 55 56 57 | wui.makeBaseData(ctx, config.GetLang(m, wui.rtConfig), "Edit Zettel", user, &base) wui.renderTemplate(ctx, w, id.FormTemplateZid, &base, formZettelData{ Heading: base.Title, MetaTitle: m.GetDefault(api.KeyTitle, ""), MetaRole: m.GetDefault(api.KeyRole, ""), MetaTags: m.GetDefault(api.KeyTags, ""), MetaSyntax: m.GetDefault(api.KeySyntax, ""), | | | | | 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | wui.makeBaseData(ctx, config.GetLang(m, wui.rtConfig), "Edit Zettel", user, &base) wui.renderTemplate(ctx, w, id.FormTemplateZid, &base, formZettelData{ Heading: base.Title, MetaTitle: m.GetDefault(api.KeyTitle, ""), MetaRole: m.GetDefault(api.KeyRole, ""), MetaTags: m.GetDefault(api.KeyTags, ""), MetaSyntax: m.GetDefault(api.KeySyntax, ""), MetaPairsRest: m.PairsRest(false), IsTextContent: !zettel.Content.IsBinary(), Content: zettel.Content.AsString(), }) } } // 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 } 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 } redirectFound(w, r, wui.NewURLBuilder('h').SetZid(api.ZettelID(zid.String()))) } } |
Changes to web/adapter/webui/forms.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ( "bytes" "net/http" "strings" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "bytes" "net/http" "strings" |
︙ | ︙ |
Changes to web/adapter/webui/get_info.go.
1 | //----------------------------------------------------------------------------- | | > < | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "bytes" "context" "fmt" "net/http" "sort" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/box" "zettelstore.de/z/collect" "zettelstore.de/z/config" "zettelstore.de/z/domain" |
︙ | ︙ | |||
43 44 45 46 47 48 49 | // 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, | < | 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | // 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, ) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() q := r.URL.Query() if enc, encText := adapter.GetEncoding(r, q, api.EncoderHTML); enc != api.EncoderHTML { wui.reportError(ctx, w, adapter.NewErrBadRequest( fmt.Sprintf("Zettel info not available in encoding %q", encText))) |
︙ | ︙ | |||
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | zn, err := parseZettel.Run(ctx, zid, q.Get(api.KeySyntax)) if err != nil { wui.reportError(ctx, w, err) return } envEval := evaluator.Environment{ GetTagRef: func(s string) *ast.Reference { return adapter.CreateTagReference(wui, 'h', api.EncodingHTML, s) }, GetHostedRef: func(s string) *ast.Reference { return adapter.CreateHostedReference(wui, s) }, GetFoundRef: func(zid id.Zid, fragment string) *ast.Reference { return adapter.CreateFoundReference(wui, 'h', "", "", zid, fragment) }, GetImageMaterial: func(zettel domain.Zettel, _ string) ast.MaterialNode { return wui.createImageMaterial(zettel.Meta.Zid) }, } lang := config.GetLang(zn.InhMeta, wui.rtConfig) envHTML := encoder.Environment{Lang: lang} | > > > | < < < < < < < < < < < < < < < < < > > < < < > < < < | 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 | zn, err := parseZettel.Run(ctx, zid, q.Get(api.KeySyntax)) if err != nil { wui.reportError(ctx, w, err) return } summary := collect.References(zn) locLinks, extLinks := splitLocExtLinks(append(summary.Links, summary.Embeds...)) envEval := evaluator.Environment{ GetTagRef: func(s string) *ast.Reference { return adapter.CreateTagReference(wui, 'h', api.EncodingHTML, s) }, GetHostedRef: func(s string) *ast.Reference { return adapter.CreateHostedReference(wui, s) }, GetFoundRef: func(zid id.Zid, fragment string) *ast.Reference { return adapter.CreateFoundReference(wui, 'h', "", "", zid, fragment) }, GetImageMaterial: func(zettel domain.Zettel, _ string) ast.MaterialNode { return wui.createImageMaterial(zettel.Meta.Zid) }, } lang := config.GetLang(zn.InhMeta, wui.rtConfig) envHTML := encoder.Environment{Lang: lang} pairs := zn.Meta.Pairs(true) 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.InlineListNode { return evaluate.RunMetadata(ctx, val, &envEval) }, &envHTML) metaData[i] = metaDataInfo{p.Key, buf.String()} } shadowLinks := getShadowLinks(ctx, zid, getAllMeta) endnotes, err := encodeBlocks(&ast.BlockListNode{}, api.EncoderHTML, &envHTML) if err != nil { endnotes = "" } textTitle := wui.encodeTitleAsText(ctx, zn.InhMeta, evaluate) user := wui.getUser(ctx) canCreate := wui.canCreate(ctx, user) apiZid := api.ZettelID(zid.String()) var base baseData wui.makeBaseData(ctx, lang, 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 HasLinks bool HasLocLinks bool LocLinks []localLink HasExtLinks bool ExtLinks []string ExtNewWindow 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('f').SetZid(apiZid).String(), CanCopy: canCreate && !zn.Content.IsBinary(), CopyURL: wui.NewURLBuilder('c').SetZid(apiZid).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, HasLinks: len(extLinks)+len(locLinks) > 0, HasLocLinks: len(locLinks) > 0, LocLinks: locLinks, HasExtLinks: len(extLinks) > 0, ExtLinks: extLinks, ExtNewWindow: htmlAttrNewWindow(len(extLinks) > 0), EvalMatrix: wui.infoAPIMatrix('v', zid), ParseMatrix: wui.infoAPIMatrixPlain('p', zid), HasShadowLinks: len(shadowLinks) > 0, ShadowLinks: shadowLinks, Endnotes: endnotes, }) } |
︙ | ︙ |
Changes to web/adapter/webui/get_zettel.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ( "bytes" "errors" "net/http" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "bytes" "errors" "net/http" |
︙ | ︙ | |||
199 200 201 202 203 204 205 | 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 { | | | 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | 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("tags", tag).String()} ub.ClearQuery() } } return tagInfos } func (wui *WebUI) encodeIdentifierSet(m *meta.Meta, key string, getTextTitle getTextTitleFunc) string { |
︙ | ︙ |
Deleted web/adapter/webui/goaction.go.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to web/adapter/webui/home.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "context" "errors" "net/http" |
︙ | ︙ | |||
34 35 36 37 38 39 40 | 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 { | | | | | | 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | 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 { redirectFound(w, r, wui.NewURLBuilder('h').SetZid(apiHomeZid)) return } homeZid = id.DefaultHomeZid } _, err := s.GetMeta(ctx, homeZid) if err == nil { redirectFound(w, r, wui.NewURLBuilder('h').SetZid(apiHomeZid)) return } if errors.Is(err, &box.ErrNotAllowed{}) && wui.authz.WithAuth() && wui.getUser(ctx) == nil { redirectFound(w, r, wui.NewURLBuilder('i')) return } redirectFound(w, r, wui.NewURLBuilder('h')) } } |
Changes to web/adapter/webui/htmlmeta.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "context" "errors" "fmt" "io" |
︙ | ︙ | |||
67 68 69 70 71 72 73 | 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, api.EncoderHTML, envEnc)) default: | | | | | | 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | 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, api.EncoderHTML, envEnc)) default: strfun.HTMLEscape(w, value, false) fmt.Fprintf(w, " <b>(Unhandled type: %v, key: %v)</b>", kt, key) } } func (wui *WebUI) writeHTMLBool(w io.Writer, key, value string) { if meta.BoolValue(value) { wui.writeLink(w, key, "true", "True") } else { wui.writeLink(w, key, "false", "False") } } func writeCredential(w io.Writer, val string) { strfun.HTMLEscape(w, val, false) } func writeEmpty(w io.Writer, val string) { strfun.HTMLEscape(w, val, false) } func (wui *WebUI) writeIdentifier(w io.Writer, val string, getTextTitle getTextTitleFunc) { zid, err := id.Parse(val) if err != nil { strfun.HTMLEscape(w, val, false) return } title, found := getTextTitle(zid) switch { case found > 0: ub := wui.NewURLBuilder('h').SetZid(api.ZettelID(zid.String())) if title == "" { |
︙ | ︙ | |||
124 125 126 127 128 129 130 | } func (wui *WebUI) writeNumber(w io.Writer, key, val string) { wui.writeLink(w, key, val, val) } func writeString(w io.Writer, val string) { | | | | | | 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | } func (wui *WebUI) writeNumber(w io.Writer, key, val string) { wui.writeLink(w, key, val, val) } func writeString(w io.Writer, val string) { strfun.HTMLEscape(w, val, false) } 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 { strfun.HTMLEscape(w, val, false) return } fmt.Fprintf(w, "<a href=\"%v\"%v>", u, htmlAttrNewWindow(true)) strfun.HTMLEscape(w, val, false) 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)) strfun.HTMLEscape(w, text, false) io.WriteString(w, "</a>") } type getTextTitleFunc func(id.Zid) (string, int) func (wui *WebUI) makeGetTextTitle( ctx context.Context, |
︙ | ︙ |
Changes to web/adapter/webui/lists.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | //----------------------------------------------------------------------------- // 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 ( "bytes" "context" "net/http" "net/url" | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "bytes" "context" "net/http" "net/url" |
︙ | ︙ | |||
52 53 54 55 56 57 58 | 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() | | | > > | | | | < < < | < | < < < < < < < < < > | | | > > | | 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | 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("Select", s) wui.renderMetaList( ctx, w, title, s, func(s *search.Search) ([]*meta.Meta, error) { if !s.EnrichNeeded() { ctx = box.NoEnrichContext(ctx) } return listMeta.Run(ctx, s) }, evaluate, ) } type roleInfo struct { Text string URL string } func (wui *WebUI) renderRolesList(w http.ResponseWriter, r *http.Request, listRole usecase.ListRole) { ctx := r.Context() roleList, err := listRole.Run(ctx) if err != nil { adapter.ReportUsecaseError(w, err) return } roleInfos := make([]roleInfo, 0, len(roleList)) for _, role := range roleList { roleInfos = append( roleInfos, roleInfo{role, wui.NewURLBuilder('h').AppendQuery("role", role).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 |
︙ | ︙ | |||
136 137 138 139 140 141 142 | countMap := make(map[int]int) baseTagListURL := wui.NewURLBuilder('h') for tag, ml := range tagData { count := len(ml) countMap[count]++ tagsList = append( tagsList, | | | 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | 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("tags", 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) |
︙ | ︙ | |||
173 174 175 176 177 178 179 180 181 182 183 184 185 186 | 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 { | > > > > > > > > > > > > > > > > > > > > > > > > | 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | Tags []tagInfo }{ ListTagsURL: base.ListTagsURL, MinCounts: minCounts, Tags: tagsList, }) } // MakeSearchHandler creates a new HTTP handler for the use case "search". func (wui *WebUI) MakeSearchHandler(ucSearch usecase.Search, evaluate *usecase.Evaluate) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() ctx := r.Context() s := adapter.GetSearch(query) if s == nil { redirectFound(w, r, wui.NewURLBuilder('h')) return } title := wui.listTitleSearch("Search", s) wui.renderMetaList( ctx, w, title, s, func(s *search.Search) ([]*meta.Meta, error) { if !s.EnrichNeeded() { ctx = box.NoEnrichContext(ctx) } return ucSearch.Run(ctx, s) }, evaluate, ) } } // 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 { |
︙ | ︙ | |||
236 237 238 239 240 241 242 | val, ok := adapter.GetInteger(q, key) if !ok || val < 0 { return minValue } return val } | > > > > > > > > > > > > > > > > > > > > > > > > > > > | > > > | > | 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | val, ok := adapter.GetInteger(q, key) if !ok || val < 0 { return minValue } return val } func (wui *WebUI) renderMetaList( ctx context.Context, w http.ResponseWriter, title string, s *search.Search, ucMetaList func(sorter *search.Search) ([]*meta.Meta, error), evaluate *usecase.Evaluate, ) { metaList, err := ucMetaList(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, }) } func (wui *WebUI) listTitleSearch(prefix string, s *search.Search) string { if s == nil { return wui.rtConfig.GetSiteName() } var buf bytes.Buffer buf.WriteString(prefix) if s != nil { buf.WriteString(": ") 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 { |
︙ | ︙ |
Changes to web/adapter/webui/login.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //----------------------------------------------------------------------------- // 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" "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) | > | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. 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) 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() { 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) redirectFound(w, r, wui.NewURLBuilder('/')) } } |
Changes to web/adapter/webui/rename_zettel.go.
1 | //----------------------------------------------------------------------------- | | > | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //----------------------------------------------------------------------------- // 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 provides web-UI handlers for web requests. package webui import ( "fmt" "net/http" "strings" |
︙ | ︙ | |||
45 46 47 48 49 50 51 | wui.reportError(ctx, w, adapter.NewErrBadRequest( fmt.Sprintf("Rename zettel %q not possible in encoding %q", zid.String(), encText))) return } getTextTitle := wui.makeGetTextTitle(ctx, getMeta, evaluate) incomingLinks := wui.encodeIncoming(m, getTextTitle) | < | | | | < < | | | | < < | | 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | wui.reportError(ctx, w, adapter.NewErrBadRequest( fmt.Sprintf("Rename zettel %q not possible in encoding %q", zid.String(), encText))) return } getTextTitle := wui.makeGetTextTitle(ctx, getMeta, evaluate) incomingLinks := wui.encodeIncoming(m, getTextTitle) 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 }{ Zid: zid.String(), MetaPairs: m.Pairs(true), HasIncoming: len(incomingLinks) > 0, Incoming: incomingLinks, }) } } // 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 } |
︙ | ︙ | |||
99 100 101 102 103 104 105 | return } if err = renameZettel.Run(r.Context(), curZid, newZid); err != nil { wui.reportError(ctx, w, err) return } | | | 95 96 97 98 99 100 101 102 103 104 | return } if err = renameZettel.Run(r.Context(), curZid, newZid); err != nil { wui.reportError(ctx, w, err) return } redirectFound(w, r, wui.NewURLBuilder('h').SetZid(api.ZettelID(newZid.String()))) } } |
Changes to web/adapter/webui/response.go.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | //----------------------------------------------------------------------------- // 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 webui import ( "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/domain/id" ) | > | < < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | //----------------------------------------------------------------------------- // 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 webui provides web-UI handlers for web requests. package webui import ( "net/http" "zettelstore.de/c/api" "zettelstore.de/z/ast" "zettelstore.de/z/domain/id" ) func redirectFound(w http.ResponseWriter, r *http.Request, ub *api.URLBuilder) { http.Redirect(w, r, ub.String(), http.StatusFound) } func (wui *WebUI) createImageMaterial(zid id.Zid) ast.MaterialNode { ub := wui.NewURLBuilder('z').SetZid(api.ZettelID(zid.String())) ref := ast.ParseReference(ub.String()) ref.State = ast.RefStateFound return &ast.ReferenceMaterialNode{Ref: ref} |
︙ | ︙ |
Changes to web/adapter/webui/webui.go.
1 | //----------------------------------------------------------------------------- | | > < < < | < < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | //----------------------------------------------------------------------------- // 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 webui provides web-UI handlers for web requests. package webui import ( "bytes" "context" "io" "log" "net/http" "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" "zettelstore.de/z/kernel" "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 { debug bool ab server.AuthBuilder authz auth.AuthzManager rtConfig config.Config token auth.TokenManager box webuiBox policy auth.Policy templateCache map[id.Zid]*template.Template mxCache sync.RWMutex tokenLifetime time.Duration cssBaseURL string cssUserURL string homeURL string listZettelURL string listRolesURL string listTagsURL 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(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{ debug: kernel.Main.GetConfig(kernel.CoreService, kernel.CoreDebug).(bool), ab: ab, rtConfig: rtConfig, authz: authz, token: token, box: mgr, policy: pol, 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(), withAuth: authz.WithAuth(), loginURL: loginoutBase.String(), logoutURL: loginoutBase.AppendQuery("logout", "").String(), searchURL: ab.NewURLBuilder('f').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) { |
︙ | ︙ | |||
143 144 145 146 147 148 149 | 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) } | < < < < | 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | 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) 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 { |
︙ | ︙ | |||
186 187 188 189 190 191 192 | UserZettelURL string UserIdent string LoginURL string LogoutURL string ListZettelURL string ListRolesURL string ListTagsURL string | < < | 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | UserZettelURL string UserIdent string LoginURL string LogoutURL string ListZettelURL string ListRolesURL string ListTagsURL string HasNewZettelLinks bool NewZettelLinks []simpleLink SearchURL string QueryKeySearch string Content string FooterHTML string } |
︙ | ︙ | |||
222 223 224 225 226 227 228 | 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 | < < | 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | 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.HasNewZettelLinks = len(newZettelLinks) > 0 data.NewZettelLinks = newZettelLinks data.SearchURL = wui.searchURL data.QueryKeySearch = api.QueryKeySearch data.FooterHTML = wui.rtConfig.GetFooterHTML() } |
︙ | ︙ | |||
292 293 294 295 296 297 298 | 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 { | | | 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | 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 { log.Printf("%v: %v", text, err) } 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 |
︙ | ︙ | |||
316 317 318 319 320 321 322 | code int, templateID id.Zid, base *baseData, data interface{}) { bt, err := wui.getTemplate(ctx, id.BaseTemplateZid) if err != nil { | < | | < | 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 | code int, templateID id.Zid, base *baseData, data interface{}) { bt, err := wui.getTemplate(ctx, id.BaseTemplateZid) if err != nil { adapter.InternalServerError(w, "Unable to get base template", err) return } t, err := wui.getTemplate(ctx, templateID) if err != nil { adapter.InternalServerError(w, "Unable to get template", err) 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) } } |
︙ | ︙ | |||
345 346 347 348 349 350 351 | err = bt.Render(w, base) if err == nil { err = wui.writeHTMLEnd(w) } } } if err != nil { | | | 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 | err = bt.Render(w, base) if err == nil { err = wui.writeHTMLEnd(w) } } } if err != nil { log.Println("Unable to write HTML via template", err) } } func writeHTMLStart(w http.ResponseWriter, lang string) error { _, err := io.WriteString(w, "<!DOCTYPE html>\n<html") if err != nil { return err |
︙ | ︙ |
Changes to web/server/impl/http.go.
︙ | ︙ | |||
66 67 68 69 70 71 72 | } go func() { srv.Serve(ln) }() return nil } // Stop the web server. | | | | 66 67 68 69 70 71 72 73 74 75 76 77 78 | } go func() { srv.Serve(ln) }() return nil } // Stop the web server. func (srv *httpServer) Stop() error { ctx, cancel := context.WithTimeout(context.Background(), shutdownTimeout) defer cancel() return srv.Shutdown(ctx) } |
Changes to web/server/impl/impl.go.
︙ | ︙ | |||
15 16 17 18 19 20 21 | "context" "net/http" "time" "zettelstore.de/c/api" "zettelstore.de/z/auth" "zettelstore.de/z/domain/meta" | < < | < | | 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | "context" "net/http" "time" "zettelstore.de/c/api" "zettelstore.de/z/auth" "zettelstore.de/z/domain/meta" "zettelstore.de/z/web/server" ) type myServer struct { server httpServer router httpRouter persistentCookie bool secureCookie bool } // New creates a new web server. func New(listenAddr, urlPrefix string, persistentCookie, secureCookie bool, auth auth.TokenManager) server.Server { srv := myServer{ persistentCookie: persistentCookie, secureCookie: secureCookie, } srv.router.initializeRouter(urlPrefix, auth) srv.server.initializeHTTPServer(listenAddr, &srv.router) return &srv } func (srv *myServer) Handle(pattern string, handler http.Handler) { srv.router.Handle(pattern, handler) } |
︙ | ︙ | |||
78 79 80 81 82 83 84 | Secure: srv.secureCookie, HttpOnly: true, SameSite: http.SameSiteStrictMode, } if srv.persistentCookie && d > 0 { cookie.Expires = time.Now().Add(d).Add(30 * time.Second).UTC() } | < < < < < | 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | Secure: srv.secureCookie, HttpOnly: true, SameSite: http.SameSiteStrictMode, } if srv.persistentCookie && d > 0 { cookie.Expires = time.Now().Add(d).Add(30 * time.Second).UTC() } http.SetCookie(w, &cookie) } // ClearToken invalidates the session cookie by sending an empty one. func (srv *myServer) ClearToken(ctx context.Context, w http.ResponseWriter) context.Context { if w != nil { srv.SetToken(w, nil, 0) } return updateContext(ctx, nil, nil) } // GetAuthData returns the full authentication data from the context. |
︙ | ︙ | |||
123 124 125 126 127 128 129 | Token: data.Token, Now: data.Now, Issued: data.Issued, Expires: data.Expires, }) } | | | | | 115 116 117 118 119 120 121 122 123 124 | 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() error { return srv.server.Stop() } |
Changes to web/server/impl/router.go.
︙ | ︙ | |||
8 9 10 11 12 13 14 | // under this license. //----------------------------------------------------------------------------- // Package impl provides the Zettelstore web service. package impl import ( | < < < | < | 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | // under this license. //----------------------------------------------------------------------------- // Package impl provides the Zettelstore web service. package impl import ( "net/http" "regexp" "strings" "zettelstore.de/c/api" "zettelstore.de/z/auth" "zettelstore.de/z/kernel" "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 { urlPrefix string auth auth.TokenManager minKey byte maxKey byte reURL *regexp.Regexp listTable routingTable zettelTable routingTable ur server.UserRetriever mux *http.ServeMux } // initializeRouter creates a new, empty router with the given root handler. func (rt *httpRouter) initializeRouter(urlPrefix string, auth auth.TokenManager) { rt.urlPrefix = urlPrefix rt.auth = auth rt.minKey = 255 rt.maxKey = 0 rt.reURL = regexp.MustCompile("^$") rt.mux = http.NewServeMux() } |
︙ | ︙ | |||
108 109 110 111 112 113 114 | // Something may panic. Ensure a kernel log. defer func() { if r := recover(); r != nil { kernel.Main.LogRecover("Web", r) } }() | < < < < < < < < < < < < < < < < < < < < < < | 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | // Something may panic. Ensure a kernel log. defer func() { if r := recover(); r != nil { kernel.Main.LogRecover("Web", r) } }() 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) return } r.URL.Path = r.URL.Path[prefixLen-1:] } match := rt.reURL.FindStringSubmatch(r.URL.Path) if len(match) != 3 { rt.mux.ServeHTTP(w, rt.addUserContext(r)) return } 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)) return } } http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) } func (rt *httpRouter) addUserContext(r *http.Request) *http.Request { if rt.ur == nil { return r } k := auth.KindJSON |
︙ | ︙ | |||
213 214 215 216 217 218 219 | 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):]) } | < < < < < < < < < < < < < < < | 187 188 189 190 191 192 193 | 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):]) } |
Changes to web/server/server.go.
︙ | ︙ | |||
85 86 87 88 89 90 91 | type Server interface { Router Auth Builder SetDebug() Run() error | | | 85 86 87 88 89 90 91 92 93 | type Server interface { Router Auth Builder SetDebug() Run() error Stop() error } |
Changes to www/build.md.
1 2 3 4 5 | # How to build the Zettelstore ## Prerequisites You must install the following software: * A current, supported [release of Go](https://golang.org/doc/devel/release.html), | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 | # How to build the Zettelstore ## Prerequisites You must install the following software: * A current, supported [release of Go](https://golang.org/doc/devel/release.html), * [golint](https://github.com/golang/lint|golint), * [Fossil](https://fossil-scm.org/). ## Clone the repository Most of this is covered by the excellent Fossil documentation. 1. Create a directory to store your Fossil repositories. Let's assume, you have created <tt>$HOME/fossil</tt>. |
︙ | ︙ | |||
29 30 31 32 33 34 35 | ``` go run tools/build.go [-v] COMMAND ``` The flag `-v` enables the verbose mode. It outputs all commands called by the tool. | | > > > | | 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | ``` go run tools/build.go [-v] COMMAND ``` The flag `-v` enables the verbose mode. It outputs all commands called by the tool. `COMMAND` is one of: * `build`: builds the software with correct version information and puts it into a freshly created directory <tt>bin</tt>. * `check`: checks the current state of the working directory to be ready for release (or commit). * `release`: executes `check` command and if this was successful, builds the software for various platforms, and creates ZIP files for each executable. Everything is put in the directory <tt>releases</tt>. * `clean`: removes the directories <tt>bin</tt> and <tt>releases</tt>. * `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 |
︙ | ︙ |
Changes to www/changes.wiki.
1 2 | <title>Change Log</title> | < < < | < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < | < < < < < < | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <title>Change Log</title> <a name="0_2"></a> <h2>Changes for Version 0.2 (pending)</h2> <a name="0_1"></a> <h2>Changes for Version 0.1 (2021-11-11)</h2> * Remove visual Zettelmarkup (italic, underline). Semantic Zettelmarkup (emphasize, insert) is still allowed, but got a different syntax. The new syntax for <ins>inserted text</ins> is <tt>>>inserted>></tt>, while its previous syntax now denotes <em>emphasized text</em>: <tt>__emphasized__</tt>. The previous syntax for emphasized text is now deprecated: <tt>//deprecated emphasized//</tt>. Starting with Version 0.0.17, the deprecated syntax will not be supported. The reason is the collision with URLs that also contain the characters <tt>//</tt>. The ZMK encoding of a zettel may help with the transition (<tt>/v/{ZettelID}?_part=zettel&_enc=zmk</tt>, on the Info page of each zettel in the WebUI). Additionally, all deprecated uses of <tt>//</tt> will be rendered with a dashed box within the WebUI. (breaking: Zettelmarkup). * API client software is now a [https://zettelstore.de/client/|separate] |
︙ | ︙ | |||
119 120 121 122 123 124 125 | uncover zettel in overlay box. (minor: webui) * Fix: do not allow control characters in JSON-based creating/updating API. Otherwise, the created / updated zettel might not be parseable by the software (but still by a human). In certain cases, even the WebUI might be affected. (minor: api, webui) | | < < | 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | uncover zettel in overlay box. (minor: webui) * Fix: do not allow control characters in JSON-based creating/updating API. Otherwise, the created / updated zettel might not be parseable by the software (but still by a human). In certain cases, even the WebUI might be affected. (minor: api, webui) * Fix: when a very log word (longer than width of browser window) is given, still allow to scroll horizontally. (minor: webui) * Separate repository for [https://zettelstore.de/contrib/|contributed] software. First entry is a software for creating a presentation by using zettel. (info) <a name="0_0_15"></a> <h2>Changes for Version 0.0.15 (2021-09-17)</h2> * Move again endpoint characters for authentication to make room for future features. WebUI authentication moves from <tt>/a</tt> to <tt>/i</tt> (login) and <tt>/i?logout</tt> (logout). API authentication moves from <tt>/v</tt> to </tt>/a</tt>. JSON-based basic zettel handling moves from |
︙ | ︙ |
Changes to www/download.wiki.
1 2 3 4 5 6 7 8 9 10 11 | <title>Download</title> <h1>Download of Zettelstore Software</h1> <h2>Foreword</h2> * 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. <h2>ZIP-ped Executables</h2> | | | | | | | | | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <title>Download</title> <h1>Download of Zettelstore Software</h1> <h2>Foreword</h2> * 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. <h2>ZIP-ped Executables</h2> Build: <code>v0.1</code> (2021-11-11). * [/uv/zettelstore-0.1-linux-amd64.zip|Linux] (amd64) * [/uv/zettelstore-0.1-linux-arm.zip|Linux] (arm6, e.g. Raspberry Pi) * [/uv/zettelstore-0.1-windows-amd64.zip|Windows] (amd64) * [/uv/zettelstore-0.1-darwin-amd64.zip|macOS] (amd64) * [/uv/zettelstore-0.1-darwin-arm64.zip|macOS] (arm64, aka Apple silicon) Unzip the appropriate file, install and execute Zettelstore according to the manual. <h2>Zettel for the manual</h2> As a starter, you can download the zettel for the manual [/uv/manual-0.1.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. |
Changes to www/index.wiki.
︙ | ︙ | |||
20 21 22 23 24 25 26 | 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://twitter.com/zettelstore|Stay tuned]… <hr> | | | | | | | | 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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://twitter.com/zettelstore|Stay tuned]… <hr> <h3>Latest Release: 0.1 (2021-11-11)</h3> * [./download.wiki|Download] * [./changes.wiki#0_1|Change summary] * [/timeline?p=v0.1&bt=v0.0.15&y=ci|Check-ins for version 0.1], [/vdiff?to=v0.1&from=v0.0.15|content diff] * [/timeline?df=v0.1&y=ci|Check-ins derived from the 0.1 release], [/vdiff?from=v0.1&to=trunk|content diff] * [./plan.wiki|Limitations and planned improvements] * [/timeline?t=release|Timeline of all past releases] <hr> <h2>Build instructions</h2> Just install [https://golang.org/dl/|Go] and some Go-based tools. Please read the [./build.md|instructions] for details. |
︙ | ︙ |
Changes to www/plan.wiki.
︙ | ︙ | |||
16 17 18 19 20 21 22 | * Quoted attribute values are not yet supported in Zettelmarkup: <code>{key="value with space"}</code>. * The horizontal tab character (<tt>U+0009</tt>) is not supported. * 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. | < < | < | | 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | * Quoted attribute values are not yet supported in Zettelmarkup: <code>{key="value with space"}</code>. * The horizontal tab character (<tt>U+0009</tt>) is not supported. * 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. * A running Zettelstore does not always detect when a directory box is removed. In case, it expects some zettel that cannot be retrieved. * … <h3>Planned improvements</h3> * Support for mathematical content is missing, e.g. <code>$$F(x) &= \\int^a_b \\frac{1}{3}x^3$$</code>. * … |