func sync(db *bolt.DB) { tc := transmission.New("http://127.0.0.1:9091", "", "") if _, err := tc.GetTorrents(); err != nil { fmt.Println("Could not connect to Transmission RPC API: " + err.Error()) return } var ( shows []*Show results []*search.Result ) waiting := 0 fin := make(chan bool) rec := make(chan *search.Result) db.View(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("Shows")) c := b.Cursor() for k, v := c.First(); k != nil; k, v = c.Next() { show, err := ShowFromBytes(v) if err == nil { shows = append(shows, show) } } return nil }) for _, show := range shows { if show.Paused { continue } waiting += 1 go syncShow(show, rec, fin) } for waiting > 0 { select { case result := <-rec: results = append(results, result) case <-fin: waiting -= 1 } } for _, result := range results { fmt.Printf("Found torrent: '%s'\n", result.Name) if _, err := tc.AddTorrentByFilename(result.MagnetURL, ""); err != nil { fmt.Println("Error adding torrent: " + err.Error()) fmt.Println("Stopping...") return } } fmt.Printf("Found %d torrent(s)\n", len(results)) err := db.Batch(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("Shows")) for _, show := range shows { if err := b.Put([]byte(show.Name), show.Bytes()); err != nil { return err } } return nil }) if err != nil { fmt.Printf("Error occurred while saving shows: %s", err.Error()) } }
func downloadThing(url, dest string) error { if _, err := os.Stat(dest); err == nil { animu.LogVerbose(fmt.Sprintf(" File %s exists; skipping", dest)) return dlSkipped } resp, err := http.Get(url) if err != nil { return fmt.Errorf("Unable to download '%s': %s", url, err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return fmt.Errorf("Unable to read response: %s", err) } err = ioutil.WriteFile(dest, body, os.FileMode(0644)) if err != nil { return fmt.Errorf("Unable to write to file '%s': %s", dest, err) } animu.LogMsg(fmt.Sprintf("Downloaded %s", path.Base(dest))) if rpcUrl != "" { client := gt.New(rpcUrl, rpcUser, rpcPass) t, err := client.AddTorrentByFile(dest, rpcDir) if err != nil { return fmt.Errorf("Error adding torrent to transmission: %s", err) } animu.LogVerbose(fmt.Sprintf("Torrent added to transmission: [%d] {%s} %s", t.ID, t.HashString, t.Name)) animu.LogMsg(fmt.Sprintf("Added %s to transmission", path.Base(dest))) } return nil }