package session

import (
	
	
	
	

	

	
)

// https://github.com/LonamiWebs/Telethon/blob/master/telethon/sessions/string.py#L11
const latestTelethonVersion byte = '1'

// TelethonSession decodes Telethon's StringSession string to the Data.
// Notice that Telethon does not save tg.Config and server salt.
//
// See https://docs.telethon.dev/en/latest/modules/sessions.html#telethon.sessions.string.StringSession.
//
// See https://github.com/LonamiWebs/Telethon/blob/master/telethon/sessions/string.py#L29-L46.
func ( string) (*Data, error) {
	if len() < 1 {
		return nil, errors.Errorf("given string too small: %d", len())
	}
	 := [0]
	if  != latestTelethonVersion {
		return nil, errors.Errorf("unexpected version %q, latest supported is %q",
			,
			latestTelethonVersion,
		)
	}

	,  := base64.URLEncoding.DecodeString([1:])
	if  != nil {
		return nil, errors.Wrap(, "decode hex")
	}

	return decodeStringSession()
}

func ( []byte) (*Data, error) {
	// Given parameter should contain version + data
	// where data encoded using pack as '>B4sH256s' or '>B16sH256s'
	// depending on IP type.
	//
	// Table:
	//
	// | Size |  Type  | Description |
	// |------|--------|-------------|
	// | 1    | byte   | DC ID       |
	// | 4/16 | bytes  | IP address  |
	// | 2    | uint16 | Port        |
	// | 256  | bytes  | Auth key    |
	var  int
	switch len() {
	case 263:
		 = 4
	case 275:
		 = 16
	default:
		return nil, errors.Errorf("decoded hex has invalid length: %d", len())
	}

	// | 1    | byte   | DC ID       |
	 := [0]

	// | 4/16 | bytes  | IP address  |
	 := make(net.IP, 0, 16)
	 = append(, [1:1+]...)

	// | 2    | uint16 | Port        |
	 := binary.BigEndian.Uint16([1+ : 3+])

	// | 256  | bytes  | Auth key    |
	var  crypto.Key
	copy([:], [3+:])
	 := .WithID().ID

	return &Data{
		DC:        int(),
		Addr:      net.JoinHostPort(.String(), strconv.Itoa(int())),
		AuthKey:   [:],
		AuthKeyID: [:],
	}, nil
}