108 lines
2.5 KiB
Go
Raw Normal View History

2017-11-22 10:51:59 +00:00
package calendar
import (
"sort"
"time"
"github.com/aerogo/aero"
"github.com/animenotifier/arn"
2018-04-08 10:59:36 +00:00
"github.com/animenotifier/arn/validate"
2017-11-22 10:51:59 +00:00
"github.com/animenotifier/notify.moe/components"
"github.com/animenotifier/notify.moe/utils"
)
var weekdayNames = []string{
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
}
// Get ...
func Get(ctx *aero.Context) string {
user := utils.GetUser(ctx)
oneWeek := 7 * 24 * time.Hour
now := time.Now()
year, month, day := now.Date()
now = time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
// Weekday index that we start with, Sunday is 0.
weekdayIndex := int(now.Weekday())
// Create days
days := make([]*utils.CalendarDay, 7, 7)
for i := 0; i < 7; i++ {
days[i] = &utils.CalendarDay{
Name: weekdayNames[(weekdayIndex+i)%7],
2017-12-03 18:08:05 +00:00
Class: "weekday",
2017-11-22 10:51:59 +00:00
Entries: []*utils.CalendarEntry{},
}
2017-12-03 18:08:05 +00:00
if days[i].Name == "Saturday" || days[i].Name == "Sunday" {
days[i].Class += " weekend"
}
2017-11-22 10:51:59 +00:00
}
// Add anime episodes to the days
for animeEpisodes := range arn.StreamAnimeEpisodes() {
if animeEpisodes.Anime().Status == "finished" {
continue
}
2017-11-22 10:51:59 +00:00
for _, episode := range animeEpisodes.Items {
2018-04-08 10:59:36 +00:00
if !validate.Date(episode.AiringDate.Start) {
2017-11-22 10:51:59 +00:00
continue
}
2017-11-22 12:04:01 +00:00
// Since we validated the date earlier, we can ignore the error value.
2017-11-22 10:51:59 +00:00
airingDate, _ := time.Parse(time.RFC3339, episode.AiringDate.Start)
2017-11-22 12:04:01 +00:00
// Subtract from the starting date offset.
2017-11-22 10:51:59 +00:00
since := airingDate.Sub(now)
2017-11-22 12:04:01 +00:00
// Ignore entries in the past and more than 1 week away.
2017-11-22 11:48:18 +00:00
if since < 0 || since >= oneWeek {
continue
}
dayIndex := int(since / (24 * time.Hour))
entry := &utils.CalendarEntry{
Anime: animeEpisodes.Anime(),
Episode: episode,
2017-12-03 18:08:05 +00:00
Added: false,
2017-11-22 10:51:59 +00:00
}
2017-11-22 11:48:18 +00:00
if user != nil {
animeListItem := user.AnimeList().Find(entry.Anime.ID)
if animeListItem != nil && (animeListItem.Status == arn.AnimeListStatusWatching || animeListItem.Status == arn.AnimeListStatusPlanned) {
2017-12-03 18:08:05 +00:00
entry.Added = true
2017-11-22 11:48:18 +00:00
}
}
days[dayIndex].Entries = append(days[dayIndex].Entries, entry)
2017-11-22 10:51:59 +00:00
}
}
for i := 0; i < 7; i++ {
sort.Slice(days[i].Entries, func(a, b int) bool {
airingA := days[i].Entries[a].Episode.AiringDate.Start
airingB := days[i].Entries[b].Episode.AiringDate.Start
if airingA == airingB {
return days[i].Entries[a].Anime.Title.Canonical < days[i].Entries[b].Anime.Title.Canonical
}
return airingA < airingB
})
}
return ctx.HTML(components.Calendar(days, user))
}