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
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

scout.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package doppel
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/9seconds/mtg/v2/essentials"
  10. "github.com/9seconds/mtg/v2/mtglib/internal/tls"
  11. )
  12. type Scout struct {
  13. network Network
  14. urls []string
  15. }
  16. func (s Scout) Learn(ctx context.Context) ([]time.Duration, error) {
  17. var durations []time.Duration
  18. for _, url := range s.urls {
  19. learned, err := s.learn(ctx, url)
  20. if err != nil {
  21. return nil, err
  22. }
  23. durations = append(durations, learned...)
  24. }
  25. return durations, nil
  26. }
  27. func (s Scout) learn(ctx context.Context, url string) ([]time.Duration, error) {
  28. client, results := s.makeClient()
  29. if !strings.HasPrefix(url, "https://") {
  30. return nil, fmt.Errorf("url %s must be https", url)
  31. }
  32. req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
  33. if err != nil {
  34. return nil, err
  35. }
  36. resp, err := client.Do(req)
  37. if resp != nil {
  38. io.Copy(io.Discard, resp.Body) //nolint: errcheck
  39. resp.Body.Close() //nolint: errcheck
  40. client.CloseIdleConnections()
  41. }
  42. if err != nil || len(results.data) == 0 {
  43. return nil, err
  44. }
  45. durations := []time.Duration{}
  46. lastTimestamp := time.Time{}
  47. for i, v := range results.data {
  48. if v.recordType != tls.TypeApplicationData {
  49. continue
  50. }
  51. if lastTimestamp.IsZero() {
  52. if i > 0 {
  53. lastTimestamp = results.data[i-1].timestamp
  54. } else {
  55. lastTimestamp = v.timestamp
  56. }
  57. }
  58. durations = append(durations, v.timestamp.Sub(lastTimestamp))
  59. lastTimestamp = v.timestamp
  60. }
  61. return durations, nil
  62. }
  63. func (s Scout) makeClient() (*http.Client, *ScoutConnCollected) {
  64. dialer := s.network.NativeDialer()
  65. collected := NewScoutConnCollected()
  66. client := s.network.MakeHTTPClient(func(
  67. ctx context.Context,
  68. network string,
  69. address string,
  70. ) (essentials.Conn, error) {
  71. conn, err := dialer.DialContext(ctx, network, address)
  72. if err != nil {
  73. return nil, err
  74. }
  75. return NewScoutConn(essentials.WrapNetConn(conn), collected), nil
  76. })
  77. return client, collected
  78. }
  79. func NewScout(network Network, urls []string) Scout {
  80. return Scout{
  81. network: network,
  82. urls: urls,
  83. }
  84. }