aboutsummaryrefslogtreecommitdiff
path: root/miniflux/client.go
blob: 29441c4ec622317154f82efd845eb343031be905 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// Miniflux API client for fluxrec.
//
// Typed over exactly what fluxrec needs: GET /v1/entries with the filter
// subset used by export (starred/status/changed_after) and serve
// (after_entry_id), GET /v1/feeds (audits, the politeness sweep), and
// exactly one write: MakeFeedPolite, whose body type carries exactly two
// fields so the request can only ever say {"crawler": false,
// "ignore_http_cache": false} and nothing else. Auth is the X-Auth-Token
// header; credentials come from the environment (MINIFLUX_* with MFLUX_*
// fallback, so existing mflux exports work). Everything else is read-only
// by construction: no entry, star, or other feed mutation exists.
package miniflux

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"time"
)

// Env var names, primary then fallback (matches mflux's exports).
var (
	urlVars   = [2]string{"MINIFLUX_URL", "MFLUX_URL"}
	tokenVars = [2]string{"MINIFLUX_TOKEN", "MFLUX_TOKEN"}
)

// Config is resolved client configuration.
type Config struct {
	BaseURL string
	Token   string
}

// ConfigFromEnv resolves MINIFLUX_URL/MINIFLUX_TOKEN, falling back to
// MFLUX_URL/MFLUX_TOKEN. Errors name both variables so a missing export is
// obvious from the message alone.
func ConfigFromEnv() (Config, error) {
	baseURL := firstEnv(urlVars)
	if baseURL == "" {
		return Config{}, fmt.Errorf("miniflux URL not set: export %s (or %s)", urlVars[0], urlVars[1])
	}
	token := firstEnv(tokenVars)
	if token == "" {
		return Config{}, fmt.Errorf("miniflux token not set: export %s (or %s)", tokenVars[0], tokenVars[1])
	}
	return Config{BaseURL: baseURL, Token: token}, nil
}

func firstEnv(names [2]string) string {
	for _, n := range names {
		if v := os.Getenv(n); v != "" {
			return v
		}
	}
	return ""
}

// Client talks to Miniflux: reads plus the single politeness write.
// Transport-level blips (DNS read timeouts, resets) are retried with the
// waits in retryWait.
type Client struct {
	baseURL    string
	token      string
	httpClient *http.Client
	retryWait  []time.Duration
}

// transportBackoff is the default retry spacing after a transport-level
// request failure (dial/read timeout, reset — live-observed as DNS read
// timeouts on a flaky resolver). Short enough to clear a flap without ever
// looking like extra load to the server.
var transportBackoff = []time.Duration{time.Second, 4 * time.Second}

// NewClient builds a Client with a sane default HTTP timeout.
func NewClient(cfg Config) *Client {
	return &Client{
		baseURL:    cfg.BaseURL,
		token:      cfg.Token,
		httpClient: &http.Client{Timeout: 60 * time.Second},
		retryWait:  transportBackoff,
	}
}

// NewClientWithHTTP is NewClient with a caller-provided http.Client
// (tests point it at httptest servers).
func NewClientWithHTTP(cfg Config, hc *http.Client) *Client {
	return &Client{baseURL: cfg.BaseURL, token: cfg.Token, httpClient: hc, retryWait: transportBackoff}
}

// Feed is the subset of a Miniflux feed fluxrec needs.
type Feed struct {
	ID    int64  `json:"id"`
	Title string `json:"title"`
}

// FeedInfo is one subscription as returned by GET /v1/feeds (the pruning-
// audit view; richer than the per-entry Feed subset above).
type FeedInfo struct {
	ID       int64  `json:"id"`
	Title    string `json:"title"`
	SiteURL  string `json:"site_url"`
	Disabled bool   `json:"disabled"`
	Category struct {
		Title string `json:"title"`
	} `json:"category"`
}

// Entry is the subset of a Miniflux entry fluxrec needs. JSON field names
// match the Miniflux API verbatim so decoding is a straight mirror.
type Entry struct {
	ID          int64     `json:"id"`
	URL         string    `json:"url"`
	Title       string    `json:"title"`
	Content     string    `json:"content"`
	Status      string    `json:"status"` // "read" | "unread" | "removed"
	Starred     bool      `json:"starred"`
	PublishedAt time.Time `json:"published_at"`
	ChangedAt   time.Time `json:"changed_at"`
	Feed        Feed      `json:"feed"`
}

// Filters selects which entries GET /v1/entries returns. Zero values mean
// "no filter" for every field; Starred is a *bool so unset vs. false stays
// distinguishable (we only ever filter starred=true, but keep the type
// honest).
type Filters struct {
	Starred        *bool  // only starred entries when true
	Status         string // "read" | "unread"; "" = any
	FeedID         int64  // restrict to one feed (feeds-lane volume probes)
	ChangedAfter   int64  // unix timestamp; incremental export cursor
	PublishedAfter int64  // unix timestamp; only entries published after this
	AfterEntryID   int64  // serve-lane poll cursor
	Direction      string // "asc" | "desc"; "" = server default
	Limit          int    // page size; 0 = server default
	Offset         int    // paging offset
}

// EntrySet is one page of GET /v1/entries results. Total is the full
// matching count across pages, which offsets paging loops can stop against.
type EntrySet struct {
	Total   int     `json:"total"`
	Entries []Entry `json:"entries"`
}

// Entries calls GET /v1/entries with the given filters.
func (c *Client) Entries(f Filters) (*EntrySet, error) {
	body, err := c.fetchEntries(f)
	if err != nil {
		return nil, err
	}
	var set EntrySet
	if err := json.Unmarshal(body, &set); err != nil {
		return nil, fmt.Errorf("decoding /v1/entries response: %w", err)
	}
	return &set, nil
}

// RawEntries returns the /v1/entries response body verbatim. Exists for
// fixture capture (`export --dump-raw`); the typed path stays Entries.
func (c *Client) RawEntries(f Filters) ([]byte, error) {
	return c.fetchEntries(f)
}

// Feeds calls GET /v1/feeds, returning every subscription (the audit lane:
// one call, no paging).
func (c *Client) Feeds() ([]FeedInfo, error) {
	body, err := c.getJSON(c.baseURL + "/v1/feeds")
	if err != nil {
		return nil, err
	}
	var feeds []FeedInfo
	if err := json.Unmarshal(body, &feeds); err != nil {
		return nil, fmt.Errorf("decoding /v1/feeds response: %w", err)
	}
	return feeds, nil
}

// MakeFeedPolite sets the two per-feed fetch settings that keep polling
// light — crawler (fetch-original-content) and ignore_http_cache — both
// false, so feeds stop being scraped and conditional requests (ETag /
// If-Modified-Since) are honored again. This is the sole write fluxrec
// performs on Miniflux. The request body is a marshalled feedPatch, which
// carries exactly these two fields, so nothing else on the feed can move
// (Miniflux's update is pointer-based: omitted fields stay untouched).
// Idempotent: same input, same state.
func (c *Client) MakeFeedPolite(id int64) error {
	payload, err := json.Marshal(feedPatch{})
	if err != nil {
		return fmt.Errorf("encoding update request: %w", err)
	}
	_, err = c.sendJSON(http.MethodPut, c.baseURL+"/v1/feeds/"+strconv.FormatInt(id, 10), payload)
	return err
}

// feedPatch is the PUT /v1/feeds/{id} request body. Exactly these two
// fields, both false: the wire format is
// {"crawler":false,"ignore_http_cache":false}.
type feedPatch struct {
	Crawler         bool `json:"crawler"`           // "Fetch original content"
	IgnoreHTTPCache bool `json:"ignore_http_cache"` // "Ignore HTTP cache"
}

// fetchEntries issues the GET and returns the body on HTTP 200.
func (c *Client) fetchEntries(f Filters) ([]byte, error) {
	return c.getJSON(entriesURL(c.baseURL, f))
}

// getJSON GETs u with the auth header and returns the body via sendJSON.
func (c *Client) getJSON(u string) ([]byte, error) {
	return c.sendJSON(http.MethodGet, u, nil)
}

// sendJSON issues an authenticated request to u — payload nil means no
// request body (GET), non-nil means a JSON body. Returns the response body
// on any 2xx status: Miniflux answers reads with 200 and mutations with
// 200, 201 or 204 (201 even for updates — live-observed; the 204 body is
// empty). Any other status becomes an error naming the method, URL, status
// and a response sniff.
//
// Transport-level failures are retried (up to len(retryWait) extra
// attempts) but status errors are not: a blip is transient, a server
// answer is an answer. Retrying is safe for every call this client makes
// — GETs are idempotent, and the one write (MakeFeedPolite) sets a fixed
// state. Each attempt re-arms the body from GetBody so a drained reader
// can never be re-sent empty.
func (c *Client) sendJSON(method, u string, payload []byte) ([]byte, error) {
	var body io.Reader
	if payload != nil {
		body = bytes.NewReader(payload)
	}
	req, err := http.NewRequest(method, u, body)
	if err != nil {
		return nil, fmt.Errorf("building request: %w", err)
	}
	req.Header.Set("X-Auth-Token", c.token)
	if payload != nil {
		req.Header.Set("Content-Type", "application/json")
	}

	resp, err := c.httpClient.Do(req)
	for attempt := 0; err != nil; attempt++ {
		if attempt >= len(c.retryWait) {
			return nil, fmt.Errorf("%s %s: %w", method, u, err)
		}
		time.Sleep(c.retryWait[attempt])
		if req.GetBody != nil {
			if fresh, berr := req.GetBody(); berr == nil {
				req.Body = fresh
			}
		}
		resp, err = c.httpClient.Do(req)
	}
	defer func() { _ = resp.Body.Close() }()

	if resp.StatusCode < 200 || resp.StatusCode > 299 {
		body, _ := io.ReadAll(io.LimitReader(resp.Body, 256))
		return nil, fmt.Errorf("%s %s: status %d: %s", method, u, resp.StatusCode, body)
	}

	out, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("reading response from %s: %w", u, err)
	}
	return out, nil
}

// entriesURL builds /v1/entries?... honoring only the non-zero filters.
func entriesURL(base string, f Filters) string {
	q := url.Values{}
	if f.Starred != nil {
		q.Set("starred", strconv.FormatBool(*f.Starred))
	}
	if f.Status != "" {
		q.Set("status", f.Status)
	}
	if f.FeedID > 0 {
		q.Set("feed_id", strconv.FormatInt(f.FeedID, 10))
	}
	if f.ChangedAfter > 0 {
		q.Set("changed_after", strconv.FormatInt(f.ChangedAfter, 10))
	}
	if f.PublishedAfter > 0 {
		q.Set("published_after", strconv.FormatInt(f.PublishedAfter, 10))
	}
	if f.AfterEntryID > 0 {
		q.Set("after_entry_id", strconv.FormatInt(f.AfterEntryID, 10))
	}
	if f.Direction != "" {
		q.Set("direction", f.Direction)
	}
	if f.Limit > 0 {
		q.Set("limit", strconv.Itoa(f.Limit))
	}
	if f.Offset > 0 {
		q.Set("offset", strconv.Itoa(f.Offset))
	}

	u := base + "/v1/entries"
	if len(q) > 0 {
		u += "?" + q.Encode()
	}
	return u
}