2020-09-27 19:23:47 +00:00
|
|
|
package fs
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/anacrolix/torrent"
|
2021-03-01 16:43:28 +00:00
|
|
|
"github.com/distribyted/distribyted/iio"
|
2020-09-27 19:23:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var _ Filesystem = &Torrent{}
|
|
|
|
|
|
|
|
type Torrent struct {
|
2021-03-06 22:08:15 +00:00
|
|
|
ts []*torrent.Torrent
|
|
|
|
s *storage
|
2020-09-27 19:23:47 +00:00
|
|
|
}
|
|
|
|
|
2021-03-06 22:08:15 +00:00
|
|
|
func NewTorrent(ts []*torrent.Torrent) *Torrent {
|
2020-09-27 19:23:47 +00:00
|
|
|
return &Torrent{
|
2021-03-06 22:08:15 +00:00
|
|
|
ts: ts,
|
|
|
|
s: newStorage(SupportedFactories),
|
2020-09-27 19:23:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (fs *Torrent) load() {
|
2021-03-06 22:08:15 +00:00
|
|
|
for _, t := range fs.ts {
|
|
|
|
<-t.GotInfo()
|
|
|
|
for _, file := range t.Files() {
|
|
|
|
fs.s.Add(&torrentFile{readerFunc: file.NewReader, len: file.Length()}, file.Path())
|
|
|
|
}
|
2020-09-27 19:23:47 +00:00
|
|
|
}
|
2021-03-06 22:08:15 +00:00
|
|
|
|
2020-09-27 19:23:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (fs *Torrent) Open(filename string) (File, error) {
|
|
|
|
fs.load()
|
|
|
|
return fs.s.Get(filename)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (fs *Torrent) ReadDir(path string) (map[string]File, error) {
|
|
|
|
fs.load()
|
|
|
|
return fs.s.Children(path), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var _ File = &torrentFile{}
|
|
|
|
|
|
|
|
type torrentFile struct {
|
|
|
|
readerFunc func() torrent.Reader
|
|
|
|
reader iio.Reader
|
|
|
|
len int64
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *torrentFile) load() {
|
|
|
|
if d.reader != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
d.reader = iio.NewReadAtWrapper(d.readerFunc())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *torrentFile) Size() int64 {
|
|
|
|
return d.len
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *torrentFile) IsDir() bool {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *torrentFile) Close() error {
|
2021-03-01 18:04:59 +00:00
|
|
|
var err error
|
|
|
|
if d.reader != nil {
|
|
|
|
err = d.reader.Close()
|
|
|
|
}
|
|
|
|
|
2020-09-27 19:23:47 +00:00
|
|
|
d.reader = nil
|
2021-03-01 18:04:59 +00:00
|
|
|
|
2020-09-27 19:23:47 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *torrentFile) Read(p []byte) (n int, err error) {
|
|
|
|
d.load()
|
|
|
|
return d.reader.Read(p)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *torrentFile) ReadAt(p []byte, off int64) (n int, err error) {
|
|
|
|
d.load()
|
|
|
|
return d.reader.ReadAt(p, off)
|
|
|
|
}
|