ADDED .deepsource.toml Index: .deepsource.toml ================================================================== --- /dev/null +++ .deepsource.toml @@ -0,0 +1,8 @@ +version = 1 + +[[analyzers]] +name = "go" +enabled = true + + [analyzers.meta] + import_root = "github.com/zettelstore/client" ADDED .github/dependabot.yml Index: .github/dependabot.yml ================================================================== --- /dev/null +++ .github/dependabot.yml @@ -0,0 +1,12 @@ +# To get started with Dependabot version updates, you'll need to specify which +# package ecosystems to update and where the package manifests are located. +# Please see the documentation for all configuration options: +# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + - package-ecosystem: "gomod" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "daily" + rebase-strategy: "disabled" Index: LICENSE.txt ================================================================== --- LICENSE.txt +++ LICENSE.txt @@ -1,6 +1,6 @@ -Copyright (c) 2021-present Detlef Stern +Copyright (c) 2021-2022 Detlef Stern Licensed under the EUPL Zettelstore client is licensed under the European Union Public License, version 1.2 or later (EUPL v. 1.2). The license is available in the Index: api/api.go ================================================================== --- api/api.go +++ api/api.go @@ -1,16 +1,13 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2021-present Detlef Stern +// Copyright (c) 2021-2022 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. -// -// SPDX-License-Identifier: EUPL-1.2 -// SPDX-FileCopyrightText: 2021-present Detlef Stern //----------------------------------------------------------------------------- // Package api contains common definitions used for client and server. package api @@ -23,11 +20,11 @@ // IsValid returns true, if the idenfifier contains 14 digits. func (zid ZettelID) IsValid() bool { if len(zid) != 14 { return false } - for i := range 14 { + for i := 0; i < 14; i++ { ch := zid[i] if ch < '0' || '9' < ch { return false } } @@ -46,31 +43,79 @@ ZettelCanCreate // Current user is allowed to create a new zettel ZettelCanRead // Requesting user is allowed to read the zettel ZettelCanWrite // Requesting user is allowed to update the zettel ZettelCanRename // Requesting user is allowed to provide the zettel with a new identifier ZettelCanDelete // Requesting user is allowed to delete the zettel - ZettelMaxRight // Sentinel value -) - -// MetaRights contains the metadata of a zettel, and its rights. -type MetaRights struct { - Meta ZettelMeta - Rights ZettelRights -} - -// ZidMetaRights contains the identifier, the metadata of a zettel, and its rights. -type ZidMetaRights struct { - ID ZettelID - Meta ZettelMeta - Rights ZettelRights -} - -// ZettelData contains all data for a zettel. -type ZettelData struct { - Meta ZettelMeta - Rights ZettelRights - Encoding string - Content string -} - -// Aggregate maps metadata keys to list of zettel identifier. -type Aggregate map[string][]ZettelID +) + +// AuthJSON contains the result of an authentication call. +type AuthJSON struct { + Token string `json:"token"` + Type string `json:"token_type"` + Expires int `json:"expires_in"` +} + +// ZidJSON contains the identifier data of a zettel. +type ZidJSON struct { + ID ZettelID `json:"id"` +} + +// MetaJSON contains the metadata of a zettel. +type MetaJSON struct { + Meta ZettelMeta `json:"meta"` + Rights ZettelRights `json:"rights"` +} + +// ZidMetaJSON contains the identifier and the metadata of a zettel. +type ZidMetaJSON struct { + ID ZettelID `json:"id"` + Meta ZettelMeta `json:"meta"` + Rights ZettelRights `json:"rights"` +} + +// ZidMetaRelatedList contains identifier/metadata of a zettel and the same for related zettel +type ZidMetaRelatedList struct { + ID ZettelID `json:"id"` + Meta ZettelMeta `json:"meta"` + Rights ZettelRights `json:"rights"` + List []ZidMetaJSON `json:"list"` +} + +// ZettelDataJSON contains all data for a zettel. +type ZettelDataJSON struct { + Meta ZettelMeta `json:"meta"` + Encoding string `json:"encoding"` + Content string `json:"content"` +} + +// ZettelJSON contains all data for a zettel, the identifier, the metadata, and the content. +type ZettelJSON struct { + ID ZettelID `json:"id"` + Meta ZettelMeta `json:"meta"` + Encoding string `json:"encoding"` + Content string `json:"content"` + Rights ZettelRights `json:"rights"` +} + +// ZettelListJSON contains data for a zettel list. +type ZettelListJSON struct { + Query string `json:"query"` + Human string `json:"human"` + List []ZidMetaJSON `json:"list"` +} + +// MapMeta maps metadata keys to list of metadata. +type MapMeta map[string][]ZettelID + +// MapListJSON specifies the map of metadata key to list of metadata that contains the key. +type MapListJSON struct { + Map MapMeta `json:"map"` +} + +// VersionJSON contains version information. +type VersionJSON struct { + Major int `json:"major"` + Minor int `json:"minor"` + Patch int `json:"patch"` + Info string `json:"info"` + Hash string `json:"hash"` +} Index: api/const.go ================================================================== --- api/const.go +++ api/const.go @@ -1,16 +1,13 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2021-present Detlef Stern +// Copyright (c) 2021-2022 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. -// -// SPDX-License-Identifier: EUPL-1.2 -// SPDX-FileCopyrightText: 2021-present Detlef Stern //----------------------------------------------------------------------------- package api import "fmt" @@ -23,55 +20,43 @@ ZidOperatingSystem = ZettelID("00000000000003") ZidLicense = ZettelID("00000000000004") ZidAuthors = ZettelID("00000000000005") ZidDependencies = ZettelID("00000000000006") ZidLog = ZettelID("00000000000007") - ZidMemory = ZettelID("00000000000008") ZidBoxManager = ZettelID("00000000000020") ZidMetadataKey = ZettelID("00000000000090") ZidParser = ZettelID("00000000000092") ZidStartupConfiguration = ZettelID("00000000000096") ZidConfiguration = ZettelID("00000000000100") // WebUI HTML templates are in the range 10000..19999 - ZidBaseTemplate = ZettelID("00000000010100") - ZidLoginTemplate = ZettelID("00000000010200") - ZidListTemplate = ZettelID("00000000010300") - ZidZettelTemplate = ZettelID("00000000010401") - ZidInfoTemplate = ZettelID("00000000010402") - ZidFormTemplate = ZettelID("00000000010403") - ZidRenameTemplate = ZettelID("00000000010404") - ZidDeleteTemplate = ZettelID("00000000010405") - ZidErrorTemplate = ZettelID("00000000010700") - - // WebUI sxn code zettel are in the range 19000..19999 - ZidSxnStart = ZettelID("00000000019000") - ZidSxnBase = ZettelID("00000000019990") + ZidBaseTemplate = ZettelID("00000000010100") + ZidLoginTemplate = ZettelID("00000000010200") + ZidListTemplate = ZettelID("00000000010300") + ZidZettelTemplate = ZettelID("00000000010401") + ZidInfoTemplate = ZettelID("00000000010402") + ZidFormTemplate = ZettelID("00000000010403") + ZidRenameTemplate = ZettelID("00000000010404") + ZidDeleteTemplate = ZettelID("00000000010405") + ZidContextTemplate = ZettelID("00000000010406") + ZidRolesTemplate = ZettelID("00000000010500") + ZidTagsTemplate = ZettelID("00000000010600") + ZidErrorTemplate = ZettelID("00000000010700") // CSS-related zettel are in the range 20000..29999 - ZidBaseCSS = ZettelID("00000000020001") - ZidUserCSS = ZettelID("00000000025001") + ZidBaseCSS = ZettelID("00000000020001") + ZidUserCSS = ZettelID("00000000025001") + ZidRoleCSSMap = ZettelID("00000000029000") // Maps roles to CSS zettel, which should be in the range 29001..29999. // WebUI JS zettel are in the range 30000..39999 // WebUI image zettel are in the range 40000..49999 ZidEmoji = ZettelID("00000000040001") - // Other sxn code zettel are in the range 50000..59999 - ZidSxnPrelude = ZettelID("00000000059900") - - // Predefined Zettelmarkup zettel are in the range 60000..69999 - ZidRoleZettelZettel = ZettelID("00000000060010") - ZidRoleConfigurationZettel = ZettelID("00000000060020") - ZidRoleRoleZettel = ZettelID("00000000060030") - ZidRoleTagZettel = ZettelID("00000000060040") - // Range 90000...99999 is reserved for zettel templates ZidTOCNewTemplate = ZettelID("00000000090000") ZidTemplateNewZettel = ZettelID("00000000090001") - ZidTemplateNewRole = ZettelID("00000000090004") - ZidTemplateNewTag = ZettelID("00000000090003") ZidTemplateNewUser = ZettelID("00000000090002") ZidDefaultHome = ZettelID("00010000000000") ) @@ -88,10 +73,11 @@ MetaString = "String" MetaTagSet = "TagSet" MetaTimestamp = "Timestamp" MetaURL = "URL" MetaWord = "Word" + MetaWordSet = "WordSet" MetaZettelmarkup = "Zettelmarkup" ) // Predefined general Metadata keys const ( @@ -98,33 +84,26 @@ KeyID = "id" KeyTitle = "title" KeyRole = "role" KeyTags = "tags" KeySyntax = "syntax" - KeyAuthor = "author" + KeyAllTags = "all-" + KeyTags KeyBack = "back" KeyBackward = "backward" KeyBoxNumber = "box-number" + KeyContentTags = "content-" + KeyTags KeyCopyright = "copyright" - KeyCreated = "created" KeyCredential = "credential" KeyDead = "dead" - KeyExpire = "expire" KeyFolge = "folge" - KeyFolgeRole = "folge-role" KeyForward = "forward" KeyLang = "lang" KeyLicense = "license" KeyModified = "modified" KeyPrecursor = "precursor" - KeyPredecessor = "predecessor" KeyPublished = "published" - KeyQuery = "query" KeyReadOnly = "read-only" - KeySubordinates = "subordinates" - KeySuccessors = "successors" - KeySuperior = "superior" KeySummary = "summary" KeyURL = "url" KeyUselessFiles = "useless-files" KeyUserID = "user-id" KeyUserRole = "user-role" @@ -131,28 +110,21 @@ KeyVisibility = "visibility" ) // Predefined Metadata values const ( + ValueRoleConfiguration = "configuration" + ValueRoleZettel = "zettel" + ValueSyntaxGif = "gif" + ValueSyntaxHTML = "html" + ValueSyntaxNone = "none" + ValueSyntaxSVG = "svg" + ValueSyntaxText = "text" + ValueSyntaxZmk = "zmk" ValueFalse = "false" ValueTrue = "true" ValueLangEN = "en" - ValueRoleConfiguration = "configuration" - ValueRoleTag = "tag" - ValueRoleRole = "role" - ValueRoleZettel = "zettel" - ValueSyntaxCSS = "css" - ValueSyntaxDraw = "draw" - ValueSyntaxGif = "gif" - ValueSyntaxHTML = "html" - ValueSyntaxMarkdown = "markdown" - ValueSyntaxMD = "md" - ValueSyntaxNone = "none" - ValueSyntaxSVG = "svg" - ValueSyntaxSxn = "sxn" - ValueSyntaxText = "text" - ValueSyntaxZmk = "zmk" ValueUserRoleCreator = "creator" ValueUserRoleOwner = "owner" ValueUserRoleReader = "reader" ValueUserRoleWriter = "writer" ValueVisibilityCreator = "creator" @@ -172,44 +144,47 @@ HeaderLocation = "Location" ) // Values for HTTP query parameter. const ( - QueryKeyCommand = "cmd" - QueryKeyEncoding = "enc" - QueryKeyParseOnly = "parseonly" - QueryKeyPart = "part" - QueryKeyPhrase = "phrase" - QueryKeyQuery = "q" - QueryKeyRole = "role" - QueryKeySeed = "_seed" - QueryKeyTag = "tag" + QueryKeyCommand = "_cmd" + QueryKeyDepth = "_depth" + QueryKeyDir = "_dir" + QueryKeyEncoding = "_enc" + QueryKeyKey = "_key" + QueryKeyLimit = "_limit" + QueryKeyMin = "_min" + QueryKeyNegate = "_negate" + QueryKeyOffset = "_offset" + QueryKeyOrder = "_order" + QueryKeyPart = "_part" + QueryKeyPhrase = "_phrase" + QueryKeySearch = "_s" + QueryKeySort = "_sort" +) + +// Supported dir values. +const ( + DirBackward = "backward" + DirForward = "forward" ) // Supported encoding values. const ( EncodingHTML = "html" - EncodingMD = "md" - EncodingSHTML = "shtml" - EncodingSz = "sz" + EncodingSexpr = "sexpr" EncodingText = "text" + EncodingZJSON = "zjson" EncodingZMK = "zmk" - - EncodingPlain = "plain" - EncodingData = "data" ) var mapEncodingEnum = map[string]EncodingEnum{ EncodingHTML: EncoderHTML, - EncodingMD: EncoderMD, - EncodingSHTML: EncoderSHTML, - EncodingSz: EncoderSz, + EncodingSexpr: EncoderSexpr, EncodingText: EncoderText, + EncodingZJSON: EncoderZJSON, EncodingZMK: EncoderZmk, - - EncodingPlain: EncoderPlain, - EncodingData: EncoderData, } var mapEnumEncoding = map[EncodingEnum]string{} func init() { for k, v := range mapEncodingEnum { @@ -230,18 +205,14 @@ // Values for EncoderEnum const ( EncoderUnknown EncodingEnum = iota EncoderHTML - EncoderMD - EncoderSHTML - EncoderSz + EncoderSexpr EncoderText + EncoderZJSON EncoderZmk - - EncoderPlain - EncoderData ) // String representation of an encoder key. func (e EncodingEnum) String() string { if f, ok := mapEnumEncoding[e]; ok { @@ -263,60 +234,5 @@ // Supported command values const ( CommandAuthenticated = Command("authenticated") CommandRefresh = Command("refresh") ) - -// Supported search operator representations -const ( - BackwardDirective = "BACKWARD" - ContextDirective = "CONTEXT" - CostDirective = "COST" - ForwardDirective = "FORWARD" - FullDirective = "FULL" - IdentDirective = "IDENT" - ItemsDirective = "ITEMS" - MaxDirective = "MAX" - LimitDirective = "LIMIT" - OffsetDirective = "OFFSET" - OrDirective = "OR" - OrderDirective = "ORDER" - PhraseDirective = "PHRASE" - PickDirective = "PICK" - RandomDirective = "RANDOM" - ReverseDirective = "REVERSE" - UnlinkedDirective = "UNLINKED" - - ActionSeparator = "|" - - AtomAction = "ATOM" - KeysAction = "KEYS" - MinAction = "MIN" - MaxAction = "MAX" - NumberedAction = "NUMBERED" - RedirectAction = "REDIRECT" - ReIndexAction = "REINDEX" - RSSAction = "RSS" - TitleAction = "TITLE" - - ExistOperator = "?" - ExistNotOperator = "!?" - - SearchOperatorNot = "!" - SearchOperatorEqual = "=" - SearchOperatorNotEqual = "!=" - SearchOperatorHas = ":" - SearchOperatorHasNot = "!:" - SearchOperatorPrefix = "[" - SearchOperatorNoPrefix = "![" - SearchOperatorSuffix = "]" - SearchOperatorNoSuffix = "!]" - SearchOperatorMatch = "~" - SearchOperatorNoMatch = "!~" - SearchOperatorLess = "<" - SearchOperatorNotLess = "!<" - SearchOperatorGreater = ">" - SearchOperatorNotGreater = "!>" -) - -// QueryPrefix is the prefix that denotes a query expression within a reference. -const QueryPrefix = "query:" Index: api/urlbuilder.go ================================================================== --- api/urlbuilder.go +++ api/urlbuilder.go @@ -1,85 +1,149 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-present Detlef Stern +// Copyright (c) 2020-2022 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. -// -// SPDX-License-Identifier: EUPL-1.2 -// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- package api -import "t73f.de/r/webs/urlbuilder" +import ( + "net/url" + "strings" +) + +type urlQuery struct{ key, val string } // URLBuilder should be used to create zettelstore URLs. type URLBuilder struct { - base urlbuilder.URLBuilder - prefix string + prefix string + key byte + rawLocal string + path []string + query []urlQuery + fragment string } // NewURLBuilder creates a new URL builder with the given prefix and key. func NewURLBuilder(prefix string, key byte) *URLBuilder { - for len(prefix) > 0 && prefix[len(prefix)-1] == '/' { - prefix = prefix[0 : len(prefix)-1] - } - result := URLBuilder{prefix: prefix} - if key != '/' { - result.base.AddPath(string([]byte{key})) - } - return &result + return &URLBuilder{prefix: prefix, key: key} } // Clone an URLBuilder func (ub *URLBuilder) Clone() *URLBuilder { cpy := new(URLBuilder) - ub.base.Copy(&cpy.base) - cpy.prefix = ub.prefix + cpy.key = ub.key + if len(ub.path) > 0 { + cpy.path = make([]string, 0, len(ub.path)) + cpy.path = append(cpy.path, ub.path...) + } + if len(ub.query) > 0 { + cpy.query = make([]urlQuery, 0, len(ub.query)) + cpy.query = append(cpy.query, ub.query...) + } + cpy.fragment = ub.fragment return cpy } + +// SetRawLocal sets everything that follows the prefix / key. +func (ub *URLBuilder) SetRawLocal(rawLocal string) *URLBuilder { + for len(rawLocal) > 0 && rawLocal[0] == '/' { + rawLocal = rawLocal[1:] + } + ub.rawLocal = rawLocal + ub.path = nil + ub.query = nil + ub.fragment = "" + return ub +} // SetZid sets the zettel identifier. func (ub *URLBuilder) SetZid(zid ZettelID) *URLBuilder { - ub.base.AddPath(string(zid)) + if len(ub.path) > 0 { + panic("Cannot add Zid") + } + ub.rawLocal = "" + ub.path = append(ub.path, string(zid)) return ub } // AppendPath adds a new path element func (ub *URLBuilder) AppendPath(p string) *URLBuilder { - ub.base.AddPath(p) + ub.rawLocal = "" + for len(p) > 0 && p[0] == '/' { + p = p[1:] + } + if p != "" { + ub.path = append(ub.path, p) + } return ub } -// AppendKVQuery adds a new key/value query parameter -func (ub *URLBuilder) AppendKVQuery(key, value string) *URLBuilder { - ub.base.AddQuery(key, value) +// AppendQuery adds a new query parameter +func (ub *URLBuilder) AppendQuery(key, value string) *URLBuilder { + ub.rawLocal = "" + ub.query = append(ub.query, urlQuery{key, value}) return ub } -// AppendQuery adds a new query -func (ub *URLBuilder) AppendQuery(value string) *URLBuilder { - if value != "" { - ub.base.AddQuery(QueryKeyQuery, value) - } +// AppendSearch adds a new search +func (ub *URLBuilder) AppendSearch(value string) *URLBuilder { + ub.rawLocal = "" + ub.query = append(ub.query, urlQuery{QueryKeySearch, value}) return ub } // ClearQuery removes all query parameters. func (ub *URLBuilder) ClearQuery() *URLBuilder { - ub.base.RemoveQueries() + ub.rawLocal = "" + ub.query = nil + ub.fragment = "" return ub } // SetFragment stores the fragment func (ub *URLBuilder) SetFragment(s string) *URLBuilder { - ub.base.SetFragment(s) + ub.rawLocal = "" + ub.fragment = s return ub } // String produces a string value. func (ub *URLBuilder) String() string { - return ub.prefix + ub.base.String() + var sb strings.Builder + + sb.WriteString(ub.prefix) + if ub.key != '/' { + sb.WriteByte(ub.key) + } + if ub.rawLocal != "" { + sb.WriteString(ub.rawLocal) + return sb.String() + } + for i, p := range ub.path { + if i > 0 || ub.key != '/' { + sb.WriteByte('/') + } + sb.WriteString(url.PathEscape(p)) + } + if len(ub.fragment) > 0 { + sb.WriteByte('#') + sb.WriteString(ub.fragment) + } + for i, q := range ub.query { + if i == 0 { + sb.WriteByte('?') + } else { + sb.WriteByte('&') + } + sb.WriteString(q.key) + if val := q.val; val != "" { + sb.WriteByte('=') + sb.WriteString(url.QueryEscape(val)) + } + } + return sb.String() } Index: attrs/attrs.go ================================================================== --- attrs/attrs.go +++ attrs/attrs.go @@ -1,25 +1,22 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-present Detlef Stern +// Copyright (c) 2020-2022 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. -// -// SPDX-License-Identifier: EUPL-1.2 -// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- // Package attrs stores attributes of zettel parts. package attrs import ( "strings" - "t73f.de/r/zsc/maps" + "zettelstore.de/c/maps" ) // Attributes store additional information about some node types. type Attributes map[string]string Index: attrs/attrs_test.go ================================================================== --- attrs/attrs_test.go +++ attrs/attrs_test.go @@ -1,24 +1,21 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2020-present Detlef Stern +// Copyright (c) 2020-2022 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. -// -// SPDX-License-Identifier: EUPL-1.2 -// SPDX-FileCopyrightText: 2020-present Detlef Stern //----------------------------------------------------------------------------- package attrs_test import ( "testing" - "t73f.de/r/zsc/attrs" + "zettelstore.de/c/attrs" ) func TestHasDefault(t *testing.T) { t.Parallel() attr := attrs.Attributes{} Index: client/client.go ================================================================== --- client/client.go +++ client/client.go @@ -1,39 +1,35 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2021-present Detlef Stern +// Copyright (c) 2021-2022 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. -// -// SPDX-License-Identifier: EUPL-1.2 -// SPDX-FileCopyrightText: 2021-present Detlef Stern //----------------------------------------------------------------------------- // Package client provides a client for accessing the Zettelstore via its API. package client import ( "bufio" "bytes" "context" - "fmt" + "encoding/json" "io" "net" "net/http" "net/url" "strconv" "strings" "time" - "t73f.de/r/sx" - "t73f.de/r/sx/sxreader" - "t73f.de/r/zsc/api" - "t73f.de/r/zsc/sexp" - "t73f.de/r/zsc/sz" + "codeberg.org/t73fde/sxpf" + "zettelstore.de/c/api" + "zettelstore.de/c/sexpr" + "zettelstore.de/c/zjson" ) // Client contains all data to execute requests. type Client struct { base string @@ -55,10 +51,13 @@ myURL.ForceQuery = false myURL.RawQuery = "" myURL.Fragment = "" myURL.RawFragment = "" base := myURL.String() + if !strings.HasSuffix(base, "/") { + base += "/" + } c := Client{ base: base, client: http.Client{ Timeout: 10 * time.Second, Transport: &http.Transport{ @@ -70,23 +69,10 @@ }, } return &c } -// AllowRedirect will modify the client to not follow redirect status code when -// using the Zettelstore. The original behaviour can be restored by settinh -// "allow" to false. -func (c *Client) AllowRedirect(allow bool) { - if allow { - c.client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - } - } else { - c.client.CheckRedirect = nil - } -} - // Error encapsulates the possible client call errors. type Error struct { StatusCode int Message string Body []byte @@ -124,12 +110,11 @@ Message: resp.Status[4:], Body: body, } } -// NewURLBuilder creates a new URL builder for the client with the given key. -func (c *Client) NewURLBuilder(key byte) *api.URLBuilder { +func (c *Client) newURLBuilder(key byte) *api.URLBuilder { return api.NewURLBuilder(c.base, key) } func (*Client) newRequest(ctx context.Context, method string, ub *api.URLBuilder, body io.Reader) (*http.Request, error) { return http.NewRequestWithContext(ctx, method, ub.String(), body) } @@ -180,26 +165,19 @@ } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return statusToError(resp) } - rd := sxreader.MakeReader(resp.Body) - obj, err := rd.Read() - if err != nil { - return err - } - vals, err := sexp.ParseList(obj, "ssi") + dec := json.NewDecoder(resp.Body) + var tinfo api.AuthJSON + err = dec.Decode(&tinfo) if err != nil { return err } - token := vals[1].(sx.String).GetValue() - if len(token) < 4 { - return fmt.Errorf("no valid token found: %q", token) - } - c.token = token - c.tokenType = vals[0].(sx.String).GetValue() - c.expires = time.Now().Add(time.Duration(vals[2].(sx.Int64)*9/10) * time.Second) + c.token = tinfo.Token + c.tokenType = tinfo.Type + c.expires = time.Now().Add(time.Duration(tinfo.Expires*10/9) * time.Second) return nil } func (c *Client) updateToken(ctx context.Context) error { if c.username == "" { @@ -212,30 +190,30 @@ } // Authenticate sets a new token by sending user name and password. func (c *Client) Authenticate(ctx context.Context) error { authData := url.Values{"username": {c.username}, "password": {c.password}} - req, err := c.newRequest(ctx, http.MethodPost, c.NewURLBuilder('a'), strings.NewReader(authData.Encode())) + req, err := c.newRequest(ctx, http.MethodPost, c.newURLBuilder('a'), strings.NewReader(authData.Encode())) if err != nil { return err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") return c.executeAuthRequest(req) } // RefreshToken updates the access token func (c *Client) RefreshToken(ctx context.Context) error { - req, err := c.newRequest(ctx, http.MethodPut, c.NewURLBuilder('a'), nil) + req, err := c.newRequest(ctx, http.MethodPut, c.newURLBuilder('a'), nil) if err != nil { return err } return c.executeAuthRequest(req) } // CreateZettel creates a new zettel and returns its URL. func (c *Client) CreateZettel(ctx context.Context, data []byte) (api.ZettelID, error) { - ub := c.NewURLBuilder('z') + ub := c.newURLBuilder('z') resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, bytes.NewBuffer(data), nil) if err != nil { return api.InvalidZID, err } defer resp.Body.Close() @@ -250,51 +228,57 @@ return zid, nil } return api.InvalidZID, err } -// CreateZettelData creates a new zettel and returns its URL. -func (c *Client) CreateZettelData(ctx context.Context, data api.ZettelData) (api.ZettelID, error) { +// CreateZettelJSON creates a new zettel and returns its URL. +func (c *Client) CreateZettelJSON(ctx context.Context, data *api.ZettelDataJSON) (api.ZettelID, error) { var buf bytes.Buffer - if _, err := sx.Print(&buf, sexp.EncodeZettel(data)); err != nil { + if err := encodeZettelData(&buf, data); err != nil { return api.InvalidZID, err } - ub := c.NewURLBuilder('z').AppendKVQuery(api.QueryKeyEncoding, api.EncodingData) + ub := c.newURLBuilder('j') resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, &buf, nil) if err != nil { return api.InvalidZID, err } defer resp.Body.Close() - rdr := sxreader.MakeReader(resp.Body) - obj, err := rdr.Read() if resp.StatusCode != http.StatusCreated { return api.InvalidZID, statusToError(resp) } + dec := json.NewDecoder(resp.Body) + var newZid api.ZidJSON + err = dec.Decode(&newZid) if err != nil { return api.InvalidZID, err } - return makeZettelID(obj) + if zid := newZid.ID; zid.IsValid() { + return zid, nil + } + return api.InvalidZID, err +} + +func encodeZettelData(buf *bytes.Buffer, data *api.ZettelDataJSON) error { + enc := json.NewEncoder(buf) + enc.SetEscapeHTML(false) + return enc.Encode(&data) } var bsLF = []byte{'\n'} -// QueryZettel returns a list of all Zettel. -func (c *Client) QueryZettel(ctx context.Context, query string) ([][]byte, error) { - ub := c.NewURLBuilder('z').AppendQuery(query) +// ListZettel returns a list of all Zettel. +func (c *Client) ListZettel(ctx context.Context, query url.Values) ([][]byte, error) { + ub := c.newQueryURLBuilder('z', query) resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) if err != nil { return nil, err } defer resp.Body.Close() - data, err := io.ReadAll(resp.Body) - switch resp.StatusCode { - case http.StatusOK: - case http.StatusNoContent: - return nil, nil - default: + if resp.StatusCode != http.StatusOK { return nil, statusToError(resp) } + data, err := io.ReadAll(resp.Body) if err != nil { return nil, err } lines := bytes.Split(data, bsLF) if len(lines[len(lines)-1]) == 0 { @@ -301,331 +285,259 @@ lines = lines[:len(lines)-1] } return lines, nil } -// QueryZettelData returns a list of zettel metadata. -func (c *Client) QueryZettelData(ctx context.Context, query string) (string, string, []api.ZidMetaRights, error) { - ub := c.NewURLBuilder('z').AppendKVQuery(api.QueryKeyEncoding, api.EncodingData).AppendQuery(query) - resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) - if err != nil { - return "", "", nil, err - } - defer resp.Body.Close() - rdr := sxreader.MakeReader(resp.Body) - obj, err := rdr.Read() - switch resp.StatusCode { - case http.StatusOK: - case http.StatusNoContent: - return "", "", nil, nil - default: - return "", "", nil, statusToError(resp) - } - if err != nil { - return "", "", nil, err - } - vals, err := sexp.ParseList(obj, "yppp") - if err != nil { - return "", "", nil, err - } - qVals, err := sexp.ParseList(vals[1], "ys") - if err != nil { - return "", "", nil, err - } - hVals, err := sexp.ParseList(vals[2], "ys") - if err != nil { - return "", "", nil, err - } - metaList, err := parseMetaList(vals[3].(*sx.Pair)) - return sz.GoValue(qVals[1]), sz.GoValue(hVals[1]), metaList, err -} - -func parseMetaList(metaPair *sx.Pair) ([]api.ZidMetaRights, error) { - if metaPair == nil { - return nil, fmt.Errorf("no zettel list") - } - if errSym := sexp.CheckSymbol(metaPair.Car(), "list"); errSym != nil { - return nil, errSym - } - var result []api.ZidMetaRights - for node := metaPair.Cdr(); !sx.IsNil(node); { - elem, isPair := sx.GetPair(node) - if !isPair { - return nil, fmt.Errorf("meta-list not a proper list: %v", metaPair.String()) - } - node = elem.Cdr() - vals, err := sexp.ParseList(elem.Car(), "yppp") - if err != nil { - return nil, err - } - - if errSym := sexp.CheckSymbol(vals[0], "zettel"); errSym != nil { - return nil, errSym - } - - idVals, err := sexp.ParseList(vals[1], "yi") - if err != nil { - return nil, err - } - if errSym := sexp.CheckSymbol(idVals[0], "id"); errSym != nil { - return nil, errSym - } - zid, err := makeZettelID(idVals[1]) - if err != nil { - return nil, err - } - - meta, err := sexp.ParseMeta(vals[2].(*sx.Pair)) - if err != nil { - return nil, err - } - - rights, err := sexp.ParseRights(vals[3]) - if err != nil { - return nil, err - } - - result = append(result, api.ZidMetaRights{ - ID: zid, - Meta: meta, - Rights: rights, - }) - } - return result, nil -} -func makeZettelID(obj sx.Object) (api.ZettelID, error) { - val, isInt64 := obj.(sx.Int64) - if !isInt64 || val <= 0 { - return api.InvalidZID, fmt.Errorf("invalid zettel ID: %v", val) - } - sVal := strconv.FormatInt(int64(val), 10) - if len(sVal) < 14 { - sVal = "00000000000000"[0:14-len(sVal)] + sVal - } - zid := api.ZettelID(sVal) - if !zid.IsValid() { - return api.InvalidZID, fmt.Errorf("invalid zettel ID: %v", val) - } - return zid, nil -} - -// QueryAggregate returns a aggregate as a result of a query. -// It is most often used in a query with an action, where the action is either -// a metadata key of type Word or of type TagSet. -func (c *Client) QueryAggregate(ctx context.Context, query string) (api.Aggregate, error) { - lines, err := c.QueryZettel(ctx, query) - if err != nil { - return nil, err - } - if len(lines) == 0 { - return nil, nil - } - agg := make(api.Aggregate, len(lines)) - for _, line := range lines { - if fields := bytes.Fields(line); len(fields) > 1 { - key := string(fields[0]) - for _, field := range fields[1:] { - if zid := api.ZettelID(string(field)); zid.IsValid() { - agg[key] = append(agg[key], zid) - } - } - } - } - return agg, nil -} - -// TagZettel returns the tag zettel of a given tag. -// -// This method only works if c.AllowRedirect(true) was called. -func (c *Client) TagZettel(ctx context.Context, tag string) (api.ZettelID, error) { - return c.fetchTagOrRoleZettel(ctx, api.QueryKeyTag, tag) -} - -// RoleZettel returns the tag zettel of a given tag. -// -// This method only works if c.AllowRedirect(true) was called. -func (c *Client) RoleZettel(ctx context.Context, role string) (api.ZettelID, error) { - return c.fetchTagOrRoleZettel(ctx, api.QueryKeyRole, role) -} - -func (c *Client) fetchTagOrRoleZettel(ctx context.Context, key, val string) (api.ZettelID, error) { - if c.client.CheckRedirect == nil { - panic("client does not allow to track redirect") - } - ub := c.NewURLBuilder('z').AppendKVQuery(key, val) - resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) - if err != nil { - return api.InvalidZID, err - } - defer resp.Body.Close() - data, err := io.ReadAll(resp.Body) - if err != nil { - return api.InvalidZID, err - } - - switch resp.StatusCode { - case http.StatusNotFound: - return "", nil - case http.StatusFound: - zid := api.ZettelID(data) - if zid.IsValid() { - return zid, nil - } - return api.InvalidZID, nil - default: - return api.InvalidZID, statusToError(resp) - } +// ListZettelJSON returns a list of zettel. +func (c *Client) ListZettelJSON(ctx context.Context, query url.Values) (string, string, []api.ZidMetaJSON, error) { + ub := c.newQueryURLBuilder('j', query) + resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) + if err != nil { + return "", "", nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", "", nil, statusToError(resp) + } + dec := json.NewDecoder(resp.Body) + var zl api.ZettelListJSON + err = dec.Decode(&zl) + if err != nil { + return "", "", nil, err + } + return zl.Query, zl.Human, zl.List, nil } // GetZettel returns a zettel as a string. func (c *Client) GetZettel(ctx context.Context, zid api.ZettelID, part string) ([]byte, error) { - ub := c.NewURLBuilder('z').SetZid(zid) + ub := c.newURLBuilder('z').SetZid(zid) if part != "" && part != api.PartContent { - ub.AppendKVQuery(api.QueryKeyPart, part) + ub.AppendQuery(api.QueryKeyPart, part) + } + resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, statusToError(resp) + } + return io.ReadAll(resp.Body) +} + +// GetZettelJSON returns a zettel as a JSON struct. +func (c *Client) GetZettelJSON(ctx context.Context, zid api.ZettelID) (*api.ZettelDataJSON, error) { + ub := c.newURLBuilder('j').SetZid(zid) + resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, statusToError(resp) + } + dec := json.NewDecoder(resp.Body) + var out api.ZettelDataJSON + err = dec.Decode(&out) + if err != nil { + return nil, err + } + return &out, nil +} + +// GetParsedZettel return a parsed zettel in a defined encoding. +func (c *Client) GetParsedZettel(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum) ([]byte, error) { + return c.getZettelString(ctx, 'p', zid, enc) +} + +// GetEvaluatedZettel return an evaluated zettel in a defined encoding. +func (c *Client) GetEvaluatedZettel(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum) ([]byte, error) { + return c.getZettelString(ctx, 'v', zid, enc) +} + +func (c *Client) getZettelString(ctx context.Context, key byte, zid api.ZettelID, enc api.EncodingEnum) ([]byte, error) { + ub := c.newURLBuilder(key).SetZid(zid) + ub.AppendQuery(api.QueryKeyEncoding, enc.String()) + ub.AppendQuery(api.QueryKeyPart, api.PartContent) + resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, statusToError(resp) + } + return io.ReadAll(resp.Body) +} + +// GetParsedZettelZJSON returns an parsed zettel as a JSON-decoded data structure. +func (c *Client) GetParsedSexpr(ctx context.Context, zid api.ZettelID, part string) (sxpf.Value, error) { + return c.getSexpr(ctx, 'p', zid, part) +} + +// GetEvaluatedZettelZJSON returns an evaluated zettel as a JSON-decoded data structure. +func (c *Client) GetEvaluatedSexpr(ctx context.Context, zid api.ZettelID, part string) (sxpf.Value, error) { + return c.getSexpr(ctx, 'v', zid, part) +} + +func (c *Client) getSexpr(ctx context.Context, key byte, zid api.ZettelID, part string) (sxpf.Value, error) { + ub := c.newURLBuilder(key).SetZid(zid) + ub.AppendQuery(api.QueryKeyEncoding, api.EncodingSexpr) + if part != "" { + ub.AppendQuery(api.QueryKeyPart, part) + } + resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, statusToError(resp) + } + + return sxpf.ParseValue(sexpr.Smk, bufio.NewReaderSize(resp.Body, 8)) +} + +// GetParsedZettelZJSON returns an parsed zettel as a JSON-decoded data structure. +func (c *Client) GetParsedZJSON(ctx context.Context, zid api.ZettelID, part string) (zjson.Value, error) { + return c.getZJSON(ctx, 'p', zid, part) +} + +// GetEvaluatedZettelZJSON returns an evaluated zettel as a JSON-decoded data structure. +func (c *Client) GetEvaluatedZJSON(ctx context.Context, zid api.ZettelID, part string) (zjson.Value, error) { + return c.getZJSON(ctx, 'v', zid, part) +} + +func (c *Client) getZJSON(ctx context.Context, key byte, zid api.ZettelID, part string) (zjson.Value, error) { + ub := c.newURLBuilder(key).SetZid(zid) + ub.AppendQuery(api.QueryKeyEncoding, api.EncodingZJSON) + if part != "" { + ub.AppendQuery(api.QueryKeyPart, part) + } + resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, statusToError(resp) + } + return zjson.Decode(resp.Body) +} + +// GetMeta returns the metadata of a zettel. +func (c *Client) GetMeta(ctx context.Context, zid api.ZettelID) (api.ZettelMeta, error) { + ub := c.newURLBuilder('m').SetZid(zid) + resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, statusToError(resp) + } + dec := json.NewDecoder(resp.Body) + var out api.MetaJSON + err = dec.Decode(&out) + if err != nil { + return nil, err + } + return out.Meta, nil +} + +// GetZettelOrder returns metadata of the given zettel and, more important, +// metadata of zettel that are referenced in a list within the first zettel. +func (c *Client) GetZettelOrder(ctx context.Context, zid api.ZettelID) (*api.ZidMetaRelatedList, error) { + ub := c.newURLBuilder('o').SetZid(zid) + resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, statusToError(resp) + } + dec := json.NewDecoder(resp.Body) + var out api.ZidMetaRelatedList + err = dec.Decode(&out) + if err != nil { + return nil, err + } + return &out, nil +} + +// ContextDirection specifies how the context should be calculated. +type ContextDirection uint8 + +// Allowed values for ContextDirection +const ( + _ ContextDirection = iota + DirBoth + DirBackward + DirForward +) + +// GetZettelContext returns metadata of the given zettel and, more important, +// metadata of zettel that for the context of the first zettel. +func (c *Client) GetZettelContext( + ctx context.Context, zid api.ZettelID, dir ContextDirection, depth, limit int) ( + *api.ZidMetaRelatedList, error, +) { + ub := c.newURLBuilder('x').SetZid(zid) + switch dir { + case DirBackward: + ub.AppendQuery(api.QueryKeyDir, api.DirBackward) + case DirForward: + ub.AppendQuery(api.QueryKeyDir, api.DirForward) + } + if depth > 0 { + ub.AppendQuery(api.QueryKeyDepth, strconv.Itoa(depth)) + } + if limit > 0 { + ub.AppendQuery(api.QueryKeyLimit, strconv.Itoa(limit)) } resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) if err != nil { return nil, err } defer resp.Body.Close() - data, err := io.ReadAll(resp.Body) - switch resp.StatusCode { - case http.StatusOK: - case http.StatusNoContent: - return nil, nil - default: - return nil, statusToError(resp) - } - return data, err -} - -// GetZettelData returns a zettel as a struct of its parts. -func (c *Client) GetZettelData(ctx context.Context, zid api.ZettelID) (api.ZettelData, error) { - ub := c.NewURLBuilder('z').SetZid(zid) - ub.AppendKVQuery(api.QueryKeyEncoding, api.EncodingData) - ub.AppendKVQuery(api.QueryKeyPart, api.PartZettel) - resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) - if err == nil { - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return api.ZettelData{}, statusToError(resp) - } - rdr := sxreader.MakeReader(resp.Body) - obj, err2 := rdr.Read() - if err2 == nil { - return sexp.ParseZettel(obj) - } - } - return api.ZettelData{}, err -} - -// GetParsedZettel return a parsed zettel in a defined encoding. -func (c *Client) GetParsedZettel(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum) ([]byte, error) { - return c.getZettelString(ctx, zid, enc, true) -} - -// GetEvaluatedZettel return an evaluated zettel in a defined encoding. -func (c *Client) GetEvaluatedZettel(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum) ([]byte, error) { - return c.getZettelString(ctx, zid, enc, false) -} - -func (c *Client) getZettelString(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum, parseOnly bool) ([]byte, error) { - ub := c.NewURLBuilder('z').SetZid(zid) - ub.AppendKVQuery(api.QueryKeyEncoding, enc.String()) - ub.AppendKVQuery(api.QueryKeyPart, api.PartContent) - if parseOnly { - ub.AppendKVQuery(api.QueryKeyParseOnly, "") - } - resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) - if err != nil { - return nil, err - } - defer resp.Body.Close() - switch resp.StatusCode { - case http.StatusOK: - case http.StatusNoContent: - default: - return nil, statusToError(resp) - } - return io.ReadAll(resp.Body) -} - -// GetParsedSz returns an parsed zettel as a Sexpr-decoded data structure. -func (c *Client) GetParsedSz(ctx context.Context, zid api.ZettelID, part string) (sx.Object, error) { - return c.getSz(ctx, zid, part, true) -} - -// GetEvaluatedSz returns an evaluated zettel as a Sexpr-decoded data structure. -func (c *Client) GetEvaluatedSz(ctx context.Context, zid api.ZettelID, part string) (sx.Object, error) { - return c.getSz(ctx, zid, part, false) -} - -func (c *Client) getSz(ctx context.Context, zid api.ZettelID, part string, parseOnly bool) (sx.Object, error) { - ub := c.NewURLBuilder('z').SetZid(zid) - ub.AppendKVQuery(api.QueryKeyEncoding, api.EncodingSz) - if part != "" { - ub.AppendKVQuery(api.QueryKeyPart, part) - } - if parseOnly { - ub.AppendKVQuery(api.QueryKeyParseOnly, "") - } + if resp.StatusCode != http.StatusOK { + return nil, statusToError(resp) + } + dec := json.NewDecoder(resp.Body) + var out api.ZidMetaRelatedList + err = dec.Decode(&out) + if err != nil { + return nil, err + } + return &out, nil +} + +// GetUnlinkedReferences returns connections to other zettel, embedded material, externals URLs. +func (c *Client) GetUnlinkedReferences( + ctx context.Context, zid api.ZettelID, query url.Values) (*api.ZidMetaRelatedList, error) { + ub := c.newQueryURLBuilder('u', query).SetZid(zid) resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, statusToError(resp) } - return sxreader.MakeReader(bufio.NewReaderSize(resp.Body, 8)).Read() -} - -// GetMetaData returns the metadata of a zettel. -func (c *Client) GetMetaData(ctx context.Context, zid api.ZettelID) (api.MetaRights, error) { - ub := c.NewURLBuilder('z').SetZid(zid) - ub.AppendKVQuery(api.QueryKeyEncoding, api.EncodingData) - ub.AppendKVQuery(api.QueryKeyPart, api.PartMeta) - resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) - if err != nil { - return api.MetaRights{}, err - } - defer resp.Body.Close() - rdr := sxreader.MakeReader(resp.Body) - obj, err := rdr.Read() - if resp.StatusCode != http.StatusOK { - return api.MetaRights{}, statusToError(resp) - } - if err != nil { - return api.MetaRights{}, err - } - vals, err := sexp.ParseList(obj, "ypp") - if err != nil { - return api.MetaRights{}, err - } - if errSym := sexp.CheckSymbol(vals[0], "list"); errSym != nil { - return api.MetaRights{}, err - } - - meta, err := sexp.ParseMeta(vals[1].(*sx.Pair)) - if err != nil { - return api.MetaRights{}, err - } - - rights, err := sexp.ParseRights(vals[2]) - if err != nil { - return api.MetaRights{}, err - } - - return api.MetaRights{ - Meta: meta, - Rights: rights, - }, nil + dec := json.NewDecoder(resp.Body) + var out api.ZidMetaRelatedList + err = dec.Decode(&out) + if err != nil { + return nil, err + } + return &out, nil } // UpdateZettel updates an existing zettel. func (c *Client) UpdateZettel(ctx context.Context, zid api.ZettelID, data []byte) error { - ub := c.NewURLBuilder('z').SetZid(zid) + ub := c.newURLBuilder('z').SetZid(zid) resp, err := c.buildAndExecuteRequest(ctx, http.MethodPut, ub, bytes.NewBuffer(data), nil) if err != nil { return err } defer resp.Body.Close() @@ -633,17 +545,17 @@ return statusToError(resp) } return nil } -// UpdateZettelData updates an existing zettel. -func (c *Client) UpdateZettelData(ctx context.Context, zid api.ZettelID, data api.ZettelData) error { +// UpdateZettelJSON updates an existing zettel. +func (c *Client) UpdateZettelJSON(ctx context.Context, zid api.ZettelID, data *api.ZettelDataJSON) error { var buf bytes.Buffer - if _, err := sx.Print(&buf, sexp.EncodeZettel(data)); err != nil { + if err := encodeZettelData(&buf, data); err != nil { return err } - ub := c.NewURLBuilder('z').SetZid(zid).AppendKVQuery(api.QueryKeyEncoding, api.EncodingData) + ub := c.newURLBuilder('j').SetZid(zid) resp, err := c.buildAndExecuteRequest(ctx, http.MethodPut, ub, &buf, nil) if err != nil { return err } defer resp.Body.Close() @@ -653,13 +565,13 @@ return nil } // RenameZettel renames a zettel. func (c *Client) RenameZettel(ctx context.Context, oldZid, newZid api.ZettelID) error { - ub := c.NewURLBuilder('z').SetZid(oldZid) + ub := c.newURLBuilder('z').SetZid(oldZid) h := http.Header{ - api.HeaderDestination: {c.NewURLBuilder('z').SetZid(newZid).String()}, + api.HeaderDestination: {c.newURLBuilder('z').SetZid(newZid).String()}, } resp, err := c.buildAndExecuteRequest(ctx, api.MethodMove, ub, nil, h) if err != nil { return err } @@ -670,11 +582,11 @@ return nil } // DeleteZettel deletes a zettel with the given identifier. func (c *Client) DeleteZettel(ctx context.Context, zid api.ZettelID) error { - ub := c.NewURLBuilder('z').SetZid(zid) + ub := c.newURLBuilder('z').SetZid(zid) resp, err := c.buildAndExecuteRequest(ctx, http.MethodDelete, ub, nil, nil) if err != nil { return err } defer resp.Body.Close() @@ -684,11 +596,11 @@ return nil } // ExecuteCommand will execute a given command at the Zettelstore. func (c *Client) ExecuteCommand(ctx context.Context, command api.Command) error { - ub := c.NewURLBuilder('x').AppendKVQuery(api.QueryKeyCommand, string(command)) + ub := c.newURLBuilder('x').AppendQuery(api.QueryKeyCommand, string(command)) resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, nil, nil) if err != nil { return err } defer resp.Body.Close() @@ -696,57 +608,64 @@ return statusToError(resp) } return nil } -// GetVersionInfo returns version information.. -func (c *Client) GetVersionInfo(ctx context.Context) (VersionInfo, error) { - resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, c.NewURLBuilder('x'), nil, nil) +func (c *Client) newQueryURLBuilder(key byte, query url.Values) *api.URLBuilder { + ub := c.newURLBuilder(key) + for key, values := range query { + if key == api.QueryKeyEncoding { + continue + } + for _, val := range values { + ub.AppendQuery(key, val) + } + } + return ub +} + +// ListMapMeta returns a map of all metadata values with the given key to the +// list of zettel IDs containing this value. +func (c *Client) ListMapMeta(ctx context.Context, key string) (api.MapMeta, error) { + err := c.updateToken(ctx) + if err != nil { + return nil, err + } + req, err := c.newRequest(ctx, http.MethodGet, c.newURLBuilder('m').AppendQuery(api.QueryKeyKey, key), nil) + if err != nil { + return nil, err + } + resp, err := c.executeRequest(req) if err != nil { - return VersionInfo{}, err + return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return VersionInfo{}, statusToError(resp) - } - rdr := sxreader.MakeReader(resp.Body) - obj, err := rdr.Read() - if err == nil { - if vals, errVals := sexp.ParseList(obj, "iiiss"); errVals == nil { - return VersionInfo{ - Major: int(vals[0].(sx.Int64)), - Minor: int(vals[1].(sx.Int64)), - Patch: int(vals[2].(sx.Int64)), - Info: vals[3].(sx.String).GetValue(), - Hash: vals[4].(sx.String).GetValue(), - }, nil - } - } - return VersionInfo{}, err -} - -// VersionInfo contains version information. -type VersionInfo struct { - Major int - Minor int - Patch int - Info string - Hash string -} - -// Get executes a GET request to the given URL and returns the read data. -func (c *Client) Get(ctx context.Context, ub *api.URLBuilder) ([]byte, error) { - resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil) + return nil, statusToError(resp) + } + dec := json.NewDecoder(resp.Body) + var mlj api.MapListJSON + err = dec.Decode(&mlj) if err != nil { return nil, err } - defer resp.Body.Close() - switch resp.StatusCode { - case http.StatusOK: - case http.StatusNoContent: - return nil, nil - default: - return nil, statusToError(resp) - } - data, err := io.ReadAll(resp.Body) - return data, err + return mlj.Map, nil +} + +// GetVersionJSON returns version information.. +func (c *Client) GetVersionJSON(ctx context.Context) (api.VersionJSON, error) { + resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, c.newURLBuilder('x'), nil, nil) + if err != nil { + return api.VersionJSON{}, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return api.VersionJSON{}, statusToError(resp) + } + dec := json.NewDecoder(resp.Body) + var version api.VersionJSON + err = dec.Decode(&version) + if err != nil { + return api.VersionJSON{}, err + } + return version, nil } Index: client/client_test.go ================================================================== --- client/client_test.go +++ client/client_test.go @@ -1,34 +1,34 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2022-present Detlef Stern +// Copyright (c) 2022 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. -// -// SPDX-License-Identifier: EUPL-1.2 -// SPDX-FileCopyrightText: 2022-present Detlef Stern //----------------------------------------------------------------------------- package client_test import ( "context" "flag" + "log" "net/http" "net/url" "testing" - "t73f.de/r/zsc/api" - "t73f.de/r/zsc/client" + "codeberg.org/t73fde/sxpf" + "zettelstore.de/c/api" + "zettelstore.de/c/client" + "zettelstore.de/c/zjson" ) func TestZettelList(t *testing.T) { c := getClient() - _, err := c.QueryZettel(context.Background(), "") + _, err := c.ListZettel(context.Background(), nil) if err != nil { t.Error(err) return } } @@ -44,21 +44,76 @@ } return } } -func TestGetSzZettel(t *testing.T) { +func TestGetZJSONZettel(t *testing.T) { + c := getClient() + data, err := c.GetEvaluatedZJSON(context.Background(), api.ZidDefaultHome, api.PartContent) + if err != nil { + t.Error(err) + return + } + if data == nil { + t.Error("No data") + } + var v vis + zjson.WalkBlock(&v, data.(zjson.Array), -1) + // t.Error("Argh") +} + +type vis struct{} + +func (*vis) BlockArray(a zjson.Array, pos int) zjson.CloseFunc { + log.Println("SBLO", pos, a) + return nil +} +func (*vis) InlineArray(a zjson.Array, pos int) zjson.CloseFunc { + log.Println("SINL", pos, a) + return nil +} +func (*vis) ItemArray(a zjson.Array, pos int) zjson.CloseFunc { + log.Println("SITE", pos, a) + return nil +} +func (*vis) BlockObject(t string, obj zjson.Object, pos int) (bool, zjson.CloseFunc) { + log.Println("BOBJ", pos, t, obj) + return true, nil +} +func (*vis) InlineObject(t string, obj zjson.Object, pos int) (bool, zjson.CloseFunc) { + log.Println("IOBJ", pos, t, obj) + return true, nil +} +func (*vis) Unexpected(val zjson.Value, pos int, exp string) { log.Println("Expect", pos, exp, val) } + +func TestGetSexprZettel(t *testing.T) { c := getClient() - value, err := c.GetEvaluatedSz(context.Background(), api.ZidDefaultHome, api.PartContent) + value, err := c.GetEvaluatedSexpr(context.Background(), api.ZidDefaultHome, api.PartContent) if err != nil { t.Error(err) return } - if value.IsNil() { + if value == nil { t.Error("No data") } + var env testEnv + env.t = t + res, err := sxpf.Eval(&env, value) + if err != nil { + t.Error(res, err) + } +} + +type testEnv struct{ t *testing.T } + +func noneFn(sxpf.Environment, *sxpf.Pair, int) (sxpf.Value, error) { return sxpf.Nil(), nil } +func (*testEnv) LookupForm(*sxpf.Symbol) (sxpf.Form, error) { + return sxpf.NewBuiltin("none", false, 0, -1, noneFn), nil } +func (*testEnv) EvalSymbol(sym *sxpf.Symbol) (sxpf.Value, error) { return sym, nil } +func (*testEnv) EvalOther(val sxpf.Value) (sxpf.Value, error) { return val, nil } +func (te *testEnv) EvalPair(p *sxpf.Pair) (sxpf.Value, error) { return sxpf.EvalCallOrSeq(te, p) } var baseURL string func init() { flag.StringVar(&baseURL, "base-url", "http://localhost:23123/", "Base URL") Index: go.mod ================================================================== --- go.mod +++ go.mod @@ -1,9 +1,5 @@ -module t73f.de/r/zsc - -go 1.22 - -require ( - t73f.de/r/sx v0.0.0-20240418072254-b6eff7d787f9 - t73f.de/r/sxwebs v0.0.0-20240422143910-320427142398 - t73f.de/r/webs v0.0.0-20240422103534-8f5067bc11bc -) +module zettelstore.de/c + +go 1.19 + +require codeberg.org/t73fde/sxpf v0.0.0-20220719090054-749a39d0a7a0 Index: go.sum ================================================================== --- go.sum +++ go.sum @@ -1,6 +1,2 @@ -t73f.de/r/sx v0.0.0-20240418072254-b6eff7d787f9 h1:lVPkYN8+J9f6JA9SmoF6icvpLxz4u3h1MCTuDYJYwdU= -t73f.de/r/sx v0.0.0-20240418072254-b6eff7d787f9/go.mod h1:G9pD1j2R6y9ZkPBb81mSnmwaAvTOg7r6jKp/OF7WeFA= -t73f.de/r/sxwebs v0.0.0-20240422143910-320427142398 h1:/G054FNxS8zEYbdhOTNk+GhdhjWBVt398FTm1Ud4A4o= -t73f.de/r/sxwebs v0.0.0-20240422143910-320427142398/go.mod h1:PtIkpRfTTiQITciKaWcTiAwy9FJ63WSQKciTp/dJbOA= -t73f.de/r/webs v0.0.0-20240422103534-8f5067bc11bc h1:i6tm/AEJUs8J8m7iDP8bTZgM0wYERh97RR47soJglxs= -t73f.de/r/webs v0.0.0-20240422103534-8f5067bc11bc/go.mod h1:UGAAtul0TK5ACeZ6zTS3SX6GqwMFXxlUpHiV8oqNq5w= +codeberg.org/t73fde/sxpf v0.0.0-20220719090054-749a39d0a7a0 h1:viya/OgeF16+i8caBPJmcLQhGpZodPh+/nxtJzSSO1s= +codeberg.org/t73fde/sxpf v0.0.0-20220719090054-749a39d0a7a0/go.mod h1:4fAHEF3VH+ofbZkF6NzqiItTNy2X11tVCnZX99jXouA= ADDED html/html.go Index: html/html.go ================================================================== --- /dev/null +++ html/html.go @@ -0,0 +1,106 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2022 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 html provides types, constants and function to work with HTML. +package html + +import ( + "io" + "strings" +) + +const ( + htmlQuot = """ // longer than """, but often requested in standards + htmlAmp = "&" + htmlLt = "<" + htmlGt = ">" + htmlNull = "\uFFFD" + htmlLitSpace = "\u00a0" + htmlVisSpace = "\u2423" +) + +var ( + htmlEscapes = []string{`&`, htmlAmp, + `<`, htmlLt, + `>`, htmlGt, + `"`, htmlQuot, + "\000", htmlNull, + } + htmlEscaper = strings.NewReplacer(htmlEscapes...) + + htmlVisEscapes = append(append([]string{}, htmlEscapes...), + " ", htmlVisSpace, + htmlLitSpace, htmlVisSpace, + ) + htmlVisEscaper = strings.NewReplacer(htmlVisEscapes...) +) + +// Escape writes to w the escaped HTML equivalent of the given string. +func Escape(w io.Writer, s string) (int, error) { return htmlEscaper.WriteString(w, s) } + +// EscapeVisible writes to w the escaped HTML equivalent of the given string. +// Each space is written as U-2423. +func EscapeVisible(w io.Writer, s string) (int, error) { return htmlVisEscaper.WriteString(w, s) } + +var ( + escQuot = []byte(htmlQuot) // longer than """, but often requested in standards + escAmp = []byte(htmlAmp) + escNull = []byte(htmlNull) +) + +// AttributeEscape writes to w the escaped HTML equivalent of the given string to be used +// in attributes. +func AttributeEscape(w io.Writer, s string) (int, error) { + length := 0 + last := 0 + var html []byte + lenS := len(s) + for i := 0; i < lenS; i++ { + switch s[i] { + case '\000': + html = escNull + case '"': + html = escQuot + case '&': + html = escAmp + default: + continue + } + l, err := io.WriteString(w, s[last:i]) + length += l + if err != nil { + return length, err + } + l, err = w.Write(html) + length += l + if err != nil { + return length, err + } + last = i + 1 + } + l, err := io.WriteString(w, s[last:]) + return length + l, err +} + +var unsafeSnippets = []string{ + " 0 { - return result - } - return nil -} -func doMakeMeta(obj sx.Object) Meta { - lst, isList := sx.GetPair(obj) - if !isList || !lst.Car().IsEqual(SymMeta) { - return nil - } - result := make(map[string]MetaValue) - for node := lst.Tail(); node != nil; node = node.Tail() { - if mv, found := makeMetaValue(node.Head()); found { - result[mv.Key] = mv - } - } - return result -} -func makeMetaValue(mnode *sx.Pair) (MetaValue, bool) { - var result MetaValue - typeSym, isSymbol := sx.GetSymbol(mnode.Car()) - if !isSymbol { - return result, false - } - next := mnode.Tail() - keySym, isSymbol := sx.GetSymbol(next.Car()) - if !isSymbol { - return result, false - } - next = next.Tail() - result.Type = typeSym.GetValue() - result.Key = keySym.GetValue() - result.Value = next.Car() - return result, true -} - -func (m Meta) GetString(key string) string { - if v, found := m[key]; found { - return GoValue(v.Value) - } - return "" -} - -func (m Meta) GetPair(key string) *sx.Pair { - if mv, found := m[key]; found { - if pair, isPair := sx.GetPair(mv.Value); isPair { - return pair - } - } - return nil -} ADDED text/stext.go Index: text/stext.go ================================================================== --- /dev/null +++ text/stext.go @@ -0,0 +1,98 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2022 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 text provides types, constants and function to work with text output. +package text + +import ( + "bytes" + "io" + + "codeberg.org/t73fde/sxpf" + "zettelstore.de/c/sexpr" +) + +// EvaluateInlineString returns the text content of the given inline list as a string. +func EvaluateInlineString(pl *sxpf.Pair) string { + var buf bytes.Buffer + env := newTextEnvironment(&buf) + env.EvalPair(pl) + return buf.String() +} + +type textEnvironment struct { + err error + w io.Writer + sm *sxpf.SymbolMap +} + +func newTextEnvironment(w io.Writer) textEnvironment { + sm := sxpf.NewSymbolMap(sexpr.Smk, nil) + for _, bFn := range builtins { + sym := bFn.sym + minArgs := bFn.minArgs + fn := bFn.fn + sm.Set(sym, sxpf.NewBuiltin( + sym.GetValue(), + true, minArgs, -1, + func(env sxpf.Environment, args *sxpf.Pair, _ int) (sxpf.Value, error) { + fn(env.(*textEnvironment), args) + return sxpf.Nil(), nil + }, + )) + } + + return textEnvironment{ + w: w, + sm: sm, + } +} + +func (env *textEnvironment) GetString(p *sxpf.Pair) (res string) { + if env.err == nil { + res, env.err = p.GetString() + return res + } + return "" +} + +func (env *textEnvironment) WriteString(s string) { + if env.err == nil { + _, env.err = io.WriteString(env.w, s) + } +} + +func (env *textEnvironment) LookupForm(sym *sxpf.Symbol) (sxpf.Form, error) { + return env.sm.LookupForm(sym) +} + +func (*textEnvironment) EvalSymbol(*sxpf.Symbol) (sxpf.Value, error) { return nil, nil } +func (env *textEnvironment) EvalPair(p *sxpf.Pair) (sxpf.Value, error) { + return sxpf.EvalCallOrSeq(env, p) +} +func (env *textEnvironment) EvalOther(val sxpf.Value) (sxpf.Value, error) { + if strVal, ok := val.(*sxpf.String); ok { + env.WriteString(strVal.GetValue()) + return nil, nil + } + return val, nil +} + +var builtins = []struct { + sym *sxpf.Symbol + minArgs int + fn func(env *textEnvironment, args *sxpf.Pair) +}{ + {sexpr.SymText, 1, func(env *textEnvironment, args *sxpf.Pair) { env.WriteString(env.GetString(args)) }}, + {sexpr.SymTag, 1, func(env *textEnvironment, args *sxpf.Pair) { env.WriteString(env.GetString(args)) }}, + {sexpr.SymSpace, 0, func(env *textEnvironment, _ *sxpf.Pair) { env.WriteString(" ") }}, + {sexpr.SymSoft, 0, func(env *textEnvironment, _ *sxpf.Pair) { env.WriteString(" ") }}, + {sexpr.SymHard, 0, func(env *textEnvironment, _ *sxpf.Pair) { env.WriteString("\n") }}, +} DELETED text/text.go Index: text/text.go ================================================================== --- text/text.go +++ /dev/null @@ -1,77 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (c) 2022-present 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. -// -// SPDX-License-Identifier: EUPL-1.2 -// SPDX-FileCopyrightText: 2022-present Detlef Stern -//----------------------------------------------------------------------------- - -// Package text provides types, constants and function to work with text output. -package text - -import ( - "strings" - - "t73f.de/r/sx" - "t73f.de/r/zsc/sz" -) - -// Encoder is the structure to hold relevant data to execute the encoding. -type Encoder struct { - sb strings.Builder -} - -func NewEncoder() *Encoder { - enc := &Encoder{ - sb: strings.Builder{}, - } - return enc -} - -func (enc *Encoder) Encode(lst *sx.Pair) string { - enc.executeList(lst) - result := enc.sb.String() - enc.sb.Reset() - return result -} - -// EvaluateInlineString returns the text content of the given inline list as a string. -func EvaluateInlineString(lst *sx.Pair) string { - return NewEncoder().Encode(lst) -} - -func (enc *Encoder) executeList(lst *sx.Pair) { - for elem := lst; elem != nil; elem = elem.Tail() { - enc.execute(elem.Car()) - } -} -func (enc *Encoder) execute(obj sx.Object) { - cmd, isPair := sx.GetPair(obj) - if !isPair { - return - } - sym := cmd.Car() - if sx.IsNil(sym) { - return - } - if sym.IsEqual(sz.SymText) { - args := cmd.Tail() - if args == nil { - return - } - if val, isString := sx.GetString(args.Car()); isString { - enc.sb.WriteString(val.GetValue()) - } - } else if sym.IsEqual(sz.SymSpace) || sym.IsEqual(sz.SymSoft) { - enc.sb.WriteByte(' ') - } else if sym.IsEqual(sz.SymHard) { - enc.sb.WriteByte('\n') - } else if !sym.IsEqual(sx.SymbolQuote) { - enc.executeList(cmd.Tail()) - } -} Index: text/text_test.go ================================================================== --- text/text_test.go +++ text/text_test.go @@ -1,46 +1,42 @@ //----------------------------------------------------------------------------- -// Copyright (c) 2022-present Detlef Stern +// Copyright (c) 2022 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. -// -// SPDX-License-Identifier: EUPL-1.2 -// SPDX-FileCopyrightText: 2022-present Detlef Stern //----------------------------------------------------------------------------- package text_test import ( - "strings" "testing" - "t73f.de/r/sx" - "t73f.de/r/sx/sxreader" - "t73f.de/r/zsc/text" + "codeberg.org/t73fde/sxpf" + "zettelstore.de/c/sexpr" + "zettelstore.de/c/text" ) -func TestSzText(t *testing.T) { +func TestSexprText(t *testing.T) { testcases := []struct { src string exp string }{ {"()", ""}, - {`(INLINE (TEXT "a"))`, "a"}, - {`(INLINE (SPACE "a"))`, " "}, + {`(TEXT "a")`, "a"}, + {`(SPACE "a")`, " "}, } for i, tc := range testcases { - sval, err := sxreader.MakeReader(strings.NewReader(tc.src)).Read() + sval, err := sxpf.ParseString(sexpr.Smk, tc.src) if err != nil { t.Error(err) continue } - seq, isPair := sx.GetPair(sval) - if !isPair { + seq, ok := sval.(*sxpf.Pair) + if !ok { t.Errorf("%d: not a list: %v", i, sval) } got := text.EvaluateInlineString(seq) if got != tc.exp { t.Errorf("%d: EncodeBlock(%q) == %q, but got %q", i, tc.src, tc.exp, got) Index: www/changes.wiki ================================================================== --- www/changes.wiki +++ www/changes.wiki @@ -1,61 +1,7 @@
go get
command. Since Go treats non-standard
-software and non-standard platforms quite badly, you must use some non-standard
-commands.
-
-First, you must install the version control system
-[https://fossil-scm.org|Fossil], which is a superior solution compared to Git,
-in too many use cases. It is just a single executable, nothing more. Make sure,
-it is in your search path for commands.
-
-How you can execute the following Go command to retrieve a given version of
-this library:
-
-GOVCS=zettelstore.de:fossil go get -x t73f.de/r/zsc@HASH
-
-where HASH
is the hash value of the commit you want to use.
-
-Go currently seems not to support software versions when the software is
-managed by Fossil. This explains the need for the hash value. However, this
-methods works and you can use the client software to access a Zettelstore.
ADDED zjson/const.go
Index: zjson/const.go
==================================================================
--- /dev/null
+++ zjson/const.go
@@ -0,0 +1,100 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2022 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 zjson
+
+// Values for Zettelmarkup element object names
+const (
+ NameType = ""
+ NameAttribute = "a"
+ NameBLOB = "j"
+ NameBinary = "o"
+ NameBlock = "b"
+ NameDescrList = "d"
+ NameDescription = "e"
+ NameInline = "i"
+ NameList = "c"
+ NameNumeric = "n"
+ NameSet = "y"
+ NameString = "s"
+ NameString2 = "q"
+ NameString3 = "v"
+ NameTable = "p"
+)
+
+// Values to specify the Zettelmarkup element type
+const (
+ TypeBLOB = "BLOB"
+ TypeBlock = "Block"
+ TypeBreakHard = "Hard"
+ TypeBreakSoft = "Soft"
+ TypeBreakThematic = "Thematic"
+ TypeCitation = "Cite"
+ TypeDescrList = "Description"
+ TypeEmbed = "Embed"
+ TypeEmbedBLOB = "EmbedBLOB"
+ TypeExcerpt = "Excerpt"
+ TypeFootnote = "Footnote"
+ TypeFormatDelete = "Delete"
+ TypeFormatEmph = "Emph"
+ TypeFormatInsert = "Insert"
+ TypeFormatQuote = "Quote"
+ TypeFormatSpan = "Span"
+ TypeFormatStrong = "Strong"
+ TypeFormatSub = "Sub"
+ TypeFormatSuper = "Super"
+ TypeHeading = "Heading"
+ TypeLink = "Link"
+ TypeListBullet = "Bullet"
+ TypeListOrdered = "Ordered"
+ TypeListQuotation = "Quotation"
+ TypeLiteralCode = "Code"
+ TypeLiteralComment = "Comment"
+ TypeLiteralHTML = "HTML"
+ TypeLiteralInput = "Input"
+ TypeLiteralOutput = "Output"
+ TypeLiteralMath = "Math"
+ TypeLiteralZettel = "Zettel"
+ TypeMark = "Mark"
+ TypeParagraph = "Para"
+ TypePoem = "Poem"
+ TypeSpace = "Space"
+ TypeTable = "Table"
+ TypeTag = "Tag"
+ TypeText = "Text"
+ TypeTransclude = "Transclude"
+ TypeVerbatimCode = "CodeBlock"
+ TypeVerbatimComment = "CommentBlock"
+ TypeVerbatimEval = "EvalBlock"
+ TypeVerbatimHTML = "HTMLBlock"
+ TypeVerbatimMath = "MathBlock"
+ TypeVerbatimZettel = "ZettelBlock"
+)
+
+// Values to specify the state of a reference
+const (
+ RefStateBased = "based"
+ RefStateBroken = "broken"
+ RefStateExternal = "external"
+ RefStateFound = "found"
+ RefStateHosted = "local"
+ RefStateInvalid = "invalid"
+ RefStateSearch = "search"
+ RefStateSelf = "self"
+ RefStateZettel = "zettel"
+)
+
+// Values for table cell alignment
+const (
+ AlignDefault = ""
+ AlignLeft = "<"
+ AlignCenter = ":"
+ AlignRight = ">"
+)
ADDED zjson/meta.go
Index: zjson/meta.go
==================================================================
--- /dev/null
+++ zjson/meta.go
@@ -0,0 +1,65 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2022 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 zjson
+
+type Meta map[string]MetaValue
+type MetaValue struct {
+ Type string
+ Key string
+ Value Value
+}
+
+func MakeMeta(val Value) Meta {
+ obj := MakeObject(val)
+ if len(obj) == 0 {
+ return nil
+ }
+ result := make(Meta, len(obj))
+ for k, v := range obj {
+ mvObj := MakeObject(v)
+ if len(mvObj) == 0 {
+ continue
+ }
+ mv := makeMetaValue(mvObj)
+ if mv.Type != "" {
+ result[k] = mv
+ }
+ }
+ return result
+}
+func makeMetaValue(mvObj Object) MetaValue {
+ mv := MetaValue{}
+ for n, val := range mvObj {
+ if n == NameType {
+ if t, ok := val.(string); ok {
+ mv.Type = t
+ }
+ } else {
+ mv.Key = n
+ mv.Value = val
+ }
+ }
+ return mv
+}
+
+func (m Meta) GetArray(key string) Array {
+ if v, found := m[key]; found {
+ return MakeArray(v.Value)
+ }
+ return nil
+}
+
+func (m Meta) GetString(key string) string {
+ if v, found := m[key]; found {
+ return MakeString(v.Value)
+ }
+ return ""
+}
ADDED zjson/zjson.go
Index: zjson/zjson.go
==================================================================
--- /dev/null
+++ zjson/zjson.go
@@ -0,0 +1,326 @@
+//-----------------------------------------------------------------------------
+// Copyright (c) 2022 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 zjson provides types, constants and function to work with the ZJSON
+// encoding of zettel.
+package zjson
+
+import (
+ "encoding/json"
+ "fmt"
+ "io"
+
+ "zettelstore.de/c/attrs"
+)
+
+// Value is the gerneric JSON value.
+type Value = interface{}
+
+// Array represents a JSON array.
+type Array = []Value
+
+// Object represents a JSON object.
+type Object = map[string]Value
+
+// Decode some JSON data and return the tree.
+func Decode(data io.Reader) (Value, error) {
+ var result interface{}
+ dec := json.NewDecoder(data)
+ dec.UseNumber()
+ err := dec.Decode(&result)
+ if err != nil {
+ return nil, err
+ }
+ return result, nil
+}
+
+// GetMetaContent returns the metadata and the content of a zettel ZJSON.
+func GetMetaContent(zjZettel Value) (Meta, Array) {
+ if zettel, ok := zjZettel.(Object); ok {
+ meta := MakeMeta(zettel["meta"])
+ content := MakeArray(zettel["content"])
+ return meta, content
+ }
+ return nil, nil
+}
+
+// Visitor provides functionality when a Value is traversed.
+type Visitor interface {
+ BlockArray(a Array, pos int) CloseFunc
+ InlineArray(a Array, pos int) CloseFunc
+ ItemArray(a Array, pos int) CloseFunc
+
+ BlockObject(t string, obj Object, pos int) (bool, CloseFunc)
+ InlineObject(t string, obj Object, pos int) (bool, CloseFunc)
+
+ Unexpected(val Value, pos int, exp string)
+}
+
+// CloseFunc is a function that executes after a ZJSON element is visited.
+type CloseFunc func()
+
+// WalkBlock traverses a block array.
+func WalkBlock(v Visitor, a Array, pos int) {
+ ef := v.BlockArray(a, pos)
+ for i, elem := range a {
+ WalkBlockObject(v, elem, i)
+ }
+ if ef != nil {
+ ef()
+ }
+}
+
+// WalkInline traverses an inline array.
+func WalkInline(v Visitor, a Array, pos int) {
+ ef := v.InlineArray(a, pos)
+ for i, elem := range a {
+ WalkInlineObject(v, elem, i)
+ }
+ if ef != nil {
+ ef()
+ }
+}
+
+// WalkBlockObject traverses a value as a JSON object in a block array.
+func WalkBlockObject(v Visitor, val Value, pos int) { walkObject(v, val, pos, v.BlockObject) }
+
+// WalkInlineObject traverses a value as a JSON object in an inline array.
+func WalkInlineObject(v Visitor, val Value, pos int) { walkObject(v, val, pos, v.InlineObject) }
+
+func walkObject(v Visitor, val Value, pos int, objFunc func(string, Object, int) (bool, CloseFunc)) {
+ obj, ok := val.(Object)
+ if !ok {
+ v.Unexpected(val, pos, "Object")
+ return
+ }
+
+ tVal, ok := obj[NameType]
+ if !ok {
+ v.Unexpected(obj, pos, "Object type")
+ return
+ }
+ t, ok := tVal.(string)
+ if !ok {
+ v.Unexpected(obj, pos, "Object type value")
+ return
+ }
+
+ doChilds, ef := objFunc(t, obj, pos)
+ if doChilds {
+ WalkBlockChild(v, obj, pos)
+ WalkItemChild(v, obj, pos)
+ WalkInlineChild(v, obj, pos)
+ walkDescriptionList(v, obj)
+ walkTable(v, obj, pos)
+ }
+ if ef != nil {
+ ef()
+ }
+}
+
+// WalkInlineChild traverses the array found at the name NameInline ('i').
+func WalkInlineChild(v Visitor, obj Object, pos int) {
+ if iVal, ok := obj[NameInline]; ok {
+ if il, ok := iVal.(Array); ok {
+ WalkInline(v, il, 0)
+ } else {
+ v.Unexpected(iVal, pos, "Inline array")
+ }
+ }
+}
+
+// WalkBlockChild traverses the array found at the name NameBlock ('b').
+func WalkBlockChild(v Visitor, obj Object, pos int) {
+ if bVal, ok := obj[NameBlock]; ok {
+ if bl, ok := bVal.(Array); ok {
+ WalkBlock(v, bl, 0)
+ } else {
+ v.Unexpected(bVal, pos, "Block array")
+ }
+ }
+}
+
+// WalkItemChild traverses the arrays found at the name NameList ('c').
+func WalkItemChild(v Visitor, obj Object, pos int) {
+ iVal, ok := obj[NameList]
+ if !ok {
+ return
+ }
+ it, ok := iVal.(Array)
+ if !ok {
+ v.Unexpected(iVal, pos, "Item array")
+ return
+ }
+ for i, l := range it {
+ ef := v.ItemArray(it, i)
+ if bl, ok := l.(Array); ok {
+ WalkBlock(v, bl, i)
+ } else {
+ v.Unexpected(l, i, "Item block array")
+ }
+ if ef != nil {
+ ef()
+ }
+ }
+}
+
+func walkDescriptionList(v Visitor, obj Object) {
+ descrs := GetArray(obj, NameDescrList)
+ if len(descrs) == 0 {
+ return
+ }
+ for i, elem := range descrs {
+ dObj := MakeObject(elem)
+ if dObj == nil {
+ continue
+ }
+ WalkInlineChild(v, dObj, i)
+ descr := GetArray(dObj, NameDescription)
+ if len(descr) == 0 {
+ continue
+ }
+ for j, ddv := range descr {
+ dd := MakeArray(ddv)
+ if len(dd) == 0 {
+ continue
+ }
+ WalkBlock(v, dd, j)
+ }
+ }
+}
+
+func walkTable(v Visitor, obj Object, pos int) {
+ tdata := GetArray(obj, NameTable)
+ if len(tdata) == 0 {
+ return
+ }
+ if len(tdata) != 2 {
+ v.Unexpected(obj, pos, "Table header/rows")
+ return
+ }
+ walkRow(v, MakeArray(tdata[0]))
+ if bArray := MakeArray(tdata[1]); len(bArray) > 0 {
+ for _, row := range bArray {
+ if rArray := MakeArray(row); rArray != nil {
+ walkRow(v, rArray)
+ }
+ }
+ }
+}
+func walkRow(v Visitor, row Array) {
+ if len(row) > 0 {
+ for _, cell := range row {
+ if cObj := MakeObject(cell); cObj != nil {
+ WalkInlineChild(v, cObj, 0)
+ }
+ }
+ }
+}
+
+// GetArray returns the array-typed value under the given name.
+func GetArray(obj Object, name string) Array {
+ if v, ok := obj[name]; ok && v != nil {
+ return MakeArray(v)
+ }
+ return nil
+}
+
+// GetNumber returns the numeric value at NameNumberic ('n') as a string.
+func GetNumber(obj Object) string {
+ if v, ok := obj[NameNumeric]; ok {
+ if n, ok := v.(json.Number); ok {
+ return string(n)
+ }
+ if f, ok := v.(float64); ok {
+ return fmt.Sprint(f)
+ }
+ }
+ return ""
+}
+
+// GetString returns the string value at the given name.
+func GetString(obj Object, name string) string {
+ if v, ok := obj[name]; ok {
+ return MakeString(v)
+ }
+ return ""
+}
+
+// MakeArray returns the given value as a JSON array.
+func MakeArray(val Value) Array {
+ if a, ok := val.(Array); ok {
+ return a
+ }
+ return nil
+}
+
+// MakeString returns the given value as a string.
+func MakeString(val Value) string {
+ if s, ok := val.(string); ok {
+ return s
+ }
+ return ""
+}
+
+// GetAttribute returns a copy of the attributes of the given object.
+func GetAttributes(obj Object) attrs.Attributes {
+ a := GetObject(obj, NameAttribute)
+ if len(a) == 0 {
+ return nil
+ }
+ result := make(attrs.Attributes, len(a))
+ for n, v := range a {
+ if val, ok := v.(string); ok {
+ result[n] = val
+ }
+ }
+ return result
+}
+
+// SetAttributes copies the attributes to the given object.
+func SetAttributes(obj Object, a attrs.Attributes) {
+ if len(a) == 0 {
+ delete(obj, NameAttribute)
+ }
+ val := make(Object)
+ for k, v := range a {
+ val[k] = v
+ }
+ obj[NameAttribute] = val
+}
+
+// GetObject returns the object found at the given object with the given name.
+func GetObject(obj Object, name string) Object {
+ if v, ok := obj[name]; ok && v != nil {
+ return MakeObject(v)
+ }
+ return nil
+}
+
+// MakeObject returns the given value as a JSON object.
+func MakeObject(val Value) Object {
+ if o, ok := val.(Object); ok {
+ return o
+ }
+ return nil
+}
+
+// GetParagraphInline return the inline list of the first paragraph (or nil if there is no such thing)
+func GetParagraphInline(a Array) Array {
+ if len(a) != 1 {
+ return nil
+ }
+ if o := MakeObject(a[0]); o != nil {
+ if GetString(o, NameType) == TypeParagraph {
+ return GetArray(o, NameInline)
+ }
+ }
+ return nil
+}