services

package
v3.10.0 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2025 License: MIT Imports: 40 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrUserNotAuthenticated = errors.New("user not authenticated")
	ErrSessionNotFound      = errors.New("session not found")
	ErrInvalidToken         = errors.New("invalid token")
	ErrTokenExpired         = errors.New("token expired")
	ErrUserAlreadyVerified  = errors.New("user already verified")
	ErrRateLimitExceeded    = errors.New("rate limit exceeded")
)
View Source
var (
	ErrTeamNotFound             = errors.New("team not found")
	ErrLocationNotFound         = errors.New("location not found")
	ErrCheckOutAtWrongLocation  = errors.New("team is not at the correct location to check out")
	ErrUnfinishedCheckIn        = errors.New("unfinished check in")
	ErrAlreadyCheckedIn         = errors.New("player has already scanned in")
	ErrUnecessaryCheckOut       = errors.New("player does not need to scan out")
	ErrInstanceSettingsNotFound = errors.New("instance settings not found")
)

Define errors.

View Source
var (
	ErrAllLocationsVisited = errors.New("all locations visited")
	ErrInstanceNotFound    = errors.New("instance not found")
)
View Source
var (
	ErrPasswordsDoNotMatch  = errors.New("passwords do not match")
	ErrIncorrectOldPassword = errors.New("current password is incorrect")
	ErrEmptyPassword        = errors.New("password cannot be empty")
	ErrPasswordUpdateFailed = errors.New("failed to update password")
)

Password-related errors

View Source
var ErrInvalidArgument = errors.New("invalid argument")
View Source
var (
	ErrPermissionDenied = errors.New("permission denied")
)

Functions

func NewValidationError

func NewValidationError(param string) error

NewValidationError returns a new error indicating that a parameter is invalid.

Types

type AssetGenerator

type AssetGenerator interface {
	// CreateQRCodeImage creates a QR code image with the given options
	// Supported options are:
	// - WithQRFormat(format string), where format is "png" or "svg"
	// - WithScanType(scanType string), where scanType is "in" or "out"
	// - WithForeground(color string), where color is a hex color code
	// - WithBackground(color string), where color is a hex color code
	CreateQRCodeImage(ctx context.Context, path string, content string, options ...QRCodeOption) (err error)
	// WithQRFormat sets the format of the QR code
	// Supported formats are "png" and "svg"
	WithQRFormat(format string) QRCodeOption
	// WithQRForeground sets the foreground color of the QR code
	WithQRForeground(color string) QRCodeOption
	// WithQRBackground sets the background color of the QR code
	WithQRBackground(color string) QRCodeOption

	// CreateArchive creates a zip archive from the given paths
	// Returns the path to the archive
	// Accepts a list of paths to files to add to the archive
	// Accepts an optional list of filenames to use for the files in the archive
	CreateArchive(ctx context.Context, paths []string) (path string, err error)
	// CreatePDF creates a PDF document from the given data
	// Returns the path to the PDF
	CreatePDF(ctx context.Context, data PDFData) (string, error)
	// GetQRCodePathAndContent returns the path and content for a QR code
	GetQRCodePathAndContent(action, id, name, extension string) (string, string)
}

func NewAssetGenerator

func NewAssetGenerator() AssetGenerator

type AuthService

type AuthService interface {
	AuthenticateUser(ctx context.Context, email, password string) (*models.User, error)
	GetAuthenticatedUser(r *http.Request) (*models.User, error)
	IsUserAuthenticated(r *http.Request) bool
	AllowGoogleLogin() bool
	OAuthLogin(ctx context.Context, provider string, user goth.User) (*models.User, error)
	CheckUserRegisteredWithOAuth(ctx context.Context, provider, userID string) (*models.User, error)
	CreateUserWithOAuth(ctx context.Context, user goth.User) (*models.User, error)
	CompleteUserAuth(w http.ResponseWriter, r *http.Request) (*models.User, error)
	VerifyEmail(ctx context.Context, token string) error
	SendEmailVerification(ctx context.Context, user *models.User) error
}

func NewAuthService

func NewAuthService(userRepository repositories.UserRepository) AuthService

type BlockService

type BlockService interface {
	// NewBlock creates a new content block of the specified type for the given location
	NewBlock(ctx context.Context, locationID string, blockType string) (blocks.Block, error)
	// NewBlockState creates a new player state for the given block and team
	NewBlockState(ctx context.Context, blockID, teamCode string) (blocks.PlayerState, error)
	// NewMockBlockState creates a mock player state (for testing/demo scenarios)
	NewMockBlockState(ctx context.Context, blockID, teamCode string) (blocks.PlayerState, error)

	// GetByBlockID fetches a content block by its ID
	GetByBlockID(ctx context.Context, blockID string) (blocks.Block, error)
	// GetBlockWithStateByBlockIDAndTeamCode fetches a block + its state
	// for the given block ID and team
	GetBlockWithStateByBlockIDAndTeamCode(ctx context.Context, blockID, teamCode string) (blocks.Block, blocks.PlayerState, error)
	// FindByLocationID fetches all content blocks for a location
	FindByLocationID(ctx context.Context, locationID string) (blocks.Blocks, error)
	// FindByLocationIDAndTeamCodeWithState fetches all blocks and their states
	// for the given location and team
	FindByLocationIDAndTeamCodeWithState(ctx context.Context, locationID, teamCode string) ([]blocks.Block, map[string]blocks.PlayerState, error)

	// UpdateBlock updates the data for the given block
	UpdateBlock(ctx context.Context, block blocks.Block, data map[string][]string) (blocks.Block, error)
	// UpdateState updates the player state for a block
	UpdateState(ctx context.Context, state blocks.PlayerState) (blocks.PlayerState, error)
	// ReorderBlocks changes the display/order of blocks at a location
	ReorderBlocks(ctx context.Context, locationID string, blockIDs []string) error

	// DeleteBlock removes the specified block and its associated player states
	DeleteBlock(ctx context.Context, blockID string) error

	// CheckValidationRequiredForLocation checks if any blocks in a location require validation
	CheckValidationRequiredForLocation(ctx context.Context, locationID string) (bool, error)
	// CheckValidationRequiredForCheckIn checks if any blocks still require validation for a check-in
	CheckValidationRequiredForCheckIn(ctx context.Context, locationID, teamCode string) (bool, error)
}

func NewBlockService

func NewBlockService(transactor db.Transactor, blockRepo repositories.BlockRepository, blockStateRepo repositories.BlockStateRepository) BlockService

type CheckInService

type CheckInService interface {
	// CompleteBlocks marks all blocks for a location as complete
	CompleteBlocks(ctx context.Context, teamCode string, locationID string) error
	// CheckIn logs a check in for a team at a location
	CheckIn(ctx context.Context, team models.Team, location models.Location, mustCheckOut bool, validationRequired bool) (models.CheckIn, error)
	// CheckOut logs a check out for a team at a location
	CheckOut(ctx context.Context, team *models.Team, location *models.Location) (models.CheckIn, error)
	// UpdateCheckIn updates an existing check-in
	UpdateCheckIn(ctx context.Context, checkIn *models.CheckIn) error
}

type ClueService

type ClueService interface {
	UpdateClues(ctx context.Context, location *models.Location, clues []string, clueIDs []string) error
}

func NewClueService

func NewClueService(clueRepo repositories.ClueRepository, locationRepo repositories.LocationRepository) ClueService

type EmailService

type EmailService interface {
	// SendVerificationEmail sends a verification email to the user to complete their registration
	SendVerificationEmail(ctx context.Context, user models.User) (*rest.Response, error)
	// SendContactEmail sends an email to the site owner from the contact form
	SendContactEmail(ctx context.Context, name, contactEmail, content string) (*rest.Response, error)
}

func NewEmailService

func NewEmailService() EmailService

type FacilitatorService

type FacilitatorService struct {
	// contains filtered or unexported fields
}

func (*FacilitatorService) CleanupExpiredTokens

func (s *FacilitatorService) CleanupExpiredTokens(ctx context.Context) error

CleanupExpiredTokens removes all expired facilitator tokens.

func (*FacilitatorService) CreateFacilitatorToken

func (s *FacilitatorService) CreateFacilitatorToken(ctx context.Context, instanceID string, locations []string, duration time.Duration) (string, error)

CreateFacilitatorToken generates and stores a facilitator access token.

func (*FacilitatorService) FormatTokenResponse

func (s *FacilitatorService) FormatTokenResponse(token *models.FacilitatorToken) (string, error)

FormatTokenResponse converts a FacilitatorToken to JSON output format.

func (*FacilitatorService) ValidateToken

func (s *FacilitatorService) ValidateToken(ctx context.Context, token string) (*models.FacilitatorToken, error)

ValidateToken checks if a token is valid and not expired.

type GameManagerService

type GameManagerService interface {
	// Game Control
	StartGame(ctx context.Context, user *models.User) (response ServiceResponse)
	StopGame(ctx context.Context, user *models.User) (response ServiceResponse)
	SetStartTime(ctx context.Context, user *models.User, time time.Time) (response ServiceResponse)
	SetEndTime(ctx context.Context, user *models.User, time time.Time) (response ServiceResponse)
	ScheduleGame(ctx context.Context, user *models.User, start time.Time, end time.Time) (response ServiceResponse)

	// Team & Location Management
	LoadTeams(ctx context.Context, teams *[]models.Team) error
	CreateLocation(ctx context.Context, user *models.User, data map[string]string) (models.Location, error)
	SaveLocation(ctx context.Context, location *models.Location, lat, lng, name string) error

	// Marker & Validation
	ValidateLocationMarker(user *models.User, id string) bool
	ValidateLocationID(user *models.User, id string) bool

	// Settings & Utilities
	UpdateSettings(ctx context.Context, settings *models.InstanceSettings, form url.Values) error
	DismissQuickstart(ctx context.Context, instanceID string) error
}

TODO: Split this service into smaller services.

func NewGameManagerService

func NewGameManagerService(
	transactor db.Transactor,
	locationService LocationService,
	userService UserService,
	teamService TeamService,
	markerRepo repositories.MarkerRepository,
	clueRepo repositories.ClueRepository,
	instanceRepo repositories.InstanceRepository,
	instanceSettingsRepo repositories.InstanceSettingsRepository,
	instanceService InstanceService,
) GameManagerService

type GameplayService

type GameplayService interface {
	CheckGameStatus(ctx context.Context, team *models.Team) *ServiceResponse
	GetTeamByCode(ctx context.Context, teamCode string) (*models.Team, error)
	GetMarkerByCode(ctx context.Context, locationCode string) *ServiceResponse
	StartPlaying(ctx context.Context, teamCode, customTeamName string) *ServiceResponse
	SuggestNextLocations(ctx context.Context, team *models.Team) ([]models.Location, error)
	// CheckIn checks a team in at a location
	// It also manages the points and mustScanOut fields
	// As well as checking if any blocks must be completed
	CheckIn(ctx context.Context, team *models.Team, locationCode string) error
	CheckOut(ctx context.Context, team *models.Team, locationCode string) error
	CheckValidLocation(ctx context.Context, team *models.Team, locationCode string) (bool, error)
	ValidateAndUpdateBlockState(ctx context.Context, team models.Team, data map[string][]string) (blocks.PlayerState, blocks.Block, error)
}

func NewGameplayService

func NewGameplayService(
	checkInService CheckInService,
	locationService LocationService,
	teamService TeamService,
	blockService BlockService,
	navigationService NavigationService,
	markerRepository repositories.MarkerRepository,
) GameplayService

type InstanceService

type InstanceService interface {
	// CreateInstance creates a new instance for the given user
	CreateInstance(ctx context.Context, name string, user *models.User) (*models.Instance, error)
	// DuplicateInstance duplicates an instance for the given user
	DuplicateInstance(ctx context.Context, user *models.User, id, name string) (*models.Instance, error)

	// FindByUserID returns all instances for the given user
	FindByUserID(ctx context.Context, userID string) ([]models.Instance, error)
	// FindInstanceIDsForUser returns the IDs of all instances for the given user
	FindInstanceIDsForUser(ctx context.Context, userID string) ([]string, error)

	// DeleteInstance deletes an instance for the given user
	DeleteInstance(ctx context.Context, user *models.User, instanceID, confirmName string) (bool, error)
	// GetInstanceSettings gets the settings for the given instance
	GetInstanceSettings(ctx context.Context, instanceID string) (*models.InstanceSettings, error)
}

func NewInstanceService

func NewInstanceService(
	transactor db.Transactor,
	locationService LocationService,
	teamService TeamService,
	instanceRepo repositories.InstanceRepository,
	instanceSettingsRepo repositories.InstanceSettingsRepository,
) InstanceService

type LocationActivity

type LocationActivity struct {
	Location models.Location
	Visited  bool
	Visiting bool
	Duration float64
	TimeIn   time.Time
	TimeOut  time.Time
}

type LocationService

type LocationService interface {
	// CreateLocation creates a new location
	CreateLocation(ctx context.Context, instanceID, name string, lat, lng float64, points int) (models.Location, error)
	// CreateLocationFromMarker creates a new location from an existing marker
	CreateLocationFromMarker(ctx context.Context, instanceID, name string, points int, markerCode string) (models.Location, error)
	// CreateMarker creates a new marker
	CreateMarker(ctx context.Context, name string, lat, lng float64) (models.Marker, error)
	// DuplicateLocation creates a new location given an existing location and the instance ID of the new location
	DuplicateLocation(ctx context.Context, location models.Location, newInstanceID string) (models.Location, error)

	// GetByID finds a location by its ID
	GetByID(ctx context.Context, locationID string) (*models.Location, error)
	// GetByInstanceAndCode finds a location by its instance and code
	GetByInstanceAndCode(ctx context.Context, instanceID string, code string) (*models.Location, error)
	// FindByInstance finds all locations for an instance
	FindByInstance(ctx context.Context, instanceID string) ([]models.Location, error)
	// FindMarkersNotInInstance finds all markers that are not in the given instance
	FindMarkersNotInInstance(ctx context.Context, instanceID string, otherInstances []string) ([]models.Marker, error)

	// Update visitor stats for a location
	IncrementVisitorStats(ctx context.Context, location *models.Location) error
	// UpdateCoords updates the coordinates for a location
	UpdateCoords(ctx context.Context, location *models.Location, lat, lng float64) error
	// UpdateName updates the name of a location
	UpdateName(ctx context.Context, location *models.Location, name string) error
	// UpdateLocation updates a location
	UpdateLocation(ctx context.Context, location *models.Location, data LocationUpdateData) error
	// ReorderLocations accepts IDs of locations and reorders them
	ReorderLocations(ctx context.Context, instanceID string, locationIDs []string) error

	// DeleteLocation deletes a location
	DeleteLocation(ctx context.Context, locationID string) error
	// DeleteByInstanceID deletes all locations for an instance
	DeleteLocations(ctx context.Context, tx *bun.Tx, locations []models.Location) error

	// LoadCluesForLocation loads the clues for a specific location if they are not already loaded
	LoadCluesForLocation(ctx context.Context, location *models.Location) error
	// LoadCluesForLocations loads the clues for all given locations if they are not already loaded
	LoadCluesForLocations(ctx context.Context, locations *[]models.Location) error
	// LoadRelations loads the related data for a location
	LoadRelations(ctx context.Context, location *models.Location) error
}

func NewLocationService

func NewLocationService(
	transactor db.Transactor,
	clueRepo repositories.ClueRepository,
	locationRepo repositories.LocationRepository,
	markerRepo repositories.MarkerRepository,
	blockRepo repositories.BlockRepository,
) LocationService

NewLocationService creates a new instance of LocationService.

type LocationUpdateData

type LocationUpdateData struct {
	Name      string
	Latitude  float64
	Longitude float64
	Points    int
}

LocationData is the data required to update a new location. Blank fields are ignored, with the exception of Clues and ClueIDs which are always required.

type NavigationService interface {
	// CheckValidLocation checks if the location code is valid for the team to check in to
	// This function returns an error if the location code is invalid
	CheckValidLocation(ctx context.Context, team *models.Team, settings *models.InstanceSettings, markerID string) (bool, error)
	// DetermineNextLocations returns the next locations for the team to visit
	// Team.Instance.Settings must be loaded before calling this function
	DetermineNextLocations(ctx context.Context, team *models.Team) ([]models.Location, error)
	// HasVisited returns true if the team has visited the location
	HasVisited(checkins []models.CheckIn, locationID string) bool
}

func NewNavigationService

func NewNavigationService() NavigationService

type NotificationService

type NotificationService interface {
	SendNotification(ctx context.Context, teamCode string, content string) (models.Notification, error)
	SendNotificationToAllTeams(ctx context.Context, instanceID string, content string) error
	GetNotifications(ctx context.Context, teamCode string) ([]models.Notification, error)
	DismissNotification(ctx context.Context, notificationID string) error
}

func NewNotificationService

func NewNotificationService(
	notificationRepository repositories.NotificationRepository,
	teamRepository repositories.TeamRepository,
) NotificationService

type PDFData

type PDFData struct {
	InstanceName string
	Pages        PDFPages
}

type PDFPage

type PDFPage struct {
	LocationName string
	URL          string
	ImagePath    string
	// []int{R, G, B}
	Background []int
}

type PDFPages

type PDFPages []PDFPage

type QRCodeOption

type QRCodeOption func(*QRCodeOptions)

type QRCodeOptions

type QRCodeOptions struct {
	// contains filtered or unexported fields
}

type ServiceResponse

type ServiceResponse struct {
	FlashMessages []flash.Message
	Error         error
	Data          map[string]interface{}
}

func (*ServiceResponse) AddFlashMessage

func (r *ServiceResponse) AddFlashMessage(message flash.Message)

Add a flash message to the response.

func (*ServiceResponse) HasError

func (r *ServiceResponse) HasError() bool

Check if there is an error.

func (*ServiceResponse) HasFlash

func (r *ServiceResponse) HasFlash() bool

Check if there is a flash message.

type ShareLinkData added in v3.5.0

type ShareLinkData struct {
	TemplateID string
	Validity   string
	MaxUses    int
	Regenerate bool
}

type TeamActivity

type TeamActivity struct {
	Team      models.Team
	Locations []LocationActivity
}

type TeamService

type TeamService interface {
	// AddTeams adds teams to the database
	AddTeams(ctx context.Context, instanceID string, count int) ([]models.Team, error)

	// FindAll returns all teams for an instance
	FindAll(ctx context.Context, instanceID string) ([]models.Team, error)
	// FindTeamByCode returns a team by code
	FindTeamByCode(ctx context.Context, code string) (*models.Team, error)
	// GetTeamActivityOverview returns a list of teams and their activity
	GetTeamActivityOverview(ctx context.Context, instanceID string, locations []models.Location) ([]TeamActivity, error)

	// Update updates a team in the database
	Update(ctx context.Context, team *models.Team) error
	// AwardPoints awards points to a team
	AwardPoints(ctx context.Context, team *models.Team, points int, reason string) error
	// Reset wipes a team's progress for re-use
	Reset(ctx context.Context, instanceID string, teamCodes []string) error

	// Delete removes a team from the database
	Delete(ctx context.Context, instanceID string, teamCode string) error
	// DeleteByInstanceID removes all teams for a specific instance
	DeleteByInstanceID(ctx context.Context, tx *bun.Tx, instanceID string) error

	// LoadRelation loads relations for a team
	LoadRelation(ctx context.Context, team *models.Team, relation string) error
	// LoadRelations loads all relations for a team
	LoadRelations(ctx context.Context, team *models.Team) error
}

func NewTeamService

NewTeamService creates a new TeamService.

type TemplateService added in v3.5.0

type TemplateService struct {
	// contains filtered or unexported fields
}

func NewTemplateService added in v3.5.0

func NewTemplateService(
	transactor db.Transactor,
	locationService LocationService,
	instanceRepo repositories.InstanceRepository,
	instanceSettingsRepo repositories.InstanceSettingsRepository,
	shareLinkRepo repositories.ShareLinkRepository,
) TemplateService

func (*TemplateService) CreateFromInstance added in v3.5.0

func (s *TemplateService) CreateFromInstance(ctx context.Context, userID, instanceID, name string) (*models.Instance, error)

CreateFromInstance creates a new template from an existing instance.

func (s *TemplateService) CreateShareLink(ctx context.Context, userID string, data ShareLinkData) (string, error)

CreateShareLink creates a share link for a template.

func (*TemplateService) Find added in v3.5.0

func (s *TemplateService) Find(ctx context.Context, userID string) ([]models.Instance, error)

Find retrieves all templates.

func (*TemplateService) GetByID added in v3.5.0

func (s *TemplateService) GetByID(ctx context.Context, id string) (*models.Instance, error)

GetByID retrieves a template by ID.

func (s *TemplateService) GetShareLink(ctx context.Context, id string) (*models.ShareLink, error)

GetShareLink retrieves a share link by ID.

func (*TemplateService) LaunchInstance added in v3.5.0

func (s *TemplateService) LaunchInstance(ctx context.Context, userID, templateID, name string, regen_location_codes bool) (*models.Instance, error)

LaunchInstance creates a new instance from a template.

func (s *TemplateService) LaunchInstanceFromShareLink(ctx context.Context, userID, shareLinkID string, name string, regen bool) (*models.Instance, error)

LaunchInstanceFromShareLink creates a new instance from a share link.

func (*TemplateService) Update added in v3.5.0

func (s *TemplateService) Update(ctx context.Context, instance *models.Instance) error

Update updates a template.

type UploadMetadata

type UploadMetadata struct {
	InstanceID string `json:"instanceID,omitempty"`
	TeamID     string `json:"teamID,omitempty"`
	BlockID    string `json:"blockID,omitempty"`
	LocationID string `json:"locationID,omitempty"`
}

UploadMetadata contains metadata for an uploaded file.

type UploadService

type UploadService struct {
	// contains filtered or unexported fields
}

UploadService provides methods for uploading files and managing metadata.

func NewUploadService

func NewUploadService(repo repositories.UploadsRepository, storage UploadStorage) UploadService

NewUploadService creates a new UploadService.

func (*UploadService) Search

func (s *UploadService) Search(ctx context.Context, filters map[string]string) ([]*models.Upload, error)

Search retrieves uploads based on search criteria.

func (*UploadService) UploadFile

func (s *UploadService) UploadFile(ctx context.Context, file multipart.File, fileHeader *multipart.FileHeader, data UploadMetadata) (*models.Upload, error)

UploadFile uploads a file and saves metadata to the database.

type UploadStorage

type UploadStorage interface {
	Upload(ctx context.Context, file multipart.File, filename string) (map[string]string, string, error)
	Type() string
}

UploadStorage is an interface for storing files.

type UserService

type UserService interface {
	// CreateUser creates a new user
	CreateUser(ctx context.Context, user *models.User, passwordConfirm string) error

	// GetUserByEmail retrieves a user by their email address
	GetUserByEmail(ctx context.Context, email string) (*models.User, error)

	// UpdateUser updates a user
	UpdateUser(ctx context.Context, user *models.User) error

	// UpdateUserProfile updates a user's profile with form data
	UpdateUserProfile(ctx context.Context, user *models.User, profile map[string]string) error

	// ChangePassword changes a user's password
	ChangePassword(ctx context.Context, user *models.User, oldPassword, newPassword, confirmPassword string) error

	// SwitchInstance switches the user's current instance
	SwitchInstance(ctx context.Context, user *models.User, instanceID string) error

	// DeleteUser deletes a user
	DeleteUser(ctx context.Context, userID string) error
}

func NewUserService

func NewUserService(transactor db.Transactor, userRepository repositories.UserRepository, instanceRepository repositories.InstanceRepository) UserService

Jump to

Keyboard shortcuts

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