/
chat.go
117 lines (97 loc) · 2.41 KB
/
chat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package main
import (
"net/http"
"strings"
"github.com/bbhmakerlab/openinnovation/debug"
"github.com/bbhmakerlab/openinnovation/response"
"github.com/bbhmakerlab/openinnovation/store"
"github.com/gorilla/context"
)
func init() {
store.Notify = onNotify
}
// id/userID/channelID/channelType
func onNotify(channel, extra string) {
params := strings.Split(extra, "/")
if len(params) < 5 {
return
}
var parser store.Parser
id := parser.Int(params[1])
userID := parser.Int(params[2])
channelID := parser.Int(params[3])
channelType := params[4]
if parser.Err != nil {
return
}
notification := struct {
ID int64 `json:"id"`
UserID int64 `json:"userID"`
ChannelID int64 `json:"channelID"`
ChannelType string `json:"channelType"`
}{
ID: id,
UserID: userID,
ChannelID: channelID,
ChannelType: channelType,
}
switch channelType {
case "user":
h.notifyUser(userID, channelID, "newChatMessage", notification)
case "project":
h.notifyProject(channelID, "newChatMessage", notification)
}
}
func GetChats(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
response.ServerError(w, err)
return
}
var parser store.Parser
var startID int64
var count int64 = 10
if v, ok := r.Form["count"]; ok {
count = parser.Int(v[0])
}
if v, ok := r.Form["startID"]; ok {
startID = parser.Int(v[0])
}
channelID := parser.Int(r.FormValue("channelID"))
if parser.Err != nil {
response.ClientError(w, http.StatusBadRequest)
return
}
channelType := r.FormValue("channelType")
user := context.Get(r, "user").(store.User)
chats, err := store.GetChats(user.ID(), channelID, channelType, startID, count)
if err != nil {
response.ServerError(w, err)
return
}
response.OK(w, chats)
}
func PostChat(w http.ResponseWriter, r *http.Request) {
var parser store.Parser
userID := parser.Int(r.FormValue("userID"))
channelID := parser.Int(r.FormValue("channelID"))
if parser.Err != nil {
response.ClientError(w, http.StatusBadRequest)
return
}
chatParams := store.PostChatParams{
UserID: userID,
ChannelID: channelID,
ChannelType: r.FormValue("channelType"),
Text: r.FormValue("text"),
}
id, err := store.PostChat(chatParams)
if err != nil {
response.ServerError(w, err)
return
}
if err = store.NotifyChat(store.NotifyChatParams{id, chatParams}); err != nil {
debug.Warn(err)
return
}
response.OK(w, id)
}