105 lines
2.3 KiB
Go
105 lines
2.3 KiB
Go
package realdebrid
|
|
|
|
import (
|
|
"fmt"
|
|
"sync"
|
|
|
|
"github.com/debridmediamanager/zurg/pkg/logutil"
|
|
"github.com/debridmediamanager/zurg/pkg/utils"
|
|
)
|
|
|
|
type Token struct {
|
|
value string
|
|
expired bool
|
|
}
|
|
|
|
type DownloadTokenManager struct {
|
|
tokens []Token
|
|
current int
|
|
mu sync.RWMutex
|
|
log *logutil.Logger
|
|
}
|
|
|
|
// NewDownloadTokenManager initializes a new DownloadTokenManager with the given tokens.
|
|
func NewDownloadTokenManager(tokenStrings []string, log *logutil.Logger) *DownloadTokenManager {
|
|
tokens := make([]Token, len(tokenStrings))
|
|
for i, t := range tokenStrings {
|
|
tokens[i] = Token{value: t, expired: false}
|
|
}
|
|
return &DownloadTokenManager{tokens: tokens, current: 0, log: log}
|
|
}
|
|
|
|
// GetCurrentToken returns the current non-expired token.
|
|
func (dtm *DownloadTokenManager) GetCurrentToken() (string, error) {
|
|
dtm.mu.RLock()
|
|
defer dtm.mu.RUnlock()
|
|
|
|
for {
|
|
if !dtm.tokens[dtm.current].expired {
|
|
return dtm.tokens[dtm.current].value, nil
|
|
}
|
|
|
|
dtm.current = (dtm.current + 1) % len(dtm.tokens)
|
|
|
|
if dtm.current == 0 {
|
|
return "", fmt.Errorf("all tokens are expired")
|
|
}
|
|
}
|
|
}
|
|
|
|
// SetTokenAsExpired sets the specified token as expired.
|
|
func (dtm *DownloadTokenManager) SetTokenAsExpired(token, reason string) error {
|
|
dtm.mu.Lock()
|
|
defer dtm.mu.Unlock()
|
|
|
|
for i, t := range dtm.tokens {
|
|
if t.value == token {
|
|
dtm.tokens[i].expired = true
|
|
dtm.log.Errorf("Token %s set as expired (reason=%s)", utils.MaskToken(token), reason)
|
|
return nil
|
|
}
|
|
}
|
|
|
|
return fmt.Errorf("token not found")
|
|
}
|
|
|
|
// SetTokenAsUnexpired sets the specified token as unexpired.
|
|
func (dtm *DownloadTokenManager) SetTokenAsUnexpired(token string) error {
|
|
dtm.mu.Lock()
|
|
defer dtm.mu.Unlock()
|
|
|
|
for i, t := range dtm.tokens {
|
|
if t.value == token {
|
|
dtm.tokens[i].expired = false
|
|
dtm.log.Infof("Token %s set as unexpired", utils.MaskToken(token))
|
|
return nil
|
|
}
|
|
}
|
|
|
|
return fmt.Errorf("token not found")
|
|
}
|
|
|
|
// ResetAllTokens resets all tokens to expired=false.
|
|
func (dtm *DownloadTokenManager) ResetAllTokens() {
|
|
dtm.mu.Lock()
|
|
defer dtm.mu.Unlock()
|
|
|
|
for i := range dtm.tokens {
|
|
dtm.tokens[i].expired = false
|
|
}
|
|
dtm.current = 0
|
|
}
|
|
|
|
func (dtm *DownloadTokenManager) GetExpiredTokens() []string {
|
|
dtm.mu.RLock()
|
|
defer dtm.mu.RUnlock()
|
|
|
|
var tokens []string
|
|
for _, t := range dtm.tokens {
|
|
if t.expired {
|
|
tokens = append(tokens, t.value)
|
|
}
|
|
}
|
|
return tokens
|
|
}
|