67 lines
1.2 KiB
Go
67 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/anacrolix/torrent"
|
|
)
|
|
|
|
func main() {
|
|
if len(os.Args) < 2 {
|
|
fmt.Println("Usage: ./magnet-to-torrent \"magnet_link\" [output.torrent]")
|
|
os.Exit(1)
|
|
}
|
|
|
|
magnetLink := os.Args[1]
|
|
outputFile := ""
|
|
|
|
if len(os.Args) == 3 {
|
|
outputFile = os.Args[2]
|
|
}
|
|
|
|
clientConfig := torrent.NewDefaultClientConfig()
|
|
clientConfig.DataDir = os.TempDir()
|
|
clientConfig.NoUpload = true
|
|
|
|
client, err := torrent.NewClient(clientConfig)
|
|
if err != nil {
|
|
log.Fatalf("Error creating torrent client: %v", err)
|
|
}
|
|
defer client.Close()
|
|
|
|
t, err := client.AddMagnet(magnetLink)
|
|
if err != nil {
|
|
log.Fatalf("Error adding magnet link: %v", err)
|
|
}
|
|
|
|
<-t.GotInfo()
|
|
info := t.Metainfo()
|
|
|
|
if outputFile == "" {
|
|
outputFile = strings.ReplaceAll(t.Name(), " ", "_") + ".torrent"
|
|
}
|
|
|
|
f, err := os.Create(outputFile)
|
|
if err != nil {
|
|
log.Fatalf("Error creating file: %v", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
err = info.Write(f)
|
|
if err != nil {
|
|
log.Fatalf("Error writing torrent file: %v", err)
|
|
}
|
|
|
|
fmt.Printf("Torrent metadata saved to %s\n", outputFile)
|
|
|
|
t.Drop()
|
|
client.Close()
|
|
|
|
// Give client some time to gracefully close
|
|
time.Sleep(2 * time.Second)
|
|
}
|
|
|