1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
16
17 package serverinit
18
19 import (
20 "context"
21 "errors"
22 "fmt"
23 "log"
24 "strings"
25
26 "perkeep.org/pkg/blob"
27 "perkeep.org/pkg/blobserver"
28 "perkeep.org/pkg/env"
29 "perkeep.org/pkg/jsonsign/signhandler"
30 "perkeep.org/pkg/schema"
31 "perkeep.org/pkg/search"
32 "perkeep.org/pkg/server/app"
33 )
34
35 func (hl *handlerLoader) initPublisherRootNode(ah *app.Handler) error {
36 if !env.IsDev() {
37 return nil
38 }
39
40 h, err := hl.GetHandler("/my-search/")
41 if err != nil {
42 return err
43 }
44 sh := h.(*search.Handler)
45 camliRootQuery := func(camliRoot string) (*search.SearchResult, error) {
46 return sh.Query(context.TODO(), &search.SearchQuery{
47 Limit: 1,
48 Constraint: &search.Constraint{
49 Permanode: &search.PermanodeConstraint{
50 Attr: "camliRoot",
51 Value: camliRoot,
52 },
53 },
54 })
55 }
56
57 appConfig := ah.AppConfig()
58 if appConfig == nil {
59 return errors.New("publisher app handler has no AppConfig")
60 }
61 camliRoot, ok := appConfig["camliRoot"].(string)
62 if !ok {
63 return fmt.Errorf("camliRoot in publisher app handler appConfig is %T, want string", appConfig["camliRoot"])
64 }
65 result, err := camliRootQuery(camliRoot)
66 if err == nil && len(result.Blobs) > 0 && result.Blobs[0].Blob.Valid() {
67
68 log.Printf("Found %v camliRoot node for publisher: %v", camliRoot, result.Blobs[0].Blob.String())
69 return nil
70 }
71
72 log.Printf("No %v camliRoot node found, creating one from scratch now.", camliRoot)
73
74 bs, err := hl.GetStorage("/bs-recv/")
75 if err != nil {
76 return err
77 }
78 h, err = hl.GetHandler("/sighelper/")
79 if err != nil {
80 return err
81 }
82 sigh := h.(*signhandler.Handler)
83
84 ctx := context.TODO()
85 signUpload := func(bb *schema.Builder) (blob.Ref, error) {
86 signed, err := sigh.Sign(ctx, bb)
87 if err != nil {
88 return blob.Ref{}, fmt.Errorf("could not sign blob: %v", err)
89 }
90 br := blob.RefFromString(signed)
91 if _, err := blobserver.Receive(ctx, bs, br, strings.NewReader(signed)); err != nil {
92 return blob.Ref{}, fmt.Errorf("could not upload %v: %v", br.String(), err)
93 }
94 return br, nil
95 }
96
97 pn, err := signUpload(schema.NewUnsignedPermanode())
98 if err != nil {
99 return fmt.Errorf("could not create new camliRoot node: %v", err)
100 }
101 if _, err := signUpload(schema.NewSetAttributeClaim(pn, "camliRoot", camliRoot)); err != nil {
102 return fmt.Errorf("could not set camliRoot on new node %v: %v", pn, err)
103 }
104 if _, err := signUpload(schema.NewSetAttributeClaim(pn, "title", "Publish root node for "+camliRoot)); err != nil {
105 return fmt.Errorf("could not set camliRoot on new node %v: %v", pn, err)
106 }
107 return nil
108 }