package telegram

import (
	
	
	

	
	
	

	

	
	
	
)

// AuthLostKind is why authorization is lost, see AuthLostKindOf.
type AuthLostKind int

const (
	// AuthLostUnknown is an error that is not one of IsAuthLost errors.
	AuthLostUnknown AuthLostKind = iota
	// AuthLostBanned means that the account is banned by Telegram
	// (USER_DEACTIVATED_BAN).
	AuthLostBanned
	// AuthLostDeleted means that the account is deleted (USER_DEACTIVATED).
	AuthLostDeleted
	// AuthLostRevoked means that the session was terminated, e.g. from
	// another device (SESSION_REVOKED), or the server asked to drop the key
	// (AUTH_KEY_DROP_* service notification).
	AuthLostRevoked
	// AuthLostUnregistered means that the server doesn't know the auth key
	// as an authorized one (AUTH_KEY_UNREGISTERED). It is what a terminated
	// session usually returns, but also what the keys of a deleted or banned
	// account return once they are dropped.
	AuthLostUnregistered
	// AuthLostExpired means that the session expired (SESSION_EXPIRED).
	AuthLostExpired
	// AuthLostKeyInvalid means that the auth key is invalid or used by
	// another connection (AUTH_KEY_INVALID, AUTH_KEY_DUPLICATED).
	AuthLostKeyInvalid
)

// String implements fmt.Stringer. Values are used in logs and metrics.
func ( AuthLostKind) () string {
	switch  {
	case AuthLostBanned:
		return "banned"
	case AuthLostDeleted:
		return "deleted"
	case AuthLostRevoked:
		return "revoked"
	case AuthLostUnregistered:
		return "unregistered"
	case AuthLostExpired:
		return "expired"
	case AuthLostKeyInvalid:
		return "key_invalid"
	default:
		return "unknown"
	}
}

// AuthLostKindOf classifies an error of IsAuthLost.
func ( error) AuthLostKind {
	,  := tgerr.As()
	if ! {
		return AuthLostUnknown
	}
	switch .Type {
	case "USER_DEACTIVATED_BAN":
		return AuthLostBanned
	case "USER_DEACTIVATED":
		return AuthLostDeleted
	case "SESSION_REVOKED":
		return AuthLostRevoked
	case "AUTH_KEY_UNREGISTERED":
		return AuthLostUnregistered
	case "SESSION_EXPIRED":
		return AuthLostExpired
	case "AUTH_KEY_INVALID", "AUTH_KEY_DUPLICATED":
		return AuthLostKeyInvalid
	}
	if strings.HasPrefix(.Type, authKeyDropPrefix) {
		return AuthLostRevoked
	}
	return AuthLostUnknown
}

// IsAccountBanned reports whether err means that the account is banned by
// Telegram: USER_DEACTIVATED_BAN for a signed in account, PHONE_NUMBER_BANNED
// when signing in.
func ( error) bool {
	return tgerr.Is(, "USER_DEACTIVATED_BAN", tg.ErrPhoneNumberBanned)
}

// Kind returns why authorization is lost.
func ( *AuthLostError) () AuthLostKind {
	return AuthLostKindOf(.Err)
}

// authKeyDropPrefix is the type prefix of service notifications asking to
// drop the auth key, e.g. after a key leak. Telegram Desktop logs out on
// them, mobile apps offer to.
const authKeyDropPrefix = "AUTH_KEY_DROP_"

// AuthKeyDropError returns the error that is reported via OnAuthLost when
// the server sends an AUTH_KEY_DROP_* service notification: a *tgerr.Error
// with code 401, the notification type as Type and its text as Message.
func ( *tg.UpdateServiceNotification) error {
	return &tgerr.Error{
		Code:    401,
		Type:    .Type,
		Message: .Message,
	}
}

// handleServiceNotification logs service notifications and reports
// AUTH_KEY_DROP_* ones as lost authorization.
func ( *Client) ( *tg.UpdateServiceNotification) {
	 := context.Background()
	if strings.HasPrefix(.Type, authKeyDropPrefix) {
		.log.Warn(, "Server asked to drop the auth key",
			log.String("type", .Type),
			log.String("message", .Message),
		)
		.authLostDetected(AuthKeyDropError())
		return
	}
	if .Popup {
		// Popups are how Telegram tells about restrictions, e.g. bans for
		// spam: worth seeing in logs.
		.log.Info(, "Service notification",
			log.String("type", .Type),
			log.String("message", .Message),
		)
		return
	}
	.log.Debug(, "Service notification", log.String("type", .Type))
}

// FreezeState is the freeze state of the account, from app config.
//
// A frozen account is signed in and can read, but most methods fail with
// FROZEN_METHOD_INVALID until Until or a successful appeal.
//
// See https://core.telegram.org/api/config#freeze-since-date.
type FreezeState struct {
	// Since is when the account was frozen, zero if it is not.
	Since time.Time
	// Until is when the account will be deleted unless the appeal succeeds.
	Until time.Time
	// AppealURL is a t.me link to the bot to appeal with.
	AppealURL string
}

// Frozen reports whether the account is frozen.
func ( FreezeState) () bool {
	return !.Since.IsZero()
}

// FreezeStateFrom returns the freeze state from help.getAppConfig result.
func ( tg.JSONValueClass) FreezeState {
	var  FreezeState
	,  := .(*tg.JSONObject)
	if ! {
		return 
	}
	 := func( tg.JSONValueClass) time.Time {
		,  := .(*tg.JSONNumber)
		if ! || .Value <= 0 {
			return time.Time{}
		}
		return time.Unix(int64(.Value), 0)
	}
	for ,  := range .Value {
		switch .Key {
		case "freeze_since_date":
			.Since = (.Value)
		case "freeze_until_date":
			.Until = (.Value)
		case "freeze_appeal_url":
			if ,  := .Value.(*tg.JSONString);  {
				.AppealURL = .Value
			}
		}
	}
	return 
}

// FreezeState fetches app config and returns the freeze state of the account.
func ( *Client) ( context.Context) (FreezeState, error) {
	,  := .API().HelpGetAppConfig(, 0)
	if  != nil {
		return FreezeState{}, errors.Wrap(, "get app config")
	}
	,  := .(*tg.HelpAppConfig)
	if ! {
		// helpAppConfigNotModified is not returned for hash 0.
		return FreezeState{}, errors.Errorf("unexpected app config %T", )
	}
	return FreezeStateFrom(.Config), nil
}

// IsFrozen reports whether err means that the request was refused because
// the account is frozen: FROZEN_METHOD_INVALID (code 420, not a flood
// wait) or FROZEN_PARTICIPANT_MISSING.
func ( error) bool {
	return tgerr.Is(, tg.ErrFrozenMethodInvalid, tg.ErrFrozenParticipantMissing)
}

// freezeCheckInterval limits app config fetches on frozen errors, as in
// Telegram Desktop.
const freezeCheckInterval = time.Hour

// observeRestriction logs and counts errors that tell about restrictions
// of the account, and checks the freeze state on frozen errors.
func ( *Client) ( bin.Encoder,  error) {
	,  := tgerr.As()
	if ! {
		return
	}
	 := IsFrozen()
	if ! && !.IsType(tg.ErrPhoneNumberBanned) {
		return
	}
	 := context.Background()
	.meters().restricted.Add(, 1, metric.WithAttributes(
		attribute.String("reason", .Type),
	))
	 := methodName()
	if ! {
		.log.Error(, "Phone number is banned by Telegram. "+
			"If this is a mistake, log in from an official mobile app and follow "+
			"its instructions to recover the account",
			log.String("method", ),
		)
		return
	}
	.log.Debug(, "Request refused: account is frozen",
		log.String("reason", .Type),
		log.String("method", ),
	)

	 := .clock.Now()
	.freezeMux.Lock()
	if !.freezeChecked.IsZero() && .Sub(.freezeChecked) < freezeCheckInterval {
		.freezeMux.Unlock()
		return
	}
	.freezeChecked = 
	.freezeMux.Unlock()

	 := .ctx
	if  == nil || .Err() != nil {
		return
	}
	// Not in the failing request's goroutine: app config is another request.
	go .checkFreeze(, )
}

// checkFreeze fetches the freeze state, logs it and calls OnFrozen.
func ( *Client) ( context.Context,  string) {
	,  := .FreezeState()
	if  != nil {
		if .Err() == nil {
			.log.Warn(, "Failed to check freeze state", log.Error())
		}
		return
	}
	if !.Frozen() {
		.log.Warn(, "Frozen error, but app config has no freeze state",
			log.String("method", ),
		)
		return
	}
	.log.Warn(, "Account is frozen",
		log.Time("since", .Since),
		log.Time("until", .Until),
		log.String("appeal_url", .AppealURL),
		log.String("method", ),
	)
	if .onFrozen != nil {
		.onFrozen(, )
	}
}