summaryrefslogtreecommitdiffstats
path: root/api/web_hub.go
blob: 5fe9d6ae8d9dfaab0b39d2c38ec40d374f6bade1 (plain)
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
// Copyright (c) 2015 Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package api

import (
	l4g "github.com/alecthomas/log4go"
	"github.com/mattermost/platform/model"
	"github.com/mattermost/platform/utils"
)

type Hub struct {
	teamHubs   map[string]*TeamHub
	register   chan *WebConn
	unregister chan *WebConn
	broadcast  chan *model.Message
	stop       chan string
}

var hub = &Hub{
	register:   make(chan *WebConn),
	unregister: make(chan *WebConn),
	teamHubs:   make(map[string]*TeamHub),
	broadcast:  make(chan *model.Message),
	stop:       make(chan string),
}

func PublishAndForget(message *model.Message) {
	go func() {
		hub.Broadcast(message)
	}()
}

func UpdateChannelAccessCache(teamId, userId, channelId string) {
	if nh, ok := hub.teamHubs[teamId]; ok {
		nh.UpdateChannelAccessCache(userId, channelId)
	}
}

func UpdateChannelAccessCacheAndForget(teamId, userId, channelId string) {
	go func() {
		UpdateChannelAccessCache(teamId, userId, channelId)
	}()
}

func (h *Hub) Register(webConn *WebConn) {
	h.register <- webConn
}

func (h *Hub) Unregister(webConn *WebConn) {
	h.unregister <- webConn
}

func (h *Hub) Broadcast(message *model.Message) {
	if message != nil {
		h.broadcast <- message
	}
}

func (h *Hub) Stop() {
	h.stop <- "all"
}

func (h *Hub) Start() {
	go func() {
		for {
			select {

			case c := <-h.register:
				nh := h.teamHubs[c.TeamId]

				if nh == nil {
					nh = NewTeamHub(c.TeamId)
					h.teamHubs[c.TeamId] = nh
					nh.Start()
				}

				nh.Register(c)

			case c := <-h.unregister:
				if nh, ok := h.teamHubs[c.TeamId]; ok {
					nh.Unregister(c)
				}
			case msg := <-h.broadcast:
				nh := h.teamHubs[msg.TeamId]
				if nh != nil {
					nh.broadcast <- msg
				}
			case s := <-h.stop:
				l4g.Debug(utils.T("api.web_hub.start.stopping.debug"), s)
				for _, v := range h.teamHubs {
					v.Stop()
				}
				return
			}
		}
	}()
}