forked from torgtaitai/DodontoF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DodontoFServerMySql.rb
786 lines (550 loc) · 18.2 KB
/
DodontoFServerMySql.rb
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
#!/usr/local/bin/ruby -Ku
#--*-coding:utf-8-*--
require 'DodontoFServer.rb'
#require 'rubygems'
require 'mysql'
$SAVE_DATA_DIR = '.'
#サーバCGIとクライアントFlashのバージョン一致確認用
$version = "Ver.1.44.01(2014/04/15)"
class SaveDataManagerOnMySql
def initialize
@tableLocked = false
@db = nil
end
def getDb
if( @db.nil? )
@db = openDb
end
@db
end
def openDb
logging("OPEN DB")
Mysql::new($databaseHostName, $databaseUserName, $databasePassword, $databaseName)
end
def closeDb
return if( @db.nil? )
logging("CLOSE DB")
getDb.close
@db = nil
end
def open(fileName, isReadOnly, tableName = nil)
#yield
#return;
if( tableName.nil? )
dirName = File.dirname(fileName)
tableName = getTableName(dirName)
end
lockType = (isReadOnly ? "READ" : "WRITE")
if( @tableLocked )
yield
return
end
begin
executeSql("LOCK TABLES #{tableName} #{lockType}")
@tableLocked = true
yield
ensure
@tableLocked = false
executeSql("UNLOCK TABLES")
closeDb
end
end
def changeText(fileName, text)
if( isExist?(fileName) )
update(fileName, text)
else
createData(fileName, text)
end
end
def getTableName(dirName)
#return dirName.gsub(/\./, "_").gsub(/\//, "_")
return dirName.gsub(/\./, "_").gsub(/\//, "_").downcase
end
def executeSql(sqlOriginal, *args)
sqlOriginal += " "
logging(sqlOriginal, "executeSql sqlOriginal")
#logging(args.join(", "), "executeSql args")
sqlParts = sqlOriginal.split(/\?/)
if( (sqlParts.length - 1) != args.length )
raise "executeSql args.lengt error (sqlParts.lengt:#{sqlParts.length.to_s}, args.length:#{args.length.to_s})"
end
sql = sqlParts.shift
args.each_with_index do |arg, index|
if( arg.class.name == "String" )
arg = "'" + Mysql::quote(arg) + "'"
end
sql += arg.to_s
sql += sqlParts.shift
end
logging(sql, "SQL query")
result = getDb.query(sql)
return result
end
def getSaveDataLastAccessTimes(dirNames, roomNumberRange)
logging(dirNames, "getSaveDataLastAccessTimes dirNames")
logging(roomNumberRange, "getSaveDataLastAccessTimes roomNumberRange")
lastAccessTimeInfos = {}
dirNames.each do |dirName|
next unless ( isExistDir?(dirName) )
next unless( /data_(\d+)\Z/ === dirName )
dirIndex = $1.to_i
next unless( roomNumberRange.include?(dirIndex) )
tableName = getTableName(dirName)
times = []
result = executeSql("SELECT fileName, time FROM #{tableName}")
result.each do |row|
fileName = row.shift
logging(fileName, "fileName")
baseName = File.basename(fileName)
logging(baseName, "baseName")
timeValue = row.shift.to_f
logging(timeValue, "timeValue")
times << Time.at(timeValue)
end
lastAccessTimeInfos[dirIndex] = times.max
end
logging(lastAccessTimeInfos, "getSaveDataLastAccessTimes lastAccessTimeInfos")
return lastAccessTimeInfos
end
def update(fileName, text)
dirName = File.dirname(fileName)
tableName = getTableName(dirName)
time = getCurrentTime
executeSql("UPDATE #{tableName} SET text=?, time=? WHERE fileName=?", text, time, fileName);
end
def getText(fileName)
dirName = File.dirname(fileName)
tableName = getTableName(dirName)
text = ''
result = executeSql("SELECT text FROM #{tableName} WHERE fileName=?", fileName)
result.each do |row|
text += row.first
end
return text
end
def isChatFileName(fileName)
base = File.basename(fileName)
return ( base == "chat.json" )
end
def getChatTime(fileName)
logging(fileName, "getChatTime fileName")
dirName = File.dirname(fileName)
tableName = getChatTableName(dirName)
createChatTable(tableName)
maxTime = 0
numberLimit = $chatMessageDataLogAllLineMax
result = executeSql("SELECT MAX(time) FROM #{tableName} WHERE number<#{numberLimit}")
result.each do |row|
maxTime = row.first.to_f
end
logging(maxTime, "getChatTime maxTime")
return maxTime
end
def getTime(fileName)
logging(fileName, "getTime fileName")
if( isChatFileName(fileName) )
return getChatTime(fileName)
end
dirName = File.dirname(fileName)
tableName = getTableName(dirName)
time = 0
result = executeSql("SELECT time FROM #{tableName} WHERE fileName=?", fileName)
result.each do |row|
time = row.first.to_f
end
return time.to_f
end
def createTable(dirName)
if( isExistDir?(dirName) )
raise "このプレイルームはすでに作成済みです。"
end
tableName = getTableName(dirName)
sql = <<SQL
CREATE TABLE #{tableName} (
fileName CHAR(255) UNIQUE,
text LONGBLOB,
time DECIMAL(15,5)
);
SQL
executeSql(sql)
@allTableNames = []
insertNewData(dirName)
end
def insertNewData(dirName)
sourceDir = 'saveData_forNewCreation'
saveFileNames = $saveFiles.values
saveFileNames.each do |saveFileName|
sourceFileName = File.join(sourceDir, saveFileName)
logging(sourceFileName, "insertNewData sourceFileName")
next unless( File.exist?(sourceFileName) )
logging(sourceFileName, "insertNewData exist sourceFileName")
text = File.readlines(sourceFileName).join
fileName = File.join(dirName, saveFileName)
logging(fileName, "insertNewData fileName")
createData(fileName, text)
end
end
def getChatTableName(dirName)
return getTableName(dirName + "_chat")
end
def createChatTable(tableName)
createChatTableOnly(tableName)
createChatTableInstance(tableName)
end
def createChatTableOnly(tableName)
logging(tableName, "createChatTableOnly tableName")
return if( isExistTable?(tableName) )
logging(tableName, "createChatTableOnly tableName NOT exist")
sql = <<SQL
CREATE TABLE #{tableName} (
number INT UNIQUE,
text LONGBLOB,
time DECIMAL(15,5)
);
SQL
executeSql(sql)
@allTableNames = []
end
def executeMaxSql(tableName, item)
sql = "SELECT MAX(#{item}) FROM #{tableName}"
logging(sql, "executeCountSql sql")
result = executeSql(sql)
row = result.fetch_row
logging(row, "result.fetch_row")
return -1 if( row.nil? )
maxNumber = row.first
logging(maxNumber, "row.first")
if( maxNumber == nil )
maxNumber = -1
else
maxNumber = maxNumber.to_i
end
return maxNumber
end
def createChatTableInstance(tableName)
logging(tableName, "createChatTableInstance tableName")
numberLimit = $chatMessageDataLogAllLineMax
logging(numberLimit, "createChatTableInstance numberLimit")
maxNumber = executeMaxSql(tableName, "number")
logging(maxNumber, "maxNumber")
return if( maxNumber >= numberLimit )
((maxNumber + 1) ... numberLimit).each do |number|
logging(number, "createChatTableInstance each number")
text = ""
time = getCurrentTime
executeSql("INSERT INTO #{tableName} VALUES (?, ?, ?)", number, text, time)
end
end
def removeSaveDir(dirName)
tableName = getTableName(dirName)
deleteTable(tableName)
chatTableName = getChatTableName(dirName)
deleteTable(chatTableName)
end
def deleteTable(tableName)
return unless( isExistTable?(tableName))
executeSql("DROP TABLE #{tableName}")
end
def createData(fileName, text)
dirName = File.dirname(fileName)
tableName = getTableName(dirName)
time = getCurrentTime
executeSql("INSERT INTO #{tableName} VALUES (?, ?, ?)", fileName, text, time)
end
def getCurrentTime
@currentMilliTime ||= Time.now.to_f;
return @currentMilliTime;
end
def isExist?(fileName)
dirName = File.dirname(fileName)
return false unless( isExistDir?(dirName) )
tableName = getTableName(dirName)
count = 0
begin
count = executeCountSql("SELECT count(*) FROM #{tableName} WHERE fileName=?", fileName)
rescue
end
return (count >= 1)
end
def executeCountSql(sql, *args)
logging(sql, "executeCountSql sql")
result = executeSql(sql, *args)
row = result.fetch_row
return 0 if( row.nil? )
first = row.first
count = first.to_i
logging(count, "executeCountSql count")
return count
end
def loadSaveFileForChat(typeName, fileName, lastUpdateTimes)
lastTime = lastUpdateTimes[typeName]
logging(lastUpdateTimes, "loadSaveFileForChat lastUpdateTimes")
logging(lastTime, "loadSaveFileForChat lastTime")
dirName = File.dirname(fileName)
tableName = getChatTableName(dirName)
createChatTable(tableName)
lines = []
result = executeSql("SELECT text,time FROM #{tableName} WHERE (time>#{lastTime}) and (text!=\"\") ORDER BY time")
result.each do |row|
text = row.shift
lines << text
lastUpdateTimes[typeName] = row.shift.to_f
end
if( lines.empty? )
return {}
end
data = lines.collect{|line| DodontoFServer.getJsonDataFromText(line.chomp) }
saveData = {"chatMessageDataLog" => data}
return saveData
end
def isSaveData(dirName)
saveDir = File.join($SAVE_DATA_DIR, "saveData")
saveDir2 = File.join(saveDir, "")
logging(saveDir, "saveDir")
logging(saveDir2, "saveDir2")
return (( saveDir == dirName ) || ( dirName.index(saveDir2) == 0 ))
end
def isExistTable?(tableName)
logging(tableName, "isExistDir? tableName")
@allTableNames ||= []
if( @allTableNames.empty? )
result = executeSql("SHOW TABLES;")
result.each do |row|
@allTableNames << row.first
end
end
logging(@allTableNames, "@allTableNames")
isExist = @allTableNames.include?(tableName)
logging(isExist, "isExistDir? isExist")
return isExist
end
def isExistDir?(dirName)
logging(dirName, "isExistDir? dirName")
unless( isSaveData(dirName) )
logging("unless( isSaveData(dirName) )")
return File.exist?(dirName)
end
logging(dirName, "this dir is SaveData dir")
tableName = getTableName(dirName)
isExistTable?(tableName)
end
def sendChatMessage(chatMessageData, fileName)
dirName = File.dirname(fileName)
tableName = getChatTableName(dirName)
createChatTable(tableName)
isReadOnly = false
open(nil, isReadOnly, tableName) do
time = getCurrentTime
text = DodontoFServer.getTextFromJsonData([time, chatMessageData])
numberLimit = $chatMessageDataLogAllLineMax
oldestNumber = 0
result = executeSql("SELECT number FROM #{tableName} WHERE number<#{numberLimit} ORDER BY time limit 1")
result.each do |row|
oldestNumber = row.first
end
logging(oldestNumber, "oldestNumber")
executeSql("UPDATE #{tableName} SET text=?,time=? WHERE (number=#{oldestNumber})", text, time);
end
end
def loadSaveFileDataForChatType(trueSaveFileName, saveDataForChat)
logging("loadSaveFileDataForChatType begin")
dirName = File.dirname(trueSaveFileName)
tableName = getChatTableName(dirName)
createChatTable(tableName)
numberLimit = $chatMessageDataLogAllLineMax
(0 ... numberLimit).each do |number|
count = executeCountSql("SELECT count(*) FROM #{tableName} WHERE (number=?)", number);
next if( count == 0 )
text = ""
unless( saveDataForChat.nil? )
chatData = saveDataForChat[number]
unless( chatData.nil? )
text = DodontoFServer.getTextFromJsonData(chatData)
end
end
time = getCurrentTime
executeSql("UPDATE #{tableName} SET text=?,time=? WHERE (number=?)", text, time, number);
end
logging("loadSaveFileDataForChatType end")
end
def deleteChatLogBySaveFile(trueSaveFileName)
dirName = File.dirname(trueSaveFileName)
tableName = getChatTableName(dirName)
deleteTable(tableName)
createChatTable(tableName)
end
end
class MySqlAccesser
def self.setSaveDataManager(manager)
@@saveDataManager = manager
end
def isExist?(fileName)
@@saveDataManager.isExist?(fileName)
end
def isExistDir?(dirName)
@@saveDataManager.isExistDir?(dirName)
end
def createFile(fileName, text)
@@saveDataManager.changeText(fileName, text)
end
def isSaveData(fileName)
@@saveDataManager.isSaveData(fileName)
end
def getSaveFileText(fileName)
@@saveDataManager.getText(fileName)
end
def getSaveFileTimeStamp(fileName)
@@saveDataManager.getTime(fileName)
end
def sendChatMessage(chatMessageData, saveFileName)
@@saveDataManager.sendChatMessage(chatMessageData, saveFileName)
end
def loadSaveFileForChat(typeName, fileName, lastUpdateTimes)
@@saveDataManager.loadSaveFileForChat(typeName, fileName, lastUpdateTimes)
end
def loadSaveFileDataForChatType(trueSaveFileName, saveDataForChat)
@@saveDataManager.loadSaveFileDataForChatType(trueSaveFileName, saveDataForChat)
end
def deleteChatLogBySaveFile(trueSaveFileName)
@@saveDataManager.deleteChatLogBySaveFile(trueSaveFileName)
end
end
class SaveDirInfoMySql < SaveDirInfo
def self.setSaveDataManager(manager)
@@saveDataManager = manager
end
def createDir()
dirName = getDirName()
@@saveDataManager.createTable(dirName)
end
def removeSaveDir(saveDataDirIndex)
dirName = getDirNameByIndex(saveDataDirIndex)
@@saveDataManager.removeSaveDir(dirName)
end
def getExistFileNames(dirName, fileNames)
existFileNames = []
fileNames.each do |fileName|
full_fileName = File.join(dirName, fileName)
logging(full_fileName, "getExistFileNames full_fileName")
if( @@saveDataManager.isExistDir?(full_fileName) or
@@saveDataManager.isExist?(full_fileName) )
logging(full_fileName, "getExistFileNames full_fileName exist")
existFileNames << full_fileName
end
end
logging(existFileNames, "getExistFileNames existFileNames")
return existFileNames
end
def getSaveDataLastAccessTimes(fileNames, roomNumberRange)
saveDirs = getSaveDataDirs(roomNumberRange)
return @@saveDataManager.getSaveDataLastAccessTimes(saveDirs, roomNumberRange)
end
end
require "FileLock"
class FileLockMySql < FileLock
def self.setSaveDataManager(manager)
@@saveDataManager = manager
end
def initialize(lockFileName, isReadOnly = false)
@lockFileName = lockFileName
@isReadOnly = isReadOnly
end
def lock(&action)
@@saveDataManager.open(@lockFileName, @isReadOnly) do
action.call
end
end
end
class DodontoFServer_MySql < DodontoFServer
def getDataAccesser
@dataAccesser ||= MySqlAccesser.new
@dataAccesser
end
def addTextToFile(fileName, addedText)
return super unless( getDataAccesser().isSaveData(fileName) )
text = getSaveTextOnFileLocked(fileName)
text += addedText
createFile(fileName, text)
end
def createFile(fileName, text)
return super unless( getDataAccesser().isSaveData(fileName) )
@dataAccesser.createFile(fileName, text)
end
def getSaveTextOnFileLocked(fileName)
return super unless( getDataAccesser().isSaveData(fileName) )
text = getDataAccesser().getSaveFileText(fileName)
return "{}" if( text.nil? )
return text
end
def getSaveFileLock(fileName, isReadOnly = false)
return super unless( getDataAccesser().isSaveData(fileName) )
begin
return FileLockMySql.new(fileName, isReadOnly)
rescue => e
loggingForce(@saveDirInfo.inspect, "when getSaveFileLock error : @saveDirInfo.inspect");
raise
end
end
def getSaveFileTimeStamp(fileName)
return super unless( getDataAccesser().isSaveData(fileName) )
getDataAccesser().getSaveFileTimeStamp(fileName)
end
def isExist?(fileName)
return super unless( getDataAccesser().isSaveData(fileName) )
getDataAccesser().isExist?(fileName)
end
def isExistDir?(dirName)
return super unless( getDataAccesser().isSaveData(dirName) )
getDataAccesser().isExistDir?(dirName)
end
def readLines(fileName)
return super unless( getDataAccesser().isSaveData(fileName) )
saveData = getSaveTextOnFileLocked(fileName)
lines = saveData.split(/\n/)
return lines
end
def loadSaveFileForChat(typeName, saveFileName)
getDataAccesser().loadSaveFileForChat(typeName, saveFileName, @lastUpdateTimes)
end
def loadSaveFile(typeName, saveFileName)
if( isChatType(typeName) )
return loadSaveFileForChat(typeName, saveFileName)
end
return super
end
def sendChatMessageByChatData(chatData)
logging(chatData, "sendChatMessage chatData")
saveFileName = @saveFiles['chatMessageDataLog']
getDataAccesser().sendChatMessage(chatData, saveFileName)
end
def loadSaveFileDataForEachType(fileTypeName, trueSaveFileName, saveDataForType)
if( isChatType(fileTypeName) )
getDataAccesser().loadSaveFileDataForChatType(trueSaveFileName, saveDataForType[fileTypeName])
return
end
super
end
def deleteChatLogBySaveFile(trueSaveFileName)
getDataAccesser().deleteChatLogBySaveFile(trueSaveFileName)
end
def getTestResponseText
"「どどんとふ(MySQL)」の動作環境は正常に起動しています。";
end
end
def mainMySql(cgiParams)
saveDataManager = SaveDataManagerOnMySql.new
begin
FileLockMySql.setSaveDataManager(saveDataManager)
MySqlAccesser.setSaveDataManager(saveDataManager)
SaveDirInfoMySql.setSaveDataManager(saveDataManager)
server = DodontoFServer_MySql.new(SaveDirInfoMySql.new(), cgiParams)
printResult(server)
ensure
saveDataManager.closeDb
end
end
if( $0 === __FILE__ )
initLog();
cgiParams = getCgiParams()
mainMySql(cgiParams)
end