data

package
v0.0.0-...-075af76 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 24, 2020 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Subscribe is used to broadcast a message indicating user has joined ChatRoom
	Subscribe = "join"
	// Broadcast is used to broadcast messages to all subscribed users
	Broadcast = "send"
	// Unsubscribe is used to broadcast a message indicating user has left ChatRoom
	Unsubscribe = "leave"
)
View Source
const (
	// PublicRoom is a room open for anyone to join without authentication
	PublicRoom = "public"
	// PrivateRoom is password protected and requires an authentication token in order to process requests
	PrivateRoom = "private"
	// HiddenRoom is a private room that is not listed on public-facing APIs. TODO: Hide this from GET /chats/<id> as well?
	HiddenRoom = "hidden"
)

Variables

This section is empty.

Functions

func EncodeJWT

func EncodeJWT(c *ChatEvent, cr *ChatRoom, secretKey string) (tokenString string, err error)

EncodeJWT will generate a jwt token based

func ParseJWT

func ParseJWT(tokenString string, c *Claims, secretKey string) (err error)

ParseJWT parses a JWT and stores Claims object in c

Types

type APIError

type APIError struct {
	Code  int    `json:"code,omitempty"`
	Msg   string `json:"error,omitempty"`
	Field string `json:"field,omitempty"`
}

APIError represents an error that was thrown at some point with some relevant information for users to correct their input

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) SetMsg

func (e *APIError) SetMsg()

SetMsg will set the Msg based on the provided code

type Broker

type Broker struct {
	// Registered Clients.
	Clients map[*Client]bool

	// Inbound messages from the Clients.
	Notification chan []byte

	// Register requests from the Clients.
	OpenClient chan *Client

	// Unregister requests from Clients.
	CloseClient chan *Client

	RoomID int
}

Broker maintains the client connections and handles events using a listener goroutine

type ChatEvent

type ChatEvent struct {
	EventType string    `json:"event_type,omitempty"`
	User      string    `json:"name,omitempty"`
	RoomID    int       `json:"room_id,omitempty"`
	Color     string    `json:"color,omitempty"`
	Msg       string    `json:"msg,omitempty"`
	Password  string    `json:"secret,omitempty"`
	Timestamp time.Time `json:"time,omitempty"`
}

ChatEvent represents a message event in an associated ChatRoom

func ValidateEvent

func ValidateEvent(data []byte) (ChatEvent, error)

ValidateEvent ensures data is a valid JSON representation of Chat Event and can be parsed as such

type ChatRoom

type ChatRoom struct {
	Title       string             `json:"title"`
	Description string             `json:"description,omitempty"`
	Type        string             `json:"visibility"`
	Password    string             `json:"password,omitempty"`
	CreatedAt   time.Time          `json:"createdAt"`
	UpdatedAt   time.Time          `json:"updatedAt"`
	ID          int                `json:"id"`
	Broker      *Broker            `json:"-"`
	Clients     map[string]*Client `json:"-"`
}

ChatRoom is a struct representing a chat room TODO: Add Administrator

func (ChatRoom) AddClient

func (cr ChatRoom) AddClient(c *Client) (err error)

AddClient will add a user to a ChatRoom

func (ChatRoom) Authorize

func (cr ChatRoom) Authorize(c *ChatEvent) bool

Authorize authorizes a given ChatEvent for the Room

func (ChatRoom) IsValid

func (cr ChatRoom) IsValid() (err *APIError, validity bool)

IsValid validates a chat room fields are still valid

func (ChatRoom) MatchesPassword

func (cr ChatRoom) MatchesPassword(val string) bool

MatchesPassword takes in a value and compares it with the room's password

func (ChatRoom) Participants

func (cr ChatRoom) Participants() int

Participants prints the # of active clients

func (ChatRoom) PrettyTime

func (cr ChatRoom) PrettyTime() string

PrettyTime prints the creation date in a pretty format

func (ChatRoom) RemoveClient

func (cr ChatRoom) RemoveClient(user string) (err error)

RemoveClient will remove a user from a ChatRoom

func (ChatRoom) ToJSON

func (cr ChatRoom) ToJSON() (jsonEncoding []byte, err error)

ToJSON marshals a ChatRoom object in a JSON encoding that can be returned to users

type ChatServer

type ChatServer struct {
	RoomsID map[int]*ChatRoom
	Rooms   map[string]*ChatRoom // TODO: Remove this duplication once data layer moves to DB
	Index   *int
}

ChatServer maintains all ChatRooms. TODO: This will be replaced by a database soon

var CS ChatServer = ChatServer{
	RoomsID: make(map[int]*ChatRoom),
	Rooms:   make(map[string]*ChatRoom),
	Index:   &index,
}

CS is the global ChatServer referencing all chat room objects

func (ChatServer) Add

func (cs ChatServer) Add(cr *ChatRoom) (err error)

Add will create a new chat room and add it to the server

func (ChatServer) Chats

func (cs ChatServer) Chats() (rooms []ChatRoom, err error)

Chats will return all non-hidden ChatRooms

func (ChatServer) Delete

func (cs ChatServer) Delete(cr *ChatRoom) (err error)

Delete a chat room

func (ChatServer) Init

func (cs ChatServer) Init()

Init will initialize the ChatServer with the default public room.

func (ChatServer) Retrieve

func (cs ChatServer) Retrieve(title string) (cr *ChatRoom, err error)

Retrieve returns a single chat room based on title or ID

func (ChatServer) RetrieveID

func (cs ChatServer) RetrieveID(ID int) (cr *ChatRoom, err error)

RetrieveID returns a single chat room based on ID. NOTE: This has no error handling unlike cs.Retrieve()

func (ChatServer) Update

func (cs ChatServer) Update(titleOrID string, modifiedChatRoom *ChatRoom) (err error)

Update a chat room. NOTE: Authorization should have been done before calling this TODO: Get input from requested ID. Edit both RoomsID and Rooms.

type Claims

type Claims struct {
	Username string `json:"username"`
	RoomID   int    `json:"room_id,omitempty"`
	jwt.StandardClaims
}

Claims is a model that represents JSON web tokens used for authentication by users

func (Claims) RefreshJWT

func (c Claims) RefreshJWT(secretKey string) (tokenString string, err error)

RefreshJWT will refresh return a signed token with new expiration time

type Client

type Client struct {
	Username     string    `json:"username"`
	Color        string    `json:"color"`
	LastActivity time.Time `json:"last_activity"`
	// The websocket Connection.
	Conn *websocket.Conn `json:"-"`
	// Buffered channel of outbound messages.
	Send chan []byte `json:"-"`
	// ChatRoom that client is registered with
	Room *ChatRoom `json:"-"`
}

Client represents a user in a ChatRoom

func (*Client) ReadPump

func (c *Client) ReadPump()

ReadPump pumps messages from the websocket connection to the broker.

The application runs ReadPump in a per-connection goroutine. The application ensures that there is at most one reader on a connection by executing all reads from this goroutine.

func (*Client) WritePump

func (c *Client) WritePump()

WritePump pumps messages from the broker to the websocket connection.

A goroutine running WritePump is started for each connection. The application ensures that there is at most one writer to a connection by executing all writes from this goroutine.

type Outcome

type Outcome struct {
	Status bool      `json:"status"`
	Error  *APIError `json:"error,omitempty"`
}

Outcome represents status indicating success/failure of an operation

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL