-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepository.go
1355 lines (1215 loc) · 35.9 KB
/
repository.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package fs
import (
"bytes"
"crypto"
"crypto/dsa"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
xerrors "errors"
"fmt"
"io/fs"
"math/rand"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"time"
"git.sr.ht/~mariusor/lw"
"github.com/RoaringBitmap/roaring/roaring64"
vocab "github.com/go-ap/activitypub"
"github.com/go-ap/cache"
"github.com/go-ap/errors"
"github.com/go-ap/filters"
"github.com/go-ap/processing"
"golang.org/x/crypto/bcrypt"
)
var encodeItemFn = vocab.MarshalJSON
var decodeItemFn = vocab.UnmarshalJSON
var errNotImplemented = errors.NotImplementedf("not implemented")
var emptyLogger = lw.Dev()
type Config struct {
Path string
CacheEnable bool
UseIndex bool
Logger lw.Logger
}
var errMissingPath = errors.Newf("missing path in config")
// New returns a new repo repository
func New(c Config) (*repo, error) {
if c.Path == "" {
return nil, errMissingPath
}
p, err := getAbsStoragePath(c.Path)
if err != nil {
return nil, err
}
if err := mkDirIfNotExists(p); err != nil {
return nil, err
}
cwd, _ := getwd()
b := repo{
path: p,
cwd: cwd,
logger: emptyLogger,
cache: cache.New(c.CacheEnable),
}
if c.Logger != nil {
b.logger = c.Logger
}
if c.UseIndex {
b.index = newBitmap()
}
return &b, nil
}
type repo struct {
path string
cwd string
opened bool
index *bitmaps
cache cache.CanStore
logger lw.Logger
}
// Open
func (r *repo) Open() error {
if r.opened {
return nil
}
// NOTE(marius): this is needed in order that the relative symlinks used for collection items to work
if err := os.Chdir(r.path); err != nil {
return err
}
r.opened = true
return nil
}
func (r *repo) close() error {
if !r.opened {
return nil
}
r.opened = false
return os.Chdir(r.cwd)
}
// Close
func (r *repo) Close() {
r.close()
}
// Load
func (r *repo) Load(i vocab.IRI, f ...filters.Check) (vocab.Item, error) {
if err := r.Open(); err != nil {
return nil, err
}
defer r.Close()
it, err := r.loadFromIRI(i, f...)
if err != nil {
return nil, err
}
return it, nil
}
// Create
func (r *repo) Create(col vocab.CollectionInterface) (vocab.CollectionInterface, error) {
err := r.Open()
if err != nil {
return nil, err
}
defer r.Close()
if vocab.IsNil(col) {
return col, errors.Newf("Unable to operate on nil element")
}
if len(col.GetLink()) == 0 {
return col, errors.Newf("Invalid collection, it does not have a valid IRI")
}
return saveCollection(r, col)
}
// Save
func (r *repo) Save(it vocab.Item) (vocab.Item, error) {
err := r.Open()
if err != nil {
return nil, err
}
defer r.Close()
if it, err = save(r, it); err == nil {
op := "Updated"
id := it.GetID()
if !id.IsValid() {
op = "Added new"
}
r.logger.Debugf("%s %s: %s", op, it.GetType(), it.GetLink())
}
return it, err
}
// RemoveFrom
func (r *repo) RemoveFrom(col vocab.IRI, it vocab.Item) error {
err := r.Open()
defer r.Close()
if err != nil {
return err
}
ob, t := vocab.Split(col)
var link vocab.IRI
if filters.ValidCollection(t) {
// Create the collection on the object, if it doesn't exist
i, err := r.loadOneFromIRI(ob)
if err != nil {
return err
}
if p, ok := t.AddTo(i); ok {
_, _ = save(r, i)
link = p
} else {
link = t.IRI(i)
}
}
linkPath := r.itemStoragePath(link)
name := path.Base(r.itemStoragePath(it.GetLink()))
// we create a symlink to the persisted object in the current collection
err = onCollection(r, col, it, func(p string) error {
inCollection := false
if dirInfo, err := os.ReadDir(p); err == nil {
for _, di := range dirInfo {
fi, err := di.Info()
if err != nil {
continue
}
if fi.Name() == name && isSymLink(fi) {
inCollection = true
}
}
}
if inCollection {
link := path.Join(linkPath, name)
return os.RemoveAll(link)
}
return nil
})
if err != nil {
return err
}
err = vocab.OnCollectionIntf(col, r.collectionBitmapOp((*roaring64.Bitmap).Remove, it))
if err != nil && !errors.Is(err, cacheDisabled) {
r.logger.Errorf("unable to remote item %s from collection index: %s", it.GetLink(), err)
}
r.removeFromCache(it.GetLink())
return nil
}
func isSymLink(fi os.FileInfo) bool {
if fi == nil {
return false
}
return fi.Mode()&os.ModeSymlink == os.ModeSymlink
}
var allStorageCollections = append(vocab.ActivityPubCollections, filters.FedBOXCollections...)
func iriPath(iri vocab.IRI) string {
u, err := iri.URL()
if err != nil {
return ""
}
pieces := make([]string, 0)
if h := u.Host; h != "" {
pieces = append(pieces, h)
}
if p := u.Path; p != "" && p != "/" {
pieces = append(pieces, p)
}
//if u.ForceQuery || u.RawQuery != "" {
// pieces = append(pieces, url.PathEscape(u.RawQuery))
//}
if u.Fragment != "" {
pieces = append(pieces, strings.ReplaceAll(u.Fragment, "#", ""))
}
return filepath.Join(pieces...)
}
func saveCollection(r *repo, col vocab.CollectionInterface) (vocab.CollectionInterface, error) {
it, err := save(r, col)
if err != nil {
return nil, err
}
err = vocab.OnOrderedCollection(it, func(c *vocab.OrderedCollection) error {
col = c
return nil
})
return col, err
}
func createCollection(r *repo, colIRI vocab.IRI) (vocab.CollectionInterface, error) {
col := vocab.OrderedCollection{
ID: colIRI,
Type: vocab.OrderedCollectionType,
Published: time.Now().UTC(),
}
return saveCollection(r, &col)
}
var orderedCollectionTypes = vocab.ActivityVocabularyTypes{vocab.OrderedCollectionPageType, vocab.OrderedCollectionType}
var collectionTypes = vocab.ActivityVocabularyTypes{vocab.CollectionPageType, vocab.CollectionType}
// AddTo
func (r *repo) AddTo(colIRI vocab.IRI, it vocab.Item) error {
err := r.Open()
defer r.Close()
if err != nil {
return err
}
var link vocab.IRI
var col vocab.Item
// NOTE(marius): We make sure the collection exists (unless it's a hidden collection)
if !isHiddenCollectionKey(r.itemStoragePath(colIRI)) {
itPath := r.itemStoragePath(colIRI)
if col, err = r.loadItemFromPath(getObjectKey(itPath)); err != nil {
return err
}
parent, destination := allStorageCollections.Split(colIRI)
if isStorageCollectionKey(string(destination)) {
// Create the collection on the object, if it doesn't exist
i, err := r.loadFromIRI(parent, filters.WithMaxCount(1))
if err != nil {
return err
}
if p, ok := destination.AddTo(i); ok {
_, _ = save(r, i)
link = p
} else {
link = destination.IRI(i)
}
} else {
return errors.Newf("Invalid collection %s", destination)
}
} else {
// NOTE(marius): for hidden collections we might not have the __raw file on disk, so we just wing it
link = colIRI
col = link
}
linkPath := r.itemStoragePath(link)
itOriginalPath := r.itemStoragePath(it.GetLink())
fullLink := path.Join(linkPath, url.PathEscape(iriPath(it.GetLink())))
// we create a symlink to the persisted object in the current collection
err = onCollection(r, col, it, func(p string) error {
if err := mkDirIfNotExists(p); err != nil {
return errors.Annotatef(err, "Unable to create collection folder %s", p)
}
// NOTE(marius): if 'it' IRI belongs to the 'col' collection we can skip symlinking it
if it.GetLink().Contains(col.GetLink(), true) {
return nil
}
if fi, _ := os.Stat(fullLink); fi != nil {
if isSymLink(fi) {
return nil
}
}
if itOriginalPath, err = filepath.Abs(itOriginalPath); err != nil {
return err
}
if fullLink, err = filepath.Abs(fullLink); err != nil {
return err
}
if itOriginalPath, err = filepath.Rel(fullLink, itOriginalPath); err != nil {
return err
}
// TODO(marius): using filepath.Rel returns one extra parent for some reason, I need to look into why
itOriginalPath = strings.Replace(itOriginalPath, "../", "", 1)
if itOriginalPath == "." {
// NOTE(marius): if the relative path resolves to the current folder, we don't try to symlink
r.logger.Debugf("symlinking path resolved to the current directory: %s", itOriginalPath)
return nil
}
// NOTE(marius): we can't use hard links as we're linking to folders :(
// This would have been tremendously easier (as in, not having to compute paths) with hard-links.
if err = os.Symlink(itOriginalPath, fullLink); err != nil {
//_ = os.Remove(fullLink)
//err = os.Symlink(itOriginalPath, fullLink)
if !os.IsExist(err) {
r.logger.Debugf("unable to symlink to collection %s: %s", fullLink, err.Error())
}
}
return err
})
if err != nil {
return errors.Annotatef(err, "unable to symlink object into collection")
}
if orderedCollectionTypes.Contains(col.GetType()) {
err = vocab.OnOrderedCollection(col, func(c *vocab.OrderedCollection) error {
c.TotalItems += 1
c.OrderedItems = nil
return nil
})
} else if collectionTypes.Contains(col.GetType()) {
err = vocab.OnCollection(col, func(c *vocab.Collection) error {
c.TotalItems += 1
c.Items = nil
return nil
})
}
if _, err = save(r, col); err != nil {
return err
}
err = vocab.OnCollectionIntf(col, r.collectionBitmapOp((*roaring64.Bitmap).Add, it))
if err != nil && !errors.IsNotImplemented(err) {
r.logger.Debugf("unable to add item %s to collection index: %s", it.GetLink(), err)
}
return nil
}
// Delete
func (r *repo) Delete(it vocab.Item) error {
err := r.Open()
defer r.Close()
if err != nil {
return err
}
return r.delete(it)
}
func (r *repo) delete(it vocab.Item) error {
if it.IsCollection() {
return vocab.OnCollectionIntf(it, func(c vocab.CollectionInterface) error {
var err error
for _, it := range c.Collection() {
if err = deleteItem(r, it); err != nil {
r.logger.Debugf("Unable to remove item %s", it.GetLink())
}
}
return nil
})
}
return deleteItem(r, it.GetLink())
}
// PasswordSet
func (r *repo) PasswordSet(it vocab.Item, pw []byte) error {
pw, err := bcrypt.GenerateFromPassword(pw, -1)
if err != nil {
return errors.Annotatef(err, "could not generate pw hash")
}
m := processing.Metadata{
Pw: pw,
}
return r.SaveMetadata(m, it.GetLink())
}
// PasswordCheck
func (r *repo) PasswordCheck(it vocab.Item, pw []byte) error {
m, err := r.LoadMetadata(it.GetLink())
if err != nil {
return errors.Annotatef(err, "Could not find load metadata for %s", it)
}
if err := bcrypt.CompareHashAndPassword(m.Pw, pw); err != nil {
return errors.NewUnauthorized(err, "Invalid pw")
}
return err
}
// LoadMetadata
func (r *repo) LoadMetadata(iri vocab.IRI) (*processing.Metadata, error) {
err := r.Open()
defer r.Close()
if err != nil {
return nil, err
}
p := r.itemStoragePath(iri)
raw, err := loadRawFromPath(getMetadataKey(p))
if err != nil {
err = errors.NewNotFound(asPathErr(err, r.path), "Could not find metadata in path %s", sanitizePath(p, r.path))
return nil, err
}
m := new(processing.Metadata)
if err = decodeFn(raw, m); err != nil {
return nil, errors.Annotatef(err, "Could not unmarshal metadata")
}
return m, nil
}
// SaveMetadata
func (r *repo) SaveMetadata(m processing.Metadata, iri vocab.IRI) error {
err := r.Open()
defer r.Close()
if err != nil {
return err
}
p := getMetadataKey(r.itemStoragePath(iri))
f, err := createOrOpenFile(p)
if err != nil {
return err
}
defer f.Close()
entryBytes, err := encodeFn(m)
if err != nil {
return errors.Annotatef(err, "Could not marshal metadata")
}
wrote, err := f.Write(entryBytes)
if err != nil {
return errors.Annotatef(err, "could not store encoded object")
}
if wrote != len(entryBytes) {
return errors.Annotatef(err, "failed writing full object")
}
return nil
}
// LoadKey loads a private key for an actor found by its IRI
func (r *repo) LoadKey(iri vocab.IRI) (crypto.PrivateKey, error) {
m, err := r.LoadMetadata(iri)
if err != nil {
return nil, asPathErr(err, r.path)
}
b, _ := pem.Decode(m.PrivateKey)
if b == nil {
return nil, errors.Errorf("failed decoding pem")
}
prvKey, err := x509.ParsePKCS8PrivateKey(b.Bytes)
if err != nil {
return nil, err
}
return prvKey, nil
}
// SaveKey saves a private key for an actor found by its IRI
func (r *repo) SaveKey(iri vocab.IRI, key crypto.PrivateKey) (vocab.Item, error) {
ob, err := r.loadOneFromIRI(iri)
if err != nil {
return nil, err
}
typ := ob.GetType()
if !vocab.ActorTypes.Contains(typ) {
return ob, errors.Newf("trying to generate keys for invalid ActivityPub object type: %s", typ)
}
actor, err := vocab.ToActor(ob)
if err != nil {
return ob, errors.Newf("trying to generate keys for invalid ActivityPub object type: %s", typ)
}
m, err := r.LoadMetadata(iri)
if err != nil && !errors.IsNotFound(err) {
return ob, err
}
if m != nil && m.PrivateKey != nil {
r.logger.Debugf("actor %s already has a private key", iri)
}
m = new(processing.Metadata)
prvEnc, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
r.logger.Errorf("unable to x509.MarshalPKCS8PrivateKey() the private key %T for %s", key, iri)
return ob, err
}
m.PrivateKey = pem.EncodeToMemory(&pem.Block{
Type: "PRIVATE KEY",
Bytes: prvEnc,
})
if err = r.SaveMetadata(*m, iri); err != nil {
r.logger.Errorf("unable to save the private key %T for %s", key, iri)
return ob, err
}
var pub crypto.PublicKey
switch prv := key.(type) {
case *ecdsa.PrivateKey:
pub = prv.Public()
case *rsa.PrivateKey:
pub = prv.Public()
case *dsa.PrivateKey:
pub = &prv.PublicKey
case *ed25519.PrivateKey:
pub = prv.Public()
default:
r.logger.Errorf("received key %T does not match any of the known private key types", key)
return ob, nil
}
pubEnc, err := x509.MarshalPKIXPublicKey(pub)
if err != nil {
r.logger.Errorf("unable to x509.MarshalPKIXPublicKey() the private key %T for %s", pub, iri)
return ob, err
}
pubEncoded := pem.EncodeToMemory(&pem.Block{
Type: "PUBLIC KEY",
Bytes: pubEnc,
})
actor.PublicKey = vocab.PublicKey{
ID: vocab.IRI(fmt.Sprintf("%s#main", iri)),
Owner: iri,
PublicKeyPem: string(pubEncoded),
}
return r.Save(actor)
}
// GenKey creates and saves a private key for an actor found by its IRI
func (r *repo) GenKey(iri vocab.IRI) error {
ob, err := r.loadOneFromIRI(iri)
if err != nil {
return err
}
if ob.GetType() != vocab.PersonType {
return errors.Newf("trying to generate keys for invalid ActivityPub object type: %s", ob.GetType())
}
m, err := r.LoadMetadata(iri)
if err != nil && !errors.IsNotFound(err) {
return err
}
if m.PrivateKey != nil {
return nil
}
// TODO(marius): this needs a way to choose between ED25519 and RSA keys
pubB, prvB := generateECKeyPair()
m.PrivateKey = pem.EncodeToMemory(&prvB)
if err = r.SaveMetadata(*m, iri); err != nil {
return err
}
vocab.OnActor(ob, func(act *vocab.Actor) error {
act.PublicKey = vocab.PublicKey{
ID: vocab.IRI(fmt.Sprintf("%s#main", iri)),
Owner: iri,
PublicKeyPem: string(pem.EncodeToMemory(&pubB)),
}
return nil
})
return nil
}
func generateECKeyPair() (pem.Block, pem.Block) {
// TODO(marius): make this actually produce proper keys
keyPub, keyPrv, _ := ed25519.GenerateKey(rand.New(rand.NewSource(6667)))
var p, r pem.Block
if pubEnc, err := x509.MarshalPKIXPublicKey(keyPub); err == nil {
p = pem.Block{
Type: "PUBLIC KEY",
Bytes: pubEnc,
}
}
if prvEnc, err := x509.MarshalPKCS8PrivateKey(keyPrv); err == nil {
r = pem.Block{
Type: "PRIVATE KEY",
Bytes: prvEnc,
}
}
return p, r
}
func createOrOpenFile(p string) (*os.File, error) {
err := mkDirIfNotExists(path.Dir(p))
if err != nil {
return nil, err
}
return os.OpenFile(p, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
}
var storageCollectionPaths = append(filters.FedBOXCollections, append(vocab.OfActor, vocab.OfObject...)...)
func isStorageCollectionKey(p string) bool {
lst := vocab.CollectionPath(filepath.Base(p))
return storageCollectionPaths.Contains(lst)
}
func isHiddenCollectionKey(p string) bool {
lst := vocab.CollectionPath(filepath.Base(p))
return filters.HiddenCollections.Contains(lst)
}
func (r *repo) itemStoragePath(iri vocab.IRI) string {
return filepath.Join(r.path, iriPath(iri))
}
// createCollections
// FIXME(marius): this seems to be quite slow... INVESTIGATE!!!
func createCollections(r *repo, it vocab.Item) error {
if vocab.IsNil(it) || !it.IsObject() {
return nil
}
if vocab.ActorTypes.Contains(it.GetType()) {
_ = vocab.OnActor(it, func(p *vocab.Actor) error {
p.Inbox, _ = createCollectionInPath(r, p.Inbox)
p.Outbox, _ = createCollectionInPath(r, p.Outbox)
p.Followers, _ = createCollectionInPath(r, p.Followers)
p.Following, _ = createCollectionInPath(r, p.Following)
p.Liked, _ = createCollectionInPath(r, p.Liked)
// NOTE(marius): shadow creating hidden collections for Blocked and Ignored items
_, _ = createCollectionInPath(r, filters.BlockedType.Of(p))
_, _ = createCollectionInPath(r, filters.IgnoredType.Of(p))
return nil
})
}
return vocab.OnObject(it, func(o *vocab.Object) error {
o.Replies, _ = createCollectionInPath(r, o.Replies)
o.Likes, _ = createCollectionInPath(r, o.Likes)
o.Shares, _ = createCollectionInPath(r, o.Shares)
return nil
})
}
const (
objectKey = "__raw"
metaDataKey = "__meta_data"
)
func getMetadataKey(p string) string {
return path.Join(p, metaDataKey)
}
func getObjectKey(p string) string {
return path.Join(p, objectKey)
}
func createCollectionInPath(r *repo, it vocab.Item) (vocab.Item, error) {
if vocab.IsNil(it) {
return nil, nil
}
itPath := r.itemStoragePath(it.GetLink())
colObject, err := r.loadItemFromPath(getObjectKey(itPath))
if colObject == nil {
it, err = createCollection(r, it.GetLink())
}
if err != nil {
return nil, errors.Annotatef(err, "saving collection object is not done")
}
return it.GetLink(), asPathErr(mkDirIfNotExists(itPath), r.path)
}
func deleteCollectionFromPath(r repo, it vocab.Item) error {
if vocab.IsNil(it) {
return nil
}
itPath := r.itemStoragePath(it.GetLink())
if fi, err := os.Stat(itPath); err != nil {
if !os.IsNotExist(err) {
return errors.NewNotFound(asPathErr(err, r.path), "not found")
}
} else if fi.IsDir() {
return os.Remove(itPath)
}
r.removeFromCache(it.GetLink())
return nil
}
func (r *repo) removeFromCache(iri vocab.IRI) {
if r.cache == nil {
return
}
r.cache.Delete(iri.GetLink())
}
// deleteCollections
func deleteCollections(r repo, it vocab.Item) error {
if vocab.ActorTypes.Contains(it.GetType()) {
return vocab.OnActor(it, func(p *vocab.Actor) error {
// NOTE(marius): deleting the hidden collections for Blocked and Ignored items
_ = deleteCollectionFromPath(r, filters.BlockedType.Of(p))
_ = deleteCollectionFromPath(r, filters.IgnoredType.Of(p))
var err error
err = deleteCollectionFromPath(r, vocab.Inbox.IRI(p))
err = deleteCollectionFromPath(r, vocab.Outbox.IRI(p))
err = deleteCollectionFromPath(r, vocab.Followers.IRI(p))
err = deleteCollectionFromPath(r, vocab.Following.IRI(p))
err = deleteCollectionFromPath(r, vocab.Liked.IRI(p))
return err
})
}
if vocab.ObjectTypes.Contains(it.GetType()) {
return vocab.OnObject(it, func(o *vocab.Object) error {
var err error
err = deleteCollectionFromPath(r, vocab.Replies.IRI(o))
err = deleteCollectionFromPath(r, vocab.Likes.IRI(o))
err = deleteCollectionFromPath(r, vocab.Shares.IRI(o))
return err
})
}
return nil
}
func getAbsStoragePath(p string) (string, error) {
if !filepath.IsAbs(p) {
var err error
p, err = filepath.Abs(p)
if err != nil {
return "", err
}
}
if fi, err := os.Stat(p); err != nil {
return "", err
} else if !fi.IsDir() {
return "", errors.NotValidf("path %s is invalid for storage", p)
}
return p, nil
}
func deleteItem(r *repo, it vocab.Item) error {
itemPath := r.itemStoragePath(it.GetLink())
if err := os.RemoveAll(itemPath); err != nil {
return err
}
r.removeFromCache(it.GetLink())
return nil
}
func save(r *repo, it vocab.Item) (vocab.Item, error) {
if err := createCollections(r, it); err != nil {
return it, errors.Annotatef(err, "could not create object's collections")
}
_ = loadIndex(r)
defer func() {
_ = saveIndex(r)
}()
writeSingleObjFn := func(it vocab.Item) (vocab.Item, error) {
itPath := r.itemStoragePath(it.GetLink())
_ = mkDirIfNotExists(itPath)
entryBytes, err := encodeItemFn(it)
if err != nil {
return it, errors.Annotatef(err, "could not marshal object")
}
if err := mkDirIfNotExists(itPath); err != nil {
r.logger.Errorf("unable to create path: %s, %s", itPath, err)
return it, errors.Annotatef(err, "could not create file")
}
objPath := getObjectKey(itPath)
f, err := os.OpenFile(objPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
r.logger.Errorf("%s not found", objPath)
return it, errors.NewNotFound(asPathErr(err, r.path), "not found")
}
defer func() {
if err := f.Close(); err != nil {
r.logger.Errorf("Unable to close file: %s", err)
}
}()
wrote, err := f.Write(entryBytes)
if err != nil {
return it, errors.Annotatef(err, "could not store encoded object")
}
if wrote != len(entryBytes) {
return it, errors.Annotatef(err, "failed writing object")
}
if err = r.addToIndex(it, itPath); err != nil && !errors.IsNotImplemented(err) {
r.logger.Errorf("unable to add item %s to index: %s", it.GetLink(), err)
}
r.setToCache(it)
return it, nil
}
if vocab.IsItemCollection(it) {
err := vocab.OnItemCollection(it, func(col *vocab.ItemCollection) error {
m := make([]error, 0)
for i, ob := range *col {
saved, err := writeSingleObjFn(ob)
if err == nil {
(*col)[i] = saved
} else {
m = append(m, err)
}
}
if len(m) > 0 {
return xerrors.Join(m...)
}
return nil
})
return it, err
}
return writeSingleObjFn(it)
}
func onCollection(r *repo, col vocab.Item, it vocab.Item, fn func(p string) error) error {
if vocab.IsNil(it) {
return errors.Newf("Unable to operate on nil element")
}
if len(col.GetLink()) == 0 {
return errors.Newf("Unable to find collection")
}
if len(it.GetLink()) == 0 {
return errors.Newf("Invalid collection, it does not have a valid IRI")
}
itPath := r.itemStoragePath(col.GetLink())
if err := fn(itPath); err != nil {
if os.IsExist(err) {
return errors.NewConflict(err, "%s already exists in collection %s", it.GetID(), itPath)
}
return errors.Annotatef(err, "Unable to save entries to collection %s", itPath)
}
r.removeFromCache(col.GetLink())
return nil
}
func loadRawFromPath(itPath string) ([]byte, error) {
return os.ReadFile(itPath)
}
func loadFromRaw(raw []byte) (vocab.Item, error) {
if raw == nil || len(raw) == 0 {
// TODO(marius): log this instead of stopping the iteration and returning an error
return nil, errors.Errorf("empty raw item")
}
return decodeItemFn(raw)
}
func (r *repo) loadOneFromIRI(i vocab.IRI) (vocab.Item, error) {
col, err := r.loadItemFromPath(getObjectKey(r.itemStoragePath(i)))
if err != nil {
return nil, err
}
if col == nil {
return nil, errors.NotFoundf("nothing found")
}
if vocab.IsIRI(col) {
return nil, errors.Conflictf("%s could not be loaded from disk", col)
}
if col.IsCollection() {
var result vocab.Item
_ = vocab.OnCollectionIntf(col, func(col vocab.CollectionInterface) error {
result = col.Collection().First()
return nil
})
if vocab.IsIRI(result) && result.GetLink().Equals(i.GetLink(), false) {
// NOTE(marius): this covers the case where we ended up with the same IRI
return nil, errors.NotFoundf("nothing found")
}
return result, nil
}
return col, nil
}
func loadFilteredPropsForActor(r *repo, fil ...filters.Check) func(a *vocab.Actor) error {
return func(a *vocab.Actor) error {
return vocab.OnObject(a, loadFilteredPropsForObject(r, fil...))
}
}
func loadFilteredPropsForObject(r *repo, fil ...filters.Check) func(o *vocab.Object) error {
return func(o *vocab.Object) error {
if len(o.Tag) == 0 {
return nil
}
return vocab.OnItemCollection(o.Tag, func(col *vocab.ItemCollection) error {
for i, t := range *col {
if vocab.IsNil(t) || !vocab.IsIRI(t) {
return nil
}
ob, err := r.loadItemFromPath(getObjectKey(r.itemStoragePath(t.GetLink())))
if err != nil {
continue
}
if ob = filters.TagChecks(fil...).Run(ob); ob == nil {
continue
}
(*col)[i] = ob
}
return nil
})
}
}
func dereferenceItemAndFilter(r *repo, ob vocab.Item, fil ...filters.Check) (vocab.Item, error) {
if vocab.IsNil(ob) {
return ob, nil
}
if !vocab.IsIRI(ob) {
return ob, nil
}
itPath := r.itemStoragePath(ob.GetLink())
o, err := r.loadItemFromPath(getObjectKey(itPath), fil...)
if err != nil {
return ob, nil
}
return o, nil
}
func loadFilteredPropsForActivity(r *repo, fil ...filters.Check) func(a *vocab.Activity) error {
objectChecks := filters.ObjectChecks(fil...)
return func(a *vocab.Activity) error {
var err error
if !vocab.IsNil(a.Object) {
if a.ID.Equals(a.Object.GetLink(), false) {
//r.logger.Debugf("Invalid %s activity (probably from mastodon), that overwrote the original actor. (%s)", a.Type, a.ID)
return errors.BadGatewayf("invalid activity with id %s, referencing itself as an object: %s", a.ID, a.Object.GetLink())
}
if a.Object, err = dereferenceItemAndFilter(r, a.Object, objectChecks...); err != nil {
return err
}
}
intransitiveChecks := filters.IntransitiveActivityChecks(fil...)
return vocab.OnIntransitiveActivity(a, loadFilteredPropsForIntransitiveActivity(r, intransitiveChecks...))
}
}
func loadFilteredPropsForIntransitiveActivity(r *repo, fil ...filters.Check) func(a *vocab.IntransitiveActivity) error {
//actorChecks := filters.ActorChecks(fil...)
targetChecks := filters.TargetChecks(fil...)
return func(a *vocab.IntransitiveActivity) error {
var err error
//if !vocab.IsNil(a.Actor) {
// if a.ID.Equals(a.Actor.GetLink(), false) {
// //r.logger.Debugf("Invalid %s activity (probably from mastodon), that overwrote the original actor. (%s)", a.Type, a.ID)
// return errors.BadGatewayf("invalid activity with id %s, referencing itself as an actor: %s", a.ID, a.Actor.GetLink())
// }
// if a.Actor, err = dereferenceItemAndFilter(r, a.Actor, actorChecks...); err != nil {