107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
|
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
|
+
+
+
+
+
+
-
+
-
+
-
+
+
+
+
+
-
-
-
+
+
-
+
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
-
+
+
+
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
+
-
-
+
-
-
-
-
+
+
+
-
+
-
-
+
+
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
+
+
+
-
-
-
+
-
-
-
-
+
+
+
-
-
-
-
+
-
-
-
-
-
+
-
+
-
+
-
-
-
-
-
-
-
+
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
+
-
-
-
-
+
+
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
+
-
+
-
+
+
+
-
-
+
+
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
-
+
+
+
+
+
-
-
+
+
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
|
return &Error{
StatusCode: resp.StatusCode,
Message: resp.Status[4:],
Body: body,
}
}
// NewURLBuilder creates a new URL builder for the client with the given key.
//
// key is one of the defined lower case letters to specify an endpoint.
// See [Endpoints used by the API] for details.
//
// [Endpoints used by the API]: https://zettelstore.de/manual/h/00001012920000
func (c *Client) newURLBuilder(key byte) *api.URLBuilder {
func (c *Client) NewURLBuilder(key byte) *api.URLBuilder {
return api.NewURLBuilder(c.base, key)
}
func (*Client) newRequest(ctx context.Context, method string, ub *api.URLBuilder, body io.Reader) (*http.Request, error) {
return http.NewRequestWithContext(ctx, method, ub.String(), body)
}
func (c *Client) executeRequest(req *http.Request) (*http.Response, error) {
if c.token != "" {
req.Header.Add("Authorization", c.tokenType+" "+c.token)
}
resp, err := c.client.Do(req)
if err != nil {
if resp != nil && resp.Body != nil {
resp.Body.Close()
_ = resp.Body.Close()
}
return nil, err
}
return resp, err
}
func (c *Client) buildAndExecuteRequest(
ctx context.Context, method string, ub *api.URLBuilder, body io.Reader, h http.Header) (*http.Response, error) {
ctx context.Context,
method string,
ub *api.URLBuilder,
body io.Reader,
) (*http.Response, error) {
req, err := c.newRequest(ctx, method, ub, body)
if err != nil {
return nil, err
}
err = c.updateToken(ctx)
if err != nil {
return nil, err
}
for key, val := range h {
req.Header[key] = append(req.Header[key], val...)
}
return c.executeRequest(req)
}
// SetAuth sets authentication data.
//
// username and password are the same values that are used to authenticate via the Web-UI.
func (c *Client) SetAuth(username, password string) {
c.username = username
c.password = password
c.token = ""
c.tokenType = ""
c.expires = time.Time{}
}
func (c *Client) executeAuthRequest(req *http.Request) error {
resp, err := c.executeRequest(req)
if err != nil {
return err
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var tinfo api.AuthJSON
err = dec.Decode(&tinfo)
rd := sxreader.MakeReader(resp.Body)
obj, err := rd.Read()
if err != nil {
return err
}
vals, err := sexp.ParseList(obj, "ssi")
if err != nil {
return err
}
token := vals[1].(sx.String).GetValue()
if len(token) < 4 {
return fmt.Errorf("no valid token found: %q", token)
}
c.token = tinfo.Token
c.tokenType = tinfo.Type
c.expires = time.Now().Add(time.Duration(tinfo.Expires*10/9) * time.Second)
c.token = token
c.tokenType = vals[0].(sx.String).GetValue()
c.expires = time.Now().Add(time.Duration(vals[2].(sx.Int64)*9/10) * time.Second)
return nil
}
func (c *Client) updateToken(ctx context.Context) error {
if c.username == "" {
return nil
}
if time.Now().After(c.expires) {
return c.Authenticate(ctx)
}
return c.RefreshToken(ctx)
}
// Authenticate sets a new token by sending user name and password.
//
// [Client.SetAuth] should be called before.
func (c *Client) Authenticate(ctx context.Context) error {
authData := url.Values{"username": {c.username}, "password": {c.password}}
req, err := c.newRequest(ctx, http.MethodPost, c.newURLBuilder('a'), strings.NewReader(authData.Encode()))
req, err := c.newRequest(ctx, http.MethodPost, c.NewURLBuilder('a'), strings.NewReader(authData.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return c.executeAuthRequest(req)
}
// RefreshToken updates the access token
//
// [Client.SetAuth] should be called before.
func (c *Client) RefreshToken(ctx context.Context) error {
req, err := c.newRequest(ctx, http.MethodPut, c.newURLBuilder('a'), nil)
req, err := c.newRequest(ctx, http.MethodPut, c.NewURLBuilder('a'), nil)
if err != nil {
return err
}
return c.executeAuthRequest(req)
}
// CreateZettel creates a new zettel and returns its URL.
func (c *Client) CreateZettel(ctx context.Context, data []byte) (api.ZettelID, error) {
ub := c.newURLBuilder('z')
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, bytes.NewBuffer(data), nil)
if err != nil {
return api.InvalidZID, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return api.InvalidZID, statusToError(resp)
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return api.InvalidZID, err
}
if zid := api.ZettelID(b); zid.IsValid() {
return zid, nil
}
return api.InvalidZID, err
}
//
// CreateZettelJSON creates a new zettel and returns its URL.
func (c *Client) CreateZettelJSON(ctx context.Context, data *api.ZettelDataJSON) (api.ZettelID, error) {
var buf bytes.Buffer
if err := encodeZettelData(&buf, data); err != nil {
return api.InvalidZID, err
}
ub := c.newURLBuilder('z').AppendKVQuery(api.QueryKeyEncoding, api.EncodingJson)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, &buf, nil)
if err != nil {
return api.InvalidZID, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return api.InvalidZID, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var newZid api.ZidJSON
err = dec.Decode(&newZid)
if err != nil {
return api.InvalidZID, err
}
if zid := newZid.ID; zid.IsValid() {
return zid, nil
}
return api.InvalidZID, err
}
// data contains the zettel metadata and content, as it is stored in a file in a zettel box,
func encodeZettelData(buf *bytes.Buffer, data *api.ZettelDataJSON) error {
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
return enc.Encode(&data)
}
// or as returned by [Client.GetZettel].
var bsLF = []byte{'\n'}
// Metadata is separated from zettel content by an empty line.
// ListZettel returns a list of all Zettel.
func (c *Client) ListZettel(ctx context.Context, query string) ([][]byte, error) {
ub := c.newURLBuilder('z').AppendQuery(query)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
func (c *Client) CreateZettel(ctx context.Context, data []byte) (id.Zid, error) {
ub := c.NewURLBuilder('z')
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, bytes.NewBuffer(data))
if err != nil {
return nil, err
return id.Invalid, err
}
defer resp.Body.Close()
switch resp.StatusCode {
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusCreated {
case http.StatusOK:
case http.StatusNoContent:
default:
return nil, statusToError(resp)
return id.Invalid, statusToError(resp)
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
lines := bytes.Split(data, bsLF)
if len(lines[len(lines)-1]) == 0 {
lines = lines[:len(lines)-1]
}
return lines, nil
}
}
// ListZettelJSON returns a list of zettel.
func (c *Client) ListZettelJSON(ctx context.Context, query string) (string, string, []api.ZidMetaJSON, error) {
ub := c.newURLBuilder('z').AppendKVQuery(api.QueryKeyEncoding, api.EncodingJson).AppendQuery(query)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
if err != nil {
return "", "", nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", "", nil, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
b, err := io.ReadAll(resp.Body)
var zl api.ZettelListJSON
err = dec.Decode(&zl)
if err != nil {
return "", "", nil, err
}
return zl.Query, zl.Human, zl.List, nil
}
return id.Invalid, err
// GetZettel returns a zettel as a string.
func (c *Client) GetZettel(ctx context.Context, zid api.ZettelID, part string) ([]byte, error) {
ub := c.newURLBuilder('z').SetZid(zid)
if part != "" && part != api.PartContent {
ub.AppendKVQuery(api.QueryKeyPart, part)
}
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
if err != nil {
return nil, err
}
return id.Parse(string(b))
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNoContent:
default:
return nil, statusToError(resp)
}
return io.ReadAll(resp.Body)
}
// GetZettelJSON returns a zettel as a JSON struct.
func (c *Client) GetZettelJSON(ctx context.Context, zid api.ZettelID) (*api.ZettelDataJSON, error) {
ub := c.newURLBuilder('z').SetZid(zid)
ub.AppendKVQuery(api.QueryKeyEncoding, api.EncodingJson)
ub.AppendKVQuery(api.QueryKeyPart, api.PartZettel)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var out api.ZettelDataJSON
// CreateZettelData creates a new zettel and returns its URL.
err = dec.Decode(&out)
if err != nil {
return nil, err
}
return &out, nil
}
// GetParsedZettel return a parsed zettel in a defined encoding.
func (c *Client) GetParsedZettel(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum) ([]byte, error) {
//
// data contains the zettel date, encoded as explicit struct.
func (c *Client) CreateZettelData(ctx context.Context, data api.ZettelData) (id.Zid, error) {
return c.getZettelString(ctx, zid, enc, true)
}
var buf bytes.Buffer
// GetEvaluatedZettel return an evaluated zettel in a defined encoding.
func (c *Client) GetEvaluatedZettel(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum) ([]byte, error) {
return c.getZettelString(ctx, zid, enc, false)
}
if _, err := sx.Print(&buf, sexp.EncodeZettel(data)); err != nil {
return id.Invalid, err
}
func (c *Client) getZettelString(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum, parseOnly bool) ([]byte, error) {
ub := c.newURLBuilder('z').SetZid(zid)
ub.AppendKVQuery(api.QueryKeyEncoding, enc.String())
ub := c.NewURLBuilder('z').AppendKVQuery(api.QueryKeyEncoding, api.EncodingData)
ub.AppendKVQuery(api.QueryKeyPart, api.PartContent)
if parseOnly {
ub.AppendKVQuery(api.QueryKeyParseOnly, "")
}
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, &buf)
if err != nil {
return nil, err
return id.Invalid, err
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNoContent:
default:
return nil, statusToError(resp)
}
return io.ReadAll(resp.Body)
rdr := sxreader.MakeReader(resp.Body)
}
obj, err := rdr.Read()
// GetParsedSexpr returns an parsed zettel as a Sexpr-decoded data structure.
func (c *Client) GetParsedSexpr(ctx context.Context, zid api.ZettelID, part string, sf sxpf.SymbolFactory) (sxpf.Object, error) {
return c.getSexpr(ctx, zid, part, true, sf)
}
// GetEvaluatedSexpr returns an evaluated zettel as a Sexpr-decoded data structure.
func (c *Client) GetEvaluatedSexpr(ctx context.Context, zid api.ZettelID, part string, sf sxpf.SymbolFactory) (sxpf.Object, error) {
return c.getSexpr(ctx, zid, part, false, sf)
}
func (c *Client) getSexpr(ctx context.Context, zid api.ZettelID, part string, parseOnly bool, sf sxpf.SymbolFactory) (sxpf.Object, error) {
ub := c.newURLBuilder('z').SetZid(zid)
ub.AppendKVQuery(api.QueryKeyEncoding, api.EncodingSexpr)
if part != "" {
ub.AppendKVQuery(api.QueryKeyPart, part)
}
if parseOnly {
ub.AppendKVQuery(api.QueryKeyParseOnly, "")
}
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
if resp.StatusCode != http.StatusCreated {
return id.Invalid, statusToError(resp)
}
return reader.MakeReader(bufio.NewReaderSize(resp.Body, 8), reader.WithSymbolFactory(sf)).Read()
}
// GetMeta returns the metadata of a zettel.
func (c *Client) GetMeta(ctx context.Context, zid api.ZettelID) (api.ZettelMeta, error) {
ub := c.newURLBuilder('z').SetZid(zid)
ub.AppendKVQuery(api.QueryKeyEncoding, api.EncodingJson)
ub.AppendKVQuery(api.QueryKeyPart, api.PartMeta)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
if err != nil {
return nil, err
return id.Invalid, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var out api.MetaJSON
err = dec.Decode(&out)
if err != nil {
return nil, err
}
return makeZettelID(obj)
}
return out.Meta, nil
}
// GetZettelOrder returns metadata of the given zettel and, more important,
// metadata of zettel that are referenced in a list within the first zettel.
func (c *Client) GetZettelOrder(ctx context.Context, zid api.ZettelID) (*api.ZidMetaRelatedList, error) {
ub := c.newURLBuilder('o').SetZid(zid)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var out api.ZidMetaRelatedList
err = dec.Decode(&out)
if err != nil {
return nil, err
}
return &out, nil
}
func makeZettelID(obj sx.Object) (id.Zid, error) {
// ContextDirection specifies how the context should be calculated.
type ContextDirection uint8
// Allowed values for ContextDirection
val, isInt64 := obj.(sx.Int64)
if !isInt64 || val <= 0 {
const (
_ ContextDirection = iota
DirBoth
DirBackward
DirForward
)
return id.Invalid, fmt.Errorf("invalid zettel ID: %v", val)
// GetZettelContext returns metadata of the given zettel and, more important,
// metadata of zettel that for the context of the first zettel.
func (c *Client) GetZettelContext(
ctx context.Context, zid api.ZettelID, dir ContextDirection, cost, limit int) (
*api.ZidMetaRelatedList, error,
) {
ub := c.newURLBuilder('x').SetZid(zid)
switch dir {
case DirBackward:
ub.AppendKVQuery(api.QueryKeyDir, api.DirBackward)
case DirForward:
ub.AppendKVQuery(api.QueryKeyDir, api.DirForward)
}
if cost > 0 {
ub.AppendKVQuery(api.QueryKeyCost, strconv.Itoa(cost))
sVal := strconv.FormatInt(int64(val), 10)
}
if limit > 0 {
if len(sVal) < 14 {
ub.AppendKVQuery(api.QueryKeyLimit, strconv.Itoa(limit))
sVal = "00000000000000"[0:14-len(sVal)] + sVal
}
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
zid, err := id.Parse(sVal)
if err != nil {
return id.Invalid, fmt.Errorf("invalid zettel ID %v: %w", val, err)
}
return nil, err
}
return zid, nil
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var out api.ZidMetaRelatedList
err = dec.Decode(&out)
if err != nil {
return nil, err
}
return &out, nil
}
// GetUnlinkedReferences returns connections to other zettel, embedded material, externals URLs.
func (c *Client) GetUnlinkedReferences(
ctx context.Context, zid api.ZettelID, query url.Values) (*api.ZidMetaRelatedList, error) {
ub := c.newQueryURLBuilder('u', query).SetZid(zid)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var out api.ZidMetaRelatedList
err = dec.Decode(&out)
if err != nil {
return nil, err
}
return &out, nil
}
// UpdateZettel updates an existing zettel.
func (c *Client) UpdateZettel(ctx context.Context, zid api.ZettelID, data []byte) error {
ub := c.newURLBuilder('z').SetZid(zid)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPut, ub, bytes.NewBuffer(data), nil)
// UpdateZettel updates an existing zettel, specified by its zettel identifier.
//
// data contains the zettel metadata and content, as it is stored in a file in a zettel box,
// or as returned by [Client.GetZettel].
// Metadata is separated from zettel content by an empty line.
func (c *Client) UpdateZettel(ctx context.Context, zid id.Zid, data []byte) error {
ub := c.NewURLBuilder('z').SetZid(zid)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPut, ub, bytes.NewBuffer(data))
if err != nil {
return err
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNoContent {
return statusToError(resp)
}
return nil
}
// UpdateZettelJSON updates an existing zettel.
func (c *Client) UpdateZettelJSON(ctx context.Context, zid api.ZettelID, data *api.ZettelDataJSON) error {
// UpdateZettelData updates an existing zettel, specified by its zettel identifier.
func (c *Client) UpdateZettelData(ctx context.Context, zid id.Zid, data api.ZettelData) error {
var buf bytes.Buffer
if err := encodeZettelData(&buf, data); err != nil {
if _, err := sx.Print(&buf, sexp.EncodeZettel(data)); err != nil {
return err
}
ub := c.newURLBuilder('z').SetZid(zid).AppendKVQuery(api.QueryKeyEncoding, api.EncodingJson)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPut, ub, &buf, nil)
ub := c.NewURLBuilder('z').SetZid(zid).AppendKVQuery(api.QueryKeyEncoding, api.EncodingData)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPut, ub, &buf)
if err != nil {
return err
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNoContent {
return statusToError(resp)
}
return nil
}
// RenameZettel renames a zettel.
func (c *Client) RenameZettel(ctx context.Context, oldZid, newZid api.ZettelID) error {
ub := c.newURLBuilder('z').SetZid(oldZid)
h := http.Header{
api.HeaderDestination: {c.newURLBuilder('z').SetZid(newZid).String()},
}
resp, err := c.buildAndExecuteRequest(ctx, api.MethodMove, ub, nil, h)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
return statusToError(resp)
}
return nil
}
// DeleteZettel deletes a zettel with the given identifier.
func (c *Client) DeleteZettel(ctx context.Context, zid api.ZettelID) error {
ub := c.newURLBuilder('z').SetZid(zid)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodDelete, ub, nil, nil)
func (c *Client) DeleteZettel(ctx context.Context, zid id.Zid) error {
ub := c.NewURLBuilder('z').SetZid(zid)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodDelete, ub, nil)
if err != nil {
return err
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNoContent {
return statusToError(resp)
}
return nil
}
// ExecuteCommand will execute a given command at the Zettelstore.
//
// See [API commands] for a list of valid commands.
//
// [API commands]: https://zettelstore.de/manual/h/00001012080100
func (c *Client) ExecuteCommand(ctx context.Context, command api.Command) error {
ub := c.newURLBuilder('x').AppendKVQuery(api.QueryKeyCommand, string(command))
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, nil, nil)
ub := c.NewURLBuilder('x').AppendKVQuery(api.QueryKeyCommand, string(command))
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, nil)
if err != nil {
return err
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNoContent {
return statusToError(resp)
}
return nil
}
func (c *Client) newQueryURLBuilder(key byte, query url.Values) *api.URLBuilder {
ub := c.newURLBuilder(key)
for key, values := range query {
if key == api.QueryKeyEncoding {
continue
}
for _, val := range values {
ub.AppendKVQuery(key, val)
}
}
return ub
}
// QueryMapMeta returns a map of all metadata values with the given query action to the
// list of zettel IDs containing this value.
func (c *Client) QueryMapMeta(ctx context.Context, query string) (api.MapMeta, error) {
err := c.updateToken(ctx)
if err != nil {
return nil, err
}
req, err := c.newRequest(ctx, http.MethodGet, c.newURLBuilder('z').AppendKVQuery(api.QueryKeyEncoding, api.EncodingJson).AppendQuery(query), nil)
if err != nil {
return nil, err
}
resp, err := c.executeRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var mlj api.MapListJSON
err = dec.Decode(&mlj)
if err != nil {
return nil, err
}
return mlj.Map, nil
}
// GetVersionJSON returns version information..
func (c *Client) GetVersionJSON(ctx context.Context) (api.VersionJSON, error) {
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, c.newURLBuilder('x'), nil, nil)
if err != nil {
return api.VersionJSON{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return api.VersionJSON{}, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var version api.VersionJSON
err = dec.Decode(&version)
if err != nil {
return api.VersionJSON{}, err
}
return version, nil
}
|