package qrlogin
import (
"context"
"time"
"github.com/go-faster/errors"
"github.com/gotd/td/clock"
"github.com/gotd/td/crypto"
"github.com/gotd/td/telegram/auth"
"github.com/gotd/td/tg"
"github.com/gotd/td/tgerr"
)
type QR struct {
api *tg .Client
appID int
appHash string
migrate func (ctx context .Context , dcID int ) error
clock clock .Clock
password func (ctx context .Context ) (string , error )
}
func NewQR (api *tg .Client , appID int , appHash string , opts Options ) QR {
opts .setDefaults ()
return QR {
api : api ,
appID : appID ,
appHash : appHash ,
clock : opts .Clock ,
migrate : opts .Migrate ,
password : opts .Password ,
}
}
type ExportResult struct {
Token Token
Authorization *tg .AuthAuthorization
MigrateTo *tg .AuthLoginTokenMigrateTo
}
func (q QR ) ExportResult (ctx context .Context , exceptIDs ...int64 ) (ExportResult , error ) {
result , err := q .export (ctx , exceptIDs ...)
if err != nil {
return ExportResult {}, err
}
switch t := result .(type ) {
case *tg .AuthLoginToken :
return ExportResult {Token : NewToken (t .Token , t .Expires )}, nil
case *tg .AuthLoginTokenSuccess :
a , ok := t .Authorization .(*tg .AuthAuthorization )
if !ok {
return ExportResult {}, errors .Errorf ("unexpected type %T" , t .Authorization )
}
return ExportResult {Authorization : a }, nil
case *tg .AuthLoginTokenMigrateTo :
return ExportResult {MigrateTo : t }, nil
default :
return ExportResult {}, errors .Errorf ("unexpected type %T" , result )
}
}
func (q QR ) Export (ctx context .Context , exceptIDs ...int64 ) (Token , error ) {
result , err := q .export (ctx , exceptIDs ...)
if err != nil {
return Token {}, err
}
switch t := result .(type ) {
case *tg .AuthLoginToken :
return NewToken (t .Token , t .Expires ), nil
case *tg .AuthLoginTokenSuccess :
return Token {}, nil
case *tg .AuthLoginTokenMigrateTo :
return Token {}, &MigrationNeededError {
MigrateTo : t ,
}
default :
return Token {}, errors .Errorf ("unexpected type %T" , result )
}
}
func (q QR ) export (ctx context .Context , exceptIDs ...int64 ) (tg .AuthLoginTokenClass , error ) {
result , err := q .api .AuthExportLoginToken (ctx , &tg .AuthExportLoginTokenRequest {
APIID : q .appID ,
APIHash : q .appHash ,
ExceptIDs : exceptIDs ,
})
if err != nil {
return nil , errors .Wrap (err , "export" )
}
return result , nil
}
func (q QR ) Accept (ctx context .Context , t Token ) (*tg .Authorization , error ) {
return AcceptQR (ctx , q .api , t )
}
func (q QR ) Import (ctx context .Context ) (*tg .AuthAuthorization , error ) {
a , err := q .importToken (ctx )
if q .needPassword (err ) {
return q .checkPassword (ctx )
}
return a , err
}
func (q QR ) needPassword (err error ) bool {
return err != nil && q .password != nil && tgerr .Is (err , "SESSION_PASSWORD_NEEDED" )
}
func (q QR ) checkPassword (ctx context .Context ) (*tg .AuthAuthorization , error ) {
password , err := q .password (ctx )
if err != nil {
return nil , errors .Wrap (err , "get password" )
}
a , err := auth .NewClient (q .api , crypto .DefaultRand (), q .appID , q .appHash ).Password (ctx , password )
if err != nil {
return nil , errors .Wrap (err , "check password" )
}
return a , nil
}
func (q QR ) importToken (ctx context .Context ) (*tg .AuthAuthorization , error ) {
result , err := q .api .AuthExportLoginToken (ctx , &tg .AuthExportLoginTokenRequest {
APIID : q .appID ,
APIHash : q .appHash ,
})
if err != nil {
return nil , errors .Wrap (err , "import" )
}
switch t := result .(type ) {
case *tg .AuthLoginTokenMigrateTo :
return q .importMigrated (ctx , t )
case *tg .AuthLoginTokenSuccess :
auth , ok := t .Authorization .(*tg .AuthAuthorization )
if !ok {
return nil , errors .Errorf ("unexpected type %T" , t .Authorization )
}
return auth , nil
default :
return nil , errors .Errorf ("unexpected type %T" , result )
}
}
func (q QR ) importMigrated (ctx context .Context , t *tg .AuthLoginTokenMigrateTo ) (*tg .AuthAuthorization , error ) {
if q .migrate == nil {
return nil , &MigrationNeededError {
MigrateTo : t ,
}
}
if err := q .migrate (ctx , t .DCID ); err != nil {
return nil , errors .Wrap (err , "migrate" )
}
res , err := q .api .AuthImportLoginToken (ctx , t .Token )
if err != nil {
return nil , errors .Wrap (err , "import" )
}
success , ok := res .(*tg .AuthLoginTokenSuccess )
if !ok {
return nil , errors .Errorf ("unexpected type %T" , res )
}
auth , ok := success .Authorization .(*tg .AuthAuthorization )
if !ok {
return nil , errors .Errorf ("unexpected type %T" , success .Authorization )
}
return auth , nil
}
func (q QR ) finishMigrated (ctx context .Context , t *tg .AuthLoginTokenMigrateTo ) (*tg .AuthAuthorization , error ) {
a , err := q .importMigrated (ctx , t )
if q .needPassword (err ) {
return q .checkPassword (ctx )
}
return a , err
}
type LoggedIn <-chan struct {}
func OnLoginToken (d interface {
OnLoginToken (tg .LoginTokenHandler )
},
) LoggedIn {
loggedIn := make (chan struct {}, 1 )
d .OnLoginToken (func (ctx context .Context , e tg .Entities , update *tg .UpdateLoginToken ) error {
select {
case loggedIn <- struct {}{}:
default :
}
return nil
})
return loggedIn
}
const (
minTokenWait = time .Second
minRetryDelay = time .Second
maxRetryDelay = time .Minute
)
func retryableExportError (err error ) bool {
if _ , ok := tgerr .AsFloodWait (err ); ok {
return true
}
if rpcErr , ok := tgerr .As (err ); ok {
return rpcErr .Code >= 500
}
return true
}
func nextRetryDelay (prev time .Duration , err error ) time .Duration {
d := min (max (2 *prev , minRetryDelay ), maxRetryDelay )
if wait , ok := tgerr .AsFloodWait (err ); ok && wait > d {
d = wait
}
return d
}
func (q QR ) Auth (
ctx context .Context ,
loggedIn LoggedIn ,
show func (ctx context .Context , token Token ) error ,
exceptIDs ...int64 ,
) (*tg .AuthAuthorization , error ) {
until := func (token Token ) time .Duration {
return max (token .Expires ().Sub (q .clock .Now ()).Truncate (time .Second ), minTokenWait )
}
r , err := q .ExportResult (ctx , exceptIDs ...)
if err != nil {
if q .needPassword (err ) {
return q .checkPassword (ctx )
}
return nil , err
}
switch {
case r .Authorization != nil :
return r .Authorization , nil
case r .MigrateTo != nil :
return q .finishMigrated (ctx , r .MigrateTo )
}
token := r .Token
timer := q .clock .Timer (until (token ))
defer clock .StopTimer (timer )
var (
retryDelay time .Duration
needShow = true
)
for {
if needShow {
if err := show (ctx , token ); err != nil {
return nil , errors .Wrap (err , "show" )
}
needShow = false
}
select {
case <- ctx .Done ():
return nil , errors .Wrap (ctx .Err (), "wait for login" )
case <- loggedIn :
return q .Import (ctx )
case <- timer .C ():
}
r , err := q .ExportResult (ctx , exceptIDs ...)
if err != nil {
if q .needPassword (err ) {
return q .checkPassword (ctx )
}
if ctxErr := ctx .Err (); ctxErr != nil {
return nil , errors .Wrap (ctxErr , "refresh token" )
}
if !retryableExportError (err ) {
return nil , err
}
retryDelay = nextRetryDelay (retryDelay , err )
timer .Reset (retryDelay )
continue
}
retryDelay = 0
switch {
case r .Authorization != nil :
return r .Authorization , nil
case r .MigrateTo != nil :
return q .finishMigrated (ctx , r .MigrateTo )
}
token = r .Token
needShow = true
timer .Reset (until (token ))
}
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .