Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Difference From v0.13.0
To trunk
2023-09-25
| | |
18:05 |
|
...
(Leaf
check-in: 34a725707a user: stern tags: trunk)
|
15:36 |
|
...
(check-in: 60bb4e4c61 user: stern tags: trunk)
|
2023-08-07
| | |
13:56 |
|
...
(check-in: d2fe74163e user: stern tags: trunk)
|
13:53 |
|
...
(check-in: 37fed58a18 user: stern tags: trunk, release, v0.13.0)
|
10:49 |
|
...
(check-in: 8da4351a55 user: stern tags: trunk)
|
| | |
Changes to VERSION.
1
|
1
|
-
+
|
0.13.0
0.15.0-dev
|
Changes to auth/cred/cred.go.
︙ | | |
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
-
+
|
return false, nil
}
return false, err
}
func createFullCredential(zid id.Zid, ident, credential string) []byte {
var buf bytes.Buffer
buf.WriteString(zid.String())
buf.Write(zid.Bytes())
buf.WriteByte(' ')
buf.WriteString(ident)
buf.WriteByte(' ')
buf.WriteString(credential)
return buf.Bytes()
}
|
Changes to auth/impl/impl.go.
︙ | | |
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
-
+
|
if !ok || subject == "" {
return nil, ErrNoIdent
}
now := time.Now().Round(time.Second)
sClaim := sx.MakeList(
sx.Int64(kind),
sx.MakeString(subject),
sx.String(subject),
sx.Int64(now.Unix()),
sx.Int64(now.Add(d).Unix()),
sx.Int64(ident.Zid),
)
return sign(sClaim, a.secret)
}
|
︙ | | |
Changes to auth/policy/box.go.
︙ | | |
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
-
+
-
-
-
-
|
"zettelstore.de/z/web/server"
"zettelstore.de/z/zettel"
"zettelstore.de/z/zettel/id"
"zettelstore.de/z/zettel/meta"
)
// BoxWithPolicy wraps the given box inside a policy box.
func BoxWithPolicy(
func BoxWithPolicy(manager auth.AuthzManager, box box.Box, authConfig config.AuthConfig) (box.Box, auth.Policy) {
manager auth.AuthzManager,
box box.Box,
authConfig config.AuthConfig,
) (box.Box, auth.Policy) {
pol := newPolicy(manager, authConfig)
return newBox(box, pol), pol
}
// polBox implements a policy box.
type polBox struct {
box box.Box
|
︙ | | |
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
|
-
+
|
return pp.box.CanUpdateZettel(ctx, zettel)
}
func (pp *polBox) UpdateZettel(ctx context.Context, zettel zettel.Zettel) error {
zid := zettel.Meta.Zid
user := server.GetUser(ctx)
if !zid.IsValid() {
return &box.ErrInvalidID{Zid: zid}
return box.ErrInvalidZid{Zid: zid.String()}
}
// Write existing zettel
oldZettel, err := pp.box.GetZettel(ctx, zid)
if err != nil {
return err
}
if pp.policy.CanWrite(user, oldZettel.Meta, zettel.Meta) {
|
︙ | | |
Changes to box/box.go.
︙ | | |
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
|
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
|
-
-
+
+
+
+
-
-
+
+
-
+
|
// ErrStopped is returned if calling methods on a box that was not started.
var ErrStopped = errors.New("box is stopped")
// ErrReadOnly is returned if there is an attepmt to write to a read-only box.
var ErrReadOnly = errors.New("read-only box")
// ErrNotFound is returned if a zettel was not found in the box.
var ErrNotFound = errors.New("zettel not found")
// ErrZettelNotFound is returned if a zettel was not found in the box.
type ErrZettelNotFound struct{ Zid id.Zid }
func (eznf ErrZettelNotFound) Error() string { return "zettel not found: " + eznf.Zid.String() }
// ErrConflict is returned if a box operation detected a conflict..
// One example: if calculating a new zettel identifier takes too long.
var ErrConflict = errors.New("conflict")
// ErrCapacity is returned if a box has reached its capacity.
var ErrCapacity = errors.New("capacity exceeded")
// ErrInvalidID is returned if the zettel id is not appropriate for the box operation.
type ErrInvalidID struct{ Zid id.Zid }
// ErrInvalidZid is returned if the zettel id is not appropriate for the box operation.
type ErrInvalidZid struct{ Zid string }
func (err *ErrInvalidID) Error() string { return "invalid Zettel id: " + err.Zid.String() }
func (err ErrInvalidZid) Error() string { return "invalid Zettel id: " + err.Zid }
|
Changes to box/compbox/compbox.go.
︙ | | |
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
+
-
-
+
+
|
Content: zettel.NewContent(genContent(m)),
}, nil
}
cb.log.Trace().Msg("GetZettel/NoContent")
return zettel.Zettel{Meta: m}, nil
}
}
err := box.ErrZettelNotFound{Zid: zid}
cb.log.Trace().Err(box.ErrNotFound).Msg("GetZettel/Err")
return zettel.Zettel{}, box.ErrNotFound
cb.log.Trace().Err(err).Msg("GetZettel/Err")
return zettel.Zettel{}, err
}
func (*compBox) HasZettel(_ context.Context, zid id.Zid) bool {
_, found := myZettel[zid]
return found
}
|
︙ | | |
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
|
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
|
-
+
-
+
+
-
+
-
+
+
|
}
func (*compBox) AllowRenameZettel(_ context.Context, zid id.Zid) bool {
_, ok := myZettel[zid]
return !ok
}
func (cb *compBox) RenameZettel(_ context.Context, curZid, _ id.Zid) error {
func (cb *compBox) RenameZettel(_ context.Context, curZid, _ id.Zid) (err error) {
err := box.ErrNotFound
if _, ok := myZettel[curZid]; ok {
err = box.ErrReadOnly
} else {
err = box.ErrZettelNotFound{Zid: curZid}
}
cb.log.Trace().Err(err).Msg("RenameZettel")
return err
}
func (*compBox) CanDeleteZettel(context.Context, id.Zid) bool { return false }
func (cb *compBox) DeleteZettel(_ context.Context, zid id.Zid) error {
func (cb *compBox) DeleteZettel(_ context.Context, zid id.Zid) (err error) {
err := box.ErrNotFound
if _, ok := myZettel[zid]; ok {
err = box.ErrReadOnly
} else {
err = box.ErrZettelNotFound{Zid: zid}
}
cb.log.Trace().Err(err).Msg("DeleteZettel")
return err
}
func (cb *compBox) ReadStats(st *box.ManagedBoxStats) {
st.ReadOnly = true
|
︙ | | |
Changes to box/constbox/base.css.
︙ | | |
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
+
|
h1 { font-size:1.5rem; margin:.65rem 0 }
h2 { font-size:1.25rem; margin:.70rem 0 }
h3 { font-size:1.15rem; margin:.75rem 0 }
h4 { font-size:1.05rem; margin:.8rem 0; font-weight: bold }
h5 { font-size:1.05rem; margin:.8rem 0 }
h6 { font-size:1.05rem; margin:.8rem 0; font-weight: lighter }
p { margin: .5rem 0 0 0 }
p.zs-tag-zettel { margin-top: .5rem; margin-left: 0.5rem }
li,figure,figcaption,dl { margin: 0 }
dt { margin: .5rem 0 0 0 }
dt+dd { margin-top: 0 }
dd { margin: .5rem 0 0 2rem }
dd > p:first-child { margin: 0 0 0 0 }
blockquote {
border-left: 0.5rem solid lightgray;
|
︙ | | |
Changes to box/constbox/base.sxn.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
-
+
|
`(@@@@
(html ,@(if lang `((@ (lang ,lang))))
(head
(meta (@ (charset "utf-8")))
(meta (@ (name "viewport") (content "width=device-width, initial-scale=1.0")))
(meta (@ (name "generator") (content "Zettelstore")))
(meta (@ (name "format-detection") (content "telephone=no")))
,@META-HEADER
(link (@ (rel "stylesheet") (href ,css-base-url)))
(link (@ (rel "stylesheet") (href ,css-user-url)))
,@(if css-role-url `((link (@ (rel "stylesheet") (href ,css-role-url)))))
,@(ROLE-DEFAULT-meta (current-environment))
(title ,title))
(body
(nav (@ (class "zs-menu"))
(a (@ (href ,home-url)) "Home")
,@(if with-auth
`((div (@ (class "zs-dropdown"))
(button "User")
|
︙ | | |
36
37
38
39
40
41
42
43
44
45
46
47
48
|
36
37
38
39
40
41
42
43
44
45
46
47
48
|
-
+
|
`((div (@ (class "zs-dropdown"))
(button "New")
(nav (@ (class "zs-dropdown-content"))
,@(map wui-link new-zettel-links)
)))
)
(form (@ (action ,search-url))
(input (@ (type "text") (placeholder "Search..") (name ,query-key-query))))
(input (@ (type "text") (placeholder "Search..") (name ,query-key-query) (dir "auto"))))
)
(main (@ (class "content")) ,DETAIL)
,@(if FOOTER `((footer (hr) ,@FOOTER)))
,@(if debug-mode '((div (b "WARNING: Debug mode is enabled. DO NOT USE IN PRODUCTION!"))))
)))
|
Changes to box/constbox/constbox.go.
︙ | | |
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
+
-
-
+
+
|
}
func (cb *constBox) GetZettel(_ context.Context, zid id.Zid) (zettel.Zettel, error) {
if z, ok := cb.zettel[zid]; ok {
cb.log.Trace().Msg("GetZettel")
return zettel.Zettel{Meta: meta.NewWithData(zid, z.header), Content: z.content}, nil
}
err := box.ErrZettelNotFound{Zid: zid}
cb.log.Trace().Err(box.ErrNotFound).Msg("GetZettel")
return zettel.Zettel{}, box.ErrNotFound
cb.log.Trace().Err(err).Msg("GetZettel/Err")
return zettel.Zettel{}, err
}
func (cb *constBox) HasZettel(_ context.Context, zid id.Zid) bool {
_, found := cb.zettel[zid]
return found
}
|
︙ | | |
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
|
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
|
-
+
-
+
+
-
+
-
+
+
|
}
func (cb *constBox) AllowRenameZettel(_ context.Context, zid id.Zid) bool {
_, ok := cb.zettel[zid]
return !ok
}
func (cb *constBox) RenameZettel(_ context.Context, curZid, _ id.Zid) error {
func (cb *constBox) RenameZettel(_ context.Context, curZid, _ id.Zid) (err error) {
err := box.ErrNotFound
if _, ok := cb.zettel[curZid]; ok {
err = box.ErrReadOnly
} else {
err = box.ErrZettelNotFound{Zid: curZid}
}
cb.log.Trace().Err(err).Msg("RenameZettel")
return err
}
func (*constBox) CanDeleteZettel(context.Context, id.Zid) bool { return false }
func (cb *constBox) DeleteZettel(_ context.Context, zid id.Zid) error {
func (cb *constBox) DeleteZettel(_ context.Context, zid id.Zid) (err error) {
err := box.ErrNotFound
if _, ok := cb.zettel[zid]; ok {
err = box.ErrReadOnly
} else {
err = box.ErrZettelNotFound{Zid: zid}
}
cb.log.Trace().Err(err).Msg("DeleteZettel")
return err
}
func (cb *constBox) ReadStats(st *box.ManagedBoxStats) {
st.ReadOnly = true
|
︙ | | |
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
|
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
|
-
+
-
+
-
+
|
zettel.NewContent(contentDependencies)},
id.BaseTemplateZid: {
constHeader{
api.KeyTitle: "Zettelstore Base HTML Template",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxSxn,
api.KeyCreated: "20230510155100",
api.KeyModified: "20230523144403",
api.KeyModified: "20230827212200",
api.KeyVisibility: api.ValueVisibilityExpert,
},
zettel.NewContent(contentBaseSxn)},
id.LoginTemplateZid: {
constHeader{
api.KeyTitle: "Zettelstore Login Form HTML Template",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxSxn,
api.KeyCreated: "20200804111624",
api.KeyModified: "20230527144100",
api.KeyVisibility: api.ValueVisibilityExpert,
},
zettel.NewContent(contentLoginSxn)},
id.ZettelTemplateZid: {
constHeader{
api.KeyTitle: "Zettelstore Zettel HTML Template",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxSxn,
api.KeyCreated: "20230510155300",
api.KeyModified: "20230523212800",
api.KeyModified: "20230907203300",
api.KeyVisibility: api.ValueVisibilityExpert,
},
zettel.NewContent(contentZettelSxn)},
id.InfoTemplateZid: {
constHeader{
api.KeyTitle: "Zettelstore Info HTML Template",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxSxn,
api.KeyCreated: "20200804111624",
api.KeyModified: "20230621131500",
api.KeyModified: "20230907203300",
api.KeyVisibility: api.ValueVisibilityExpert,
},
zettel.NewContent(contentInfoSxn)},
id.FormTemplateZid: {
constHeader{
api.KeyTitle: "Zettelstore Form HTML Template",
api.KeyRole: api.ValueRoleConfiguration,
|
︙ | | |
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
|
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
|
+
+
+
+
+
+
+
+
+
+
+
-
+
-
+
+
+
-
+
-
-
-
-
-
-
-
-
-
|
zettel.NewContent(contentDeleteSxn)},
id.ListTemplateZid: {
constHeader{
api.KeyTitle: "Zettelstore List Zettel HTML Template",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxSxn,
api.KeyCreated: "20230704122100",
api.KeyModified: "20230829223600",
api.KeyVisibility: api.ValueVisibilityExpert,
},
zettel.NewContent(contentListZettelSxn)},
id.ErrorTemplateZid: {
constHeader{
api.KeyTitle: "Zettelstore Error HTML Template",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxSxn,
api.KeyCreated: "20210305133215",
api.KeyModified: "20230527224800",
api.KeyVisibility: api.ValueVisibilityExpert,
},
zettel.NewContent(contentErrorSxn)},
id.StartSxnZid: {
constHeader{
api.KeyTitle: "Zettelstore Sxn Start Code",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxSxn,
api.KeyCreated: "20230824160700",
api.KeyVisibility: api.ValueVisibilityExpert,
api.KeyPrecursor: id.BaseSxnZid.String(),
},
zettel.NewContent(contentStartCodeSxn)},
id.TemplateSxnZid: {
id.BaseSxnZid: {
constHeader{
api.KeyTitle: "Zettelstore Sxn Code for Templates",
api.KeyTitle: "Zettelstore Sxn Base Code",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxSxn,
api.KeyCreated: "20230619132800",
api.KeyModified: "20230907203100",
api.KeyReadOnly: api.ValueTrue,
api.KeyVisibility: api.ValueVisibilityExpert,
},
zettel.NewContent(contentTemplateCodeSxn)},
zettel.NewContent(contentBaseCodeSxn)},
id.MustParse(api.ZidBaseCSS): {
constHeader{
api.KeyTitle: "Zettelstore Base CSS",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxCSS,
api.KeyCreated: "20200804111624",
api.KeyVisibility: api.ValueVisibilityPublic,
},
zettel.NewContent(contentBaseCSS)},
id.MustParse(api.ZidUserCSS): {
constHeader{
api.KeyTitle: "Zettelstore User CSS",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxCSS,
api.KeyCreated: "20210622110143",
api.KeyVisibility: api.ValueVisibilityPublic,
},
zettel.NewContent([]byte("/* User-defined CSS */"))},
id.RoleCSSMapZid: {
constHeader{
api.KeyTitle: "Zettelstore Role to CSS Map",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxNone,
api.KeyCreated: "20220321183214",
api.KeyVisibility: api.ValueVisibilityExpert,
},
zettel.NewContent(nil)},
id.EmojiZid: {
constHeader{
api.KeyTitle: "Zettelstore Generic Emoji",
api.KeyRole: api.ValueRoleConfiguration,
api.KeySyntax: meta.SyntaxGif,
api.KeyReadOnly: api.ValueTrue,
api.KeyCreated: "20210504175807",
|
︙ | | |
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
|
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
|
+
+
+
-
+
|
//go:embed listzettel.sxn
var contentListZettelSxn []byte
//go:embed error.sxn
var contentErrorSxn []byte
//go:embed start.sxn
var contentStartCodeSxn []byte
//go:embed wuicode.sxn
var contentTemplateCodeSxn []byte
var contentBaseCodeSxn []byte
//go:embed base.css
var contentBaseCSS []byte
//go:embed emoji_spin.gif
var contentEmoji []byte
//go:embed newtoc.zettel
var contentNewTOCZettel []byte
//go:embed home.zettel
var contentHomeZettel []byte
|
Changes to box/constbox/form.sxn.
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
|
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
|
-
+
-
+
-
+
-
+
-
+
-
+
|
`(article
(header (h1 ,heading))
(form (@ (action ,form-action-url) (method "POST") (enctype "multipart/form-data"))
(div
(label (@ (for "zs-title")) "Title " (a (@ (title "Main heading of this zettel.")) (@H "ⓘ")))
(input (@ (class "zs-input") (type "text") (id "zs-title") (name "title") (placeholder "Title..") (value ,meta-title) (autofocus))))
(input (@ (class "zs-input") (type "text") (id "zs-title") (name "title") (placeholder "Title..") (value ,meta-title) (dir "auto") (autofocus))))
(div
(label (@ (for "zs-role")) "Role " (a (@ (title "One word, without spaces, to set the main role of this zettel.")) (@H "ⓘ")))
(input (@ (class "zs-input") (type "text") (id "zs-role") (name "role") (placeholder "role..") (value ,meta-role)
(input (@ (class "zs-input") (type "text") (id "zs-role") (name "role") (placeholder "role..") (value ,meta-role) (dir "auto")
,@(if role-data '((list "zs-role-data")))
))
,@(wui-datalist "zs-role-data" role-data)
)
(div
(label (@ (for "zs-tags")) "Tags " (a (@ (title "Tags must begin with an '#' sign. They are separated by spaces.")) (@H "ⓘ")))
(input (@ (class "zs-input") (type "text") (id "zs-tags") (name "tags") (placeholder "#tag") (value ,meta-tags))))
(input (@ (class "zs-input") (type "text") (id "zs-tags") (name "tags") (placeholder "#tag") (value ,meta-tags) (dir "auto"))))
(div
(label (@ (for "zs-meta")) "Metadata " (a (@ (title "Other metadata for this zettel. Each line contains a key/value pair, separated by a colon ':'.")) (@H "ⓘ")))
(textarea (@ (class "zs-input") (id "zs-meta") (name "meta") (rows "4") (placeholder "metakey: metavalue")) ,meta))
(textarea (@ (class "zs-input") (id "zs-meta") (name "meta") (rows "4") (placeholder "metakey: metavalue") (dir "auto")) ,meta))
(div
(label (@ (for "zs-syntax")) "Syntax " (a (@ (title "Syntax of zettel content below, one word. Typically 'zmk' (for zettelmarkup).")) (@H "ⓘ")))
(input (@ (class "zs-input") (type "text") (id "zs-syntax") (name "syntax") (placeholder "syntax..") (value ,meta-syntax)
(input (@ (class "zs-input") (type "text") (id "zs-syntax") (name "syntax") (placeholder "syntax..") (value ,meta-syntax) (dir "auto")
,@(if syntax-data '((list "zs-syntax-data")))
))
,@(wui-datalist "zs-syntax-data" syntax-data)
)
,@(if (bound? 'content)
`((div
(label (@ (for "zs-content")) "Content " (a (@ (title "Content for this zettel, according to above syntax.")) (@H "ⓘ")))
(textarea (@ (class "zs-input zs-content") (id "zs-content") (name "content") (rows "20") (placeholder "Zettel content..")) ,content)
(textarea (@ (class "zs-input zs-content") (id "zs-content") (name "content") (rows "20") (placeholder "Zettel content..") (dir "auto")) ,content)
))
)
(div
(input (@ (class "zs-primary") (type "submit") (value "Submit")))
(input (@ (class "zs-secondary") (type "submit") (value "Save") (formaction "?save")))
(input (@ (class "zs-upload") (type "file") (id "zs-file") (name "file")))
))
)
|
Changes to box/constbox/info.sxn.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
-
-
-
|
`(article
(header (h1 "Information for Zettel " ,zid)
(p
(a (@ (href ,web-url)) "Web")
(@H " · ") (a (@ (href ,context-url)) "Context")
,@(if (bound? 'edit-url) `((@H " · ") (a (@ (href ,edit-url)) "Edit")))
,@(if (bound? 'copy-url) `((@H " · ") (a (@ (href ,copy-url)) "Copy")))
,@(ROLE-DEFAULT-actions (current-environment))
,@(if (bound? 'version-url) `((@H " · ") (a (@ (href ,version-url)) "Version")))
,@(if (bound? 'child-url) `((@H " · ") (a (@ (href ,child-url)) "Child")))
,@(if (bound? 'folge-url) `((@H " · ") (a (@ (href ,folge-url)) "Folge")))
,@(if (bound? 'rename-url) `((@H " · ") (a (@ (href ,rename-url)) "Rename")))
,@(if (bound? 'delete-url) `((@H " · ") (a (@ (href ,delete-url)) "Delete")))
)
)
(h2 "Interpreted Metadata")
(table ,@(map wui-table-row metadata))
(h2 "References")
|
︙ | | |
Changes to box/constbox/listzettel.sxn.
1
2
3
4
5
6
7
8
9
10
11
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
+
+
+
|
`(article
(header (h1 ,heading))
(form (@ (action ,search-url))
(input (@ (class "zs-input") (type "text") (placeholder "Search..") (name ,query-key-query) (value ,query-value))))
(input (@ (class "zs-input") (type "text") (placeholder "Search..") (name ,query-key-query) (value ,query-value) (dir "auto"))))
,@(if (bound? 'tag-zettel)
`((p (@ (class "zs-tag-zettel")) "Tag zettel: " ,@tag-zettel))
)
,@content
,@endnotes
(form (@ (action ,(if (bound? 'create-url) create-url)))
"Other encodings: "
(a (@ (href ,data-url)) "data")
", "
(a (@ (href ,plain-url)) "plain")
|
︙ | | |
Added box/constbox/start.sxn.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
+
+
+
+
+
+
+
+
+
+
+
+
+
+
|
;;;----------------------------------------------------------------------------
;;; Copyright (c) 2023-present Detlef Stern
;;;
;;; This file is part of Zettelstore.
;;;
;;; Zettelstore is licensed under the latest version of the EUPL (European
;;; Union Public License). Please see file LICENSE.txt for your rights and
;;; obligations under this license.
;;;----------------------------------------------------------------------------
;;; This zettel is the start of the loading sequence for Sx code used in the
;;; Zettelstore. Via the precursor metadata, dependend zettel are evaluated
;;; before this zettel. You must always depend, directly or indirectly on the
;;; "Zettelstore Sxn Base Code" zettel. It provides the base definitions.
|
| | | | | | | | | | | | |
Changes to box/constbox/wuicode.sxn.
︙ | | |
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
-
+
|
;; wui-valid-link translates a local link into a HTML link. A link is a pair
;; (valid . url). If valid is not truish, only the invalid url is returned.
(define (wui-valid-link l)
(if (car l)
`(li (a (@ (href ,(cdr l))) ,(cdr l)))
`(li ,(cdr l))))
;; wui-link taks an url and returns a HTML link inside.
;; wui-link takes a link (title . url) and returns a HTML reference.
(define (wui-link q)
`(a (@ (href ,(cdr q))) ,(car q)))
;; wui-item-link taks a pair (text . url) and returns a HTML link inside
;; a list item.
(define (wui-item-link q) `(li ,(wui-link q)))
|
︙ | | |
60
61
62
63
64
65
66
|
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
|
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
|
;; wui-enc-matrix returns the HTML table of all encodings and parts.
(define (wui-enc-matrix matrix)
`(table
,@(map
(lambda (row) `(tr (th ,(car row)) ,@(map wui-tdata-link (cdr row))))
matrix)))
;; CSS-ROLE-map is a mapping (pair list, assoc list) of role names to zettel
;; identifier. It is used in the base template to update the metadata of the
;; HTML page to include some role specific CSS code.
;; Referenced in function "ROLE-DEFAULT-meta".
(define CSS-ROLE-map '())
;; ROLE-DEFAULT-meta returns some metadata for the base template. Any role
;; specific code should include the returned list of this function.
(define (ROLE-DEFAULT-meta env)
`(,@(let (meta-role (environment-lookup 'meta-role env))
(let (entry (assoc CSS-ROLE-map meta-role))
(if (pair? entry)
`((link (@ (rel "stylesheet") (href ,(zid-content-path (cdr entry))))))
)
)
)
)
)
;;; ACTION-SEPARATOR defines a HTML value that separates actions links.
(define ACTION-SEPARATOR '(@H " · "))
;;; ROLE-DEFAULT-actions returns the default text for actions.
(define (ROLE-DEFAULT-actions env)
`(,@(let (copy-url (environment-lookup 'copy-url env))
(if (defined? copy-url) `((@H " · ") (a (@ (href ,copy-url)) "Copy"))))
,@(let (version-url (environment-lookup 'version-url env))
(if (defined? version-url) `((@H " · ") (a (@ (href ,version-url)) "Version"))))
,@(let (child-url (environment-lookup 'child-url env))
(if (defined? child-url) `((@H " · ") (a (@ (href ,child-url)) "Child"))))
,@(let (folge-url (environment-lookup 'folge-url env))
(if (defined? folge-url) `((@H " · ") (a (@ (href ,folge-url)) "Folge"))))
)
)
;;; ROLE-tag-actions returns an additional action "Zettel" for zettel with role "tag".
(define (ROLE-tag-actions env)
`(,@(ROLE-DEFAULT-actions env)
,@(let (title (environment-lookup 'title env))
(if (and (defined? title) title)
`(,ACTION-SEPARATOR (a (@ (href ,(query->url (string-append "tags:" title)))) "Zettel"))
)
)
)
)
;;; ROLE-DEFAULT-heading returns the default text for headings, below the
;;; references of a zettel. In most cases it should be called from an
;;; overwriting function.
(define (ROLE-DEFAULT-heading env)
`(,@(let (meta-url (environment-lookup 'meta-url env))
(if (defined? meta-url) `((br) "URL: " ,(url-to-html meta-url))))
,@(let (meta-author (environment-lookup 'meta-author env))
(if (and (defined? meta-author) meta-author) `((br) "By " ,meta-author)))
)
)
|
Changes to box/constbox/zettel.sxn.
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
|
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
|
-
+
-
-
-
-
+
-
|
`(article
(header
(h1 ,heading)
(div (@ (class "zs-meta"))
,@(if (bound? 'edit-url) `((a (@ (href ,edit-url)) "Edit") (@H " · ")))
,zid (@H " · ")
(a (@ (href ,info-url)) "Info") (@H " · ")
"(" ,@(if (bound? 'role-url) `((a (@ (href ,role-url)) ,meta-role)))
,@(if (and (bound? 'folge-role-url) (bound? 'meta-folge-role))
`((@H " → ") (a (@ (href ,folge-role-url)) ,meta-folge-role)))
")"
,@(if tag-refs `((@H " · ") ,@tag-refs))
,@(if (bound? 'copy-url) `((@H " · ") (a (@ (href ,copy-url)) "Copy")))
,@(ROLE-DEFAULT-actions (current-environment))
,@(if (bound? 'version-url) `((@H " · ") (a (@ (href ,version-url)) "Version")))
,@(if (bound? 'child-url) `((@H " · ") (a (@ (href ,child-url)) "Child")))
,@(if (bound? 'folge-url) `((@H " · ") (a (@ (href ,folge-url)) "Folge")))
,@(if predecessor-refs `((br) "Predecessor: " ,predecessor-refs))
,@(if precursor-refs `((br) "Precursor: " ,precursor-refs))
,@(if superior-refs `((br) "Superior: " ,superior-refs))
,@(if (bound? 'meta-url) `((br) "URL: " ,(url-to-html meta-url)))
,@(ROLE-DEFAULT-heading (current-environment))
,@(let (author (and (bound? 'meta-author) meta-author)) (if author `((br) "By " ,author)))
)
)
,@content
,endnotes
,@(if (or folge-links subordinate-links back-links successor-links)
`((nav
,@(if folge-links `((details (@ (open)) (summary "Folgezettel") (ul ,@(map wui-item-link folge-links)))))
,@(if subordinate-links `((details (@ (open)) (summary "Subordinates") (ul ,@(map wui-item-link subordinate-links)))))
,@(if back-links `((details (@ (open)) (summary "Incoming") (ul ,@(map wui-item-link back-links)))))
,@(if successor-links `((details (@ (open)) (summary "Successors") (ul ,@(map wui-item-link successor-links)))))
))
)
)
|
Changes to box/dirbox/dirbox.go.
︙ | | |
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
|
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
|
-
+
|
dp.log.Trace().Err(err).Zid(meta.Zid).Msg("CreateZettel")
return meta.Zid, err
}
func (dp *dirBox) GetZettel(ctx context.Context, zid id.Zid) (zettel.Zettel, error) {
entry := dp.dirSrv.GetDirEntry(zid)
if !entry.IsValid() {
return zettel.Zettel{}, box.ErrNotFound
return zettel.Zettel{}, box.ErrZettelNotFound{Zid: zid}
}
m, c, err := dp.srvGetMetaContent(ctx, entry, zid)
if err != nil {
return zettel.Zettel{}, err
}
zettel := zettel.Zettel{Meta: m, Content: zettel.NewContent(c)}
dp.log.Trace().Zid(zid).Msg("GetZettel")
|
︙ | | |
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
|
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
|
-
+
|
if dp.readonly {
return box.ErrReadOnly
}
meta := zettel.Meta
zid := meta.Zid
if !zid.IsValid() {
return &box.ErrInvalidID{Zid: zid}
return box.ErrInvalidZid{Zid: zid.String()}
}
entry := dp.dirSrv.GetDirEntry(zid)
if !entry.IsValid() {
// Existing zettel, but new in this box.
entry = ¬ify.DirEntry{Zid: zid}
}
dp.updateEntryFromMetaContent(entry, meta, zettel.Content)
|
︙ | | |
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
|
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
|
-
+
-
+
|
func (dp *dirBox) RenameZettel(ctx context.Context, curZid, newZid id.Zid) error {
if curZid == newZid {
return nil
}
curEntry := dp.dirSrv.GetDirEntry(curZid)
if !curEntry.IsValid() {
return box.ErrNotFound
return box.ErrZettelNotFound{Zid: curZid}
}
if dp.readonly {
return box.ErrReadOnly
}
// Check whether zettel with new ID already exists in this box.
if dp.HasZettel(ctx, newZid) {
return &box.ErrInvalidID{Zid: newZid}
return box.ErrInvalidZid{Zid: newZid.String()}
}
oldMeta, oldContent, err := dp.srvGetMetaContent(ctx, curEntry, curZid)
if err != nil {
return err
}
|
︙ | | |
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
|
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
|
-
+
|
func (dp *dirBox) DeleteZettel(ctx context.Context, zid id.Zid) error {
if dp.readonly {
return box.ErrReadOnly
}
entry := dp.dirSrv.GetDirEntry(zid)
if !entry.IsValid() {
return box.ErrNotFound
return box.ErrZettelNotFound{Zid: zid}
}
err := dp.dirSrv.DeleteDirEntry(zid)
if err != nil {
return nil
}
err = dp.srvDeleteZettel(ctx, entry, zid)
if err == nil {
|
︙ | | |
Changes to box/dirbox/service.go.
︙ | | |
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
-
-
+
+
|
"zettelstore.de/z/zettel/id"
"zettelstore.de/z/zettel/meta"
)
func fileService(i uint32, log *logger.Logger, dirPath string, cmds <-chan fileCmd) {
// Something may panic. Ensure a running service.
defer func() {
if r := recover(); r != nil {
kernel.Main.LogRecover("FileService", r)
if ri := recover(); ri != nil {
kernel.Main.LogRecover("FileService", ri)
go fileService(i, log, dirPath, cmds)
}
}()
log.Trace().Uint("i", uint64(i)).Str("dirpath", dirPath).Msg("File service started")
for cmd := range cmds {
cmd.run(log, dirPath)
|
︙ | | |
Changes to box/filebox/zipbox.go.
︙ | | |
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
-
+
|
zb.log.Trace().Err(err).Msg("CreateZettel")
return id.Invalid, err
}
func (zb *zipBox) GetZettel(_ context.Context, zid id.Zid) (zettel.Zettel, error) {
entry := zb.dirSrv.GetDirEntry(zid)
if !entry.IsValid() {
return zettel.Zettel{}, box.ErrNotFound
return zettel.Zettel{}, box.ErrZettelNotFound{Zid: zid}
}
reader, err := zip.OpenReader(zb.name)
if err != nil {
return zettel.Zettel{}, err
}
defer reader.Close()
|
︙ | | |
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
|
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
|
-
+
-
+
|
func (zb *zipBox) RenameZettel(_ context.Context, curZid, newZid id.Zid) error {
err := box.ErrReadOnly
if curZid == newZid {
err = nil
}
curEntry := zb.dirSrv.GetDirEntry(curZid)
if !curEntry.IsValid() {
err = box.ErrNotFound
err = box.ErrZettelNotFound{Zid: curZid}
}
zb.log.Trace().Err(err).Msg("RenameZettel")
return err
}
func (*zipBox) CanDeleteZettel(context.Context, id.Zid) bool { return false }
func (zb *zipBox) DeleteZettel(_ context.Context, zid id.Zid) error {
err := box.ErrReadOnly
entry := zb.dirSrv.GetDirEntry(zid)
if !entry.IsValid() {
err = box.ErrNotFound
err = box.ErrZettelNotFound{Zid: zid}
}
zb.log.Trace().Err(err).Msg("DeleteZettel")
return err
}
func (zb *zipBox) ReadStats(st *box.ManagedBoxStats) {
st.ReadOnly = true
|
︙ | | |
Changes to box/manager/anteroom.go.
︙ | | |
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
|
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
|
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
+
-
+
-
-
+
+
-
-
-
+
+
+
-
+
|
num uint64
next *anteroom
waiting id.Set
curLoad int
reload bool
}
type anterooms struct {
type anteroomQueue struct {
mx sync.Mutex
nextNum uint64
first *anteroom
last *anteroom
maxLoad int
}
func newAnterooms(maxLoad int) *anterooms { return &anterooms{maxLoad: maxLoad} }
func newAnteroomQueue(maxLoad int) *anteroomQueue { return &anteroomQueue{maxLoad: maxLoad} }
func (ar *anterooms) EnqueueZettel(zid id.Zid) {
func (ar *anteroomQueue) EnqueueZettel(zid id.Zid) {
if !zid.IsValid() {
return
}
ar.mx.Lock()
defer ar.mx.Unlock()
if ar.first == nil {
ar.first = ar.makeAnteroom(zid)
ar.last = ar.first
return
}
for room := ar.first; room != nil; room = room.next {
if room.reload {
continue // Do not put zettel in reload room
}
if _, ok := room.waiting[zid]; ok {
// Zettel is already waiting. Nothing to do.
return
}
}
if room := ar.last; !room.reload && (ar.maxLoad == 0 || room.curLoad < ar.maxLoad) {
room.waiting.Zid(zid)
room.waiting.Add(zid)
room.curLoad++
return
}
room := ar.makeAnteroom(zid)
ar.last.next = room
ar.last = room
}
func (ar *anterooms) makeAnteroom(zid id.Zid) *anteroom {
func (ar *anteroomQueue) makeAnteroom(zid id.Zid) *anteroom {
ar.nextNum++
if zid == id.Invalid {
return &anteroom{num: ar.nextNum, next: nil, waiting: nil, curLoad: 0, reload: true}
}
c := ar.maxLoad
if c == 0 {
c = 100
}
waiting := id.NewSetCap(ar.maxLoad, zid)
return &anteroom{num: ar.nextNum, next: nil, waiting: waiting, curLoad: 1, reload: false}
}
func (ar *anterooms) Reset() {
func (ar *anteroomQueue) Reset() {
ar.mx.Lock()
defer ar.mx.Unlock()
ar.first = ar.makeAnteroom(id.Invalid)
ar.last = ar.first
}
func (ar *anterooms) Reload(newZids id.Set) uint64 {
func (ar *anteroomQueue) Reload(allZids id.Set) uint64 {
ar.mx.Lock()
defer ar.mx.Unlock()
ar.deleteReloadedRooms()
if ns := len(newZids); ns > 0 {
if ns := len(allZids); ns > 0 {
ar.nextNum++
ar.first = &anteroom{num: ar.nextNum, next: ar.first, waiting: newZids, curLoad: ns, reload: true}
ar.first = &anteroom{num: ar.nextNum, next: ar.first, waiting: allZids, curLoad: ns, reload: true}
if ar.first.next == nil {
ar.last = ar.first
}
return ar.nextNum
}
ar.first = nil
ar.last = nil
return 0
}
func (ar *anterooms) deleteReloadedRooms() {
func (ar *anteroomQueue) deleteReloadedRooms() {
room := ar.first
for room != nil && room.reload {
room = room.next
}
ar.first = room
if room == nil {
ar.last = nil
}
}
func (ar *anterooms) Dequeue() (arAction, id.Zid, uint64) {
func (ar *anteroomQueue) Dequeue() (arAction, id.Zid, uint64) {
ar.mx.Lock()
defer ar.mx.Unlock()
first := ar.first
if ar.first == nil {
if first == nil {
return arNothing, id.Invalid, 0
}
roomNo := ar.first.num
if ar.first.waiting == nil {
roomNo := first.num
if first.waiting == nil && first.reload {
ar.removeFirst()
return arReload, id.Invalid, roomNo
}
for zid := range ar.first.waiting {
delete(ar.first.waiting, zid)
if len(ar.first.waiting) == 0 {
for zid := range first.waiting {
delete(first.waiting, zid)
if len(first.waiting) == 0 {
ar.removeFirst()
}
return arZettel, zid, roomNo
}
ar.removeFirst()
return arNothing, id.Invalid, 0
}
func (ar *anterooms) removeFirst() {
func (ar *anteroomQueue) removeFirst() {
ar.first = ar.first.next
if ar.first == nil {
ar.last = nil
}
}
|
Changes to box/manager/anteroom_test.go.
︙ | | |
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
-
+
|
"testing"
"zettelstore.de/z/zettel/id"
)
func TestSimple(t *testing.T) {
t.Parallel()
ar := newAnterooms(2)
ar := newAnteroomQueue(2)
ar.EnqueueZettel(id.Zid(1))
action, zid, rno := ar.Dequeue()
if zid != id.Zid(1) || action != arZettel || rno != 1 {
t.Errorf("Expected arZettel/1/1, but got %v/%v/%v", action, zid, rno)
}
_, zid, _ = ar.Dequeue()
if zid != id.Invalid {
|
︙ | | |
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
-
+
|
if count != 3 {
t.Errorf("Expected 3 dequeues, but got %v", count)
}
}
func TestReset(t *testing.T) {
t.Parallel()
ar := newAnterooms(1)
ar := newAnteroomQueue(1)
ar.EnqueueZettel(id.Zid(1))
ar.Reset()
action, zid, _ := ar.Dequeue()
if action != arReload || zid != id.Invalid {
t.Errorf("Expected reload & invalid Zid, but got %v/%v", action, zid)
}
ar.Reload(id.NewSet(3, 4))
|
︙ | | |
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
|
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
|
-
+
-
+
|
t.Errorf("Expected 5/arZettel, but got %v/%v", zid, action)
}
action, zid, _ = ar.Dequeue()
if action != arNothing || zid != id.Invalid {
t.Errorf("Expected nothing & invalid Zid, but got %v/%v", action, zid)
}
ar = newAnterooms(1)
ar = newAnteroomQueue(1)
ar.Reload(id.NewSet(id.Zid(6)))
action, zid, _ = ar.Dequeue()
if zid != id.Zid(6) || action != arZettel {
t.Errorf("Expected 6/arZettel, but got %v/%v", zid, action)
}
action, zid, _ = ar.Dequeue()
if action != arNothing || zid != id.Invalid {
t.Errorf("Expected nothing & invalid Zid, but got %v/%v", action, zid)
}
ar = newAnterooms(1)
ar = newAnteroomQueue(1)
ar.EnqueueZettel(id.Zid(8))
ar.Reload(nil)
action, zid, _ = ar.Dequeue()
if action != arNothing || zid != id.Invalid {
t.Errorf("Expected nothing & invalid Zid, but got %v/%v", action, zid)
}
}
|
Changes to box/manager/box.go.
︙ | | |
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
+
-
+
-
+
|
mgr.mgrLog.Debug().Zid(zid).Msg("GetZettel")
if mgr.State() != box.StartStateStarted {
return zettel.Zettel{}, box.ErrStopped
}
mgr.mgrMx.RLock()
defer mgr.mgrMx.RUnlock()
for i, p := range mgr.boxes {
var errZNF box.ErrZettelNotFound
if z, err := p.GetZettel(ctx, zid); err != box.ErrNotFound {
if z, err := p.GetZettel(ctx, zid); !errors.As(err, &errZNF) {
if err == nil {
mgr.Enrich(ctx, z.Meta, i+1)
}
return z, err
}
}
return zettel.Zettel{}, box.ErrNotFound
return zettel.Zettel{}, box.ErrZettelNotFound{Zid: zid}
}
// GetAllZettel retrieves a specific zettel from all managed boxes.
func (mgr *Manager) GetAllZettel(ctx context.Context, zid id.Zid) ([]zettel.Zettel, error) {
mgr.mgrLog.Debug().Zid(zid).Msg("GetAllZettel")
if mgr.State() != box.StartStateStarted {
return nil, box.ErrStopped
|
︙ | | |
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
|
-
+
|
if mgr.State() != box.StartStateStarted {
return nil, box.ErrStopped
}
result := id.Set{}
mgr.mgrMx.RLock()
defer mgr.mgrMx.RUnlock()
for _, p := range mgr.boxes {
err := p.ApplyZid(ctx, func(zid id.Zid) { result.Zid(zid) }, func(id.Zid) bool { return true })
err := p.ApplyZid(ctx, func(zid id.Zid) { result.Add(zid) }, func(id.Zid) bool { return true })
if err != nil {
return nil, err
}
}
return result, nil
}
|
︙ | | |
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
|
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
|
-
+
-
+
|
return result, nil
}
selected := map[id.Zid]*meta.Meta{}
for _, term := range compSearch.Terms {
rejected := id.Set{}
handleMeta := func(m *meta.Meta) {
zid := m.Zid
if rejected.Contains(zid) {
if rejected.ContainsOrNil(zid) {
mgr.mgrLog.Trace().Zid(zid).Msg("SelectMeta/alreadyRejected")
return
}
if _, ok := selected[zid]; ok {
mgr.mgrLog.Trace().Zid(zid).Msg("SelectMeta/alreadySelected")
return
}
if compSearch.PreMatch(m) && term.Match(m) {
selected[zid] = m
mgr.mgrLog.Trace().Zid(zid).Msg("SelectMeta/match")
} else {
rejected.Zid(zid)
rejected.Add(zid)
mgr.mgrLog.Trace().Zid(zid).Msg("SelectMeta/reject")
}
}
for _, p := range mgr.boxes {
if err2 := p.ApplyMeta(ctx, handleMeta, term.Retrieve); err2 != nil {
return nil, err2
}
|
︙ | | |
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
|
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
|
+
-
+
|
if mgr.State() != box.StartStateStarted {
return box.ErrStopped
}
mgr.mgrMx.RLock()
defer mgr.mgrMx.RUnlock()
for i, p := range mgr.boxes {
err := p.RenameZettel(ctx, curZid, newZid)
var errZNF box.ErrZettelNotFound
if err != nil && !errors.Is(err, box.ErrNotFound) {
if err != nil && !errors.As(err, &errZNF) {
for j := 0; j < i; j++ {
mgr.boxes[j].RenameZettel(ctx, newZid, curZid)
}
return err
}
}
return nil
|
︙ | | |
276
277
278
279
280
281
282
283
284
285
286
287
288
|
278
279
280
281
282
283
284
285
286
287
288
289
290
291
|
+
-
+
-
+
|
mgr.mgrMx.RLock()
defer mgr.mgrMx.RUnlock()
for _, p := range mgr.boxes {
err := p.DeleteZettel(ctx, zid)
if err == nil {
return nil
}
var errZNF box.ErrZettelNotFound
if !errors.Is(err, box.ErrNotFound) && !errors.Is(err, box.ErrReadOnly) {
if !errors.As(err, &errZNF) && !errors.Is(err, box.ErrReadOnly) {
return err
}
}
return box.ErrNotFound
return box.ErrZettelNotFound{Zid: zid}
}
|
Changes to box/manager/collect.go.
︙ | | |
72
73
74
75
76
77
78
79
80
81
|
72
73
74
75
76
77
78
79
80
81
|
-
+
|
if ref.IsExternal() {
data.urls.Add(strings.ToLower(ref.Value))
}
if !ref.IsZettel() {
return
}
if zid, err := id.Parse(ref.URL.Path); err == nil {
data.refs.Zid(zid)
data.refs.Add(zid)
}
}
|
Changes to box/manager/indexer.go.
︙ | | |
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
-
-
+
+
|
}
// idxIndexer runs in the background and updates the index data structures.
// This is the main service of the idxIndexer.
func (mgr *Manager) idxIndexer() {
// Something may panic. Ensure a running indexer.
defer func() {
if r := recover(); r != nil {
kernel.Main.LogRecover("Indexer", r)
if ri := recover(); ri != nil {
kernel.Main.LogRecover("Indexer", ri)
go mgr.idxIndexer()
}
}()
timerDuration := 15 * time.Second
timer := time.NewTimer(timerDuration)
ctx := box.NoEnrichContext(context.Background())
|
︙ | | |
Changes to box/manager/manager.go.
︙ | | |
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
-
+
|
done chan struct{}
infos chan box.UpdateInfo
propertyKeys strfun.Set // Set of property key names
// Indexer data
idxLog *logger.Logger
idxStore store.Store
idxAr *anterooms
idxAr *anteroomQueue
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
|
︙ | | |
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
|
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
|
-
+
|
mgrLog: boxLog.Clone().Str("box", "manager").Child(),
rtConfig: rtConfig,
infos: make(chan box.UpdateInfo, len(boxURIs)*10),
propertyKeys: propertyKeys,
idxLog: boxLog.Clone().Str("box", "index").Child(),
idxStore: memstore.New(),
idxAr: newAnterooms(1000),
idxAr: newAnteroomQueue(1000),
idxReady: make(chan struct{}, 1),
}
cdata := ConnectData{Number: 1, Config: rtConfig, Enricher: mgr, Notify: mgr.infos}
boxes := make([]box.ManagedBox, 0, len(boxURIs)+2)
for _, uri := range boxURIs {
p, err := Connect(uri, authManager, &cdata)
if err != nil {
|
︙ | | |
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
|
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
|
-
-
+
+
|
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)
if ri := recover(); ri != nil {
kernel.Main.LogRecover("Notifier", ri)
go mgr.notifier()
}
}()
tsLastEvent := time.Now()
cache := destutterCache{}
for {
|
︙ | | |
Changes to box/manager/memstore/memstore.go.
︙ | | |
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
-
+
+
-
+
|
urls: make(stringRefs),
}
}
func (ms *memStore) GetMeta(_ context.Context, zid id.Zid) (*meta.Meta, error) {
ms.mx.RLock()
defer ms.mx.RUnlock()
if zi, found := ms.idx[zid]; found {
if zi, found := ms.idx[zid]; found && zi.meta != nil {
// zi.meta is nil, if zettel was referenced, but is not indexed yet.
return zi.meta.Clone(), nil
}
return nil, box.ErrNotFound
return nil, box.ErrZettelNotFound{Zid: zid}
}
func (ms *memStore) Enrich(_ context.Context, m *meta.Meta) {
if ms.doEnrich(m) {
ms.mxStats.Lock()
ms.updates++
ms.mxStats.Unlock()
|
︙ | | |
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
|
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
-
+
|
return false
}
var updated bool
if len(zi.dead) > 0 {
m.Set(api.KeyDead, zi.dead.String())
updated = true
}
back := removeOtherMetaRefs(m, zi.backward.Copy())
back := removeOtherMetaRefs(m, zi.backward.Clone())
if len(zi.backward) > 0 {
m.Set(api.KeyBackward, zi.backward.String())
updated = true
}
if len(zi.forward) > 0 {
m.Set(api.KeyForward, zi.forward.String())
back = remRefs(back, zi.forward)
|
︙ | | |
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
|
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
-
+
-
+
|
// SearchEqual returns all zettel that contains the given exact word.
// The word must be normalized through Unicode NKFD, trimmed and not empty.
func (ms *memStore) SearchEqual(word string) id.Set {
ms.mx.RLock()
defer ms.mx.RUnlock()
result := id.NewSet()
if refs, ok := ms.words[word]; ok {
result.AddSlice(refs)
result.CopySlice(refs)
}
if refs, ok := ms.urls[word]; ok {
result.AddSlice(refs)
result.CopySlice(refs)
}
zid, err := id.Parse(word)
if err != nil {
return result
}
zi, ok := ms.idx[zid]
if !ok {
|
︙ | | |
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
|
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
|
-
+
-
+
-
-
+
+
-
+
|
func (ms *memStore) selectWithPred(s string, pred func(string, string) bool) id.Set {
// Must only be called if ms.mx is read-locked!
result := id.NewSet()
for word, refs := range ms.words {
if !pred(word, s) {
continue
}
result.AddSlice(refs)
result.CopySlice(refs)
}
for u, refs := range ms.urls {
if !pred(u, s) {
continue
}
result.AddSlice(refs)
result.CopySlice(refs)
}
return result
}
func addBackwardZids(result id.Set, zid id.Zid, zi *zettelData) {
// Must only be called if ms.mx is read-locked!
result.Zid(zid)
result.AddSlice(zi.backward)
result.Add(zid)
result.CopySlice(zi.backward)
for _, mref := range zi.otherRefs {
result.AddSlice(mref.backward)
result.CopySlice(mref.backward)
}
}
func removeOtherMetaRefs(m *meta.Meta, back id.Slice) id.Slice {
for _, p := range m.PairsRest() {
switch meta.Type(p.Key) {
case meta.TypeID:
|
︙ | | |
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
|
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
|
-
-
+
+
+
+
|
// These must be checked later again
toCheck = id.NewSet(refs...)
delete(ms.dead, zidx.Zid)
}
zi.meta = m
ms.updateDeadReferences(zidx, zi)
ms.updateForwardBackwardReferences(zidx, zi)
ms.updateMetadataReferences(zidx, zi)
ids := ms.updateForwardBackwardReferences(zidx, zi)
toCheck = toCheck.Copy(ids)
ids = ms.updateMetadataReferences(zidx, zi)
toCheck = toCheck.Copy(ids)
zi.words = updateWordSet(zidx.Zid, ms.words, zi.words, zidx.GetWords())
zi.urls = updateWordSet(zidx.Zid, ms.urls, zi.urls, zidx.GetUrls())
// Check if zi must be inserted into ms.idx
if !ziExist {
ms.idx[zidx.Zid] = zi
}
|
︙ | | |
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
|
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
412
413
414
415
416
417
418
419
420
421
|
-
+
+
+
-
+
+
+
-
+
+
-
+
+
+
-
-
-
-
+
+
+
+
+
+
+
-
+
+
+
+
+
|
ms.dead[ref] = remRef(ms.dead[ref], zidx.Zid)
}
for _, ref := range newRefs {
ms.dead[ref] = addRef(ms.dead[ref], zidx.Zid)
}
}
func (ms *memStore) updateForwardBackwardReferences(zidx *store.ZettelIndex, zi *zettelData) {
func (ms *memStore) updateForwardBackwardReferences(zidx *store.ZettelIndex, zi *zettelData) id.Set {
// Must only be called if ms.mx is write-locked!
brefs := zidx.GetBackRefs()
newRefs, remRefs := refsDiff(brefs, zi.forward)
zi.forward = brefs
var toCheck id.Set
for _, ref := range remRefs {
bzi := ms.getEntry(ref)
bzi := ms.getOrCreateEntry(ref)
bzi.backward = remRef(bzi.backward, zidx.Zid)
if bzi.meta == nil {
toCheck = toCheck.Add(ref)
}
}
}
for _, ref := range newRefs {
bzi := ms.getEntry(ref)
bzi := ms.getOrCreateEntry(ref)
bzi.backward = addRef(bzi.backward, zidx.Zid)
if bzi.meta == nil {
toCheck = toCheck.Add(ref)
}
}
func (ms *memStore) updateMetadataReferences(zidx *store.ZettelIndex, zi *zettelData) {
}
}
return toCheck
}
func (ms *memStore) updateMetadataReferences(zidx *store.ZettelIndex, zi *zettelData) id.Set {
// Must only be called if ms.mx is write-locked!
inverseRefs := zidx.GetInverseRefs()
for key, mr := range zi.otherRefs {
if _, ok := inverseRefs[key]; ok {
continue
}
ms.removeInverseMeta(zidx.Zid, key, mr.forward)
}
if zi.otherRefs == nil {
zi.otherRefs = make(map[string]bidiRefs)
}
var toCheck id.Set
for key, mrefs := range inverseRefs {
mr := zi.otherRefs[key]
newRefs, remRefs := refsDiff(mrefs, mr.forward)
mr.forward = mrefs
zi.otherRefs[key] = mr
for _, ref := range newRefs {
bzi := ms.getEntry(ref)
bzi := ms.getOrCreateEntry(ref)
if bzi.otherRefs == nil {
bzi.otherRefs = make(map[string]bidiRefs)
}
bmr := bzi.otherRefs[key]
bmr.backward = addRef(bmr.backward, zidx.Zid)
bzi.otherRefs[key] = bmr
if bzi.meta == nil {
toCheck = toCheck.Add(ref)
}
}
ms.removeInverseMeta(zidx.Zid, key, remRefs)
}
return toCheck
}
func updateWordSet(zid id.Zid, srefs stringRefs, prev []string, next store.WordSet) []string {
newWords, removeWords := next.Diff(prev)
for _, word := range newWords {
if refs, ok := srefs[word]; ok {
srefs[word] = addRef(refs, zid)
|
︙ | | |
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
|
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
|
-
+
|
continue
}
srefs[word] = refs2
}
return next.Words()
}
func (ms *memStore) getEntry(zid id.Zid) *zettelData {
func (ms *memStore) getOrCreateEntry(zid id.Zid) *zettelData {
// Must only be called if ms.mx is write-locked!
if zi, ok := ms.idx[zid]; ok {
return zi
}
zi := &zettelData{}
ms.idx[zid] = zi
return zi
|
︙ | | |
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
|
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
|
-
+
|
}
for _, ref := range zi.backward {
if bzi, ok := ms.idx[ref]; ok {
bzi.forward = remRef(bzi.forward, zid)
if toCheck == nil {
toCheck = id.NewSet()
}
toCheck.Zid(ref)
toCheck.Add(ref)
}
}
return toCheck
}
func (ms *memStore) removeInverseMeta(zid id.Zid, key string, forward id.Slice) {
// Must only be called if ms.mx is write-locked!
|
︙ | | |
Changes to box/manager/memstore/refs.go.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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-present Detlef Stern
//
// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
//-----------------------------------------------------------------------------
package memstore
import (
"slices"
import "zettelstore.de/z/zettel/id"
"zettelstore.de/z/zettel/id"
)
func refsDiff(refsN, refsO id.Slice) (newRefs, remRefs id.Slice) {
npos, opos := 0, 0
for npos < len(refsN) && opos < len(refsO) {
rn, ro := refsN[npos], refsO[opos]
if rn == ro {
npos++
|
︙ | | |
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
-
+
-
-
|
return refs
} else if r < ref {
lo = m + 1
} else {
hi = m
}
}
refs = append(refs, id.Invalid)
refs = slices.Insert(refs, hi, ref)
copy(refs[hi+1:], refs[hi:])
refs[hi] = ref
return refs
}
func remRefs(refs, rem id.Slice) id.Slice {
if len(refs) == 0 || len(rem) == 0 {
return refs
}
|
︙ | | |
Changes to box/manager/store/zettel.go.
︙ | | |
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
|
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
|
-
+
-
+
-
+
|
deadrefs: id.NewSet(),
}
}
// AddBackRef adds a reference to a zettel where the current zettel links to
// without any more information.
func (zi *ZettelIndex) AddBackRef(zid id.Zid) {
zi.backrefs.Zid(zid)
zi.backrefs.Add(zid)
}
// AddInverseRef adds a named reference to a zettel. On that zettel, the given
// metadata key should point back to the current zettel.
func (zi *ZettelIndex) AddInverseRef(key string, zid id.Zid) {
if zids, ok := zi.inverseRefs[key]; ok {
zids.Zid(zid)
zids.Add(zid)
return
}
zi.inverseRefs[key] = id.NewSet(zid)
}
// AddDeadRef adds a dead reference to a zettel.
func (zi *ZettelIndex) AddDeadRef(zid id.Zid) {
zi.deadrefs.Zid(zid)
zi.deadrefs.Add(zid)
}
// SetWords sets the words to the given value.
func (zi *ZettelIndex) SetWords(words WordSet) { zi.words = words }
// SetUrls sets the words to the given value.
func (zi *ZettelIndex) SetUrls(urls WordSet) { zi.urls = urls }
|
︙ | | |
Changes to box/membox/membox.go.
︙ | | |
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
|
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
|
-
+
|
}
func (mb *memBox) GetZettel(_ context.Context, zid id.Zid) (zettel.Zettel, error) {
mb.mx.RLock()
z, ok := mb.zettel[zid]
mb.mx.RUnlock()
if !ok {
return zettel.Zettel{}, box.ErrNotFound
return zettel.Zettel{}, box.ErrZettelNotFound{Zid: zid}
}
z.Meta = z.Meta.Clone()
mb.log.Trace().Msg("GetZettel")
return z, nil
}
func (mb *memBox) HasZettel(_ context.Context, zid id.Zid) bool {
|
︙ | | |
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
|
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
|
-
+
|
}
return newBytes < mb.maxBytes
}
func (mb *memBox) UpdateZettel(_ context.Context, zettel zettel.Zettel) error {
m := zettel.Meta.Clone()
if !m.Zid.IsValid() {
return &box.ErrInvalidID{Zid: m.Zid}
return box.ErrInvalidZid{Zid: m.Zid.String()}
}
mb.mx.Lock()
newBytes := mb.curBytes + zettel.Length()
if prevZettel, found := mb.zettel[m.Zid]; found {
newBytes -= prevZettel.Length()
}
|
︙ | | |
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
|
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
|
-
+
-
+
|
func (*memBox) AllowRenameZettel(context.Context, id.Zid) bool { return true }
func (mb *memBox) RenameZettel(_ context.Context, curZid, newZid id.Zid) error {
mb.mx.Lock()
zettel, ok := mb.zettel[curZid]
if !ok {
mb.mx.Unlock()
return box.ErrNotFound
return box.ErrZettelNotFound{Zid: curZid}
}
// Check that there is no zettel with newZid
if _, ok = mb.zettel[newZid]; ok {
mb.mx.Unlock()
return &box.ErrInvalidID{Zid: newZid}
return box.ErrInvalidZid{Zid: newZid.String()}
}
meta := zettel.Meta.Clone()
meta.Zid = newZid
zettel.Meta = meta
mb.zettel[newZid] = zettel
delete(mb.zettel, curZid)
|
︙ | | |
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
|
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
|
-
+
|
}
func (mb *memBox) DeleteZettel(_ context.Context, zid id.Zid) error {
mb.mx.Lock()
oldZettel, found := mb.zettel[zid]
if !found {
mb.mx.Unlock()
return box.ErrNotFound
return box.ErrZettelNotFound{Zid: zid}
}
delete(mb.zettel, zid)
mb.curBytes -= oldZettel.Length()
mb.mx.Unlock()
mb.notifyChanged(zid)
mb.log.Trace().Msg("DeleteZettel")
return nil
|
︙ | | |
Changes to box/notify/directory.go.
︙ | | |
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
|
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
|
-
+
|
func (ds *DirService) RenameDirEntry(oldEntry *DirEntry, newZid id.Zid) (DirEntry, error) {
ds.mx.Lock()
defer ds.mx.Unlock()
if ds.entries == nil {
return DirEntry{}, ds.logMissingEntry("rename")
}
if _, found := ds.entries[newZid]; found {
return DirEntry{}, &box.ErrInvalidID{Zid: newZid}
return DirEntry{}, box.ErrInvalidZid{Zid: newZid.String()}
}
oldZid := oldEntry.Zid
newEntry := DirEntry{
Zid: newZid,
MetaName: renameFilename(oldEntry.MetaName, oldZid, newZid),
ContentName: renameFilename(oldEntry.ContentName, oldZid, newZid),
ContentExt: oldEntry.ContentExt,
|
︙ | | |
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
|
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
|
-
-
+
+
|
delete(ds.entries, zid)
return nil
}
func (ds *DirService) updateEvents(newEntries entrySet) {
// Something may panic. Ensure a running service.
defer func() {
if r := recover(); r != nil {
kernel.Main.LogRecover("DirectoryService", r)
if ri := recover(); ri != nil {
kernel.Main.LogRecover("DirectoryService", ri)
go ds.updateEvents(newEntries)
}
}()
for ev := range ds.notifier.Events() {
e, ok := ds.handleEvent(ev, newEntries)
if !ok {
|
︙ | | |
Changes to cmd/cmd_run.go.
︙ | | |
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
+
|
ucCreateZettel := usecase.NewCreateZettel(logUc, rtConfig, protectedBoxManager)
ucGetAllZettel := usecase.NewGetAllZettel(protectedBoxManager)
ucGetZettel := usecase.NewGetZettel(protectedBoxManager)
ucParseZettel := usecase.NewParseZettel(rtConfig, ucGetZettel)
ucQuery := usecase.NewQuery(protectedBoxManager)
ucEvaluate := usecase.NewEvaluate(rtConfig, &ucGetZettel, &ucQuery)
ucQuery.SetEvaluate(&ucEvaluate)
ucTagZettel := usecase.NewTagZettel(protectedBoxManager, &ucQuery)
ucListSyntax := usecase.NewListSyntax(protectedBoxManager)
ucListRoles := usecase.NewListRoles(protectedBoxManager)
ucDelete := usecase.NewDeleteZettel(logUc, protectedBoxManager)
ucUpdate := usecase.NewUpdateZettel(logUc, protectedBoxManager)
ucRename := usecase.NewRenameZettel(logUc, protectedBoxManager)
ucRefresh := usecase.NewRefresh(logUc, protectedBoxManager)
ucVersion := usecase.NewVersion(kernel.Main.GetConfig(kernel.CoreService, kernel.CoreVersion).(string))
|
︙ | | |
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
|
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
|
-
+
-
+
|
webSrv.AddZettelRoute('c', server.MethodPost, wui.MakePostCreateZettelHandler(&ucCreateZettel))
webSrv.AddZettelRoute('d', server.MethodGet, wui.MakeGetDeleteZettelHandler(ucGetZettel, ucGetAllZettel))
webSrv.AddZettelRoute('d', server.MethodPost, wui.MakePostDeleteZettelHandler(&ucDelete))
webSrv.AddZettelRoute('e', server.MethodGet, wui.MakeEditGetZettelHandler(ucGetZettel, ucListRoles, ucListSyntax))
webSrv.AddZettelRoute('e', server.MethodPost, wui.MakeEditSetZettelHandler(&ucUpdate))
}
webSrv.AddListRoute('g', server.MethodGet, wui.MakeGetGoActionHandler(&ucRefresh))
webSrv.AddListRoute('h', server.MethodGet, wui.MakeListHTMLMetaHandler(&ucQuery))
webSrv.AddListRoute('h', server.MethodGet, wui.MakeListHTMLMetaHandler(&ucQuery, &ucTagZettel))
webSrv.AddZettelRoute('h', server.MethodGet, wui.MakeGetHTMLZettelHandler(&ucEvaluate, ucGetZettel))
webSrv.AddListRoute('i', server.MethodGet, wui.MakeGetLoginOutHandler())
webSrv.AddListRoute('i', server.MethodPost, wui.MakePostLoginHandler(&ucAuthenticate))
webSrv.AddZettelRoute('i', server.MethodGet, wui.MakeGetInfoHandler(
ucParseZettel, &ucEvaluate, ucGetZettel, ucGetAllZettel, &ucQuery))
// API
webSrv.AddListRoute('a', server.MethodPost, a.MakePostLoginHandler(&ucAuthenticate))
webSrv.AddListRoute('a', server.MethodPut, a.MakeRenewAuthHandler())
webSrv.AddListRoute('x', server.MethodGet, a.MakeGetDataHandler(ucVersion))
webSrv.AddListRoute('x', server.MethodPost, a.MakePostCommandHandler(&ucIsAuth, &ucRefresh))
webSrv.AddListRoute('z', server.MethodGet, a.MakeQueryHandler(&ucQuery))
webSrv.AddListRoute('z', server.MethodGet, a.MakeQueryHandler(&ucQuery, &ucTagZettel))
webSrv.AddZettelRoute('z', server.MethodGet, a.MakeGetZettelHandler(ucGetZettel, ucParseZettel, ucEvaluate))
if !authManager.IsReadonly() {
webSrv.AddListRoute('z', server.MethodPost, a.MakePostCreateZettelHandler(&ucCreateZettel))
webSrv.AddZettelRoute('z', server.MethodPut, a.MakeUpdateZettelHandler(&ucUpdate))
webSrv.AddZettelRoute('z', server.MethodDelete, a.MakeDeleteZettelHandler(&ucDelete))
webSrv.AddZettelRoute('z', server.MethodMove, a.MakeRenameZettelHandler(&ucRename))
}
|
︙ | | |
Changes to docs/manual/00001004020000.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
|
id: 00001004020000
title: Configure the running Zettelstore
role: manual
tags: #configuration #manual #zettelstore
syntax: zmk
created: 20210126175322
modified: 20230317183435
modified: 20230807171016
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.
Some of them can be overwritten in an [[user zettel|00001010040200]], a subset of those may be overwritten in zettel that is currently used.
See the full list of [[metadata that may be overwritten|00001004020200]].
|
︙ | | |
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
-
+
|
Default: ""login"".
; [!expert-mode|''expert-mode'']
: If set to a [[boolean true value|00001006030500]], all zettel with [[visibility ""expert""|00001010070200]] will be shown (to the owner, if [[authentication is enabled|00001010040100]]; to all, otherwise).
This affects most computed zettel.
Default: ""False"".
; [!footer-zettel|''footer-zettel'']
: Identifier of a zettel that is rendered as HTML and will be placed as the footer of every zettel in the [[web user interface|00001014000000]].
Zettel content, delivered via the [[API|00001012000000]] as JSON, etc. is not affected.
Zettel content, delivered via the [[API|00001012000000]] as symbolic expressions, etc. is not affected.
If the zettel identifier is invalid or references a zettel that could not be read (possibly because of a limited [[visibility setting|00001010070200]]), nothing is written as the footer.
May be [[overwritten|00001004020200]] in a user zettel.
Default: (an invalid zettel identifier)
; [!home-zettel|''home-zettel'']
: Specifies the identifier of the zettel, that should be presented for the default view / home view.
|
︙ | | |
Changes to docs/manual/00001005090000.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
|
id: 00001005090000
title: List of predefined zettel
role: manual
tags: #manual #reference #zettelstore
syntax: zmk
created: 20210126175322
modified: 20230619133707
modified: 20230827212840
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
|
︙ | | |
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
+
-
+
-
|
| [[00000000010300]] | Zettelstore List Zettel 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 Template | 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
| [[00000000010700]] | Zettelstore Error HTML Template | View to show an error message
| [[00000000019000]] | Zettelstore Sxn Start Code | Starting point of sxn functions to build the templates
| [[00000000019100]] | Zettelstore Sxn Code for Templates | Some helper functions to build the templates
| [[00000000019990]] | Zettelstore Sxn Base Code | Base sxn functions to build the templates
| [[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]]
| [[00000000029000]] | Zettelstore Role to CSS Map | [[Maps|00001017000000#role-css]] [[role|00001006020000#role]] to a zettel identifier that is included by the [[Base HTML Template|00000000010100]] as an CSS file
| [[00000000040001]] | Generic Emoji | Image that is shown if [[original image reference|00001007040322]] 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 [[user zettel|00001010040200]]
| [[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/00001006020100.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
|
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: 00001006020100
title: Supported Zettel Roles
role: manual
tags: #manual #meta #reference #zettel #zettelstore
syntax: zmk
created: 00010101000000
modified: 20220623183234
modified: 20230829233016
The [[''role'' key|00001006020000#role]] defines what kind of zettel you are writing.
You are free to define your own roles.
It is allowed to set an empty value or to omit the 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 only used in this specific Zettelstore.
; [!tag|''tag'']
: A zettel with the role ""tag"" and a title, which names a [[tag|00001006020000#tags]], is treated as a __tag zettel__.
Basically, tag zettel describe the tag, and form a hierarchiy of meta-tags.
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/00001007030900.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
+
-
+
-
+
|
id: 00001007030900
title: Zettelmarkup: Comment Blocks
role: manual
tags: #manual #zettelmarkup #zettelstore
syntax: zmk
created: 20210126175322
modified: 20220218130330
modified: 20230807170858
Comment blocks are quite similar to [[verbatim blocks|00001007030500]]: both are used to enter text that should not be interpreted.
While the text entered inside a verbatim block will be processed somehow, text inside a comment block will be ignored[^Well, not completely ignored: text is read, but it will typically not rendered visible.].
Comment blocks are typically used to give some internal comments, e.g. the license of a text or some internal remarks.
Comment blocks begin with at least three percent sign characters (""''%''"", U+0025) at the first position of a line.
You can add some [[attributes|00001007050000]] on the beginning line of a comment block, following the initiating characters.
The comment block supports the default attribute: when given, the text will be rendered, e.g. as an HTML comment.
When rendered to JSON, the comment block will not be ignored but it will output some JSON text.
When rendered to a symbolic expression, the comment block will not be ignored but it will output some text.
Same for other renderer.
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 percent sign characters in the text that should not be interpreted.
|
︙ | | |
Changes to docs/manual/00001007702000.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
|
id: 00001007702000
title: Search term
role: manual
tags: #manual #search #zettelstore
syntax: zmk
created: 20220805150154
modified: 20230612180954
modified: 20230925173539
A search term allows you to specify one search restriction.
The result [[search expression|00001007700000]], which contains more than one search term, will be the applications of all restrictions.
A search term can be one of the following (the first three term are collectively called __search literals__):
* A metadata-based search, by specifying the name of a [[metadata key|00001006010000]], followed by a [[search operator|00001007705000]], followed by an optional [[search value|00001007706000]].
|
︙ | | |
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
-
+
|
A zero value of N will produce the same result as if nothing was specified.
If specified multiple times, the lower value takes precedence.
Example: ''PICK 5 PICK 3'' will be interpreted as ''PICK 3''.
* The string ''ORDER'', followed by a non-empty sequence of spaces and the name of a metadata key, will specify an ordering of the result list.
If you include the string ''REVERSE'' after ''ORDER'' but before the metadata key, the ordering will be reversed.
Example: ''ORDER published'' will order the resulting list based on the publishing data, while ''ORDER REVERSED published'' will return a reversed result order.
Example: ''ORDER published'' will order the resulting list based on the publishing data, while ''ORDER REVERSE published'' will return a reversed result order.
An explicit order field will take precedence over the random order described below.
If no random order is effective, a ``ORDER REVERSE id`` will be added.
This makes the sort stable.
Example: ``ORDER created`` will be interpreted as ``ORDER created ORDER REVERSE id``.
|
︙ | | |
Changes to docs/manual/00001012000000.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
-
+
-
+
|
id: 00001012000000
title: API
role: manual
tags: #api #manual #zettelstore
syntax: zmk
created: 20210126175322
modified: 20230731162018
modified: 20230807171136
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.
The API is HTTP-based and uses plain text and [[symbolic expressions|00001012930000]] as its main encoding formats for exchanging messages between a Zettelstore and its client software.
There is an [[overview zettel|00001012920000]] that shows the structure of the endpoints used by the API and gives an indication about its use.
=== Authentication
If [[authentication is enabled|00001010040100]], most API calls must include an [[access token|00001010040700]] that proves the identity of the caller.
* [[Authenticate an user|00001012050200]] to obtain an access token
* [[Renew an access token|00001012050400]] without costly re-authentication
|
︙ | | |
Changes to docs/manual/00001012051200.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
|
id: 00001012051200
title: API: List all zettel
role: manual
tags: #api #manual #zettelstore
syntax: zmk
created: 20210126175322
modified: 20230703180113
modified: 20230807170810
To list all zettel just send a HTTP GET request to the [[endpoint|00001012920000]] ''/z''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header].
Always use the endpoint ''/z'' to work with a list of zettel.
Without further specifications, a plain text document is returned, with one line per zettel.
Each line contains in the first 14 characters the [[zettel identifier|00001006050000]].
Separated by a space character, the title of the zettel follows:
|
︙ | | |
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
|
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
|
* Keys ''query'' and ''human'' will be explained [[later in this manual|00001012051400]].
* ''list'' starts a list of zettel.
* ''zettel'' itself start, well, a zettel.
* ''id'' denotes the zettel identifier, encoded as a string.
* Nested in ''meta'' are the metadata, each as a key/value pair.
* ''rights'' specifies the [[access rights|00001012921200]] the user has for this zettel.
=== JSON output (deprecated)
Alternatively, you may retrieve the list of all zettel as a JSON object by specifying the encoding with the query parameter ''enc=json'':
```sh
# curl 'http://127.0.0.1:23123/z?enc=json'
{"query":"","human":"","list":[{"id":"00001012051200","meta":{"back":"00001012000000","backward":"00001012000000 00001012920000","box-number":"1","created":"20210126175322","forward":"00001006020000 00001006050000 00001007700000 00001010040100 00001012050200 00001012051400 00001012920000 00001012921000 00001014000000","modified":"20221219150626","published":"20221219150626","role":"manual","syntax":"zmk","tags":"#api #manual #zettelstore","title":"API: List all zettel"},"rights":62},{"id":"00001012050600","meta":{"back":"00001012000000 00001012080500","backward":"00001012000000 00001012080500","box-number":"1","created":"00010101000000","forward":"00001012050200 00001012921000","modified":"20220218130020","published":"20220218130020","role":"manual","syntax":"zmk","tags":"#api #manual #zettelstore","title":"API: Provide an access token"},"rights":62},{"id":"00001012050400","meta":{"back":"00001010040700 00001012000000","backward":"00001010040700 00001012000000 00001012920000 00001012921000","box-number":"1","created":"00010101000000","forward":"00001010040100 00001012050200 00001012920000 00001012921000","modified":"20220107215751","published":"20220107215751","role":"manual","syntax":"zmk","tags":"#api #manual #zettelstore","title":"API: Renew an access token"},"rights":62},{"id":"00001012050200","meta":{"back":"00001012000000 00001012050400 00001012050600 00001012051200 00001012051400 00001012053300 00001012053400 00001012053500 00001012053600 00001012080200","backward":"00001010040700 00001012000000 00001012050400 00001012050600 00001012051200 00001012051400 00001012053300 00001012053400 00001012053500 00001012053600 00001012080200 00001012920000 00001012921000","box-number":"1","created":"00010101000000","forward":"00001004010000 00001010040100 00001010040200 00001010040700 00001012920000 00001012921000","modified":"20220107215844","published":"20220107215844","role":"manual","syntax":"zmk","tags":"#api #manual #zettelstore","title":"API: Authenticate a client"},"rights":62}, ...]}
```
If you reformat the JSON output, you will see its structure better:
```
{
"query": "",
"human": "",
"list": [
{
"id": "00001012051200",
"meta": {
"back": "00001012000000",
"backward": "00001012000000 00001012920000",
"box-number": "1",
"created": "20210126175322",
"forward": "00001006020000 00001006050000 00001007700000 00001010040100 00001012050200 00001012051400 00001012920000 00001012921000 00001014000000",
"modified": "20221219151200",
"published": "20221219151200",
"role": "manual",
"syntax": "zmk",
"tags": "#api #manual #zettelstore",
"title": "API: List all zettel"
},
"rights": 62
},
{
"id": "00001012050600",
"meta": {
"back": "00001012000000 00001012080500",
"backward": "00001012000000 00001012080500",
"box-number": "1",
"created": "00010101000000",
"forward": "00001012050200 00001012921000",
"modified": "20220218130020",
"published": "20220218130020",
"role": "manual",
"syntax": "zmk",
"tags": "#api #manual #zettelstore",
"title": "API: Provide an access token"
},
"rights": 62
},
{
"id": "00001012050400",
"meta": {
"back": "00001010040700 00001012000000",
"backward": "00001010040700 00001012000000 00001012920000 00001012921000",
"box-number": "1",
"created": "00010101000000",
"forward": "00001010040100 00001012050200 00001012920000 00001012921000",
"modified": "20220107215751",
"published": "20220107215751",
"role": "manual",
"syntax": "zmk",
"tags": "#api #manual #zettelstore",
"title": "API: Renew an access token"
},
"rights": 62
},
{
"id": "00001012050200",
"meta": {
"back": "00001012000000 00001012050400 00001012050600 00001012051200 00001012051400 00001012053300 00001012053400 00001012053500 00001012053600 00001012
080200",
"backward": "00001010040700 00001012000000 00001012050400 00001012050600 00001012051200 00001012051400 00001012053300 00001012053400 00001012053500 0000
1012053600 00001012080200 00001012920000 00001012921000",
"box-number": "1",
"created": "00010101000000",
"forward": "00001004010000 00001010040100 00001010040200 00001010040700 00001012920000 00001012921000",
"modified": "20220107215844",
"published": "20220107215844",
"role": "manual",
"syntax": "zmk",
"tags": "#api #manual #zettelstore",
"title": "API: Authenticate a client"
},
"rights": 62
}
]
}
```
Again, the list is typically **not** sorted, for example by the zettel identifier.
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|00001006050000]]), ''"meta"'' (value as a JSON object), and ''"rights"'' (encodes the [[access rights|00001012921200]] for the given zettel).
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.
The JSON objects keys ''"query"'' and ''"human"'' will be explained later in this manual.
=== Note
This request (and similar others) will always return a list of metadata, provided the request was syntactically correct.
There will never be a HTTP status code 403 (Forbidden), even if [[authentication was enabled|00001010040100]] and you did not provide a valid access token.
In this case, the resulting list might be quite short (some zettel will have [[public visibility|00001010070200]]) or the list might be empty.
With this call, you cannot differentiate between an empty result list (e.g because your search did not found a zettel with the specified term) and an empty list because of missing authorization (e.g. an invalid access token).
=== HTTP Status codes
; ''200''
: Retrieval was successful, the body contains an [[appropriate JSON object|00001012921000]].
: Retrieval was successful, the body contains an appropriate data value.
; ''400''
: Request was not valid.
There are several reasons for this.
Maybe the access bearer token was not valid.
|
Changes to docs/manual/00001012051400.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
63
64
65
66
67
68
69
70
71
72
73
|
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: 00001012051400
title: API: Query the list of all zettel
role: manual
tags: #api #manual #zettelstore
syntax: zmk
created: 20220912111111
modified: 20230731162234
modified: 20230807170638
precursor: 00001012051200
The [[endpoint|00001012920000]] ''/z'' also allows you to filter the list of all zettel[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header] and optionally to provide some actions.
A [[query|00001007700000]] is an optional [[search expression|00001007700000#search-expression]], together with an optional [[list of actions|00001007700000#action-list]] (described below).
An empty search expression will select all zettel.
An empty list of action, or no valid action, returns the list of all selected zettel metadata.
Search expression and action list are separated by a vertical bar character (""''|''"", U+007C), and must be given with the query parameter ''q''.
The query parameter ""''q''"" allows you to specify [[query expressions|00001007700000]] for a full-text search of all zettel content and/or restricting the search according to specific metadata.
It is allowed to specify this query parameter more than once.
This parameter loosely resembles the search form of the [[web user interface|00001014000000]] or those of [[Zettelmarkup's Query Transclusion|00001007031140]].
For example, if you want to retrieve all zettel that contain the string ""API"" in its title, your request will be:
```sh
# curl 'http://127.0.0.1:23123/z?q=title%3AAPI+ORDER+REVERSE+id+OFFSET+1'
00001012921000 API: JSON structure of an access token
00001012921000 API: Structure of an access token
00001012920500 Formats available by the API
00001012920000 Endpoints used by the API
...
```
If you want to retrieve a data document, as a [[symbolic expression|00001012930500]]:
```sh
# curl 'http://127.0.0.1:23123/z?q=title%3AAPI+ORDER+REVERSE+id+OFFSET+1&enc=data'
(meta-list (query "title:API ORDER REVERSE id OFFSET 1") (human "title HAS API ORDER REVERSE id OFFSET 1") (list (zettel (id 1012921000) (meta (title "API: Structure of an access token") (role "manual") (tags "#api #manual #reference #zettelstore") (syntax "zmk") (back "00001012050600 00001012051200") (backward "00001012050200 00001012050400 00001012050600 00001012051200") (box-number "1") (created "20210126175322") (forward "00001012050200 00001012050400 00001012930000") (modified "20230412155303") (published "20230412155303")) (rights 62)) (zettel (id 1012920500) (meta (title "Encodings available via the API") (role "manual") (tags "#api #manual #reference #zettelstore") (syntax "zmk") (back "00001006000000 00001008010000 00001008010500 00001012053500 00001012053600") (backward "00001006000000 00001008010000 00001008010500 00001012053500 00001012053600") (box-number "1") (created "20210126175322") (forward "00001012000000 00001012920510 00001012920513 00001012920516 00001012920519 00001012920522 00001012920525") (modified "20230403123653") (published "20230403123653")) (rights 62)) (zettel (id 1012920000) (meta (title "Endpoints used by the API") ...
```
The data object contains a key ''"meta-list"'' to signal that it contains a list of metadata values (and some more).
It contains the keys ''"query"'' and ''"human"'' with a string value.
Both will contain a textual description of the underlying query if you select only some zettel with a [[query expression|00001007700000]].
Without a selection, the values are the empty string.
''"query"'' returns the normalized query expression itself, while ''"human"'' is the normalized query expression to be read by humans.
where its value is a list of zettel JSON objects.
The symbol ''list'' starts the list of zettel data.
Data of a zettel is indicated by the symbol ''zettel'', followed by ''(id ID)'' that describes the zettel identifier as a numeric value.
Leading zeroes are removed.
Metadata starts with the symbol ''meta'', and each metadatum itself is a list of metadata key / metadata value.
Metadata keys are encoded as a symbol, metadata values as a string.
''"rights"'' encodes the [[access rights|00001012921200]] for the given zettel.
If you want to retrieve a JSON document:
```sh
# curl 'http://127.0.0.1:23123/z?q=title%3AAPI+ORDER+REVERSE+id+OFFSET+1&enc=json'
{"query":"title:API ORDER REVERSE id OFFSET 1","human":"title HAS API ORDER REVERSE id OFFSET 1","list":[{"id":"00001012921200","meta":{"back":"00001012051200 00001012051400 00001012053300 00001012053400 00001012053800 00001012053900 00001012054000","backward":"00001012051200 00001012051400 00001012053300 00001012053400 00001012053800 00001012053900 00001012054000","box-number":"1","created":"00010101000000","forward":"00001003000000 00001006020400 00001010000000 00001010040100 00001010040200 00001010070200 00001010070300","modified":"20220201171959","published":"20220201171959","role":"manual","syntax":"zmk","tags":"#api #manual #reference #zettelstore","title":"API: Encoding of Zettel Access Rights"},"rights":62},{"id":"00001012921000","meta":{"back":"00001012050600 00001012051200","backward":"00001012050200 00001012050400 00001012050600 00001012051200","box-number":"1","created":"00010101000000","forward":"00001012050200 00001012050400","published":"00010101000000","role":"manual","syntax":"zmk","tags":"#api #manual #reference #zettelstore","title":"API: JSON structure of an access token"},"rights":62}, ...]
```
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|00001006050000]]), ''"meta"'' (value as a JSON object), and ''"rights"'' (encodes the [[access rights|00001012921200]] for the given zettel).
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 the keys ''"query"'' and ''"human"'' with a string value.
=== Aggregates
An implicit precondition is that the zettel must contain the given metadata key.
For a metadata key like [[''title''|00001006020000#title]], which have a default value, this precondition should always be true.
But the situation is different for a key like [[''url''|00001006020000#url]].
Both ``curl 'http://localhost:23123/z?q=url%3A'`` and ``curl 'http://localhost:23123/z?q=url%3A!'`` may result in an empty list.
|
︙ | | |
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
|
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
|
# curl 'http://127.0.0.1:23123/z?q=|tags&enc=data'
(aggregate "tags" (query "| tags") (human "| tags") (list ("#zettel" 1006034500 1006034000 1006031000 1006020400 1006033500 1006036500 1006032500 1006020100 1006031500 1006030500 1006035500 1006033000 1006020000 1006036000 1006030000 1006032000 1006035000) ("#reference" 1006034500 1006034000 1007800000 1012920500 1006031000 1012931000 1006020400 1012930000 1006033500 1012920513 1007050100 1012920800 1007780000 1012921000 1012920510 1007990000 1006036500 1006032500 1006020100 1012931400 1012931800 1012920516 1012931600 1012920525 1012931200 1006031500 1012931900 1012920000 1005090000 1012920522 1006030500 1007050200 1012921200 1006035500 1012920519 1006033000 1006020000 1006036000 1006030000 1006032000 1012930500 1006035000) ("#graphic" 1008050000) ("#search" 1007700000 1007705000 1007790000 1007780000 1007702000 1007706000 1007031140) ("#installation" 1003315000 1003310000 1003000000 1003305000 1003300000 1003600000) ("#zettelmarkup" 1007900000 1007030700 1007031300 1007030600 1007800000 1007000000 1007031400 1007040100 1007030300 1007031200 1007040350 1007030400 1007030900 1007050100 1007040000 1007030500 1007903000 1007040200 1007040330 1007990000 1007040320 1007050000 1007040310 1007031100 1007040340 1007020000 1007031110 1007031140 1007040324 1007030800 1007031000 1007030000 1007010000 1007906000 1007050200 1007030100 1007030200 1007040300 1007040322) ("#design" 1005000000 1006000000 1002000000 1006050000 1006055000) ("#markdown" 1008010000 1008010500) ("#goal" 1002000000) ("#syntax" 1006010000) ...
```
If you want only those tags that occur at least 100 times, use the endpoint ''/z?q=|MIN100+tags''.
You see from this that actions are separated by space characters.
Of course, this list can also be returned as a JSON object:
```sh
# curl 'http://127.0.0.1:23123/z?q=|role&enc=json'
{"map":{"configuration":["00000000090002","00000000090000", ... ,"00000000000001"],"manual":["00001014000000", ... ,"00001000000000"],"zettel":["00010000000000", ... ,"00001012070500","00000000090001"]}}
```
The JSON object only contains the key ''"map"'' with the value of another object.
This second object contains all role names as keys and the list of identifier of those zettel with this specific role as a value.
Similar, to list all tags used in the Zettelstore, send a HTTP GET request to the endpoint ''/z?q=|tags''.
If successful, the output is a JSON object:
```sh
# curl 'http://127.0.0.1:23123/z?q=|tags&enc=json'
{"map":{"#api":[:["00001012921000","00001012920800","00001012920522",...],"#authorization":["00001010040700","00001010040400",...],...,"#zettelstore":["00010000000000","00001014000000",...,"00001001000000"]}}
```
The JSON object only contains the key ''"map"'' with the value of another object.
This second object contains all tags as keys and the list of identifier of those zettel with this tag as a value.
=== Actions
There are two types of actions: parameters and aggregates.
The following actions are supported:
; ''MINn'' (parameter)
: Emit only those values with at least __n__ aggregated values.
__n__ must be a positive integer, ''MIN'' must be given in upper-case letters.
|
︙ | | |
Changes to docs/manual/00001012053200.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
|
id: 00001012053200
title: API: Create a new zettel
role: manual
tags: #api #manual #zettelstore
syntax: zmk
created: 20210713150005
modified: 20230807124310
modified: 20230807170416
A zettel is created by adding it to the [[list of zettel|00001012000000]].
Therefore, the [[endpoint|00001012920000]] to create a new zettel is also ''/z'', but you must send the data of the new zettel via a HTTP POST request.
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]].
|
︙ | | |
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
|
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
|
=== Data input
Alternatively, you may encode the zettel as a parseable object / a [[symbolic expression|00001012930500]] by providing the query parameter ''enc=data''.
The encoding is the same as the data output encoding when you [[retrieve a zettel|00001012053300#data-output]].
The encoding for [[access rights|00001012921200]] must be given, but is ignored.
You may encode computed or property [[metadata keys|00001006020000]], but these are also ignored.
=== JSON input (deprecated)
Alternatively, the body of the POST request may contain a JSON object that specifies metadata and content of the zettel to be created.
To do this, you must add the query parameter ''enc=json''.
The following keys of the JSON object are used:
; ''"meta"''
: References an embedded JSON object with only string values.
The name/value pairs of this objects are interpreted as the metadata of the new zettel.
Please consider the [[list of supported metadata keys|00001006020000]] (and their value types).
; ''"encoding"''
: States how the content is encoded.
Currently, only two values are allowed: the empty string (''""'') that specifies an empty encoding, and the string ''"base64"'' that specifies the [[standard Base64 encoding|https://www.rfc-editor.org/rfc/rfc4648.txt]].
Other values will result in a HTTP response status code ''400''.
; ''"content"''
: Is a string value that contains the content of the zettel to be created.
Typically, text content is not encoded, and binary content is encoded via Base64.
Other keys will be ignored.
Even these three keys are just optional.
The body of the HTTP POST request must not be empty and it must contain a JSON object.
Therefore, a body containing just ''{}'' is perfectly valid.
The new zettel will have no content, and only an identifier as [[metadata|00001006020000]]:
```
# curl -X POST --data '{}' 'http://127.0.0.1:23123/z?enc=json'
{"id":"20210713161000"}
```
If creating the zettel was successful, the HTTP response will contain a JSON object with one key:
; ''"id"''
: Contains the [[zettel identifier|00001006050000]] of the created zettel for further usage.
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/z?enc=json'
{"id":"20210713163100"}
```
=== HTTP Status codes
; ''201''
: Zettel creation was successful, the body contains its [[zettel identifier|00001006050000]] (JSON object or plain text).
: Zettel creation was successful, the body contains its [[zettel identifier|00001006050000]] (data value or plain text).
; ''400''
: Request was not valid.
There are several reasons for this.
Most likely, the JSON was not formed according to above rules.
Most likely, the symbolic expression was not formed according to above rules.
; ''403''
: You are not allowed to create a new zettel.
|
Changes to docs/manual/00001012053300.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
|
id: 00001012053300
title: API: Retrieve metadata and content of an existing zettel
role: manual
tags: #api #manual #zettelstore
syntax: zmk
created: 20211004093206
modified: 20230807123533
modified: 20230807170259
The [[endpoint|00001012920000]] to work with metadata and content of a specific zettel is ''/z/{ID}'', where ''{ID}'' is a placeholder for the [[zettel identifier|00001006050000]].
For example, to retrieve some data about this zettel you are currently viewing, just send a HTTP GET request to the endpoint ''/z/00001012053300''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header].
````sh
# curl 'http://127.0.0.1:23123/z/00001012053300'
|
︙ | | |
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
|
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
|
* Nested in ''meta'' are the metadata, each as a key/value pair.
* ''rights'' specifies the [[access rights|00001012921200]] the user has for this zettel.
* ''"encoding"'' states how the content is encoded.
Currently, only two values are allowed: the empty string (''""'') that specifies an empty encoding, and the string ''"base64"'' that specifies the [[standard Base64 encoding|https://www.rfc-editor.org/rfc/rfc4648.txt]].
* The zettel contents is stored as a value of the key ''content''.
Typically, text content is not encoded, and binary content is encoded via Base64.
=== JSON output (deprecated)
You may also retrieve the zettel as a JSON object by providing the query parameter ''enc=json'':
```sh
# curl 'http://127.0.0.1:23123/z/00001012053300?enc=json&part=zettel'
{"id":"00001012053300","meta":{"back":"00001012000000 00001012054400","backward":"00001012000000 00001012054400 00001012920000","box-number":"1","created":"20211004093206","forward":"00001006020000 00001006050000 00001010040100 00001012050200 00001012053400 00001012920000 00001012920800 00001012921200","modified":"20221219160211","published":"20221219160211","role":"manual","syntax":"zmk","tags":"#api #manual #zettelstore","title":"API: Retrieve metadata and content of an existing zettel"},"encoding":"","content":"The [[endpoint|00001012920000]] to work with metadata and content of a specific zettel is ''/z/{ID}'', where ''{ID}'' is a placeholder for the [[zettel identifier|00001006050000]].\n\nFor example, ...
```
Pretty-printed, this results in:
```
{
"id": "00001012053300",
"meta": {
"back": "00001012000000 00001012054400",
"backward": "00001012000000 00001012054400 00001012920000",
"box-number": "1",
"created": "20211004093206",
"forward": "00001006020000 00001006050000 00001010040100 00001012050200 00001012053400 00001012920000 00001012920800 00001012921200",
"modified": "20221219160211",
"published": "20221219160211",
"role": "manual",
"syntax": "zmk",
"tags": "#api #manual #zettelstore",
"title": "API: Retrieve metadata and content of an existing zettel"
},
"encoding": "",
"content": "The [[endpoint|00001012920000]] to work with metadata and content of a specific zettel is ''/z/{ID}'', where ''{ID}'' (...)
"rights": 62
}
```
The following keys of the JSON object are used:
; ''"id"''
: The zettel identifier of the zettel you requested.
; ''"meta"''
: References an embedded JSON object with only string values.
The name/value pairs of this objects are interpreted as the metadata of the new zettel.
Please consider the [[list of supported metadata keys|00001006020000]] (and their value types).
; ''"encoding"''
: States how the content is encoded.
Currently, only two values are allowed: the empty string (''""'') that specifies an empty encoding, and the string ''"base64"'' that specifies the [[standard Base64 encoding|https://www.rfc-editor.org/rfc/rfc4648.txt]].
; ''"content"''
: Is a string value that contains the content of the zettel to be created.
Typically, text content is not encoded, and binary content is encoded via Base64.
; ''"rights"''
: An integer number that describes the [[access rights|00001012921200]] for the zettel.
=== HTTP Status codes
; ''200''
: Retrieval was successful, the body contains an appropriate JSON object / plain zettel data.
: Retrieval was successful, the body contains an appropriate data value.
; ''204''
: Request was valid, but there is no data to be returned.
Most likely, you specified the query parameter ''part=content'', but the zettel does not contain any content.
; ''400''
: Request was not valid.
There are several reasons for this.
Maybe the [[zettel identifier|00001006050000]] did not consists 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
6
7
8
9
10
11
12
13
14
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
|
id: 00001012053400
title: API: Retrieve metadata of an existing zettel
role: manual
tags: #api #manual #zettelstore
syntax: zmk
created: 20210726174524
modified: 20230703175153
modified: 20230807170155
The [[endpoint|00001012920000]] to work with metadata of a specific zettel is ''/z/{ID}'', where ''{ID}'' is a placeholder for the [[zettel identifier|00001006050000]][^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header].
To retrieve the plain metadata of a zettel, use the query parameter ''part=meta''
````sh
# curl 'http://127.0.0.1:23123/z/00001012053400?part=meta'
|
︙ | | |
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
|
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
|
(rights 62))
```
* The result is a list, starting with the symbol ''list''.
* Then, some key/value pairs are following, also nested.
* Nested in ''meta'' are the metadata, each as a key/value pair.
* ''rights'' specifies the [[access rights|00001012921200]] the user has for this zettel.
=== JSON output (deprecated)
To return a JSON object, use also the query parameter ''enc=json''.
```sh
# curl 'http://127.0.0.1:23123/z/00001012053400?part=meta&enc=json'
{"meta":{"back":"00001012000000 00001012053300","backward":"00001012000000 00001012053300","box-number":"1","created":"20210726174524","forward":"00001006020000 00001006050000 00001010040100 00001012050200 00001012920000 00001012921200","modified":"20230703174515","published":"20230703174515","role":"manual","syntax":"zmk","tags":"#api #manual #zettelstore","title":"API: Retrieve metadata of an existing zettel"},"rights":62}
```
Pretty-printed, this results in:
```
{
"meta": {
"back": "00001012000000 00001012053300",
"backward": "00001012000000 00001012053300 00001012920000",
"box-number": "1",
"created": "20210726174524",
"forward": "00001006020000 00001006050000 00001010040100 00001012050200 00001012920000 00001012921200",
"modified": "20220917175233",
"published": "20220917175233",
"role": "manual",
"syntax": "zmk",
"tags": "#api #manual #zettelstore",
"title": "API: Retrieve metadata of an existing zettel"
},
"rights": 62
}
```
The following keys of the JSON object are used:
; ''"meta"''
: References an embedded JSON object with only string values.
The name/value pairs of this objects are interpreted as the metadata of the new zettel.
Please consider the [[list of supported metadata keys|00001006020000]] (and their value types).
; ''"rights"''
: An integer number that describes the [[access rights|00001012921200]] for the zettel.
=== HTTP Status codes
; ''200''
: Retrieval was successful, the body contains an appropriate JSON object.
: Retrieval was successful, the body contains an appropriate data value.
; ''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/00001012053500.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
-
+
-
+
|
id: 00001012053500
title: API: Retrieve evaluated metadata and content of an existing zettel in various encodings
role: manual
tags: #api #manual #zettelstore
syntax: zmk
created: 20210726174524
modified: 20230109105303
modified: 20230807170112
The [[endpoint|00001012920000]] to work with evaluated metadata and content of a specific zettel is ''/z/{ID}'', where ''{ID}'' is a placeholder for the [[zettel identifier|00001006050000]].
For example, to retrieve some evaluated data about this zettel you are currently viewing in [[Sz encoding|00001012920516]], just send a HTTP GET request to the endpoint ''/z/00001012053500''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header] with the query parameter ''enc=sz''.
If successful, the output is a JSON object:
If successful, the output is a symbolic expression value:
```sh
# curl 'http://127.0.0.1:23123/z/00001012053500?enc=sz'
((PARA (TEXT "The") (SPACE) (LINK-ZETTEL () "00001012920000" (TEXT "endpoint")) (SPACE) (TEXT "to") (SPACE) (TEXT "work") (SPACE) (TEXT "with") (SPACE) (TEXT "evaluated") (SPACE) (TEXT "metadata") (SPACE) (TEXT "and") (SPACE) (TEXT "content") (SPACE) (TEXT "of") (SPACE) (TEXT "a") (SPACE) (TEXT "specific") (SPACE) (TEXT "zettel") (SPACE) (TEXT "is") (SPACE) (LITERAL-INPUT () "/z/{ID}") (TEXT ",") (SPACE) (TEXT "where") (SPACE) (LITERAL-INPUT () "{ID}") ...
```
To select another encoding, you must provide the query parameter ''enc=ENCODING''.
Others are ""[[html|00001012920510]]"", ""[[text|00001012920519]]"", and some [[more|00001012920500]].
|
︙ | | |
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
-
+
|
<h1>API: Retrieve evaluated metadata and content of an existing zettel in various encodings</h1>
<p>The <a href="00001012920000">endpoint</a> to work with evaluated metadata and content of a specific zettel is <kbd>/z/{ID}</kbd>,
...
```
=== HTTP Status codes
; ''200''
: Retrieval was successful, the body contains an appropriate JSON object.
: Retrieval was successful, the body contains an appropriate data value.
; ''400''
: Request was not valid.
There are several reasons for this.
Maybe the zettel identifier did not consist of exactly 14 digits or ''enc'' / ''part'' contained illegal values.
; ''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/00001012053600.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
|
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
|
-
+
-
+
|
id: 00001012053600
title: API: Retrieve parsed metadata and content of an existing zettel in various encodings
role: manual
tags: #api #manual #zettelstore
syntax: zmk
created: 20210126175322
modified: 20230109105034
modified: 20230807170019
The [[endpoint|00001012920000]] to work with parsed metadata and content of a specific zettel is ''/z/{ID}'', where ''{ID}'' is a placeholder for the [[zettel identifier|00001006050000]].
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 ''/z/00001012053600''[^If [[authentication is enabled|00001010040100]], you must include the a valid [[access token|00001012050200]] in the ''Authorization'' header] with the query parameter ''parseonly'' (and other appropriate query parameter).
For example:
```sh
# curl 'http://127.0.0.1:23123/z/00001012053600?enc=sz&parseonly'
((PARA (TEXT "The") (SPACE) (LINK-ZETTEL () "00001012920000" (TEXT "endpoint")) (SPACE) (TEXT "to") (SPACE) (TEXT "work") (SPACE) (TEXT "with") (SPACE) ...
```
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''
: Retrieval was successful, the body contains an appropriate JSON object.
: Retrieval was successful, the body contains an appropriate data value.
; ''400''
: Request was not valid.
There are several reasons for this.
Maybe the zettel identifier did not consist of exactly 14 digits or ''enc'' / ''part'' contained illegal values.
; ''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/00001012054200.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
|
id: 00001012054200
title: API: Update a zettel
role: manual
tags: #api #manual #zettelstore
syntax: zmk
created: 20210713150005
modified: 20230807124354
modified: 20230807165948
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 ''/z/{ID}'', where ''{ID}'' is a placeholder for the [[zettel identifier|00001006050000]].
You must send a HTTP PUT request to that endpoint.
|
︙ | | |
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
|
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
-
-
-
-
-
-
-
-
-
-
-
|
=== Data input
Alternatively, you may encode the zettel as a parseable object / a [[symbolic expression|00001012930500]] by providing the query parameter ''enc=data''.
The encoding is the same as the data output encoding when you [[retrieve a zettel|00001012053300#data-output]].
The encoding for [[access rights|00001012921200]] must be given, but is ignored.
You may encode computed or property [[metadata keys|00001006020000]], but these are also ignored.
=== JSON input (deprecated)
Alternatively, you can use the JSON encoding by using the query parameter ''enc=json''.
```
# curl -X PUT --data '{}' 'http://127.0.0.1:23123/z/00001012054200?enc=json'
```
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.
The body of the HTTP response is empty, if the request was successful.
=== HTTP Status codes
; ''204''
: Update was successful, there is no body in the response.
; ''400''
: Request was not valid.
For example, the request body was not valid.
; ''403''
: You are not allowed to delete the given zettel.
; ''404''
: Zettel not found.
You probably used a zettel identifier that is not used in the Zettelstore.
|
Changes to docs/manual/00001012921000.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
-
+
-
-
+
+
+
+
+
+
+
+
+
+
|
id: 00001012921000
title: API: Structure of an access token
role: manual
tags: #api #manual #reference #zettelstore
syntax: zmk
created: 20210126175322
modified: 20230412155303
modified: 20230807165915
If the [[authentication process|00001012050200]] was successful, an access token with some additional data is returned.
The same is true, if the access token was [[renewed|00001012050400]].
The response is structured as a [[symbolic expression|00001012930000]] list, with the following elements:
# The type of the token, always set to ''"Bearer"'', as described in [[RFC 6750|https://tools.ietf.org/html/rfc6750]]
# The token itself, as string value, which is technically a [[JSON Web Token|https://tools.ietf.org/html/rfc7519]] (JWT, RFC 7915)
# An integer that gives a hint about the lifetime / endurance of the token, measured in seconds
# The token itself, which is technically the string representation of a [[symbolic expression|00001012930500]] containing relevant data, plus a check sum.
#* The symbolic expression has the form ''(KIND USERNAME NOW EXPIRE Z-ID)''
#* ''KIND'' is ''0'' for an API access, ''1'' if it created for the Web user interface.
#* ''USERNAME'' is the user name of the user.
#* ''NOW'' is a timestamp of the current time.
#* ''EXPIRE'' is the timestamp when the access token expires.
#* ''Z-ID'' is the zettel identifier of the user zettel.
The symbolic expression is encoded via ""base64"".
Based on this encoding, a checksum is calculated, also encoded via ""base64"".
Both encoded values are concatenated, with a period (''"."'') as a delimiter.
|
Changes to docs/manual/00001012921200.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
+
-
+
-
-
+
+
|
id: 00001012921200
title: API: Encoding of Zettel Access Rights
role: manual
tags: #api #manual #reference #zettelstore
syntax: zmk
created: 20220201173115
modified: 20220201171959
modified: 20230807164817
Various API calls return a JSON key ''"rights"'' that encodes the access rights the user currently has.
It is an integer number between 0 and 62.[^Not all values in this range are used.]
Various API calls return a symbolic expression list ''(rights N)'', with ''N'' as a number, that encodes the access rights the user currently has.
''N'' is an integer number between 0 and 62.[^Not all values in this range are used.]
The value ""0"" signals that something went wrong internally while determining the access rights.
A value of ""1"" says, that the current user has no access right for the given zettel.
In most cases, this value will not occur, because only zettel are presented, which are at least readable by the current user.
Values ""2"" to ""62"" are binary encoded values, where each bit signals a special right.
|
︙ | | |
Changes to docs/manual/00001017000000.zettel.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
-
+
|
id: 00001017000000
title: Tips and Tricks
role: manual
tags: #manual #zettelstore
syntax: zmk
created: 20220803170112
modified: 20221205154406
modified: 20230827225202
=== Welcome Zettel
* **Problem:** You want to put your Zettelstore into the public and need a starting zettel for your users.
In addition, you still want a ""home zettel"", with all your references to internal, non-public zettel.
Zettelstore only allows to specify one [[''home-zettel''|00001004020000#home-zettel]].
* **Solution 1:**
*# Create a new zettel with all your references to internal, non-public zettel.
|
︙ | | |
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
|
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
|
-
-
+
+
-
-
+
+
-
-
-
+
+
+
-
-
+
+
-
|
If multiple user should use the same home zettel, its zettel identifier must be set in all relevant user zettel.
=== Role-specific Layout of Zettel in Web User Interface (WebUI)
[!role-css]
* **Problem:** You want to add some CSS when displaying zettel of a specific [[role|00001006020000#role]].
For example, you might want to add a yellow background color for all [[configuration|00001006020100#configuration]] zettel.
Or you want a multi-column layout.
* **Solution:** If you enable [[''expert-mode''|00001004020000#expert-mode]], you will have access to a zettel called ""[[Zettelstore Role to CSS Map|00000000029000]]"" (its identifier is ''00000000029000'').
This zettel maps a role name to a zettel that must contain the role-specific CSS code.
* **Solution:** If you enable [[''expert-mode''|00001004020000#expert-mode]], you will have access to a zettel called ""[[Zettelstore Sxn Start Code|00000000019000]]"" (its identifier is ''00000000019000'').
This zettel is the starting point for Sxn code, where you can place a definition for a variable named ""CSS-ROLE-map"".
First, create a zettel containing the needed CSS: give it any title, its role is preferably ""configuration"" (but this is not a must).
Set its [[''syntax''|00001006020000#syntax]]Â must be set to ""[[css|00001008000000#css]]"".
But first, create a zettel containing the needed CSS: give it any title, its role is preferably ""configuration"" (but this is not a must).
Its [[''syntax''|00001006020000#syntax]]Â must be set to ""[[css|00001008000000#css]]"".
The content must contain the role-specific CSS code, for example ``body {background-color: #FFFFD0}``for a background in a light yellow color.
Let's assume, the newly created CSS zettel got the identifier ''20220825200100''.
Now, you have to connect this zettel to the zettel called ""Zettelstore Role CSS Map"".
Since you have enabled ''expert-mode'', you are allowed to modify it.
Add the following metadata ''css-configuration-zid: 20220825200100'' to assign the role-specific CSS code for the role ""configuration"" to the CSS zettel containing that CSS.
Now, you have to map this freshly created zettel to a role, for example ""zettel"".
Since you have enabled ''expert-mode'', you are allowed to modify the zettel ""[[Zettelstore Sxn Start Code|00000000019000]]"".
Add the following code to the Sxn Start Code zettel: ``(define CSS-ROLE-map '(("zettel" . "20220825200100")))``.
In general, its role-assigning metadata must be like this pattern: ''css-ROLE-zid: ID'', where ''ROLE'' is the placeholder for the role, and ''ID'' for the zettel identifier containing CSS code.
It is allowed to assign more than one role to a specific CSS zettel.
In general, the mapping must follow the pattern: ``(ROLE . ID)``, where ''ROLE'' is the placeholder for the role, and ''ID'' for the zettel identifier containing CSS code.
For example, if you also want the role ""configuration"" to be rendered using that CSS, the code should be something like ``(define CSS-ROLE-map '(("zettel" . "20220825200100") ("configuration" . "20220825200100")))``.
* **Discussion:** you have to ensure that the CSS zettel is allowed to be read by the intended audience of the zettel with that given role.
For example, if you made zettel with a specific role public visible, the CSS zettel must also have a [[''visibility: public''|00001010070200]] metadata.
* **Extension:** if you have already established a role-specific layout for zettel, but you additionally want just one another zettel with another role to be rendered with the same CSS, you have to add metadata to the one zettel: ''css-role: ROLE'', where ''ROLE'' is the placeholder for the role that already is assigned to a specific CSS-based layout.
=== Zettel synchronization with iCloud (Apple)
* **Problem:** You use Zettelstore on various macOS computers and you want to use the sameset of zettel across all computers.
* **Solution:** Place your zettel in an iCloud folder.
To configure Zettelstore to use the folder, you must specify its location within you directory structure as [[''box-uri-X''|00001004010000#box-uri-x]] (replace ''X'' with an appropriate number).
Your iCloud folder is typically placed in the folder ''~/Library/Mobile Documents/com~apple~CloudDocs''.
|
︙ | | |
Changes to encoder/htmlenc/htmlenc.go.
︙ | | |
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
|
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
|
-
+
-
+
|
hen := he.th.Endnotes()
sf := he.th.SymbolFactory()
symAttr := sf.MustMake(sxhtml.NameSymAttr)
head := sx.MakeList(sf.MustMake("head"))
curr := head
curr = curr.AppendBang(sx.Nil().Cons(sx.Nil().Cons(sx.Cons(sf.MustMake("charset"), sx.MakeString("utf-8"))).Cons(symAttr)).Cons(sf.MustMake("meta")))
curr = curr.AppendBang(sx.Nil().Cons(sx.Nil().Cons(sx.Cons(sf.MustMake("charset"), sx.String("utf-8"))).Cons(symAttr)).Cons(sf.MustMake("meta")))
for elem := hm; elem != nil; elem = elem.Tail() {
curr = curr.AppendBang(elem.Car())
}
var sb strings.Builder
if hasTitle {
he.textEnc.WriteInlines(&sb, &isTitle)
} else {
sb.Write(zn.Meta.Zid.Bytes())
}
_ = curr.AppendBang(sx.Nil().Cons(sx.MakeString(sb.String())).Cons(sf.MustMake("title")))
_ = curr.AppendBang(sx.Nil().Cons(sx.String(sb.String())).Cons(sf.MustMake("title")))
body := sx.MakeList(sf.MustMake("body"))
curr = body
if hasTitle {
curr = curr.AppendBang(htitle.Cons(sf.MustMake("h1")))
}
for elem := hast; elem != nil; elem = elem.Tail() {
|
︙ | | |
Changes to encoder/szenc/transform.go.
︙ | | |
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
-
+
|
"zettelstore.de/z/ast"
"zettelstore.de/z/encoder"
"zettelstore.de/z/zettel/meta"
)
// NewTransformer returns a new transformer to create s-expressions from AST nodes.
func NewTransformer() *Transformer {
sf := sx.MakeMappedFactory()
sf := sx.MakeMappedFactory(1024)
t := Transformer{sf: sf}
t.zetSyms.InitializeZettelSymbols(sf)
t.mapVerbatimKindS = map[ast.VerbatimKind]*sx.Symbol{
ast.VerbatimZettel: t.zetSyms.SymVerbatimZettel,
ast.VerbatimProg: t.zetSyms.SymVerbatimProg,
ast.VerbatimEval: t.zetSyms.SymVerbatimEval,
|
︙ | | |
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
|
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
|
-
+
-
-
+
+
-
+
-
+
-
+
-
+
-
-
-
+
+
+
-
+
-
+
|
return t.getInlineSlice(*n)
case *ast.ParaNode:
return t.getInlineSlice(n.Inlines).Tail().Cons(t.zetSyms.SymPara)
case *ast.VerbatimNode:
return sx.MakeList(
mapGetS(t, t.mapVerbatimKindS, n.Kind),
t.getAttributes(n.Attrs),
sx.MakeString(string(n.Content)),
sx.String(string(n.Content)),
)
case *ast.RegionNode:
return t.getRegion(n)
case *ast.HeadingNode:
return sx.MakeList(
t.zetSyms.SymHeading,
sx.Int64(int64(n.Level)),
t.getAttributes(n.Attrs),
sx.MakeString(n.Slug),
sx.MakeString(n.Fragment),
sx.String(n.Slug),
sx.String(n.Fragment),
t.getInlineSlice(n.Inlines),
)
case *ast.HRuleNode:
return sx.MakeList(t.zetSyms.SymThematic, t.getAttributes(n.Attrs))
case *ast.NestedListNode:
return t.getNestedList(n)
case *ast.DescriptionListNode:
return t.getDescriptionList(n)
case *ast.TableNode:
return t.getTable(n)
case *ast.TranscludeNode:
return sx.MakeList(t.zetSyms.SymTransclude, t.getAttributes(n.Attrs), t.getReference(n.Ref))
case *ast.BLOBNode:
return t.getBLOB(n)
case *ast.TextNode:
return sx.MakeList(t.zetSyms.SymText, sx.MakeString(n.Text))
return sx.MakeList(t.zetSyms.SymText, sx.String(n.Text))
case *ast.SpaceNode:
if t.inVerse {
return sx.MakeList(t.zetSyms.SymSpace, sx.MakeString(n.Lexeme))
return sx.MakeList(t.zetSyms.SymSpace, sx.String(n.Lexeme))
}
return sx.MakeList(t.zetSyms.SymSpace)
case *ast.BreakNode:
if n.Hard {
return sx.MakeList(t.zetSyms.SymHard)
}
return sx.MakeList(t.zetSyms.SymSoft)
case *ast.LinkNode:
return t.getLink(n)
case *ast.EmbedRefNode:
return t.getInlineSlice(n.Inlines).Tail().
Cons(sx.MakeString(n.Syntax)).
Cons(sx.String(n.Syntax)).
Cons(t.getReference(n.Ref)).
Cons(t.getAttributes(n.Attrs)).
Cons(t.zetSyms.SymEmbed)
case *ast.EmbedBLOBNode:
return t.getEmbedBLOB(n)
case *ast.CiteNode:
return t.getInlineSlice(n.Inlines).Tail().
Cons(sx.MakeString(n.Key)).
Cons(sx.String(n.Key)).
Cons(t.getAttributes(n.Attrs)).
Cons(t.zetSyms.SymCite)
case *ast.FootnoteNode:
text := sx.Nil().Cons(sx.Nil().Cons(t.getInlineSlice(n.Inlines)).Cons(t.zetSyms.SymQuote))
return text.Cons(t.getAttributes(n.Attrs)).Cons(t.zetSyms.SymEndnote)
case *ast.MarkNode:
return t.getInlineSlice(n.Inlines).Tail().
Cons(sx.MakeString(n.Fragment)).
Cons(sx.MakeString(n.Slug)).
Cons(sx.MakeString(n.Mark)).
Cons(sx.String(n.Fragment)).
Cons(sx.String(n.Slug)).
Cons(sx.String(n.Mark)).
Cons(t.zetSyms.SymMark)
case *ast.FormatNode:
return t.getInlineSlice(n.Inlines).Tail().
Cons(t.getAttributes(n.Attrs)).
Cons(mapGetS(t, t.mapFormatKindS, n.Kind))
case *ast.LiteralNode:
return sx.MakeList(
mapGetS(t, t.mapLiteralKindS, n.Kind),
t.getAttributes(n.Attrs),
sx.MakeString(string(n.Content)),
sx.String(string(n.Content)),
)
}
return sx.MakeList(t.zetSyms.SymUnknown, sx.MakeString(fmt.Sprintf("%T %v", node, node)))
return sx.MakeList(t.zetSyms.SymUnknown, sx.String(fmt.Sprintf("%T %v", node, node)))
}
func (t *Transformer) getRegion(rn *ast.RegionNode) *sx.Pair {
saveInVerse := t.inVerse
if rn.Kind == ast.RegionVerse {
t.inVerse = true
}
|
︙ | | |
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
|
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
|
-
+
-
+
-
+
-
+
-
+
|
func (t *Transformer) getCell(cell *ast.TableCell) *sx.Pair {
return t.getInlineSlice(cell.Inlines).Tail().Cons(mapGetS(t, t.alignmentSymbolS, cell.Align))
}
func (t *Transformer) getBLOB(bn *ast.BLOBNode) *sx.Pair {
var lastObj sx.Object
if bn.Syntax == meta.SyntaxSVG {
lastObj = sx.MakeString(string(bn.Blob))
lastObj = sx.String(string(bn.Blob))
} else {
lastObj = getBase64String(bn.Blob)
}
return sx.MakeList(
t.zetSyms.SymBLOB,
t.getInlineSlice(bn.Description),
sx.MakeString(bn.Syntax),
sx.String(bn.Syntax),
lastObj,
)
}
func (t *Transformer) getLink(ln *ast.LinkNode) *sx.Pair {
return t.getInlineSlice(ln.Inlines).Tail().
Cons(sx.MakeString(ln.Ref.Value)).
Cons(sx.String(ln.Ref.Value)).
Cons(t.getAttributes(ln.Attrs)).
Cons(mapGetS(t, t.mapRefStateLink, ln.Ref.State))
}
func (t *Transformer) getEmbedBLOB(en *ast.EmbedBLOBNode) *sx.Pair {
tail := t.getInlineSlice(en.Inlines).Tail()
if en.Syntax == meta.SyntaxSVG {
tail = tail.Cons(sx.MakeString(string(en.Blob)))
tail = tail.Cons(sx.String(string(en.Blob)))
} else {
tail = tail.Cons(getBase64String(en.Blob))
}
return tail.Cons(sx.MakeString(en.Syntax)).Cons(t.getAttributes(en.Attrs)).Cons(t.zetSyms.SymEmbedBLOB)
return tail.Cons(sx.String(en.Syntax)).Cons(t.getAttributes(en.Attrs)).Cons(t.zetSyms.SymEmbedBLOB)
}
func (t *Transformer) getBlockSlice(bs *ast.BlockSlice) *sx.Pair {
objs := make([]sx.Object, len(*bs))
for i, n := range *bs {
objs[i] = t.GetSz(n)
}
|
︙ | | |
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
|
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
|
-
+
-
+
-
+
-
+
|
func (t *Transformer) getAttributes(a attrs.Attributes) sx.Object {
if a.IsEmpty() {
return sx.Nil()
}
keys := a.Keys()
objs := make([]sx.Object, 0, len(keys))
for _, k := range keys {
objs = append(objs, sx.Cons(sx.MakeString(k), sx.MakeString(a[k])))
objs = append(objs, sx.Cons(sx.String(k), sx.String(a[k])))
}
return sx.Nil().Cons(sx.MakeList(objs...)).Cons(t.zetSyms.SymQuote)
}
func (t *Transformer) getReference(ref *ast.Reference) *sx.Pair {
return sx.MakeList(
t.zetSyms.SymQuote,
sx.MakeList(
mapGetS(t, t.mapRefStateS, ref.State),
sx.MakeString(ref.Value),
sx.String(ref.Value),
),
)
}
func (t *Transformer) GetMeta(m *meta.Meta, evalMeta encoder.EvalMetaFunc) *sx.Pair {
pairs := m.ComputedPairs()
objs := make([]sx.Object, 0, len(pairs))
for _, p := range pairs {
key := p.Key
ty := m.Type(key)
symType := mapGetS(t, t.mapMetaTypeS, ty)
var obj sx.Object
if ty.IsSet {
setList := meta.ListFromValue(p.Value)
setObjs := make([]sx.Object, len(setList))
for i, val := range setList {
setObjs[i] = sx.MakeString(val)
setObjs[i] = sx.String(val)
}
obj = sx.MakeList(setObjs...).Cons(t.zetSyms.SymList)
} else if ty == meta.TypeZettelmarkup {
is := evalMeta(p.Value)
obj = t.GetSz(&is)
} else {
obj = sx.MakeString(p.Value)
obj = sx.String(p.Value)
}
symKey := sx.MakeList(t.zetSyms.SymQuote, t.sf.MustMake(key))
objs = append(objs, sx.Nil().Cons(obj).Cons(symKey).Cons(symType))
}
return sx.MakeList(objs...).Cons(t.zetSyms.SymMeta)
}
|
︙ | | |
417
418
419
420
421
422
423
424
425
426
427
|
417
418
419
420
421
422
423
424
425
426
427
|
-
+
-
+
|
var sb strings.Builder
encoder := base64.NewEncoder(base64.StdEncoding, &sb)
_, err := encoder.Write(data)
if err == nil {
err = encoder.Close()
}
if err == nil {
return sx.MakeString(sb.String())
return sx.String(sb.String())
}
return sx.MakeString("")
return sx.String("")
}
|
Changes to evaluator/metadata.go.
︙ | | |
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
-
-
-
-
+
-
|
sliceData = meta.ListFromValue(value)
if len(sliceData) == 0 {
return nil
}
} else {
sliceData = []string{value}
}
var makeLink bool
switch dt {
case meta.TypeID, meta.TypeIDSet:
makeLink = true
makeLink := dt == meta.TypeID || dt == meta.TypeIDSet
}
result := make(ast.InlineSlice, 0, 2*len(sliceData)-1)
for i, val := range sliceData {
if i > 0 {
result = append(result, &ast.SpaceNode{Lexeme: " "})
}
tn := &ast.TextNode{Text: val}
|
︙ | | |
Changes to go.mod.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
-
+
-
-
-
-
-
-
+
+
+
+
+
+
-
+
|
module zettelstore.de/z
go 1.20
go 1.21
require (
github.com/fsnotify/fsnotify v1.6.0
github.com/yuin/goldmark v1.5.5
golang.org/x/crypto v0.12.0
golang.org/x/term v0.11.0
golang.org/x/text v0.12.0
zettelstore.de/client.fossil v0.0.0-20230807134407-92d8dd7df841
zettelstore.de/sx.fossil v0.0.0-20230727172325-adec5a7ba284
github.com/yuin/goldmark v1.5.6
golang.org/x/crypto v0.13.0
golang.org/x/term v0.12.0
golang.org/x/text v0.13.0
zettelstore.de/client.fossil v0.0.0-20230925145719-59713892870c
zettelstore.de/sx.fossil v0.0.0-20230915173519-fa23195f2b56
)
require golang.org/x/sys v0.11.0 // indirect
require golang.org/x/sys v0.12.0 // indirect
|
Changes to go.sum.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
-
-
-
-
+
+
+
+
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
|
github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/yuin/goldmark v1.5.5 h1:IJznPe8wOzfIKETmMkd06F8nXkmlhaHqFRM9l1hAGsU=
github.com/yuin/goldmark v1.5.5/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk=
golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw=
github.com/yuin/goldmark v1.5.6 h1:COmQAWTCcGetChm3Ig7G/t8AFAN00t+o8Mt4cf7JpwA=
github.com/yuin/goldmark v1.5.6/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.13.0 h1:mvySKfSWJ+UKUii46M40LOvyWfN0s2U+46/jDd0e6Ck=
golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.11.0 h1:F9tnn/DA/Im8nCwm+fX+1/eBwi4qFjRT++MhtVC4ZX0=
golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU=
golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc=
golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
zettelstore.de/client.fossil v0.0.0-20230807134407-92d8dd7df841 h1:QlOIlT2cURqM2nYEvL7zOrjiE5/ZA3iAAfslcd6u2PY=
zettelstore.de/client.fossil v0.0.0-20230807134407-92d8dd7df841/go.mod h1:MaVH7f0eHaWB5bK0GHNUiPJxKIYGyBk9amBUSbDZM0g=
zettelstore.de/sx.fossil v0.0.0-20230727172325-adec5a7ba284 h1:26xwZWEjdyL3wObczc/PKugv0EY6mgSH5NUe5kYFCt4=
zettelstore.de/sx.fossil v0.0.0-20230727172325-adec5a7ba284/go.mod h1:nsWXVrQG8RNKtoXzEMrWXNMdnpfIDU6Hb0pk56KpVKE=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.12.0 h1:/ZfYdc3zq+q02Rv9vGqTeSItdzZTSNDmfTi0mBAuidU=
golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/text v0.13.0 h1:ablQoSUd0tRdKxZewP80B+BaqeKJuVhuRxj/dkrun3k=
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
zettelstore.de/client.fossil v0.0.0-20230925145719-59713892870c h1:y/6Njmh9luzySJw6ZttmDcq+xKzqpx1n4UxHysYjBn0=
zettelstore.de/client.fossil v0.0.0-20230925145719-59713892870c/go.mod h1:XtlEvc8JZQLJH4DO9Lvdwv5wEpr96gJ/NYyfyutnf0Y=
zettelstore.de/sx.fossil v0.0.0-20230915173519-fa23195f2b56 h1:Y1cw0BCmxDZMImE5c5jGDIOz1XdTpG5/GBBjMkZZUo8=
zettelstore.de/sx.fossil v0.0.0-20230915173519-fa23195f2b56/go.mod h1:Uw3OLM1ufOM4Xe0G51mvkTDUv2okd+HyDBMx+0ZG7ME=
|
Changes to kernel/impl/cfg.go.
︙ | | |
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
+
|
"zettelstore.de/z/zettel/meta"
)
type configService struct {
srvConfig
mxService sync.RWMutex
orig *meta.Meta
manager box.Manager
}
// Predefined Metadata keys for runtime configuration
// See: https://zettelstore.de/manual/h/00001004020000
const (
keyDefaultCopyright = "default-copyright"
keyDefaultLicense = "default-license"
|
︙ | | |
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
|
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
|
+
+
+
+
-
+
|
return cs.orig != nil
}
func (cs *configService) Stop(*myKernel) {
cs.logger.Info().Msg("Stop Service")
cs.mxService.Lock()
cs.orig = nil
cs.manager = nil
cs.mxService.Unlock()
}
func (*configService) GetStatistics() []kernel.KeyValue {
return nil
}
func (cs *configService) setBox(mgr box.Manager) {
cs.mxService.Lock()
cs.manager = mgr
cs.mxService.Unlock()
mgr.RegisterObserver(cs.observe)
cs.observe(box.UpdateInfo{Box: mgr, Reason: box.OnZettel, Zid: id.ConfigurationZid})
}
func (cs *configService) doUpdate(p box.BaseBox) error {
z, err := p.GetZettel(context.Background(), cs.orig.Zid)
z, err := p.GetZettel(context.Background(), id.ConfigurationZid)
cs.logger.Trace().Err(err).Msg("got config meta")
if err != nil {
return err
}
m := z.Meta
cs.mxService.Lock()
for _, pair := range cs.orig.Pairs() {
|
︙ | | |
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
|
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
|
-
+
+
+
+
+
+
+
+
+
+
|
cs.SwitchNextToCur() // Poor man's restart
return nil
}
func (cs *configService) observe(ci box.UpdateInfo) {
if ci.Reason != box.OnZettel || ci.Zid == id.ConfigurationZid {
cs.logger.Debug().Uint("reason", uint64(ci.Reason)).Zid(ci.Zid).Msg("observe")
go func() { cs.doUpdate(ci.Box) }()
go func() {
cs.mxService.RLock()
mgr := cs.manager
cs.mxService.RUnlock()
if mgr != nil {
cs.doUpdate(mgr)
} else {
cs.doUpdate(ci.Box)
}
}()
}
}
// --- config.Config
func (cs *configService) Get(ctx context.Context, m *meta.Meta, key string) string {
if m != nil {
|
︙ | | |
Changes to kernel/impl/server.go.
︙ | | |
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
|
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
|
-
-
+
+
-
-
+
+
|
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)
if ri := recover(); ri != nil {
kern.doLogRecover("Line", ri)
go lineServer(ln, kern)
}
}()
for {
conn, err := ln.Accept()
if err != nil {
// handle error
kern.logger.IfErr(err).Msg("Unable to accept connection")
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)
if ri := recover(); ri != nil {
kern.doLogRecover("LineConn", ri)
go handleLineConnection(conn, kern)
}
}()
kern.logger.Mandatory().Str("from", conn.RemoteAddr().String()).Msg("Start session on administration console")
cmds := cmdSession{}
cmds.initialize(conn, kern)
|
︙ | | |
Changes to parser/plain/plain.go.
︙ | | |
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
-
+
-
|
package plain
import (
"bytes"
"strings"
"zettelstore.de/client.fossil/attrs"
"zettelstore.de/sx.fossil/sxbuiltins/pprint"
"zettelstore.de/sx.fossil/sxbuiltins"
"zettelstore.de/sx.fossil/sxbuiltins/quote"
"zettelstore.de/sx.fossil/sxreader"
"zettelstore.de/z/ast"
"zettelstore.de/z/input"
"zettelstore.de/z/parser"
"zettelstore.de/z/zettel/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
|
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
|
-
-
+
-
+
|
// TODO: check proper end </svg>
return svgSrc
}
func parseSxnBlocks(inp *input.Input, _ *meta.Meta, syntax string) ast.BlockSlice {
rd := sxreader.MakeReader(bytes.NewReader(inp.Src))
sf := rd.SymbolFactory()
quote.InstallQuoteReader(rd, sf.MustMake("quote"), '\'')
quote.InstallQuasiQuoteReader(rd,
sxbuiltins.InstallQuasiQuoteReader(rd,
sf.MustMake("quasiquote"), '`',
sf.MustMake("unquote"), ',',
sf.MustMake("unquote-splicing"), '@')
objs, err := rd.ReadAll()
if err != nil {
return ast.BlockSlice{
&ast.VerbatimNode{
Kind: ast.VerbatimProg,
Attrs: attrs.Attributes{"": syntax},
Content: inp.ScanLineContent(),
},
ast.CreateParaNode(&ast.TextNode{
Text: err.Error(),
}),
}
}
result := make(ast.BlockSlice, len(objs))
for i, obj := range objs {
var buf bytes.Buffer
pprint.Print(&buf, obj)
sxbuiltins.Print(&buf, obj)
result[i] = &ast.VerbatimNode{
Kind: ast.VerbatimProg,
Attrs: attrs.Attributes{"": syntax},
Content: buf.Bytes(),
}
}
return result
|
︙ | | |
Changes to query/compiled.go.
︙ | | |
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
+
+
+
+
|
type CompiledTerm struct {
Match MetaMatchFunc // Match on metadata
Retrieve RetrievePredicate // Retrieve from full-text search
}
// RetrievePredicate returns true, if the given Zid is contained in the (full-text) search.
type RetrievePredicate func(id.Zid) bool
// AlwaysIncluded is a RetrievePredicate that always returns true.
func AlwaysIncluded(id.Zid) bool { return true }
func neverIncluded(id.Zid) bool { return false }
func (c *Compiled) isDeterministic() bool { return c.seed > 0 }
// Result returns a result of the compiled search, that is achievable without iterating through a box.
func (c *Compiled) Result() []*meta.Meta {
if len(c.startMeta) == 0 {
// nil -> no directive
|
︙ | | |
Changes to query/context.go.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
+
|
//-----------------------------------------------------------------------------
// Copyright (c) 2023-present Detlef Stern
//
// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
//-----------------------------------------------------------------------------
package query
import (
"container/heap"
"context"
"zettelstore.de/client.fossil/api"
"zettelstore.de/z/zettel/id"
"zettelstore.de/z/zettel/meta"
)
|
︙ | | |
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
|
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
|
-
-
+
+
-
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-
+
-
-
-
+
+
-
-
-
+
-
+
-
-
-
-
-
-
+
+
+
-
-
-
+
-
+
-
+
-
+
-
+
-
-
+
+
-
-
+
+
-
-
+
+
+
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
+
-
+
-
+
-
+
+
-
+
-
-
+
-
-
+
-
-
+
-
-
+
-
-
+
+
-
+
-
+
-
+
-
+
-
-
+
+
-
-
+
+
-
-
-
-
-
-
-
+
-
+
-
-
-
+
+
-
-
-
+
+
+
|
tasks.addSameTag(ctx, tag, cost)
}
}
}
return result
}
type ztlCtxTask struct {
next *ztlCtxTask
type ztlCtxItem struct {
cost int
prev *ztlCtxTask
meta *meta.Meta
}
type ztlCtxQueue []ztlCtxItem
cost int
func (q ztlCtxQueue) Len() int { return len(q) }
func (q ztlCtxQueue) Less(i, j int) bool { return q[i].cost < q[j].cost }
func (q ztlCtxQueue) Swap(i, j int) { q[i], q[j] = q[j], q[i] }
func (q *ztlCtxQueue) Push(x any) { *q = append(*q, x.(ztlCtxItem)) }
func (q *ztlCtxQueue) Pop() any {
old := *q
n := len(old)
item := old[n-1]
old[n-1].meta = nil // avoid memory leak
*q = old[0 : n-1]
return item
}
type contextQueue struct {
type contextTask struct {
port ContextPort
seen id.Set
first *ztlCtxTask
queue ztlCtxQueue
last *ztlCtxTask
maxCost int
limit int
tagCost map[string][]*meta.Meta
}
func newQueue(startSeq []*meta.Meta, maxCost, limit int, port ContextPort) *contextQueue {
result := &contextQueue{
func newQueue(startSeq []*meta.Meta, maxCost, limit int, port ContextPort) *contextTask {
result := &contextTask{
port: port,
seen: id.NewSet(),
first: nil,
last: nil,
maxCost: maxCost,
limit: limit,
tagCost: make(map[string][]*meta.Meta, 1024),
}
var prev *ztlCtxTask
queue := make(ztlCtxQueue, 0, len(startSeq))
for _, m := range startSeq {
task := &ztlCtxTask{next: nil, prev: prev, meta: m, cost: 1}
queue = append(queue, ztlCtxItem{cost: 1, meta: m})
if prev == nil {
result.first = task
} else {
prev.next = task
}
result.last = task
}
heap.Init(&queue)
result.queue = queue
prev = task
}
return result
}
func (zc *contextQueue) addPair(ctx context.Context, key, value string, curCost int, isBackward, isForward bool) {
func (ct *contextTask) addPair(ctx context.Context, key, value string, curCost int, isBackward, isForward bool) {
if key == api.KeyBack {
return
}
newCost := curCost + contextCost(key)
if key == api.KeyBackward {
if isBackward {
zc.addIDSet(ctx, newCost, value)
ct.addIDSet(ctx, newCost, value)
}
return
}
if key == api.KeyForward {
if isForward {
zc.addIDSet(ctx, newCost, value)
ct.addIDSet(ctx, newCost, value)
}
return
}
hasInverse := meta.Inverse(key) != ""
if (!hasInverse || !isBackward) && (hasInverse || !isForward) {
return
}
if t := meta.Type(key); t == meta.TypeID {
zc.addID(ctx, newCost, value)
ct.addID(ctx, newCost, value)
} else if t == meta.TypeIDSet {
zc.addIDSet(ctx, newCost, value)
ct.addIDSet(ctx, newCost, value)
}
}
func contextCost(key string) int {
switch key {
case api.KeyFolge, api.KeyPrecursor:
return 1
case api.KeySuccessors, api.KeyPredecessor,
api.KeySubordinates, api.KeySuperior:
return 2
}
return 3
}
func (zc *contextQueue) addID(ctx context.Context, newCost int, value string) {
if zc.costMaxed(newCost) {
func (ct *contextTask) addID(ctx context.Context, newCost int, value string) {
if ct.costMaxed(newCost) {
return
}
if zid, errParse := id.Parse(value); errParse == nil {
if m, errGetMeta := zc.port.GetMeta(ctx, zid); errGetMeta == nil {
zc.addMeta(m, newCost)
if m, errGetMeta := ct.port.GetMeta(ctx, zid); errGetMeta == nil {
ct.addMeta(m, newCost)
}
}
}
func (zc *contextQueue) addMeta(m *meta.Meta, newCost int) {
task := &ztlCtxTask{next: nil, prev: nil, meta: m, cost: newCost}
func (ct *contextTask) addMeta(m *meta.Meta, newCost int) {
if _, found := ct.seen[m.Zid]; !found {
heap.Push(&ct.queue, ztlCtxItem{cost: newCost, meta: m})
if zc.first == nil {
zc.first = task
zc.last = task
return
}
}
// Search backward for a task t with at most the same cost
for t := zc.last; t != nil; t = t.prev {
if t.cost <= task.cost {
// Found!
if t.next != nil {
t.next.prev = task
}
task.next = t.next
t.next = task
task.prev = t
if task.next == nil {
zc.last = task
}
return
}
}
// We have not found a task, therefore the new task is the first one
task.next = zc.first
zc.first.prev = task
zc.first = task
}
func (zc *contextQueue) costMaxed(newCost int) bool {
func (ct *contextTask) costMaxed(newCost int) bool {
// If len(zc.seen) <= 1, the initial zettel is processed. In this case allow all
// other zettel that are directly reachable, without taking the cost into account.
// Of course, the limit ist still relevant.
return (len(zc.seen) > 1 && zc.maxCost > 0 && newCost > zc.maxCost) || zc.hasLimit()
return (len(ct.seen) > 1 && ct.maxCost > 0 && newCost > ct.maxCost) || ct.hasLimit()
}
func (zc *contextQueue) addIDSet(ctx context.Context, newCost int, value string) {
func (ct *contextTask) addIDSet(ctx context.Context, newCost int, value string) {
elems := meta.ListFromValue(value)
refCost := referenceCost(newCost, len(elems))
for _, val := range elems {
zc.addID(ctx, refCost, val)
ct.addID(ctx, refCost, val)
}
}
func referenceCost(baseCost int, numReferences int) int {
switch {
if numReferences < 5 {
case numReferences < 5:
return baseCost + 1
}
if numReferences < 9 {
case numReferences < 9:
return baseCost * 2
}
if numReferences < 17 {
case numReferences < 17:
return baseCost * 3
}
if numReferences < 33 {
case numReferences < 33:
return baseCost * 4
}
if numReferences < 65 {
case numReferences < 65:
return baseCost * 5
}
return baseCost * numReferences / 8
}
func (zc *contextQueue) addSameTag(ctx context.Context, tag string, baseCost int) {
tagMetas, found := zc.tagCost[tag]
func (ct *contextTask) addSameTag(ctx context.Context, tag string, baseCost int) {
tagMetas, found := ct.tagCost[tag]
if !found {
q := Parse(api.KeyTags + api.SearchOperatorHas + tag + " ORDER REVERSE " + api.KeyID)
ml, err := zc.port.SelectMeta(ctx, nil, q)
ml, err := ct.port.SelectMeta(ctx, nil, q)
if err != nil {
return
}
tagMetas = ml
zc.tagCost[tag] = ml
ct.tagCost[tag] = ml
}
cost := tagCost(baseCost, len(tagMetas))
if zc.costMaxed(cost) {
if ct.costMaxed(cost) {
return
}
for _, m := range tagMetas {
zc.addMeta(m, cost)
ct.addMeta(m, cost)
}
}
func tagCost(baseCost, numTags int) int {
if numTags < 8 {
return baseCost + numTags/2
}
return (baseCost + 2) * (numTags / 4)
}
func (zc *contextQueue) next() (*meta.Meta, int) {
if zc.hasLimit() {
func (ct *contextTask) next() (*meta.Meta, int) {
if ct.hasLimit() {
return nil, -1
}
for zc.first != nil {
task := zc.first
for len(ct.queue) > 0 {
item := heap.Pop(&ct.queue).(ztlCtxItem)
zc.first = task.next
if zc.first == nil {
zc.last = nil
} else {
zc.first.prev = nil
}
m := task.meta
m := item.meta
zid := m.Zid
_, found := zc.seen[zid]
if _, found := ct.seen[zid]; found {
if found {
continue
}
zc.seen.Zid(zid)
return m, task.cost
ct.seen.Add(zid)
return m, item.cost
}
return nil, -1
}
func (zc *contextQueue) hasLimit() bool {
limit := zc.limit
return limit > 0 && len(zc.seen) >= limit
func (ct *contextTask) hasLimit() bool {
limit := ct.limit
return limit > 0 && len(ct.seen) >= limit
}
|
Changes to query/parser.go.
︙ | | |
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
-
-
+
+
|
for {
pos := inp.Pos
zid, found := ps.scanZid()
if !found {
inp.SetPos(pos)
break
}
if !zidSet.Contains(zid) {
zidSet.Zid(zid)
if !zidSet.ContainsOrNil(zid) {
zidSet.Add(zid)
q = createIfNeeded(q)
q.zids = append(q.zids, zid)
}
ps.skipSpace()
if ps.mustStop() {
q.zids = nil
break
|
︙ | | |
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
-
+
|
}
pos := inp.Pos
if ps.acceptSingleKw(api.ContextDirective) {
if hasContext {
inp.SetPos(pos)
break
}
q = ps.parseContext(q, pos)
q = ps.parseContext(q)
hasContext = true
continue
}
inp.SetPos(pos)
if q == nil || len(q.zids) == 0 {
break
}
|
︙ | | |
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
|
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
|
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
|
break
}
q = ps.parseText(q)
}
return q
}
func (ps *parserState) parseContext(q *Query, pos int) *Query {
func (ps *parserState) parseContext(q *Query) *Query {
inp := ps.inp
if q == nil || len(q.zids) == 0 {
ps.skipSpace()
if ps.mustStop() {
inp.SetPos(pos)
return q
}
zid, ok := ps.scanZid()
if !ok {
inp.SetPos(pos)
return q
}
q = createIfNeeded(q)
q.zids = append(q.zids, zid)
}
spec := &ContextSpec{}
for {
ps.skipSpace()
if ps.mustStop() {
break
}
pos = inp.Pos
pos := inp.Pos
if ps.acceptSingleKw(api.BackwardDirective) {
spec.Direction = ContextDirBackward
continue
}
inp.SetPos(pos)
if ps.acceptSingleKw(api.ForwardDirective) {
spec.Direction = ContextDirForward
|
︙ | | |
242
243
244
245
246
247
248
249
250
251
252
253
254
255
|
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
|
+
|
continue
}
}
inp.SetPos(pos)
break
}
q = createIfNeeded(q)
q.directives = append(q.directives, spec)
return q
}
func (ps *parserState) parseCost(spec *ContextSpec) bool {
num, ok := ps.scanPosInt()
if !ok {
return false
|
︙ | | |
Changes to query/parser_test.go.
︙ | | |
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
-
+
-
-
-
-
-
-
-
-
|
{"1 CONTEXT MAX 5", "00000000000001 CONTEXT MAX 5"}, {"1 CONTEXT MAX y", "00000000000001 CONTEXT MAX y"},
{"1 CONTEXT MAX 5 COST 7", "00000000000001 CONTEXT COST 7 MAX 5"},
{"1 CONTEXT | N", "00000000000001 CONTEXT | N"},
{"1 1 CONTEXT", "00000000000001 CONTEXT"},
{"1 2 CONTEXT", "00000000000001 00000000000002 CONTEXT"},
{"2 1 CONTEXT", "00000000000002 00000000000001 CONTEXT"},
{"CONTEXT 0", "CONTEXT 0"}, {"CONTEXT 1", "00000000000001 CONTEXT"},
{"CONTEXT 0", "CONTEXT 0"},
{"CONTEXT 00000000000001", "00000000000001 CONTEXT"},
{"CONTEXT 100000000000001", "CONTEXT 100000000000001"},
{"CONTEXT 1 BACKWARD", "00000000000001 CONTEXT BACKWARD"},
{"CONTEXT 1 FORWARD", "00000000000001 CONTEXT FORWARD"},
{"CONTEXT 1 COST 3", "00000000000001 CONTEXT COST 3"}, {"CONTEXT 1 COST x", "00000000000001 CONTEXT COST x"},
{"CONTEXT 1 MAX 5", "00000000000001 CONTEXT MAX 5"}, {"CONTEXT 1 MAX y", "00000000000001 CONTEXT MAX y"},
{"CONTEXT 1 MAX 5 COST 7", "00000000000001 CONTEXT COST 7 MAX 5"},
{"CONTEXT 1 | N", "00000000000001 CONTEXT | N"},
{"1 UNLINKED", "00000000000001 UNLINKED"},
{"UNLINKED", "UNLINKED"},
{"1 UNLINKED PHRASE", "00000000000001 UNLINKED PHRASE"},
{"1 UNLINKED PHRASE Zettel", "00000000000001 UNLINKED PHRASE Zettel"},
{"?", "?"}, {"!?", "!?"}, {"?a", "?a"}, {"!?a", "!?a"},
|
︙ | | |
Changes to query/query.go.
︙ | | |
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
+
|
// Package query provides a query for zettel.
package query
import (
"context"
"math/rand"
"slices"
"zettelstore.de/z/zettel/id"
"zettelstore.de/z/zettel/meta"
)
// Searcher is used to select zettel identifier based on search criteria.
type Searcher interface {
|
︙ | | |
241
242
243
244
245
246
247
248
249
250
251
252
253
254
|
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
|
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
|
func (q *Query) addSearch(val expValue) { q.terms[len(q.terms)-1].addSearch(val) }
func (q *Query) addKey(key string, op compareOp) *Query {
q = createIfNeeded(q)
q.terms[len(q.terms)-1].addKey(key, op)
return q
}
func (q *Query) GetMetaValues(key string) (vals []string) {
if q == nil {
return nil
}
for _, term := range q.terms {
if mvs, hasMv := term.mvals[key]; hasMv {
for _, ev := range mvs {
vals = append(vals, ev.value)
}
}
}
slices.Sort(vals)
return slices.Compact(vals)
}
// SetPreMatch sets the pre-selection predicate.
func (q *Query) SetPreMatch(preMatch MetaMatchFunc) *Query {
q = createIfNeeded(q)
if q.preMatch != nil {
panic("search PreMatch already set")
}
|
︙ | | |
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
|
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
|
-
+
|
// for its results and returns a matching predicate.
func (q *Query) RetrieveAndCompile(_ context.Context, searcher Searcher, metaSeq []*meta.Meta) Compiled {
if q == nil {
return Compiled{
PreMatch: matchAlways,
Terms: []CompiledTerm{{
Match: matchAlways,
Retrieve: alwaysIncluded,
Retrieve: AlwaysIncluded,
}}}
}
q = q.Clone()
preMatch := q.preMatch
if preMatch == nil {
preMatch = matchAlways
|
︙ | | |
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
412
413
414
415
416
|
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
|
-
+
-
+
-
+
-
+
-
+
-
+
|
for _, term := range q.terms {
cTerm := term.retrieveAndCompileTerm(searcher, startSet)
if cTerm.Retrieve == nil {
if cTerm.Match == nil {
// no restriction on match/retrieve -> all will match
result.Terms = []CompiledTerm{{
Match: matchAlways,
Retrieve: alwaysIncluded,
Retrieve: AlwaysIncluded,
}}
break
}
cTerm.Retrieve = alwaysIncluded
cTerm.Retrieve = AlwaysIncluded
}
if cTerm.Match == nil {
cTerm.Match = matchAlways
}
result.Terms = append(result.Terms, cTerm)
}
return result
}
func metaList2idSet(ml []*meta.Meta) id.Set {
if ml == nil {
return nil
}
result := id.NewSetCap(len(ml))
for _, m := range ml {
result = result.Zid(m.Zid)
result = result.Add(m.Zid)
}
return result
}
func (ct *conjTerms) retrieveAndCompileTerm(searcher Searcher, startSet id.Set) CompiledTerm {
match := ct.compileMeta() // Match might add some searches
var pred RetrievePredicate
if searcher != nil {
pred = ct.retrieveIndex(searcher)
if startSet != nil {
if pred == nil {
pred = startSet.Contains
pred = startSet.ContainsOrNil
} else {
predSet := id.NewSetCap(len(startSet))
for zid := range startSet {
if pred(zid) {
predSet = predSet.Zid(zid)
predSet = predSet.Add(zid)
}
}
pred = predSet.Contains
pred = predSet.ContainsOrNil
}
}
}
return CompiledTerm{Match: match, Retrieve: pred}
}
// retrieveIndex and return a predicate to ask for results.
|
︙ | | |
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
|
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
|
-
+
-
+
-
+
-
+
|
}
positives := retrievePositives(normCalls, plainCalls)
if positives == nil {
// No positive search for words, must contain only words for a negative search.
// Otherwise len(search) == 0 (see above)
negatives := retrieveNegatives(negCalls)
return func(zid id.Zid) bool { return !negatives.Contains(zid) }
return func(zid id.Zid) bool { return !negatives.ContainsOrNil(zid) }
}
if len(positives) == 0 {
// Positive search didn't found anything. We can omit the negative search.
return neverIncluded
}
if len(negCalls) == 0 {
// Positive search found something, but there is no negative search.
return positives.Contains
return positives.ContainsOrNil
}
negatives := retrieveNegatives(negCalls)
if negatives == nil {
return positives.Contains
return positives.ContainsOrNil
}
return func(zid id.Zid) bool {
return positives.Contains(zid) && !negatives.Contains(zid)
return positives.ContainsOrNil(zid) && !negatives.ContainsOrNil(zid)
}
}
// Limit returns only s.GetLimit() elements of the given list.
func (q *Query) Limit(metaList []*meta.Meta) []*meta.Meta {
if q == nil {
return metaList
}
return limitElements(metaList, q.limit)
}
|
Changes to query/retrieve.go.
︙ | | |
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
-
-
-
|
if pred(s, k.s) {
delete(scm, k)
}
}
scm[searchOp{s: s, op: op}] = sf
}
func alwaysIncluded(id.Zid) bool { return true }
func neverIncluded(id.Zid) bool { return false }
func prepareRetrieveCalls(searcher Searcher, search []expValue) (normCalls, plainCalls, negCalls searchCallMap) {
normCalls = make(searchCallMap, len(search))
negCalls = make(searchCallMap, len(search))
for _, val := range search {
for _, word := range strfun.NormalizeWords(val.value) {
if cmpOp := val.op; cmpOp.isNegated() {
cmpOp = cmpOp.negate()
|
︙ | | |
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
|
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
|
-
+
-
+
|
if result, found := cache[c]; found {
normResult = normResult.IntersectOrSet(result)
continue
}
}
normResult = normResult.IntersectOrSet(sf(c.s))
}
return normResult.Add(plainResult)
return normResult.Copy(plainResult)
}
func isSuperset(normCalls, plainCalls searchCallMap) bool {
for c := range plainCalls {
if _, found := normCalls[c]; !found {
return false
}
}
return true
}
func retrieveNegatives(negCalls searchCallMap) id.Set {
var negatives id.Set
for val, sf := range negCalls {
negatives = negatives.Add(sf(val.s))
negatives = negatives.Copy(sf(val.s))
}
return negatives
}
func getSearchFunc(searcher Searcher, op compareOp) searchFunc {
switch op {
case cmpEqual:
|
︙ | | |
Changes to tests/regression_test.go.
︙ | | |
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
+
|
"zettelstore.de/z/ast"
"zettelstore.de/z/box"
"zettelstore.de/z/box/manager"
"zettelstore.de/z/config"
"zettelstore.de/z/encoder"
"zettelstore.de/z/kernel"
"zettelstore.de/z/parser"
"zettelstore.de/z/query"
"zettelstore.de/z/zettel/meta"
_ "zettelstore.de/z/box/dirbox"
)
var encodings = []api.EncodingEnum{
api.EncoderHTML,
|
︙ | | |
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
|
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
|
+
-
-
+
+
-
-
-
+
+
+
|
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{}
if err := p.ApplyMeta(context.Background(),
err := p.ApplyMeta(context.Background(), func(m *meta.Meta) { metaList = append(metaList, m) }, nil)
if err != nil {
func(m *meta.Meta) { metaList = append(metaList, m) },
query.AlwaysIncluded); err != nil {
panic(err)
}
for _, meta := range metaList {
zettel, err2 := p.GetZettel(context.Background(), meta.Zid)
if err2 != nil {
panic(err2)
zettel, err := p.GetZettel(context.Background(), meta.Zid)
if err != nil {
panic(err)
}
z := parser.ParseZettel(context.Background(), zettel, "", testConfig)
for _, enc := range encodings {
t.Run(fmt.Sprintf("%s::%d(%s)", p.Location(), meta.Zid, enc), func(st *testing.T) {
resultName := filepath.Join(wd, "result", "meta", boxName, z.Zid.String()+"."+enc.String())
checkMetaFile(st, resultName, z, enc)
})
|
︙ | | |
Added usecase/get_special_zettel.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
|
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
|
//-----------------------------------------------------------------------------
// Copyright (c) 2023-present Detlef Stern
//
// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
//-----------------------------------------------------------------------------
package usecase
import (
"context"
"zettelstore.de/client.fossil/api"
"zettelstore.de/z/query"
"zettelstore.de/z/zettel"
"zettelstore.de/z/zettel/id"
"zettelstore.de/z/zettel/meta"
)
// TagZettel is the usecase of retrieving a "tag zettel", i.e. a zettel that
// describes a given tag. A tag zettel must habe the tag's name in its title
// and must have a role=tag.
// TagZettelPort is the interface used by this use case.
type TagZettelPort interface {
// GetZettel retrieves a specific zettel.
GetZettel(ctx context.Context, zid id.Zid) (zettel.Zettel, error)
}
// TagZettel is the data for this use case.
type TagZettel struct {
port GetZettelPort
query *Query
}
// NewTagZettel creates a new use case.
func NewTagZettel(port GetZettelPort, query *Query) TagZettel {
return TagZettel{port: port, query: query}
}
// Run executes the use case.
func (uc TagZettel) Run(ctx context.Context, tag string) (zettel.Zettel, error) {
tag = meta.NormalizeTag(tag)
q := query.Parse(
api.KeyTitle + api.SearchOperatorEqual + tag + " " +
api.KeyRole + api.SearchOperatorHas + api.ValueRoleTag)
ml, err := uc.query.Run(ctx, q)
if err != nil {
return zettel.Zettel{}, err
}
for _, m := range ml {
z, errZ := uc.port.GetZettel(ctx, m.Zid)
if errZ == nil {
return z, nil
}
}
return zettel.Zettel{}, ErrTagZettelNotFound{Tag: tag}
}
// ErrTagZettelNotFound is returned if a tag zettel was not found.
type ErrTagZettelNotFound struct{ Tag string }
func (etznf ErrTagZettelNotFound) Error() string { return "tag zettel not found: " + etznf.Tag }
|
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | |
Changes to usecase/query.go.
︙ | | |
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
|
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
|
-
-
+
+
-
+
-
+
-
+
|
candidates, err := uc.port.SelectMeta(ctx, nil, q)
if err != nil {
return nil
}
metaZids := id.NewSetCap(len(metaSeq))
refZids := id.NewSetCap(len(metaSeq) * 4) // Assumption: there are four zids per zettel
for _, m := range metaSeq {
metaZids.Zid(m.Zid)
refZids.Zid(m.Zid)
metaZids.Add(m.Zid)
refZids.Add(m.Zid)
for _, pair := range m.ComputedPairsRest() {
switch meta.Type(pair.Key) {
case meta.TypeID:
if zid, errParse := id.Parse(pair.Value); errParse == nil {
refZids.Zid(zid)
refZids.Add(zid)
}
case meta.TypeIDSet:
for _, value := range meta.ListFromValue(pair.Value) {
if zid, errParse := id.Parse(value); errParse == nil {
refZids.Zid(zid)
refZids.Add(zid)
}
}
}
}
}
candidates = filterByZid(candidates, refZids)
return uc.filterCandidates(ctx, candidates, words)
}
func filterByZid(candidates []*meta.Meta, ignoreSeq id.Set) []*meta.Meta {
result := make([]*meta.Meta, 0, len(candidates))
for _, m := range candidates {
if !ignoreSeq.Contains(m.Zid) {
if !ignoreSeq.ContainsOrNil(m.Zid) {
result = append(result, m)
}
}
return result
}
func (uc *Query) filterCandidates(ctx context.Context, candidates []*meta.Meta, words []string) []*meta.Meta {
|
︙ | | |
Changes to usecase/rename_zettel.go.
︙ | | |
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
|
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
|
-
+
-
+
|
log *logger.Logger
port RenameZettelPort
}
// ErrZidInUse is returned if the zettel id is not appropriate for the box operation.
type ErrZidInUse struct{ Zid id.Zid }
func (err *ErrZidInUse) Error() string {
func (err ErrZidInUse) Error() string {
return "Zettel id already in use: " + err.Zid.String()
}
// NewRenameZettel creates a new use case.
func NewRenameZettel(log *logger.Logger, port RenameZettelPort) RenameZettel {
return RenameZettel{log: log, port: port}
}
// Run executes the use case.
func (uc *RenameZettel) Run(ctx context.Context, curZid, newZid id.Zid) error {
noEnrichCtx := box.NoEnrichContext(ctx)
if _, err := uc.port.GetZettel(noEnrichCtx, curZid); err != nil {
return err
}
if newZid == curZid {
// Nothing to do
return nil
}
if _, err := uc.port.GetZettel(noEnrichCtx, newZid); err == nil {
return &ErrZidInUse{Zid: newZid}
return ErrZidInUse{Zid: newZid}
}
err := uc.port.RenameZettel(ctx, curZid, newZid)
uc.log.Info().User(ctx).Zid(curZid).Err(err).Zid(newZid).Msg("Rename zettel")
return err
}
|
Changes to web/adapter/api/create_zettel.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
|
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) 2021-present Detlef Stern
//
// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
//-----------------------------------------------------------------------------
package api
import (
"bytes"
"net/http"
"zettelstore.de/client.fossil/api"
"zettelstore.de/sx.fossil"
"zettelstore.de/z/usecase"
"zettelstore.de/z/web/adapter"
"zettelstore.de/z/web/content"
"zettelstore.de/z/zettel"
"zettelstore.de/z/zettel/id"
)
type zidJSON struct {
ID api.ZettelID `json:"id"`
}
// 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) {
q := r.URL.Query()
enc, encStr := getEncoding(r, q)
var zettel zettel.Zettel
var err error
switch enc {
case api.EncoderPlain:
zettel, err = buildZettelFromPlainData(r, id.Invalid)
case api.EncoderData:
zettel, err = buildZettelFromData(r, id.Invalid)
case api.EncoderJson:
zettel, err = buildZettelFromJSONData(r, id.Invalid)
default:
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
if err != nil {
a.reportUsecaseError(w, adapter.NewErrBadRequest(err.Error()))
return
|
︙ | | |
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
|
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
-
-
-
-
-
-
-
-
-
-
-
|
switch enc {
case api.EncoderPlain:
result = newZid.Bytes()
contentType = content.PlainText
case api.EncoderData:
result = []byte(sx.Int64(newZid).Repr())
contentType = content.SXPF
case api.EncoderJson:
var buf bytes.Buffer
err = encodeJSONData(&buf, zidJSON{ID: api.ZettelID(newZid.String())})
if err != nil {
a.log.Fatal().Err(err).Zid(newZid).Msg("Unable to store new Zid in buffer")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
result = buf.Bytes()
contentType = content.JSON
location.AppendKVQuery(api.QueryKeyEncoding, api.EncodingJson)
default:
panic(encStr)
}
h := adapter.PrepareHeader(w, contentType)
h.Set(api.HeaderLocation, location.String())
w.WriteHeader(http.StatusCreated)
_, err = w.Write(result)
a.log.IfErr(err).Zid(newZid).Msg("Create Zettel")
}
}
|
Changes to web/adapter/api/get_data.go.
︙ | | |
22
23
24
25
26
27
28
29
30
31
32
33
34
|
22
23
24
25
26
27
28
29
30
31
32
33
34
|
-
-
+
+
|
func (a *API) MakeGetDataHandler(ucVersion usecase.Version) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
version := ucVersion.Run()
err := a.writeObject(w, id.Invalid, sx.MakeList(
sx.Int64(version.Major),
sx.Int64(version.Minor),
sx.Int64(version.Patch),
sx.MakeString(version.Info),
sx.MakeString(version.Hash),
sx.String(version.Info),
sx.String(version.Hash),
))
a.log.IfErr(err).Msg("Write Version Info")
}
}
|
Changes to web/adapter/api/get_zettel.go.
︙ | | |
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
-
-
-
|
switch enc, encStr := getEncoding(r, q); enc {
case api.EncoderPlain:
a.writePlainData(w, ctx, zid, part, getZettel)
case api.EncoderData:
a.writeSzData(w, ctx, zid, part, getZettel)
case api.EncoderJson:
a.writeJSONData(w, ctx, zid, part, getZettel)
default:
var zn *ast.ZettelNode
var em func(value string) ast.InlineSlice
if q.Has(api.QueryKeyParseOnly) {
zn, err = parseZettel.Run(ctx, zid, q.Get(api.KeySyntax))
em = parser.ParseMetadata
} else {
|
︙ | | |
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
|
131
132
133
134
135
136
137
138
139
140
141
142
143
144
|
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
|
Rights: a.getRights(ctx, z.Meta),
})
}
err = a.writeObject(w, zid, obj)
a.log.IfErr(err).Zid(zid).Msg("write sx data")
}
type zettelJSON struct {
ID api.ZettelID `json:"id"`
Meta api.ZettelMeta `json:"meta"`
Encoding string `json:"encoding"`
Content string `json:"content"`
Rights api.ZettelRights `json:"rights"`
}
type zettelMetaJSON struct {
Meta api.ZettelMeta `json:"meta"`
Rights api.ZettelRights `json:"rights"`
}
type zettelContentJSON struct {
Encoding string `json:"encoding"`
Content string `json:"content"`
}
func (a *API) writeJSONData(w http.ResponseWriter, ctx context.Context, zid id.Zid, part partType, getZettel usecase.GetZettel) {
z, err := getZettel.Run(ctx, zid)
if err != nil {
a.reportUsecaseError(w, err)
return
}
var buf bytes.Buffer
switch part {
case partZettel:
zContent, encoding := z.Content.Encode()
err = encodeJSONData(&buf, zettelJSON{
ID: api.ZettelID(zid.String()),
Meta: z.Meta.Map(),
Encoding: encoding,
Content: zContent,
Rights: a.getRights(ctx, z.Meta),
})
case partMeta:
m := z.Meta
err = encodeJSONData(&buf, zettelMetaJSON{
Meta: m.Map(),
Rights: a.getRights(ctx, m),
})
case partContent:
zContent, encoding := z.Content.Encode()
err = encodeJSONData(&buf, zettelContentJSON{
Encoding: encoding,
Content: zContent,
})
}
if err != nil {
a.log.Fatal().Err(err).Zid(zid).Msg("Unable to store zettel in buffer")
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
err = writeBuffer(w, &buf, content.JSON)
a.log.IfErr(err).Zid(zid).Msg("Write JSON data")
}
func (a *API) writeEncodedZettelPart(
w http.ResponseWriter, zn *ast.ZettelNode,
evalMeta encoder.EvalMetaFunc,
enc api.EncodingEnum, encStr string, part partType,
) {
encdr := encoder.Create(enc)
if encdr == nil {
|
︙ | | |
Deleted web/adapter/api/json.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-present Detlef Stern
//
// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
//-----------------------------------------------------------------------------
package api
import (
"encoding/json"
"io"
"net/http"
"zettelstore.de/client.fossil/api"
"zettelstore.de/z/zettel"
"zettelstore.de/z/zettel/id"
"zettelstore.de/z/zettel/meta"
)
func encodeJSONData(w io.Writer, data interface{}) error {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
return enc.Encode(data)
}
type zettelDataJSON struct {
Meta api.ZettelMeta `json:"meta"`
Encoding string `json:"encoding"`
Content string `json:"content"`
}
func buildZettelFromJSONData(r *http.Request, zid id.Zid) (zettel.Zettel, error) {
var zettel zettel.Zettel
defer r.Body.Close()
dec := json.NewDecoder(r.Body)
var zettelData zettelDataJSON
if err := dec.Decode(&zettelData); err != nil {
return zettel, err
}
m := meta.New(zid)
for k, v := range zettelData.Meta {
m.Set(meta.RemoveNonGraphic(k), meta.RemoveNonGraphic(v))
}
zettel.Meta = m
if err := zettel.Content.SetDecoded(zettelData.Content, zettelData.Encoding); err != nil {
return zettel, err
}
return zettel, nil
}
|
Changes to web/adapter/api/login.go.
︙ | | |
91
92
93
94
95
96
97
98
99
100
101
102
|
91
92
93
94
95
96
97
98
99
100
101
102
|
-
-
+
+
|
err = a.writeToken(w, string(token), a.tokenLifetime)
a.log.IfErr(err).Msg("Write renewed token")
}
}
func (a *API) writeToken(w http.ResponseWriter, token string, lifetime time.Duration) error {
return a.writeObject(w, id.Invalid, sx.MakeList(
sx.MakeString("Bearer"),
sx.MakeString(token),
sx.String("Bearer"),
sx.String(token),
sx.Int64(int64(lifetime/time.Second)),
))
}
|
Changes to web/adapter/api/query.go.
︙ | | |
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
|
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
|
+
-
+
-
-
+
+
+
+
+
+
-
+
-
+
-
-
-
-
-
-
-
|
package api
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"zettelstore.de/client.fossil/api"
"zettelstore.de/client.fossil/sexp"
"zettelstore.de/sx.fossil"
"zettelstore.de/z/query"
"zettelstore.de/z/usecase"
"zettelstore.de/z/web/adapter"
"zettelstore.de/z/web/content"
"zettelstore.de/z/zettel/meta"
)
// MakeQueryHandler creates a new HTTP handler to perform a query.
func (a *API) MakeQueryHandler(queryMeta *usecase.Query) http.HandlerFunc {
func (a *API) MakeQueryHandler(queryMeta *usecase.Query, tagZettel *usecase.TagZettel) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
q := r.URL.Query()
sq := adapter.GetQuery(q)
urlQuery := r.URL.Query()
if a.handleTagZettel(w, r, tagZettel, urlQuery) {
return
}
sq := adapter.GetQuery(urlQuery)
metaSeq, err := queryMeta.Run(ctx, sq)
if err != nil {
a.reportUsecaseError(w, err)
return
}
var encoder zettelEncoder
var contentType string
switch enc, _ := getEncoding(r, q); enc {
switch enc, _ := getEncoding(r, urlQuery); enc {
case api.EncoderPlain:
encoder = &plainZettelEncoder{}
contentType = content.PlainText
case api.EncoderData:
encoder = &dataZettelEncoder{
sf: sx.MakeMappedFactory(),
sf: sx.MakeMappedFactory(256),
sq: sq,
getRights: func(m *meta.Meta) api.ZettelRights { return a.getRights(ctx, m) },
}
contentType = content.SXPF
case api.EncoderJson: // DEPRECATED
encoder = &jsonZettelEncoder{
sq: sq,
getRights: func(m *meta.Meta) api.ZettelRights { return a.getRights(ctx, m) },
}
contentType = content.JSON
default:
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
var buf bytes.Buffer
err = queryAction(&buf, encoder, metaSeq, sq)
|
︙ | | |
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
|
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
|
-
-
+
+
-
+
-
-
-
+
+
+
-
+
-
-
+
-
-
-
+
-
-
-
-
-
-
+
-
-
-
-
-
-
+
+
-
-
-
-
-
+
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
|
})
msz = sx.Cons(sx.MakeList(symID, sx.Int64(m.Zid)), msz.Cdr()).Cons(symZettel)
result[i+1] = msz
}
_, err := sx.Print(w, sx.MakeList(
sf.MustMake("meta-list"),
sx.MakeList(sf.MustMake("query"), sx.MakeString(dze.sq.String())),
sx.MakeList(sf.MustMake("human"), sx.MakeString(dze.sq.Human())),
sx.MakeList(sf.MustMake("query"), sx.String(dze.sq.String())),
sx.MakeList(sf.MustMake("human"), sx.String(dze.sq.Human())),
sx.MakeList(result...),
))
return err
}
func (dze *dataZettelEncoder) writeArrangement(w io.Writer, act string, arr meta.Arrangement) error {
sf := dze.sf
result := sx.Nil()
for aggKey, metaList := range arr {
sxMeta := sx.Nil()
for i := len(metaList) - 1; i >= 0; i-- {
sxMeta = sxMeta.Cons(sx.Int64(metaList[i].Zid))
}
sxMeta = sxMeta.Cons(sx.MakeString(aggKey))
sxMeta = sxMeta.Cons(sx.String(aggKey))
result = result.Cons(sxMeta)
}
_, err := sx.Print(w, sx.MakeList(
sf.MustMake("aggregate"),
sx.MakeString(act),
sx.MakeList(sf.MustMake("query"), sx.MakeString(dze.sq.String())),
sx.MakeList(sf.MustMake("human"), sx.MakeString(dze.sq.Human())),
sx.String(act),
sx.MakeList(sf.MustMake("query"), sx.String(dze.sq.String())),
sx.MakeList(sf.MustMake("human"), sx.String(dze.sq.Human())),
result.Cons(sf.MustMake("list")),
))
return err
}
// jsonZettelEncoder is DEPRECATED
func (a *API) handleTagZettel(w http.ResponseWriter, r *http.Request, tagZettel *usecase.TagZettel, vals url.Values) bool {
type jsonZettelEncoder struct {
sq *query.Query
tag := vals.Get(api.QueryKeyTag)
getRights func(*meta.Meta) api.ZettelRights
}
if tag == "" {
type zidMetaJSON struct {
ID api.ZettelID `json:"id"`
Meta api.ZettelMeta `json:"meta"`
Rights api.ZettelRights `json:"rights"`
}
return false
type zettelListJSON struct {
Query string `json:"query"`
Human string `json:"human"`
List []zidMetaJSON `json:"list"`
}
}
ctx := r.Context()
func (jze *jsonZettelEncoder) writeMetaList(w io.Writer, ml []*meta.Meta) error {
result := make([]zidMetaJSON, 0, len(ml))
for _, m := range ml {
result = append(result, zidMetaJSON{
ID: api.ZettelID(m.Zid.String()),
z, err := tagZettel.Run(ctx, tag)
Meta: m.Map(),
Rights: jze.getRights(m),
})
}
err := encodeJSONData(w, zettelListJSON{
if err != nil {
a.reportUsecaseError(w, err)
Query: jze.sq.String(),
Human: jze.sq.Human(),
List: result,
})
return err
}
return true
}
http.Redirect(w, r, a.NewURLBuilder('z').SetZid(api.ZettelID(z.Meta.Zid.String())).String(), http.StatusFound)
type mapListJSON struct {
Map api.Aggregate `json:"map"`
}
func (*jsonZettelEncoder) writeArrangement(w io.Writer, _ string, arr meta.Arrangement) error {
mm := make(api.Aggregate, len(arr))
for key, metaList := range arr {
zidList := make([]api.ZettelID, 0, len(metaList))
for _, m := range metaList {
zidList = append(zidList, api.ZettelID(m.Zid.String()))
}
mm[key] = zidList
}
return encodeJSONData(w, mapListJSON{Map: mm})
return true
}
|
Changes to web/adapter/api/request.go.
︙ | | |
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
-
-
+
|
}
}
}
return "", false
}
var mapCT2encoding = map[string]string{
"application/json": "json",
"text/html": api.EncodingHTML,
"text/html": api.EncodingHTML,
}
func contentType2encoding(contentType string) (string, bool) {
// TODO: only check before first ';'
enc, ok := mapCT2encoding[contentType]
return enc, ok
}
|
︙ | | |
Changes to web/adapter/api/update_zettel.go.
︙ | | |
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
-
-
|
q := r.URL.Query()
var zettel zettel.Zettel
switch enc, _ := getEncoding(r, q); enc {
case api.EncoderPlain:
zettel, err = buildZettelFromPlainData(r, zid)
case api.EncoderData:
zettel, err = buildZettelFromData(r, zid)
case api.EncoderJson:
zettel, err = buildZettelFromJSONData(r, zid)
default:
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
if err != nil {
a.reportUsecaseError(w, adapter.NewErrBadRequest(err.Error()))
|
︙ | | |
Changes to web/adapter/errors.go.
︙ | | |
23
24
25
26
27
28
29
|
23
24
25
26
27
28
29
30
31
32
33
34
|
+
+
+
+
+
|
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)
}
// ErrResourceNotFound is signalled when a web resource was not found.
type ErrResourceNotFound struct{ Path string }
func (ernf ErrResourceNotFound) Error() string { return "resource not found: " + ernf.Path }
|
Changes to web/adapter/response.go.
︙ | | |
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
+
|
package adapter
import (
"errors"
"fmt"
"net/http"
"strings"
"zettelstore.de/client.fossil/api"
"zettelstore.de/z/box"
"zettelstore.de/z/usecase"
)
// WriteData emits the given data to the response writer.
|
︙ | | |
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
|
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
|
-
+
-
+
-
-
+
+
+
-
-
+
+
+
+
-
-
+
+
+
-
-
+
+
+
+
+
+
+
-
-
+
+
+
+
+
+
+
|
// ErrBadRequest is returned if the caller made an invalid HTTP request.
type ErrBadRequest struct {
Text string
}
// NewErrBadRequest creates an new bad request error.
func NewErrBadRequest(text string) error { return &ErrBadRequest{Text: text} }
func NewErrBadRequest(text string) error { return ErrBadRequest{Text: text} }
func (err *ErrBadRequest) Error() string { return err.Text }
func (err ErrBadRequest) Error() string { return err.Text }
// CodeMessageFromError returns an appropriate HTTP status code and text from a given error.
func CodeMessageFromError(err error) (int, string) {
if err == box.ErrNotFound {
return http.StatusNotFound, http.StatusText(http.StatusNotFound)
var eznf box.ErrZettelNotFound
if errors.As(err, &eznf) {
return http.StatusNotFound, "Zettel not found: " + eznf.Zid.String()
}
if err1, ok := err.(*box.ErrNotAllowed); ok {
return http.StatusForbidden, err1.Error()
var ena *box.ErrNotAllowed
if errors.As(err, &ena) {
msg := ena.Error()
return http.StatusForbidden, strings.ToUpper(msg[:1]) + msg[1:]
}
if err1, ok := err.(*box.ErrInvalidID); ok {
return http.StatusBadRequest, fmt.Sprintf("Zettel-ID %q not appropriate in this context", err1.Zid)
var eiz box.ErrInvalidZid
if errors.As(err, &eiz) {
return http.StatusBadRequest, fmt.Sprintf("Zettel-ID %q not appropriate in this context", eiz.Zid)
}
if err1, ok := err.(*usecase.ErrZidInUse); ok {
return http.StatusBadRequest, fmt.Sprintf("Zettel-ID %q already in use", err1.Zid)
var ezin usecase.ErrZidInUse
if errors.As(err, &ezin) {
return http.StatusBadRequest, fmt.Sprintf("Zettel-ID %q already in use", ezin.Zid)
}
var etznf usecase.ErrTagZettelNotFound
if errors.As(err, &etznf) {
return http.StatusNotFound, "Tag zettel not found: " + etznf.Tag
}
if err1, ok := err.(*ErrBadRequest); ok {
return http.StatusBadRequest, err1.Text
var ebr ErrBadRequest
if errors.As(err, &ebr) {
return http.StatusBadRequest, ebr.Text
}
if errors.Is(err, box.ErrStopped) {
return http.StatusInternalServerError, fmt.Sprintf("Zettelstore not operational: %v", err)
}
if errors.Is(err, box.ErrConflict) {
return http.StatusConflict, "Zettelstore operations conflicted"
}
if errors.Is(err, box.ErrCapacity) {
return http.StatusInsufficientStorage, "Zettelstore reached one of its storage limits"
}
var ernf ErrResourceNotFound
if errors.As(err, &ernf) {
return http.StatusNotFound, "Resource not found: " + ernf.Path
}
return http.StatusInternalServerError, err.Error()
}
|
Changes to web/adapter/webui/create_zettel.go.
︙ | | |
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
+
-
+
-
+
-
+
|
func (wui *WebUI) MakeGetCreateZettelHandler(
getZettel usecase.GetZettel, createZettel *usecase.CreateZettel,
ucListRoles usecase.ListRoles, ucListSyntax usecase.ListSyntax) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
q := r.URL.Query()
op := getCreateAction(q.Get(queryKeyAction))
path := r.URL.Path[1:]
zid, err := id.Parse(r.URL.Path[1:])
zid, err := id.Parse(path)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrInvalidZid{Zid: path})
return
}
origZettel, err := getZettel.Run(box.NoEnrichContext(ctx), zid)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrZettelNotFound{Zid: zid})
return
}
roleData, syntaxData := retrieveDataLists(ctx, ucListRoles, ucListSyntax)
switch op {
case actionChild:
wui.renderZettelForm(ctx, w, createZettel.PrepareChild(origZettel), "Child Zettel", "", roleData, syntaxData)
|
︙ | | |
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
|
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
-
-
+
+
-
+
-
+
|
for _, p := range m.PairsRest() {
sb.WriteString(p.Key)
sb.WriteString(": ")
sb.WriteString(p.Value)
sb.WriteByte('\n')
}
env, rb := wui.createRenderEnv(ctx, "form", wui.rtConfig.Get(ctx, nil, api.KeyLang), title, user)
rb.bindString("heading", sx.MakeString(title))
rb.bindString("form-action-url", sx.MakeString(formActionURL))
rb.bindString("heading", sx.String(title))
rb.bindString("form-action-url", sx.String(formActionURL))
rb.bindString("role-data", makeStringList(roleData))
rb.bindString("syntax-data", makeStringList(syntaxData))
rb.bindString("meta", sx.MakeString(sb.String()))
rb.bindString("meta", sx.String(sb.String()))
if !ztl.Content.IsBinary() {
rb.bindString("content", sx.MakeString(ztl.Content.AsString()))
rb.bindString("content", sx.String(ztl.Content.AsString()))
}
wui.bindCommonZettelData(ctx, &rb, user, m, &ztl.Content)
if rb.err == nil {
rb.err = wui.renderSxnTemplate(ctx, w, id.FormTemplateZid, env)
}
if err := rb.err; err != nil {
wui.reportError(ctx, w, err)
|
︙ | | |
Changes to web/adapter/webui/delete_zettel.go.
︙ | | |
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
|
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
|
+
-
+
-
+
-
+
|
)
// MakeGetDeleteZettelHandler creates a new HTTP handler to display the
// HTML delete view of a zettel.
func (wui *WebUI) MakeGetDeleteZettelHandler(getZettel usecase.GetZettel, getAllZettel usecase.GetAllZettel) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
path := r.URL.Path[1:]
zid, err := id.Parse(r.URL.Path[1:])
zid, err := id.Parse(path)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrInvalidZid{Zid: path})
return
}
zs, err := getAllZettel.Run(ctx, zid)
if err != nil {
wui.reportError(ctx, w, err)
return
}
m := zs[0].Meta
user := server.GetUser(ctx)
env, rb := wui.createRenderEnv(
ctx, "delete",
wui.rtConfig.Get(ctx, nil, api.KeyLang), "Delete Zettel "+m.Zid.String(), user)
if len(zs) > 1 {
rb.bindString("shadowed-box", sx.MakeString(zs[1].Meta.GetDefault(api.KeyBoxNumber, "???")))
rb.bindString("shadowed-box", sx.String(zs[1].Meta.GetDefault(api.KeyBoxNumber, "???")))
rb.bindString("incoming", nil)
} else {
rb.bindString("shadowed-box", nil)
rb.bindString("incoming", wui.encodeIncoming(m, wui.makeGetTextTitle(ctx, getZettel)))
}
wui.bindCommonZettelData(ctx, &rb, user, m, nil)
|
︙ | | |
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
+
-
+
-
+
|
}
}
// 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()
path := r.URL.Path[1:]
zid, err := id.Parse(r.URL.Path[1:])
zid, err := id.Parse(path)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrInvalidZid{Zid: path})
return
}
if err = deleteZettel.Run(r.Context(), zid); err != nil {
wui.reportError(ctx, w, err)
return
}
wui.redirectFound(w, r, wui.NewURLBuilder('/'))
}
}
|
Changes to web/adapter/webui/edit_zettel.go.
︙ | | |
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
|
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
|
+
-
+
-
+
+
-
+
-
+
|
)
// MakeEditGetZettelHandler creates a new HTTP handler to display the
// HTML edit view of a zettel.
func (wui *WebUI) MakeEditGetZettelHandler(getZettel usecase.GetZettel, ucListRoles usecase.ListRoles, ucListSyntax usecase.ListSyntax) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
path := r.URL.Path[1:]
zid, err := id.Parse(r.URL.Path[1:])
zid, err := id.Parse(path)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrInvalidZid{Zid: path})
return
}
zettel, err := getZettel.Run(box.NoEnrichContext(ctx), zid)
if err != nil {
wui.reportError(ctx, w, err)
return
}
roleData, syntaxData := retrieveDataLists(ctx, ucListRoles, ucListSyntax)
wui.renderZettelForm(ctx, w, zettel, "Edit Zettel", "", roleData, syntaxData)
}
}
// MakeEditSetZettelHandler creates a new HTTP handler to store content of
// an existing zettel.
func (wui *WebUI) MakeEditSetZettelHandler(updateZettel *usecase.UpdateZettel) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
path := r.URL.Path[1:]
zid, err := id.Parse(r.URL.Path[1:])
zid, err := id.Parse(path)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrInvalidZid{Zid: path})
return
}
reEdit, zettel, err := parseZettelForm(r, zid)
hasContent := true
if err != nil {
if err != errMissingContent {
|
︙ | | |
Changes to web/adapter/webui/forms.go.
︙ | | |
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
-
-
+
-
|
}
if postTitle, ok := trimmedFormValue(r, "title"); ok {
m.Set(api.KeyTitle, meta.RemoveNonGraphic(postTitle))
}
if postTags, ok := trimmedFormValue(r, "tags"); ok {
if tags := meta.ListFromValue(meta.RemoveNonGraphic(postTags)); len(tags) > 0 {
for i, tag := range tags {
if tag[0] != '#' {
tags[i] = "#" + tag
tags[i] = meta.NormalizeTag(tag)
}
}
m.SetList(api.KeyTags, tags)
}
}
if postRole, ok := trimmedFormValue(r, "role"); ok {
m.SetWord(api.KeyRole, meta.RemoveNonGraphic(postRole))
}
|
︙ | | |
Changes to web/adapter/webui/get_info.go.
︙ | | |
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
|
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
|
+
-
+
-
+
-
+
|
ucGetAllMeta usecase.GetAllZettel,
ucQuery *usecase.Query,
) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
q := r.URL.Query()
path := r.URL.Path[1:]
zid, err := id.Parse(r.URL.Path[1:])
zid, err := id.Parse(path)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrInvalidZid{Zid: path})
return
}
zn, err := ucParseZettel.Run(ctx, zid, q.Get(api.KeySyntax))
if err != nil {
wui.reportError(ctx, w, err)
return
}
enc := wui.getSimpleHTMLEncoder()
getTextTitle := wui.makeGetTextTitle(ctx, ucGetZettel)
evalMeta := func(val string) ast.InlineSlice {
return ucEvaluate.RunMetadata(ctx, val)
}
pairs := zn.Meta.ComputedPairs()
metadata := sx.Nil()
for i := len(pairs) - 1; i >= 0; i-- {
key := pairs[i].Key
sxval := wui.writeHTMLMetaValue(key, pairs[i].Value, getTextTitle, evalMeta, enc)
metadata = metadata.Cons(sx.Cons(sx.MakeString(key), sxval))
metadata = metadata.Cons(sx.Cons(sx.String(key), sxval))
}
summary := collect.References(zn)
locLinks, queryLinks, extLinks := wui.splitLocSeaExtLinks(append(summary.Links, summary.Embeds...))
title := parser.NormalizedSpacedText(zn.InhMeta.GetTitle())
phrase := q.Get(api.QueryKeyPhrase)
|
︙ | | |
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
-
-
+
+
|
user := server.GetUser(ctx)
env, rb := wui.createRenderEnv(ctx, "info", wui.rtConfig.Get(ctx, nil, api.KeyLang), title, user)
rb.bindString("metadata", metadata)
rb.bindString("local-links", locLinks)
rb.bindString("query-links", queryLinks)
rb.bindString("ext-links", extLinks)
rb.bindString("unlinked-content", unlinkedContent)
rb.bindString("phrase", sx.MakeString(phrase))
rb.bindString("query-key-phrase", sx.MakeString(api.QueryKeyPhrase))
rb.bindString("phrase", sx.String(phrase))
rb.bindString("query-key-phrase", sx.String(api.QueryKeyPhrase))
rb.bindString("enc-eval", wui.infoAPIMatrix(zid, false, encTexts))
rb.bindString("enc-parsed", wui.infoAPIMatrixParsed(zid, encTexts))
rb.bindString("shadow-links", shadowLinks)
wui.bindCommonZettelData(ctx, &rb, user, zn.InhMeta, &zn.Content)
if rb.err == nil {
err = wui.renderSxnTemplate(ctx, w, id.InfoTemplateZid, env)
}
|
︙ | | |
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
|
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
|
-
-
+
+
-
+
-
+
|
ref := links[i]
if ref.State == ast.RefStateSelf || ref.IsZettel() {
continue
}
if ref.State == ast.RefStateQuery {
queries = queries.Cons(
sx.Cons(
sx.MakeString(ref.Value),
sx.MakeString(wui.NewURLBuilder('h').AppendQuery(ref.Value).String())))
sx.String(ref.Value),
sx.String(wui.NewURLBuilder('h').AppendQuery(ref.Value).String())))
continue
}
if ref.IsExternal() {
extLinks = extLinks.Cons(sx.MakeString(ref.String()))
extLinks = extLinks.Cons(sx.String(ref.String()))
continue
}
locLinks = locLinks.Cons(sx.Cons(sx.MakeBoolean(ref.IsValid()), sx.MakeString(ref.String())))
locLinks = locLinks.Cons(sx.Cons(sx.MakeBoolean(ref.IsValid()), sx.String(ref.String())))
}
return locLinks, queries, extLinks
}
func createUnlinkedQuery(zid id.Zid, phrase string) *query.Query {
var sb strings.Builder
sb.Write(zid.Bytes())
|
︙ | | |
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
|
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
|
-
+
-
+
-
+
-
-
-
-
-
+
-
+
|
for je := len(encTexts) - 1; je >= 0; je-- {
enc := encTexts[je]
if parseOnly {
u.AppendKVQuery(api.QueryKeyParseOnly, "")
}
u.AppendKVQuery(api.QueryKeyPart, part)
u.AppendKVQuery(api.QueryKeyEncoding, enc)
row = row.Cons(sx.Cons(sx.MakeString(enc), sx.MakeString(u.String())))
row = row.Cons(sx.Cons(sx.String(enc), sx.String(u.String())))
u.ClearQuery()
}
matrix = matrix.Cons(sx.Cons(sx.MakeString(part), row))
matrix = matrix.Cons(sx.Cons(sx.String(part), row))
}
return matrix
}
func (wui *WebUI) infoAPIMatrixParsed(zid id.Zid, encTexts []string) *sx.Pair {
matrix := wui.infoAPIMatrix(zid, true, encTexts)
u := wui.NewURLBuilder('z').SetZid(api.ZettelID(zid.String()))
for i, row := 0, matrix; i < len(apiParts) && row != nil; row = row.Tail() {
line, isLine := sx.GetPair(row.Car())
if !isLine || line == nil {
continue
}
last := line.LastPair()
part := apiParts[i]
u.AppendKVQuery(api.QueryKeyPart, part)
last = last.AppendBang(sx.Cons(sx.MakeString("plain"), sx.MakeString(u.String())))
last = last.AppendBang(sx.Cons(sx.String("plain"), sx.String(u.String())))
u.ClearQuery()
if i < 2 {
u.AppendKVQuery(api.QueryKeyEncoding, api.EncodingData)
u.AppendKVQuery(api.QueryKeyPart, part)
last = last.AppendBang(sx.Cons(sx.MakeString("data"), sx.MakeString(u.String())))
u.ClearQuery()
u.AppendKVQuery(api.QueryKeyEncoding, api.EncodingJson)
u.AppendKVQuery(api.QueryKeyPart, part)
last.AppendBang(sx.Cons(sx.MakeString("json"), sx.MakeString(u.String())))
last.AppendBang(sx.Cons(sx.String("data"), sx.String(u.String())))
u.ClearQuery()
}
i++
}
return matrix
}
func getShadowLinks(ctx context.Context, zid id.Zid, getAllZettel usecase.GetAllZettel) *sx.Pair {
result := sx.Nil()
if zl, err := getAllZettel.Run(ctx, zid); err == nil {
for i := len(zl) - 1; i >= 1; i-- {
if boxNo, ok := zl[i].Meta.Get(api.KeyBoxNumber); ok {
result = result.Cons(sx.MakeString(boxNo))
result = result.Cons(sx.String(boxNo))
}
}
}
return result
}
|
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
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
|
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
|
-
+
-
+
-
+
-
-
-
-
-
-
-
-
+
-
+
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
|
//-----------------------------------------------------------------------------
// Copyright (c) 2020-present Detlef Stern
//
// This file is part of Zettelstore.
//
// Zettelstore is licensed under the latest version of the EUPL (European Union
// Public License). Please see file LICENSE.txt for your rights and obligations
// under this license.
//-----------------------------------------------------------------------------
package webui
import (
"context"
"net/http"
"zettelstore.de/client.fossil/api"
"zettelstore.de/sx.fossil"
"zettelstore.de/z/box"
"zettelstore.de/z/parser"
"zettelstore.de/z/usecase"
"zettelstore.de/z/web/server"
"zettelstore.de/z/zettel/id"
"zettelstore.de/z/zettel/meta"
)
// MakeGetHTMLZettelHandler creates a new HTTP handler for the use case "get zettel".
func (wui *WebUI) MakeGetHTMLZettelHandler(evaluate *usecase.Evaluate, getZettel usecase.GetZettel) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
path := r.URL.Path[1:]
zid, err := id.Parse(r.URL.Path[1:])
zid, err := id.Parse(path)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrInvalidZid{Zid: path})
return
}
q := r.URL.Query()
zn, err := evaluate.Run(ctx, zid, q.Get(api.KeySyntax))
if err != nil {
wui.reportError(ctx, w, err)
return
}
enc := wui.getSimpleHTMLEncoder()
metaObj := enc.MetaSxn(zn.InhMeta, createEvalMetadataFunc(ctx, evaluate))
content, endnotes, err := enc.BlocksSxn(&zn.Ast)
if err != nil {
wui.reportError(ctx, w, err)
return
}
cssRoleURL, err := wui.getCSSRoleURL(ctx, zn.InhMeta)
if err != nil {
wui.reportError(ctx, w, err)
return
}
user := server.GetUser(ctx)
getTextTitle := wui.makeGetTextTitle(ctx, getZettel)
title := parser.NormalizedSpacedText(zn.InhMeta.GetTitle())
env, rb := wui.createRenderEnv(ctx, "zettel", wui.rtConfig.Get(ctx, zn.InhMeta, api.KeyLang), title, user)
rb.bindSymbol(wui.symMetaHeader, metaObj)
rb.bindString("css-role-url", sx.MakeString(cssRoleURL))
rb.bindString("heading", sx.MakeString(title))
rb.bindString("heading", sx.String(title))
if role, found := zn.InhMeta.Get(api.KeyRole); found && role != "" {
rb.bindString("role-url", sx.MakeString(wui.NewURLBuilder('h').AppendQuery(api.KeyRole+api.SearchOperatorHas+role).String()))
rb.bindString("role-url", sx.String(wui.NewURLBuilder('h').AppendQuery(api.KeyRole+api.SearchOperatorHas+role).String()))
}
if role, found := zn.InhMeta.Get(api.KeyFolgeRole); found && role != "" {
rb.bindString("folge-role-url", sx.MakeString(wui.NewURLBuilder('h').AppendQuery(api.KeyRole+api.SearchOperatorHas+role).String()))
if folgeRole, found := zn.InhMeta.Get(api.KeyFolgeRole); found && folgeRole != "" {
rb.bindString("folge-role-url", sx.String(wui.NewURLBuilder('h').AppendQuery(api.KeyRole+api.SearchOperatorHas+folgeRole).String()))
}
rb.bindString("tag-refs", wui.transformTagSet(api.KeyTags, meta.ListFromValue(zn.InhMeta.GetDefault(api.KeyTags, ""))))
rb.bindString("predecessor-refs", wui.identifierSetAsLinks(zn.InhMeta, api.KeyPredecessor, getTextTitle))
rb.bindString("precursor-refs", wui.identifierSetAsLinks(zn.InhMeta, api.KeyPrecursor, getTextTitle))
rb.bindString("superior-refs", wui.identifierSetAsLinks(zn.InhMeta, api.KeySuperior, getTextTitle))
rb.bindString("content", content)
rb.bindString("endnotes", endnotes)
rb.bindString("folge-links", wui.zettelLinksSxn(zn.InhMeta, api.KeyFolge, getTextTitle))
rb.bindString("subordinate-links", wui.zettelLinksSxn(zn.InhMeta, api.KeySubordinates, getTextTitle))
rb.bindString("back-links", wui.zettelLinksSxn(zn.InhMeta, api.KeyBack, getTextTitle))
rb.bindString("successor-links", wui.zettelLinksSxn(zn.InhMeta, api.KeySuccessors, getTextTitle))
if role, found := zn.InhMeta.Get(api.KeyRole); found && role != "" {
for _, part := range []string{"meta", "actions", "heading"} {
rb.rebindResolved("ROLE-"+role+"-"+part, "ROLE-DEFAULT-"+part)
}
}
wui.bindCommonZettelData(ctx, &rb, user, zn.InhMeta, &zn.Content)
if rb.err == nil {
err = wui.renderSxnTemplate(ctx, w, id.ZettelTemplateZid, env)
}
if err != nil {
wui.reportError(ctx, w, err)
}
}
}
func (wui *WebUI) getCSSRoleURL(ctx context.Context, m *meta.Meta) (string, error) {
cssZid, err := wui.retrieveCSSZidFromRole(ctx, m)
if err != nil {
return "", err
}
if cssZid == id.Invalid {
return "", nil
}
return wui.NewURLBuilder('z').SetZid(api.ZettelID(cssZid.String())).String(), nil
}
func (wui *WebUI) identifierSetAsLinks(m *meta.Meta, key string, getTextTitle getTextTitleFunc) *sx.Pair {
if values, ok := m.GetList(key); ok {
return wui.transformIdentifierSet(values, getTextTitle)
}
return nil
}
|
︙ | | |
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
|
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
-
+
-
+
-
+
|
for i := len(values) - 1; i >= 0; i-- {
val := values[i]
zid, err := id.Parse(val)
if err != nil {
continue
}
if title, found := getTextTitle(zid); found > 0 {
url := sx.MakeString(wui.NewURLBuilder('h').SetZid(api.ZettelID(zid.String())).String())
url := sx.String(wui.NewURLBuilder('h').SetZid(api.ZettelID(zid.String())).String())
if title == "" {
lst = lst.Cons(sx.Cons(sx.MakeString(val), url))
lst = lst.Cons(sx.Cons(sx.String(val), url))
} else {
lst = lst.Cons(sx.Cons(sx.MakeString(title), url))
lst = lst.Cons(sx.Cons(sx.String(title), url))
}
}
}
return lst
}
|
Changes to web/adapter/webui/home.go.
︙ | | |
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
|
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
|
+
-
-
+
+
|
"context"
"errors"
"net/http"
"zettelstore.de/client.fossil/api"
"zettelstore.de/z/box"
"zettelstore.de/z/config"
"zettelstore.de/z/web/adapter"
"zettelstore.de/z/web/server"
"zettelstore.de/z/zettel"
"zettelstore.de/z/zettel/id"
)
type getRootStore interface {
GetZettel(ctx context.Context, zid id.Zid) (zettel.Zettel, error)
}
// MakeGetRootHandler creates a new HTTP handler to show the root URL.
func (wui *WebUI) MakeGetRootHandler(s getRootStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.URL.Path != "/" {
wui.reportError(ctx, w, box.ErrNotFound)
if p := r.URL.Path; p != "/" {
wui.reportError(ctx, w, adapter.ErrResourceNotFound{Path: p})
return
}
homeZid, _ := id.Parse(wui.rtConfig.Get(ctx, nil, config.KeyHomeZettel))
apiHomeZid := api.ZettelID(homeZid.String())
if homeZid != id.DefaultHomeZid {
if _, err := s.GetZettel(ctx, homeZid); err == nil {
wui.redirectFound(w, r, wui.NewURLBuilder('h').SetZid(apiHomeZid))
|
︙ | | |
Changes to web/adapter/webui/htmlgen.go.
︙ | | |
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
-
+
|
attr, isPair = sx.GetPair(objA)
if !isPair || !symAttr.IsEqual(attr.Car()) {
return nil, nil, nil
}
return attr, attr.Tail(), rest.Tail()
}
linkZettel := func(args []sx.Object, prevFn sxeval.Callable) sx.Object {
obj, err := prevFn.Call(nil, nil, args)
obj, err := prevFn.Call(nil, args)
if err != nil {
return sx.Nil()
}
attr, assoc, rest := findA(obj)
if attr == nil {
return obj
}
|
︙ | | |
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
|
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
|
-
+
-
+
-
+
-
+
|
return obj
}
zid, fragment, hasFragment := strings.Cut(href.String(), "#")
u := builder.NewURLBuilder('h').SetZid(api.ZettelID(zid))
if hasFragment {
u = u.SetFragment(fragment)
}
assoc = assoc.Cons(sx.Cons(symHref, sx.MakeString(u.String())))
assoc = assoc.Cons(sx.Cons(symHref, sx.String(u.String())))
return rest.Cons(assoc.Cons(symAttr)).Cons(symA)
}
th.SetRebinder(func(te *shtml.TransformEnv) {
te.Rebind(sz.NameSymLinkZettel, linkZettel)
te.Rebind(sz.NameSymLinkFound, linkZettel)
te.Rebind(sz.NameSymLinkBased, func(args []sx.Object, prevFn sxeval.Callable) sx.Object {
obj, err := prevFn.Call(nil, nil, args)
obj, err := prevFn.Call(nil, args)
if err != nil {
return sx.Nil()
}
attr, assoc, rest := findA(obj)
if attr == nil {
return obj
}
hrefP := assoc.Assoc(symHref)
if hrefP == nil {
return obj
}
href, ok := sx.GetString(hrefP.Cdr())
if !ok {
return obj
}
u := builder.NewURLBuilder('/').SetRawLocal(href.String())
assoc = assoc.Cons(sx.Cons(symHref, sx.MakeString(u.String())))
assoc = assoc.Cons(sx.Cons(symHref, sx.String(u.String())))
return rest.Cons(assoc.Cons(symAttr)).Cons(symA)
})
te.Rebind(sz.NameSymLinkQuery, func(args []sx.Object, prevFn sxeval.Callable) sx.Object {
obj, err := prevFn.Call(nil, nil, args)
obj, err := prevFn.Call(nil, args)
if err != nil {
return sx.Nil()
}
attr, assoc, rest := findA(obj)
if attr == nil {
return obj
}
|
︙ | | |
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
|
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
|
-
+
-
+
-
-
-
+
+
+
-
+
|
return obj
}
q := ur.Query().Get(api.QueryKeyQuery)
if q == "" {
return obj
}
u := builder.NewURLBuilder('h').AppendQuery(q)
assoc = assoc.Cons(sx.Cons(symHref, sx.MakeString(u.String())))
assoc = assoc.Cons(sx.Cons(symHref, sx.String(u.String())))
return rest.Cons(assoc.Cons(symAttr)).Cons(symA)
})
te.Rebind(sz.NameSymLinkExternal, func(args []sx.Object, prevFn sxeval.Callable) sx.Object {
obj, err := prevFn.Call(nil, nil, args)
obj, err := prevFn.Call(nil, args)
if err != nil {
return sx.Nil()
}
attr, assoc, rest := findA(obj)
if attr == nil {
return obj
}
assoc = assoc.Cons(sx.Cons(symClass, sx.MakeString("external"))).
Cons(sx.Cons(symTarget, sx.MakeString("_blank"))).
Cons(sx.Cons(symRel, sx.MakeString("noopener noreferrer")))
assoc = assoc.Cons(sx.Cons(symClass, sx.String("external"))).
Cons(sx.Cons(symTarget, sx.String("_blank"))).
Cons(sx.Cons(symRel, sx.String("noopener noreferrer")))
return rest.Cons(assoc.Cons(symAttr)).Cons(symA)
})
te.Rebind(sz.NameSymEmbed, func(args []sx.Object, prevFn sxeval.Callable) sx.Object {
obj, err := prevFn.Call(nil, nil, args)
obj, err := prevFn.Call(nil, args)
if err != nil {
return sx.Nil()
}
pair, isPair := sx.GetPair(obj)
if !isPair || !symImg.IsEqual(pair.Car()) {
return obj
}
|
︙ | | |
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
|
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
|
-
+
|
return obj
}
zid := api.ZettelID(src)
if !zid.IsValid() {
return obj
}
u := builder.NewURLBuilder('z').SetZid(zid)
imgAttr := attr.Tail().Cons(sx.Cons(symSrc, sx.MakeString(u.String()))).Cons(symAttr)
imgAttr := attr.Tail().Cons(sx.Cons(symSrc, sx.String(u.String()))).Cons(symAttr)
return pair.Tail().Tail().Cons(imgAttr).Cons(symImg)
})
})
return &htmlGenerator{
tx: szenc.NewTransformer(),
th: th,
|
︙ | | |
Changes to web/adapter/webui/htmlmeta.go.
︙ | | |
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
|
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
|
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
+
-
-
+
+
-
+
-
+
-
+
-
+
-
+
|
key, value string,
getTextTitle getTextTitleFunc,
evalMetadata evalMetadataFunc,
gen *htmlGenerator,
) sx.Object {
switch kt := meta.Type(key); kt {
case meta.TypeCredential:
return sx.MakeString(value)
return sx.String(value)
case meta.TypeEmpty:
return sx.MakeString(value)
return sx.String(value)
case meta.TypeID:
return wui.transformIdentifier(value, getTextTitle)
case meta.TypeIDSet:
return wui.transformIdentifierSet(meta.ListFromValue(value), getTextTitle)
case meta.TypeNumber:
return wui.transformLink(key, value, value)
case meta.TypeString:
return sx.MakeString(value)
return sx.String(value)
case meta.TypeTagSet:
return wui.transformTagSet(key, meta.ListFromValue(value))
case meta.TypeTimestamp:
if ts, ok := meta.TimeValue(value); ok {
return sx.MakeList(
wui.sf.MustMake("time"),
sx.MakeList(
wui.symAttr,
sx.Cons(wui.sf.MustMake("datetime"), sx.MakeString(ts.Format("2006-01-02T15:04:05"))),
sx.Cons(wui.sf.MustMake("datetime"), sx.String(ts.Format("2006-01-02T15:04:05"))),
),
sx.MakeList(wui.sf.MustMake(sxhtml.NameSymNoEscape), sx.MakeString(ts.Format("2006-01-02 15:04:05"))),
sx.MakeList(wui.sf.MustMake(sxhtml.NameSymNoEscape), sx.String(ts.Format("2006-01-02 15:04:05"))),
)
}
return sx.Nil()
case meta.TypeURL:
text := sx.MakeString(value)
text := sx.String(value)
if res, err := wui.url2html([]sx.Object{text}); err == nil {
return res
}
return text
case meta.TypeWord:
return wui.transformLink(key, value, value)
case meta.TypeWordSet:
return wui.transformWordSet(key, meta.ListFromValue(value))
case meta.TypeZettelmarkup:
return wui.transformZmkMetadata(value, evalMetadata, gen)
default:
return sx.MakeList(wui.sf.MustMake("b"), sx.MakeString("Unhandled type: "), sx.MakeString(kt.Name))
return sx.MakeList(wui.sf.MustMake("b"), sx.String("Unhandled type: "), sx.String(kt.Name))
}
}
func (wui *WebUI) transformIdentifier(val string, getTextTitle getTextTitleFunc) sx.Object {
text := sx.MakeString(val)
text := sx.String(val)
zid, err := id.Parse(val)
if err != nil {
return text
}
title, found := getTextTitle(zid)
switch {
case found > 0:
ub := wui.NewURLBuilder('h').SetZid(api.ZettelID(zid.String()))
attrs := sx.Nil()
if title != "" {
attrs = attrs.Cons(sx.Cons(wui.sf.MustMake("title"), sx.MakeString(title)))
attrs = attrs.Cons(sx.Cons(wui.sf.MustMake("title"), sx.String(title)))
}
attrs = attrs.Cons(sx.Cons(wui.symHref, sx.MakeString(ub.String()))).Cons(wui.symAttr)
return sx.Nil().Cons(sx.MakeString(zid.String())).Cons(attrs).Cons(wui.symA)
attrs = attrs.Cons(sx.Cons(wui.symHref, sx.String(ub.String()))).Cons(wui.symAttr)
return sx.Nil().Cons(sx.String(zid.String())).Cons(attrs).Cons(wui.symA)
case found == 0:
return sx.MakeList(wui.sf.MustMake("s"), text)
default: // case found < 0:
return text
}
}
func (wui *WebUI) transformIdentifierSet(vals []string, getTextTitle getTextTitleFunc) *sx.Pair {
if len(vals) == 0 {
return nil
}
space := sx.MakeString(" ")
space := sx.String(" ")
text := make([]sx.Object, 0, 2*len(vals))
for _, val := range vals {
text = append(text, space, wui.transformIdentifier(val, getTextTitle))
}
return sx.MakeList(text[1:]...).Cons(wui.symSpan)
}
func (wui *WebUI) transformTagSet(key string, tags []string) *sx.Pair {
if len(tags) == 0 {
return nil
}
space := sx.MakeString(" ")
space := sx.String(" ")
text := make([]sx.Object, 0, 2*len(tags))
for _, tag := range tags {
text = append(text, space, wui.transformLink(key, tag, tag))
}
return sx.MakeList(text[1:]...).Cons(wui.symSpan)
}
func (wui *WebUI) transformWordSet(key string, words []string) sx.Object {
if len(words) == 0 {
return sx.Nil()
}
space := sx.MakeString(" ")
space := sx.String(" ")
text := make([]sx.Object, 0, 2*len(words))
for _, word := range words {
text = append(text, space, wui.transformLink(key, word, word))
}
return sx.MakeList(text[1:]...).Cons(wui.symSpan)
}
func (wui *WebUI) transformLink(key, value, text string) *sx.Pair {
return sx.MakeList(
wui.symA,
sx.MakeList(
wui.symAttr,
sx.Cons(wui.symHref, sx.MakeString(wui.NewURLBuilder('h').AppendQuery(key+api.SearchOperatorHas+value).String())),
sx.Cons(wui.symHref, sx.String(wui.NewURLBuilder('h').AppendQuery(key+api.SearchOperatorHas+value).String())),
),
sx.MakeString(text),
sx.String(text),
)
}
type evalMetadataFunc = func(string) ast.InlineSlice
func createEvalMetadataFunc(ctx context.Context, evaluate *usecase.Evaluate) evalMetadataFunc {
return func(value string) ast.InlineSlice { return evaluate.RunMetadata(ctx, value) }
|
︙ | | |
Changes to web/adapter/webui/lists.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
42
43
44
45
|
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
|
+
+
-
+
+
+
+
+
-
+
|
package webui
import (
"context"
"io"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"zettelstore.de/client.fossil/api"
"zettelstore.de/sx.fossil"
"zettelstore.de/z/ast"
"zettelstore.de/z/encoding/atom"
"zettelstore.de/z/encoding/rss"
"zettelstore.de/z/encoding/xml"
"zettelstore.de/z/evaluator"
"zettelstore.de/z/query"
"zettelstore.de/z/usecase"
"zettelstore.de/z/web/adapter"
"zettelstore.de/z/web/server"
"zettelstore.de/z/zettel/id"
"zettelstore.de/z/zettel/meta"
)
// MakeListHTMLMetaHandler creates a HTTP handler for rendering the list of zettel as HTML.
func (wui *WebUI) MakeListHTMLMetaHandler(queryMeta *usecase.Query) http.HandlerFunc {
func (wui *WebUI) MakeListHTMLMetaHandler(queryMeta *usecase.Query, tagZettel *usecase.TagZettel) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
urlQuery := r.URL.Query()
if wui.handleTagZettel(w, r, tagZettel, urlQuery) {
return
}
q := adapter.GetQuery(r.URL.Query())
q := adapter.GetQuery(urlQuery)
q = q.SetDeterministic()
ctx := r.Context()
metaSeq, err := queryMeta.Run(ctx, q)
if err != nil {
wui.reportError(ctx, w, err)
return
}
|
︙ | | |
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
|
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
|
-
+
-
+
-
+
+
+
+
+
+
-
-
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
|
user := server.GetUser(ctx)
env, rb := wui.createRenderEnv(
ctx, "list",
wui.rtConfig.Get(ctx, nil, api.KeyLang),
wui.rtConfig.GetSiteName(), user)
if q == nil {
rb.bindString("heading", sx.MakeString(wui.rtConfig.GetSiteName()))
rb.bindString("heading", sx.String(wui.rtConfig.GetSiteName()))
} else {
var sb strings.Builder
q.PrintHuman(&sb)
rb.bindString("heading", sx.MakeString(sb.String()))
rb.bindString("heading", sx.String(sb.String()))
}
rb.bindString("query-value", sx.MakeString(q.String()))
rb.bindString("query-value", sx.String(q.String()))
if tzl := q.GetMetaValues(api.KeyTags); len(tzl) > 0 {
if sxTzl := wui.transformTagZettelList(ctx, tagZettel, tzl); !sx.IsNil(sxTzl) {
rb.bindString("tag-zettel", sxTzl)
}
}
rb.bindString("content", content)
rb.bindString("endnotes", endnotes)
apiURL := wui.NewURLBuilder('z').AppendQuery(q.String())
seed, found := q.GetSeed()
if found {
apiURL = apiURL.AppendKVQuery(api.QueryKeySeed, strconv.Itoa(seed))
} else {
seed = 0
}
rb.bindString("plain-url", sx.MakeString(apiURL.String()))
rb.bindString("data-url", sx.MakeString(apiURL.AppendKVQuery(api.QueryKeyEncoding, api.EncodingData).String()))
rb.bindString("plain-url", sx.String(apiURL.String()))
rb.bindString("data-url", sx.String(apiURL.AppendKVQuery(api.QueryKeyEncoding, api.EncodingData).String()))
if wui.canCreate(ctx, user) {
rb.bindString("create-url", sx.MakeString(wui.createNewURL))
rb.bindString("create-url", sx.String(wui.createNewURL))
rb.bindString("seed", sx.Int64(seed))
}
if rb.err == nil {
err = wui.renderSxnTemplate(ctx, w, id.ListTemplateZid, env)
}
if err != nil {
wui.reportError(ctx, w, err)
}
}
}
func (wui *WebUI) transformTagZettelList(ctx context.Context, tagZettel *usecase.TagZettel, tags []string) *sx.Pair {
result := sx.Nil()
slices.Reverse(tags)
for _, tag := range tags {
if _, err := tagZettel.Run(ctx, tag); err != nil {
continue
}
u := wui.NewURLBuilder('h').AppendKVQuery(api.QueryKeyTag, tag)
link := sx.MakeList(
wui.symA,
sx.MakeList(
wui.symAttr,
sx.Cons(wui.symHref, sx.String(u.String())),
),
sx.String(tag),
)
if result != nil {
result = result.Cons(sx.String(", "))
}
result = result.Cons(link)
}
return result
}
func (wui *WebUI) renderRSS(ctx context.Context, w http.ResponseWriter, q *query.Query, ml []*meta.Meta) {
var rssConfig rss.Configuration
rssConfig.Setup(ctx, wui.rtConfig)
if actions := q.Actions(); len(actions) > 2 && actions[1] == "TITLE" {
rssConfig.Title = strings.Join(actions[2:], " ")
}
|
︙ | | |
133
134
135
136
137
138
139
|
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
|
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
|
if _, err = io.WriteString(w, xml.Header); err == nil {
_, err = w.Write(data)
}
if err != nil {
wui.log.IfErr(err).Msg("unable to write Atom data")
}
}
func (wui *WebUI) handleTagZettel(w http.ResponseWriter, r *http.Request, tagZettel *usecase.TagZettel, vals url.Values) bool {
tag := vals.Get(api.QueryKeyTag)
if tag == "" {
return false
}
ctx := r.Context()
z, err := tagZettel.Run(ctx, tag)
if err != nil {
wui.reportError(ctx, w, err)
return true
}
wui.redirectFound(w, r, wui.NewURLBuilder('h').SetZid(api.ZettelID(z.Meta.Zid.String())))
return true
}
|
Changes to web/adapter/webui/rename_zettel.go.
︙ | | |
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
+
-
+
-
+
|
)
// MakeGetRenameZettelHandler creates a new HTTP handler to display the
// HTML rename view of a zettel.
func (wui *WebUI) MakeGetRenameZettelHandler(getZettel usecase.GetZettel) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
path := r.URL.Path[1:]
zid, err := id.Parse(r.URL.Path[1:])
zid, err := id.Parse(path)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrInvalidZid{Zid: path})
return
}
z, err := getZettel.Run(ctx, zid)
if err != nil {
wui.reportError(ctx, w, err)
return
|
︙ | | |
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
+
-
+
-
+
|
}
}
// 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()
path := r.URL.Path[1:]
curZid, err := id.Parse(r.URL.Path[1:])
curZid, err := id.Parse(path)
if err != nil {
wui.reportError(ctx, w, box.ErrNotFound)
wui.reportError(ctx, w, box.ErrInvalidZid{Zid: path})
return
}
if err = r.ParseForm(); err != nil {
wui.log.Trace().Err(err).Msg("unable to read rename zettel form")
wui.reportError(ctx, w, adapter.NewErrBadRequest("Unable to read rename zettel form"))
return
|
︙ | | |
Added web/adapter/webui/sxn_code.go.