-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathapi.go
359 lines (316 loc) · 8.77 KB
/
api.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package mitake
import (
"bufio"
"context"
"fmt"
"io"
"net/url"
"regexp"
"strconv"
"strings"
)
type MessageParams struct {
Encoding string // The encoding of the message body
ObjectID string // Name fo the batch
HideDeductedPoints bool // Set to true to hide the points deducted per SMS in the response
Message
}
func (p MessageParams) Validate() error {
if p.Dstaddr == "" {
return &ParameterError{Reason: "empty Dstaddr"}
}
if p.Smbody == "" {
return &ParameterError{Reason: "empty Smbody"}
}
return nil
}
// ToData converts the message to url.Values for sending.
func (p MessageParams) ToData() url.Values {
data := url.Values{}
data.Set("dstaddr", p.Dstaddr)
if p.Destname != "" {
data.Set("destname", p.Destname)
}
if p.Dlvtime != "" {
data.Set("dlvtime", p.Dlvtime)
}
if p.Vldtime != "" {
data.Set("vldtime", p.Vldtime)
}
data.Set("smbody", p.Smbody)
if p.Response != "" {
data.Set("response", p.Response)
}
if p.ClientID != "" {
data.Set("clientid", p.ClientID)
}
if p.ObjectID != "" {
data.Set("objectID", p.ObjectID)
}
if !p.HideDeductedPoints {
data.Set("smsPointFlag", "1")
}
return data
}
// Send sends a SMS.
func (c *Client) Send(ctx context.Context, params MessageParams) (*MessageResponse, error) {
if err := params.Validate(); err != nil {
return nil, err
}
u, _ := url.Parse("b2c/mtk/SmSend")
u.RawQuery = c.buildSendQuery(params).Encode()
data := c.buildSendFormData(params)
resp, err := c.Post(ctx, u.String(), "application/x-www-form-urlencoded", strings.NewReader(data.Encode()))
if err != nil {
return nil, err
}
defer resp.Body.Close()
return parseMessageResponse(resp.Body)
}
func (c *Client) buildSendQuery(params MessageParams) url.Values {
encoding := defaultEncoding
if params.Encoding != "" {
encoding = params.Encoding
}
q := url.Values{}
q.Set("CharsetURL", encoding)
return q
}
func (c *Client) buildSendFormData(params MessageParams) url.Values {
data := params.ToData()
data.Set("username", c.username)
data.Set("password", c.password)
return data
}
type BatchMessagesParams struct {
Encoding string `json:"Encoding_postIn"` // The encoding of the message body
ObjectID string `json:"objectID"` // Name fo the batch
HideDeductedPoints bool // Set to true to hide the points deducted per SMS in the response
Messages []Message
}
func (p BatchMessagesParams) Validate() error {
if len(p.Messages) == 0 {
return &ParameterError{Reason: "empty messages"}
}
for i, message := range p.Messages {
if message.ClientID == "" {
return &ParameterError{Reason: fmt.Sprintf("%d: empty ClientID", i)}
}
if message.Dstaddr == "" {
return &ParameterError{Reason: fmt.Sprintf("%d: [%s] empty Dstaddr", i, message.ClientID)}
}
if message.Smbody == "" {
return &ParameterError{Reason: fmt.Sprintf("%d: [%s] empty Smbody", i, message.ClientID)}
}
}
return nil
}
func (p BatchMessagesParams) ToData() string {
var data string
for _, message := range p.Messages {
data += fmt.Sprintf("%s$$%s$$%s$$%s$$%s$$%s$$%s\r\n",
message.ClientID,
message.Dstaddr,
message.Dlvtime,
message.Vldtime,
message.Destname,
message.Response,
message.Smbody,
)
}
return data
}
// SendBatch sends multiple SMS.
func (c *Client) SendBatch(ctx context.Context, opts BatchMessagesParams) (*MessageResponse, error) {
if err := opts.Validate(); err != nil {
return nil, err
}
u, _ := url.Parse("b2c/mtk/SmBulkSend")
u.RawQuery = c.buildSendBatchQuery(opts).Encode()
data := opts.ToData()
resp, err := c.Post(ctx, u.String(), "application/x-www-form-urlencoded", strings.NewReader(data))
if err != nil {
return nil, err
}
defer resp.Body.Close()
return parseMessageResponse(resp.Body)
}
func (c *Client) buildSendBatchQuery(opts BatchMessagesParams) url.Values {
encoding := defaultEncoding
if opts.Encoding != "" {
encoding = opts.Encoding
}
q := url.Values{}
q.Set("username", c.username)
q.Set("password", c.password)
q.Set("Encoding_PostIn", encoding)
if opts.ObjectID != "" {
q.Set("objectID", opts.ObjectID)
}
if !opts.HideDeductedPoints {
q.Set("smsPointFlag", "1")
}
return q
}
// MessageResult represents result of send SMS.
type MessageResult struct {
Msgid string
StatusCode StatusCode
SmsPoint *int // Points deducted per SMS, only available when SmsPointFlag is set
}
// MessageResponse represents response of send SMS.
type MessageResponse struct {
Results []*MessageResult
AccountPoint int // The available balance after this send
Duplicate *string // `Y` if the message is duplicated
}
func parseMessageResponse(body io.Reader) (*MessageResponse, error) {
var (
scanner = bufio.NewScanner(body)
re = regexp.MustCompile(`^\[(.+?)]$`)
response = new(MessageResponse)
result *MessageResult
)
for scanner.Scan() {
text := strings.TrimSpace(scanner.Text())
if matched := re.MatchString(text); matched {
result = new(MessageResult)
response.Results = append(response.Results, result)
} else {
if result == nil {
return nil, &UnexpectedResponseError{Reason: "no clientid"}
}
s := strings.Split(text, "=")
if len(s) != 2 {
return nil, &UnexpectedResponseError{Reason: "invalid key value pair"}
}
switch s[0] {
case "msgid":
result.Msgid = s[1]
case "statuscode":
result.StatusCode = StatusCode(s[1])
case "smsPoint":
point, _ := strconv.Atoi(s[1])
result.SmsPoint = Ptr(point)
case "AccountPoint":
response.AccountPoint, _ = strconv.Atoi(s[1])
case "Duplicate":
response.Duplicate = Ptr(s[1])
}
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
if result == nil {
return nil, &UnexpectedResponseError{Reason: "invalid response"}
}
return response, nil
}
// MessageStatusParams represents parameters of query message status.
type MessageStatusParams struct {
MessageIDs []string
HideDeductedPoints bool
}
// MessageStatus represents status of message.
type MessageStatus struct {
MessageResult
StatusTime string
}
// MessageStatusResponse represents response of query message status.
type MessageStatusResponse struct {
Statuses []*MessageStatus
}
// QueryMessageStatus fetch the status of specific messages.
func (c *Client) QueryMessageStatus(ctx context.Context, params MessageStatusParams) (*MessageStatusResponse, error) {
q := c.buildDefaultQuery()
q.Set("msgid", strings.Join(params.MessageIDs, ","))
if !params.HideDeductedPoints {
q.Set("smsPointFlag", "1")
}
u, _ := url.Parse("/b2c/mtk/SmQuery")
u.RawQuery = q.Encode()
resp, err := c.Get(ctx, u.String())
if err != nil {
return nil, err
}
defer resp.Body.Close()
return parseMessageStatusResponse(resp.Body)
}
func parseMessageStatusResponse(body io.Reader) (*MessageStatusResponse, error) {
var (
scanner = bufio.NewScanner(body)
response = new(MessageStatusResponse)
)
for scanner.Scan() {
text := strings.TrimSpace(scanner.Text())
s := strings.Split(text, "\t")
messageStatus := &MessageStatus{
MessageResult: MessageResult{
Msgid: s[0],
StatusCode: StatusCode(s[1]),
},
StatusTime: s[2],
}
if len(s) == 4 {
point, _ := strconv.Atoi(s[3])
messageStatus.SmsPoint = Ptr(point)
}
response.Statuses = append(response.Statuses, messageStatus)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return response, nil
}
// QueryAccountPoint retrieves your account balance.
func (c *Client) QueryAccountPoint(ctx context.Context) (int, error) {
u, _ := url.Parse("b2c/mtk/SmQuery")
u.RawQuery = c.buildDefaultQuery().Encode()
resp, err := c.Get(ctx, u.String())
if err != nil {
return 0, err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return 0, err
}
return strconv.Atoi(strings.Split(string(data), "=")[1])
}
// CanceledMessage represents the canceled message.
type CanceledMessage struct {
Msgid string
StatusCode StatusCode
}
// CancelScheduledMessages cancels scheduled messages.
func (c *Client) CancelScheduledMessages(ctx context.Context, messageIDs []string) ([]*CanceledMessage, error) {
q := c.buildDefaultQuery()
q.Set("msgid", strings.Join(messageIDs, ","))
u, _ := url.Parse("b2c/mtk/SmCancel")
u.RawQuery = q.Encode()
resp, err := c.Get(ctx, u.String())
if err != nil {
return nil, err
}
defer resp.Body.Close()
return parseCancelScheduledMessagesResponse(resp.Body)
}
func parseCancelScheduledMessagesResponse(body io.Reader) ([]*CanceledMessage, error) {
var (
scanner = bufio.NewScanner(body)
messages = make([]*CanceledMessage, 0)
)
for scanner.Scan() {
text := strings.TrimSpace(scanner.Text())
s := strings.Split(text, "=")
messages = append(messages, &CanceledMessage{
Msgid: s[0],
StatusCode: StatusCode(s[1]),
})
}
if err := scanner.Err(); err != nil {
return nil, err
}
return messages, nil
}