package hn import ( "net/http" "time" u "git.eeqj.de/sneak/goutil" "github.com/flosch/pongo2" "github.com/jinzhu/gorm" "github.com/labstack/echo" ) // RequestHandlerSet holds the dependencies shared by the HTTP handlers. type RequestHandlerSet struct { db *gorm.DB version string } // NewRequestHandlerSet builds a RequestHandlerSet for the given version and // database handle. func NewRequestHandlerSet(version string, db *gorm.DB) *RequestHandlerSet { rhs := new(RequestHandlerSet) rhs.db = db rhs.version = version return rhs } // exitRow is a story that has left the front page within the last 24h. type exitRow struct { Duration string DurationSecs uint URL string Title string HighestRank uint HNID uint Score uint TimeGone string TimeGoneSecs uint } // currentRow is a story currently on the front page. type currentRow struct { Duration string DurationSecs uint URL string Title string Score uint HighestRank uint HNID uint Rank uint } // exitedRows returns the stories that left the front page in the last 24h, // most recently departed first. func (r *RequestHandlerSet) exitedRows() []exitRow { last24h := time.Now().Add(time.Second * 86400 * -1) var fpi []HNFrontPage r.db.Where("disappeared is not ? and disappeared > ?", time.Time{}, last24h).Order("disappeared desc").Find(&fpi) rows := make([]exitRow, 0, len(fpi)) for _, item := range fpi { rows = append(rows, exitRow{ Duration: u.TimeDiffHuman(item.Disappeared, item.Appeared), DurationSecs: u.TimeDiffAbsSeconds(item.Disappeared, item.Appeared), URL: item.URL, HNID: item.HNID, Score: item.Score, Title: item.Title, HighestRank: item.HighestRank, TimeGone: u.TimeDiffHuman(time.Now(), item.Disappeared), TimeGoneSecs: u.TimeDiffAbsSeconds(time.Now(), item.Disappeared), }) } return rows } // currentRows returns the stories currently on the front page, best rank first. func (r *RequestHandlerSet) currentRows() []currentRow { var cur []HNFrontPage r.db.Where("disappeared is ?", time.Time{}).Order("rank asc").Find(&cur) rows := make([]currentRow, 0, len(cur)) for _, item := range cur { rows = append(rows, currentRow{ Duration: u.TimeDiffHuman(time.Now(), item.Appeared), DurationSecs: u.TimeDiffAbsSeconds(time.Now(), item.Appeared), URL: item.URL, HNID: item.HNID, Score: item.Score, Title: item.Title, HighestRank: item.HighestRank, Rank: item.Rank, }) } return rows } func (r *RequestHandlerSet) indexHandler(c echo.Context) error { tc := pongo2.Context{ "time": time.Now().UTC().Format(time.RFC3339Nano), "exits": r.exitedRows(), "current": r.currentRows(), "gitrev": r.version, } return c.Render(http.StatusOK, "index.html", tc) } func (r *RequestHandlerSet) aboutHandler(c echo.Context) error { tc := pongo2.Context{ "time": time.Now().UTC().Format(time.RFC3339Nano), "gitrev": r.version, } return c.Render(http.StatusOK, "about.html", tc) }