예제 #1
0
func handleChangeNotification(socket *websocket.Conn, userID string, err chan string) {
	res, errr := r.Table("notifications").
		Filter(r.Row.Field("UserId").
			Eq(userID)).
		Changes().
		Run(api.Sess)

	var value HandleChange
	if errr != nil {
		err <- errr.Error()
	}
	for res.Next(&value) {
		var notif api.Notification
		var simpleNotif api.WebSocketNotification

		mapstructure.Decode(value.NewVal, &notif)
		if notif.Id == "" {
			mapstructure.Decode(value.OldVal, &notif)
			simpleNotif.OldVal = true
		} else {
			simpleNotif.OldVal = false
		}
		simpleNotif.Title = "notification"
		simpleNotif.Type = notif.Type
		simpleNotif.Name = notif.Name
		simpleNotif.UserIdFrom = notif.UserIdFrom
		simpleNotif.IdLink = notif.IdLink
		simpleNotif.CreatedAt = notif.CreatedAt
		errr := socket.WriteJSON(simpleNotif)
		if errr != nil {
			err <- errr.Error()
		}
	}
}
예제 #2
0
파일: server.go 프로젝트: fgeller/rad
func streamResults(sock *websocket.Conn, params searchParams, limit int) {
	start := time.Now()
	count := 0
	results := make(chan searchResult)
	control := make(chan struct{}, 1)

	go find(results, control, params)
	for {
		res, ok := <-results
		if !ok {
			log.Printf("Finished request in %v\n", time.Since(start))
			return
		}

		count++
		log.Printf("Found result #%v after %v\n", count, time.Since(start))

		err := sock.WriteJSON(res)
		if err != nil {
			log.Printf("Error while writing result: %v\n", err)
			control <- struct{}{}
			return
		}

		if count >= limit {
			log.Printf("Finished request after hitting limit in %v\n", time.Since(start))
			control <- struct{}{}
			return
		}
	}
}
예제 #3
0
func subChannelEvent(c *websocket.Conn, channel string) {
	subChan := subChannel{Event: "addChannel", Channel: channel}
	err := c.WriteJSON(subChan)
	if err != nil {
		log.Printf("sub channel %s err :%s", channel, err)
	}
}
예제 #4
0
// writer runs in a goroutine for each connected WS client. It emits all message returned by the observer.
func writer(ws *websocket.Conn, a *ApiHandlers) {
	pingTicker := time.NewTicker(pingPeriod)
	s := a.getDBSubscriber()
	jww.INFO.Println("Opened WebSocket connection.")
	defer func(is *subscriber) {
		jww.INFO.Println("Closing WebSocket connection.")
		is.quitChan <- true
		pingTicker.Stop()
		ws.Close()
	}(s)

	for {
		select {
		case msg := <-s.bufChan:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteJSON(msg); err != nil {
				return
			}
		case <-pingTicker.C:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}
예제 #5
0
func messagePing(ws *websocket.Conn, vault *client) MessageHandler {
	return func(data map[string]interface{}) error {
		return ws.WriteJSON(&messagePingResponse{
			Pong: true,
		})
	}
}
예제 #6
0
파일: server.go 프로젝트: fgeller/rad
func streamStatus(sock *websocket.Conn) {
	installed := installedPacks()
	filteredInstalled := []shared.Pack{}
	available := availablePacks()

loopinstalled:
	for _, ip := range installed {
		for ai, ap := range available {
			if ip.Installing && ip.File == ap.File {
				available[ai].Installing = true
				continue loopinstalled
			}
		}
		filteredInstalled = append(filteredInstalled, ip)
	}

	info := StatusInfo{
		Packs: PackInfo{
			Installed: filteredInstalled,
			Available: available,
		},
		Version: global.buildVersion,
	}

	err := sock.WriteJSON(controlResponse{Typ: "StatusResponse", Data: info})
	if err != nil {
		log.Printf("Error while writing status info: %v\n", err)
		return
	}
}
예제 #7
0
func clientGetRequest(wsConn *websocket.Conn, action string) {

	messageMap := make(map[string]interface{})
	messageMap["action"] = action

	wsConn.WriteJSON(messageMap)
}
예제 #8
0
func clientDiffRequest(wsConn *websocket.Conn, session *mgo.Session) {

	// init client_diff_request
	response_map := make(map[string]interface{})
	response_map["action"] = "client_diff_request"

	// find syncable object uuids
	cb := session.DB("landline").C("SyncableObjects")
	var m_result []map[string]interface{}
	err := cb.Find(bson.M{}).All(&m_result)
	if err != nil {
		log.Println(err)
	} else {

		// objects that the clients knows, but the server may not
		object_uuids := make(map[string]interface{})

		// loop results
		for u, result := range m_result {
			_ = u
			object_uuids[result["uuid"].(string)] = result["time_modified_since_creation"]
		}
		response_map["object_uuids"] = object_uuids

		// send it over websocket
		wsConn.WriteJSON(response_map)

		log.Println("Wrote message:")
		jsonString, _ := json.Marshal(response_map)
		log.Println(string(jsonString))
	}
}
예제 #9
0
파일: main.go 프로젝트: comoyo/tributary
func commandUnsubscribeFromTreeState(conn *websocket.Conn, id string, message map[string]interface{}) {
	name, ok := stringProp(message, "name")
	if !ok {
		sendErrorMessage(conn, "No \"name\" property specified or not a string in UNSUBSCRIBE_FROM_TREE_STATE message")
		return
	}

	globalLock.Lock()
	defer globalLock.Unlock()

	_, ok = broadcasts[name]
	if !ok {
		sendErrorMessage(conn, fmt.Sprintf("Unknown broadcast: %v", name))
		return
	}

	listeners, ok := treeStateListeners[name]
	if !ok {
		return
	}

	delete(*listeners, id)

	conn.WriteJSON(struct {
		Command string `json:"command"`
	}{
		"UNSUBSCRIBE_FROM_TREE_STATE_RECEIVED",
	})
}
예제 #10
0
파일: main.go 프로젝트: comoyo/tributary
func sendErrorMessage(conn *websocket.Conn, message string) {
	log.Println(message)
	conn.WriteJSON(struct {
		Command string `json:"command"`
		Message string `json:"message"`
	}{"ERROR", message})
}
예제 #11
0
파일: main.go 프로젝트: comoyo/tributary
func commandSubscribeToTreeState(conn *websocket.Conn, id string, message map[string]interface{}) {
	name, ok := stringProp(message, "name")
	if !ok {
		sendErrorMessage(conn, "No \"name\" property specified or not a string in SUBSCRIBE_TO_TREE_STATE message")
		return
	}

	globalLock.Lock()
	defer globalLock.Unlock()

	_, ok = broadcasts[name]
	if !ok {
		sendErrorMessage(conn, fmt.Sprintf("Unknown broadcast: %v", name))
		return
	}

	listeners, ok := treeStateListeners[name]
	if !ok {
		listeners = &map[string]*websocket.Conn{}
		treeStateListeners[name] = listeners
	}

	(*listeners)[id] = conn
	conn.WriteJSON(struct {
		Command string `json:"command"`
	}{
		"SUBSCRIBE_TO_TREE_STATE_RECEIVED",
	})

	notifyTreeListeners(name)
}
예제 #12
0
파일: main.go 프로젝트: comoyo/tributary
func commandEndBroadcast(conn *websocket.Conn, id string, message map[string]interface{}) {
	name, ok := stringProp(message, "name")
	if !ok {
		sendErrorMessage(conn, "No \"name\" property specified or not a string in END_BROADCAST message")
		return
	}

	globalLock.Lock()
	defer globalLock.Unlock()

	broadcast, ok := broadcasts[name]
	if !ok {
		sendErrorMessage(conn, fmt.Sprintf("Broadcast \"%v\" does not exist", name))
		return
	}

	if broadcast.id != id {
		sendErrorMessage(conn, fmt.Sprintf("Peer \"%v\" did not start broadcast \"%v\"", id, name))
		return
	}

	endBroadcast(name, broadcast)

	conn.WriteJSON(struct {
		Command string `json:"command"`
		Name    string `json:"name"`
	}{
		"END_BROADCAST_RECEIVED",
		name,
	})
}
예제 #13
0
func PubSubHandler(conn *websocket.Conn, pubsubClient *redis.PubSub) {
	for {
		msgi, err := pubsubClient.ReceiveMessage()

		if err != nil {
			return
		}

		switch msg := interface{}(msgi).(type) {
		case *redis.Message:
			var json_blob interface{}
			bytes_blob := []byte(msg.Payload)

			if err := json.Unmarshal(bytes_blob, &json_blob); err != nil {
				logger.Printf("[%s][error] failed to parse JSON %v, because %v", conn.RemoteAddr(), msg.Payload, err)
				continue
			}

			if err := conn.WriteJSON(json_blob); err != nil {
				logger.Printf("[%s][error] failed to send JSON, because %v", conn.RemoteAddr(), err)
				conn.Close()
				return
			}

			logger.Printf("[%s][send] OK", conn.RemoteAddr())
		default:
			logger.Printf("[%s][error] Unkown message: %s", conn.RemoteAddr(), msg)
			return
		}
	}
}
예제 #14
0
파일: voice.go 프로젝트: 42wim/matterbridge
// NOTE :: When a guild voice server changes how do we shut this down
// properly, so a new connection can be setup without fuss?
//
// wsHeartbeat sends regular heartbeats to voice Discord so it knows the client
// is still connected.  If you do not send these heartbeats Discord will
// disconnect the websocket connection after a few seconds.
func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) {

	if close == nil || wsConn == nil {
		return
	}

	var err error
	ticker := time.NewTicker(i * time.Millisecond)
	for {
		v.log(LogDebug, "sending heartbeat packet")
		v.wsMutex.Lock()
		err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())})
		v.wsMutex.Unlock()
		if err != nil {
			v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err)
			return
		}

		select {
		case <-ticker.C:
			// continue loop and send heartbeat
		case <-close:
			return
		}
	}
}
예제 #15
0
파일: wsapi.go 프로젝트: Xackery/gobeam
// heartbeat sends regular heartbeats to Beam so it knows the client
// is still connected.  If you do not send these heartbeats Beam will
// disconnect the websocket connection after a few seconds.
func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) {

	if listening == nil || wsConn == nil {
		return
	}

	s.Lock()
	s.DataReady = true
	s.Unlock()

	var err error
	ticker := time.NewTicker(i * time.Millisecond)
	for {
		err = wsConn.WriteJSON(heartbeatOp{1, int(time.Now().Unix())})
		if err != nil {
			fmt.Println("Error sending heartbeat:", err)
			return
		}

		select {
		case <-ticker.C:
			// continue loop and send heartbeat
		case <-listening:
			return
		}
	}
}
func loadLatestSales(websocketConnection *websocket.Conn) {
	results, err := r.Table("analytics").Filter(M{
		"type": "sale",
	}).OrderBy(
		r.Desc(r.Row.Field("data").Field("date")),
	).Limit(10).Map(func(row r.Term) interface{} {
		return row.Field("data")
	}).Run(rethinkSession)
	if err != nil {
		log.Printf("error loadLatestSales: %q", err)
	}
	defer results.Close()

	var latestSales []interface{}
	err = results.All(&latestSales)
	if err != nil {
		log.Println(err)
		return
	}

	log.Printf("sending latest %d sales\n", len(latestSales))

	socketOutgoingMessage := &SocketOutgoingMessage{
		Function: "loadLatestSales",
		Data: M{
			"type": "sale",
			"data": latestSales,
		},
	}

	err = websocketConnection.WriteJSON(socketOutgoingMessage)
	if err != nil {
		log.Println(err)
	}
}
예제 #17
0
파일: ws.go 프로젝트: uniquoooo/discordapi
func (c Discord) WSInit(con *websocket.Conn, msgChan chan WSMsg) {
	//send init on wire
	p := Properties{
		OS:              "DiscordBot",
		Browser:         "discord.go",
		Device:          "console",
		Referrer:        "",
		ReferringDomain: "",
	}
	msgData := INIT{
		Token:      c.Token,
		Version:    3, // hard-coded so changes will only happen when coded in
		Properties: &p,
	}
	msg := WSMsg{
		Op:   2,
		Data: msgData,
	}
	j, _ := json.Marshal(msg)
	fmt.Printf("msgSentInit: `%s`\n", j)
	/* if err := con.WriteMessage(1, j); err != nil {
		fmt.Println("wsInit:",err)
	} */
	err := con.WriteJSON(msg)
	if err != nil {
		fmt.Println("wsInit:", err)
	}
}
예제 #18
0
파일: ws.go 프로젝트: uniquoooo/discordapi
func wsSend(con *websocket.Conn, msgSend chan WSMsg, done, readDone, stopWS chan int) {
	defer fmt.Println("wsSend: goroutine stopped")
	seq := 1
	for {
		select {
		case <-stopWS:
			stopSend(con, done)
			return
		case <-readDone:
			stopSend(con, done)
			return
		case nextMsg, ok := <-msgSend:
			if ok {
				//send the message on the channel to the connection
				nextMsg.Seq = seq
				seq++
				fmt.Println("wsSend: sending msg", nextMsg.Type)
				j, _ := json.Marshal(nextMsg)
				fmt.Printf("wsSend: msg sent: `%s`\n", j)
				if err := con.WriteJSON(&nextMsg); err != nil {
					fmt.Println("wsSend:", err)
				}
			}
		}
	}
}
예제 #19
0
// Handle open Subscriber.
func onOpen(conn *websocket.Conn, w http.ResponseWriter, r *http.Request, sessionID string, app *app) websocketError {
	params := r.URL.Query()
	p := params.Get("protocol")

	protocol, err := strconv.Atoi(p)

	if err != nil {
		return newInvalidVersionStringFormatError()
	}

	switch {
	case strings.TrimSpace(p) == "":
		return newNoProtocolVersionSuppliedError()
	case protocol != SUPPORTED_PROTOCOL_VERSION:
		return newUnsupportedProtocolVersionError()
	case app.ApplicationDisabled:
		return newApplicationDisabledError()
	case r.TLS != nil:
		if app.OnlySSL {
			return newApplicationOnlyAccepsSSLError()
		}
	}

	// Create the new Subscriber
	connection := newConnection(sessionID, conn)
	app.Connect(connection)

	// Everything went fine. Huhu.
	if err := conn.WriteJSON(newConnectionEstablishedEvent(connection.SocketID)); err != nil {
		return newGenericReconnectImmediatelyError()
	}

	return nil
}
예제 #20
0
func hostState(msg Message, gameId string, playerId int, gs GameService, ws *websocket.Conn, db *gorp.DbMap, log *log.Logger) error {
	log.Printf("Got state change request from host: %v", msg["state"])

	game, _, err := gs.GetGame(db, gameId, playerId)
	if err != nil {
		log.Printf("%#v", err)
		return err
	}

	// TODO: check to make sure this is a valid state
	game.State = msg["state"].(string)
	var board *TicTacToe_Board
	if game.State == "start" {
		board = &TicTacToe_Board{Game: gameId}
		log.Printf("Setting up starting objects")
		// we are starting a game, so insert a new board
		err = board.setBoard([]int{0, 0, 0, 0, 0, 0, 0, 0, 0})
		if err != nil {
			log.Printf("Unable to set game board: %#v", err)
			return err
		}
		log.Printf("Inserting board: %#v", board)
		err = db.Insert(board)
		if err != nil {
			log.Printf("Couldn't insert board: %#v", err)
			return err
		}
	} else {
		board, err = getBoard(gameId, db)
		if err != nil {
			log.Printf("Unable to get board: %#v", err)
			return err
		}
	}
	log.Printf("Updating game state to %#v", game.State)
	count, err := db.Update(game)
	if err != nil || count == 0 {
		log.Printf("Unable to change game state: %v", err)
		return err
	}
	niceBoard, err := board.getBoard()
	if err != nil {
		log.Printf("Error getting board: %#v", board)
		return err
	}
	log.Printf("Sending state %v to all players", msg["state"])
	gs.Broadcast(gameId, Message{
		"type":  "update",
		"board": niceBoard,
		"state": "start",
	})
	log.Printf("Updating UI")
	ws.WriteJSON(Message{
		"type":  "update",
		"board": niceBoard,
		"state": "start",
	})
	return nil
}
예제 #21
0
파일: ws.go 프로젝트: Dachande663/PowerPlex
// Handle sending messages to the front-end via websockets
func wsWriter(ws *websocket.Conn, msgs chan wsMessage) {

	for {
		msg := <-msgs
		ws.WriteJSON(msg)
	}

}
예제 #22
0
// Emit an Websocket ErrorEvent
func emitWSError(err websocketError, conn *websocket.Conn) {

	event := newErrorEvent(err.GetCode(), err.GetMsg())

	if err := conn.WriteJSON(event); err != nil {
		log.Error(err)
	}
}
예제 #23
0
// Registers the connection from to the intools engine
func (appClient *AppClient) Register(conn *websocket.Conn) {
	// Add the client to the connected clients
	logs.Debug.Printf("Connection event from client")

	var client = &Client{
		Socket:   conn,
		GroupIds: []string{},
	}
	logs.Debug.Printf("clients before %v", appClient.Clients)

	appClient.Clients[conn] = client
	// appClient.Clients = append(appClient.Clients, client)

	logs.Debug.Printf("clients %v", appClient.Clients)

	// Send ack
	message := Message{
		Command: "connected",
		Data:    nil,
	}
	conn.WriteJSON(message)

	// Handles events from client
Events:
	for {
		var message Message
		err := conn.ReadJSON(&message)
		if err != nil {
			switch err.(type) {
			case *websocket.CloseError:
				logs.Debug.Printf("Websocket %p is deconnected. Removing from clients", conn)
				delete(appclient.Clients, conn)
				logs.Debug.Printf("Clients are now  %v", appClient.Clients)
				break Events
			default:
				logs.Error.Printf("Error while reading json message : %s", err)
				continue Events
			}
		}

		logs.Debug.Printf("Message %v", message)

		switch message.Command {
		case "register-group":
			// Handles group registering for the client
			client.GroupIds = append(client.GroupIds, message.Data["groupId"].(string))
			logs.Debug.Printf("Registered group %s for client %p", message.Data["groupId"], client)
		case "unregister-group":
			// Handles group unregistering for the client
			i := utils.IndexOf(client.GroupIds, message.Data["groupId"].(string))
			if i != -1 {
				client.GroupIds = append(client.GroupIds[:i], client.GroupIds[i+1:]...)
				logs.Debug.Printf("Unregistered group %s for client %p", message.Data["groupId"], client)
			}
		}
		logs.Debug.Printf("Registered groups for client %p are now : %s", client, client.GroupIds)
	}
}
예제 #24
0
// unsubscribe from an event
func unsubscribe(t *testing.T, con *websocket.Conn, eventid string) {
	err := con.WriteJSON(rpctypes.WSRequest{
		Type:  "unsubscribe",
		Event: eventid,
	})
	if err != nil {
		t.Fatal(err)
	}
}
예제 #25
0
파일: aliker.go 프로젝트: hut8/aliker
func sendErrorNotification(c *websocket.Conn, err error) error {
	return c.WriteJSON(&struct {
		MsgType string `json:"msg-type"`
		Message string `json:"message"`
	}{
		"error",
		err.Error(),
	})
}
예제 #26
0
파일: aliker.go 프로젝트: hut8/aliker
func sendPostSimilarities(c *websocket.Conn, s map[int64]int64) error {
	return c.WriteJSON(&struct {
		MsgType       string          `json:"msg-type"`
		SimilarityMap map[int64]int64 `json:"similarities"`
	}{
		"post-similarities",
		s,
	})
}
예제 #27
0
파일: aliker.go 프로젝트: hut8/aliker
func sendBlogsLikingPostData(c *websocket.Conn, blogs []string) error {
	return c.WriteJSON(&struct {
		MsgType string   `json:"msg-type"`
		Blogs   []string `json:"blogs"`
	}{
		"blogs-liking-post",
		blogs,
	})
}
예제 #28
0
파일: aliker.go 프로젝트: hut8/aliker
func sendPostsData(c *websocket.Conn, pd map[int64]tumblr.Post) error {
	return c.WriteJSON(&struct {
		MsgType  string                `json:"msg-type"`
		PostData map[int64]tumblr.Post `json:"posts-data"`
	}{
		"posts-data",
		pd,
	})
}
예제 #29
0
func PlayerInit(playerId int, gameId string, gs GameService, ws *websocket.Conn, db *gorp.DbMap) error {
	log.Printf("Player is connected: %#v", playerId)

	game, _, err := gs.GetGame(db, gameId, playerId)
	if err != nil {
		log.Printf("Couldn't get player and/or game")
		return err
	}

	if game.State == "start" {
		log.Printf("Player %#v rejoining game in play", playerId)
		board, err := getBoard(gameId, db)
		if err != nil {
			log.Printf("Can't get TTT board: %#v", err)
			return err
		}

		log.Printf("Got board, getting nicer one: %#v", board)
		niceBoard, err := board.getBoard()
		if err != nil {
			log.Printf("Unable to get nice board: %#v", err)
			return err
		}
		log.Printf("Got board for player %#v: %#v", playerId, board)

		// There may not be a board yet so just try and send it
		ws.WriteJSON(Message{
			"type":  "update",
			"state": game.State,
			"board": niceBoard,
		})
	} else {
		ws.WriteJSON(Message{
			"type":  "update",
			"state": game.State,
			"board": nil,
		})
	}

	// check to make sure this player has a turn row
	turn := TicTacToe_Turn{}
	err = db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, playerId)
	if err != nil {
		turn.Game = gameId
		turn.Player = playerId
		turn.Move = -1
		err = db.Insert(&turn)
		if err != nil {
			log.Printf("Unable to insert initial turn row: %#v", err)
			return err
		}
	}

	gs.SendHost(gameId, Message{"type": "join"})
	return nil
}
예제 #30
0
파일: ws.go 프로젝트: uniquoooo/discordapi
func wsSendBeat(con *websocket.Conn, now time.Time) {
	beat := WSMsg{
		Op:   1,
		Data: now.Unix(),
	}
	fmt.Println("sent beat")
	con.WriteJSON(beat)
	j, _ := json.Marshal(beat)
	fmt.Printf("beat: %s\n", j)
}