diff options
-rw-r--r-- | anime/anime.go | 36 | ||||
-rw-r--r-- | anime/general.structs.go | 19 | ||||
-rw-r--r-- | anime/request_handler.go | 49 | ||||
-rw-r--r-- | errhandlers/errhandlers.go (renamed from anime/errhandlers.go) | 11 | ||||
-rw-r--r-- | errhandlers/validators.go (renamed from anime/validators.go) | 10 | ||||
-rw-r--r-- | user/anime/animelist.go | 19 | ||||
-rw-r--r-- | user/anime/request_handler.go (renamed from user/anime/util.go) | 37 | ||||
-rw-r--r-- | util/structs.go | 36 | ||||
-rw-r--r-- | util/url_generator.go (renamed from anime/util.go) | 35 |
9 files changed, 134 insertions, 118 deletions
diff --git a/anime/anime.go b/anime/anime.go index 90231e3..323105b 100644 --- a/anime/anime.go +++ b/anime/anime.go @@ -21,6 +21,8 @@ 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" @@ -30,19 +32,19 @@ func (c AnimeClient) SearchAnime(searchString string, limit, offset int, fields var searchResults AnimeSearch // error handling for limit and offset - limitsErr := limitsErrHandler(limit, offset) + limitsErr := e.LimitsErrHandler(limit, offset) 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 +76,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 +102,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) 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 +159,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) 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.IsValidSort(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 +213,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) 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 77bd22a..5df1357 100644 --- a/anime/general.structs.go +++ b/anime/general.structs.go @@ -16,25 +16,6 @@ package anime -/* 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", -} - // contains previous/next page for anime list type ListPaging struct { NextPage string `json:"next"` 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 3a60f7c..50f4aac 100644 --- a/anime/errhandlers.go +++ b/errhandlers/errhandlers.go @@ -14,23 +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" ) // 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)) } } @@ -40,7 +41,7 @@ func fieldsErrHandler(fields []string) ([]string, error) { } // if limit or error specified are above the limit -func limitsErrHandler(limit, offset int) error { +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)) diff --git a/anime/validators.go b/errhandlers/validators.go index 7f6a7cc..f9baea1 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,7 @@ func isValidSeason(season string) bool { } // Checks if given sort is valid -func isValidSort(sort string) bool { +func IsValidSort(sort string) bool { switch sort { case "anime_score", diff --git a/user/anime/animelist.go b/user/anime/animelist.go index b36b50d..e4cddc3 100644 --- a/user/anime/animelist.go +++ b/user/anime/animelist.go @@ -20,18 +20,31 @@ import ( "encoding/json" "fmt" "github.com/MikunoNaka/mal2go/anime" + e "github.com/MikunoNaka/mal2go/errhandlers" ) const BASE_URL string = "https://api.myanimelist.net/v2" // Get authenticated user's anime list -func (c AnimeListClient) GetAnimeList(user, status, sort string/*, limit, offset int*/) { +func (c AnimeListClient) GetAnimeList(user, status, sort string, limit, offset int, fields []string) (anime.AnimeList, error){ + var userAnimeList anime.AnimeList + // error handling for limit and offset + limitsErr := e.LimitsErrHandler(limit, offset) + if limitsErr != nil { + return userAnimeList, limitsErr + } + + // handle all the errors for the fields + fields, err := e.FieldsErrHandler(fields) + if err != nil { + return userAnimeList, err + } + // get own list if user not specified if user == "" { user = "@me" } - var userAnimeList anime.AnimeList endpoint := BASE_URL + "/users/0ZeroTsu/animelist?fields=list_status&limit=4" // get data from API @@ -54,6 +67,6 @@ func (c AnimeListClient) GetAnimeList(user, status, sort string/*, limit, offset Paging: animeListData.Paging, } - fmt.Println(userAnimeList) + return userAnimeList, nil } diff --git a/user/anime/util.go b/user/anime/request_handler.go index d9a4a4c..f424c29 100644 --- a/user/anime/util.go +++ b/user/anime/request_handler.go @@ -46,40 +46,3 @@ func (c AnimeListClient) requestHandler(endpoint, method string) string { return string(body) } - -// 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.") -// } -// -// var fields string -// -// for index, name := range(names) { -// var data string -// /* if the data is the first field in URL, -// * it goes like ?key=value -// * else it is &nextkey=value */ -// if isPrimary { -// data = "?" + name + "=" -// } else { -// data = "&" + name + "=" -// } -// -// // add values to data variable -// for i, j := range values[index] { -// if i > 0 { -// data = data + "," + j -// } else { -// data = data + j -// } -// } -// -// fields = fields + data -// -// // from now on all other fields will be secondary -// isPrimary = false -// } -// -// return baseUrl + fields, nil -// } 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 |