github.com/anacrolix/torrent@v1.61.0/webtorrent/tracker-protocol.go (about)

     1  package webtorrent
     2  
     3  import (
     4  	"fmt"
     5  	"math"
     6  
     7  	"github.com/pion/webrtc/v4"
     8  )
     9  
    10  type AnnounceRequest struct {
    11  	Numwant    int     `json:"numwant"`
    12  	Uploaded   int64   `json:"uploaded"`
    13  	Downloaded int64   `json:"downloaded"`
    14  	Left       int64   `json:"left"`
    15  	Event      string  `json:"event,omitempty"`
    16  	Action     string  `json:"action"`
    17  	InfoHash   string  `json:"info_hash"`
    18  	PeerID     string  `json:"peer_id"`
    19  	Offers     []Offer `json:"offers"`
    20  }
    21  
    22  type Offer struct {
    23  	OfferID string                    `json:"offer_id"`
    24  	Offer   webrtc.SessionDescription `json:"offer"`
    25  }
    26  
    27  type AnnounceResponse struct {
    28  	InfoHash   string                     `json:"info_hash"`
    29  	Action     string                     `json:"action"`
    30  	Interval   *int                       `json:"interval,omitempty"`
    31  	Complete   *int                       `json:"complete,omitempty"`
    32  	Incomplete *int                       `json:"incomplete,omitempty"`
    33  	PeerID     string                     `json:"peer_id,omitempty"`
    34  	ToPeerID   string                     `json:"to_peer_id,omitempty"`
    35  	Answer     *webrtc.SessionDescription `json:"answer,omitempty"`
    36  	Offer      *webrtc.SessionDescription `json:"offer,omitempty"`
    37  	OfferID    string                     `json:"offer_id,omitempty"`
    38  }
    39  
    40  // I wonder if this is a defacto standard way to decode bytes to JSON for webtorrent. I don't really
    41  // care.
    42  func binaryToJsonString(b []byte) string {
    43  	var seq []rune
    44  	for _, v := range b {
    45  		seq = append(seq, rune(v))
    46  	}
    47  	return string(seq)
    48  }
    49  
    50  func jsonStringToInfoHash(s string) (ih [20]byte, err error) {
    51  	b, err := decodeJsonByteString(s, ih[:0])
    52  	if err != nil {
    53  		return
    54  	}
    55  	if len(b) != len(ih) {
    56  		err = fmt.Errorf("string decoded to %v bytes", len(b))
    57  	}
    58  	return
    59  }
    60  
    61  func decodeJsonByteString(s string, b []byte) ([]byte, error) {
    62  	defer func() {
    63  		r := recover()
    64  		if r == nil {
    65  			return
    66  		}
    67  		panic(fmt.Sprintf("%q", s))
    68  	}()
    69  	for _, c := range []rune(s) {
    70  		if c < 0 || c > math.MaxUint8 {
    71  			return b, fmt.Errorf("rune out of bounds: %v", c)
    72  		}
    73  		b = append(b, byte(c))
    74  	}
    75  	return b, nil
    76  }