go-mastodon/lists.go
2022-11-20 21:53:02 +01:00

99 lines
2.3 KiB
Go

package mastodon
import (
"fmt"
"net/http"
"net/url"
)
type List struct {
ID ID `json:"id"`
Title string `json:"title"`
}
func (l *List) GetID() string {
if l != nil {
return string(l.ID)
} else {
return ""
}
}
func GetLists() ([]*List, error) {
var lists []*List
err := doAPI(http.MethodGet, "/api/v1/lists", nil, &lists, nil)
if err != nil {
return nil, err
}
return lists, nil
}
func (a *Account) GetContainingLists() ([]*List, error) {
var lists []*List
err := doAPI(http.MethodGet, fmt.Sprintf("/api/v1/accounts/%s/lists", url.PathEscape(a.GetID())), nil, &lists, nil)
if err != nil {
return nil, err
}
return lists, nil
}
func (l *List) GetAccounts() ([]*Account, error) {
var accounts []*Account
err := doAPI(http.MethodGet, fmt.Sprintf("/api/v1/lists/%s/accounts", url.PathEscape(l.GetID())), url.Values{"limit": {"0"}}, &accounts, nil)
if err != nil {
return nil, err
}
return accounts, nil
}
func GetList(id ID) (*List, error) {
var list List
err := doAPI(http.MethodGet, fmt.Sprintf("/api/v1/lists/%s", url.PathEscape(string(id))), nil, &list, nil)
if err != nil {
return nil, err
}
return &list, nil
}
func CreateList(title string) (*List, error) {
params := url.Values{}
params.Set("title", title)
var list List
err := doAPI(http.MethodPost, "/api/v1/lists", params, &list, nil)
if err != nil {
return nil, err
}
return &list, nil
}
func (l *List) Rename(newTitle string) error {
params := url.Values{}
params.Set("title", newTitle)
return doAPI(http.MethodPut, fmt.Sprintf("/api/v1/lists/%s", url.PathEscape(l.GetID())), params, nil, nil)
}
func (l *List) Delete() error {
return doAPI(http.MethodDelete, fmt.Sprintf("/api/v1/lists/%s", url.PathEscape(l.GetID())), nil, nil, nil)
}
// Only accounts already followed by the user can be added to a list.
func (l *List) Add(accounts ...*Account) error {
params := url.Values{}
for _, a := range accounts {
params.Add("account_ids", string(a.GetID()))
}
return doAPI(http.MethodPost, fmt.Sprintf("/api/v1/lists/%s/accounts", url.PathEscape(l.GetID())), params, nil, nil)
}
func (l *List) Remove(accounts ...*Account) error {
params := url.Values{}
for _, a := range accounts {
params.Add("account_ids", a.GetID())
}
return doAPI(http.MethodDelete, fmt.Sprintf("/api/v1/lists/%s/accounts", url.PathEscape(l.GetID())), params, nil, nil)
}