This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
e621-sdk-go/e621/favorite.go

61 lines
1.4 KiB
Go
Raw Normal View History

2023-05-24 14:05:27 +00:00
package e621
2023-05-22 11:08:08 +00:00
import (
2023-05-24 14:05:27 +00:00
"e621_to_neo4j/e621/models"
2023-05-22 11:08:08 +00:00
"fmt"
"io"
"log"
"net/http"
"time"
)
// GetFavorites retrieves all favorites from the e621 API.
func (c *Client) GetFavorites(user models.E621User) ([]models.Post, error) {
time.Sleep(1 * time.Second)
2023-05-22 11:08:08 +00:00
var lastPostID int64
var allFavorites []models.Post
var url string
2023-05-22 11:08:08 +00:00
for {
url = fmt.Sprintf("%s/favorites.json?user_id=%d&page=%d", baseURL, user.ID, lastPostID)
2023-05-22 11:08:08 +00:00
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "e621 to GraphDB (by Selloo)")
2023-05-22 11:08:08 +00:00
req.Header.Add("Accept", "application/json")
req.SetBasicAuth(c.username, c.apiKey)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to retrieve posts: %s", resp.Status)
}
fetchedFavorites, err := models.UnmarshalE621Post(body)
if err != nil {
log.Printf(err.Error())
}
// Append the fetched posts to the result slice
allFavorites = append(allFavorites, fetchedFavorites.Posts...)
// If no more posts are returned, return the accumulated favorites
if len(fetchedFavorites.Posts) == 0 {
return allFavorites, nil
}
// Update the last post ID for the next page request
lastPostID = lastPostID + 1
2023-05-22 11:08:08 +00:00
}
}