package content import ( "crypto/rand" "database/sql" "encoding/hex" "encoding/json" "errors" "fmt" "strings" "time" "unicode/utf8" "supermarket/internal/api/twitter" "supermarket/internal/db" ) // Channels a draft can be for. const ( ChannelX = "x" ChannelLinkedIn = "linkedin" ) // Channel describes where drafts are published. type Channel struct { ID string Name string Limit int // characters, counted the way the channel counts them } // Channels lists the channels drafts can be written for, in display order. var Channels = []Channel{ {ChannelX, "X", 280}, {ChannelLinkedIn, "LinkedIn", 3000}, } // ChannelByID returns the channel, or false. func ChannelByID(id string) (Channel, bool) { for _, c := range Channels { if c.ID == id { return c, true } } return Channel{}, false } // Draft statuses. const ( StatusDraft = "draft" StatusPublishing = "publishing" // claimed by a publish in progress StatusPublished = "published" StatusFailed = "failed" StatusDiscarded = "discarded" ) // Draft is a post for one channel. type Draft struct { ID int64 Batch string // drafts written together share it InventoryName string Kind string // the entry's relationship Channel string Content string SourceURL string // added when publishing: appended on X, a link preview on LinkedIn ItemIDs []string Status string Error string PostURL string CreatedAt time.Time UpdatedAt time.Time PublishedAt time.Time } // Length is the draft's length as its channel counts it, including the // source link on X. func (d *Draft) Length() int { return Length(d.Channel, d.Content, d.SourceURL) } // Length counts content for channel. func Length(channel, text, sourceURL string) int { if channel == ChannelX { return twitter.TweetLength(text, sourceURL) } return utf8.RuneCountInString(text) } // Limit is the channel's limit for the draft's text. func (d *Draft) Limit() int { c, _ := ChannelByID(d.Channel) return c.Limit } // TooLong reports whether the draft can't be published as it is. func (d *Draft) TooLong() bool { return d.Length() > d.Limit() } // ChannelName is the channel's display name. func (d *Draft) ChannelName() string { if c, ok := ChannelByID(d.Channel); ok { return c.Name } return d.Channel } // Editable reports whether the draft can still be changed and published. func (d *Draft) Editable() bool { return d.Status == StatusDraft || d.Status == StatusFailed } func newBatchID() string { b := make([]byte, 8) _, _ = rand.Read(b) return hex.EncodeToString(b) } // CreateDrafts stores drafts written together under one new batch and marks // their items as used. func CreateDrafts(d *db.DB, drafts []Draft) (string, error) { batch := newBatchID() tx, err := d.Begin() if err != nil { return "", err } defer tx.Rollback() used := map[string]bool{} var usedIDs []string for _, dr := range drafts { if _, ok := ChannelByID(dr.Channel); !ok { return "", fmt.Errorf("unknown channel %q", dr.Channel) } ids, _ := json.Marshal(nonNil(dr.ItemIDs)) if _, err := tx.Exec(`INSERT INTO drafts (batch, inventory_name, kind, channel, content, source_url, item_ids) VALUES (?, ?, ?, ?, ?, ?, ?)`, batch, dr.InventoryName, dr.Kind, dr.Channel, strings.TrimSpace(dr.Content), dr.SourceURL, string(ids)); err != nil { return "", err } for _, id := range dr.ItemIDs { if !used[id] { used[id] = true usedIDs = append(usedIDs, id) } } } if err := markUsed(tx, usedIDs); err != nil { return "", err } return batch, tx.Commit() } func nonNil(s []string) []string { if s == nil { return []string{} } return s } const draftColumns = `id, batch, inventory_name, kind, channel, content, source_url, item_ids, status, error, post_url, created_at, updated_at, COALESCE(published_at, '')` func scanDrafts(rows *sql.Rows) ([]Draft, error) { defer rows.Close() var out []Draft for rows.Next() { var dr Draft var ids, created, updated, published string if err := rows.Scan(&dr.ID, &dr.Batch, &dr.InventoryName, &dr.Kind, &dr.Channel, &dr.Content, &dr.SourceURL, &ids, &dr.Status, &dr.Error, &dr.PostURL, &created, &updated, &published); err != nil { return nil, err } _ = json.Unmarshal([]byte(ids), &dr.ItemIDs) dr.CreatedAt, dr.UpdatedAt, dr.PublishedAt = parseTime(created), parseTime(updated), parseTime(published) out = append(out, dr) } return out, rows.Err() } // ListDrafts returns drafts with the given statuses, newest first. func ListDrafts(d *db.DB, limit int, statuses ...string) ([]Draft, error) { if len(statuses) == 0 { return nil, errors.New("no statuses given") } args := make([]any, 0, len(statuses)+1) for _, s := range statuses { args = append(args, s) } args = append(args, limit) order := "created_at DESC, id DESC" if len(statuses) == 1 && statuses[0] == StatusPublished { order = "published_at DESC, id DESC" } rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE status IN (?`+ strings.Repeat(", ?", len(statuses)-1)+`) ORDER BY `+order+` LIMIT ?`, args...) if err != nil { return nil, err } return scanDrafts(rows) } // ErrNoDraft means there's no draft with that ID. var ErrNoDraft = errors.New("no such draft") // GetDraft returns one draft. func GetDraft(d *db.DB, id int64) (*Draft, error) { rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE id = ?`, id) if err != nil { return nil, err } drafts, err := scanDrafts(rows) if err != nil { return nil, err } if len(drafts) == 0 { return nil, ErrNoDraft } return &drafts[0], nil } // ErrNotEditable means the draft was published, discarded, or is being // published. var ErrNotEditable = errors.New("this draft can't be changed any more") // UpdateDraft saves edited text. func UpdateDraft(d *db.DB, id int64, text string) error { text = strings.TrimSpace(text) if text == "" { return errors.New("the post is empty") } res, err := d.Exec(`UPDATE drafts SET content = ?, updated_at = ? WHERE id = ? AND status IN (?, ?)`, text, formatTime(time.Now()), id, StatusDraft, StatusFailed) return oneRow(res, err) } // DiscardDraft drops a draft without publishing it. func DiscardDraft(d *db.DB, id int64) error { res, err := d.Exec(`UPDATE drafts SET status = ?, updated_at = ? WHERE id = ? AND status IN (?, ?)`, StatusDiscarded, formatTime(time.Now()), id, StatusDraft, StatusFailed) return oneRow(res, err) } func oneRow(res sql.Result, err error) error { if err != nil { return err } if n, _ := res.RowsAffected(); n != 1 { return ErrNotEditable } return nil } // RecoverInterrupted marks drafts left "publishing" by a stopped app as // failed: they may or may not have gone out, so the user checks first. func RecoverInterrupted(d *db.DB) (int, error) { res, err := d.Exec(`UPDATE drafts SET status = ?, error = ?, updated_at = ? WHERE status = ?`, StatusFailed, "Supermarket stopped while publishing this. Check the channel before publishing it again.", formatTime(time.Now()), StatusPublishing) if err != nil { return 0, err } n, _ := res.RowsAffected() return int(n), nil } // CountDrafts is how many drafts wait for review. func CountDrafts(d *db.DB) (int, error) { var n int err := d.QueryRow(`SELECT count(*) FROM drafts WHERE status IN (?, ?)`, StatusDraft, StatusFailed).Scan(&n) return n, err }