This repository was archived by the owner on Jun 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsubdb.go
91 lines (76 loc) · 1.88 KB
/
subdb.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
package emuarius
import (
"encoding/json"
"log"
"strings"
"time"
"github.com/boltdb/bolt"
"github.com/emersion/go-ostatus/pubsubhubbub"
)
var subscriptionsBucket = []byte("subscriptions")
type subscriptionData struct {
Secret string `json:"secret"`
LeaseEnd time.Time `json:"lease_end"`
}
func subscriptionToKey(topicURL, callbackURL string) []byte {
return []byte(topicURL + " " + callbackURL)
}
func keyToSubscription(k []byte) (topicURL, callbackURL string) {
parts := strings.SplitN(string(k), " ", 2)
if len(parts) == 2 {
topicURL, callbackURL = parts[0], parts[1]
}
return
}
func NewSubscriptionDB(p *pubsubhubbub.Publisher, db *bolt.DB) error {
// Restore old subscriptions
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(subscriptionsBucket)
if b == nil {
return nil
}
return b.ForEach(func(k, v []byte) error {
topicURL, callbackURL := keyToSubscription(k)
s := new(subscriptionData)
if err := json.Unmarshal(v, s); err != nil {
return err
}
if s.LeaseEnd.Before(time.Now()) {
return b.Delete(k)
}
return p.Register(topicURL, callbackURL, s.Secret, s.LeaseEnd)
})
})
if err != nil {
return err
}
// Save new subscriptions
p.SubscriptionState = func(topicURL, callbackURL, secret string, leaseEnd time.Time) {
err := db.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists(subscriptionsBucket)
if err != nil {
return err
}
k := subscriptionToKey(topicURL, callbackURL)
if !leaseEnd.IsZero() {
s := &subscriptionData{Secret: secret, LeaseEnd: leaseEnd}
v, err := json.Marshal(s)
if err != nil {
return err
}
if err := b.Put(k, v); err != nil {
return err
}
} else {
if err := b.Delete(k); err != nil {
return err
}
}
return nil
})
if err != nil {
log.Println("emuarius: cannot save subscription:", err)
}
}
return nil
}