2024-04-27 21:10:24 +02:00
|
|
|
package widget
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"html/template"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/glanceapp/glance/internal/assets"
|
|
|
|
"github.com/glanceapp/glance/internal/feed"
|
|
|
|
)
|
|
|
|
|
|
|
|
type HackerNews struct {
|
2024-05-01 20:08:25 +02:00
|
|
|
widgetBase `yaml:",inline"`
|
|
|
|
Posts feed.ForumPosts `yaml:"-"`
|
|
|
|
Limit int `yaml:"limit"`
|
2024-05-10 15:08:01 +02:00
|
|
|
SortBy string `yaml:"sort-by"`
|
|
|
|
ExtraSortBy string `yaml:"extra-sort-by"`
|
2024-05-01 20:08:25 +02:00
|
|
|
CollapseAfter int `yaml:"collapse-after"`
|
|
|
|
CommentsUrlTemplate string `yaml:"comments-url-template"`
|
2024-05-02 19:45:15 +02:00
|
|
|
ShowThumbnails bool `yaml:"-"`
|
2024-04-27 21:10:24 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (widget *HackerNews) Initialize() error {
|
|
|
|
widget.withTitle("Hacker News").withCacheDuration(30 * time.Minute)
|
|
|
|
|
|
|
|
if widget.Limit <= 0 {
|
|
|
|
widget.Limit = 15
|
|
|
|
}
|
|
|
|
|
|
|
|
if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {
|
|
|
|
widget.CollapseAfter = 5
|
|
|
|
}
|
|
|
|
|
2024-05-10 15:08:01 +02:00
|
|
|
if widget.SortBy != "top" && widget.SortBy != "new" && widget.SortBy != "best" {
|
|
|
|
widget.SortBy = "top"
|
|
|
|
}
|
|
|
|
|
2024-04-27 21:10:24 +02:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (widget *HackerNews) Update(ctx context.Context) {
|
2024-05-10 15:08:01 +02:00
|
|
|
posts, err := feed.FetchHackerNewsPosts(widget.SortBy, 40, widget.CommentsUrlTemplate)
|
2024-04-27 21:10:24 +02:00
|
|
|
|
|
|
|
if !widget.canContinueUpdateAfterHandlingErr(err) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-05-10 15:08:01 +02:00
|
|
|
if widget.ExtraSortBy == "engagement" {
|
|
|
|
posts.CalculateEngagement()
|
|
|
|
posts.SortByEngagement()
|
|
|
|
}
|
2024-04-27 21:10:24 +02:00
|
|
|
|
|
|
|
if widget.Limit < len(posts) {
|
|
|
|
posts = posts[:widget.Limit]
|
|
|
|
}
|
|
|
|
|
|
|
|
widget.Posts = posts
|
|
|
|
}
|
|
|
|
|
|
|
|
func (widget *HackerNews) Render() template.HTML {
|
|
|
|
return widget.render(widget, assets.ForumPostsTemplate)
|
|
|
|
}
|