sojorn/go-backend/internal/services/official_accounts_service.go

811 lines
26 KiB
Go

package services
import (
"context"
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"regexp"
"strings"
"sync"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/rs/zerolog/log"
)
// OfficialAccountConfig represents a row in official_account_configs
type OfficialAccountConfig struct {
ID string `json:"id"`
ProfileID string `json:"profile_id"`
AccountType string `json:"account_type"`
Enabled bool `json:"enabled"`
ModelID string `json:"model_id"`
SystemPrompt string `json:"system_prompt"`
Temperature float64 `json:"temperature"`
MaxTokens int `json:"max_tokens"`
PostIntervalMinutes int `json:"post_interval_minutes"`
MaxPostsPerDay int `json:"max_posts_per_day"`
PostsToday int `json:"posts_today"`
PostsTodayResetAt time.Time `json:"posts_today_reset_at"`
LastPostedAt *time.Time `json:"last_posted_at"`
NewsSources json.RawMessage `json:"news_sources"`
LastFetchedAt *time.Time `json:"last_fetched_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// Joined fields
Handle string `json:"handle,omitempty"`
DisplayName string `json:"display_name,omitempty"`
AvatarURL string `json:"avatar_url,omitempty"`
}
// NewsSource represents a single RSS feed configuration.
// If Site is set, the Google News RSS URL is auto-constructed.
// If RSSURL is set directly, it's used as-is (legacy/fallback).
type NewsSource struct {
Name string `json:"name"`
Site string `json:"site,omitempty"`
RSSURL string `json:"rss_url,omitempty"`
Enabled bool `json:"enabled"`
}
// GoogleNewsRSSURL builds a Google News RSS search URL for the given site domain.
func GoogleNewsRSSURL(site string) string {
return fmt.Sprintf("https://news.google.com/rss/search?q=site:%s&hl=en-US&gl=US&ceid=US:en", site)
}
// EffectiveRSSURL returns the RSS URL to fetch — Google News if Site is set, otherwise RSSURL.
func (ns *NewsSource) EffectiveRSSURL() string {
if ns.Site != "" {
return GoogleNewsRSSURL(ns.Site)
}
return ns.RSSURL
}
// RSSFeed represents a parsed RSS feed
type RSSFeed struct {
Channel struct {
Title string `xml:"title"`
Items []RSSItem `xml:"item"`
} `xml:"channel"`
}
// RSSItem represents a single RSS item
type RSSItem struct {
Title string `xml:"title" json:"title"`
Link string `xml:"link" json:"link"`
Description string `xml:"description" json:"description"`
PubDate string `xml:"pubDate" json:"pub_date"`
GUID string `xml:"guid" json:"guid"`
Source RSSSource `xml:"source" json:"source"`
}
// RSSSource represents the <source> element in Google News RSS items.
type RSSSource struct {
URL string `xml:"url,attr" json:"url"`
Name string `xml:",chardata" json:"name"`
}
// PostedArticle represents a previously posted article
type PostedArticle struct {
ID string `json:"id"`
ConfigID string `json:"config_id"`
ArticleURL string `json:"article_url"`
ArticleTitle string `json:"article_title"`
SourceName string `json:"source_name"`
PostedAt time.Time `json:"posted_at"`
PostID *string `json:"post_id"`
}
// OfficialAccountsService manages official account automation
type OfficialAccountsService struct {
pool *pgxpool.Pool
openRouterService *OpenRouterService
httpClient *http.Client
stopCh chan struct{}
wg sync.WaitGroup
}
func NewOfficialAccountsService(pool *pgxpool.Pool, openRouterService *OpenRouterService) *OfficialAccountsService {
return &OfficialAccountsService{
pool: pool,
openRouterService: openRouterService,
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
stopCh: make(chan struct{}),
}
}
// ── CRUD ─────────────────────────────────────────────
func (s *OfficialAccountsService) ListConfigs(ctx context.Context) ([]OfficialAccountConfig, error) {
rows, err := s.pool.Query(ctx, `
SELECT c.id, c.profile_id, c.account_type, c.enabled,
c.model_id, c.system_prompt, c.temperature, c.max_tokens,
c.post_interval_minutes, c.max_posts_per_day, c.posts_today, c.posts_today_reset_at,
c.last_posted_at, c.news_sources, c.last_fetched_at,
c.created_at, c.updated_at,
p.handle, p.display_name, COALESCE(p.avatar_url, '')
FROM official_account_configs c
JOIN public.profiles p ON p.id = c.profile_id
ORDER BY c.created_at DESC
`)
if err != nil {
return nil, err
}
defer rows.Close()
var configs []OfficialAccountConfig
for rows.Next() {
var c OfficialAccountConfig
if err := rows.Scan(
&c.ID, &c.ProfileID, &c.AccountType, &c.Enabled,
&c.ModelID, &c.SystemPrompt, &c.Temperature, &c.MaxTokens,
&c.PostIntervalMinutes, &c.MaxPostsPerDay, &c.PostsToday, &c.PostsTodayResetAt,
&c.LastPostedAt, &c.NewsSources, &c.LastFetchedAt,
&c.CreatedAt, &c.UpdatedAt,
&c.Handle, &c.DisplayName, &c.AvatarURL,
); err != nil {
return nil, err
}
configs = append(configs, c)
}
return configs, nil
}
func (s *OfficialAccountsService) GetConfig(ctx context.Context, id string) (*OfficialAccountConfig, error) {
var c OfficialAccountConfig
err := s.pool.QueryRow(ctx, `
SELECT c.id, c.profile_id, c.account_type, c.enabled,
c.model_id, c.system_prompt, c.temperature, c.max_tokens,
c.post_interval_minutes, c.max_posts_per_day, c.posts_today, c.posts_today_reset_at,
c.last_posted_at, c.news_sources, c.last_fetched_at,
c.created_at, c.updated_at,
p.handle, p.display_name, COALESCE(p.avatar_url, '')
FROM official_account_configs c
JOIN public.profiles p ON p.id = c.profile_id
WHERE c.id = $1
`, id).Scan(
&c.ID, &c.ProfileID, &c.AccountType, &c.Enabled,
&c.ModelID, &c.SystemPrompt, &c.Temperature, &c.MaxTokens,
&c.PostIntervalMinutes, &c.MaxPostsPerDay, &c.PostsToday, &c.PostsTodayResetAt,
&c.LastPostedAt, &c.NewsSources, &c.LastFetchedAt,
&c.CreatedAt, &c.UpdatedAt,
&c.Handle, &c.DisplayName, &c.AvatarURL,
)
if err != nil {
return nil, err
}
return &c, nil
}
func (s *OfficialAccountsService) UpsertConfig(ctx context.Context, cfg OfficialAccountConfig) (*OfficialAccountConfig, error) {
newsJSON, err := json.Marshal(cfg.NewsSources)
if err != nil {
newsJSON = []byte("[]")
}
var id string
err = s.pool.QueryRow(ctx, `
INSERT INTO official_account_configs
(profile_id, account_type, enabled, model_id, system_prompt, temperature, max_tokens,
post_interval_minutes, max_posts_per_day, news_sources, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW())
ON CONFLICT (profile_id)
DO UPDATE SET
account_type = EXCLUDED.account_type,
enabled = EXCLUDED.enabled,
model_id = EXCLUDED.model_id,
system_prompt = EXCLUDED.system_prompt,
temperature = EXCLUDED.temperature,
max_tokens = EXCLUDED.max_tokens,
post_interval_minutes = EXCLUDED.post_interval_minutes,
max_posts_per_day = EXCLUDED.max_posts_per_day,
news_sources = EXCLUDED.news_sources,
updated_at = NOW()
RETURNING id
`, cfg.ProfileID, cfg.AccountType, cfg.Enabled, cfg.ModelID, cfg.SystemPrompt,
cfg.Temperature, cfg.MaxTokens, cfg.PostIntervalMinutes, cfg.MaxPostsPerDay, newsJSON,
).Scan(&id)
if err != nil {
return nil, err
}
return s.GetConfig(ctx, id)
}
func (s *OfficialAccountsService) DeleteConfig(ctx context.Context, id string) error {
_, err := s.pool.Exec(ctx, `DELETE FROM official_account_configs WHERE id = $1`, id)
return err
}
func (s *OfficialAccountsService) ToggleEnabled(ctx context.Context, id string, enabled bool) error {
_, err := s.pool.Exec(ctx, `UPDATE official_account_configs SET enabled = $2, updated_at = NOW() WHERE id = $1`, id, enabled)
return err
}
// ── RSS News Fetching ────────────────────────────────
func (s *OfficialAccountsService) FetchRSS(ctx context.Context, rssURL string) ([]RSSItem, error) {
req, err := http.NewRequestWithContext(ctx, "GET", rssURL, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "Mozilla/5.0 (compatible; Sojorn/1.0)")
resp, err := s.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to fetch RSS %s: %w", rssURL, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("RSS feed %s returned status %d", rssURL, resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var feed RSSFeed
if err := xml.Unmarshal(body, &feed); err != nil {
return nil, fmt.Errorf("failed to parse RSS from %s: %w", rssURL, err)
}
// If items come from Google News, resolve redirect links to actual article URLs
isGoogleNews := strings.Contains(rssURL, "news.google.com/rss")
if isGoogleNews {
for i := range feed.Channel.Items {
resolved := s.resolveGoogleNewsLink(feed.Channel.Items[i].Link)
if resolved != "" {
feed.Channel.Items[i].Link = resolved
}
}
}
return feed.Channel.Items, nil
}
// resolveGoogleNewsLink follows the Google News redirect chain to get the actual article URL.
func (s *OfficialAccountsService) resolveGoogleNewsLink(googleURL string) string {
return ResolveGoogleNewsURL(googleURL)
}
// ResolveGoogleNewsURL is a package-level helper that resolves a Google News URL
// to the underlying article URL by following the full redirect chain.
func ResolveGoogleNewsURL(googleURL string) string {
if googleURL == "" || !strings.Contains(googleURL, "news.google.com") {
return googleURL
}
// Track the final URL after all redirects
var finalURL string
client := &http.Client{
Timeout: 15 * time.Second,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return fmt.Errorf("too many redirects")
}
// Track every hop; stop if we've left Google domains
host := req.URL.Hostname()
if !strings.Contains(host, "google.com") && !strings.Contains(host, "google.") {
finalURL = req.URL.String()
return http.ErrUseLastResponse
}
return nil
},
}
req, err := http.NewRequest("GET", googleURL, nil)
if err != nil {
return googleURL
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
req.Header.Set("Accept", "text/html,application/xhtml+xml")
resp, err := client.Do(req)
if err != nil {
// If we captured a non-Google URL before the error, use it
if finalURL != "" {
log.Debug().Str("resolved", finalURL).Str("original", googleURL).Msg("Resolved Google News link via redirect chain")
return finalURL
}
log.Debug().Err(err).Str("url", googleURL).Msg("Failed to resolve Google News link")
return googleURL
}
defer resp.Body.Close()
// If we captured a non-Google URL during redirects, use that
if finalURL != "" {
log.Debug().Str("resolved", finalURL).Str("original", googleURL).Msg("Resolved Google News link via redirect chain")
return finalURL
}
// Check final response URL
if resp.Request != nil && resp.Request.URL != nil {
final := resp.Request.URL.String()
if !strings.Contains(final, "news.google.com") && !strings.Contains(final, "consent.google") {
log.Debug().Str("resolved", final).Str("original", googleURL).Msg("Resolved Google News link via final URL")
return final
}
}
// Fallback: parse meta refresh or JS redirect from response body
body, err := io.ReadAll(io.LimitReader(resp.Body, 64*1024))
if err == nil {
html := string(body)
// Look for <meta http-equiv="refresh" content="0;url=...">
metaRe := regexp.MustCompile(`(?i)http-equiv\s*=\s*["']refresh["'][^>]*content\s*=\s*["'][^;]*;\s*url\s*=\s*([^"'\s>]+)`)
if m := metaRe.FindStringSubmatch(html); len(m) > 1 {
resolved := strings.TrimSpace(m[1])
if !strings.Contains(resolved, "google.com") {
log.Debug().Str("resolved", resolved).Str("original", googleURL).Msg("Resolved Google News link via meta refresh")
return resolved
}
}
// Look for window.location or document.location JS redirects
jsRe := regexp.MustCompile(`(?:window|document)\.location\s*[=]\s*["']([^"']+)["']`)
if m := jsRe.FindStringSubmatch(html); len(m) > 1 {
resolved := strings.TrimSpace(m[1])
if !strings.Contains(resolved, "google.com") {
log.Debug().Str("resolved", resolved).Str("original", googleURL).Msg("Resolved Google News link via JS redirect")
return resolved
}
}
// Look for <a href="..."> with data-n-au attribute (Google News article link)
auRe := regexp.MustCompile(`data-n-au\s*=\s*["']([^"']+)["']`)
if m := auRe.FindStringSubmatch(html); len(m) > 1 {
log.Debug().Str("resolved", m[1]).Str("original", googleURL).Msg("Resolved Google News link via data-n-au")
return m[1]
}
}
log.Warn().Str("url", googleURL).Msg("Could not resolve Google News link to source article")
return googleURL
}
// FetchNewArticles fetches new articles from all enabled news sources for a config,
// filtering out already-posted articles.
func (s *OfficialAccountsService) FetchNewArticles(ctx context.Context, configID string) ([]RSSItem, []string, error) {
cfg, err := s.GetConfig(ctx, configID)
if err != nil {
return nil, nil, err
}
var sources []NewsSource
if err := json.Unmarshal(cfg.NewsSources, &sources); err != nil {
return nil, nil, fmt.Errorf("failed to parse news sources: %w", err)
}
var allItems []RSSItem
var sourceNames []string
for _, src := range sources {
rssURL := src.EffectiveRSSURL()
if !src.Enabled || rssURL == "" {
continue
}
items, err := s.FetchRSS(ctx, rssURL)
if err != nil {
log.Warn().Err(err).Str("source", src.Name).Msg("Failed to fetch RSS feed")
continue
}
for _, item := range items {
allItems = append(allItems, item)
sourceNames = append(sourceNames, src.Name)
}
}
// Filter out already-posted articles
var newItems []RSSItem
var newSourceNames []string
for i, item := range allItems {
link := item.Link
if link == "" {
link = item.GUID
}
if link == "" {
continue
}
var exists bool
_ = s.pool.QueryRow(ctx,
`SELECT EXISTS(SELECT 1 FROM official_account_posted_articles WHERE config_id = $1 AND article_url = $2)`,
configID, link,
).Scan(&exists)
if !exists {
newItems = append(newItems, item)
newSourceNames = append(newSourceNames, sourceNames[i])
}
}
// Update last_fetched_at
_, _ = s.pool.Exec(ctx, `UPDATE official_account_configs SET last_fetched_at = NOW() WHERE id = $1`, configID)
return newItems, newSourceNames, nil
}
// ── AI Post Generation ───────────────────────────────
// GeneratePost creates a post using AI for a given official account config.
// For news accounts, it takes an article and generates a commentary/summary.
// For general accounts, it generates an original post.
func (s *OfficialAccountsService) GeneratePost(ctx context.Context, configID string, article *RSSItem, sourceName string) (string, error) {
cfg, err := s.GetConfig(ctx, configID)
if err != nil {
return "", err
}
var userPrompt string
if article != nil {
// News mode: generate a post about this article
desc := article.Description
// Strip HTML tags from description
desc = stripHTMLTags(desc)
if len(desc) > 500 {
desc = desc[:500] + "..."
}
userPrompt = fmt.Sprintf(
"Write a social media post about this news article. Include the link.\n\nSource: %s\nTitle: %s\nDescription: %s\nLink: %s",
sourceName, article.Title, desc, article.Link,
)
} else {
// General mode: generate an original post
userPrompt = "Generate a new social media post. Be creative and engaging."
}
generated, err := s.openRouterService.GenerateText(
ctx, cfg.ModelID, cfg.SystemPrompt, userPrompt, cfg.Temperature, cfg.MaxTokens,
)
if err != nil {
return "", fmt.Errorf("AI generation failed: %w", err)
}
return generated, nil
}
// CreatePostForAccount creates a post in the database for the official account
func (s *OfficialAccountsService) CreatePostForAccount(ctx context.Context, configID string, body string, article *RSSItem, sourceName string) (string, error) {
cfg, err := s.GetConfig(ctx, configID)
if err != nil {
return "", err
}
// Check daily limit
if cfg.PostsToday >= cfg.MaxPostsPerDay {
// Reset if it's a new day
if time.Since(cfg.PostsTodayResetAt) > 24*time.Hour {
_, _ = s.pool.Exec(ctx, `UPDATE official_account_configs SET posts_today = 0, posts_today_reset_at = NOW() WHERE id = $1`, configID)
} else {
return "", fmt.Errorf("daily post limit reached (%d/%d)", cfg.PostsToday, cfg.MaxPostsPerDay)
}
}
// profile_id IS the author_id (profiles.id = users.id in this schema)
authorUUID, _ := uuid.Parse(cfg.ProfileID)
postID := uuid.New()
tx, err := s.pool.Begin(ctx)
if err != nil {
return "", err
}
defer tx.Rollback(ctx)
_, err = tx.Exec(ctx, `
INSERT INTO public.posts (id, author_id, body, status, body_format, is_beacon, allow_chain, visibility, is_nsfw, confidence_score, created_at)
VALUES ($1, $2, $3, 'active', 'plain', false, true, 'public', false, 1.0, $4)
`, postID, authorUUID, body, time.Now())
if err != nil {
return "", fmt.Errorf("failed to insert post: %w", err)
}
_, err = tx.Exec(ctx, `
INSERT INTO public.post_metrics (post_id, like_count, save_count, view_count, comment_count, updated_at)
VALUES ($1, 0, 0, 0, 0, $2) ON CONFLICT DO NOTHING
`, postID, time.Now())
if err != nil {
return "", fmt.Errorf("failed to insert post_metrics: %w", err)
}
// Track article if this was a news post
if article != nil {
link := article.Link
if link == "" {
link = article.GUID
}
postIDStr := postID.String()
_, _ = tx.Exec(ctx, `
INSERT INTO official_account_posted_articles (config_id, article_url, article_title, source_name, post_id)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (config_id, article_url) DO NOTHING
`, configID, link, article.Title, sourceName, postIDStr)
}
// Update counters
_, _ = tx.Exec(ctx, `
UPDATE official_account_configs
SET posts_today = posts_today + 1, last_posted_at = NOW(), updated_at = NOW()
WHERE id = $1
`, configID)
if err := tx.Commit(ctx); err != nil {
return "", err
}
// Fetch and store link preview for posts with URLs (trusted — official account)
go func() {
bgCtx := context.Background()
linkURL := ExtractFirstURL(body)
if linkURL == "" && article != nil {
linkURL = article.Link
}
if linkURL != "" {
lps := NewLinkPreviewService(s.pool)
lp, err := lps.FetchPreview(bgCtx, linkURL, true)
if err == nil && lp != nil {
_ = lps.SaveLinkPreview(bgCtx, postID.String(), lp)
log.Debug().Str("post_id", postID.String()).Str("url", linkURL).Msg("Saved link preview for official account post")
}
}
}()
return postID.String(), nil
}
// GenerateAndPost generates an AI post and creates it in the database
func (s *OfficialAccountsService) GenerateAndPost(ctx context.Context, configID string, article *RSSItem, sourceName string) (string, string, error) {
body, err := s.GeneratePost(ctx, configID, article, sourceName)
if err != nil {
return "", "", err
}
postID, err := s.CreatePostForAccount(ctx, configID, body, article, sourceName)
if err != nil {
return "", "", err
}
return postID, body, nil
}
// ── Scheduled Auto-Posting ───────────────────────────
func (s *OfficialAccountsService) StartScheduler() {
s.wg.Add(1)
go func() {
defer s.wg.Done()
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
log.Info().Msg("[OfficialAccounts] Scheduler started (5-min tick)")
for {
select {
case <-s.stopCh:
log.Info().Msg("[OfficialAccounts] Scheduler stopped")
return
case <-ticker.C:
s.runScheduledPosts()
}
}
}()
}
func (s *OfficialAccountsService) StopScheduler() {
close(s.stopCh)
s.wg.Wait()
}
func (s *OfficialAccountsService) runScheduledPosts() {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
// Find enabled configs that are due for a post
rows, err := s.pool.Query(ctx, `
SELECT id, account_type, post_interval_minutes, last_posted_at, posts_today, max_posts_per_day, posts_today_reset_at
FROM official_account_configs
WHERE enabled = true
`)
if err != nil {
log.Error().Err(err).Msg("[OfficialAccounts] Failed to query configs")
return
}
defer rows.Close()
type candidate struct {
ID string
AccountType string
PostIntervalMinutes int
LastPostedAt *time.Time
PostsToday int
MaxPostsPerDay int
PostsTodayResetAt time.Time
}
var candidates []candidate
for rows.Next() {
var c candidate
if err := rows.Scan(&c.ID, &c.AccountType, &c.PostIntervalMinutes, &c.LastPostedAt, &c.PostsToday, &c.MaxPostsPerDay, &c.PostsTodayResetAt); err != nil {
continue
}
candidates = append(candidates, c)
}
for _, c := range candidates {
// Reset daily counter if needed
if time.Since(c.PostsTodayResetAt) > 24*time.Hour {
_, _ = s.pool.Exec(ctx, `UPDATE official_account_configs SET posts_today = 0, posts_today_reset_at = NOW() WHERE id = $1`, c.ID)
c.PostsToday = 0
}
// Check daily limit
if c.PostsToday >= c.MaxPostsPerDay {
continue
}
// Check interval
if c.LastPostedAt != nil && time.Since(*c.LastPostedAt) < time.Duration(c.PostIntervalMinutes)*time.Minute {
continue
}
// Time to post!
if c.AccountType == "news" {
s.scheduleNewsPost(ctx, c.ID)
} else {
s.scheduleGeneralPost(ctx, c.ID)
}
}
}
func (s *OfficialAccountsService) scheduleNewsPost(ctx context.Context, configID string) {
items, sourceNames, err := s.FetchNewArticles(ctx, configID)
if err != nil {
log.Error().Err(err).Str("config", configID).Msg("[OfficialAccounts] Failed to fetch news")
return
}
if len(items) == 0 {
log.Debug().Str("config", configID).Msg("[OfficialAccounts] No new articles to post")
return
}
// Post the first new article
article := items[0]
sourceName := sourceNames[0]
postID, body, err := s.GenerateAndPost(ctx, configID, &article, sourceName)
if err != nil {
log.Error().Err(err).Str("config", configID).Msg("[OfficialAccounts] Failed to generate news post")
return
}
log.Info().Str("config", configID).Str("post_id", postID).Str("source", sourceName).Str("title", article.Title).Msg("[OfficialAccounts] News post created")
_ = body // logged implicitly via post
}
func (s *OfficialAccountsService) scheduleGeneralPost(ctx context.Context, configID string) {
postID, body, err := s.GenerateAndPost(ctx, configID, nil, "")
if err != nil {
log.Error().Err(err).Str("config", configID).Msg("[OfficialAccounts] Failed to generate post")
return
}
log.Info().Str("config", configID).Str("post_id", postID).Msg("[OfficialAccounts] General post created")
_ = body
}
// ── Recent Articles ──────────────────────────────────
func (s *OfficialAccountsService) GetRecentArticles(ctx context.Context, configID string, limit int) ([]PostedArticle, error) {
if limit <= 0 {
limit = 20
}
rows, err := s.pool.Query(ctx, `
SELECT id, config_id, article_url, article_title, source_name, posted_at, post_id
FROM official_account_posted_articles
WHERE config_id = $1
ORDER BY posted_at DESC
LIMIT $2
`, configID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var articles []PostedArticle
for rows.Next() {
var a PostedArticle
if err := rows.Scan(&a.ID, &a.ConfigID, &a.ArticleURL, &a.ArticleTitle, &a.SourceName, &a.PostedAt, &a.PostID); err != nil {
continue
}
articles = append(articles, a)
}
return articles, nil
}
// ── Helpers ──────────────────────────────────────────
// StripHTMLTagsPublic is the exported version for use by handlers
func StripHTMLTagsPublic(s string) string {
return stripHTMLTags(s)
}
func stripHTMLTags(s string) string {
var result strings.Builder
inTag := false
for _, r := range s {
if r == '<' {
inTag = true
continue
}
if r == '>' {
inTag = false
continue
}
if !inTag {
result.WriteRune(r)
}
}
return strings.TrimSpace(result.String())
}
// OfficialProfile represents a profile with is_official = true
type OfficialProfile struct {
ProfileID string `json:"profile_id"`
Handle string `json:"handle"`
DisplayName string `json:"display_name"`
AvatarURL string `json:"avatar_url"`
Bio string `json:"bio"`
IsVerified bool `json:"is_verified"`
HasConfig bool `json:"has_config"`
ConfigID *string `json:"config_id,omitempty"`
}
// ListOfficialProfiles returns all profiles where is_official = true,
// along with whether they have an official_account_configs entry
func (s *OfficialAccountsService) ListOfficialProfiles(ctx context.Context) ([]OfficialProfile, error) {
rows, err := s.pool.Query(ctx, `
SELECT p.id, p.handle, p.display_name, COALESCE(p.avatar_url, ''),
COALESCE(p.bio, ''), COALESCE(p.is_verified, false),
c.id AS config_id
FROM public.profiles p
LEFT JOIN official_account_configs c ON c.profile_id = p.id
WHERE p.is_official = true
ORDER BY p.handle
`)
if err != nil {
return nil, err
}
defer rows.Close()
var profiles []OfficialProfile
for rows.Next() {
var p OfficialProfile
var configID *string
if err := rows.Scan(&p.ProfileID, &p.Handle, &p.DisplayName, &p.AvatarURL, &p.Bio, &p.IsVerified, &configID); err != nil {
continue
}
p.ConfigID = configID
p.HasConfig = configID != nil
profiles = append(profiles, p)
}
return profiles, nil
}
// LookupProfileID finds a profile ID by handle
func (s *OfficialAccountsService) LookupProfileID(ctx context.Context, handle string) (string, error) {
var id string
err := s.pool.QueryRow(ctx, `SELECT id FROM public.profiles WHERE handle = $1`, strings.ToLower(handle)).Scan(&id)
if err != nil {
if err == pgx.ErrNoRows {
return "", fmt.Errorf("profile not found: @%s", handle)
}
return "", err
}
return id, nil
}