Add a lot to server

This commit is contained in:
qowevisa 2024-06-07 21:57:23 +03:00
parent 763e9a497c
commit 9d0e49c461
2 changed files with 100 additions and 0 deletions

54
cmd/server/links.go Normal file
View File

@ -0,0 +1,54 @@
package main
import (
"sync"
com "git.qowevisa.me/Qowevisa/gotell/communication"
)
type UserLink struct {
LeftNum uint16
UserID uint16
}
type LinkCenter struct {
Links map[string]*UserLink
Mu sync.Mutex
}
var (
linkCenter LinkCenter
)
func (l *LinkCenter) Init() {
l.Links = make(map[string]*UserLink)
}
func (l *LinkCenter) AddLink(id uint16, link com.Link) error {
_, found := l.Links[string(link.Data)]
if found {
return ERROR_ALREADY_HAVE
}
l.Mu.Lock()
l.Links[string(link.Data)] = &UserLink{
LeftNum: link.UseCount,
UserID: id,
}
l.Mu.Unlock()
return nil
}
func (l *LinkCenter) DeleteLink(data []byte) error {
l.Mu.Lock()
delete(l.Links, string(data))
l.Mu.Unlock()
return nil
}
func (l *LinkCenter) GetLink(data []byte) (*UserLink, error) {
val, found := l.Links[string(data)]
if !found {
return nil, ERROR_DONT_HAVE
}
return val, nil
}

View File

@ -15,6 +15,7 @@ import (
func main() { func main() {
userCenter.Init() userCenter.Init()
linkCenter.Init()
host, err := env.GetHost() host, err := env.GetHost()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@ -110,6 +111,51 @@ func handleClient(conn net.Conn) {
registeredID = id registeredID = id
} }
case com.ID_CLIENT_SEND_SERVER_LINK: case com.ID_CLIENT_SEND_SERVER_LINK:
l, err := com.DecodeLink(msg.Data)
if err != nil {
log.Printf("ERROR: DecodeLink: %v\n", err)
continue
}
err = linkCenter.AddLink(msg.FromID, *l)
if err != nil {
log.Printf("ERROR: AddLink: %v\n", err)
answ, err := com.ServerDeclineClientLink()
if err != nil {
log.Printf("ERROR: BYTES: %v\n", err)
continue
}
conn.Write(answ)
continue
}
answ, err := com.ServerApproveClientLink()
if err != nil {
log.Printf("ERROR: BYTES: %v\n", err)
continue
}
conn.Write(answ)
case com.ID_CLIENT_ASK_SERVER_LINK:
link, err := linkCenter.GetLink(msg.Data)
if err != nil {
log.Printf("Error: %v\n", err)
continue
}
if link.LeftNum == 0 {
linkCenter.DeleteLink(msg.Data)
continue
}
// TODO: there can be an error on multi-thread app
link.LeftNum -= 1
name, err := userCenter.GetName(link.UserID)
if err != nil {
log.Printf("ERROR: userCenter: Getname: %v\n", err)
continue
}
answ, err := com.ServerSendClientIDFromLink(link.UserID, []byte(name))
if err != nil {
log.Printf("ERROR: BYTES: %v\n", err)
continue
}
conn.Write(answ)
default: default:
} }
// Handle // Handle