Some work on unfying actions on different sources.

This commit is contained in:
2021-02-27 19:38:43 +03:00
parent 3e94eb51d2
commit e70d1de06f
7 changed files with 217 additions and 4 deletions

81
gelbooru/api.go Normal file
View File

@@ -0,0 +1,81 @@
package gelbooru
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
)
type API struct {
apiKey string
userID string
httpClient http.Client
}
const (
apiEndpoint = "https://gelbooru.com/index.php"
)
func newRequest(params map[string]string) (r *http.Request, err error) {
if _, ok := params["page"]; !ok {
params["page"] = "dapi"
}
if _, ok := params["s"]; !ok {
params["s"] = "post"
}
if _, ok := params["q"]; !ok {
params["s"] = "index"
}
if _, ok := params["json"]; !ok {
params["json"] = "1"
}
var addr string
for name, value := range params {
if len(addr) == 0 {
addr = fmt.Sprintf("%s?%s=%s", addr, name, value)
} else {
addr = fmt.Sprintf("%s&%s=%s", addr, name, value)
}
}
addr = fmt.Sprintf("%s%s", apiEndpoint, addr)
r, err = http.NewRequest(http.MethodGet, addr, nil)
if err != nil {
err = fmt.Errorf("newRequest: %s", err.Error())
}
return
}
func New(userID string, APIKey string) (a API) {
a.userID = userID
a.apiKey = APIKey
a.httpClient = http.Client{
Transport: nil,
CheckRedirect: nil,
Jar: nil,
Timeout: time.Second * 30,
}
return
}
func (a *API) Search(querry string) (p []Post, err error) {
req, err := newRequest(map[string]string{"tags": querry})
if err != nil {
err = fmt.Errorf("Search: %s", err.Error())
return
}
resp, err := a.httpClient.Do(req)
if err != nil {
err = fmt.Errorf("Search: %s", err.Error())
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &p)
if err != nil {
err = fmt.Errorf("Search: %s", err.Error())
}
return
}

47
gelbooru/types.go Normal file
View File

@@ -0,0 +1,47 @@
package gelbooru
import "strings"
type Post struct {
Change int `json:"change"`
CreatedAt string `json:"created_at"`
Directory string `json:"directory"`
FileURL string `json:"file_url"`
Hash string `json:"hash"`
Height int `json:"height"`
Width int `json:"width"`
ID int `json:"id"`
Image string `json:"image"`
Owner string `json:"owner"`
ParentID string `json:"parent_id"`
PreviewHeight int `json:"preview_height"`
PreviewWidth int `json:"preview_width"`
Rating string `json:"raiting"`
Sample int `json:"sample"`
SampleHeight int `json:"sample_height"`
SampleWidth int `json:"sample_width"`
Score int `json:"score"`
Source string `json:"source"`
TagsOriginal string `json:"tags"`
Title string `json:"title"`
}
func (p *Post) Name() string {
return p.Title
}
func (p *Post) Author() string {
return ""
}
func (p *Post) Comment() string {
return ""
}
func (p *Post) Tags() []string {
return strings.Split(p.TagsOriginal, " ")
}
func (p *Post) Files() []string {
return []string{p.FileURL}
}