Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

telegram.go 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package telegram
  2. import (
  3. "context"
  4. "math/rand"
  5. "github.com/juju/errors"
  6. "github.com/9seconds/mtg/mtproto"
  7. "github.com/9seconds/mtg/wrappers"
  8. )
  9. // Telegram is an interface for different Telegram work modes.
  10. type Telegram interface {
  11. Dial(context.Context, context.CancelFunc, string, *mtproto.ConnectionOpts) (wrappers.StreamReadWriteCloser, error)
  12. Init(*mtproto.ConnectionOpts, wrappers.StreamReadWriteCloser) (wrappers.Wrap, error)
  13. }
  14. type baseTelegram struct {
  15. dialer tgDialer
  16. v4DefaultIdx int16
  17. v6DefaultIdx int16
  18. v4Addresses map[int16][]string
  19. v6Addresses map[int16][]string
  20. }
  21. func (b *baseTelegram) dial(ctx context.Context, cancel context.CancelFunc, dcIdx int16, connID string,
  22. proto mtproto.ConnectionProtocol) (wrappers.StreamReadWriteCloser, error) {
  23. addrs := make([]string, 2)
  24. if proto&mtproto.ConnectionProtocolIPv6 != 0 {
  25. if addr := b.chooseAddress(b.v6Addresses, dcIdx, b.v6DefaultIdx); addr != "" {
  26. addrs = append(addrs, addr)
  27. }
  28. }
  29. if proto&mtproto.ConnectionProtocolIPv4 != 0 {
  30. if addr := b.chooseAddress(b.v4Addresses, dcIdx, b.v4DefaultIdx); addr != "" {
  31. addrs = append(addrs, addr)
  32. }
  33. }
  34. for _, addr := range addrs {
  35. if conn, err := b.dialer.dialRWC(ctx, cancel, addr, connID); err == nil {
  36. return conn, err
  37. }
  38. }
  39. return nil, errors.New("Cannot connect to Telegram")
  40. }
  41. func (b *baseTelegram) chooseAddress(addresses map[int16][]string, idx, defaultIdx int16) string {
  42. if addr, ok := addresses[idx]; ok {
  43. return b.chooseRandomAddress(addr)
  44. } else if addr, ok := addresses[defaultIdx]; ok {
  45. return b.chooseRandomAddress(addr)
  46. }
  47. return ""
  48. }
  49. func (b *baseTelegram) chooseRandomAddress(addresses []string) string {
  50. if len(addresses) > 0 {
  51. return addresses[rand.Intn(len(addresses))]
  52. }
  53. return ""
  54. }