Browse Source

Renamed everything which was named user to session in preperation for user implementation.

pull/28/head
Simon Eisenmann 12 years ago committed by Simon Eisenmann
parent
commit
c7bddeda5f
  1. 6
      src/app/spreed-speakfreely-server/channeling.go
  2. 6
      src/app/spreed-speakfreely-server/connection.go
  3. 68
      src/app/spreed-speakfreely-server/hub.go
  4. 30
      src/app/spreed-speakfreely-server/images.go
  5. 28
      src/app/spreed-speakfreely-server/roomworker.go
  6. 20
      src/app/spreed-speakfreely-server/server.go
  7. 37
      src/app/spreed-speakfreely-server/session.go

6
src/app/spreed-speakfreely-server/wsdata.go → src/app/spreed-speakfreely-server/channeling.go

@ -61,7 +61,7 @@ type DataTurn struct {
Urls []string `json:"urls"` Urls []string `json:"urls"`
} }
type DataUser struct { type DataSession struct {
Type string Type string
Id string Id string
Ua string Ua string
@ -120,9 +120,9 @@ type DataOutgoing struct {
To string To string
} }
type DataUsers struct { type DataSessions struct {
Type string Type string
Users []*DataUser Users []*DataSession
Index uint64 Index uint64
Batch uint64 Batch uint64
} }

6
src/app/spreed-speakfreely-server/connection.go

@ -66,9 +66,9 @@ type Connection struct {
// Metadata. // Metadata.
Id string Id string
Roomid string // Keep Roomid here for quick acess without locking c.User. Roomid string // Keep Roomid here for quick acess without locking c.Session.
Idx uint64 Idx uint64
User *User Session *Session
IsRegistered bool IsRegistered bool
Hello bool Hello bool
Version string Version string
@ -93,7 +93,7 @@ func (c *Connection) close() {
if !c.isClosed { if !c.isClosed {
c.ws.Close() c.ws.Close()
c.mutex.Lock() c.mutex.Lock()
c.User = nil c.Session = nil
c.isClosed = true c.isClosed = true
for { for {
head := c.queue.Front() head := c.queue.Front()

68
src/app/spreed-speakfreely-server/hub.go

@ -51,21 +51,21 @@ type MessageRequest struct {
} }
type HubStat struct { type HubStat struct {
Rooms int `json:"rooms"` Rooms int `json:"rooms"`
Connections int `json:"connections"` Connections int `json:"connections"`
Users int `json:"users"` Sessions int `json:"sessions"`
Count uint64 `json:"count"` Count uint64 `json:"count"`
BroadcastChatMessages uint64 `json:"broadcastchatmessages"` BroadcastChatMessages uint64 `json:"broadcastchatmessages"`
UnicastChatMessages uint64 `json:"unicastchatmessages"` UnicastChatMessages uint64 `json:"unicastchatmessages"`
IdsInRoom map[string][]string `json:"idsinroom,omitempty"` IdsInRoom map[string][]string `json:"idsinroom,omitempty"`
UsersById map[string]*DataUser `json:"usersbyid,omitempty"` SessionsById map[string]*DataSession `json:"sessionsbyid,omitempty"`
ConnectionsByIdx map[string]string `json:"connectionsbyidx,omitempty"` ConnectionsByIdx map[string]string `json:"connectionsbyidx,omitempty"`
} }
type Hub struct { type Hub struct {
server *Server server *Server
connectionTable map[string]*Connection connectionTable map[string]*Connection
userTable map[string]*User sessionTable map[string]*Session
roomTable map[string]*RoomWorker roomTable map[string]*RoomWorker
version string version string
config *Config config *Config
@ -84,7 +84,7 @@ func NewHub(version string, config *Config, sessionSecret, turnSecret string) *H
h := &Hub{ h := &Hub{
connectionTable: make(map[string]*Connection), connectionTable: make(map[string]*Connection),
userTable: make(map[string]*User), sessionTable: make(map[string]*Session),
roomTable: make(map[string]*RoomWorker), roomTable: make(map[string]*RoomWorker),
version: version, version: version,
config: config, config: config,
@ -105,7 +105,7 @@ func (h *Hub) Stat(details bool) *HubStat {
stat := &HubStat{ stat := &HubStat{
Rooms: len(h.roomTable), Rooms: len(h.roomTable),
Connections: len(h.connectionTable), Connections: len(h.connectionTable),
Users: len(h.userTable), Sessions: len(h.sessionTable),
Count: h.count, Count: h.count,
BroadcastChatMessages: atomic.LoadUint64(&h.broadcastChatMessages), BroadcastChatMessages: atomic.LoadUint64(&h.broadcastChatMessages),
UnicastChatMessages: atomic.LoadUint64(&h.unicastChatMessages), UnicastChatMessages: atomic.LoadUint64(&h.unicastChatMessages),
@ -113,18 +113,18 @@ func (h *Hub) Stat(details bool) *HubStat {
if details { if details {
rooms := make(map[string][]string) rooms := make(map[string][]string)
for roomid, room := range h.roomTable { for roomid, room := range h.roomTable {
users := make([]string, 0, len(room.connections)) sessions := make([]string, 0, len(room.connections))
for id := range room.connections { for id := range room.connections {
users = append(users, id) sessions = append(sessions, id)
} }
rooms[roomid] = users rooms[roomid] = sessions
} }
stat.IdsInRoom = rooms stat.IdsInRoom = rooms
users := make(map[string]*DataUser) sessions := make(map[string]*DataSession)
for userid, user := range h.userTable { for sessionid, session := range h.sessionTable {
users[userid] = user.Data() sessions[sessionid] = session.Data()
} }
stat.UsersById = users stat.SessionsById = sessions
connections := make(map[string]string) connections := make(map[string]string)
for id, connection := range h.connectionTable { for id, connection := range h.connectionTable {
connections[fmt.Sprintf("%d", connection.Idx)] = id connections[fmt.Sprintf("%d", connection.Idx)] = id
@ -248,12 +248,12 @@ func (h *Hub) registerHandler(c *Connection) {
h.mutex.Lock() h.mutex.Lock()
// Create new user instance. // Create new session instance.
h.count++ h.count++
c.Idx = h.count c.Idx = h.count
u := &User{Id: c.Id} s := &Session{Id: c.Id}
h.userTable[c.Id] = u h.sessionTable[c.Id] = s
c.User = u c.Session = s
c.IsRegistered = true c.IsRegistered = true
// Register connection or replace existing one. // Register connection or replace existing one.
@ -281,13 +281,13 @@ func (h *Hub) unregisterHandler(c *Connection) {
h.mutex.Unlock() h.mutex.Unlock()
return return
} }
user := c.User session := c.Session
c.close() c.close()
delete(h.connectionTable, c.Id) delete(h.connectionTable, c.Id)
delete(h.userTable, c.Id) delete(h.sessionTable, c.Id)
h.mutex.Unlock() h.mutex.Unlock()
if user != nil { if session != nil {
h.buddyImages.DeleteUserImage(user.Id) h.buddyImages.Delete(session.Id)
} }
//log.Printf("Unregister (%d) from %s: %s\n", c.Idx, c.RemoteAddr, c.Id) //log.Printf("Unregister (%d) from %s: %s\n", c.Idx, c.RemoteAddr, c.Id)
h.server.OnUnregister(c) h.server.OnUnregister(c)
@ -322,21 +322,21 @@ func (h *Hub) aliveHandler(c *Connection, alive *DataAlive) {
} }
func (h *Hub) userupdateHandler(u *UserUpdate) uint64 { func (h *Hub) sessionupdateHandler(s *SessionUpdate) uint64 {
//fmt.Println("Userupdate", u) //fmt.Println("Userupdate", u)
h.mutex.RLock() h.mutex.RLock()
user, ok := h.userTable[u.Id] session, ok := h.sessionTable[s.Id]
h.mutex.RUnlock() h.mutex.RUnlock()
var rev uint64 var rev uint64
if ok { if ok {
rev = user.Update(u) rev = session.Update(s)
if u.Status != nil { if s.Status != nil {
status, ok := u.Status.(map[string]interface{}) status, ok := s.Status.(map[string]interface{})
if ok && status["buddyPicture"] != nil { if ok && status["buddyPicture"] != nil {
pic := status["buddyPicture"].(string) pic := status["buddyPicture"].(string)
if strings.HasPrefix(pic, "data:") { if strings.HasPrefix(pic, "data:") {
imageId := h.buddyImages.Update(u.Id, pic[5:]) imageId := h.buddyImages.Update(s.Id, pic[5:])
if imageId != "" { if imageId != "" {
status["buddyPicture"] = "img:" + imageId status["buddyPicture"] = "img:" + imageId
} }
@ -344,7 +344,7 @@ func (h *Hub) userupdateHandler(u *UserUpdate) uint64 {
} }
} }
} else { } else {
log.Printf("Update data for unknown user %s\n", u.Id) log.Printf("Update data for unknown user %s\n", s.Id)
} }
return rev return rev

30
src/app/spreed-speakfreely-server/images.go

@ -38,29 +38,29 @@ type Image struct {
updateIdx int updateIdx int
lastChange time.Time lastChange time.Time
lastChangeId string lastChangeId string
userid string sessionid string
mimetype string mimetype string
data []byte data []byte
} }
type ImageCache interface { type ImageCache interface {
Update(userId string, image string) string Update(sessionId string, image string) string
Get(imageId string) *Image Get(imageId string) *Image
DeleteUserImage(userId string) Delete(sessionId string)
} }
type imageCache struct { type imageCache struct {
images map[string]*Image images map[string]*Image
userImages map[string]string sessionImages map[string]string
mutex sync.RWMutex mutex sync.RWMutex
} }
func NewImageCache() ImageCache { func NewImageCache() ImageCache {
result := &imageCache{} result := &imageCache{}
result.images = make(map[string]*Image) result.images = make(map[string]*Image)
result.userImages = make(map[string]string) result.sessionImages = make(map[string]string)
if imageFilenames == nil { if imageFilenames == nil {
imageFilenames = map[string]string{ imageFilenames = map[string]string{
"image/png": "picture.png", "image/png": "picture.png",
@ -71,7 +71,7 @@ func NewImageCache() ImageCache {
return result return result
} }
func (self *imageCache) Update(userId string, image string) string { func (self *imageCache) Update(sessionId string, image string) string {
mimetype := "image/x-unknown" mimetype := "image/x-unknown"
pos := strings.Index(image, ";") pos := strings.Index(image, ";")
if pos != -1 { if pos != -1 {
@ -98,7 +98,7 @@ func (self *imageCache) Update(userId string, image string) string {
} }
var img *Image var img *Image
self.mutex.RLock() self.mutex.RLock()
result, ok := self.userImages[userId] result, ok := self.sessionImages[sessionId]
if !ok { if !ok {
self.mutex.RUnlock() self.mutex.RUnlock()
imageId := make([]byte, 15, 15) imageId := make([]byte, 15, 15)
@ -106,11 +106,11 @@ func (self *imageCache) Update(userId string, image string) string {
return "" return ""
} }
result = base64.URLEncoding.EncodeToString(imageId) result = base64.URLEncoding.EncodeToString(imageId)
img = &Image{userid: userId} img = &Image{sessionid: sessionId}
self.mutex.Lock() self.mutex.Lock()
resultTmp, ok := self.userImages[userId] resultTmp, ok := self.sessionImages[sessionId]
if !ok { if !ok {
self.userImages[userId] = result self.sessionImages[sessionId] = result
self.images[result] = img self.images[result] = img
} else { } else {
result = resultTmp result = resultTmp
@ -145,11 +145,11 @@ func (self *imageCache) Get(imageId string) *Image {
return image return image
} }
func (self *imageCache) DeleteUserImage(userId string) { func (self *imageCache) Delete(sessionId string) {
self.mutex.Lock() self.mutex.Lock()
imageId, ok := self.userImages[userId] imageId, ok := self.sessionImages[sessionId]
if ok { if ok {
delete(self.userImages, userId) delete(self.sessionImages, sessionId)
delete(self.images, imageId) delete(self.images, imageId)
} }
self.mutex.Unlock() self.mutex.Unlock()

28
src/app/spreed-speakfreely-server/roomworker.go

@ -35,7 +35,7 @@ const (
type RoomConnectionUpdate struct { type RoomConnectionUpdate struct {
Id string Id string
Userid string Sessionid string
Status bool Status bool
Connection *Connection Connection *Connection
} }
@ -134,15 +134,15 @@ func (r *RoomWorker) Run(f func()) bool {
func (r *RoomWorker) usersHandler(c *Connection) { func (r *RoomWorker) usersHandler(c *Connection) {
worker := func() { worker := func() {
users := &DataUsers{Type: "Users"} users := &DataSessions{Type: "Users"}
var ul []*DataUser var sl []*DataSession
appender := func(ec *Connection) bool { appender := func(ec *Connection) bool {
ecuser := ec.User ecsession := ec.Session
if ecuser != nil { if ecsession != nil {
user := ecuser.Data() session := ecsession.Data()
user.Type = "Online" session.Type = "Online"
ul = append(ul, user) sl = append(sl, session)
if len(ul) > maxUsersLength { if len(sl) > maxUsersLength {
log.Println("Limiting users response length in channel", r.Id) log.Println("Limiting users response length in channel", r.Id)
return false return false
} }
@ -150,7 +150,7 @@ func (r *RoomWorker) usersHandler(c *Connection) {
return true return true
} }
r.mutex.RLock() r.mutex.RLock()
ul = make([]*DataUser, 0, len(r.connections)) sl = make([]*DataSession, 0, len(r.connections))
// Include connections in this room. // Include connections in this room.
for _, ec := range r.connections { for _, ec := range r.connections {
if !appender(ec) { if !appender(ec) {
@ -164,7 +164,7 @@ func (r *RoomWorker) usersHandler(c *Connection) {
break break
} }
} }
users.Users = ul users.Users = sl
usersJson := c.h.buffers.New() usersJson := c.h.buffers.New()
encoder := json.NewEncoder(usersJson) encoder := json.NewEncoder(usersJson)
err := encoder.Encode(&DataOutgoing{From: c.Id, Data: users}) err := encoder.Encode(&DataOutgoing{From: c.Id, Data: users})
@ -209,10 +209,10 @@ func (r *RoomWorker) connectionHandler(rcu *RoomConnectionUpdate) {
r.mutex.Lock() r.mutex.Lock()
defer r.mutex.Unlock() defer r.mutex.Unlock()
if rcu.Status { if rcu.Status {
r.connections[rcu.Userid] = rcu.Connection r.connections[rcu.Sessionid] = rcu.Connection
} else { } else {
if _, ok := r.connections[rcu.Userid]; ok { if _, ok := r.connections[rcu.Sessionid]; ok {
delete(r.connections, rcu.Userid) delete(r.connections, rcu.Sessionid)
} }
} }
} }

20
src/app/spreed-speakfreely-server/server.go

@ -49,7 +49,7 @@ func (s *Server) OnUnregister(c *Connection) {
//log.Println("OnUnregister", c.id) //log.Println("OnUnregister", c.id)
if c.Hello { if c.Hello {
s.UpdateRoomConnection(c, &RoomConnectionUpdate{Id: c.Roomid}) s.UpdateRoomConnection(c, &RoomConnectionUpdate{Id: c.Roomid})
s.Broadcast(c, &DataUser{Type: "Left", Id: c.Id, Status: "hard"}) s.Broadcast(c, &DataSession{Type: "Left", Id: c.Id, Status: "hard"})
} else { } else {
//log.Println("Ingoring OnUnregister because of no Hello", c.Idx) //log.Println("Ingoring OnUnregister because of no Hello", c.Idx)
} }
@ -72,17 +72,17 @@ func (s *Server) OnText(c *Connection, b Buffer) {
case "Hello": case "Hello":
//log.Println("Hello", msg.Hello, c.Idx) //log.Println("Hello", msg.Hello, c.Idx)
// TODO(longsleep): Filter room id and user agent. // TODO(longsleep): Filter room id and user agent.
s.UpdateUser(c, &UserUpdate{Types: []string{"Roomid", "Ua"}, Roomid: msg.Hello.Id, Ua: msg.Hello.Ua}) s.UpdateSession(c, &SessionUpdate{Types: []string{"Roomid", "Ua"}, Roomid: msg.Hello.Id, Ua: msg.Hello.Ua})
if c.Hello && c.Roomid != msg.Hello.Id { if c.Hello && c.Roomid != msg.Hello.Id {
// Room changed. // Room changed.
s.UpdateRoomConnection(c, &RoomConnectionUpdate{Id: c.Roomid}) s.UpdateRoomConnection(c, &RoomConnectionUpdate{Id: c.Roomid})
s.Broadcast(c, &DataUser{Type: "Left", Id: c.Id, Status: "soft"}) s.Broadcast(c, &DataSession{Type: "Left", Id: c.Id, Status: "soft"})
} }
c.Roomid = msg.Hello.Id c.Roomid = msg.Hello.Id
if c.h.config.defaultRoomEnabled || !c.h.isDefaultRoomid(c.Roomid) { if c.h.config.defaultRoomEnabled || !c.h.isDefaultRoomid(c.Roomid) {
c.Hello = true c.Hello = true
s.UpdateRoomConnection(c, &RoomConnectionUpdate{Id: c.Roomid, Status: true}) s.UpdateRoomConnection(c, &RoomConnectionUpdate{Id: c.Roomid, Status: true})
s.Broadcast(c, &DataUser{Type: "Joined", Id: c.Id, Ua: msg.Hello.Ua}) s.Broadcast(c, &DataSession{Type: "Joined", Id: c.Id, Ua: msg.Hello.Ua})
} else { } else {
c.Hello = false c.Hello = false
} }
@ -103,9 +103,9 @@ func (s *Server) OnText(c *Connection, b Buffer) {
s.Unicast(c, msg.Bye.To, msg.Bye) s.Unicast(c, msg.Bye.To, msg.Bye)
case "Status": case "Status":
//log.Println("Status", msg.Status) //log.Println("Status", msg.Status)
rev := s.UpdateUser(c, &UserUpdate{Types: []string{"Status"}, Status: msg.Status.Status}) rev := s.UpdateSession(c, &SessionUpdate{Types: []string{"Status"}, Status: msg.Status.Status})
if c.h.config.defaultRoomEnabled || !c.h.isDefaultRoomid(c.Roomid) { if c.h.config.defaultRoomEnabled || !c.h.isDefaultRoomid(c.Roomid) {
s.Broadcast(c, &DataUser{Type: "Status", Id: c.Id, Status: msg.Status.Status, Rev: rev}) s.Broadcast(c, &DataSession{Type: "Status", Id: c.Id, Status: msg.Status.Status, Rev: rev})
} }
case "Chat": case "Chat":
// TODO(longsleep): Limit sent chat messages per incoming connection. // TODO(longsleep): Limit sent chat messages per incoming connection.
@ -170,10 +170,10 @@ func (s *Server) Alive(c *Connection, alive *DataAlive) {
} }
func (s *Server) UpdateUser(c *Connection, userupdate *UserUpdate) uint64 { func (s *Server) UpdateSession(c *Connection, su *SessionUpdate) uint64 {
userupdate.Id = c.Id su.Id = c.Id
return c.h.userupdateHandler(userupdate) return c.h.sessionupdateHandler(su)
} }
@ -211,7 +211,7 @@ func (s *Server) Users(c *Connection) {
func (s *Server) UpdateRoomConnection(c *Connection, rcu *RoomConnectionUpdate) { func (s *Server) UpdateRoomConnection(c *Connection, rcu *RoomConnectionUpdate) {
rcu.Userid = c.Id rcu.Sessionid = c.Id
rcu.Connection = c rcu.Connection = c
room := c.h.GetRoom(c.Roomid) room := c.h.GetRoom(c.Roomid)
room.connectionHandler(rcu) room.connectionHandler(rcu)

37
src/app/spreed-speakfreely-server/user.go → src/app/spreed-speakfreely-server/session.go

@ -25,7 +25,7 @@ import (
"sync" "sync"
) )
type User struct { type Session struct {
Id string Id string
Roomid string Roomid string
Ua string Ua string
@ -34,46 +34,45 @@ type User struct {
mutex sync.RWMutex mutex sync.RWMutex
} }
func (u *User) Update(update *UserUpdate) uint64 { func (s *Session) Update(update *SessionUpdate) uint64 {
//user := reflect.ValueOf(&u).Elem() s.mutex.Lock()
u.mutex.Lock() defer s.mutex.Unlock()
defer u.mutex.Unlock()
for _, key := range update.Types { for _, key := range update.Types {
//fmt.Println("type update", key) //fmt.Println("type update", key)
switch key { switch key {
case "Roomid": case "Roomid":
u.Roomid = update.Roomid s.Roomid = update.Roomid
case "Ua": case "Ua":
u.Ua = update.Ua s.Ua = update.Ua
case "Status": case "Status":
u.Status = update.Status s.Status = update.Status
} }
} }
u.UpdateRev++ s.UpdateRev++
return u.UpdateRev return s.UpdateRev
} }
func (u *User) Data() *DataUser { func (s *Session) Data() *DataSession {
u.mutex.RLock() s.mutex.RLock()
defer u.mutex.RUnlock() defer s.mutex.RUnlock()
return &DataUser{ return &DataSession{
Id: u.Id, Id: s.Id,
Ua: u.Ua, Ua: s.Ua,
Status: u.Status, Status: s.Status,
Rev: u.UpdateRev, Rev: s.UpdateRev,
} }
} }
type UserUpdate struct { type SessionUpdate struct {
Id string Id string
Types []string Types []string
Roomid string Roomid string
Loading…
Cancel
Save