package mastodon import ( "errors" "fmt" "net/http" "net/url" "time" ) type Filter struct { ID ID `json:"id"` Phrase string `json:"phrase"` Context []string `json:"context"` WholeWord bool `json:"whole_word"` ExpiresAt time.Time `json:"expires_at"` Irreversible bool `json:"irreversible"` } func (f *Filter) GetID() string { if f != nil { return string(f.ID) } else { return "" } } func GetFilters() ([]*Filter, error) { var filters []*Filter err := doAPI(http.MethodGet, "/api/v1/filters", nil, &filters, nil) if err != nil { return nil, err } return filters, nil } func GetFilter(filterId ID) (*Filter, error) { var filter Filter err := doAPI(http.MethodGet, fmt.Sprintf("/api/v1/filters/%s", url.PathEscape(string(filterId))), nil, &filter, nil) if err != nil { return nil, err } return &filter, nil } func (f *Filter) Create() (*Filter, error) { if f == nil { return nil, errors.New("filter can't be nil") } if f.Phrase == "" { return nil, errors.New("phrase can't be empty") } if len(f.Context) == 0 { return nil, errors.New("context can't be empty") } params := url.Values{} params.Set("phrase", f.Phrase) for _, c := range f.Context { params.Add("context[]", c) } if f.WholeWord { params.Add("whole_word", "true") } if f.Irreversible { params.Add("irreversible", "true") } if !f.ExpiresAt.IsZero() { diff := time.Until(f.ExpiresAt) params.Add("expires_in", fmt.Sprintf("%.0f", diff.Seconds())) } var ret Filter err := doAPI(http.MethodPost, "/api/v1/filters", params, &ret, nil) if err != nil { return nil, err } return &ret, nil } func (f *Filter) Update(newFilter *Filter) (*Filter, error) { if newFilter == nil { return nil, errors.New("filter can't be nil") } if f.GetID() == "" { return nil, errors.New("ID can't be empty") } if newFilter.Phrase == "" { return nil, errors.New("phrase can't be empty") } if len(newFilter.Context) == 0 { return nil, errors.New("context can't be empty") } params := url.Values{} params.Set("phrase", newFilter.Phrase) for _, c := range newFilter.Context { params.Add("context[]", c) } if newFilter.WholeWord { params.Add("whole_word", "true") } else { params.Add("whole_word", "false") } if newFilter.Irreversible { params.Add("irreversible", "true") } else { params.Add("irreversible", "false") } if !newFilter.ExpiresAt.IsZero() { diff := time.Until(newFilter.ExpiresAt) params.Add("expires_in", fmt.Sprintf("%.0f", diff.Seconds())) } else { params.Add("expires_in", "") } var ret Filter err := doAPI(http.MethodPut, fmt.Sprintf("/api/v1/filters/%s", url.PathEscape(f.GetID())), params, &ret, nil) if err != nil { return nil, err } return &ret, nil } func (f *Filter) Delete() error { return doAPI(http.MethodDelete, fmt.Sprintf("/api/v1/filters/%s", url.PathEscape(f.GetID())), nil, nil, nil) }