service

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2026 License: AGPL-3.0 Imports: 63 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BillingSourceWallet       = "wallet"
	BillingSourceSubscription = "subscription"
)
View Source
const (
	ViolationFeeCodePrefix     = "violation_fee."
	CSAMViolationMarker        = "Failed check: SAFETY_CHECK_TYPE"
	ContentViolatesUsageMarker = "Content violates usage guidelines"
)

Variables

View Source
var GetTaskAdaptorFunc func(platform constant.TaskPlatform) TaskPollingAdaptor

GetTaskAdaptorFunc 由 main 包注入,用于获取指定平台的任务适配器。 打破 service -> relay -> relay/channel -> service 的循环依赖。

Functions

func AcSearch

func AcSearch(findText string, dict []string, stopImmediately bool) (bool, []string)

func AddExp

func AddExp(pet *model.UserPet, amount int) (leveledUp bool, evolved bool, err error)

AddExp grants experience points to a pet, handling level-ups and auto-evolution. Returns whether a level-up occurred, whether an evolution occurred, and any error.

func AdminGetRecentTransactions

func AdminGetRecentTransactions(limit int) ([]model.PetMarketTransaction, error)

AdminGetRecentTransactions returns recent market transactions

func AdminGetUserPets

func AdminGetUserPets(userId int) ([]model.UserPet, error)

AdminGetUserPets returns all pets for a given user

func AdminGrantItem

func AdminGrantItem(userId, itemId, quantity int) error

AdminGrantItem grants items to a user

func AdminGrantPet

func AdminGrantPet(userId, speciesId, level, star int) (*model.UserPet, error)

AdminGrantPet creates a pet and assigns it to a user

func AdoptStarter

func AdoptStarter(userId int, speciesId int) (*model.UserPet, error)

AdoptStarter lets a user adopt one of the starter species

func AppendChannelAffinityAdminInfo

func AppendChannelAffinityAdminInfo(c *gin.Context, adminInfo map[string]interface{})

func ApplyChannelAffinityOverrideTemplate

func ApplyChannelAffinityOverrideTemplate(c *gin.Context, paramOverride map[string]interface{}) (map[string]interface{}, bool)

ApplyChannelAffinityOverrideTemplate merges per-rule channel override templates onto the selected channel override config.

func BlackjackAction added in v0.1.4

func BlackjackAction(userId int, gameId int, action string) (map[string]interface{}, error)

BlackjackAction 执行21点操作

func BuyItem

func BuyItem(userId int, itemId int, quantity int) error

BuyItem purchases an item from the shop using user quota

func BuyListing

func BuyListing(buyerId, listingId int) (*model.PetMarketTransaction, error)

BuyListing processes a fixed-price purchase

func CacheGetRandomSatisfiedChannel

func CacheGetRandomSatisfiedChannel(param *RetryParam) (*model.Channel, string, error)

CacheGetRandomSatisfiedChannel tries to get a random channel that satisfies the requirements. 尝试获取一个满足要求的随机渠道。

For "auto" tokenGroup with cross-group Retry enabled: 对于启用了跨分组重试的 "auto" tokenGroup:

  • Each group will exhaust all its priorities before moving to the next group. 每个分组会用完所有优先级后才会切换到下一个分组。

  • Uses ContextKeyAutoGroupIndex to track current group index. 使用 ContextKeyAutoGroupIndex 跟踪当前分组索引。

  • Uses ContextKeyAutoGroupRetryIndex to track the global Retry count when current group started. 使用 ContextKeyAutoGroupRetryIndex 跟踪当前分组开始时的全局重试次数。

  • priorityRetry = Retry - startRetryIndex, represents the priority level within current group. priorityRetry = Retry - startRetryIndex,表示当前分组内的优先级级别。

  • When GetRandomSatisfiedChannel returns nil (priorities exhausted), moves to next group. 当 GetRandomSatisfiedChannel 返回 nil(优先级用完)时,切换到下一个分组。

Example flow (2 groups, each with 2 priorities, RetryTimes=3): 示例流程(2个分组,每个有2个优先级,RetryTimes=3):

Retry=0: GroupA, priority0 (startRetryIndex=0, priorityRetry=0)
         分组A, 优先级0

Retry=1: GroupA, priority1 (startRetryIndex=0, priorityRetry=1)
         分组A, 优先级1

Retry=2: GroupA exhausted → GroupB, priority0 (startRetryIndex=2, priorityRetry=0)
         分组A用完 → 分组B, 优先级0

Retry=3: GroupB, priority1 (startRetryIndex=2, priorityRetry=1)
         分组B, 优先级1

func CalcOpenRouterCacheCreateTokens

func CalcOpenRouterCacheCreateTokens(usage dto.Usage, priceData types.PriceData) int

func CalculateSuccessRate

func CalculateSuccessRate(pet *model.UserPet, mission *model.PetMission) float64

CalculateSuccessRate computes the success probability for a pet on a mission Success rate = sum(stat_value * weight) / sum(max_stat * weight), clamped to [0.1, 0.95]

func CancelListing

func CancelListing(userId, listingId int) error

CancelListing cancels a listing and restores the pet

func Challenge added in v0.1.7

func Challenge(attackerUserId int, attackerPetId int, defenderUserId int) (map[string]interface{}, error)

Challenge 攻擂

func ChargeViolationFeeIfNeeded

func ChargeViolationFeeIfNeeded(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, apiErr *types.NewAPIError) bool

ChargeViolationFeeIfNeeded charges an additional fee after the normal flow finishes (including refund). It uses Grok fee settings as the fee policy.

func ChatCompletionsRequestToResponsesRequest

func ChatCompletionsRequestToResponsesRequest(req *dto.GeneralOpenAIRequest) (*dto.OpenAIResponsesRequest, error)

func CheckAndCompleteDispatches

func CheckAndCompleteDispatches(userId int) (int, error)

CheckAndCompleteDispatches performs lazy completion of expired dispatches

func CheckAndUpdateAchievements added in v0.1.4

func CheckAndUpdateAchievements(userId int, gameResult map[string]interface{}) ([]map[string]interface{}, error)

CheckAndUpdateAchievements 检查并更新用户成就进度 gameResult 包含当前游戏的结果信息:

game_type, bet_amount, payout, result, is_natural_blackjack, is_royal_flush, has_free_spin, is_allin

func CheckArenaTitles added in v0.1.7

func CheckArenaTitles(userId int, isAttacker bool, attackWins int, defenseStreak int)

CheckArenaTitles 检查擂台相关称号

func CheckCasinoTitles added in v0.1.7

func CheckCasinoTitles(userId int, stats map[string]interface{})

CheckCasinoTitles 检查赌场相关称号(在 SettleBet 后调用)

func CheckHeistTitles added in v0.1.7

func CheckHeistTitles(userId int)

CheckHeistTitles 检查打劫相关称号

func CheckNotificationLimit

func CheckNotificationLimit(userId int, notifyType string) (bool, error)

CheckNotificationLimit checks if the user has exceeded their notification limit Returns true if the user can send notification, false if limit exceeded

func CheckPetTitles added in v0.1.7

func CheckPetTitles(userId int)

CheckPetTitles 检查宠物相关称号

func CheckSensitiveMessages

func CheckSensitiveMessages(messages []dto.Message) ([]string, error)

func CheckSensitiveText

func CheckSensitiveText(text string) (bool, []string)

func CheckWinStreakTitles added in v0.1.7

func CheckWinStreakTitles(userId int, streak int)

CheckWinStreakTitles 检查连胜称号

func ClaimAchievementReward added in v0.1.4

func ClaimAchievementReward(userId int, achievementId int) (map[string]interface{}, error)

ClaimAchievementReward 领取成就奖励

func ClaudeErrorWrapper

func ClaudeErrorWrapper(err error, code string, statusCode int) *dto.ClaudeErrorWithStatusCode

func ClaudeErrorWrapperLocal

func ClaudeErrorWrapperLocal(err error, code string, statusCode int) *dto.ClaudeErrorWithStatusCode

func ClaudeToOpenAIRequest

func ClaudeToOpenAIRequest(claudeRequest dto.ClaudeRequest, info *relaycommon.RelayInfo) (*dto.GeneralOpenAIRequest, error)

func CleanPet

func CleanPet(userId int, petId int) (map[string]interface{}, error)

CleanPet performs a basic clean on a pet (no item consumed). Limited to 3 times per day. Restores +20 cleanliness and grants +5 EXP.

func CleanupFileSources

func CleanupFileSources(c *gin.Context)

CleanupFileSources 清理请求中所有注册的 FileSource 应在请求结束时调用(通常由中间件自动调用)

func ClearChannelAffinityCacheAll

func ClearChannelAffinityCacheAll() int

func ClearChannelAffinityCacheByRuleName

func ClearChannelAffinityCacheByRuleName(ruleName string) (int, error)

func CloseResponseBodyGracefully

func CloseResponseBodyGracefully(httpResponse *http.Response)

func CollectReward

func CollectReward(userId, dispatchId int) (map[string]interface{}, error)

CollectReward collects rewards from a completed dispatch

func CompleteExpiredAuctions

func CompleteExpiredAuctions() (int, error)

CompleteExpiredAuctions processes all expired auction listings

func ComputeCurrentStatus

func ComputeCurrentStatus(pet *model.UserPet) map[string]int

ComputeCurrentStatus calculates real-time pet status with lazy decay. It reads the stored status and applies time-based decay:

  • hunger: -4 per hour since last_fed_at
  • mood: -3 per hour since last_played_at
  • cleanliness: -2 per hour since updated_at

If any stat hits 0 and pet is "normal", state becomes "weak" (saved to DB). If all stats > 0 and pet is "weak", state becomes "normal" (saved to DB).

func ComputePetSummary

func ComputePetSummary(pet *model.UserPet, speciesOpt ...*model.PetSpecies) map[string]interface{}

ComputePetSummary returns a lightweight summary of a pet with computed status. An optional species parameter can be passed to avoid an extra DB query.

func ConvertSimpleChangeParams

func ConvertSimpleChangeParams(content string) *dto.MidjourneyRequest

func CountAudioTokenInput

func CountAudioTokenInput(audioBase64 string, audioFormat string) (int, error)

func CountAudioTokenOutput

func CountAudioTokenOutput(audioBase64 string, audioFormat string) (int, error)

func CountTextToken

func CountTextToken(text string, model string) int

CountTextToken 统计文本的token数量,仅OpenAI模型使用tokenizer,其余模型使用估算

func CountTokenInput

func CountTokenInput(input any, model string) int

func CountTokenRealtime

func CountTokenRealtime(info *relaycommon.RelayInfo, request dto.RealtimeEvent, model string) (int, int, error)

func CoverPlusActionToNormalAction

func CoverPlusActionToNormalAction(midjRequest *dto.MidjourneyRequest) *dto.MidjourneyResponse

func CoverTaskActionToModelName

func CoverTaskActionToModelName(platform constant.TaskPlatform, action string) string

func CovertMjpActionToModelName

func CovertMjpActionToModelName(mjAction string) string

func CreateMarketListing

func CreateMarketListing(userId, petId int, listingType string, price, minBid int, expiresAt int64) (*model.PetMarketListing, error)

CreateMarketListing creates a new market listing for a pet

func CreatePetActivity

func CreatePetActivity(userId, petId int, activityType string, data interface{}) error

CreatePetActivity creates a pet activity record

func DealBlackjack added in v0.1.4

func DealBlackjack(userId int, betAmount int) (map[string]interface{}, error)

DealBlackjack 发牌开始21点游戏

func DealPoker added in v0.1.4

func DealPoker(userId int, betAmount int) (map[string]interface{}, error)

DealPoker starts a new poker hand

func DecodeBase64AudioData

func DecodeBase64AudioData(audioBase64 string) (string, error)

func DecodeBase64FileData

func DecodeBase64FileData(base64String string) (string, string, error)

func DecodeBase64ImageData

func DecodeBase64ImageData(base64String string) (image.Config, string, string, error)

return image.Config, format, clean base64 string, error

func DecodeUrlImageData

func DecodeUrlImageData(imageUrl string) (image.Config, string, error)

func DetectFileType

func DetectFileType(mimeType string) types.FileType

DetectFileType 检测文件类型

func DisableChannel

func DisableChannel(channelError types.ChannelError, reason string)

disable & notify

func DispatchPet

func DispatchPet(userId, petId, missionId int) (map[string]interface{}, error)

DispatchPet sends a pet on a mission

func DispatchPlatformUpdate

func DispatchPlatformUpdate(platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task)

DispatchPlatformUpdate 按平台分发轮询更新

func DoDownloadRequest

func DoDownloadRequest(originUrl string, reason ...string) (resp *http.Response, err error)

func DoMidjourneyHttpRequest

func DoMidjourneyHttpRequest(c *gin.Context, timeout time.Duration, fullRequestURL string) (*dto.MidjourneyResponseWithStatusCode, []byte, error)

func DoWorkerRequest

func DoWorkerRequest(req *WorkerRequest) (*http.Response, error)

DoWorkerRequest 通过Worker发送请求

func EnableChannel

func EnableChannel(channelId int, usingKey string, channelName string)

func EquipTitle added in v0.1.7

func EquipTitle(userId int, titleId int) error

EquipTitle 佩戴称号

func EstimateRequestToken

func EstimateRequestToken(c *gin.Context, meta *types.TokenCountMeta, info *relaycommon.RelayInfo) (int, error)

func EstimateToken

func EstimateToken(provider Provider, text string) int

EstimateToken 计算 Token 数量

func EstimateTokenByModel

func EstimateTokenByModel(model, text string) int

func EvolvePet

func EvolvePet(userId int, petId int) error

EvolvePet evolves a pet to the next stage if conditions are met

func ExecuteHeist added in v0.1.7

func ExecuteHeist(userId int, heistType string) (map[string]interface{}, error)

ExecuteHeist 执行打劫

func ExtractCodexAccountIDFromJWT

func ExtractCodexAccountIDFromJWT(token string) (string, bool)

func ExtractEmailFromJWT

func ExtractEmailFromJWT(token string) (string, bool)

func ExtractOutputTextFromResponses

func ExtractOutputTextFromResponses(resp *dto.OpenAIResponsesResponse) string

func FeedAllPet added in v0.1.5

func FeedAllPet(userId int, petId int) (map[string]interface{}, error)

FeedAllPet feeds a pet with all food and potion items from the user's inventory until hunger, mood, and cleanliness are all >= 100, or items run out.

func FeedPet

func FeedPet(userId int, petId int, itemId int) (map[string]interface{}, error)

FeedPet feeds a pet using an item from the user's inventory. Returns a result map with exp/level change info, or an error.

func FetchCodexWhamUsage

func FetchCodexWhamUsage(
	ctx context.Context,
	client *http.Client,
	baseURL string,
	accessToken string,
	accountID string,
) (statusCode int, body []byte, err error)

func FusePet

func FusePet(userId, petId, materialPetId int) (map[string]interface{}, error)

FusePet fuses a material pet into a main pet to increase its star level

func GachaPull

func GachaPull(userId, poolId, count int) ([]map[string]interface{}, error)

GachaPull performs gacha pulls for a user

func GeminiToOpenAIRequest

func GeminiToOpenAIRequest(geminiRequest *dto.GeminiChatRequest, info *relaycommon.RelayInfo) (*dto.GeneralOpenAIRequest, error)

func GenerateAudioOtherInfo

func GenerateAudioOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, modelRatio, groupRatio, completionRatio, audioRatio, audioCompletionRatio, modelPrice, userGroupRatio float64) map[string]interface{}

func GenerateClaudeOtherInfo

func GenerateClaudeOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelRatio, groupRatio, completionRatio float64,
	cacheTokens int, cacheRatio float64,
	cacheCreationTokens int, cacheCreationRatio float64,
	cacheCreationTokens5m int, cacheCreationRatio5m float64,
	cacheCreationTokens1h int, cacheCreationRatio1h float64,
	modelPrice float64, userGroupRatio float64) map[string]interface{}

func GenerateMjOtherInfo

func GenerateMjOtherInfo(relayInfo *relaycommon.RelayInfo, priceData types.PriceData) map[string]interface{}

func GenerateTextOtherInfo

func GenerateTextOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelRatio, groupRatio, completionRatio float64,
	cacheTokens int, cacheRatio float64, modelPrice float64, userGroupRatio float64) map[string]interface{}

func GenerateWssOtherInfo

func GenerateWssOtherInfo(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.RealtimeUsage, modelRatio, groupRatio, completionRatio, audioRatio, audioCompletionRatio, modelPrice, userGroupRatio float64) map[string]interface{}

func GetAllTitles added in v0.1.7

func GetAllTitles() ([]model.Title, error)

GetAllTitles 获取所有称号

func GetArenaInfo added in v0.1.7

func GetArenaInfo(userId int) (map[string]interface{}, error)

GetArenaInfo 获取擂台信息

func GetArenaRanking added in v0.1.7

func GetArenaRanking(page, perPage int) ([]map[string]interface{}, int64, error)

GetArenaRanking 获取擂台排名

func GetBase64Data

func GetBase64Data(c *gin.Context, source *types.FileSource, reason ...string) (string, string, error)

GetBase64Data 获取 base64 编码的数据

func GetBattleById added in v0.1.7

func GetBattleById(id int) (*model.PetArenaBattle, error)

GetBattleById 获取战斗详情

func GetBattleHistory added in v0.1.7

func GetBattleHistory(userId int, page, perPage int) ([]model.PetArenaBattle, int64, error)

GetBattleHistory 获取用户战斗历史

func GetCallbackAddress

func GetCallbackAddress() string

func GetCasinoConfig added in v0.1.4

func GetCasinoConfig(userId int) (map[string]interface{}, error)

GetCasinoConfig 获取赌场配置(面向用户)

func GetFileBase64FromUrl

func GetFileBase64FromUrl(c *gin.Context, url string, reason ...string) (*types.LocalFileData, error)

GetFileBase64FromUrl 从 URL 获取文件的 base64 编码数据 Deprecated: 请使用 GetBase64Data 配合 types.NewURLFileSource 替代 此函数保留用于向后兼容,内部已重构为调用统一的文件服务

func GetFileTypeFromUrl

func GetFileTypeFromUrl(c *gin.Context, url string, reason ...string) (string, error)

GetFileTypeFromUrl 获取文件类型,返回 mime type, 例如 image/jpeg, image/png, image/gif, image/bmp, image/tiff, application/pdf 如果获取失败,返回 application/octet-stream

func GetGringottsInfo added in v0.1.7

func GetGringottsInfo(userId int) (map[string]interface{}, error)

GetGringottsInfo 获取金库信息(面向用户)

func GetHeistHistory added in v0.1.7

func GetHeistHistory(userId int, page, perPage int) ([]model.GringottsHeistRecord, int64, error)

GetHeistHistory 获取打劫历史

func GetHttpClient

func GetHttpClient() *http.Client

func GetHttpClientWithProxy

func GetHttpClientWithProxy(proxyURL string) (*http.Client, error)

GetHttpClientWithProxy returns the default client or a proxy-enabled one when proxyURL is provided.

func GetImageConfig

func GetImageConfig(c *gin.Context, source *types.FileSource) (image.Config, string, error)

GetImageConfig 获取图片配置

func GetImageFromUrl

func GetImageFromUrl(url string) (mimeType string, data string, err error)

GetImageFromUrl 获取图片的类型和base64编码的数据

func GetMarketListings

func GetMarketListings(page, pageSize int, filters model.MarketFilter) ([]model.PetMarketListing, int64, error)

GetMarketListings retrieves active listings with lazy auction cleanup

func GetMimeType

func GetMimeType(c *gin.Context, source *types.FileSource) (string, error)

GetMimeType 获取文件的 MIME 类型

func GetMimeTypeByExtension

func GetMimeTypeByExtension(ext string) string

func GetMjRequestModel

func GetMjRequestModel(relayMode int, midjRequest *dto.MidjourneyRequest) (string, *dto.MidjourneyResponse, bool)

func GetMyTitles added in v0.1.7

func GetMyTitles(userId int) ([]map[string]interface{}, error)

GetMyTitles 获取我的称号

func GetPetDetail

func GetPetDetail(userId int, petId int) (map[string]interface{}, error)

GetPetDetail returns a pet with its species info, computed status, and exp progress

func GetPetRanking

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

GetPetRanking returns top 20 rankings by level, pet count, and star count

func GetPreferredChannelByAffinity

func GetPreferredChannelByAffinity(c *gin.Context, modelName string, usingGroup string) (int, bool)

func GetPublicPetProfile

func GetPublicPetProfile(userId int) (map[string]interface{}, error)

GetPublicPetProfile returns a user's pets and stats for public viewing

func GetUserAchievementStatus added in v0.1.4

func GetUserAchievementStatus(userId int) ([]map[string]interface{}, error)

GetUserAchievementStatus 获取用户所有成就状态

func GetUserAutoGroup

func GetUserAutoGroup(userGroup string) []string

GetUserAutoGroup 根据用户分组获取自动分组设置

func GetUserCasinoStats added in v0.1.4

func GetUserCasinoStats(userId int) (map[string]interface{}, error)

GetUserCasinoStats 获取用户赌场统计

func GetUserGroupRatio

func GetUserGroupRatio(userGroup, group string) float64

GetUserGroupRatio 获取用户使用某个分组的倍率 userGroup 用户分组 group 需要获取倍率的分组

func GetUserUsableGroups

func GetUserUsableGroups(userGroup string) map[string]string

func GroupInUserUsableGroups

func GroupInUserUsableGroups(userGroup, groupName string) bool

func HasCSAMViolationMarker

func HasCSAMViolationMarker(err *types.NewAPIError) bool

func HatchPet

func HatchPet(userId int, petId int) error

HatchPet evolves a pet from egg (stage 0) to baby (stage 1)

func IOCopyBytesGracefully

func IOCopyBytesGracefully(c *gin.Context, src *http.Response, data []byte)

func InitAc

func InitAc(dict []string) *goahocorasick.Machine

func InitHttpClient

func InitHttpClient()

func InitTokenEncoders

func InitTokenEncoders()

func IsUserCasinoBanned added in v0.1.4

func IsUserCasinoBanned(userId int) bool

IsUserCasinoBanned 检查用户是否被赌场封禁

func IsViolationFeeCode

func IsViolationFeeCode(code types.ErrorCode) bool

func LoadFileSource

func LoadFileSource(c *gin.Context, source *types.FileSource, reason ...string) (*types.CachedFileData, error)

LoadFileSource 加载文件源数据 这是统一的入口,会自动处理缓存和不同的来源类型

func LogTaskConsumption

func LogTaskConsumption(c *gin.Context, info *relaycommon.RelayInfo)

LogTaskConsumption 记录任务消费日志和统计信息(仅记录,不涉及实际扣费)。 实际扣费已由 BillingSession(PreConsumeBilling + SettleBilling)完成。

func ManageSeason added in v0.1.7

func ManageSeason(action string) (map[string]interface{}, error)

ManageSeason 创建/结束赛季

func MarkChannelAffinityUsed

func MarkChannelAffinityUsed(c *gin.Context, selectedGroup string, channelID int)

func MidjourneyErrorWithStatusCodeWrapper

func MidjourneyErrorWithStatusCodeWrapper(code int, desc string, statusCode int) *dto.MidjourneyResponseWithStatusCode

func MidjourneyErrorWrapper

func MidjourneyErrorWrapper(code int, desc string) *dto.MidjourneyResponse

func NewProxyHttpClient

func NewProxyHttpClient(proxyURL string) (*http.Client, error)

NewProxyHttpClient 创建支持代理的 HTTP 客户端

func NormalizeViolationFeeError

func NormalizeViolationFeeError(err *types.NewAPIError) *types.NewAPIError

NormalizeViolationFeeError ensures: - if the CSAM marker is present, error.code is set to a stable violation-fee code and skip-retry is enabled. - if error.code already has the violation-fee prefix, skip-retry is enabled.

It must be called before retry decision logic.

func NotifyRootUser

func NotifyRootUser(t string, subject string, content string)

func NotifyUpstreamModelUpdateWatchers

func NotifyUpstreamModelUpdateWatchers(subject string, content string)

func NotifyUser

func NotifyUser(userId int, userEmail string, userSetting dto.UserSetting, data dto.Notify) error

func ObserveChannelAffinityUsageCacheByRelayFormat

func ObserveChannelAffinityUsageCacheByRelayFormat(c *gin.Context, usage *dto.Usage, relayFormat types.RelayFormat)

ObserveChannelAffinityUsageCacheByRelayFormat records usage cache stats with a stable rate mode derived from relay format.

func ObserveChannelAffinityUsageCacheFromContext

func ObserveChannelAffinityUsageCacheFromContext(c *gin.Context, usage *dto.Usage, cachedTokenRateMode string)

func PlaceBet added in v0.1.4

func PlaceBet(userId int, amount int) error

PlaceBet 扣除下注额度(原子操作,防止并发导致负余额)

func PlaceBid

func PlaceBid(bidderId, listingId, amount int) error

PlaceBid places a bid on an auction listing

func PlayBaccarat added in v0.1.4

func PlayBaccarat(userId int, betAmount int, betType string) (map[string]interface{}, error)

PlayBaccarat 百家乐游戏 (8副牌)

func PlayDice added in v0.1.4

func PlayDice(userId int, betAmount int, betType string, betValue *int) (map[string]interface{}, error)

PlayDice 掷骰子游戏

func PlayRoulette added in v0.1.4

func PlayRoulette(userId int, betAmount int, betType string, betNumber *int) (map[string]interface{}, error)

PlayRoulette 欧式轮盘游戏 (单零)

func PlaySlots added in v0.1.4

func PlaySlots(userId int, betAmount int) (map[string]interface{}, error)

PlaySlots plays the HP-themed slot machine (instant game)

func PlayWithPet

func PlayWithPet(userId int, petId int) (map[string]interface{}, error)

PlayWithPet interacts with a pet to increase mood. Returns a result map with exp/level change info, or an error.

func PokerAction added in v0.1.4

func PokerAction(userId int, gameId int, action string, raiseAmount int) (map[string]interface{}, error)

PokerAction handles a user's poker action

func PostAudioConsumeQuota

func PostAudioConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage, extraContent string)

func PostClaudeConsumeQuota

func PostClaudeConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.Usage)

func PostConsumeQuota

func PostConsumeQuota(relayInfo *relaycommon.RelayInfo, quota int, preConsumedQuota int, sendEmail bool) (err error)

func PostWssConsumeQuota

func PostWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, modelName string,
	usage *dto.RealtimeUsage, extraContent string)

func PreConsumeBilling

func PreConsumeBilling(c *gin.Context, preConsumedQuota int, relayInfo *relaycommon.RelayInfo) *types.NewAPIError

PreConsumeBilling 根据用户计费偏好创建 BillingSession 并执行预扣费。 会话存储在 relayInfo.Billing 上,供后续 Settle / Refund 使用。

func PreConsumeTokenQuota

func PreConsumeTokenQuota(relayInfo *relaycommon.RelayInfo, quota int) error

func PreWssConsumeQuota

func PreWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usage *dto.RealtimeUsage) error

func RecalculateTaskQuota

func RecalculateTaskQuota(ctx context.Context, task *model.Task, actualQuota int, reason string)

RecalculateTaskQuota 通用的异步差额结算。 actualQuota 是任务完成后的实际应扣额度,与预扣额度 (task.Quota) 做差额结算。 reason 用于日志记录(例如 "token重算" 或 "adaptor调整")。

func RecalculateTaskQuotaByTokens

func RecalculateTaskQuotaByTokens(ctx context.Context, task *model.Task, totalTokens int)

RecalculateTaskQuotaByTokens 根据实际 token 消耗重新计费(异步差额结算)。 当任务成功且返回了 totalTokens 时,根据模型倍率和分组倍率重新计算实际扣费额度, 与预扣费的差额进行补扣或退还。支持钱包和订阅计费来源。

func RecordChannelAffinity

func RecordChannelAffinity(c *gin.Context, channelID int)

func RefundTaskQuota

func RefundTaskQuota(ctx context.Context, task *model.Task, reason string)

RefundTaskQuota 统一的任务失败退款逻辑。 当异步任务失败时,将预扣的 quota 退还给用户(支持钱包和订阅),并退还令牌额度。

func RelayErrorHandler

func RelayErrorHandler(ctx context.Context, resp *http.Response, showBodyWhenFail bool) (newApiErr *types.NewAPIError)

func ReleasePet

func ReleasePet(userId int, petId int) error

ReleasePet permanently releases a pet (deletes it)

func RemoveDuplicate

func RemoveDuplicate(s []string) []string

func ResetProxyClientCache

func ResetProxyClientCache()

ResetProxyClientCache 清空代理客户端缓存,确保下次使用时重新初始化

func ResetStatusCode

func ResetStatusCode(newApiErr *types.NewAPIError, statusCodeMappingStr string)

func ResponseOpenAI2Claude

func ResponseOpenAI2Claude(openAIResponse *dto.OpenAITextResponse, info *relaycommon.RelayInfo) *dto.ClaudeResponse

func ResponseOpenAI2Gemini

func ResponseOpenAI2Gemini(openAIResponse *dto.OpenAITextResponse, info *relaycommon.RelayInfo) *dto.GeminiChatResponse

ResponseOpenAI2Gemini 将 OpenAI 响应转换为 Gemini 格式

func ResponseText2Usage

func ResponseText2Usage(c *gin.Context, responseText string, modeName string, promptTokens int) *dto.Usage

func ResponsesResponseToChatCompletionsResponse

func ResponsesResponseToChatCompletionsResponse(resp *dto.OpenAIResponsesResponse, id string) (*dto.OpenAITextResponse, *dto.Usage, error)

func SendWebhookNotify

func SendWebhookNotify(webhookURL string, secret string, data dto.Notify) error

SendWebhookNotify 发送 webhook 通知

func SensitiveWordContains

func SensitiveWordContains(text string) (bool, []string)

SensitiveWordContains 是否包含敏感词,返回是否包含敏感词和敏感词列表

func SensitiveWordReplace

func SensitiveWordReplace(text string, returnImmediately bool) (bool, []string, string)

SensitiveWordReplace 敏感词替换,返回是否包含敏感词和替换后的文本

func SetDefender added in v0.1.7

func SetDefender(userId int, petId int) error

SetDefender 设置守擂宠物

func SettleBet added in v0.1.4

func SettleBet(userId int, record *model.CasinoGameRecord, result string, payout int, gameExtra ...map[string]interface{}) error

SettleBet 结算游戏 gameExtra 用于传递额外的游戏信息给成就系统,可为 nil

func SettleBilling

func SettleBilling(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, actualQuota int) error

SettleBilling 执行计费结算。如果 RelayInfo 上有 BillingSession 则通过 session 结算, 否则回退到旧的 PostConsumeQuota 路径(兼容按次计费等场景)。

func SettleSeason added in v0.1.7

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

SettleSeason 结算赛季奖励

func ShouldChatCompletionsUseResponsesGlobal

func ShouldChatCompletionsUseResponsesGlobal(channelID int, channelType int, model string) bool

func ShouldChatCompletionsUseResponsesPolicy

func ShouldChatCompletionsUseResponsesPolicy(policy model_setting.ChatCompletionsToResponsesPolicy, channelID int, channelType int, model string) bool

func ShouldDisableChannel

func ShouldDisableChannel(channelType int, err *types.NewAPIError) bool

func ShouldEnableChannel

func ShouldEnableChannel(newAPIError *types.NewAPIError, status int) bool

func ShouldSkipRetryAfterChannelAffinityFailure

func ShouldSkipRetryAfterChannelAffinityFailure(c *gin.Context) bool

func StartCodexCredentialAutoRefreshTask

func StartCodexCredentialAutoRefreshTask()

func StartSubscriptionQuotaResetTask

func StartSubscriptionQuotaResetTask()

func StreamResponseOpenAI2Claude

func StreamResponseOpenAI2Claude(openAIResponse *dto.ChatCompletionsStreamResponse, info *relaycommon.RelayInfo) []*dto.ClaudeResponse

func StreamResponseOpenAI2Gemini

func StreamResponseOpenAI2Gemini(openAIResponse *dto.ChatCompletionsStreamResponse, info *relaycommon.RelayInfo) *dto.GeminiChatResponse

StreamResponseOpenAI2Gemini 将 OpenAI 流式响应转换为 Gemini 格式

func SundaySearch

func SundaySearch(text string, pattern string) bool

func TaskErrorFromAPIError

func TaskErrorFromAPIError(apiErr *types.NewAPIError) *dto.TaskError

TaskErrorFromAPIError 将 PreConsumeBilling 返回的 NewAPIError 转换为 TaskError。

func TaskErrorWrapper

func TaskErrorWrapper(err error, code string, statusCode int) *dto.TaskError

func TaskErrorWrapperLocal

func TaskErrorWrapperLocal(err error, code string, statusCode int) *dto.TaskError

func TaskPollingLoop

func TaskPollingLoop()

TaskPollingLoop 主轮询循环,每 15 秒检查一次未完成的任务

func TranscendPet added in v0.1.3

func TranscendPet(userId, petId, materialPetId int) (map[string]interface{}, error)

TranscendPet transcends two max-star same-species pets into a higher rarity.

func UnequipTitle added in v0.1.7

func UnequipTitle(userId int) error

UnequipTitle 取消佩戴称号

func UpdateSunoTasks

func UpdateSunoTasks(ctx context.Context, taskChannelM map[int][]string, taskM map[string]*model.Task) error

UpdateSunoTasks 按渠道更新所有 Suno 任务

func UpdateVideoTasks

func UpdateVideoTasks(ctx context.Context, platform constant.TaskPlatform, taskChannelM map[int][]string, taskM map[string]*model.Task) error

UpdateVideoTasks 按渠道更新所有视频任务

func UseItem

func UseItem(userId int, petId int, itemId int) error

UseItem applies a potion item on a pet

func ValidUsage

func ValidUsage(usage *dto.Usage) bool

func ValidateBet added in v0.1.4

func ValidateBet(userId int, amount int, gameType string) error

ValidateBet 验证下注

func WrapAsViolationFeeGrokCSAM

func WrapAsViolationFeeGrokCSAM(err *types.NewAPIError) *types.NewAPIError

Types

type BattleRound added in v0.1.7

type BattleRound struct {
	Round         int    `json:"round"`
	Attacker      string `json:"attacker"` // "attacker" or "defender"
	Action        string `json:"action"`   // "attack", "crit", "dodge"
	Damage        int    `json:"damage"`
	AttackerHPPct int    `json:"attacker_hp_pct"` // 百分比
	DefenderHPPct int    `json:"defender_hp_pct"`
	Description   string `json:"description"`
}

BattleRound 战斗回合

type BillingSession

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

BillingSession 封装单次请求的预扣费/结算/退款生命周期。 实现 relaycommon.BillingSettler 接口。

func NewBillingSession

func NewBillingSession(c *gin.Context, relayInfo *relaycommon.RelayInfo, preConsumedQuota int) (*BillingSession, *types.NewAPIError)

NewBillingSession 根据用户计费偏好创建 BillingSession,处理 subscription_first / wallet_first 的回退。

func (*BillingSession) GetPreConsumedQuota

func (s *BillingSession) GetPreConsumedQuota() int

GetPreConsumedQuota 返回实际预扣的额度。

func (*BillingSession) NeedsRefund

func (s *BillingSession) NeedsRefund() bool

NeedsRefund 返回是否存在需要退还的预扣状态。

func (*BillingSession) Refund

func (s *BillingSession) Refund(c *gin.Context)

Refund 退还所有预扣费,幂等安全,异步执行。

func (*BillingSession) Settle

func (s *BillingSession) Settle(actualQuota int) error

Settle 根据实际消耗额度进行结算。 资金来源和令牌额度分两步提交:若资金来源已提交但令牌调整失败, 会标记 fundingSettled 防止 Refund 对已提交的资金来源执行退款。

type BlackjackState added in v0.1.4

type BlackjackState struct {
	Deck        []Card   `json:"deck"`
	PlayerHands [][]Card `json:"player_hands"`
	DealerHand  []Card   `json:"dealer_hand"`
	CurrentHand int      `json:"current_hand"`
	Bets        []int    `json:"bets"`
	Phase       string   `json:"phase"`
}

BlackjackState 21点游戏状态

type Card added in v0.1.4

type Card struct {
	Rank string `json:"rank"`
	Suit string `json:"suit"`
}

Card 扑克牌

type ChannelAffinityCacheStats

type ChannelAffinityCacheStats struct {
	Enabled       bool           `json:"enabled"`
	Total         int            `json:"total"`
	Unknown       int            `json:"unknown"`
	ByRuleName    map[string]int `json:"by_rule_name"`
	CacheCapacity int            `json:"cache_capacity"`
	CacheAlgo     string         `json:"cache_algo"`
}

func GetChannelAffinityCacheStats

func GetChannelAffinityCacheStats() ChannelAffinityCacheStats

type ChannelAffinityStatsContext

type ChannelAffinityStatsContext struct {
	RuleName       string
	UsingGroup     string
	KeyFingerprint string
	TTLSeconds     int64
}

func GetChannelAffinityStatsContext

func GetChannelAffinityStatsContext(c *gin.Context) (ChannelAffinityStatsContext, bool)

type ChannelAffinityUsageCacheCounters

type ChannelAffinityUsageCacheCounters struct {
	CachedTokenRateMode string `json:"cached_token_rate_mode"`

	Hit           int64 `json:"hit"`
	Total         int64 `json:"total"`
	WindowSeconds int64 `json:"window_seconds"`

	PromptTokens         int64 `json:"prompt_tokens"`
	CompletionTokens     int64 `json:"completion_tokens"`
	TotalTokens          int64 `json:"total_tokens"`
	CachedTokens         int64 `json:"cached_tokens"`
	PromptCacheHitTokens int64 `json:"prompt_cache_hit_tokens"`
	LastSeenAt           int64 `json:"last_seen_at"`
}

type ChannelAffinityUsageCacheStats

type ChannelAffinityUsageCacheStats struct {
	RuleName            string `json:"rule_name"`
	UsingGroup          string `json:"using_group"`
	KeyFingerprint      string `json:"key_fp"`
	CachedTokenRateMode string `json:"cached_token_rate_mode"`

	Hit           int64 `json:"hit"`
	Total         int64 `json:"total"`
	WindowSeconds int64 `json:"window_seconds"`

	PromptTokens         int64 `json:"prompt_tokens"`
	CompletionTokens     int64 `json:"completion_tokens"`
	TotalTokens          int64 `json:"total_tokens"`
	CachedTokens         int64 `json:"cached_tokens"`
	PromptCacheHitTokens int64 `json:"prompt_cache_hit_tokens"`
	LastSeenAt           int64 `json:"last_seen_at"`
}

func GetChannelAffinityUsageCacheStats

func GetChannelAffinityUsageCacheStats(ruleName, usingGroup, keyFp string) ChannelAffinityUsageCacheStats

type CodexCredentialRefreshOptions

type CodexCredentialRefreshOptions struct {
	ResetCaches bool
}

type CodexOAuthAuthorizationFlow

type CodexOAuthAuthorizationFlow struct {
	State        string
	Verifier     string
	Challenge    string
	AuthorizeURL string
}

func CreateCodexOAuthAuthorizationFlow

func CreateCodexOAuthAuthorizationFlow() (*CodexOAuthAuthorizationFlow, error)

type CodexOAuthKey

type CodexOAuthKey struct {
	IDToken      string `json:"id_token,omitempty"`
	AccessToken  string `json:"access_token,omitempty"`
	RefreshToken string `json:"refresh_token,omitempty"`

	AccountID   string `json:"account_id,omitempty"`
	LastRefresh string `json:"last_refresh,omitempty"`
	Email       string `json:"email,omitempty"`
	Type        string `json:"type,omitempty"`
	Expired     string `json:"expired,omitempty"`
}

func RefreshCodexChannelCredential

func RefreshCodexChannelCredential(ctx context.Context, channelID int, opts CodexCredentialRefreshOptions) (*CodexOAuthKey, *model.Channel, error)

type CodexOAuthTokenResult

type CodexOAuthTokenResult struct {
	AccessToken  string
	RefreshToken string
	ExpiresAt    time.Time
}

func ExchangeCodexAuthorizationCode

func ExchangeCodexAuthorizationCode(ctx context.Context, code string, verifier string) (*CodexOAuthTokenResult, error)

func ExchangeCodexAuthorizationCodeWithProxy

func ExchangeCodexAuthorizationCodeWithProxy(ctx context.Context, code string, verifier string, proxyURL string) (*CodexOAuthTokenResult, error)

func RefreshCodexOAuthToken

func RefreshCodexOAuthToken(ctx context.Context, refreshToken string) (*CodexOAuthTokenResult, error)

func RefreshCodexOAuthTokenWithProxy

func RefreshCodexOAuthTokenWithProxy(ctx context.Context, refreshToken string, proxyURL string) (*CodexOAuthTokenResult, error)

type FundingSource

type FundingSource interface {
	// Source 返回资金来源标识:"wallet" 或 "subscription"
	Source() string
	// PreConsume 从该资金来源预扣 amount 额度
	PreConsume(amount int) error
	// Settle 根据差额调整资金来源(正数补扣,负数退还)
	Settle(delta int) error
	// Refund 退还所有预扣费
	Refund() error
}

FundingSource 抽象了预扣费的资金来源。

type MissionReward

type MissionReward struct {
	Type        string  `json:"type"`        // "quota", "item", "exp"
	Amount      int     `json:"amount"`      // amount to grant
	ItemId      int     `json:"id"`          // item id (for type=item)
	Probability float64 `json:"probability"` // 0.0-1.0
}

MissionReward defines a single reward entry in a mission's rewards JSON

type PetSystemStats

type PetSystemStats struct {
	TotalPets          int64            `json:"total_pets"`
	TotalUsersWithPets int64            `json:"total_users_with_pets"`
	TotalTransactions  int64            `json:"total_transactions"`
	TotalVolume        int64            `json:"total_volume"`
	RarityDistribution map[string]int64 `json:"rarity_distribution"`
}

PetSystemStats holds aggregated pet system statistics

func AdminGetPetSystemStats

func AdminGetPetSystemStats() (*PetSystemStats, error)

AdminGetPetSystemStats returns aggregate statistics about the pet system

type PityConfig

type PityConfig struct {
	SrPity  int `json:"sr_pity"`
	SsrPity int `json:"ssr_pity"`
}

PityConfig holds pity thresholds

type PokerPlayer added in v0.1.4

type PokerPlayer struct {
	Name     string `json:"name"`
	Cards    []Card `json:"cards"`
	Stack    int    `json:"stack"`
	Bet      int    `json:"bet"`       // current round bet
	TotalBet int    `json:"total_bet"` // total bet this hand
	Folded   bool   `json:"folded"`
	IsAI     bool   `json:"is_ai"`
	Style    string `json:"style"` // aggressive, conservative, balanced
	IsAllIn  bool   `json:"is_all_in"`
}

PokerPlayer represents a single player in the poker game

type PokerState added in v0.1.4

type PokerState struct {
	Deck           []Card        `json:"deck"`
	CommunityCards []Card        `json:"community_cards"`
	Players        []PokerPlayer `json:"players"`
	Pot            int           `json:"pot"`
	CurrentBet     int           `json:"current_bet"`
	Phase          string        `json:"phase"` // preflop, flop, turn, river, showdown, complete
	ActivePlayer   int           `json:"active_player"`
	DealerIndex    int           `json:"dealer_index"`
	LastRaiser     int           `json:"last_raiser"`
}

PokerState stores the full state of a Texas Hold'em hand

type Provider

type Provider string

Provider 定义模型厂商大类

const (
	OpenAI  Provider = "openai"  // 代表 GPT-3.5, GPT-4, GPT-4o
	Gemini  Provider = "gemini"  // 代表 Gemini 1.0, 1.5 Pro/Flash
	Claude  Provider = "claude"  // 代表 Claude 3, 3.5 Sonnet
	Unknown Provider = "unknown" // 兜底默认
)

type QuotaInfo

type QuotaInfo struct {
	InputDetails  TokenDetails
	OutputDetails TokenDetails
	ModelName     string
	UsePrice      bool
	ModelPrice    float64
	ModelRatio    float64
	GroupRatio    float64
}

type RankingEntry

type RankingEntry struct {
	UserId    int    `json:"user_id"`
	Username  string `json:"username"`
	AvatarUrl string `json:"avatar_url,omitempty"`
	Value     int    `json:"value"`
	PetName   string `json:"pet_name,omitempty"`
}

RankingEntry represents a single entry in a ranking list

type RetryParam

type RetryParam struct {
	Ctx        *gin.Context
	TokenGroup string
	ModelName  string
	Retry      *int
	// contains filtered or unexported fields
}

func (*RetryParam) GetRetry

func (p *RetryParam) GetRetry() int

func (*RetryParam) IncreaseRetry

func (p *RetryParam) IncreaseRetry()

func (*RetryParam) ResetRetryNextTry

func (p *RetryParam) ResetRetryNextTry()

func (*RetryParam) SetRetry

func (p *RetryParam) SetRetry(retry int)

type SpeciesPoolEntry

type SpeciesPoolEntry struct {
	SpeciesId int    `json:"species_id"`
	Rarity    string `json:"rarity"`
	Weight    int    `json:"weight"`
}

SpeciesPoolEntry represents one entry in a gacha pool's species list

type SubscriptionFunding

type SubscriptionFunding struct {

	// 以下字段在 PreConsume 成功后填充,供 RelayInfo 同步使用
	AmountTotal     int64
	AmountUsedAfter int64
	PlanId          int
	PlanTitle       string
	// contains filtered or unexported fields
}

func (*SubscriptionFunding) PreConsume

func (s *SubscriptionFunding) PreConsume(_ int) error

func (*SubscriptionFunding) Refund

func (s *SubscriptionFunding) Refund() error

func (*SubscriptionFunding) Settle

func (s *SubscriptionFunding) Settle(delta int) error

func (*SubscriptionFunding) Source

func (s *SubscriptionFunding) Source() string

type TaskPollingAdaptor

type TaskPollingAdaptor interface {
	Init(info *relaycommon.RelayInfo)
	FetchTask(baseURL string, key string, body map[string]any, proxy string) (*http.Response, error)
	ParseTaskResult(body []byte) (*relaycommon.TaskInfo, error)
	// AdjustBillingOnComplete 在任务到达终态(成功/失败)时由轮询循环调用。
	// 返回正数触发差额结算(补扣/退还),返回 0 保持预扣费金额不变。
	AdjustBillingOnComplete(task *model.Task, taskResult *relaycommon.TaskInfo) int
}

TaskPollingAdaptor 定义轮询所需的最小适配器接口,避免 service -> relay 的循环依赖

type TokenDetails

type TokenDetails struct {
	TextTokens  int
	AudioTokens int
}

type WalletFunding

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

func (*WalletFunding) PreConsume

func (w *WalletFunding) PreConsume(amount int) error

func (*WalletFunding) Refund

func (w *WalletFunding) Refund() error

func (*WalletFunding) Settle

func (w *WalletFunding) Settle(delta int) error

func (*WalletFunding) Source

func (w *WalletFunding) Source() string

type WebhookPayload

type WebhookPayload struct {
	Type      string        `json:"type"`
	Title     string        `json:"title"`
	Content   string        `json:"content"`
	Values    []interface{} `json:"values,omitempty"`
	Timestamp int64         `json:"timestamp"`
}

WebhookPayload webhook 通知的负载数据

type WorkerRequest

type WorkerRequest struct {
	URL     string            `json:"url"`
	Key     string            `json:"key"`
	Method  string            `json:"method,omitempty"`
	Headers map[string]string `json:"headers,omitempty"`
	Body    json.RawMessage   `json:"body,omitempty"`
}

WorkerRequest Worker请求的数据结构

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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