// Package content is the Content module: fetched items, per-channel drafts // written from them, and publishing those drafts. package content import ( "database/sql" "errors" "strings" "time" "supermarket/internal/db" "supermarket/internal/models" ) // DefaultLookback is how far back the first fetch for an entry goes. const DefaultLookback = 7 * 24 * time.Hour // Item is a stored content item. type Item struct { models.ContentItem FetchedAt time.Time Used bool // a draft was written from it Dismissed bool } const timeFormat = time.RFC3339 func formatTime(t time.Time) string { return t.UTC().Format(timeFormat) } func parseTime(s string) time.Time { t, _ := time.Parse(timeFormat, s) return t } // SaveItems stores fetched items, keeping ones already stored as they are. // It returns how many were new. func SaveItems(d *db.DB, items []models.ContentItem) (int, error) { tx, err := d.Begin() if err != nil { return 0, err } defer tx.Rollback() n := 0 for _, it := range items { res, err := tx.Exec(`INSERT INTO content_items (id, inventory_name, source, author, author_handle, title, body, url, published_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING`, it.ID, it.AppName, string(it.Source), it.Author, it.AuthorHandle, it.Title, it.Body, it.URL, formatTime(it.PublishedAt)) if err != nil { return 0, err } if k, _ := res.RowsAffected(); k > 0 { n++ } } return n, tx.Commit() } const itemColumns = `c.id, c.inventory_name, c.source, c.author, c.author_handle, c.title, c.body, c.url, c.published_at, c.fetched_at, c.used_at IS NOT NULL, d.item_id IS NOT NULL` const itemFrom = ` FROM content_items c LEFT JOIN dismissed d ON d.item_id = c.id` func scanItems(rows *sql.Rows) ([]Item, error) { defer rows.Close() var out []Item for rows.Next() { var it Item var source, published, fetched string if err := rows.Scan(&it.ID, &it.AppName, &source, &it.Author, &it.AuthorHandle, &it.Title, &it.Body, &it.URL, &published, &fetched, &it.Used, &it.Dismissed); err != nil { return nil, err } it.Source = models.ContentSource(source) it.PublishedAt = parseTime(published) it.FetchedAt = parseTime(fetched) out = append(out, it) } return out, rows.Err() } // ListItems returns an entry's items, newest first. Dismissed items are left // out unless dismissed is true, and then only they are returned. func ListItems(d *db.DB, entryName string, dismissed bool, limit int) ([]Item, error) { cond := "d.item_id IS NULL" if dismissed { cond = "d.item_id IS NOT NULL" } rows, err := d.Query(`SELECT `+itemColumns+itemFrom+` WHERE c.inventory_name = ? AND `+cond+` ORDER BY c.published_at DESC LIMIT ?`, entryName, limit) if err != nil { return nil, err } return scanItems(rows) } // GetItems returns the items with these IDs, in the order given; unknown // IDs are skipped. func GetItems(d *db.DB, ids []string) ([]Item, error) { var out []Item for _, id := range ids { rows, err := d.Query(`SELECT `+itemColumns+itemFrom+` WHERE c.id = ?`, id) if err != nil { return nil, err } items, err := scanItems(rows) if err != nil { return nil, err } out = append(out, items...) } return out, nil } // Counts is how many items an entry has waiting (not used, not dismissed). func Counts(d *db.DB) (map[string]int, error) { rows, err := d.Query(`SELECT c.inventory_name, count(*)` + itemFrom + ` WHERE d.item_id IS NULL AND c.used_at IS NULL AND c.source != 'Product' GROUP BY c.inventory_name`) // the column ignores case if err != nil { return nil, err } defer rows.Close() out := map[string]int{} for rows.Next() { var name string var n int if err := rows.Scan(&name, &n); err != nil { return nil, err } out[strings.ToLower(name)] = n } return out, rows.Err() } // Dismiss hides items from the list for good (until restored). func Dismiss(d *db.DB, ids []string) error { for _, id := range ids { if _, err := d.Exec(`INSERT INTO dismissed (item_id) VALUES (?) ON CONFLICT DO NOTHING`, id); err != nil { return err } } return nil } // Restore brings dismissed items back. func Restore(d *db.DB, ids []string) error { for _, id := range ids { if _, err := d.Exec(`DELETE FROM dismissed WHERE item_id = ?`, id); err != nil { return err } } return nil } func markUsed(tx *db.Tx, ids []string) error { for _, id := range ids { if _, err := tx.Exec(`UPDATE content_items SET used_at = ? WHERE id = ? AND used_at IS NULL`, formatTime(time.Now()), id); err != nil { return err } } return nil } // LastChecked is when the entry was last fetched, or zero. func LastChecked(d *db.DB, entryName string) (time.Time, error) { var s string err := d.QueryRow(`SELECT last_checked FROM fetch_state WHERE key = ?`, entryName).Scan(&s) if errors.Is(err, sql.ErrNoRows) { return time.Time{}, nil } if err != nil { return time.Time{}, err } return parseTime(s), nil } // Since is where the next fetch for the entry starts. func Since(d *db.DB, entryName string, now time.Time) (time.Time, error) { last, err := LastChecked(d, entryName) if err != nil || last.IsZero() || now.Sub(last) > 30*24*time.Hour { return now.Add(-DefaultLookback), err } return last, nil } // SetLastChecked records a fetch. func SetLastChecked(d *db.DB, entryName string, at time.Time) error { _, err := d.Exec(`INSERT INTO fetch_state (key, last_checked) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET last_checked = excluded.last_checked`, entryName, formatTime(at)) return err }