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
|
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
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
|
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
-
+
-
+
-
-
+
+
-
-
+
+
-
+
-
-
+
+
+
+
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
-
-
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
-
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-
+
-
-
-
+
+
+
-
-
-
+
+
+
-
-
-
+
+
+
-
+
-
+
-
-
-
-
+
+
+
+
-
+
-
+
-
-
-
-
+
-
-
-
-
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
-
-
-
+
-
-
-
+
-
-
+
-
-
-
-
+
+
-
-
-
-
+
+
-
+
-
-
-
-
-
-
-
-
-
-
+
-
-
-
+
-
-
-
-
-
-
+
-
-
-
-
+
-
-
-
-
-
+
-
-
+
+
+
-
-
+
+
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
-
+
+
+
-
-
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
-
-
+
+
+
+
+
-
-
-
-
-
-
-
+
+
+
+
+
+
+
-
+
-
-
-
-
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
-
-
-
-
+
|
if err != nil {
return err
}
defer 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.
func (c *Client) Authenticate(ctx context.Context) error {
authData := url.Values{"username": {c.username}, "password": {c.password}}
req, err := c.newRequest(ctx, http.MethodPost, c.newURLBuilder('a'), strings.NewReader(authData.Encode()))
req, err := c.newRequest(ctx, http.MethodPost, c.NewURLBuilder('a'), strings.NewReader(authData.Encode()))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
return c.executeAuthRequest(req)
}
// RefreshToken updates the access token
func (c *Client) RefreshToken(ctx context.Context) error {
req, err := c.newRequest(ctx, http.MethodPut, c.newURLBuilder('a'), nil)
req, err := c.newRequest(ctx, http.MethodPut, c.NewURLBuilder('a'), nil)
if err != nil {
return err
}
return c.executeAuthRequest(req)
}
// CreateZettel creates a new zettel and returns its URL.
func (c *Client) CreateZettel(ctx context.Context, data []byte) (api.ZettelID, error) {
ub := c.newURLBuilder('z')
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, bytes.NewBuffer(data), nil)
ub := c.NewURLBuilder('z')
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, bytes.NewBuffer(data))
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) {
// CreateZettelData creates a new zettel and returns its URL.
func (c *Client) CreateZettelData(ctx context.Context, data api.ZettelData) (api.ZettelID, error) {
var buf bytes.Buffer
if err := encodeZettelData(&buf, data); err != nil {
if _, err := sx.Print(&buf, sexp.EncodeZettel(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)
ub := c.NewURLBuilder('z').AppendKVQuery(api.QueryKeyEncoding, api.EncodingData)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodPost, ub, &buf)
if err != nil {
return api.InvalidZID, err
}
defer resp.Body.Close()
rdr := sxreader.MakeReader(resp.Body)
obj, err := rdr.Read()
if resp.StatusCode != http.StatusCreated {
return api.InvalidZID, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var newZid api.ZidJSON
err = dec.Decode(&newZid)
if err != nil {
return api.InvalidZID, err
}
if zid := newZid.ID; zid.IsValid() {
return zid, nil
return makeZettelID(obj)
}
return api.InvalidZID, err
}
func encodeZettelData(buf *bytes.Buffer, data *api.ZettelDataJSON) error {
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
return enc.Encode(&data)
}
var bsLF = []byte{'\n'}
// 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)
// QueryZettel returns a list of all Zettel.
func (c *Client) QueryZettel(ctx context.Context, query string) ([][]byte, error) {
ub := c.NewURLBuilder('z').AppendQuery(query)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNoContent:
return nil, nil
default:
return nil, statusToError(resp)
}
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)
// QueryZettelData returns a list of zettel metadata.
func (c *Client) QueryZettelData(ctx context.Context, query string) (string, string, []api.ZidMetaRights, error) {
ub := c.NewURLBuilder('z').AppendKVQuery(api.QueryKeyEncoding, api.EncodingData).AppendQuery(query)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil)
if err != nil {
return "", "", nil, err
}
defer resp.Body.Close()
rdr := sxreader.MakeReader(resp.Body)
obj, err := rdr.Read()
if resp.StatusCode != http.StatusOK {
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNoContent:
return "", "", nil, nil
default:
return "", "", nil, statusToError(resp)
}
if err != nil {
return "", "", nil, err
}
dec := json.NewDecoder(resp.Body)
var zl api.ZettelListJSON
err = dec.Decode(&zl)
vals, err := sexp.ParseList(obj, "yppp")
if err != nil {
return "", "", nil, err
}
qVals, err := sexp.ParseList(vals[1], "ys")
if err != nil {
return "", "", nil, err
}
hVals, err := sexp.ParseList(vals[2], "ys")
if err != nil {
return "", "", nil, err
}
metaList, err := parseMetaList(vals[3].(*sx.Pair))
return sz.GoValue(qVals[1]), sz.GoValue(hVals[1]), metaList, err
}
return zl.Query, zl.Human, zl.List, nil
}
// GetZettel returns a zettel as a string.
func (c *Client) GetZettel(ctx context.Context, zid api.ZettelID, part string) ([]byte, error) {
ub := c.newURLBuilder('z').SetZid(zid)
if part != "" && part != api.PartContent {
func parseMetaList(metaPair *sx.Pair) ([]api.ZidMetaRights, error) {
if metaPair == nil {
return nil, fmt.Errorf("no zettel list")
}
if errSym := sexp.CheckSymbol(metaPair.Car(), "list"); errSym != nil {
return nil, errSym
}
var result []api.ZidMetaRights
for node := metaPair.Cdr(); !sx.IsNil(node); {
elem, isPair := sx.GetPair(node)
if !isPair {
return nil, fmt.Errorf("meta-list not a proper list: %v", metaPair.String())
}
node = elem.Cdr()
vals, err := sexp.ParseList(elem.Car(), "yppp")
if err != nil {
return nil, err
}
if errSym := sexp.CheckSymbol(vals[0], "zettel"); errSym != nil {
return nil, errSym
}
idVals, err := sexp.ParseList(vals[1], "yi")
if err != nil {
ub.AppendKVQuery(api.QueryKeyPart, part)
}
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return nil, err
}
if errSym := sexp.CheckSymbol(idVals[0], "id"); errSym != nil {
return nil, errSym
}
zid, err := makeZettelID(idVals[1])
if err != nil {
return nil, err
}
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNoContent:
meta, err := sexp.ParseMeta(vals[2].(*sx.Pair))
if err != nil {
return nil, err
}
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)
rights, err := sexp.ParseRights(vals[3])
if err != nil {
return nil, err
}
result = append(result, api.ZidMetaRights{
ID: zid,
Meta: meta,
Rights: rights,
})
}
return result, nil
}
func makeZettelID(obj sx.Object) (api.ZettelID, error) {
val, isInt64 := obj.(sx.Int64)
if !isInt64 || val <= 0 {
return api.InvalidZID, fmt.Errorf("invalid zettel ID: %v", val)
}
sVal := strconv.FormatInt(int64(val), 10)
if len(sVal) < 14 {
sVal = "00000000000000"[0:14-len(sVal)] + sVal
}
zid := api.ZettelID(sVal)
if !zid.IsValid() {
return api.InvalidZID, fmt.Errorf("invalid zettel ID: %v", val)
}
return zid, nil
}
// QueryAggregate returns a aggregate as a result of a query.
// It is most often used in a query with an action, where the action is either
// a metadata key of type Word or of type TagSet.
func (c *Client) QueryAggregate(ctx context.Context, query string) (api.Aggregate, error) {
lines, err := c.QueryZettel(ctx, query)
if err != nil {
return nil, err
}
if len(lines) == 0 {
return nil, nil
}
agg := make(api.Aggregate, len(lines))
for _, line := range lines {
if fields := bytes.Fields(line); len(fields) > 1 {
key := string(fields[0])
for _, field := range fields[1:] {
if zid := api.ZettelID(string(field)); zid.IsValid() {
agg[key] = append(agg[key], zid)
}
}
}
}
return agg, nil
}
// TagZettel returns the tag zettel of a given tag.
//
// This method only works if c.AllowRedirect(true) was called.
func (c *Client) TagZettel(ctx context.Context, tag string) (api.ZettelID, error) {
return c.fetchTagOrRoleZettel(ctx, api.QueryKeyTag, tag)
}
// RoleZettel returns the tag zettel of a given tag.
//
// This method only works if c.AllowRedirect(true) was called.
func (c *Client) RoleZettel(ctx context.Context, role string) (api.ZettelID, error) {
return c.fetchTagOrRoleZettel(ctx, api.QueryKeyRole, role)
}
func (c *Client) fetchTagOrRoleZettel(ctx context.Context, key, val string) (api.ZettelID, error) {
if c.client.CheckRedirect == nil {
panic("client does not allow to track redirect")
}
ub := c.NewURLBuilder('z').AppendKVQuery(key, val)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil)
if err != nil {
return nil, err
return api.InvalidZID, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return api.InvalidZID, err
}
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
switch resp.StatusCode {
case http.StatusNotFound:
return "", nil
case http.StatusFound:
zid := api.ZettelID(data)
if zid.IsValid() {
return zid, nil
}
return api.InvalidZID, nil
default:
return api.InvalidZID, statusToError(resp)
}
}
dec := json.NewDecoder(resp.Body)
var out api.ZettelDataJSON
// GetZettel returns a zettel as a string.
err = dec.Decode(&out)
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)
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNoContent:
return &out, nil
return nil, nil
default:
return nil, statusToError(resp)
}
return data, err
}
// GetZettelData returns a zettel as a struct of its parts.
func (c *Client) GetZettelData(ctx context.Context, zid api.ZettelID) (api.ZettelData, error) {
ub := c.NewURLBuilder('z').SetZid(zid)
ub.AppendKVQuery(api.QueryKeyEncoding, api.EncodingData)
ub.AppendKVQuery(api.QueryKeyPart, api.PartZettel)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil)
if err == nil {
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return api.ZettelData{}, statusToError(resp)
}
rdr := sxreader.MakeReader(resp.Body)
obj, err2 := rdr.Read()
if err2 == nil {
return sexp.ParseZettel(obj)
}
}
return api.ZettelData{}, err
}
// GetParsedZettel return a parsed zettel in a defined encoding.
func (c *Client) GetParsedZettel(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum) ([]byte, error) {
return c.getZettelString(ctx, zid, enc, true)
}
// GetEvaluatedZettel return an evaluated zettel in a defined encoding.
func (c *Client) GetEvaluatedZettel(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum) ([]byte, error) {
return c.getZettelString(ctx, zid, enc, false)
}
func (c *Client) getZettelString(ctx context.Context, zid api.ZettelID, enc api.EncodingEnum, parseOnly bool) ([]byte, error) {
ub := c.newURLBuilder('z').SetZid(zid)
ub := c.NewURLBuilder('z').SetZid(zid)
ub.AppendKVQuery(api.QueryKeyEncoding, enc.String())
ub.AppendKVQuery(api.QueryKeyPart, api.PartContent)
if parseOnly {
ub.AppendKVQuery(api.QueryKeyParseOnly, "")
}
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNoContent:
default:
return nil, statusToError(resp)
}
return io.ReadAll(resp.Body)
}
// 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)
// GetParsedSz returns an parsed zettel as a Sexpr-decoded data structure.
func (c *Client) GetParsedSz(ctx context.Context, zid api.ZettelID, part string) (sx.Object, error) {
return c.getSz(ctx, zid, part, true)
}
// 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)
// GetEvaluatedSz returns an evaluated zettel as a Sexpr-decoded data structure.
func (c *Client) GetEvaluatedSz(ctx context.Context, zid api.ZettelID, part string) (sx.Object, error) {
return c.getSz(ctx, zid, part, false)
}
func (c *Client) 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)
func (c *Client) getSz(ctx context.Context, zid api.ZettelID, part string, parseOnly bool) (sx.Object, error) {
ub := c.NewURLBuilder('z').SetZid(zid)
ub.AppendKVQuery(api.QueryKeyEncoding, api.EncodingSz)
if part != "" {
ub.AppendKVQuery(api.QueryKeyPart, part)
}
if parseOnly {
ub.AppendKVQuery(api.QueryKeyParseOnly, "")
}
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
}
return reader.MakeReader(bufio.NewReaderSize(resp.Body, 8), reader.WithSymbolFactory(sf)).Read()
return sxreader.MakeReader(bufio.NewReaderSize(resp.Body, 8)).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)
// GetMetaData returns the metadata of a zettel.
func (c *Client) GetMetaData(ctx context.Context, zid api.ZettelID) (api.MetaRights, error) {
ub := c.NewURLBuilder('z').SetZid(zid)
ub.AppendKVQuery(api.QueryKeyEncoding, api.EncodingData)
ub.AppendKVQuery(api.QueryKeyPart, api.PartMeta)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil)
if err != nil {
return nil, err
return api.MetaRights{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
rdr := sxreader.MakeReader(resp.Body)
var out api.MetaJSON
err = dec.Decode(&out)
if err != nil {
return nil, err
}
return out.Meta, nil
}
obj, err := rdr.Read()
// 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)
return api.MetaRights{}, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
var out api.ZidMetaRelatedList
err = dec.Decode(&out)
if err != nil {
return nil, err
return api.MetaRights{}, err
}
return &out, nil
}
// ContextDirection specifies how the context should be calculated.
type ContextDirection uint8
// Allowed values for ContextDirection
const (
_ ContextDirection = iota
DirBoth
DirBackward
DirForward
)
}
// GetZettelContext returns metadata of the given zettel and, more important,
// metadata of zettel that for the context of the first zettel.
func (c *Client) GetZettelContext(
ctx context.Context, zid api.ZettelID, dir ContextDirection, cost, limit int) (
*api.ZidMetaRelatedList, error,
vals, err := sexp.ParseList(obj, "ypp")
) {
ub := c.newURLBuilder('x').SetZid(zid)
switch dir {
if err != nil {
case DirBackward:
ub.AppendKVQuery(api.QueryKeyDir, api.DirBackward)
return api.MetaRights{}, err
case DirForward:
ub.AppendKVQuery(api.QueryKeyDir, api.DirForward)
}
if cost > 0 {
ub.AppendKVQuery(api.QueryKeyCost, strconv.Itoa(cost))
if errSym := sexp.CheckSymbol(vals[0], "list"); errSym != nil {
return api.MetaRights{}, err
}
if limit > 0 {
ub.AppendKVQuery(api.QueryKeyLimit, strconv.Itoa(limit))
}
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil, nil)
meta, err := sexp.ParseMeta(vals[1].(*sx.Pair))
if err != nil {
return nil, err
return api.MetaRights{}, 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
}
rights, err := sexp.ParseRights(vals[2])
// 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
return api.MetaRights{}, 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 api.MetaRights{
}
return &out, nil
Meta: meta,
Rights: rights,
}, 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)
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()
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.
func (c *Client) UpdateZettelData(ctx context.Context, zid api.ZettelID, 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()
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)
ub := c.NewURLBuilder('z').SetZid(zid)
resp, err := c.buildAndExecuteRequest(ctx, http.MethodDelete, ub, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
return statusToError(resp)
}
return nil
}
// ExecuteCommand will execute a given command at the Zettelstore.
func (c *Client) ExecuteCommand(ctx context.Context, command api.Command) error {
ub := c.newURLBuilder('x').AppendKVQuery(api.QueryKeyCommand, string(command))
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()
if resp.StatusCode != http.StatusNoContent {
return statusToError(resp)
}
return nil
}
// GetVersionInfo returns version information.
func (c *Client) newQueryURLBuilder(key byte, query url.Values) *api.URLBuilder {
ub := c.newURLBuilder(key)
func (c *Client) GetVersionInfo(ctx context.Context) (VersionInfo, error) {
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, c.NewURLBuilder('x'), nil)
for key, values := range query {
if key == api.QueryKeyEncoding {
continue
}
for _, val := range values {
ub.AppendKVQuery(key, val)
}
if err != nil {
return VersionInfo{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return VersionInfo{}, statusToError(resp)
}
rdr := sxreader.MakeReader(resp.Body)
obj, err := rdr.Read()
if err == nil {
if vals, errVals := sexp.ParseList(obj, "iiiss"); errVals == nil {
return ub
}
return VersionInfo{
Major: int(vals[0].(sx.Int64)),
Minor: int(vals[1].(sx.Int64)),
Patch: int(vals[2].(sx.Int64)),
Info: vals[3].(sx.String).GetValue(),
Hash: vals[4].(sx.String).GetValue(),
}, nil
}
}
// 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 VersionInfo{}, err
}
// VersionInfo contains version information.
type VersionInfo struct {
Major int
return nil, err
}
Minor int
Patch int
Info string
Hash string
}
resp, err := c.executeRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, statusToError(resp)
// GetApplicationZid returns the zettel identifier used to configure client
// application with the given name.
func (c *Client) GetApplicationZid(ctx context.Context, appname string) (api.ZettelID, error) {
mr, err := c.GetMetaData(ctx, api.ZidAppDirectory)
if err != nil {
return api.InvalidZID, err
}
dec := json.NewDecoder(resp.Body)
key := appname + "-zid"
var mlj api.MapListJSON
err = dec.Decode(&mlj)
if err != nil {
return nil, err
val, found := mr.Meta[key]
if !found {
return api.InvalidZID, fmt.Errorf("no application registered: %v", appname)
}
if zid := api.ZettelID(val); zid.IsValid() {
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)
return zid, nil
}
return api.InvalidZID, fmt.Errorf("invalid identifier for application %v: %v", appname, val)
}
// Get executes a GET request to the given URL and returns the read data.
func (c *Client) Get(ctx context.Context, ub *api.URLBuilder) ([]byte, error) {
resp, err := c.buildAndExecuteRequest(ctx, http.MethodGet, ub, nil)
if err != nil {
return api.VersionJSON{}, err
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return api.VersionJSON{}, statusToError(resp)
switch resp.StatusCode {
case http.StatusOK:
case http.StatusNoContent:
return nil, nil
default:
return nil, statusToError(resp)
}
dec := json.NewDecoder(resp.Body)
data, err := io.ReadAll(resp.Body)
var version api.VersionJSON
err = dec.Decode(&version)
if err != nil {
return api.VersionJSON{}, err
}
return version, nil
return data, err
}
|