databag/net/server/internal/api_addChannel.go

86 lines
2.3 KiB
Go
Raw Normal View History

2022-02-15 22:30:04 +00:00
package databag
import (
"net/http"
"gorm.io/gorm"
"github.com/google/uuid"
"databag/internal/store"
)
func AddChannel(w http.ResponseWriter, r *http.Request) {
2022-04-06 21:02:18 +00:00
account, code, err := ParamAgentToken(r, false)
2022-02-15 22:30:04 +00:00
if err != nil {
ErrResponse(w, code, err)
return
}
2022-04-06 21:02:18 +00:00
var params ChannelParams
if err := ParseRequest(r, w, &params); err != nil {
2022-02-15 22:30:04 +00:00
ErrResponse(w, http.StatusBadRequest, err)
return
}
2022-04-06 21:02:18 +00:00
cards := []*store.Card{}
2022-02-15 22:30:04 +00:00
slot := &store.ChannelSlot{}
err = store.DB.Transaction(func(tx *gorm.DB) error {
channel := &store.Channel{}
channel.AccountID = account.ID
2022-04-06 21:02:18 +00:00
channel.Data = params.Data
channel.DataType = params.DataType
channel.DetailRevision = account.ChannelRevision + 1
channel.TopicRevision = account.ChannelRevision + 1
2022-02-15 22:30:04 +00:00
if res := tx.Save(channel).Error; res != nil {
return res
}
slot.ChannelSlotId = uuid.New().String()
slot.AccountID = account.ID
slot.ChannelID = channel.ID
slot.Revision = account.ChannelRevision + 1
slot.Channel = channel
if res := tx.Save(slot).Error; res != nil {
return res
}
2022-04-06 21:02:18 +00:00
for _, cardId := range params.Cards {
cardSlot := store.CardSlot{}
if res := tx.Preload("Card").Where("account_id = ? AND card_slot_id = ?", account.ID, cardId).First(&cardSlot).Error; res != nil {
return res
}
if res := tx.Model(&slot.Channel).Association("Cards").Append(cardSlot.Card); res != nil {
return res
}
cards = append(cards, cardSlot.Card);
}
for _, groupId := range params.Groups {
groupSlot := store.GroupSlot{}
if res := tx.Preload("Group").Where("account_id = ? AND group_slot_id = ?", account.ID, groupId).First(&groupSlot).Error; res != nil {
return res
}
if res := tx.Model(&slot.Channel).Association("Groups").Append(groupSlot.Group); res != nil {
return res
}
}
2022-02-15 22:30:04 +00:00
if res := tx.Model(&account).Update("channel_revision", account.ChannelRevision + 1).Error; res != nil {
return res
}
2022-04-06 21:02:18 +00:00
2022-02-15 22:30:04 +00:00
return nil
})
if err != nil {
ErrResponse(w, http.StatusInternalServerError, err)
return
}
SetStatus(account)
2022-04-06 21:02:18 +00:00
for _, card := range cards {
SetContactChannelNotification(account, card);
}
2022-02-15 22:30:04 +00:00
WriteResponse(w, getChannelModel(slot, true, true))
}