2023-10-19 14:12:56 +00:00
|
|
|
package endpoints
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
2023-10-24 13:10:39 +00:00
|
|
|
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
|
|
|
|
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
|
2023-10-19 14:12:56 +00:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
|
|
|
// GetFavorites retrieves a user's favorite posts from the e621 API.
|
|
|
|
//
|
|
|
|
// The user_id parameter is required to get the favorites of a user.
|
|
|
|
//
|
|
|
|
// Parameters:
|
|
|
|
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
|
|
|
|
// - query: A map containing additional query parameters for the API request.
|
|
|
|
//
|
|
|
|
// Returns:
|
|
|
|
// - []model.Post: A slice of favorite posts.
|
|
|
|
// - error: An error, if any, encountered during the API request or response handling.
|
2023-10-23 14:01:42 +00:00
|
|
|
func GetFavorites(requestContext model.RequestContext, query map[string]string) ([]model.Post, error) {
|
2023-10-19 14:12:56 +00:00
|
|
|
// Create a new HTTP GET request.
|
|
|
|
r, err := http.NewRequest("GET", fmt.Sprintf("%s/favorites.json", requestContext.Host), nil)
|
|
|
|
if err != nil {
|
2023-11-06 14:31:46 +00:00
|
|
|
return nil, err
|
2023-10-19 14:12:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Append query parameters to the request URL.
|
|
|
|
q := r.URL.Query()
|
|
|
|
for k, v := range query {
|
|
|
|
q.Add(k, v)
|
|
|
|
}
|
|
|
|
r.URL.RawQuery = q.Encode()
|
|
|
|
|
|
|
|
r.Header.Set("User-Agent", requestContext.UserAgent)
|
|
|
|
r.Header.Add("Accept", "application/json")
|
|
|
|
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
|
|
|
|
|
2023-10-23 06:56:14 +00:00
|
|
|
// Send the request using the provided http.Client.
|
2023-10-23 14:01:42 +00:00
|
|
|
resp, err := requestContext.Client.Do(r)
|
2023-10-19 14:12:56 +00:00
|
|
|
if err != nil {
|
2023-11-06 14:31:46 +00:00
|
|
|
return nil, err
|
2023-10-19 14:12:56 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Check if the HTTP response status code indicates success (2xx range).
|
|
|
|
if resp.StatusCode < 200 || resp.StatusCode > 300 {
|
|
|
|
// If the status code is outside the 2xx range, return an error based on the status code.
|
|
|
|
return nil, utils.StatusCodesToError(resp.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Initialize a User struct to store the response data.
|
|
|
|
var favoriteResponse model.PostResponse
|
|
|
|
|
|
|
|
// Decode the JSON response into the user struct.
|
|
|
|
err = json.NewDecoder(resp.Body).Decode(&favoriteResponse)
|
|
|
|
if err != nil {
|
|
|
|
// Log the error and return an empty User struct and the error.
|
2023-10-24 08:35:33 +00:00
|
|
|
|
2023-10-19 14:12:56 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return favoriteResponse.Posts, nil
|
|
|
|
}
|