forked from cryptix/gobotexample
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.go
291 lines (240 loc) · 6.14 KB
/
bot.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
//go:generate go-mobile-collection $GOFILE
package gobotexample
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"sync"
"time"
"github.com/cryptix/go/logging"
"github.com/pkg/errors"
"go.cryptoscope.co/luigi"
"go.cryptoscope.co/margaret"
"go.cryptoscope.co/margaret/multilog"
"go.cryptoscope.co/netwrap"
"go.cryptoscope.co/secretstream"
"go.cryptoscope.co/ssb"
"go.cryptoscope.co/ssb/multilogs"
"go.cryptoscope.co/ssb/repo"
mksbot "go.cryptoscope.co/ssb/sbot"
"github.com/pietgeursen/gobotexample/internal/multiserver"
)
var (
// helper
log logging.Interface
checkFatal = logging.CheckFatal
// juicy bits
appKey string = "1KHLiKZvAvjbY1ziZEHMXawbCEIM6qwjCDm3VYRan/s="
hmacSec string
runningLock sync.Mutex
theBot *mksbot.Sbot
)
func checkAndLog(err error) {
if err != nil {
panic(err)
}
}
var ErrNotInitialized = errors.New("gobot: not initialized")
//How much is checked by the stack if a not json string gets passed?
func Publish(message string) error {
var v interface{}
err := json.Unmarshal([]byte(message), &v)
if err != nil {
return errors.Wrap(err, "publish: invalid json input")
}
_, err = theBot.PublishLog.Publish(v)
return err
}
func CurrentMessageCount() (int64, error) {
runningLock.Lock()
if theBot == nil {
runningLock.Unlock()
return -2, ErrNotInitialized
}
runningLock.Unlock()
v, err := theBot.RootLog.Seq().Value()
if err != nil {
return -2, errors.Wrap(err, "query creation failed")
}
seq := v.(margaret.Seq)
return seq.Seq(), nil
}
type MessageWithRootSeq struct {
ssb.KeyValueRaw
RootSeq int64 `json:"seqField"`
}
func PullMessages(last, limit int) ([]byte, error) {
runningLock.Lock()
if theBot == nil {
runningLock.Unlock()
return nil, ErrNotInitialized
}
runningLock.Unlock()
src, err := theBot.RootLog.Query(
margaret.Gte(margaret.BaseSeq(last)),
margaret.Limit(limit),
margaret.SeqWrap(true))
if err != nil {
return nil, errors.Wrap(err, "query creation failed")
}
w := &bytes.Buffer{}
i := 0
fmt.Fprint(w, "[")
for {
v, err := src.Next(context.Background())
if err != nil {
if luigi.IsEOS(err) {
fmt.Fprint(w, "]")
break
}
return nil, errors.Wrapf(err, "drainLog: failed to drain log msg:%d", i)
}
if i > 0 {
fmt.Fprint(w, ",")
}
sw, ok := v.(margaret.SeqWrapper)
if !ok {
return nil, errors.Errorf("publish: unexpected message type: %T", v)
}
storedMsg, ok := sw.Value().(ssb.Message)
if !ok {
return nil, errors.Errorf("publish: unexpected message type: %T", v)
}
msgValue := storedMsg.ValueContent()
var msg MessageWithRootSeq
msg.RootSeq = sw.Seq().Seq()
msg.Key_ = storedMsg.Key()
msg.Value = *msgValue
if err := json.NewEncoder(w).Encode(msg); err != nil {
return nil, errors.Wrapf(err, "drainLog: failed to k:v map message %d", i)
}
i++
}
return w.Bytes(), nil
}
func WhoAmI() string {
return theBot.KeyPair.Id.Ref()
}
func GossipConnect(multiserveraddress string) error {
runningLock.Lock()
if theBot == nil {
runningLock.Unlock()
return ErrNotInitialized
}
runningLock.Unlock()
msaddr, err := multiserver.ParseNetAddress([]byte(multiserveraddress))
if err != nil {
return errors.Wrapf(err, "gossip.connect call: failed to parse input")
}
wrappedAddr := netwrap.WrapAddr(&msaddr.Addr, secretstream.Addr{PubKey: msaddr.Ref.ID})
fmt.Println("doing gossip.connect", wrappedAddr.String())
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(15 * time.Minute)
cancel()
}()
err = theBot.Network.Connect(ctx, wrappedAddr)
return errors.Wrapf(err, "gossip.connect call: error connecting to %q", msaddr.Addr)
}
func BlobsWant(blobref string) {
br, err := ssb.ParseBlobRef(blobref)
if err != nil {
log.Log("blobsWant", "failed to parse reference", "ref", blobref, "err", err)
return
}
err = theBot.WantManager.Want(br)
if err != nil {
log.Log("blobsWant", "failed add want to local peer", "ref", blobref, "err", err)
return
}
}
func BlobsRemove() {}
func BlobsList() {}
func BlobsHas() {}
func BlobsAdd(blob []byte) (string, error) {
r := bytes.NewReader(blob)
ref, err := theBot.BlobStore.Put(r)
if err != nil {
return "", err
}
return ref.Ref(), nil
}
func BlobsGet(refStr string) ([]byte, error) {
ref, err := ssb.ParseBlobRef(refStr)
if err != nil {
return nil, err
}
r, err := theBot.BlobStore.Get(ref)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(r)
if err != nil {
return nil, err
}
var slice = buf.Bytes()
return slice, nil
}
func Peers() ([]byte, error){
w := &bytes.Buffer{}
status, err := theBot.Status()
if err != nil {
return nil, err
}
var peers = status.Peers
// Apparently peers can be null and that's painful for converting to json and back
// If peers is null then set it to an empty list.
if peers == nil {
peers = []ssb.PeerStatus{}
}
if err := json.NewEncoder(w).Encode(peers); err != nil {
return nil, err
}
return w.Bytes(), nil
}
func Stop() error {
theBot.Shutdown()
return theBot.Close()
}
// use old badger implementation for now
func openBadgerUserFeeds(r repo.Interface) (multilog.MultiLog, repo.ServeFunc, error) {
return repo.OpenBadgerMultiLog(r, "userFeeds", multilogs.UserFeedsUpdate)
}
func Start(repoPath string) {
logging.SetupLogging(os.Stderr)
log = logging.Logger("sbot")
ctx := context.Background()
ak, err := base64.StdEncoding.DecodeString(appKey)
checkFatal(err)
listenAddr := ":8008"
theBot, err = mksbot.New(
mksbot.WithInfo(log),
mksbot.WithAppKey(ak),
mksbot.WithRepoPath(repoPath),
mksbot.WithListenAddr(listenAddr),
mksbot.EnableAdvertismentBroadcasts(true),
mksbot.EnableAdvertismentDialing(true),
//mksbot.LateOption(mksbot.MountMultiLog("userFeeds", openBadgerUserFeeds)),
)
checkFatal(err)
id := theBot.KeyPair.Id
checkFatal(err)
log.Log("event", "serving", "ID", id.Ref(), "addr", listenAddr)
go func() {
for {
// Note: This is where the serving starts ;)
err = theBot.Network.Serve(ctx)
log.Log("event", "sbot node.Serve returned, restarting..", "err", err)
time.Sleep(1 * time.Second)
select {
case <-ctx.Done():
os.Exit(0)
default:
}
}
}()
}