package telegram

import (
	
	
	

	

	

	
	
	
	
	
)

func ( *Client) ( context.Context) error {
	if .storage == nil {
		return nil
	}

	,  := .storage.Load()
	if errors.Is(, session.ErrNotFound) {
		return nil
	}
	if  != nil {
		return errors.Wrap(, "load")
	}

	// If file does not contain DC ID, so we use DC from options.
	 := .session.Load()
	if .DC == 0 {
		.DC = .DC
	}

	// Restoring persisted auth key.
	var  crypto.AuthKey
	copy(.Value[:], .AuthKey)
	copy(.ID[:], .AuthKeyID)

	if .Value.ID() != .ID {
		return errors.New("corrupted key")
	}

	// Re-initializing connection from persisted state.
	.log.Info(, "Connection restored from state",
		log.String("addr", .Addr),
		log.String("key_id", fmt.Sprintf("%x", .AuthKeyID)),
	)

	.connMux.Lock()
	.session.Store(pool.Session{
		DC:           .DC,
		AuthKey:      ,
		Salt:         .Salt,
		KeyCreatedAt: .AuthKeyCreatedAt,
	})
	.replaceConn(.createPrimaryConn(nil))
	.connMux.Unlock()

	.restoreDCKeys(, )
	if .ServerTimeOffset != 0 && !.serverTimeSet && .serverTime != nil {
		// The offset of the previous run, until the server corrects it.
		.serverTime.Seed(.ServerTimeOffset)
	}
	if .UserID != 0 {
		.selfID.Store(.UserID)
		.selfBot.Store(.Bot)
	}

	return nil
}

// restoreDCKeys loads authorized keys of the other DCs, so that their pools
// skip key exchange and authorization transfer.
func ( *Client) ( context.Context,  *session.Data) {
	for ,  := range .DCs {
		if  == .DC || !.Authorized {
			continue
		}
		var  crypto.AuthKey
		copy(.Value[:], .AuthKey)
		copy(.ID[:], .AuthKeyID)
		if .Zero() || .Value.ID() != .ID {
			.log.Warn(, "Skipping corrupted stored DC key", log.Int("dc_id", ))
			continue
		}
		.sessionsMux.Lock()
		.sessions[] = pool.NewSyncSession(pool.Session{
			DC:           ,
			AuthKey:      ,
			Salt:         .Salt,
			KeyCreatedAt: .CreatedAt,
		})
		.dcAuthorized[] = .ID
		.sessionsMux.Unlock()
	}
}

// fillDCKeys sets data.DCs to the authorized keys of the other DCs.
func ( *Client) ( *session.Data) {
	.sessionsMux.Lock()
	defer .sessionsMux.Unlock()
	 := map[int]session.DCKey{}
	for ,  := range .dcAuthorized {
		,  := .sessions[]
		if ! ||  == .DC {
			continue
		}
		 := .Load()
		if .AuthKey.Zero() || .AuthKey.ID !=  {
			continue
		}
		[] = session.DCKey{
			AuthKey:    append([]byte(nil), .AuthKey.Value[:]...),
			AuthKeyID:  append([]byte(nil), .AuthKey.ID[:]...),
			CreatedAt:  .KeyCreatedAt,
			Authorized: true,
			Salt:       .Salt,
		}
	}
	if len() == 0 {
		 = nil
	}
	.DCs = 
}

// updateStoredSession loads the stored session, applies f and saves it. It
// does nothing if there is no storage, no stored session yet, or after
// LogOut.
func ( *Client) ( context.Context,  func( *session.Data)) error {
	if .storage == nil || .auth.loggedOut.Load() {
		return nil
	}
	.saveMux.Lock()
	defer .saveMux.Unlock()
	,  := .storage.Load()
	if errors.Is(, session.ErrNotFound) {
		// The primary session is saved first; it will include this.
		return nil
	}
	if  != nil {
		return errors.Wrap(, "load")
	}
	()
	if  := .storage.Save(, );  != nil {
		return errors.Wrap(, "save")
	}
	return nil
}

// dcAuthPendingFor reports whether the authorization of the DC of data was
// transferred before its key was stored, see setDCAuthorized.
func ( *Client) ( pool.Session) bool {
	if .AuthKey.Zero() {
		return false
	}
	.sessionsMux.Lock()
	defer .sessionsMux.Unlock()
	return .dcAuthPending[.DC]
}

func ( *Client) () context.Context {
	if .ctx != nil {
		return .ctx
	}
	return context.Background()
}

// dcKeyAuthorized reports whether the stored key of dc already has the
// authorization transferred.
func ( *Client) ( int) bool {
	.sessionsMux.Lock()
	defer .sessionsMux.Unlock()
	,  := .sessions[]
	if ! {
		return false
	}
	,  := .dcAuthorized[]
	 := .Load().AuthKey
	return  && !.Zero() && .ID == 
}

// setDCAuthorized marks the current key of dc as authorized (or not) and
// persists the authorized keys.
func ( *Client) ( context.Context,  int,  bool) {
	.sessionsMux.Lock()
	 := false
	delete(.dcAuthPending, )
	if  {
		var  crypto.AuthKey
		if ,  := .sessions[];  {
			 = .Load().AuthKey
		}
		switch {
		case .Zero():
			// The connection reports its session after it is ready, so the
			// transfer may finish first: mark the key when it is stored.
			.dcAuthPending[] = true
		case .dcAuthorized[] != .ID:
			.dcAuthorized[] = .ID
			 = true
		}
	} else if ,  := .dcAuthorized[];  {
		delete(.dcAuthorized, )
		 = true
	}
	.sessionsMux.Unlock()
	if ! {
		return
	}
	if  := .updateStoredSession(, .fillDCKeys);  != nil {
		.log.Warn(, "Failed to save DC keys", log.Int("dc_id", ), log.Error())
	}
}

// acquireSessionState returns a free server session slot of dc for a new
// connection, see mtproto.SessionState.
func ( *Client) ( int) *mtproto.SessionState {
	.sessionsMux.Lock()
	defer .sessionsMux.Unlock()
	for ,  := range .sessionStates[] {
		if .TryAcquire() {
			return 
		}
	}
	 := mtproto.NewSessionState()
	.TryAcquire()
	.sessionStates[] = append(.sessionStates[], )
	return 
}

// onPrimaryNewSession recovers updates after the server started a new
// session on the primary connection: updates sent to the previous session
// may be lost, so the update handler gets updatesTooLong (getDifference in
// telegram/updates), like TDLib and Telegram Desktop. The first session of
// the client is skipped: there is no previous one.
func ( *Client) () {
	if .primarySessions.Inc() == 1 || .noUpdatesMode || .updateHandler == nil {
		return
	}
	 := .ctx
	if  == nil {
		return
	}
	.log.Info(, "New server session on primary connection, recovering updates")
	go func() {
		if  := .updateHandler.Handle(, &tg.UpdatesTooLong{});  != nil {
			.log.Debug(, "Update handler failed on updatesTooLong", log.Error())
		}
	}()
}

// SelfID returns the ID of the authorized user or bot and whether it is a
// bot, without a request: ok is false if it is not known yet. It is known
// after a successful Self call (including the one Run makes on connect) and
// is restored from the stored session.
func ( *Client) () ( int64,  bool,  bool) {
	 = .selfID.Load()
	return , .selfBot.Load(),  != 0
}

// setSelf records the authorized user and persists it.
func ( *Client) ( context.Context,  *tg.User) {
	if  == nil || .ID == 0 {
		return
	}
	if .selfID.Load() == .ID && .selfBot.Load() == .Bot {
		return
	}
	.selfID.Store(.ID)
	.selfBot.Store(.Bot)
	if  := .updateStoredSession(, func( *session.Data) {
		.UserID = .ID
		.Bot = .Bot
	});  != nil {
		.log.Warn(, "Failed to save self ID", log.Error())
	}
}

func ( *Client) ( tg.Config,  mtproto.Session) error {
	if .storage == nil || .auth.loggedOut.Load() {
		// After LogOut the stored session stays wiped until the client is
		// authorized again.
		return nil
	}

	.saveMux.Lock()
	defer .saveMux.Unlock()
	,  := .storage.Load(.ctx)
	if errors.Is(, session.ErrNotFound) {
		// Initializing new state.
		 = nil
		 = &session.Data{}
	}
	if  != nil {
		return errors.Wrap(, "load")
	}

	// Updating previous data.
	.Config = session.ConfigFromTG()
	 := .Key
	if !.PermKey.Zero() {
		// Persist permanent key in PFS mode: temporary key is expected to rotate.
		 = .PermKey
	}
	switch {
	case .KeyCreatedAt != 0:
		.AuthKeyCreatedAt = .KeyCreatedAt
	case !bytes.Equal(.AuthKeyID, .ID[:]):
		// A different key of unknown age.
		.AuthKeyCreatedAt = 0
	}
	.AuthKey = .Value[:]
	.AuthKeyID = .ID[:]
	.DC = .ThisDC
	.Salt = .Salt
	.fillDCKeys()
	if .serverTime != nil && .serverTime.Known() {
		.ServerTimeOffset = .serverTime.Offset()
	}
	if  := .selfID.Load();  != 0 {
		.UserID = 
		.Bot = .selfBot.Load()
	}

	if  := .storage.Save(.ctx, );  != nil {
		return errors.Wrap(, "save")
	}

	.log.Debug(.ctx, "Data saved",
		log.String("key_id", fmt.Sprintf("%x", .AuthKeyID)),
	)
	return nil
}

func ( *Client) ( tg.Config,  mtproto.Session) error {
	 := dcSessionFromMTProto(.ThisDC, )
	if .isDroppedKey() {
		// A connection that was still running on a key dropped after
		// ErrPFSDropKeysRequired reported its session: storing it would make
		// new connections reuse the dropped key.
		.log.Debug(context.Background(), "Ignoring session with dropped auth key",
			log.Int("dc_id", .DC),
		)
		return nil
	}
	// Track per-DC session in memory for pool reconnections/migrations.
	.storeDCSess(.sessions, )
	if .dcAuthPendingFor() {
		.setDCAuthorized(.ctxOrBackground(), .DC, true)
	}

	 := .session.Load().DC
	// Do not save session for non-primary DC.
	if .ThisDC != 0 &&  != 0 &&  != .ThisDC {
		return nil
	}

	.connMux.Lock()
	.session.Store()
	.cfg.Store()
	.onReady()
	.connMux.Unlock()

	if  := .saveSession(, );  != nil {
		return errors.Wrap(, "save")
	}

	return nil
}

func ( *Client) ( tg.Config,  mtproto.Session) error {
	// CDN sessions are isolated from regular DC map because lifecycle and reset
	// triggers differ (fingerprint misses, CDN-specific reconnects).
	.storeDCSess(.cdnSessions, dcSessionFromMTProto(.ThisDC, ))
	return nil
}

// isDroppedKey reports whether data carries an auth key dropped for its DC
// after ErrPFSDropKeysRequired.
func ( *Client) ( pool.Session) bool {
	if .AuthKey.Zero() {
		return false
	}
	.sessionsMux.Lock()
	defer .sessionsMux.Unlock()
	,  := .droppedKeys[.DC]
	return  &&  == .AuthKey.ID
}

func ( *Client) ( map[int]*pool.SyncSession,  pool.Session) {
	.sessionsMux.Lock()
	if ,  := [.DC];  {
		if  := .Load(); .KeyCreatedAt == 0 && .AuthKey.ID == .AuthKey.ID {
			// Same key reported by a connection that doesn't know its age.
			.KeyCreatedAt = .KeyCreatedAt
		}
		.Store()
		.sessionsMux.Unlock()
		return
	}
	[.DC] = pool.NewSyncSession()
	.sessionsMux.Unlock()
}

func ( int,  mtproto.Session) pool.Session {
	 := .Key
	if !.PermKey.Zero() {
		// Keep in-memory/persisted key format backward-compatible: one key slot.
		// In PFS mode temp key rotates, so we pin permanent key.
		 = .PermKey
	}

	return pool.Session{
		DC:           ,
		Salt:         .Salt,
		AuthKey:      ,
		KeyCreatedAt: .KeyCreatedAt,
	}
}