-
Notifications
You must be signed in to change notification settings - Fork 20
/
index.js
712 lines (661 loc) · 17.4 KB
/
index.js
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
const fs = require('fs')
const path = require('path')
const pkg = require('./package')
const async = require('async')
const glob = require('multi-glob').glob
const xml = require('xml2js').Parser()
const sort = require('sort-keys')
const unidecode = require('unidecode')
const sanitizeFilename = require('sanitize-filename')
const dats = require('./dats.json')
const request = require('request')
const download = require('./download')
const replaceAll = require('replace-string')
const dateFormat = require('dateformat')
async function start() {
await download()
async.mapValues(dats, processDat, function (err, results) {
if (err) {
throw err
}
})
}
start()
/**
* Verifies whether or not the entry is valid to be added to the DAT.
*/
function validEntry(gameName) {
// Skip all BIOS files.
if (gameName.indexOf('[BIOS]') >= 0) {
return false
}
// Skip all bad dumps
if (gameName.indexOf('[b]') >= 0) {
return false
}
// Skip all demos and programs.
if (gameName.indexOf('(Test Program)') >= 0) {
return false
}
if (gameName.indexOf(' (Demo)') >= 0) {
return false
}
if (gameName.indexOf('(Program)') >= 0) {
return false
}
if (gameName.indexOf('- Program -') >= 0) {
return false
}
if (gameName.indexOf('Test Cartridge') >= 0) {
return false
}
if (gameName.indexOf('Super Nintendo Tester') >= 0) {
return false
}
// The serial conflicts with Sonic Adventure 2
// https://github.com/libretro/libretro-database/issues/1444
if (gameName.indexOf('Phantasy Star Online' >= 0) && gameName.indexOf('(Rev B)') >= 0) {
return false
}
return true
}
/**
* Act on a DAT file.
*/
function processDat(datsInfo, name, done) {
// Retrieve all associated files for the DAT.
glob(datsInfo.files, function (err, files) {
if (!files) {
console.log('EMPTY', name)
}
// Output the files to the user.
//console.log(name, files)
// Loop through each given XML file associated with the DAT.
async.map(files, processXml, function (err, results) {
// Error handling.
if (err) {
return done(err)
}
// Loop through the results and build a game database.
var games = {}
for (var i in results) {
for (var game in results[i]) {
var gameName = results[i][game].title
if (validEntry(gameName)) {
while (gameName in games) {
gameName = gameName + ' '
}
games[gameName] = results[i][game]
}
}
}
if (Object.entries(games).length === 0) {
return
}
var output = getHeader(name, pkg)
// Loop through the sorted games database, and output the rom.
for (let game in sort(games)) {
let rom = games[game]
game = game.trim()
let gameOutput = getGameEntry(game, rom, name)
output += gameOutput
}
// Save the new DAT file.
var outputFile = `${name}.dat`
//console.log(outputFile)
fs.writeFile(outputFile, output, done)
})
})
}
/**
* Construct a header for a DAT file.
*/
function getHeader(name, pkg) {
const version = dateFormat(new Date(), "yyyy.mm.dd")
return `clrmamepro (
name "${path.basename(name)}"
description "${path.basename(name)}"
version "${version}"
homepage "${pkg.homepage}"
)\n`
}
/**
* Construct a game entry for a DAT file.
*/
function getGameEntry(game, rom, name) {
// Replace Unicode characters, and trim the title.
let gameName = unidecode(game).trim();
// Clean the name some more.
gameName = gameName
.replace('Games (Europe)\\', '')
.replace('Games\\', '')
.replace('Games (USA)\\', '')
.replace('Games (Japan)\\', '')
.replace('Games (cdi)\\', '')
.replace('Games (elf)\\', '')
.replace('MISSING\\', '')
.replace('Samplers\\', '')
.replace('Multimedia\\', '')
.replace('(Sony Imagesoft)', '')
.replace('(Sony)', '')
.replace('(Sega)', '')
.replace('(Riot)', '')
.replace('(Bignet - Micronet)', '')
.replace('(Bignet)', '')
.replace('(M4)', '')
.replace('(Acclaim - Domark)', '')
.replace('(Acclaim)', '')
.replace('(Gametek)', '')
.replace('(Good Deal Games)', '')
.replace('(Good Deal Games - Stargate Films)', '')
.replace('(Sega - Tec Toy)', '')
.replace('(SIMS)', '')
.replace('(Sims)', '')
.replace('(Tecmo)', '')
.replace('(Sensible Software - Sony)', '')
.replace('(Taito)', '')
.replace('(Infogrames)', '')
.replace('(Interplay)', '')
.replace('(Domark)', '')
.replace('(Pony Canyon)', '')
.replace('(Panasonic)', '')
.replace('(LG)', '')
.replace('(Yoshimoto Kogyo)', '')
.replace('(Studio 3DO)', '')
.replace('(GoldStar)', '')
.replace('(Human)', '')
.replace('(Bandai)', '')
.replace('(Activision)', '')
.replace('(Infomedia)', '')
.replace('(RE)', '')
.replace('(Data East - Sega)', '')
.replace('(ReadySoft)', '')
.replace('(Virgin)', '')
.replace('[a]', '(Alt 1)')
.replace('[a1]', '(Alt 1)')
.replace('[a2]', '(Alt 2)')
.replace('[a3]', '(Alt 3)')
.replace('[a4]', '(Alt 4)')
.replace('[a5]', '(Alt 5)')
.replace('[a6]', '(Alt 6)')
.replace('[a7]', '(Alt 7)')
.replace('[a8]', '(Alt 8)')
.replace('[a9]', '(Alt 9)')
.replace('[a10]', '(Alt 10)')
.replace('[a11]', '(Alt 11)')
.replace('(EA Sports)', '')
.replace('(Electronic Arts)', '')
.replace('(Digital Pictures)', '')
.replace('(Good Deal Games - Oldergames)', '')
.replace('(Victor)', '')
.replace('(JVC)', '')
.replace('(Wolf Team)', '')
.replace('(Polydor K.K.)', '')
.replace('(NTSC)', '')
.replace(' (Mega Power)', '')
.replace(' (SMW Hack)', '')
.replace('Games - Unlicensed\\', '')
.replace('Magazines\\', '')
.replace('Applications (cdi)\\', '')
.replace('Applications (elf)\\', '')
.replace('Demos (cdi)\\', '')
.replace('Demos (elf)\\', '')
.replace(' (United States)', ' (USA)')
//does not seem to improve situation nowadays .replace('(PAL)', '(Europe)')
.replace('(EU)', '(Europe)')
.replace('(en)', '')
.replace(')(beta)', ') (Beta)')
.replace('(fr)', '(France)')
.replace('(es)', '(Spain)')
.replace('(JP)', '(Japan)')
.replace('(US)', '(USA)')
.replace('(AE)', '(United Arab Emirates)')
.replace('(AL)', '(Albania)')
.replace('(AS)', '(Asia)')
.replace('(AT)', '(Austria)')
.replace('(AU)', '(Australia)')
.replace('(BA)', '(Bosnia and Herzegovina)')
.replace('(BE)', '(Belgium)')
.replace('(BG)', '(Bulgaria)')
.replace('(BR)', '(Brazil)')
.replace('(CA)', '(Canada)')
.replace('(CH)', '(Switzerland)')
.replace('(CL)', '(Chile)')
.replace('(CN)', '(China)')
.replace('(CS)', '(Serbia and Montenegro)')
.replace('(CY)', '(Cyprus)')
.replace('(CZ)', '(Czech Republic)')
.replace('(DE)', '(Germany)')
.replace('(DK)', '(Denmark)')
.replace('(EE)', '(Estonia)')
.replace('(EG)', '(Egypt)')
.replace('(ES)', '(Spain)')
.replace('(FI)', '(Finland)')
.replace('(FR)', '(France)')
.replace('(GB)', '(United Kingdom)')
.replace('(GR)', '(Greece)')
.replace('(HK)', '(Hong Kong)')
.replace('(HR)', '(Croatia)')
.replace('(HU)', '(Hungary)')
.replace('(ID)', '(Indonesia)')
.replace('(IE)', '(Ireland)')
.replace('(IL)', '(Israel)')
.replace('(IN)', '(India)')
.replace('(IR)', '(Iran)')
.replace('(IS)', '(Iceland)')
.replace('(IT)', '(Italy)')
.replace('(JO)', '(Jordan)')
.replace('(JP)', '(Japan)')
.replace('(KR)', '(Korea)')
.replace('(LT)', '(Lithuania)')
.replace('(LU)', '(Luxembourg)')
.replace('(LV)', '(Latvia)')
.replace('(MN)', '(Mongolia)')
.replace('(MX)', '(Mexico)')
.replace('(MY)', '(Malaysia)')
.replace('(NL)', '(Netherlands)')
.replace('(NO)', '(Norway)')
// conflicts with (NP) flag .replace('(NP)', '(Nepal)')
.replace('(NZ)', '(New Zealand)')
.replace('(OM)', '(Oman)')
.replace('(PE)', '(Peru)')
.replace('(PH)', '(Philippines)')
.replace('(PL)', '(Poland)')
.replace('(PT)', '(Portugal)')
.replace('(QA)', '(Qatar)')
.replace('(RO)', '(Romania)')
.replace('(RU)', '(Russia)')
.replace('(SE)', '(Sweden)')
.replace('(SG)', '(Singapore)')
.replace('(SI)', '(Slovenia)')
.replace('(SK)', '(Slovakia)')
.replace('(TH)', '(Thailand)')
.replace('(TR)', '(Turkey)')
.replace('(TW)', '(Taiwan)')
.replace('(VN)', '(Vietnam)')
.replace('(YU)', '(Yugoslavia)')
.replace('(ZA)', '(South Africa)')
.replace('(BY)', '(Belarus)')
.replace('(UA)', '(Ukraine)')
.replace('(proto)', '(Proto)')
.replace('[!]', '')
.replace('[joystick]', '')
.replace('Applications\\', '')
.replace(''', '\'')
.replace('[MIA] ', '')
// Remove the " of y" in " (Disc x of y)"
const diskRegexp = /\(((Tape|Dis[ck]) \d{1,2}) of \d{1,2}\)/;
const diskArray = diskRegexp.exec(gameName);
if (diskArray !== null) {
gameName = gameName.replace(diskRegexp, "($1)")
}
// Parse release date and remove from title
let extraParams = ''
const dateRegexp = /\((\d{4})-?(\d{0,2})-?(\d{0,2})\)/;
const dateArray = dateRegexp.exec(gameName);
if (dateArray !== null) {
if (dateArray[1] > 1950 && dateArray[1] < 2025) {
extraParams += `\n\treleaseyear "${dateArray[1]}"`
if (dateArray[2] !== '' && dateArray[2] > 0 && dateArray[2] < 13) {
extraParams += `\n\treleasemonth "${dateArray[2]}"`
if (dateArray[3] !== '' && dateArray[3] > 0 && dateArray[3] < 32) {
extraParams += `\n\treleaseday "${dateArray[3]}"`
}
}
gameName = gameName.replace(dateRegexp, '')
}
}
// Remove unclear TOSEC date indications
gameName = gameName.replace('(19xx)', '')
.replace('(197x)', '')
.replace('(198x)', '')
.replace('(199x)', '')
.replace('(20xx)', '')
.replace('(200x)', '')
.replace('(201x)', '')
.replace('(202x)', '')
gameName = gameName.replace(' ', ' ')
.replace('(RE1)', '(Rev 1)')
.replace('(RE2)', '(Rev 2)')
.replace('(RE3)', '(Rev 3)')
.replace('(RE4)', '(Rev 4)')
.replace('(RE5)', '(Rev 5)')
.replace('(RE6)', '(Rev 6)')
.replace(')(', ') (')
.replace(')(', ') (')
.replace(')(', ') (')
.replace(')(', ') (')
.trim()
// Protect against #### - Game Name (Country) -- Remove the prefixing numbers.
// Game Boy Advance only does this numbering?
if (name.includes('Game Boy Advance') || name.includes('Nintendo DS')) {
if (/^[0-9xyz][0-9][0-9][0-9] - /.test(gameName)) {
gameName = gameName.substring(7)
}
}
// The filename must be a valid filename.
let gameFile = sanitizeFilename(path.basename(unidecode(rom.name)))
// Skip any .sav files.
if (gameFile.indexOf('.sav') >= 0) {
return ''
}
let gameParams = `name "${gameFile}"`
if (rom.size) {
gameParams += ` size ${rom.size}`
}
if (rom.crc) {
gameParams += ` crc ${rom.crc.toUpperCase()}`
}
if (rom.md5) {
gameParams += ` md5 ${rom.md5.toUpperCase()}`
}
if (rom.sha1) {
gameParams += ` sha1 ${rom.sha1.toUpperCase()}`
}
let countries = require('./countries')
for (let country of countries) {
if (game.includes('(' + country + ')') || gameName.includes('(' + country + ')')) {
extraParams += `\n\tregion "${country}"`
}
}
// Handle when there's a serial.
let ignoreserials = [
'1',
1,
'n/a',
'N/A',
'!none'
]
if (rom.serial && !ignoreserials.includes(rom.serial.trim())) {
// Multiple serial split into multiple games.
let seperator = ' / '
if (rom.serial.includes(', ')) {
seperator = ', '
}
let serials = rom.serial.split(seperator)
let output = ''
for (let serial of serials) {
let ogParams = extraParams
serial = cleanSerial(serial)
if (serial) {
let discNumber = grabDiscNumber(gameName)
if (discNumber !== false) {
output += `\ngame (
name "${gameName}"
description "${gameName}"${ogParams}
serial "${serial}"
rom ( ${gameParams} serial "${serial}" )
)`
serial = serial + '-' + (discNumber - 1).toString()
}
ogParams += `\n\tserial "${serial}"`
output += `\ngame (
name "${gameName}"
description "${gameName}"${ogParams}
rom ( ${gameParams} serial "${serial}" )
)`
}
}
return output
}
return `\ngame (
name "${gameName}"
description "${gameName}"${extraParams}
rom ( ${gameParams} )
)`
}
function grabDiscNumber(gameName) {
gameName = gameName.replace('(Disk ', '(Disc ')
const regex = /\(Disc (\d+)/gm;
let m;
while ((m = regex.exec(gameName)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++
}
let output = parseInt(m[1])
if (!Number.isNaN(output)) {
return output
}
}
return false
}
function cleanSerial(serial) {
if (!serial) {
return ''
}
let output = serial.trim()
output = replaceAll(output, ' ', '-')
output = replaceAll(output, '#', '')
if (output.charAt(0) == '-') {
output = output.substr(1)
}
return output.trim()
}
/**
* Process the given XML file.
*/
function processXml(filepath, done) {
if (fs.lstatSync(filepath).isDirectory()) {
return done(null, [])
}
// Read in the file asyncronously.
fs.readFile(filepath, {encoding: 'utf8'}, (err, data) => {
if (err) {
return done(err)
}
// Convert the string to a JSON object.
console.log(filepath)
xml.parseString(data, (error, dat) => {
if (error) {
return done(error)
}
// Convert the JSON object to a Games array.
var result = getGamesFromXml(filepath, dat)
// We have the result, move to the next one.
done(null, result)
})
})
}
/**
* Convert an XML dat object to a games array.
*/
function getGamesFromXml(filepath, dat) {
var dir = path.dirname(filepath)
var out = {}
var header = dat.datafile || dat.dat
var games = header.machine || header.game || null
// Find the games array.
if (!games) {
if (header.games && header.games[0] && header.games[0].game) {
games = header.games[0].game
}
else {
console.log('No Games Found: ', header.header[0].name[0])
return {}
}
}
// Loop through each game.
games.forEach(function (game, i) {
// Set up the entries to watch for.
var title = null
var largestData = 0
var dataTracks = []
var finalPrimary = null
var finalBin = null
var finalIso = null
var finalImg = null
var finalEntry = null
// Find all the entries.
if (game.rom) {
if (game.title) {
title = game.title
}
else if (game['$'] && game['$'].name) {
title = game['$'].name
}
else if (game.description && game.description[0]) {
title = game.description[0]
}
else if (game.rom[0]['$']) {
title = path.basename(game.rom[0]['$'].name)
}
else {
console.log('Could not find title for....')
console.log(game, i)
process.exit()
}
for (var x in game.rom) {
var rom = game.rom[x]['$']
let lowerCaseName = rom.name.toLowerCase()
let extname = path.extname(lowerCaseName)
if (lowerCaseName.endsWith('.cue')) {
dataTracks = cueDataTracks(path.join(dir, rom.name))
}
else if (lowerCaseName.endsWith('.gdi')) {
dataTracks = gdiDataTracks(path.join(dir, rom.name))
}
else if (dataTracks.includes(rom.name) && Number(rom.size) > largestData) {
finalPrimary = rom
largestData = Number(rom.size)
}
else if (lowerCaseName.endsWith('.bin') && !finalBin) {
finalBin = rom
}
else if (lowerCaseName.endsWith('.iso') && !finalIso) {
finalIso = rom
}
else if (lowerCaseName.endsWith('.img') && !finalImg) {
finalImg = rom
}
else if (lowerCaseName.endsWith('.txt')) {
// Ignore text files
}
else if (extname == '.snd') {
// Ignore
}
else if (extname == '.cg1') {
// Ignore
}
else if (extname == '.eg1') {
// Ignore
}
else if (extname == '.mg1') {
// Ignore
}
else if (extname.length == 0) {
// Ignore zero extension
}
else {
finalEntry = rom
}
}
}
else if (!game.trurip) {
// AdvanceSCENE
title = game.title
finalIso = {
name: game.title + '.iso',
size: game.romSize,
serial: game.serial,
crc: game.files[0].romCRC[0]['_']
}
}
else {
console.log('Could not entry for....')
if (game['$']) {
console.log(game['$'], i)
}
else {
console.log(game, i)
}
return;
}
// Choose which entry to use.
var final = null
if (finalPrimary) {
final = finalPrimary
}
else if (finalBin) {
final = finalBin
}
else if (finalIso) {
final = finalIso
}
else if (finalImg) {
final = finalImg
}
else if (finalEntry) {
final = finalEntry
}
if (final) {
final.title = title
if (game.serial) {
final.serial = game.serial[0]
}
if (final.crc) {
out[final.crc] = final
}
else if (final.status == 'nodump') {
// Nothing.
console.log("No dump for " + final.title)
}
else {
console.log("Couldn't find key for....")
console.log(final)
//process.exit()
}
}
})
return out
}
function cueDataTracks(filepath) {
var data
try {
data = fs.readFileSync(filepath, {encoding: 'utf8'})
} catch (err) {
return []
}
var fileStmt = /^\s*FILE\s+"([^"]+)"\s+(.*)$/
var trackStmt = /^\s*TRACK\s+(\d+)\s+(.*)$/
var tracks = []
var lastFile = null
lines = data.split(/\r?\n/)
for (var line in lines) {
line = lines[line]
var match
match = line.match(fileStmt)
if (match) {
lastFile = match[1]
continue
}
match = line.match(trackStmt)
if (match && lastFile != null && match[2] != "AUDIO") {
tracks.push(lastFile)
}
}
return tracks
}
function gdiDataTracks(filepath) {
var data
try {
data = fs.readFileSync(filepath, {encoding: 'utf8'})
} catch (err) {
return []
}
var stmt = /^\s*\d+\s+\d+\s+(\d+)\s+(\d+)\s+"([^"]+)"\s+\d+$/
var tracks = []
lines = data.split(/\r?\n/)
for (var line in lines) {
if (line == 0) {
continue
}
line = lines[line]
var match
match = line.match(stmt)
if (match && !(match[1] == 0 && match[2] == 2352)) {
tracks.push(match[3])
}
}
return tracks
}