services

package
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: May 31, 2025 License: AGPL-3.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DBMutex sync.Mutex
)

Functions

func BalanceWarningFields

func BalanceWarningFields() []*discordgo.MessageEmbedField

func CheckAccount

func CheckAccount(ssoCookie string, userID string, captchaAPIKey string) (models.Status, error)

func CheckAccountAge

func CheckAccountAge(ssoCookie string) (int, int, int, int64, error)

func CheckAccounts

func CheckAccounts(s *discordgo.Session)

func CheckAndNotifyBalance

func CheckAndNotifyBalance(s *discordgo.Session, userID string, balance float64)

func CheckRateLimitWithBackoff added in v1.1.1

func CheckRateLimitWithBackoff(userID string, endpoint string) error
func validateRateLimit(userID string, action string, limit time.Duration) bool {
	userSettings, err := GetUserSettings(userID)
	if err != nil {
		logger.Log.WithError(err).Error("Failed to get user settings for rate limit check")
		return false
	}

	userSettings.EnsureMapsInitialized()

	lastAction, exists := userSettings.LastActionTimes[action]
	if !exists || time.Since(lastAction) >= limit {
		userSettings.LastActionTimes[action] = time.Now()
		if err := database.DB.Save(&userSettings).Error; err != nil {
			logger.Log.WithError(err).Error("Failed to update rate limit timestamp")
			return false
		}
		return true
	}

	return false
}

func CheckSSOCookieExpiration

func CheckSSOCookieExpiration(expirationTimestamp int64) (time.Duration, error)

func CheckVIPStatus

func CheckVIPStatus(ssoCookie string) (bool, error)

func CleanupInactiveUsers

func CleanupInactiveUsers()

func CleanupOldAnalyticsData

func CleanupOldAnalyticsData(retentionDays int) error

func CleanupOldRateLimitData

func CleanupOldRateLimitData()

func CreateAccountListEmbed added in v1.1.1

func CreateAccountListEmbed(accounts []models.Account, userID string, page int, totalPages int) *discordgo.MessageEmbed

func CreateAnnouncementEmbed

func CreateAnnouncementEmbed() *discordgo.MessageEmbed

func CreateCheckResultEmbed added in v1.1.1

func CreateCheckResultEmbed(account models.Account, status models.Status, userSettings models.UserSettings) *discordgo.MessageEmbed

func CreateErrorEmbed added in v1.1.1

func CreateErrorEmbed(title string, errorMessage string) *discordgo.MessageEmbed

func CreateInfoEmbed added in v1.1.1

func CreateInfoEmbed(title string, message string) *discordgo.MessageEmbed

func CreateSuccessEmbed added in v1.1.1

func CreateSuccessEmbed(title string, message string) *discordgo.MessageEmbed

func DecodeSSOCookie

func DecodeSSOCookie(encodedStr string) (int64, error)

func DisableUserCaptcha

func DisableUserCaptcha(s *discordgo.Session, userID string, reason string) error

func DoRequest added in v1.1.1

func DoRequest(req *http.Request) (*http.Response, error)

func EmbedTitleFromStatus

func EmbedTitleFromStatus(status models.Status) string

func FilterAccountsByShardAssignment added in v1.1.1

func FilterAccountsByShardAssignment(accounts []models.Account) []models.Account

func FilterUserSettingsByShardAssignment added in v1.1.1

func FilterUserSettingsByShardAssignment(settings []models.UserSettings) []models.UserSettings

func FormatDuration

func FormatDuration(d time.Duration) string

func FormatExpirationTime

func FormatExpirationTime(expirationTimestamp int64) string

func GenerateHeaders

func GenerateHeaders(ssoCookie string) map[string]string

func GetCheckStatus

func GetCheckStatus(isCheckDisabled bool) string

func GetColorForStatus

func GetColorForStatus(status models.Status, isExpiredCookie bool, isCheckDisabled bool) int

func GetCooldownDuration

func GetCooldownDuration(userSettings models.UserSettings, notificationType string, defaultCooldown time.Duration) time.Duration

func GetDailyStats

func GetDailyStats(day string) (map[string]interface{}, error)

func GetDefaultHTTPClient

func GetDefaultHTTPClient() *http.Client

func GetDefaultSettings

func GetDefaultSettings() (models.UserSettings, error)

func GetGatewayBotInfo added in v1.0.1

func GetGatewayBotInfo(token string) (*discordgo.GatewayBotResponse, error)

GetGatewayBotInfo retrieves the gateway bot info from Discord

func GetInstallationStats

func GetInstallationStats() (serverCount int64, directCount int64, err error)

func GetInteractionFlags added in v1.1.1

func GetInteractionFlags(i *discordgo.InteractionCreate, forceEphemeral bool) discordgo.MessageFlags

func GetLongTimeoutHTTPClient

func GetLongTimeoutHTTPClient() *http.Client

func GetNotificationChannel

func GetNotificationChannel(s *discordgo.Session, account models.Account, userSettings models.UserSettings) (string, error)

func GetRateLimitStatus added in v1.1.1

func GetRateLimitStatus(userID string, action string) (remaining time.Duration, isLimited bool)

func GetResponseChannel

func GetResponseChannel(s *discordgo.Session, userID string, i *discordgo.InteractionCreate) (string, error)

func GetSharedClient added in v1.1.1

func GetSharedClient() *http.Client

func GetStatusDescription

func GetStatusDescription(status models.Status, accountTitle string, ban models.Ban) string

func GetStatusIcon

func GetStatusIcon(status models.Status) string

func GetUserCaptchaKey

func GetUserCaptchaKey(userID string) (string, float64, error)

func GetUserEphemeralPreference added in v1.1.1

func GetUserEphemeralPreference(userID string) bool

func GetUserID

func GetUserID(i *discordgo.InteractionCreate) (string, error)

func GetUserRateLimitStatus

func GetUserRateLimitStatus(userID string) (bool, time.Duration, int)

func GetUserSettings

func GetUserSettings(userID string) (models.UserSettings, error)

func GetUserStats

func GetUserStats(userID string, days int) (map[string]interface{}, error)

func HandleStatusChange

func HandleStatusChange(s *discordgo.Session, account models.Account, newStatus models.Status, userSettings *models.UserSettings)

func InitHTTPClients

func InitHTTPClients()

func InitializeServices

func InitializeServices()

func IsServiceEnabled

func IsServiceEnabled(provider string) bool

func IsUserRateLimited

func IsUserRateLimited(userID string) bool
func CleanupOldRateLimitData() {
	adaptiveRateLimits.Lock()
	defer adaptiveRateLimits.Unlock()

	now := time.Now()
	initialCount := len(adaptiveRateLimits.UserBackoffs)
	cleaned := 0

	for userID, backoff := range adaptiveRateLimits.UserBackoffs {
		var recentHistory []time.Time
		for _, t := range backoff.NotificationHistory {
			if now.Sub(t) <= adaptiveRateLimits.HistoryWindow {
				recentHistory = append(recentHistory, t)
			}
		}

		if len(recentHistory) == 0 {
			backoff.BackoffMultiplier = 1.0
			backoff.ConsecutiveCount = 0
			cleaned++
		}

		backoff.NotificationHistory = recentHistory

		if len(recentHistory) == 0 && now.Sub(backoff.LastSent) > adaptiveRateLimits.HistoryWindow {
			delete(adaptiveRateLimits.UserBackoffs, userID)
			cleaned++
		}
	}

	logger.Log.Infof("Rate limit cleanup completed: processed %d entries, cleaned %d", initialCount, cleaned)
}

func LoadProxyConfiguration added in v1.1.1

func LoadProxyConfiguration(pm *ProxyManager)

func LogAccountCheck

func LogAccountCheck(accountID uint, userID string, status models.Status, success bool,
	captchaProvider string, captchaCost float64, responseTimeMs int64)

func LogCommandExecution

func LogCommandExecution(commandName, userID, guildID string, success bool, responseTimeMs int64, errorDetails string)

func LogInstallationStats

func LogInstallationStats(s *discordgo.Session)

func LogNotification

func LogNotification(userID string, accountID uint, notificationType string, success bool)

func LogStatusChange

func LogStatusChange(accountID uint, userID string, status models.Status,
	previousStatus models.Status)

func NewHeaderTransport added in v1.1.1

func NewHeaderTransport(base http.RoundTripper, userAgents []string) http.RoundTripper

func NotifyAdmin

func NotifyAdmin(s *discordgo.Session, message string)

func NotifyAdminWithCooldown

func NotifyAdminWithCooldown(s *discordgo.Session, message string, cooldownDuration time.Duration)

func NotifyCookieExpiringSoon

func NotifyCookieExpiringSoon(s *discordgo.Session, accounts []models.Account) error

func NotifyNewInstallation

func NotifyNewInstallation(s *discordgo.Session, context string)

func NotifyUserAboutDisabledAccount

func NotifyUserAboutDisabledAccount(s *discordgo.Session, account models.Account, reason string)

func QueueNotification

func QueueNotification(userID string, content string)

func RemoveCaptchaKey

func RemoveCaptchaKey(userID string) error

func ReportCapsolverTaskResult

func ReportCapsolverTaskResult(token string, isValid bool, errorMessage string)

func ResetRateLimitBackoff added in v1.1.1

func ResetRateLimitBackoff(userID string, endpoint string) error

func RespondWithPreference added in v1.1.1

func RespondWithPreference(s *discordgo.Session, i *discordgo.InteractionCreate, content string, embeds []*discordgo.MessageEmbed, forceEphemeral bool) error

func ScheduleBalanceChecks

func ScheduleBalanceChecks(s *discordgo.Session)

func ScheduleTempBanNotification

func ScheduleTempBanNotification(s *discordgo.Session, account models.Account, duration string)

func SendAnnouncementToAllUsers

func SendAnnouncementToAllUsers(s *discordgo.Session) error

func SendConsolidatedDailyUpdate

func SendConsolidatedDailyUpdate(s *discordgo.Session, userID string, userSettings models.UserSettings, accounts []models.Account)

func SendEmbedToUser

func SendEmbedToUser(s *discordgo.Session, userID string, i *discordgo.InteractionCreate, embed *discordgo.MessageEmbed) error

func SendGlobalAnnouncement

func SendGlobalAnnouncement(s *discordgo.Session, userID string) error

func SendMessageToUser

func SendMessageToUser(s *discordgo.Session, userID string, i *discordgo.InteractionCreate, message string) error

func SendNotification

func SendNotification(s *discordgo.Session, account models.Account, embed *discordgo.MessageEmbed, content, notificationType string) error

func StartAdminAPI

func StartAdminAPI()

func StartNotificationProcessor

func StartNotificationProcessor(discord *discordgo.Session)

func StoreCapsolverTaskInfo

func StoreCapsolverTaskInfo(taskID, token string)

func TrackMessageFailure

func TrackMessageFailure(userID string, errorMessage string)

func TrackUserInteraction

func TrackUserInteraction(s *discordgo.Session, i *discordgo.InteractionCreate) error

func UpdateCaptchaUsage

func UpdateCaptchaUsage(userID string) error

func UpdateMessageWithPreference added in v1.1.1

func UpdateMessageWithPreference(s *discordgo.Session, i *discordgo.InteractionCreate, content string, embeds []*discordgo.MessageEmbed, components []discordgo.MessageComponent) error

func UpdateRateLimitBackoff added in v1.1.1

func UpdateRateLimitBackoff(userID string, endpoint string) error

func ValidateCaptchaKey

func ValidateCaptchaKey(apiKey, provider string) (bool, float64, error)

func ValidateDefaultCapsolverConfig

func ValidateDefaultCapsolverConfig() error

func VerifyEZCaptchaConfig

func VerifyEZCaptchaConfig() bool

func VerifySSOCookie

func VerifySSOCookie(ssoCookie string) bool

Types

type AccountValidationResult

type AccountValidationResult struct {
	IsValid     bool
	Created     int64
	IsVIP       bool
	ExpiresAt   int64
	ProfileData map[string]interface{}
}

func ValidateAndGetAccountInfo

func ValidateAndGetAccountInfo(ssoCookie string) (*AccountValidationResult, error)

type AdaptiveRateLimits

type AdaptiveRateLimits struct {
	sync.RWMutex
	UserBackoffs  map[string]*UserBackoff
	BaseLimit     int
	HistoryWindow time.Duration
}

func (*AdaptiveRateLimits) GetBackoffDuration

func (a *AdaptiveRateLimits) GetBackoffDuration(userID string) time.Duration

type AppShardManager added in v1.1.1

type AppShardManager struct {
	sync.RWMutex
	ShardID       int
	TotalShards   int
	InstanceID    string
	HeartbeatTime time.Time
	Initialized   bool
}

func GetAppShardManager added in v1.1.1

func GetAppShardManager() *AppShardManager

func (*AppShardManager) FilterUsersByShardAssignment added in v1.1.1

func (asm *AppShardManager) FilterUsersByShardAssignment(userIDs []string) []string

func (*AppShardManager) GetGuildShardID added in v1.1.1

func (asm *AppShardManager) GetGuildShardID(guildID string) int

func (*AppShardManager) GetShardedUserCount added in v1.1.1

func (asm *AppShardManager) GetShardedUserCount() (int64, error)

func (*AppShardManager) GetShardingStatus added in v1.1.1

func (asm *AppShardManager) GetShardingStatus() map[string]interface{}

func (*AppShardManager) GetUserShardID added in v1.1.1

func (asm *AppShardManager) GetUserShardID(userID string) int

func (*AppShardManager) GuildBelongsToInstance added in v1.1.1

func (asm *AppShardManager) GuildBelongsToInstance(guildID string) bool

func (*AppShardManager) Initialize added in v1.1.1

func (asm *AppShardManager) Initialize() error

func (*AppShardManager) IsUserAssignedToShard added in v1.1.1

func (asm *AppShardManager) IsUserAssignedToShard(userID string) bool

func (*AppShardManager) ShardBelongsToInstance added in v1.1.1

func (asm *AppShardManager) ShardBelongsToInstance(userID string) bool

func (*AppShardManager) StartHeartbeat added in v1.1.1

func (asm *AppShardManager) StartHeartbeat(ctx context.Context)

type BanResponse added in v1.1.1

type BanResponse struct {
	Error     string `json:"error"`
	Success   string `json:"success"`
	CanAppeal bool   `json:"canAppeal"`
	Bans      []struct {
		Enforcement string `json:"enforcement"`
		Title       string `json:"title"`
		CanAppeal   bool   `json:"canAppeal"`
	} `json:"bans"`
}

type CapsolverSolver

type CapsolverSolver struct {
	APIKey string
	AppID  string
}

func (*CapsolverSolver) SolveReCaptchaV2

func (s *CapsolverSolver) SolveReCaptchaV2(siteKey, pageURL string) (string, error)

type CaptchaSolver

type CaptchaSolver interface {
	SolveReCaptchaV2(siteKey, pageURL string) (string, error)
}

func GetCaptchaSolver

func GetCaptchaSolver(userID string) (CaptchaSolver, error)

func NewCaptchaSolver

func NewCaptchaSolver(apiKey, provider string) (CaptchaSolver, error)

type EZCaptchaSolver

type EZCaptchaSolver struct {
	APIKey  string
	EzappID string
}

func (*EZCaptchaSolver) SolveReCaptchaV2

func (s *EZCaptchaSolver) SolveReCaptchaV2(siteKey, pageURL string) (string, error)

type InstallContext

type InstallContext string
const (
	ServerContext InstallContext = "server"
	DirectContext InstallContext = "direct"
)

type NotificationConfig

type NotificationConfig struct {
	Type              string
	Cooldown          time.Duration
	AllowConsolidated bool
	MaxPerHour        int
}

type NotificationItem

type NotificationItem struct {
	UserID     string
	Content    string
	AddedAt    time.Time
	RetryCount int
	Priority   int
}

type NotificationLimiter

type NotificationLimiter struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

func NewNotificationLimiter

func NewNotificationLimiter() *NotificationLimiter

func (*NotificationLimiter) CanSendNotification

func (nl *NotificationLimiter) CanSendNotification(userID string, notificationType string) bool

type NotificationQueue

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

func (*NotificationQueue) AddNotification

func (q *NotificationQueue) AddNotification(item NotificationItem)

func (*NotificationQueue) Shutdown

func (q *NotificationQueue) Shutdown(ctx context.Context) error

type NotificationState

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

type ProxyManager added in v1.1.1

type ProxyManager struct {
	sync.RWMutex
	Proxies            []string        // List of available proxies in format http://user:pass@host:port
	ActiveProxies      map[string]bool // Map of active proxies
	ProxyFailures      map[string]int  // Count of consecutive failures per proxy
	ProxyLastUsed      map[string]time.Time
	ProxyRateLimits    map[string]time.Time
	DefaultClient      *http.Client
	ProxyClients       map[string]*http.Client
	ProxyEnabled       bool
	RotationStrategy   string // "round-robin", "random", "least-used"
	CurrentProxyIndex  int
	MaxFailures        int
	CooldownPeriod     time.Duration
	ProxyRefreshPeriod time.Duration
	LastRefresh        time.Time
	UserAgents         []string
}

func GetProxyManager added in v1.1.1

func GetProxyManager() *ProxyManager

func (*ProxyManager) GetClient added in v1.1.1

func (pm *ProxyManager) GetClient() *http.Client

func (*ProxyManager) MarkProxyFailure added in v1.1.1

func (pm *ProxyManager) MarkProxyFailure(proxyURL string, reason string)

func (*ProxyManager) MarkProxyRateLimited added in v1.1.1

func (pm *ProxyManager) MarkProxyRateLimited(proxyURL string, duration time.Duration)

func (*ProxyManager) MarkProxySuccess added in v1.1.1

func (pm *ProxyManager) MarkProxySuccess(proxyURL string)

func (*ProxyManager) RefreshProxies added in v1.1.1

func (pm *ProxyManager) RefreshProxies()

type ShardManager added in v1.0.1

type ShardManager struct {
	sync.Mutex
	Sessions       []*discordgo.Session
	MaxConcurrency int
	TotalShards    int
	StartedShards  int
}

ShardManager handles the creation and management of Discord gateway shards

func NewShardManager added in v1.0.1

func NewShardManager() (*ShardManager, error)

NewShardManager creates a new shard manager

func (*ShardManager) Close added in v1.0.1

func (sm *ShardManager) Close()

Close closes all shard connections

func (*ShardManager) GetSession added in v1.0.1

func (sm *ShardManager) GetSession(guildID string) *discordgo.Session

GetSession returns the session for a specific guild

func (*ShardManager) StartShards added in v1.0.1

func (sm *ShardManager) StartShards(token string, handlers map[string]func(*discordgo.Session, *discordgo.InteractionCreate)) error

StartShards initializes and connects all shards

type TwoCaptchaSolver

type TwoCaptchaSolver struct {
	APIKey string
	SoftID string
}

func (*TwoCaptchaSolver) SolveReCaptchaV2

func (s *TwoCaptchaSolver) SolveReCaptchaV2(siteKey, pageURL string) (string, error)

type UserBackoff

type UserBackoff struct {
	LastSent            time.Time
	NotificationHistory []time.Time
	BackoffMultiplier   float64
	ConsecutiveCount    int
}

Jump to

Keyboard shortcuts

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