86 lines
2.0 KiB
Go
86 lines
2.0 KiB
Go
package format
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
const anilistURL = "https://graphql.anilist.co"
|
|
|
|
var httpClient = &http.Client{Timeout: 10 * time.Second}
|
|
|
|
const batchAiringQuery = `
|
|
query ($mediaIds: [Int]) {
|
|
Page(page: 1, perPage: 50) {
|
|
media(id_in: $mediaIds) {
|
|
id
|
|
title { romaji english }
|
|
format
|
|
status
|
|
airingSchedule(notYetAired: true) {
|
|
nodes { episode airingAt timeUntilAiring }
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`
|
|
|
|
const airingQuery = `
|
|
query ($mediaId: Int!) {
|
|
Media(id: $mediaId) {
|
|
id
|
|
title { romaji english }
|
|
format
|
|
status
|
|
airingSchedule(notYetAired: true) {
|
|
nodes { episode airingAt timeUntilAiring }
|
|
}
|
|
}
|
|
}
|
|
`
|
|
|
|
func postGraphQL(query string, variables map[string]any) ([]byte, error) {
|
|
payload, err := json.Marshal(map[string]any{
|
|
"query": query,
|
|
"variables": variables,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("marshal request: %w", err)
|
|
}
|
|
|
|
req, err := http.NewRequest(http.MethodPost, anilistURL, bytes.NewReader(payload))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("build request: %w", err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Accept", "application/json")
|
|
|
|
resp, err := httpClient.Do(req)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("send request: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("read response: %w", err)
|
|
}
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("anilist: %s: %s", resp.Status, body)
|
|
}
|
|
return body, nil
|
|
}
|
|
|
|
// BatchAiringSchedule fetches schedules for up to 50 media IDs per call.
|
|
func BatchAiringSchedule(mediaIds []int32) ([]byte, error) {
|
|
return postGraphQL(batchAiringQuery, map[string]any{"mediaIds": mediaIds})
|
|
}
|
|
|
|
// AiringSchedule fetches the upcoming airing schedule for one media ID.
|
|
func AiringSchedule(mediaId int32) ([]byte, error) {
|
|
return postGraphQL(airingQuery, map[string]any{"mediaId": mediaId})
|
|
} |