backend

package
v0.0.0-...-c0471e9 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2024 License: AGPL-3.0 Imports: 48 Imported by: 0

Documentation

Index

Constants

View Source
const (
	PermissionsDefault = 0o744
	PermissionWrite    = 0o600

	RequestSizeLimit = 20_000_000

	MaxAge = time.Hour * 24 * 7 * 4 // 4 weeks
)
View Source
const (
	// Recaptcha must return a value higher than this threshold to be considered valid.
	// Anything above the value of 0.5 is considered as "low risk".
	RecaptchaThreshold = 0.5

	// IPIntel must return a value below this threshold to be considered valid.
	// Anything below the value of 0.90 is considered as "low risk".
	IPIntelThreshold = 0.9
)
View Source
const (
	MaxRuleCount  = 25
	MaxRuleLength = 250
)
View Source
const (
	MaxBackgroundSize = 20_000_000 // 20MB file size.
	MaxFileResolution = 16_777_216 // Maximum pixels. This is ~4096x4096 for a 1:1 image.

	MIMEPNG  = "image/png"
	MIMEJPEG = "image/jpeg"
	MIMEGIF  = "image/gif"
	MIMEWEBP = "image/webp"
)
View Source
const (
	RefreshFrequency        = time.Minute * 15
	MinimumRefreshFrequency = time.Second * 30
	LazyRefreshFrequency    = time.Hour
)
View Source
const (
	UserKey         = "user"
	GuildKey        = "guild"
	GuildIDKey      = "guildID"
	KeyKey          = "key"
	TokenKey        = "token"
	StateKey        = "state"
	PreviousPathKey = "previous_path"
)
View Source
const (
	StateStringLength = 16
)
View Source
const VERSION = "0.1"

Variables

View Source
var (
	ErrBackendAlreadyExists = errors.New("backend already created")

	ErrMissingToken = errors.New("missing token in session")
	ErrMissingUser  = errors.New("missing user in session")

	ErrMissingParameter = errors.New("missing parameter \"%s\" in request")
	ErrWelcomerMissing  = errors.New("bot is missing from server")
	ErrEnsureFailure    = errors.New("failed to ensure guild")

	ErrOAuthFailure = errors.New("issue checking oauth2 token")
)
View Source
var (
	ErrRequired                 = errors.New("this field is required")
	ErrChannelInvalid           = errors.New("this channel does not exist")
	ErrInvalidJSON              = errors.New("invalid json")
	ErrInvalidColour            = errors.New("colour format is not recognised")
	ErrInvalidBackground        = errors.New("invalid background")
	ErrInvalidImageAlignment    = errors.New("image alignment is not recognised")
	ErrInvalidImageTheme        = errors.New("image theme is not recognised")
	ErrInvalidProfileBorderType = errors.New("profile border type is not recognised")

	ErrBackgroundTooLarge = errors.New("background size is too large")
	ErrFileSizeTooLarge   = errors.New("this file has an image resolution that is too high")
	ErrFileNotSupported   = errors.New("this file format is not supported")
	ErrConversionFailed   = errors.New("failed to convert background")

	ErrCannotUseCustomBackgrounds = errors.New("you cannot upload custom utils.backgrounds")

	ErrStringTooLong = errors.New("string is too long")
	ErrListTooLong   = errors.New("list is too long")
)

Validation errors.

View Source
var (
	ErrBorderwallRequestAlreadyVerified = errors.New("borderwall request already verified")
	ErrBorderwallInvalidKey             = errors.New("invalid key")
	ErrBorderwallUserInvalid            = errors.New("user is not the owner of this request")
	ErrRecaptchaValidationFailed        = errors.New("reCAPTCHA validation failed")
	ErrInsecureUser                     = errors.New("failed to verify your request. Please disable any proxy or VPN and try again")
)

Borderwall errors.

View Source
var (
	ErrInvalidContentType = errors.New("content type not accepted")
)

HTTP errors.

View Source
var OAuth2Config = &oauth2.Config{
	ClientID:     "",
	ClientSecret: "",
	Endpoint: oauth2.Endpoint{
		AuthURL:   discord.EndpointDiscord + discord.EndpointOAuth2Authorize + "?prompt=none",
		TokenURL:  discord.EndpointDiscord + "/api/v10" + discord.EndpointOAuth2Token,
		AuthStyle: oauth2.AuthStyleInParams,
	},
	RedirectURL: "",
	Scopes:      []string{"identify", "guilds"},
}
View Source
var RecoderQuantizationAttributes = recoder.NewQuantizationAttributes()

Functions

func BytesToJSONB

func BytesToJSONB(value []byte) pgtype.JSONB

func ClearTokenSession

func ClearTokenSession(session sessions.Session)

func GetPreviousPathSession

func GetPreviousPathSession(session sessions.Session) (previousPath string, ok bool)

func GetStateSession

func GetStateSession(session sessions.Session) (state string, ok bool)

func GetTokenSession

func GetTokenSession(session sessions.Session) (token oauth2.Token, ok bool)

func Int64SliceToString

func Int64SliceToString(values []int64) []string

func Int64ToStringPointer

func Int64ToStringPointer(value int64) *string

func JSONBToBytes

func JSONBToBytes(value pgtype.JSONB) []byte

func JSONBToString

func JSONBToString(value pgtype.JSONB) string

func MinimalRolesToMap

func MinimalRolesToMap(roles []MinimalRole) map[discord.Snowflake]MinimalRole

func ParseImageAlignment

func ParseImageAlignment(value string) utils.ImageAlignment

func ParseImageProfileBorderType

func ParseImageProfileBorderType(value string) utils.ImageProfileBorderType

func ParseImageTheme

func ParseImageTheme(value string) utils.ImageTheme

func PartialToGuildSettings

func PartialToGuildSettings(guildID int64, guildSettings *GuildSettingsSettings) *database.Guilds

func PartialToGuildSettingsAutoRolesSettings

func PartialToGuildSettingsAutoRolesSettings(guildID int64, guildSettings *GuildSettingsAutoRoles) *database.GuildSettingsAutoroles

func PartialToGuildSettingsBorderwallSettings

func PartialToGuildSettingsBorderwallSettings(guildID int64, guildSettings *GuildSettingsBorderwall) *database.GuildSettingsBorderwall

func PartialToGuildSettingsFreeRolesSettings

func PartialToGuildSettingsFreeRolesSettings(guildID int64, guildSettings *GuildSettingsFreeRoles) *database.GuildSettingsFreeroles

func PartialToGuildSettingsLeaverSettings

func PartialToGuildSettingsLeaverSettings(guildID int64, guildSettings *GuildSettingsLeaver) *database.GuildSettingsLeaver

func PartialToGuildSettingsRulesSettings

func PartialToGuildSettingsRulesSettings(guildID int64, guildSettings *GuildSettingsRules) *database.GuildSettingsRules

func PartialToGuildSettingsTempChannelsSettings

func PartialToGuildSettingsTempChannelsSettings(guildID int64, guildSettings *GuildSettingsTempChannels) *database.GuildSettingsTempchannels

func PartialToGuildSettingsTimeRolesSettings

func PartialToGuildSettingsTimeRolesSettings(guildID int64, guildSettings *GuildSettingsTimeRoles) *database.GuildSettingsTimeroles

func SetPreviousPathSession

func SetPreviousPathSession(session sessions.Session, previousPath string)

func SetStateSession

func SetStateSession(session sessions.Session, state string)

func SetTokenSession

func SetTokenSession(session sessions.Session, token oauth2.Token)

func SetUserSession

func SetUserSession(session sessions.Session, sessionUser SessionUser)

func StringPointerToInt64

func StringPointerToInt64(value *string) int64

func StringSliceToInt64

func StringSliceToInt64(value []string) []int64

func StringToJSONB

func StringToJSONB(value string) pgtype.JSONB

Types

type Backend

type Backend struct {
	Logger    zerolog.Logger
	StartTime time.Time

	Options BackendOptions

	RESTInterface discord.RESTInterface

	SandwichClient protobuf.SandwichClient
	GRPCInterface  sandwich.GRPC

	PrometheusHandler *gin_prometheus.Prometheus

	Route *gin.Engine

	Store Store

	Database *database.Queries
	Pool     *pgxpool.Pool

	IPChecker utils.IPChecker

	EmptySession      *discord.Session
	BotSession        *discord.Session
	DonatorBotSession *discord.Session

	PaypalClient *paypal.Client
	// contains filtered or unexported fields
}

func NewBackend

func NewBackend(ctx context.Context, logger zerolog.Logger, options BackendOptions) (b *Backend, err error)

NewBackend creates a new backend.

func (*Backend) Close

func (b *Backend) Close() error

Close gracefully closes the backend.

func (*Backend) GetBasicEventContext

func (b *Backend) GetBasicEventContext() (client *sandwich.EventContext)

GetEventContext.

func (*Backend) GetUserGuilds

func (b *Backend) GetUserGuilds(session sessions.Session) (guilds map[discord.Snowflake]*SessionGuild, err error)

func (*Backend) GetUserMemberships

func (b *Backend) GetUserMemberships(session sessions.Session) (memberships []*Membership, err error)

func (*Backend) Open

func (b *Backend) Open() error

Open sets up any services and starts the web server.

func (*Backend) PrepareGin

func (b *Backend) PrepareGin() *gin.Engine

PrepareGin prepares gin routes and middleware.

func (*Backend) SetupPrometheus

func (b *Backend) SetupPrometheus() error

SetupPrometheus sets up prometheus.

type BackendOptions

type BackendOptions struct {
	BotToken            string
	Conn                grpc.ClientConnInterface
	DiscordClientID     string
	DiscordClientSecret string
	Domain              string
	DonatorBotToken     string
	Host                string
	KeyPairs            string
	NginxAddress        string
	PaypalClientID      string
	PaypalClientSecret  string
	PaypalIsLive        bool
	Pool                *pgxpool.Pool
	PostgresAddress     string
	PrometheusAddress   string
	RedirectURL         string
	RESTInterface       discord.RESTInterface
}

BackendOptions represents any options passable when creating the backend service.

type BaseResponse

type BaseResponse struct {
	Data  interface{} `json:"data,omitempty"`
	Error string      `json:"error,omitempty"`
	Ok    bool        `json:"ok"`
}

BaseResponse represents the base response sent to a client.

type BorderwallRequest

type BorderwallRequest struct {
	Response        string `json:"response"`
	PlatformVersion string `json:"platform_version"`
}

type BorderwallResponse

type BorderwallResponse struct {
	GuildName string `json:"guild_name"`
	Valid     bool   `json:"valid"`
}

type CreatePaymentRequest

type CreatePaymentRequest struct {
	SKU      welcomer.SKUName  `json:"sku"`
	Currency welcomer.Currency `json:"currency"`
}

type CreatePaymentResponse

type CreatePaymentResponse struct {
	URL string `json:"url"`
}

type GetSKUsResponse

type GetSKUsResponse struct {
	AvailableCurrencies []welcomer.Currency   `json:"available_currencies"`
	DefaultCurrency     welcomer.Currency     `json:"default_currency"`
	SKUs                []welcomer.PricingSKU `json:"skus"`
}

type GetStatusResponse

type GetStatusResponse struct {
	UpdatedAt time.Time                  `json:"updated_at"`
	Managers  []GetStatusResponseManager `json:"managers"`
}

type GetStatusResponseManager

type GetStatusResponseManager struct {
	Name   string                   `json:"name"`
	Shards []GetStatusResponseShard `json:"shards"`
}

type GetStatusResponseShard

type GetStatusResponseShard struct {
	ShardID int `json:"shard_id"`
	Status  int `json:"status"`
	Latency int `json:"latency"`
	Guilds  int `json:"guilds"`
	Uptime  int `json:"uptime"`
}

type Guild

type Guild struct {
	CreatedAt            time.Time     `json:"created_at"`
	UpdatedAt            time.Time     `json:"updated_at"`
	Guild                *PartialGuild `json:"guild,omitempty"`
	SplashURL            string        `json:"splash_url"`
	EmbedColour          int           `json:"embed_colour"`
	HasWelcomerPro       bool          `json:"has_welcomer_pro"`
	HasCustomBackgrounds bool          `json:"has_custom_backgrounds"`
	StaffVisible         bool          `json:"staff_visible"`
	GuildVisible         bool          `json:"guild_visible"`
	AllowInvites         bool          `json:"allow_invites"`
}

type GuildSettingsAutoRoles

type GuildSettingsAutoRoles struct {
	Roles         []string `json:"roles"`
	ToggleEnabled bool     `json:"enabled"`
}

func GuildSettingsAutoRolesSettingsToPartial

func GuildSettingsAutoRolesSettingsToPartial(
	autoRoles *database.GuildSettingsAutoroles,
) *GuildSettingsAutoRoles

type GuildSettingsBorderwall

type GuildSettingsBorderwall struct {
	Channel         *string  `json:"channel"`
	MessageVerify   string   `json:"message_verify"`
	MessageVerified string   `json:"message_verified"`
	RolesOnJoin     []string `json:"roles_on_join"`
	RolesOnVerify   []string `json:"roles_on_verify"`
	ToggleEnabled   bool     `json:"enabled"`
	ToggleSendDm    bool     `json:"send_dm"`
}

func GuildSettingsBorderwallSettingsToPartial

func GuildSettingsBorderwallSettingsToPartial(borderwall database.GuildSettingsBorderwall) *GuildSettingsBorderwall

type GuildSettingsFreeRoles

type GuildSettingsFreeRoles struct {
	Roles         []string `json:"roles"`
	ToggleEnabled bool     `json:"enabled"`
}

func GuildSettingsFreeRolesSettingsToPartial

func GuildSettingsFreeRolesSettingsToPartial(
	freeRoles *database.GuildSettingsFreeroles,
) *GuildSettingsFreeRoles

type GuildSettingsLeaver

type GuildSettingsLeaver struct {
	Channel       *string `json:"channel"`
	MessageFormat string  `json:"message_json"`
	ToggleEnabled bool    `json:"enabled"`
}

func GuildSettingsLeaverSettingsToPartial

func GuildSettingsLeaverSettingsToPartial(leaver database.GuildSettingsLeaver) *GuildSettingsLeaver

type GuildSettingsRules

type GuildSettingsRules struct {
	Rules            []string `json:"rules"`
	ToggleEnabled    bool     `json:"enabled"`
	ToggleDmsEnabled bool     `json:"dms_enabled"`
}

func GuildSettingsRulesSettingsToPartial

func GuildSettingsRulesSettingsToPartial(
	rules *database.GuildSettingsRules,
) *GuildSettingsRules

type GuildSettingsSettings

type GuildSettingsSettings struct {
	Name             string `json:"name"`
	SiteSplashUrl    string `json:"site_splash_url"`
	EmbedColour      int32  `json:"embed_colour"`
	SiteStaffVisible bool   `json:"site_staff_visible"`
	SiteGuildVisible bool   `json:"site_guild_visible"`
	SiteAllowInvites bool   `json:"site_allow_invites"`
}

func GuildSettingsToPartial

func GuildSettingsToPartial(
	guildSettings *database.Guilds,
) *GuildSettingsSettings

type GuildSettingsTempChannels

type GuildSettingsTempChannels struct {
	ChannelLobby     *string `json:"channel_lobby"`
	ChannelCategory  *string `json:"channel_category"`
	DefaultUserCount int32   `json:"default_user_count"`
	ToggleEnabled    bool    `json:"enabled"`
	ToggleAutopurge  bool    `json:"autopurge"`
}

func GuildSettingsTempChannelsSettingsToPartial

func GuildSettingsTempChannelsSettingsToPartial(
	tempChannels *database.GuildSettingsTempchannels,
) *GuildSettingsTempChannels

type GuildSettingsTimeRoles

type GuildSettingsTimeRoles struct {
	Roles         []welcomer.GuildSettingsTimeRolesRole `json:"roles"`
	ToggleEnabled bool                                  `json:"enabled"`
}

func GuildSettingsTimeRolesSettingsToPartial

func GuildSettingsTimeRolesSettingsToPartial(
	timeroles *database.GuildSettingsTimeroles,
) *GuildSettingsTimeRoles

type GuildSettingsWelcomer

type GuildSettingsWelcomer struct {
	Text   *GuildSettingsWelcomerText   `json:"text"`
	Images *GuildSettingsWelcomerImages `json:"images"`
	DMs    *GuildSettingsWelcomerDms    `json:"dms"`
	Custom *GuildSettingsWelcomerCustom `json:"custom,omitempty"`
}

type GuildSettingsWelcomerCustom

type GuildSettingsWelcomerCustom struct {
	CustomBackgroundIDs []string `json:"custom_ids"`
}

type GuildSettingsWelcomerDms

type GuildSettingsWelcomerDms struct {
	MessageFormat       string `json:"message_json"`
	ToggleEnabled       bool   `json:"enabled"`
	ToggleUseTextFormat bool   `json:"reuse_message"`
	ToggleIncludeImage  bool   `json:"include_image"`
}

type GuildSettingsWelcomerImages

type GuildSettingsWelcomerImages struct {
	BackgroundName         string `json:"background"`
	ColourText             string `json:"text_colour"`
	ColourTextBorder       string `json:"text_colour_border"`
	ColourImageBorder      string `json:"border_colour"`
	ColourProfileBorder    string `json:"profile_border_colour"`
	ImageAlignment         string `json:"image_alignment"`
	ImageTheme             string `json:"image_theme"`
	ImageMessage           string `json:"message"`
	ImageProfileBorderType string `json:"profile_border_type"`
	ToggleEnabled          bool   `json:"enabled"`
	ToggleImageBorder      bool   `json:"enable_border"`
}

type GuildSettingsWelcomerText

type GuildSettingsWelcomerText struct {
	Channel       *string `json:"channel"`
	MessageFormat string  `json:"message_json"`
	ToggleEnabled bool    `json:"enabled"`
}

type Membership

type Membership struct {
	CreatedAt      time.Time         `json:"created_at"`
	UpdatedAt      time.Time         `json:"updated_at"`
	StartedAt      time.Time         `json:"started_at"`
	ExpiresAt      time.Time         `json:"expires_at"`
	Guild          MinimalGuild      `json:"guild"`
	GuildID        discord.Snowflake `json:"guild_id"`
	Status         int32             `json:"status"`
	MembershipType int32             `json:"membership_type"`
	MembershipUuid uuid.UUID         `json:"membership_uuid"`
}

Membership represents a membership to a server.

type MinimalChannel

type MinimalChannel struct {
	Name     string              `json:"name,omitempty"`
	ID       discord.Snowflake   `json:"id"`
	Position int32               `json:"position,omitempty"`
	Type     discord.ChannelType `json:"type"`
}

func ChannelsToMinimal

func ChannelsToMinimal(channels []discord.Channel) []MinimalChannel

type MinimalEmoji

type MinimalEmoji struct {
	Name      string            `json:"name"`
	ID        discord.Snowflake `json:"id"`
	Managed   bool              `json:"managed"`
	Animated  bool              `json:"animated"`
	Available bool              `json:"available"`
}

func EmojisToMinimal

func EmojisToMinimal(emojis []discord.Emoji) []MinimalEmoji

type MinimalGuild

type MinimalGuild struct {
	Name            string            `json:"name"`
	Icon            string            `json:"icon"`
	IconHash        string            `json:"icon_hash"`
	Splash          string            `json:"splash,omitempty"`
	DiscoverySplash string            `json:"discovery_splash,omitempty"`
	Description     string            `json:"description,omitempty"`
	Banner          string            `json:"banner,omitempty"`
	ID              discord.Snowflake `json:"id"`
}

func GuildToMinimal

func GuildToMinimal(guild discord.Guild) MinimalGuild

type MinimalRole

type MinimalRole struct {
	Name string            `json:"name"`
	ID   discord.Snowflake `json:"id"`

	Color        int32 `json:"color"`
	Position     int32 `json:"position"`
	IsAssignable bool  `json:"is_assignable"`
	IsElevated   bool  `json:"is_elevated"`
	// contains filtered or unexported fields
}

func CalculateRoleValues

func CalculateRoleValues(roles []MinimalRole, guildMembers []discord.GuildMember) (convertedRoles []MinimalRole)

func RolesToMinimal

func RolesToMinimal(roles []discord.Role) []MinimalRole

type MinimalUser

type MinimalUser struct {
	Username      string            `json:"username"`
	Discriminator string            `json:"discriminator"`
	GlobalName    string            `json:"global_name"`
	Avatar        string            `json:"avatar"`
	Memberships   []*Membership     `json:"memberships,omitempty"`
	ID            discord.Snowflake `json:"id"`
}

func SessionUserToMinimal

func SessionUserToMinimal(sessionUser *SessionUser) *MinimalUser

type PartialGuild

type PartialGuild struct {
	MinimalGuild
	Channels    []MinimalChannel `json:"channels"`
	Roles       []MinimalRole    `json:"roles"`
	Emojis      []MinimalEmoji   `json:"emojis"`
	MemberCount int32            `json:"member_count"`
}

func GuildToPartial

func GuildToPartial(guild discord.Guild) PartialGuild

type SessionGuild

type SessionGuild struct {
	Name                 string            `json:"name"`
	Icon                 string            `json:"icon"`
	ID                   discord.Snowflake `json:"id"`
	HasWelcomer          bool              `json:"has_welcomer"`
	HasWelcomerPro       bool              `json:"has_welcomer_pro"`
	HasCustomBackgrounds bool              `json:"has_custom_backgrounds"`
	HasElevation         bool              `json:"has_elevation"`
	IsOwner              bool              `json:"is_owner"`
}

SessionGuild represents a guild passed through /api/users/guilds and is stored in the session.

type SessionUser

type SessionUser struct {
	GuildsLastRequestedAt      time.Time                           `json:"-"`
	MembershipsLastRequestedAt time.Time                           `json:"-"`
	Guilds                     map[discord.Snowflake]*SessionGuild `json:"guilds"`
	Username                   string                              `json:"username"`
	Discriminator              string                              `json:"discriminator"`
	GlobalName                 string                              `json:"global_name"`
	Avatar                     string                              `json:"avatar"`
	Memberships                []*Membership                       `json:"memberships"`
	ID                         discord.Snowflake                   `json:"id"`
}

SessionUser stores the user in a session.

func GetUserSession

func GetUserSession(session sessions.Session) (sessionUser SessionUser, ok bool)

type Store

type Store interface {
	sessions.Store
}

func NewStore

func NewStore(db *pgxpool.Pool, keyPairs ...[]byte) (Store, error)

Jump to

Keyboard shortcuts

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