rankingCalendar.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package core
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "time"
  7. "github.com/andybalholm/cascadia"
  8. "golang.org/x/net/html"
  9. "codeberg.org/vnpower/pixivfe/v2/session"
  10. )
  11. func get_weekday(n time.Weekday) int {
  12. switch n {
  13. case time.Sunday:
  14. return 1
  15. case time.Monday:
  16. return 2
  17. case time.Tuesday:
  18. return 3
  19. case time.Wednesday:
  20. return 4
  21. case time.Thursday:
  22. return 5
  23. case time.Friday:
  24. return 6
  25. case time.Saturday:
  26. return 7
  27. }
  28. return 0
  29. }
  30. var selector_img = cascadia.MustCompile("img")
  31. // note(@iacore):
  32. // so the funny thing about Pixiv is that they will return this month's data for a request of a future date
  33. // is it a bug or a feature?
  34. func GetRankingCalendar(r *http.Request, mode string, year, month int) (HTML, error) {
  35. token := session.GetPixivToken(r)
  36. URL := GetRankingCalendarURL(mode, year, month)
  37. resp, err := API_GET(r.Context(), URL, token)
  38. if err != nil {
  39. return "", err
  40. }
  41. // Use the html package to parse the response body from the request
  42. doc, err := html.Parse(strings.NewReader(resp.Body))
  43. if err != nil {
  44. return "", err
  45. }
  46. // Find and print all links on the web page
  47. var links []string
  48. for _, node := range cascadia.QueryAll(doc, selector_img) {
  49. for _, attr := range node.Attr {
  50. if attr.Key == "data-src" {
  51. // adds a new link entry when the attribute matches
  52. links = append(links, session.ProxyImageUrlNoEscape(r, attr.Val))
  53. }
  54. }
  55. }
  56. // now := r.Context().Time()
  57. // yearNow := now.Year()
  58. // monthNow := now.Month()
  59. lastMonth := time.Date(year, time.Month(month), 0, 0, 0, 0, 0, time.UTC)
  60. thisMonth := time.Date(year, time.Month(month+1), 0, 0, 0, 0, 0, time.UTC)
  61. renderString := ""
  62. for i := 0; i < get_weekday(lastMonth.Weekday()); i++ {
  63. renderString += "<div class=\"calendar-node calendar-node-empty\"></div>"
  64. }
  65. for i := 0; i < thisMonth.Day(); i++ {
  66. date := fmt.Sprintf("%d%02d%02d", year, month, i+1)
  67. if len(links) > i {
  68. renderString += fmt.Sprintf(`<a href="/ranking?mode=%s&date=%s"><div class="calendar-node"><img src="%s" alt="Day %d" /><span>%d</span></div></a>`, mode, date, links[i], i+1, i+1)
  69. } else {
  70. renderString += fmt.Sprintf(`<div class="calendar-node"><span>%d</span></div>`, i+1)
  71. }
  72. }
  73. return HTML(renderString), nil
  74. }