Ejemplo n.º 1
0
func replayStream(ws *websocket.Conn, s *ServerState) {
	var form struct {
		Id int64 `json:"id" form:"id" validate:"required,nonzero"`
	}
	if err := parseForm(ws.Request(), &form); err != nil {
		log.Println("Error parsing form", err)
	} else if replay, err := s.Tournament.GetMatchReplay(form.Id); err != nil {
		log.Println("Error getting replay", err)
	} else {
		messages := make(chan interface{})
		done := make(chan bool)
		go replay.Stream(messages, done)
		for message := range messages {
			var ping string
			if err := websocket.Message.Receive(ws, &ping); err != nil {
				log.Println("Error receiving message", err)
				done <- true
			} else if err := web.JsonCodec.Send(ws, message); err != nil {
				log.Println("Error writing message", err)
				done <- true
			} else {
				done <- false
			}
		}
		close(done)
	}
	ws.Close()
}
Ejemplo n.º 2
0
// on new student connection, assert they are in class and then listen for their answers
// if there are any quizzes going on.
func studServer(ws *websocket.Conn) {
	id := mux.Vars(ws.Request())["id"]
	s, ok := sessions[id]

	if !ok {
		return
	}

	auth := ws.Request().Header["Authorization"]
	if len(auth) < 1 {
		return
	}
	sid := auth[0]

	// TODO put me back
	fmt.Println(sid, "connected to", id)
	if _, ok := s.registered[sid]; !ok {
		ws.Close()
		return
	}
	s.conns[ws] = true

	if s.state != math.MaxInt32 {
		websocket.JSON.Send(ws, s.questions[s.state])
	}

	listenAnswers(ws, sid, id)
}
Ejemplo n.º 3
0
//Function that handles all the request and creates response
func WShandler(ws *websocket.Conn) {
	var err error

	// cleanout
	defer ws.Close()
	//Here we are creating list of clients that gets connected
	socketClientIP := ws.Request().RemoteAddr
	socketClient := Clients{ws, socketClientIP}
	ActiveClients[socketClient] = 0
	log.Println("Total clients live:", len(ActiveClients))
	//For loop to keep it open, It closes after one Send/Recieve
	for {
		var reply string
		var clientMessage string
		if err = websocket.Message.Receive(ws, &reply); err != nil {
			log.Println("Can't receive ", socketClientIP, err.Error())
		}
		fmt.Println("Received back from client: " + reply)

		clientMessage = socketClient.IP + " : " + reply
		//ForEACH client conected, send back the msg to everyone
		for cs, _ := range ActiveClients {
			if err = websocket.Message.Send(cs.websocket, clientMessage); err != nil {
				// It could not send message to a peer
				log.Println("Could not send message to ", cs.IP, err.Error())
			}
		}
	}
}
Ejemplo n.º 4
0
func BuildConnection(ws *websocket.Conn) {
	email := ws.Request().URL.Query().Get("email")

	if email == "" {
		return
	}
	email = template.HTMLEscapeString(email)
	onlineUser := &OnlineUser{
		InRoom:     runningActiveRoom,
		Connection: ws,
		Send:       make(chan Message, 256),
		UserInfo: &User{
			Email:    email,
			Name:     strings.Split(email, "@")[0],
			Gravatar: helper.UrlSize(email, 20),
		},
	}
	runningActiveRoom.OnlineUsers[email] = onlineUser

	m := Message{
		MType: STATUS_MTYPE,
		UserStatus: UserStatus{
			Users: runningActiveRoom.GetOnlineUsers(),
		},
	}
	runningActiveRoom.Broadcast <- m

	go onlineUser.PushToClient()
	onlineUser.PullFromClient()

	onlineUser.killUserResource()
}
Ejemplo n.º 5
0
func wsockHandler(ws *websocket.Conn) {
	// Start a sniffer.
	req := ws.Request()
	req.ParseForm()
	local := req.Form.Get("local")
	remote := req.Form.Get("remote")

	if local != "" && remote != "" {
		l, err := net.Listen("tcp", local)
		if err != nil {
			sendMessage(ws, "error", err.Error())
			ws.Close()
			return
		}

		go func() {
			buf := make([]byte, 256)
			for {
				_, err := ws.Read(buf)
				if err != nil {
					l.Close()
					return
				}
			}
		}()

		fn := func(m map[string]interface{}) error {
			return websocket.JSON.Send(ws, m)
		}
		fromClient := webSniffer{fn, true}
		fromServer := webSniffer{fn, false}
		err = sniffer.SniffToOutput(l, remote, fromClient, fromServer)
		ws.Close()
	}
}
Ejemplo n.º 6
0
func (ws *WebSocketServer) wslogsHandler(w *websocket.Conn) {
	source := w.Request().FormValue("source")
	host := fmt.Sprintf("%s/%d", w.RemoteAddr().String(), time.Now().UnixNano())

	defer func() {
		log.Printf("[%s] closing websocket conn", w.RemoteAddr().String())
		ws.b.DelSubscriber(host)
		w.Close()
	}()

	log.Printf("[%s] accepting websocket conn", w.RemoteAddr().String())

	r := make(chan *buffer.Event, recvBuffer)
	ws.b.AddSubscriber(host, r)

	for {
		select {
		case ev := <-r:
			if len(source) > 0 {
				if ev.Source != source {
					continue
				}
			}

			err := websocket.Message.Send(w, *ev.Text)
			if err != nil {
				log.Printf("[%s] error sending ws message: %v", w.RemoteAddr().String(), err.Error())
				return
			}
		}
	}
}
Ejemplo n.º 7
0
// WebSocket server to handle chat between clients
func SockServer(ws *websocket.Conn) {
	var err error
	var clientMessage string
	// use []byte if websocket binary type is blob or arraybuffer
	// var clientMessage []byte

	// cleanup on server side
	defer func() {
		if err = ws.Close(); err != nil {
			log.Println("Websocket could not be closed", err.Error())
		}
	}()

	client := ws.Request().RemoteAddr
	log.Println("Client connected:", client)
	sockCli := ClientConn{ws, client}
	ActiveClients[sockCli] = 0
	log.Println("Number of clients connected ...", len(ActiveClients))

	updateNewClient(sockCli)
	// for loop so the websocket stays open otherwise
	// it'll close after one Receive
	for {
		if err = Message.Receive(ws, &clientMessage); err != nil {
			// If we cannot Read then the connection is closed
			log.Println("Websocket Disconnected waiting", err.Error())
			// remove the ws client conn from our active clients
			delete(ActiveClients, sockCli)
			log.Println("Number of clients still connected ...", len(ActiveClients))
			return
		}
		piano_ctrl <- clientMessage
	}
}
Ejemplo n.º 8
0
func EchoServer(ws *websocket.Conn) {
	var req map[string]string

	defer server.Remove(ws)

	for websocket.JSON.Receive(ws, &req) != io.EOF {
		fmt.Println(ws.Request().RemoteAddr)
		switch req["event"] {
		case "ADD":
			roomName := req["roomName"]
			server.Add(roomName, ws)
			fmt.Println(server.Room)
		case "ECHO":
			for _, client := range server.Room[req["roomName"]] {
				websocket.Message.Send(client, req["message"])
			}
		case "CLOSE":
			fmt.Println(req["message"])
		}
	}

	fmt.Println("connection ", ws)
	fmt.Println(server.Clients)
	fmt.Println(server.Room)
}
Ejemplo n.º 9
0
func WSHandler(ws *websocket.Conn) {
	fmt.Printf("Websocket connected from %s\n", ws.Request().RemoteAddr)
	defer func() {
		if err := ws.Close(); err != nil {
			fmt.Println("Websocket could not be closed", err.Error())
		}
	}()

	var err error
	var data ProxyConf

	if err = websocket.JSON.Receive(ws, &data); err != nil {
		fmt.Printf("Error: %s", err.Error())
		return
	}
	fmt.Printf("Port: %d Name: %s\n", data.Port, data.Name)

	proxy := NewProxy(data.Port, data.Name)
	go proxy.run()

	for msg := range proxy.ch {
		fmt.Println("Message sent")
		if err := websocket.Message.Send(ws, msg); err != nil {
			fmt.Printf("Error: %s", err.Error())
			break
		}
	}

	fmt.Printf("Websocket disconnected from %s", ws.Request().RemoteAddr)
}
Ejemplo n.º 10
0
func debugSocket(ws *websocket.Conn) {
	_, pidStr := path.Split(ws.Request().URL.Path)
	pid, err := strconv.ParseInt(pidStr, 10, 64)

	if err != nil {
		ws.Write([]byte("Process not found or is finished"))
		ws.Close()
		return
	}

	response := make(chan *ProcessData)
	GetProcessData <- &ProcessDataRequest{int(pid), response}
	procData := <-response

	if procData == nil {
		ws.Write([]byte("Process not found or is finished"))
		ws.Close()
		return
	}

	for {
		buffer := <-procData.output

		if buffer == "" {
			ws.Write([]byte(""))
			ws.Close()
			break
		}

		ws.Write([]byte(buffer))
	}
}
Ejemplo n.º 11
0
func getResolution(ws *websocket.Conn) (width int64, height int64) {
	request := ws.Request()
	dtsize := request.FormValue("dtsize")

	if !strings.Contains(dtsize, "x") {
		width = 800
		height = 600
	} else {
		sizeparts := strings.Split(dtsize, "x")

		width, _ = strconv.ParseInt(sizeparts[0], 10, 32)
		height, _ = strconv.ParseInt(sizeparts[1], 10, 32)

		if width < 400 {
			width = 400
		} else if width > 1920 {
			width = 1920
		}

		if height < 300 {
			height = 300
		} else if height > 1080 {
			height = 1080
		}
	}

	return width, height
}
Ejemplo n.º 12
0
func (g *Game) wsHandler(ws *websocket.Conn) {
	id, err := strconv.Atoi(misc.GetCookie(ws.Request(), "playerId"))
	name := misc.GetCookie(ws.Request(), "playerName")

	if err == nil {
		p := g.lobby.Players[id]
		if p != nil {
			p.Init(id, name, ws)

			g.register <- p
			defer func() {
				recover()
				g.unregister <- p
				p.cleanup()
			}()

			go p.writer()
			p.reader(g)
		} else {
			log.Debug("Player not in players list. Send him to lobby.")
		}
	} else {
		log.Debug("Player ID not found in cookie.")
	}
}
Ejemplo n.º 13
0
func (fh *FakeHandler) handle(conn *websocket.Conn) {
	fh.call()
	request := conn.Request()
	fh.setLastURL(request.URL.String())
	fh.setAuthHeader(request.Header.Get("Authorization"))

	if fh.messageReceived != nil {
		go func() {
			for {
				buffer := make([]byte, 1024)
				_, err := conn.Read(buffer)

				if err == nil {
					fh.messageReceived <- true
				} else {
					break
				}
			}
		}()
	}

	for _, protoMessage := range fh.Messages {
		if protoMessage == nil {
			conn.Write([]byte{})
		} else {
			message, err := proto.Marshal(protoMessage)
			Expect(err).ToNot(HaveOccurred())

			conn.Write(message)
		}
	}

	<-fh.closeConnection
	conn.Close()
}
Ejemplo n.º 14
0
func (proxy *Proxy) HandleWebSocket(clientWS *websocket.Conn) {
	req := clientWS.Request()
	req.ParseForm()
	req.Form.Get("app")
	clientAddress := clientWS.RemoteAddr()

	appId := req.Form.Get("app")

	extractAuthTokenFromUrl := func(u *url.URL) string {
		authorization := ""
		queryValues := u.Query()
		if len(queryValues["authorization"]) == 1 {
			authorization = queryValues["authorization"][0]
		}
		return authorization
	}

	authToken := clientWS.Request().Header.Get("Authorization")
	if authToken == "" {
		authToken = extractAuthTokenFromUrl(req.URL)
	}

	if authorized, errorMessage := proxy.isAuthorized(appId, authToken, clientAddress); !authorized {
		data, err := proto.Marshal(errorMessage)
		if err != nil {
			proxy.logger.Errorf("Error marshalling log message: %s", err)
		}
		websocket.Message.Send(clientWS, data)
		clientWS.Close()
		return
	}

	defer clientWS.Close()

	proxy.logger.Debugf("Output Proxy: Request for app: %v", req.Form.Get("app"))
	serverWSs := make([]*websocket.Conn, len(proxy.hashers))
	for index, hasher := range proxy.hashers {
		proxy.logger.Debugf("Output Proxy: Servers in group [%v]: %v", index, hasher.LoggregatorServers())

		server := hasher.GetLoggregatorServerForAppId(appId)
		proxy.logger.Debugf("Output Proxy: AppId is %v. Using server: %v", appId, server)

		config, err := websocket.NewConfig("ws://"+server+req.URL.RequestURI(), "http://localhost")

		if err != nil {
			proxy.logger.Errorf("Output Proxy: Error creating config for websocket - %v", err)
		}

		serverWS, err := websocket.DialConfig(config)
		if err != nil {
			proxy.logger.Errorf("Output Proxy: Error connecting to loggregator server - %v", err)
		}

		if serverWS != nil {
			serverWSs[index] = serverWS
		}
	}
	proxy.forwardIO(serverWSs, clientWS)

}
Ejemplo n.º 15
0
//wsHandler now used ws.Config as protocol handshake now supported
func wsHandler(ws *websocket.Conn) {
	defer flow.DontPanic()
	defer ws.Close()

	hdr := ws.Request().Header

	// keep track of connected clients for reload broadcasting
	id := hdr.Get("Sec-Websocket-Key")
	wsClients[id] = ws
	defer delete(wsClients, id)

	// the protocol name is used as tag to locate the proper circuit
	//lightbulb: We use the protocol provided by ws, rather than header, as that contains server accepted value
	tag := ws.Config().Protocol[0]

	fmt.Println("WS Protocol Selected:", tag)

	if tag == "" { //no specific protocol, lets opt for 'default' which just echoes (or return with no circuit!)
		tag = "default"
	}

	g := flow.NewCircuit()
	g.AddCircuitry("head", &wsHead{ws: ws})
	g.Add("ws", "WebSocket-"+tag) //the client has negotiated this support
	g.AddCircuitry("tail", &wsTail{ws: ws})
	g.Connect("head.Out", "ws.In", 0)
	g.Connect("ws.Out", "tail.In", 0)
	g.Run()
}
Ejemplo n.º 16
0
// WebSocket server to handle chat between clients
func SockServer(ws *websocket.Conn) {
	var err error
	var clientMessage string
	// use []byte if websocket binary type is blob or arraybuffer
	// var clientMessage []byte

	// cleanup on server side
	defer func() {
		if err = ws.Close(); err != nil {
			log.Println("Websocket could not be closed", err.Error())
		}
	}()

	client := ws.Request().RemoteAddr
	log.Println("Client connected:", client)
	sockCli := ClientConn{ws, client}
	ActiveClients[sockCli] = ""
	log.Println("Number of clients connected:", len(ActiveClients))

	// for loop so the websocket stays open otherwise
	// it'll close after one Receieve and Send
	for {
		if err = Message.Receive(ws, &clientMessage); err != nil {
			// If we cannot Read then the connection is closed
			log.Println("Websocket Disconnected waiting", err.Error())
			// remove the ws client conn from our active clients
			delete(ActiveClients, sockCli)
			log.Println("Number of clients still connected:", len(ActiveClients))
			return
		}

		var msg_arr = strings.Split(clientMessage, "|")
		if msg_arr[0] == "login" && len(msg_arr) == 3 {
			name := msg_arr[1]
			pass := msg_arr[2]

			if pass == User[name] {
				ActiveClients[sockCli] = name

				if err = Message.Send(ws, "login|"+name); err != nil {
					log.Println("Could not send message to ", client, err.Error())
				}
			} else {
				log.Println("login faild:", clientMessage)
			}

		} else if msg_arr[0] == "msg" {
			if ActiveClients[sockCli] != "" {
				clientMessage = "msg|" + time.Now().Format("2006-01-02 15:04:05") + " " + ActiveClients[sockCli] + " Said: " + msg_arr[1]
				for cs, na := range ActiveClients {
					if na != "" {
						if err = Message.Send(cs.websocket, clientMessage); err != nil {
							log.Println("Could not send message to ", cs.clientIP, err.Error())
						}
					}
				}
			}
		}
	}
}
Ejemplo n.º 17
0
func (sinkServer *sinkServer) sinkRelayHandler(ws *websocket.Conn) {
	clientAddress := ws.RemoteAddr()

	appId := appid.FromUrl(ws.Request().URL)
	authToken := ws.Request().Header.Get("Authorization")

	if appId == "" {
		message := fmt.Sprintf("SinkServer: Did not accept sink connection with invalid app id: %s.", clientAddress)
		sinkServer.logger.Warn(message)
		ws.CloseWithStatus(4000)
		return
	}

	if authToken == "" {
		message := fmt.Sprintf("SinkServer: Did not accept sink connection from %s without authorization.", clientAddress)
		sinkServer.logger.Warnf(message)
		ws.CloseWithStatus(4001)
		return
	}

	if !sinkServer.authorize(authToken, appId, sinkServer.logger) {
		message := fmt.Sprintf("SinkServer: Auth token [%s] not authorized to access appId [%s].", authToken, appId)
		sinkServer.logger.Warn(message)
		ws.CloseWithStatus(4002)
		return
	}

	s := sinks.NewWebsocketSink(appId, sinkServer.logger, ws, clientAddress, sinkServer.keepAliveInterval)

	sinkServer.activeSinksChans.Register(s.Channel(), appId)
	s.Run(sinkServer.sinkCloseChan)
}
Ejemplo n.º 18
0
func receiver(ws *websocket.Conn, p *player.Player) chan int {
	quit := make(chan int, 0)
	go func() {
		for {
			m := &player.Message{}
			err := websocket.JSON.Receive(ws, m)
			if err != nil {
				break
			}
			if m.Ping != "" {
				fmt.Printf(
					"%s %s %s\n",
					time.Now().UTC(),
					time.Since(p.PingSent),
					ws.Request().RemoteAddr,
				)
			} else {
				p.FromClient <- m
			}
		}
		p.Disconnected = true
		quit <- 1
	}()
	return quit
}
Ejemplo n.º 19
0
func acceptWebSocket(ws *websocket.Conn, config *Config, log *LogScope) {
	defer ws.Close()

	req := ws.Request()
	id := generateId()
	_, remoteHost, _, err := remoteDetails(ws, config)
	if err != nil {
		log.Error("session", "Could not understand remote address '%s': %s", req.RemoteAddr, err)
		return
	}

	log = log.NewLevel(log.LogFunc)
	log.Associate("id", id)
	log.Associate("url", fmt.Sprintf("http://%s%s", req.RemoteAddr, req.URL.RequestURI()))
	log.Associate("origin", req.Header.Get("Origin"))
	log.Associate("remote", remoteHost)

	log.Access("session", "CONNECT")
	defer log.Access("session", "DISCONNECT")

	urlInfo, err := parsePath(ws.Request().URL.Path, config)
	if err != nil {
		log.Access("session", "NOT FOUND: %s", err)
		return
	}
	log.Debug("session", "URLInfo: %s", urlInfo)

	env, err := createEnv(ws, config, urlInfo, id)
	if err != nil {
		log.Error("process", "Could not create ENV: %s", err)
		return
	}

	commandName := config.CommandName
	if config.UsingScriptDir {
		commandName = urlInfo.FilePath
	}
	log.Associate("command", commandName)

	launched, err := launchCmd(commandName, config.CommandArgs, env)
	if err != nil {
		log.Error("process", "Could not launch process %s %s (%s)", commandName, strings.Join(config.CommandArgs, " "), err)
		return
	}

	log.Associate("pid", strconv.Itoa(launched.cmd.Process.Pid))

	process := NewProcessEndpoint(launched, log)
	wsEndpoint := NewWebSocketEndpoint(ws, log)

	defer process.Terminate()

	go process.ReadOutput(launched.stdout, config)
	go wsEndpoint.ReadOutput(config)
	go process.pipeStdErr(config)

	pipeEndpoints(process, wsEndpoint, log)
}
Ejemplo n.º 20
0
func websocketRequestHandler(ws *websocket.Conn) {
	vars := mux.Vars(ws.Request())
	receiver := vars["mailbox"]

	mail := &mailbox.Mailbox{Receiver: receiver}
	c := &dispatch.Connection{Send: make(chan string, 1024), WebSocket: ws, Mailbox: mail}
	dispatcher.Register <- c
	c.Writer(dispatcher)
}
Ejemplo n.º 21
0
func connect(ws *websocket.Conn) {
	// Message receive from client should either be 'new' or a game id
	log.Println("New websocket connection:", ws.Request().RemoteAddr)
	var msg string
	websocket.Message.Receive(ws, &msg)

	var g *game.Game
	var ok bool

	// Check if the player creates a new game or is connecting to an exiting game
	if msg == "new" {
		g = game.New()
		games[g.Id] = g
		log.Printf("Player %s created game %s", ws.Request().RemoteAddr, g.Id)
	} else {
		log.Printf("Player %s is requesting game %s", ws.Request().RemoteAddr, msg)
		g, ok = games[msg]
		if !ok {
			websocket.Message.Send(ws, "notfound")
			return
		}
	}

	log.Printf("Adding Player %s to game %s", ws.Request().RemoteAddr, g.Id)
	// Send back game id
	g.AddPlayer(ws)
	websocket.Message.Send(ws, g.Id)
	if len(g.Players) == 1 {
		go g.Run()
	}

	defer func() {
		g.RemovePlayer(ws)
		if len(g.Players) == 0 {
			log.Println("Removing game", g.Id)
			delete(games, g.Id)
		}
	}()

	for {
		err := websocket.Message.Receive(ws, &msg)
		if err != nil {
			log.Printf("Player %s disconnected and left game %s", ws.Request().RemoteAddr, g.Id)
			return
		}
		switch msg {
		case "left":
			g.Input(ws, game.Left)
		case "right":
			g.Input(ws, game.Right)
		case "up":
			g.Input(ws, game.Up)
		case "down":
			g.Input(ws, game.Down)
		}
	}
}
Ejemplo n.º 22
0
func (httpServer *httpServer) websocketRouter(ws *websocket.Conn) {
	if ws.Request().URL.Path == TAIL_PATH {
		httpServer.websocketSinkHandler(ws)
	} else if ws.Request().URL.Path == DUMP_PATH {
		httpServer.dumpSinkHandler(ws)
	} else {
		ws.CloseWithStatus(400)
		return
	}
}
Ejemplo n.º 23
0
// socketHandler handles the websocket connection for a given present session.
// It handles transcoding Messages to and from JSON format, and starting
// and killing processes.
func socketHandler(c *websocket.Conn) {
	in, out := make(chan *Message), make(chan *Message)
	errc := make(chan error, 1)

	// Decode messages from client and send to the in channel.
	go func() {
		dec := json.NewDecoder(c)
		for {
			var m Message
			if err := dec.Decode(&m); err != nil {
				errc <- err
				return
			}
			in <- &m
		}
	}()

	// Receive messages from the out channel and encode to the client.
	go func() {
		enc := json.NewEncoder(c)
		for m := range out {
			if err := enc.Encode(m); err != nil {
				errc <- err
				return
			}
		}
	}()

	// Start and kill processes and handle errors.
	proc := make(map[string]*process)
	for {
		select {
		case m := <-in:
			switch m.Kind {
			case "run":
				log.Println("running snippet from:", c.Request().RemoteAddr)
				proc[m.Id].Kill()
				lOut := limiter(in, out)
				proc[m.Id] = startProcess(m.Id, m.Body, lOut, m.Options)
			case "kill":
				proc[m.Id].Kill()
			}
		case err := <-errc:
			if err != io.EOF {
				// A encode or decode has failed; bail.
				log.Println(err)
			}
			// Shut down any running processes.
			for _, p := range proc {
				p.Kill()
			}
			return
		}
	}
}
Ejemplo n.º 24
0
func (websocketServer *websocketServer) route(ws *websocket.Conn) {
	switch ws.Request().URL.Path {
	case TAIL_LOGS_PATH:
		websocketServer.streamLogs(ws)
	case RECENT_LOGS_PATH:
		websocketServer.recentLogs(ws)
	default:
		ws.CloseWithStatus(400)
		return
	}
}
Ejemplo n.º 25
0
func Handler(socket *websocket.Conn) {
	defer socket.Close()
	r := socket.Request()
	user, banned := getUserFromWebRequest(r)

	if banned {
		websocket.Message.Send(socket, `ERR "banned"`)
		return
	}

	newConnection(socket, user)
}
// Entrance that builds and maintains the websocket connection for users
func BuildConnection(conn *websocket.Conn) {

	defer func() {
		if err := recover(); err != nil {
			log.Printf("********** WebSocket Error: %+v ***********\n", err)
			debug.PrintStack()
		}
	}()

	orgIdHex := conn.Request().URL.Query().Get("o")
	if orgIdHex == "" {
		return
	}

	wsCookie := ""
	for _, cc := range conn.Request().Cookies() {
		if cc.Name == "qortex" {
			wsCookie = cc.Value
			break
		}
	}
	if wsCookie == "" {
		return
	}

	member, _ := getSessionMember(wsCookie)
	if member == nil {
		return
	}

	activeOrg, err := MyActiveOrg(orgIdHex)
	if err != nil {
		utils.PrintStackAndError(err)
		return
	}

	user, err := users.FindById(activeOrg.Organization.Database, member.Id)
	if err != nil {
		utils.PrintStackAndError(err)
		return
	}

	onlineUser := activeOrg.GetOrInitOnlineUser(user, conn)
	log.Printf("----> New websocket connection for: %s, %+v running totally",
		user.Email, len(onlineUser.WsConns))

	// Holding the connection
	jsonrpc.ServeConn(conn)

	// Cut current connection and clean up related resources
	onlineUser.KillWebsocket(conn)
}
Ejemplo n.º 27
0
// Twitter検索
func twitterSearchHandler(ws *websocket.Conn) {
	defer ws.Close()

	// 検索キーワードの取得
	req := ws.Request() // http.Requestが返る
	query := req.FormValue("q")
	log.Printf("query: %s", query)

	// Twitter streaming APIに接続
	client := twitterstream.NewClientTimeout(
		*consumerKey,
		*consumerSecret,
		*accessToken,
		*accessTokenSecret,
		timeout,
	)
	conn, err := client.Track(query)
	if err != nil {
		log.Printf("Tracking failed: %s", err)
		return
	}
	defer conn.Close()

	for {
		if tweet, err := conn.Next(); err == nil {
			// Tweetが公式Retweetだった場合はなにもしない
			if tweet.RetweetedStatus != nil {
				continue
			}

			// Websocketに流すJSONを作成
			data := WSTweet{
				tweet.Text,
				tweet.User.Name,
				tweet.User.ScreenName,
				tweet.User.ProfileImageUrl,
			}
			json, _ := json.Marshal(data)

			// Websocketに流す
			_, err = ws.Write(json)
			if err != nil {
				log.Printf("Writing to Websocket failed: %s", err)
				return
			}
		} else {
			log.Printf("Decoding tweet failed: %s", err)
			return
		}
	}
}
Ejemplo n.º 28
0
func wsHandler(ws *websocket.Conn) {
	ircServerAddr := strings.TrimPrefix(ws.Request().URL.Path, "/")

	log.Println("Opening connection to ", ircServerAddr)
	ircConn, err := net.Dial("tcp", ircServerAddr)

	if err != nil {
		log.Println("Cannot open TCP connection to %s", ircServerAddr)
		ws.Close()
	} else {
		bridge := WS2IRCBridge{ws: ws, irc: ircConn}
		bridge.run()
	}
}
Ejemplo n.º 29
0
func Subscribe(ws *websocket.Conn) {
	defer recoverFunc()

	params := ws.Request().URL.Query()
	subKey := params.Get("key")
	//TODO auth
	// get lastest message id

	midStr := params.Get("msg_id")
	mid, err := strconv.ParseInt(midStr, 10, 64)
	if err != nil {
		Log.Printf("argument error (%s)", err.Error())
		return
	}

	Log.Printf("client (%s) subscribe to key %s with msg_id = %s", ws.Request().RemoteAddr, subKey, midStr)
	// fetch subscriber from the channel
	sub := subChannel(subKey)
	// add a conn to the subscriber
	if err := sub.AddConn(ws); err != nil {
		Log.Printf("sub.AddConn failed (%s)", err.Error())
		return
	}

	// remove exists conn
	defer sub.RemoveConn(ws)
	// send stored message
	msgs, scores := sub.Message(mid)
	if msgs != nil && scores != nil {
		for i := 0; i < len(msgs); i++ {
			msg := msgs[i]
			score := scores[i]
			if err = subRetWrite(ws, msg, score); err != nil {
				// remove exists conn
				// delete(s.conn, ws)
				Log.Printf("subRetWrite() failed (%s)", err.Error())
				return
			}
		}
	}

	// blocking untill someone pub the key
	reply := ""
	if err = websocket.Message.Receive(ws, &reply); err != nil {
		Log.Printf("websocket.Message.Receive() failed (%s)", err.Error())
	}

	return
}
Ejemplo n.º 30
0
func wsHandler(ws *websocket.Conn) {
	// check that they're logged in!
	httpRequest := ws.Request()
	session := getSession(httpRequest)
	if !isLoggedIn(session) {
		websocket.Message.Send(ws, "NOT_LOGGED_IN")
		ws.Close()
		return
	}

	c := &connection{send: make(chan string, 256), ws: ws, user: session.Values["username"].(string)}
	h.register <- c
	defer func() { h.unregister <- c }()
	c.writer()
}