Documentation
¶
Index ¶
- Constants
- Variables
- func AdminBindSubscription(userId int, planId int, sourceNote string) (string, error)
- func AdminDeleteUserSubscription(userSubscriptionId int) (string, error)
- func AdminInvalidateUserSubscription(userSubscriptionId int) (string, error)
- func ApplyChannelGroupFilter(query *gorm.DB, group string) *gorm.DB
- func BatchDeleteChannels(ids []int) (int64, error)
- func BatchDeleteTokens(ids []int, userId int) (int, error)
- func BatchInsertChannels(channels []Channel) error
- func BatchSetChannelTag(ids []int, tag *string) error
- func BindEmailToUser(user *User, email string) error
- func BumpUserAuthVersion(userId int) (int64, error)
- func CacheUpdateChannel(channel *Channel)
- func CacheUpdateChannelStatus(id int, status int)
- func CheckSetup()
- func CheckUserExistOrDeleted(username string, email string) (bool, error)
- func ClaimExternalAuthAssertion(purpose, assertion string, expiresAt time.Time) error
- func ClaimExternalAuthAssertionWithTx(tx *gorm.DB, purpose, assertion string, expiresAt time.Time) error
- func ClaimExternalIdentityWithTx(tx *gorm.DB, provider, subject string, userId int) error
- func CleanupChannelPollingLocks()
- func CleanupSubscriptionPreConsumeRecords(olderThanSeconds int64) (int64, error)
- func CloseDB() error
- func CompleteSubscriptionOrder(tradeNo string, providerPayload string, expectedPaymentProvider string, ...) error
- func CountActiveUserSessions(userID int, now int64) (int64, error)
- func CountAllChannels() (int64, error)
- func CountAllTags() (int64, error)
- func CountAllTasks(queryParams TaskQueryParams) int64
- func CountAllUserTask(userId int, queryParams TaskQueryParams) int64
- func CountChannelTags(query *gorm.DB) (int64, error)
- func CountChannelsByType(channelType int) (int64, error)
- func CountChannelsGroupByType() (map[int64]int64, error)
- func CountOldLog(ctx context.Context, targetTimestamp int64) (int64, error)
- func CountUserSessionsCreatedSince(userID int, createdAfter int64) (int64, error)
- func CountUserSubscriptionsByPlan(userId int, planId int) (int64, error)
- func CountUserTokens(userId int) (int64, error)
- func CountUsersByEmail(email string) (int64, error)
- func CreateCustomOAuthProvider(provider *CustomOAuthProvider) error
- func CreatePendingTwoFASetupBackupCodes(userId int, codes []string) error
- func CreateUserOAuthBinding(binding *UserOAuthBinding) error
- func CreateUserOAuthBindingWithTx(tx *gorm.DB, binding *UserOAuthBinding) error
- func CreateUserSession(session *UserSession) error
- func DecreaseTokenQuota(id int, key string, quota int) (err error)
- func DecreaseUserQuota(id int, quota int, db bool) (err error)
- func DeleteChannelByStatus(status int64) (int64, error)
- func DeleteCustomOAuthProvider(id int) error
- func DeleteDisabledChannel() (int64, error)
- func DeleteExpiredAuthFlows(now time.Time) error
- func DeleteExpiredUserSessions(now int64) error
- func DeleteInvalidRedemptions() (int64, error)
- func DeleteOldLogBatch(ctx context.Context, targetTimestamp int64, limit int) (int64, error)
- func DeleteOldRevokedUserSessions(now int64) error
- func DeletePasskeyByUserIDWithAuthVersion(userID int) error
- func DeletePerfMetricsBefore(cutoffTs int64) error
- func DeletePrefillGroupByID(id int) error
- func DeleteRedemptionById(id int) (err error)
- func DeleteStaleSystemInstance(nodeName string, now int64) (bool, error)
- func DeleteStaleSystemInstances(now int64) (int64, error)
- func DeleteTokenById(id int, userId int) (err error)
- func DeleteUserById(id int) (err error)
- func DeleteUserOAuthBinding(userId, providerId int) error
- func DeltaUpdateUserQuota(id int, delta int) (err error)
- func DisableChannelByTag(tag string) error
- func DisableModelLimits(tokenId int) error
- func DisableTwoFAWithAuthVersion(userId int) error
- func EditChannelByTag(tag string, newTag *string, modelMapping *string, models *string, ...) error
- func EnableChannelByTag(tag string) error
- func EnsureEmailAvailable(email string, excludeUserID int) error
- func ExpireDueSubscriptions(limit int) (int, error)
- func ExpireStaleSystemTaskLocks(now int64) error
- func ExpireSubscriptionOrder(tradeNo string, expectedPaymentProvider string) error
- func FindEarliestPendingSystemTasks(taskTypes []string) (map[string]*SystemTask, error)
- func FinishSystemTask(taskID string, lockedBy string, status SystemTaskStatus, resultPayload any, ...) error
- func FixAbility() (int, int, error)
- func GenerateSystemTaskID() (string, error)
- func GenerateTaskID() string
- func GetBindingCountByProviderId(providerId int) (int64, error)
- func GetBoundChannelsByModelsMap(modelNames []string) (map[string][]BoundChannel, error)
- func GetChannelPollingLock(channelId int) *sync.Mutex
- func GetDBTimestamp() int64
- func GetEnabledModels() []string
- func GetGroupEnabledModels(group string) []string
- func GetLatestSystemTasks(taskTypes []string) (map[string]*SystemTask, error)
- func GetMaxUserId() int
- func GetMissingModels() ([]string, error)
- func GetModelEnableGroups(modelName string) []string
- func GetModelQuotaTypes(modelName string) []int
- func GetModelSupportEndpointTypes(model string) []constant.EndpointType
- func GetPaginatedChannelTags(query *gorm.DB, offset int, limit int) ([]*string, error)
- func GetPaginatedTags(offset int, limit int) ([]*string, error)
- func GetPreferredModelOwnerChannelTypes(modelNames []string, groups []string) (map[string]int, error)
- func GetSupportedEndpointMap() map[string]common.EndpointInfo
- func GetTwoFAStats() (map[string]interface{}, error)
- func GetUnusedBackupCodeCount(userId int) (int, error)
- func GetUserCheckinStats(userId int, month string) (map[string]interface{}, error)
- func GetUserEmail(id int) (email string, err error)
- func GetUserGroup(id int, fromDB bool) (group string, err error)
- func GetUserIdByAffCode(affCode string) (int, error)
- func GetUserLanguage(userId int) string
- func GetUserQuota(id int, fromDB bool) (quota int, err error)
- func GetUserSetting(id int, fromDB bool) (settingMap dto.UserSetting, err error)
- func GetUserUsedQuota(id int) (quota int, err error)
- func GetUsernameById(id int, fromDB bool) (username string, err error)
- func GetVendorModelCounts() (map[int64]int64, error)
- func HardDeleteUserById(id int) error
- func HasActiveUserSubscription(userId int) (bool, error)
- func HasCheckedInToday(userId int) (bool, error)
- func HasUnfinishedMidjourneyTasks() bool
- func HasUnfinishedSyncTasks() bool
- func IncreaseTokenQuota(tokenId int, key string, quota int) (err error)
- func IncreaseUserQuota(id int, quota int, db bool) (err error)
- func IncrementUserAuthVersionWithTx(tx *gorm.DB, userId int) (int64, error)
- func InitBatchUpdater()
- func InitChannelCache()
- func InitDB() (err error)
- func InitLogDB() (err error)
- func InitOptionMap()
- func InitializeExternalIdentityClaims() error
- func InitializeUserAuthVersions() error
- func InvalidatePricingCache()
- func InvalidateSubscriptionPlanCache(planId int)
- func InvalidateUserTokensCache(userId int) error
- func IsAdmin(userId int) bool
- func IsChannelEnabledForAnyGroupModel(groups []string, modelName string, channelID int) bool
- func IsChannelEnabledForGroupModel(group string, modelName string, channelID int) bool
- func IsDiscordIdAlreadyTaken(discordId string) bool
- func IsEmailAlreadyTaken(email string) bool
- func IsEmailAvailable(email string, excludeUserID int) (bool, error)
- func IsGitHubIdAlreadyTaken(githubId string) bool
- func IsLinuxDOIdAlreadyTaken(linuxDOId string) bool
- func IsModelNameDuplicated(id int, name string) (bool, error)
- func IsOidcIdAlreadyTaken(oidcId string) bool
- func IsPrefillGroupNameDuplicated(id int, name string) (bool, error)
- func IsProviderUserIdTaken(providerId int, providerUserId string) bool
- func IsSlugTaken(slug string, excludeId int) bool
- func IsTelegramIdAlreadyTaken(telegramId string) bool
- func IsTwoFAEnabled(userId int) (bool, error)
- func IsVendorNameDuplicated(id int, name string) (bool, error)
- func IsWeChatIdAlreadyTaken(wechatId string) bool
- func LogQuotaData(params QuotaDataLogParams)
- func ManualCompleteTopUp(tradeNo string, callerIp string) error
- func MarkSystemTaskLeaseExpired(taskID string) error
- func MaskTokenKey(key string) string
- func MigrateRetiredFrontendOptions() error
- func MjBulkUpdate(mjIds []string, params map[string]any) error
- func MjBulkUpdateByTaskIds(taskIDs []int, params map[string]any) error
- func NormalizeChannelGroupFilter(group string) string
- func NormalizeEmail(email string) string
- func NormalizeResetPeriod(period string) string
- func PerfMetricStartTime(hours int) int64
- func PingDB() error
- func PostConsumeUserSubscriptionDelta(userSubscriptionId int, delta int64) error
- func PublishUserAuthCache(userId int) error
- func PurchaseSubscriptionWithBalance(userId int, planId int) error
- func Recharge(referenceId string, customerId string, callerIp string) (err error)
- func RechargeCreem(referenceId string, customerEmail string, customerName string, callerIp string) (err error)
- func RechargeEpay(tradeNo string, actualPaymentMethod string, callerIp string) (alreadyDone bool, err error)
- func RechargeWaffo(tradeNo string, callerIp string) (err error)
- func RechargeWaffoPancake(tradeNo string) (err error)
- func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)
- func RecordErrorLog(c *gin.Context, userId int, channelId int, modelName string, tokenName string, ...)
- func RecordExist(err error) (bool, error)
- func RecordLog(userId int, logType int, content string)
- func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo map[string]interface{})
- func RecordLoginLog(userId int, username string, content string, ip string, action string, ...)
- func RecordOperationAuditLog(logUserId int, content string, ip string, action string, ...)
- func RecordTaskBillingLog(params RecordTaskBillingLogParams)
- func RecordTopupLog(userId int, content string, callerIp string, paymentMethod string, ...)
- func Redeem(key string, userId int) (quota int, err error)
- func RefreshPricing()
- func RefreshUserGroupCache(userId int) error
- func RefundSubscriptionPreConsume(requestId string) error
- func ReleaseExternalIdentityWithTx(tx *gorm.DB, provider string, userId int) error
- func ReleaseSystemTaskLock(taskID string, lockedBy string) error
- func RenewSystemTaskLock(taskID string, lockedBy string, lockUntil int64) error
- func ReplaceBackupCodesWithAuthVersion(userId int, codes []string) error
- func ResetDueSubscriptions(limit int) (int, error)
- func ResetUserPasswordByEmail(email string, password string) error
- func RevokeAllUserSessions(userID int, reason string) (int64, error)
- func RevokeOtherUserSessions(userID int, currentSID, reason string) (int64, error)
- func RevokeUserSession(userID int, sid, reason string) (bool, error)
- func RevokeUserSessionByRefreshHash(sid, presentedHash, reason string) (bool, error)
- func RootUserExists() bool
- func SaveQuotaDataCache()
- func SearchTags(keyword string, group string, model string, idSort bool) ([]*string, error)
- func SetUserAuthVersionFence(userId int, authVersion int64) error
- func SumUsedToken(logType int, startTimestamp int64, endTimestamp int64, modelName string, ...) (token int)
- func SyncChannelCache(frequency int)
- func SyncOptions(frequency int)
- func TaskBulkUpdateByID(ids []int64, params map[string]any) error
- func TaskCountAllTasks(queryParams SyncTaskQueryParams) int64
- func TaskCountAllUserTask(userId int, queryParams SyncTaskQueryParams) int64
- func TryReserveTokenQuota(id int, key string, quota int, unlimited bool) (bool, error)
- func TryReserveUserQuota(id int, quota int) (bool, error)
- func UpdateAbilityByTag(tag string, newTag *string, priority *int64, weight *uint) error
- func UpdateAbilityStatus(channelId int, status bool) error
- func UpdateAbilityStatusByTag(tag string, status bool) error
- func UpdateChannelStatus(channelId int, usingKey string, status int, reason string) bool
- func UpdateChannelUsedQuota(id int, quota int)
- func UpdateCustomOAuthProvider(provider *CustomOAuthProvider) error
- func UpdateOption(key string, value string) error
- func UpdateOptionsBulk(values map[string]string) error
- func UpdatePasskeyAssertionState(userID int, credential *webauthn.Credential, lastUsedAt time.Time) error
- func UpdatePendingTopUpStatus(tradeNo string, expectedPaymentProvider string, targetStatus string) error
- func UpdateProgress(id int, progress string) error
- func UpdateQuotaData()
- func UpdateSystemTaskState(taskID string, lockedBy string, state any) error
- func UpdateUserAccessToken(id int, token string) error
- func UpdateUserBindColumn(userId int, column string, value string) error
- func UpdateUserLastLoginAt(id int)
- func UpdateUserOAuthBinding(userId, providerId int, newProviderUserId string) error
- func UpdateUserSetting(userId int, setting dto.UserSetting) error
- func UpdateUserUsedQuota(id int, quota int)
- func UpdateUserUsedQuotaAndRequestCount(id int, quota int)
- func UpsertPasskeyCredentialWithAuthVersion(credential *PasskeyCredential) error
- func UpsertPerfMetric(metric *PerfMetric) error
- func UpsertSystemInstance(nodeName string, info any, startedAt int64, lastSeenAt int64) error
- func UserActiveSubscriptionsAllowWalletOverflow(userId int) (bool, error)
- func ValidateBackupCode(userId int, code string) (bool, error)
- func ValidateTopUpQuotaCapacity(userId int, creditedQuota int) error
- type Ability
- type AbilityWithChannel
- type AuthFlow
- func ConsumeAuthFlow(token string, match AuthFlowMatch) (*AuthFlow, error)
- func ConsumeAuthFlowWithAction(token string, match AuthFlowMatch, ...) (*AuthFlow, error)
- func CreateAuthFlow(input AuthFlowCreate) (string, *AuthFlow, error)
- func GetAuthFlow(token string, match AuthFlowMatch) (*AuthFlow, error)
- type AuthFlowCreate
- type AuthFlowMatch
- type AuthzRole
- type BoundChannel
- type CasbinRule
- type Channel
- func CacheGetChannel(id int) (*Channel, error)
- func GetAllChannels(startIdx int, num int, selectAll bool, idSort bool, ...) ([]*Channel, error)
- func GetChannel(group string, model string, retry int, requestPath string) (*Channel, error)
- func GetChannelById(id int, selectAll bool) (*Channel, error)
- func GetChannelsByIds(ids []int) ([]*Channel, error)
- func GetChannelsByTag(tag string, idSort bool, selectAll bool, sortOptions ...ChannelSortOptions) ([]*Channel, error)
- func GetChannelsByType(startIdx int, num int, idSort bool, channelType int) ([]*Channel, error)
- func GetRandomSatisfiedChannel(group string, model string, retry int, requestPath string) (*Channel, error)
- func SearchChannels(keyword string, group string, model string, idSort bool, ...) ([]*Channel, error)
- func (channel *Channel) AddAbilities(tx *gorm.DB) error
- func (channel *Channel) Delete() error
- func (channel *Channel) DeleteAbilities() error
- func (channel *Channel) GetAutoBan() bool
- func (channel *Channel) GetBaseURL() string
- func (channel *Channel) GetGroups() []string
- func (channel *Channel) GetHeaderOverride() map[string]interface{}
- func (channel *Channel) GetKeys() []string
- func (channel *Channel) GetModelMapping() string
- func (channel *Channel) GetModels() []string
- func (channel *Channel) GetNextEnabledKey() (string, int, *types.NewAPIError)
- func (channel *Channel) GetOtherInfo() map[string]interface{}
- func (channel *Channel) GetOtherSettings() dto.ChannelOtherSettings
- func (channel *Channel) GetParamOverride() map[string]interface{}
- func (channel *Channel) GetPriority() int64
- func (channel *Channel) GetSetting() dto.ChannelSettings
- func (channel *Channel) GetStatusCodeMapping() string
- func (channel *Channel) GetTag() string
- func (channel *Channel) GetWeight() int
- func (channel *Channel) Insert() error
- func (channel *Channel) Save() error
- func (channel *Channel) SaveChannelInfo() error
- func (channel *Channel) SetOtherInfo(otherInfo map[string]interface{})
- func (channel *Channel) SetOtherSettings(setting dto.ChannelOtherSettings)
- func (channel *Channel) SetSetting(setting dto.ChannelSettings)
- func (channel *Channel) SetTag(tag string)
- func (channel *Channel) Update() error
- func (channel *Channel) UpdateAbilities(tx *gorm.DB) error
- func (channel *Channel) UpdateBalance(balance float64)
- func (channel *Channel) UpdateResponseTime(responseTime int64)
- func (channel *Channel) ValidateSettings() error
- type ChannelInfo
- type ChannelSortOptions
- type Checkin
- type CheckinRecord
- type CustomOAuthProvider
- type ExternalIdentityClaim
- type FlowQuotaData
- type JSONValue
- type Log
- func GetAllLogs(logType int, startTimestamp int64, endTimestamp int64, modelName string, ...) (logs []*Log, total int64, err error)
- func GetLogByTokenId(tokenId int) (logs []*Log, err error)
- func GetUserLogs(userId int, logType int, startTimestamp int64, endTimestamp int64, ...) (logs []*Log, total int64, err error)
- type Midjourney
- func GetAllTasks(startIdx int, num int, queryParams TaskQueryParams) []*Midjourney
- func GetAllUnFinishTasks() []*Midjourney
- func GetAllUserTask(userId int, startIdx int, num int, queryParams TaskQueryParams) []*Midjourney
- func GetByMJId(userId int, mjId string) *Midjourney
- func GetByMJIds(userId int, mjIds []string) []*Midjourney
- func GetByOnlyMJId(mjId string) *Midjourney
- func GetMjByuId(id int) *Midjourney
- type Model
- type Option
- type PasskeyCredential
- type PerfMetric
- type PerfMetricSummary
- type PerfMetricSummaryBucket
- type PrefillGroup
- type Pricing
- type PricingVendor
- type Properties
- type QuotaData
- func GetAllQuotaDates(startTime int64, endTime int64, username string) (quotaData []*QuotaData, err error)
- func GetQuotaDataByUserId(userId int, startTime int64, endTime int64) (quotaData []*QuotaData, err error)
- func GetQuotaDataByUsername(username string, startTime int64, endTime int64) (quotaData []*QuotaData, err error)
- func GetQuotaDataGroupByUser(startTime int64, endTime int64) (quotaData []*QuotaData, err error)
- type QuotaDataLogParams
- type RankingQuotaBucket
- type RankingQuotaTotal
- type RecordConsumeLogParams
- type RecordTaskBillingLogParams
- type Redemption
- type Setup
- type Stat
- type SubscriptionOrder
- type SubscriptionPlan
- type SubscriptionPlanInfo
- type SubscriptionPreConsumeRecord
- type SubscriptionPreConsumeResult
- type SubscriptionResetResult
- type SubscriptionSummary
- type SyncTaskQueryParams
- type SystemInstance
- type SystemInstanceResponse
- type SystemTask
- func ClaimSystemTask(id int64, taskType string, runnerID string, lockUntil int64) (*SystemTask, bool, error)
- func CreateSystemTask(taskType string, payload any, state any) (*SystemTask, error)
- func FindPendingSystemTasks(taskType string, limit int) ([]*SystemTask, error)
- func GetActiveSystemTask(taskType string) (*SystemTask, error)
- func GetLatestSystemTask(taskType string) (*SystemTask, error)
- func GetSystemTaskByTaskID(taskID string) (*SystemTask, error)
- func ListSystemTasks(limit int) ([]*SystemTask, error)
- type SystemTaskLock
- type SystemTaskResponse
- type SystemTaskStatus
- type Task
- func GetAllUnFinishSyncTasks(limit int) []*Task
- func GetByTaskId(userId int, taskId string) (*Task, bool, error)
- func GetByTaskIds(userId int, taskIds []any) ([]*Task, error)
- func GetTimedOutUnfinishedTasks(cutoffUnix int64, limit int) []*Task
- func InitTask(platform constant.TaskPlatform, relayInfo *commonRelay.RelayInfo) *Task
- func TaskGetAllTasks(startIdx int, num int, queryParams SyncTaskQueryParams) []*Task
- func TaskGetAllUserTask(userId int, startIdx int, num int, queryParams SyncTaskQueryParams) []*Task
- func (t *Task) GetData(v any) error
- func (t *Task) GetResultURL() string
- func (t *Task) GetUpstreamTaskID() string
- func (Task *Task) Insert() error
- func (t *Task) SetData(data any)
- func (t *Task) Snapshot() taskSnapshot
- func (t *Task) ToOpenAIVideo() *dto.OpenAIVideo
- func (Task *Task) Update() error
- func (t *Task) UpdateQuota() error
- func (t *Task) UpdateWithStatus(fromStatus TaskStatus) (bool, error)
- type TaskBillingContext
- type TaskPrivateData
- type TaskQueryParams
- type TaskQuotaUsage
- type TaskStatus
- type Token
- func GetAllUserTokens(userId int, startIdx int, num int) ([]*Token, error)
- func GetTokenById(id int) (*Token, error)
- func GetTokenByIds(id int, userId int) (*Token, error)
- func GetTokenByKey(key string, fromDB bool) (token *Token, err error)
- func GetTokenKeysByIds(ids []int, userId int) ([]Token, error)
- func SearchUserTokens(userId int, keyword string, token string, offset int, limit int) (tokens []*Token, total int64, err error)
- func ValidateUserToken(key string) (token *Token, err error)
- func (token *Token) Clean()
- func (token *Token) Delete() (err error)
- func (token *Token) GetAutoGroups() ([]string, error)
- func (token *Token) GetFullKey() string
- func (token *Token) GetIpLimits() []string
- func (token *Token) GetMaskedKey() string
- func (token *Token) GetModelLimits() []string
- func (token *Token) GetModelLimitsMap() map[string]bool
- func (token *Token) Insert() error
- func (token *Token) IsModelLimitsEnabled() bool
- func (token *Token) SelectUpdate() (err error)
- func (token *Token) SetAutoGroups(groups []string) error
- func (token *Token) Update() (err error)
- type TopUp
- func GetAllTopUps(pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
- func GetTopUpById(id int) *TopUp
- func GetTopUpByTradeNo(tradeNo string) *TopUp
- func GetUserTopUps(userId int, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
- func SearchAllTopUps(keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
- func SearchUserTopUps(userId int, keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
- type TwoFA
- func (t *TwoFA) CreatePendingTwoFASetup() error
- func (t *TwoFA) DeletePendingTwoFASetup() error
- func (t *TwoFA) EnableWithAuthVersion() error
- func (t *TwoFA) IncrementFailedAttempts() error
- func (t *TwoFA) IsLocked() bool
- func (t *TwoFA) ResetFailedAttempts() error
- func (t *TwoFA) ValidateBackupCodeAndUpdateUsage(code string) (bool, error)
- func (t *TwoFA) ValidateTOTPAndUpdateUsage(code string) (bool, error)
- type TwoFABackupCode
- type User
- func GetAllUsers(pageInfo *common.PageInfo, sortOptions ...UserSortOptions) (users []*User, total int64, err error)
- func GetRootUser() (user *User)
- func GetUniqueUserByEmail(email string) (*User, error)
- func GetUserById(id int, selectAll bool) (*User, error)
- func GetUserByOAuthBinding(providerId int, providerUserId string) (*User, error)
- func SearchUsers(keyword string, group string, role *int, status *int, startIdx int, num int, ...) ([]*User, int64, error)
- func ValidateAccessToken(token string) (*User, error)
- func (user *User) ClearBinding(bindingType string) error
- func (user *User) Delete() error
- func (user *User) Edit(updatePassword bool) error
- func (user *User) EditWithTx(tx *gorm.DB, updatePassword bool) error
- func (user *User) FillUserByDiscordId() error
- func (user *User) FillUserByEmail() error
- func (user *User) FillUserByGitHubId() error
- func (user *User) FillUserById() error
- func (user *User) FillUserByLinuxDOId() error
- func (user *User) FillUserByOidcId() error
- func (user *User) FillUserByTelegramId() error
- func (user *User) FillUserByWeChatId() error
- func (user *User) FinalizeOAuthUserCreation(inviterId int)
- func (user *User) FinishInsert(inviterId int)
- func (user *User) GetAccessToken() string
- func (user *User) GetSetting() dto.UserSetting
- func (user *User) HardDelete() error
- func (user *User) Insert(inviterId int) error
- func (user *User) InsertWithTx(tx *gorm.DB, inviterId int) error
- func (user *User) SetAccessToken(token string)
- func (user *User) SetSetting(setting dto.UserSetting)
- func (user *User) ToBaseUser() *UserBase
- func (user *User) TransferAffQuotaToQuota(quota int) error
- func (user *User) Update(updatePassword bool) error
- func (user *User) UpdateGitHubId(newGitHubId string) error
- func (user *User) UpdateWithTx(tx *gorm.DB, updatePassword bool) error
- func (user *User) ValidateAndFill() (err error)
- type UserBase
- type UserOAuthBinding
- type UserSession
- func AdvanceUserSessionAuthVersion(userID int, sid string, ...) (*UserSession, error)
- func GetUserSessionBySID(sid string) (*UserSession, error)
- func GetUserSessionCached(sid string) (*UserSession, error)
- func ListActiveUserSessions(userID int, currentSID string, now int64) ([]UserSession, error)
- func RotateUserSessionRefresh(userID int, sid, presentedHash, nextHash string, now int64, ...) (*UserSession, error)
- type UserSortOptions
- type UserSubscription
- type Vendor
Constants ¶
const ( AuthFlowPurposeOAuth = "oauth" AuthFlowPurposeTwoFALogin = "2fa_login" AuthFlowPurposePasskeyLogin = "passkey_login" AuthFlowPurposePasskeyRegister = "passkey_register" AuthFlowPurposePasskeyStepUp = "passkey_step_up" AuthFlowPurposeTelegramBind = "telegram_bind" AuthFlowPurposeTelegramAssertion = "telegram_assertion" AuthFlowIntentLogin = "login" AuthFlowIntentBind = "bind" AuthFlowTokenBytes = 32 AuthFlowDefaultCleanupRetention = 24 * time.Hour )
const ( LogTypeUnknown = 0 LogTypeTopup = 1 LogTypeConsume = 2 LogTypeManage = 3 LogTypeSystem = 4 LogTypeError = 5 LogTypeRefund = 6 LogTypeLogin = 7 )
don't use iota, avoid change log type value
const ( NameRuleExact = iota NameRulePrefix NameRuleContains NameRuleSuffix )
const ( SubscriptionDurationYear = "year" SubscriptionDurationMonth = "month" SubscriptionDurationDay = "day" SubscriptionDurationHour = "hour" SubscriptionDurationCustom = "custom" )
Subscription duration units
const ( SubscriptionResetNever = "never" SubscriptionResetDaily = "daily" SubscriptionResetWeekly = "weekly" SubscriptionResetMonthly = "monthly" SubscriptionResetCustom = "custom" )
Subscription quota reset period
const ( SystemInstanceStatusOnline = "online" SystemInstanceStatusStale = "stale" SystemInstanceStaleAfterSeconds int64 = 90 )
const ( SystemTaskStatusPending SystemTaskStatus = "pending" SystemTaskStatusRunning SystemTaskStatus = "running" SystemTaskStatusSucceeded SystemTaskStatus = "succeeded" SystemTaskStatusFailed SystemTaskStatus = "failed" SystemTaskTypeLogCleanup = "log_cleanup" SystemTaskTypeChannelTest = "channel_test" SystemTaskTypeModelUpdate = "model_update" SystemTaskTypeMidjourneyPoll = "midjourney_poll" SystemTaskTypeAsyncTaskPoll = "async_task_poll" )
const ( TaskStatusNotStart TaskStatus = "NOT_START" TaskStatusSubmitted = "SUBMITTED" TaskStatusQueued = "QUEUED" TaskStatusInProgress = "IN_PROGRESS" TaskStatusFailure = "FAILURE" TaskStatusSuccess = "SUCCESS" TaskStatusUnknown = "UNKNOWN" )
const ( PaymentMethodStripe = "stripe" PaymentMethodCreem = "creem" PaymentMethodWaffo = "waffo" PaymentMethodWaffoPancake = "waffo_pancake" PaymentMethodBalance = "balance" )
const ( PaymentProviderEpay = "epay" PaymentProviderStripe = "stripe" PaymentProviderCreem = "creem" PaymentProviderWaffo = "waffo" PaymentProviderWaffoPancake = "waffo_pancake" PaymentProviderBalance = "balance" )
const ( UserSessionStatusActive = "active" UserSessionStatusRevoking = "revoking" UserSessionStatusRevoked = "revoked" )
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 )
const ExternalIdentityProviderTelegram = "telegram"
const TaskRefundLegacyCutoff int64 = 1771718400 // 2026-02-22 00:00:00 UTC
TaskRefundLegacyCutoff separates tasks created before timeout refunds were introduced. Those legacy tasks are failed without an automatic refund.
const UserNameMaxLength = 20
Variables ¶
var ( ErrAuthFlowInvalid = errors.New("auth flow is invalid") ErrAuthFlowExpired = errors.New("auth flow has expired") ErrAuthFlowConsumed = errors.New("auth flow has already been consumed") )
var ( ErrInvalidCredentials = errors.New("invalid credentials") ErrUserEmptyCredentials = errors.New("empty credentials") ErrEmailAlreadyTaken = errors.New("email already taken") ErrEmailNotFound = errors.New("email not found") ErrEmailAmbiguous = errors.New("email matches multiple users") )
User auth errors
var ( ErrTokenNotProvided = errors.New("token not provided") ErrTokenInvalid = errors.New("token invalid") )
Token auth errors
var ( ErrPasskeyNotFound = errors.New("passkey credential not found") ErrFriendlyPasskeyNotFound = errors.New("Passkey 验证失败,请重试或联系管理员") )
var ( ErrSubscriptionOrderNotFound = errors.New("subscription order not found") ErrSubscriptionOrderStatusInvalid = errors.New("subscription order status invalid") )
var ( ErrPaymentMethodMismatch = errors.New("payment method mismatch") ErrTopUpNotFound = errors.New("topup not found") ErrTopUpStatusInvalid = errors.New("topup status invalid") ErrInvalidTopUpQuota = errors.New("invalid top-up quota") ErrTopUpQuotaLimitExceeded = errors.New("top-up quota limit exceeded") ErrWalletQuotaLimitExceeded = errors.New("wallet quota limit exceeded") )
var ( ErrUserSessionInvalid = errors.New("user session is invalid") ErrUserSessionInactive = errors.New("user session is inactive") ErrUserSessionRefreshInvalid = errors.New("user session refresh token is invalid") ErrUserSessionRefreshRace = errors.New("user session refresh is already in progress") ErrUserSessionRefreshReuse = errors.New("user session refresh token was reused") ErrUserSessionLimit = errors.New("active user session limit reached") ErrUserSessionIssuanceLimit = errors.New("user session issuance limit reached") )
var CacheQuotaData = make(map[string]*QuotaData)
var CacheQuotaDataLock = sync.Mutex{}
var DB *gorm.DB
var (
ErrDatabase = errors.New("database error")
)
Common errors
var ErrExternalIdentityAlreadyClaimed = errors.New("external identity is already claimed")
var ErrRedeemFailed = errors.New("redeem.failed")
Redemption errors
var ErrSystemTaskLockLost = errors.New("system task lock lost")
var ErrTwoFAAlreadyEnabled = errors.New("2fa already enabled")
var ErrTwoFANotEnabled = errors.New("2fa not enabled")
2FA errors
var ErrUserAuthCachePending = errors.New("user authentication state update is pending")
var ErrUserAuthVersionConflict = errors.New("user authentication version update conflicted")
var LOG_DB *gorm.DB
Functions ¶
func AdminBindSubscription ¶ added in v0.10.8
Admin bind (no payment). Creates a UserSubscription from a plan.
func AdminDeleteUserSubscription ¶ added in v0.10.8
AdminDeleteUserSubscription hard-deletes a user subscription.
func AdminInvalidateUserSubscription ¶ added in v0.10.8
AdminInvalidateUserSubscription marks a user subscription as cancelled and ends it immediately.
func BatchDeleteChannels ¶
func BatchDeleteTokens ¶
BatchDeleteTokens 删除指定用户的一组令牌,返回成功删除数量
func BatchInsertChannels ¶
func BatchSetChannelTag ¶
func BindEmailToUser ¶
BindEmailToUser atomically checks email availability and assigns it to the user, serializing concurrent binds of the same email so two accounts cannot end up sharing one address. The email is normalized before check and store.
func BumpUserAuthVersion ¶
BumpUserAuthVersion is the transaction-owning variant used by password, role, status and security-factor changes outside another transaction.
func CacheUpdateChannel ¶
func CacheUpdateChannel(channel *Channel)
func CheckSetup ¶
func CheckSetup()
func CheckUserExistOrDeleted ¶
CheckUserExistOrDeleted check if user exist or deleted, if not exist, return false, nil, if deleted or exist, return true, nil
func ClaimExternalAuthAssertion ¶
ClaimExternalAuthAssertion records a signed provider assertion as consumed. The assertion is HMACed before storage and the unique token_hash index makes replay rejection atomic on SQLite, MySQL and PostgreSQL.
func ClaimExternalAuthAssertionWithTx ¶
func ClaimExternalAuthAssertionWithTx(tx *gorm.DB, purpose, assertion string, expiresAt time.Time) error
ClaimExternalAuthAssertionWithTx records a provider assertion in the caller's transaction so replay protection can commit atomically with the authentication flow and its resulting state change.
func ClaimExternalIdentityWithTx ¶
ClaimExternalIdentityWithTx atomically claims a provider subject for one user. Repeating the exact mapping is idempotent; every competing subject or user is rejected. Ownership is read back instead of trusting RowsAffected, whose duplicate-key semantics differ between supported databases.
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 ¶ added in v0.10.8
CleanupSubscriptionPreConsumeRecords removes old idempotency records to keep table small.
func CompleteSubscriptionOrder ¶ added in v0.10.8
func CompleteSubscriptionOrder(tradeNo string, providerPayload string, expectedPaymentProvider string, actualPaymentMethod string) error
Complete a subscription order (idempotent). Creates a UserSubscription snapshot from the plan. expectedPaymentProvider guards against cross-gateway callback attacks (empty skips the check). actualPaymentMethod updates the order's PaymentMethod to reflect the real payment type used (empty skips update).
func CountAllChannels ¶
CountAllChannels returns total channels in DB
func CountAllTags ¶
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 ¶
Count channels of specific type
func CountChannelsGroupByType ¶
Return map[type]count for all channels
func CountUserSessionsCreatedSince ¶
CountUserSessionsCreatedSince counts every issued row, regardless of its current status or expiry. userID zero selects the global count.
func CountUserSubscriptionsByPlan ¶ added in v0.10.8
func CountUserTokens ¶
CountUserTokens returns total number of tokens for the given user, used for pagination
func CountUsersByEmail ¶
func CreateCustomOAuthProvider ¶ added in v0.10.8
func CreateCustomOAuthProvider(provider *CustomOAuthProvider) error
CreateCustomOAuthProvider creates a new custom OAuth provider
func CreatePendingTwoFASetupBackupCodes ¶
CreatePendingTwoFASetupBackupCodes stores recovery codes for an unverified setup. Regeneration for an enabled factor must advance auth_version.
func CreateUserOAuthBinding ¶ added in v0.10.8
func CreateUserOAuthBinding(binding *UserOAuthBinding) error
CreateUserOAuthBinding creates a new OAuth binding
func CreateUserOAuthBindingWithTx ¶ added in v0.10.9
func CreateUserOAuthBindingWithTx(tx *gorm.DB, binding *UserOAuthBinding) error
CreateUserOAuthBindingWithTx creates a new OAuth binding within a transaction
func CreateUserSession ¶
func CreateUserSession(session *UserSession) error
func DeleteChannelByStatus ¶
func DeleteCustomOAuthProvider ¶ added in v0.10.8
DeleteCustomOAuthProvider deletes a custom OAuth provider by ID
func DeleteDisabledChannel ¶
func DeleteExpiredAuthFlows ¶
func DeleteOldLogBatch ¶
func DeletePerfMetricsBefore ¶
func DeleteRedemptionById ¶
func DeleteTokenById ¶
func DeleteUserById ¶
func DeleteUserOAuthBinding ¶ added in v0.10.8
DeleteUserOAuthBinding deletes an OAuth binding
func DeltaUpdateUserQuota ¶
func DisableChannelByTag ¶
func DisableModelLimits ¶
func DisableTwoFAWithAuthVersion ¶
DisableTwoFAWithAuthVersion atomically removes the factor and invalidates every access token issued against the previous security configuration.
func EditChannelByTag ¶
func EnableChannelByTag ¶
func EnsureEmailAvailable ¶
func ExpireDueSubscriptions ¶ added in v0.10.8
ExpireDueSubscriptions marks expired subscriptions and handles group downgrade.
func ExpireSubscriptionOrder ¶ added in v0.10.8
func FindEarliestPendingSystemTasks ¶
func FindEarliestPendingSystemTasks(taskTypes []string) (map[string]*SystemTask, error)
func FinishSystemTask ¶
func FixAbility ¶
func GenerateSystemTaskID ¶
func GenerateTaskID ¶ added in v0.11.0
func GenerateTaskID() string
GenerateTaskID 生成对外暴露的 task_xxxx 格式 ID
func GetBindingCountByProviderId ¶ added in v0.10.8
GetBindingCountByProviderId returns the number of bindings for a provider
func GetBoundChannelsByModelsMap ¶
func GetBoundChannelsByModelsMap(modelNames []string) (map[string][]BoundChannel, error)
func GetChannelPollingLock ¶
GetChannelPollingLock returns or creates a mutex for the given channel ID
func GetDBTimestamp ¶ added in v0.10.8
func GetDBTimestamp() int64
GetDBTimestamp returns a UNIX timestamp from database time. Falls back to application time on error.
func GetEnabledModels ¶
func GetEnabledModels() []string
func GetGroupEnabledModels ¶
func GetLatestSystemTasks ¶
func GetLatestSystemTasks(taskTypes []string) (map[string]*SystemTask, error)
func GetMaxUserId ¶
func GetMaxUserId() int
func GetMissingModels ¶
GetMissingModels returns model names that are referenced in the system
func GetModelEnableGroups ¶
func GetModelQuotaTypes ¶
GetModelQuotaTypes 返回指定模型的计费类型集合(来自缓存)
func GetModelSupportEndpointTypes ¶
func GetModelSupportEndpointTypes(model string) []constant.EndpointType
func GetPaginatedChannelTags ¶
func GetSupportedEndpointMap ¶
func GetSupportedEndpointMap() map[string]common.EndpointInfo
GetSupportedEndpointMap 返回全局端点到路径的映射
func GetTwoFAStats ¶
GetTwoFAStats 获取2FA统计信息(管理员使用)
func GetUnusedBackupCodeCount ¶
GetUnusedBackupCodeCount 获取未使用的备用码数量
func GetUserCheckinStats ¶
GetUserCheckinStats 获取用户签到统计信息
func GetUserEmail ¶
func GetUserGroup ¶
GetUserGroup gets group from Redis first, falls back to DB if needed
func GetUserIdByAffCode ¶
func GetUserLanguage ¶ added in v0.10.8
GetUserLanguage returns the user's language preference from cache Uses the existing GetUserCache mechanism for efficiency
func GetUserQuota ¶
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 GetUserUsedQuota ¶
func GetUsernameById ¶
GetUsernameById gets username from Redis first, falls back to DB if needed
func GetVendorModelCounts ¶
func HardDeleteUserById ¶
func HasActiveUserSubscription ¶ added in v0.10.8
HasActiveUserSubscription returns whether the user has any active subscription. This is a lightweight existence check to avoid heavy pre-consume transactions.
func HasCheckedInToday ¶
HasCheckedInToday 检查用户今天是否已签到
func HasUnfinishedMidjourneyTasks ¶
func HasUnfinishedMidjourneyTasks() bool
HasUnfinishedMidjourneyTasks reports whether at least one Midjourney task is still in progress. It is a cheap existence check (LIMIT 1) used to decide whether the midjourney_poll system task needs to run; when no task is pending the scheduler skips creating a row entirely.
func HasUnfinishedSyncTasks ¶
func HasUnfinishedSyncTasks() bool
HasUnfinishedSyncTasks reports whether at least one async (Suno/video) task is still in progress. It is a cheap existence check (LIMIT 1) used to decide whether the async_task_poll system task needs to run; when no task is pending the scheduler skips creating a row entirely.
func IncrementUserAuthVersionWithTx ¶
IncrementUserAuthVersionWithTx locks the user, publishes the next deny fence, then persists the version in the caller's transaction. Unscoped is intentional so the same fail-closed path also covers hard deletion of an already soft-deleted user.
func InitBatchUpdater ¶
func InitBatchUpdater()
func InitChannelCache ¶
func InitChannelCache()
func InitOptionMap ¶
func InitOptionMap()
func InitializeExternalIdentityClaims ¶
func InitializeExternalIdentityClaims() error
InitializeExternalIdentityClaims imports legacy Telegram bindings after the claim table is migrated. Existing duplicate ownership fails migration rather than preserving an ambiguous login identity.
func InitializeUserAuthVersions ¶
func InitializeUserAuthVersions() error
InitializeUserAuthVersions must run after AutoMigrate when upgrading an existing database. It is idempotent and portable across all supported DBs.
func InvalidatePricingCache ¶ added in v0.13.1
func InvalidatePricingCache()
func InvalidateSubscriptionPlanCache ¶ added in v0.10.8
func InvalidateSubscriptionPlanCache(planId int)
func InvalidateUserTokensCache ¶ added in v0.12.13
InvalidateUserTokensCache 清理指定用户所有令牌在 Redis 中的缓存, 配合 InvalidateUserCache 使用,可在用户被禁用/删除时立即阻断其令牌的请求。 下一次请求将从数据库重新加载令牌及用户状态,从而立即识别出被禁用的用户。
func IsDiscordIdAlreadyTaken ¶
func IsEmailAlreadyTaken ¶
func IsGitHubIdAlreadyTaken ¶
func IsLinuxDOIdAlreadyTaken ¶
func IsOidcIdAlreadyTaken ¶
func IsPrefillGroupNameDuplicated ¶
IsPrefillGroupNameDuplicated 检查组名称是否重复(排除自身 ID)
func IsProviderUserIdTaken ¶ added in v0.10.8
IsProviderUserIdTaken checks if a provider user ID is already bound to any user
func IsSlugTaken ¶ added in v0.10.8
IsSlugTaken checks if a slug is already taken by another provider Returns true on DB errors (fail-closed) to prevent slug conflicts
func IsVendorNameDuplicated ¶
IsVendorNameDuplicated 检查供应商名称是否重复(排除自身 ID)
func IsWeChatIdAlreadyTaken ¶
func LogQuotaData ¶
func LogQuotaData(params QuotaDataLogParams)
func ManualCompleteTopUp ¶
ManualCompleteTopUp 管理员手动完成订单并给用户充值
func MaskTokenKey ¶ added in v0.11.4
func MigrateRetiredFrontendOptions ¶
func MigrateRetiredFrontendOptions() error
MigrateRetiredFrontendOptions normalizes options that belonged to the removed dashboard frontend. Each legacy console setting is migrated in its own transaction so one malformed value cannot block the other settings.
func NormalizeEmail ¶
func NormalizeResetPeriod ¶ added in v0.10.8
func PerfMetricStartTime ¶
func PostConsumeUserSubscriptionDelta ¶ added in v0.10.8
Update subscription used amount by delta (positive consume more, negative refund).
func PublishUserAuthCache ¶
PublishUserAuthCache refreshes the current database state after a successful auth-sensitive transaction without touching the cached quota field.
func PurchaseSubscriptionWithBalance ¶
PurchaseSubscriptionWithBalance creates a subscription by deducting the user's wallet quota.
func RechargeCreem ¶
func RechargeEpay ¶
func RechargeEpay(tradeNo string, actualPaymentMethod string, callerIp string) (alreadyDone bool, err error)
RechargeEpay 原子完成易支付订单:订单行锁、状态校验、成功更新与用户额度增加 在同一个事务内完成,因此同一订单的并发/重复回调(包括多实例部署下)最多充值一次。 alreadyDone=true 表示订单此前已完成,本次为幂等重复回调。 进程内的 LockOrder 只是优化,正确性由本函数的数据库行锁保证。
func RechargeWaffo ¶ added in v0.11.7
func RechargeWaffoPancake ¶ added in v0.12.15
func RecordConsumeLog ¶
func RecordConsumeLog(c *gin.Context, userId int, params RecordConsumeLogParams)
func RecordErrorLog ¶
func RecordExist ¶
func RecordLogWithAdminInfo ¶ added in v0.12.14
func RecordLogWithAdminInfo(userId int, logType int, content string, adminInfo map[string]interface{})
RecordLogWithAdminInfo 记录操作日志,并将管理员相关信息存入 Other.admin_info,
func RecordLoginLog ¶
func RecordLoginLog(userId int, username string, content string, ip string, action string, params map[string]interface{}, extra map[string]interface{})
RecordLoginLog 记录用户登录成功的审计日志(type=LogTypeLogin)。 username 由调用方传入(登录流程已持有用户对象),避免额外的数据库查询。 content 为英文兜底文本(用于导出);action+params 供前端本地化渲染。 extra 可携带 login_method、user_agent 等附加信息(普通用户可见)。
func RecordOperationAuditLog ¶
func RecordOperationAuditLog(logUserId int, content string, ip string, action string, params map[string]interface{}, adminInfo map[string]interface{}, auditInfo map[string]interface{})
RecordOperationAuditLog 记录管理/高危操作审计日志(type=LogTypeManage)。 logUserId 为日志归属者,管理审计日志应归属实际操作者;目标资源/用户放入 action params。username 内部按 logUserId 查询。content 为英文兜底文本(供导出使用)。 action+params 写入 Other.op,供前端本地化渲染(普通用户可见,不含敏感信息)。 adminInfo 存放操作者身份(写入 Other.admin_info,普通用户查询时剥离); auditInfo 存放路由/方法/结果等中间件兜底信息(写入 Other.audit_info,普通用户查询时剥离)。
func RecordTaskBillingLog ¶ added in v0.11.0
func RecordTaskBillingLog(params RecordTaskBillingLogParams)
func RecordTopupLog ¶ added in v0.12.13
func RefreshPricing ¶
func RefreshPricing()
RefreshPricing 强制立即重新计算与定价相关的缓存。 该方法用于需要最新数据的内部管理 API, 因此会绕过默认的 1 分钟延迟刷新。
func RefreshUserGroupCache ¶
RefreshUserGroupCache writes the database-authoritative group into an existing user hash without changing the user's authentication version.
func RefundSubscriptionPreConsume ¶ added in v0.10.8
RefundSubscriptionPreConsume is idempotent and refunds pre-consumed subscription quota by requestId.
func ReleaseSystemTaskLock ¶
func RenewSystemTaskLock ¶
func ReplaceBackupCodesWithAuthVersion ¶
ReplaceBackupCodesWithAuthVersion atomically replaces the factor's recovery credentials and advances the user's authentication version.
func ResetDueSubscriptions ¶ added in v0.10.8
ResetDueSubscriptions resets subscriptions whose next_reset_time has passed.
func RevokeOtherUserSessions ¶
func RevokeUserSessionByRefreshHash ¶
RevokeUserSessionByRefreshHash is used when logout is authenticated only by the HttpOnly refresh cookie. Possession of a SID alone is insufficient. The immediately previous digest is accepted only inside the refresh race window.
func RootUserExists ¶
func RootUserExists() bool
func SaveQuotaDataCache ¶
func SaveQuotaDataCache()
func SearchTags ¶
func SetUserAuthVersionFence ¶
SetUserAuthVersionFence publishes a fail-closed version before a restrictive database update. Pending fences expire only after every pre-existing user hash must have expired; a committed update is promoted separately to a permanent monotonic version floor.
func SumUsedToken ¶
func SyncChannelCache ¶
func SyncChannelCache(frequency int)
func SyncOptions ¶
func SyncOptions(frequency int)
func TaskBulkUpdateByID ¶
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 TryReserveTokenQuota ¶
TryReserveTokenQuota atomically checks and deducts a token quota. Unlimited tokens skip the balance check but still update remain/used accounting.
func TryReserveUserQuota ¶
TryReserveUserQuota atomically checks and deducts a user's wallet quota. 缓存命中时以缓存余额为准(避免批量模式下过期的数据库余额放大并发超扣); Redis 异常或水合失败时降级为数据库条件更新,保证服务可用。
func UpdateAbilityByTag ¶
func UpdateAbilityStatus ¶
func UpdateChannelStatus ¶
func UpdateChannelUsedQuota ¶
func UpdateCustomOAuthProvider ¶ added in v0.10.8
func UpdateCustomOAuthProvider(provider *CustomOAuthProvider) error
UpdateCustomOAuthProvider updates an existing custom OAuth provider
func UpdateOption ¶
func UpdateOptionsBulk ¶
UpdateOptionsBulk persists multiple key/value pairs in a single database transaction, then dispatches them through updateOptionMap in one pass. If any DB write fails the whole transaction rolls back and no in-memory state is touched — safe for callers that must commit a set of related options atomically (e.g. payment gateway binding).
func UpdatePasskeyAssertionState ¶
func UpdatePasskeyAssertionState(userID int, credential *webauthn.Credential, lastUsedAt time.Time) error
UpdatePasskeyAssertionState persists only fields produced by a successful assertion. Registration identity (credential ID, public key, AAGUID, transports and attestation metadata) is immutable on this path.
func UpdatePendingTopUpStatus ¶ added in v0.12.15
func UpdateProgress ¶
func UpdateQuotaData ¶
func UpdateQuotaData()
func UpdateSystemTaskState ¶
func UpdateUserAccessToken ¶
UpdateUserAccessToken rotates a dashboard personal access token without writing a stale user snapshot back over concurrently updated fields.
func UpdateUserBindColumn ¶
UpdateUserBindColumn 第三方账号绑定字段的专用更新。 绑定操作必须只写绑定列:若改为“读取完整用户 → 改一个字段 → 整体更新”, 读快照期间并发发生的封禁、降权或分组变更会被旧快照覆盖恢复。 角色、状态、分组只允许通过各自带锁/CAS 的专用方法修改。
func UpdateUserLastLoginAt ¶ added in v0.13.2
func UpdateUserLastLoginAt(id int)
func UpdateUserOAuthBinding ¶ added in v0.10.8
UpdateUserOAuthBinding updates an existing OAuth binding (e.g., rebind to different OAuth account)
func UpdateUserSetting ¶
func UpdateUserSetting(userId int, setting dto.UserSetting) error
func UpdateUserUsedQuota ¶
UpdateUserUsedQuota adjusts accumulated usage without changing request count.
func UpsertPasskeyCredentialWithAuthVersion ¶
func UpsertPasskeyCredentialWithAuthVersion(credential *PasskeyCredential) error
UpsertPasskeyCredentialWithAuthVersion is reserved for enrollment changes; assertion sign-count updates must use UpdatePasskeyAssertionState.
func UpsertPerfMetric ¶
func UpsertPerfMetric(metric *PerfMetric) error
func UpsertSystemInstance ¶
func UserActiveSubscriptionsAllowWalletOverflow ¶
UserActiveSubscriptionsAllowWalletOverflow returns whether wallet balance may be used after the user's subscription quota is exhausted. A single active subscription that disallows wallet overflow (allow_wallet_overflow = false) blocks the fallback.
func ValidateBackupCode ¶
ValidateBackupCode 验证并使用备用码
func ValidateTopUpQuotaCapacity ¶
ValidateTopUpQuotaCapacity performs the user-facing pre-payment check. The settlement path repeats the same invariant with an atomic conditional update, because the wallet balance can change after checkout creation.
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 ¶
func GetAllEnableAbilityWithChannels ¶
func GetAllEnableAbilityWithChannels() ([]AbilityWithChannel, error)
type AuthFlow ¶
type AuthFlow struct {
Id int64 `json:"id" gorm:"primaryKey"`
TokenHash string `json:"-" gorm:"type:char(64);not null;uniqueIndex"`
Purpose string `json:"purpose" gorm:"type:varchar(32);not null;index:idx_auth_flow_purpose_expiry"`
Provider string `json:"provider,omitempty" gorm:"type:varchar(64)"`
Intent string `json:"intent,omitempty" gorm:"type:varchar(16)"`
UserId int `json:"user_id,omitempty" gorm:"index"`
SessionId string `json:"session_id,omitempty" gorm:"type:varchar(64);index"`
Payload string `json:"-" gorm:"type:text"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at" gorm:"not null;index:idx_auth_flow_purpose_expiry"`
ConsumedAt *time.Time `json:"consumed_at,omitempty" gorm:"index"`
}
AuthFlow stores one-time, short-lived state for authentication ceremonies. TokenHash is an HMAC of the opaque token; the token itself is never persisted.
func ConsumeAuthFlow ¶
func ConsumeAuthFlow(token string, match AuthFlowMatch) (*AuthFlow, error)
ConsumeAuthFlow atomically validates and consumes a flow. Optional match fields are enforced when non-zero so tokens cannot cross purposes or users.
func ConsumeAuthFlowWithAction ¶
func ConsumeAuthFlowWithAction(token string, match AuthFlowMatch, action func(tx *gorm.DB, flow *AuthFlow) error) (*AuthFlow, error)
ConsumeAuthFlowWithAction consumes a flow and runs action in the same database transaction. An action failure rolls the consumption back.
func CreateAuthFlow ¶
func CreateAuthFlow(input AuthFlowCreate) (string, *AuthFlow, error)
func GetAuthFlow ¶
func GetAuthFlow(token string, match AuthFlowMatch) (*AuthFlow, error)
GetAuthFlow validates a flow without consuming it. Callers must still use ConsumeAuthFlow with all identity-bound fields before performing the action.
type AuthFlowCreate ¶
type AuthFlowMatch ¶
type AuthzRole ¶
type AuthzRole struct {
Id uint `json:"id" gorm:"primaryKey;autoIncrement"`
Key string `json:"key" gorm:"size:64;uniqueIndex;not null"`
Name string `json:"name" gorm:"size:100;not null"`
Description string `json:"description" gorm:"type:text"`
BuiltIn bool `json:"built_in"`
Enabled bool `json:"enabled"`
Sort int `json:"sort"`
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"`
UpdatedAt int64 `json:"updated_at" gorm:"autoUpdateTime;column:updated_at"`
}
type BoundChannel ¶
type CasbinRule ¶
type CasbinRule struct {
Id uint `gorm:"primaryKey;autoIncrement"`
Ptype string `gorm:"size:100;index:idx_casbin_rule,priority:1;uniqueIndex:idx_casbin_rule_unique,priority:1"`
V0 string `gorm:"size:100;index:idx_casbin_rule,priority:2;uniqueIndex:idx_casbin_rule_unique,priority:2"`
V1 string `gorm:"size:100;index:idx_casbin_rule,priority:3;uniqueIndex:idx_casbin_rule_unique,priority:3"`
V2 string `gorm:"size:100;index:idx_casbin_rule,priority:4;uniqueIndex:idx_casbin_rule_unique,priority:4"`
V3 string `gorm:"size:100;index:idx_casbin_rule,priority:5;uniqueIndex:idx_casbin_rule_unique,priority:5"`
V4 string `gorm:"size:100;index:idx_casbin_rule,priority:6;uniqueIndex:idx_casbin_rule_unique,priority:6"`
V5 string `gorm:"size:100;index:idx_casbin_rule,priority:7;uniqueIndex:idx_casbin_rule_unique,priority:7"`
}
func (CasbinRule) TableName ¶
func (CasbinRule) 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 GetAllChannels ¶
func GetChannel ¶
func GetChannelsByIds ¶
func GetChannelsByTag ¶
func GetChannelsByType ¶
Get channels of specified type with pagination
func SearchChannels ¶
func (*Channel) DeleteAbilities ¶
func (*Channel) GetAutoBan ¶
func (*Channel) GetBaseURL ¶
func (*Channel) GetHeaderOverride ¶
func (*Channel) GetModelMapping ¶
func (*Channel) GetNextEnabledKey ¶
func (channel *Channel) GetNextEnabledKey() (string, int, *types.NewAPIError)
func (*Channel) GetOtherInfo ¶
func (*Channel) GetOtherSettings ¶
func (channel *Channel) GetOtherSettings() dto.ChannelOtherSettings
func (*Channel) GetParamOverride ¶
func (*Channel) GetPriority ¶
func (*Channel) GetSetting ¶
func (channel *Channel) GetSetting() dto.ChannelSettings
func (*Channel) GetStatusCodeMapping ¶
func (*Channel) SaveChannelInfo ¶
func (*Channel) SetOtherInfo ¶
func (*Channel) SetOtherSettings ¶
func (channel *Channel) SetOtherSettings(setting dto.ChannelOtherSettings)
func (*Channel) SetSetting ¶
func (channel *Channel) SetSetting(setting dto.ChannelSettings)
func (*Channel) UpdateAbilities ¶
UpdateAbilities updates abilities of this channel. Make sure the channel is completed before calling this function.
func (*Channel) UpdateBalance ¶
func (*Channel) UpdateResponseTime ¶
func (*Channel) ValidateSettings ¶
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
type ChannelSortOptions ¶
func NewChannelSortOptions ¶
func NewChannelSortOptions(sortBy string, sortOrder string, idSort bool) ChannelSortOptions
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 ¶
GetUserCheckinRecords 获取用户在指定日期范围内的签到记录
func UserCheckin ¶
UserCheckin 执行用户签到 MySQL 和 PostgreSQL 使用事务保证原子性 SQLite 不支持嵌套事务,使用顺序操作 + 手动回滚
type CheckinRecord ¶
type CheckinRecord struct {
CheckinDate string `json:"checkin_date"`
QuotaAwarded int `json:"quota_awarded"`
}
CheckinRecord 用于API返回的签到记录(不包含敏感字段)
type CustomOAuthProvider ¶ added in v0.10.8
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 ¶ added in v0.10.8
func GetAllCustomOAuthProviders() ([]*CustomOAuthProvider, error)
GetAllCustomOAuthProviders returns all custom OAuth providers
func GetCustomOAuthProviderById ¶ added in v0.10.8
func GetCustomOAuthProviderById(id int) (*CustomOAuthProvider, error)
GetCustomOAuthProviderById returns a custom OAuth provider by ID
func GetCustomOAuthProviderBySlug ¶ added in v0.10.8
func GetCustomOAuthProviderBySlug(slug string) (*CustomOAuthProvider, error)
GetCustomOAuthProviderBySlug returns a custom OAuth provider by slug
func GetEnabledCustomOAuthProviders ¶ added in v0.10.8
func GetEnabledCustomOAuthProviders() ([]*CustomOAuthProvider, error)
GetEnabledCustomOAuthProviders returns all enabled custom OAuth providers
func (CustomOAuthProvider) TableName ¶ added in v0.10.8
func (CustomOAuthProvider) TableName() string
type ExternalIdentityClaim ¶
type ExternalIdentityClaim struct {
Id int64 `json:"id" gorm:"primaryKey"`
Provider string `` /* 151-byte string literal not displayed */
Subject string `json:"subject" gorm:"type:varchar(128);not null;uniqueIndex:idx_external_identity_subject,priority:2"`
UserId int `json:"user_id" gorm:"not null;index;uniqueIndex:idx_external_identity_user,priority:2"`
CreatedAt time.Time `json:"created_at"`
}
ExternalIdentityClaim is the durable ownership record for an identity issued by an external provider. The two unique indexes make both the provider subject and the user's provider slot single-owner without relying on a check-then-update sequence.
func (ExternalIdentityClaim) TableName ¶
func (ExternalIdentityClaim) TableName() string
type FlowQuotaData ¶
type FlowQuotaData struct {
UserID int `json:"user_id,omitempty" gorm:"column:user_id"`
Username string `json:"username,omitempty" gorm:"column:username"`
NodeName string `json:"node_name,omitempty" gorm:"column:node_name"`
TokenID int `json:"token_id,omitempty" gorm:"column:token_id"`
TokenName string `json:"token_name,omitempty" gorm:"-"`
UseGroup string `json:"use_group" gorm:"column:use_group"`
ChannelID int `json:"channel_id,omitempty" gorm:"column:channel_id"`
ChannelName string `json:"channel_name,omitempty" gorm:"-"`
ModelName string `json:"model_name" gorm:"column:model_name"`
TokenUsed int `json:"token_used" gorm:"column:token_used"`
Count int `json:"count" gorm:"column:count"`
Quota int `json:"quota" gorm:"column:quota"`
}
func GetFlowQuotaData ¶
type JSONValue ¶
type JSONValue json.RawMessage
JSONValue 基于 json.RawMessage 实现,支持从数据库的 []byte 和 string 两种类型读取
func (JSONValue) MarshalJSON ¶
MarshalJSON 确保在对外编码时与 json.RawMessage 行为一致
func (*JSONValue) UnmarshalJSON ¶
UnmarshalJSON 确保在对外解码时与 json.RawMessage 行为一致
type Log ¶
type Log struct {
Id int `json:"id" gorm:"index:idx_created_at_id,priority:2;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:1;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:''"`
UpstreamRequestId string `json:"upstream_request_id,omitempty" gorm:"type:varchar(128);index:idx_logs_upstream_request_id;default:''"`
Other string `json:"other"`
}
func GetAllLogs ¶
func GetLogByTokenId ¶ added in v0.10.8
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"`
TokenId int `json:"-" gorm:"default:0"`
BillingChannelId int `json:"-" gorm:"default:0"`
}
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) GetBillingChannelId ¶
func (midjourney *Midjourney) GetBillingChannelId() int
func (*Midjourney) Insert ¶
func (midjourney *Midjourney) Insert() error
func (*Midjourney) Update ¶
func (midjourney *Midjourney) Update() error
func (*Midjourney) UpdateBillingState ¶
func (midjourney *Midjourney) UpdateBillingState() error
func (*Midjourney) UpdateWithStatus ¶ added in v0.11.0
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 SearchModels ¶
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) 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 PerfMetric ¶
type PerfMetric struct {
Id int `json:"id" gorm:"primaryKey"`
ModelName string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1"`
Group string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"`
BucketTs int64 `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts"`
RequestCount int64 `json:"-" gorm:"default:0"`
SuccessCount int64 `json:"-" gorm:"default:0"`
TotalLatencyMs int64 `json:"-" gorm:"default:0"`
TtftSumMs int64 `json:"-" gorm:"default:0"`
TtftCount int64 `json:"-" gorm:"default:0"`
OutputTokens int64 `json:"-" gorm:"default:0"`
GenerationMs int64 `json:"-" gorm:"default:0"`
}
PerfMetric stores aggregated relay performance metrics for the model square.
func GetPerfMetrics ¶
func (PerfMetric) TableName ¶
func (PerfMetric) TableName() string
type PerfMetricSummary ¶
type PerfMetricSummary struct {
ModelName string `json:"model_name"`
RequestCount int64 `json:"request_count"`
SuccessCount int64 `json:"success_count"`
TotalLatencyMs int64 `json:"total_latency_ms"`
OutputTokens int64 `json:"output_tokens"`
GenerationMs int64 `json:"generation_ms"`
}
func GetPerfMetricsSummaryAll ¶
func GetPerfMetricsSummaryAll(startTs int64, endTs int64, groups []string) ([]PerfMetricSummary, error)
type PerfMetricSummaryBucket ¶
type PerfMetricSummaryBucket struct {
ModelName string `json:"model_name"`
BucketTs int64 `json:"bucket_ts"`
RequestCount int64 `json:"request_count"`
SuccessCount int64 `json:"success_count"`
TotalLatencyMs int64 `json:"total_latency_ms"`
OutputTokens int64 `json:"output_tokens"`
GenerationMs int64 `json:"generation_ms"`
}
func GetPerfMetricsSummaryBucketsAll ¶
func GetPerfMetricsSummaryBucketsAll(startTs int64, endTs int64, groups []string) ([]PerfMetricSummaryBucket, error)
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 获取全部组,可按类型过滤(为空则返回全部)
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"`
BillingMode string `json:"billing_mode,omitempty"`
BillingExpr string `json:"billing_expr,omitempty"`
PricingVersion string `json:"pricing_version,omitempty"`
}
func GetPricing ¶
func GetPricing() []Pricing
type PricingVendor ¶
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
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"`
UseGroup string `json:"use_group" gorm:"index;size:64;default:''"`
TokenID int `json:"token_id" gorm:"index;default:0"`
ChannelID int `json:"channel_id" gorm:"index;default:0"`
NodeName string `json:"node_name" gorm:"index;size:64;default:''"`
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 GetQuotaDataByUserId ¶
func GetQuotaDataByUsername ¶
type QuotaDataLogParams ¶
type RankingQuotaBucket ¶
type RankingQuotaBucket struct {
ModelName string `json:"model_name"`
Bucket int64 `json:"bucket"`
Tokens int64 `json:"tokens"`
}
func GetRankingQuotaBuckets ¶
func GetRankingQuotaBuckets(startTime int64, endTime int64, bucketSize int64) ([]RankingQuotaBucket, error)
type RankingQuotaTotal ¶
type RankingQuotaTotal struct {
ModelName string `json:"model_name"`
TotalTokens int64 `json:"total_tokens"`
}
func GetRankingQuotaTotals ¶
func GetRankingQuotaTotals(startTime int64, endTime int64) ([]RankingQuotaTotal, error)
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 ¶ added in v0.11.0
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 (*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 SubscriptionOrder ¶ added in v0.10.8
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)"`
PaymentProvider string `json:"payment_provider" gorm:"type:varchar(50);default:''"`
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 ¶ added in v0.10.8
func GetSubscriptionOrderByTradeNo(tradeNo string) *SubscriptionOrder
func (*SubscriptionOrder) Insert ¶ added in v0.10.8
func (o *SubscriptionOrder) Insert() error
func (*SubscriptionOrder) Update ¶ added in v0.10.8
func (o *SubscriptionOrder) Update() error
type SubscriptionPlan ¶ added in v0.10.8
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"`
AllowBalancePay *bool `json:"allow_balance_pay"`
// Allow falling back to wallet balance after subscription quota is exhausted (empty = true)
AllowWalletOverflow *bool `json:"allow_wallet_overflow"`
StripePriceId string `json:"stripe_price_id" gorm:"type:varchar(128);default:''"`
CreemProductId string `json:"creem_product_id" gorm:"type:varchar(128);default:''"`
WaffoPancakeProductId string `json:"waffo_pancake_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:''"`
// Downgrade user group on expiry (empty = revert to the group held before purchase)
DowngradeGroup string `json:"downgrade_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 ¶ added in v0.10.8
func GetSubscriptionPlanById(id int) (*SubscriptionPlan, error)
func (*SubscriptionPlan) BeforeCreate ¶ added in v0.10.8
func (p *SubscriptionPlan) BeforeCreate(tx *gorm.DB) error
func (*SubscriptionPlan) BeforeUpdate ¶ added in v0.10.8
func (p *SubscriptionPlan) BeforeUpdate(tx *gorm.DB) error
func (*SubscriptionPlan) NormalizeDefaults ¶
func (p *SubscriptionPlan) NormalizeDefaults()
type SubscriptionPlanInfo ¶ added in v0.10.8
func GetSubscriptionPlanInfoByUserSubscriptionId ¶ added in v0.10.8
func GetSubscriptionPlanInfoByUserSubscriptionId(userSubscriptionId int) (*SubscriptionPlanInfo, error)
type SubscriptionPreConsumeRecord ¶ added in v0.10.8
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 ¶ added in v0.10.8
func (r *SubscriptionPreConsumeRecord) BeforeCreate(tx *gorm.DB) error
func (*SubscriptionPreConsumeRecord) BeforeUpdate ¶ added in v0.10.8
func (r *SubscriptionPreConsumeRecord) BeforeUpdate(tx *gorm.DB) error
type SubscriptionPreConsumeResult ¶ added in v0.10.8
type SubscriptionPreConsumeResult struct {
UserSubscriptionId int
PreConsumed int64
AmountTotal int64
AmountUsedBefore int64
AmountUsedAfter int64
}
func PreConsumeUserSubscription ¶ added in v0.10.8
func PreConsumeUserSubscription(requestId string, userId int, modelName string, quotaType int, amount int64) (*SubscriptionPreConsumeResult, error)
PreConsumeUserSubscription pre-consumes from any active subscription total quota.
type SubscriptionResetResult ¶
type SubscriptionResetResult struct {
PlanId int `json:"plan_id"`
MatchedCount int `json:"matched_count"`
ResetCount int `json:"reset_count"`
UserCount int `json:"user_count"`
AdvanceResetTime bool `json:"advance_reset_time"`
PlanTitle string `json:"-"`
AffectedUserIds []int `json:"-"`
}
func AdminResetPlanSubscriptions ¶
func AdminResetPlanSubscriptions(planId int, advanceResetTime bool) (*SubscriptionResetResult, error)
func AdminResetUserSubscriptionsByPlan ¶
func AdminResetUserSubscriptionsByPlan(userId int, planId int, advanceResetTime bool) (*SubscriptionResetResult, error)
type SubscriptionSummary ¶ added in v0.10.8
type SubscriptionSummary struct {
Subscription *UserSubscription `json:"subscription"`
}
func GetAllActiveUserSubscriptions ¶ added in v0.10.8
func GetAllActiveUserSubscriptions(userId int) ([]SubscriptionSummary, error)
GetAllActiveUserSubscriptions returns all active subscriptions for a user.
func GetAllUserSubscriptions ¶ added in v0.10.8
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 SystemInstance ¶
type SystemInstance struct {
NodeName string `json:"node_name" gorm:"type:varchar(128);primaryKey"`
Info string `json:"info" gorm:"type:text"`
StartedAt int64 `json:"started_at" gorm:"bigint;index"`
LastSeenAt int64 `json:"last_seen_at" gorm:"bigint;index"`
CreatedAt int64 `json:"created_at" gorm:"bigint;index"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
}
func ListSystemInstances ¶
func ListSystemInstances() ([]*SystemInstance, error)
func (*SystemInstance) BeforeCreate ¶
func (instance *SystemInstance) BeforeCreate(_ *gorm.DB) error
func (*SystemInstance) ToResponse ¶
func (instance *SystemInstance) ToResponse(now int64) SystemInstanceResponse
type SystemInstanceResponse ¶
type SystemTask ¶
type SystemTask struct {
ID int64 `json:"id" gorm:"primary_key"`
TaskID string `json:"task_id" gorm:"type:varchar(64);uniqueIndex"`
Type string `json:"type" gorm:"type:varchar(64);index"`
Status SystemTaskStatus `json:"status" gorm:"type:varchar(32);index"`
ActiveKey *string `json:"active_key,omitempty" gorm:"type:varchar(64);uniqueIndex"`
Payload string `json:"payload" gorm:"type:text"`
State string `json:"state" gorm:"type:text"`
Result string `json:"result" gorm:"type:text"`
Error string `json:"error" gorm:"type:text"`
LockedBy string `json:"locked_by" gorm:"type:varchar(128);index"`
CreatedAt int64 `json:"created_at" gorm:"bigint;index"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
}
func ClaimSystemTask ¶
func CreateSystemTask ¶
func CreateSystemTask(taskType string, payload any, state any) (*SystemTask, error)
func FindPendingSystemTasks ¶
func FindPendingSystemTasks(taskType string, limit int) ([]*SystemTask, error)
func GetActiveSystemTask ¶
func GetActiveSystemTask(taskType string) (*SystemTask, error)
func GetLatestSystemTask ¶
func GetLatestSystemTask(taskType string) (*SystemTask, error)
GetLatestSystemTask returns the most recent task row of the given type (any status) so the scheduler can decide whether enough time has elapsed since the last run. Returns (nil, nil) when no row exists.
func GetSystemTaskByTaskID ¶
func GetSystemTaskByTaskID(taskID string) (*SystemTask, error)
func ListSystemTasks ¶
func ListSystemTasks(limit int) ([]*SystemTask, error)
func (*SystemTask) BeforeCreate ¶
func (task *SystemTask) BeforeCreate(_ *gorm.DB) error
func (*SystemTask) DecodePayload ¶
func (task *SystemTask) DecodePayload(v any) error
func (*SystemTask) DecodeState ¶
func (task *SystemTask) DecodeState(v any) error
func (*SystemTask) ToResponse ¶
func (task *SystemTask) ToResponse() SystemTaskResponse
type SystemTaskLock ¶
type SystemTaskLock struct {
Type string `json:"type" gorm:"type:varchar(64);primaryKey"`
TaskID string `json:"task_id" gorm:"type:varchar(64);index"`
LockedBy string `json:"locked_by" gorm:"type:varchar(128);index"`
LockedUntil int64 `json:"locked_until" gorm:"bigint;index"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint;index"`
}
func (*SystemTaskLock) BeforeCreate ¶
func (lock *SystemTaskLock) BeforeCreate(_ *gorm.DB) error
type SystemTaskResponse ¶
type SystemTaskResponse struct {
ID int64 `json:"id"`
TaskID string `json:"task_id"`
Type string `json:"type"`
Status SystemTaskStatus `json:"status"`
ActiveKey *string `json:"active_key,omitempty"`
Payload any `json:"payload"`
State any `json:"state"`
Result any `json:"result"`
Error string `json:"error"`
LockedBy string `json:"locked_by"`
CreatedAt int64 `json:"created_at"`
UpdatedAt int64 `json:"updated_at"`
}
type SystemTaskStatus ¶
type SystemTaskStatus string
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 GetTimedOutUnfinishedTasks ¶ added in v0.11.0
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) GetResultURL ¶ added in v0.11.0
GetResultURL 获取任务结果 URL(视频地址等) 新数据存在 PrivateData.ResultURL 中;旧数据回退到 FailReason(历史兼容)
func (*Task) GetUpstreamTaskID ¶ added in v0.11.0
GetUpstreamTaskID 获取上游真实 task ID(用于与 provider 通信) 旧数据没有 UpstreamTaskID 时,TaskID 本身就是上游 ID
func (*Task) ToOpenAIVideo ¶
func (t *Task) ToOpenAIVideo() *dto.OpenAIVideo
func (*Task) UpdateQuota ¶
func (*Task) UpdateWithStatus ¶ added in v0.11.0
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. MySQL commonly reports changed rows rather than matched rows, so a same-value no-op update can also return false even when the status predicate still matched.
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 ¶ added in v0.11.0
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,用于令牌额度退款
NodeName string `json:"node_name,omitempty"` // 发起任务的节点名,轮询结算阶段据此归属日志而非最后查询节点
BillingContext *TaskBillingContext `json:"billing_context,omitempty"` // 计费参数快照(用于轮询阶段重新计算)
}
func (*TaskPrivateData) Scan ¶
func (p *TaskPrivateData) Scan(val interface{}) error
type TaskQueryParams ¶
type TaskQueryParams struct {
ChannelID string
MjID string
StartTimestamp string
EndTimestamp string
}
TaskQueryParams 用于包含所有搜索条件的结构体,可以根据需求添加更多字段
type TaskQuotaUsage ¶
type TaskStatus ¶
type TaskStatus string
func (TaskStatus) ToVideoStatus ¶
func (t TaskStatus) ToVideoStatus() string
type Token ¶
type Token struct {
Id int `json:"id"`
UserId int `json:"user_id" gorm:"index"`
Key string `json:"key" gorm:"type:varchar(128);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分组有效
AutoGroups string `json:"-" gorm:"type:text"`
DeletedAt gorm.DeletedAt `gorm:"index"`
}
func GetTokenById ¶
func GetTokenKeysByIds ¶ added in v0.12.3
func SearchUserTokens ¶
func ValidateUserToken ¶
func (*Token) GetAutoGroups ¶
func (*Token) GetFullKey ¶ added in v0.11.4
func (*Token) GetIpLimits ¶
func (*Token) GetMaskedKey ¶ added in v0.11.4
func (*Token) GetModelLimits ¶
func (*Token) GetModelLimitsMap ¶
func (*Token) IsModelLimitsEnabled ¶
func (*Token) SelectUpdate ¶
func (*Token) SetAutoGroups ¶
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)"`
PaymentProvider string `json:"payment_provider" gorm:"type:varchar(50);default:''"`
CreateTime int64 `json:"create_time"`
CompleteTime int64 `json:"complete_time"`
Status string `json:"status"`
}
func GetAllTopUps ¶
GetAllTopUps 获取全平台的充值记录(管理员使用,不限制时间窗口)
func GetTopUpById ¶
func GetTopUpByTradeNo ¶
func GetUserTopUps ¶
func SearchAllTopUps ¶
func SearchAllTopUps(keyword string, pageInfo *common.PageInfo) (topups []*TopUp, total int64, err error)
SearchAllTopUps 按订单号搜索全平台充值记录(管理员使用,不限制时间窗口)
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 ¶
GetTwoFAByUserId 根据用户ID获取2FA设置
func (*TwoFA) CreatePendingTwoFASetup ¶
CreatePendingTwoFASetup stores a disabled factor while the user completes enrollment. Enabling a factor must use EnableWithAuthVersion.
func (*TwoFA) DeletePendingTwoFASetup ¶
DeletePendingTwoFASetup removes only an unverified setup. Enabled factors must use DisableTwoFAWithAuthVersion.
func (*TwoFA) EnableWithAuthVersion ¶
EnableWithAuthVersion atomically enables this factor and advances the user authentication version so pre-enrollment sessions cannot remain valid.
func (*TwoFA) IncrementFailedAttempts ¶
IncrementFailedAttempts 增加失败尝试次数
func (*TwoFA) ResetFailedAttempts ¶
ResetFailedAttempts 重置失败尝试次数
func (*TwoFA) ValidateBackupCodeAndUpdateUsage ¶
ValidateBackupCodeAndUpdateUsage 验证备用码并更新使用记录
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:"-" 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"`
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at"`
LastLoginAt int64 `json:"last_login_at" gorm:"default:0;column:last_login_at"`
AuthVersion int64 `json:"-" gorm:"type:bigint;not null;default:1;column:auth_version"`
AdminPermissions map[string]map[string]bool `json:"admin_permissions,omitempty" gorm:"-:all"`
}
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 GetRootUser ¶
func GetRootUser() (user *User)
func GetUniqueUserByEmail ¶
func GetUserByOAuthBinding ¶ added in v0.10.8
GetUserByOAuthBinding finds a user by provider ID and provider user ID
func SearchUsers ¶
func ValidateAccessToken ¶
func (*User) ClearBinding ¶ added in v0.11.0
func (*User) FillUserByDiscordId ¶
func (*User) FillUserByEmail ¶
func (*User) FillUserByGitHubId ¶
func (*User) FillUserById ¶
func (*User) FillUserByLinuxDOId ¶
func (*User) FillUserByOidcId ¶
func (*User) FillUserByTelegramId ¶
func (*User) FillUserByWeChatId ¶
func (*User) FinalizeOAuthUserCreation ¶ added in v0.10.9
FinalizeOAuthUserCreation performs post-transaction tasks for OAuth user creation. This should be called after the transaction commits successfully.
func (*User) FinishInsert ¶
func (*User) GetAccessToken ¶
func (*User) GetSetting ¶
func (user *User) GetSetting() dto.UserSetting
func (*User) HardDelete ¶
func (*User) InsertWithTx ¶ added in v0.10.9
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) SetSetting ¶
func (user *User) SetSetting(setting dto.UserSetting)
func (*User) ToBaseUser ¶
func (*User) TransferAffQuotaToQuota ¶
func (*User) UpdateGitHubId ¶ added in v0.10.8
UpdateGitHubId updates the user's GitHub ID (used for migration from login to numeric ID)
func (*User) ValidateAndFill ¶
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"`
Role int `json:"role"`
Username string `json:"username"`
Setting string `json:"setting"`
AuthVersion int64 `json:"-"`
CacheSchema int `json:"-"`
}
func GetUserCache ¶
GetUserCache gets complete user cache from hash
func (*UserBase) GetSetting ¶
func (user *UserBase) GetSetting() dto.UserSetting
func (*UserBase) WriteContext ¶
type UserOAuthBinding ¶ added in v0.10.8
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 ¶ added in v0.10.8
func GetUserOAuthBinding(userId, providerId int) (*UserOAuthBinding, error)
GetUserOAuthBinding returns a specific binding for a user and provider
func GetUserOAuthBindingsByUserId ¶ added in v0.10.8
func GetUserOAuthBindingsByUserId(userId int) ([]*UserOAuthBinding, error)
GetUserOAuthBindingsByUserId returns all OAuth bindings for a user
func (UserOAuthBinding) TableName ¶ added in v0.10.8
func (UserOAuthBinding) TableName() string
type UserSession ¶
type UserSession struct {
SID string `json:"sid" gorm:"column:sid;type:varchar(64);primaryKey"`
UserID int `` /* 147-byte string literal not displayed */
Version int64 `json:"version" gorm:"type:bigint;not null;default:1"`
UserAuthVersion int64 `json:"user_auth_version" gorm:"type:bigint;not null"`
Status string `` /* 150-byte string literal not displayed */
RefreshHash string `json:"-" gorm:"type:char(64);not null"`
PreviousRefreshHash string `json:"-" gorm:"type:varchar(64)"`
PreviousValidUntil int64 `json:"-" gorm:"type:bigint;not null;default:0"`
LoginMethod string `json:"login_method" gorm:"type:varchar(32);not null"`
IP string `json:"ip" gorm:"type:varchar(64)"`
UserAgent string `json:"user_agent" gorm:"type:text"`
CreatedAt int64 `json:"created_at" gorm:"autoCreateTime;column:created_at;index:idx_user_sessions_user_created,priority:2"`
LastActiveAt int64 `json:"last_active_at" gorm:"type:bigint;not null;column:last_active_at"`
ExpiresAt int64 `` /* 152-byte string literal not displayed */
RevokedAt int64 `` /* 133-byte string literal not displayed */
RevokedReason string `json:"revoked_reason,omitempty" gorm:"type:varchar(64);column:revoked_reason"`
}
UserSession is the server-side control plane for short-lived access JWTs. RefreshHash values are HMAC digests supplied by the service layer; opaque refresh secrets are never persisted.
func AdvanceUserSessionAuthVersion ¶
func AdvanceUserSessionAuthVersion(userID int, sid string, expectedSessionVersion, expectedUserAuthVersion, nextUserAuthVersion int64) (*UserSession, error)
AdvanceUserSessionAuthVersion preserves one browser session across a user-level security-version change. Both old access JWTs and concurrent updates are invalidated by advancing the per-session version as well.
func GetUserSessionBySID ¶
func GetUserSessionBySID(sid string) (*UserSession, error)
func GetUserSessionCached ¶
func GetUserSessionCached(sid string) (*UserSession, error)
GetUserSessionCached validates cached state first and falls back to the database on a miss or Redis read failure. A deny tombstone never falls back.
func ListActiveUserSessions ¶
func ListActiveUserSessions(userID int, currentSID string, now int64) ([]UserSession, error)
func RotateUserSessionRefresh ¶
func RotateUserSessionRefresh(userID int, sid, presentedHash, nextHash string, now int64, grace time.Duration) (*UserSession, error)
RotateUserSessionRefresh atomically rotates HMAC digests. The UPDATE itself is a compare-and-swap so SQLite, where lockForUpdate is intentionally a no-op, has the same single-winner behavior as MySQL and PostgreSQL. Only a recognized previous digest outside its grace window is treated as reuse; an unknown secret never revokes the victim session.
func (UserSession) TableName ¶
func (UserSession) TableName() string
type UserSortOptions ¶
func NewUserSortOptions ¶
func NewUserSortOptions(sortBy string, sortOrder string) UserSortOptions
type UserSubscription ¶ added in v0.10.8
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:''"`
// Downgrade target group on expiry (snapshot from plan; empty = revert to PrevUserGroup)
DowngradeGroup string `json:"downgrade_group" gorm:"type:varchar(64);default:''"`
// Whether wallet fallback is allowed after this subscription's quota is exhausted (snapshot from plan)
AllowWalletOverflow bool `json:"allow_wallet_overflow"`
CreatedAt int64 `json:"created_at" gorm:"bigint"`
UpdatedAt int64 `json:"updated_at" gorm:"bigint"`
}
User subscription instance
func CreateUserSubscriptionFromPlanTx ¶ added in v0.10.8
func CreateUserSubscriptionFromPlanTx(tx *gorm.DB, userId int, plan *SubscriptionPlan, source string) (*UserSubscription, error)
func (*UserSubscription) BeforeCreate ¶ added in v0.10.8
func (s *UserSubscription) BeforeCreate(tx *gorm.DB) error
func (*UserSubscription) BeforeUpdate ¶ added in v0.10.8
func (s *UserSubscription) BeforeUpdate(tx *gorm.DB) error
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 ¶
GetAllVendors 获取全部供应商(分页)
func SearchVendors ¶
SearchVendors 按关键字搜索供应商
Source Files
¶
- ability.go
- auth_flow.go
- authz_role.go
- casbin_rule.go
- channel.go
- channel_cache.go
- channel_satisfy.go
- checkin.go
- custom_oauth_provider.go
- db_time.go
- errors.go
- external_identity_claim.go
- frontend_option_migration.go
- gorm_logger.go
- locking.go
- log.go
- main.go
- midjourney.go
- missing_models.go
- model_extra.go
- model_meta.go
- option.go
- passkey.go
- perf_metric.go
- prefill_group.go
- pricing.go
- pricing_default.go
- pricing_refresh.go
- quota_reserve.go
- redemption.go
- setup.go
- subscription.go
- system_instance.go
- system_task.go
- task.go
- token.go
- token_cache.go
- topup.go
- twofa.go
- usedata.go
- usedata_flow.go
- usedata_rankings.go
- user.go
- user_auth_cache.go
- user_cache.go
- user_oauth_binding.go
- user_session.go
- utils.go
- vendor_meta.go