diff options
author | Vidhu Kant Sharma <bokuwakanojogahoshii@yahoo.com> | 2022-02-13 11:27:12 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-02-13 11:27:12 +0000 |
commit | 541c75949e862f6fd1081bc4081b08187fa7da7b (patch) | |
tree | c32a78c0c6f16416f42975cac86fbfc23d1b1735 | |
parent | 0eb32bb339f66d3416c1088d6372bc7219b6e323 (diff) | |
parent | 419e08bc3a369a0c1138871184e1a30320032afd (diff) |
Merge pull request #3 from MikunoNaka/user-animelist
User animelist functions complete
-rw-r--r-- | anime/anime.go | 39 | ||||
-rw-r--r-- | anime/general.structs.go | 5 | ||||
-rw-r--r-- | anime/request_handler.go | 49 | ||||
-rw-r--r-- | errhandlers/errhandlers.go (renamed from anime/errhandlers.go) | 36 | ||||
-rw-r--r-- | errhandlers/validators.go (renamed from anime/validators.go) | 38 | ||||
-rw-r--r-- | user/anime/animelist.go | 108 | ||||
-rw-r--r-- | user/anime/animelist.structs.go | 42 | ||||
-rw-r--r-- | user/anime/client.go | 27 | ||||
-rw-r--r-- | user/anime/request_handler.go | 80 | ||||
-rw-r--r-- | util/structs.go | 36 | ||||
-rw-r--r-- | util/url_generator.go (renamed from anime/util.go) | 35 |
11 files changed, 414 insertions, 81 deletions
diff --git a/anime/anime.go b/anime/anime.go index 90231e3..969b04c 100644 --- a/anime/anime.go +++ b/anime/anime.go @@ -21,28 +21,33 @@ import ( "errors" "fmt" "strconv" + e "github.com/MikunoNaka/mal2go/errhandlers" + u "github.com/MikunoNaka/mal2go/util" ) const BASE_URL string = "https://api.myanimelist.net/v2/anime" +// MAL Might change this +const maxAnimeLimit int = 500 + // in MAL documentation this is named Get Anime List func (c AnimeClient) SearchAnime(searchString string, limit, offset int, fields []string) (AnimeSearch, error) { var searchResults AnimeSearch // error handling for limit and offset - limitsErr := limitsErrHandler(limit, offset) + limitsErr := e.LimitsErrHandler(limit, offset, maxAnimeLimit) if limitsErr != nil { return searchResults, limitsErr } // handle all the errors for the fields - fields, err := fieldsErrHandler(fields) + fields, err := e.FieldsErrHandler(fields) if err != nil { return searchResults, err } // generate endpoint url with custom params - endpoint, _ := urlGenerator( + endpoint, _ := u.UrlGenerator( BASE_URL, []string{"q", "limit", "offset", "fields"}, [][]string{{searchString}, {strconv.Itoa(limit)}, {strconv.Itoa(offset)}, fields}, @@ -74,12 +79,12 @@ func (c AnimeClient) GetAnimeById(animeId int, fields []string) (Anime, error) { var anime Anime // handle all the errors for the fields - fields, err := fieldsErrHandler(fields) + fields, err := e.FieldsErrHandler(fields) if err != nil { return anime, err } - endpoint, _ := urlGenerator( + endpoint, _ := u.UrlGenerator( BASE_URL + "/" + strconv.Itoa(animeId), []string{"fields"}, /* it seems to still return all fields from the API. @@ -100,23 +105,23 @@ func (c AnimeClient) GetAnimeRanking(rankingType string, limit, offset int, fiel var animeRanking AnimeRanking // error handling for limit and offset - limitsErr := limitsErrHandler(limit, offset) + limitsErr := e.LimitsErrHandler(limit, offset, maxAnimeLimit) if limitsErr != nil { return animeRanking, limitsErr } // handle all the errors for the fields - fields, err := fieldsErrHandler(fields) + fields, err := e.FieldsErrHandler(fields) if err != nil { return animeRanking, err } // if ranking type is invalid - if !isValidRankingType(rankingType) { + if !e.IsValidRankingType(rankingType) { return animeRanking, errors.New(fmt.Sprintf("GetAnimeRanking: Invalid ranking type specified: \"%s\"", rankingType)) } - endpoint, _ := urlGenerator( + endpoint, _ := u.UrlGenerator( BASE_URL + "/ranking", []string{"ranking_type", "limit", "offset", "fields"}, [][]string{{rankingType}, {strconv.Itoa(limit)}, {strconv.Itoa(offset)}, fields}, @@ -157,28 +162,28 @@ func (c AnimeClient) GetSeasonalAnime(year, season, sort string, limit, offset i var seasonalAnime SeasonalAnime // error handling for limit and offset - limitsErr := limitsErrHandler(limit, offset) + limitsErr := e.LimitsErrHandler(limit, offset, maxAnimeLimit) if limitsErr != nil { return seasonalAnime, limitsErr } // handle all the errors for the fields - fields, err := fieldsErrHandler(fields) + fields, err := e.FieldsErrHandler(fields) if err != nil { return seasonalAnime, err } // checks if valid season is specified - if !isValidSeason(season) { + if !e.IsValidSeason(season) { return seasonalAnime, errors.New(fmt.Sprintf("GetSeasonalAnime: Invalid season specified: \"%s\"", season)) } // checks if valid sort is specified - if !isValidSort(sort) { + if !e.IsValidSeasonalSort(sort) { return seasonalAnime, errors.New(fmt.Sprintf("GetSeasonalAnime: Invalid sort specified: \"%s\"", sort)) } - endpoint, _ := urlGenerator( + endpoint, _ := u.UrlGenerator( BASE_URL + fmt.Sprintf("/season/%s/%s", year, season), []string{"sort", "limit", "offset", "fields"}, [][]string{{sort}, {strconv.Itoa(limit)}, {strconv.Itoa(offset)}, fields}, @@ -211,18 +216,18 @@ func (c AnimeClient) GetSuggestedAnime(limit, offset int, fields []string) (Sugg var suggestedAnime SuggestedAnime // error handling for limit and offset - limitsErr := limitsErrHandler(limit, offset) + limitsErr := e.LimitsErrHandler(limit, offset, maxAnimeLimit) if limitsErr != nil { return suggestedAnime, limitsErr } // handle all the errors for the fields - fields, err := fieldsErrHandler(fields) + fields, err := e.FieldsErrHandler(fields) if err != nil { return suggestedAnime, err } - endpoint, _ := urlGenerator( + endpoint, _ := u.UrlGenerator( BASE_URL + "/suggestions", []string{"limit", "offset", "fields"}, [][]string{{strconv.Itoa(limit)}, {strconv.Itoa(offset)}, fields}, diff --git a/anime/general.structs.go b/anime/general.structs.go index c49b762..5df1357 100644 --- a/anime/general.structs.go +++ b/anime/general.structs.go @@ -26,3 +26,8 @@ type Season struct { Year int `json:"year"` Name string `json:"season"` } + +type AnimeList struct { + Animes []Anime + Paging ListPaging +} diff --git a/anime/request_handler.go b/anime/request_handler.go new file mode 100644 index 0000000..809ca07 --- /dev/null +++ b/anime/request_handler.go @@ -0,0 +1,49 @@ +/* mal2go - MyAnimeList V2 API wrapper for Go + * Copyright (C) 2022 Vidhu Kant Sharma <vidhukant@protonmail.ch> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. */ + +package anime + +import ( + "io/ioutil" + "log" + "net/http" +) + +// Handles HTTP request with your OAuth token as a Header +// TODO: Verify that this function is safe to use +func (c AnimeClient) requestHandler(endpoint string) string { + // generate request + req, err := http.NewRequest("GET", endpoint, nil) + if err != nil { + log.Fatal(err) + } + req.Header.Add("Authorization", c.AuthToken) + + // do request + res, err := c.HttpClient.Do(req) + if err != nil { + log.Fatal(err) + } + defer res.Body.Close() + + // read body + body, err := ioutil.ReadAll(res.Body) + if err != nil { + log.Fatal(err) + } + + return string(body) +} diff --git a/anime/errhandlers.go b/errhandlers/errhandlers.go index d7f70f9..a9f8054 100644 --- a/anime/errhandlers.go +++ b/errhandlers/errhandlers.go @@ -14,42 +14,24 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ -package anime +package errhandlers import ( "errors" "fmt" + "github.com/MikunoNaka/mal2go/util" ) -/* NOTE: MAL still seems to send some fields - * even if they aren't requested. - * those include Title, Picture, Id, etc */ -// default fields to use when none are specified -var defaultFields []string = []string{ - "id", "title", "main_picture", - "alternative_titles", "start_date", - "end_date", "synopsis", "mean", "rank", - "popularity", "num_list_users", - "num_scoring_users", "nsfw", "created_at", - "updated_at", "media_type", "status", - "genres", "my_list_status", "num_episodes", - "start_season", "broadcast", "source", - "average_episode_duration", "rating", - "pictures", "background", "related_anime", - "related_manga", "recommendations", - "studios", "statistics", -} - // if fields aren't specified -func fieldsErrHandler(fields []string) ([]string, error) { +func FieldsErrHandler(fields []string) ([]string, error) { if cap(fields) == 0 { // uses all the default fields if none specified - return defaultFields, nil + return util.DefaultFields, nil } // checks if each given field is valid for _, j := range(fields) { - if !isValidField(j) { + if !IsValidField(j) { return []string{}, errors.New(fmt.Sprintf("InvalidFieldError: Invalid field specified: \"%s\"", j)) } } @@ -59,10 +41,10 @@ func fieldsErrHandler(fields []string) ([]string, error) { } // if limit or error specified are above the limit -func limitsErrHandler(limit, offset int) error { - maxOffset := 500 - limit - if limit > 500 { - return errors.New(fmt.Sprintf("InvalidLimitError: Limit specified too high (%d > 500).", limit)) +func LimitsErrHandler(limit, offset, maxLimit int) error { + maxOffset := maxLimit - limit + if limit > maxLimit { + return errors.New(fmt.Sprintf("InvalidLimitError: Limit specified too high (%d > %d).", limit, maxLimit)) } else if offset > maxOffset { return errors.New(fmt.Sprintf("InvalidOffsetError: Offset specified too high (%d > %d).", offset, maxOffset)) } diff --git a/anime/validators.go b/errhandlers/validators.go index 7f6a7cc..6bf7a3f 100644 --- a/anime/validators.go +++ b/errhandlers/validators.go @@ -14,10 +14,10 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ -package anime +package errhandlers // Checks if given rankingType is valid -func isValidRankingType(rankingType string) bool { +func IsValidRankingType(rankingType string) bool { switch rankingType { case "all", @@ -34,7 +34,7 @@ func isValidRankingType(rankingType string) bool { } // Checks if given rankingType is valid -func isValidField(field string) bool { +func IsValidField(field string) bool { switch field { case "id", @@ -74,7 +74,7 @@ func isValidField(field string) bool { } // Checks if given season is valid -func isValidSeason(season string) bool { +func IsValidSeason(season string) bool { switch season { case "winter", @@ -86,7 +86,8 @@ func isValidSeason(season string) bool { } // Checks if given sort is valid -func isValidSort(sort string) bool { +// For seasonal anime lists +func IsValidSeasonalSort(sort string) bool { switch sort { case "anime_score", @@ -94,3 +95,30 @@ func isValidSort(sort string) bool { } return false } + +// Checks if given sort is valid +// for user anime lists +func IsValidListSort(sort string) bool { + switch sort { + case + "list_score", + "list_updated_at", + "anime_title", + "anime_start_date", + "anime_id": return true + } + return false +} + +// Checks if given anime list status is valid +func IsValidListStatus(status string) bool { + switch status { + case + "watching", + "completed", + "on_hold", + "dropped", + "plan_to_watch": return true + } + return false +} diff --git a/user/anime/animelist.go b/user/anime/animelist.go new file mode 100644 index 0000000..4f5eac5 --- /dev/null +++ b/user/anime/animelist.go @@ -0,0 +1,108 @@ +/* mal2go - MyAnimeList V2 API wrapper for Go + * Copyright (C) 2022 Vidhu Kant Sharma <vidhukant@protonmail.ch> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. */ + +package anime + +import ( + "encoding/json" + "strconv" + "fmt" + "errors" + a "github.com/MikunoNaka/mal2go/anime" + e "github.com/MikunoNaka/mal2go/errhandlers" +) + +const BASE_URL string = "https://api.myanimelist.net/v2" +const maxListLimit int = 1000 + +// Delete an anime from user's anime list +func (c AnimeListClient)DeleteAnime(id int) string { + endpoint := fmt.Sprintf("%s/anime/%d/my_list_status", BASE_URL, id) + /* Returns 200 if anime successfully deleted + * Alternatively returns 404 if anime not in user's anime list */ + return c.requestHandler(endpoint, "DELETE") +} + +// Update/Add an anime to user's anime list +func (c AnimeListClient)UpdateAnime(id int, data UpdateAnimeData) string { + endpoint := fmt.Sprintf("%s/anime/%d/my_list_status", BASE_URL, id) + + // turn data struct into json + pepe, err := json.Marshal(data) + if err != nil { + fmt.Println(err) + } + + // finally make API request + res := c.putRequestHandler(endpoint, pepe) + return res +} + +// Get authenticated user's anime list +func (c AnimeListClient) GetAnimeList(user, status, sort string, limit, offset int) (a.AnimeList, error){ + var userAnimeList a.AnimeList + // error handling for limit and offset + limitsErr := e.LimitsErrHandler(limit, offset, maxListLimit) + if limitsErr != nil { + return userAnimeList, limitsErr + } + + // checks if valid sort is specified + if !e.IsValidListSort(sort) { + return userAnimeList, errors.New(fmt.Sprintf("GetAnimeList: Invalid sort specified: \"%s\"", sort)) + } + + // checks if valid status is specified + if status != "" && !e.IsValidListStatus(status) { + return userAnimeList, errors.New(fmt.Sprintf("GetAnimeList: Invalid status specified: \"%s\"", status)) + } + + // get own list if user not specified + if user == "" { + user = "@me" + } + + // if status is "" it returns all anime + var endpoint string + if status == "" { + endpoint = BASE_URL + "/users/" + user + "/animelist?sort=" + sort + "&limit=" + strconv.Itoa(limit) + "&offset=" + strconv.Itoa(offset) + } else { + endpoint = BASE_URL + "/users/" + user + "/animelist?status=" + status + "&sort=" + sort + "&limit=" + strconv.Itoa(limit) + "&offset=" + strconv.Itoa(offset) + } + + // get data from API + var animeListData AnimeListRaw + data := c.requestHandler(endpoint, "GET") + json.Unmarshal([]byte(data), &animeListData) + + // set MyListStatus for each element and add it to array + var animes []a.Anime + for _, element := range animeListData.Data { + a := element.Anime + a.MyListStatus = element.ListStatus + + animes = append(animes, a) + } + + // finally create AnimeList + userAnimeList = a.AnimeList { + Animes: animes, + Paging: animeListData.Paging, + } + + return userAnimeList, nil +} + diff --git a/user/anime/animelist.structs.go b/user/anime/animelist.structs.go new file mode 100644 index 0000000..d874f7b --- /dev/null +++ b/user/anime/animelist.structs.go @@ -0,0 +1,42 @@ +/* mal2go - MyAnimeList V2 API wrapper for Go + * Copyright (C) 2022 Vidhu Kant Sharma <vidhukant@protonmail.ch> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. */ + +package anime + +import ( + "github.com/MikunoNaka/mal2go/anime" +) + +type AnimeListRaw struct { + Data []struct { + Anime anime.Anime `json:"node"` + ListStatus anime.ListStatus `json:"list_status"` + } `json:"data"` + Paging anime.ListPaging `json:"paging"` +} + +type UpdateAnimeData struct { + Status string `json:"status"` + IsRewatching bool `json:"is_rewatching"` + Score int `json:"score"` + EpWatched int `json:"num_watched_episodes"` + Priority int `json:"priority"` + TimesRewatched int `json:"num_times_rewatched"` + // NOTE: idk what RewatchValue is + RewatchValue int `json:"rewatch_value"` + Tags string `json:"tags"` + Comments string `json:"comments"` +} diff --git a/user/anime/client.go b/user/anime/client.go new file mode 100644 index 0000000..e9a99d3 --- /dev/null +++ b/user/anime/client.go @@ -0,0 +1,27 @@ +/* mal2go - MyAnimeList V2 API wrapper for Go + * Copyright (C) 2022 Vidhu Kant Sharma <vidhukant@protonmail.ch> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. */ + +package anime + +import ( + "net/http" +) + +// MyAnimeList Client for mal2go/anime package +type AnimeListClient struct { + AuthToken, RefreshToken string + HttpClient http.Client +} diff --git a/user/anime/request_handler.go b/user/anime/request_handler.go new file mode 100644 index 0000000..22c6e0b --- /dev/null +++ b/user/anime/request_handler.go @@ -0,0 +1,80 @@ +/* mal2go - MyAnimeList V2 API wrapper for Go + * Copyright (C) 2022 Vidhu Kant Sharma <vidhukant@protonmail.ch> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. */ + +package anime + +import ( + "io/ioutil" + "log" + "net/http" + "strconv" + "bytes" +) + +// Handles HTTP request with your OAuth token as a Header +func (c AnimeListClient) requestHandler(endpoint, method string) string { + // generate request + req, err := http.NewRequest(method, endpoint, nil) + if err != nil { + log.Fatal(err) + } + req.Header.Add("Authorization", c.AuthToken) + + // do request + res, err := c.HttpClient.Do(req) + if err != nil { + log.Fatal(err) + } + defer res.Body.Close() + + // read body + body, err := ioutil.ReadAll(res.Body) + if err != nil { + log.Fatal(err) + } + + // for DeleteAnime, its endpoint returns null data + if method == "DELETE" { + return strconv.Itoa(res.StatusCode) + } + + return string(body) +} + +// for PUT requests (used by UpdateAnime) +func (c AnimeListClient) putRequestHandler(endpoint string, data []uint8) string { + // generate request + req, err := http.NewRequest(http.MethodPut, endpoint, bytes.NewBuffer(data)) + if err != nil { + log.Fatal(err) + } + req.Header.Add("Authorization", c.AuthToken) + + // do request + res, err := c.HttpClient.Do(req) + if err != nil { + log.Fatal(err) + } + defer res.Body.Close() + + // read body + body, err := ioutil.ReadAll(res.Body) + if err != nil { + log.Fatal(err) + } + + return string(body) +} diff --git a/util/structs.go b/util/structs.go new file mode 100644 index 0000000..d242e7f --- /dev/null +++ b/util/structs.go @@ -0,0 +1,36 @@ +/* mal2go - MyAnimeList V2 API wrapper for Go + * Copyright (C) 2022 Vidhu Kant Sharma <vidhukant@protonmail.ch> + + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with this program. If not, see <https://www.gnu.org/licenses/>. */ + +package util + +/* NOTE: MAL still seems to send some fields + * even if they aren't requested. + * those include Title, Picture, Id, etc */ +// default fields to use when none are specified +var DefaultFields []string = []string{ + "id", "title", "main_picture", + "alternative_titles", "start_date", + "end_date", "synopsis", "mean", "rank", + "popularity", "num_list_users", + "num_scoring_users", "nsfw", "created_at", + "updated_at", "media_type", "status", + "genres", "my_list_status", "num_episodes", + "start_season", "broadcast", "source", + "average_episode_duration", "rating", + "pictures", "background", "related_anime", + "related_manga", "recommendations", + "studios", "statistics", +} diff --git a/anime/util.go b/util/url_generator.go index 862b54d..3d21a98 100644 --- a/anime/util.go +++ b/util/url_generator.go @@ -14,45 +14,16 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ -package anime +package util import ( - "io/ioutil" - "log" - "net/http" "errors" ) -// Handles HTTP request with your OAuth token as a Header -// TODO: Verify that this function is safe to use -func (c AnimeClient) requestHandler(endpoint string) string { - // generate request - req, err := http.NewRequest("GET", endpoint, nil) - if err != nil { - log.Fatal(err) - } - req.Header.Add("Authorization", c.AuthToken) - - // do request - res, err := c.HttpClient.Do(req) - if err != nil { - log.Fatal(err) - } - defer res.Body.Close() - - // read body - body, err := ioutil.ReadAll(res.Body) - if err != nil { - log.Fatal(err) - } - - return string(body) -} - -func urlGenerator(baseUrl string, names []string, values [][]string, isPrimary bool) (string, error) { +func UrlGenerator(baseUrl string, names []string, values [][]string, isPrimary bool) (string, error) { // length of names and values should be same if cap(names) != cap(values) { - return "", errors.New("urlGenerator: Error: Length of names and values don't match.") + return "", errors.New("util.UrlGenerator: Error: Length of names and values don't match.") } var fields string |