Commit 05a134cfc3

05a134cfc36bf9f9a2bbdd02b4f966d7af5b96a2

parent: d734957927

Unsigned

Wraient <wraient.911@gmail.com> · 2024-10-23 10:24 UTC

Add: Get anime by anilistid Function

Layout: unified · split

internal/anilist.go +80 −1
@@ -5,6 +5,7 @@ import (
55 "encoding/json"
66 "fmt"
77 "io"
8 "io/ioutil"
89 "net/http"
910 "os"
1011 "strconv"
@@ -539,4 +540,82 @@ func FindAnimeByAnilistIDInAnimes(animes []Anime, anilistID int) (*Anime, error)
539540 }
540541 }
541542 return nil, fmt.Errorf("anime with ID %d not found", anilistID)
542}
\ No newline at end of file
543}
544
545// GetAnimeDataByID retrieves detailed anime data from AniList using the anime's ID and user token
546func GetAnimeDataByID(anilistID int, token string) (Anime, error) {
547 query := `
548 query ($id: Int) {
549 Media (id: $id, type: ANIME) {
550 id
551 title {
552 romaji
553 english
554 native
555 }
556 episodes
557 duration
558 status
559 }
560 }
561 `
562
563 variables := map[string]interface{}{
564 "id": anilistID,
565 }
566
567 jsonValue, _ := json.Marshal(map[string]interface{}{
568 "query": query,
569 "variables": variables,
570 })
571
572 req, err := http.NewRequest("POST", "https://graphql.anilist.co", bytes.NewBuffer(jsonValue))
573 if err != nil {
574 return Anime{}, fmt.Errorf("error creating request: %v", err)
575 }
576
577 req.Header.Set("Content-Type", "application/json")
578 req.Header.Set("Authorization", "Bearer "+token)
579
580 client := &http.Client{}
581 resp, err := client.Do(req)
582 if err != nil {
583 return Anime{}, fmt.Errorf("error sending request: %v", err)
584 }
585 defer resp.Body.Close()
586
587 body, err := ioutil.ReadAll(resp.Body)
588 if err != nil {
589 return Anime{}, fmt.Errorf("error reading response: %v", err)
590 }
591
592 var result struct {
593 Data struct {
594 Media struct {
595 ID int `json:"id"`
596 Title AnimeTitle `json:"title"`
597 Episodes int `json:"episodes"`
598 Duration int `json:"duration"`
599 Status string `json:"status"`
600 CoverImage struct {
601 Large string `json:"large"`
602 } `json:"coverImage"`
603 Genres []string `json:"genres"`
604 AverageScore int `json:"averageScore"`
605 } `json:"Media"`
606 } `json:"data"`
607 }
608
609 if err := json.Unmarshal(body, &result); err != nil {
610 return Anime{}, fmt.Errorf("error unmarshaling JSON: %v", err)
611 }
612
613 anime := Anime{
614 AnilistId: result.Data.Media.ID,
615 Title: result.Data.Media.Title,
616 TotalEpisodes: result.Data.Media.Episodes,
617 CoverImage: result.Data.Media.CoverImage.Large,
618 }
619
620 return anime, nil
621}