2024-04-09 14:30:54 +07:00
|
|
|
package routes
|
|
|
|
|
|
|
|
import (
|
2024-04-27 22:07:20 +07:00
|
|
|
"encoding/json"
|
2024-04-09 14:30:54 +07:00
|
|
|
"net/http"
|
2024-04-27 22:07:20 +07:00
|
|
|
"time"
|
2024-04-09 14:30:54 +07:00
|
|
|
|
2024-04-27 22:07:20 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/api"
|
|
|
|
"github.com/tigorlazuardi/redmage/pkg/errs"
|
2024-04-09 14:30:54 +07:00
|
|
|
"github.com/tigorlazuardi/redmage/pkg/log"
|
|
|
|
"github.com/tigorlazuardi/redmage/views"
|
|
|
|
"github.com/tigorlazuardi/redmage/views/homeview"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (routes *Routes) PageHome(rw http.ResponseWriter, r *http.Request) {
|
2024-04-13 00:15:31 +07:00
|
|
|
ctx, span := tracer.Start(r.Context(), "routes.PageHome")
|
|
|
|
defer span.End()
|
|
|
|
|
2024-04-09 14:30:54 +07:00
|
|
|
vc := views.NewContext(routes.Config, r)
|
2024-04-09 16:09:08 +07:00
|
|
|
|
2024-04-27 22:07:20 +07:00
|
|
|
listSubredditParams := parseSubredditListQuery(r)
|
2024-04-09 16:09:08 +07:00
|
|
|
|
2024-04-27 22:07:20 +07:00
|
|
|
list, err := routes.API.ListSubreddits(ctx, listSubredditParams)
|
2024-04-09 16:09:08 +07:00
|
|
|
if err != nil {
|
2024-04-27 22:07:20 +07:00
|
|
|
log.New(ctx).Err(err).Error("failed to list subreddits")
|
|
|
|
code, message := errs.HTTPMessage(err)
|
|
|
|
rw.WriteHeader(code)
|
|
|
|
_ = json.NewEncoder(rw).Encode(map[string]string{"error": message})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
imageListParams := api.ImageListParams{}
|
|
|
|
imageListParams.FillFromQuery(r.URL.Query())
|
2024-04-29 21:45:18 +07:00
|
|
|
if imageListParams.CreatedAt.IsZero() {
|
|
|
|
imageListParams.CreatedAt = time.Now().Add(-time.Hour * 24) // images in the last 24 hours
|
|
|
|
}
|
2024-04-28 22:00:56 +07:00
|
|
|
imageListParams.Limit = 0
|
2024-04-27 22:07:20 +07:00
|
|
|
|
|
|
|
imageList, err := routes.API.ImagesListWithDevicesAndSubreddits(ctx, imageListParams)
|
|
|
|
if err != nil {
|
|
|
|
log.New(ctx).Err(err).Error("failed to list subreddits")
|
|
|
|
code, message := errs.HTTPMessage(err)
|
2024-04-29 15:18:23 +07:00
|
|
|
data := homeview.Data{Error: message}
|
2024-04-27 22:07:20 +07:00
|
|
|
rw.WriteHeader(code)
|
2024-04-29 15:18:23 +07:00
|
|
|
if err := homeview.Home(vc, data).Render(ctx, rw); err != nil {
|
|
|
|
log.New(ctx).Err(err).Error("failed to render home view")
|
|
|
|
}
|
2024-04-27 22:07:20 +07:00
|
|
|
return
|
2024-04-09 16:09:08 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
data := homeview.Data{
|
2024-04-27 22:07:20 +07:00
|
|
|
SubredditsList: list,
|
2024-04-28 22:00:56 +07:00
|
|
|
RecentlyAddedImages: homeview.NewRecentlyAddedImages(imageList.Images),
|
2024-04-29 21:45:18 +07:00
|
|
|
Now: time.Now(),
|
|
|
|
TotalImages: imageList.Total,
|
2024-04-09 16:09:08 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
if err := homeview.Home(vc, data).Render(ctx, rw); err != nil {
|
2024-04-09 14:30:54 +07:00
|
|
|
log.New(ctx).Err(err).Error("failed to render home view")
|
|
|
|
}
|
|
|
|
}
|