tracker-protocol.go 2.0 KB

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