-
Notifications
You must be signed in to change notification settings - Fork 34
/
viber.go
225 lines (193 loc) · 5.49 KB
/
viber.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
package viber
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io/ioutil"
"log"
"net/http"
"regexp"
"strings"
"time"
)
// Sender structure
type Sender struct {
Name string `json:"name"`
Avatar string `json:"avatar,omitempty"`
}
type event struct {
Event string `json:"event"`
Timestamp Timestamp `json:"timestamp"`
MessageToken uint64 `json:"message_token,omitempty"`
UserID string `json:"user_id,omitempty"`
// failed event
Descr string `json:"descr,omitempty"`
//conversation_started event
Type string `json:"type,omitempty"`
Context string `json:"context,omitempty"`
Subscribed bool `json:"subscribed,omitempty"`
User json.RawMessage `json:"user,omitempty"`
// message event
Sender json.RawMessage `json:"sender,omitempty"`
Message json.RawMessage `json:"message,omitempty"`
}
// Viber app
type Viber struct {
AppKey string
Sender Sender
// event methods
ConversationStarted func(v *Viber, u User, conversationType, context string, subscribed bool, token uint64, t time.Time) Message
Message func(v *Viber, u User, m Message, token uint64, t time.Time)
Subscribed func(v *Viber, u User, token uint64, t time.Time)
Unsubscribed func(v *Viber, userID string, token uint64, t time.Time)
Delivered func(v *Viber, userID string, token uint64, t time.Time)
Seen func(v *Viber, userID string, token uint64, t time.Time)
Failed func(v *Viber, userID string, token uint64, descr string, t time.Time)
// client for sending messages
client *http.Client
}
var (
// Log errors, set to logger if you want to log package activities and errors
Log = log.New(ioutil.Discard, "Viber >>", 0)
regexpPeekMsgType = regexp.MustCompile("\"type\":\\s*\"([^\"]+)\"")
)
// New returns Viber app with specified app key and default sender
// You can also create *VIber{} struct directly
func New(appKey, senderName, senderAvatar string) *Viber {
return &Viber{
AppKey: appKey,
Sender: Sender{
Name: senderName,
Avatar: senderAvatar,
},
client: &http.Client{},
}
}
// ServeHTTP
// https://developers.viber.com/docs/api/rest-bot-api/#callbacks
func (v *Viber) ServeHTTP(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
r.Body.Close()
if err != nil {
Log.Println(err)
return
}
Log.Println("Received from Viber:", string(body))
if !v.checkHMAC(body, r.Header.Get("X-Viber-Content-Signature")) {
Log.Println("X-Viber-Content-Signature doesn't match")
return
}
var e event
if err := json.Unmarshal(body, &e); err != nil {
Log.Println(err)
return
}
switch e.Event {
case "subscribed":
if v.Subscribed != nil {
var u User
if err := json.Unmarshal(e.User, &u); err != nil {
Log.Println(err)
return
}
go v.Subscribed(v, u, e.MessageToken, e.Timestamp.Time)
}
case "unsubscribed":
if v.Unsubscribed != nil {
go v.Unsubscribed(v, e.UserID, e.MessageToken, e.Timestamp.Time)
}
case "conversation_started":
if v.ConversationStarted != nil {
var u User
if err := json.Unmarshal(e.User, &u); err != nil {
Log.Println(err)
return
}
if msg := v.ConversationStarted(v, u, e.Type, e.Context, e.Subscribed, e.MessageToken, e.Timestamp.Time); msg != nil {
msg.SetReceiver("")
msg.SetFrom("")
b, _ := json.Marshal(msg)
w.Write(b)
}
}
case "delivered":
if v.Delivered != nil {
go v.Delivered(v, e.UserID, e.MessageToken, e.Timestamp.Time)
}
case "seen":
if v.Seen != nil {
go v.Seen(v, e.UserID, e.MessageToken, e.Timestamp.Time)
}
case "failed":
if v.Failed != nil {
go v.Failed(v, e.UserID, e.MessageToken, e.Descr, e.Timestamp.Time)
}
case "message":
if v.Message != nil {
var u User
if err := json.Unmarshal(e.Sender, &u); err != nil {
Log.Println(err)
return
}
msgType := peakMessageType(e.Message)
switch msgType {
case "text":
var m TextMessage
if err := json.Unmarshal(e.Message, &m); err != nil {
Log.Println(err)
return
}
go v.Message(v, u, &m, e.MessageToken, e.Timestamp.Time)
case "picture":
var m PictureMessage
if err := json.Unmarshal(e.Message, &m); err != nil {
Log.Println(err)
return
}
go v.Message(v, u, &m, e.MessageToken, e.Timestamp.Time)
case "video":
var m VideoMessage
if err := json.Unmarshal(e.Message, &m); err != nil {
Log.Println(err)
return
}
go v.Message(v, u, &m, e.MessageToken, e.Timestamp.Time)
case "url":
var m URLMessage
if err := json.Unmarshal(e.Message, &m); err != nil {
Log.Println(err)
return
}
go v.Message(v, u, &m, e.MessageToken, e.Timestamp.Time)
case "contact":
// TODO
case "location":
// TODO
default:
return
}
}
}
}
// checkHMAC reports whether messageMAC is a valid HMAC tag for message.
func (v *Viber) checkHMAC(message []byte, messageMAC string) bool {
hmac := hmac.New(sha256.New, []byte(v.AppKey))
hmac.Write(message)
return messageMAC == hex.EncodeToString(hmac.Sum(nil))
}
// peakMessageType uses regexp to determin message type for unmarshaling
func peakMessageType(b []byte) string {
matches := regexpPeekMsgType.FindAllSubmatch(b, -1)
if len(matches) == 0 {
return ""
}
return strings.ToLower(string(matches[0][1]))
}
// SetRequestTimeout for sending messages to viber server
func (v *Viber) SetRequestTimeout(t time.Duration) {
if v.client == nil {
v.client = &http.Client{}
}
v.client.Timeout = t
}