Changes in communication package

This commit is contained in:
qowevisa 2024-06-07 21:57:18 +03:00
parent a4d6137a5a
commit 763e9a497c
2 changed files with 61 additions and 7 deletions

View File

@ -3,6 +3,7 @@ package communication
import ( import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"encoding/base64"
"encoding/gob" "encoding/gob"
"git.qowevisa.me/Qowevisa/gotell/gmyerr" "git.qowevisa.me/Qowevisa/gotell/gmyerr"
@ -126,7 +127,10 @@ func ServerSendClientDecline() ([]byte, error) {
return c.Bytes() return c.Bytes()
} }
func (r *RegisteredUser) GenerateLink(count uint32) (Link, error) { func (r *RegisteredUser) GenerateLink(count uint16) (Link, error) {
if count == 0 {
return Link{}, ERROR_LINK_ZERO_COUNT
}
var l Link var l Link
buf := make([]byte, LINK_LEN_V1) buf := make([]byte, LINK_LEN_V1)
@ -134,11 +138,9 @@ func (r *RegisteredUser) GenerateLink(count uint32) (Link, error) {
if err != nil { if err != nil {
return Link{}, err return Link{}, err
} }
if count == 0 { encoded := base64.StdEncoding.EncodeToString(buf)
return Link{}, ERROR_LINK_ZERO_COUNT
}
l.Status = LINK_STATUS_CREATED l.Status = LINK_STATUS_CREATED
l.Data = buf l.Data = []byte(encoded)
l.UseCount = count l.UseCount = count
return l, nil return l, nil
@ -154,6 +156,57 @@ func (l *Link) Bytes() ([]byte, error) {
return buf.Bytes(), nil return buf.Bytes(), nil
} }
func DecodeLink(data []byte) (*Link, error) {
var l Link
buf := bytes.NewBuffer(data)
decoder := gob.NewDecoder(buf)
err := decoder.Decode(&l)
if err != nil {
return nil, err
}
return &l, nil
}
func ClientSendServerLink(l Link) ([]byte, error) {
bb, err := l.Bytes()
if err != nil {
return nil, err
}
c := Message{
Version: V1,
ID: ID_CLIENT_SEND_SERVER_LINK,
FromID: 0,
ToID: 0,
DataLen: uint16(len(bb)),
Data: bb,
}
return c.Bytes()
}
func ServerApproveClientLink() ([]byte, error) {
c := Message{
Version: V1,
ID: ID_SERVER_APPROVE_CLIENT_LINK,
FromID: 0,
ToID: 0,
DataLen: 0,
Data: []byte{},
}
return c.Bytes()
}
func ServerDeclineClientLink() ([]byte, error) {
c := Message{
Version: V1,
ID: ID_SERVER_DECLINE_CLIENT_LINK,
FromID: 0,
ToID: 0,
DataLen: 0,
Data: []byte{},
}
return c.Bytes()
}
func (r *RegisteredUser) GetIDFromLink(l Link) ([]byte, error) { func (r *RegisteredUser) GetIDFromLink(l Link) ([]byte, error) {
bb, err := l.Bytes() bb, err := l.Bytes()
if err != nil { if err != nil {

View File

@ -6,7 +6,8 @@ type ClientForServer struct {
} }
type RegisteredUser struct { type RegisteredUser struct {
ID uint16 IsRegistered bool
ID uint16
} }
const ( const (
@ -22,5 +23,5 @@ const (
type Link struct { type Link struct {
Status uint8 Status uint8
Data []byte Data []byte
UseCount uint32 UseCount uint16
} }