From f43a055d63d33599404d2616bf54216bc74a2506 Mon Sep 17 00:00:00 2001 From: Frédéric Guillot Date: Fri, 24 Aug 2018 22:23:03 -0700 Subject: Move Golang API client here --- client/README.md | 50 ++++++ client/client.go | 508 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ client/core.go | 176 +++++++++++++++++++ client/doc.go | 35 ++++ client/request.go | 145 ++++++++++++++++ 5 files changed, 914 insertions(+) create mode 100644 client/README.md create mode 100644 client/client.go create mode 100644 client/core.go create mode 100644 client/doc.go create mode 100644 client/request.go (limited to 'client') diff --git a/client/README.md b/client/README.md new file mode 100644 index 0000000..1791d7f --- /dev/null +++ b/client/README.md @@ -0,0 +1,50 @@ +Miniflux API Client +=================== + +Client library for Miniflux REST API. + +Installation +------------ + +```bash +go get -u miniflux.app/client +``` + +Example +------- + +```go +package main + +import ( + "fmt" + "io/ioutil" + + miniflux "miniflux.app/client" +) + +func main() { + client := miniflux.New("https://api.example.org", "admin", "secret") + + // Fetch all feeds. + feeds, err := client.Feeds() + if err != nil { + fmt.Println(err) + return + } + fmt.Println(feeds) + + // Backup your feeds to an OPML file. + opml, err := client.Export() + if err != nil { + fmt.Println(err) + return + } + + err = ioutil.WriteFile("opml.xml", opml, 0644) + if err != nil { + fmt.Println(err) + return + } +} +``` diff --git a/client/client.go b/client/client.go new file mode 100644 index 0000000..75f5876 --- /dev/null +++ b/client/client.go @@ -0,0 +1,508 @@ +// Copyright 2018 Frédéric Guillot. All rights reserved. +// Use of this source code is governed by the MIT license +// that can be found in the LICENSE file. + +package client // import "miniflux.app/client" + +import ( + "encoding/json" + "fmt" + "io" + "io/ioutil" + "net/url" + "strconv" +) + +// Client holds API procedure calls. +type Client struct { + request *request +} + +// Me returns the logged user information. +func (c *Client) Me() (*User, error) { + body, err := c.request.Get("/v1/me") + if err != nil { + return nil, err + } + defer body.Close() + + var user *User + decoder := json.NewDecoder(body) + if err := decoder.Decode(&user); err != nil { + return nil, fmt.Errorf("miniflux: json error (%v)", err) + } + + return user, nil +} + +// Users returns all users. +func (c *Client) Users() (Users, error) { + body, err := c.request.Get("/v1/users") + if err != nil { + return nil, err + } + defer body.Close() + + var users Users + decoder := json.NewDecoder(body) + if err := decoder.Decode(&users); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return users, nil +} + +// UserByID returns a single user. +func (c *Client) UserByID(userID int64) (*User, error) { + body, err := c.request.Get(fmt.Sprintf("/v1/users/%d", userID)) + if err != nil { + return nil, err + } + defer body.Close() + + var user User + decoder := json.NewDecoder(body) + if err := decoder.Decode(&user); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return &user, nil +} + +// UserByUsername returns a single user. +func (c *Client) UserByUsername(username string) (*User, error) { + body, err := c.request.Get(fmt.Sprintf("/v1/users/%s", username)) + if err != nil { + return nil, err + } + defer body.Close() + + var user User + decoder := json.NewDecoder(body) + if err := decoder.Decode(&user); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return &user, nil +} + +// CreateUser creates a new user in the system. +func (c *Client) CreateUser(username, password string, isAdmin bool) (*User, error) { + body, err := c.request.Post("/v1/users", &User{Username: username, Password: password, IsAdmin: isAdmin}) + if err != nil { + return nil, err + } + defer body.Close() + + var user *User + decoder := json.NewDecoder(body) + if err := decoder.Decode(&user); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return user, nil +} + +// UpdateUser updates a user in the system. +func (c *Client) UpdateUser(userID int64, userChanges *UserModification) (*User, error) { + body, err := c.request.Put(fmt.Sprintf("/v1/users/%d", userID), userChanges) + if err != nil { + return nil, err + } + defer body.Close() + + var u *User + decoder := json.NewDecoder(body) + if err := decoder.Decode(&u); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return u, nil +} + +// DeleteUser removes a user from the system. +func (c *Client) DeleteUser(userID int64) error { + body, err := c.request.Delete(fmt.Sprintf("/v1/users/%d", userID)) + if err != nil { + return err + } + body.Close() + return nil +} + +// Discover try to find subscriptions from a website. +func (c *Client) Discover(url string) (Subscriptions, error) { + body, err := c.request.Post("/v1/discover", map[string]string{"url": url}) + if err != nil { + return nil, err + } + defer body.Close() + + var subscriptions Subscriptions + decoder := json.NewDecoder(body) + if err := decoder.Decode(&subscriptions); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return subscriptions, nil +} + +// Categories gets the list of categories. +func (c *Client) Categories() (Categories, error) { + body, err := c.request.Get("/v1/categories") + if err != nil { + return nil, err + } + defer body.Close() + + var categories Categories + decoder := json.NewDecoder(body) + if err := decoder.Decode(&categories); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return categories, nil +} + +// CreateCategory creates a new category. +func (c *Client) CreateCategory(title string) (*Category, error) { + body, err := c.request.Post("/v1/categories", map[string]interface{}{ + "title": title, + }) + + if err != nil { + return nil, err + } + defer body.Close() + + var category *Category + decoder := json.NewDecoder(body) + if err := decoder.Decode(&category); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return category, nil +} + +// UpdateCategory updates a category. +func (c *Client) UpdateCategory(categoryID int64, title string) (*Category, error) { + body, err := c.request.Put(fmt.Sprintf("/v1/categories/%d", categoryID), map[string]interface{}{ + "title": title, + }) + + if err != nil { + return nil, err + } + defer body.Close() + + var category *Category + decoder := json.NewDecoder(body) + if err := decoder.Decode(&category); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return category, nil +} + +// DeleteCategory removes a category. +func (c *Client) DeleteCategory(categoryID int64) error { + body, err := c.request.Delete(fmt.Sprintf("/v1/categories/%d", categoryID)) + if err != nil { + return err + } + defer body.Close() + + return nil +} + +// Feeds gets all feeds. +func (c *Client) Feeds() (Feeds, error) { + body, err := c.request.Get("/v1/feeds") + if err != nil { + return nil, err + } + defer body.Close() + + var feeds Feeds + decoder := json.NewDecoder(body) + if err := decoder.Decode(&feeds); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return feeds, nil +} + +// Export creates OPML file. +func (c *Client) Export() ([]byte, error) { + body, err := c.request.Get("/v1/export") + if err != nil { + return nil, err + } + defer body.Close() + + opml, err := ioutil.ReadAll(body) + if err != nil { + return nil, err + } + + return opml, nil +} + +// Import imports an OPML file. +func (c *Client) Import(f io.ReadCloser) error { + _, err := c.request.PostFile("/v1/import", f) + return err +} + +// Feed gets a feed. +func (c *Client) Feed(feedID int64) (*Feed, error) { + body, err := c.request.Get(fmt.Sprintf("/v1/feeds/%d", feedID)) + if err != nil { + return nil, err + } + defer body.Close() + + var feed *Feed + decoder := json.NewDecoder(body) + if err := decoder.Decode(&feed); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return feed, nil +} + +// CreateFeed creates a new feed. +func (c *Client) CreateFeed(url string, categoryID int64) (int64, error) { + body, err := c.request.Post("/v1/feeds", map[string]interface{}{ + "feed_url": url, + "category_id": categoryID, + }) + if err != nil { + return 0, err + } + defer body.Close() + + type result struct { + FeedID int64 `json:"feed_id"` + } + + var r result + decoder := json.NewDecoder(body) + if err := decoder.Decode(&r); err != nil { + return 0, fmt.Errorf("miniflux: response error (%v)", err) + } + + return r.FeedID, nil +} + +// UpdateFeed updates a feed. +func (c *Client) UpdateFeed(feedID int64, feedChanges *FeedModification) (*Feed, error) { + body, err := c.request.Put(fmt.Sprintf("/v1/feeds/%d", feedID), feedChanges) + if err != nil { + return nil, err + } + defer body.Close() + + var f *Feed + decoder := json.NewDecoder(body) + if err := decoder.Decode(&f); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return f, nil +} + +// RefreshFeed refresh a feed. +func (c *Client) RefreshFeed(feedID int64) error { + body, err := c.request.Put(fmt.Sprintf("/v1/feeds/%d/refresh", feedID), nil) + if err != nil { + return err + } + body.Close() + return nil +} + +// DeleteFeed removes a feed. +func (c *Client) DeleteFeed(feedID int64) error { + body, err := c.request.Delete(fmt.Sprintf("/v1/feeds/%d", feedID)) + if err != nil { + return err + } + body.Close() + return nil +} + +// FeedIcon gets a feed icon. +func (c *Client) FeedIcon(feedID int64) (*FeedIcon, error) { + body, err := c.request.Get(fmt.Sprintf("/v1/feeds/%d/icon", feedID)) + if err != nil { + return nil, err + } + defer body.Close() + + var feedIcon *FeedIcon + decoder := json.NewDecoder(body) + if err := decoder.Decode(&feedIcon); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return feedIcon, nil +} + +// FeedEntry gets a single feed entry. +func (c *Client) FeedEntry(feedID, entryID int64) (*Entry, error) { + body, err := c.request.Get(fmt.Sprintf("/v1/feeds/%d/entries/%d", feedID, entryID)) + if err != nil { + return nil, err + } + defer body.Close() + + var entry *Entry + decoder := json.NewDecoder(body) + if err := decoder.Decode(&entry); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return entry, nil +} + +// Entry gets a single entry. +func (c *Client) Entry(entryID int64) (*Entry, error) { + body, err := c.request.Get(fmt.Sprintf("/v1/entries/%d", entryID)) + if err != nil { + return nil, err + } + defer body.Close() + + var entry *Entry + decoder := json.NewDecoder(body) + if err := decoder.Decode(&entry); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return entry, nil +} + +// Entries fetch entries. +func (c *Client) Entries(filter *Filter) (*EntryResultSet, error) { + path := buildFilterQueryString("/v1/entries", filter) + + body, err := c.request.Get(path) + if err != nil { + return nil, err + } + defer body.Close() + + var result EntryResultSet + decoder := json.NewDecoder(body) + if err := decoder.Decode(&result); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return &result, nil +} + +// FeedEntries fetch feed entries. +func (c *Client) FeedEntries(feedID int64, filter *Filter) (*EntryResultSet, error) { + path := buildFilterQueryString(fmt.Sprintf("/v1/feeds/%d/entries", feedID), filter) + + body, err := c.request.Get(path) + if err != nil { + return nil, err + } + defer body.Close() + + var result EntryResultSet + decoder := json.NewDecoder(body) + if err := decoder.Decode(&result); err != nil { + return nil, fmt.Errorf("miniflux: response error (%v)", err) + } + + return &result, nil +} + +// UpdateEntries updates the status of a list of entries. +func (c *Client) UpdateEntries(entryIDs []int64, status string) error { + type payload struct { + EntryIDs []int64 `json:"entry_ids"` + Status string `json:"status"` + } + + body, err := c.request.Put("/v1/entries", &payload{EntryIDs: entryIDs, Status: status}) + if err != nil { + return err + } + body.Close() + + return nil +} + +// ToggleBookmark toggles entry bookmark value. +func (c *Client) ToggleBookmark(entryID int64) error { + body, err := c.request.Put(fmt.Sprintf("/v1/entries/%d/bookmark", entryID), nil) + if err != nil { + return err + } + body.Close() + + return nil +} + +// New returns a new Miniflux client. +func New(endpoint, username, password string) *Client { + return &Client{request: &request{endpoint: endpoint, username: username, password: password}} +} + +func buildFilterQueryString(path string, filter *Filter) string { + if filter != nil { + values := url.Values{} + + if filter.Status != "" { + values.Set("status", filter.Status) + } + + if filter.Direction != "" { + values.Set("direction", filter.Direction) + } + + if filter.Order != "" { + values.Set("order", filter.Order) + } + + if filter.Limit >= 0 { + values.Set("limit", strconv.Itoa(filter.Limit)) + } + + if filter.Offset >= 0 { + values.Set("offset", strconv.Itoa(filter.Offset)) + } + + if filter.After > 0 { + values.Set("after", strconv.FormatInt(filter.After, 10)) + } + + if filter.AfterEntryID > 0 { + values.Set("after_entry_id", strconv.FormatInt(filter.AfterEntryID, 10)) + } + + if filter.Before > 0 { + values.Set("before", strconv.FormatInt(filter.Before, 10)) + } + + if filter.BeforeEntryID > 0 { + values.Set("before_entry_id", strconv.FormatInt(filter.BeforeEntryID, 10)) + } + + if filter.Starred { + values.Set("starred", "1") + } + + if filter.Search != "" { + values.Set("search", filter.Search) + } + + path = fmt.Sprintf("%s?%s", path, values.Encode()) + } + + return path +} diff --git a/client/core.go b/client/core.go new file mode 100644 index 0000000..437af51 --- /dev/null +++ b/client/core.go @@ -0,0 +1,176 @@ +// Copyright 2018 Frédéric Guillot. All rights reserved. +// Use of this source code is governed by the MIT license +// that can be found in the LICENSE file. + +package client // import "miniflux.app/client" + +import ( + "fmt" + "time" +) + +// Entry statuses. +const ( + EntryStatusUnread = "unread" + EntryStatusRead = "read" + EntryStatusRemoved = "removed" +) + +// User represents a user in the system. +type User struct { + ID int64 `json:"id"` + Username string `json:"username"` + Password string `json:"password,omitempty"` + IsAdmin bool `json:"is_admin"` + Theme string `json:"theme"` + Language string `json:"language"` + Timezone string `json:"timezone"` + EntryDirection string `json:"entry_sorting_direction"` + LastLoginAt *time.Time `json:"last_login_at"` + Extra map[string]string `json:"extra"` +} + +func (u User) String() string { + return fmt.Sprintf("#%d - %s (admin=%v)", u.ID, u.Username, u.IsAdmin) +} + +// UserModification is used to update a user. +type UserModification struct { + Username *string `json:"username"` + Password *string `json:"password"` + IsAdmin *bool `json:"is_admin"` + Theme *string `json:"theme"` + Language *string `json:"language"` + Timezone *string `json:"timezone"` + EntryDirection *string `json:"entry_sorting_direction"` +} + +// Users represents a list of users. +type Users []User + +// Category represents a category in the system. +type Category struct { + ID int64 `json:"id,omitempty"` + Title string `json:"title,omitempty"` + UserID int64 `json:"user_id,omitempty"` +} + +func (c Category) String() string { + return fmt.Sprintf("#%d %s", c.ID, c.Title) +} + +// Categories represents a list of categories. +type Categories []*Category + +// Subscription represents a feed subscription. +type Subscription struct { + Title string `json:"title"` + URL string `json:"url"` + Type string `json:"type"` +} + +func (s Subscription) String() string { + return fmt.Sprintf(`Title="%s", URL="%s", Type="%s"`, s.Title, s.URL, s.Type) +} + +// Subscriptions represents a list of subscriptions. +type Subscriptions []*Subscription + +// Feed represents a Miniflux feed. +type Feed struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + FeedURL string `json:"feed_url"` + SiteURL string `json:"site_url"` + Title string `json:"title"` + CheckedAt time.Time `json:"checked_at,omitempty"` + EtagHeader string `json:"etag_header,omitempty"` + LastModifiedHeader string `json:"last_modified_header,omitempty"` + ParsingErrorMsg string `json:"parsing_error_message,omitempty"` + ParsingErrorCount int `json:"parsing_error_count,omitempty"` + ScraperRules string `json:"scraper_rules"` + RewriteRules string `json:"rewrite_rules"` + Crawler bool `json:"crawler"` + Username string `json:"username"` + Password string `json:"password"` + Category *Category `json:"category,omitempty"` + Entries Entries `json:"entries,omitempty"` +} + +// FeedModification represents changes for a feed. +type FeedModification struct { + FeedURL *string `json:"feed_url"` + SiteURL *string `json:"site_url"` + Title *string `json:"title"` + ScraperRules *string `json:"scraper_rules"` + RewriteRules *string `json:"rewrite_rules"` + Crawler *bool `json:"crawler"` + Username *string `json:"username"` + Password *string `json:"password"` + CategoryID *int64 `json:"category_id"` +} + +// FeedIcon represents the feed icon. +type FeedIcon struct { + ID int64 `json:"id"` + MimeType string `json:"mime_type"` + Data string `json:"data"` +} + +// Feeds represents a list of feeds. +type Feeds []*Feed + +// Entry represents a subscription item in the system. +type Entry struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + FeedID int64 `json:"feed_id"` + Status string `json:"status"` + Hash string `json:"hash"` + Title string `json:"title"` + URL string `json:"url"` + Date time.Time `json:"published_at"` + Content string `json:"content"` + Author string `json:"author"` + Starred bool `json:"starred"` + Enclosures Enclosures `json:"enclosures,omitempty"` + Feed *Feed `json:"feed,omitempty"` + Category *Category `json:"category,omitempty"` +} + +// Entries represents a list of entries. +type Entries []*Entry + +// Enclosure represents an attachment. +type Enclosure struct { + ID int64 `json:"id"` + UserID int64 `json:"user_id"` + EntryID int64 `json:"entry_id"` + URL string `json:"url"` + MimeType string `json:"mime_type"` + Size int `json:"size"` +} + +// Enclosures represents a list of attachments. +type Enclosures []*Enclosure + +// Filter is used to filter entries. +type Filter struct { + Status string + Offset int + Limit int + Order string + Direction string + Starred bool + Before int64 + After int64 + BeforeEntryID int64 + AfterEntryID int64 + Search string +} + +// EntryResultSet represents the response when fetching entries. +type EntryResultSet struct { + Total int `json:"total"` + Entries Entries `json:"entries"` +} diff --git a/client/doc.go b/client/doc.go new file mode 100644 index 0000000..60d63aa --- /dev/null +++ b/client/doc.go @@ -0,0 +1,35 @@ +// Copyright 2018 Frédéric Guillot. All rights reserved. +// Use of this source code is governed by the MIT license +// that can be found in the LICENSE file. + +/* + +Package client implements a client library for the Miniflux REST API. + +Examples + +This code snippet fetch the list of users: + + import ( + miniflux "miniflux.app/client" + ) + + client := miniflux.New("https://api.example.org", "admin", "secret") + users, err := client.Users() + if err != nil { + fmt.Println(err) + return + } + fmt.Println(users, err) + +This one discover subscriptions on a website: + + subscriptions, err := client.Discover("https://example.org/") + if err != nil { + fmt.Println(err) + return + } + fmt.Println(subscriptions) + +*/ +package client // import "miniflux.app/client" diff --git a/client/request.go b/client/request.go new file mode 100644 index 0000000..e5a546d --- /dev/null +++ b/client/request.go @@ -0,0 +1,145 @@ +// Copyright 2018 Frédéric Guillot. All rights reserved. +// Use of this source code is governed by the MIT license +// that can be found in the LICENSE file. + +package client // import "miniflux.app/client" + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + "net/url" + "time" +) + +const ( + userAgent = "Miniflux Client Library " + defaultTimeout = 80 +) + +// List of exposed errors. +var ( + ErrNotAuthorized = errors.New("miniflux: unauthorized (bad credentials)") + ErrForbidden = errors.New("miniflux: access forbidden") + ErrServerError = errors.New("miniflux: internal server error") + ErrNotFound = errors.New("miniflux: resource not found") +) + +type errorResponse struct { + ErrorMessage string `json:"error_message"` +} + +type request struct { + endpoint string + username string + password string +} + +func (r *request) Get(path string) (io.ReadCloser, error) { + return r.execute(http.MethodGet, path, nil) +} + +func (r *request) Post(path string, data interface{}) (io.ReadCloser, error) { + return r.execute(http.MethodPost, path, data) +} + +func (r *request) PostFile(path string, f io.ReadCloser) (io.ReadCloser, error) { + return r.execute(http.MethodPost, path, f) +} + +func (r *request) Put(path string, data interface{}) (io.ReadCloser, error) { + return r.execute(http.MethodPut, path, data) +} + +func (r *request) Delete(path string) (io.ReadCloser, error) { + return r.execute(http.MethodDelete, path, nil) +} + +func (r *request) execute(method, path string, data interface{}) (io.ReadCloser, error) { + if r.endpoint[len(r.endpoint)-1:] == "/" { + r.endpoint = r.endpoint[:len(r.endpoint)-1] + } + + u, err := url.Parse(r.endpoint + path) + if err != nil { + return nil, err + } + + request := &http.Request{ + URL: u, + Method: method, + Header: r.buildHeaders(), + } + request.SetBasicAuth(r.username, r.password) + + if data != nil { + switch data.(type) { + case io.ReadCloser: + request.Body = data.(io.ReadCloser) + default: + request.Body = ioutil.NopCloser(bytes.NewBuffer(r.toJSON(data))) + } + } + + client := r.buildClient() + response, err := client.Do(request) + if err != nil { + return nil, err + } + + switch response.StatusCode { + case http.StatusUnauthorized: + return nil, ErrNotAuthorized + case http.StatusForbidden: + return nil, ErrForbidden + case http.StatusInternalServerError: + return nil, ErrServerError + case http.StatusNotFound: + return nil, ErrNotFound + case http.StatusBadRequest: + defer response.Body.Close() + + var resp errorResponse + decoder := json.NewDecoder(response.Body) + if err := decoder.Decode(&resp); err != nil { + return nil, fmt.Errorf("miniflux: bad request error (%v)", err) + } + + return nil, fmt.Errorf("miniflux: bad request (%s)", resp.ErrorMessage) + } + + if response.StatusCode > 400 { + return nil, fmt.Errorf("miniflux: status code=%d", response.StatusCode) + } + + return response.Body, nil +} + +func (r *request) buildClient() http.Client { + return http.Client{ + Timeout: time.Duration(defaultTimeout * time.Second), + } +} + +func (r *request) buildHeaders() http.Header { + headers := make(http.Header) + headers.Add("User-Agent", userAgent) + headers.Add("Content-Type", "application/json") + headers.Add("Accept", "application/json") + return headers +} + +func (r *request) toJSON(v interface{}) []byte { + b, err := json.Marshal(v) + if err != nil { + log.Println("Unable to convert interface to JSON:", err) + return []byte("") + } + + return b +} -- cgit v1.2.3