summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/sromku/go-gitter/faye.go
blob: dcd3e210d30f6373f4b7d6ec60408b85d99b5dc7 (plain) (blame)
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
package gitter

import (
	"encoding/json"
	"fmt"

	"github.com/mrexodia/wray"
)

type Faye struct {
	endpoint string
	Event    chan Event
	client   *wray.FayeClient
	gitter   *Gitter
}

func (gitter *Gitter) Faye(roomID string) *Faye {
	wray.RegisterTransports([]wray.Transport{
		&wray.HttpTransport{
			SendHook: func(data map[string]interface{}) {
				if channel, ok := data["channel"]; ok && channel == "/meta/handshake" {
					data["ext"] = map[string]interface{}{"token": gitter.config.token}
				}
			},
		},
	})
	return &Faye{
		endpoint: "/api/v1/rooms/" + roomID + "/chatMessages",
		Event:    make(chan Event),
		client:   wray.NewFayeClient(fayeBaseURL),
		gitter:   gitter,
	}
}

func (faye *Faye) Listen() {
	defer faye.destroy()

	faye.client.Subscribe(faye.endpoint, false, func(message wray.Message) {
		dataBytes, err := json.Marshal(message.Data["model"])
		if err != nil {
			fmt.Printf("JSON Marshal error: %v\n", err)
			return
		}
		var gitterMessage Message
		err = json.Unmarshal(dataBytes, &gitterMessage)
		if err != nil {
			fmt.Printf("JSON Unmarshal error: %v\n", err)
			return
		}
		faye.Event <- Event{
			Data: &MessageReceived{
				Message: gitterMessage,
			},
		}
	})

	//TODO: this might be needed in the future
	/*go func() {
		for {
			faye.client.Publish("/api/v1/ping2", map[string]interface{}{"reason": "ping"})
			time.Sleep(60 * time.Second)
		}
	}()*/

	faye.client.Listen()
}

func (faye *Faye) destroy() {
	close(faye.Event)
}