reddit.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package feed
  2. import (
  3. "fmt"
  4. "html"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "time"
  9. )
  10. type subredditResponseJson struct {
  11. Data struct {
  12. Children []struct {
  13. Data struct {
  14. Id string `json:"id"`
  15. Title string `json:"title"`
  16. Upvotes int `json:"ups"`
  17. Url string `json:"url"`
  18. Time float64 `json:"created"`
  19. CommentsCount int `json:"num_comments"`
  20. Domain string `json:"domain"`
  21. Permalink string `json:"permalink"`
  22. Stickied bool `json:"stickied"`
  23. Pinned bool `json:"pinned"`
  24. IsSelf bool `json:"is_self"`
  25. Thumbnail string `json:"thumbnail"`
  26. } `json:"data"`
  27. } `json:"children"`
  28. } `json:"data"`
  29. }
  30. func FetchSubredditPosts(subreddit string, commentsUrlTemplate string) (ForumPosts, error) {
  31. requestUrl := fmt.Sprintf("https://www.reddit.com/r/%s/hot.json", url.QueryEscape(subreddit))
  32. request, err := http.NewRequest("GET", requestUrl, nil)
  33. if err != nil {
  34. return nil, err
  35. }
  36. // Required to increase rate limit, otherwise Reddit randomly returns 429 even after just 2 requests
  37. addBrowserUserAgentHeader(request)
  38. responseJson, err := decodeJsonFromRequest[subredditResponseJson](defaultClient, request)
  39. if err != nil {
  40. return nil, err
  41. }
  42. if len(responseJson.Data.Children) == 0 {
  43. return nil, fmt.Errorf("no posts found")
  44. }
  45. posts := make(ForumPosts, 0, len(responseJson.Data.Children))
  46. for i := range responseJson.Data.Children {
  47. post := &responseJson.Data.Children[i].Data
  48. if post.Stickied || post.Pinned {
  49. continue
  50. }
  51. var commentsUrl string
  52. if commentsUrlTemplate == "" {
  53. commentsUrl = "https://www.reddit.com" + post.Permalink
  54. } else {
  55. commentsUrl = strings.ReplaceAll(commentsUrlTemplate, "{SUBREDDIT}", subreddit)
  56. commentsUrl = strings.ReplaceAll(commentsUrl, "{POST-ID}", post.Id)
  57. commentsUrl = strings.ReplaceAll(commentsUrl, "{POST-PATH}", strings.TrimLeft(post.Permalink, "/"))
  58. }
  59. forumPost := ForumPost{
  60. Title: html.UnescapeString(post.Title),
  61. DiscussionUrl: commentsUrl,
  62. TargetUrlDomain: post.Domain,
  63. CommentCount: post.CommentsCount,
  64. Score: post.Upvotes,
  65. TimePosted: time.Unix(int64(post.Time), 0),
  66. }
  67. if post.Thumbnail != "" && post.Thumbnail != "self" && post.Thumbnail != "default" {
  68. forumPost.ThumbnailUrl = post.Thumbnail
  69. }
  70. if !post.IsSelf {
  71. forumPost.TargetUrl = post.Url
  72. }
  73. posts = append(posts, forumPost)
  74. }
  75. posts.CalculateEngagement()
  76. return posts, nil
  77. }