Improve random post picker
This commit is contained in:
@@ -7,6 +7,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -106,19 +107,33 @@ func (ps *PostService) InsertNewAccounts(newAccounts []domain.Account) int {
|
|||||||
|
|
||||||
func (ps *PostService) GetRandomPost() domain.Post {
|
func (ps *PostService) GetRandomPost() domain.Post {
|
||||||
var post domain.Post
|
var post domain.Post
|
||||||
orderExpr := "RANDOM()" // sqlite
|
var postIDs []uint
|
||||||
if config.Config.DBEngine != "sqlite" {
|
|
||||||
orderExpr = "RAND()" // mariadb/mysql
|
// AI Enhanced
|
||||||
|
// Step 1: Fetch eligible post IDs (with at least one approved attachment)
|
||||||
|
ps.db.
|
||||||
|
Model(&domain.Post{}).
|
||||||
|
Where("exists (select 1 from media_attachments where post_id = posts.id and approved = ?)", true).
|
||||||
|
Pluck("id", &postIDs)
|
||||||
|
|
||||||
|
if len(postIDs) == 0 {
|
||||||
|
return domain.Post{} // No eligible posts
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Step 2: Pick a random ID in Go
|
||||||
|
randomID := postIDs[rand.Intn(len(postIDs))]
|
||||||
|
|
||||||
|
// Step 3: Load the full post with related data
|
||||||
ps.db.
|
ps.db.
|
||||||
Preload("Account").
|
Preload("Account").
|
||||||
Preload("Attachments", "Approved = ?", true).
|
Preload("Attachments", "Approved = ?", true).
|
||||||
Where("exists (select 1 from media_attachments where post_id = posts.id and approved = ?)", true).
|
First(&post, randomID)
|
||||||
Order(orderExpr).
|
|
||||||
First(&post)
|
// Step 4: Keep only the first attachment if any
|
||||||
if len(post.Attachments) > 0 {
|
if len(post.Attachments) > 0 {
|
||||||
post.Attachments = []domain.MediaAttachment{post.Attachments[0]}
|
post.Attachments = []domain.MediaAttachment{post.Attachments[0]}
|
||||||
}
|
}
|
||||||
|
|
||||||
return post
|
return post
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user