README

libtorrent

Go torrent library with nice and simple interface. Can be used as standart Go library or gomobile library (iOS / Android)

Features

Base Features (https://github.com/anacrolix/torrent):

  • Protocol obfuscation
  • DHT
  • uTP
  • PEX
  • Magnet links
  • IP Blocklists
  • Some IPv6
  • HTTP and UDP tracker clients

BEPs:

  • 3: Basic BitTorrent protocol
  • 5: DHT
  • 6: Fast Extension (have all/none only)
  • 7: IPv6 Tracker Extension
  • 9: ut_metadata
  • 10: Extension protocol
  • 11: PEX
  • 12: Multitracker metadata extension
  • 15: UDP Tracker Protocol
  • 20: Peer ID convention ("-GTnnnn-")
  • 23: Tracker Returns Compact Peer Lists
  • 27: Private torrents
  • 29: uTorrent transport protocol
  • 41: UDP Tracker Protocol Extensions
  • 42: DHT Security extension
  • 43: Read-only DHT Nodes

Additional features:

  • UPnP / PMP
  • Rename Torrent top folder
  • Runtime torrent states (save state between restarts)
  • Queue Engine (active/queued torrent list)
  • Full Contorl over torrent state (download metadata, download data, stop, pause, resume)

BEPs:

  • 14: Local Peers Discovery
  • 19: WebSeeds

Build

# git clone https://gitlab.com/axet/torrent $GOPATH/src/github.com/anacrolix/torrent
# go get -u bitbucket.org/JakeKalstad/libtorrent-go

Headers

# go tool cgo libtorrent.go

Android

Use within your android gralde project:

# gomobile bind -o libtorrent.aar bitbucket.org/JakeKalstad/libtorrent-go

Then import your libtorrent.arr into Android Studio or Eclipse.

Examples

package main

import (
	"log"
	"time"

	"bitbucket.org/JakeKalstad/libtorrent-go"
)

func createTorrentFileExample() {
	t1 := libtorrent.CreateTorrentFile("/Users/axet/Downloads/Prattchet")
	ioutil.WriteFile("./test.torrent", t1, 0644)
}

func downloadMagnetWaitExample() {
	libtorrent.Create()
	t1 := libtorrent.AddMagnet("/tmp", "magnet:?...")
	libtorrent.StartTorrent(t1)
	libtorrent.WaitAll()
	log.Println("done")
	libtorrent.Close()
}

func downloadMagnetStatusExample() {
	libtorrent.Create()
	t1 := libtorrent.AddMagnet("/tmp", "magnet:?...")
	libtorrent.StartTorrent(t1)
	for libtorrent.TorrentStatus(t1) == libtorrent.StatusDownloading {
		time.Sleep(100 * time.Millisecond)
		log.Println("loop")
	}
	log.Println("done")
	libtorrent.Close()
}
Expand ▾ Collapse ▴

Documentation

Index

Constants

View Source
const (
	StatusPaused      int32 = 0
	StatusDownloading int32 = 1
	StatusSeeding     int32 = 2
	StatusChecking    int32 = 3
	StatusQueued      int32 = 4
)
View Source
const (
	PieceEmpty    int32 = 0 // gray
	PieceComplete int32 = 1 // blue
	PieceChecking int32 = 2 // yellow
	PiecePartial  int32 = 3 // green, when booth empty and completed
	PieceWriting  int32 = 4 // red, when have partial pieces
	PieceUnpended int32 = 5 // ltgray, empy pieces can be unpended
)
View Source
const WEBSEED_BUF = 64 * 1024 // read buffer size
View Source
const WEBSEED_CONCURENT = 4 // how many concurent downloading total
View Source
const WEBSEED_SPLIT = 10 * 1024 * 1024 // how large split for single sizes
View Source
const WEBSEED_TIMEOUT = time.Duration(5 * time.Second) // dial up and socket read timeouts
View Source
const WEBSEED_URL_CONCURENT = 2 // how many concurent downloading per one Url

Variables

View Source
var (
	Version                  = ""
	Bep20                    = ""
	SocketsPerTorrent int    = 40
	BindAddr          string = ":53007"
)
View Source
var ActiveCount = 3
View Source
var CONTENT_RANGE = regexp.MustCompile("bytes (\\d+)-(\\d+)/(\\d+)")
View Source
var QueueTimeout = (30 * time.Minute).Nanoseconds()
View Source
var (
	RefreshPort = (1 * time.Minute).Nanoseconds()
)

Functions

func AddMagnet

func AddMagnet(path string, magnet string) int

AddMagnet

export AddMagnet

func AddTorrent

func AddTorrent(file string) int

    AddTorrent

    Add torrent from local file and seed.

    export AddTorrent

    func AddTorrentFromBytes

    func AddTorrentFromBytes(path string, buf []byte) int

      export AddTorrentFromBytes

      func AddTorrentFromURL

      func AddTorrentFromURL(path string, url string) int

        AddTorrent

        Add torrent from local file or remote url.

        export AddTorrentFromURL

        func CheckTorrent

        func CheckTorrent(i int)

          CheckTorrent

          Check torrent file consisteny (pices hases) on a disk. Pause torrent if downloading, resume after.

          export CheckTorrent

          func Close

          func Close()

            export Close

            func CloseMetaInfo

            func CloseMetaInfo()

              export CloseMetaInfo

              func Count

              func Count() int

                Get Torrent Count

                export Count

                func Create

                func Create() bool

                Create

                Create libtorrent object

                export Create

                func CreateMetainfo

                func CreateMetainfo(root string) int

                  export CreateMetaInfo

                  func CreateMetainfoBuilder

                  func CreateMetainfoBuilder(b MetainfoBuilder) int

                    export CreateMetaInfo

                    func CreateTorrentFile

                    func CreateTorrentFile(root string) []byte

                    func CreateTorrentFileFromMetaInfo

                    func CreateTorrentFileFromMetaInfo() []byte

                      export CreateTorrentFileFromMetaInfo

                      func CreateTorrentFromMetaInfo

                      func CreateTorrentFromMetaInfo() int

                        export CreateTorrentFromMetaInfo

                        func DownloadMetadata

                        func DownloadMetadata(i int) bool

                          Download only metadata from magnet link and stop torrent

                          export DownloadMetadata

                          func Error

                          func Error() string

                            export Error

                            func GetTorrent

                            func GetTorrent(i int) []byte

                              Get Torrent file from runtime torrent

                              export GetTorrent

                              func HashMetaInfo

                              func HashMetaInfo(piece int) bool

                                export HashMetaInfo

                                func ListenAddr

                                func ListenAddr() string

                                  export ListenAddr

                                  func LoadTorrent

                                  func LoadTorrent(path string, buf []byte) int

                                  LoadTorrent

                                  Load runtime torrent data from saved state file

                                  export LoadTorrent

                                  func MetaTorrent

                                  func MetaTorrent(i int) bool

                                  func Pause

                                  func Pause()

                                  func Paused

                                  func Paused() bool

                                  func PendingCompleted

                                  func PendingCompleted(i int) bool

                                  func Port

                                  func Port(i int) string

                                  func PortCheck

                                  func PortCheck() (bool, error)

                                  func PortCount

                                  func PortCount() int

                                  func RemoveTorrent

                                  func RemoveTorrent(i int)

                                    Remote torrent for library

                                    export RemoveTorrent

                                    func Resume

                                    func Resume()

                                    func SaveTorrent

                                    func SaveTorrent(i int) []byte

                                    SaveTorrent

                                    Every torrent application restarts it require to check files consistency. To avoid this, and save machine time we need to store torrents runtime states completed pieces and other information externaly.

                                    Save runtime torrent data to state file

                                    export SaveTorrent

                                    func SetDefaultAnnouncesList

                                    func SetDefaultAnnouncesList(str string)

                                    func SetDownloadRate

                                    func SetDownloadRate(i int)

                                    func SetUploadRate

                                    func SetUploadRate(i int)

                                    func StartTorrent

                                    func StartTorrent(i int) bool

                                      Separate load / create torrent from network activity.

                                      Start announce torrent, seed/download

                                      export StartTorrent

                                      func StopTorrent

                                      func StopTorrent(i int)

                                        Stop torrent from announce, check, seed, download

                                        export StopTorrent

                                        func TorrentActive

                                        func TorrentActive(i int) bool

                                          export TorrentActive

                                          func TorrentBytesCompleted

                                          func TorrentBytesCompleted(i int) int64

                                            export TorrentBytesCompleted

                                            func TorrentBytesLength

                                            func TorrentBytesLength(i int) int64

                                              export TorrentBytesLength

                                              func TorrentFileDeleteUnselected

                                              func TorrentFileDeleteUnselected(i int)

                                                export TorrentFileDeleteUnselected

                                                func TorrentFileRename

                                                func TorrentFileRename(i int, f int, n string) bool

                                                  TorrentFileRename

                                                  To implement this we need to keep two Metainfo one for network operations, and second for local file storage.

                                                  export TorrentFileRename

                                                  func TorrentFilesCheck

                                                  func TorrentFilesCheck(i int, p int, b bool)

                                                  func TorrentFilesCheckAll

                                                  func TorrentFilesCheckAll(i int, b bool)

                                                  func TorrentFilesCheckFilter

                                                  func TorrentFilesCheckFilter(i int, filter string, b bool)

                                                  func TorrentFilesCount

                                                  func TorrentFilesCount(i int) int

                                                  func TorrentHash

                                                  func TorrentHash(i int) string

                                                    export TorrentHash

                                                    func TorrentInfoComment

                                                    func TorrentInfoComment(i int, s string)

                                                    func TorrentInfoCreator

                                                    func TorrentInfoCreator(i int, s string)

                                                    func TorrentInfoName

                                                    func TorrentInfoName(i int, s string)

                                                    func TorrentMagnet

                                                    func TorrentMagnet(i int) string

                                                      Get Magnet from runtime torrent.

                                                      export TorrentMagnet

                                                      func TorrentMetainfo

                                                      func TorrentMetainfo(i int) *metainfo.MetaInfo

                                                      func TorrentName

                                                      func TorrentName(i int) string

                                                        export TorrentName

                                                        func TorrentPeersCount

                                                        func TorrentPeersCount(i int) int

                                                        func TorrentPendingBytesCompleted

                                                        func TorrentPendingBytesCompleted(i int) int64

                                                          Get total bytes downloaded by pending pieces list

                                                          func TorrentPendingBytesLength

                                                          func TorrentPendingBytesLength(i int) int64

                                                            Get total bytes for pending pieces list

                                                            func TorrentPieceLength

                                                            func TorrentPieceLength(i int) int64

                                                            func TorrentPiecesCompact

                                                            func TorrentPiecesCompact(i int, p int) int32

                                                            func TorrentPiecesCompactCount

                                                            func TorrentPiecesCompactCount(i int, size int) int

                                                            func TorrentPiecesCount

                                                            func TorrentPiecesCount(i int) int

                                                            func TorrentRename

                                                            func TorrentRename(i int, n string) bool

                                                            func TorrentSetName

                                                            func TorrentSetName(i int, n string)

                                                            func TorrentStatus

                                                            func TorrentStatus(i int) int32

                                                              export TorrentStatus

                                                              func TorrentStorageSet

                                                              func TorrentStorageSet(p FileStorageTorrent)

                                                              func TorrentTrackerAdd

                                                              func TorrentTrackerAdd(i int, addr string)

                                                              func TorrentTrackerRemove

                                                              func TorrentTrackerRemove(i int, url string)

                                                              func TorrentTrackersCount

                                                              func TorrentTrackersCount(i int) int

                                                              func TorrentWebSeedsCount

                                                              func TorrentWebSeedsCount(i int) int

                                                              func WaitAll

                                                              func WaitAll() bool

                                                              func WebSeedStart

                                                              func WebSeedStart(t *torrent.Torrent)

                                                              Types

                                                              type BodyReader

                                                              type BodyReader struct {
                                                              	// contains filtered or unexported fields
                                                              }

                                                              func (*BodyReader) Read

                                                              func (m *BodyReader) Read(b []byte) (int, error)

                                                              type Buffer

                                                              type Buffer struct {
                                                              	// contains filtered or unexported fields
                                                              }

                                                              func (*Buffer) Length

                                                              func (m *Buffer) Length() int

                                                              func (*Buffer) Write

                                                              func (m *Buffer) Write(b []byte, pos int, len int) (int, error)

                                                              type BytesInfo

                                                              type BytesInfo struct {
                                                              	Downloaded int64
                                                              	Uploaded   int64
                                                              }

                                                              func Stats

                                                              func Stats() *BytesInfo

                                                              type File

                                                              type File struct {
                                                              	Check          bool
                                                              	Path           string
                                                              	Length         int64
                                                              	BytesCompleted int64
                                                              }

                                                              func TorrentFiles

                                                              func TorrentFiles(i int, p int) *File

                                                                return torrent files array

                                                                type FileStorageTorrent

                                                                type FileStorageTorrent interface {
                                                                	ReadFileAt(hash string, path string, buf *Buffer, off int64) (n int, err error) // java unable to change []byte buf if it passed as a parameter
                                                                	WriteFileAt(hash string, path string, b []byte, off int64) (n int, err error)
                                                                	Remove(hash string, path string) error
                                                                	Rename(hash string, old string, path string) error
                                                                }

                                                                type InfoTorrent

                                                                type InfoTorrent struct {
                                                                	Creator       string
                                                                	CreateOn      int64
                                                                	Comment       string
                                                                	DateAdded     int64
                                                                	DateCompleted int64
                                                                }

                                                                func TorrentInfo

                                                                func TorrentInfo(i int) *InfoTorrent

                                                                type Int64Slice

                                                                type Int64Slice []int64

                                                                func (Int64Slice) Len

                                                                func (p Int64Slice) Len() int

                                                                func (Int64Slice) Less

                                                                func (p Int64Slice) Less(i, j int) bool

                                                                func (Int64Slice) Sort

                                                                func (p Int64Slice) Sort()

                                                                func (Int64Slice) Swap

                                                                func (p Int64Slice) Swap(i, j int)

                                                                type LPDConn

                                                                type LPDConn struct {
                                                                	// contains filtered or unexported fields
                                                                }

                                                                func (*LPDConn) Close

                                                                func (m *LPDConn) Close()

                                                                type LPDServer

                                                                type LPDServer struct {
                                                                	// contains filtered or unexported fields
                                                                }

                                                                type MetainfoBuilder

                                                                type MetainfoBuilder interface {
                                                                	Name() string
                                                                	Root() string // root directory / url for torrent register
                                                                	FilesCount() (int, error)
                                                                	FilesName(i int) string
                                                                	FilesLength(i int) int64
                                                                	ReadFileAt(path string, buf *Buffer, off int64) (n int, err error) // java unable to change buf if it passed as a parameter
                                                                }

                                                                type MultipartReader

                                                                type MultipartReader struct {
                                                                	// contains filtered or unexported fields
                                                                }

                                                                func (*MultipartReader) Read

                                                                func (m *MultipartReader) Read(b []byte) (int, error)

                                                                type Peer

                                                                type Peer struct {
                                                                	Id     [20]byte
                                                                	Name   string
                                                                	Addr   string
                                                                	Source string
                                                                	// Peer is known to support encryption.
                                                                	SupportsEncryption bool
                                                                	PiecesCompleted    int64
                                                                	// how many data we downloaded/uploaded from peer
                                                                	Downloaded int64
                                                                	Uploaded   int64
                                                                }

                                                                func TorrentPeers

                                                                func TorrentPeers(i int, p int) *Peer

                                                                type StatsTorrent

                                                                type StatsTorrent struct {
                                                                	Downloaded  int64 // bytes
                                                                	Uploaded    int64 // bytes
                                                                	Downloading int64 // time
                                                                	Seeding     int64 // time
                                                                }

                                                                func TorrentStats

                                                                func TorrentStats(i int) *StatsTorrent

                                                                type TorrentState

                                                                type TorrentState struct {
                                                                	Version int `json:"version"`
                                                                
                                                                	// metainfo or these
                                                                	InfoHash *metainfo.Hash `json:"hash,omitempty"`
                                                                	Name     string         `json:"name,omitempty"`
                                                                	Trackers [][]string     `json:"trackers,omitempty"`
                                                                
                                                                	MetaInfo *metainfo.MetaInfo `json:"metainfo,omitempty"`
                                                                	Pieces   []bool             `json:"pieces,omitempty"`
                                                                
                                                                	Root string `json:root,omitempty`
                                                                
                                                                	Checks []bool `json:"checks,omitempty"`
                                                                
                                                                	// Stats bytes
                                                                	Downloaded int64 `json:"downloaded,omitempty"`
                                                                	Uploaded   int64 `json:"uploaded,omitempty"`
                                                                
                                                                	// dates
                                                                	AddedDate     int64 `json:"added_date,omitempty"`
                                                                	CompletedDate int64 `json:"completed_date,omitempty"`
                                                                
                                                                	// time
                                                                	DownloadingTime int64 `json:"downloading_time,omitempty"`
                                                                	SeedingTime     int64 `json:"seeding_time,omitempty"`
                                                                
                                                                	// .torrent
                                                                	Comment   string `json:"comment,omitempty"`
                                                                	Creator   string `json:"creator,omitempty"`
                                                                	CreatedOn int64  `json:"created_on,omitempty"`
                                                                
                                                                	UrlList metainfo.UrlList `bencode:"url-list,omitempty"`
                                                                }

                                                                type Tracker

                                                                type Tracker struct {
                                                                	// Tracker URI or DHT, LSD, PE
                                                                	Addr         string
                                                                	Error        string
                                                                	LastAnnounce int64
                                                                	NextAnnounce int64
                                                                	Peers        int
                                                                
                                                                	// scrape info
                                                                	LastScrape int64
                                                                	Seeders    int
                                                                	Leechers   int
                                                                	Downloaded int
                                                                }

                                                                func TorrentTrackers

                                                                func TorrentTrackers(i int, p int) *Tracker

                                                                type WebSeedUrl

                                                                type WebSeedUrl struct {
                                                                	Url        string
                                                                	Downloaded int64  // total bytes / speed test
                                                                	Error      string // error if url were removed
                                                                }

                                                                func TorrentWebSeeds

                                                                func TorrentWebSeeds(i int, p int) *WebSeedUrl