1 // Mounts a FUSE filesystem backed by torrents and magnet links.
17 fusefs "bazil.org/fuse/fs"
18 _ "github.com/anacrolix/envpprof"
19 "github.com/anacrolix/log"
20 "github.com/anacrolix/tagflag"
22 "github.com/anacrolix/torrent"
23 torrentfs "github.com/anacrolix/torrent/fs"
24 "github.com/anacrolix/torrent/util/dirwatch"
28 MetainfoDir string `help:"torrent files in this location describe the contents of the mounted filesystem"`
29 DownloadDir string `help:"location to save torrent data"`
30 MountDir string `help:"location the torrent contents are made available"`
34 ReadaheadBytes tagflag.Bytes
35 ListenAddr *net.TCPAddr
37 MetainfoDir: func() string {
38 _user, err := user.Current()
42 return filepath.Join(_user.HomeDir, ".config/transmission/torrents")
44 ReadaheadBytes: 10 << 20,
45 ListenAddr: &net.TCPAddr{},
48 func exitSignalHandlers(fs *torrentfs.TorrentFS) {
49 c := make(chan os.Signal, 1)
50 signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
54 err := fuse.Unmount(args.MountDir)
61 func addTestPeer(client *torrent.Client) {
62 for _, t := range client.Torrents() {
63 t.AddPeers([]torrent.PeerInfo{{
72 log.Printf("error in main: %v", err)
77 func mainErr() error {
79 if args.MountDir == "" {
80 os.Stderr.WriteString("y u no specify mountpoint?\n")
83 conn, err := fuse.Mount(args.MountDir)
85 return fmt.Errorf("mounting: %w", err)
87 defer fuse.Unmount(args.MountDir)
88 // TODO: Think about the ramifications of exiting not due to a signal.
90 cfg := torrent.NewDefaultClientConfig()
91 cfg.DataDir = args.DownloadDir
92 cfg.DisableTrackers = args.DisableTrackers
93 cfg.NoUpload = true // Ensure that downloads are responsive.
94 cfg.SetListenAddr(args.ListenAddr.String())
95 client, err := torrent.NewClient(cfg)
97 return fmt.Errorf("creating torrent client: %w", err)
99 // This is naturally exported via GOPPROF=http.
100 http.DefaultServeMux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
101 client.WriteStatus(w)
103 dw, err := dirwatch.New(args.MetainfoDir)
105 return fmt.Errorf("watching torrent dir: %w", err)
107 dw.Logger = dw.Logger.FilterLevel(log.Info)
109 for ev := range dw.Events {
112 if ev.TorrentFilePath != "" {
113 _, err := client.AddTorrentFromFile(ev.TorrentFilePath)
115 log.Printf("error adding torrent from file %q to client: %v", ev.TorrentFilePath, err)
117 } else if ev.MagnetURI != "" {
118 _, err := client.AddMagnet(ev.MagnetURI)
120 log.Printf("error adding magnet: %s", err)
123 case dirwatch.Removed:
124 T, ok := client.Torrent(ev.InfoHash)
132 fs := torrentfs.New(client)
133 go exitSignalHandlers(fs)
135 if args.TestPeer != nil {
139 time.Sleep(10 * time.Second)
144 if err := fusefs.Serve(conn, fs); err != nil {
145 return fmt.Errorf("serving fuse fs: %w", err)
148 if err := conn.MountError; err != nil {
149 return fmt.Errorf("mount error: %w", err)