2023-08-10 15:02:51 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"codeberg.org/rimgo/rimgo/utils"
|
|
|
|
"github.com/PuerkitoBio/goquery"
|
|
|
|
)
|
|
|
|
|
|
|
|
type SearchResult struct {
|
|
|
|
Id string
|
|
|
|
Url string
|
|
|
|
ImageUrl string
|
|
|
|
Title string
|
|
|
|
User string
|
|
|
|
Points string
|
|
|
|
Views string
|
|
|
|
RelTime string
|
|
|
|
}
|
|
|
|
|
2023-08-10 16:00:42 +00:00
|
|
|
func (client *Client) Search(query string, page string) ([]SearchResult, error) {
|
2023-08-10 15:02:51 +00:00
|
|
|
query = url.QueryEscape(query)
|
2023-08-10 16:00:42 +00:00
|
|
|
req, err := http.NewRequest("GET", "https://imgur.com/search/all/page/" + page + "?scrolled&q_size_is_mpx=off&qs=list&q=" + query, nil)
|
2023-08-10 15:02:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return []SearchResult{}, err
|
|
|
|
}
|
|
|
|
utils.SetReqHeaders(req)
|
|
|
|
|
|
|
|
res, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return []SearchResult{}, err
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
if res.StatusCode != 200 {
|
|
|
|
return []SearchResult{}, fmt.Errorf("invalid status code, got %d", res.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
doc, err := goquery.NewDocumentFromReader(res.Body)
|
|
|
|
if err != nil {
|
|
|
|
return []SearchResult{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
results := []SearchResult{}
|
|
|
|
doc.Find(".post-list").Each(func(i int, s *goquery.Selection) {
|
|
|
|
url, _ := s.Find("a").Attr("href")
|
|
|
|
imageUrl, _ := s.Find("img").Attr("src")
|
|
|
|
|
|
|
|
postInfo := strings.Split(s.Find(".post-info").Text(), "·")
|
|
|
|
points := strings.TrimSpace(postInfo[0])
|
|
|
|
points = strings.TrimSuffix(points, " points")
|
|
|
|
views := strings.TrimSpace(postInfo[1])
|
|
|
|
views = strings.TrimSuffix(views, " views")
|
|
|
|
|
|
|
|
result := SearchResult{
|
|
|
|
Id: strings.Split(url, "/")[2],
|
|
|
|
Url: url,
|
2023-06-13 13:37:00 +00:00
|
|
|
ImageUrl: imageUrl,
|
2023-08-10 15:02:51 +00:00
|
|
|
Title: s.Find(".search-item-title a").Text(),
|
|
|
|
User: s.Find(".account").Text(),
|
|
|
|
Views: views,
|
|
|
|
Points: points,
|
|
|
|
RelTime: strings.TrimSpace(postInfo[2]),
|
|
|
|
}
|
|
|
|
|
|
|
|
results = append(results, result)
|
|
|
|
})
|
|
|
|
|
|
|
|
return results, nil
|
2023-06-13 13:37:00 +00:00
|
|
|
}
|