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 (
2022-07-22 19:28:14 +00:00
"databag/internal/store"
"errors"
"github.com/gorilla/mux"
"gorm.io/gorm"
"net/http"
2022-02-14 05:36:29 +00:00
)
2022-07-29 21:50:40 +00:00
//SetArticleSubject updates the subject of specified article in account
2022-02-14 05:36:29 +00:00
func SetArticleSubject(w http.ResponseWriter, r *http.Request) {
2022-07-22 19:28:14 +00:00
account, code, err := ParamAgentToken(r, false)
if err != nil {
ErrResponse(w, code, err)
return
}
2022-02-14 05:36:29 +00:00
2022-07-22 19:28:14 +00:00
// scan parameters
params := mux.Vars(r)
articleID := params["articleID"]
2022-02-14 05:36:29 +00:00
2022-07-22 19:28:14 +00:00
var subject Subject
if err := ParseRequest(r, w, &subject); err != nil {
ErrResponse(w, http.StatusBadRequest, err)
return
}
2022-02-14 05:36:29 +00:00
2022-07-22 19:28:14 +00:00
// 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
}
2022-02-14 05:36:29 +00:00
2022-07-22 19:28:14 +00:00
// determine affected contact list
cards := make(map[string]store.Card)
for _, group := range slot.Article.Groups {
for _, card := range group.Cards {
cards[card.GUID] = card
}
}
2022-02-14 05:36:29 +00:00
2022-07-22 19:28:14 +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
}
2022-02-14 05:36:29 +00:00
2022-07-22 19:28:14 +00:00
// notify contacts of content change
SetStatus(account)
for _, card := range cards {
SetContactArticleNotification(account, &card)
}
WriteResponse(w, getArticleModel(&slot, true, true))
2022-02-14 05:36:29 +00:00
}