users

package
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2025 License: GPL-3.0 Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	IndexVersion           = 1
	IndexLineTerminatorV1  = byte(10) // "\n"
	IndexRecordSizeV1      = 89
	FixedHeaderTotalLength = 100 // 99 bytes header content + 1 byte newline
)
View Source
const (
	LogMinAllocation = 50
	LogMaxAllocation = 1000
)

Variables

View Source
var (
	ErrIndexMissing        = errors.New(`index does not exist`)
	ErrUserFilesOldFormat  = errors.New(`user files are in old format of username.yaml`)
	ErrIndexVersionInvalid = errors.New(`version out of date.`)
	ErrSearchNameTooLong   = errors.New(`search name provided is too long`)
	ErrNotFound            = errors.New("user not found")
)
View Source
var (
	// immutable roles
	RoleGuest string = "guest"
	RoleUser  string = "user"
	RoleAdmin string = "admin"
)
View Source
var (
	ErrBothFilesExist = errors.New("could not migrate due to both file formats existing")
)

Functions

func CharacterNameSearch

func CharacterNameSearch(nameToFind string) (foundUserId int, foundUserName string)

searches for a character name and returns the user that owns it Slow and possibly memory intensive - use strategically

func CreateUser

func CreateUser(u *UserRecord) error

First time creating a user.

func DoFilenameMigrationV1

func DoFilenameMigrationV1() error

func DoUserMigrations

func DoUserMigrations()

func Exists

func Exists(name string) bool

func FindUserId

func FindUserId(username string) int

func GetConnectionId

func GetConnectionId(userId int) connections.ConnectionId

func GetConnectionIds

func GetConnectionIds(userIds []int) []connections.ConnectionId

func GetExpiredZombies

func GetExpiredZombies(expirationTurn uint64) []int

Returns a slice of userId's These userId's are zombies that have reached expiration

func GetMemoryUsage

func GetMemoryUsage() map[string]util.MemoryResult

func GetOnlineUserIds

func GetOnlineUserIds() []int

func GetUniqueUserId

func GetUniqueUserId() int

func IsZombieConnection

func IsZombieConnection(connectionId connections.ConnectionId) bool

func LogOutUserByConnectionId

func LogOutUserByConnectionId(connectionId connections.ConnectionId) error

func RemoveZombieConnection

func RemoveZombieConnection(connectionId connections.ConnectionId)

func RemoveZombieUser

func RemoveZombieUser(userId int)

func SaveAllUsers

func SaveAllUsers(isAutoSave ...bool)

func SaveUser

func SaveUser(u UserRecord, isAutoSave ...bool) error

func SearchOfflineUsers

func SearchOfflineUsers(searchFunc func(u *UserRecord) bool)

Loads all user recvords and runs against a function. Stops searching if false is returned.

func SetZombieUser

func SetZombieUser(userId int)

func ValidateName

func ValidateName(name string) error

func ValidatePassword

func ValidatePassword(pw string) error

Types

type ActiveUsers

type ActiveUsers struct {
	Users             map[int]*UserRecord                 // userId to UserRecord
	Usernames         map[string]int                      // username to userId
	Connections       map[connections.ConnectionId]int    // connectionId to userId
	UserConnections   map[int]connections.ConnectionId    // userId to connectionId
	ZombieConnections map[connections.ConnectionId]uint64 // connectionId to turn they became a zombie
}

type Inbox

type Inbox []Message

func (*Inbox) Add

func (i *Inbox) Add(msg Message)

func (*Inbox) CountRead

func (i *Inbox) CountRead() int

func (*Inbox) CountUnread

func (i *Inbox) CountUnread() int

func (*Inbox) Empty

func (i *Inbox) Empty()

type IndexMetaData

type IndexMetaData struct {
	MetaDataSize uint64 // size of the metadata header (in bytes)
	IndexVersion uint64
	RecordCount  uint64
	RecordSize   uint64
}

IndexMetaData holds header info that helps in reading the file.

func (IndexMetaData) Format

func (m IndexMetaData) Format() ([]byte, error)

formatFixedHeader formats the metadata header as a fixed-width string. The header (without newline) is exactly 99 bytes.

type IndexUserRecord

type IndexUserRecord struct {
	UserID   int64
	Username [80]byte
}

IndexUserRecord represents one fixed-width record.

type Message

type Message struct {
	FromUserId int
	FromName   string
	Message    string
	Item       *items.Item
	Gold       int
	Read       bool
	DateSent   time.Time
}

func (Message) DateString

func (m Message) DateString() string

type OnlineInfo

type OnlineInfo struct {
	Username      string
	CharacterName string
	Level         int
	Alignment     string
	Profession    string
	OnlineTime    int64
	OnlineTimeStr string
	IsAFK         bool
	Role          string
}

type Storage

type Storage struct {
	Items []items.Item
}

func (*Storage) AddItem

func (s *Storage) AddItem(i items.Item) bool

func (*Storage) FindItem

func (s *Storage) FindItem(itemName string) (items.Item, bool)

func (*Storage) GetItems

func (s *Storage) GetItems() []items.Item

func (*Storage) RemoveItem

func (s *Storage) RemoveItem(i items.Item) bool

type UserIndex

type UserIndex struct {
	Filename string
	// contains filtered or unexported fields
}

UserIndex is the central struct that holds the index filename and methods to work with the index.

func NewUserIndex

func NewUserIndex() *UserIndex

NewUserIndex creates a new instance of UserIndex using the configured file path.

func (*UserIndex) AddUser

func (idx *UserIndex) AddUser(userId int, username string) error

AppendUserRecord appends a new record to the index file and updates the header.

func (*UserIndex) Create

func (idx *UserIndex) Create() error

Writes a new index header then processes all user records to write a new index

func (*UserIndex) Delete

func (idx *UserIndex) Delete()

func (*UserIndex) Exists

func (idx *UserIndex) Exists() bool

func (*UserIndex) FindByUserId

func (idx *UserIndex) FindByUserId(userId int64) (string, bool)

FindByUserId searches for a user record matching the provided userId. If found, it returns the corresponding username.

func (*UserIndex) FindByUsername

func (idx *UserIndex) FindByUsername(username string) (int64, bool)

FindByUsername opens the index file, reads its header, then iterates over

func (*UserIndex) GetHighestUserId

func (idx *UserIndex) GetHighestUserId() int

func (*UserIndex) GetMetaData

func (idx *UserIndex) GetMetaData() IndexMetaData

func (*UserIndex) Rebuild

func (idx *UserIndex) Rebuild() error

Writes a new index header then processes all user records to write a new index

func (*UserIndex) RemoveByUsername

func (idx *UserIndex) RemoveByUsername(username string) error

RemoveUserRecordByUsername removes the first record that matches the provided username, updates the header, and rewrites the file.

type UserLog

type UserLog []UserLogEntry

func (*UserLog) Add

func (ul *UserLog) Add(cat string, message string)

func (*UserLog) Items

func (ul *UserLog) Items(yield func(UserLogEntry) bool)

type UserLogEntry

type UserLogEntry struct {
	Category  string    // optional category such as "combat" "communication" etc
	WhenRound uint64    // Game round it occured
	WhenTime  time.Time // Actual time it occured
	What      string    // String describing occurance
}

type UserRecord

type UserRecord struct {
	UserId        int                   `yaml:"userid"`
	Role          string                `yaml:"role"` // Roles group one or more admin commands
	Username      string                `yaml:"username"`
	Password      string                `yaml:"password"`
	Joined        time.Time             `yaml:"joined"`
	Macros        map[string]string     `yaml:"macros,omitempty"`  // Up to 10 macros, just string commands.
	Aliases       map[string]string     `yaml:"aliases,omitempty"` // string=>string remapping of commands
	Character     *characters.Character `yaml:"character,omitempty"`
	ItemStorage   Storage               `yaml:"itemstorage,omitempty"`
	ConfigOptions map[string]any        `yaml:"configoptions,omitempty"`
	Inbox         Inbox                 `yaml:"inbox,omitempty"`
	Muted         bool                  `yaml:"muted,omitempty"`        // Cannot SEND custom communications to anyone but admin/mods
	Deafened      bool                  `yaml:"deafened,omitempty"`     // Cannot HEAR custom communications from anyone but admin/mods
	ScreenReader  bool                  `yaml:"screenreader,omitempty"` // Are they using a screen reader? (We should remove excess symbols)
	EmailAddress  string                `yaml:"emailaddress,omitempty"` // Email address (if provided)
	TipsComplete  map[string]bool       `yaml:"tipscomplete,omitempty"` // Tips the user has followed/completed so they can be quiet
	EventLog      UserLog               `yaml:"-"`                      // Do not retain in user file (for now)
	LastMusic     string                `yaml:"-"`                      // Keeps track of the last music that was played
	// contains filtered or unexported fields
}

func GetAllActiveUsers

func GetAllActiveUsers() []*UserRecord

func GetByCharacterName

func GetByCharacterName(name string) *UserRecord

func GetByConnectionId

func GetByConnectionId(connectionId connections.ConnectionId) *UserRecord

func GetByUserId

func GetByUserId(userId int) *UserRecord

func LoadUser

func LoadUser(username string, skipValidation ...bool) (*UserRecord, error)

func LoginUser

func LoginUser(user *UserRecord, connectionId connections.ConnectionId) (*UserRecord, string, error)

First time creating a user.

func NewUserRecord

func NewUserRecord(userId int, connectionId uint64) *UserRecord

func (*UserRecord) AddBuff

func (u *UserRecord) AddBuff(buffId int, source string)

func (*UserRecord) AddCommandAlias

func (u *UserRecord) AddCommandAlias(input string, output string) (addedAlias string, deletedAlias string)

func (*UserRecord) BlockInput

func (u *UserRecord) BlockInput()

func (*UserRecord) ClearPrompt

func (u *UserRecord) ClearPrompt()

func (*UserRecord) ClientSettings

func (u *UserRecord) ClientSettings() connections.ClientSettings

func (*UserRecord) Command

func (u *UserRecord) Command(inputTxt string, waitSeconds ...float64)

func (*UserRecord) CommandFlagged

func (u *UserRecord) CommandFlagged(inputTxt string, flagData events.EventFlag, waitSeconds ...float64)

func (*UserRecord) ConnectionId

func (u *UserRecord) ConnectionId() uint64

func (*UserRecord) DidTip

func (u *UserRecord) DidTip(tipName string, completed ...bool) bool

func (*UserRecord) GetCommandPrompt

func (u *UserRecord) GetCommandPrompt() string

func (*UserRecord) GetConfigOption

func (u *UserRecord) GetConfigOption(key string) any

func (*UserRecord) GetConnectTime

func (u *UserRecord) GetConnectTime() time.Time

func (*UserRecord) GetLastInputRound

func (u *UserRecord) GetLastInputRound() uint64

func (*UserRecord) GetOnlineInfo

func (u *UserRecord) GetOnlineInfo() OnlineInfo

func (*UserRecord) GetPrompt

func (u *UserRecord) GetPrompt() *prompt.Prompt

func (*UserRecord) GetTempData

func (u *UserRecord) GetTempData(key string) any

func (*UserRecord) GetUnsentText

func (u *UserRecord) GetUnsentText() (unsent string, suggestion string)

func (*UserRecord) GrantXP

func (u *UserRecord) GrantXP(amt int, source string)

Grants experience to the user and notifies them Additionally accepts `source` as a short identifier of the XP source Example source: "combat", "quest progress", "trash cleanup", "exploration"

func (*UserRecord) HasRolePermission

func (u *UserRecord) HasRolePermission(permissionId string, simpleMatch ...bool) bool

func (*UserRecord) HasShop

func (u *UserRecord) HasShop() bool

func (*UserRecord) InputBlocked

func (u *UserRecord) InputBlocked() bool

func (*UserRecord) PasswordMatches

func (u *UserRecord) PasswordMatches(input string) bool

func (*UserRecord) PlayMusic

func (u *UserRecord) PlayMusic(musicFileOrId string)

func (*UserRecord) PlaySound

func (u *UserRecord) PlaySound(soundId string, category string)

func (*UserRecord) ProcessPromptString

func (u *UserRecord) ProcessPromptString(promptStr string) string

func (*UserRecord) ReplaceCharacter

func (u *UserRecord) ReplaceCharacter(replacement *characters.Character)

Replace a characters information with another.

func (*UserRecord) RoundTick

func (u *UserRecord) RoundTick()

func (*UserRecord) SendText

func (u *UserRecord) SendText(txt string)

func (*UserRecord) SendWebClientCommand

func (u *UserRecord) SendWebClientCommand(txt string)

func (*UserRecord) SetCharacterName

func (u *UserRecord) SetCharacterName(cn string) error

func (*UserRecord) SetConfigOption

func (u *UserRecord) SetConfigOption(key string, value any)

func (*UserRecord) SetLastInputRound

func (u *UserRecord) SetLastInputRound(rdNum uint64)

func (*UserRecord) SetPassword

func (u *UserRecord) SetPassword(pw string) error

func (*UserRecord) SetTempData

func (u *UserRecord) SetTempData(key string, value any)

func (*UserRecord) SetUnsentText

func (u *UserRecord) SetUnsentText(t string, suggest string)

The purpose of SetUnsentText(), GetUnsentText() is to Capture what the user is typing so that when we redraw the "prompt" or status bar, we can redraw what they were in the middle of typing. I don't like the idea of capturing it every time they hit a key though There is probably a better way.

func (*UserRecord) SetUsername

func (u *UserRecord) SetUsername(un string) error

func (*UserRecord) ShorthandId

func (u *UserRecord) ShorthandId() string

func (*UserRecord) StartPrompt

func (u *UserRecord) StartPrompt(command string, rest string) (*prompt.Prompt, bool)

Prompt related functionality

func (*UserRecord) SwapToAlt

func (u *UserRecord) SwapToAlt(targetAltName string) bool

func (*UserRecord) TempName

func (u *UserRecord) TempName() string

func (*UserRecord) TryCommandAlias

func (u *UserRecord) TryCommandAlias(input string) string

func (*UserRecord) UnblockInput

func (u *UserRecord) UnblockInput()

func (*UserRecord) WimpyCheck

func (u *UserRecord) WimpyCheck()

Jump to

Keyboard shortcuts

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