databag/net/server/internal/api_setArticleSubject.go

81 lines
2.1 KiB
Go
Raw Normal View History

2022-02-14 05:36:29 +00:00
package databag
import (
"errors"
"net/http"
"gorm.io/gorm"
"github.com/gorilla/mux"
"databag/internal/store"
)
func SetArticleSubject(w http.ResponseWriter, r *http.Request) {
account, code, err := ParamAgentToken(r, false);
2022-02-14 05:36:29 +00:00
if err != nil {
ErrResponse(w, code, err)
return
}
// scan parameters
params := mux.Vars(r)
articleId := params["articleId"]
var subject Subject
if err := ParseRequest(r, w, &subject); err != nil {
ErrResponse(w, http.StatusBadRequest, err)
return
}
// load referenced article
var slot store.ArticleSlot
if err := store.DB.Preload("Article.Groups.Cards").Where("account_id = ? AND article_slot_id = ?", account.ID, articleId).First(&slot).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {
ErrResponse(w, http.StatusInternalServerError, err)
} else {
ErrResponse(w, http.StatusNotFound, err)
}
return
}
if slot.Article == nil {
ErrResponse(w, http.StatusNotFound, errors.New("article has been deleted"))
return
}
// determine affected contact list
2022-02-17 08:30:33 +00:00
cards := make(map[string]store.Card)
2022-02-14 05:36:29 +00:00
for _, group := range slot.Article.Groups {
for _, card := range group.Cards {
2022-02-17 08:30:33 +00:00
cards[card.Guid] = card
2022-02-14 05:36:29 +00:00
}
}
// save and update contact revision
err = store.DB.Transaction(func(tx *gorm.DB) error {
if res := tx.Model(&slot.Article).Update("data", subject.Data).Error; res != nil {
return res
}
if res := tx.Model(&slot.Article).Update("data_type", subject.DataType).Error; res != nil {
return res
}
if res := tx.Model(&slot).Update("revision", account.ArticleRevision + 1).Error; res != nil {
return res
}
if res := tx.Model(&account).Update("article_revision", account.ArticleRevision + 1).Error; res != nil {
return res
}
return nil
})
if err != nil {
ErrResponse(w, http.StatusInternalServerError, err)
return
}
// notify contacts of content change
SetStatus(account)
for _, card := range cards {
2022-02-17 08:30:33 +00:00
SetContactArticleNotification(account, &card)
2022-02-14 05:36:29 +00:00
}
2022-02-14 20:55:02 +00:00
WriteResponse(w, getArticleModel(&slot, true, true));
2022-02-14 05:36:29 +00:00
}