本文整理汇总了Golang中github.com/anacrolix/torrent.NewClient函数的典型用法代码示例。如果您正苦于以下问题:Golang NewClient函数的具体用法?Golang NewClient怎么用?Golang NewClient使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewClient函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestDownloadOnDemand
func TestDownloadOnDemand(t *testing.T) {
layout, err := newGreetingLayout()
require.NoError(t, err)
defer layout.Destroy()
seeder, err := torrent.NewClient(&torrent.Config{
DataDir: layout.Completed,
DisableTrackers: true,
NoDHT: true,
ListenAddr: "localhost:0",
Seed: true,
// Ensure that the metainfo is obtained over the wire, since we added
// the torrent to the seeder by magnet.
DisableMetainfoCache: true,
})
require.NoError(t, err)
defer seeder.Close()
testutil.ExportStatusWriter(seeder, "s")
_, err = seeder.AddMagnet(fmt.Sprintf("magnet:?xt=urn:btih:%s", layout.Metainfo.Info.Hash.HexString()))
require.NoError(t, err)
leecher, err := torrent.NewClient(&torrent.Config{
DisableTrackers: true,
NoDHT: true,
ListenAddr: "localhost:0",
DisableTCP: true,
DefaultStorage: storage.NewMMap(filepath.Join(layout.BaseDir, "download")),
// This can be used to check if clients can connect to other clients
// with the same ID.
// PeerID: seeder.PeerID(),
})
require.NoError(t, err)
testutil.ExportStatusWriter(leecher, "l")
defer leecher.Close()
leecherTorrent, _ := leecher.AddTorrent(layout.Metainfo)
leecherTorrent.AddPeers([]torrent.Peer{
torrent.Peer{
IP: missinggo.AddrIP(seeder.ListenAddr()),
Port: missinggo.AddrPort(seeder.ListenAddr()),
},
})
fs := New(leecher)
defer fs.Destroy()
root, _ := fs.Root()
node, _ := root.(fusefs.NodeStringLookuper).Lookup(netContext.Background(), "greeting")
var attr fuse.Attr
node.Attr(netContext.Background(), &attr)
size := attr.Size
resp := &fuse.ReadResponse{
Data: make([]byte, size),
}
node.(fusefs.HandleReader).Read(netContext.Background(), &fuse.ReadRequest{
Size: int(size),
}, resp)
assert.EqualValues(t, testutil.GreetingFileContents, resp.Data)
}
示例2: Configure
func (e *Engine) Configure(c Config) error {
//recieve config
if e.client != nil {
e.client.Close()
}
tc := torrent.Config{
DataDir: c.DownloadDirectory,
ConfigDir: filepath.Join(c.DownloadDirectory, ".config"),
NoUpload: !c.EnableUpload,
Seed: c.EnableSeeding,
}
client, err := torrent.NewClient(&tc)
if err != nil {
return err
}
e.mut.Lock()
e.cacheDir = filepath.Join(tc.ConfigDir, "torrents")
if files, err := ioutil.ReadDir(e.cacheDir); err == nil {
for _, f := range files {
if filepath.Ext(f.Name()) != ".torrent" {
continue
}
tt, err := client.AddTorrentFromFile(filepath.Join(e.cacheDir, f.Name()))
if err == nil {
e.upsertTorrent(tt)
}
}
}
e.config = c
e.client = client
e.mut.Unlock()
//reset
e.GetTorrents()
return nil
}
示例3: main
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
tagflag.Parse(&opts, tagflag.SkipBadTypes())
clientConfig := opts.Config
if opts.Mmap {
clientConfig.TorrentDataOpener = func(info *metainfo.Info) torrent.Data {
ret, err := mmap.TorrentData(info, "")
if err != nil {
log.Fatalf("error opening torrent data for %q: %s", info.Name, err)
}
return ret
}
}
client, err := torrent.NewClient(&clientConfig)
if err != nil {
log.Fatalf("error creating client: %s", err)
}
defer client.Close()
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
client.WriteStatus(w)
})
uiprogress.Start()
addTorrents(client)
if client.WaitAll() {
log.Print("downloaded ALL the torrents")
} else {
log.Fatal("y u no complete torrents?!")
}
if opts.Seed {
select {}
}
}
示例4: main
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
tagflag.Parse(&flags)
var clientConfig torrent.Config
if flags.Mmap {
clientConfig.DefaultStorage = storage.NewMMap("")
}
if flags.Addr != nil {
clientConfig.ListenAddr = flags.Addr.String()
}
client, err := torrent.NewClient(&clientConfig)
if err != nil {
log.Fatalf("error creating client: %s", err)
}
defer client.Close()
// Write status on the root path on the default HTTP muxer. This will be
// bound to localhost somewhere if GOPPROF is set, thanks to the envpprof
// import.
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
client.WriteStatus(w)
})
uiprogress.Start()
addTorrents(client)
if client.WaitAll() {
log.Print("downloaded ALL the torrents")
} else {
log.Fatal("y u no complete torrents?!")
}
if flags.Seed {
select {}
}
}
示例5: main
func main() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
tagflag.Parse(&opts, tagflag.SkipBadTypes())
clientConfig := opts.Config
if opts.Mmap {
clientConfig.DefaultStorage = storage.NewMMap("")
}
client, err := torrent.NewClient(&clientConfig)
if err != nil {
log.Fatalf("error creating client: %s", err)
}
defer client.Close()
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
client.WriteStatus(w)
})
uiprogress.Start()
addTorrents(client)
if client.WaitAll() {
log.Print("downloaded ALL the torrents")
} else {
log.Fatal("y u no complete torrents?!")
}
if opts.Seed {
select {}
}
}
示例6: NewClient
// NewClient creates a new torrent client based on a magnet or a torrent file.
// If the torrent file is on http, we try downloading it.
func NewClient(torrentPath string, port int, seed bool) (client Client, err error) {
var t torrent.Torrent
var c *torrent.Client
client.Port = port
// Create client.
c, err = torrent.NewClient(&torrent.Config{
DataDir: os.TempDir(),
NoUpload: !seed,
Seed: seed,
})
if err != nil {
return client, ClientError{Type: "creating torrent client", Origin: err}
}
client.Client = c
// Add torrent.
// Add as magnet url.
if strings.HasPrefix(torrentPath, "magnet:") {
if t, err = c.AddMagnet(torrentPath); err != nil {
return client, ClientError{Type: "adding torrent", Origin: err}
}
} else {
// Otherwise add as a torrent file.
// If it's online, we try downloading the file.
if isHTTP.MatchString(torrentPath) {
if torrentPath, err = downloadFile(torrentPath); err != nil {
return client, ClientError{Type: "downloading torrent file", Origin: err}
}
}
// Check if the file exists.
if _, err = os.Stat(torrentPath); err != nil {
return client, ClientError{Type: "file not found", Origin: err}
}
if t, err = c.AddTorrentFromFile(torrentPath); err != nil {
return client, ClientError{Type: "adding torrent to the client", Origin: err}
}
}
client.Torrent = t
go func() {
<-t.GotInfo()
t.DownloadAll()
// Prioritize first 5% of the file.
client.getLargestFile().PrioritizeRegion(0, int64(t.NumPieces()/100*5))
}()
go client.addBlocklist()
return
}
示例7: New
func New(uri string) (*Downloader, string, error) {
var err error
var id string
var client *torrent.Client
var downloader = &Downloader{}
id = utils.CalcMd5(uri)
downloader.Id = id
client, err = torrent.NewClient(&torrent.Config{
DataDir: filepath.Join(os.TempDir(), "gochromecast"),
NoUpload: true,
Seed: true,
})
if err != nil {
return downloader, id, errors.New(
errors.DOWNLOADER_CANNOT_CREATE_TCLIENT_CODE,
errors.DOWNLOADER_CANNOT_CREATE_TCLIENT_MESSAGE,
err,
)
}
downloader.Client = client
return downloader, id, nil
}
示例8: main
func main() {
flag.Parse()
cl, err := torrent.NewClient(nil)
if err != nil {
log.Fatalf("error creating client: %s", err)
}
wg := sync.WaitGroup{}
for _, arg := range flag.Args() {
t, err := cl.AddMagnet(arg)
if err != nil {
log.Fatalf("error adding magnet to client: %s", err)
}
wg.Add(1)
go func() {
defer wg.Done()
<-t.GotInfo()
mi := t.Metainfo()
t.Drop()
f, err := os.Create(mi.Info.Name + ".torrent")
if err != nil {
log.Fatalf("error creating torrent metainfo file: %s", err)
}
defer f.Close()
err = bencode.NewEncoder(f).Encode(mi)
if err != nil {
log.Fatalf("error writing torrent metainfo file: %s", err)
}
}()
}
wg.Wait()
}
示例9: NewClient
// NewClient creates a new torrent client based on a magnet or a torrent file.
// If the torrent file is on http, we try downloading it.
func NewClient(cfg ClientConfig) (client Client, err error) {
var t *torrent.Torrent
var c *torrent.Client
client.Config = cfg
// Create client.
c, err = torrent.NewClient(&torrent.Config{
DataDir: os.TempDir(),
NoUpload: !cfg.Seed,
Seed: cfg.Seed,
DisableTCP: !cfg.TCP,
ListenAddr: fmt.Sprintf(":%d", cfg.TorrentPort),
})
if err != nil {
return client, ClientError{Type: "creating torrent client", Origin: err}
}
client.Client = c
// Add torrent.
// Add as magnet url.
if strings.HasPrefix(cfg.TorrentPath, "magnet:") {
if t, err = c.AddMagnet(cfg.TorrentPath); err != nil {
return client, ClientError{Type: "adding torrent", Origin: err}
}
} else {
// Otherwise add as a torrent file.
// If it's online, we try downloading the file.
if isHTTP.MatchString(cfg.TorrentPath) {
if cfg.TorrentPath, err = downloadFile(cfg.TorrentPath); err != nil {
return client, ClientError{Type: "downloading torrent file", Origin: err}
}
}
if t, err = c.AddTorrentFromFile(cfg.TorrentPath); err != nil {
return client, ClientError{Type: "adding torrent to the client", Origin: err}
}
}
client.Torrent = t
client.Torrent.SetMaxEstablishedConns(cfg.MaxConnections)
go func() {
<-t.GotInfo()
t.DownloadAll()
// Prioritize first 5% of the file.
client.getLargestFile().PrioritizeRegion(0, int64(t.NumPieces()/100*5))
}()
go client.addBlocklist()
return
}
示例10: Example
func Example() {
c, _ := torrent.NewClient(nil)
defer c.Close()
t, _ := c.AddMagnet("magnet:?xt=urn:btih:ZOCMZQIPFFW7OLLMIC5HUB6BPCSDEOQU")
<-t.GotInfo()
t.DownloadAll()
c.WaitAll()
log.Print("ermahgerd, torrent downloaded")
}
示例11: NewClient
// NewClient creates a new torrent client based on a magnet or a torrent file.
// If the torrent file is on http, we try downloading it.
func NewClient(torrentPath string) (client Client, err error) {
var t torrent.Torrent
var c *torrent.Client
// Create client.
c, err = torrent.NewClient(&torrent.Config{
DataDir: os.TempDir(),
NoUpload: !(*seed),
})
if err != nil {
return client, ClientError{Type: "creating torrent client", Origin: err}
}
client.Client = c
// Add torrent.
// Add as magnet url.
if strings.HasPrefix(torrentPath, "magnet:") {
if t, err = c.AddMagnet(torrentPath); err != nil {
return client, ClientError{Type: "adding torrent", Origin: err}
}
} else {
// Otherwise add as a torrent file.
// If it's online, we try downloading the file.
if isHTTP.MatchString(torrentPath) {
if torrentPath, err = downloadFile(torrentPath); err != nil {
return client, ClientError{Type: "downloading torrent file", Origin: err}
}
}
// Check if the file exists.
if _, err = os.Stat(torrentPath); err != nil {
return client, ClientError{Type: "file not found", Origin: err}
}
if t, err = c.AddTorrentFromFile(torrentPath); err != nil {
return client, ClientError{Type: "adding torrent to the client", Origin: err}
}
}
client.Torrent = t
go func() {
<-t.GotInfo()
t.DownloadAll()
}()
return
}
示例12: SetConfig
func (n *Native) SetConfig(obj interface{}) error {
//recieve config
c, ok := obj.(*config)
if !ok {
return fmt.Errorf("Invalid config")
}
client, err := torrent.NewClient(&c.Config)
if err != nil {
return err
}
n.client = client
return nil
}
示例13: NewClient
func NewClient(downloadFolder string) (*Client, error) {
client, err := torrent.NewClient(&torrent.Config{
DataDir: downloadFolder,
NoUpload: false,
Seed: true,
DisableTCP: false,
})
if err != nil {
return nil, ClientError{Type: "creating torrent client", Origin: err}
}
return &Client{
Client: client,
downloadFolder: downloadFolder,
}, nil
}
示例14: NewBuiltin
func NewBuiltin(dataDir string) (builtin *Builtin, err error) {
cfg := &torrent.Config{
DataDir: dataDir,
Seed: true,
NoDHT: true,
}
client, err := torrent.NewClient(cfg)
if err != nil {
return
}
builtin = &Builtin{
Client: client,
}
return
}
示例15: Configure
func (e *Engine) Configure(c Config) error {
//recieve config
if e.client != nil {
e.client.Close()
time.Sleep(1 * time.Second)
}
if c.IncomingPort <= 0 {
return fmt.Errorf("Invalid incoming port (%d)", c.IncomingPort)
}
tc := torrent.Config{
DataDir: c.DownloadDirectory,
ListenAddr: "0.0.0.0:" + strconv.Itoa(c.IncomingPort),
NoUpload: !c.EnableUpload,
Seed: c.EnableSeeding,
DisableEncryption: c.DisableEncryption,
}
client, err := torrent.NewClient(&tc)
if err != nil {
return err
}
e.mut.Lock()
e.cacheDir = filepath.Join(c.DownloadDirectory, ".config", "magnets")
os.MkdirAll(e.cacheDir, 0777)
if files, err := ioutil.ReadDir(e.cacheDir); err == nil {
for _, f := range files {
if filepath.Ext(f.Name()) != ".magnet" {
continue
}
b, err := ioutil.ReadFile(filepath.Join(e.cacheDir, f.Name()))
if err == nil {
tt, err := client.AddMagnet(string(b[:]))
if err == nil {
e.upsertTorrent(tt)
}
}
}
}
e.config = c
e.client = client
e.mut.Unlock()
//reset
e.GetTorrents()
return nil
}