2019-03-16 18:44:18 +01:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2019-03-23 18:30:04 +01:00
|
|
|
"fmt"
|
2019-03-20 21:57:29 +01:00
|
|
|
"net"
|
2019-03-16 18:44:18 +01:00
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
2019-03-24 23:51:39 +01:00
|
|
|
"github.com/zorchenhimer/MovieNight/common"
|
2019-03-16 18:44:18 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
type chatConnection struct {
|
|
|
|
*websocket.Conn
|
2019-03-23 19:50:47 +01:00
|
|
|
mutex sync.RWMutex
|
2019-03-20 21:57:29 +01:00
|
|
|
forwardedFor string
|
2019-03-23 21:09:47 +01:00
|
|
|
clientName string
|
2019-03-16 18:44:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
func (cc *chatConnection) ReadData(data interface{}) error {
|
2019-03-23 19:50:47 +01:00
|
|
|
cc.mutex.RLock()
|
|
|
|
defer cc.mutex.RUnlock()
|
|
|
|
|
2019-03-21 21:20:50 +01:00
|
|
|
stats.msgInInc()
|
2019-03-16 18:44:18 +01:00
|
|
|
return cc.ReadJSON(data)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (cc *chatConnection) WriteData(data interface{}) error {
|
|
|
|
cc.mutex.Lock()
|
2019-03-23 19:50:47 +01:00
|
|
|
defer cc.mutex.Unlock()
|
|
|
|
|
2019-03-21 21:20:50 +01:00
|
|
|
stats.msgOutInc()
|
2019-03-23 18:30:04 +01:00
|
|
|
err := cc.WriteJSON(data)
|
|
|
|
if err != nil {
|
2019-03-23 21:09:47 +01:00
|
|
|
if operr, ok := err.(*net.OpError); ok {
|
2019-03-24 23:51:39 +01:00
|
|
|
common.LogDebugln("OpError: " + operr.Err.Error())
|
2019-03-23 21:09:47 +01:00
|
|
|
}
|
|
|
|
return fmt.Errorf("Error writing data to %s %s: %v", cc.clientName, cc.Host(), err)
|
2019-03-23 18:30:04 +01:00
|
|
|
}
|
|
|
|
return nil
|
2019-03-16 18:44:18 +01:00
|
|
|
}
|
2019-03-20 21:57:29 +01:00
|
|
|
|
|
|
|
func (cc *chatConnection) Host() string {
|
|
|
|
if len(cc.forwardedFor) > 0 {
|
|
|
|
return cc.forwardedFor
|
|
|
|
}
|
|
|
|
|
|
|
|
host, _, err := net.SplitHostPort(cc.RemoteAddr().String())
|
|
|
|
if err != nil {
|
|
|
|
return cc.RemoteAddr().String()
|
|
|
|
}
|
|
|
|
return host
|
|
|
|
}
|