2024-04-27 21:10:24 +02:00
|
|
|
package widget
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"errors"
|
|
|
|
"html/template"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/glanceapp/glance/internal/assets"
|
|
|
|
"github.com/glanceapp/glance/internal/feed"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Reddit struct {
|
2024-05-01 20:08:25 +02:00
|
|
|
widgetBase `yaml:",inline"`
|
|
|
|
Posts feed.ForumPosts `yaml:"-"`
|
|
|
|
Subreddit string `yaml:"subreddit"`
|
|
|
|
Style string `yaml:"style"`
|
2024-05-02 01:34:25 +02:00
|
|
|
Thumbnails bool `yaml:"thumbnails"`
|
2024-05-01 20:08:25 +02:00
|
|
|
CommentsUrlTemplate string `yaml:"comments-url-template"`
|
|
|
|
Limit int `yaml:"limit"`
|
|
|
|
CollapseAfter int `yaml:"collapse-after"`
|
2024-04-27 21:10:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (widget *Reddit) Initialize() error {
|
|
|
|
if widget.Subreddit == "" {
|
|
|
|
return errors.New("no subreddit specified")
|
|
|
|
}
|
|
|
|
|
|
|
|
if widget.Limit <= 0 {
|
|
|
|
widget.Limit = 15
|
|
|
|
}
|
|
|
|
|
|
|
|
if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {
|
|
|
|
widget.CollapseAfter = 5
|
|
|
|
}
|
|
|
|
|
|
|
|
widget.withTitle("/r/" + widget.Subreddit).withCacheDuration(30 * time.Minute)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (widget *Reddit) Update(ctx context.Context) {
|
2024-05-01 20:08:25 +02:00
|
|
|
posts, err := feed.FetchSubredditPosts(widget.Subreddit, widget.CommentsUrlTemplate)
|
2024-04-27 21:10:24 +02:00
|
|
|
|
|
|
|
if !widget.canContinueUpdateAfterHandlingErr(err) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(posts) > widget.Limit {
|
|
|
|
posts = posts[:widget.Limit]
|
|
|
|
}
|
|
|
|
|
|
|
|
posts.SortByEngagement()
|
|
|
|
widget.Posts = posts
|
|
|
|
}
|
|
|
|
|
|
|
|
func (widget *Reddit) Render() template.HTML {
|
|
|
|
if widget.Style == "horizontal-cards" {
|
|
|
|
return widget.render(widget, assets.RedditCardsHorizontalTemplate)
|
|
|
|
}
|
|
|
|
|
|
|
|
if widget.Style == "vertical-cards" {
|
|
|
|
return widget.render(widget, assets.RedditCardsVerticalTemplate)
|
|
|
|
}
|
|
|
|
|
|
|
|
return widget.render(widget, assets.ForumPostsTemplate)
|
|
|
|
|
|
|
|
}
|