Documentation
¶
Overview ¶
Package v2 provides caching utilities for performance optimization
Package v2 provides circuit breaker pattern for fault tolerance ¶
Package v2 provides HTTP client utilities based on github.com/sunerpy/requests
Package v2 provides level management for PT sites ¶
Package v2 provides metrics collection for performance monitoring ¶
Package v2 provides migration utilities for backward compatibility ¶
Package v2 provides site registry for managing site metadata and creation ¶
Package v2 provides a generic site architecture using the Driver pattern. This package implements type-safe site drivers for different PT site architectures including NexusPHP, Unit3D, Gazelle, and mTorrent (M-Team).
Package v2 provides database-backed user info repository ¶
Package v2 provides input validation utilities
Index ¶
- Constants
- Variables
- func AddAtPausedToAutoStart(addAtPaused bool) bool
- func AddDays(date string, n int) (string, error)
- func ApplyFilters(value any, filters []Filter) any
- func AttendanceMayUseAI(def *SiteDefinition) bool
- func AttendanceSupport(def *SiteDefinition) (bool, string)
- func AutoStartToAddAtPaused(autoStart bool) bool
- func BuildMagnetLink(infoHash, name string, trackers []string) string
- func CalculateEffectiveDownload(sizeBytes int64, discountLevel DiscountLevel) int64
- func CalculateEffectiveUpload(sizeBytes int64, discountLevel DiscountLevel) int64
- func CalculateRatioImpact(currentUploaded, currentDownloaded, torrentSize int64, ...) float64
- func CanDownloadInTimeSimple(sizeBytes, downloadSpeedBps int64, discountLevel DiscountLevel, ...) bool
- func CheckTorrentFile(data []byte) error
- func CompareDiscounts(a, b DiscountLevel) int
- func ComputeTorrentHash(data []byte) (string, error)
- func ComputeTorrentHashFromFile(path string) (string, error)
- func CurrentSessionCookie(site Site) (string, bool)
- func DiscountPriority(level DiscountLevel) int
- func DiscountTimeParseNote(field string) string
- func EstimateDownloadTime(sizeBytes, downloadSpeedBps int64) time.Duration
- func ExtractMagnetHash(magnetURI string) (string, error)
- func FetchFailureReason(err error) string
- func FormatBytes(bytes int64) string
- func FreshAfterFrom(ctx context.Context) (time.Time, bool)
- func GetAllSiteCategoryConfigs() map[string]SiteCategoryConfig
- func GetSiteNextLevelUnmet(info *UserInfo, requirements []SiteLevelRequirement) map[string]any
- func GetSiteURLsForKind(kind SiteKind) map[SiteName][]string
- func GuessUserLevelID(info *UserInfo, requirements []SiteLevelRequirement) int
- func HandleQBittorrentAuthWithRequests(ctx context.Context, baseURL, username, password string) (string, error)
- func HandleTransmissionSession(resp *http.Response) string
- func IgnorePartial(info UserInfo, err error) error
- func IsAttendancePageNotFound(err error) bool
- func IsBetterDiscount(a, b DiscountLevel) bool
- func IsFreeTorrent(level DiscountLevel) bool
- func IsTorrentHash(s string) bool
- func ListRegisteredSchemas() []string
- func NewSizeTieredHRCalc(rules []HRSeedTimeRule, windowH int) func(sizeBytes int64) int
- func NormalizeDoubanID(s string) string
- func NormalizeIMDbID(s string) string
- func NormalizeInfoHash(hash string) string
- func NoteDiscountTimeUnparsable(item *TorrentItem, field string)
- func ParseDownloadURL(def *SiteDefinition, rawURL string) (string, bool)
- func ParseTimeInCST(layout, value string) (time.Time, error)
- func RangeBounds(name, today string) (from, to string, err error)
- func RegisterDriverForSchema(schema string, factory DriverFactory)
- func RegisterFilter(name string, fn FilterFunc)
- func RegisterSiteDefinition(def *SiteDefinition)
- func ResolveHRSeedTimeH(def *SiteDefinition, sizeBytes int64, settingH int) int
- func ResolveSiteByTracker(announceURL string) (string, bool)
- func SanitizeHTML(input string) string
- func SanitizeSearchKeyword(keyword string) string
- func SetSessionCookieSink(fn SessionCookieSink)
- func StripHTMLTags(input string) string
- func ValidateAPIKey(apiKey string) error
- func ValidateCookie(cookie string) error
- func ValidateInfoHash(hash string) bool
- func ValidateTorrentFile(data []byte) error
- func WithAttendanceAIUsage(ctx context.Context, u *AttendanceAIUsage) context.Context
- func WithAttendanceSolver(ctx context.Context, s AttendanceSolver) context.Context
- func WithFreshAfter(ctx context.Context, t time.Time) context.Context
- type AggregatedStats
- type AlternativeRequirement
- type AttendResult
- type AttendStatus
- type AttendanceAIUsage
- type AttendanceCapable
- type AttendanceChallenge
- type AttendanceConfig
- type AttendanceQuestion
- type AttendanceSolver
- type Attender
- type AuthMethod
- type BaseSite
- func (b *BaseSite[Req, Res]) Attend(ctx context.Context) (AttendResult, error)
- func (b *BaseSite[Req, Res]) AttendanceUnsupportedReason() string
- func (b *BaseSite[Req, Res]) Close() error
- func (b *BaseSite[Req, Res]) CurrentCookie() (string, bool)
- func (b *BaseSite[Req, Res]) Download(ctx context.Context, torrentID string) ([]byte, error)
- func (b *BaseSite[Req, Res]) DownloadWithHash(ctx context.Context, torrentID, hash string) ([]byte, error)
- func (b *BaseSite[Req, Res]) GetDetailFetcher() TorrentDetailFetcher
- func (b *BaseSite[Req, Res]) GetDriver() Driver[Req, Res]
- func (b *BaseSite[Req, Res]) GetRateLimiter() *rate.Limiter
- func (b *BaseSite[Req, Res]) GetUserInfo(ctx context.Context) (UserInfo, error)
- func (b *BaseSite[Req, Res]) ID() string
- func (b *BaseSite[Req, Res]) IsLoggedIn() bool
- func (b *BaseSite[Req, Res]) Kind() SiteKind
- func (b *BaseSite[Req, Res]) Login(ctx context.Context, creds Credentials) error
- func (b *BaseSite[Req, Res]) Name() string
- func (b *BaseSite[Req, Res]) Search(ctx context.Context, query SearchQuery) ([]TorrentItem, error)
- func (b *BaseSite[Req, Res]) Subtitles() SubtitleProvider
- func (b *BaseSite[Req, Res]) SupportsAttendance() bool
- type BaseSiteConfig
- type BatchDownloadService
- type CacheEntry
- type CachedSearchOrchestrator
- func (c *CachedSearchOrchestrator) CacheSize() int
- func (c *CachedSearchOrchestrator) CachedTorrent(site, id string) (TorrentItem, bool)
- func (c *CachedSearchOrchestrator) CleanupCache() int
- func (c *CachedSearchOrchestrator) ClearCache()
- func (c *CachedSearchOrchestrator) Search(ctx context.Context, query MultiSiteSearchQuery) (*MultiSiteSearchResult, error)
- type CaptchaImage
- type CategoryDefinition
- type CategoryOption
- type CircuitBreaker
- type CircuitBreakerConfig
- type CircuitBreakerRegistry
- type CircuitBreakerStats
- type CircuitState
- type ConfigMigrator
- func (m *ConfigMigrator) CheckForDeprecatedFields(configJSON []byte) []DeprecationWarning
- func (m *ConfigMigrator) DetectDownloaderConfigVersion(configJSON []byte) string
- func (m *ConfigMigrator) MigrateDownloaderConfig(old OldDownloaderConfig) NewDownloaderConfig
- func (m *ConfigMigrator) MigrateDownloaderConfigIfNeeded(configJSON []byte) ([]byte, bool, error)
- func (m *ConfigMigrator) MigrateDownloaderConfigJSON(oldJSON []byte) ([]byte, error)
- func (m *ConfigMigrator) MigrateSiteConfig(old OldSiteConfig) SiteConfig
- func (m *ConfigMigrator) MigrateSiteConfigJSON(oldJSON []byte) ([]byte, error)
- type ContextDownloadParser
- type Counter
- type Credentials
- type DBUserInfoRepo
- func (r *DBUserInfoRepo) Count(ctx context.Context) (int64, error)
- func (r *DBUserInfoRepo) Delete(ctx context.Context, site string) error
- func (r *DBUserInfoRepo) DeleteAll(ctx context.Context) error
- func (r *DBUserInfoRepo) Get(ctx context.Context, site string) (UserInfo, error)
- func (r *DBUserInfoRepo) GetAggregated(ctx context.Context) (AggregatedStats, error)
- func (r *DBUserInfoRepo) ListAll(ctx context.Context) ([]UserInfo, error)
- func (r *DBUserInfoRepo) ListBySites(ctx context.Context, sites []string) ([]UserInfo, error)
- func (r *DBUserInfoRepo) ListSnapshots(ctx context.Context, site, from, to string) ([]UserInfoDailySnapshot, error)
- func (r *DBUserInfoRepo) PruneSnapshots(ctx context.Context, before string) (int64, error)
- func (r *DBUserInfoRepo) Save(ctx context.Context, info UserInfo) error
- func (r *DBUserInfoRepo) SetClock(now func() time.Time, loc *time.Location)
- func (r *DBUserInfoRepo) SnapshotBaselines(ctx context.Context, before string) (map[string]UserInfoDailySnapshot, error)
- func (r *DBUserInfoRepo) Today() string
- type DailyPoint
- type Deduper
- type DeltaSummary
- func LoadDaySummary(ctx context.Context, repo UserInfoHistoryRepo, day string) (DeltaSummary, error)
- func LoadDeltaSummary(ctx context.Context, repo UserInfoHistoryRepo, rangeName string) (DeltaSummary, error)
- func SummarizeDeltas(rangeName, from, to string, baselines map[string]UserInfoDailySnapshot, ...) DeltaSummary
- type DeprecationWarning
- type DetailFetcherProvider
- type DetailParserConfig
- type DiscountLevel
- type DownloadFeasibility
- type Driver
- type DriverFactory
- type FailoverHTTPClient
- func (c *FailoverHTTPClient) Do(ctx context.Context, method, path string, body []byte, ...) (*HTTPResponse, error)
- func (c *FailoverHTTPClient) Get(ctx context.Context, path string, headers map[string]string) (*HTTPResponse, error)
- func (c *FailoverHTTPClient) GetCurrentBaseURL() string
- func (c *FailoverHTTPClient) Post(ctx context.Context, path string, body []byte, headers map[string]string) (*HTTPResponse, error)
- type FailoverOption
- type FieldSelector
- type Filter
- type FilterFunc
- type FlexInt
- type FlexibleCode
- type FreeTorrentBatchResult
- type FreeValidity
- type Gauge
- type GazelleDriver
- func (d *GazelleDriver) Execute(ctx context.Context, req GazelleRequest) (GazelleResponse, error)
- func (d *GazelleDriver) GetTorrentDetail(ctx context.Context, guid, link, title string) (*TorrentItem, error)
- func (d *GazelleDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
- func (d *GazelleDriver) ParseDownload(res GazelleResponse) ([]byte, error)
- func (d *GazelleDriver) ParseSearch(res GazelleResponse) ([]TorrentItem, error)
- func (d *GazelleDriver) ParseUserInfo(res GazelleResponse) (UserInfo, error)
- func (d *GazelleDriver) PrepareDownload(torrentID string) (GazelleRequest, error)
- func (d *GazelleDriver) PrepareSearch(query SearchQuery) (GazelleRequest, error)
- func (d *GazelleDriver) PrepareUserInfo() (GazelleRequest, error)
- type GazelleDriverConfig
- type GazelleOptions
- type GazelleRequest
- type GazelleResponse
- type GazelleSearchResponse
- type GazelleTorrent
- type GazelleTorrentGroup
- type GazelleUserResponse
- type HDDolbyAPIError
- type HDDolbyDriver
- func (d *HDDolbyDriver) Attend(ctx context.Context) (AttendResult, error)
- func (d *HDDolbyDriver) AttendanceUnsupportedReason() string
- func (d *HDDolbyDriver) Download(ctx context.Context, torrentID string) ([]byte, error)
- func (d *HDDolbyDriver) DownloadWithHash(ctx context.Context, torrentID, downhash string) ([]byte, error)
- func (d *HDDolbyDriver) Execute(ctx context.Context, req HDDolbyRequest) (HDDolbyResponse, error)
- func (d *HDDolbyDriver) GetBonusPerHour(ctx context.Context) (float64, error)
- func (d *HDDolbyDriver) GetPeerData(ctx context.Context) (*HDDolbyPeerData, error)
- func (d *HDDolbyDriver) GetTorrentDetail(ctx context.Context, guid, link, title string) (*TorrentItem, error)
- func (d *HDDolbyDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
- func (d *HDDolbyDriver) ParseDownload(res HDDolbyResponse) ([]byte, error)
- func (d *HDDolbyDriver) ParseSearch(res HDDolbyResponse) ([]TorrentItem, error)
- func (d *HDDolbyDriver) ParseUserInfo(res HDDolbyResponse) (UserInfo, error)
- func (d *HDDolbyDriver) PrepareDownload(torrentID string) (HDDolbyRequest, error)
- func (d *HDDolbyDriver) PrepareSearch(query SearchQuery) (HDDolbyRequest, error)
- func (d *HDDolbyDriver) PrepareUserInfo() (HDDolbyRequest, error)
- func (d *HDDolbyDriver) Search(ctx context.Context, query SearchQuery) ([]TorrentItem, error)
- func (d *HDDolbyDriver) SetSiteDefinition(def *SiteDefinition)
- type HDDolbyDriverConfig
- type HDDolbyOptions
- type HDDolbyPeerData
- type HDDolbyPeerItem
- type HDDolbyRequest
- type HDDolbyResponse
- type HDDolbySearchRequest
- type HDDolbySearchResponse
- type HDDolbyTorrent
- type HDDolbyUserData
- type HDSkyParser
- type HRSeedTimeRule
- type HTTPClientConfig
- type HTTPClientPool
- type HTTPResponse
- type HTTPStatusError
- type HashDownloader
- type Histogram
- type HistogramStats
- type InMemoryUserInfoRepo
- func (r *InMemoryUserInfoRepo) Clear()
- func (r *InMemoryUserInfoRepo) Count() int
- func (r *InMemoryUserInfoRepo) Delete(ctx context.Context, site string) error
- func (r *InMemoryUserInfoRepo) Get(ctx context.Context, site string) (UserInfo, error)
- func (r *InMemoryUserInfoRepo) GetAggregated(ctx context.Context) (AggregatedStats, error)
- func (r *InMemoryUserInfoRepo) ListAll(ctx context.Context) ([]UserInfo, error)
- func (r *InMemoryUserInfoRepo) ListBySites(ctx context.Context, sites []string) ([]UserInfo, error)
- func (r *InMemoryUserInfoRepo) Save(ctx context.Context, info UserInfo) error
- type L2Cache
- type LRUCache
- type LevelGroupType
- type LevelManager
- func (lm *LevelManager) CalculateNextLevel(kind SiteKind, upload int64, ratio float64, days int) *LevelProgress
- func (lm *LevelManager) GetCurrentLevel(kind SiteKind, upload int64, ratio float64, days int) string
- func (lm *LevelManager) GetLevels(kind SiteKind) []LevelRequirement
- func (lm *LevelManager) SetLevels(kind SiteKind, levels []LevelRequirement)
- type LevelProgress
- type LevelRequirement
- type MTorrentBonusResponse
- type MTorrentDriver
- func (d *MTorrentDriver) Execute(ctx context.Context, req MTorrentRequest) (MTorrentResponse, error)
- func (d *MTorrentDriver) GetBonusPerHour(ctx context.Context) (float64, error)
- func (d *MTorrentDriver) GetPeerStatistics(ctx context.Context) (*PeerStatistics, error)
- func (d *MTorrentDriver) GetPeerStatus(ctx context.Context) (seeder, leecher int, err error)
- func (d *MTorrentDriver) GetSeedingSize(ctx context.Context, userID string) (count int, size int64, err error)
- func (d *MTorrentDriver) GetSiteDefinition() *SiteDefinition
- func (d *MTorrentDriver) GetTorrentDetail(ctx context.Context, guid, _, _ string) (*TorrentItem, error)
- func (d *MTorrentDriver) GetUnreadMessageCount(ctx context.Context) (int, int, error)
- func (d *MTorrentDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
- func (d *MTorrentDriver) ParseBonusPerHour(res MTorrentResponse) (float64, error)
- func (d *MTorrentDriver) ParseDownload(res MTorrentResponse) ([]byte, error)
- func (d *MTorrentDriver) ParseDownloadContext(ctx context.Context, res MTorrentResponse) ([]byte, error)
- func (d *MTorrentDriver) ParsePeerStatistics(res MTorrentResponse) (*PeerStatistics, error)
- func (d *MTorrentDriver) ParseSearch(res MTorrentResponse) ([]TorrentItem, error)
- func (d *MTorrentDriver) ParseUnreadMessageCount(res MTorrentResponse) (int, int, error)
- func (d *MTorrentDriver) ParseUserInfo(res MTorrentResponse) (UserInfo, error)
- func (d *MTorrentDriver) PrepareDownload(torrentID string) (MTorrentRequest, error)
- func (d *MTorrentDriver) PrepareGetBonusPerHour() (MTorrentRequest, error)
- func (d *MTorrentDriver) PrepareGetPeerStatistics() (MTorrentRequest, error)
- func (d *MTorrentDriver) PrepareGetUnreadMessageCount() (MTorrentRequest, error)
- func (d *MTorrentDriver) PrepareSearch(query SearchQuery) (MTorrentRequest, error)
- func (d *MTorrentDriver) PrepareUserInfo() (MTorrentRequest, error)
- func (d *MTorrentDriver) SetSiteDefinition(def *SiteDefinition)
- type MTorrentDriverConfig
- type MTorrentID
- type MTorrentIDList
- type MTorrentMemberCount
- type MTorrentMemberStatus
- type MTorrentMessageStatResponse
- type MTorrentOptions
- type MTorrentPeerStatResponse
- type MTorrentPeerStatusResponse
- type MTorrentPromotionRule
- type MTorrentRequest
- type MTorrentResponse
- type MTorrentSearchData
- type MTorrentSearchRequest
- type MTorrentTorrent
- type MTorrentUserInfo
- type MTorrentUserTorrentListResponse
- type MallSingleFree
- type MetricType
- type MetricsRegistry
- type MetricsSnapshot
- type MigrationStatus
- type MultiSiteSearchQuery
- type MultiSiteSearchResult
- type NewDownloaderConfig
- type NexusPHPDetailParser
- type NexusPHPDriver
- func (d *NexusPHPDriver) Attend(ctx context.Context) (AttendResult, error)
- func (d *NexusPHPDriver) AttendanceUnsupportedReason() string
- func (d *NexusPHPDriver) CurrentCookie() (string, bool)
- func (d *NexusPHPDriver) DownloadSubtitle(ctx context.Context, sub Subtitle) (SubtitleFile, error)
- func (d *NexusPHPDriver) Execute(ctx context.Context, req NexusPHPRequest) (NexusPHPResponse, error)
- func (d *NexusPHPDriver) ExtractFieldValuePublic(doc *goquery.Document, selector FieldSelector) string
- func (d *NexusPHPDriver) FetchSeedingStatus(ctx context.Context, userID string) (seeding int, seedingSize int64, err error)
- func (d *NexusPHPDriver) GetSiteDefinition() *SiteDefinition
- func (d *NexusPHPDriver) GetTorrentDetail(ctx context.Context, guid, link, _ string) (*TorrentItem, error)
- func (d *NexusPHPDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
- func (d *NexusPHPDriver) ListSubtitles(ctx context.Context, torrentID string) ([]Subtitle, error)
- func (d *NexusPHPDriver) ParseDetail(res NexusPHPResponse) (TorrentDetail, error)
- func (d *NexusPHPDriver) ParseDownload(res NexusPHPResponse) ([]byte, error)
- func (d *NexusPHPDriver) ParseDownloadContext(ctx context.Context, res NexusPHPResponse) ([]byte, error)
- func (d *NexusPHPDriver) ParseSearch(res NexusPHPResponse) ([]TorrentItem, error)
- func (d *NexusPHPDriver) ParseSeedingStatus(res NexusPHPResponse) (seeding int, seedingSize int64, err error)
- func (d *NexusPHPDriver) ParseUserDetails(res NexusPHPResponse) (UserInfo, error)
- func (d *NexusPHPDriver) ParseUserInfo(res NexusPHPResponse) (UserInfo, error)
- func (d *NexusPHPDriver) PrepareDetail(torrentID string) (NexusPHPRequest, error)
- func (d *NexusPHPDriver) PrepareDownload(torrentID string) (NexusPHPRequest, error)
- func (d *NexusPHPDriver) PrepareSearch(query SearchQuery) (NexusPHPRequest, error)
- func (d *NexusPHPDriver) PrepareUserDetails(userID string) (NexusPHPRequest, error)
- func (d *NexusPHPDriver) PrepareUserInfo() (NexusPHPRequest, error)
- func (d *NexusPHPDriver) PrepareUserSeedingPage(userID, listType string) (NexusPHPRequest, error)
- func (d *NexusPHPDriver) SetSiteDefinition(def *SiteDefinition)
- type NexusPHPDriverConfig
- type NexusPHPOptions
- type NexusPHPParser
- func (p *NexusPHPParser) ParseAll(doc *goquery.Selection) *TorrentDetailInfo
- func (p *NexusPHPParser) ParseDiscount(doc *goquery.Selection) (DiscountLevel, time.Time)
- func (p *NexusPHPParser) ParseExternalIDs(doc *goquery.Selection) (imdbID, doubanID string)
- func (p *NexusPHPParser) ParseHR(doc *goquery.Selection) bool
- func (p *NexusPHPParser) ParseSizeMB(doc *goquery.Selection) float64
- func (p *NexusPHPParser) ParseTitleAndID(doc *goquery.Selection) (title, torrentID string)
- type NexusPHPParserConfig
- type NexusPHPParserOption
- type NexusPHPRequest
- type NexusPHPResponse
- type Normalizer
- type OldDownloaderConfig
- type OldSiteConfig
- type ParsedTorrent
- type PartialUserInfoError
- type PeerStatistics
- type PersistentRateLimiter
- type PersistentRateLimiterConfig
- type PromotionSnapshot
- type Ranker
- type RankerConfig
- type RequestConfig
- type RequestsClient
- type RequestsResponse
- type RetryConfig
- type RetryableHTTPClient
- type RousiOptions
- type Schema
- type SearchCache
- func (c *SearchCache) Cleanup() int
- func (c *SearchCache) Clear()
- func (c *SearchCache) Delete(query MultiSiteSearchQuery)
- func (c *SearchCache) Get(query MultiSiteSearchQuery) (*MultiSiteSearchResult, bool)
- func (c *SearchCache) Item(site, id string) (TorrentItem, bool)
- func (c *SearchCache) Set(query MultiSiteSearchQuery, result *MultiSiteSearchResult)
- func (c *SearchCache) Size() int
- type SearchCacheConfig
- type SearchError
- type SearchOrchestrator
- func (o *SearchOrchestrator) GetSite(siteID string) Site
- func (o *SearchOrchestrator) ListSites() []string
- func (o *SearchOrchestrator) RegisterSite(site Site)
- func (o *SearchOrchestrator) Search(ctx context.Context, query MultiSiteSearchQuery) (*MultiSiteSearchResult, error)
- func (o *SearchOrchestrator) UnregisterSite(siteID string)
- type SearchOrchestratorConfig
- type SearchQuery
- type Session
- type SessionCookieHolder
- type SessionCookieSink
- type SessionManager
- func (m *SessionManager) GetSession(siteID string) (*Session, bool)
- func (m *SessionManager) IncrementLoginCount(siteID string) int
- func (m *SessionManager) InvalidateSession(siteID string)
- func (m *SessionManager) IsSessionValid(siteID string) bool
- func (m *SessionManager) RemoveSession(siteID string)
- func (m *SessionManager) ResetLoginCount(siteID string)
- func (m *SessionManager) SetSession(siteID string, session *Session)
- func (m *SessionManager) UpdateSessionID(siteID, sessionID string)
- type Site
- type SiteAdapter
- type SiteCategoryConfig
- type SiteConfig
- type SiteCredentials
- type SiteDefinition
- type SiteDefinitionRegistry
- func (r *SiteDefinitionRegistry) Get(siteID string) (*SiteDefinition, bool)
- func (r *SiteDefinitionRegistry) GetAll() []*SiteDefinition
- func (r *SiteDefinitionRegistry) GetOrDefault(siteID string) *SiteDefinition
- func (r *SiteDefinitionRegistry) List() []string
- func (r *SiteDefinitionRegistry) Register(def *SiteDefinition)
- type SiteDelta
- type SiteFactory
- type SiteHTTPClient
- func (c *SiteHTTPClient) Close() error
- func (c *SiteHTTPClient) DoRequest(ctx context.Context, method, url string, body io.Reader, ...) (*HTTPResponse, error)
- func (c *SiteHTTPClient) Get(ctx context.Context, url string, headers map[string]string) (*HTTPResponse, error)
- func (c *SiteHTTPClient) Post(ctx context.Context, url string, body []byte, headers map[string]string) (*HTTPResponse, error)
- func (c *SiteHTTPClient) PostJSON(ctx context.Context, url string, body []byte, headers map[string]string) (*HTTPResponse, error)
- type SiteHTTPClientConfig
- type SiteKind
- type SiteLevelProgressInfo
- type SiteLevelRequirement
- type SiteMeta
- type SiteMetrics
- func (m *SiteMetrics) RecordCacheHit(cacheType string)
- func (m *SiteMetrics) RecordCacheMiss(cacheType string)
- func (m *SiteMetrics) RecordDownloaderRequest(downloader string, success bool, duration time.Duration)
- func (m *SiteMetrics) RecordError(errorType string)
- func (m *SiteMetrics) RecordRequest(site string, success bool, duration time.Duration)
- func (m *SiteMetrics) SetActiveDownloaders(count int)
- func (m *SiteMetrics) SetActiveSites(count int)
- func (m *SiteMetrics) Snapshot() MetricsSnapshot
- type SiteMigrationGuide
- type SiteMigrationManager
- func (m *SiteMigrationManager) GetMigrationStatus() []MigrationStatus
- func (m *SiteMigrationManager) GetNewSite(siteID string) Site
- func (m *SiteMigrationManager) GetSite(siteID string) any
- func (m *SiteMigrationManager) MigrateToNew(siteID string) error
- func (m *SiteMigrationManager) RegisterSite(siteID string, oldSite any, newSite Site, useNew bool)
- func (m *SiteMigrationManager) RollbackToOld(siteID string) error
- type SiteName
- type SiteRegistry
- func (r *SiteRegistry) CreateSite(siteID string, creds SiteCredentials, customBaseURL string) (Site, error)
- func (r *SiteRegistry) Get(id string) (SiteMeta, bool)
- func (r *SiteRegistry) GetDefaultBaseURL(siteID string) (string, bool)
- func (r *SiteRegistry) GetSiteKind(siteID string) (SiteKind, bool)
- func (r *SiteRegistry) List() []string
- func (r *SiteRegistry) Register(meta SiteMeta)
- type SiteSelectors
- type SiteURLRegistry
- func (r *SiteURLRegistry) GetFailoverClient(siteName SiteName, opts ...FailoverOption) (*FailoverHTTPClient, error)
- func (r *SiteURLRegistry) GetFailoverConfig(siteName SiteName) (URLFailoverConfig, error)
- func (r *SiteURLRegistry) GetURLs(siteName SiteName) []string
- func (r *SiteURLRegistry) HasSite(siteName SiteName) bool
- func (r *SiteURLRegistry) ListSites() []SiteName
- func (r *SiteURLRegistry) RegisterURLs(siteName SiteName, urls []string)
- type SpringSundayParser
- type Subtitle
- type SubtitleFile
- type SubtitleProvider
- type SubtitleSource
- type SyncError
- type Timer
- type TorrentDetail
- type TorrentDetailFetcher
- type TorrentDetailInfo
- type TorrentFile
- type TorrentItem
- func (t *TorrentItem) CanbeFinished(enabled bool, speedLimit, sizeLimitGB int) bool
- func (t *TorrentItem) GetFreeEndTime() *time.Time
- func (t *TorrentItem) GetFreeLevel() string
- func (t *TorrentItem) GetName() string
- func (t *TorrentItem) GetSubTitle() string
- func (t *TorrentItem) IsDiscountActive() bool
- func (t *TorrentItem) IsFree() bool
- func (t *TorrentItem) Promotion(verifiedAt time.Time) PromotionSnapshot
- type TorrentManifest
- type TrackerResolver
- type TrendPoint
- type TwoLevelCache
- type TwoLevelCacheConfig
- type URLFailoverConfig
- type URLFailoverManager
- type Unit3DDriver
- func (d *Unit3DDriver) Execute(ctx context.Context, req Unit3DRequest) (Unit3DResponse, error)
- func (d *Unit3DDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
- func (d *Unit3DDriver) ParseDownload(res Unit3DResponse) ([]byte, error)
- func (d *Unit3DDriver) ParseSearch(res Unit3DResponse) ([]TorrentItem, error)
- func (d *Unit3DDriver) ParseUserInfo(res Unit3DResponse) (UserInfo, error)
- func (d *Unit3DDriver) PrepareDownload(torrentID string) (Unit3DRequest, error)
- func (d *Unit3DDriver) PrepareSearch(query SearchQuery) (Unit3DRequest, error)
- func (d *Unit3DDriver) PrepareUserInfo() (Unit3DRequest, error)
- type Unit3DDriverConfig
- type Unit3DOptions
- type Unit3DRequest
- type Unit3DResponse
- type Unit3DTorrent
- type Unit3DUserProfile
- type UserInfo
- type UserInfoConfig
- type UserInfoDailySnapshot
- type UserInfoHistoryRepo
- type UserInfoProcess
- type UserInfoRecord
- type UserInfoRepo
- type UserInfoService
- func (s *UserInfoService) ClearCache()
- func (s *UserInfoService) DeleteUserInfo(ctx context.Context, siteID string) error
- func (s *UserInfoService) FetchAndSave(ctx context.Context, siteID string) (UserInfo, error)
- func (s *UserInfoService) FetchAndSaveAll(ctx context.Context) ([]UserInfo, []error)
- func (s *UserInfoService) FetchAndSaveAllWithConcurrency(ctx context.Context, maxConcurrent int, timeout time.Duration) ([]UserInfo, []SyncError)
- func (s *UserInfoService) GetAggregated(ctx context.Context) (AggregatedStats, error)
- func (s *UserInfoService) GetAllUserInfo(ctx context.Context) ([]UserInfo, error)
- func (s *UserInfoService) GetSite(siteID string) (Site, bool)
- func (s *UserInfoService) GetUserInfo(ctx context.Context, siteID string) (UserInfo, error)
- func (s *UserInfoService) History() (UserInfoHistoryRepo, bool)
- func (s *UserInfoService) ListSites() []string
- func (s *UserInfoService) RegisterSite(site Site)
- func (s *UserInfoService) UnregisterSite(siteID string)
- type UserInfoServiceConfig
- type ValidationConfig
- type ValidationError
- type ValidationErrors
- type Validator
- func (v *Validator) ValidateFileSize(size int64) error
- func (v *Validator) ValidateInfoHash(input string) (string, error)
- func (v *Validator) ValidateSearchQuery(query SearchQuery) error
- func (v *Validator) ValidateString(input string) (string, error)
- func (v *Validator) ValidateURL(input string) (string, error)
Constants ¶
const ( KB int64 = 1024 MB int64 = 1024 * KB GB int64 = 1024 * MB TB int64 = 1024 * GB )
Size constants
const ( // MinVipLevelID is the minimum level ID for VIP users MinVipLevelID = 100 // MinManagerLevelID is the minimum level ID for manager/staff users MinManagerLevelID = 200 )
Level ID constants for special user groups
const ( MTeamSectionNormal = "normal" MTeamSectionAdult = "adult" )
MTeamSectionNormal、MTeamSectionAdult 是 M-Team 搜索接口的 mode:综合区与成人区。
const InfiniteRatio = 9999999
InfiniteRatio 记「无穷」分享率:有上传、下载量为 0(NexusPHP 页面写「无限」「無限」「Inf.」或 ∞)。JSON 存不了 +Inf, 所以用一个足够大的数:网页、App、ChatOps 大于 999999 时显示 ∞,平均分享率只算小于 1000 的(不计入), 分享率要求按达标算。CrabPT、GGPT 的站点定义把「无限」直接换成同一个数。
const SnapshotRetentionDays = 400
SnapshotRetentionDays 是每日快照的保留天数,更早的由定期清理删除。
Variables ¶
var ( // ErrAttendanceUnsupported 表示站点不支持自动签到(架构不支持,或站点定义标记为不支持)。 ErrAttendanceUnsupported = errors.New("attendance not supported") // ErrAttendanceUnrecognized 表示签到请求成功返回,但页面里既没有签到成功也没有今日已签的文字。 ErrAttendanceUnrecognized = errors.New("attendance result not recognized") // ErrAttendancePageNotFound 表示签到地址回了 404 / 410:站点没有这一页(多半改了签到方式),当天重试也签不上。 ErrAttendancePageNotFound = errors.New("attendance page not found") )
var ( // ErrAttendanceNeedsAI 表示站点签到要过验证码或答题,而这次没有可用的 AI。 ErrAttendanceNeedsAI = errors.New("attendance needs AI") // ErrAttendanceChallengeFailed 表示几次都没过那一关(验证码一直没认对、页面里找不到题目等)。 ErrAttendanceChallengeFailed = errors.New("attendance challenge failed") )
var ( ErrNoFreeTorrents = errors.New("no free torrents found") ErrArchiveCreationFailed = errors.New("failed to create archive") ErrTorrentDownloadFailed = errors.New("failed to download torrent") )
Batch download errors
var ( ErrAllURLsFailed = errors.New("all URLs failed") ErrNoURLsConfigured = errors.New("no URLs configured for site") )
Failover errors
var ( NewHDSkyParser = NewNexusPHPParser NewSpringSundayParser = NewNexusPHPParser )
兼容旧代码的别名
var ( ErrInvalidTorrent = errors.New("invalid torrent file") ErrInvalidMagnet = errors.New("invalid magnet link") ErrTorrentNotFound = errors.New("torrent not found") ErrInvalidInfoHash = errors.New("invalid info hash") )
Common errors for torrent operations
var ( ErrSiteNotFound = errors.New("site not found") ErrInvalidCredentials = errors.New("invalid credentials") ErrSessionExpired = errors.New("session expired or cookie invalid") ErrAuthFailed = errors.New("authentication failed: please check cookie or 2FA settings") Err2FARequired = ErrAuthFailed // Alias for backward compatibility ErrRateLimited = errors.New("rate limited") ErrParseError = errors.New("failed to parse response") ErrNetworkError = errors.New("network error") ErrCircuitOpen = errors.New("circuit breaker open") ErrNotImplemented = errors.New("not implemented") // ErrEmptyUsername 表示取回的用户信息没有用户名,通常说明拿到的不是登录后的页面。 ErrEmptyUsername = errors.New("parsed empty username") // ErrUserInfoPersist 表示用户信息已经取到、但保存失败;UserInfoService.FetchAndSave 此时会同时返回取到的数据。 ErrUserInfoPersist = errors.New("persist user info failed") // ErrCloudflareChallenge 表示站点返回的是 Cloudflare 质询页:请求被反爬拦截,凭证本身未必有问题。 ErrCloudflareChallenge = errors.New("cloudflare challenge") // 调用方要当作取详情失败处理,不能当成「不是免费」,也不能沿用旧数据。 ErrTorrentDetailUnavailable = errors.New("torrent detail unavailable") // ErrUnexpectedPage 表示站点回的不是种子列表:一个种子都没有,页面也不像登录以后的站点页面(拦截、维护、验证页等)。 ErrUnexpectedPage = errors.New("站点返回的不是种子列表页面") // ErrInvalidTorrentID 表示种子或字幕的编号不是站点认的写法(NexusPHP 的是数字,RSS 的 guid 是 info hash),不发请求。 ErrInvalidTorrentID = errors.New("种子编号不对") // ErrSubtitleNotFound 表示站点上没有这份字幕(NexusPHP 的 downloadsubs.php 回「Not found」「File not found」)。 ErrSubtitleNotFound = errors.New("站点上没有这份字幕") )
Common errors for site operations
var ( // ErrSeedingSizeUnknown 是做种列表里认不出体积列:做种数照样有,体积按没取到算(保存时沿用上一次的),不当成 0 ErrSeedingSizeUnknown = errors.New("seeding size column not found") )
Extended info errors
var ( ErrEmptyInput = errors.New("input cannot be empty") ErrInputTooLong = errors.New("input exceeds maximum length") ErrInvalidURL = errors.New("invalid URL format") ErrInvalidEmail = errors.New("invalid email format") ErrInvalidHash = errors.New("invalid hash format") ErrInvalidCharacter = errors.New("input contains invalid characters") ErrFileTooLarge = errors.New("file exceeds maximum size") )
Validation errors
var CSTLocation = utils.CSTLocation
CSTLocation is the China Standard Time timezone (UTC+8). Re-exported from utils for convenience within this package.
var DebugUserInfo = false
DebugUserInfo enables debug output for user info parsing Set to true to see detailed parsing information
var DefaultMetrics = NewMetricsRegistry()
DefaultMetrics is the default metrics registry
var DefaultSiteMetrics = NewSiteMetrics(DefaultMetrics)
DefaultSiteMetrics is the default site metrics instance
var DefaultSiteURLs = map[SiteName][]string{ SiteNameMTeam: { "https://api.m-team.cc", "https://kp.m-team.cc", "https://pt.m-team.cc", }, SiteNameHDSky: { "https://hdsky.me", }, SiteNameSpringSunday: { "https://springsunday.net", }, SiteNameCHDBits: { "https://chdbits.co", }, SiteNameTTG: { "https://totheglory.im", }, SiteNameOurBits: { "https://ourbits.club", }, SiteNamePterClub: { "https://pterclub.com", }, SiteNameAudiences: { "https://audiences.me", }, }
DefaultSiteURLs contains the default base URLs for each site Sites can have multiple URLs for failover purposes
var DefaultValidator = NewValidator(DefaultValidationConfig())
DefaultValidator is the default validator instance
var ErrAttendanceCaptchaRequired = errors.New("attendance needs a captcha")
ErrAttendanceCaptchaRequired 表示签到表单要过 pt-tools 过不了的验证(Turnstile、reCAPTCHA 等人机验证组件),当天重试也签不上。 图片验证码不算:交给 AI 识别,没有 AI 时是 ErrAttendanceNeedsAI。
var ErrDuplicateSiteID = fmt.Errorf("duplicate site definition ID")
ErrDuplicateSiteID is returned when attempting to register a site with an already-used ID
var ErrNotTorrentFile = errors.New("站点返回的不是种子文件")
ErrNotTorrentFile 是下载到的不是种子文件:站点回了网页(登录页、两步验证页、「下载提示」页……)、JSON 或一段文字。 以前这些内容原样当成种子交给调用方,辅种因此报「下载到的种子与 IYUU 给的 info hash 不符」(2026-11-02 织梦)。
var ErrTooManyRequests = errors.New("too many requests in half-open state")
ErrTooManyRequests is returned when too many requests in half-open state
var FreeDiscountLevels = []DiscountLevel{ DiscountFree, Discount2xFree, }
FreeDiscountLevels contains all discount levels that result in free download
var InfoHashFromMagnet = ExtractMagnetHash
InfoHashFromMagnet is an alias for ExtractMagnetHash
var SiteKindMap = map[SiteName]SiteKind{ SiteNameMTeam: SiteMTorrent, SiteNameHDSky: SiteNexusPHP, SiteNameSpringSunday: SiteNexusPHP, SiteNameCHDBits: SiteNexusPHP, SiteNameTTG: SiteNexusPHP, SiteNameOurBits: SiteNexusPHP, SiteNamePterClub: SiteNexusPHP, SiteNameAudiences: SiteNexusPHP, }
SiteKindMap maps site names to their architecture kinds
var TorrentHashRegex = regexp.MustCompile(`^[a-fA-F0-9]{40}$`)
TorrentHashRegex matches a 40-character hex info hash
Functions ¶
func AddAtPausedToAutoStart ¶
AddAtPausedToAutoStart converts the new AddAtPaused field back to the old autoStart field This is the inverse of AutoStartToAddAtPaused
func ApplyFilters ¶
ApplyFilters applies a chain of filters to a value
func AttendanceMayUseAI ¶ added in v1.0.0
func AttendanceMayUseAI(def *SiteDefinition) bool
AttendanceMayUseAI 报告签到时可能要用 AI:站点定义写明了要过的一关, 或者走 NexusPHP 默认的 GET 签到——新版签到页的表单可能带图片验证码,打开签到页才知道。 签到监控按它决定要不要备好 AI。
func AttendanceSupport ¶ added in v1.0.0
func AttendanceSupport(def *SiteDefinition) (bool, string)
AttendanceSupport 只看站点定义判断能否自动签到,不支持时返回原因,供界面在不创建站点实例时展示。
func AutoStartToAddAtPaused ¶
AutoStartToAddAtPaused converts the old autoStart field to the new AddAtPaused field The mapping is: autoStart=true → AddAtPaused=false (start immediately)
autoStart=false → AddAtPaused=true (add paused)
func BuildMagnetLink ¶
BuildMagnetLink builds a magnet link from an info hash and optional name
func CalculateEffectiveDownload ¶
func CalculateEffectiveDownload(sizeBytes int64, discountLevel DiscountLevel) int64
CalculateEffectiveDownload calculates the effective download size based on discount
func CalculateEffectiveUpload ¶
func CalculateEffectiveUpload(sizeBytes int64, discountLevel DiscountLevel) int64
CalculateEffectiveUpload calculates the effective upload size based on discount
func CalculateRatioImpact ¶
func CalculateRatioImpact(currentUploaded, currentDownloaded, torrentSize int64, discountLevel DiscountLevel, expectedUploadRatio float64) float64
CalculateRatioImpact calculates the ratio impact of downloading a torrent Returns the change in ratio (positive = ratio increases, negative = ratio decreases)
func CanDownloadInTimeSimple ¶
func CanDownloadInTimeSimple(sizeBytes, downloadSpeedBps int64, discountLevel DiscountLevel, discountEndTime time.Time) bool
CanDownloadInTimeSimple is a simplified version that returns just a boolean
func CheckTorrentFile ¶ added in v1.0.0
CheckTorrentFile 检查下载到的是不是种子文件(bencode 的字典,以 d 开头):是就返回 nil;不是时返回包着 ErrNotTorrentFile 的错误, 写明站点回的是什么。登录页另外包着 ErrSessionExpired,两步验证页包着 Err2FARequired。
func CompareDiscounts ¶
func CompareDiscounts(a, b DiscountLevel) int
CompareDiscounts compares two discount levels Returns: -1 if a < b, 0 if a == b, 1 if a > b
func ComputeTorrentHash ¶
ComputeTorrentHash computes the info hash from torrent file bytes
func ComputeTorrentHashFromFile ¶
ComputeTorrentHashFromFile computes the info hash from a torrent file path
func CurrentSessionCookie ¶ added in v1.0.0
CurrentSessionCookie 取站点现在用的那组 Cookie(续期过就是换发后的);站点没有续期会话时 ok 为假。 验证扩展推来的 Cookie 时要用它:验证那次请求要是续了期,原来那组的 refresh_token 已经用掉了,要存换发后的。
func DiscountPriority ¶
func DiscountPriority(level DiscountLevel) int
DiscountPriority returns a priority value for sorting torrents by discount Higher priority = better discount
func DiscountTimeParseNote ¶ added in v1.0.0
DiscountTimeParseNote 是「字段 field 的时间非空但无法解析」的诊断说明,例如 "discountEndTime: 时间格式无法解析"。
func EstimateDownloadTime ¶
EstimateDownloadTime estimates the download time for a given size and speed
func ExtractMagnetHash ¶
ExtractMagnetHash extracts the info hash from a magnet link
func FetchFailureReason ¶ added in v1.0.0
FetchFailureReason 是取用户信息失败的原因分类(日志里用):Cloudflare 质询、登录失效、限流、超时、网络错误等。
func FormatBytes ¶
FormatBytes formats bytes to human readable string
func FreshAfterFrom ¶ added in v1.0.0
FreshAfterFrom 取出 WithFreshAfter 设置的时间;没有设置(或设置的是零时间)时 ok 为 false。
func GetAllSiteCategoryConfigs ¶
func GetAllSiteCategoryConfigs() map[string]SiteCategoryConfig
GetAllSiteCategoryConfigs 获取所有站点的分类配置
func GetSiteNextLevelUnmet ¶
func GetSiteNextLevelUnmet(info *UserInfo, requirements []SiteLevelRequirement) map[string]any
GetSiteNextLevelUnmet returns unmet requirements for next level
func GetSiteURLsForKind ¶
GetSiteURLsForKind returns URLs for sites of a specific kind This is a convenience function for getting URLs by site architecture type
func GuessUserLevelID ¶
func GuessUserLevelID(info *UserInfo, requirements []SiteLevelRequirement) int
GuessUserLevelID determines user level from info and requirements
func HandleQBittorrentAuthWithRequests ¶
func HandleQBittorrentAuthWithRequests(ctx context.Context, baseURL, username, password string) (string, error)
HandleQBittorrentAuthWithRequests handles QBittorrent 403 responses using requests library
func HandleTransmissionSession ¶
HandleTransmissionSession handles Transmission 409 responses by extracting session ID
func IgnorePartial ¶ added in v1.0.0
IgnorePartial 把「只取到一部分」的错误换成 nil:用户名到手了,登录与站点状态照样能判断。其余错误原样返回。
func IsAttendancePageNotFound ¶ added in v1.0.0
IsAttendancePageNotFound 报告签到失败是不是因为站点没有签到的那一页:驱动换成了 ErrAttendancePageNotFound, 或者错误链里有 404 / 410 的 HTTPStatusError(要过一关的签到取验证码、题目的那几页)。
func IsBetterDiscount ¶
func IsBetterDiscount(a, b DiscountLevel) bool
IsBetterDiscount returns true if a is a better discount than b
func IsFreeTorrent ¶
func IsFreeTorrent(level DiscountLevel) bool
IsFreeTorrent checks if the given discount level results in free download
func IsTorrentHash ¶
IsTorrentHash checks if a string is a valid torrent info hash
func ListRegisteredSchemas ¶ added in v0.10.0
func ListRegisteredSchemas() []string
func NewSizeTieredHRCalc ¶ added in v0.19.0
func NewSizeTieredHRCalc(rules []HRSeedTimeRule, windowH int) func(sizeBytes int64) int
NewSizeTieredHRCalc creates an HRCalcSeedTime function from size-tiered rules. windowH is added to each tier's base seedtime (e.g., 168h for a 7-day grace window). This is a convenience factory for the common "seedtime by torrent size" pattern.
func NormalizeDoubanID ¶ added in v1.0.0
NormalizeDoubanID 从豆瓣电影条目链接或纯数字编号里取出数字编号;取不到时为空串。
func NormalizeIMDbID ¶ added in v1.0.0
NormalizeIMDbID 从 IMDb 链接或编号里取出 tt 开头的编号(如 tt0111161);取不到时为空串。
func NormalizeInfoHash ¶
NormalizeInfoHash normalizes an info hash to lowercase
func NoteDiscountTimeUnparsable ¶ added in v1.0.0
func NoteDiscountTimeUnparsable(item *TorrentItem, field string)
NoteDiscountTimeUnparsable 记下优惠时间字段 field 非空但无法解析:说明追加到 DiscountErr(多条用「; 」连接), 免费级别的有效性改为 unknown——结束时间不可信,不能当作免费放行的凭据,更不能当成长期免费。 调用前先写好 DiscountLevel;没有优惠时结束时间无关,不记。
func ParseDownloadURL ¶ added in v1.0.0
func ParseDownloadURL(def *SiteDefinition, rawURL string) (string, bool)
ParseDownloadURL 按站点架构从种子下载地址里取出种子 ID: NexusPHP 与 HDDolby 是 download.php?id=,Unit3D 是 /torrents/download/{id}(RSS 链接带 .{key} 后缀), Gazelle 是 torrents.php?action=download&id=。M-Team 的下载地址是临时签名链接、不含种子 ID,返回 false; 地址的主机不属于这个站点时也返回 false。
func ParseTimeInCST ¶ added in v0.3.0
ParseTimeInCST parses a time string in CST timezone. Re-exported from utils for convenience within this package.
func RangeBounds ¶ added in v1.0.0
RangeBounds 把 today / 7d / 30d 换成含两端的日期区间。
func RegisterDriverForSchema ¶ added in v0.10.0
func RegisterDriverForSchema(schema string, factory DriverFactory)
func RegisterFilter ¶
func RegisterFilter(name string, fn FilterFunc)
RegisterFilter adds a custom filter
func RegisterSiteDefinition ¶
func RegisterSiteDefinition(def *SiteDefinition)
RegisterSiteDefinition is a convenience function for init() registration
func ResolveHRSeedTimeH ¶ added in v1.0.0
func ResolveHRSeedTimeH(def *SiteDefinition, sizeBytes int64, settingH int) int
CalcHRSeedTimeH calculates the required HR seed time (hours) for a torrent. Priority chain:
- HRCalcSeedTime — custom function (site-specific logic, e.g., ratio-based, tier-based)
- HRSeedTimeRules — built-in size-tiered rules
- HRSeedTimeHours — flat site-wide fallback
ResolveHRSeedTimeH 是一个种子的 H&R 做种要求(小时):站点定义能算出来时按定义(固定值、按体积分档或自定义规则), 算不出时用站点设置里用户填的值 settingH(#727);都没有时为 0,表示要求未知——刷流不收这类有 H&R 的种子、 自动删种保护它们。def 可以为 nil。
func ResolveSiteByTracker ¶ added in v1.0.0
ResolveSiteByTracker 是 NewTrackerResolver().Resolve 的简写,适合偶尔判断一次。
func SanitizeHTML ¶
SanitizeHTML sanitizes HTML content by escaping dangerous tags
func SanitizeSearchKeyword ¶
SanitizeSearchKeyword sanitizes a search keyword
func SetSessionCookieSink ¶ added in v1.0.0
func SetSessionCookieSink(fn SessionCookieSink)
SetSessionCookieSink 设置存续期 Cookie 的方法;nil 表示不存(只在这个进程里接着用新值)。
func StripHTMLTags ¶
StripHTMLTags removes HTML tags from a string
func ValidateCookie ¶
ValidateCookie validates a cookie string
func ValidateInfoHash ¶
ValidateInfoHash validates an info hash string
func ValidateTorrentFile ¶
ValidateTorrentFile validates torrent file content
func WithAttendanceAIUsage ¶ added in v1.0.0
func WithAttendanceAIUsage(ctx context.Context, u *AttendanceAIUsage) context.Context
WithAttendanceAIUsage 把记 AI 用量的地方放进 ctx。
func WithAttendanceSolver ¶ added in v1.0.0
func WithAttendanceSolver(ctx context.Context, s AttendanceSolver) context.Context
WithAttendanceSolver 把签到用的 AI 放进 ctx。
Types ¶
type AggregatedStats ¶
type AggregatedStats struct {
// TotalUploaded is the sum of all uploaded bytes
TotalUploaded int64 `json:"totalUploaded"`
// TotalDownloaded is the sum of all billed downloaded bytes (UserInfo.Downloaded)
TotalDownloaded int64 `json:"totalDownloaded"`
// AverageRatio is the average ratio across all sites
AverageRatio float64 `json:"averageRatio"`
// TotalSeeding is the sum of all seeding torrents
TotalSeeding int `json:"totalSeeding"`
// TotalLeeching is the sum of all leeching torrents
TotalLeeching int `json:"totalLeeching"`
// TotalBonus is the sum of all bonus points
TotalBonus float64 `json:"totalBonus"`
// SiteCount is the number of sites included
SiteCount int `json:"siteCount"`
// LastUpdate is when this was last calculated (Unix seconds)
LastUpdate int64 `json:"lastUpdate"`
// PerSiteStats contains individual site statistics
PerSiteStats []UserInfo `json:"perSiteStats"`
// TotalBonusPerHour is the sum of all bonus per hour
TotalBonusPerHour float64 `json:"totalBonusPerHour,omitempty"`
// TotalSeedingBonus is the sum of all seeding bonus points
TotalSeedingBonus float64 `json:"totalSeedingBonus,omitempty"`
// TotalUnreadMessages is the sum of all unread messages
TotalUnreadMessages int `json:"totalUnreadMessages,omitempty"`
// TotalSeederSize is the sum of all seeding sizes
TotalSeederSize int64 `json:"totalSeederSize,omitempty"`
// TotalLeecherSize is the sum of all leeching sizes
TotalLeecherSize int64 `json:"totalLeecherSize,omitempty"`
}
AggregatedStats represents aggregated statistics across all sites
type AlternativeRequirement ¶
type AlternativeRequirement struct {
SeedingBonus float64 `json:"seedingBonus,omitempty"`
Uploads int `json:"uploads,omitempty"`
Bonus float64 `json:"bonus,omitempty"`
Downloaded string `json:"downloaded,omitempty"`
Ratio float64 `json:"ratio,omitempty"`
}
AlternativeRequirement for OR-based requirements
type AttendResult ¶ added in v1.0.0
type AttendResult struct {
Status AttendStatus
Message string
}
AttendResult 是一次签到的结果与页面上的一句提示。
type AttendStatus ¶ added in v1.0.0
type AttendStatus string
AttendStatus 是一次签到的结果。
const ( // AttendSigned 表示本次签到成功。 AttendSigned AttendStatus = "signed" // AttendAlready 表示今天已经签到过。 AttendAlready AttendStatus = "already" )
type AttendanceAIUsage ¶ added in v1.0.0
type AttendanceAIUsage struct {
// contains filtered or unexported fields
}
AttendanceAIUsage 记一次签到里 AI 被调了几次、用的模型与 token:签到监控放进 ctx(WithAttendanceAIUsage), AI 那一边(cmd 里接的 AI 助手)每拿到一次回答往里加一次。并发安全。
func AttendanceAIUsageFrom ¶ added in v1.0.0
func AttendanceAIUsageFrom(ctx context.Context) *AttendanceAIUsage
AttendanceAIUsageFrom 取 ctx 里记 AI 用量的地方,没有时为 nil(Add 对 nil 什么也不做)。
func (*AttendanceAIUsage) Add ¶ added in v1.0.0
func (u *AttendanceAIUsage) Add(model string, prompt, completion int64)
Add 记一次模型的回答:用的模型与服务商报的 token(没报时为 0)。
type AttendanceCapable ¶ added in v1.0.0
type AttendanceCapable interface {
SupportsAttendance() bool
Attend(ctx context.Context) (AttendResult, error)
}
AttendanceCapable 由 BaseSite 实现:SupportsAttendance 报告能否签到,Attend 先经过本站的限速器再签到。
type AttendanceChallenge ¶ added in v1.0.0
type AttendanceChallenge string
AttendanceChallenge 是签到前要过的一关:认验证码或者答题。站点定义里设了它,签到时要有 AI(AttendanceSolver)。
const ( // ChallengeHDSkyCaptcha 是 HDSky 的签到验证码:POST /image_code_ajax.php 取 imagehash, // 认 /image.php?action=regimage&imagehash=… 上的 6 位字符,POST /showup.php 提交。 ChallengeHDSkyCaptcha AttendanceChallenge = "hdsky_captcha" // ChallengeOpenCDCaptcha 是 OpenCD 签到插件的验证码:GET /plugin_sign-in.php 取表单里的 csrf_token、imagehash 与验证码图片, // POST /plugin_sign-in.php?cmd=signin 提交。 ChallengeOpenCDCaptcha AttendanceChallenge = "opencd_captcha" // ChallengeBakaQuiz 是 CHDBits、52PT 的签到答题(bakatest.php):单选或多选,选项的值是 1、2、4、8, // 按「提交」答题;答错站点照样记签到,只是奖励少。 ChallengeBakaQuiz AttendanceChallenge = "baka_quiz" )
func AttendanceChallengeOf ¶ added in v1.0.0
func AttendanceChallengeOf(def *SiteDefinition) AttendanceChallenge
AttendanceChallengeOf 返回站点签到要过的一关;不用过的返回空串。
func (AttendanceChallenge) IsCaptcha ¶ added in v1.0.0
func (c AttendanceChallenge) IsCaptcha() bool
IsCaptcha 报告这一关是不是认验证码(要能看图的模型);不是的话是答题(文字模型就行)。
func (AttendanceChallenge) NeedsAIReason ¶ added in v1.0.0
func (c AttendanceChallenge) NeedsAIReason() string
NeedsAIReason 是没有 AI 时写给用户的原因(不含怎么打开,那一半由签到监控按设置补上)。
type AttendanceConfig ¶ added in v1.0.0
type AttendanceConfig struct {
// Path 是签到请求的路径,可以带查询参数(如 /attendance-ajax.php?act=sign)。
Path string `json:"path,omitempty"`
// Method 是请求方法,GET(默认)或 POST;POST 时 Path 里的查询参数作为表单提交。
Method string `json:"method,omitempty"`
// SuccessPatterns 匹配「本次签到成功」的页面文字(正则);为空时用 NexusPHP 的默认规则。
SuccessPatterns []string `json:"successPatterns,omitempty"`
// AlreadyPatterns 匹配「今天已经签到过」的页面文字(正则);为空时用 NexusPHP 的默认规则。
AlreadyPatterns []string `json:"alreadyPatterns,omitempty"`
// Unsupported 非空表示该站不支持自动签到,值是原因。
Unsupported string `json:"unsupported,omitempty"`
// Challenge 非空表示签到要先过一关(识别验证码或答题),按这一关的流程签到,不用 Path 与 Patterns。
Challenge AttendanceChallenge `json:"challenge,omitempty"`
}
AttendanceConfig 描述站点的每日签到:按 Method 请求 Path,按返回页面的文字判断结果。 NexusPHP 站点不配置时使用 DefaultNexusPHPAttendance;签到要识别验证码或答题、而 pt-tools 写好了流程的站点 设置 Challenge(要有 AI,见 attendance_challenge.go);没有签到或流程没写的站点设置 Unsupported,值是界面上显示的原因。
func DefaultNexusPHPAttendance ¶ added in v1.0.0
func DefaultNexusPHPAttendance() *AttendanceConfig
DefaultNexusPHPAttendance 返回 NexusPHP 签到插件的默认配置:GET /attendance.php。
func ResolveAttendanceConfig ¶ added in v1.0.0
func ResolveAttendanceConfig(def *SiteDefinition) *AttendanceConfig
ResolveAttendanceConfig 返回站点生效的签到配置:以站点定义里的配置为准,缺的字段用 NexusPHP 的默认值补齐; 不是 NexusPHP 架构又没有配置的站点返回 nil,表示不支持。
func (*AttendanceConfig) Match ¶ added in v1.0.0
func (c *AttendanceConfig) Match(text string) (AttendResult, bool)
Match 在页面文字里找签到结果:先找签到成功,再找今日已签。
type AttendanceQuestion ¶ added in v1.0.0
type AttendanceQuestion struct {
Question string
Options []string
// Multiple 为真时是多选题
Multiple bool
}
AttendanceQuestion 是一道签到选择题。
type AttendanceSolver ¶ added in v1.0.0
type AttendanceSolver interface {
// ReadCaptcha 读出验证码图片上的字符。
ReadCaptcha(ctx context.Context, img CaptchaImage) (string, error)
// ChooseAnswer 回答选择题,返回选中的选项下标(从 0 开始;多选题可以有几个)。
ChooseAnswer(ctx context.Context, q AttendanceQuestion) ([]int, error)
}
AttendanceSolver 帮签到过那一关:认验证码、答选择题。由 AI 助手实现,签到监控按设置放进 ctx(WithAttendanceSolver)。
func AttendanceSolverFrom ¶ added in v1.0.0
func AttendanceSolverFrom(ctx context.Context) AttendanceSolver
AttendanceSolverFrom 取 ctx 里签到用的 AI,没有时为 nil。
type Attender ¶ added in v1.0.0
type Attender interface {
Attend(ctx context.Context) (AttendResult, error)
}
Attender 由能签到的驱动实现。
type AuthMethod ¶ added in v0.10.0
type AuthMethod string
AuthMethod represents the authentication method for a site
const ( // AuthMethodCookie uses browser cookie for authentication AuthMethodCookie AuthMethod = "cookie" // AuthMethodAPIKey uses API key for authentication AuthMethodAPIKey AuthMethod = "api_key" // AuthMethodCookieAndAPIKey uses both cookie and API key AuthMethodCookieAndAPIKey AuthMethod = "cookie_and_api_key" // AuthMethodPasskey uses passkey for RSS/download authentication AuthMethodPasskey AuthMethod = "passkey" )
func (AuthMethod) IsValid ¶ added in v0.10.0
func (a AuthMethod) IsValid() bool
IsValid checks if the auth method is a known valid value
func (AuthMethod) String ¶ added in v0.10.0
func (a AuthMethod) String() string
String returns the string representation of the auth method
type BaseSite ¶
BaseSite wraps a Driver and provides common functionality like rate limiting and logging. It implements the Site interface by delegating to the underlying Driver.
func NewBaseSite ¶
func NewBaseSite[Req, Res any](driver Driver[Req, Res], config BaseSiteConfig) *BaseSite[Req, Res]
NewBaseSite creates a new BaseSite with the given driver and configuration
func (*BaseSite[Req, Res]) Attend ¶ added in v1.0.0
func (b *BaseSite[Req, Res]) Attend(ctx context.Context) (AttendResult, error)
Attend 签到一次。与 GetUserInfo 一样先经过本站的限速器——不能像 GetDetailFetcher 那样把驱动直接交出去。
func (*BaseSite[Req, Res]) AttendanceUnsupportedReason ¶ added in v1.0.0
AttendanceUnsupportedReason 是这个站点实例不能签到的原因(例如 UHDDolby 没配 Cookie);能签到时为空。
func (*BaseSite[Req, Res]) CurrentCookie ¶ added in v1.0.0
CurrentCookie 是驱动现在用的那组 Cookie(续期过就是换发后的,见 session_cookies.go);驱动没有续期会话时 ok 为假。
func (*BaseSite[Req, Res]) DownloadWithHash ¶ added in v0.8.0
func (b *BaseSite[Req, Res]) DownloadWithHash(ctx context.Context, torrentID, hash string) ([]byte, error)
DownloadWithHash downloads a torrent using hash if driver supports it
func (*BaseSite[Req, Res]) GetDetailFetcher ¶ added in v0.10.0
func (b *BaseSite[Req, Res]) GetDetailFetcher() TorrentDetailFetcher
func (*BaseSite[Req, Res]) GetDriver ¶
GetDriver returns the underlying driver (for testing purposes)
func (*BaseSite[Req, Res]) GetRateLimiter ¶
GetRateLimiter returns the rate limiter (for testing purposes)
func (*BaseSite[Req, Res]) GetUserInfo ¶
GetUserInfo fetches the current user's information
func (*BaseSite[Req, Res]) IsLoggedIn ¶
IsLoggedIn returns whether the site is currently logged in
func (*BaseSite[Req, Res]) Login ¶
func (b *BaseSite[Req, Res]) Login(ctx context.Context, creds Credentials) error
Login authenticates with the site
func (*BaseSite[Req, Res]) Search ¶
func (b *BaseSite[Req, Res]) Search(ctx context.Context, query SearchQuery) ([]TorrentItem, error)
Search searches for torrents on the site
func (*BaseSite[Req, Res]) Subtitles ¶ added in v1.0.0
func (b *BaseSite[Req, Res]) Subtitles() SubtitleProvider
Subtitles 是这个站点的字幕(驱动实现了 SubtitleProvider 时;不支持时为 nil):每次请求先等限速的令牌, 一时的错误(网络、5xx)按指数退避再发,重试前同样先等令牌(同下载种子)。
func (*BaseSite[Req, Res]) SupportsAttendance ¶ added in v1.0.0
SupportsAttendance 报告站点能否自动签到:驱动实现了签到,且站点定义没有标记为不支持。
type BaseSiteConfig ¶
type BaseSiteConfig struct {
ID string
Name string
Kind SiteKind
RateLimit float64 // Requests per second
RateBurst int // Maximum burst size
Logger *zap.Logger
}
BaseSiteConfig holds configuration for creating a BaseSite
type BatchDownloadService ¶
type BatchDownloadService struct {
// contains filtered or unexported fields
}
BatchDownloadService provides batch download functionality for free torrents
func NewBatchDownloadService ¶
func NewBatchDownloadService(site Site, logger *zap.Logger) *BatchDownloadService
NewBatchDownloadService creates a new batch download service
func (*BatchDownloadService) DownloadFreeTorrents ¶
func (s *BatchDownloadService) DownloadFreeTorrents( ctx context.Context, archiveType string, outputDir string, ) (*FreeTorrentBatchResult, error)
DownloadFreeTorrents downloads all free torrents and packages them into an archive
func (*BatchDownloadService) FetchFreeTorrents ¶
func (s *BatchDownloadService) FetchFreeTorrents(ctx context.Context) ([]TorrentItem, error)
FetchFreeTorrents fetches all free torrents from the site This method only filters by free status, no other filter rules are applied
type CacheEntry ¶
CacheEntry represents a cached item with TTL
func (*CacheEntry) IsExpired ¶
func (e *CacheEntry) IsExpired() bool
IsExpired checks if the cache entry has expired
type CachedSearchOrchestrator ¶
type CachedSearchOrchestrator struct {
*SearchOrchestrator
// contains filtered or unexported fields
}
CachedSearchOrchestrator wraps SearchOrchestrator with caching
func NewCachedSearchOrchestrator ¶
func NewCachedSearchOrchestrator(orchestrator *SearchOrchestrator, cacheConfig SearchCacheConfig) *CachedSearchOrchestrator
NewCachedSearchOrchestrator creates a new CachedSearchOrchestrator
func (*CachedSearchOrchestrator) CacheSize ¶
func (c *CachedSearchOrchestrator) CacheSize() int
CacheSize returns the number of cached entries
func (*CachedSearchOrchestrator) CachedTorrent ¶ added in v1.0.0
func (c *CachedSearchOrchestrator) CachedTorrent(site, id string) (TorrentItem, bool)
CachedTorrent 取最近搜索结果里的一个种子(按站点与种子编号,与搜索结果同样的过期时间)。
func (*CachedSearchOrchestrator) CleanupCache ¶
func (c *CachedSearchOrchestrator) CleanupCache() int
CleanupCache removes expired entries
func (*CachedSearchOrchestrator) ClearCache ¶
func (c *CachedSearchOrchestrator) ClearCache()
ClearCache clears the search cache
func (*CachedSearchOrchestrator) Search ¶
func (c *CachedSearchOrchestrator) Search(ctx context.Context, query MultiSiteSearchQuery) (*MultiSiteSearchResult, error)
Search performs a cached search
type CaptchaImage ¶ added in v1.0.0
type CaptchaImage struct {
Data []byte
// MIME 是图片类型,如 image/png
MIME string
// Length 是验证码的字符数,0 表示不确定
Length int
// UpperOnly 为真时验证码只有大写字母和数字(NexusPHP 的签到验证码),认出来的统一换成大写
UpperOnly bool
}
CaptchaImage 是一张验证码图片。
type CategoryDefinition ¶
type CategoryDefinition struct {
Name string `json:"name"`
Key string `json:"key"`
Options []CategoryOption `json:"options"`
Notes string `json:"notes,omitempty"`
}
CategoryDefinition 分类定义
type CategoryOption ¶
type CategoryOption struct {
Value any `json:"value"`
Name string `json:"name"`
Type string `json:"type,omitempty"` // e.g., "normal", "adult" for mteam
}
CategoryOption 分类选项
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements the circuit breaker pattern
func NewCircuitBreaker ¶
func NewCircuitBreaker(name string, config CircuitBreakerConfig) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker
func (*CircuitBreaker) Execute ¶
func (cb *CircuitBreaker) Execute(fn func() error) error
Execute runs the given function if the circuit allows it
func (*CircuitBreaker) Name ¶
func (cb *CircuitBreaker) Name() string
Name returns the circuit breaker name
func (*CircuitBreaker) Reset ¶
func (cb *CircuitBreaker) Reset()
Reset resets the circuit breaker to closed state
func (*CircuitBreaker) State ¶
func (cb *CircuitBreaker) State() CircuitState
State returns the current circuit state
func (*CircuitBreaker) Stats ¶
func (cb *CircuitBreaker) Stats() CircuitBreakerStats
Stats returns circuit breaker statistics
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
// FailureThreshold is the number of failures before opening the circuit
FailureThreshold int
// SuccessThreshold is the number of successes in half-open to close the circuit
SuccessThreshold int
// Timeout is how long to wait before transitioning from open to half-open
Timeout time.Duration
// MaxHalfOpenRequests is the max concurrent requests in half-open state
MaxHalfOpenRequests int
}
CircuitBreakerConfig configures the circuit breaker
func DefaultCircuitBreakerConfig ¶
func DefaultCircuitBreakerConfig() CircuitBreakerConfig
DefaultCircuitBreakerConfig returns default configuration
type CircuitBreakerRegistry ¶
type CircuitBreakerRegistry struct {
// contains filtered or unexported fields
}
CircuitBreakerRegistry manages multiple circuit breakers
func NewCircuitBreakerRegistry ¶
func NewCircuitBreakerRegistry(config CircuitBreakerConfig) *CircuitBreakerRegistry
NewCircuitBreakerRegistry creates a new registry
func (*CircuitBreakerRegistry) Get ¶
func (r *CircuitBreakerRegistry) Get(name string) *CircuitBreaker
Get returns or creates a circuit breaker for the given name
func (*CircuitBreakerRegistry) GetAll ¶
func (r *CircuitBreakerRegistry) GetAll() []*CircuitBreaker
GetAll returns all circuit breakers
func (*CircuitBreakerRegistry) Reset ¶
func (r *CircuitBreakerRegistry) Reset()
Reset resets all circuit breakers
func (*CircuitBreakerRegistry) Stats ¶
func (r *CircuitBreakerRegistry) Stats() []CircuitBreakerStats
Stats returns statistics for all circuit breakers
type CircuitBreakerStats ¶
type CircuitBreakerStats struct {
Name string `json:"name"`
State string `json:"state"`
Failures int `json:"failures"`
Successes int `json:"successes"`
LastFailureTime time.Time `json:"lastFailureTime,omitempty"`
}
CircuitBreakerStats contains circuit breaker statistics
type CircuitState ¶
type CircuitState int
CircuitState represents the state of a circuit breaker
const ( // CircuitClosed allows requests to pass through CircuitClosed CircuitState = iota // CircuitOpen blocks all requests CircuitOpen // CircuitHalfOpen allows limited requests for testing recovery CircuitHalfOpen )
func (CircuitState) String ¶
func (s CircuitState) String() string
String returns the string representation of the circuit state
type ConfigMigrator ¶
type ConfigMigrator struct {
// contains filtered or unexported fields
}
ConfigMigrator handles migration from old configuration formats to new ones
func NewConfigMigrator ¶
func NewConfigMigrator(logger *zap.Logger) *ConfigMigrator
NewConfigMigrator creates a new ConfigMigrator
func (*ConfigMigrator) CheckForDeprecatedFields ¶
func (m *ConfigMigrator) CheckForDeprecatedFields(configJSON []byte) []DeprecationWarning
CheckForDeprecatedFields checks a config JSON for deprecated fields and logs warnings
func (*ConfigMigrator) DetectDownloaderConfigVersion ¶
func (m *ConfigMigrator) DetectDownloaderConfigVersion(configJSON []byte) string
DetectConfigVersion attempts to detect if a config is in old or new format Returns "old" for old format, "new" for new format, or "unknown"
func (*ConfigMigrator) MigrateDownloaderConfig ¶
func (m *ConfigMigrator) MigrateDownloaderConfig(old OldDownloaderConfig) NewDownloaderConfig
MigrateDownloaderConfig converts an old downloader config to the new format
func (*ConfigMigrator) MigrateDownloaderConfigIfNeeded ¶
func (m *ConfigMigrator) MigrateDownloaderConfigIfNeeded(configJSON []byte) ([]byte, bool, error)
MigrateDownloaderConfigIfNeeded migrates config only if it's in old format
func (*ConfigMigrator) MigrateDownloaderConfigJSON ¶
func (m *ConfigMigrator) MigrateDownloaderConfigJSON(oldJSON []byte) ([]byte, error)
MigrateDownloaderConfigJSON converts old downloader config JSON to new format
func (*ConfigMigrator) MigrateSiteConfig ¶
func (m *ConfigMigrator) MigrateSiteConfig(old OldSiteConfig) SiteConfig
MigrateSiteConfig converts an old site config to the new SiteConfig format
func (*ConfigMigrator) MigrateSiteConfigJSON ¶
func (m *ConfigMigrator) MigrateSiteConfigJSON(oldJSON []byte) ([]byte, error)
MigrateSiteConfigJSON converts old site config JSON to new format
type ContextDownloadParser ¶ added in v1.0.0
type ContextDownloadParser[Res any] interface { ParseDownloadContext(ctx context.Context, res Res) ([]byte, error) }
ContextDownloadParser 是驱动可选实现的解析下载:带上调用方的 ctx。两段式下载(先取签名地址、再拉种子文件)的 第二段请求要跟着调用方取消、受它的期限约束;BaseSite 下载时驱动实现了它就用它,不调 ParseDownload。
type Counter ¶
type Counter struct {
// contains filtered or unexported fields
}
Counter is a monotonically increasing counter
type Credentials ¶
type Credentials struct {
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
Cookie string `json:"cookie,omitempty"`
APIKey string `json:"apiKey,omitempty"`
}
Credentials holds authentication information for a site
type DBUserInfoRepo ¶
type DBUserInfoRepo struct {
// contains filtered or unexported fields
}
DBUserInfoRepo is a database-backed implementation of UserInfoRepo
func NewDBUserInfoRepo ¶
func NewDBUserInfoRepo(db *gorm.DB) (*DBUserInfoRepo, error)
NewDBUserInfoRepo creates a new database-backed user info repository
func (*DBUserInfoRepo) Count ¶
func (r *DBUserInfoRepo) Count(ctx context.Context) (int64, error)
Count returns the number of stored user info entries
func (*DBUserInfoRepo) Delete ¶
func (r *DBUserInfoRepo) Delete(ctx context.Context, site string) error
Delete removes user info for a site
func (*DBUserInfoRepo) DeleteAll ¶
func (r *DBUserInfoRepo) DeleteAll(ctx context.Context) error
DeleteAll removes all user info records
func (*DBUserInfoRepo) GetAggregated ¶
func (r *DBUserInfoRepo) GetAggregated(ctx context.Context) (AggregatedStats, error)
GetAggregated calculates aggregated statistics
func (*DBUserInfoRepo) ListAll ¶
func (r *DBUserInfoRepo) ListAll(ctx context.Context) ([]UserInfo, error)
ListAll retrieves all stored user info
func (*DBUserInfoRepo) ListBySites ¶
ListBySites retrieves user info for specific sites
func (*DBUserInfoRepo) ListSnapshots ¶ added in v1.0.0
func (r *DBUserInfoRepo) ListSnapshots(ctx context.Context, site, from, to string) ([]UserInfoDailySnapshot, error)
ListSnapshots 返回 [from, to](含两端)之间的快照,按站点、日期升序;site 为空时返回所有站点。
func (*DBUserInfoRepo) PruneSnapshots ¶ added in v1.0.0
PruneSnapshots 删除日期早于 before 的快照,返回删除的行数。
func (*DBUserInfoRepo) Save ¶
func (r *DBUserInfoRepo) Save(ctx context.Context, info UserInfo) error
Save stores user info for a site (upsert)
记录与当天的快照在同一个事务里写:快照写失败时记录也回滚,调用方(UserInfoService.FetchAndSave) 据此返回 ErrUserInfoPersist。同一天之后任意一次成功获取都会再次 upsert 当天的快照。
func (*DBUserInfoRepo) SetClock ¶ added in v1.0.0
func (r *DBUserInfoRepo) SetClock(now func() time.Time, loc *time.Location)
SetClock 换掉取当前时间的函数与计算日期的时区(测试用)。
func (*DBUserInfoRepo) SnapshotBaselines ¶ added in v1.0.0
func (r *DBUserInfoRepo) SnapshotBaselines(ctx context.Context, before string) (map[string]UserInfoDailySnapshot, error)
SnapshotBaselines 返回每站在 before 之前(不含)最近的一份快照。
func (*DBUserInfoRepo) Today ¶ added in v1.0.0
func (r *DBUserInfoRepo) Today() string
Today 是仓库时区的当天日期(YYYY-MM-DD)。
type DailyPoint ¶ added in v1.0.0
type DailyPoint struct {
Date string `json:"date"`
Uploaded int64 `json:"uploaded"`
Downloaded int64 `json:"downloaded"`
Bonus float64 `json:"bonus"`
Seeding int `json:"seeding"`
DeltaUploaded int64 `json:"deltaUploaded"`
DeltaDownloaded int64 `json:"deltaDownloaded"`
DeltaBonus float64 `json:"deltaBonus"`
// SpanDays 是这份增量覆盖的天数:上一份快照不是前一天时大于 1(中间缺天,不插值);
// 没有更早的快照可比时为 0,增量记 0。
SpanDays int `json:"spanDays"`
// Negative 表示有数值比上一份快照小(站点数据回退、魔力兑换):那一项增量按 0 计。
Negative bool `json:"negative"`
}
DailyPoint 是某站某天的数据与相对上一份快照的增量。
func BuildDailyPoints ¶ added in v1.0.0
func BuildDailyPoints(snaps []UserInfoDailySnapshot, baseline *UserInfoDailySnapshot) []DailyPoint
BuildDailyPoints 按日期升序给出每天相对上一份快照的增量。snaps 须是同一站点; baseline 是区间开始前最近的一份快照,没有时第一天不算增量。
type Deduper ¶
type Deduper struct{}
Deduper removes duplicate torrents based on InfoHash
func (*Deduper) Deduplicate ¶
func (d *Deduper) Deduplicate(items []TorrentItem) []TorrentItem
Deduplicate removes duplicate torrents, keeping the best version of each
func (*Deduper) DeduplicateByTitle ¶
func (d *Deduper) DeduplicateByTitle(items []TorrentItem, normalizer *Normalizer) []TorrentItem
DeduplicateByTitle removes duplicates based on normalized title This is useful when InfoHash is not available
type DeltaSummary ¶ added in v1.0.0
type DeltaSummary struct {
Range string `json:"range"`
From string `json:"from"`
To string `json:"to"`
Sites []SiteDelta `json:"sites"`
TotalUploaded int64 `json:"totalUploaded"`
TotalDownloaded int64 `json:"totalDownloaded"`
TotalBonus float64 `json:"totalBonus"`
}
DeltaSummary 是一个区间内各站的增量与合计。
func LoadDaySummary ¶ added in v1.0.0
func LoadDaySummary(ctx context.Context, repo UserInfoHistoryRepo, day string) (DeltaSummary, error)
LoadDaySummary 是某一天(YYYY-MM-DD)各站的增量:那天最后一份快照减它之前最近的一份, 与 LoadDeltaSummary 的 today 是同一个算法,只是日期由调用方给(每日战报的「前一天」用它)。
func LoadDeltaSummary ¶ added in v1.0.0
func LoadDeltaSummary(ctx context.Context, repo UserInfoHistoryRepo, rangeName string) (DeltaSummary, error)
LoadDeltaSummary 从仓库读出区间 range 的增量汇总。
func SummarizeDeltas ¶ added in v1.0.0
func SummarizeDeltas(rangeName, from, to string, baselines map[string]UserInfoDailySnapshot, inRange []UserInfoDailySnapshot) DeltaSummary
SummarizeDeltas 计算区间 [from, to] 内各站的增量:最新一份快照减基线。基线取区间开始前最近的 一份快照(baselines),没有就取区间里最早的一份。区间里没有快照的站点不出现。
func (DeltaSummary) Filter ¶ added in v1.0.0
func (s DeltaSummary) Filter(keep map[string]bool) DeltaSummary
Filter 只保留 keep 里的站点(按小写站点名匹配)并重算合计;keep 为 nil 时原样返回。
type DeprecationWarning ¶
type DeprecationWarning struct {
Field string `json:"field"`
Message string `json:"message"`
Replacement string `json:"replacement"`
Version string `json:"version"` // Version when it will be removed
}
DeprecationWarning represents a deprecation warning message
func GetDeprecationWarnings ¶
func GetDeprecationWarnings() []DeprecationWarning
GetDeprecationWarnings returns a list of deprecation warnings for old config fields
type DetailFetcherProvider ¶ added in v0.10.0
type DetailFetcherProvider interface {
// GetDetailFetcher returns a TorrentDetailFetcher if the site supports it.
// Returns nil if the site doesn't support detail fetching (e.g., NexusPHP uses HTML scraping).
GetDetailFetcher() TorrentDetailFetcher
}
DetailFetcherProvider is an optional interface for Site implementations that can provide a TorrentDetailFetcher. This allows unified_site.go to delegate detail fetching to drivers.
type DetailParserConfig ¶ added in v0.8.0
type DetailParserConfig struct {
TimeLayout string `json:"timeLayout,omitempty"`
DiscountMapping map[string]DiscountLevel `json:"discountMapping,omitempty"`
HRKeywords []string `json:"hrKeywords,omitempty"`
TitleSelector string `json:"titleSelector,omitempty"`
IDSelector string `json:"idSelector,omitempty"`
DiscountSelector string `json:"discountSelector,omitempty"`
EndTimeSelector string `json:"endTimeSelector,omitempty"`
SizeSelector string `json:"sizeSelector,omitempty"`
SizeRegex string `json:"sizeRegex,omitempty"`
// IMDbRegex、DoubanRegex 在详情页 HTML 里找外部编号(第一个分组是编号,取第一处匹配);为空时用默认的链接格式。
IMDbRegex string `json:"imdbRegex,omitempty"`
DoubanRegex string `json:"doubanRegex,omitempty"`
}
DetailParserConfig defines how to parse torrent detail pages Used for RSS detail fetching to extract discount status, size, HR flag, etc.
func DefaultDetailParserConfig ¶ added in v0.8.0
func DefaultDetailParserConfig() *DetailParserConfig
DefaultDetailParserConfig returns default config for standard NexusPHP sites
type DiscountLevel ¶
type DiscountLevel string
DiscountLevel represents the discount level of a torrent
const ( // DiscountNone represents no discount (normal download/upload counting) DiscountNone DiscountLevel = "NONE" // DiscountFree represents free download (0% download counting) DiscountFree DiscountLevel = "FREE" // Discount2xFree represents 2x free (0% download, 2x upload counting) Discount2xFree DiscountLevel = "2XFREE" // DiscountPercent50 represents 50% download counting DiscountPercent50 DiscountLevel = "PERCENT_50" // DiscountPercent30 represents 30% download counting DiscountPercent30 DiscountLevel = "PERCENT_30" // DiscountPercent70 represents 70% download counting DiscountPercent70 DiscountLevel = "PERCENT_70" // Discount2xUp represents 2x upload counting Discount2xUp DiscountLevel = "2XUP" // Discount2x50 represents 2x upload and 50% download counting Discount2x50 DiscountLevel = "2X50" )
func SuggestBestDiscount ¶
func SuggestBestDiscount(currentDiscount DiscountLevel, discountEndTime time.Time, minTimeNeeded time.Duration) DiscountLevel
SuggestBestDiscount suggests the best discount level to wait for based on current discount and time constraints
func (DiscountLevel) GetDownloadRatio ¶
func (d DiscountLevel) GetDownloadRatio() float64
GetDownloadRatio returns the download counting ratio (0.0 = free, 1.0 = normal)
func (DiscountLevel) GetUploadRatio ¶
func (d DiscountLevel) GetUploadRatio() float64
GetUploadRatio returns the upload counting ratio (1.0 = normal, 2.0 = double)
type DownloadFeasibility ¶
type DownloadFeasibility struct {
// CanComplete indicates if the download can complete before discount ends
CanComplete bool `json:"canComplete"`
// EstimatedTime is the estimated download time
EstimatedTime time.Duration `json:"estimatedTime"`
// TimeRemaining is the time remaining before discount ends
TimeRemaining time.Duration `json:"timeRemaining"`
// EffectiveSize is the size that counts towards download quota
EffectiveSize int64 `json:"effectiveSize"`
// Margin is the time margin (positive = can complete with time to spare)
Margin time.Duration `json:"margin"`
}
DownloadFeasibility represents the result of download feasibility calculation
func CanDownloadInTime ¶
func CanDownloadInTime(sizeBytes, downloadSpeedBps int64, discountLevel DiscountLevel, discountEndTime time.Time) DownloadFeasibility
CanDownloadInTime calculates if a torrent can be downloaded before the discount expires Parameters:
- sizeBytes: total torrent size in bytes
- downloadSpeedBps: download speed in bytes per second
- discountLevel: current discount level
- discountEndTime: when the discount expires (zero time means permanent)
Returns DownloadFeasibility with detailed information
type Driver ¶
type Driver[Req any, Res any] interface { // PrepareSearch converts a standard SearchQuery to site-specific request PrepareSearch(query SearchQuery) (Req, error) // Execute performs the actual network call Execute(ctx context.Context, req Req) (Res, error) // ParseSearch converts the raw response into standard TorrentItem list ParseSearch(res Res) ([]TorrentItem, error) // GetUserInfo fetches complete user information (including extended info if supported) // This method is responsible for making all necessary API calls GetUserInfo(ctx context.Context) (UserInfo, error) // PrepareDownload prepares request for downloading a torrent PrepareDownload(torrentID string) (Req, error) // ParseDownload extracts torrent file data from response ParseDownload(res Res) ([]byte, error) }
Driver defines how to interact with a specific type of site architecture. Req is the type of request payload (e.g., url.Values for forms, struct for JSON). Res is the raw response type (e.g., *goquery.Document, JSON struct).
type DriverFactory ¶ added in v0.10.0
type DriverFactory func(config SiteConfig, logger *zap.Logger) (Site, error)
func GetDriverFactoryForSchema ¶ added in v0.10.0
func GetDriverFactoryForSchema(schema string) (DriverFactory, bool)
type FailoverHTTPClient ¶
type FailoverHTTPClient struct {
// contains filtered or unexported fields
}
FailoverHTTPClient is a generic HTTP client with automatic URL failover All site drivers can use this client for making HTTP requests Uses requests library instead of net/http directly
func NewFailoverHTTPClient ¶
func NewFailoverHTTPClient(config URLFailoverConfig, opts ...FailoverOption) *FailoverHTTPClient
NewFailoverHTTPClient creates a new failover HTTP client
func (*FailoverHTTPClient) Do ¶
func (c *FailoverHTTPClient) Do(ctx context.Context, method, path string, body []byte, headers map[string]string) (*HTTPResponse, error)
Do performs a custom request with automatic URL failover Note: The request URL should be a path (e.g., "/api/search"), not a full URL
func (*FailoverHTTPClient) Get ¶
func (c *FailoverHTTPClient) Get(ctx context.Context, path string, headers map[string]string) (*HTTPResponse, error)
Get performs a GET request with automatic URL failover
func (*FailoverHTTPClient) GetCurrentBaseURL ¶
func (c *FailoverHTTPClient) GetCurrentBaseURL() string
GetCurrentBaseURL returns the currently active base URL
type FailoverOption ¶
type FailoverOption func(*FailoverHTTPClient)
FailoverOption is a functional option for FailoverHTTPClient
func WithUserAgent ¶
func WithUserAgent(ua string) FailoverOption
WithUserAgent sets the User-Agent header
type FieldSelector ¶
type FieldSelector struct {
// Selector is CSS selector(s) for HTML or JSON path for API
Selector []string `json:"selector,omitempty"`
// Text is the default value if selector doesn't match
Text string `json:"text,omitempty"`
// Attr is the attribute to extract (for HTML elements)
Attr string `json:"attr,omitempty"`
// Filters to apply to extracted value
Filters []Filter `json:"filters,omitempty"`
// ElementProcess is a custom processing function name
ElementProcess string `json:"elementProcess,omitempty"`
// SwitchFilters for different selectors
SwitchFilters map[string][]Filter `json:"switchFilters,omitempty"`
}
FieldSelector defines how to extract a field value
type Filter ¶
type Filter struct {
// Name is the filter function name
Name string `json:"name"`
// Args are optional arguments
Args []any `json:"args,omitempty"`
}
Filter defines a value transformation
type FilterFunc ¶
FilterFunc is a function that transforms a value
type FlexInt ¶
type FlexInt int
FlexInt handles fields that can be either string or int in JSON
func (*FlexInt) UnmarshalJSON ¶
UnmarshalJSON implements custom JSON unmarshaling for FlexInt
type FlexibleCode ¶
type FlexibleCode string
FlexibleCode handles M-Team API code field which can be either string or number
func (FlexibleCode) IsSuccess ¶
func (fc FlexibleCode) IsSuccess() bool
IsSuccess checks if the code represents success (typically "0" or "SUCCESS")
func (FlexibleCode) String ¶
func (fc FlexibleCode) String() string
String returns the string representation of the code
func (*FlexibleCode) UnmarshalJSON ¶
func (fc *FlexibleCode) UnmarshalJSON(data []byte) error
UnmarshalJSON implements custom JSON unmarshaling for FlexibleCode
type FreeTorrentBatchResult ¶
type FreeTorrentBatchResult struct {
// ArchivePath is the path to the created archive file
ArchivePath string `json:"archivePath"`
// ArchiveType is the type of archive (tar.gz or zip)
ArchiveType string `json:"archiveType"`
// TorrentCount is the number of torrents in the archive
TorrentCount int `json:"torrentCount"`
// TotalSize is the total size of all torrents (bytes)
TotalSize int64 `json:"totalSize"`
// Manifest contains metadata for all torrents
Manifest []TorrentManifest `json:"manifest"`
}
FreeTorrentBatchResult represents the result of a batch download operation
type FreeValidity ¶ added in v1.0.0
type FreeValidity string
FreeValidity 是免费资格的规范状态(docs/design/free-expiry-safety.md §4.1)。
const ( // FreeNotFree:不是免费,或免费已经结束 FreeNotFree FreeValidity = "not_free" // FreeUntil:免费,结束时间可信(EndsAt) FreeUntil FreeValidity = "free_until" // FreePermanent:站点明确表示长期有效的免费 FreePermanent FreeValidity = "free_permanent" // FreeUnknown:免费但结束时间缺失或无法解析,不能当作免费放行的凭据 FreeUnknown FreeValidity = "unknown" )
type Gauge ¶
type Gauge struct {
// contains filtered or unexported fields
}
Gauge is a value that can go up and down
type GazelleDriver ¶
type GazelleDriver struct {
BaseURL string
APIKey string
Cookie string
// contains filtered or unexported fields
}
GazelleDriver implements the Driver interface for Gazelle sites
func NewGazelleDriver ¶
func NewGazelleDriver(config GazelleDriverConfig) *GazelleDriver
NewGazelleDriver creates a new Gazelle driver
func (*GazelleDriver) Execute ¶
func (d *GazelleDriver) Execute(ctx context.Context, req GazelleRequest) (GazelleResponse, error)
Execute performs the HTTP request
func (*GazelleDriver) GetTorrentDetail ¶ added in v0.19.2
func (d *GazelleDriver) GetTorrentDetail(ctx context.Context, guid, link, title string) (*TorrentItem, error)
func (*GazelleDriver) GetUserInfo ¶
func (d *GazelleDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
GetUserInfo fetches complete user information
func (*GazelleDriver) ParseDownload ¶
func (d *GazelleDriver) ParseDownload(res GazelleResponse) ([]byte, error)
ParseDownload extracts torrent file data from the response
func (*GazelleDriver) ParseSearch ¶
func (d *GazelleDriver) ParseSearch(res GazelleResponse) ([]TorrentItem, error)
ParseSearch extracts torrent items from the response
func (*GazelleDriver) ParseUserInfo ¶
func (d *GazelleDriver) ParseUserInfo(res GazelleResponse) (UserInfo, error)
ParseUserInfo extracts user info from the response
func (*GazelleDriver) PrepareDownload ¶
func (d *GazelleDriver) PrepareDownload(torrentID string) (GazelleRequest, error)
PrepareDownload prepares a request for downloading a torrent
func (*GazelleDriver) PrepareSearch ¶
func (d *GazelleDriver) PrepareSearch(query SearchQuery) (GazelleRequest, error)
PrepareSearch converts a SearchQuery to a Gazelle request
func (*GazelleDriver) PrepareUserInfo ¶
func (d *GazelleDriver) PrepareUserInfo() (GazelleRequest, error)
PrepareUserInfo prepares a request for user info
type GazelleDriverConfig ¶
type GazelleDriverConfig struct {
BaseURL string
APIKey string
Cookie string
HTTPClient *SiteHTTPClient // Use SiteHTTPClient instead of *http.Client
UserAgent string
// SiteID 是站点在 pt-tools 里注册的 ID:搜索结果的代理下载地址 /api/site/{id}/… 按它找站点
SiteID string
}
GazelleDriverConfig holds configuration for creating a Gazelle driver
type GazelleOptions ¶
type GazelleRequest ¶
type GazelleRequest struct {
// Action is the API action
Action string
// Params are the query parameters
Params url.Values
// RawBody 为 true 时响应体按原始字节返回(种子文件下载),不按 JSON 解析
RawBody bool
}
GazelleRequest represents a request to a Gazelle site
type GazelleResponse ¶
type GazelleResponse struct {
// Status is the response status ("success" or "failure")
Status string `json:"status"`
// Error is the error message (if status is "failure")
Error string `json:"error,omitempty"`
// Response is the response data
Response json.RawMessage `json:"response"`
// RawBody is the raw response body
RawBody []byte `json:"-"`
// StatusCode is the HTTP status code
StatusCode int `json:"-"`
}
GazelleResponse represents a response from Gazelle API
type GazelleSearchResponse ¶
type GazelleSearchResponse struct {
CurrentPage int `json:"currentPage"`
Pages int `json:"pages"`
Results []GazelleTorrentGroup `json:"results"`
}
GazelleSearchResponse represents search results from Gazelle API
type GazelleTorrent ¶
type GazelleTorrent struct {
TorrentID int `json:"torrentId"`
EditionID int `json:"editionId,omitempty"`
Artists []struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"artists,omitempty"`
Remastered bool `json:"remastered"`
RemasterYear int `json:"remasterYear,omitempty"`
RemasterTitle string `json:"remasterTitle,omitempty"`
Media string `json:"media"`
Encoding string `json:"encoding"`
Format string `json:"format"`
HasLog bool `json:"hasLog"`
LogScore int `json:"logScore"`
HasCue bool `json:"hasCue"`
Scene bool `json:"scene"`
VanityHouse bool `json:"vanityHouse"`
FileCount int `json:"fileCount"`
Time string `json:"time"`
Size int64 `json:"size"`
Snatches int `json:"snatches"`
Seeders int `json:"seeders"`
Leechers int `json:"leechers"`
IsFreeleech bool `json:"isFreeleech"`
IsNeutralLeech bool `json:"isNeutralLeech"`
IsPersonalFL bool `json:"isPersonalFreeleech"`
CanUseToken bool `json:"canUseToken"`
}
GazelleTorrent represents a torrent in Gazelle
type GazelleTorrentGroup ¶
type GazelleTorrentGroup struct {
GroupID int `json:"groupId"`
GroupName string `json:"groupName"`
Artist string `json:"artist,omitempty"`
Tags []string `json:"tags"`
Torrents []GazelleTorrent `json:"torrents"`
}
GazelleTorrentGroup represents a torrent group in Gazelle
type GazelleUserResponse ¶
type GazelleUserResponse struct {
Username string `json:"username"`
ID int `json:"id"`
Stats struct {
Uploaded int64 `json:"uploaded"`
Downloaded int64 `json:"downloaded"`
Ratio float64 `json:"ratio"`
Buffer int64 `json:"buffer"`
// LastAccess is the user's last access time (only populated by /ajax.php?action=user&id={uid})
// Format is typically "2006-01-02 15:04:05" in site-local timezone (CST for most Gazelle deployments)
LastAccess string `json:"LastAccess,omitempty"`
} `json:"stats"`
Ranks struct {
Class string `json:"class"`
} `json:"ranks"`
Personal struct {
Bonus float64 `json:"bonus"`
} `json:"personal"`
Community struct {
Seeding int `json:"seeding"`
Leeching int `json:"leeching"`
} `json:"community"`
}
GazelleUserResponse represents user info from Gazelle API
type HDDolbyAPIError ¶ added in v0.8.0
type HDDolbyDriver ¶ added in v0.8.0
type HDDolbyDriver struct {
BaseURL string
APIURL string
APIKey string
Cookie string
// contains filtered or unexported fields
}
func NewHDDolbyDriver ¶ added in v0.8.0
func NewHDDolbyDriver(config HDDolbyDriverConfig) *HDDolbyDriver
func (*HDDolbyDriver) Attend ¶ added in v1.0.0
func (d *HDDolbyDriver) Attend(ctx context.Context) (AttendResult, error)
Attend 用 Cookie 打开签到页签到(NexusPHP 的 attendance.php,打开就签到),按页面文字判断结果。
func (*HDDolbyDriver) AttendanceUnsupportedReason ¶ added in v1.0.0
func (d *HDDolbyDriver) AttendanceUnsupportedReason() string
AttendanceUnsupportedReason 报告这个站点实例能不能签到:站点定义没写签到,或者没配 Cookie 时返回原因。
func (*HDDolbyDriver) Download ¶ added in v0.8.0
Download 按种子编号下载(辅种、转种、批量下载这些只知道编号的入口;BaseSite 下载时用它)。
func (*HDDolbyDriver) DownloadWithHash ¶ added in v0.8.0
func (d *HDDolbyDriver) DownloadWithHash(ctx context.Context, torrentID, downhash string) ([]byte, error)
DownloadWithHash 下载种子文件:带 downhash 的 download.php(downhash 只在 API 搜索结果里)不要 Cookie,不带 downhash 又没有 Cookie 时站点回登录页。调用方没有 downhash(只知道种子编号)时:配了 Cookie 就像在网页上点「下载」一样用 Cookie 下, 什么种子都行(见 downloadWithCookie);没配 Cookie 时到详情缓存(最近 100 条搜索结果)里找 downhash,老种子找不到。
func (*HDDolbyDriver) Execute ¶ added in v0.8.0
func (d *HDDolbyDriver) Execute(ctx context.Context, req HDDolbyRequest) (HDDolbyResponse, error)
func (*HDDolbyDriver) GetBonusPerHour ¶ added in v0.8.0
func (d *HDDolbyDriver) GetBonusPerHour(ctx context.Context) (float64, error)
GetBonusPerHour 用 Cookie 读时魔页的每小时鲸币。没配 Cookie 时是 0、没有错误(API 不给时魔); 页面打不开、要两步验证、或者认不出「合计」那一行时返回错误。
func (*HDDolbyDriver) GetPeerData ¶ added in v0.8.0
func (d *HDDolbyDriver) GetPeerData(ctx context.Context) (*HDDolbyPeerData, error)
func (*HDDolbyDriver) GetTorrentDetail ¶ added in v0.10.0
func (d *HDDolbyDriver) GetTorrentDetail(ctx context.Context, guid, link, title string) (*TorrentItem, error)
GetTorrentDetail 在详情缓存(最近 100 条列表结果,最多 hddolbyDetailCacheTTL 刷新一次)里找种子。 结果的 FetchedAt 是缓存取得的时间;ctx 带 WithFreshAfter 时缓存早于那个时间就先刷新,刷新失败返回错误。 缓存里找不到时返回 ErrTorrentDetailUnavailable:读不到优惠不等于不是免费。
func (*HDDolbyDriver) GetUserInfo ¶ added in v0.8.0
func (d *HDDolbyDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
func (*HDDolbyDriver) ParseDownload ¶ added in v0.8.0
func (d *HDDolbyDriver) ParseDownload(res HDDolbyResponse) ([]byte, error)
func (*HDDolbyDriver) ParseSearch ¶ added in v0.8.0
func (d *HDDolbyDriver) ParseSearch(res HDDolbyResponse) ([]TorrentItem, error)
func (*HDDolbyDriver) ParseUserInfo ¶ added in v0.8.0
func (d *HDDolbyDriver) ParseUserInfo(res HDDolbyResponse) (UserInfo, error)
func (*HDDolbyDriver) PrepareDownload ¶ added in v0.8.0
func (d *HDDolbyDriver) PrepareDownload(torrentID string) (HDDolbyRequest, error)
PrepareDownload、ParseDownload 是 Driver 接口要的;BaseSite 下载时用驱动自己的 Download(下载要 downhash 或 Cookie, 这一个请求给不了)。
func (*HDDolbyDriver) PrepareSearch ¶ added in v0.8.0
func (d *HDDolbyDriver) PrepareSearch(query SearchQuery) (HDDolbyRequest, error)
func (*HDDolbyDriver) PrepareUserInfo ¶ added in v0.8.0
func (d *HDDolbyDriver) PrepareUserInfo() (HDDolbyRequest, error)
func (*HDDolbyDriver) Search ¶ added in v0.8.0
func (d *HDDolbyDriver) Search(ctx context.Context, query SearchQuery) ([]TorrentItem, error)
func (*HDDolbyDriver) SetSiteDefinition ¶ added in v0.8.0
func (d *HDDolbyDriver) SetSiteDefinition(def *SiteDefinition)
type HDDolbyDriverConfig ¶ added in v0.8.0
type HDDolbyOptions ¶ added in v0.8.0
type HDDolbyPeerData ¶ added in v0.8.0
type HDDolbyPeerItem ¶ added in v0.8.0
type HDDolbyRequest ¶ added in v0.8.0
type HDDolbyResponse ¶ added in v0.8.0
type HDDolbyResponse struct {
Status int `json:"status"`
Error *HDDolbyAPIError `json:"error,omitempty"`
Data json.RawMessage `json:"data"`
RawBody []byte `json:"-"`
StatusCode int `json:"-"`
}
type HDDolbySearchRequest ¶ added in v0.8.0
type HDDolbySearchResponse ¶ added in v0.8.0
type HDDolbySearchResponse struct {
Data []HDDolbyTorrent `json:"data"`
Total int `json:"total"`
}
type HDDolbyTorrent ¶ added in v0.8.0
type HDDolbyTorrent struct {
ID int `json:"id"`
SpState int `json:"sp_state"`
Name string `json:"name"`
SmallDescr string `json:"small_descr"`
Category int `json:"category"`
Size int64 `json:"size"`
Seeders int `json:"seeders"`
Leechers int `json:"leechers"`
TimesCompleted int `json:"times_completed"`
Added string `json:"added"`
PromotionTimeType int `json:"promotion_time_type"`
PromotionUntil string `json:"promotion_until"`
Tags string `json:"tags"`
DownHash string `json:"downhash"`
HR int `json:"hr"`
InfoHash string `json:"info_hash"`
}
HDDolbyTorrent 是 API 搜索结果里的一个种子。sp_state 是优惠(NexusPHP 的促销状态),promotion_time_type 是优惠的时限: 0 跟站点默认、1 永久、2 到 promotion_until 为止(见 applyDiscount)。tags 是分号分隔的标签代码(gf 官方、zz 中字……),不是优惠。
type HDDolbyUserData ¶ added in v0.8.0
type HDDolbyUserData struct {
ID string `json:"id"`
Username string `json:"username"`
Added string `json:"added"`
LastAccess string `json:"last_access"`
Class string `json:"class"`
Uploaded string `json:"uploaded"`
Downloaded string `json:"downloaded"`
SeedBonus string `json:"seedbonus"`
SeBonus string `json:"sebonus"`
UnreadMessages string `json:"unread_messages"`
}
type HRSeedTimeRule ¶ added in v0.19.0
type HRSeedTimeRule struct {
// MinSizeGB is the lower bound of the size range (inclusive), in GiB
MinSizeGB float64 `json:"minSizeGB"`
// MaxSizeGB is the upper bound of the size range (exclusive, 0 = unlimited), in GiB
MaxSizeGB float64 `json:"maxSizeGB,omitempty"`
// SeedTimeH is the required seed time in hours for this size tier
SeedTimeH int `json:"seedTimeH"`
}
HRSeedTimeRule defines a size-tiered HR seed time requirement. When a torrent's size falls within [MinSizeGB, MaxSizeGB), the required seed time is SeedTimeH hours.
type HTTPClientConfig ¶
type HTTPClientConfig struct {
// Timeout is the request timeout
Timeout time.Duration
// MaxIdleConns is the maximum number of idle connections
MaxIdleConns int
// MaxIdleConnsPerHost is the maximum idle connections per host
MaxIdleConnsPerHost int
// IdleConnTimeout is the idle connection timeout
IdleConnTimeout time.Duration
// DisableKeepAlives disables HTTP keep-alives
DisableKeepAlives bool
}
HTTPClientConfig holds configuration for HTTP clients
func DefaultHTTPClientConfig ¶
func DefaultHTTPClientConfig() HTTPClientConfig
DefaultHTTPClientConfig returns default HTTP client configuration
type HTTPClientPool ¶
type HTTPClientPool struct {
// contains filtered or unexported fields
}
func NewHTTPClientPool ¶
func NewHTTPClientPool(config HTTPClientConfig, logger *zap.Logger) *HTTPClientPool
func (*HTTPClientPool) CloseAll ¶
func (p *HTTPClientPool) CloseAll()
func (*HTTPClientPool) CloseClient ¶
func (p *HTTPClientPool) CloseClient(siteID string)
func (*HTTPClientPool) GetSession ¶
func (p *HTTPClientPool) GetSession(siteID string) requests.Session
GetSession returns a requests.Session for the given site ID
type HTTPResponse ¶
HTTPResponse wraps the response from requests library
func (*HTTPResponse) IsCloudflareChallenge ¶ added in v1.0.0
func (r *HTTPResponse) IsCloudflareChallenge() bool
IsCloudflareChallenge 判断响应是不是 Cloudflare 的质询页(403/503):Cloudflare 给质询响应加的 cf-mitigated: challenge 头,或质询页特有的 cf_chl_opt 脚本变量、/cdn-cgi/challenge-platform/ 资源路径。 这类响应不能当成凭证无效处理。
func (*HTTPResponse) IsError ¶
func (r *HTTPResponse) IsError() bool
IsError returns true if status code is 4xx or 5xx
func (*HTTPResponse) IsSuccess ¶
func (r *HTTPResponse) IsSuccess() bool
IsSuccess returns true if status code is 2xx
type HTTPStatusError ¶ added in v1.0.0
type HTTPStatusError struct {
Code int
}
HTTPStatusError 是站点回了不是 200 的状态码(文本与以前一样,例如 HTTP 502: Bad Gateway)。
func (*HTTPStatusError) Error ¶ added in v1.0.0
func (e *HTTPStatusError) Error() string
type HashDownloader ¶ added in v0.8.0
type HashDownloader interface {
DownloadWithHash(ctx context.Context, torrentID, hash string) ([]byte, error)
}
HashDownloader is an optional interface for sites that require a hash for download
type Histogram ¶
type Histogram struct {
// contains filtered or unexported fields
}
Histogram tracks the distribution of values
func (*Histogram) Stats ¶
func (h *Histogram) Stats() HistogramStats
Stats returns histogram statistics
type HistogramStats ¶
type HistogramStats struct {
Count int64 `json:"count"`
Sum float64 `json:"sum"`
Min float64 `json:"min"`
Max float64 `json:"max"`
Avg float64 `json:"avg"`
}
HistogramStats contains histogram statistics
type InMemoryUserInfoRepo ¶
type InMemoryUserInfoRepo struct {
// contains filtered or unexported fields
}
InMemoryUserInfoRepo is an in-memory implementation of UserInfoRepo
func NewInMemoryUserInfoRepo ¶
func NewInMemoryUserInfoRepo() *InMemoryUserInfoRepo
NewInMemoryUserInfoRepo creates a new in-memory user info repository
func (*InMemoryUserInfoRepo) Clear ¶
func (r *InMemoryUserInfoRepo) Clear()
Clear removes all stored user info
func (*InMemoryUserInfoRepo) Count ¶
func (r *InMemoryUserInfoRepo) Count() int
Count returns the number of stored user info entries
func (*InMemoryUserInfoRepo) Delete ¶
func (r *InMemoryUserInfoRepo) Delete(ctx context.Context, site string) error
Delete removes user info for a site
func (*InMemoryUserInfoRepo) GetAggregated ¶
func (r *InMemoryUserInfoRepo) GetAggregated(ctx context.Context) (AggregatedStats, error)
GetAggregated calculates aggregated statistics
func (*InMemoryUserInfoRepo) ListAll ¶
func (r *InMemoryUserInfoRepo) ListAll(ctx context.Context) ([]UserInfo, error)
ListAll retrieves all stored user info
func (*InMemoryUserInfoRepo) ListBySites ¶
ListBySites retrieves user info for specific sites
type L2Cache ¶
type L2Cache interface {
Get(key string) ([]byte, error)
Set(key string, value []byte, ttl time.Duration) error
Delete(key string) error
}
L2Cache defines the interface for L2 cache (e.g., Redis)
type LRUCache ¶
type LRUCache struct {
// contains filtered or unexported fields
}
LRUCache is a thread-safe LRU cache with TTL support
func NewLRUCache ¶
NewLRUCache creates a new LRU cache with the specified capacity and TTL
type LevelGroupType ¶
type LevelGroupType string
LevelGroupType represents the type of user level group
const ( // LevelGroupUser represents regular user levels LevelGroupUser LevelGroupType = "user" // LevelGroupVIP represents VIP/donor levels LevelGroupVIP LevelGroupType = "vip" // LevelGroupManager represents staff/manager levels LevelGroupManager LevelGroupType = "manager" )
type LevelManager ¶
type LevelManager struct {
// contains filtered or unexported fields
}
LevelManager manages user levels and calculates progress
func NewLevelManager ¶
func NewLevelManager() *LevelManager
NewLevelManager creates a new level manager with default configurations
func (*LevelManager) CalculateNextLevel ¶
func (lm *LevelManager) CalculateNextLevel(kind SiteKind, upload int64, ratio float64, days int) *LevelProgress
CalculateNextLevel calculates progress towards the next level
func (*LevelManager) GetCurrentLevel ¶
func (lm *LevelManager) GetCurrentLevel(kind SiteKind, upload int64, ratio float64, days int) string
GetCurrentLevel determines the user's current level based on their stats
func (*LevelManager) GetLevels ¶
func (lm *LevelManager) GetLevels(kind SiteKind) []LevelRequirement
GetLevels returns the level requirements for a site kind
func (*LevelManager) SetLevels ¶
func (lm *LevelManager) SetLevels(kind SiteKind, levels []LevelRequirement)
SetLevels sets custom level requirements for a site kind
type LevelProgress ¶
type LevelProgress struct {
// CurrentLevel is the user's current level/rank
CurrentLevel string `json:"currentLevel"`
// NextLevel is the next level to achieve
NextLevel string `json:"nextLevel"`
// UploadNeeded is the additional upload needed (bytes)
UploadNeeded int64 `json:"uploadNeeded,omitempty"`
// DownloadNeeded is the additional download needed (bytes)
DownloadNeeded int64 `json:"downloadNeeded,omitempty"`
// RatioNeeded is the additional ratio needed
RatioNeeded float64 `json:"ratioNeeded,omitempty"`
// TimeNeeded is the additional time needed
TimeNeeded time.Duration `json:"timeNeeded,omitempty"`
// ProgressPercent is the overall progress percentage (0-100)
ProgressPercent float64 `json:"progressPercent"`
}
LevelProgress represents progress towards the next user level
type LevelRequirement ¶
type LevelRequirement struct {
// Level is the level name (e.g., "Power User", "Elite", "Master")
Level string
// MinUpload is the minimum upload amount in bytes
MinUpload int64
// MinRatio is the minimum ratio required
MinRatio float64
// MinDays is the minimum account age in days
MinDays int
// MinSeedingTorrents is the minimum number of seeding torrents
MinSeedingTorrents int
// MinSeedingTime is the minimum total seeding time in hours
MinSeedingTime int
// Order is the level order (higher = better)
Order int
}
LevelRequirement defines the requirements for a user level
type MTorrentBonusResponse ¶
type MTorrentBonusResponse struct {
Code FlexibleCode `json:"code"`
Message string `json:"message"`
Data struct {
FormulaParams struct {
FinalBs json.Number `json:"finalBs"` // Bonus per hour (时魔) - can be string or number
} `json:"formulaParams"`
} `json:"data"`
}
MTorrentBonusResponse represents the response from /api/tracker/mybonus
type MTorrentDriver ¶
type MTorrentDriver struct {
BaseURL string // API URL (e.g., https://api.m-team.cc)
WebURL string // Web URL for detail pages (e.g., https://kp.m-team.cc)
APIKey string
LoginCookie string // 仅用于登录态探测,绝不用于检索/下载请求
// contains filtered or unexported fields
}
MTorrentDriver implements the Driver interface for M-Team sites
func NewMTorrentDriver ¶
func NewMTorrentDriver(config MTorrentDriverConfig) *MTorrentDriver
NewMTorrentDriver creates a new M-Team driver
func NewMTorrentDriverWithFailover ¶
func NewMTorrentDriverWithFailover(apiKey string) *MTorrentDriver
NewMTorrentDriverWithFailover creates a new M-Team driver with failover enabled
func (*MTorrentDriver) Execute ¶
func (d *MTorrentDriver) Execute(ctx context.Context, req MTorrentRequest) (MTorrentResponse, error)
Execute performs the HTTP request
func (*MTorrentDriver) GetBonusPerHour ¶
func (d *MTorrentDriver) GetBonusPerHour(ctx context.Context) (float64, error)
GetBonusPerHour fetches the bonus per hour (时魔) for the user
func (*MTorrentDriver) GetPeerStatistics ¶
func (d *MTorrentDriver) GetPeerStatistics(ctx context.Context) (*PeerStatistics, error)
GetPeerStatistics fetches the peer statistics for the user
func (*MTorrentDriver) GetPeerStatus ¶ added in v1.0.0
func (d *MTorrentDriver) GetPeerStatus(ctx context.Context) (seeder, leecher int, err error)
GetPeerStatus 取正在做种与正在下载的种子数(/api/tracker/myPeerStatus)
func (*MTorrentDriver) GetSeedingSize ¶ added in v1.0.0
func (d *MTorrentDriver) GetSeedingSize(ctx context.Context, userID string) (count int, size int64, err error)
GetSeedingSize 把个人页「目前做種」列表(type=SEEDING)各页的种子体积加起来,返回做种数与体积。 个人页「保種總體積」用的 /api/member/seedingStats 不认 API Key(401),myPeerStatistics 对 API Key 全返回 0,只能这样算。 页数超过 mtorrentMaxSeedingPages 时报错,不读一半就当总数。
func (*MTorrentDriver) GetSiteDefinition ¶
func (d *MTorrentDriver) GetSiteDefinition() *SiteDefinition
GetSiteDefinition returns the site definition
func (*MTorrentDriver) GetTorrentDetail ¶ added in v0.10.0
func (d *MTorrentDriver) GetTorrentDetail(ctx context.Context, guid, _, _ string) (*TorrentItem, error)
func (*MTorrentDriver) GetUnreadMessageCount ¶
GetUnreadMessageCount fetches the unread message count for the user Returns (unread, total, error)
func (*MTorrentDriver) GetUserInfo ¶
func (d *MTorrentDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
GetUserInfo fetches complete user information including extended stats Uses parallel requests for independent API calls to improve performance
func (*MTorrentDriver) ParseBonusPerHour ¶
func (d *MTorrentDriver) ParseBonusPerHour(res MTorrentResponse) (float64, error)
ParseBonusPerHour extracts bonus per hour from the response
func (*MTorrentDriver) ParseDownload ¶
func (d *MTorrentDriver) ParseDownload(res MTorrentResponse) ([]byte, error)
ParseDownload extracts torrent file data from the response
func (*MTorrentDriver) ParseDownloadContext ¶ added in v1.0.0
func (d *MTorrentDriver) ParseDownloadContext(ctx context.Context, res MTorrentResponse) ([]byte, error)
ParseDownloadContext 同 ParseDownload:拉种子文件的第二段请求跟着 ctx 取消(BaseSite 下载时用它)。
func (*MTorrentDriver) ParsePeerStatistics ¶
func (d *MTorrentDriver) ParsePeerStatistics(res MTorrentResponse) (*PeerStatistics, error)
ParsePeerStatistics extracts peer statistics from the response
func (*MTorrentDriver) ParseSearch ¶
func (d *MTorrentDriver) ParseSearch(res MTorrentResponse) ([]TorrentItem, error)
ParseSearch extracts torrent items from the response
func (*MTorrentDriver) ParseUnreadMessageCount ¶
func (d *MTorrentDriver) ParseUnreadMessageCount(res MTorrentResponse) (int, int, error)
ParseUnreadMessageCount extracts unread message count from the response
func (*MTorrentDriver) ParseUserInfo ¶
func (d *MTorrentDriver) ParseUserInfo(res MTorrentResponse) (UserInfo, error)
ParseUserInfo extracts user info from the response
func (*MTorrentDriver) PrepareDownload ¶
func (d *MTorrentDriver) PrepareDownload(torrentID string) (MTorrentRequest, error)
PrepareDownload prepares a request for downloading a torrent
func (*MTorrentDriver) PrepareGetBonusPerHour ¶
func (d *MTorrentDriver) PrepareGetBonusPerHour() (MTorrentRequest, error)
PrepareGetBonusPerHour prepares a request for fetching bonus per hour
func (*MTorrentDriver) PrepareGetPeerStatistics ¶
func (d *MTorrentDriver) PrepareGetPeerStatistics() (MTorrentRequest, error)
PrepareGetPeerStatistics prepares a request for fetching peer statistics
func (*MTorrentDriver) PrepareGetUnreadMessageCount ¶
func (d *MTorrentDriver) PrepareGetUnreadMessageCount() (MTorrentRequest, error)
PrepareGetUnreadMessageCount prepares a request for fetching unread message count
func (*MTorrentDriver) PrepareSearch ¶
func (d *MTorrentDriver) PrepareSearch(query SearchQuery) (MTorrentRequest, error)
PrepareSearch converts a SearchQuery to an M-Team request.
mode 取 query.Section,只认 normal 和 adult,空值或别的值都用 normal(综合区)。 有意忽略 FreeOnly,不往请求里加 discount 筛选:单种免费(mallSingleFree)的种子本身的优惠不是 FREE, 交给服务端按 discount 筛会把它漏掉;免费与否由 evaluateMTorrentDiscount 在本地判断。
func (*MTorrentDriver) PrepareUserInfo ¶
func (d *MTorrentDriver) PrepareUserInfo() (MTorrentRequest, error)
PrepareUserInfo prepares a request for user info
func (*MTorrentDriver) SetSiteDefinition ¶
func (d *MTorrentDriver) SetSiteDefinition(def *SiteDefinition)
SetSiteDefinition sets the site definition for custom parsing
type MTorrentDriverConfig ¶
type MTorrentDriverConfig struct {
BaseURL string
WebURL string // Optional: Web URL for detail pages, defaults to "https://kp.m-team.cc"
APIKey string
LoginCookie string // 仅用于登录态探测,绝不用于检索/下载请求
HTTPClient *SiteHTTPClient // Use SiteHTTPClient instead of *http.Client
UserAgent string
UseFailover bool // Enable multi-URL failover
// SiteID 是站点在 pt-tools 里注册的 ID:全局设置里的「站点代理」按它判定走不走代理
SiteID string
}
MTorrentDriverConfig holds configuration for creating an M-Team driver
type MTorrentID ¶ added in v1.0.0
type MTorrentID string
MTorrentID 是可能以字符串或数字出现的编号(例如种子的 team)。解不开时当作没有,不报错: 新读取的字段不能让原本能解析的整页结果失败。
func (*MTorrentID) UnmarshalJSON ¶ added in v1.0.0
func (id *MTorrentID) UnmarshalJSON(data []byte) error
UnmarshalJSON 接受字符串或数字;null、对象、数组当作没有
type MTorrentIDList ¶ added in v1.0.0
MTorrentIDList 是促销规则里的编号列表(categories、teams),元素可能是字符串也可能是数字。 解不开时不报错(一个字段异常不该让整页结果都解析失败),记为 Invalid:无法证明覆盖,促销不适用。
func (*MTorrentIDList) UnmarshalJSON ¶ added in v1.0.0
func (l *MTorrentIDList) UnmarshalJSON(data []byte) error
UnmarshalJSON 接受字符串或数字组成的数组;null 当作空列表
type MTorrentMemberCount ¶
type MTorrentMemberCount struct {
Uploaded string `json:"uploaded"`
Downloaded string `json:"downloaded"`
TrueUploaded string `json:"trueUploaded"`
TrueDownloaded string `json:"trueDownloaded"`
Bonus string `json:"bonus"`
Seedtime string `json:"seedtime"`
Leechtime string `json:"leechtime"`
}
MTorrentMemberCount contains upload/download stats
type MTorrentMemberStatus ¶
type MTorrentMemberStatus struct {
LastLogin string `json:"lastLogin"`
LastBrowse string `json:"lastBrowse"`
Vip bool `json:"vip"`
}
MTorrentMemberStatus contains user status info
type MTorrentMessageStatResponse ¶
type MTorrentMessageStatResponse struct {
Code FlexibleCode `json:"code"`
Message string `json:"message"`
Data struct {
Count string `json:"count"` // Total message count
UnMake string `json:"unMake"` // Unread message count (string in API response)
} `json:"data"`
}
MTorrentMessageStatResponse represents the response from /api/msg/notify/statistic
type MTorrentOptions ¶
type MTorrentPeerStatResponse ¶
type MTorrentPeerStatResponse struct {
Code FlexibleCode `json:"code"`
Message string `json:"message"`
Data struct {
UID string `json:"uid"`
SeederCount string `json:"seederCount"`
SeederSize string `json:"seederSize"`
LeecherCount string `json:"leecherCount"`
LeecherSize string `json:"leecherSize"`
UploadCount string `json:"uploadCount"`
} `json:"data"`
}
MTorrentPeerStatResponse represents the response from /api/tracker/myPeerStatistics
type MTorrentPeerStatusResponse ¶ added in v1.0.0
type MTorrentPeerStatusResponse struct {
Data struct {
Seeder json.Number `json:"seeder"`
Leecher json.Number `json:"leecher"`
} `json:"data"`
}
MTorrentPeerStatusResponse 是 /api/tracker/myPeerStatus 的返回:网页页头「當前活動」后面的做种数与下载数
type MTorrentPromotionRule ¶ added in v0.10.1
type MTorrentPromotionRule struct {
Discount string `json:"discount"`
StartTime string `json:"startTime,omitempty"`
EndTime string `json:"endTime,omitempty"`
Categories MTorrentIDList `json:"categories"`
Teams MTorrentIDList `json:"teams"`
}
MTorrentPromotionRule represents an additional promotion rule from M-Team API. 接口里的促销规则没有状态字段,只能按起止时间判断是否生效;Categories、Teams 是适用范围,空列表表示全站。
type MTorrentRequest ¶
type MTorrentRequest struct {
// Endpoint is the API endpoint path
Endpoint string
// Method is the HTTP method
Method string
// Body is the request body (will be JSON encoded or form-urlencoded based on ContentType)
Body any
// ContentType specifies the request content type (default: "application/json")
// Use "application/x-www-form-urlencoded" for form data
ContentType string
}
MTorrentRequest represents a request to M-Team API
type MTorrentResponse ¶
type MTorrentResponse struct {
// Code is the response code ("0" for success)
Code FlexibleCode `json:"code"`
// Message is the response message
Message string `json:"message"`
// Data is the response data
Data json.RawMessage `json:"data"`
// RawBody is the raw response body (for downloads)
RawBody []byte `json:"-"`
// StatusCode is the HTTP status code
StatusCode int `json:"-"`
}
MTorrentResponse represents a response from M-Team API
type MTorrentSearchData ¶
type MTorrentSearchData struct {
Data []MTorrentTorrent `json:"data"`
Total FlexInt `json:"total"`
}
MTorrentSearchData is the search response data
type MTorrentSearchRequest ¶
type MTorrentSearchRequest struct {
Mode string `json:"mode"`
Categories []string `json:"categories,omitempty"`
Keyword string `json:"keyword,omitempty"`
PageNumber int `json:"pageNumber"`
PageSize int `json:"pageSize"`
}
MTorrentSearchRequest is the search request body
type MTorrentTorrent ¶
type MTorrentTorrent struct {
ID string `json:"id"`
Name string `json:"name"`
SmallDescr string `json:"smallDescr"`
Size string `json:"size"`
CreatedDate string `json:"createdDate"`
Status struct {
Seeders FlexInt `json:"seeders"`
Leechers FlexInt `json:"leechers"`
TimesCompleted FlexInt `json:"timesCompleted"`
Discount string `json:"discount"`
DiscountEndTime string `json:"discountEndTime,omitempty"`
PromotionRule *MTorrentPromotionRule `json:"promotionRule,omitempty"`
MallSingleFree *MallSingleFree `json:"mallSingleFree,omitempty"`
} `json:"status"`
Category string `json:"category"`
// Team 是制作组编号,用来判断促销规则的 teams 范围
Team MTorrentID `json:"team"`
// IMDb、Douban 是条目链接(或编号),用 NormalizeIMDbID、NormalizeDoubanID 规整
IMDb string `json:"imdb"`
Douban string `json:"douban"`
}
MTorrentTorrent represents a torrent in M-Team API response
type MTorrentUserInfo ¶
type MTorrentUserInfo struct {
ID string `json:"id"`
Username string `json:"username"`
CreatedDate string `json:"createdDate"`
LastModifiedDate string `json:"lastModifiedDate"`
Role string `json:"role"`
MemberCount MTorrentMemberCount `json:"memberCount"`
MemberStatus MTorrentMemberStatus `json:"memberStatus"`
}
MTorrentUserInfo represents user info from M-Team API
type MTorrentUserTorrentListResponse ¶ added in v1.0.0
type MTorrentUserTorrentListResponse struct {
Data struct {
Total json.Number `json:"total"`
TotalPages json.Number `json:"totalPages"`
Data []struct {
Torrent struct {
Size json.Number `json:"size"`
} `json:"torrent"`
} `json:"data"`
} `json:"data"`
}
MTorrentUserTorrentListResponse 是 /api/member/getUserTorrentList 的返回(个人页「目前做種」用的接口)
type MallSingleFree ¶ added in v0.20.1
type MallSingleFree struct {
Status string `json:"status,omitempty"`
StartDate string `json:"startDate,omitempty"`
EndDate string `json:"endDate,omitempty"`
}
MallSingleFree represents a mall single free from M-Team API
type MetricType ¶
type MetricType string
MetricType represents the type of metric
const ( MetricTypeCounter MetricType = "counter" MetricTypeGauge MetricType = "gauge" MetricTypeHistogram MetricType = "histogram" )
type MetricsRegistry ¶
type MetricsRegistry struct {
// contains filtered or unexported fields
}
MetricsRegistry manages all metrics
func NewMetricsRegistry ¶
func NewMetricsRegistry() *MetricsRegistry
NewMetricsRegistry creates a new metrics registry
func (*MetricsRegistry) Counter ¶
func (r *MetricsRegistry) Counter(name string) *Counter
Counter returns or creates a counter with the given name
func (*MetricsRegistry) Gauge ¶
func (r *MetricsRegistry) Gauge(name string) *Gauge
Gauge returns or creates a gauge with the given name
func (*MetricsRegistry) Histogram ¶
func (r *MetricsRegistry) Histogram(name string) *Histogram
Histogram returns or creates a histogram with the given name
func (*MetricsRegistry) Snapshot ¶
func (r *MetricsRegistry) Snapshot() MetricsSnapshot
Snapshot returns a snapshot of all metrics
func (*MetricsRegistry) Timer ¶
func (r *MetricsRegistry) Timer(name string) *Timer
Timer creates a new timer for the given histogram
type MetricsSnapshot ¶
type MetricsSnapshot struct {
Counters map[string]int64 `json:"counters"`
Gauges map[string]int64 `json:"gauges"`
Histograms map[string]HistogramStats `json:"histograms"`
Timestamp time.Time `json:"timestamp"`
}
MetricsSnapshot contains a point-in-time snapshot of all metrics
type MigrationStatus ¶
type MigrationStatus struct {
SiteID string `json:"siteId"`
SiteName string `json:"siteName"`
OldImplementation bool `json:"oldImplementation"`
NewImplementation bool `json:"newImplementation"`
MigrationReady bool `json:"migrationReady"`
Notes string `json:"notes,omitempty"`
}
MigrationStatus represents the migration status of a site
type MultiSiteSearchQuery ¶
type MultiSiteSearchQuery struct {
SearchQuery
// Sites specifies which sites to search (empty means all)
Sites []string `json:"sites,omitempty"`
// Timeout is the maximum time to wait for all searches
Timeout time.Duration `json:"timeout,omitempty"`
// MinSeeders filters results by minimum seeders
MinSeeders int `json:"minSeeders,omitempty"`
// MaxSizeBytes filters results by maximum size
MaxSizeBytes int64 `json:"maxSizeBytes,omitempty"`
// MinSizeBytes filters results by minimum size
MinSizeBytes int64 `json:"minSizeBytes,omitempty"`
// RawTitles 为真时不规整标题:订阅要按站点上原样的标题解析画质(规整会把 UHD 换成 2160p、x265 换成 H.265)
RawTitles bool `json:"rawTitles,omitempty"`
// KeepDuplicates 为真时不按 InfoHash 合并,各站点的结果原样返回:按条目搜索要列出同一资源的每个来源
// (合并只留一条,其他站点的种子编号与下载入口就丢了)。缓存键是整个查询,两种结果分开缓存
KeepDuplicates bool `json:"keepDuplicates,omitempty"`
}
MultiSiteSearchQuery extends SearchQuery with multi-site options
type MultiSiteSearchResult ¶
type MultiSiteSearchResult struct {
// Items contains deduplicated and ranked torrent items
Items []TorrentItem `json:"items"`
// TotalResults is the total number of results before deduplication
TotalResults int `json:"totalResults"`
// SiteResults contains per-site result counts
SiteResults map[string]int `json:"siteResults"`
// Errors contains any errors that occurred during search
Errors []SearchError `json:"errors,omitempty"`
// Duration is how long the search took
Duration time.Duration `json:"duration"`
}
MultiSiteSearchResult contains results from a multi-site search
type NewDownloaderConfig ¶
type NewDownloaderConfig struct {
Type string `json:"type"` // "qbittorrent", "transmission"
Name string `json:"name"` // Downloader name
URL string `json:"url"` // Downloader URL
Username string `json:"username"` // Username for authentication
Password string `json:"password"` // Password for authentication
AddAtPaused bool `json:"addAtPaused"` // New field: true = add paused
}
NewDownloaderConfig represents the new downloader configuration format with AddAtPaused field for controlling torrent start behavior
type NexusPHPDetailParser ¶
type NexusPHPDetailParser interface {
ParseTitleAndID(doc *goquery.Selection) (title, torrentID string)
ParseDiscount(doc *goquery.Selection) (DiscountLevel, time.Time)
ParseHR(doc *goquery.Selection) bool
ParseSizeMB(doc *goquery.Selection) float64
ParseAll(doc *goquery.Selection) *TorrentDetailInfo
}
NexusPHPDetailParser 接口定义
type NexusPHPDriver ¶
type NexusPHPDriver struct {
BaseURL string
Cookie string
Selectors SiteSelectors
// contains filtered or unexported fields
}
NexusPHPDriver implements the Driver interface for NexusPHP sites
func NewNexusPHPDriver ¶
func NewNexusPHPDriver(config NexusPHPDriverConfig) *NexusPHPDriver
NewNexusPHPDriver creates a new NexusPHP driver
func NewNexusPHPDriverWithFailover ¶
func NewNexusPHPDriverWithFailover(siteName SiteName, cookie string) *NexusPHPDriver
NewNexusPHPDriverWithFailover creates a new NexusPHP driver with failover enabled
func (*NexusPHPDriver) Attend ¶ added in v1.0.0
func (d *NexusPHPDriver) Attend(ctx context.Context) (AttendResult, error)
Attend 按站点的签到配置发一次请求,按页面文字判断结果。请求经驱动的 Execute, 会话失效、权限错误等与其他页面请求的判断一致。 GET 的签到页里认不出结果、却有提交回本页的「立即签到」表单时(新版 NexusPHP,见 attendance_form.go),照按钮的做法提交再认: 表单带 NexusPHP 图片验证码时让 AI 认(ctx 里没有 AI 时返回 ErrAttendanceNeedsAI),要过人机验证组件时返回 ErrAttendanceCaptchaRequired。
func (*NexusPHPDriver) AttendanceUnsupportedReason ¶ added in v1.0.0
func (d *NexusPHPDriver) AttendanceUnsupportedReason() string
AttendanceUnsupportedReason 报告站点定义是否把签到标记为不支持,支持时返回空串。
func (*NexusPHPDriver) CurrentCookie ¶ added in v1.0.0
func (d *NexusPHPDriver) CurrentCookie() (string, bool)
CurrentCookie 是现在用的那组 Cookie(续期过就是换发后的);站点没有续期会话时 ok 为假。
func (*NexusPHPDriver) DownloadSubtitle ¶ added in v1.0.0
func (d *NexusPHPDriver) DownloadSubtitle(ctx context.Context, sub Subtitle) (SubtitleFile, error)
DownloadSubtitle 下载列表里的一份字幕(downloadsubs.php?torrentid=&subid=)。
func (*NexusPHPDriver) Execute ¶
func (d *NexusPHPDriver) Execute(ctx context.Context, req NexusPHPRequest) (NexusPHPResponse, error)
Execute performs the HTTP request
func (*NexusPHPDriver) ExtractFieldValuePublic ¶
func (d *NexusPHPDriver) ExtractFieldValuePublic(doc *goquery.Document, selector FieldSelector) string
ExtractFieldValuePublic is a public wrapper for extractFieldValue for testing purposes
func (*NexusPHPDriver) FetchSeedingStatus ¶
func (d *NexusPHPDriver) FetchSeedingStatus(ctx context.Context, userID string) (seeding int, seedingSize int64, err error)
FetchSeedingStatus fetches the seeding status (count and size) for a user This method requests /getusertorrentlistajax.php and parses the response
func (*NexusPHPDriver) GetSiteDefinition ¶
func (d *NexusPHPDriver) GetSiteDefinition() *SiteDefinition
GetSiteDefinition returns the site definition
func (*NexusPHPDriver) GetTorrentDetail ¶ added in v0.10.0
func (d *NexusPHPDriver) GetTorrentDetail(ctx context.Context, guid, link, _ string) (*TorrentItem, error)
func (*NexusPHPDriver) GetUserInfo ¶
func (d *NexusPHPDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
GetUserInfo fetches complete user information For NexusPHP sites, this involves two steps: 1. Fetch /index.php to get user ID and basic info from info_block 2. Fetch /userdetails.php?id=xxx to get detailed info
func (*NexusPHPDriver) ListSubtitles ¶ added in v1.0.0
ListSubtitles 读种子详情页「字幕」一行里的字幕。编号不是数字时不发请求(RSS 的 guid 是 info hash,取不到详情)。
func (*NexusPHPDriver) ParseDetail ¶
func (d *NexusPHPDriver) ParseDetail(res NexusPHPResponse) (TorrentDetail, error)
ParseDetail extracts download URL and other info from detail page
func (*NexusPHPDriver) ParseDownload ¶
func (d *NexusPHPDriver) ParseDownload(res NexusPHPResponse) ([]byte, error)
ParseDownload extracts torrent file data from the response For NexusPHP, the response is a detail page - we need to extract the download URL and fetch the torrent
func (*NexusPHPDriver) ParseDownloadContext ¶ added in v1.0.0
func (d *NexusPHPDriver) ParseDownloadContext(ctx context.Context, res NexusPHPResponse) ([]byte, error)
ParseDownloadContext 同 ParseDownload:拉种子文件的第二段请求跟着 ctx 取消,一时的错误按指数退避重拉同一个下载地址 (见 retryTransient,不再重取详情页)。账号开着「第一次下载提示」时带上 letdown=1 再拉一次(见 fetchSkippingFirstNotice)。 BaseSite 下载时用它。
func (*NexusPHPDriver) ParseSearch ¶
func (d *NexusPHPDriver) ParseSearch(res NexusPHPResponse) ([]TorrentItem, error)
ParseSearch extracts torrent items from the response
func (*NexusPHPDriver) ParseSeedingStatus ¶
func (d *NexusPHPDriver) ParseSeedingStatus(res NexusPHPResponse) (seeding int, seedingSize int64, err error)
ParseSeedingStatus parses the seeding status from the AJAX response Implements two parsing strategies based on NexusPHP.ts: 1. Direct parsing: Look for summary text like "10 | 100 GB" or "<b>94</b>条记录,共计<b>2.756 TB</b>" 2. Table accumulation: Sum up sizes from individual torrent rows
func (*NexusPHPDriver) ParseUserDetails ¶
func (d *NexusPHPDriver) ParseUserDetails(res NexusPHPResponse) (UserInfo, error)
ParseUserDetails extracts detailed user info from userdetails.php page
func (*NexusPHPDriver) ParseUserInfo ¶
func (d *NexusPHPDriver) ParseUserInfo(res NexusPHPResponse) (UserInfo, error)
ParseUserInfo extracts user info from the response
func (*NexusPHPDriver) PrepareDetail ¶
func (d *NexusPHPDriver) PrepareDetail(torrentID string) (NexusPHPRequest, error)
PrepareDetail prepares a request for torrent detail page
func (*NexusPHPDriver) PrepareDownload ¶
func (d *NexusPHPDriver) PrepareDownload(torrentID string) (NexusPHPRequest, error)
PrepareDownload prepares a request for downloading a torrent For NexusPHP sites, we first need to visit the detail page to get the download URL with passkey
func (*NexusPHPDriver) PrepareSearch ¶
func (d *NexusPHPDriver) PrepareSearch(query SearchQuery) (NexusPHPRequest, error)
PrepareSearch converts a SearchQuery to a NexusPHP request
func (*NexusPHPDriver) PrepareUserDetails ¶
func (d *NexusPHPDriver) PrepareUserDetails(userID string) (NexusPHPRequest, error)
PrepareUserDetails prepares a request for user details page
func (*NexusPHPDriver) PrepareUserInfo ¶
func (d *NexusPHPDriver) PrepareUserInfo() (NexusPHPRequest, error)
PrepareUserInfo prepares a request for user info (index page to get user ID)
func (*NexusPHPDriver) PrepareUserSeedingPage ¶
func (d *NexusPHPDriver) PrepareUserSeedingPage(userID, listType string) (NexusPHPRequest, error)
PrepareUserSeedingPage prepares a request for user seeding page via AJAX This is used to fetch seeding size information from /getusertorrentlistajax.php
func (*NexusPHPDriver) SetSiteDefinition ¶
func (d *NexusPHPDriver) SetSiteDefinition(def *SiteDefinition)
SetSiteDefinition sets the site definition for custom parsing
type NexusPHPDriverConfig ¶
type NexusPHPDriverConfig struct {
BaseURL string
Cookie string
Selectors *SiteSelectors
HTTPClient *SiteHTTPClient // Use SiteHTTPClient instead of *http.Client
UserAgent string
UseFailover bool // Enable multi-URL failover
SiteName SiteName // Site name for failover URL lookup
// SiteID 是站点在 pt-tools 里注册的 ID:搜索结果的代理下载地址 /api/site/{id}/… 按它找站点
SiteID string
}
NexusPHPDriverConfig holds configuration for creating a NexusPHP driver
type NexusPHPOptions ¶
type NexusPHPOptions struct {
Cookie string `json:"cookie"`
Selectors *SiteSelectors `json:"selectors,omitempty"`
}
type NexusPHPParser ¶ added in v0.8.0
type NexusPHPParser struct {
// contains filtered or unexported fields
}
NexusPHPParser 通用 NexusPHP 详情页解析器
func NewNexusPHPParser ¶ added in v0.8.0
func NewNexusPHPParser(options ...NexusPHPParserOption) *NexusPHPParser
NewNexusPHPParser 创建通用解析器
func NewNexusPHPParserFromDefinition ¶ added in v0.8.0
func NewNexusPHPParserFromDefinition(def *SiteDefinition) *NexusPHPParser
NewNexusPHPParserFromDefinition creates a parser from SiteDefinition Falls back to default config if def or def.DetailParser is nil
func (*NexusPHPParser) ParseAll ¶ added in v0.8.0
func (p *NexusPHPParser) ParseAll(doc *goquery.Selection) *TorrentDetailInfo
func (*NexusPHPParser) ParseDiscount ¶ added in v0.8.0
func (p *NexusPHPParser) ParseDiscount(doc *goquery.Selection) (DiscountLevel, time.Time)
func (*NexusPHPParser) ParseExternalIDs ¶ added in v1.0.0
func (p *NexusPHPParser) ParseExternalIDs(doc *goquery.Selection) (imdbID, doubanID string)
ParseExternalIDs 在详情页 HTML 里找 IMDb 与豆瓣编号(各取第一处匹配),并规整成 tt… 与数字编号。
func (*NexusPHPParser) ParseHR ¶ added in v0.8.0
func (p *NexusPHPParser) ParseHR(doc *goquery.Selection) bool
func (*NexusPHPParser) ParseSizeMB ¶ added in v0.8.0
func (p *NexusPHPParser) ParseSizeMB(doc *goquery.Selection) float64
func (*NexusPHPParser) ParseTitleAndID ¶ added in v0.8.0
func (p *NexusPHPParser) ParseTitleAndID(doc *goquery.Selection) (title, torrentID string)
type NexusPHPParserConfig ¶
type NexusPHPParserConfig struct {
TimeLayout string
DiscountMapping map[string]DiscountLevel
HRKeywords []string
TitleSelector string
IDSelector string
DiscountSelector string
EndTimeSelector string
SizeSelector string
SizeRegex string
IMDbRegex string
DoubanRegex string
}
NexusPHPParserConfig 解析器配置
func DefaultNexusPHPParserConfig ¶
func DefaultNexusPHPParserConfig() NexusPHPParserConfig
DefaultNexusPHPParserConfig 返回默认配置,适用于大多数 NexusPHP 站点
type NexusPHPParserOption ¶
type NexusPHPParserOption func(*NexusPHPParserConfig)
func WithDiscountMapping ¶ added in v0.8.0
func WithDiscountMapping(mapping map[string]DiscountLevel) NexusPHPParserOption
func WithHRKeywords ¶ added in v0.8.0
func WithHRKeywords(keywords []string) NexusPHPParserOption
func WithTimeLayout ¶ added in v0.8.0
func WithTimeLayout(layout string) NexusPHPParserOption
type NexusPHPRequest ¶
type NexusPHPRequest struct {
// Path is the URL path (e.g., "/torrents.php")
Path string
// Params are the query parameters
Params url.Values
// Method is the HTTP method (default: GET)
Method string
// Referer 不为空时作为 Referer 请求头;以 / 开头的按站点地址补全(签到的验证码接口会看它)
Referer string
}
NexusPHPRequest represents a request to a NexusPHP site
type NexusPHPResponse ¶
type NexusPHPResponse struct {
// Document is the parsed HTML document
Document *goquery.Document
// RawBody is the raw response body (for downloads)
RawBody []byte
// StatusCode is the HTTP status code
StatusCode int
// Header 是响应头(下载字幕时取 Content-Disposition 里的文件名)
Header http.Header
}
NexusPHPResponse wraps a goquery document for parsing
type Normalizer ¶
type Normalizer struct {
// contains filtered or unexported fields
}
Normalizer standardizes torrent titles and tags
func (*Normalizer) ExtractEncoding ¶
func (n *Normalizer) ExtractEncoding(title string) string
ExtractEncoding extracts the encoding from a title
func (*Normalizer) ExtractFormat ¶
func (n *Normalizer) ExtractFormat(title string) string
ExtractFormat extracts the format from a title
func (*Normalizer) ExtractResolution ¶
func (n *Normalizer) ExtractResolution(title string) string
ExtractResolution extracts the resolution from a title
func (*Normalizer) NormalizeTags ¶
func (n *Normalizer) NormalizeTags(tags []string) []string
NormalizeTags standardizes a list of tags
func (*Normalizer) NormalizeTitle ¶
func (n *Normalizer) NormalizeTitle(title string) string
NormalizeTitle standardizes a torrent title
type OldDownloaderConfig ¶
type OldDownloaderConfig struct {
Type string `json:"type"` // "qbittorrent", "transmission"
Name string `json:"name"` // Downloader name
URL string `json:"url"` // Downloader URL
Username string `json:"username"` // Username for authentication
Password string `json:"password"` // Password for authentication
AutoStart bool `json:"autoStart"` // Old field: true = start immediately
}
OldDownloaderConfig represents the old downloader configuration format with autoStart field that needs to be converted to AddAtPaused
type OldSiteConfig ¶
type OldSiteConfig struct {
Name string `json:"name"`
Type string `json:"type"` // "nexusphp", "mteam", etc.
URL string `json:"url"`
Cookie string `json:"cookie,omitempty"`
APIKey string `json:"apiKey,omitempty"`
RateLimit int `json:"rateLimit,omitempty"`
Selectors any `json:"selectors,omitempty"`
AuthMethod string `json:"authMethod,omitempty"` // Old field name
}
OldSiteConfig represents the old site configuration format
type ParsedTorrent ¶
type ParsedTorrent struct {
// Name is the torrent name
Name string `json:"name"`
// InfoHash is the 40-character hex info hash
InfoHash string `json:"infoHash"`
// Size is the total size in bytes
Size int64 `json:"size"`
// Files is the list of files in the torrent
Files []TorrentFile `json:"files,omitempty"`
// PieceLength is the piece size in bytes
PieceLength int64 `json:"pieceLength"`
// Comment is the torrent comment
Comment string `json:"comment,omitempty"`
// CreatedBy is the creator of the torrent
CreatedBy string `json:"createdBy,omitempty"`
// CreationDate is when the torrent was created
CreationDate time.Time `json:"creationDate,omitempty"`
// Announce is the primary tracker URL
Announce string `json:"announce,omitempty"`
// AnnounceList is the list of tracker URLs
AnnounceList [][]string `json:"announceList,omitempty"`
// RawMetadata is the raw torrent file bytes
RawMetadata []byte `json:"-"`
}
ParsedTorrent represents parsed torrent metadata
func GetRemoteTorrent ¶
func GetRemoteTorrent(torrentURL, cookie string) (*ParsedTorrent, error)
GetRemoteTorrent fetches a torrent file from a URL
func GetRemoteTorrentWithRequests ¶
func GetRemoteTorrentWithRequests(torrentURL, cookie string) (*ParsedTorrent, error)
GetRemoteTorrentWithRequests fetches a torrent file from a URL using requests library
func ParseTorrent ¶
func ParseTorrent(data []byte) (*ParsedTorrent, error)
ParseTorrent parses torrent file bytes into ParsedTorrent
func ParseTorrentFromFile ¶
func ParseTorrentFromFile(path string) (*ParsedTorrent, error)
ParseTorrentFromFile parses a torrent file from path
type PartialUserInfoError ¶ added in v1.0.0
PartialUserInfoError 是取用户信息只取到一部分:用户名到手了,有的页面没取到。和它一起返回的 UserInfo 是取到的部分; Missing 是没取到的字段(站点定义里的字段名),Err 是第一个失败的原因。
func (*PartialUserInfoError) Error ¶ added in v1.0.0
func (e *PartialUserInfoError) Error() string
func (*PartialUserInfoError) Unwrap ¶ added in v1.0.0
func (e *PartialUserInfoError) Unwrap() error
type PeerStatistics ¶
type PeerStatistics struct {
// SeederCount is the number of torrents being seeded
SeederCount int `json:"seederCount"`
// SeederSize is the total size of seeding torrents (bytes)
SeederSize int64 `json:"seederSize"`
// LeecherCount is the number of torrents being downloaded
LeecherCount int `json:"leecherCount"`
// LeecherSize is the total size of leeching torrents (bytes)
LeecherSize int64 `json:"leecherSize"`
}
PeerStatistics represents user's seeding/leeching statistics
type PersistentRateLimiter ¶ added in v0.8.0
type PersistentRateLimiter struct {
// contains filtered or unexported fields
}
PersistentRateLimiter 持久化速率限制器 使用滑动窗口算法,状态存储在数据库中,重启后可恢复
func NewPersistentRateLimiter ¶ added in v0.8.0
func NewPersistentRateLimiter(cfg PersistentRateLimiterConfig) *PersistentRateLimiter
func NewPersistentRateLimiterFromRPS ¶ added in v0.8.0
func NewPersistentRateLimiterFromRPS(db *gorm.DB, siteID string, rps float64, burst int) *PersistentRateLimiter
NewPersistentRateLimiterFromRPS 从每秒请求数创建限速器
func (*PersistentRateLimiter) Allow ¶ added in v0.8.0
func (p *PersistentRateLimiter) Allow() bool
Allow 检查是否允许请求,如果允许则增加计数
func (*PersistentRateLimiter) ForceSync ¶ added in v0.8.0
func (p *PersistentRateLimiter) ForceSync()
ForceSync 强制同步到数据库
func (*PersistentRateLimiter) Reset ¶ added in v0.8.0
func (p *PersistentRateLimiter) Reset()
Reset 重置限速器状态
type PersistentRateLimiterConfig ¶ added in v0.8.0
type PromotionSnapshot ¶ added in v1.0.0
type PromotionSnapshot struct {
Level DiscountLevel
Validity FreeValidity
EndsAt *time.Time
VerifiedAt time.Time
Source string
Err string
}
PromotionSnapshot 是一次读取站点得到的优惠快照。不变量:free_until 一定有晚于 VerifiedAt 的 EndsAt; free_permanent 只来自站点明确语义;unknown 不是免费放行的凭据。EndsAt 一律是绝对时间。
type Ranker ¶
type Ranker struct {
// contains filtered or unexported fields
}
Ranker scores and ranks torrent search results
func NewRanker ¶
func NewRanker(config RankerConfig) *Ranker
NewRanker creates a new Ranker with the given configuration
func (*Ranker) GetSiteReliability ¶
GetSiteReliability returns the reliability score for a site
func (*Ranker) Rank ¶
func (r *Ranker) Rank(items []TorrentItem) []TorrentItem
Rank sorts torrents by score in descending order
func (*Ranker) Score ¶
func (r *Ranker) Score(item TorrentItem) float64
Score calculates a score for a torrent item
func (*Ranker) SetSiteReliability ¶
SetSiteReliability sets the reliability score for a site
type RankerConfig ¶
type RankerConfig struct {
// SeederWeight is the weight for seeders in scoring (default: 1.0)
SeederWeight float64 `json:"seederWeight,omitempty"`
// LeecherWeight is the weight for leechers in scoring (default: 0.5)
LeecherWeight float64 `json:"leecherWeight,omitempty"`
// FreeBonus is the bonus score for free torrents (default: 100)
FreeBonus float64 `json:"freeBonus,omitempty"`
// SizeWeight is the weight for size in scoring (default: 0.1)
SizeWeight float64 `json:"sizeWeight,omitempty"`
// RecencyWeight is the weight for recency in scoring (default: 0.2)
RecencyWeight float64 `json:"recencyWeight,omitempty"`
// SiteReliability maps site IDs to reliability scores (0-1)
SiteReliability map[string]float64 `json:"siteReliability,omitempty"`
}
RankerConfig holds configuration for the Ranker
type RequestConfig ¶
type RequestConfig struct {
// URL is the request path (e.g., "/index.php")
URL string `json:"url"`
// Method is the HTTP method (default: GET)
Method string `json:"method,omitempty"`
// Params are query parameters
Params map[string]string `json:"params,omitempty"`
// Data is the request body for POST requests
Data map[string]any `json:"data,omitempty"`
// ResponseType is "document" for HTML or "json" for JSON
ResponseType string `json:"responseType,omitempty"`
// Headers are additional HTTP headers
Headers map[string]string `json:"headers,omitempty"`
}
RequestConfig for HTTP requests
type RequestsClient ¶
type RequestsClient struct {
// contains filtered or unexported fields
}
RequestsClient provides a high-level HTTP client using requests library
func NewRequestsClient ¶
func NewRequestsClient(config HTTPClientConfig, retryConfig RetryConfig, logger *zap.Logger) *RequestsClient
NewRequestsClient creates a new requests-based HTTP client
func (*RequestsClient) Close ¶
func (c *RequestsClient) Close() error
Close closes the underlying session
func (*RequestsClient) Get ¶
func (c *RequestsClient) Get(ctx context.Context, url string, opts ...requests.RequestOption) (*RequestsResponse, error)
Get performs a GET request with retry logic
func (*RequestsClient) Post ¶
func (c *RequestsClient) Post(ctx context.Context, url string, body any, opts ...requests.RequestOption) (*RequestsResponse, error)
Post performs a POST request with retry logic
type RequestsResponse ¶
type RequestsResponse struct {
// contains filtered or unexported fields
}
RequestsResponse wraps the response from requests library
func (*RequestsResponse) Bytes ¶
func (r *RequestsResponse) Bytes() []byte
Bytes returns the response body as bytes
func (*RequestsResponse) Headers ¶
func (r *RequestsResponse) Headers() http.Header
Headers returns the response headers
func (*RequestsResponse) IsError ¶
func (r *RequestsResponse) IsError() bool
IsError returns true if status code is 4xx or 5xx
func (*RequestsResponse) IsSuccess ¶
func (r *RequestsResponse) IsSuccess() bool
IsSuccess returns true if status code is 2xx
func (*RequestsResponse) StatusCode ¶
func (r *RequestsResponse) StatusCode() int
StatusCode returns the HTTP status code
func (*RequestsResponse) Text ¶
func (r *RequestsResponse) Text() string
Text returns the response body as string
type RetryConfig ¶
type RetryConfig struct {
// MaxRetries is the maximum number of retries
MaxRetries int
// InitialBackoff is the initial backoff duration
InitialBackoff time.Duration
// MaxBackoff is the maximum backoff duration
MaxBackoff time.Duration
// BackoffMultiplier is the backoff multiplier
BackoffMultiplier float64
// Jitter adds randomness to backoff
Jitter bool
// RetryableStatusCodes are HTTP status codes that should trigger a retry
RetryableStatusCodes []int
}
RetryConfig holds configuration for retry logic
func DefaultRetryConfig ¶
func DefaultRetryConfig() RetryConfig
DefaultRetryConfig returns default retry configuration
type RetryableHTTPClient ¶
type RetryableHTTPClient struct {
// contains filtered or unexported fields
}
RetryableHTTPClient wraps an HTTP client with retry logic
func NewRetryableHTTPClient ¶
func NewRetryableHTTPClient(client *http.Client, config RetryConfig, logger *zap.Logger) *RetryableHTTPClient
NewRetryableHTTPClient creates a new retryable HTTP client
type RousiOptions ¶ added in v0.10.0
type Schema ¶ added in v0.10.0
type Schema string
Schema represents the site architecture/schema type
const ( // SchemaNexusPHP is the NexusPHP architecture (most common for Chinese PT sites) SchemaNexusPHP Schema = "NexusPHP" // SchemaMTorrent is M-Team's custom API architecture SchemaMTorrent Schema = "mTorrent" // SchemaUnit3D is the Unit3D architecture SchemaUnit3D Schema = "Unit3D" // SchemaGazelle is the Gazelle architecture SchemaGazelle Schema = "Gazelle" // SchemaHDDolby is HDDolby's custom REST API architecture SchemaHDDolby Schema = "HDDolby" // SchemaRousi is RousiPro's custom architecture SchemaRousi Schema = "Rousi" )
func (Schema) DefaultAuthMethod ¶ added in v0.10.0
func (s Schema) DefaultAuthMethod() AuthMethod
DefaultAuthMethod returns the default auth method for this schema
func (Schema) ToSiteKind ¶ added in v0.10.0
ToSiteKind converts a Schema to corresponding SiteKind
type SearchCache ¶
type SearchCache struct {
// contains filtered or unexported fields
}
SearchCache provides caching for search results
func NewSearchCache ¶
func NewSearchCache(config SearchCacheConfig) *SearchCache
NewSearchCache creates a new SearchCache
func (*SearchCache) Cleanup ¶
func (c *SearchCache) Cleanup() int
Cleanup removes expired entries from the cache
func (*SearchCache) Delete ¶
func (c *SearchCache) Delete(query MultiSiteSearchQuery)
Delete removes a specific entry from the cache
func (*SearchCache) Get ¶
func (c *SearchCache) Get(query MultiSiteSearchQuery) (*MultiSiteSearchResult, bool)
Get retrieves a cached search result
func (*SearchCache) Item ¶ added in v1.0.0
func (c *SearchCache) Item(site, id string) (TorrentItem, bool)
Item 取缓存的搜索结果里的一个种子(按站点与种子编号;过期的不算)。
func (*SearchCache) Set ¶
func (c *SearchCache) Set(query MultiSiteSearchQuery, result *MultiSiteSearchResult)
Set stores a search result in the cache
func (*SearchCache) Size ¶
func (c *SearchCache) Size() int
Size returns the number of entries in the cache
type SearchCacheConfig ¶
type SearchCacheConfig struct {
// TTL is the time-to-live for cache entries (default: 5 minutes)
TTL time.Duration `json:"ttl,omitempty"`
// MaxSize is the maximum number of entries (default: 1000)
MaxSize int `json:"maxSize,omitempty"`
}
SearchCacheConfig holds configuration for SearchCache
type SearchError ¶
SearchError represents an error from a specific site
type SearchOrchestrator ¶
type SearchOrchestrator struct {
// contains filtered or unexported fields
}
SearchOrchestrator coordinates concurrent searches across multiple sites
func NewSearchOrchestrator ¶
func NewSearchOrchestrator(config SearchOrchestratorConfig) *SearchOrchestrator
NewSearchOrchestrator creates a new SearchOrchestrator
func (*SearchOrchestrator) GetSite ¶
func (o *SearchOrchestrator) GetSite(siteID string) Site
GetSite returns a registered site by ID, or nil if not found
func (*SearchOrchestrator) ListSites ¶
func (o *SearchOrchestrator) ListSites() []string
ListSites returns all registered site IDs
func (*SearchOrchestrator) RegisterSite ¶
func (o *SearchOrchestrator) RegisterSite(site Site)
RegisterSite adds a site to the orchestrator
func (*SearchOrchestrator) Search ¶
func (o *SearchOrchestrator) Search(ctx context.Context, query MultiSiteSearchQuery) (*MultiSiteSearchResult, error)
Search performs a concurrent search across multiple sites
func (*SearchOrchestrator) UnregisterSite ¶
func (o *SearchOrchestrator) UnregisterSite(siteID string)
UnregisterSite removes a site from the orchestrator
type SearchOrchestratorConfig ¶
SearchOrchestratorConfig holds configuration for SearchOrchestrator
type SearchQuery ¶
type SearchQuery struct {
// Keyword is the search term
Keyword string `json:"keyword"`
// Category filters by torrent category
Category string `json:"category,omitempty"`
// FreeOnly filters to only show free torrents
FreeOnly bool `json:"freeOnly,omitempty"`
// Page is the page number (1-indexed)
Page int `json:"page,omitempty"`
// PageSize is the number of results per page
PageSize int `json:"pageSize,omitempty"`
// SortBy specifies the sort field
SortBy string `json:"sortBy,omitempty"`
// OrderDesc specifies descending order when true
OrderDesc bool `json:"orderDesc,omitempty"`
// Section 是站点分区:M-Team 取 normal(综合区)或 adult(成人区),空值按 normal;其他站点忽略
Section string `json:"section,omitempty"`
}
SearchQuery represents a search request to a PT site
func (*SearchQuery) Validate ¶
func (q *SearchQuery) Validate() error
Validate validates the search query
type Session ¶
type Session struct {
SiteID string
Cookie string
APIKey string
SessionID string // For Transmission
ExpiresAt time.Time
LastUsed time.Time
LoginCount int
// contains filtered or unexported fields
}
Session represents an authentication session
type SessionCookieHolder ¶ added in v1.0.0
SessionCookieHolder 是有续期会话的站点或驱动:CurrentCookie 是现在用的那组(续期过就是换发后的);没有续期会话时 ok 为假。
type SessionCookieSink ¶ added in v1.0.0
SessionCookieSink 存续期后换发的那组 Cookie:chain 是这个会话用过的 Cookie(旧的在前,最后一个就是 renewed)。 站点设置里存着的是 chain 里的一个时换成 renewed;已经是别的(扩展推来了新的、用户改了)时不要覆盖,返回 stored=false。 cmd 里接到 ConfigStore。
type SessionManager ¶
type SessionManager struct {
// contains filtered or unexported fields
}
SessionManager manages authentication sessions for sites
func NewSessionManager ¶
func NewSessionManager(logger *zap.Logger) *SessionManager
NewSessionManager creates a new session manager
func (*SessionManager) GetSession ¶
func (m *SessionManager) GetSession(siteID string) (*Session, bool)
GetSession returns the session for a site
func (*SessionManager) IncrementLoginCount ¶
func (m *SessionManager) IncrementLoginCount(siteID string) int
IncrementLoginCount increments the login count for a session
func (*SessionManager) InvalidateSession ¶
func (m *SessionManager) InvalidateSession(siteID string)
InvalidateSession marks a session as expired
func (*SessionManager) IsSessionValid ¶
func (m *SessionManager) IsSessionValid(siteID string) bool
IsSessionValid checks if a session is still valid
func (*SessionManager) RemoveSession ¶
func (m *SessionManager) RemoveSession(siteID string)
RemoveSession removes a session
func (*SessionManager) ResetLoginCount ¶
func (m *SessionManager) ResetLoginCount(siteID string)
ResetLoginCount resets the login count for a session
func (*SessionManager) SetSession ¶
func (m *SessionManager) SetSession(siteID string, session *Session)
SetSession sets the session for a site
func (*SessionManager) UpdateSessionID ¶
func (m *SessionManager) UpdateSessionID(siteID, sessionID string)
UpdateSessionID updates the session ID (for Transmission)
type Site ¶
type Site interface {
// ID returns the unique site identifier
ID() string
// Name returns the human-readable site name
Name() string
// Kind returns the site architecture type
Kind() SiteKind
// Login authenticates with the site
Login(ctx context.Context, creds Credentials) error
// Search searches for torrents
Search(ctx context.Context, query SearchQuery) ([]TorrentItem, error)
// GetUserInfo fetches the current user's information
GetUserInfo(ctx context.Context) (UserInfo, error)
// Download downloads a torrent file by ID
Download(ctx context.Context, torrentID string) ([]byte, error)
// Close releases any resources held by the site
Close() error
}
Site is the core interface for interacting with a PT site
func CreateSiteFromDefinition ¶ added in v0.10.0
func CreateSiteFromDefinition(def *SiteDefinition, config SiteConfig, logger *zap.Logger) (Site, error)
type SiteAdapter ¶
type SiteAdapter struct {
// OldSite is the old site implementation (if any)
OldSite any
// NewSite is the new v2 site implementation
NewSite Site
// UseNew indicates whether to use the new implementation
UseNew bool
}
SiteAdapter provides an adapter layer to use old site implementations with new interface This allows gradual migration of site implementations
func NewSiteAdapter ¶
func NewSiteAdapter(oldSite any, newSite Site, useNew bool) *SiteAdapter
NewSiteAdapter creates a new SiteAdapter If newSite is provided and useNew is true, it will be used Otherwise, oldSite will be used (for backward compatibility)
func (*SiteAdapter) GetSite ¶
func (a *SiteAdapter) GetSite() any
GetSite returns the appropriate site implementation based on configuration
func (*SiteAdapter) IsUsingNewImplementation ¶
func (a *SiteAdapter) IsUsingNewImplementation() bool
IsUsingNewImplementation returns true if using the new v2 implementation
type SiteCategoryConfig ¶
type SiteCategoryConfig struct {
SiteID string `json:"siteId"`
SiteName string `json:"siteName"`
Categories []CategoryDefinition `json:"categories"`
}
SiteCategoryConfig 站点分类配置
func GetSiteCategoryConfig ¶
func GetSiteCategoryConfig(siteID string) *SiteCategoryConfig
GetSiteCategoryConfig 获取站点分类配置
type SiteConfig ¶
type SiteCredentials ¶
SiteCredentials holds authentication credentials for a site
type SiteDefinition ¶
type SiteDefinition struct {
ID string `json:"id"`
Name string `json:"name"`
Aka []string `json:"aka,omitempty"`
Description string `json:"description,omitempty"`
Schema Schema `json:"schema"`
URLs []string `json:"urls"`
WebURL string `json:"webUrl,omitempty"`
LegacyURLs []string `json:"legacyUrls,omitempty"`
// TrackerHosts 是 tracker 用的主机名或可注册域,只在它们与站点地址的可注册域不同时才需要写。
TrackerHosts []string `json:"trackerHosts,omitempty"`
FaviconURL string `json:"faviconUrl,omitempty"`
AuthMethod AuthMethod `json:"authMethod,omitempty"`
RateLimit float64 `json:"rateLimit,omitempty"`
RateBurst int `json:"rateBurst,omitempty"`
RateWindow time.Duration `json:"-"`
RateWindowLimit int `json:"rateWindowLimit,omitempty"`
HREnabled bool `json:"hrEnabled,omitempty"`
HRSeedTimeHours int `json:"hrSeedTimeHours,omitempty"`
HRSeedTimeRules []HRSeedTimeRule `json:"hrSeedTimeRules,omitempty"`
// HRCalcSeedTime is an optional custom function that calculates the required
// HR seed time (in hours) for a torrent based on its size in bytes.
// This allows each site to implement its own HR rule logic.
// If nil, CalcHRSeedTimeH() falls back to HRSeedTimeRules, then HRSeedTimeHours.
HRCalcSeedTime func(sizeBytes int64) int `json:"-"`
TimezoneOffset string `json:"timezoneOffset,omitempty"`
UserInfo *UserInfoConfig `json:"userInfo,omitempty"`
LevelRequirements []SiteLevelRequirement `json:"levelRequirements,omitempty"`
Selectors *SiteSelectors `json:"selectors,omitempty"`
DetailParser *DetailParserConfig `json:"detailParser,omitempty"`
// Attendance 是每日签到配置;为空时 NexusPHP 站点用 DefaultNexusPHPAttendance,其他架构不支持签到。
Attendance *AttendanceConfig `json:"attendance,omitempty"`
// SessionCookies 是站点会续期换发的登录 Cookie(BYR:auth_token 15 分钟过期,过期后站点用 refresh_token 换发一对新的,
// refresh_token 也换)。写了的 NexusPHP 站点:同一个实例的请求排队发,响应里换了这些 Cookie 就用新值接着请求,
// 并经 SessionCookieSink 存回站点设置(见 session_cookies.go)。没写的站点照旧只用存着的那组。
SessionCookies []string `json:"sessionCookies,omitempty"`
// CreateDriver is an optional custom driver factory for this site.
// If nil, the driver is created based on Schema field.
// This allows sites with unique APIs to provide custom driver logic.
CreateDriver DriverFactory `json:"-"`
}
func (*SiteDefinition) CalcHRSeedTimeH ¶ added in v0.19.0
func (d *SiteDefinition) CalcHRSeedTimeH(sizeBytes int64) int
func (*SiteDefinition) HasHRSeedTimeRule ¶ added in v1.0.0
func (d *SiteDefinition) HasHRSeedTimeRule() bool
HasHRSeedTimeRule 报告站点定义里写了 H&R 做种时长(固定值、按体积分档或自定义规则)。
func (*SiteDefinition) Validate ¶ added in v0.12.3
func (d *SiteDefinition) Validate() error
Validate checks the SiteDefinition for completeness and correctness. Returns nil if valid, or ValidationErrors containing all issues found.
type SiteDefinitionRegistry ¶
type SiteDefinitionRegistry struct {
// contains filtered or unexported fields
}
SiteDefinitionRegistry manages site definitions
func GetDefinitionRegistry ¶
func GetDefinitionRegistry() *SiteDefinitionRegistry
GetDefinitionRegistry returns the global site definition registry
func (*SiteDefinitionRegistry) Get ¶
func (r *SiteDefinitionRegistry) Get(siteID string) (*SiteDefinition, bool)
Get retrieves a site definition by ID
func (*SiteDefinitionRegistry) GetAll ¶
func (r *SiteDefinitionRegistry) GetAll() []*SiteDefinition
GetAll returns all registered site definitions
func (*SiteDefinitionRegistry) GetOrDefault ¶
func (r *SiteDefinitionRegistry) GetOrDefault(siteID string) *SiteDefinition
GetOrDefault returns site definition or nil if not found
func (*SiteDefinitionRegistry) List ¶
func (r *SiteDefinitionRegistry) List() []string
List returns all registered site IDs
func (*SiteDefinitionRegistry) Register ¶
func (r *SiteDefinitionRegistry) Register(def *SiteDefinition)
Register adds a site definition to the registry. Panics if a definition with the same ID is already registered.
type SiteDelta ¶ added in v1.0.0
type SiteDelta struct {
Site string `json:"site"`
// From 是基线快照的日期,To 是区间内最新一份快照的日期。
From string `json:"from"`
To string `json:"to"`
Uploaded int64 `json:"uploaded"`
Downloaded int64 `json:"downloaded"`
Bonus float64 `json:"bonus"`
// HasBaseline 为 false 表示区间里只有一份快照、之前也没有,增量记 0。
HasBaseline bool `json:"hasBaseline"`
// Negative 表示有数值回退,那一项按 0 计,不进合计。
Negative bool `json:"negative"`
}
SiteDelta 是某站在区间内的增量。
type SiteFactory ¶
type SiteFactory struct {
// contains filtered or unexported fields
}
func NewSiteFactory ¶
func NewSiteFactory(logger *zap.Logger) *SiteFactory
func (*SiteFactory) CreateSite ¶
func (f *SiteFactory) CreateSite(config SiteConfig) (Site, error)
func (*SiteFactory) CreateSiteFromJSON ¶
func (f *SiteFactory) CreateSiteFromJSON(jsonData []byte) (Site, error)
func (*SiteFactory) CreateSitesFromJSON ¶
func (f *SiteFactory) CreateSitesFromJSON(jsonData []byte) ([]Site, error)
type SiteHTTPClient ¶
type SiteHTTPClient struct {
// contains filtered or unexported fields
}
SiteHTTPClient provides a unified HTTP client interface for site drivers using the requests library instead of net/http directly
func NewSiteHTTPClient ¶
func NewSiteHTTPClient(config SiteHTTPClientConfig) *SiteHTTPClient
NewSiteHTTPClient creates a new SiteHTTPClient
func (*SiteHTTPClient) Close ¶
func (c *SiteHTTPClient) Close() error
Close closes the underlying session
func (*SiteHTTPClient) DoRequest ¶
func (c *SiteHTTPClient) DoRequest(ctx context.Context, method, url string, body io.Reader, headers map[string]string) (*HTTPResponse, error)
DoRequest performs an HTTP request using the requests library
func (*SiteHTTPClient) Get ¶
func (c *SiteHTTPClient) Get(ctx context.Context, url string, headers map[string]string) (*HTTPResponse, error)
Get performs a GET request
type SiteHTTPClientConfig ¶
type SiteHTTPClientConfig struct {
Timeout time.Duration
MaxIdleConns int
IdleConnTimeout time.Duration
DisableKeepAlives bool
ProxyURL string
UserAgent string
Logger *zap.Logger
// SiteID 是这个客户端所属站点的注册表 ID:全局设置里的「站点代理」按它判定走不走代理,为空时按环境变量
SiteID string
}
SiteHTTPClientConfig holds configuration for SiteHTTPClient
func DefaultSiteHTTPClientConfig ¶
func DefaultSiteHTTPClientConfig() SiteHTTPClientConfig
DefaultSiteHTTPClientConfig returns default configuration
type SiteKind ¶
type SiteKind string
SiteKind represents the type of PT site architecture
const ( // SiteNexusPHP represents NexusPHP-based sites (e.g., HDSky, CHDBits) SiteNexusPHP SiteKind = "nexusphp" // SiteUnit3D represents Unit3D-based sites SiteUnit3D SiteKind = "unit3d" // SiteGazelle represents Gazelle-based sites (e.g., What.CD clones) SiteGazelle SiteKind = "gazelle" // SiteMTorrent represents M-Team's custom API SiteMTorrent SiteKind = "mtorrent" // SiteHDDolby represents HDDolby's REST API SiteHDDolby SiteKind = "hddolby" // SiteRousi represents Rousi-based sites using passkey auth SiteRousi SiteKind = "rousi" )
func GetSiteKind ¶
GetSiteKind returns the architecture kind for a site
type SiteLevelProgressInfo ¶
type SiteLevelProgressInfo struct {
// CurrentLevel is the current level requirement
CurrentLevel *SiteLevelRequirement `json:"currentLevel,omitempty"`
// NextLevel is the next level requirement
NextLevel *SiteLevelRequirement `json:"nextLevel,omitempty"`
// UnmetRequirements contains what's still needed
UnmetRequirements map[string]any `json:"unmetRequirements,omitempty"`
// ProgressPercent is the overall progress percentage (0-100)
ProgressPercent float64 `json:"progressPercent"`
}
SiteLevelProgressInfo represents progress towards the next user level
func CalculateSiteLevelProgress ¶
func CalculateSiteLevelProgress(info *UserInfo, requirements []SiteLevelRequirement) *SiteLevelProgressInfo
CalculateSiteLevelProgress calculates progress to next level
type SiteLevelRequirement ¶
type SiteLevelRequirement struct {
// ID is the numeric level identifier
ID int `json:"id"`
// Name is the level name (e.g., "Power User")
Name string `json:"name"`
// NameAka contains alternative names for matching
NameAka []string `json:"nameAka,omitempty"`
// GroupType: "user", "vip", "manager"
GroupType LevelGroupType `json:"groupType,omitempty"`
// Requirements (all optional)
// Interval is ISO 8601 duration (e.g., "P5W" for 5 weeks)
Interval string `json:"interval,omitempty"`
// Downloaded is size string (e.g., "200GB")
Downloaded string `json:"downloaded,omitempty"`
// Uploaded is size string
Uploaded string `json:"uploaded,omitempty"`
// Ratio is minimum ratio
Ratio float64 `json:"ratio,omitempty"`
// Bonus is minimum bonus points
Bonus float64 `json:"bonus,omitempty"`
// Extended requirements
// SeedingBonus is seeding bonus points requirement
SeedingBonus float64 `json:"seedingBonus,omitempty"`
// Uploads is number of uploads requirement
Uploads int `json:"uploads,omitempty"`
// Seeding is number of seeding torrents requirement
Seeding int `json:"seeding,omitempty"`
// SeedingSize is total seeding size requirement
SeedingSize string `json:"seedingSize,omitempty"`
// Alternative contains OR-based alternative requirements
Alternative []AlternativeRequirement `json:"alternative,omitempty"`
// Privilege describes the privileges granted at this level
Privilege string `json:"privilege,omitempty"`
}
SiteLevelRequirement defines requirements for a user level (site-specific) This is different from LevelRequirement in level_manager.go which is for generic level management
type SiteMeta ¶
type SiteMeta struct {
// ID is the unique site identifier (e.g., "mteam", "hdsky")
ID string
// Name is the human-readable site name
Name string
// Kind is the site architecture type
Kind SiteKind
// DefaultBaseURL is the default base URL for the site
DefaultBaseURL string
// AuthMethod is the authentication method
AuthMethod AuthMethod
// RateLimit is the default rate limit (requests per second)
RateLimit float64
// RateBurst is the default rate burst
RateBurst int
}
SiteMeta contains metadata for a site type
type SiteMetrics ¶
type SiteMetrics struct {
// contains filtered or unexported fields
}
SiteMetrics provides site-specific metrics
func NewSiteMetrics ¶
func NewSiteMetrics(registry *MetricsRegistry) *SiteMetrics
NewSiteMetrics creates a new site metrics instance
func (*SiteMetrics) RecordCacheHit ¶
func (m *SiteMetrics) RecordCacheHit(cacheType string)
RecordCacheHit records a cache hit
func (*SiteMetrics) RecordCacheMiss ¶
func (m *SiteMetrics) RecordCacheMiss(cacheType string)
RecordCacheMiss records a cache miss
func (*SiteMetrics) RecordDownloaderRequest ¶
func (m *SiteMetrics) RecordDownloaderRequest(downloader string, success bool, duration time.Duration)
RecordDownloaderRequest records a downloader request
func (*SiteMetrics) RecordError ¶
func (m *SiteMetrics) RecordError(errorType string)
RecordError records an error by type
func (*SiteMetrics) RecordRequest ¶
func (m *SiteMetrics) RecordRequest(site string, success bool, duration time.Duration)
RecordRequest records a site request
func (*SiteMetrics) SetActiveDownloaders ¶
func (m *SiteMetrics) SetActiveDownloaders(count int)
SetActiveDownloaders sets the number of active downloaders
func (*SiteMetrics) SetActiveSites ¶
func (m *SiteMetrics) SetActiveSites(count int)
SetActiveSites sets the number of active sites
func (*SiteMetrics) Snapshot ¶
func (m *SiteMetrics) Snapshot() MetricsSnapshot
Snapshot returns a snapshot of all metrics
type SiteMigrationGuide ¶
type SiteMigrationGuide struct {
SiteType string `json:"siteType"`
OldFormat string `json:"oldFormat"`
NewFormat string `json:"newFormat"`
Steps []string `json:"steps"`
Notes []string `json:"notes,omitempty"`
BreakingChanges []string `json:"breakingChanges,omitempty"`
}
SiteMigrationGuide provides migration guidance for each site type
func GetSiteMigrationGuides ¶
func GetSiteMigrationGuides() []SiteMigrationGuide
GetSiteMigrationGuides returns migration guides for all site types
type SiteMigrationManager ¶
type SiteMigrationManager struct {
// contains filtered or unexported fields
}
SiteMigrationManager manages the migration of sites from old to new implementation
func NewSiteMigrationManager ¶
func NewSiteMigrationManager(logger *zap.Logger) *SiteMigrationManager
NewSiteMigrationManager creates a new SiteMigrationManager
func (*SiteMigrationManager) GetMigrationStatus ¶
func (m *SiteMigrationManager) GetMigrationStatus() []MigrationStatus
GetMigrationStatus returns the migration status of all registered sites
func (*SiteMigrationManager) GetNewSite ¶
func (m *SiteMigrationManager) GetNewSite(siteID string) Site
GetNewSite returns the new v2 site implementation if available
func (*SiteMigrationManager) GetSite ¶
func (m *SiteMigrationManager) GetSite(siteID string) any
GetSite returns the site implementation for the given ID
func (*SiteMigrationManager) MigrateToNew ¶
func (m *SiteMigrationManager) MigrateToNew(siteID string) error
MigrateToNew switches a site to use the new implementation
func (*SiteMigrationManager) RegisterSite ¶
func (m *SiteMigrationManager) RegisterSite(siteID string, oldSite any, newSite Site, useNew bool)
RegisterSite registers a site with both old and new implementations
func (*SiteMigrationManager) RollbackToOld ¶
func (m *SiteMigrationManager) RollbackToOld(siteID string) error
RollbackToOld switches a site back to the old implementation
type SiteName ¶
type SiteName string
SiteName represents a PT site identifier
const ( SiteNameMTeam SiteName = "mteam" SiteNameHDSky SiteName = "hdsky" SiteNameSpringSunday SiteName = "springsunday" SiteNameCHDBits SiteName = "chdbits" SiteNameTTG SiteName = "ttg" SiteNameOurBits SiteName = "ourbits" SiteNamePterClub SiteName = "pterclub" SiteNameAudiences SiteName = "audiences" )
Site name constants
type SiteRegistry ¶
type SiteRegistry struct {
// contains filtered or unexported fields
}
SiteRegistry manages site metadata and creation
func GetGlobalSiteRegistry ¶ added in v0.6.0
func GetGlobalSiteRegistry() *SiteRegistry
GetGlobalSiteRegistry returns the global site registry singleton
func NewSiteRegistry ¶
func NewSiteRegistry(logger *zap.Logger) *SiteRegistry
NewSiteRegistry creates a new SiteRegistry with default site metadata
func (*SiteRegistry) CreateSite ¶
func (r *SiteRegistry) CreateSite(siteID string, creds SiteCredentials, customBaseURL string) (Site, error)
CreateSite creates a Site instance from registry metadata and credentials
func (*SiteRegistry) Get ¶
func (r *SiteRegistry) Get(id string) (SiteMeta, bool)
Get returns site metadata by ID
func (*SiteRegistry) GetDefaultBaseURL ¶
func (r *SiteRegistry) GetDefaultBaseURL(siteID string) (string, bool)
GetDefaultBaseURL returns the default base URL for a given site ID
func (*SiteRegistry) GetSiteKind ¶
func (r *SiteRegistry) GetSiteKind(siteID string) (SiteKind, bool)
GetSiteKind returns the site kind for a given site ID
func (*SiteRegistry) List ¶
func (r *SiteRegistry) List() []string
List returns all registered site IDs
func (*SiteRegistry) Register ¶
func (r *SiteRegistry) Register(meta SiteMeta)
Register adds or updates site metadata
type SiteSelectors ¶
type SiteSelectors struct {
// TableRows selects torrent rows in the search results
TableRows string `json:"tableRows"`
// Title selects the torrent title
Title string `json:"title"`
// TitleLink selects the link containing torrent ID
TitleLink string `json:"titleLink"`
// Size selects the torrent size
Size string `json:"size"`
// Seeders selects the seeder count
Seeders string `json:"seeders"`
// Leechers selects the leecher count
Leechers string `json:"leechers"`
// Snatched selects the snatch count
Snatched string `json:"snatched"`
// DiscountIcon selects the discount icon element
DiscountIcon string `json:"discountIcon"`
// DiscountMapping maps keywords to discount levels (optional, uses default if nil)
// Keys are matched against class, src, alt attributes (case-insensitive)
DiscountMapping map[string]DiscountLevel `json:"discountMapping,omitempty"`
// DiscountEndTime selects the discount end time
DiscountEndTime string `json:"discountEndTime"`
// DownloadLink selects the download link
DownloadLink string `json:"downloadLink"`
// Category selects the category
Category string `json:"category"`
// UploadTime selects the upload time
UploadTime string `json:"uploadTime"`
// HRIcon selects the H&R icon
HRIcon string `json:"hrIcon"`
// Subtitle selects the subtitle in search results
Subtitle string `json:"subtitle"`
// SubtitleSelector extracts subtitles that require HTML attributes or filters
SubtitleSelector *FieldSelector `json:"subtitleSelector,omitempty"`
// UserInfo selectors for user page
UserInfoUsername string `json:"userInfoUsername"`
UserInfoUploaded string `json:"userInfoUploaded"`
UserInfoDownloaded string `json:"userInfoDownloaded"`
UserInfoRatio string `json:"userInfoRatio"`
UserInfoBonus string `json:"userInfoBonus"`
UserInfoRank string `json:"userInfoRank"`
// Detail page selectors
// DetailDownloadLink selects the download link from details page
DetailDownloadLink string `json:"detailDownloadLink"`
// DetailSubtitle selects the subtitle from details page
DetailSubtitle string `json:"detailSubtitle"`
}
SiteSelectors defines CSS selectors for parsing NexusPHP pages
func DefaultNexusPHPSelectors ¶
func DefaultNexusPHPSelectors() SiteSelectors
DefaultNexusPHPSelectors returns default selectors for standard NexusPHP sites
type SiteURLRegistry ¶
type SiteURLRegistry struct {
// contains filtered or unexported fields
}
SiteURLRegistry manages site URL configurations It provides a centralized way to register and retrieve site URLs
func GetGlobalRegistry ¶
func GetGlobalRegistry() *SiteURLRegistry
GetGlobalRegistry returns the global site URL registry
func NewSiteURLRegistry ¶
func NewSiteURLRegistry(logger *zap.Logger) *SiteURLRegistry
NewSiteURLRegistry creates a new site URL registry
func (*SiteURLRegistry) GetFailoverClient ¶
func (r *SiteURLRegistry) GetFailoverClient(siteName SiteName, opts ...FailoverOption) (*FailoverHTTPClient, error)
GetFailoverClient creates a FailoverHTTPClient for the specified site
func (*SiteURLRegistry) GetFailoverConfig ¶
func (r *SiteURLRegistry) GetFailoverConfig(siteName SiteName) (URLFailoverConfig, error)
GetFailoverConfig returns a failover config for the specified site
func (*SiteURLRegistry) GetURLs ¶
func (r *SiteURLRegistry) GetURLs(siteName SiteName) []string
GetURLs returns the URL list for a site Returns nil if the site is not registered
func (*SiteURLRegistry) HasSite ¶
func (r *SiteURLRegistry) HasSite(siteName SiteName) bool
HasSite checks if a site is registered
func (*SiteURLRegistry) ListSites ¶
func (r *SiteURLRegistry) ListSites() []SiteName
ListSites returns all registered site names
func (*SiteURLRegistry) RegisterURLs ¶
func (r *SiteURLRegistry) RegisterURLs(siteName SiteName, urls []string)
RegisterURLs registers or updates URLs for a site
type Subtitle ¶ added in v1.0.0
type Subtitle struct {
// ID 是字幕的编号(downloadsubs.php 的 subid);TorrentID 是字幕挂在哪个种子上(torrentid,同一部别的种子的字幕也会列出来)
ID string `json:"id"`
TorrentID string `json:"torrent_id"`
// Title 是列表上写的标题(多数是上传时的文件名)
Title string `json:"title"`
// Language 是列表上写的语言(国旗图的 alt 或 title,例如「简体中文」);Flag 是国旗图的文件名(例如 china.gif)。站点没写时为空
Language string `json:"language,omitempty"`
Flag string `json:"flag,omitempty"`
}
Subtitle 是站点上一个种子的一份字幕(NexusPHP 详情页「字幕」一行里的一项)。
type SubtitleFile ¶ added in v1.0.0
SubtitleFile 是下载下来的一份字幕:Name 是站点给的文件名(只留最后一段,没有时为空)。
type SubtitleProvider ¶ added in v1.0.0
type SubtitleProvider interface {
// ListSubtitles 是这个种子的字幕(站点上没有时是空的);种子不在了返回包装了 ErrTorrentNotFound 的错误
ListSubtitles(ctx context.Context, torrentID string) ([]Subtitle, error)
// DownloadSubtitle 下载列表里的一份字幕;站点上没有了返回包装了 ErrSubtitleNotFound 的错误
DownloadSubtitle(ctx context.Context, sub Subtitle) (SubtitleFile, error)
}
SubtitleProvider 是能列出、下载种子字幕的驱动(可选接口,现在只有 NexusPHP)。
type SubtitleSource ¶ added in v1.0.0
type SubtitleSource interface {
Subtitles() SubtitleProvider
}
SubtitleSource 是能给出 SubtitleProvider 的站点(BaseSite):驱动支持字幕时返回的 SubtitleProvider 每次请求先等站点限速的令牌、 一时的错误按退避重试;不支持时返回 nil。
type Timer ¶
type Timer struct {
// contains filtered or unexported fields
}
Timer measures elapsed time
func (*Timer) ObserveDuration ¶
ObserveDuration records the elapsed time since the timer was created
type TorrentDetail ¶
type TorrentDetail struct {
// DownloadURL is the direct download URL with passkey
DownloadURL string `json:"downloadUrl"`
// Subtitle is the torrent subtitle
Subtitle string `json:"subtitle"`
// InfoHash is the torrent info hash
InfoHash string `json:"infoHash,omitempty"`
}
TorrentDetail contains detailed information from a torrent detail page
type TorrentDetailFetcher ¶ added in v0.10.0
type TorrentDetailFetcher interface {
// GetTorrentDetail fetches detailed torrent info given an RSS item's GUID and link.
// The guid is typically the torrent ID, and link is the detail page URL.
// 能判断出找不到种子、或读不到详情时,返回包装了 ErrTorrentDetailUnavailable 的错误,不返回 (nil, nil),
// 也不返回一个「没有优惠」的占位结果(那等于声称不是免费)。
// 实时请求得到的结果写 FetchedAt;结果来自缓存时 FetchedAt 是缓存刷新的时间。
GetTorrentDetail(ctx context.Context, guid, link, title string) (*TorrentItem, error)
}
TorrentDetailFetcher is an optional interface for drivers that can fetch torrent details from RSS item metadata. This is used by RSS processing to get discount info, size, etc. Drivers that implement this interface can be used with GetTorrentDetails in unified_site.go.
type TorrentDetailInfo ¶
type TorrentDetailInfo struct {
TorrentID string
Title string
SizeMB float64
DiscountLevel DiscountLevel
DiscountEnd time.Time
// DiscountErr 是读取优惠时遇到的问题:有优惠、结束时间元素也在,但值无法解析(只写字段名与错误类型)
DiscountErr string
HasHR bool
IMDbID string
DoubanID string
}
TorrentDetailInfo 解析后的种子详情
type TorrentFile ¶
TorrentFile represents a file in a torrent
type TorrentItem ¶
type TorrentItem struct {
// ID is the site-specific torrent identifier
ID string `json:"id"`
// URL is the torrent detail page URL
URL string `json:"url,omitempty"`
// Title is the torrent title
Title string `json:"title"`
// Subtitle is the torrent subtitle (副标题)
Subtitle string `json:"subtitle,omitempty"`
// InfoHash is the torrent info hash (if available)
InfoHash string `json:"infoHash,omitempty"`
// Magnet is the magnet link (if available)
Magnet string `json:"magnet,omitempty"`
// SizeBytes is the torrent size in bytes
SizeBytes int64 `json:"sizeBytes"`
// Seeders is the number of seeders
Seeders int `json:"seeders"`
// Leechers is the number of leechers
Leechers int `json:"leechers"`
// Snatched is the number of completed downloads
Snatched int `json:"snatched,omitempty"`
// UploadedAt is the upload timestamp (Unix seconds)
UploadedAt int64 `json:"uploadedAt,omitempty"`
// Tags are the torrent tags/labels
Tags []string `json:"tags,omitempty"`
// SourceSite is the site this torrent came from
SourceSite string `json:"sourceSite"`
// DiscountLevel is the current discount level
DiscountLevel DiscountLevel `json:"discountLevel"`
// DiscountEndTime is when the discount expires
DiscountEndTime time.Time `json:"discountEndTime,omitempty"`
// DiscountValidity 是站点驱动按原始响应给出的免费有效性(见 Promotion)。为空时按保守规则推导:
// 免费但没有结束时间为 unknown(零时间不等于永久),结束时间已过为 not_free。只有站点明确表示长期有效才写 free_permanent。
DiscountValidity FreeValidity `json:"discountValidity,omitempty"`
// DiscountSource 是优惠来自哪里:base、promotion_rule、mall_single_free,或适配层(adapter)
DiscountSource string `json:"discountSource,omitempty"`
// DiscountErr 是读取优惠时遇到的问题(例如结束时间无法解析),只写字段名与错误类型,不放原始响应
DiscountErr string `json:"discountErr,omitempty"`
// FetchedAt 是底层数据实际取得的时间(缓存命中时是缓存刷新的时间);为零时调用方按调用时间算
FetchedAt time.Time `json:"fetchedAt,omitempty"`
// HasHR indicates if the torrent has H&R requirements
HasHR bool `json:"hasHR,omitempty"`
// DownloadURL is the direct download URL
DownloadURL string `json:"downloadUrl,omitempty"`
// Category is the torrent category
Category string `json:"category,omitempty"`
// IMDbID 是 IMDb 编号(tt 开头),站点给了时才有
IMDbID string `json:"imdbId,omitempty"`
// DoubanID 是豆瓣电影条目的数字编号,站点给了时才有
DoubanID string `json:"doubanId,omitempty"`
}
TorrentItem represents a torrent search result
func (*TorrentItem) CanbeFinished ¶
func (t *TorrentItem) CanbeFinished(enabled bool, speedLimit, sizeLimitGB int) bool
CanbeFinished checks if the torrent can be downloaded within the free period enabled: whether download limit is enabled speedLimit: download speed limit in MB/s sizeLimitGB: maximum torrent size in GB
func (*TorrentItem) GetFreeEndTime ¶
func (t *TorrentItem) GetFreeEndTime() *time.Time
GetFreeEndTime returns the discount end time
func (*TorrentItem) GetFreeLevel ¶
func (t *TorrentItem) GetFreeLevel() string
GetFreeLevel returns the discount level as string
func (*TorrentItem) GetName ¶
func (t *TorrentItem) GetName() string
GetName returns the torrent title
func (*TorrentItem) GetSubTitle ¶
func (t *TorrentItem) GetSubTitle() string
GetSubTitle returns the torrent tags as subtitle
func (*TorrentItem) IsDiscountActive ¶
func (t *TorrentItem) IsDiscountActive() bool
IsDiscountActive returns true if the discount is still active
func (*TorrentItem) IsFree ¶
func (t *TorrentItem) IsFree() bool
IsFree returns true if the torrent is currently free
func (*TorrentItem) Promotion ¶ added in v1.0.0
func (t *TorrentItem) Promotion(verifiedAt time.Time) PromotionSnapshot
Promotion 把驱动给出的优惠字段整理成规范快照。verifiedAt 是读到这份数据的时间。
type TorrentManifest ¶
type TorrentManifest struct {
ID string `json:"id"`
Title string `json:"title"`
SizeBytes int64 `json:"sizeBytes"`
DiscountLevel DiscountLevel `json:"discountLevel"`
DownloadURL string `json:"downloadUrl"`
Category string `json:"category,omitempty"`
Seeders int `json:"seeders,omitempty"`
Leechers int `json:"leechers,omitempty"`
}
TorrentManifest represents metadata for a torrent in the batch download
type TrackerResolver ¶ added in v1.0.0
type TrackerResolver struct {
// contains filtered or unexported fields
}
TrackerResolver 按 tracker 或下载地址的主机名找出所属站点:先比主机名(TrackerHosts 与站点地址), 再比可注册域(如 tracker.hdsky.me 与 hdsky.me 同属 hdsky.me)。多个站点共用一个可注册域时只认主机名完全相同的。
它是注册表的一份快照;循环里判断很多种子时建一个复用,不要每次都调 ResolveSiteByTracker。
func NewTrackerResolver ¶ added in v1.0.0
func NewTrackerResolver() *TrackerResolver
NewTrackerResolver 用当前注册的全部站点定义建一个解析器(含已停用的站点:旧种子仍归它们)。
func NewTrackerResolverFrom ¶ added in v1.0.0
func NewTrackerResolverFrom(defs ...*SiteDefinition) *TrackerResolver
NewTrackerResolverFrom 用给定的站点定义建一个解析器(测试与只关心部分站点的调用方用)。
func (*TrackerResolver) Definition ¶ added in v1.0.0
func (r *TrackerResolver) Definition(siteID string) (*SiteDefinition, bool)
Definition 返回站点 ID 对应的定义。
func (*TrackerResolver) Resolve ¶ added in v1.0.0
func (r *TrackerResolver) Resolve(rawURL string) (string, bool)
Resolve 返回 tracker 地址(announce URL)所属站点的 ID。
func (*TrackerResolver) ResolveDownloadURL ¶ added in v1.0.0
func (r *TrackerResolver) ResolveDownloadURL(rawURL string) (siteID, torrentID string, ok bool)
ResolveDownloadURL 找出下载地址所属的站点与种子 ID;地址不属于任何内置站点或格式认不出时 ok 为 false。
type TrendPoint ¶ added in v1.0.0
type TrendPoint struct {
Date string `json:"date"`
Uploaded int64 `json:"uploaded"`
Downloaded int64 `json:"downloaded"`
Bonus float64 `json:"bonus"`
}
TrendPoint 是某天的增量。
func BuildTrends ¶ added in v1.0.0
func BuildTrends(dates []string, baselines map[string]UserInfoDailySnapshot, snaps []UserInfoDailySnapshot) ([]TrendPoint, map[string][]TrendPoint)
BuildTrends 按 dates(升序、连续的日期)给出每站每天的增量与各站合计。没有快照的那天记 0; 一份快照跨了好几天时,增量记在快照所在的那天。数值回退的项按 0 计。
func LoadTrends ¶ added in v1.0.0
func LoadTrends(ctx context.Context, repo UserInfoHistoryRepo, days int) ([]string, []TrendPoint, map[string][]TrendPoint, error)
LoadTrends 从仓库读出最近 days 天(含今天)的走势。
type TwoLevelCache ¶
type TwoLevelCache struct {
// contains filtered or unexported fields
}
TwoLevelCache provides L1 (in-memory) and optional L2 (external) caching
func NewTwoLevelCache ¶
func NewTwoLevelCache(config TwoLevelCacheConfig) *TwoLevelCache
NewTwoLevelCache creates a new two-level cache
func (*TwoLevelCache) Clear ¶
func (c *TwoLevelCache) Clear()
Clear removes all entries from L1 (L2 is not cleared)
func (*TwoLevelCache) Delete ¶
func (c *TwoLevelCache) Delete(key string) error
Delete removes a value from both L1 and L2
type TwoLevelCacheConfig ¶
type TwoLevelCacheConfig struct {
L1Capacity int // L1 cache capacity (default: 1000)
L1TTL time.Duration // L1 TTL (default: 5 minutes)
L2TTL time.Duration // L2 TTL (default: 1 hour)
L2Cache L2Cache // Optional L2 cache implementation
}
TwoLevelCacheConfig configures the two-level cache
type URLFailoverConfig ¶
type URLFailoverConfig struct {
// BaseURLs is the list of base URLs to try in order
BaseURLs []string
// RetryDelay is the delay between retries on the same URL
RetryDelay time.Duration
// MaxRetries is the maximum number of retries per URL (0 = no retry, just try once)
MaxRetries int
// Timeout is the timeout for each request
Timeout time.Duration
}
URLFailoverConfig configures multi-URL failover behavior
func DefaultFailoverConfig ¶
func DefaultFailoverConfig(baseURLs []string) URLFailoverConfig
DefaultFailoverConfig returns a default failover configuration
type URLFailoverManager ¶
type URLFailoverManager struct {
// contains filtered or unexported fields
}
URLFailoverManager manages multi-URL failover for site requests
func NewURLFailoverManager ¶
func NewURLFailoverManager(config URLFailoverConfig, logger *zap.Logger) *URLFailoverManager
NewURLFailoverManager creates a new URL failover manager
func (*URLFailoverManager) ExecuteWithFailover ¶
func (m *URLFailoverManager) ExecuteWithFailover( ctx context.Context, execFunc func(baseURL string) error, ) error
ExecuteWithFailover executes a function with automatic URL failover The execFunc receives the base URL and should return an error if the request fails Returns the error from the last attempted URL if all URLs fail
func (*URLFailoverManager) GetAllURLs ¶
func (m *URLFailoverManager) GetAllURLs() []string
GetAllURLs returns all configured base URLs
func (*URLFailoverManager) GetCurrentURL ¶
func (m *URLFailoverManager) GetCurrentURL() string
GetCurrentURL returns the currently active base URL
type Unit3DDriver ¶
Unit3DDriver implements the Driver interface for Unit3D sites
func NewUnit3DDriver ¶
func NewUnit3DDriver(config Unit3DDriverConfig) *Unit3DDriver
NewUnit3DDriver creates a new Unit3D driver
func (*Unit3DDriver) Execute ¶
func (d *Unit3DDriver) Execute(ctx context.Context, req Unit3DRequest) (Unit3DResponse, error)
Execute performs the HTTP request
func (*Unit3DDriver) GetUserInfo ¶
func (d *Unit3DDriver) GetUserInfo(ctx context.Context) (UserInfo, error)
GetUserInfo fetches complete user information
func (*Unit3DDriver) ParseDownload ¶
func (d *Unit3DDriver) ParseDownload(res Unit3DResponse) ([]byte, error)
ParseDownload extracts torrent file data from the response
func (*Unit3DDriver) ParseSearch ¶
func (d *Unit3DDriver) ParseSearch(res Unit3DResponse) ([]TorrentItem, error)
ParseSearch extracts torrent items from the response
func (*Unit3DDriver) ParseUserInfo ¶
func (d *Unit3DDriver) ParseUserInfo(res Unit3DResponse) (UserInfo, error)
ParseUserInfo extracts user info from the response
func (*Unit3DDriver) PrepareDownload ¶
func (d *Unit3DDriver) PrepareDownload(torrentID string) (Unit3DRequest, error)
PrepareDownload prepares a request for downloading a torrent
func (*Unit3DDriver) PrepareSearch ¶
func (d *Unit3DDriver) PrepareSearch(query SearchQuery) (Unit3DRequest, error)
PrepareSearch converts a SearchQuery to a Unit3D request
func (*Unit3DDriver) PrepareUserInfo ¶
func (d *Unit3DDriver) PrepareUserInfo() (Unit3DRequest, error)
PrepareUserInfo prepares a request for user info
type Unit3DDriverConfig ¶
type Unit3DDriverConfig struct {
BaseURL string
APIKey string
HTTPClient *SiteHTTPClient // Use SiteHTTPClient instead of *http.Client
UserAgent string
// SiteID 是站点在 pt-tools 里注册的 ID:全局设置里的「站点代理」按它判定走不走代理
SiteID string
}
Unit3DDriverConfig holds configuration for creating a Unit3D driver
type Unit3DOptions ¶
type Unit3DOptions struct {
APIKey string `json:"apiKey"`
}
type Unit3DRequest ¶
type Unit3DRequest struct {
// Endpoint is the API endpoint path
Endpoint string
// Method is the HTTP method
Method string
// Params are the query parameters
Params url.Values
// RawBody 为 true 时响应体按原始字节返回(种子文件下载),不按 JSON 解析
RawBody bool
}
Unit3DRequest represents a request to a Unit3D site
type Unit3DResponse ¶
type Unit3DResponse struct {
// Data is the response data
Data json.RawMessage `json:"data"`
// Links contains pagination links
Links json.RawMessage `json:"links,omitempty"`
// Meta contains pagination metadata
Meta json.RawMessage `json:"meta,omitempty"`
// RawBody is the raw response body
RawBody []byte `json:"-"`
// StatusCode is the HTTP status code
StatusCode int `json:"-"`
}
Unit3DResponse represents a response from Unit3D API
type Unit3DTorrent ¶
type Unit3DTorrent struct {
ID int `json:"id"`
Name string `json:"name"`
InfoHash string `json:"info_hash"`
Size int64 `json:"size"`
Seeders int `json:"seeders"`
Leechers int `json:"leechers"`
TimesCompleted int `json:"times_completed"`
Category struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"category"`
Type struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"type"`
Freeleech string `json:"freeleech"`
FreeleechEnds string `json:"freeleech_ends,omitempty"`
DoubleUpload bool `json:"double_upload"`
Featured bool `json:"featured"`
CreatedAt string `json:"created_at"`
DownloadLink string `json:"download_link,omitempty"`
}
Unit3DTorrent represents a torrent in Unit3D API response
type Unit3DUserProfile ¶
type Unit3DUserProfile struct {
ID int `json:"id"`
Username string `json:"username"`
Uploaded int64 `json:"uploaded"`
Downloaded int64 `json:"downloaded"`
Ratio float64 `json:"ratio"`
Buffer int64 `json:"buffer"`
Seedbonus float64 `json:"seedbonus"`
Seeding int `json:"seeding"`
Leeching int `json:"leeching"`
Group struct {
Name string `json:"name"`
} `json:"group"`
CreatedAt string `json:"created_at"`
LastLogin string `json:"last_login,omitempty"`
LastAction string `json:"last_action,omitempty"`
}
Unit3DUserProfile represents user profile from Unit3D API
type UserInfo ¶
type UserInfo struct {
// Site is the site identifier
Site string `json:"site"`
// Username is the user's username
Username string `json:"username"`
// UserID is the site-specific user ID
UserID string `json:"userId"`
// Uploaded is the total uploaded bytes
Uploaded int64 `json:"uploaded"`
// Downloaded is the total downloaded bytes as the site bills them (计费下载量): free and
// discount promotions already applied, the figure that counts toward ratio
Downloaded int64 `json:"downloaded"`
// Ratio is the upload/download ratio
Ratio float64 `json:"ratio"`
// Bonus is the bonus points
Bonus float64 `json:"bonus"`
// Seeding is the number of torrents being seeded
Seeding int `json:"seeding"`
// Leeching is the number of torrents being downloaded
Leeching int `json:"leeching"`
// Rank is the user's rank/class
Rank string `json:"rank"`
// JoinDate is when the user joined (Unix seconds)
JoinDate int64 `json:"joinDate,omitempty"`
// LastAccess is the last access time (Unix seconds)
LastAccess int64 `json:"lastAccess,omitempty"`
// LastLogin is the last login time (Unix seconds)
LastLogin int64 `json:"lastLogin,omitempty"`
// LastUpdate is when this info was last updated (Unix seconds)
LastUpdate int64 `json:"lastUpdate"`
// NextLevel contains level progression info (optional)
NextLevel *LevelProgress `json:"nextLevel,omitempty"`
// Extended fields (populated by sites that support them)
// LevelName is the user's level/rank name
LevelName string `json:"levelName,omitempty"`
// LevelID is the numeric level ID
LevelID int `json:"levelId,omitempty"`
// BonusPerHour is the bonus points earned per hour (时魔)
BonusPerHour float64 `json:"bonusPerHour,omitempty"`
// SeedingBonus is the seeding bonus points (做种积分)
SeedingBonus float64 `json:"seedingBonus,omitempty"`
// SeedingBonusPerHour is the seeding bonus per hour
SeedingBonusPerHour float64 `json:"seedingBonusPerHour,omitempty"`
// UnreadMessageCount is the number of unread messages
UnreadMessageCount int `json:"unreadMessageCount,omitempty"`
// TotalMessageCount is the total number of messages
TotalMessageCount int `json:"totalMessageCount,omitempty"`
// SeederCount is the number of torrents being seeded (from peer statistics)
SeederCount int `json:"seederCount,omitempty"`
// SeederSize is the total size of seeding torrents (bytes)
SeederSize int64 `json:"seederSize,omitempty"`
// LeecherCount is the number of torrents being downloaded
LeecherCount int `json:"leecherCount,omitempty"`
// LeecherSize is the total size of leeching torrents (bytes)
LeecherSize int64 `json:"leecherSize,omitempty"`
// HnRUnsatisfied is the number of unsatisfied H&R
HnRUnsatisfied int `json:"hnrUnsatisfied,omitempty"`
// HnRPreWarning is the number of H&R pre-warnings
HnRPreWarning int `json:"hnrPreWarning,omitempty"`
// TrueUploaded is the actual uploaded bytes, reported separately by some sites (实际上传量)
TrueUploaded int64 `json:"trueUploaded,omitempty"`
// TrueDownloaded is the actual downloaded bytes before promotions (实际下载量). It grows on
// free torrents while Downloaded does not; daily snapshots do not keep it.
TrueDownloaded int64 `json:"trueDownloaded,omitempty"`
// Uploads is the number of torrents uploaded by user
Uploads int `json:"uploads,omitempty"`
}
UserInfo represents user information from a PT site
type UserInfoConfig ¶
type UserInfoConfig struct {
// PickLast specifies fields that should retain last known value
PickLast []string `json:"pickLast,omitempty"`
// RequestDelay between multi-step requests (milliseconds)
RequestDelay int `json:"requestDelay,omitempty"`
// Process defines multi-step user info fetching
Process []UserInfoProcess `json:"process,omitempty"`
// Selectors for parsing user info fields
Selectors map[string]FieldSelector `json:"selectors,omitempty"`
}
UserInfoConfig defines how to fetch and parse user info
type UserInfoDailySnapshot ¶ added in v1.0.0
type UserInfoDailySnapshot struct {
ID uint `gorm:"primaryKey" json:"id"`
Site string `gorm:"size:64;not null;uniqueIndex:idx_userinfo_snapshot_site_date,priority:1" json:"site"`
Date string `gorm:"size:10;not null;uniqueIndex:idx_userinfo_snapshot_site_date,priority:2;index" json:"date"`
Uploaded int64 `json:"uploaded"`
Downloaded int64 `json:"downloaded"`
Bonus float64 `json:"bonus"`
Ratio float64 `json:"ratio"`
Seeding int `json:"seeding"`
SeederSize int64 `json:"seederSize"`
CapturedAt int64 `json:"capturedAt"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
UserInfoDailySnapshot 是每站每天一行的用户数据快照,用来算每日增量与趋势。
日期按仓库的时区(默认进程时区,Docker 里即 TZ)取 YYYY-MM-DD。只由 DBUserInfoRepo.Save 写: 与 UserInfoRecord 在同一个事务里 upsert,同一天多次获取只留最后一次。
Downloaded 是计费下载量(UserInfo.Downloaded);快照不存实际下载量(TrueDownloaded), 所以增量、走势与每日战报里的下载只有计费口径。
func (UserInfoDailySnapshot) TableName ¶ added in v1.0.0
func (UserInfoDailySnapshot) TableName() string
TableName returns the table name for UserInfoDailySnapshot
type UserInfoHistoryRepo ¶ added in v1.0.0
type UserInfoHistoryRepo interface {
// ListSnapshots 返回 [from, to](含两端)之间的快照,按站点、日期升序;site 为空时返回所有站点。
ListSnapshots(ctx context.Context, site, from, to string) ([]UserInfoDailySnapshot, error)
// SnapshotBaselines 返回每站在 before 之前(不含)最近的一份快照,作为区间增量的基线。
SnapshotBaselines(ctx context.Context, before string) (map[string]UserInfoDailySnapshot, error)
// PruneSnapshots 删除日期早于 before 的快照,返回删除的行数。
PruneSnapshots(ctx context.Context, before string) (int64, error)
// Today 是仓库时区的当天日期(YYYY-MM-DD)。
Today() string
}
UserInfoHistoryRepo 是带每日快照的仓库。DBUserInfoRepo 实现它;内存仓库不实现,没有历史数据。
type UserInfoProcess ¶
type UserInfoProcess struct {
// RequestConfig for this step
RequestConfig RequestConfig `json:"requestConfig"`
// Assertion for parameter passing (e.g., {"id": "params.id"})
Assertion map[string]string `json:"assertion,omitempty"`
// Fields to extract in this step
Fields []string `json:"fields"`
}
UserInfoProcess defines a single step in user info fetching
type UserInfoRecord ¶
type UserInfoRecord struct {
ID uint `gorm:"primaryKey" json:"id"`
Site string `gorm:"uniqueIndex;size:64;not null" json:"site"`
Username string `gorm:"size:128" json:"username"`
UserID string `gorm:"size:64" json:"userId"`
Rank string `gorm:"size:64" json:"rank"`
Uploaded int64 `json:"uploaded"`
Downloaded int64 `json:"downloaded"`
Ratio float64 `json:"ratio"`
Seeding int `json:"seeding"`
Leeching int `json:"leeching"`
Bonus float64 `json:"bonus"`
JoinDate int64 `json:"joinDate"`
LastAccess int64 `json:"lastAccess"`
LastUpdate int64 `json:"lastUpdate"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
// Extended fields
LevelName string `gorm:"size:64" json:"levelName"`
LevelID int `json:"levelId"`
BonusPerHour float64 `json:"bonusPerHour"`
SeedingBonus float64 `json:"seedingBonus"`
SeedingBonusPerHour float64 `json:"seedingBonusPerHour"`
UnreadMessageCount int `json:"unreadMessageCount"`
TotalMessageCount int `json:"totalMessageCount"`
SeederCount int `json:"seederCount"`
SeederSize int64 `json:"seederSize"`
LeecherCount int `json:"leecherCount"`
LeecherSize int64 `json:"leecherSize"`
HnRUnsatisfied int `json:"hnrUnsatisfied"`
HnRPreWarning int `json:"hnrPreWarning"`
TrueUploaded int64 `json:"trueUploaded"`
TrueDownloaded int64 `json:"trueDownloaded"`
Uploads int `json:"uploads"`
}
UserInfoRecord represents the database model for user info
func FromUserInfo ¶
func FromUserInfo(info UserInfo) UserInfoRecord
FromUserInfo creates a UserInfoRecord from UserInfo
func (UserInfoRecord) TableName ¶
func (UserInfoRecord) TableName() string
TableName returns the table name for UserInfoRecord
func (*UserInfoRecord) ToUserInfo ¶
func (r *UserInfoRecord) ToUserInfo() UserInfo
ToUserInfo converts UserInfoRecord to UserInfo
type UserInfoRepo ¶
type UserInfoRepo interface {
// Save stores user info for a site
Save(ctx context.Context, info UserInfo) error
// Get retrieves user info for a specific site
Get(ctx context.Context, site string) (UserInfo, error)
// ListAll retrieves all stored user info
ListAll(ctx context.Context) ([]UserInfo, error)
// ListBySites retrieves user info for specific sites
ListBySites(ctx context.Context, sites []string) ([]UserInfo, error)
// Delete removes user info for a site
Delete(ctx context.Context, site string) error
// GetAggregated calculates aggregated statistics
GetAggregated(ctx context.Context) (AggregatedStats, error)
}
UserInfoRepo defines the interface for storing and retrieving user information
type UserInfoService ¶
type UserInfoService struct {
// contains filtered or unexported fields
}
UserInfoService provides user information management across multiple sites
func NewUserInfoService ¶
func NewUserInfoService(config UserInfoServiceConfig) *UserInfoService
NewUserInfoService creates a new UserInfoService
func (*UserInfoService) ClearCache ¶
func (s *UserInfoService) ClearCache()
ClearCache clears the user info cache
func (*UserInfoService) DeleteUserInfo ¶
func (s *UserInfoService) DeleteUserInfo(ctx context.Context, siteID string) error
DeleteUserInfo removes user info for a site
func (*UserInfoService) FetchAndSave ¶
FetchAndSave fetches user info from a site and saves it. 站点没注册时错误包装 ErrSiteNotFound,用户名为空时包装 ErrEmptyUsername; 保存失败时同时返回取到的 UserInfo 和包装 ErrUserInfoPersist 的错误(不更新缓存)。
func (*UserInfoService) FetchAndSaveAll ¶
func (s *UserInfoService) FetchAndSaveAll(ctx context.Context) ([]UserInfo, []error)
FetchAndSaveAll fetches user info from all registered sites
func (*UserInfoService) FetchAndSaveAllWithConcurrency ¶
func (s *UserInfoService) FetchAndSaveAllWithConcurrency( ctx context.Context, maxConcurrent int, timeout time.Duration, ) ([]UserInfo, []SyncError)
FetchAndSaveAllWithConcurrency fetches user info from all registered sites with concurrency control maxConcurrent: maximum number of concurrent requests timeout: timeout for each site request
func (*UserInfoService) GetAggregated ¶
func (s *UserInfoService) GetAggregated(ctx context.Context) (AggregatedStats, error)
GetAggregated returns aggregated statistics across all sites
func (*UserInfoService) GetAllUserInfo ¶
func (s *UserInfoService) GetAllUserInfo(ctx context.Context) ([]UserInfo, error)
GetAllUserInfo retrieves all stored user info
func (*UserInfoService) GetSite ¶
func (s *UserInfoService) GetSite(siteID string) (Site, bool)
GetSite returns a registered site by ID
func (*UserInfoService) GetUserInfo ¶
GetUserInfo retrieves user info for a site (from cache or repository)
func (*UserInfoService) History ¶ added in v1.0.0
func (s *UserInfoService) History() (UserInfoHistoryRepo, bool)
History 返回带每日快照的仓库;内存仓库没有历史数据,返回 false。
func (*UserInfoService) ListSites ¶
func (s *UserInfoService) ListSites() []string
ListSites returns all registered site IDs
func (*UserInfoService) RegisterSite ¶
func (s *UserInfoService) RegisterSite(site Site)
RegisterSite registers a site for user info fetching
func (*UserInfoService) UnregisterSite ¶
func (s *UserInfoService) UnregisterSite(siteID string)
UnregisterSite removes a site from the service
type UserInfoServiceConfig ¶
type UserInfoServiceConfig struct {
Repo UserInfoRepo
CacheTTL time.Duration
Logger *zap.Logger
}
UserInfoServiceConfig holds configuration for UserInfoService
type ValidationConfig ¶
type ValidationConfig struct {
MaxStringLength int // Maximum string length (default: 10000)
MaxURLLength int // Maximum URL length (default: 2048)
MaxFileSizeBytes int64 // Maximum file size in bytes (default: 100MB)
AllowHTML bool // Whether to allow HTML content
StripHTML bool // Whether to strip HTML tags
}
ValidationConfig configures validation limits
func DefaultValidationConfig ¶
func DefaultValidationConfig() ValidationConfig
DefaultValidationConfig returns default validation configuration
type ValidationError ¶ added in v0.12.3
ValidationError contains structured validation error information
func (*ValidationError) Error ¶ added in v0.12.3
func (e *ValidationError) Error() string
type ValidationErrors ¶ added in v0.12.3
type ValidationErrors []*ValidationError
ValidationErrors collects multiple validation errors
func (ValidationErrors) Error ¶ added in v0.12.3
func (errs ValidationErrors) Error() string
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator provides input validation methods
func NewValidator ¶
func NewValidator(config ValidationConfig) *Validator
NewValidator creates a new validator with the given configuration
func (*Validator) ValidateFileSize ¶
ValidateFileSize validates a file size
func (*Validator) ValidateInfoHash ¶
ValidateInfoHash validates a torrent info hash
func (*Validator) ValidateSearchQuery ¶
func (v *Validator) ValidateSearchQuery(query SearchQuery) error
ValidateSearchQuery validates a search query
func (*Validator) ValidateString ¶
ValidateString validates a string input
Source Files
¶
- attendance.go
- attendance_challenge.go
- attendance_form.go
- base_site.go
- batch_download.go
- cache.go
- circuit_breaker.go
- deduper.go
- definition_registry.go
- discount_utils.go
- download_notice.go
- download_retry.go
- driver_registry.go
- external_ids.go
- factory.go
- failover.go
- filters.go
- freshness.go
- gazelle_driver.go
- hddolby_driver.go
- http_client.go
- level.go
- level_manager.go
- level_requirement.go
- metrics.go
- migration.go
- mtorrent_driver.go
- nexusphp_driver.go
- nexusphp_parser.go
- nexusphp_subtitles.go
- normalizer.go
- persistent_rate_limiter.go
- promotion_parse.go
- ranker.go
- ratio.go
- registry.go
- search_cache.go
- search_orchestrator.go
- session_cookies.go
- site_categories.go
- site_definition.go
- site_retry.go
- site_urls.go
- torrent_utils.go
- tracker_resolve.go
- types.go
- unit3d_driver.go
- userinfo_db_repo.go
- userinfo_history.go
- userinfo_partial.go
- userinfo_repo.go
- userinfo_service.go
- validation.go