diff --git a/models/channels/ensure.go b/models/channels/ensure.go new file mode 100644 index 0000000..5eddef7 --- /dev/null +++ b/models/channels/ensure.go @@ -0,0 +1,33 @@ +package channels + +import ( + "strings" + + "github.com/globalsign/mgo" + + "git.aiterp.net/rpdata/api/models" +) + +// Ensure adds a channel if it doesn't exist. If logged is set and the found channel isn't logged, +// that is changed. +func Ensure(name string, logged bool) (models.Channel, error) { + if len(name) < 3 && !strings.HasPrefix(name, "#") { + return models.Channel{}, ErrInvalidName + } + + channel, err := FindName(name) + if err == mgo.ErrNotFound { + return Add(name, logged, false, "", "") + } else if err != nil { + return models.Channel{}, err + } + + if logged && !channel.Logged { + channel, err = Edit(channel, &logged, nil, nil, nil) + if err != nil { + return models.Channel{}, err + } + } + + return channel, nil +} diff --git a/models/logs/add.go b/models/logs/add.go index dd3dd81..bf077fb 100644 --- a/models/logs/add.go +++ b/models/logs/add.go @@ -6,8 +6,8 @@ import ( "time" "git.aiterp.net/rpdata/api/internal/counter" - "git.aiterp.net/rpdata/api/model/channel" "git.aiterp.net/rpdata/api/models" + "git.aiterp.net/rpdata/api/models/channels" "github.com/globalsign/mgo/bson" ) @@ -18,7 +18,7 @@ func Add(date time.Time, channelName, title, eventName, description string, open return models.Log{}, errors.New("Failed to allocate short ID: " + err.Error()) } - _, err = channel.Ensure(channelName, open) + _, err = channels.Ensure(channelName, open) if err != nil { return models.Log{}, errors.New("Failed to ensure channel: " + err.Error()) }