databag/net/server/internal/api_setChannelCard.go

95 lines
2.7 KiB
Go
Raw Normal View History

2022-02-16 08:00:07 +00:00
package databag
import (
"errors"
"net/http"
"gorm.io/gorm"
"github.com/gorilla/mux"
"databag/internal/store"
)
func SetChannelCard(w http.ResponseWriter, r *http.Request) {
2022-05-24 22:21:12 +00:00
account, code, err := ParamAgentToken(r, false);
2022-02-16 08:00:07 +00:00
if err != nil {
ErrResponse(w, code, err)
return
}
// scan parameters
params := mux.Vars(r)
channelID := params["channelID"]
cardID := params["cardID"]
2022-02-16 08:00:07 +00:00
// load referenced channel
var channelSlot store.ChannelSlot
if err := store.DB.Preload("Channel.Cards.CardSlot").Preload("Channel.Groups.GroupSlot").Preload("Channel.Groups.Cards").Where("account_id = ? AND channel_slot_id = ?", account.ID, channelID).First(&channelSlot).Error; err != nil {
2022-02-16 08:00:07 +00:00
if !errors.Is(err, gorm.ErrRecordNotFound) {
ErrResponse(w, http.StatusInternalServerError, err)
} else {
ErrResponse(w, http.StatusNotFound, err)
}
return
}
if channelSlot.Channel == nil {
ErrResponse(w, http.StatusNotFound, errors.New("channel has been deleted"))
return
}
// load referenced card
var cardSlot store.CardSlot
if err := store.DB.Preload("Card.CardSlot").Where("account_id = ? AND card_slot_id = ?", account.ID, cardID).First(&cardSlot).Error; err != nil {
2022-02-16 08:00:07 +00:00
if !errors.Is(err, gorm.ErrRecordNotFound) {
ErrResponse(w, http.StatusInternalServerError, err)
} else {
ErrResponse(w, http.StatusNotFound, err)
}
return
}
if cardSlot.Card == nil {
ErrResponse(w, http.StatusNotFound, errors.New("card has been deleted"))
return
}
2022-02-17 08:30:33 +00:00
// determine contact list
cards := make(map[string]store.Card)
for _, card := range channelSlot.Channel.Cards {
cards[card.GUID] = card
2022-02-17 08:30:33 +00:00
}
for _, group := range channelSlot.Channel.Groups {
for _, card := range group.Cards {
cards[card.GUID] = card
2022-02-17 08:30:33 +00:00
}
}
cards[cardSlot.Card.GUID] = *cardSlot.Card
2022-02-17 08:30:33 +00:00
2022-02-16 08:00:07 +00:00
// save and update contact revision
err = store.DB.Transaction(func(tx *gorm.DB) error {
if res := tx.Model(&channelSlot.Channel).Association("Cards").Append(cardSlot.Card); res != nil {
return res
}
if res := tx.Model(&channelSlot.Channel).Update("detail_revision", account.ChannelRevision + 1).Error; res != nil {
return res
}
if res := tx.Model(&channelSlot).Update("revision", account.ChannelRevision + 1).Error; res != nil {
return res
}
if res := tx.Model(&account).Update("channel_revision", account.ChannelRevision + 1).Error; res != nil {
return res
}
return nil
})
if err != nil {
ErrResponse(w, http.StatusInternalServerError, err)
return
}
// notify contacts of content change
SetStatus(account)
2022-02-17 08:30:33 +00:00
for _, card := range cards {
2022-02-16 08:00:07 +00:00
SetContactChannelNotification(account, &card)
}
WriteResponse(w, getChannelModel(&channelSlot, true, true));
}