forked from Gideon9212/ygopro-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ygopro-server.coffee
1907 lines (1728 loc) · 71.4 KB
/
ygopro-server.coffee
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 标准库
net = require 'net'
http = require 'http'
url = require 'url'
path = require 'path'
fs = require 'fs'
os = require 'os'
crypto = require 'crypto'
execFile = require('child_process').execFile
spawn = require('child_process').spawn
spawnSync = require('child_process').spawnSync
# 三方库
_ = require 'underscore'
_.str = require 'underscore.string'
_.mixin(_.str.exports())
request = require 'request'
bunyan = require 'bunyan'
log = bunyan.createLogger name: "mycard"
moment = require 'moment'
moment.locale('zh-cn', {
relativeTime: {
future: '%s内',
past: '%s前',
s: '%d秒',
m: '1分钟',
mm: '%d分钟',
h: '1小时',
hh: '%d小时',
d: '1天',
dd: '%d天',
M: '1个月',
MM: '%d个月',
y: '1年',
yy: '%d年'
}
})
#heapdump = require 'heapdump'
# 配置
# use nconf to save user config.user.json .
# config.json shouldn't be changed
nconf = require 'nconf'
nconf.file('./config.user.json')
defaultconfig = require('./config.json')
nconf.defaults(defaultconfig)
settings = global.settings = nconf.get()
nconf.myset = (settings, path, val) ->
# path should be like "modules:welcome"
nconf.set(path, val)
nconf.save()
log.info("setting changed", path, val) if _.isString(val)
path=path.split(':')
if path.length == 0
settings[path[0]]=val
else
target=settings
while path.length > 1
key=path.shift()
target=target[key]
key = path.shift()
target[key] = val
return
try
cppversion = parseInt(fs.readFileSync('ygopro/gframe/game.cpp', 'utf8').match(/PRO_VERSION = ([x\dABCDEF]+)/)[1], '16')
nconf.myset(settings, "version", cppversion)
log.info "ygopro version 0x"+settings.version.toString(16), "(from source code)"
catch
#settings.version = settings.version_default
log.info "ygopro version 0x"+settings.version.toString(16), "(from config)"
# load the lflist of current date
settings.lflist = (for list in fs.readFileSync('ygopro/lflist.conf', 'utf8').match(/!.*/g)
date=list.match(/!([\d\.]+)/)
continue unless date
{date: moment(list.match(/!([\d\.]+)/)[1], 'YYYY.MM.DD').utcOffset("-08:00"), tcg: list.indexOf('TCG') != -1})
if settings.modules.cloud_replay.enabled
redis = require 'redis'
zlib = require 'zlib'
redisdb = redis.createClient host: "127.0.0.1", port: settings.modules.cloud_replay.redis_port
redisdb.on 'error', (err)->
log.warn err
return
if settings.modules.windbot.enabled
settings.modules.windbots = require(settings.modules.windbot.botlist).windbots
# 组件
ygopro = require './ygopro.js'
roomlist = require './roomlist.js' if settings.modules.http.websocket_roomlist
if settings.modules.i18n.auto_pick
geoip = require('geoip-country-lite')
# cache users of mycard login
users_cache = {}
if settings.modules.mycard.enabled
pgClient = require('pg').Client
pg_client = new pgClient(settings.modules.mycard.auth_database)
pg_client.on 'error', (err) ->
log.warn "PostgreSQL ERROR: ", err
return
pg_query = pg_client.query('SELECT username, id from users')
pg_query.on 'error', (err) ->
log.warn "PostgreSQL Query ERROR: ", err
return
pg_query.on 'row', (row) ->
#log.info "load user", row.username, row.id
users_cache[row.username] = row.id
return
pg_query.on 'end', (result) ->
log.info "users loaded", result.rowCount
return
pg_client.on 'drain', pg_client.end.bind(pg_client)
log.info "loading mycard user..."
pg_client.connect()
# 获取可用内存
get_memory_usage = ()->
prc_free = spawnSync("free", [])
if (prc_free.stdout)
lines = prc_free.stdout.toString().split(/\n/g)
line = lines[1].split(/\s+/)
total = parseInt(line[1], 10)
free = parseInt(line[3], 10)
buffers = parseInt(line[5], 10)
cached = parseInt(line[6], 10)
actualFree = free + buffers + cached
percentUsed = parseFloat(((1 - (actualFree / total)) * 100).toFixed(2))
else
percentUsed = 0
return percentUsed
Cloud_replay_ids = []
ROOM_all = []
ROOM_players_oppentlist = {}
ROOM_players_banned = []
ROOM_connected_ip = {}
ROOM_bad_ip = {}
# ban a user manually and permanently
ban_user = (name) ->
settings.ban.banned_user.push(name)
nconf.myset(settings, "ban:banned_user", settings.ban.banned_user)
bad_ip=0
for room in ROOM_all when room and room.established
for player in room.players
if player and (player.name == name or player.ip == bad_ip)
bad_ip = player.ip
ROOM_bad_ip[bad_ip]=99
settings.ban.banned_ip.push(player.ip)
ygopro.stoc_send_chat_to_room(room, "#{player.name} ${kicked_by_system}", ygopro.constants.COLORS.RED)
player.destroy()
continue
return
# automatically ban user to use random duel
ROOM_ban_player = (name, ip, reason, countadd = 1)->
bannedplayer = _.find ROOM_players_banned, (bannedplayer)->
ip == bannedplayer.ip
if bannedplayer
bannedplayer.count = bannedplayer.count + countadd
bantime = if bannedplayer.count > 3 then Math.pow(2, bannedplayer.count - 3) * 2 else 0
bannedplayer.time = if moment() < bannedplayer.time then moment(bannedplayer.time).add(bantime, 'm') else moment().add(bantime, 'm')
bannedplayer.reasons.push(reason) if not _.find bannedplayer.reasons, (bannedreason)->
bannedreason == reason
bannedplayer.need_tip = true
else
bannedplayer = {"ip": ip, "time": moment(), "count": countadd, "reasons": [reason], "need_tip": true}
ROOM_players_banned.push(bannedplayer)
#log.info("banned", name, ip, reason, bannedplayer.count)
return
ROOM_find_or_create_by_name = (name, player_ip)->
uname=name.toUpperCase()
if settings.modules.windbot.enabled and (uname[0...2] == 'AI' or (!settings.modules.random_duel.enabled and uname == ''))
return ROOM_find_or_create_ai(name)
if settings.modules.random_duel.enabled and (uname == '' or uname == 'S' or uname == 'M' or uname == 'T')
return ROOM_find_or_create_random(uname, player_ip)
if room = ROOM_find_by_name(name)
return room
else if get_memory_usage() >= 90
return null
else
return new Room(name)
ROOM_find_or_create_random = (type, player_ip)->
bannedplayer = _.find ROOM_players_banned, (bannedplayer)->
return player_ip == bannedplayer.ip
if bannedplayer
if bannedplayer.count > 6 and moment() < bannedplayer.time
return {"error": "${random_banned_part1}#{bannedplayer.reasons.join('${random_ban_reason_separator}')}${random_banned_part2}#{moment(bannedplayer.time).fromNow(true)}${random_banned_part3}"}
if bannedplayer.count > 3 and moment() < bannedplayer.time and bannedplayer.need_tip and type != 'T'
bannedplayer.need_tip = false
return {"error": "${random_deprecated_part1}#{bannedplayer.reasons.join('${random_ban_reason_separator}')}${random_deprecated_part2}#{moment(bannedplayer.time).fromNow(true)}${random_deprecated_part3}"}
else if bannedplayer.need_tip
bannedplayer.need_tip = false
return {"error": "${random_warn_part1}#{bannedplayer.reasons.join('${random_ban_reason_separator}')}${random_warn_part2}"}
else if bannedplayer.count > 2
bannedplayer.need_tip = true
max_player = if type == 'T' then 4 else 2
playerbanned = (bannedplayer and bannedplayer.count > 3 and moment() < bannedplayer.time)
result = _.find ROOM_all, (room)->
return room and room.random_type != '' and !room.started and
((type == '' and room.random_type != 'T') or room.random_type == type) and
room.get_playing_player().length < max_player and
(room.get_host() == null or room.get_host().ip != ROOM_players_oppentlist[player_ip]) and
(playerbanned == room.deprecated or type == 'T')
if result
result.welcome = '${random_duel_enter_room_waiting}'
#log.info 'found room', player_name
else if get_memory_usage() < 90
type = if type then type else 'S'
name = type + ',RANDOM#' + Math.floor(Math.random() * 100000)
result = new Room(name)
result.random_type = type
result.max_player = max_player
result.welcome = '${random_duel_enter_room_new}'
result.deprecated = playerbanned
#log.info 'create room', player_name, name
else
return null
if result.random_type=='M' then result.welcome = result.welcome + '\n${random_duel_enter_room_match}'
return result
ROOM_find_or_create_ai = (name)->
if name == ''
name = 'AI'
namea = name.split('#')
uname = name.toUpperCase()
if room = ROOM_find_by_name(name)
return room
else if uname == 'AI'
windbot = _.sample settings.modules.windbots
name = 'AI#' + Math.floor(Math.random() * 100000)
else if namea.length>1
ainame = namea[namea.length-1]
windbot = _.sample _.filter settings.modules.windbots, (w)->
w.name == ainame or w.deck == ainame
if !windbot
return { "error": "${windbot_deck_not_found}" }
name = name + ',' + Math.floor(Math.random() * 100000)
else
windbot = _.sample settings.modules.windbots
name = name + '#' + Math.floor(Math.random() * 100000)
if name.replace(/[^\x00-\xff]/g,"00").length>20
log.info "long ai name", name
return { "error": "${windbot_name_too_long}" }
result = new Room(name)
result.windbot = windbot
result.private = true
return result
ROOM_find_by_name = (name)->
result = _.find ROOM_all, (room)->
return room and room.name == name
return result
ROOM_find_by_title = (title)->
result = _.find ROOM_all, (room)->
return room and room.title == title
return result
ROOM_find_by_port = (port)->
_.find ROOM_all, (room)->
return room and room.port == port
ROOM_validate = (name)->
client_name_and_pass = name.split('$', 2)
client_name = client_name_and_pass[0]
client_pass = client_name_and_pass[1]
return true if !client_pass
!_.find ROOM_all, (room)->
return false unless room
room_name_and_pass = room.name.split('$', 2)
room_name = room_name_and_pass[0]
room_pass = room_name_and_pass[1]
client_name == room_name and client_pass != room_pass
ROOM_unwelcome = (room, bad_player, reason)->
return unless room
for player in room.players
if player and player == bad_player
ygopro.stoc_send_chat(player, "${unwelcome_warn_part1}#{reason}${unwelcome_warn_part2}", ygopro.constants.COLORS.RED)
else if player and player.pos!=7 and player != bad_player
player.flee_free=true
ygopro.stoc_send_chat(player, "${unwelcome_tip_part1}#{reason}${unwelcome_tip_part2}", ygopro.constants.COLORS.BABYBLUE)
return
class Room
constructor: (name, @hostinfo) ->
@name = name
@alive = true
@players = []
@player_datas = []
@status = 'starting'
@started = false
@established = false
@watcher_buffers = []
@recorder_buffers = []
@cloud_replay_id = Math.floor(Math.random()*100000000)
@watchers = []
@random_type = ''
@welcome = ''
@scores = {}
ROOM_all.push this
@hostinfo ||= JSON.parse(JSON.stringify(settings.hostinfo))
if settings.lflist.length
if @hostinfo.rule == 1 and @hostinfo.lflist == 0
@hostinfo.lflist = _.findIndex settings.lflist, (list)-> list.tcg
else
@hostinfo.lflist = -1
@hostinfo.replay_mode = if settings.modules.tournament_mode.enabled and settings.modules.tournament_mode.replay_safe then 1 else 0
if name[0...2] == 'M#'
@hostinfo.mode = 1
else if name[0...2] == 'T#'
@hostinfo.mode = 2
@hostinfo.start_lp = 16000
else if name[0...3] == 'AI#'
@hostinfo.rule = 2
@hostinfo.lflist = -1
else if (param = name.match /^(\d)(\d)(T|F)(T|F)(T|F)(\d+),(\d+),(\d+)/i)
@hostinfo.rule = parseInt(param[1])
@hostinfo.mode = parseInt(param[2])
@hostinfo.enable_priority = param[3] == 'T'
@hostinfo.no_check_deck = param[4] == 'T'
@hostinfo.no_shuffle_deck = param[5] == 'T'
@hostinfo.start_lp = parseInt(param[6])
@hostinfo.start_hand = parseInt(param[7])
@hostinfo.draw_count = parseInt(param[8])
else if ((param = name.match /(.+)#/) != null)
rule = param[1].toUpperCase()
if (rule.match /(^|,|,)(M|MATCH)(,|,|$)/)
@hostinfo.mode = 1
if (rule.match /(^|,|,)(T|TAG)(,|,|$)/)
@hostinfo.mode = 2
@hostinfo.start_lp = 16000
if (rule.match /(^|,|,)(TCGONLY|TO)(,|,|$)/)
@hostinfo.rule = 1
@hostinfo.lflist = _.findIndex settings.lflist, (list)-> list.tcg
if (rule.match /(^|,|,)(OCGONLY|OO)(,|,|$)/)
@hostinfo.rule = 0
if (rule.match /(^|,|,)(OT|TCG)(,|,|$)/)
@hostinfo.rule = 2
if (param = rule.match /(^|,|,)LP(\d+)(,|,|$)/)
start_lp = parseInt(param[2])
if (start_lp <= 0) then start_lp = 1
if (start_lp >= 99999) then start_lp = 99999
@hostinfo.start_lp = start_lp
if (param = rule.match /(^|,|,)(TIME|TM|TI)(\d+)(,|,|$)/)
time_limit = parseInt(param[3])
if (time_limit < 0) then time_limit = 180
if (time_limit >= 1 and time_limit <= 60) then time_limit = time_limit * 60
if (time_limit >= 999) then time_limit = 999
@hostinfo.time_limit = time_limit
if (param = rule.match /(^|,|,)(START|ST)(\d+)(,|,|$)/)
start_hand = parseInt(param[3])
if (start_hand <= 0) then start_hand = 1
if (start_hand >= 40) then start_hand = 40
@hostinfo.start_hand = start_hand
if (param = rule.match /(^|,|,)(DRAW|DR)(\d+)(,|,|$)/)
draw_count = parseInt(param[3])
if (draw_count >= 35) then draw_count = 35
@hostinfo.draw_count = draw_count
if (param = rule.match /(^|,|,)(LFLIST|LF)(\d+)(,|,|$)/)
lflist = parseInt(param[3]) - 1
@hostinfo.lflist = lflist
if (rule.match /(^|,|,)(NOLFLIST|NF)(,|,|$)/)
@hostinfo.lflist = -1
if (rule.match /(^|,|,)(NOUNIQUE|NU)(,|,|$)/)
@hostinfo.rule = 3
if (rule.match /(^|,|,)(NOCHECK|NC)(,|,|$)/)
@hostinfo.no_check_deck = true
if (rule.match /(^|,|,)(NOSHUFFLE|NS)(,|,|$)/)
@hostinfo.no_shuffle_deck = true
if (rule.match /(^|,|,)(IGPRIORITY|PR)(,|,|$)/)
@hostinfo.enable_priority = true
param = [0, @hostinfo.lflist, @hostinfo.rule, @hostinfo.mode, (if @hostinfo.enable_priority then 'T' else 'F'),
(if @hostinfo.no_check_deck then 'T' else 'F'), (if @hostinfo.no_shuffle_deck then 'T' else 'F'),
@hostinfo.start_lp, @hostinfo.start_hand, @hostinfo.draw_count, @hostinfo.time_limit, @hostinfo.replay_mode]
try
@process = spawn './ygopro', param, {cwd: 'ygopro'}
@process.on 'error', (err)=>
_.each @players, (player)->
ygopro.stoc_die(player, "${create_room_failed}")
this.delete()
return
@process.on 'exit', (code)=>
@disconnector = 'server' unless @disconnector
this.delete()
return
@process.stdout.setEncoding('utf8')
@process.stdout.once 'data', (data)=>
@established = true
roomlist.create(this) if !@windbot and settings.modules.http.websocket_roomlist
@port = parseInt data
_.each @players, (player)=>
player.server.connect @port, '127.0.0.1', ->
player.server.write buffer for buffer in player.pre_establish_buffers
player.established = true
player.pre_establish_buffers = []
return
return
if @windbot
setTimeout ()=>
@add_windbot(@windbot)
, 200
return
@process.stderr.on 'data', (data)=>
data = "Debug: " + data
data = data.replace(/\n$/, "")
log.info "YGOPRO " + data
ygopro.stoc_send_chat_to_room this, data, ygopro.constants.COLORS.RED
@has_ygopro_error = true
return
catch
@error = "${create_room_failed}"
delete: ->
return if @deleted
#log.info 'room-delete', this.name, ROOM_all.length
if @started and settings.modules.arena_mode.enabled and @arena
#log.info @scores
score_array=[]
for name, score of @scores
score_array.push { name: name, score: score }
#log.info 'SCORE', score_array, @start_time
if score_array.length == 2
request.post { url : settings.modules.arena_mode.post_score , form : {
accesskey: settings.modules.arena_mode.accesskey,
usernameA: score_array[0].name,
usernameB: score_array[1].name,
userscoreA: score_array[0].score,
userscoreB: score_array[1].score,
start: @start_time,
end: moment().format(),
arena: @arena
}}, (error, response, body)=>
if error
log.warn 'SCORE POST ERROR', error
else
if response.statusCode != 204 and response.statusCode != 200
log.warn 'SCORE POST FAIL', response.statusCode, response.statusMessage, @name, body
#else
# log.info 'SCORE POST OK', response.statusCode, response.statusMessage, @name, body
return
if @player_datas.length and settings.modules.cloud_replay.enabled
replay_id = @cloud_replay_id
if @has_ygopro_error
log_rep_id = true
player_names=@player_datas[0].name + (if @player_datas[2] then "+" + @player_datas[2].name else "") +
" VS " +
(if @player_datas[1] then @player_datas[1].name else "AI") +
(if @player_datas[3] then "+" + @player_datas[3].name else "")
player_ips=[]
_.each @player_datas, (player)->
player_ips.push(player.ip)
return
recorder_buffer=Buffer.concat(@recorder_buffers)
zlib.deflate recorder_buffer, (err, replay_buffer) ->
replay_buffer=replay_buffer.toString('binary')
#log.info err, replay_buffer
date_time=moment().format('YYYY-MM-DD HH:mm:ss')
#replay_id=Math.floor(Math.random()*100000000)
redisdb.hmset("replay:"+replay_id,
"replay_id", replay_id,
"replay_buffer", replay_buffer,
"player_names", player_names,
"date_time", date_time)
if !log_rep_id
redisdb.expire("replay:"+replay_id, 60*60*24)
recorded_ip=[]
_.each player_ips, (player_ip)->
return if _.contains(recorded_ip, player_ip)
recorded_ip.push player_ip
redisdb.lpush(player_ip+":replays", replay_id)
return
if log_rep_id
log.info "error replay: R#" + replay_id
return
@watcher_buffers = []
@recorder_buffers = []
@players = []
@watcher.destroy() if @watcher
@recorder.destroy() if @recorder
@deleted = true
index = _.indexOf(ROOM_all, this)
ROOM_all[index] = null unless index == -1
#ROOM_all.splice(index, 1) unless index == -1
roomlist.delete this if !@windbot and @established and settings.modules.http.websocket_roomlist
return
get_playing_player: ->
playing_player = []
_.each @players, (player)->
if player.pos < 4 then playing_player.push player
return
return playing_player
get_host: ->
host_player = null
_.each @players, (player)->
if player.is_host then host_player = player
return
return host_player
add_windbot: (botdata)->
@windbot = botdata
request
url: "http://127.0.0.1:#{settings.modules.windbot.port}/?name=#{encodeURIComponent(botdata.name)}&deck=#{encodeURIComponent(botdata.deck)}&host=127.0.0.1&port=#{settings.port}&dialog=#{encodeURIComponent(botdata.dialog)}&version=#{settings.version}&password=#{encodeURIComponent(@name)}"
, (error, response, body)=>
if error
log.warn 'windbot add error', error, this.name
ygopro.stoc_send_chat_to_room(this, "${add_windbot_failed}", ygopro.constants.COLORS.RED)
#else
#log.info "windbot added"
return
return
connect: (client)->
@players.push client
if @random_type
client.abuse_count = 0
host_player = @get_host()
if host_player && (host_player != client)
# 进来时已经有人在等待了,互相记录为匹配过
ROOM_players_oppentlist[host_player.ip] = client.ip
ROOM_players_oppentlist[client.ip] = host_player.ip
else
# 第一个玩家刚进来,还没就位
ROOM_players_oppentlist[client.ip] = null
if @established
roomlist.update(this) if !@windbot and !@started and settings.modules.http.websocket_roomlist
client.server.connect @port, '127.0.0.1', ->
client.server.write buffer for buffer in client.pre_establish_buffers
client.established = true
client.pre_establish_buffers = []
return
return
disconnect: (client, error)->
if client.is_post_watcher
ygopro.stoc_send_chat_to_room this, "#{client.name} ${quit_watch}" + if error then ": #{error}" else ''
index = _.indexOf(@watchers, client)
@watchers.splice(index, 1) unless index == -1
#client.room = null
else
index = _.indexOf(@players, client)
@players.splice(index, 1) unless index == -1
#log.info(@started,@disconnector,@random_type)
if @started and @disconnector != 'server' and (client.pos < 4 or client.is_host)
@finished = true
@scores[client.name] = -9
if @random_type and not client.flee_free
ROOM_ban_player(client.name, client.ip, "${random_ban_reason_flee}")
if @players.length and !(@windbot and client.is_host)
ygopro.stoc_send_chat_to_room this, "#{client.name} ${left_game}" + if error then ": #{error}" else ''
roomlist.update(this) if !@windbot and !@started and settings.modules.http.websocket_roomlist
#client.room = null
else
@process.kill()
#client.room = null
this.delete()
return
# 网络连接
net.createServer (client) ->
client.ip = client.remoteAddress
connect_count = ROOM_connected_ip[client.ip] or 0
if client.ip != '::ffff:127.0.0.1'
connect_count++
ROOM_connected_ip[client.ip] = connect_count
#log.info "connect", client.ip, ROOM_connected_ip[client.ip]
# server stand for the connection to ygopro server process
server = new net.Socket()
client.server = server
client.setTimeout(2000) #连接前超时2秒
# 释放处理
client.on 'close', (had_error) ->
#log.info "client closed", client.name, had_error
room=ROOM_all[client.rid]
connect_count = ROOM_connected_ip[client.ip]
if connect_count > 0
connect_count--
ROOM_connected_ip[client.ip] = connect_count
#log.info "disconnect", client.ip, ROOM_connected_ip[client.ip]
unless client.closed
client.closed = true
room.disconnect(client) if room
server.destroy()
return
client.on 'error', (error)->
#log.info "client error", client.name, error
room=ROOM_all[client.rid]
connect_count = ROOM_connected_ip[client.ip]
if connect_count > 0
connect_count--
ROOM_connected_ip[client.ip] = connect_count
#log.info "err disconnect", client.ip, ROOM_connected_ip[client.ip]
unless client.closed
client.closed = error
room.disconnect(client, error) if room
server.destroy()
return
client.on 'timeout', ()->
server.destroy()
return
server.on 'close', (had_error) ->
#log.info "server closed", client.name, had_error
room=ROOM_all[client.rid]
#log.info "server close", client.ip, ROOM_connected_ip[client.ip]
room.disconnector = 'server' if room
server.closed = true unless server.closed
unless client.closed
ygopro.stoc_send_chat(client, "${server_closed}", ygopro.constants.COLORS.RED)
client.destroy()
return
server.on 'error', (error)->
#log.info "server error", client.name, error
room=ROOM_all[client.rid]
#log.info "server err close", client.ip, ROOM_connected_ip[client.ip]
room.disconnector = 'server' if room
server.closed = error
unless client.closed
ygopro.stoc_send_chat(client, "${server_error}: #{error}", ygopro.constants.COLORS.RED)
client.destroy()
return
if ROOM_bad_ip[client.ip] > 5 or ROOM_connected_ip[client.ip] > 10
log.info 'BAD IP', client.ip
client.destroy()
return
if settings.modules.cloud_replay.enabled
client.open_cloud_replay= (err, replay)->
if err or !replay
ygopro.stoc_die(client, "${cloud_replay_no}")
return
redisdb.expire("replay:"+replay.replay_id, 60*60*48)
buffer=new Buffer(replay.replay_buffer,'binary')
zlib.unzip buffer, (err, replay_buffer) ->
if err
log.info "cloud replay unzip error: " + err
ygopro.stoc_send_chat(client, "${cloud_replay_error}", ygopro.constants.COLORS.RED)
client.destroy()
return
ygopro.stoc_send_chat(client, "${cloud_replay_playing} R##{replay.replay_id} #{replay.player_names} #{replay.date_time}", ygopro.constants.COLORS.BABYBLUE)
client.write replay_buffer, ()->
client.destroy()
return
return
return
# 需要重构
# 客户端到服务端(ctos)协议分析
client.pre_establish_buffers = new Array()
client.on 'data', (ctos_buffer) ->
if client.is_post_watcher
room=ROOM_all[client.rid]
room.watcher.write ctos_buffer if room
else
#ctos_buffer = new Buffer(0)
ctos_message_length = 0
ctos_proto = 0
#ctos_buffer = Buffer.concat([ctos_buffer, data], ctos_buffer.length + data.length) #buffer的错误使用方式,好孩子不要学
datas = []
looplimit = 0
while true
if ctos_message_length == 0
if ctos_buffer.length >= 2
ctos_message_length = ctos_buffer.readUInt16LE(0)
else
log.warn("bad ctos_buffer length", client.ip) unless ctos_buffer.length == 0
break
else if ctos_proto == 0
if ctos_buffer.length >= 3
ctos_proto = ctos_buffer.readUInt8(2)
else
log.warn("bad ctos_proto length", client.ip)
break
else
if ctos_buffer.length >= 2 + ctos_message_length
#console.log "CTOS", ygopro.constants.CTOS[ctos_proto]
cancel = false
if ygopro.ctos_follows[ctos_proto]
b = ctos_buffer.slice(3, ctos_message_length - 1 + 3)
info = null
if struct = ygopro.structs[ygopro.proto_structs.CTOS[ygopro.constants.CTOS[ctos_proto]]]
struct._setBuff(b)
info = _.clone(struct.fields)
if ygopro.ctos_follows[ctos_proto].synchronous
cancel = ygopro.ctos_follows[ctos_proto].callback b, info, client, server
else
ygopro.ctos_follows[ctos_proto].callback b, info, client, server
datas.push ctos_buffer.slice(0, 2 + ctos_message_length) unless cancel
ctos_buffer = ctos_buffer.slice(2 + ctos_message_length)
ctos_message_length = 0
ctos_proto = 0
else
log.warn("bad ctos_message length", client.ip, ctos_buffer.length, ctos_message_length, ctos_proto) if ctos_message_length != 17735
break
looplimit++
#log.info(looplimit)
if looplimit > 800 or ROOM_bad_ip[client.ip] > 5
log.info("error ctos", client.name, client.ip)
bad_ip_count = ROOM_bad_ip[client.ip]
if bad_ip_count
ROOM_bad_ip[client.ip] = bad_ip_count + 1
else
ROOM_bad_ip[client.ip] = 1
client.destroy()
break
if client.established
server.write buffer for buffer in datas
else
client.pre_establish_buffers.push buffer for buffer in datas
return
# 服务端到客户端(stoc)
server.on 'data', (stoc_buffer)->
#stoc_buffer = new Buffer(0)
stoc_message_length = 0
stoc_proto = 0
#stoc_buffer = Buffer.concat([stoc_buffer, data], stoc_buffer.length + data.length) #buffer的错误使用方式,好孩子不要学
#unless ygopro.stoc_follows[stoc_proto] and ygopro.stoc_follows[stoc_proto].synchronous
#client.write data
datas = []
looplimit = 0
while true
if stoc_message_length == 0
if stoc_buffer.length >= 2
stoc_message_length = stoc_buffer.readUInt16LE(0)
else
log.warn("bad stoc_buffer length", client.ip) unless stoc_buffer.length == 0
break
else if stoc_proto == 0
if stoc_buffer.length >= 3
stoc_proto = stoc_buffer.readUInt8(2)
else
log.warn("bad stoc_proto length", client.ip)
break
else
if stoc_buffer.length >= 2 + stoc_message_length
#console.log "STOC", ygopro.constants.STOC[stoc_proto]
cancel = false
stanzas = stoc_proto
if ygopro.stoc_follows[stoc_proto]
b = stoc_buffer.slice(3, stoc_message_length - 1 + 3)
info = null
if struct = ygopro.structs[ygopro.proto_structs.STOC[ygopro.constants.STOC[stoc_proto]]]
struct._setBuff(b)
info = _.clone(struct.fields)
if ygopro.stoc_follows[stoc_proto].synchronous
cancel = ygopro.stoc_follows[stoc_proto].callback b, info, client, server
else
ygopro.stoc_follows[stoc_proto].callback b, info, client, server
datas.push stoc_buffer.slice(0, 2 + stoc_message_length) unless cancel
stoc_buffer = stoc_buffer.slice(2 + stoc_message_length)
stoc_message_length = 0
stoc_proto = 0
else
log.warn("bad stoc_message length", client.ip)
break
looplimit++
#log.info(looplimit)
if looplimit > 800
log.info("error stoc", client.name)
server.destroy()
break
client.write buffer for buffer in datas
return
return
.listen settings.port, ->
log.info "server started", settings.port
return
# 功能模块
# return true to cancel a synchronous message
ygopro.ctos_follow 'PLAYER_INFO', true, (buffer, info, client, server)->
# checkmate use username$password, but here don't
# so remove the password
name = info.name.split("$")[0]
if (_.any(settings.ban.illegal_id, (badid) ->
regexp = new RegExp(badid, 'i')
matchs = name.match(regexp)
if matchs
name = matchs[1]
return true
return false
, name))
client.rag = true
struct = ygopro.structs["CTOS_PlayerInfo"]
struct._setBuff(buffer)
struct.set("name", name)
buffer = struct.buffer
client.name = name
if not settings.modules.i18n.auto_pick or client.ip=="::ffff:127.0.0.1"
client.lang=settings.modules.i18n.default
else
geo = geoip.lookup(client.ip)
if not geo
log.warn("fail to locate ip", client.name, client.ip)
client.lang=settings.modules.i18n.fallback
else
if lang=settings.modules.i18n.map[geo.country]
client.lang=lang
else
#log.info("Not in map", geo.country, client.name, client.ip)
client.lang=settings.modules.i18n.fallback
return false
ygopro.ctos_follow 'JOIN_GAME', false, (buffer, info, client, server)->
#log.info info
if settings.modules.stop
ygopro.stoc_die(client, settings.modules.stop)
else if info.pass.toUpperCase()=="R" and settings.modules.cloud_replay.enabled
ygopro.stoc_send_chat(client,"${cloud_replay_hint}", ygopro.constants.COLORS.BABYBLUE)
redisdb.lrange client.ip+":replays", 0, 2, (err, result)->
_.each result, (replay_id,id)->
redisdb.hgetall "replay:"+replay_id, (err, replay)->
if err or !replay
log.info "cloud replay getall error: " + err if err
return
ygopro.stoc_send_chat(client,"<#{id-0+1}> R##{replay_id} #{replay.player_names} #{replay.date_time}", ygopro.constants.COLORS.BABYBLUE)
return
return
return
# 强行等待异步执行完毕_(:з」∠)_
setTimeout (()->
ygopro.stoc_send client, 'ERROR_MSG',{
msg: 1
code: 9
}
client.destroy()
return), 500
else if info.pass[0...2].toUpperCase()=="R#" and settings.modules.cloud_replay.enabled
replay_id=info.pass.split("#")[1]
if (replay_id>0 and replay_id<=9)
redisdb.lindex client.ip+":replays", replay_id-1, (err, replay_id)->
if err or !replay_id
log.info "cloud replay replayid error: " + err if err
ygopro.stoc_die(client, "${cloud_replay_no}")
return
redisdb.hgetall "replay:"+replay_id, client.open_cloud_replay
return
else if replay_id
redisdb.hgetall "replay:"+replay_id, client.open_cloud_replay
else
ygopro.stoc_die(client, "${cloud_replay_no}")
else if info.pass.toUpperCase()=="W" and settings.modules.cloud_replay.enabled
replay_id=Cloud_replay_ids[Math.floor(Math.random()*Cloud_replay_ids.length)]
redisdb.hgetall "replay:"+replay_id, client.open_cloud_replay
else if info.version != settings.version and (info.version < 9020 or settings.version != 4927) #强行兼容23333版
ygopro.stoc_send_chat(client, settings.modules.update, ygopro.constants.COLORS.RED)
ygopro.stoc_send client, 'ERROR_MSG', {
msg: 4
code: settings.version
}
client.destroy()
else if !info.pass.length and !settings.modules.random_duel.enabled and !settings.modules.windbot.enabled
ygopro.stoc_die(client, "${blank_room_name}")
else if info.pass.length and settings.modules.mycard.enabled and info.pass[0...3] != 'AI#'
ygopro.stoc_send_chat(client, '${loading_user_info}', ygopro.constants.COLORS.BABYBLUE)
if info.pass.length <= 8
ygopro.stoc_die(client, '${invalid_password_length}')
return
if info.version >= 9020 and settings.version == 4927 #强行兼容23333版
info.version = settings.version
struct = ygopro.structs["CTOS_JoinGame"]
struct._setBuff(buffer)
struct.set("version", info.version)
buffer = struct.buffer
buffer = new Buffer(info.pass[0...8], 'base64')
if buffer.length != 6
ygopro.stoc_die(client, '${invalid_password_payload}')
return
check = (buf)->
checksum = 0
for i in [0...buf.length]
checksum += buf.readUInt8(i)
(checksum & 0xFF) == 0
finish = (buffer)->
action = buffer.readUInt8(1) >> 4
if buffer != decrypted_buffer and action in [1, 2, 4]
ygopro.stoc_die(client, '${invalid_password_unauthorized}')
return
# 1 create public room
# 2 create private room
# 3 join room by id
# 4 create or join room by id (use for match)
# 5 join room by title
switch action
when 1,2
name = crypto.createHash('md5').update(info.pass + client.name).digest('base64')[0...10].replace('+', '-').replace('/', '_')
if ROOM_find_by_name(name)
ygopro.stoc_die(client, '${invalid_password_existed}')
return
opt1 = buffer.readUInt8(2)
opt2 = buffer.readUInt16LE(3)
opt3 = buffer.readUInt8(5)
options = {
lflist: 0
time_limit: 180
rule: (opt1 >> 5) & 3
mode: (opt1 >> 3) & 3
enable_priority: !!((opt1 >> 2) & 1)
no_check_deck: !!((opt1 >> 1) & 1)
no_shuffle_deck: !!(opt1 & 1)
start_lp: opt2
start_hand: opt3 >> 4
draw_count: opt3 & 0xF
}
options.lflist = _.findIndex settings.lflist, (list)-> ((options.rule == 1) == list.tcg) and list.date.isBefore()
room = new Room(name, options)
room.title = info.pass.slice(8).replace(String.fromCharCode(0xFEFF), ' ')
room.private = action == 2
when 3
name = info.pass.slice(8)
room = ROOM_find_by_name(name)
if(!room)
ygopro.stoc_die(client, '${invalid_password_not_found}')
return
when 4
room = ROOM_find_or_create_by_name('M#' + info.pass.slice(8))
room.private = true
room.arena = settings.modules.arena_mode.mode
when 5
title = info.pass.slice(8).replace(String.fromCharCode(0xFEFF), ' ')
room = ROOM_find_by_title(title)
if(!room)
ygopro.stoc_die(client, '${invalid_password_not_found}')
return
else
ygopro.stoc_die(client, '${invalid_password_action}')
return