hacker-news.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package widget
  2. import (
  3. "context"
  4. "html/template"
  5. "time"
  6. "github.com/glanceapp/glance/internal/assets"
  7. "github.com/glanceapp/glance/internal/feed"
  8. )
  9. type HackerNews struct {
  10. widgetBase `yaml:",inline"`
  11. Posts feed.ForumPosts `yaml:"-"`
  12. Limit int `yaml:"limit"`
  13. SortBy string `yaml:"sort-by"`
  14. ExtraSortBy string `yaml:"extra-sort-by"`
  15. CollapseAfter int `yaml:"collapse-after"`
  16. CommentsUrlTemplate string `yaml:"comments-url-template"`
  17. ShowThumbnails bool `yaml:"-"`
  18. }
  19. func (widget *HackerNews) Initialize() error {
  20. widget.
  21. withTitle("Hacker News").
  22. withTitleURL("https://news.ycombinator.com/").
  23. withCacheDuration(30 * time.Minute)
  24. if widget.Limit <= 0 {
  25. widget.Limit = 15
  26. }
  27. if widget.CollapseAfter == 0 || widget.CollapseAfter < -1 {
  28. widget.CollapseAfter = 5
  29. }
  30. if widget.SortBy != "top" && widget.SortBy != "new" && widget.SortBy != "best" {
  31. widget.SortBy = "top"
  32. }
  33. return nil
  34. }
  35. func (widget *HackerNews) Update(ctx context.Context) {
  36. posts, err := feed.FetchHackerNewsPosts(widget.SortBy, 40, widget.CommentsUrlTemplate)
  37. if !widget.canContinueUpdateAfterHandlingErr(err) {
  38. return
  39. }
  40. if widget.ExtraSortBy == "engagement" {
  41. posts.CalculateEngagement()
  42. posts.SortByEngagement()
  43. }
  44. if widget.Limit < len(posts) {
  45. posts = posts[:widget.Limit]
  46. }
  47. widget.Posts = posts
  48. }
  49. func (widget *HackerNews) Render() template.HTML {
  50. return widget.render(widget, assets.ForumPostsTemplate)
  51. }