message.go 1.82 KB
Newer Older
1
package dht_pb
2

Jeromy's avatar
Jeromy committed
3
import (
4 5
	"errors"

6
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
7
	ma "github.com/jbenet/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
Jeromy's avatar
Jeromy committed
8 9 10
	peer "github.com/jbenet/go-ipfs/peer"
)

11
func NewMessage(typ Message_MessageType, key string, level int) *Message {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
12 13 14 15 16 17 18 19
	m := &Message{
		Type: &typ,
		Key:  &key,
	}
	m.SetClusterLevel(level)
	return m
}

20
func peerToPBPeer(p peer.Peer) *Message_Peer {
21
	pbp := new(Message_Peer)
22 23
	addrs := p.Addresses()
	if len(addrs) == 0 || addrs[0] == nil {
Jeromy's avatar
Jeromy committed
24 25
		pbp.Addr = proto.String("")
	} else {
26
		addr := addrs[0].String()
Jeromy's avatar
Jeromy committed
27
		pbp.Addr = &addr
Jeromy's avatar
Jeromy committed
28
	}
29
	pid := string(p.ID())
Jeromy's avatar
Jeromy committed
30 31
	pbp.Id = &pid
	return pbp
32 33
}

34
func PeersToPBPeers(peers []peer.Peer) []*Message_Peer {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
35
	pbpeers := make([]*Message_Peer, len(peers))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
36 37 38 39 40 41
	for i, p := range peers {
		pbpeers[i] = peerToPBPeer(p)
	}
	return pbpeers
}

42 43 44 45 46 47 48 49
// Address returns a multiaddr associated with the Message_Peer entry
func (m *Message_Peer) Address() (ma.Multiaddr, error) {
	if m == nil {
		return nil, errors.New("MessagePeer is nil")
	}
	return ma.NewMultiaddr(*m.Addr)
}

50 51 52
// GetClusterLevel gets and adjusts the cluster level on the message.
// a +/- 1 adjustment is needed to distinguish a valid first level (1) and
// default "no value" protobuf behavior (0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53
func (m *Message) GetClusterLevel() int {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
54 55
	level := m.GetClusterLevelRaw() - 1
	if level < 0 {
56
		return 0
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
57
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
58
	return int(level)
59
}
60

61 62 63
// SetClusterLevel adjusts and sets the cluster level on the message.
// a +/- 1 adjustment is needed to distinguish a valid first level (1) and
// default "no value" protobuf behavior (0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
64 65 66
func (m *Message) SetClusterLevel(level int) {
	lvl := int32(level)
	m.ClusterLevelRaw = &lvl
67
}
68 69 70 71 72 73 74 75

func (m *Message) Loggable() map[string]interface{} {
	return map[string]interface{}{
		"message": map[string]string{
			"type": m.Type.String(),
		},
	}
}