794 lines
24 KiB
Go
794 lines
24 KiB
Go
package article
|
|
|
|
import (
|
|
"RenewCMS/api/pkg/access"
|
|
"RenewCMS/api/pkg/apperr"
|
|
"RenewCMS/api/pkg/articleerr"
|
|
validator "RenewCMS/api/pkg/validator"
|
|
domain "RenewCMS/internal/domain/article"
|
|
"RenewCMS/internal/domain/author"
|
|
"RenewCMS/internal/domain/language"
|
|
"RenewCMS/internal/infrastructure/useCases"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"net/url"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
playground "github.com/go-playground/validator/v10"
|
|
)
|
|
|
|
type Handler struct {
|
|
createUseCase *useCases.CreateArticleUseCase
|
|
getUseCase *useCases.GetArticleUseCase
|
|
listUseCase *useCases.ListArticlesUseCase
|
|
deleteUseCase *useCases.DeleteArticleUseCase
|
|
updateUseCase *useCases.UpdateArticleUseCase
|
|
translationUseCase *useCases.CreateTranslationUseCase
|
|
describeUseCase *useCases.DescribeArticleUseCase
|
|
}
|
|
|
|
type PostArticle struct {
|
|
Title string `json:"title" validate:"required,min=3,max=200"`
|
|
Body string `json:"body"`
|
|
Lang *string `json:"lang"`
|
|
StoryID *uint32 `json:"story_id" validate:"omitempty,gte=1"`
|
|
SourceArticleID *uint32 `json:"source_article_id" validate:"omitempty,gte=1"`
|
|
Copy *bool `json:"copy"`
|
|
}
|
|
|
|
type PostTranslation struct {
|
|
Lang string `json:"lang" validate:"required"`
|
|
Title string `json:"title" validate:"required,min=3,max=200"`
|
|
SourceArticleID *uint32 `json:"source_article_id" validate:"omitempty,gte=1"`
|
|
Copy *bool `json:"copy" validate:"required"`
|
|
}
|
|
|
|
func NewHandler(create *useCases.CreateArticleUseCase, get *useCases.GetArticleUseCase, list *useCases.ListArticlesUseCase, delete *useCases.DeleteArticleUseCase, update *useCases.UpdateArticleUseCase, translation *useCases.CreateTranslationUseCase, describe *useCases.DescribeArticleUseCase) *Handler {
|
|
return &Handler{
|
|
createUseCase: create,
|
|
getUseCase: get,
|
|
listUseCase: list,
|
|
deleteUseCase: delete,
|
|
updateUseCase: update,
|
|
translationUseCase: translation,
|
|
describeUseCase: describe,
|
|
}
|
|
}
|
|
|
|
type baseArticleResponse struct {
|
|
ID uint32 `json:"id"`
|
|
Title string `json:"title"`
|
|
Body json.RawMessage `json:"body"`
|
|
BodyFormat domain.BodyFormat `json:"body_format"`
|
|
IsOnline bool `json:"is_online"`
|
|
SiteID uint32 `json:"site_id"`
|
|
CreatedBy *uint32 `json:"created_by,omitempty"`
|
|
Authors []author.Byline `json:"authors"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
Lang string `json:"lang"`
|
|
StoryID uint32 `json:"story_id"`
|
|
Revision uint32 `json:"revision"`
|
|
}
|
|
|
|
type articleResponse struct {
|
|
baseArticleResponse
|
|
Slug string `json:"slug"`
|
|
Excerpt string `json:"excerpt"`
|
|
SEOTitle string `json:"seo_title"`
|
|
SEODescription string `json:"seo_description"`
|
|
CoverImageID *uint32 `json:"cover_image_id"`
|
|
CoverImageAlt string `json:"cover_image_alt"`
|
|
SocialTitle string `json:"social_title"`
|
|
SocialDescription string `json:"social_description"`
|
|
SocialImageID *uint32 `json:"social_image_id"`
|
|
CanonicalURL string `json:"canonical_url"`
|
|
Noindex bool `json:"noindex"`
|
|
SEODismissed []string `json:"seo_dismissed"`
|
|
Capabilities []string `json:"capabilities"`
|
|
Translations []domain.Translation `json:"translations"`
|
|
Source *domain.Source `json:"source"`
|
|
}
|
|
|
|
type listItemResponse struct {
|
|
baseArticleResponse
|
|
Excerpt string `json:"excerpt"`
|
|
Slug string `json:"slug"`
|
|
SEOStatus string `json:"seo_status"`
|
|
SEOSuggestions int `json:"seo_suggestions"`
|
|
}
|
|
|
|
func creatorFor(article domain.Article, viewer access.Caller) *uint32 {
|
|
if viewer.UserID == 0 {
|
|
return nil
|
|
}
|
|
createdBy := article.CreatedBy
|
|
return &createdBy
|
|
}
|
|
|
|
func toBaseResponse(article domain.Article, format domain.BodyFormat, viewer access.Caller) (baseArticleResponse, error) {
|
|
body := json.RawMessage(article.Body)
|
|
if format != domain.BodyFormatJSON {
|
|
encoded, err := json.Marshal(article.Body)
|
|
if err != nil {
|
|
return baseArticleResponse{}, err
|
|
}
|
|
body = encoded
|
|
}
|
|
authors := article.Authors
|
|
if authors == nil {
|
|
authors = []author.Byline{}
|
|
}
|
|
return baseArticleResponse{
|
|
ID: article.ID,
|
|
Title: article.Title,
|
|
Body: body,
|
|
BodyFormat: format,
|
|
IsOnline: article.IsOnline,
|
|
SiteID: article.SiteID,
|
|
CreatedBy: creatorFor(article, viewer),
|
|
Authors: authors,
|
|
CreatedAt: article.CreatedAt,
|
|
UpdatedAt: article.UpdatedAt,
|
|
Lang: article.Lang,
|
|
StoryID: article.StoryID,
|
|
Revision: article.EditRevision,
|
|
}, nil
|
|
}
|
|
|
|
func toArticleResponse(article domain.Article, format domain.BodyFormat, viewer access.Caller, described useCases.ArticleContext) (articleResponse, error) {
|
|
base, err := toBaseResponse(article, format, viewer)
|
|
if err != nil {
|
|
return articleResponse{}, err
|
|
}
|
|
dismissed := article.SEODismissed
|
|
if dismissed == nil {
|
|
dismissed = []string{}
|
|
}
|
|
return articleResponse{
|
|
baseArticleResponse: base,
|
|
Slug: article.Slug,
|
|
Excerpt: article.Excerpt,
|
|
SEOTitle: article.SEOTitle,
|
|
SEODescription: article.SEODescription,
|
|
CoverImageID: article.CoverImageID,
|
|
CoverImageAlt: article.CoverImageAlt,
|
|
SocialTitle: article.SocialTitle,
|
|
SocialDescription: article.SocialDescription,
|
|
SocialImageID: article.SocialImageID,
|
|
CanonicalURL: article.CanonicalURL,
|
|
Noindex: article.Noindex,
|
|
SEODismissed: dismissed,
|
|
Capabilities: described.Capabilities,
|
|
Translations: described.Translations,
|
|
Source: described.Source,
|
|
}, nil
|
|
}
|
|
|
|
func toListItemResponse(article domain.Article, summary domain.SEOSummary, format domain.BodyFormat, viewer access.Caller) (listItemResponse, error) {
|
|
base, err := toBaseResponse(article, format, viewer)
|
|
if err != nil {
|
|
return listItemResponse{}, err
|
|
}
|
|
return listItemResponse{baseArticleResponse: base, Excerpt: article.Excerpt, Slug: article.Slug, SEOStatus: summary.Status, SEOSuggestions: summary.Suggestions}, nil
|
|
}
|
|
|
|
func encodeArticle(article domain.Article, format domain.BodyFormat, viewer access.Caller, described useCases.ArticleContext) ([]byte, error) {
|
|
response, err := toArticleResponse(article, format, viewer, described)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return json.Marshal(response)
|
|
}
|
|
|
|
func parseBodyFormat(w http.ResponseWriter, r *http.Request) (domain.BodyFormat, bool) {
|
|
format, err := domain.ParseBodyFormat(r.URL.Query().Get("format"))
|
|
if err != nil {
|
|
http.Error(w, apperr.ArticleBodyFormatErrorMessage, http.StatusBadRequest)
|
|
return "", false
|
|
}
|
|
return format, true
|
|
}
|
|
|
|
func parseArticleId(r *http.Request) (uint32, error) {
|
|
id, err := strconv.ParseUint(chi.URLParam(r, "id"), 10, 32)
|
|
return uint32(id), err
|
|
}
|
|
|
|
func (h *Handler) GetArticle(w http.ResponseWriter, r *http.Request) {
|
|
id, err := parseArticleId(r)
|
|
if err != nil {
|
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
article, err := h.getUseCase.GetArticle(id, format, access.CallerOf(r))
|
|
if err != nil {
|
|
writeArticleErrorResponse(w, err)
|
|
return
|
|
}
|
|
|
|
h.writeArticle(w, r, http.StatusOK, article, format, printToStdout)
|
|
}
|
|
|
|
func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
var localArticle PostArticle
|
|
if err := json.NewDecoder(r.Body).Decode(&localArticle); err != nil {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if err := validator.Validate.Struct(localArticle); err != nil {
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if localArticle.StoryID != nil {
|
|
h.postTranslation(w, r, format, localArticle)
|
|
return
|
|
}
|
|
if localArticle.SourceArticleID != nil || localArticle.Copy != nil {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
lang := ""
|
|
if localArticle.Lang != nil {
|
|
lang = *localArticle.Lang
|
|
}
|
|
createdArticle, err := h.createUseCase.CreateArticle(r.Context(), useCases.CreateArticleCommand{
|
|
Title: localArticle.Title,
|
|
Body: localArticle.Body,
|
|
Format: format,
|
|
Lang: lang,
|
|
Caller: access.CallerOf(r),
|
|
})
|
|
if err != nil {
|
|
if !writeKnownArticleError(w, err) {
|
|
http.Error(w, "Failed to create article", http.StatusInternalServerError)
|
|
}
|
|
return
|
|
}
|
|
|
|
h.writeArticle(w, r, http.StatusCreated, createdArticle, format, log.Printf)
|
|
}
|
|
|
|
func (h *Handler) postTranslation(w http.ResponseWriter, r *http.Request, format domain.BodyFormat, request PostArticle) {
|
|
if request.Lang == nil {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
h.createTranslation(w, r, useCases.CreateTranslationCommand{
|
|
StoryID: *request.StoryID,
|
|
Lang: *request.Lang,
|
|
Title: request.Title,
|
|
Copy: request.Copy,
|
|
SourceArticleID: request.SourceArticleID,
|
|
Format: format,
|
|
Caller: access.CallerOf(r),
|
|
})
|
|
}
|
|
|
|
func (h *Handler) PostTranslation(w http.ResponseWriter, r *http.Request) {
|
|
id, err := parseArticleId(r)
|
|
if err != nil {
|
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
var request PostTranslation
|
|
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
if err := validator.Validate.Struct(request); err != nil {
|
|
writeValidationError(w, err)
|
|
return
|
|
}
|
|
h.createTranslation(w, r, useCases.CreateTranslationCommand{
|
|
ArticleID: id,
|
|
Lang: request.Lang,
|
|
Title: request.Title,
|
|
Copy: request.Copy,
|
|
SourceArticleID: request.SourceArticleID,
|
|
Format: format,
|
|
Caller: access.CallerOf(r),
|
|
})
|
|
}
|
|
|
|
func (h *Handler) createTranslation(w http.ResponseWriter, r *http.Request, command useCases.CreateTranslationCommand) {
|
|
created, err := h.translationUseCase.CreateTranslation(r.Context(), command)
|
|
if err != nil {
|
|
writeArticleErrorResponse(w, err)
|
|
return
|
|
}
|
|
h.writeArticle(w, r, http.StatusCreated, created, command.Format, log.Printf)
|
|
}
|
|
|
|
func writeArticleErrorResponse(w http.ResponseWriter, err error) {
|
|
if !writeKnownArticleError(w, err) {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
}
|
|
}
|
|
|
|
func writeKnownArticleError(w http.ResponseWriter, err error) bool {
|
|
return access.WriteIfMissingPermission(w, err) || articleerr.Write(w, err)
|
|
}
|
|
|
|
var bodyMismatchFailures = map[string]string{
|
|
"Copy": "required",
|
|
"IfRevision": "min",
|
|
"AuthorIDs": "unique",
|
|
}
|
|
|
|
func writeValidationError(w http.ResponseWriter, err error) {
|
|
var failures playground.ValidationErrors
|
|
if errors.As(err, &failures) {
|
|
for _, failure := range failures {
|
|
if failure.Tag() == validator.ArticleSlugTag {
|
|
http.Error(w, apperr.InvalidSlugErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
}
|
|
if len(failures) > 0 && bodyMismatchFailures[failures[0].Field()] == failures[0].Tag() {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
}
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
}
|
|
|
|
func printToStdout(format string, args ...any) {
|
|
fmt.Printf(format, args...)
|
|
}
|
|
|
|
func (h *Handler) writeArticle(w http.ResponseWriter, r *http.Request, status int, article domain.Article, format domain.BodyFormat, reportFailure func(string, ...any)) {
|
|
caller := access.CallerOf(r)
|
|
described, err := h.describeUseCase.Describe(article, caller)
|
|
if err != nil {
|
|
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
articleJson, err := encodeArticle(article, format, caller, described)
|
|
if err != nil {
|
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
if status != http.StatusOK {
|
|
w.WriteHeader(status)
|
|
}
|
|
if _, err := w.Write(articleJson); err != nil {
|
|
reportFailure("Failed to write response: %v", err)
|
|
}
|
|
}
|
|
|
|
func (h *Handler) setIsOnline(w http.ResponseWriter, r *http.Request, isOnline bool) {
|
|
id, err := parseArticleId(r)
|
|
if err != nil {
|
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
updatedArticle, err := h.updateUseCase.UpdateIsOnline(r.Context(), id, access.CallerOf(r), isOnline, format)
|
|
if err != nil {
|
|
writeArticleErrorResponse(w, err)
|
|
return
|
|
}
|
|
|
|
h.writeArticle(w, r, http.StatusOK, updatedArticle, format, log.Printf)
|
|
}
|
|
|
|
type optionalImageID struct {
|
|
Set bool
|
|
Value *uint32 `validate:"omitempty,gte=1"`
|
|
}
|
|
|
|
func (o *optionalImageID) UnmarshalJSON(data []byte) error {
|
|
o.Set = true
|
|
if string(data) == "null" {
|
|
o.Value = nil
|
|
return nil
|
|
}
|
|
var value uint32
|
|
if err := json.Unmarshal(data, &value); err != nil {
|
|
return err
|
|
}
|
|
o.Value = &value
|
|
return nil
|
|
}
|
|
|
|
func (o optionalImageID) toNullable() domain.Nullable[uint32] {
|
|
return domain.Nullable[uint32]{Set: o.Set, Value: o.Value}
|
|
}
|
|
|
|
type UpdateArticleBody struct {
|
|
Title *string `json:"title"`
|
|
IfRevision *uint32 `json:"if_revision" validate:"omitempty,min=1"`
|
|
Body *string `json:"body"`
|
|
SiteID *uint32 `json:"site_id" validate:"omitempty,gte=1"`
|
|
AuthorIDs *[]uint32 `json:"author_ids" validate:"omitempty,unique,dive,gte=1"`
|
|
Slug *string `json:"slug" validate:"omitempty,articleslug"`
|
|
Excerpt *string `json:"excerpt" validate:"omitempty,max=300"`
|
|
SEOTitle *string `json:"seo_title" validate:"omitempty,max=120"`
|
|
SEODescription *string `json:"seo_description" validate:"omitempty,max=320"`
|
|
CoverImageID optionalImageID `json:"cover_image_id"`
|
|
CoverImageAlt *string `json:"cover_image_alt" validate:"omitempty,max=200"`
|
|
SocialTitle *string `json:"social_title" validate:"omitempty,max=120"`
|
|
SocialDescription *string `json:"social_description" validate:"omitempty,max=320"`
|
|
SocialImageID optionalImageID `json:"social_image_id"`
|
|
CanonicalURL *string `json:"canonical_url" validate:"omitempty,max=2048"`
|
|
Noindex *bool `json:"noindex"`
|
|
SEODismissed *[]string `json:"seo_dismissed" validate:"omitempty,dive,seodismissed"`
|
|
}
|
|
|
|
var nonNullableArticleFields = []string{"title", "body", "site_id", "author_ids", "slug", "excerpt", "seo_title", "seo_description", "cover_image_alt", "social_title", "social_description", "canonical_url", "noindex", "seo_dismissed"}
|
|
|
|
var nullableArticleFields = []string{"cover_image_id", "social_image_id"}
|
|
|
|
func countKnownFields(fields map[string]json.RawMessage, nonNullable []string) (int, bool) {
|
|
known := 0
|
|
for name, value := range fields {
|
|
switch {
|
|
case slices.Contains(nonNullable, name):
|
|
if string(value) == "null" {
|
|
return 0, false
|
|
}
|
|
known++
|
|
case slices.Contains(nullableArticleFields, name):
|
|
known++
|
|
}
|
|
}
|
|
return known, true
|
|
}
|
|
|
|
func readUpdateArticleBody(r *http.Request) (UpdateArticleBody, bool) {
|
|
raw, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
return UpdateArticleBody{}, false
|
|
}
|
|
var fields map[string]json.RawMessage
|
|
if err := json.Unmarshal(raw, &fields); err != nil {
|
|
return UpdateArticleBody{}, false
|
|
}
|
|
known, ok := countKnownFields(fields, nonNullableArticleFields)
|
|
if !ok || known == 0 || string(fields["if_revision"]) == "null" {
|
|
return UpdateArticleBody{}, false
|
|
}
|
|
var request UpdateArticleBody
|
|
if err := json.Unmarshal(raw, &request); err != nil {
|
|
return UpdateArticleBody{}, false
|
|
}
|
|
return request, true
|
|
}
|
|
|
|
func (h *Handler) UpdateArticleBody(w http.ResponseWriter, r *http.Request) {
|
|
id, err := parseArticleId(r)
|
|
if err != nil {
|
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
request, ok := readUpdateArticleBody(r)
|
|
if !ok {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if err := validator.Validate.Struct(request); err != nil {
|
|
writeValidationError(w, err)
|
|
return
|
|
}
|
|
|
|
updatedArticle, err := h.updateUseCase.Update(r.Context(), id, access.CallerOf(r), useCases.UpdateArticleCommand{
|
|
Title: request.Title,
|
|
IfRevision: request.IfRevision,
|
|
Body: request.Body,
|
|
SiteID: request.SiteID,
|
|
AuthorIDs: request.AuthorIDs,
|
|
Slug: request.Slug,
|
|
Excerpt: request.Excerpt,
|
|
SEOTitle: request.SEOTitle,
|
|
SEODescription: request.SEODescription,
|
|
CoverImageID: request.CoverImageID.toNullable(),
|
|
CoverImageAlt: request.CoverImageAlt,
|
|
SocialTitle: request.SocialTitle,
|
|
SocialDescription: request.SocialDescription,
|
|
SocialImageID: request.SocialImageID.toNullable(),
|
|
CanonicalURL: request.CanonicalURL,
|
|
Noindex: request.Noindex,
|
|
SEODismissed: request.SEODismissed,
|
|
Format: format,
|
|
})
|
|
if err != nil {
|
|
writeArticleErrorResponse(w, err)
|
|
return
|
|
}
|
|
|
|
h.writeArticle(w, r, http.StatusOK, updatedArticle, format, log.Printf)
|
|
}
|
|
|
|
func (h *Handler) PublishArticle(w http.ResponseWriter, r *http.Request) {
|
|
h.setIsOnline(w, r, true)
|
|
}
|
|
|
|
func (h *Handler) UnpublishArticle(w http.ResponseWriter, r *http.Request) {
|
|
h.setIsOnline(w, r, false)
|
|
}
|
|
|
|
const (
|
|
defaultListPage = 1
|
|
defaultListSize = 25
|
|
)
|
|
|
|
type listQuery struct {
|
|
Page int `validate:"gte=1"`
|
|
Size int `validate:"oneof=5 25 50 100"`
|
|
Q string `validate:"max=200"`
|
|
Status string `validate:"omitempty,oneof=online draft"`
|
|
Site *string `validate:"omitempty,min=1"`
|
|
SEO string `validate:"omitempty,oneof=ready suggestions hidden"`
|
|
Sort string `validate:"oneof=title:asc title:desc status:asc status:desc created_at:asc created_at:desc updated_at:asc updated_at:desc"`
|
|
Group *string `validate:"required_if=Tab missing,omitempty,eq=story"`
|
|
Tab *string `validate:"omitempty,oneof=all missing"`
|
|
Lang *string `validate:"omitempty,min=1"`
|
|
Author *uint32 `validate:"omitempty,gte=1"`
|
|
}
|
|
|
|
const groupByStory = "story"
|
|
|
|
type storyItemResponse struct {
|
|
listItemResponse
|
|
StoryUpdatedAt time.Time `json:"story_updated_at"`
|
|
StoryAuthors []author.Byline `json:"story_authors"`
|
|
Coverage []domain.Translation `json:"coverage"`
|
|
MissingLangs []string `json:"missing_langs"`
|
|
Capabilities []string `json:"capabilities"`
|
|
}
|
|
|
|
type storyListResponse struct {
|
|
Items []storyItemResponse `json:"items"`
|
|
Total int `json:"total"`
|
|
Page int `json:"page"`
|
|
Size int `json:"size"`
|
|
Counts domain.StoryCounts `json:"counts"`
|
|
}
|
|
|
|
const defaultListSort = "updated_at:desc"
|
|
|
|
func parseSort(value string) domain.Sort {
|
|
field, direction, _ := strings.Cut(value, ":")
|
|
return domain.Sort{Field: domain.SortField(field), Direction: domain.SortDirection(direction)}
|
|
}
|
|
|
|
type listResponse struct {
|
|
Items []listItemResponse `json:"items"`
|
|
Total int `json:"total"`
|
|
Page int `json:"page"`
|
|
Size int `json:"size"`
|
|
Counts domain.Counts `json:"counts"`
|
|
}
|
|
|
|
func intQueryParam(values url.Values, name string, fallback int) (int, error) {
|
|
if !values.Has(name) {
|
|
return fallback, nil
|
|
}
|
|
return strconv.Atoi(values.Get(name))
|
|
}
|
|
|
|
func readListQuery(values url.Values) (listQuery, error) {
|
|
page, err := intQueryParam(values, "page", defaultListPage)
|
|
if err != nil {
|
|
return listQuery{}, err
|
|
}
|
|
size, err := intQueryParam(values, "size", defaultListSize)
|
|
if err != nil {
|
|
return listQuery{}, err
|
|
}
|
|
status := values.Get("status")
|
|
if values.Has("status") && status == "" {
|
|
return listQuery{}, errors.New("empty status")
|
|
}
|
|
sortValue := defaultListSort
|
|
if values.Has("sort") {
|
|
sortValue = values.Get("sort")
|
|
}
|
|
var siteKey *string
|
|
if values.Has("site") {
|
|
key := values.Get("site")
|
|
if key == "" {
|
|
return listQuery{}, errors.New("empty site")
|
|
}
|
|
siteKey = &key
|
|
}
|
|
seoStatus := values.Get("seo")
|
|
if values.Has("seo") && seoStatus == "" {
|
|
return listQuery{}, errors.New("empty seo")
|
|
}
|
|
query := listQuery{Page: page, Size: size, Q: values.Get("q"), Status: status, Sort: sortValue, Site: siteKey, SEO: seoStatus}
|
|
if err := readLocalizedQuery(values, &query); err != nil {
|
|
return listQuery{}, err
|
|
}
|
|
return query, nil
|
|
}
|
|
|
|
func readLocalizedQuery(values url.Values, query *listQuery) error {
|
|
if values.Has("group") {
|
|
group := values.Get("group")
|
|
query.Group = &group
|
|
}
|
|
if values.Has("tab") {
|
|
tab := values.Get("tab")
|
|
query.Tab = &tab
|
|
}
|
|
if values.Has("lang") {
|
|
tag, err := language.Normalize(values.Get("lang"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
query.Lang = &tag
|
|
}
|
|
if values.Has("author") {
|
|
id, err := strconv.ParseUint(values.Get("author"), 10, 32)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
authorID := uint32(id)
|
|
query.Author = &authorID
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
|
|
format, ok := parseBodyFormat(w, r)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
query, err := readListQuery(r.URL.Query())
|
|
if err != nil || validator.Validate.Struct(query) != nil || query.Group != nil && access.CallerOf(r).UserID == 0 {
|
|
http.Error(w, apperr.BodyErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if stringOrEmpty(query.Group) == groupByStory {
|
|
h.listStories(w, r, format, query)
|
|
return
|
|
}
|
|
|
|
page, err := h.listUseCase.ListArticlesPage(useCases.ListArticlesCommand{
|
|
Format: format,
|
|
Caller: access.CallerOf(r),
|
|
Lang: query.Lang,
|
|
Author: query.Author,
|
|
Page: query.Page,
|
|
Size: query.Size,
|
|
Q: query.Q,
|
|
Status: query.Status,
|
|
Sort: parseSort(query.Sort),
|
|
SiteKey: query.Site,
|
|
SEO: query.SEO,
|
|
})
|
|
if err != nil {
|
|
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
responses := make([]listItemResponse, 0, len(page.Items))
|
|
for _, article := range page.Items {
|
|
response, err := toListItemResponse(article, page.SEO[article.ID], format, access.CallerOf(r))
|
|
if err != nil {
|
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
responses = append(responses, response)
|
|
}
|
|
|
|
writeListJSON(w, listResponse{Items: responses, Total: page.Total, Page: page.Page, Size: page.Size, Counts: page.Counts})
|
|
}
|
|
|
|
func writeListJSON(w http.ResponseWriter, payload any) {
|
|
body, err := json.Marshal(payload)
|
|
if err != nil {
|
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
if _, err := w.Write(body); err != nil {
|
|
log.Printf("Failed to write response: %v", err)
|
|
}
|
|
}
|
|
|
|
func (h *Handler) listStories(w http.ResponseWriter, r *http.Request, format domain.BodyFormat, query listQuery) {
|
|
caller := access.CallerOf(r)
|
|
page, err := h.listUseCase.ListStoriesPage(useCases.ListStoriesCommand{
|
|
Format: format,
|
|
Caller: caller,
|
|
Page: query.Page,
|
|
Size: query.Size,
|
|
Q: query.Q,
|
|
Status: query.Status,
|
|
Sort: parseSort(query.Sort),
|
|
SiteKey: query.Site,
|
|
SEO: query.SEO,
|
|
Lang: stringOrEmpty(query.Lang),
|
|
Tab: stringOrEmpty(query.Tab),
|
|
Author: query.Author,
|
|
})
|
|
if err != nil {
|
|
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
responses := make([]storyItemResponse, 0, len(page.Rows))
|
|
for _, row := range page.Rows {
|
|
item, err := toListItemResponse(row.Article, row.SEO, format, caller)
|
|
if err != nil {
|
|
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
responses = append(responses, storyItemResponse{
|
|
listItemResponse: item,
|
|
StoryUpdatedAt: row.UpdatedAt,
|
|
StoryAuthors: row.Authors,
|
|
Coverage: row.Coverage,
|
|
MissingLangs: row.MissingLangs,
|
|
Capabilities: row.Capabilities,
|
|
})
|
|
}
|
|
writeListJSON(w, storyListResponse{Items: responses, Total: page.Total, Page: page.Page, Size: page.Size, Counts: page.Counts})
|
|
}
|
|
|
|
func stringOrEmpty(value *string) string {
|
|
if value == nil {
|
|
return ""
|
|
}
|
|
return *value
|
|
}
|
|
|
|
func (h *Handler) DeleteArticle(w http.ResponseWriter, r *http.Request) {
|
|
id, err := parseArticleId(r)
|
|
if err != nil {
|
|
http.Error(w, apperr.IdUint32ErrorMessage, http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if err := h.deleteUseCase.DeleteArticle(r.Context(), id, access.CallerOf(r)); err != nil {
|
|
if !writeKnownArticleError(w, err) {
|
|
http.Error(w, "Failed to delete article", http.StatusInternalServerError)
|
|
}
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|