forked from boramalper/magnetico
/
zeromq.go
58 lines (51 loc) · 1.29 KB
/
zeromq.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
package persistence
import (
"encoding/hex"
"encoding/json"
"github.com/patrickmn/go-cache"
"github.com/pkg/errors"
zmq "github.com/zeromq/goczmq"
"go.uber.org/zap"
"time"
)
type zeromq struct {
context *zmq.Sock
cache *cache.Cache
}
func makeZeroMQ() (Database, error) {
instance := new(zeromq)
context, err := zmq.NewPub("tcp://0.0.0.0:2222")
if err != nil {
return nil, err
}
instance.context = context
instance.cache = cache.New(5*time.Minute, 10*time.Minute)
return instance, nil
}
func (instance *zeromq) Engine() databaseEngine {
return ZeroMQ
}
func (instance *zeromq) DoesTorrentExist(infoHash []byte) (bool, error) {
_, found := instance.cache.Get(string(infoHash))
return found, nil
}
func (instance *zeromq) AddNewTorrent(infoHash []byte, name string, files []File) error {
data, err := json.Marshal(SimpleTorrentSummary{
InfoHash: hex.EncodeToString(infoHash),
Name: name,
Files: files,
})
if err != nil {
return errors.Wrap(err, "Failed to encode metadata")
}
err = instance.context.SendMessage([][]byte{data})
if err != nil {
return errors.Wrap(err, "Failed to transmit")
}
instance.cache.Set(string(infoHash), data, cache.DefaultExpiration)
zap.L().Debug(string(data))
return nil
}
func (instance *zeromq) Close() {
instance.context.Destroy()
}