Skip to content
This repository has been archived by the owner on Mar 28, 2023. It is now read-only.

Commit

Permalink
[#1571] Update chat endpoints to use repo.APITime
Browse files Browse the repository at this point in the history
Also:
- extract chat models into repo/chat_message.go
- make repo.APITime a struct that embeds a time to get free access to
  time.Time methods
  • Loading branch information
placer14 committed May 21, 2019
1 parent a525b6c commit e2fa05f
Show file tree
Hide file tree
Showing 11 changed files with 63 additions and 50 deletions.
4 changes: 2 additions & 2 deletions api/jsonapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -3285,13 +3285,13 @@ func (i *jsonAPIHandler) POSTBumpFee(w http.ResponseWriter, r *http.Request) {
ErrorResponse(w, http.StatusInternalServerError, err.Error())
return
}
t := repo.APITime(txn.Timestamp)
t := repo.NewAPITime(txn.Timestamp)
resp := &response{
Txid: newTxid.String(),
ConfirmedBalance: confirmed,
UnconfirmedBalance: unconfirmed,
Amount: -(txn.Value),
Timestamp: &t,
Timestamp: t,
Memo: fmt.Sprintf("Fee bump of %s", txid),
}
ser, err := json.MarshalIndent(resp, "", " ")
Expand Down
2 changes: 1 addition & 1 deletion api/jsonapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ func TestWallet(t *testing.T) {
{"GET", "/wallet/address", "", 200, walletAddressJSONResponse},
{"GET", "/wallet/balance", "", 200, walletBalanceJSONResponse},
{"GET", "/wallet/mnemonic", "", 200, walletMneumonicJSONResponse},
{"POST", "/wallet/spend/", spendJSON, 400, insuffientFundsJSON},
{"POST", "/wallet/spend", spendJSON, 400, insuffientFundsJSON},
// TODO: Test successful spend on regnet with coins
})
}
Expand Down
4 changes: 2 additions & 2 deletions net/service/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -1272,12 +1272,12 @@ func (service *OpenBazaarService) handleChat(p peer.ID, pmes *pb.Message, option
}

// Push to websocket
n := repo.ChatMessage{
n := repo.ChatMessageNotification{
MessageId: chat.MessageId,
PeerId: p.Pretty(),
Subject: chat.Subject,
Message: chat.Message,
Timestamp: t,
Timestamp: repo.NewAPITime(t),
}
service.broadcast <- n
log.Debugf("Received CHAT message from %s", p.Pretty())
Expand Down
16 changes: 12 additions & 4 deletions repo/api_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,23 @@ var ErrUnknownAPITimeFormat = errors.New("unknown api time format")

const JSONAPITimeFormat = `"2006-01-02T15:04:05.999999999Z07:00"` // time.RFC3339Nano

type APITime time.Time
type APITime struct {
time.Time
}

// NewAPITime returns a pointer to a new APITime instance
func NewAPITime(t time.Time) *APITime {
var val = APITime{t}
return &val
}

func (t APITime) MarshalJSON() ([]byte, error) {
return []byte(time.Time(t).Format(JSONAPITimeFormat)), nil
return []byte(t.Time.Format(JSONAPITimeFormat)), nil
}

func (t *APITime) UnmarshalJSON(b []byte) error {
if value, err := time.Parse(q(time.RFC3339), string(b)); err == nil {
*t = APITime(value)
*t = APITime{value}
return nil
}
return ErrUnknownAPITimeFormat
Expand All @@ -29,5 +37,5 @@ func q(format string) string {
}

func (t APITime) String() string {
return time.Time(t).String()
return t.Time.String()
}
12 changes: 6 additions & 6 deletions repo/api_time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ func TestAPITimeUnmarshalJSONSupportsRFC3339(t *testing.T) {
t.Logf("output: %s", string(marshaledExample))
t.Fatal(err)
}
if !when.Equal(time.Time(actual)) {
t.Errorf("expected (%s) to equal (%s), but did not when using format (%s)", time.Time(actual), when, format)
if !when.Equal(actual.Time) {
t.Errorf("expected (%s) to equal (%s), but did not when using format (%s)", actual.Time, when, format)
}
}

Expand All @@ -55,13 +55,13 @@ func TestAPITimeUnmarshalJSONSupportsRFC3339Nano(t *testing.T) {
t.Logf("output: %s", string(marshaledExample))
t.Fatal(err)
}
if !when.Equal(time.Time(actual)) {
t.Errorf("expected (%s) to equal (%s), but did not when using format (%s)", time.Time(actual), when, format)
if !when.Equal(actual.Time) {
t.Errorf("expected (%s) to equal (%s), but did not when using format (%s)", actual.Time, when, format)
}
}

func TestAPITimeMarshalIsReciprocal(t *testing.T) {
var when = repo.APITime(time.Now())
var when = repo.NewAPITime(time.Now())
subjectBytes, err := json.Marshal(&when)
if err != nil {
t.Fatal(err)
Expand All @@ -72,7 +72,7 @@ func TestAPITimeMarshalIsReciprocal(t *testing.T) {
t.Fatal(err)
}

if !time.Time(when).Equal(time.Time(actual)) {
if !when.Equal(actual.Time) {
t.Errorf("expected (%s) to equal (%s), but did not", actual, when)
}
}
25 changes: 25 additions & 0 deletions repo/chat_message.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package repo

type ChatMessage struct {
MessageId string `json:"messageId"`
PeerId string `json:"peerId"`
Subject string `json:"subject"`
Message string `json:"message"`
Read bool `json:"read"`
Outgoing bool `json:"outgoing"`
Timestamp *APITime `json:"timestamp"`
}

type ChatConversation struct {
PeerId string `json:"peerId"`
Unread int `json:"unread"`
Last string `json:"lastMessage"`
Timestamp *APITime `json:"timestamp"`
Outgoing bool `json:"outgoing"`
}

type GroupChatMessage struct {
PeerIds []string `json:"peerIds"`
Subject string `json:"subject"`
Message string `json:"message"`
}
5 changes: 2 additions & 3 deletions repo/db/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ func (c *ChatDB) GetConversations() []repo.ChatConversation {
if outInt > 0 {
outgoing = true
}
timestamp := time.Unix(0, ts)
timestamp := repo.NewAPITime(time.Unix(0, ts))
convo := repo.ChatConversation{
PeerId: peerId,
Unread: count,
Expand Down Expand Up @@ -142,7 +142,6 @@ func (c *ChatDB) GetMessages(peerID string, subject string, offsetId string, lim
message string
readInt int
timestampInt int64
timestamp time.Time
outgoingInt int
)
if err := rows.Scan(&msgID, &pid, &message, &readInt, &timestampInt, &outgoingInt); err != nil {
Expand All @@ -156,7 +155,7 @@ func (c *ChatDB) GetMessages(peerID string, subject string, offsetId string, lim
if outgoingInt == 1 {
outgoing = true
}
timestamp = time.Unix(0, timestampInt)
timestamp := repo.NewAPITime(time.Unix(0, timestampInt))
chatMessage := repo.ChatMessage{
PeerId: pid,
MessageId: msgID,
Expand Down
2 changes: 1 addition & 1 deletion repo/db/chat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,6 @@ func TestChatDB_DeterministicNanosecondOrdering_Issue1545(t *testing.T) {
t.Fatalf("expected the messages to return in decending timestamp order, but were not")
t.Logf("\tmessages recieved: %+v", messages)
}
latestTime = m.Timestamp
latestTime = m.Timestamp.Time
}
}
14 changes: 0 additions & 14 deletions repo/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,6 @@ type Coupon struct {
Hash string
}

type GroupChatMessage struct {
PeerIds []string `json:"peerIds"`
Subject string `json:"subject"`
Message string `json:"message"`
}

type ChatConversation struct {
PeerId string `json:"peerId"`
Unread int `json:"unread"`
Last string `json:"lastMessage"`
Timestamp time.Time `json:"timestamp"`
Outgoing bool `json:"outgoing"`
}

type Metadata struct {
Txid string
Address string
Expand Down
25 changes: 10 additions & 15 deletions repo/notification.go
Original file line number Diff line number Diff line change
Expand Up @@ -804,21 +804,16 @@ func (n StatusNotification) GetID() string { retur
func (n StatusNotification) GetType() NotificationType { return NotifierTypeStatusUpdateNotification }
func (n StatusNotification) GetSMTPTitleAndBody() (string, string, bool) { return "", "", false }

type ChatMessage struct {
MessageId string `json:"messageId"`
PeerId string `json:"peerId"`
Subject string `json:"subject"`
Message string `json:"message"`
Read bool `json:"read"`
Outgoing bool `json:"outgoing"`
Timestamp time.Time `json:"timestamp"`
}

func (n ChatMessage) Data() ([]byte, error) { return json.MarshalIndent(messageWrapper{n}, "", " ") }
func (n ChatMessage) WebsocketData() ([]byte, error) { return n.Data() }
func (n ChatMessage) GetID() string { return "" } // Not persisted, ID is ignored
func (n ChatMessage) GetType() NotificationType { return NotifierTypeChatMessage }
func (n ChatMessage) GetSMTPTitleAndBody() (string, string, bool) { return "", "", false }
// ChatMessageNotification handles serialization of ChatMessages for notifications
type ChatMessageNotification ChatMessage

func (n ChatMessageNotification) Data() ([]byte, error) {
return json.MarshalIndent(messageWrapper{n}, "", " ")
}
func (n ChatMessageNotification) WebsocketData() ([]byte, error) { return n.Data() }
func (n ChatMessageNotification) GetID() string { return "" } // Not persisted, ID is ignored
func (n ChatMessageNotification) GetType() NotificationType { return NotifierTypeChatMessage }
func (n ChatMessageNotification) GetSMTPTitleAndBody() (string, string, bool) { return "", "", false }

type ChatRead struct {
MessageId string `json:"messageId"`
Expand Down
4 changes: 2 additions & 2 deletions test/factory/api_time.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,6 @@ import (
"github.com/OpenBazaar/openbazaar-go/repo"
)

func NewAPITime(t time.Time) repo.APITime {
return repo.APITime(t)
func NewAPITime(t time.Time) *repo.APITime {
return repo.NewAPITime(t)
}

0 comments on commit e2fa05f

Please sign in to comment.