2021-12-18 21:02:47 -05:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-12-18 22:25:05 -05:00
|
|
|
"fmt"
|
2021-12-18 21:02:47 -05:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/uptrace/bun"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Message struct {
|
|
|
|
bun.BaseModel `bun:"table:messages"`
|
2021-12-19 01:14:25 -05:00
|
|
|
ID int `bun:",pk"`
|
|
|
|
Cookie uint64 `bun:",notnull"`
|
2021-12-18 21:02:47 -05:00
|
|
|
From string
|
|
|
|
To string
|
|
|
|
Contents string
|
2021-12-26 21:56:59 -05:00
|
|
|
StoreOffline bool
|
2021-12-18 21:02:47 -05:00
|
|
|
CreatedAt time.Time `bun:",nullzero,notnull,default:current_timestamp"`
|
|
|
|
DeliveredAt time.Time `bun:",nullzero"`
|
|
|
|
}
|
|
|
|
|
2021-12-19 01:14:25 -05:00
|
|
|
func InsertMessage(ctx context.Context, db *bun.DB, cookie uint64, from string, to string, contents string) (*Message, error) {
|
2021-12-18 21:02:47 -05:00
|
|
|
msg := &Message{
|
2021-12-26 21:56:59 -05:00
|
|
|
Cookie: cookie,
|
|
|
|
From: from,
|
|
|
|
To: to,
|
|
|
|
Contents: contents,
|
|
|
|
StoreOffline: true,
|
2021-12-18 21:02:47 -05:00
|
|
|
}
|
2021-12-18 22:25:05 -05:00
|
|
|
if _, err := db.NewInsert().Model(msg).Exec(ctx, msg); err != nil {
|
|
|
|
return nil, errors.Wrap(err, "could not update user")
|
|
|
|
}
|
|
|
|
|
|
|
|
return msg, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Message) String() string {
|
|
|
|
return fmt.Sprintf("<Message from=%s to=%s content=\"%s\">", m.From, m.To, m.Contents)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *Message) MarkDelivered(ctx context.Context, db *bun.DB) error {
|
|
|
|
m.DeliveredAt = time.Now()
|
2021-12-19 01:14:25 -05:00
|
|
|
if _, err := db.NewUpdate().Model(m).Where("cookie = ?", m.Cookie).Exec(ctx); err != nil {
|
2021-12-18 22:25:05 -05:00
|
|
|
return errors.Wrap(err, "could not mark message as updated")
|
2021-12-18 21:02:47 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|