forked from savely-krasovsky/go-chatwars-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
412 lines (372 loc) · 9.29 KB
/
main.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
package cwapi
import (
"encoding/json"
"fmt"
"github.com/streadway/amqp"
"log"
"strings"
)
func (res *Response) UnmarshalJSON(b []byte) error {
type alias Response
temp := struct {
Action string `json:"action"`
Payload json.RawMessage `json:"payload"`
*alias
}{
alias: (*alias)(res),
}
if err := json.Unmarshal(b, &temp); err != nil {
return err
}
var payload resPayload
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.RequiredOperation = payload.RequiredOperation
res.Payload.Token = payload.Token
res.Action = temp.Action
switch temp.Action {
case "createAuthCode":
var payload ResCreateAuthCode
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResCreateAuthCode = &payload
case "grantToken":
var payload ResGrantToken
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResGrantToken = &payload
case "authAdditionalOperation":
var payload ResAuthAdditionalOperation
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResAuthAdditionalOperation = &payload
case "grantAdditionalOperation":
var payload ResGrantAdditionalOperation
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResGrantAdditionalOperation = &payload
case "authorizePayment":
var payload ResAuthorizePayment
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResAuthorizePayment = &payload
case "pay":
var payload ResPay
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResPay = &payload
case "payout":
var payload ResPayout
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResPayout = &payload
case "getInfo":
var payload ResGetInfo
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResGetInfo = &payload
case "viewCraftbook":
var payload ResViewCraftbook
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResViewCraftbook = &payload
case "requestProfile":
var payload ResRequestProfile
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResRequestProfile = &payload
case "requestBasicInfo":
var payload ResRequestBasicInfo
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResRequestBasicInfo = &payload
case "requestGearInfo":
var payload ResRequestGearInfo
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResRequestGearInfo = &payload
case "requestStock":
var payload ResRequestStock
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResRequestStock = &payload
case "guildInfo":
var payload ResGuildInfo
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResGuildInfo = &payload
case "wantToBuy":
var payload ResWantToBuy
if err := json.Unmarshal(temp.Payload, &payload); err != nil {
return err
}
res.Payload.ResWantToBuy = &payload
default:
res.Action = "unknownMethod"
}
return nil
}
func (payload *reqPayload) MarshalJSON() ([]byte, error) {
if payload.reqCreateAuthCode != nil {
return json.Marshal(payload.reqCreateAuthCode)
}
if payload.reqGrantToken != nil {
return json.Marshal(payload.reqGrantToken)
}
if payload.reqAuthAdditionalOperation != nil {
return json.Marshal(payload.reqAuthAdditionalOperation)
}
if payload.reqGrantAdditionalOperation != nil {
return json.Marshal(payload.reqGrantAdditionalOperation)
}
if payload.reqAuthorizePayment != nil {
return json.Marshal(payload.reqAuthorizePayment)
}
if payload.reqPay != nil {
return json.Marshal(payload.reqPay)
}
if payload.reqPayout != nil {
return json.Marshal(payload.reqPayout)
}
if payload.reqWantToBuy != nil {
return json.Marshal(payload.reqWantToBuy)
}
return json.Marshal(nil)
}
// Create new client, you can set server optional param, defaults to Chat Wars 2 server (or EU), accepts those variants:
// cw2, eu, cw3, ru
func NewClient(user string, password string, server ...string) (*Client, error) {
rabbitUrl := fmt.Sprintf(CW2, user, password)
if len(server) > 0 {
if strings.ToLower(server[0]) == "cw2" || strings.ToLower(server[0]) == "eu" {
rabbitUrl = fmt.Sprintf(CW2, user, password)
} else if strings.ToLower(server[0]) == "cw3" || strings.ToLower(server[0]) == "ru" {
rabbitUrl = fmt.Sprintf(CW3, user, password)
}
}
client := Client{
User: user,
Password: password,
RabbitUrl: rabbitUrl,
}
client.Updates = make(chan Response, 100)
err := client.reconnect()
return &client, err
}
func (c *Client) reStartConsumers() error {
var err error
if c.Updates != nil {
err := c.startUpdateConsumer()
if err != nil {
return err
}
}
if c.Deals != nil {
err := c.startDealsConsumer()
if err != nil {
return err
}
}
if c.Duels != nil {
err := c.startDuelsConsumer()
if err != nil {
return err
}
}
if c.Offers != nil {
err := c.startOffersConsumer()
if err != nil {
return err
}
}
if c.SexDigest != nil {
err := c.startSexDigestConsumer()
if err != nil {
return err
}
}
if c.YellowPages != nil {
err := c.startYellowPages()
if err != nil {
return err
}
}
if c.AuctionDigest != nil {
err = c.startAuctionDigestConsumer()
if err != nil {
return err
}
}
return nil
}
func (c *Client) reconnect() error {
// Open new
conn, err := amqp.Dial(c.RabbitUrl)
if err != nil {
return err
}
chForPublish, err := conn.Channel()
if err != nil {
return err
}
chForUpdates, err := conn.Channel()
if err != nil {
return err
}
// force close old channels and connection to close old consumers
if c.channelForUpdates != nil {
c.channelForUpdates.Close()
}
if c.channelForPublish != nil {
c.channelForPublish.Close()
}
if c.connection != nil {
c.connection.Close()
}
// Reassign it and restart consumers
c.connection = conn
c.channelForPublish = chForPublish
c.channelForUpdates = chForUpdates
err = c.reStartConsumers()
if err != nil {
return err
}
go func() {
// Waits here for the channel to be closed
log.Printf("closing: %s", <-c.connection.NotifyClose(make(chan *amqp.Error)))
err = c.reconnect()
if err != nil {
log.Println("reconnect unsuccessful")
} else {
log.Println("reconnect successful")
}
}()
return nil
}
// Start consumer for base events
func (c *Client) startUpdateConsumer() error {
updates, err := c.channelForUpdates.Consume(
fmt.Sprintf("%s_i", c.User),
"",
true,
false,
false,
false,
nil,
)
if err != nil {
return err
}
go func() {
for update := range updates {
if update.RoutingKey == fmt.Sprintf("%s_i", c.User) {
var res Response
err := json.Unmarshal(update.Body, &res)
if err != nil {
log.Println(err)
}
var userID int
switch res.Action {
case "createAuthCode":
userID = res.Payload.ResCreateAuthCode.UserID
case "grantToken":
userID = res.Payload.ResGrantToken.UserID
case "authAdditionalOperation":
userID = res.Payload.ResAuthAdditionalOperation.UserID
case "grantAdditionalOperation":
userID = res.Payload.ResGrantAdditionalOperation.UserID
case "authorizePayment":
userID = res.Payload.ResAuthorizePayment.UserID
case "pay":
userID = res.Payload.ResPay.UserID
case "payout":
userID = res.Payload.ResPayout.UserID
case "viewCraftbook":
userID = res.Payload.ResViewCraftbook.UserID
case "requestProfile":
userID = res.Payload.ResRequestProfile.UserID
case "requestBasicInfo":
userID = res.Payload.ResRequestBasicInfo.UserID
case "requestGearInfo":
userID = res.Payload.ResRequestGearInfo.UserID
case "requestStock":
userID = res.Payload.ResRequestStock.UserID
case "guildInfo":
userID = res.Payload.ResGuildInfo.UserID
case "wantToBuy":
userID = res.Payload.ResWantToBuy.UserID
}
// trying to load update with this salt
if waiter, found := c.waiters.Load(userID); found {
// found? send it to waiter channel
waiter.(chan Response) <- res
// trying to prevent memory leak
close(waiter.(chan Response))
}
c.Updates <- res
}
}
}()
return nil
}
// Close connection and active channel
func (c *Client) CloseConnection() error {
close(c.Updates)
close(c.Deals)
close(c.Duels)
close(c.Offers)
close(c.SexDigest)
close(c.YellowPages)
close(c.AuctionDigest)
if err := c.channelForUpdates.Close(); err != nil {
return err
}
if err := c.channelForPublish.Close(); err != nil {
return err
}
if err := c.connection.Close(); err != nil {
return err
}
return nil
}
func (c *Client) makeRequest(req []byte) (err error) {
err = c.channelForPublish.Publish(
fmt.Sprintf("%s_ex", c.User),
fmt.Sprintf("%s_o", c.User),
true,
false,
amqp.Publishing{
ContentType: "text/plain",
Body: req,
},
)
// If channel closed
if err != nil && err.(*amqp.Error).Code == 504 {
err = c.reconnect()
if err != nil {
return err
}
// And try again
if err := c.makeRequest(req); err != nil {
return err
}
} else if err != nil {
return err
}
return nil
}