go-torrent-helper/common/main.go

92 lines
2.0 KiB
Go
Raw Normal View History

2023-06-24 04:33:24 +02:00
package common
import (
"fmt"
2023-07-18 04:54:36 +02:00
"io"
"log"
2023-06-24 04:33:24 +02:00
"net/http"
"strings"
"github.com/hekmon/transmissionrpc"
)
2023-07-18 04:54:36 +02:00
func GetResponse(url string) (io.ReadCloser, error) {
2023-06-24 04:33:24 +02:00
req, _ := http.NewRequest("GET", url, nil)
req.Header.Add("User-Agent", "go-torrent-helper")
// Add required headers for GitHub API
if strings.Contains(url, "github") {
req.Header.Add("Accept", "application/vnd.github.v3.text-match+json")
req.Header.Add("Accept", "application/vnd.github.moondragon+json")
}
// Carry out the request and receive response
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error while making request: %s\n", err)
}
// Status in <200 or >299
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf("Error: %d %s\n", resp.StatusCode, resp.Status)
}
2023-07-18 04:54:36 +02:00
// Return response body
return resp.Body, nil
2023-06-24 04:33:24 +02:00
}
func values[M ~map[K]V, K comparable, V any](m M) []V {
r := make([]V, 0, len(m))
for _, v := range m {
r = append(r, v)
}
return r
}
func keys[M ~map[K]V, K comparable, V any](m M) []K {
r := make([]K, 0, len(m))
for k := range m {
r = append(r, k)
}
return r
}
2023-06-24 04:33:24 +02:00
func RemoveTorrents(nameSubstr string, relver string, transmissionbt *transmissionrpc.Client) error {
torrents, err := transmissionbt.TorrentGet([]string{"id", "name"}, nil)
if err != nil {
return err
}
torrentsMap := map[string]int64{}
for _, torrent := range torrents {
if relver != "*" {
2023-06-24 04:33:24 +02:00
if strings.Contains(*torrent.Name, nameSubstr) && strings.Contains(*torrent.Name, relver) {
torrentsMap[*torrent.Name] = *torrent.ID
}
} else {
if strings.Contains(*torrent.Name, nameSubstr) {
torrentsMap[*torrent.Name] = *torrent.ID
2023-06-24 04:33:24 +02:00
}
}
}
rmPayload := &transmissionrpc.TorrentRemovePayload{
IDs: values(torrentsMap),
2023-07-05 12:27:30 +02:00
DeleteLocalData: true,
2023-06-24 04:33:24 +02:00
}
if err := transmissionbt.TorrentRemove(rmPayload); err != nil {
return err
}
for _, key := range keys(torrentsMap) {
log.Printf("%s removed\n", key)
}
2023-06-24 04:33:24 +02:00
return nil
}