Search/files-nyaa.go
partisan 67eefc2c7a
Some checks failed
Run Integration Tests / test (push) Failing after 44s
Added Nyaa to file search
2025-06-28 17:33:36 +02:00

107 lines
2.2 KiB
Go

package main
import (
"fmt"
"net/http"
"net/url"
"strings"
"github.com/PuerkitoBio/goquery"
)
const NYAA_DOMAIN = "nyaa.si"
type Nyaa struct{}
func NewNyaa() *Nyaa {
return &Nyaa{}
}
func (n *Nyaa) Name() string {
return "nyaa"
}
func (n *Nyaa) getCategoryCode(cat string) string {
switch cat {
case "all":
return ""
case "anime":
return "&c=1_0"
case "music":
return "&c=2_0"
case "game":
return "&c=6_2"
case "software":
return "&c=6_1"
default:
return "ignore"
}
}
func (n *Nyaa) Search(query string, category string) ([]TorrentResult, error) {
categoryCode := n.getCategoryCode(category)
if categoryCode == "ignore" {
return []TorrentResult{}, nil
}
searchURL := fmt.Sprintf("https://%s/?f=0&q=%s%s", NYAA_DOMAIN, url.QueryEscape(query), categoryCode)
userAgent, err := GetUserAgent("files-nyaa")
if err != nil {
return nil, err
}
req, err := http.NewRequest("GET", searchURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", userAgent)
resp, err := DoMetaProxyRequest(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status: %d", resp.StatusCode)
}
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return nil, err
}
var results []TorrentResult
doc.Find(".default, .success, .danger").Each(func(i int, s *goquery.Selection) {
tds := s.Find("td")
if tds.Length() < 7 {
return
}
title := tds.Eq(1).Find("a").Last().Text()
magnet, _ := tds.Eq(2).Find("a").Last().Attr("href")
sizeStr := strings.TrimSpace(tds.Eq(3).Text())
byteSize := parseSize(sizeStr)
seeders := parseInt(tds.Eq(5).Text())
leechers := parseInt(tds.Eq(6).Text())
results = append(results, TorrentResult{
URL: "https://" + NYAA_DOMAIN,
Title: title,
Magnet: applyTrackers(magnet),
Size: formatSize(byteSize),
Seeders: seeders,
Leechers: leechers,
Views: 0,
})
})
// Reverse the results slice, so It's from newest to oldest, but the orders is still kinda random
for i, j := 0, len(results)-1; i < j; i, j = i+1, j-1 {
results[i], results[j] = results[j], results[i]
}
return results, nil
}