Added DMail support #5

Merged
fenpaws merged 11 commits from develop/dm into main 2024-07-11 11:58:03 +00:00
79 changed files with 20651 additions and 20210 deletions

2
.gitignore vendored
View File

@ -190,3 +190,5 @@ $RECYCLE.BIN/
# End of https://www.toptal.com/developers/gitignore/api/windows,linux,goland+all,macos,go # End of https://www.toptal.com/developers/gitignore/api/windows,linux,goland+all,macos,go
/.scannerwork/ /.scannerwork/
*.env

View File

@ -48,6 +48,7 @@ _Mid Level API_
| Users | :heavy_check_mark: | | | Users | :heavy_check_mark: | |
| Favorites | :heavy_check_mark: | | | Favorites | :heavy_check_mark: | |
| DB export | :x: | | DB export | :x: |
| DMails | :heavy_minus_sign: | |
_Low Level API_ _Low Level API_
@ -63,3 +64,4 @@ _Low Level API_
| Users | :heavy_check_mark: | | | Users | :heavy_check_mark: | |
| Favorites | :heavy_check_mark: | | | Favorites | :heavy_check_mark: | |
| DB export | :x: | | | DB export | :x: | |
| DMails | :heavy_check_mark: | |

65
example/lowlevel/dmail.go Normal file
View File

@ -0,0 +1,65 @@
package main
import (
"log"
"net/http"
"os"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
)
func main() {
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"),
APIKey: os.Getenv("API_KEY"),
}
log.Println("Getting a DMail by ID:")
dmail, err := endpoints.GetDmail(requestContext, 1)
if err != nil {
log.Println(err)
} else {
log.Println(dmail.Body)
}
log.Println("----------")
log.Println("Deleting a DMail by ID:")
err = endpoints.DeleteDmail(requestContext, 1)
if err != nil {
log.Println(err)
}
log.Println("----------")
log.Println("Marking a DMail as read by ID:")
err = endpoints.MarkAsReadDmail(requestContext, 1)
if err != nil {
log.Println(err)
}
log.Println("----------")
log.Println("Getting all DMails:")
query := map[string]string{
"limit": "5",
}
dmails, err := endpoints.GetAllDmails(requestContext, query)
if err != nil {
log.Println(err)
} else {
for _, dmail := range dmails {
log.Println(dmail.Body)
}
}
log.Println("----------")
log.Println("Marking all DMails as read:")
err = endpoints.MarkAsReadAllDmails(requestContext)
if err != nil {
log.Println(err)
}
log.Println("----------")
}

43
example/midlevel/dmail.go Normal file
View File

@ -0,0 +1,43 @@
package main
import (
"log"
"net/http"
"os"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
)
func main() {
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"),
APIKey: os.Getenv("API_KEY"),
}
log.Println("Getting DMails API user: ")
getDMails := builder.NewGetDMailsBuilder(requestContext)
dMails, err := getDMails.SetLimit(5).Execute()
if err != nil {
log.Println(err)
} else {
log.Println(dMails[0].Title)
}
log.Println("----------")
log.Println("Getting DMails for user: ")
dMails, err = getDMails.SetLimit(5).ByToName("specificUser").Execute()
if err != nil {
log.Println(err)
} else {
log.Println(dMails[0].Title)
}
log.Println("----------")
}

79
pkg/e621/builder/dmail.go Normal file
View File

@ -0,0 +1,79 @@
package builder
import (
"context"
"strconv"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
)
type DMailsBuilder interface {
ByTitle(title string) DMailsBuilder
ByBody(body string) DMailsBuilder
ByToName(toName string) DMailsBuilder
ByFromName(fromName string) DMailsBuilder
SetLimit(limit int) DMailsBuilder
PageNumber(number int) DMailsBuilder
Execute() ([]model.DMail, error)
}
type getDMails struct {
requestContext model.RequestContext
query map[string]string
id int
}
func NewGetDMailsBuilder(requestContext model.RequestContext) DMailsBuilder {
dMailsBuilder := &getDMails{
requestContext: requestContext,
query: make(map[string]string),
}
return dMailsBuilder.SetLimit(utils.E621_MAX_POST_COUNT)
}
func (g getDMails) ByTitle(title string) DMailsBuilder {
g.query["search[title_matches]"] = title
return g
}
func (g getDMails) ByBody(body string) DMailsBuilder {
g.query["search[message_matches]"] = body
return g
}
func (g getDMails) ByToName(toName string) DMailsBuilder {
g.query["search[to_name]"] = toName
return g
}
func (g getDMails) ByFromName(fromName string) DMailsBuilder {
g.query["search[from_name]"] = fromName
return g
}
func (g getDMails) SetLimit(limit int) DMailsBuilder {
g.query["limit"] = strconv.Itoa(limit)
return g
}
func (g getDMails) PageNumber(number int) DMailsBuilder {
g.query["page"] = strconv.Itoa(number)
return g
}
func (g getDMails) Execute() ([]model.DMail, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
favorites, err := endpoints.GetAllDmails(g.requestContext, g.query)
if err != nil {
return nil, err
}
return favorites, nil
}

234
pkg/e621/endpoints/dmail.go Normal file
View File

@ -0,0 +1,234 @@
package endpoints
import (
"encoding/json"
"fmt"
"net/http"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
)
// GetDmail retrieves a specific DMail by its ID.
//
// This function performs an HTTP GET request to the e621 DMail endpoint and parses
// the JSON content to extract the DMail data.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
// - ID: The ID of the DMail to be fetched.
//
// Returns:
// - model.DMail: A struct containing the DMail data.
// - error: An error, if any, encountered during the API request or response handling.
func GetDmail(requestContext model.RequestContext, ID int) (model.DMail, error) {
// Create a new HTTP GET request to fetch the post information.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/dmails/%d.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Post struct and the error.
return model.DMail{}, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Post struct and the error.
return model.DMail{}, err
}
// 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 model.DMail{}, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a Post struct to store the response data.
var postResponse model.DMail
// Decode the JSON response into the PostResponse struct.
err = json.NewDecoder(resp.Body).Decode(&postResponse)
if err != nil {
// Log the error and return an empty Post struct and the error.
return model.DMail{}, err
}
// Return the post information and no error (nil).
return postResponse, nil
}
// DeleteDmail deletes a specific DMail by its ID.
//
// This function performs an HTTP DELETE request to the e621 DMail endpoint.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
// - ID: The ID of the DMail to be deleted.
//
// Returns:
// - error: An error, if any, encountered during the API request or response handling.
func DeleteDmail(requestContext model.RequestContext, ID int) error {
// Create a new HTTP GET request to fetch the post information.
r, err := http.NewRequest("DELETE", fmt.Sprintf("%s/dmails/%d.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
// 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 utils.StatusCodesToError(resp.StatusCode)
}
// Return the post information and no error (nil).
return nil
}
// MarkAsReadDmail marks a specific DMail as read by its ID.
//
// This function performs an HTTP PUT request to the e621 DMail endpoint.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
// - ID: The ID of the DMail to be marked as read.
//
// Returns:
// - error: An error, if any, encountered during the API request or response handling.
func MarkAsReadDmail(requestContext model.RequestContext, ID int) error {
// Create a new HTTP GET request to fetch the post information.
r, err := http.NewRequest("PUT", fmt.Sprintf("%s/dmails/%d/mark_as_read.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
// 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 utils.StatusCodesToError(resp.StatusCode)
}
// Return the post information and no error (nil).
return nil
}
// GetAllDmails retrieves all DMails.
//
// This function performs an HTTP GET request to the e621 DMail endpoint and parses
// the JSON content to extract the DMail data.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
// - query: A map containing the query parameters for the request.
//
// Returns:
// - []model.DMail: A slice of structs containing the DMail data.
// - error: An error, if any, encountered during the API request or response handling.
func GetAllDmails(requestContext model.RequestContext, query map[string]string) ([]model.DMail, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/dmails.json", requestContext.Host), nil)
if err != nil {
return nil, err
}
// 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)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// 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 slice of Post struct to store the response data.
var postResponse []model.DMail
// Decode the JSON response into the PostResponse struct.
err = json.NewDecoder(resp.Body).Decode(&postResponse)
if err != nil {
// Log the error and return an empty slice and the error.
return []model.DMail{}, nil
}
// Return the list of posts and no error (nil).
return postResponse, nil
}
// MarkAsReadAllDmails marks all DMails as read.
//
// This function performs an HTTP PUT request to the e621 DMail endpoint.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
//
// Returns:
// - error: An error, if any, encountered during the API request or response handling.
func MarkAsReadAllDmails(requestContext model.RequestContext) error {
// Create a new HTTP GET request to fetch the post information.
r, err := http.NewRequest("PUT", fmt.Sprintf("%s/dmails/mark_all_as_read.json", requestContext.Host), nil)
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
// 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 utils.StatusCodesToError(resp.StatusCode)
}
// Return the post information and no error (nil).
return nil
}

16
pkg/e621/model/dmail.go Normal file
View File

@ -0,0 +1,16 @@
package model
import "time"
type DMail struct {
Body string `json:"body"`
CreatedAt time.Time `json:"created_at"`
FromId int `json:"from_id"`
Id int `json:"id"`
IsDeleted bool `json:"is_deleted"`
IsRead bool `json:"is_read"`
OwnerId int `json:"owner_id"`
Title string `json:"title"`
ToId int `json:"to_id"`
UpdatedAt time.Time `json:"updated_at"`
}