model

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: 41 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LogTypeUnknown = 0
	LogTypeTopup   = 1
	LogTypeConsume = 2
	LogTypeManage  = 3
	LogTypeSystem  = 4
	LogTypeError   = 5
	LogTypeRefund  = 6
)

don't use iota, avoid change log type value

View Source
const (
	NameRuleExact = iota
	NameRulePrefix
	NameRuleContains
	NameRuleSuffix
)
View Source
const (
	SocialCommentStatusVisible = 1
	SocialCommentStatusHidden  = 2
)
View Source
const (
	NotificationTypeLike    = "like"
	NotificationTypeComment = "comment"
	NotificationTypeFollow  = "follow"
	NotificationTypeRepost  = "repost"
)
View Source
const (
	SocialPostStatusVisible = 1
	SocialPostStatusHidden  = 2
)
View Source
const (
	SubscriptionDurationYear   = "year"
	SubscriptionDurationMonth  = "month"
	SubscriptionDurationDay    = "day"
	SubscriptionDurationHour   = "hour"
	SubscriptionDurationCustom = "custom"
)

Subscription duration units

View Source
const (
	SubscriptionResetNever   = "never"
	SubscriptionResetDaily   = "daily"
	SubscriptionResetWeekly  = "weekly"
	SubscriptionResetMonthly = "monthly"
	SubscriptionResetCustom  = "custom"
)

Subscription quota reset period

View Source
const (
	TaskStatusNotStart   TaskStatus = "NOT_START"
	TaskStatusSubmitted             = "SUBMITTED"
	TaskStatusQueued                = "QUEUED"
	TaskStatusInProgress            = "IN_PROGRESS"
	TaskStatusFailure               = "FAILURE"
	TaskStatusSuccess               = "SUCCESS"
	TaskStatusUnknown               = "UNKNOWN"
)
View Source
const (
	BatchUpdateTypeUserQuota = iota
	BatchUpdateTypeTokenQuota
	BatchUpdateTypeUsedQuota
	BatchUpdateTypeChannelUsedQuota
	BatchUpdateTypeRequestCount
	BatchUpdateTypeCount // if you add a new type, you need to add a new map and a new lock
)
View Source
const UserNameMaxLength = 20

Variables

View Source
var (
	ErrPasskeyNotFound         = errors.New("passkey credential not found")
	ErrFriendlyPasskeyNotFound = errors.New("Passkey 验证失败,请重试或联系管理员")
)
View Source
var (
	ErrSubscriptionOrderNotFound      = errors.New("subscription order not found")
	ErrSubscriptionOrderStatusInvalid = errors.New("subscription order status invalid")
)
View Source
var CacheQuotaData = make(map[string]*QuotaData)
View Source
var CacheQuotaDataLock = sync.Mutex{}
View Source
var DB *gorm.DB
View Source
var ErrRedeemFailed = errors.New("redeem.failed")

ErrRedeemFailed is returned when redemption fails due to database error

View Source
var ErrTwoFANotEnabled = errors.New("用户未启用2FA")
View Source
var LOG_DB *gorm.DB

Functions

func AddUserItem

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

func AdminBindSubscription

func AdminBindSubscription(userId int, planId int, sourceNote string) (string, error)

Admin bind (no payment). Creates a UserSubscription from a plan.

func AdminDeleteComment

func AdminDeleteComment(id int) error

AdminDeleteComment 管理员硬删除评论

func AdminDeletePost

func AdminDeletePost(id int) error

AdminDeletePost 管理员硬删除帖子

func AdminDeleteUserSubscription

func AdminDeleteUserSubscription(userSubscriptionId int) (string, error)

AdminDeleteUserSubscription hard-deletes a user subscription.

func AdminInvalidateUserSubscription

func AdminInvalidateUserSubscription(userSubscriptionId int) (string, error)

AdminInvalidateUserSubscription marks a user subscription as cancelled and ends it immediately.

func AdminUpdateCommentStatus

func AdminUpdateCommentStatus(id int, status int) error

AdminUpdateCommentStatus 管理员隐藏/显示评论

func AdminUpdatePostStatus

func AdminUpdatePostStatus(id int, status int) error

AdminUpdatePostStatus 管理员修改帖子状态

func AtomicClaimAchievement added in v0.1.4

func AtomicClaimAchievement(userId int, achievementId int) (bool, error)

AtomicClaimAchievement 原子性领取成就奖励(防止竞态条件下重复领取) 仅当 claimed_at IS NULL 时更新,返回是否成功领取

func BatchDeleteChannels

func BatchDeleteChannels(ids []int) error

func BatchDeleteTokens

func BatchDeleteTokens(ids []int, userId int) (int, error)

BatchDeleteTokens 删除指定用户的一组令牌,返回成功删除数量

func BatchGetCommentCounts

func BatchGetCommentCounts(postIds []int) (map[int]int64, error)

BatchGetCommentCounts 批量获取评论数

func BatchGetLikeCounts

func BatchGetLikeCounts(postIds []int) (map[int]int64, error)

BatchGetLikeCounts 批量获取点赞数

func BatchGetRepostCounts

func BatchGetRepostCounts(postIds []int) (map[int]int64, error)

BatchGetRepostCounts 批量获取转发数

func BatchGetUserBookmarked

func BatchGetUserBookmarked(userId int, postIds []int) (map[int]bool, error)

BatchGetUserBookmarked 批量判断当前用户是否收藏

func BatchGetUserLiked

func BatchGetUserLiked(userId int, postIds []int) (map[int]bool, error)

BatchGetUserLiked 批量判断当前用户是否点赞

func BatchInsertChannels

func BatchInsertChannels(channels []Channel) error

func BatchSetChannelTag

func BatchSetChannelTag(ids []int, tag *string) error

func BookmarkPost

func BookmarkPost(userId, postId int) error

BookmarkPost 收藏帖子(幂等)

func CacheUpdateChannel

func CacheUpdateChannel(channel *Channel)

func CacheUpdateChannelStatus

func CacheUpdateChannelStatus(id int, status int)

func CheckSetup

func CheckSetup()

func CheckUserExistOrDeleted

func CheckUserExistOrDeleted(username string, email string) (bool, error)

CheckUserExistOrDeleted check if user exist or deleted, if not exist, return false, nil, if deleted or exist, return true, nil

func CleanupChannelPollingLocks

func CleanupChannelPollingLocks()

CleanupChannelPollingLocks removes locks for channels that no longer exist This is optional and can be called periodically to prevent memory leaks

func CleanupSubscriptionPreConsumeRecords

func CleanupSubscriptionPreConsumeRecords(olderThanSeconds int64) (int64, error)

CleanupSubscriptionPreConsumeRecords removes old idempotency records to keep table small.

func CloseDB

func CloseDB() error

func CompleteSubscriptionOrder

func CompleteSubscriptionOrder(tradeNo string, providerPayload string) error

Complete a subscription order (idempotent). Creates a UserSubscription snapshot from the plan.

func CountAllChannels

func CountAllChannels() (int64, error)

CountAllChannels returns total channels in DB

func CountAllTags

func CountAllTags() (int64, error)

CountAllTags returns number of non-empty distinct tags

func CountAllTasks

func CountAllTasks(queryParams TaskQueryParams) int64

CountAllTasks returns total midjourney tasks for admin query

func CountAllUserTask

func CountAllUserTask(userId int, queryParams TaskQueryParams) int64

CountAllUserTask returns total midjourney tasks for user

func CountChannelsByType

func CountChannelsByType(channelType int) (int64, error)

Count channels of specific type

func CountChannelsGroupByType

func CountChannelsGroupByType() (map[int64]int64, error)

Return map[type]count for all channels

func CountUserSubscriptionsByPlan

func CountUserSubscriptionsByPlan(userId int, planId int) (int64, error)

func CountUserTokens

func CountUserTokens(userId int) (int64, error)

CountUserTokens returns total number of tokens for the given user, used for pagination

func CreateActivity

func CreateActivity(activity *PetActivity) error

func CreateBackupCodes

func CreateBackupCodes(userId int, codes []string) error

CreateBackupCodes 创建备用码

func CreateBattle added in v0.1.7

func CreateBattle(battle *PetArenaBattle) error

func CreateBid

func CreateBid(bid *PetMarketBid) error

func CreateBigWin added in v0.1.4

func CreateBigWin(record *CasinoBigWin) error

func CreateCustomOAuthProvider

func CreateCustomOAuthProvider(provider *CustomOAuthProvider) error

CreateCustomOAuthProvider creates a new custom OAuth provider

func CreateDispatch

func CreateDispatch(dispatch *PetDispatch) error

func CreateGachaHistory

func CreateGachaHistory(history *GachaHistory) error

func CreateGachaHistoryInTx

func CreateGachaHistoryInTx(tx *gorm.DB, history *GachaHistory) error

func CreateGachaPool

func CreateGachaPool(pool *GachaPool) error

func CreateGameRecord added in v0.1.4

func CreateGameRecord(record *CasinoGameRecord) error

func CreateHeistRecord added in v0.1.7

func CreateHeistRecord(record *GringottsHeistRecord) error

func CreateItem

func CreateItem(item *PetItem) error

func CreateListing

func CreateListing(listing *PetMarketListing) error

func CreateMission

func CreateMission(mission *PetMission) error

func CreateNotification

func CreateNotification(userId, actorId int, notifType string, postId *int, commentId *int) error

CreateNotification 创建通知(自己触发自己的不创建)

func CreateNotificationIfNotExists

func CreateNotificationIfNotExists(userId, actorId int, notifType string, postId *int) error

CreateNotificationIfNotExists 去重版创建通知(用于点赞/关注,取消后再触发不重复通知)

func CreateOrUpdateDefender added in v0.1.7

func CreateOrUpdateDefender(defender *PetArenaDefender) error

func CreateOrUpdatePityCounter

func CreateOrUpdatePityCounter(counter *UserPityCounter) error

func CreateOrUpdatePityCounterInTx

func CreateOrUpdatePityCounterInTx(tx *gorm.DB, counter *UserPityCounter) error

func CreatePriceHistory

func CreatePriceHistory(history *PetPriceHistory) error

func CreateSeason added in v0.1.7

func CreateSeason(season *PetArenaSeason) error

func CreateSpecies

func CreateSpecies(species *PetSpecies) error

func CreateTransaction

func CreateTransaction(tx *PetMarketTransaction) error

func CreateUserAchievement added in v0.1.4

func CreateUserAchievement(record *CasinoUserAchievement) error

func CreateUserOAuthBinding

func CreateUserOAuthBinding(binding *UserOAuthBinding) error

CreateUserOAuthBinding creates a new OAuth binding

func CreateUserOAuthBindingWithTx

func CreateUserOAuthBindingWithTx(tx *gorm.DB, binding *UserOAuthBinding) error

CreateUserOAuthBindingWithTx creates a new OAuth binding within a transaction

func CreateUserPet

func CreateUserPet(pet *UserPet) error

func CreateUserPetInTx

func CreateUserPetInTx(tx *gorm.DB, pet *UserPet) error

func DecreaseTokenQuota

func DecreaseTokenQuota(id int, key string, quota int) (err error)

func DecreaseUserQuota

func DecreaseUserQuota(id int, quota int) (err error)

func DeleteChannelByStatus

func DeleteChannelByStatus(status int64) (int64, error)

func DeleteComment

func DeleteComment(id int, userId int) error

DeleteComment 作者 soft delete 自己的评论

func DeleteCustomOAuthProvider

func DeleteCustomOAuthProvider(id int) error

DeleteCustomOAuthProvider deletes a custom OAuth provider by ID

func DeleteDisabledChannel

func DeleteDisabledChannel() (int64, error)

func DeleteGachaPool

func DeleteGachaPool(id int) error

func DeleteInvalidRedemptions

func DeleteInvalidRedemptions() (int64, error)

func DeleteItem

func DeleteItem(id int) error

func DeleteMission

func DeleteMission(id int) error

func DeleteOldLog

func DeleteOldLog(ctx context.Context, targetTimestamp int64, limit int) (int64, error)

func DeletePasskeyByUserID

func DeletePasskeyByUserID(userID int) error

func DeletePost

func DeletePost(id int, userId int) error

DeletePost soft delete 帖子(仅帖子作者可调用)

func DeletePrefillGroupByID

func DeletePrefillGroupByID(id int) error

DeleteByID 根据 ID 删除组

func DeleteRedemptionById

func DeleteRedemptionById(id int) (err error)

func DeleteSpecies

func DeleteSpecies(id int) error

func DeleteTokenById

func DeleteTokenById(id int, userId int) (err error)

func DeleteUserById

func DeleteUserById(id int) (err error)

func DeleteUserOAuthBinding

func DeleteUserOAuthBinding(userId, providerId int) error

DeleteUserOAuthBinding deletes an OAuth binding

func DeleteUserOAuthBindingsByUserId

func DeleteUserOAuthBindingsByUserId(userId int) error

DeleteUserOAuthBindingsByUserId deletes all OAuth bindings for a user

func DeleteUserPet

func DeleteUserPet(userId int, petId int) error

func DeleteUserPetInTx

func DeleteUserPetInTx(tx *gorm.DB, userId int, petId int) error

func DeltaUpdateUserQuota

func DeltaUpdateUserQuota(id int, delta int) (err error)

func DisableChannelByTag

func DisableChannelByTag(tag string) error

func DisableModelLimits

func DisableModelLimits(tokenId int) error

func DisableTwoFA

func DisableTwoFA(userId int) error

DisableTwoFA 禁用用户的2FA

func EditChannelByTag

func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, group *string, priority *int64, weight *uint, paramOverride *string, headerOverride *string) error

func EnableChannelByTag

func EnableChannelByTag(tag string) error

func EndSeason added in v0.1.7

func EndSeason(seasonId int) error

func EquipTitle added in v0.1.7

func EquipTitle(userId int, titleId int) error

func ExpireDueSubscriptions

func ExpireDueSubscriptions(limit int) (int, error)

ExpireDueSubscriptions marks expired subscriptions and handles group downgrade.

func ExpireSubscriptionOrder

func ExpireSubscriptionOrder(tradeNo string) error

func FixAbility

func FixAbility() (int, int, error)

func FollowUser

func FollowUser(followerId, followingId int) error

FollowUser 关注用户(禁止自关注)

func GenerateTaskID

func GenerateTaskID() string

GenerateTaskID 生成对外暴露的 task_xxxx 格式 ID

func GetAdminCasinoStats added in v0.1.4

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

func GetAdminCasinoUsers added in v0.1.4

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

func GetArenaRanking added in v0.1.7

func GetArenaRanking(seasonId int, limit int) ([]map[string]interface{}, error)

func GetBindingCountByProviderId

func GetBindingCountByProviderId(providerId int) (int64, error)

GetBindingCountByProviderId returns the number of bindings for a provider

func GetBoundChannelsByModelsMap

func GetBoundChannelsByModelsMap(modelNames []string) (map[string][]BoundChannel, error)

func GetCasinoLeaderboard added in v0.1.4

func GetCasinoLeaderboard(rankType string, limit int) ([]map[string]interface{}, error)

func GetChannelPollingLock

func GetChannelPollingLock(channelId int) *sync.Mutex

GetChannelPollingLock returns or creates a mutex for the given channel ID

func GetConsecutiveCheckinDays

func GetConsecutiveCheckinDays(userId int) int

GetConsecutiveCheckinDays returns how many consecutive days (including today) the user has checked in. Starts from today and counts backwards.

func GetCurrentWinStreak added in v0.1.4

func GetCurrentWinStreak(userId int) (int, error)

func GetDBTimestamp

func GetDBTimestamp() int64

GetDBTimestamp returns a UNIX timestamp from database time. Falls back to application time on error.

func GetEnabledModels

func GetEnabledModels() []string

func GetGringottsVaultBalance added in v0.1.7

func GetGringottsVaultBalance() int64

GetGringottsVaultBalance 金库余额 = 赌场总亏损 - 赌场总赢利 - 被打劫总额

func GetGroupEnabledModels

func GetGroupEnabledModels(group string) []string

func GetHeistTotalStolen added in v0.1.7

func GetHeistTotalStolen() int64

GetHeistTotalStolen 获取所有打劫成功的总奖励

func GetMaxUserId

func GetMaxUserId() int

func GetMissingModels

func GetMissingModels() ([]string, error)

GetMissingModels returns model names that are referenced in the system

func GetModelEnableGroups

func GetModelEnableGroups(modelName string) []string

func GetModelQuotaTypes

func GetModelQuotaTypes(modelName string) []int

GetModelQuotaTypes 返回指定模型的计费类型集合(来自缓存)

func GetModelSupportEndpointTypes

func GetModelSupportEndpointTypes(model string) []constant.EndpointType

func GetPaginatedTags

func GetPaginatedTags(offset int, limit int) ([]*string, error)

func GetPostCommentCount

func GetPostCommentCount(postId int) (int64, error)

GetPostCommentCount 获取单帖评论数

func GetPostLikeCount

func GetPostLikeCount(postId int) (int64, error)

GetPostLikeCount 获取单帖点赞数

func GetSupportedEndpointMap

func GetSupportedEndpointMap() map[string]common.EndpointInfo

GetSupportedEndpointMap 返回全局端点到路径的映射

func GetTodayAttackCount added in v0.1.7

func GetTodayAttackCount(userId int) int64

func GetTodayDispatchCount

func GetTodayDispatchCount(userId int, missionId int) (int64, error)

func GetTwoFAStats

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

GetTwoFAStats 获取2FA统计信息(管理员使用)

func GetUnreadNotificationCount

func GetUnreadNotificationCount(userId int) (int64, error)

GetUnreadNotificationCount 获取未读通知数量

func GetUnusedBackupCodeCount

func GetUnusedBackupCodeCount(userId int) (int, error)

GetUnusedBackupCodeCount 获取未使用的备用码数量

func GetUserCasinoOverallStats added in v0.1.4

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

func GetUserCheckinStats

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

GetUserCheckinStats 获取用户签到统计信息

func GetUserEmail

func GetUserEmail(id int) (email string, err error)

func GetUserGroup

func GetUserGroup(id int, fromDB bool) (group string, err error)

GetUserGroup gets group from Redis first, falls back to DB if needed

func GetUserHeistSuccessCount added in v0.1.7

func GetUserHeistSuccessCount(userId int) int64

GetUserHeistSuccessCount 获取用户打劫成功次数

func GetUserIdByAffCode

func GetUserIdByAffCode(affCode string) (int, error)

func GetUserImperioSuccessCount added in v0.1.7

func GetUserImperioSuccessCount(userId int) int64

GetUserImperioSuccessCount 获取用户 imperio 打劫成功次数

func GetUserLanguage

func GetUserLanguage(userId int) string

GetUserLanguage returns the user's language preference from cache Uses the existing GetUserCache mechanism for efficiency

func GetUserPetCount

func GetUserPetCount(userId int) (int64, error)

func GetUserPostCount

func GetUserPostCount(userId int) (int64, error)

GetUserPostCount 获取用户帖子数量

func GetUserQuota

func GetUserQuota(id int, fromDB bool) (quota int, err error)

GetUserQuota gets quota from Redis first, falls back to DB if needed

func GetUserSetting

func GetUserSetting(id int, fromDB bool) (settingMap dto.UserSetting, err error)

GetUserSetting gets setting from Redis first, falls back to DB if needed

func GetUserTitles added in v0.1.7

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

func GetUserUsedQuota

func GetUserUsedQuota(id int) (quota int, err error)

func GetUsernameById

func GetUsernameById(id int, fromDB bool) (username string, err error)

GetUsernameById gets username from Redis first, falls back to DB if needed

func GetVendorModelCounts

func GetVendorModelCounts() (map[int64]int64, error)

func GrantTitle added in v0.1.7

func GrantTitle(userId int, titleId int) error

func HardDeleteUserById

func HardDeleteUserById(id int) error

func HasActiveUserSubscription

func HasActiveUserSubscription(userId int) (bool, error)

HasActiveUserSubscription returns whether the user has any active subscription. This is a lightweight existence check to avoid heavy pre-consume transactions.

func HasAdoptedStarter

func HasAdoptedStarter(userId int) (bool, error)

func HasBookmarked

func HasBookmarked(userId, postId int) (bool, error)

HasBookmarked 是否已收藏

func HasCheckedInToday

func HasCheckedInToday(userId int) (bool, error)

HasCheckedInToday 检查用户今天是否已签到

func HasLiked

func HasLiked(userId, postId int) (bool, error)

HasLiked 是否已点赞

func HasUserTitle added in v0.1.7

func HasUserTitle(userId int, titleId int) bool

func IncreaseTokenQuota

func IncreaseTokenQuota(tokenId int, key string, quota int) (err error)

func IncreaseUserQuota

func IncreaseUserQuota(id int, quota int, db bool) (err error)

func InitBatchUpdater

func InitBatchUpdater()

func InitChannelCache

func InitChannelCache()

func InitDB

func InitDB() (err error)

func InitLogDB

func InitLogDB() (err error)

func InitOptionMap

func InitOptionMap()

func InvalidateSubscriptionPlanCache

func InvalidateSubscriptionPlanCache(planId int)

func IsAdmin

func IsAdmin(userId int) bool

func IsChannelEnabledForAnyGroupModel

func IsChannelEnabledForAnyGroupModel(groups []string, modelName string, channelID int) bool

func IsChannelEnabledForGroupModel

func IsChannelEnabledForGroupModel(group string, modelName string, channelID int) bool

func IsDiscordIdAlreadyTaken

func IsDiscordIdAlreadyTaken(discordId string) bool

func IsEmailAlreadyTaken

func IsEmailAlreadyTaken(email string) bool

func IsFollowing

func IsFollowing(followerId, followingId int) (bool, error)

IsFollowing 查询是否已关注

func IsGitHubIdAlreadyTaken

func IsGitHubIdAlreadyTaken(githubId string) bool

func IsLinuxDOIdAlreadyTaken

func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool

func IsModelNameDuplicated

func IsModelNameDuplicated(id int, name string) (bool, error)

func IsOidcIdAlreadyTaken

func IsOidcIdAlreadyTaken(oidcId string) bool

func IsPrefillGroupNameDuplicated

func IsPrefillGroupNameDuplicated(id int, name string) (bool, error)

IsPrefillGroupNameDuplicated 检查组名称是否重复(排除自身 ID)

func IsProviderUserIdTaken

func IsProviderUserIdTaken(providerId int, providerUserId string) bool

IsProviderUserIdTaken checks if a provider user ID is already bound to any user

func IsSlugTaken

func IsSlugTaken(slug string, excludeId int) bool

IsSlugTaken checks if a slug is already taken by another provider Returns true on DB errors (fail-closed) to prevent slug conflicts

func IsTelegramIdAlreadyTaken

func IsTelegramIdAlreadyTaken(telegramId string) bool

func IsTwoFAEnabled

func IsTwoFAEnabled(userId int) bool

IsTwoFAEnabled 检查用户是否启用了2FA

func IsVendorNameDuplicated

func IsVendorNameDuplicated(id int, name string) (bool, error)

IsVendorNameDuplicated 检查供应商名称是否重复(排除自身 ID)

func IsWeChatIdAlreadyTaken

func IsWeChatIdAlreadyTaken(wechatId string) bool

func LikePost

func LikePost(userId, postId int) error

LikePost 点赞帖子(幂等,已点赞则忽略)

func LogQuotaData

func LogQuotaData(userId int, username string, modelName string, quota int, createdAt int64, tokenUsed int)

func ManualCompleteTopUp

func ManualCompleteTopUp(tradeNo string) error

ManualCompleteTopUp 管理员手动完成订单并给用户充值

func MarkAllNotificationsRead

func MarkAllNotificationsRead(userId int) error

MarkAllNotificationsRead 标记全部通知已读

func MarkNotificationRead

func MarkNotificationRead(id int, userId int) error

MarkNotificationRead 标记单条通知已读

func MaskTokenKey

func MaskTokenKey(key string) string

func MjBulkUpdate

func MjBulkUpdate(mjIds []string, params map[string]any) error

func MjBulkUpdateByTaskIds

func MjBulkUpdateByTaskIds(taskIDs []int, params map[string]any) error

func NormalizeResetPeriod

func NormalizeResetPeriod(period string) string

func PingDB

func PingDB() error

func PostConsumeUserSubscriptionDelta

func PostConsumeUserSubscriptionDelta(userSubscriptionId int, delta int64) error

Update subscription used amount by delta (positive consume more, negative refund).

func Recharge

func Recharge(referenceId string, customerId string) (err error)

func RechargeCreem

func RechargeCreem(referenceId string, customerEmail string, customerName string) (err error)

func RecordConsumeLog

func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)

func RecordErrorLog

func RecordErrorLog(c *gin.Context, userId int, channelId int, modelName string, tokenName string, content string, tokenId int, useTimeSeconds int,
	isStream bool, group string, other map[string]interface{})

func RecordExist

func RecordExist(err error) (bool, error)

func RecordLog

func RecordLog(userId int, logType int, content string)

func RecordTaskBillingLog

func RecordTaskBillingLog(params RecordTaskBillingLogParams)

func Redeem

func Redeem(key string, userId int) (quota int, err error)

func RefreshPricing

func RefreshPricing()

RefreshPricing 强制立即重新计算与定价相关的缓存。 该方法用于需要最新数据的内部管理 API, 因此会绕过默认的 1 分钟延迟刷新。

func RefundSubscriptionPreConsume

func RefundSubscriptionPreConsume(requestId string) error

RefundSubscriptionPreConsume is idempotent and refunds pre-consumed subscription quota by requestId.

func RemoveUserItem

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

func ResetDueSubscriptions

func ResetDueSubscriptions(limit int) (int, error)

ResetDueSubscriptions resets subscriptions whose next_reset_time has passed.

func ResetUserPasswordByEmail

func ResetUserPasswordByEmail(email string, password string) error

func RootUserExists

func RootUserExists() bool

func SafeDecreaseQuotaForBet added in v0.1.4

func SafeDecreaseQuotaForBet(userId int, amount int) (bool, error)

SafeDecreaseQuotaForBet 原子扣款 — 仅当余额充足时才扣除 返回 true 表示扣款成功,false 表示余额不足

func SaveQuotaDataCache

func SaveQuotaDataCache()

func SearchTags

func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error)

func SeedDefaultAchievements added in v0.1.4

func SeedDefaultAchievements()

func SeedFirstSeason added in v0.1.7

func SeedFirstSeason()

func SeedGachaData

func SeedGachaData()

SeedGachaData populates the initial gacha pool if the gacha_pools table is empty. This function is idempotent.

func SeedMissionData

func SeedMissionData()

SeedMissionData populates the initial missions if the pet_missions table is empty. This function is idempotent.

func SeedPetData

func SeedPetData()

SeedPetData populates initial pet species and items if the tables are empty. This function is idempotent — it only inserts when pet_species has zero rows.

func SeedTitles added in v0.1.7

func SeedTitles()

func SetPrimaryPet

func SetPrimaryPet(userId int, petId int) error

func SumUsedToken

func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string) (token int)

func SyncChannelCache

func SyncChannelCache(frequency int)

func SyncOptions

func SyncOptions(frequency int)

func TaskBulkUpdateByID

func TaskBulkUpdateByID(ids []int64, params map[string]any) error

TaskBulkUpdateByID performs an unconditional bulk UPDATE by primary key IDs. WARNING: This function has NO CAS (Compare-And-Swap) guard — it will overwrite any concurrent status changes. DO NOT use in billing/quota lifecycle flows (e.g., timeout, success, failure transitions that trigger refunds or settlements). For status transitions that involve billing, use Task.UpdateWithStatus() instead.

func TaskCountAllTasks

func TaskCountAllTasks(queryParams SyncTaskQueryParams) int64

TaskCountAllTasks returns total tasks that match the given query params (admin usage)

func TaskCountAllUserTask

func TaskCountAllUserTask(userId int, queryParams SyncTaskQueryParams) int64

TaskCountAllUserTask returns total tasks for given user

func UnbookmarkPost

func UnbookmarkPost(userId, postId int) error

UnbookmarkPost 取消收藏

func UnequipTitle added in v0.1.7

func UnequipTitle(userId int) error

func UnfollowUser

func UnfollowUser(followerId, followingId int) error

UnfollowUser 取消关注

func UnlikePost

func UnlikePost(userId, postId int) error

UnlikePost 取消点赞

func UpdateAbilityByTag

func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error

func UpdateAbilityStatus

func UpdateAbilityStatus(channelId int, status bool) error

func UpdateAbilityStatusByTag

func UpdateAbilityStatusByTag(tag string, status bool) error

func UpdateChannelStatus

func UpdateChannelStatus(channelId int, usingKey string, status int, reason string) bool

func UpdateChannelUsedQuota

func UpdateChannelUsedQuota(id int, quota int)

func UpdateCustomOAuthProvider

func UpdateCustomOAuthProvider(provider *CustomOAuthProvider) error

UpdateCustomOAuthProvider updates an existing custom OAuth provider

func UpdateDailyStats added in v0.1.4

func UpdateDailyStats(stats *CasinoDailyStats) error

func UpdateDefender added in v0.1.7

func UpdateDefender(defender *PetArenaDefender) error

func UpdateDispatch

func UpdateDispatch(dispatch *PetDispatch) error

func UpdateGachaPool

func UpdateGachaPool(pool *GachaPool) error

func UpdateGameRecord added in v0.1.4

func UpdateGameRecord(record *CasinoGameRecord) error

func UpdateItem

func UpdateItem(item *PetItem) error

func UpdateListing

func UpdateListing(listing *PetMarketListing) error

func UpdateMission

func UpdateMission(mission *PetMission) error

func UpdateOption

func UpdateOption(key string, value string) error

func UpdateProgress

func UpdateProgress(id int, progress string) error

func UpdateQuotaData

func UpdateQuotaData()

func UpdateSpecies

func UpdateSpecies(species *PetSpecies) error

func UpdateUserAchievement added in v0.1.4

func UpdateUserAchievement(record *CasinoUserAchievement) error

func UpdateUserGroupCache

func UpdateUserGroupCache(userId int, group string) error

func UpdateUserOAuthBinding

func UpdateUserOAuthBinding(userId, providerId int, newProviderUserId string) error

UpdateUserOAuthBinding updates an existing OAuth binding (e.g., rebind to different OAuth account)

func UpdateUserPet

func UpdateUserPet(pet *UserPet) error

func UpdateUserUsedQuotaAndRequestCount

func UpdateUserUsedQuotaAndRequestCount(id int, quota int)

func UpsertPasskeyCredential

func UpsertPasskeyCredential(credential *PasskeyCredential) error

func ValidateBackupCode

func ValidateBackupCode(userId int, code string) (bool, error)

ValidateBackupCode 验证并使用备用码

Types

type Ability

type Ability struct {
	Group     string  `json:"group" gorm:"type:varchar(64);primaryKey;autoIncrement:false"`
	Model     string  `json:"model" gorm:"type:varchar(255);primaryKey;autoIncrement:false"`
	ChannelId int     `json:"channel_id" gorm:"primaryKey;autoIncrement:false;index"`
	Enabled   bool    `json:"enabled"`
	Priority  *int64  `json:"priority" gorm:"bigint;default:0;index"`
	Weight    uint    `json:"weight" gorm:"default:0;index"`
	Tag       *string `json:"tag" gorm:"index"`
}

func GetAllEnableAbilities

func GetAllEnableAbilities() []Ability

type AbilityWithChannel

type AbilityWithChannel struct {
	Ability
	ChannelType int `json:"channel_type"`
}

func GetAllEnableAbilityWithChannels

func GetAllEnableAbilityWithChannels() ([]AbilityWithChannel, error)

type BoundChannel

type BoundChannel struct {
	Name string `json:"name"`
	Type int    `json:"type"`
}

type CasinoAchievement added in v0.1.4

type CasinoAchievement struct {
	Id          int    `json:"id" gorm:"primaryKey;autoIncrement"`
	Key         string `json:"key" gorm:"type:varchar(50);uniqueIndex"`
	Name        string `json:"name" gorm:"type:varchar(100);not null"`
	Description string `json:"description" gorm:"type:varchar(255)"`
	Icon        string `json:"icon" gorm:"type:varchar(50)"`
	Category    string `json:"category" gorm:"type:varchar(30)"`
	Condition   string `json:"condition" gorm:"type:text"`
	RewardType  string `json:"reward_type" gorm:"type:varchar(20)"`
	RewardValue string `json:"reward_value" gorm:"type:varchar(100)"`
	SortOrder   int    `json:"sort_order" gorm:"default:0"`
	Enabled     bool   `json:"enabled" gorm:"default:true"`
	CreatedAt   int64  `json:"created_at" gorm:"bigint"`
}

CasinoAchievement 赌场成就定义

func GetAchievementById added in v0.1.4

func GetAchievementById(id int) (*CasinoAchievement, error)

func GetAllEnabledAchievements added in v0.1.4

func GetAllEnabledAchievements() ([]CasinoAchievement, error)

func (CasinoAchievement) TableName added in v0.1.4

func (CasinoAchievement) TableName() string

type CasinoBigWin added in v0.1.4

type CasinoBigWin struct {
	Id         int     `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId     int     `json:"user_id" gorm:"not null;index:idx_casino_bigwin_user"`
	Username   string  `json:"username" gorm:"type:varchar(50)"`
	GameType   string  `json:"game_type" gorm:"type:varchar(20)"`
	BetAmount  float64 `json:"bet_amount"`
	Payout     float64 `json:"payout"`
	Multiplier float64 `json:"multiplier"`
	CreatedAt  int64   `json:"created_at" gorm:"bigint;index:idx_casino_bigwin_time"`
}

CasinoBigWin 大赢记录(用于跑马灯展示)

func GetRecentBigWins added in v0.1.4

func GetRecentBigWins(limit int) ([]CasinoBigWin, error)

func (CasinoBigWin) TableName added in v0.1.4

func (CasinoBigWin) TableName() string

type CasinoDailyStats added in v0.1.4

type CasinoDailyStats struct {
	Id           int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId       int    `json:"user_id" gorm:"not null;uniqueIndex:idx_casino_daily_ud"`
	Date         string `json:"date" gorm:"type:varchar(10);not null;uniqueIndex:idx_casino_daily_ud"`
	TotalBet     int    `json:"total_bet" gorm:"default:0"`
	TotalWon     int    `json:"total_won" gorm:"default:0"`
	TotalLost    int    `json:"total_lost" gorm:"default:0"`
	GamesPlayed  int    `json:"games_played" gorm:"default:0"`
	WinCount     int    `json:"win_count" gorm:"default:0"`
	BiggestWin   int    `json:"biggest_win" gorm:"default:0"`
	MaxWinStreak int    `json:"max_win_streak" gorm:"default:0"`
	CreatedAt    int64  `json:"created_at" gorm:"bigint"`
	UpdatedAt    int64  `json:"updated_at" gorm:"bigint"`
}

CasinoDailyStats 赌场每日统计

func GetOrCreateDailyStats added in v0.1.4

func GetOrCreateDailyStats(userId int, date string) (*CasinoDailyStats, error)

func (CasinoDailyStats) TableName added in v0.1.4

func (CasinoDailyStats) TableName() string

type CasinoGameRecord added in v0.1.4

type CasinoGameRecord struct {
	Id          int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId      int    `json:"user_id" gorm:"not null;index:idx_casino_record_user"`
	GameType    string `json:"game_type" gorm:"type:varchar(20);not null;index:idx_casino_record_type"`
	BetAmount   int    `json:"bet_amount" gorm:"not null"`
	Payout      int    `json:"payout" gorm:"default:0"`
	NetProfit   int    `json:"net_profit" gorm:"default:0"`
	Result      string `json:"result" gorm:"type:varchar(10)"`
	Status      string `json:"status" gorm:"type:varchar(10);default:'active'"`
	Details     string `json:"details" gorm:"type:text"`
	CreatedAt   int64  `json:"created_at" gorm:"bigint"`
	CompletedAt *int64 `json:"completed_at,omitempty" gorm:"bigint"`
}

CasinoGameRecord 赌场游戏记录

func GetActiveGame added in v0.1.4

func GetActiveGame(userId int, gameType string) (*CasinoGameRecord, error)

func GetGameHistory added in v0.1.4

func GetGameHistory(userId int, gameType string, page, perPage int) ([]CasinoGameRecord, int64, error)

func GetGameRecordById added in v0.1.4

func GetGameRecordById(id int) (*CasinoGameRecord, error)

func (CasinoGameRecord) TableName added in v0.1.4

func (CasinoGameRecord) TableName() string

type CasinoUserAchievement added in v0.1.4

type CasinoUserAchievement struct {
	Id            int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId        int    `json:"user_id" gorm:"not null;uniqueIndex:idx_casino_ua_user_ach"`
	AchievementId int    `json:"achievement_id" gorm:"not null;uniqueIndex:idx_casino_ua_user_ach"`
	Progress      int    `json:"progress" gorm:"default:0"`
	Completed     bool   `json:"completed" gorm:"default:false"`
	ClaimedAt     *int64 `json:"claimed_at,omitempty" gorm:"bigint"`
	CreatedAt     int64  `json:"created_at" gorm:"bigint"`
	UpdatedAt     int64  `json:"updated_at" gorm:"bigint"`
}

CasinoUserAchievement 用户成就进度

func GetUserAchievement added in v0.1.4

func GetUserAchievement(userId int, achievementId int) (*CasinoUserAchievement, error)

func GetUserAchievements added in v0.1.4

func GetUserAchievements(userId int) ([]CasinoUserAchievement, error)

func (CasinoUserAchievement) TableName added in v0.1.4

func (CasinoUserAchievement) TableName() string

type Channel

type Channel struct {
	Id                 int     `json:"id"`
	Type               int     `json:"type" gorm:"default:0"`
	Key                string  `json:"key" gorm:"not null"`
	OpenAIOrganization *string `json:"openai_organization"`
	TestModel          *string `json:"test_model"`
	Status             int     `json:"status" gorm:"default:1"`
	Name               string  `json:"name" gorm:"index"`
	Weight             *uint   `json:"weight" gorm:"default:0"`
	CreatedTime        int64   `json:"created_time" gorm:"bigint"`
	TestTime           int64   `json:"test_time" gorm:"bigint"`
	ResponseTime       int     `json:"response_time"` // in milliseconds
	BaseURL            *string `json:"base_url" gorm:"column:base_url;default:''"`
	Other              string  `json:"other"`
	Balance            float64 `json:"balance"` // in USD
	BalanceUpdatedTime int64   `json:"balance_updated_time" gorm:"bigint"`
	Models             string  `json:"models"`
	Group              string  `json:"group" gorm:"type:varchar(64);default:'default'"`
	UsedQuota          int64   `json:"used_quota" gorm:"bigint;default:0"`
	ModelMapping       *string `json:"model_mapping" gorm:"type:text"`
	//MaxInputTokens     *int    `json:"max_input_tokens" gorm:"default:0"`
	StatusCodeMapping *string `json:"status_code_mapping" gorm:"type:varchar(1024);default:''"`
	Priority          *int64  `json:"priority" gorm:"bigint;default:0"`
	AutoBan           *int    `json:"auto_ban" gorm:"default:1"`
	OtherInfo         string  `json:"other_info"`
	Tag               *string `json:"tag" gorm:"index"`
	Setting           *string `json:"setting" gorm:"type:text"` // 渠道额外设置
	ParamOverride     *string `json:"param_override" gorm:"type:text"`
	HeaderOverride    *string `json:"header_override" gorm:"type:text"`
	Remark            *string `json:"remark" gorm:"type:varchar(255)" validate:"max=255"`
	// add after v0.8.5
	ChannelInfo ChannelInfo `json:"channel_info" gorm:"type:json"`

	OtherSettings string `json:"settings" gorm:"column:settings"` // 其他设置,存储azure版本等不需要检索的信息,详见dto.ChannelOtherSettings

	// cache info
	Keys []string `json:"-" gorm:"-"`
}

func CacheGetChannel

func CacheGetChannel(id int) (*Channel, error)

func GetAllChannels

func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool) ([]*Channel, error)

func GetChannel

func GetChannel(group string, model string, retry int) (*Channel, error)

func GetChannelById

func GetChannelById(id int, selectAll bool) (*Channel, error)

func GetChannelsByIds

func GetChannelsByIds(ids []int) ([]*Channel, error)

func GetChannelsByTag

func GetChannelsByTag(tag string, idSort bool, selectAll bool) ([]*Channel, error)

func GetChannelsByType

func GetChannelsByType(startIdx int, num int, idSort bool, channelType int) ([]*Channel, error)

Get channels of specified type with pagination

func GetRandomSatisfiedChannel

func GetRandomSatisfiedChannel(group string, model string, retry int) (*Channel, error)

func SearchChannels

func SearchChannels(keyword string, group string, model string, idSort bool) ([]*Channel, error)

func (*Channel) AddAbilities

func (channel *Channel) AddAbilities(tx *gorm.DB) error

func (*Channel) Delete

func (channel *Channel) Delete() error

func (*Channel) DeleteAbilities

func (channel *Channel) DeleteAbilities() error

func (*Channel) GetAutoBan

func (channel *Channel) GetAutoBan() bool

func (*Channel) GetBaseURL

func (channel *Channel) GetBaseURL() string

func (*Channel) GetGroups

func (channel *Channel) GetGroups() []string

func (*Channel) GetHeaderOverride

func (channel *Channel) GetHeaderOverride() map[string]interface{}

func (*Channel) GetKeys

func (channel *Channel) GetKeys() []string

func (*Channel) GetModelMapping

func (channel *Channel) GetModelMapping() string

func (*Channel) GetModels

func (channel *Channel) GetModels() []string

func (*Channel) GetNextEnabledKey

func (channel *Channel) GetNextEnabledKey() (string, int, *types.NewAPIError)

func (*Channel) GetOtherInfo

func (channel *Channel) GetOtherInfo() map[string]interface{}

func (*Channel) GetOtherSettings

func (channel *Channel) GetOtherSettings() dto.ChannelOtherSettings

func (*Channel) GetParamOverride

func (channel *Channel) GetParamOverride() map[string]interface{}

func (*Channel) GetPriority

func (channel *Channel) GetPriority() int64

func (*Channel) GetSetting

func (channel *Channel) GetSetting() dto.ChannelSettings

func (*Channel) GetStatusCodeMapping

func (channel *Channel) GetStatusCodeMapping() string

func (*Channel) GetTag

func (channel *Channel) GetTag() string

func (*Channel) GetWeight

func (channel *Channel) GetWeight() int

func (*Channel) Insert

func (channel *Channel) Insert() error

func (*Channel) MaskedKey added in v0.1.1

func (channel *Channel) MaskedKey() string

MaskedKey returns a masked version of the channel key for display purposes. For single keys: shows first 4 and last 4 characters with asterisks in between. For multi-key channels: masks the first key and appends the total key count.

func (*Channel) Save

func (channel *Channel) Save() error

func (*Channel) SaveChannelInfo

func (channel *Channel) SaveChannelInfo() error

func (*Channel) SaveWithoutKey

func (channel *Channel) SaveWithoutKey() error

func (*Channel) SetOtherInfo

func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{})

func (*Channel) SetOtherSettings

func (channel *Channel) SetOtherSettings(setting dto.ChannelOtherSettings)

func (*Channel) SetSetting

func (channel *Channel) SetSetting(setting dto.ChannelSettings)

func (*Channel) SetTag

func (channel *Channel) SetTag(tag string)

func (*Channel) Update

func (channel *Channel) Update() error

func (*Channel) UpdateAbilities

func (channel *Channel) UpdateAbilities(tx *gorm.DB) error

UpdateAbilities updates abilities of this channel. Make sure the channel is completed before calling this function.

func (*Channel) UpdateBalance

func (channel *Channel) UpdateBalance(balance float64)

func (*Channel) UpdateResponseTime

func (channel *Channel) UpdateResponseTime(responseTime int64)

func (*Channel) ValidateSettings

func (channel *Channel) ValidateSettings() error

type ChannelInfo

type ChannelInfo struct {
	IsMultiKey             bool                  `json:"is_multi_key"`                        // 是否多Key模式
	MultiKeySize           int                   `json:"multi_key_size"`                      // 多Key模式下的Key数量
	MultiKeyStatusList     map[int]int           `json:"multi_key_status_list"`               // key状态列表,key index -> status
	MultiKeyDisabledReason map[int]string        `json:"multi_key_disabled_reason,omitempty"` // key禁用原因列表,key index -> reason
	MultiKeyDisabledTime   map[int]int64         `json:"multi_key_disabled_time,omitempty"`   // key禁用时间列表,key index -> time
	MultiKeyPollingIndex   int                   `json:"multi_key_polling_index"`             // 多Key模式下轮询的key索引
	MultiKeyMode           constant.MultiKeyMode `json:"multi_key_mode"`
}

func CacheGetChannelInfo

func CacheGetChannelInfo(id int) (*ChannelInfo, error)

func (*ChannelInfo) Scan

func (c *ChannelInfo) Scan(value interface{}) error

Scan implements sql.Scanner interface

func (ChannelInfo) Value

func (c ChannelInfo) Value() (driver.Value, error)

Value implements driver.Valuer interface

type Checkin

type Checkin struct {
	Id           int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId       int    `json:"user_id" gorm:"not null;uniqueIndex:idx_user_checkin_date"`
	CheckinDate  string `json:"checkin_date" gorm:"type:varchar(10);not null;uniqueIndex:idx_user_checkin_date"` // 格式: YYYY-MM-DD
	QuotaAwarded int    `json:"quota_awarded" gorm:"not null"`
	CreatedAt    int64  `json:"created_at" gorm:"bigint"`
}

Checkin 签到记录

func GetUserCheckinRecords

func GetUserCheckinRecords(userId int, startDate, endDate string) ([]Checkin, error)

GetUserCheckinRecords 获取用户在指定日期范围内的签到记录

func UserCheckin

func UserCheckin(userId int) (*Checkin, error)

UserCheckin 执行用户签到 MySQL 和 PostgreSQL 使用事务保证原子性 SQLite 不支持嵌套事务,使用顺序操作 + 手动回滚

func (Checkin) TableName

func (Checkin) TableName() string

type CheckinRecord

type CheckinRecord struct {
	CheckinDate  string `json:"checkin_date"`
	QuotaAwarded int    `json:"quota_awarded"`
}

CheckinRecord 用于API返回的签到记录(不包含敏感字段)

type CommentAuthor

type CommentAuthor struct {
	Id          int    `json:"id"`
	Username    string `json:"username"`
	DisplayName string `json:"display_name"`
	AvatarUrl   string `json:"avatar_url"`
}

CommentAuthor 评论作者信息

type CommentWithAuthor

type CommentWithAuthor struct {
	SocialComment
	Author CommentAuthor `json:"author" gorm:"-"`
}

CommentWithAuthor 评论 + 作者信息

func EnrichCommentsWithAuthors

func EnrichCommentsWithAuthors(comments []SocialComment) []CommentWithAuthor

EnrichCommentsWithAuthors 批量加载评论作者信息

type CustomOAuthProvider

type CustomOAuthProvider struct {
	Id                    int    `json:"id" gorm:"primaryKey"`
	Name                  string `json:"name" gorm:"type:varchar(64);not null"`                          // Display name, e.g., "GitHub Enterprise"
	Slug                  string `json:"slug" gorm:"type:varchar(64);uniqueIndex;not null"`              // URL identifier, e.g., "github-enterprise"
	Icon                  string `json:"icon" gorm:"type:varchar(128);default:''"`                       // Icon name from @lobehub/icons
	Enabled               bool   `json:"enabled" gorm:"default:false"`                                   // Whether this provider is enabled
	ClientId              string `json:"client_id" gorm:"type:varchar(256)"`                             // OAuth client ID
	ClientSecret          string `json:"-" gorm:"type:varchar(512)"`                                     // OAuth client secret (not returned to frontend)
	AuthorizationEndpoint string `json:"authorization_endpoint" gorm:"type:varchar(512)"`                // Authorization URL
	TokenEndpoint         string `json:"token_endpoint" gorm:"type:varchar(512)"`                        // Token exchange URL
	UserInfoEndpoint      string `json:"user_info_endpoint" gorm:"type:varchar(512)"`                    // User info URL
	Scopes                string `json:"scopes" gorm:"type:varchar(256);default:'openid profile email'"` // OAuth scopes

	// Field mapping configuration (supports JSONPath via gjson)
	UserIdField      string `json:"user_id_field" gorm:"type:varchar(128);default:'sub'"`                 // User ID field path, e.g., "sub", "id", "data.user.id"
	UsernameField    string `json:"username_field" gorm:"type:varchar(128);default:'preferred_username'"` // Username field path
	DisplayNameField string `json:"display_name_field" gorm:"type:varchar(128);default:'name'"`           // Display name field path
	EmailField       string `json:"email_field" gorm:"type:varchar(128);default:'email'"`                 // Email field path

	// Advanced options
	WellKnown           string `json:"well_known" gorm:"type:varchar(512)"`            // OIDC discovery endpoint (optional)
	AuthStyle           int    `json:"auth_style" gorm:"default:0"`                    // 0=auto, 1=params, 2=header (Basic Auth)
	AccessPolicy        string `json:"access_policy" gorm:"type:text"`                 // JSON policy for access control based on user info
	AccessDeniedMessage string `json:"access_denied_message" gorm:"type:varchar(512)"` // Custom error message template when access is denied

	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

CustomOAuthProvider stores configuration for custom OAuth providers

func GetAllCustomOAuthProviders

func GetAllCustomOAuthProviders() ([]*CustomOAuthProvider, error)

GetAllCustomOAuthProviders returns all custom OAuth providers

func GetCustomOAuthProviderById

func GetCustomOAuthProviderById(id int) (*CustomOAuthProvider, error)

GetCustomOAuthProviderById returns a custom OAuth provider by ID

func GetCustomOAuthProviderBySlug

func GetCustomOAuthProviderBySlug(slug string) (*CustomOAuthProvider, error)

GetCustomOAuthProviderBySlug returns a custom OAuth provider by slug

func GetEnabledCustomOAuthProviders

func GetEnabledCustomOAuthProviders() ([]*CustomOAuthProvider, error)

GetEnabledCustomOAuthProviders returns all enabled custom OAuth providers

func (CustomOAuthProvider) TableName

func (CustomOAuthProvider) TableName() string

type FollowCounts

type FollowCounts struct {
	Followers int64 `json:"followers"`
	Following int64 `json:"following"`
}

FollowCounts 关注计数

func GetFollowCounts

func GetFollowCounts(userId int) (*FollowCounts, error)

GetFollowCounts 获取关注/粉丝数量

type FollowUserInfo

type FollowUserInfo struct {
	Id          int    `json:"id"`
	Username    string `json:"username"`
	DisplayName string `json:"display_name"`
	AvatarUrl   string `json:"avatar_url"`
	Bio         string `json:"bio"`
}

FollowUserInfo 关注/粉丝列表中的用户信息

func GetFollowers

func GetFollowers(userId int, page, pageSize int) ([]FollowUserInfo, int64, error)

GetFollowers 获取粉丝列表(分页)

func GetFollowing

func GetFollowing(userId int, page, pageSize int) ([]FollowUserInfo, int64, error)

GetFollowing 获取关注列表(分页)

type GachaHistory

type GachaHistory struct {
	Id        int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId    int    `json:"user_id" gorm:"not null;index:idx_gacha_history_user"`
	PoolId    int    `json:"pool_id" gorm:"not null;index:idx_gacha_history_pool"`
	SpeciesId int    `json:"species_id" gorm:"not null"`
	Rarity    string `json:"rarity" gorm:"type:varchar(8)"`
	IsPity    bool   `json:"is_pity" gorm:"default:false"`
	CreatedAt int64  `json:"created_at" gorm:"bigint"`
}

GachaHistory 扭蛋抽取记录

func GetGachaHistoryByUser

func GetGachaHistoryByUser(userId int, poolId int, page int, pageSize int) ([]GachaHistory, int64, error)

func (GachaHistory) TableName

func (GachaHistory) TableName() string

type GachaPool

type GachaPool struct {
	Id              int     `json:"id" gorm:"primaryKey;autoIncrement"`
	Name            string  `json:"name" gorm:"type:varchar(64);not null"`
	Description     string  `json:"description" gorm:"type:varchar(255)"`
	CostPerPull     int     `json:"cost_per_pull" gorm:"default:500"`
	TenPullDiscount float64 `json:"ten_pull_discount" gorm:"default:0.9"`
	Rates           string  `json:"rates" gorm:"type:text"`        // JSON: {"N":0.60,"R":0.25,"SR":0.12,"SSR":0.03}
	PityConfig      string  `json:"pity_config" gorm:"type:text"`  // JSON: {"sr_pity":10,"ssr_pity":80}
	SpeciesPool     string  `json:"species_pool" gorm:"type:text"` // JSON: [{"species_id":1,"rarity":"R","weight":100}]
	Enabled         bool    `json:"enabled" gorm:"default:true"`
	StartTime       int64   `json:"start_time" gorm:"default:0"`
	EndTime         int64   `json:"end_time" gorm:"default:0"`
	CreatedAt       int64   `json:"created_at" gorm:"bigint"`
	UpdatedAt       int64   `json:"updated_at" gorm:"bigint"`
}

GachaPool 扭蛋卡池定义

func GetActiveGachaPools

func GetActiveGachaPools() ([]GachaPool, error)

func GetAllGachaPools

func GetAllGachaPools(enabledOnly bool) ([]GachaPool, error)

func GetGachaPoolById

func GetGachaPoolById(id int) (*GachaPool, error)

func (GachaPool) TableName

func (GachaPool) TableName() string

type GringottsHeistRecord added in v0.1.7

type GringottsHeistRecord struct {
	Id          int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId      int    `json:"user_id" gorm:"not null;index:idx_heist_user"`
	HeistType   string `json:"heist_type" gorm:"type:varchar(20);not null"` // sneak, dragon, imperio
	EntranceFee int    `json:"entrance_fee" gorm:"default:0"`
	Success     bool   `json:"success" gorm:"default:false"`
	Reward      int    `json:"reward" gorm:"default:0"`
	Penalty     int    `json:"penalty" gorm:"default:0"`
	VaultBefore int64  `json:"vault_before" gorm:"default:0"`
	Details     string `json:"details" gorm:"type:text"` // JSON narrative
	CreatedAt   int64  `json:"created_at" gorm:"bigint;index:idx_heist_created"`
}

GringottsHeistRecord 古灵阁打劫记录

func GetHeistHistory added in v0.1.7

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

func GetLastHeistByType added in v0.1.7

func GetLastHeistByType(userId int, heistType string) (*GringottsHeistRecord, error)

func GetRecentSuccessfulHeist added in v0.1.7

func GetRecentSuccessfulHeist(withinSeconds int64) (*GringottsHeistRecord, error)

func (GringottsHeistRecord) TableName added in v0.1.7

func (GringottsHeistRecord) TableName() string

type JSONValue

type JSONValue json.RawMessage

JSONValue 基于 json.RawMessage 实现,支持从数据库的 []byte 和 string 两种类型读取

func (JSONValue) MarshalJSON

func (j JSONValue) MarshalJSON() ([]byte, error)

MarshalJSON 确保在对外编码时与 json.RawMessage 行为一致

func (*JSONValue) Scan

func (j *JSONValue) Scan(value interface{}) error

Scan 实现 sql.Scanner 接口,兼容不同驱动返回的类型

func (*JSONValue) UnmarshalJSON

func (j *JSONValue) UnmarshalJSON(data []byte) error

UnmarshalJSON 确保在对外解码时与 json.RawMessage 行为一致

func (JSONValue) Value

func (j JSONValue) Value() (driver.Value, error)

Value 实现 driver.Valuer 接口,用于数据库写入

type Log

type Log struct {
	Id               int    `json:"id" gorm:"index:idx_created_at_id,priority:1;index:idx_user_id_id,priority:2"`
	UserId           int    `json:"user_id" gorm:"index;index:idx_user_id_id,priority:1"`
	CreatedAt        int64  `json:"created_at" gorm:"bigint;index:idx_created_at_id,priority:2;index:idx_created_at_type"`
	Type             int    `json:"type" gorm:"index:idx_created_at_type"`
	Content          string `json:"content"`
	Username         string `json:"username" gorm:"index;index:index_username_model_name,priority:2;default:''"`
	TokenName        string `json:"token_name" gorm:"index;default:''"`
	ModelName        string `json:"model_name" gorm:"index;index:index_username_model_name,priority:1;default:''"`
	Quota            int    `json:"quota" gorm:"default:0"`
	PromptTokens     int    `json:"prompt_tokens" gorm:"default:0"`
	CompletionTokens int    `json:"completion_tokens" gorm:"default:0"`
	UseTime          int    `json:"use_time" gorm:"default:0"`
	IsStream         bool   `json:"is_stream"`
	ChannelId        int    `json:"channel" gorm:"index"`
	ChannelName      string `json:"channel_name" gorm:"->"`
	TokenId          int    `json:"token_id" gorm:"default:0;index"`
	Group            string `json:"group" gorm:"index"`
	Ip               string `json:"ip" gorm:"index;default:''"`
	RequestId        string `json:"request_id,omitempty" gorm:"type:varchar(64);index:idx_logs_request_id;default:''"`
	Other            string `json:"other"`
}

func GetAllLogs

func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, startIdx int, num int, channel int, group string, requestId string) (logs []*Log, total int64, err error)

func GetLogByTokenId

func GetLogByTokenId(tokenId int) (logs []*Log, err error)

func GetUserLogs

func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, modelName string, tokenName string, startIdx int, num int, group string, requestId string) (logs []*Log, total int64, err error)

type MarketFilter

type MarketFilter struct {
	SpeciesId   int
	Rarity      string
	MinStar     int
	MaxStar     int
	ListingType string
	MinPrice    int
	MaxPrice    int
	SortBy      string // price_asc, price_desc, time_desc, rarity
}

MarketFilter 市场筛选条件

type MarketStats

type MarketStats struct {
	TotalListings     int64 `json:"total_listings"`
	ActiveListings    int64 `json:"active_listings"`
	TotalTransactions int64 `json:"total_transactions"`
	TotalVolume       int64 `json:"total_volume"`
}

func GetMarketStats

func GetMarketStats() (*MarketStats, error)

type Midjourney

type Midjourney struct {
	Id          int    `json:"id"`
	Code        int    `json:"code"`
	UserId      int    `json:"user_id" gorm:"index"`
	Action      string `json:"action" gorm:"type:varchar(40);index"`
	MjId        string `json:"mj_id" gorm:"index"`
	Prompt      string `json:"prompt"`
	PromptEn    string `json:"prompt_en"`
	Description string `json:"description"`
	State       string `json:"state"`
	SubmitTime  int64  `json:"submit_time" gorm:"index"`
	StartTime   int64  `json:"start_time" gorm:"index"`
	FinishTime  int64  `json:"finish_time" gorm:"index"`
	ImageUrl    string `json:"image_url"`
	VideoUrl    string `json:"video_url"`
	VideoUrls   string `json:"video_urls"`
	Status      string `json:"status" gorm:"type:varchar(20);index"`
	Progress    string `json:"progress" gorm:"type:varchar(30);index"`
	FailReason  string `json:"fail_reason"`
	ChannelId   int    `json:"channel_id"`
	Quota       int    `json:"quota"`
	Buttons     string `json:"buttons"`
	Properties  string `json:"properties"`
}

func GetAllTasks

func GetAllTasks(startIdx int, num int, queryParams TaskQueryParams) []*Midjourney

func GetAllUnFinishTasks

func GetAllUnFinishTasks() []*Midjourney

func GetAllUserTask

func GetAllUserTask(userId int, startIdx int, num int, queryParams TaskQueryParams) []*Midjourney

func GetByMJId

func GetByMJId(userId int, mjId string) *Midjourney

func GetByMJIds

func GetByMJIds(userId int, mjIds []string) []*Midjourney

func GetByOnlyMJId

func GetByOnlyMJId(mjId string) *Midjourney

func GetMjByuId

func GetMjByuId(id int) *Midjourney

func (*Midjourney) Insert

func (midjourney *Midjourney) Insert() error

func (*Midjourney) Update

func (midjourney *Midjourney) Update() error

func (*Midjourney) UpdateWithStatus

func (midjourney *Midjourney) UpdateWithStatus(fromStatus string) (bool, error)

UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS). Returns (true, nil) if this caller won the update, (false, nil) if another process already moved the task out of fromStatus. UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS). Uses Model().Select("*").Updates() to avoid GORM Save()'s INSERT fallback.

type Model

type Model struct {
	Id           int            `json:"id"`
	ModelName    string         `json:"model_name" gorm:"size:128;not null;uniqueIndex:uk_model_name_delete_at,priority:1"`
	Description  string         `json:"description,omitempty" gorm:"type:text"`
	Icon         string         `json:"icon,omitempty" gorm:"type:varchar(128)"`
	Tags         string         `json:"tags,omitempty" gorm:"type:varchar(255)"`
	VendorID     int            `json:"vendor_id,omitempty" gorm:"index"`
	Endpoints    string         `json:"endpoints,omitempty" gorm:"type:text"`
	Status       int            `json:"status" gorm:"default:1"`
	SyncOfficial int            `json:"sync_official" gorm:"default:1"`
	CreatedTime  int64          `json:"created_time" gorm:"bigint"`
	UpdatedTime  int64          `json:"updated_time" gorm:"bigint"`
	DeletedAt    gorm.DeletedAt `json:"-" gorm:"index;uniqueIndex:uk_model_name_delete_at,priority:2"`

	BoundChannels []BoundChannel `json:"bound_channels,omitempty" gorm:"-"`
	EnableGroups  []string       `json:"enable_groups,omitempty" gorm:"-"`
	QuotaTypes    []int          `json:"quota_types,omitempty" gorm:"-"`
	NameRule      int            `json:"name_rule" gorm:"default:0"`

	MatchedModels []string `json:"matched_models,omitempty" gorm:"-"`
	MatchedCount  int      `json:"matched_count,omitempty" gorm:"-"`
}

func GetAllModels

func GetAllModels(offset int, limit int) ([]*Model, error)

func SearchModels

func SearchModels(keyword string, vendor string, offset int, limit int) ([]*Model, int64, error)

func (*Model) Delete

func (mi *Model) Delete() error

func (*Model) Insert

func (mi *Model) Insert() error

func (*Model) Update

func (mi *Model) Update() error

type NotificationWithActor

type NotificationWithActor struct {
	SocialNotification
	Actor       PostAuthor `json:"actor" gorm:"-"`
	PostContent *string    `json:"post_content,omitempty" gorm:"-"`
}

NotificationWithActor 通知 + 触发者信息

func EnrichNotificationsWithActors

func EnrichNotificationsWithActors(notifications []SocialNotification) []NotificationWithActor

EnrichNotificationsWithActors 批量加载触发者信息 + 帖子内容预览

type Option

type Option struct {
	Key   string `json:"key" gorm:"primaryKey"`
	Value string `json:"value"`
}

func AllOption

func AllOption() ([]*Option, error)

type PasskeyCredential

type PasskeyCredential struct {
	ID              int            `json:"id" gorm:"primaryKey"`
	UserID          int            `json:"user_id" gorm:"uniqueIndex;not null"`
	CredentialID    string         `json:"credential_id" gorm:"type:varchar(512);uniqueIndex;not null"` // base64 encoded
	PublicKey       string         `json:"public_key" gorm:"type:text;not null"`                        // base64 encoded
	AttestationType string         `json:"attestation_type" gorm:"type:varchar(255)"`
	AAGUID          string         `json:"aaguid" gorm:"type:varchar(512)"` // base64 encoded
	SignCount       uint32         `json:"sign_count" gorm:"default:0"`
	CloneWarning    bool           `json:"clone_warning"`
	UserPresent     bool           `json:"user_present"`
	UserVerified    bool           `json:"user_verified"`
	BackupEligible  bool           `json:"backup_eligible"`
	BackupState     bool           `json:"backup_state"`
	Transports      string         `json:"transports" gorm:"type:text"`
	Attachment      string         `json:"attachment" gorm:"type:varchar(32)"`
	LastUsedAt      *time.Time     `json:"last_used_at"`
	CreatedAt       time.Time      `json:"created_at"`
	UpdatedAt       time.Time      `json:"updated_at"`
	DeletedAt       gorm.DeletedAt `json:"-" gorm:"index"`
}

func GetPasskeyByCredentialID

func GetPasskeyByCredentialID(credentialID []byte) (*PasskeyCredential, error)

func GetPasskeyByUserID

func GetPasskeyByUserID(userID int) (*PasskeyCredential, error)

func NewPasskeyCredentialFromWebAuthn

func NewPasskeyCredentialFromWebAuthn(userID int, credential *webauthn.Credential) *PasskeyCredential

func (*PasskeyCredential) ApplyValidatedCredential

func (p *PasskeyCredential) ApplyValidatedCredential(credential *webauthn.Credential)

func (*PasskeyCredential) SetTransports

func (p *PasskeyCredential) SetTransports(list []protocol.AuthenticatorTransport)

func (*PasskeyCredential) ToWebAuthnCredential

func (p *PasskeyCredential) ToWebAuthnCredential() webauthn.Credential

func (*PasskeyCredential) TransportList

func (p *PasskeyCredential) TransportList() []protocol.AuthenticatorTransport

type PetActivity

type PetActivity struct {
	Id           int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId       int    `json:"user_id" gorm:"not null;index:idx_pet_activity_user"`
	PetId        int    `json:"pet_id" gorm:"not null"`
	ActivityType string `json:"activity_type" gorm:"type:varchar(32);not null"` // hatched, evolved, star_up, ssr_pulled, mission_complete
	Data         string `json:"data" gorm:"type:text"`                          // JSON: activity details
	CreatedAt    int64  `json:"created_at" gorm:"bigint"`
}

PetActivity 宠物动态

func GetRecentActivities

func GetRecentActivities(limit int) ([]PetActivity, error)

func GetUserActivities

func GetUserActivities(userId int, page int, pageSize int) ([]PetActivity, int64, error)

func (PetActivity) TableName

func (PetActivity) TableName() string

type PetArenaBattle added in v0.1.7

type PetArenaBattle struct {
	Id                   int    `json:"id" gorm:"primaryKey;autoIncrement"`
	SeasonId             int    `json:"season_id" gorm:"index:idx_battle_season"`
	AttackerUserId       int    `json:"attacker_user_id" gorm:"not null"`
	AttackerPetId        int    `json:"attacker_pet_id" gorm:"not null"`
	DefenderUserId       int    `json:"defender_user_id" gorm:"not null"`
	DefenderPetId        int    `json:"defender_pet_id" gorm:"not null"`
	WinnerUserId         int    `json:"winner_user_id" gorm:"default:0"`
	AttackerRatingBefore int    `json:"attacker_rating_before" gorm:"default:0"`
	AttackerRatingAfter  int    `json:"attacker_rating_after" gorm:"default:0"`
	DefenderRatingBefore int    `json:"defender_rating_before" gorm:"default:0"`
	DefenderRatingAfter  int    `json:"defender_rating_after" gorm:"default:0"`
	BattleLog            string `json:"battle_log" gorm:"type:text"` // JSON rounds
	RewardQuota          int    `json:"reward_quota" gorm:"default:0"`
	CreatedAt            int64  `json:"created_at" gorm:"bigint;index:idx_battle_created"`
}

PetArenaBattle 战斗记录

func GetBattleById added in v0.1.7

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

func GetUserBattleHistory added in v0.1.7

func GetUserBattleHistory(userId int, page, perPage int) ([]PetArenaBattle, int64, error)

func (PetArenaBattle) TableName added in v0.1.7

func (PetArenaBattle) TableName() string

type PetArenaDefender added in v0.1.7

type PetArenaDefender struct {
	Id        int   `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId    int   `json:"user_id" gorm:"uniqueIndex"`
	PetId     int   `json:"pet_id" gorm:"not null"`
	Rating    int   `json:"rating" gorm:"default:1000;index:idx_defender_rating"`
	WinCount  int   `json:"win_count" gorm:"default:0"`
	LossCount int   `json:"loss_count" gorm:"default:0"`
	WinStreak int   `json:"win_streak" gorm:"default:0"`
	MaxStreak int   `json:"max_streak" gorm:"default:0"`
	SeasonId  int   `json:"season_id" gorm:"index:idx_defender_season"`
	CreatedAt int64 `json:"created_at" gorm:"bigint"`
	UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
}

PetArenaDefender 守擂设置

func GetAllSeasonDefenders added in v0.1.7

func GetAllSeasonDefenders(seasonId int) ([]PetArenaDefender, error)

func GetDefender added in v0.1.7

func GetDefender(userId int) (*PetArenaDefender, error)

func GetDefenderList added in v0.1.7

func GetDefenderList(seasonId int, limit, offset int) ([]PetArenaDefender, int64, error)

func GetSeasonTopDefenders added in v0.1.7

func GetSeasonTopDefenders(seasonId int, limit int) ([]PetArenaDefender, error)

func (PetArenaDefender) TableName added in v0.1.7

func (PetArenaDefender) TableName() string

type PetArenaSeason added in v0.1.7

type PetArenaSeason struct {
	Id      int    `json:"id" gorm:"primaryKey;autoIncrement"`
	Name    string `json:"name" gorm:"type:varchar(64)"`
	StartAt int64  `json:"start_at" gorm:"bigint"`
	EndAt   int64  `json:"end_at" gorm:"bigint"`
	Status  string `json:"status" gorm:"type:varchar(10);default:'active'"` // active, ended
}

PetArenaSeason 对战赛季

func GetActiveSeason added in v0.1.7

func GetActiveSeason() (*PetArenaSeason, error)

func (PetArenaSeason) TableName added in v0.1.7

func (PetArenaSeason) TableName() string

type PetDispatch

type PetDispatch struct {
	Id          int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId      int    `json:"user_id" gorm:"not null;index:idx_pet_dispatch_user"`
	PetId       int    `json:"pet_id" gorm:"not null"`
	MissionId   int    `json:"mission_id" gorm:"not null"`
	StartedAt   int64  `json:"started_at" gorm:"bigint"`
	EndsAt      int64  `json:"ends_at" gorm:"bigint"`
	Status      string `json:"status" gorm:"type:varchar(16);default:'in_progress'"` // in_progress, completed, collected
	Success     bool   `json:"success" gorm:"default:false"`
	RewardsData string `json:"rewards_data" gorm:"type:text"` // JSON: actual rewards received
	CreatedAt   int64  `json:"created_at" gorm:"bigint"`
}

PetDispatch 派遣记录

func GetActiveDispatches

func GetActiveDispatches(userId int) ([]PetDispatch, error)

func GetDispatchById

func GetDispatchById(id int) (*PetDispatch, error)

func GetDispatchHistory

func GetDispatchHistory(userId int, page int, pageSize int) ([]PetDispatch, int64, error)

func GetInProgressDispatchesEndedBefore

func GetInProgressDispatchesEndedBefore(userId int, now int64) ([]PetDispatch, error)

GetInProgressDispatchesEndedBefore returns in_progress dispatches that have ended

func (PetDispatch) TableName

func (PetDispatch) TableName() string

type PetItem

type PetItem struct {
	Id          int     `json:"id" gorm:"primaryKey;autoIncrement"`
	Name        string  `json:"name" gorm:"type:varchar(64);not null"`
	Description string  `json:"description" gorm:"type:varchar(255)"`
	Type        string  `json:"type" gorm:"type:varchar(16);not null"` // food, potion, material
	Rarity      string  `json:"rarity" gorm:"type:varchar(8)"`
	Effect      string  `json:"effect" gorm:"type:text"` // JSON: effect definition
	Price       float64 `json:"price" gorm:"default:0"`
	VisualKey   string  `json:"visual_key" gorm:"type:varchar(64)"`
	Enabled     bool    `json:"enabled" gorm:"default:true"`
	CreatedAt   int64   `json:"created_at" gorm:"bigint"`
	UpdatedAt   int64   `json:"updated_at" gorm:"bigint"`
}

PetItem 物品定义

func GetAllItems

func GetAllItems(enabledOnly bool) ([]PetItem, error)

func GetEnabledFoodItems

func GetEnabledFoodItems() ([]PetItem, error)

GetEnabledFoodItems returns all enabled items of type "food"

func GetItemById

func GetItemById(id int) (*PetItem, error)

func (PetItem) TableName

func (PetItem) TableName() string

type PetMarketBid

type PetMarketBid struct {
	Id        int   `json:"id" gorm:"primaryKey;autoIncrement"`
	ListingId int   `json:"listing_id" gorm:"not null;index:idx_bid_listing"`
	BidderId  int   `json:"bidder_id" gorm:"not null;index:idx_bid_bidder"`
	Amount    int   `json:"amount" gorm:"not null"`
	CreatedAt int64 `json:"created_at" gorm:"bigint"`
}

PetMarketBid 竞价记录

func GetBidsForListing

func GetBidsForListing(listingId int) ([]PetMarketBid, error)

func GetHighestBid

func GetHighestBid(listingId int) (*PetMarketBid, error)

func (PetMarketBid) TableName

func (PetMarketBid) TableName() string

type PetMarketListing

type PetMarketListing struct {
	Id              int    `json:"id" gorm:"primaryKey;autoIncrement"`
	SellerId        int    `json:"seller_id" gorm:"not null;index:idx_listing_seller"`
	PetId           int    `json:"pet_id" gorm:"not null"`
	ListingType     string `json:"listing_type" gorm:"type:varchar(16);not null"` // fixed_price, auction
	Price           int    `json:"price" gorm:"default:0"`
	MinBid          int    `json:"min_bid" gorm:"default:0"`
	CurrentBid      int    `json:"current_bid" gorm:"default:0"`
	CurrentBidderId int    `json:"current_bidder_id" gorm:"default:0"`
	BidCount        int    `json:"bid_count" gorm:"default:0"`
	ExpiresAt       int64  `json:"expires_at" gorm:"bigint"`
	Status          string `json:"status" gorm:"type:varchar(16);default:'active';index:idx_listing_status"` // active, sold, expired, cancelled
	CreatedAt       int64  `json:"created_at" gorm:"bigint"`
	UpdatedAt       int64  `json:"updated_at" gorm:"bigint"`
}

PetMarketListing 市场挂单

func GetActiveListings

func GetActiveListings(page, pageSize int, filters MarketFilter) ([]PetMarketListing, int64, error)

func GetExpiredAuctions

func GetExpiredAuctions() ([]PetMarketListing, error)

func GetListingById

func GetListingById(id int) (*PetMarketListing, error)

func GetUserListings

func GetUserListings(userId, page, pageSize int) ([]PetMarketListing, int64, error)

func (PetMarketListing) TableName

func (PetMarketListing) TableName() string

type PetMarketTransaction

type PetMarketTransaction struct {
	Id          int    `json:"id" gorm:"primaryKey;autoIncrement"`
	ListingId   int    `json:"listing_id" gorm:"not null;index:idx_tx_listing"`
	SellerId    int    `json:"seller_id" gorm:"not null;index:idx_tx_seller"`
	BuyerId     int    `json:"buyer_id" gorm:"not null;index:idx_tx_buyer"`
	PetId       int    `json:"pet_id" gorm:"not null"`
	Price       int    `json:"price" gorm:"not null"`
	ListingType string `json:"listing_type" gorm:"type:varchar(16)"`
	Fee         int    `json:"fee" gorm:"default:0"`
	CreatedAt   int64  `json:"created_at" gorm:"bigint"`
}

PetMarketTransaction 成交记录

func GetRecentTransactions

func GetRecentTransactions(limit int) ([]PetMarketTransaction, error)

func GetUserTransactions

func GetUserTransactions(userId, page, pageSize int) ([]PetMarketTransaction, int64, error)

func (PetMarketTransaction) TableName

func (PetMarketTransaction) TableName() string

type PetMission

type PetMission struct {
	Id            int    `json:"id" gorm:"primaryKey;autoIncrement"`
	Name          string `json:"name" gorm:"type:varchar(64);not null"`
	Description   string `json:"description" gorm:"type:varchar(255)"`
	Duration      int    `json:"duration" gorm:"default:3600"` // seconds
	Difficulty    int    `json:"difficulty" gorm:"default:1"`  // 1-5
	RequiredLevel int    `json:"required_level" gorm:"default:1"`
	StatWeights   string `json:"stat_weights" gorm:"type:text"` // JSON: {"attack":0.3,"speed":0.5,"luck":0.2}
	Rewards       string `json:"rewards" gorm:"type:text"`      // JSON: [{"type":"quota","amount":100,"probability":1.0},{"type":"item","id":1,"amount":1,"probability":0.5}]
	MaxDaily      int    `json:"max_daily" gorm:"default:3"`
	Enabled       bool   `json:"enabled" gorm:"default:true"`
	CreatedAt     int64  `json:"created_at" gorm:"bigint"`
	UpdatedAt     int64  `json:"updated_at" gorm:"bigint"`
}

PetMission 任务定义

func GetAllMissions

func GetAllMissions(enabledOnly bool) ([]PetMission, error)

func GetMissionById

func GetMissionById(id int) (*PetMission, error)

func (PetMission) TableName

func (PetMission) TableName() string

type PetPriceHistory

type PetPriceHistory struct {
	Id               int    `json:"id" gorm:"primaryKey;autoIncrement"`
	SpeciesId        int    `json:"species_id" gorm:"not null;index:idx_price_species"`
	Rarity           string `json:"rarity" gorm:"type:varchar(8)"`
	Star             int    `json:"star" gorm:"default:0"`
	AvgPrice         int    `json:"avg_price" gorm:"default:0"`
	MinPrice         int    `json:"min_price" gorm:"default:0"`
	MaxPrice         int    `json:"max_price" gorm:"default:0"`
	TransactionCount int    `json:"transaction_count" gorm:"default:0"`
	Period           string `json:"period" gorm:"type:varchar(16)"` // daily, weekly
	Date             string `json:"date" gorm:"type:varchar(16)"`
	CreatedAt        int64  `json:"created_at" gorm:"bigint"`
}

PetPriceHistory 价格历史

func GetPriceHistory

func GetPriceHistory(speciesId int, limit int) ([]PetPriceHistory, error)

func (PetPriceHistory) TableName

func (PetPriceHistory) TableName() string

type PetSpecies

type PetSpecies struct {
	Id              int    `json:"id" gorm:"primaryKey;autoIncrement"`
	Name            string `json:"name" gorm:"type:varchar(64);not null"`
	Description     string `json:"description" gorm:"type:varchar(255)"`
	Rarity          string `json:"rarity" gorm:"type:varchar(8);not null"` // N, R, SR, SSR
	Element         string `json:"element" gorm:"type:varchar(16)"`
	BaseStats       string `json:"base_stats" gorm:"type:text"`       // JSON: {hp, atk, def, spd, ...}
	EvolutionStages string `json:"evolution_stages" gorm:"type:text"` // JSON: [{stage, name, visual_key}, ...]
	VisualKey       string `json:"visual_key" gorm:"type:varchar(64)"`
	IsStarter       bool   `json:"is_starter" gorm:"default:false"`
	Enabled         bool   `json:"enabled" gorm:"default:true"`
	CreatedAt       int64  `json:"created_at" gorm:"bigint"`
	UpdatedAt       int64  `json:"updated_at" gorm:"bigint"`
}

PetSpecies 宠物物种定义

func GetAllSpecies

func GetAllSpecies(enabledOnly bool) ([]PetSpecies, error)

func GetSpeciesById

func GetSpeciesById(id int) (*PetSpecies, error)

func GetStarterSpecies

func GetStarterSpecies() ([]PetSpecies, error)

func (PetSpecies) TableName

func (PetSpecies) TableName() string

type PetStatsResult

type PetStatsResult struct {
	PetCount   int `json:"pet_count"`
	MaxLevel   int `json:"max_level"`
	TotalStars int `json:"total_stars"`
}

PetStatsResult holds aggregated pet stats for a user

func GetUserPetStats

func GetUserPetStats(userId int) (*PetStatsResult, error)

GetUserPetStats returns aggregated pet statistics for a user

type PostAuthor

type PostAuthor struct {
	Id          int    `json:"id"`
	Username    string `json:"username"`
	DisplayName string `json:"display_name"`
	AvatarUrl   string `json:"avatar_url"`
}

PostAuthor 帖子作者信息(用于批量加载,避免 N+1 查询)

type PostWithAuthor

type PostWithAuthor struct {
	SocialPost
	Author         PostAuthor      `json:"author" gorm:"-"`
	LikeCount      int64           `json:"like_count" gorm:"-"`
	CommentCount   int64           `json:"comment_count" gorm:"-"`
	RepostCount    int64           `json:"repost_count" gorm:"-"`
	Liked          bool            `json:"liked" gorm:"-"`
	Bookmarked     bool            `json:"bookmarked" gorm:"-"`
	RepostOriginal *PostWithAuthor `json:"repost_original,omitempty" gorm:"-"`
}

PostWithAuthor 帖子 + 作者信息 + 互动数据

func EnrichPostsWithAuthors

func EnrichPostsWithAuthors(posts []SocialPost) []PostWithAuthor

EnrichPostsWithAuthors 批量加载帖子作者信息

func EnrichPostsWithInteractions

func EnrichPostsWithInteractions(posts []SocialPost, currentUserId int) []PostWithAuthor

EnrichPostsWithInteractions 批量加载帖子的作者 + 互动数据(点赞/评论/收藏)

type PrefillGroup

type PrefillGroup struct {
	Id          int            `json:"id"`
	Name        string         `json:"name" gorm:"size:64;not null;uniqueIndex:uk_prefill_name,where:deleted_at IS NULL"`
	Type        string         `json:"type" gorm:"size:32;index;not null"`
	Items       JSONValue      `json:"items" gorm:"type:json"`
	Description string         `json:"description,omitempty" gorm:"type:varchar(255)"`
	CreatedTime int64          `json:"created_time" gorm:"bigint"`
	UpdatedTime int64          `json:"updated_time" gorm:"bigint"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index"`
}

func GetAllPrefillGroups

func GetAllPrefillGroups(groupType string) ([]*PrefillGroup, error)

GetAllPrefillGroups 获取全部组,可按类型过滤(为空则返回全部)

func (*PrefillGroup) Insert

func (g *PrefillGroup) Insert() error

Insert 新建组

func (*PrefillGroup) Update

func (g *PrefillGroup) Update() error

Update 更新组

type Pricing

type Pricing struct {
	ModelName              string                  `json:"model_name"`
	Description            string                  `json:"description,omitempty"`
	Icon                   string                  `json:"icon,omitempty"`
	Tags                   string                  `json:"tags,omitempty"`
	VendorID               int                     `json:"vendor_id,omitempty"`
	QuotaType              int                     `json:"quota_type"`
	ModelRatio             float64                 `json:"model_ratio"`
	ModelPrice             float64                 `json:"model_price"`
	OwnerBy                string                  `json:"owner_by"`
	CompletionRatio        float64                 `json:"completion_ratio"`
	CacheRatio             *float64                `json:"cache_ratio,omitempty"`
	CreateCacheRatio       *float64                `json:"create_cache_ratio,omitempty"`
	ImageRatio             *float64                `json:"image_ratio,omitempty"`
	AudioRatio             *float64                `json:"audio_ratio,omitempty"`
	AudioCompletionRatio   *float64                `json:"audio_completion_ratio,omitempty"`
	EnableGroup            []string                `json:"enable_groups"`
	SupportedEndpointTypes []constant.EndpointType `json:"supported_endpoint_types"`
	PricingVersion         string                  `json:"pricing_version,omitempty"`
}

func GetPricing

func GetPricing() []Pricing

type PricingVendor

type PricingVendor struct {
	ID          int    `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Icon        string `json:"icon,omitempty"`
}

func GetVendors

func GetVendors() []PricingVendor

GetVendors 返回当前定价接口使用到的供应商信息

type Properties

type Properties struct {
	Input             string `json:"input"`
	UpstreamModelName string `json:"upstream_model_name,omitempty"`
	OriginModelName   string `json:"origin_model_name,omitempty"`
}

func (*Properties) Scan

func (m *Properties) Scan(val interface{}) error

func (Properties) Value

func (m Properties) Value() (driver.Value, error)

type QuotaData

type QuotaData struct {
	Id        int    `json:"id"`
	UserID    int    `json:"user_id" gorm:"index"`
	Username  string `json:"username" gorm:"index:idx_qdt_model_user_name,priority:2;size:64;default:''"`
	ModelName string `json:"model_name" gorm:"index:idx_qdt_model_user_name,priority:1;size:64;default:''"`
	CreatedAt int64  `json:"created_at" gorm:"bigint;index:idx_qdt_created_at,priority:2"`
	TokenUsed int    `json:"token_used" gorm:"default:0"`
	Count     int    `json:"count" gorm:"default:0"`
	Quota     int    `json:"quota" gorm:"default:0"`
}

QuotaData 柱状图数据

func GetAllQuotaDates

func GetAllQuotaDates(startTime int64, endTime int64, username string) (quotaData []*QuotaData, err error)

func GetQuotaDataByUserId

func GetQuotaDataByUserId(userId int, startTime int64, endTime int64) (quotaData []*QuotaData, err error)

func GetQuotaDataByUsername

func GetQuotaDataByUsername(username string, startTime int64, endTime int64) (quotaData []*QuotaData, err error)

type RankingUser

type RankingUser struct {
	Rank        int    `json:"rank"`
	Id          int    `json:"id"`
	Username    string `json:"username"`
	DisplayName string `json:"display_name"`
	AvatarUrl   string `json:"avatar_url"`
	Value       int    `json:"value"`
}

RankingUser represents a user entry in the ranking leaderboard

func GetAIKingRanking

func GetAIKingRanking(limit int) ([]RankingUser, error)

GetAIKingRanking returns top users by used quota (AI大王排名)

func GetHoarderRanking

func GetHoarderRanking(limit int) ([]RankingUser, error)

GetHoarderRanking returns top users by available quota (屯屯鼠排名)

type RecordConsumeLogParams

type RecordConsumeLogParams struct {
	ChannelId        int                    `json:"channel_id"`
	PromptTokens     int                    `json:"prompt_tokens"`
	CompletionTokens int                    `json:"completion_tokens"`
	ModelName        string                 `json:"model_name"`
	TokenName        string                 `json:"token_name"`
	Quota            int                    `json:"quota"`
	Content          string                 `json:"content"`
	TokenId          int                    `json:"token_id"`
	UseTimeSeconds   int                    `json:"use_time_seconds"`
	IsStream         bool                   `json:"is_stream"`
	Group            string                 `json:"group"`
	Other            map[string]interface{} `json:"other"`
}

type RecordTaskBillingLogParams

type RecordTaskBillingLogParams struct {
	UserId    int
	LogType   int
	Content   string
	ChannelId int
	ModelName string
	Quota     int
	TokenId   int
	Group     string
	Other     map[string]interface{}
}

type Redemption

type Redemption struct {
	Id           int            `json:"id"`
	UserId       int            `json:"user_id"`
	Key          string         `json:"key" gorm:"type:char(32);uniqueIndex"`
	Status       int            `json:"status" gorm:"default:1"`
	Name         string         `json:"name" gorm:"index"`
	Quota        int            `json:"quota" gorm:"default:100"`
	CreatedTime  int64          `json:"created_time" gorm:"bigint"`
	RedeemedTime int64          `json:"redeemed_time" gorm:"bigint"`
	Count        int            `json:"count" gorm:"-:all"` // only for api request
	UsedUserId   int            `json:"used_user_id"`
	DeletedAt    gorm.DeletedAt `gorm:"index"`
	ExpiredTime  int64          `json:"expired_time" gorm:"bigint"` // 过期时间,0 表示不过期
}

func GetAllRedemptions

func GetAllRedemptions(startIdx int, num int) (redemptions []*Redemption, total int64, err error)

func GetRedemptionById

func GetRedemptionById(id int) (*Redemption, error)

func SearchRedemptions

func SearchRedemptions(keyword string, startIdx int, num int) (redemptions []*Redemption, total int64, err error)

func (*Redemption) Delete

func (redemption *Redemption) Delete() error

func (*Redemption) Insert

func (redemption *Redemption) Insert() error

func (*Redemption) SelectUpdate

func (redemption *Redemption) SelectUpdate() error

func (*Redemption) Update

func (redemption *Redemption) Update() error

Update Make sure your token's fields is completed, because this will update non-zero values

type Setup

type Setup struct {
	ID            uint   `json:"id" gorm:"primaryKey"`
	Version       string `json:"version" gorm:"type:varchar(50);not null"`
	InitializedAt int64  `json:"initialized_at" gorm:"type:bigint;not null"`
}

func GetSetup

func GetSetup() *Setup

type SocialBookmark

type SocialBookmark struct {
	Id        int   `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId    int   `json:"user_id" gorm:"not null;uniqueIndex:idx_bookmark_pair;index:idx_bookmark_user"`
	PostId    int   `json:"post_id" gorm:"not null;uniqueIndex:idx_bookmark_pair"`
	CreatedAt int64 `json:"created_at" gorm:"bigint"`
}

SocialBookmark 收藏记录

func (SocialBookmark) TableName

func (SocialBookmark) TableName() string

type SocialComment

type SocialComment struct {
	Id        int            `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId    int            `json:"user_id" gorm:"not null;index:idx_comment_user"`
	PostId    int            `json:"post_id" gorm:"not null;index:idx_comment_post"`
	Content   string         `json:"content" gorm:"type:text;not null"`
	Status    int            `json:"status" gorm:"type:int;default:1"` // 1=visible, 2=hidden
	CreatedAt int64          `json:"created_at" gorm:"bigint"`
	UpdatedAt int64          `json:"updated_at" gorm:"bigint"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

SocialComment 社区评论

func CreateComment

func CreateComment(userId, postId int, content string) (*SocialComment, error)

CreateComment 创建评论

func GetPostComments

func GetPostComments(postId int, page, pageSize int) ([]SocialComment, int64, error)

GetPostComments 获取帖子评论列表(分页,仅 visible)

func (SocialComment) TableName

func (SocialComment) TableName() string

type SocialFollow

type SocialFollow struct {
	Id          int   `json:"id" gorm:"primaryKey;autoIncrement"`
	FollowerId  int   `json:"follower_id" gorm:"not null;uniqueIndex:idx_follow_pair"`
	FollowingId int   `json:"following_id" gorm:"not null;uniqueIndex:idx_follow_pair"`
	CreatedAt   int64 `json:"created_at" gorm:"bigint"`
}

SocialFollow 关注关系

func (SocialFollow) TableName

func (SocialFollow) TableName() string

type SocialLike

type SocialLike struct {
	Id        int   `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId    int   `json:"user_id" gorm:"not null;uniqueIndex:idx_like_pair"`
	PostId    int   `json:"post_id" gorm:"not null;uniqueIndex:idx_like_pair;index:idx_like_post"`
	CreatedAt int64 `json:"created_at" gorm:"bigint"`
}

SocialLike 点赞记录

func (SocialLike) TableName

func (SocialLike) TableName() string

type SocialNotification

type SocialNotification struct {
	Id        int    `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId    int    `json:"user_id" gorm:"not null;index:idx_notif_user_read"`
	ActorId   int    `json:"actor_id" gorm:"not null"`
	Type      string `json:"type" gorm:"type:varchar(16);not null"`
	PostId    *int   `json:"post_id,omitempty" gorm:"index:idx_notif_post"`
	CommentId *int   `json:"comment_id,omitempty"`
	IsRead    bool   `json:"is_read" gorm:"default:false;index:idx_notif_user_read"`
	CreatedAt int64  `json:"created_at" gorm:"bigint"`
}

SocialNotification 社区通知

func GetNotifications

func GetNotifications(userId int, page, pageSize int) ([]SocialNotification, int64, error)

GetNotifications 获取通知列表(分页)

func (SocialNotification) TableName

func (SocialNotification) TableName() string

type SocialPost

type SocialPost struct {
	Id        int            `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId    int            `json:"user_id" gorm:"not null;index:idx_social_post_user"`
	Content   string         `json:"content" gorm:"type:text;not null"`
	RepostId  *int           `json:"repost_id,omitempty" gorm:"index:idx_social_post_repost"`
	Status    int            `json:"status" gorm:"type:int;default:1;index:idx_social_post_status"` // 1=visible, 2=hidden
	CreatedAt int64          `json:"created_at" gorm:"bigint;index:idx_social_post_created"`
	UpdatedAt int64          `json:"updated_at" gorm:"bigint"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

SocialPost 社区帖子

func AdminGetPosts

func AdminGetPosts(status int, page, pageSize int) ([]SocialPost, int64, error)

AdminGetPosts 管理员获取帖子列表(分页,可按状态筛选)

func CreatePost

func CreatePost(userId int, content string) (*SocialPost, error)

CreatePost 创建帖子

func CreateRepost

func CreateRepost(userId, originalPostId int, content string) (*SocialPost, error)

CreateRepost 创建引用转发

func GetFeedPosts

func GetFeedPosts(userId int, page, pageSize int) ([]SocialPost, int64, error)

GetFeedPosts 获取关注时间线(关注者的帖子,分页)

func GetPostById

func GetPostById(id int) (*SocialPost, error)

GetPostById 根据 ID 获取帖子

func GetSquarePosts

func GetSquarePosts(page, pageSize int) ([]SocialPost, int64, error)

GetSquarePosts 获取广场帖子(全站,分页)

func GetUserBookmarks

func GetUserBookmarks(userId int, page, pageSize int) ([]SocialPost, int64, error)

GetUserBookmarks 获取用户收藏列表(分页,返回帖子)

func GetUserPosts

func GetUserPosts(userId int, page, pageSize int) ([]SocialPost, int64, error)

GetUserPosts 获取用户的帖子(分页,仅 visible)

func (SocialPost) TableName

func (SocialPost) TableName() string

type Stat

type Stat struct {
	Quota int `json:"quota"`
	Rpm   int `json:"rpm"`
	Tpm   int `json:"tpm"`
}

func SumUsedQuota

func SumUsedQuota(logType int, startTimestamp int64, endTimestamp int64, modelName string, username string, tokenName string, channel int, group string) (stat Stat, err error)

type SubscriptionOrder

type SubscriptionOrder struct {
	Id     int     `json:"id"`
	UserId int     `json:"user_id" gorm:"index"`
	PlanId int     `json:"plan_id" gorm:"index"`
	Money  float64 `json:"money"`

	TradeNo       string `json:"trade_no" gorm:"unique;type:varchar(255);index"`
	PaymentMethod string `json:"payment_method" gorm:"type:varchar(50)"`
	Status        string `json:"status"`
	CreateTime    int64  `json:"create_time"`
	CompleteTime  int64  `json:"complete_time"`

	ProviderPayload string `json:"provider_payload" gorm:"type:text"`
}

Subscription order (payment -> webhook -> create UserSubscription)

func GetSubscriptionOrderByTradeNo

func GetSubscriptionOrderByTradeNo(tradeNo string) *SubscriptionOrder

func (*SubscriptionOrder) Insert

func (o *SubscriptionOrder) Insert() error

func (*SubscriptionOrder) Update

func (o *SubscriptionOrder) Update() error

type SubscriptionPlan

type SubscriptionPlan struct {
	Id int `json:"id"`

	Title    string `json:"title" gorm:"type:varchar(128);not null"`
	Subtitle string `json:"subtitle" gorm:"type:varchar(255);default:''"`

	// Display money amount (follow existing code style: float64 for money)
	PriceAmount float64 `json:"price_amount" gorm:"type:decimal(10,6);not null;default:0"`
	Currency    string  `json:"currency" gorm:"type:varchar(8);not null;default:'USD'"`

	DurationUnit  string `json:"duration_unit" gorm:"type:varchar(16);not null;default:'month'"`
	DurationValue int    `json:"duration_value" gorm:"type:int;not null;default:1"`
	CustomSeconds int64  `json:"custom_seconds" gorm:"type:bigint;not null;default:0"`

	Enabled   bool `json:"enabled" gorm:"default:true"`
	SortOrder int  `json:"sort_order" gorm:"type:int;default:0"`

	StripePriceId  string `json:"stripe_price_id" gorm:"type:varchar(128);default:''"`
	CreemProductId string `json:"creem_product_id" gorm:"type:varchar(128);default:''"`

	// Max purchases per user (0 = unlimited)
	MaxPurchasePerUser int `json:"max_purchase_per_user" gorm:"type:int;default:0"`

	// Upgrade user group after purchase (empty = no change)
	UpgradeGroup string `json:"upgrade_group" gorm:"type:varchar(64);default:''"`

	// Total quota (amount in quota units, 0 = unlimited)
	TotalAmount int64 `json:"total_amount" gorm:"type:bigint;not null;default:0"`

	// Quota reset period for plan
	QuotaResetPeriod        string `json:"quota_reset_period" gorm:"type:varchar(16);default:'never'"`
	QuotaResetCustomSeconds int64  `json:"quota_reset_custom_seconds" gorm:"type:bigint;default:0"`

	CreatedAt int64 `json:"created_at" gorm:"bigint"`
	UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
}

Subscription plan

func GetSubscriptionPlanById

func GetSubscriptionPlanById(id int) (*SubscriptionPlan, error)

func (*SubscriptionPlan) BeforeCreate

func (p *SubscriptionPlan) BeforeCreate(tx *gorm.DB) error

func (*SubscriptionPlan) BeforeUpdate

func (p *SubscriptionPlan) BeforeUpdate(tx *gorm.DB) error

type SubscriptionPlanInfo

type SubscriptionPlanInfo struct {
	PlanId    int
	PlanTitle string
}

func GetSubscriptionPlanInfoByUserSubscriptionId

func GetSubscriptionPlanInfoByUserSubscriptionId(userSubscriptionId int) (*SubscriptionPlanInfo, error)

type SubscriptionPreConsumeRecord

type SubscriptionPreConsumeRecord struct {
	Id                 int    `json:"id"`
	RequestId          string `json:"request_id" gorm:"type:varchar(64);uniqueIndex"`
	UserId             int    `json:"user_id" gorm:"index"`
	UserSubscriptionId int    `json:"user_subscription_id" gorm:"index"`
	PreConsumed        int64  `json:"pre_consumed" gorm:"type:bigint;not null;default:0"`
	Status             string `json:"status" gorm:"type:varchar(32);index"` // consumed/refunded
	CreatedAt          int64  `json:"created_at" gorm:"bigint"`
	UpdatedAt          int64  `json:"updated_at" gorm:"bigint;index"`
}

SubscriptionPreConsumeRecord stores idempotent pre-consume operations per request.

func (*SubscriptionPreConsumeRecord) BeforeCreate

func (r *SubscriptionPreConsumeRecord) BeforeCreate(tx *gorm.DB) error

func (*SubscriptionPreConsumeRecord) BeforeUpdate

func (r *SubscriptionPreConsumeRecord) BeforeUpdate(tx *gorm.DB) error

type SubscriptionPreConsumeResult

type SubscriptionPreConsumeResult struct {
	UserSubscriptionId int
	PreConsumed        int64
	AmountTotal        int64
	AmountUsedBefore   int64
	AmountUsedAfter    int64
}

func PreConsumeUserSubscription

func PreConsumeUserSubscription(requestId string, userId int, modelName string, quotaType int, amount int64) (*SubscriptionPreConsumeResult, error)

PreConsumeUserSubscription pre-consumes from any active subscription total quota.

type SubscriptionSummary

type SubscriptionSummary struct {
	Subscription *UserSubscription `json:"subscription"`
}

func GetAllActiveUserSubscriptions

func GetAllActiveUserSubscriptions(userId int) ([]SubscriptionSummary, error)

GetAllActiveUserSubscriptions returns all active subscriptions for a user.

func GetAllUserSubscriptions

func GetAllUserSubscriptions(userId int) ([]SubscriptionSummary, error)

GetAllUserSubscriptions returns all subscriptions (active and expired) for a user.

type SyncTaskQueryParams

type SyncTaskQueryParams struct {
	Platform       constant.TaskPlatform
	ChannelID      string
	TaskID         string
	UserID         string
	Action         string
	Status         string
	StartTimestamp int64
	EndTimestamp   int64
	UserIDs        []int
}

SyncTaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段

type Task

type Task struct {
	ID         int64                 `json:"id" gorm:"primary_key;AUTO_INCREMENT"`
	CreatedAt  int64                 `json:"created_at" gorm:"index"`
	UpdatedAt  int64                 `json:"updated_at"`
	TaskID     string                `json:"task_id" gorm:"type:varchar(191);index"` // 第三方id,不一定有/ song id\ Task id
	Platform   constant.TaskPlatform `json:"platform" gorm:"type:varchar(30);index"` // 平台
	UserId     int                   `json:"user_id" gorm:"index"`
	Group      string                `json:"group" gorm:"type:varchar(50)"` // 修正计费用
	ChannelId  int                   `json:"channel_id" gorm:"index"`
	Quota      int                   `json:"quota"`
	Action     string                `json:"action" gorm:"type:varchar(40);index"` // 任务类型, song, lyrics, description-mode
	Status     TaskStatus            `json:"status" gorm:"type:varchar(20);index"` // 任务状态
	FailReason string                `json:"fail_reason"`
	SubmitTime int64                 `json:"submit_time" gorm:"index"`
	StartTime  int64                 `json:"start_time" gorm:"index"`
	FinishTime int64                 `json:"finish_time" gorm:"index"`
	Progress   string                `json:"progress" gorm:"type:varchar(20);index"`
	Properties Properties            `json:"properties" gorm:"type:json"`
	Username   string                `json:"username,omitempty" gorm:"-"`
	// 禁止返回给用户,内部可能包含key等隐私信息
	PrivateData TaskPrivateData `json:"-" gorm:"column:private_data;type:json"`
	Data        json.RawMessage `json:"data" gorm:"type:json"`
}

func GetAllUnFinishSyncTasks

func GetAllUnFinishSyncTasks(limit int) []*Task

func GetByOnlyTaskId

func GetByOnlyTaskId(taskId string) (*Task, bool, error)

func GetByTaskId

func GetByTaskId(userId int, taskId string) (*Task, bool, error)

func GetByTaskIds

func GetByTaskIds(userId int, taskIds []any) ([]*Task, error)

func GetTimedOutUnfinishedTasks

func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task

func InitTask

func InitTask(platform constant.TaskPlatform, relayInfo *commonRelay.RelayInfo) *Task

func TaskGetAllTasks

func TaskGetAllTasks(startIdx int, num int, queryParams SyncTaskQueryParams) []*Task

func TaskGetAllUserTask

func TaskGetAllUserTask(userId int, startIdx int, num int, queryParams SyncTaskQueryParams) []*Task

func (*Task) GetData

func (t *Task) GetData(v any) error

func (*Task) GetResultURL

func (t *Task) GetResultURL() string

GetResultURL 获取任务结果 URL(视频地址等) 新数据存在 PrivateData.ResultURL 中;旧数据回退到 FailReason(历史兼容)

func (*Task) GetUpstreamTaskID

func (t *Task) GetUpstreamTaskID() string

GetUpstreamTaskID 获取上游真实 task ID(用于与 provider 通信) 旧数据没有 UpstreamTaskID 时,TaskID 本身就是上游 ID

func (*Task) Insert

func (Task *Task) Insert() error

func (*Task) SetData

func (t *Task) SetData(data any)

func (*Task) Snapshot

func (t *Task) Snapshot() taskSnapshot

func (*Task) ToOpenAIVideo

func (t *Task) ToOpenAIVideo() *dto.OpenAIVideo

func (*Task) Update

func (Task *Task) Update() error

func (*Task) UpdateWithStatus

func (t *Task) UpdateWithStatus(fromStatus TaskStatus) (bool, error)

UpdateWithStatus performs a conditional UPDATE guarded by fromStatus (CAS). Returns (true, nil) if this caller won the update, (false, nil) if another process already moved the task out of fromStatus.

Uses Model().Select("*").Updates() instead of Save() because GORM's Save falls back to INSERT ON CONFLICT when the WHERE-guarded UPDATE matches zero rows, which silently bypasses the CAS guard.

type TaskBillingContext

type TaskBillingContext struct {
	ModelPrice      float64            `json:"model_price,omitempty"`       // 模型单价
	GroupRatio      float64            `json:"group_ratio,omitempty"`       // 分组倍率
	ModelRatio      float64            `json:"model_ratio,omitempty"`       // 模型倍率
	OtherRatios     map[string]float64 `json:"other_ratios,omitempty"`      // 附加倍率(时长、分辨率等)
	OriginModelName string             `json:"origin_model_name,omitempty"` // 模型名称,必须为OriginModelName
	PerCallBilling  bool               `json:"per_call_billing,omitempty"`  // 按次计费:跳过轮询阶段的差额结算
}

TaskBillingContext 记录任务提交时的计费参数,以便轮询阶段可以重新计算额度。

type TaskPrivateData

type TaskPrivateData struct {
	Key            string `json:"key,omitempty"`
	UpstreamTaskID string `json:"upstream_task_id,omitempty"` // 上游真实 task ID
	ResultURL      string `json:"result_url,omitempty"`       // 任务成功后的结果 URL(视频地址等)
	// 计费上下文:用于异步退款/差额结算(轮询阶段读取)
	BillingSource  string              `json:"billing_source,omitempty"`  // "wallet" 或 "subscription"
	SubscriptionId int                 `json:"subscription_id,omitempty"` // 订阅 ID,用于订阅退款
	TokenId        int                 `json:"token_id,omitempty"`        // 令牌 ID,用于令牌额度退款
	BillingContext *TaskBillingContext `json:"billing_context,omitempty"` // 计费参数快照(用于轮询阶段重新计算)
}

func (*TaskPrivateData) Scan

func (p *TaskPrivateData) Scan(val interface{}) error

func (TaskPrivateData) Value

func (p TaskPrivateData) Value() (driver.Value, error)

type TaskQueryParams

type TaskQueryParams struct {
	ChannelID      string
	MjID           string
	StartTimestamp string
	EndTimestamp   string
}

TaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段

type TaskQuotaUsage

type TaskQuotaUsage struct {
	Mode  string  `json:"mode"`
	Count float64 `json:"count"`
}

type TaskStatus

type TaskStatus string

func (TaskStatus) ToVideoStatus

func (t TaskStatus) ToVideoStatus() string

type Title added in v0.1.7

type Title struct {
	Id          int    `json:"id" gorm:"primaryKey;autoIncrement"`
	Key         string `json:"key" gorm:"type:varchar(50);uniqueIndex"`
	Name        string `json:"name" gorm:"type:varchar(64)"`
	Description string `json:"description" gorm:"type:varchar(255)"`
	Category    string `json:"category" gorm:"type:varchar(20)"` // casino, pet, heist, arena, social
	Rarity      string `json:"rarity" gorm:"type:varchar(8)"`    // N, R, SR, SSR
	Color       string `json:"color" gorm:"type:varchar(20)"`
	Condition   string `json:"condition" gorm:"type:text"` // JSON auto-grant condition
	SortOrder   int    `json:"sort_order" gorm:"default:0"`
	Enabled     bool   `json:"enabled" gorm:"default:true"`
	CreatedAt   int64  `json:"created_at" gorm:"bigint"`
}

Title 称号定义

func GetAllTitles added in v0.1.7

func GetAllTitles() ([]Title, error)

func GetTitleById added in v0.1.7

func GetTitleById(id int) (*Title, error)

func GetTitleByKey added in v0.1.7

func GetTitleByKey(key string) (*Title, error)

func GetUserActiveTitle added in v0.1.7

func GetUserActiveTitle(userId int) (*Title, error)

func (Title) TableName added in v0.1.7

func (Title) TableName() string

type Token

type Token struct {
	Id                 int            `json:"id"`
	UserId             int            `json:"user_id" gorm:"index"`
	Key                string         `json:"key" gorm:"type:char(48);uniqueIndex"`
	Status             int            `json:"status" gorm:"default:1"`
	Name               string         `json:"name" gorm:"index" `
	CreatedTime        int64          `json:"created_time" gorm:"bigint"`
	AccessedTime       int64          `json:"accessed_time" gorm:"bigint"`
	ExpiredTime        int64          `json:"expired_time" gorm:"bigint;default:-1"` // -1 means never expired
	RemainQuota        int            `json:"remain_quota" gorm:"default:0"`
	UnlimitedQuota     bool           `json:"unlimited_quota"`
	ModelLimitsEnabled bool           `json:"model_limits_enabled"`
	ModelLimits        string         `json:"model_limits" gorm:"type:text"`
	AllowIps           *string        `json:"allow_ips" gorm:"default:''"`
	UsedQuota          int            `json:"used_quota" gorm:"default:0"` // used quota
	Group              string         `json:"group" gorm:"default:''"`
	CrossGroupRetry    bool           `json:"cross_group_retry"` // 跨分组重试,仅auto分组有效
	DeletedAt          gorm.DeletedAt `gorm:"index"`
}

func GetAllUserTokens

func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error)

func GetTokenById

func GetTokenById(id int) (*Token, error)

func GetTokenByIds

func GetTokenByIds(id int, userId int) (*Token, error)

func GetTokenByKey

func GetTokenByKey(key string, fromDB bool) (token *Token, err error)

func SearchUserTokens

func SearchUserTokens(userId int, keyword string, token string, offset int, limit int) (tokens []*Token, total int64, err error)

func ValidateUserToken

func ValidateUserToken(key string) (token *Token, err error)

func (*Token) Clean

func (token *Token) Clean()

func (*Token) Delete

func (token *Token) Delete() (err error)

func (*Token) GetFullKey

func (token *Token) GetFullKey() string

func (*Token) GetIpLimits

func (token *Token) GetIpLimits() []string

func (*Token) GetMaskedKey

func (token *Token) GetMaskedKey() string

func (*Token) GetModelLimits

func (token *Token) GetModelLimits() []string

func (*Token) GetModelLimitsMap

func (token *Token) GetModelLimitsMap() map[string]bool

func (*Token) Insert

func (token *Token) Insert() error

func (*Token) IsModelLimitsEnabled

func (token *Token) IsModelLimitsEnabled() bool

func (*Token) SelectUpdate

func (token *Token) SelectUpdate() (err error)

func (*Token) Update

func (token *Token) Update() (err error)

Update Make sure your token's fields is completed, because this will update non-zero values

type TopUp

type TopUp struct {
	Id            int     `json:"id"`
	UserId        int     `json:"user_id" gorm:"index"`
	Amount        int64   `json:"amount"`
	Money         float64 `json:"money"`
	TradeNo       string  `json:"trade_no" gorm:"unique;type:varchar(255);index"`
	PaymentMethod string  `json:"payment_method" gorm:"type:varchar(50)"`
	CreateTime    int64   `json:"create_time"`
	CompleteTime  int64   `json:"complete_time"`
	Status        string  `json:"status"`
}

func GetAllTopUps

func GetAllTopUps(pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

GetAllTopUps 获取全平台的充值记录(管理员使用)

func GetTopUpById

func GetTopUpById(id int) *TopUp

func GetTopUpByTradeNo

func GetTopUpByTradeNo(tradeNo string) *TopUp

func GetUserTopUps

func GetUserTopUps(userId int, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

func SearchAllTopUps

func SearchAllTopUps(keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

SearchAllTopUps 按订单号搜索全平台充值记录(管理员使用)

func SearchUserTopUps

func SearchUserTopUps(userId int, keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)

SearchUserTopUps 按订单号搜索某用户的充值记录

func (*TopUp) Insert

func (topUp *TopUp) Insert() error

func (*TopUp) Update

func (topUp *TopUp) Update() error

type TwoFA

type TwoFA struct {
	Id             int            `json:"id" gorm:"primaryKey"`
	UserId         int            `json:"user_id" gorm:"unique;not null;index"`
	Secret         string         `json:"-" gorm:"type:varchar(255);not null"` // TOTP密钥,不返回给前端
	IsEnabled      bool           `json:"is_enabled"`
	FailedAttempts int            `json:"failed_attempts" gorm:"default:0"`
	LockedUntil    *time.Time     `json:"locked_until,omitempty"`
	LastUsedAt     *time.Time     `json:"last_used_at,omitempty"`
	CreatedAt      time.Time      `json:"created_at"`
	UpdatedAt      time.Time      `json:"updated_at"`
	DeletedAt      gorm.DeletedAt `json:"-" gorm:"index"`
}

TwoFA 用户2FA设置表

func GetTwoFAByUserId

func GetTwoFAByUserId(userId int) (*TwoFA, error)

GetTwoFAByUserId 根据用户ID获取2FA设置

func (*TwoFA) Create

func (t *TwoFA) Create() error

CreateTwoFA 创建2FA设置

func (*TwoFA) Delete

func (t *TwoFA) Delete() error

Delete 删除2FA设置

func (*TwoFA) Enable

func (t *TwoFA) Enable() error

EnableTwoFA 启用2FA

func (*TwoFA) IncrementFailedAttempts

func (t *TwoFA) IncrementFailedAttempts() error

IncrementFailedAttempts 增加失败尝试次数

func (*TwoFA) IsLocked

func (t *TwoFA) IsLocked() bool

IsLocked 检查账户是否被锁定

func (*TwoFA) ResetFailedAttempts

func (t *TwoFA) ResetFailedAttempts() error

ResetFailedAttempts 重置失败尝试次数

func (*TwoFA) Update

func (t *TwoFA) Update() error

Update 更新2FA设置

func (*TwoFA) ValidateBackupCodeAndUpdateUsage

func (t *TwoFA) ValidateBackupCodeAndUpdateUsage(code string) (bool, error)

ValidateBackupCodeAndUpdateUsage 验证备用码并更新使用记录

func (*TwoFA) ValidateTOTPAndUpdateUsage

func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error)

ValidateTOTPAndUpdateUsage 验证TOTP并更新使用记录

type TwoFABackupCode

type TwoFABackupCode struct {
	Id        int            `json:"id" gorm:"primaryKey"`
	UserId    int            `json:"user_id" gorm:"not null;index"`
	CodeHash  string         `json:"-" gorm:"type:varchar(255);not null"` // 备用码哈希
	IsUsed    bool           `json:"is_used"`
	UsedAt    *time.Time     `json:"used_at,omitempty"`
	CreatedAt time.Time      `json:"created_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

TwoFABackupCode 备用码使用记录表

type User

type User struct {
	Id               int            `json:"id"`
	Username         string         `json:"username" gorm:"unique;index" validate:"max=20"`
	Password         string         `json:"password" gorm:"not null;" validate:"min=8,max=20"`
	OriginalPassword string         `json:"original_password" gorm:"-:all"` // this field is only for Password change verification, don't save it to database!
	DisplayName      string         `json:"display_name" gorm:"index" validate:"max=20"`
	Role             int            `json:"role" gorm:"type:int;default:1"`   // admin, common
	Status           int            `json:"status" gorm:"type:int;default:1"` // enabled, disabled
	Email            string         `json:"email" gorm:"index" validate:"max=50"`
	GitHubId         string         `json:"github_id" gorm:"column:github_id;index"`
	DiscordId        string         `json:"discord_id" gorm:"column:discord_id;index"`
	OidcId           string         `json:"oidc_id" gorm:"column:oidc_id;index"`
	WeChatId         string         `json:"wechat_id" gorm:"column:wechat_id;index"`
	TelegramId       string         `json:"telegram_id" gorm:"column:telegram_id;index"`
	VerificationCode string         `json:"verification_code" gorm:"-:all"`                                    // this field is only for Email verification, don't save it to database!
	AccessToken      *string        `json:"access_token" gorm:"type:char(32);column:access_token;uniqueIndex"` // this token is for system management
	Quota            int            `json:"quota" gorm:"type:int;default:0"`
	UsedQuota        int            `json:"used_quota" gorm:"type:int;default:0;column:used_quota"` // used quota
	RequestCount     int            `json:"request_count" gorm:"type:int;default:0;"`               // request number
	Group            string         `json:"group" gorm:"type:varchar(64);default:'default'"`
	AffCode          string         `json:"aff_code" gorm:"type:varchar(32);column:aff_code;uniqueIndex"`
	AffCount         int            `json:"aff_count" gorm:"type:int;default:0;column:aff_count"`
	AffQuota         int            `json:"aff_quota" gorm:"type:int;default:0;column:aff_quota"`           // 邀请剩余额度
	AffHistoryQuota  int            `json:"aff_history_quota" gorm:"type:int;default:0;column:aff_history"` // 邀请历史额度
	InviterId        int            `json:"inviter_id" gorm:"type:int;column:inviter_id;index"`
	DeletedAt        gorm.DeletedAt `gorm:"index"`
	LinuxDOId        string         `json:"linux_do_id" gorm:"column:linux_do_id;index"`
	Setting          string         `json:"setting" gorm:"type:text;column:setting"`
	Remark           string         `json:"remark,omitempty" gorm:"type:varchar(255)" validate:"max=255"`
	StripeCustomer   string         `json:"stripe_customer" gorm:"type:varchar(64);column:stripe_customer;index"`
	AvatarUrl        string         `json:"avatar_url" gorm:"type:varchar(255);column:avatar_url"`
	Bio              string         `json:"bio" gorm:"type:varchar(255);column:bio"`
	ActiveTitleId    int            `json:"active_title_id" gorm:"default:0"`
}

User if you add sensitive fields, don't forget to clean them in setupLogin function. Otherwise, the sensitive information will be saved on local storage in plain text!

func GetAllUsers

func GetAllUsers(pageInfo *common.PageInfo) (users []*User, total int64, err error)

func GetRootUser

func GetRootUser() (user *User)

func GetUserById

func GetUserById(id int, selectAll bool) (*User, error)

func GetUserByOAuthBinding

func GetUserByOAuthBinding(providerId int, providerUserId string) (*User, error)

GetUserByOAuthBinding finds a user by provider ID and provider user ID

func SearchUsers

func SearchUsers(keyword string, group string, startIdx int, num int) ([]*User, int64, error)

func ValidateAccessToken

func ValidateAccessToken(token string) (user *User)

func (*User) ClearBinding

func (user *User) ClearBinding(bindingType string) error

func (*User) Delete

func (user *User) Delete() error

func (*User) Edit

func (user *User) Edit(updatePassword bool) error

func (*User) FillUserByDiscordId

func (user *User) FillUserByDiscordId() error

func (*User) FillUserByEmail

func (user *User) FillUserByEmail() error

func (*User) FillUserByGitHubId

func (user *User) FillUserByGitHubId() error

func (*User) FillUserById

func (user *User) FillUserById() error

func (*User) FillUserByLinuxDOId

func (user *User) FillUserByLinuxDOId() error

func (*User) FillUserByOidcId

func (user *User) FillUserByOidcId() error

func (*User) FillUserByTelegramId

func (user *User) FillUserByTelegramId() error

func (*User) FillUserByWeChatId

func (user *User) FillUserByWeChatId() error

func (*User) FinalizeOAuthUserCreation

func (user *User) FinalizeOAuthUserCreation(inviterId int)

FinalizeOAuthUserCreation performs post-transaction tasks for OAuth user creation. This should be called after the transaction commits successfully.

func (*User) GetAccessToken

func (user *User) GetAccessToken() string

func (*User) GetSetting

func (user *User) GetSetting() dto.UserSetting

func (*User) HardDelete

func (user *User) HardDelete() error

func (*User) Insert

func (user *User) Insert(inviterId int) error

func (*User) InsertWithTx

func (user *User) InsertWithTx(tx *gorm.DB, inviterId int) error

InsertWithTx inserts a new user within an existing transaction. This is used for OAuth registration where user creation and binding need to be atomic. Post-creation tasks (sidebar config, logs, inviter rewards) are handled after the transaction commits.

func (*User) SetAccessToken

func (user *User) SetAccessToken(token string)

func (*User) SetSetting

func (user *User) SetSetting(setting dto.UserSetting)

func (*User) ToBaseUser

func (user *User) ToBaseUser() *UserBase

func (*User) TransferAffQuotaToQuota

func (user *User) TransferAffQuotaToQuota(quota int) error

func (*User) Update

func (user *User) Update(updatePassword bool) error

func (*User) UpdateGitHubId

func (user *User) UpdateGitHubId(newGitHubId string) error

UpdateGitHubId updates the user's GitHub ID (used for migration from login to numeric ID)

func (*User) ValidateAndFill

func (user *User) ValidateAndFill() (err error)

ValidateAndFill check password & user status

type UserBase

type UserBase struct {
	Id       int    `json:"id"`
	Group    string `json:"group"`
	Email    string `json:"email"`
	Quota    int    `json:"quota"`
	Status   int    `json:"status"`
	Username string `json:"username"`
	Setting  string `json:"setting"`
}

UserBase struct remains the same as it represents the cached data structure

func GetUserCache

func GetUserCache(userId int) (userCache *UserBase, err error)

GetUserCache gets complete user cache from hash

func (*UserBase) GetSetting

func (user *UserBase) GetSetting() dto.UserSetting

func (*UserBase) WriteContext

func (user *UserBase) WriteContext(c *gin.Context)

type UserOAuthBinding

type UserOAuthBinding struct {
	Id             int       `json:"id" gorm:"primaryKey"`
	UserId         int       `json:"user_id" gorm:"not null;uniqueIndex:ux_user_provider"`                                    // User ID - one binding per user per provider
	ProviderId     int       `json:"provider_id" gorm:"not null;uniqueIndex:ux_user_provider;uniqueIndex:ux_provider_userid"` // Custom OAuth provider ID
	ProviderUserId string    `json:"provider_user_id" gorm:"type:varchar(256);not null;uniqueIndex:ux_provider_userid"`       // User ID from OAuth provider - one OAuth account per provider
	CreatedAt      time.Time `json:"created_at"`
}

UserOAuthBinding stores the binding relationship between users and custom OAuth providers

func GetUserOAuthBinding

func GetUserOAuthBinding(userId, providerId int) (*UserOAuthBinding, error)

GetUserOAuthBinding returns a specific binding for a user and provider

func GetUserOAuthBindingsByUserId

func GetUserOAuthBindingsByUserId(userId int) ([]*UserOAuthBinding, error)

GetUserOAuthBindingsByUserId returns all OAuth bindings for a user

func (UserOAuthBinding) TableName

func (UserOAuthBinding) TableName() string

type UserPet

type UserPet struct {
	Id           int        `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId       int        `json:"user_id" gorm:"not null;index:idx_user_pet_user"`
	SpeciesId    int        `json:"species_id" gorm:"not null;index:idx_user_pet_species"`
	Nickname     string     `json:"nickname" gorm:"type:varchar(32)"`
	Level        int        `json:"level" gorm:"default:1"`
	Exp          int        `json:"exp" gorm:"default:0"`
	Stage        int        `json:"stage" gorm:"default:0"` // 0=蛋, 1=幼生, 2=成熟
	Star         int        `json:"star" gorm:"default:0"`
	Rarity       string     `json:"rarity" gorm:"type:varchar(8);default:''"` // override species rarity after transcendence
	Stats        string     `json:"stats" gorm:"type:text"`                   // JSON: current computed stats
	Status       string     `json:"status" gorm:"type:text"`                  // JSON: {hunger:100, mood:100, cleanliness:100}
	IsPrimary    bool       `json:"is_primary" gorm:"default:false"`
	Power        int        `json:"power" gorm:"default:0"`                         // attack+defense+speed+luck
	State        string     `json:"state" gorm:"type:varchar(16);default:'normal'"` // normal, weak, dispatched, listed
	LastFedAt    *time.Time `json:"last_fed_at"`
	LastPlayedAt *time.Time `json:"last_played_at"`
	HatchedAt    *time.Time `json:"hatched_at"`
	LastXpTick   int64      `json:"last_xp_tick" gorm:"bigint;default:0"` // unix timestamp: last passive XP calculation
	CreatedAt    int64      `json:"created_at" gorm:"bigint"`
	UpdatedAt    int64      `json:"updated_at" gorm:"bigint"`
}

UserPet 用户宠物实例

func GetPetByIdGlobal

func GetPetByIdGlobal(petId int) (*UserPet, error)

GetPetByIdGlobal retrieves a pet by its ID without user ownership check (for market use)

func GetUserPetById

func GetUserPetById(userId int, petId int) (*UserPet, error)

func GetUserPets

func GetUserPets(userId int) ([]UserPet, error)

func GetUserPetsByUserId

func GetUserPetsByUserId(userId int) ([]UserPet, error)

GetUserPetsByUserId is an alias for GetUserPets for public access

func GetUserPrimaryPet

func GetUserPrimaryPet(userId int) (*UserPet, error)

GetUserPrimaryPet returns the user's primary pet, or nil if none exists

func (UserPet) TableName

func (UserPet) TableName() string

type UserPetItem

type UserPetItem struct {
	Id        int   `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId    int   `json:"user_id" gorm:"not null;uniqueIndex:idx_user_item"`
	ItemId    int   `json:"item_id" gorm:"not null;uniqueIndex:idx_user_item"`
	Quantity  int   `json:"quantity" gorm:"default:0"`
	CreatedAt int64 `json:"created_at" gorm:"bigint"`
	UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
}

UserPetItem 用户背包

func GetUserInventory

func GetUserInventory(userId int) ([]UserPetItem, error)

func GetUserItem

func GetUserItem(userId int, itemId int) (*UserPetItem, error)

func (UserPetItem) TableName

func (UserPetItem) TableName() string

type UserPityCounter

type UserPityCounter struct {
	Id         int   `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId     int   `json:"user_id" gorm:"not null;uniqueIndex:idx_user_pool"`
	PoolId     int   `json:"pool_id" gorm:"not null;uniqueIndex:idx_user_pool"`
	SrCounter  int   `json:"sr_counter" gorm:"default:0"`
	SsrCounter int   `json:"ssr_counter" gorm:"default:0"`
	UpdatedAt  int64 `json:"updated_at" gorm:"bigint"`
}

UserPityCounter 用户保底计数器

func GetUserPityCounter

func GetUserPityCounter(userId int, poolId int) (*UserPityCounter, error)

func GetUserPityCounterInTx

func GetUserPityCounterInTx(tx *gorm.DB, userId int, poolId int) (*UserPityCounter, error)

func (UserPityCounter) TableName

func (UserPityCounter) TableName() string

type UserSubscription

type UserSubscription struct {
	Id     int `json:"id"`
	UserId int `json:"user_id" gorm:"index;index:idx_user_sub_active,priority:1"`
	PlanId int `json:"plan_id" gorm:"index"`

	AmountTotal int64 `json:"amount_total" gorm:"type:bigint;not null;default:0"`
	AmountUsed  int64 `json:"amount_used" gorm:"type:bigint;not null;default:0"`

	StartTime int64  `json:"start_time" gorm:"bigint"`
	EndTime   int64  `json:"end_time" gorm:"bigint;index;index:idx_user_sub_active,priority:3"`
	Status    string `json:"status" gorm:"type:varchar(32);index;index:idx_user_sub_active,priority:2"` // active/expired/cancelled

	Source string `json:"source" gorm:"type:varchar(32);default:'order'"` // order/admin

	LastResetTime int64 `json:"last_reset_time" gorm:"type:bigint;default:0"`
	NextResetTime int64 `json:"next_reset_time" gorm:"type:bigint;default:0;index"`

	UpgradeGroup  string `json:"upgrade_group" gorm:"type:varchar(64);default:''"`
	PrevUserGroup string `json:"prev_user_group" gorm:"type:varchar(64);default:''"`

	CreatedAt int64 `json:"created_at" gorm:"bigint"`
	UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
}

User subscription instance

func CreateUserSubscriptionFromPlanTx

func CreateUserSubscriptionFromPlanTx(tx *gorm.DB, userId int, plan *SubscriptionPlan, source string) (*UserSubscription, error)

func (*UserSubscription) BeforeCreate

func (s *UserSubscription) BeforeCreate(tx *gorm.DB) error

func (*UserSubscription) BeforeUpdate

func (s *UserSubscription) BeforeUpdate(tx *gorm.DB) error

type UserTitle added in v0.1.7

type UserTitle struct {
	Id       int   `json:"id" gorm:"primaryKey;autoIncrement"`
	UserId   int   `json:"user_id" gorm:"not null;uniqueIndex:idx_user_title"`
	TitleId  int   `json:"title_id" gorm:"not null;uniqueIndex:idx_user_title"`
	Equipped bool  `json:"equipped" gorm:"default:false"`
	EarnedAt int64 `json:"earned_at" gorm:"bigint"`
}

UserTitle 用户已获得称号

func (UserTitle) TableName added in v0.1.7

func (UserTitle) TableName() string

type Vendor

type Vendor struct {
	Id          int            `json:"id"`
	Name        string         `json:"name" gorm:"size:128;not null;uniqueIndex:uk_vendor_name_delete_at,priority:1"`
	Description string         `json:"description,omitempty" gorm:"type:text"`
	Icon        string         `json:"icon,omitempty" gorm:"type:varchar(128)"`
	Status      int            `json:"status" gorm:"default:1"`
	CreatedTime int64          `json:"created_time" gorm:"bigint"`
	UpdatedTime int64          `json:"updated_time" gorm:"bigint"`
	DeletedAt   gorm.DeletedAt `json:"-" gorm:"index;uniqueIndex:uk_vendor_name_delete_at,priority:2"`
}

func GetAllVendors

func GetAllVendors(offset int, limit int) ([]*Vendor, error)

GetAllVendors 获取全部供应商(分页)

func GetVendorByID

func GetVendorByID(id int) (*Vendor, error)

GetVendorByID 根据 ID 获取供应商

func SearchVendors

func SearchVendors(keyword string, offset int, limit int) ([]*Vendor, int64, error)

SearchVendors 按关键字搜索供应商

func (*Vendor) Delete

func (v *Vendor) Delete() error

Delete 软删除供应商

func (*Vendor) Insert

func (v *Vendor) Insert() error

Insert 创建新的供应商记录

func (*Vendor) Update

func (v *Vendor) Update() error

Update 更新供应商记录

Jump to

Keyboard shortcuts

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