forked from detain/skyscraper
-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathskyscraper.cpp
More file actions
1468 lines (1356 loc) · 55 KB
/
Copy pathskyscraper.cpp
File metadata and controls
1468 lines (1356 loc) · 55 KB
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
/***************************************************************************
* skyscraper.cpp
*
* Wed Jun 7 12:00:00 CEST 2017
* Copyright 2017 Lars Muldjord
* muldjordlars@gmail.com
****************************************************************************/
/*
* This file is part of skyscraper.
*
* skyscraper is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* skyscraper is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with skyscraper; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
#include "skyscraper.h"
#include "attractmode.h"
#include "cli.h"
#include "config.h"
#include "emulationstation.h"
#include "esde.h"
#include "pegasus.h"
#include "settings.h"
#include "strtools.h"
#include <QDebug>
#include <QDirIterator>
#include <QDomDocument>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMutexLocker>
#include <QProcess>
#include <QSettings>
#include <QStorageInfo>
#include <QStringBuilder>
#include <QThread>
#include <QTimer>
#include <iostream>
Skyscraper::Skyscraper(const QString ¤tDir) {
qRegisterMetaType<GameEntry>("GameEntry");
manager = QSharedPointer<NetManager>(new NetManager());
config.currentDir = currentDir;
printf("%s", StrTools::getVersionHeader().toStdString().c_str());
}
Skyscraper::~Skyscraper() { frontend->deleteLater(); }
void Skyscraper::run() {
if (config.platform.isEmpty()) {
if (config.cacheOptions == "purge:all") {
Cache::purgeAllPlatform(config, this);
exit(0);
} else if (config.cacheOptions.contains("report:missing")) {
Cache::reportAllPlatform(config, this);
exit(0);
} else if (config.cacheOptions == "vacuum") {
Cache::vacuumAllPlatform(config, this);
exit(0);
} else if (config.cacheOptions == "validate") {
Cache::validateAllPlatform(config, this);
exit(0);
} else {
exit(1);
}
}
cacheScrapeMode = config.scraper == "cache";
doCacheScraping = cacheScrapeMode && !config.pretend;
printf("Platform: '\033[1;32m%s\033[0m'\n",
config.platform.toStdString().c_str());
printf("Scraping module: '\033[1;32m%s\033[0m'\n",
config.scraper.toStdString().c_str());
if (cacheScrapeMode) {
printf("Frontend: '\033[1;32m%s\033[0m'\n",
config.frontend.toStdString().c_str());
if (!config.frontendExtra.isEmpty()) {
printf("Extra: '\033[1;32m%s\033[0m'\n",
config.frontendExtra.toStdString().c_str());
}
}
printf("Input folder: '\033[1;32m%s\033[0m'\n",
config.inputFolder.toStdString().c_str());
printf("Game list folder: '\033[1;32m%s\033[0m'\n",
config.gameListFolder.toStdString().c_str());
printf("Covers folder: '\033[1;32m%s\033[0m'\n",
config.coversFolder.toStdString().c_str());
printf("Screenshots folder: '\033[1;32m%s\033[0m'\n",
config.screenshotsFolder.toStdString().c_str());
printf("Wheels folder: '\033[1;32m%s\033[0m'\n",
config.wheelsFolder.toStdString().c_str());
printf("Marquees folder: '\033[1;32m%s\033[0m'\n",
config.marqueesFolder.toStdString().c_str());
printf("Textures folder: '\033[1;32m%s\033[0m'\n",
config.texturesFolder.toStdString().c_str());
if (config.videos) {
printf("Videos folder: '\033[1;32m%s\033[0m'\n",
config.videosFolder.toStdString().c_str());
}
if (config.manuals) {
printf("Manuals folder: '\033[1;32m%s\033[0m'\n",
config.manualsFolder.toStdString().c_str());
}
printf("Cache folder: '\033[1;32m%s\033[0m'\n",
config.cacheFolder.toStdString().c_str());
if (config.scraper == "import") {
printf("Import folder: '\033[1;32m%s\033[0m'\n",
config.importFolder.toStdString().c_str());
}
printf("\n");
if (config.hints) {
showHint();
}
prepareScraping();
doneThreads = 0;
notFound = 0;
found = 0;
avgCompleteness = 0;
avgSearchMatch = 0;
if (config.unpack) {
QProcess decProc;
decProc.setReadChannel(QProcess::StandardOutput);
decProc.start("which", QStringList({"7z"}));
decProc.waitForFinished(10000);
if (!decProc.readAllStandardOutput().contains("7z")) {
printf("Couldn't find '7z' command. 7z is required by the "
"'--flags unpack' flag. On Debian derivatives such as "
"RetroPie you can install it with 'sudo apt install "
"p7zip-full'.\n\nNow quitting...\n");
exit(1);
}
}
cache = QSharedPointer<Cache>(new Cache(config.cacheFolder));
if (cacheScrapeMode || cache->createFolders(config.scraper)) {
if (cacheScrapeMode && !cache->read()) {
printf("No resources for this platform found in the resource "
"cache ('%s'). Please verify the path of the cache or "
"specify a scraping module with '-s' to gather some "
"resources before trying to generate a game list. Check "
"all available modules with '--help'.\n",
config.cacheFolder.toStdString().c_str());
exit(1);
}
} else {
printf("Couldn't create cache folders, please check folder "
"permissions and try again...\n");
exit(1);
}
if (config.verbosity || config.cacheOptions == "show") {
cache->showStats(config.cacheOptions == "show" ? 2 : config.verbosity);
if (config.cacheOptions == "show") {
exit(0);
}
}
if (config.cacheOptions.contains("purge:") ||
config.cacheOptions.contains("vacuum")) {
bool success = true;
if (config.cacheOptions == "purge:all") {
success = cache->purgeAll(config.unattend || config.unattendSkip);
} else if (config.cacheOptions == "vacuum") {
success = cache->vacuumResources(
config.inputFolder, getPlatformFileExtensions(),
config.verbosity, config.unattend || config.unattendSkip);
} else if (config.cacheOptions.contains("purge:m=") ||
config.cacheOptions.contains("purge:t=")) {
success = cache->purgeResources(config.cacheOptions);
}
if (success) {
state = NO_INTR; // Ignore ctrl+c
cache->write();
state = SINGLE;
}
exit(0);
}
if (config.cacheOptions.contains("report:")) {
cache->assembleReport(config, getPlatformFileExtensions());
exit(0);
}
if (config.cacheOptions == "validate") {
cache->validate();
state = NO_INTR; // Ignore ctrl+c
cache->write();
state = SINGLE;
exit(0);
}
if (config.cacheOptions.contains("merge:")) {
QFileInfo mergeCacheInfo(config.cacheOptions.replace("merge:", ""));
if (mergeCacheInfo.isRelative()) {
mergeCacheInfo =
QFileInfo(config.currentDir + "/" + mergeCacheInfo.filePath());
}
const QString absMergeCacheFilePath = mergeCacheInfo.absoluteFilePath();
if (mergeCacheInfo.isDir()) {
Cache mergeCache(absMergeCacheFilePath);
mergeCache.read();
cache->merge(mergeCache, config.refresh, absMergeCacheFilePath);
state = NO_INTR; // Ignore ctrl+c
cache->write();
state = SINGLE;
} else {
printf("Path to merge from '%s' does not exist or is not a path, "
"can't continue...\n",
absMergeCacheFilePath.toStdString().c_str());
}
exit(0);
}
// remaining cache subcommand validation
bool cacheEditCmd = config.cacheOptions.left(4) == "edit";
if (!config.cacheOptions.isEmpty() && !cacheEditCmd) {
printf("\033[1;31mAmbiguous cache subcommand '--cache %s', "
"please check '--cache help' for more info.\n\033[0m",
config.cacheOptions.toStdString().c_str());
exit(0);
}
cache->readPriorities();
// Create shared queue with files to process
prepareFileQueue();
state = CACHE_EDIT; // Clear queue on ctrl+c
if (cacheEditCmd) {
QString editCommand = "";
QString editType = "";
if (config.cacheOptions.contains(":") &&
config.cacheOptions.contains("=")) {
config.cacheOptions.remove(0, config.cacheOptions.indexOf(":") + 1);
QStringList cacheOpts = config.cacheOptions.split("=");
if (cacheOpts.size() == 2) {
editCommand = cacheOpts.at(0);
editType = cacheOpts.at(1);
}
}
cache->editResources(queue, editCommand, editType);
if (state == CACHE_EDIT) {
printf("Done editing resources.\n");
state = NO_INTR; // Ignore ctrl+c
cache->write();
} else {
printf("Catched Ctrl-C: No changes persisted!\n");
}
state = SINGLE;
exit(0);
}
state = SINGLE;
gameListFileString =
config.gameListFolder + "/" + frontend->getGameListFileName();
QFile gameListFile(gameListFileString);
if (doCacheScraping && config.gameListBackup) {
QString gameListBackup =
gameListFile.fileName() + "-" +
QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss");
printf("Game list backup saved to '\033[1;33m%s\033[0m'\n",
gameListBackup.toStdString().c_str());
gameListFile.copy(gameListBackup);
}
if (doCacheScraping && !config.unattend && !config.unattendSkip &&
gameListFile.exists()) {
std::string userInput = "";
printf("\033[1;34m'\033[0m\033[1;33m%s\033[0m\033[1;34m' already "
"exists, do you want to overwrite it\033[0m (y/N)? ",
frontend->getGameListFileName().toStdString().c_str());
getline(std::cin, userInput);
if (userInput != "y" && userInput != "Y") {
printf("User chose not to overwrite, now exiting...\n");
exit(0);
}
printf("Checking if '\033[1;33m%s\033[0m' is writable?... ",
frontend->getGameListFileName().toStdString().c_str());
if (gameListFile.open(QIODevice::Append)) {
printf("\033[1;32mIt is! :)\033[0m\n");
gameListFile.close();
} else {
printf("\033[1;31mIt isn't! :(\nPlease check path and permissions "
"and try again.\033[0m\n");
exit(1);
}
printf("\n");
}
if (config.pretend && cacheScrapeMode) {
printf("Pretend set! Not changing any files, just showing output.\n\n");
}
QFile::remove(skippedFileString);
if (gameListFile.exists()) {
printf("Trying to parse and load existing game list metadata... ");
fflush(stdout);
if (frontend->loadOldGameList(gameListFileString)) {
printf("\033[1;32mSuccess!\033[0m\n");
if (!config.unattend && cliFiles.isEmpty() && frontend->canSkip()) {
std::string userInput = "";
if (config.unattendSkip) {
userInput = "y";
} else {
printf("\033[1;34mDo you want to skip already existing "
"game list entries\033[0m (y/N)? ");
getline(std::cin, userInput);
}
if ((userInput == "y" || userInput == "Y")) {
frontend->skipExisting(gameEntries, queue);
}
}
} else {
printf("\033[1;33mNot found or unsupported!\033[0m\n");
}
}
totalFiles = queue->length();
if (totalFiles == 0) {
QString extraInfo =
doCacheScraping
? "in cache"
: "matching these extensions '" +
getPlatformFileExtensions().split(' ').join(", ") + "'";
QString unattendSkipStr = "";
if (!config.unattend && cliFiles.isEmpty()) {
unattendSkipStr =
"\nMaybe you have opted to skip existing gamelist "
"entries (see config: unattendSkip) from this "
"\nSkyscraper run and there is none remaining to ";
unattendSkipStr =
unattendSkipStr % ((doCacheScraping)
? "generate a gamelist entry for."
: "scrape.");
}
printf("\nNo files to process %s for platform "
"'%s'.\nCheck configured and existing file extensions and cache "
"content.%s\n\n\033[1;33mSkyscraper came to an untimely "
"end.\033[0m\n\n",
extraInfo.toStdString().c_str(),
config.platform.toStdString().c_str(),
unattendSkipStr.toStdString().c_str());
exit(0);
}
if (config.romLimit != -1 && totalFiles > config.romLimit) {
int inCache = 0;
if (config.onlyMissing) {
// check queue on existing in cache and count
for (int b = 0; b < queue->length(); ++b) {
QFileInfo info = queue->at(b);
QString cacheId = cache->getQuickId(info);
if (!cacheId.isEmpty() && cache->hasEntries(cacheId)) {
// in cache from any scraping source
inCache++;
}
}
qDebug() << "Only missing applied. Found" << inCache
<< "existing game entries";
}
if (totalFiles - inCache > config.romLimit) {
printf(
"\n\033[1;33mRestriction overrun!\033[0m This scraping module "
"only allows for scraping up to %d roms at a time. You can "
"either supply a few rom filenames on command line, apply the "
"--flags onlymissing option, or make use of the '--startat' "
"and / or '--endat' command line options to adhere to this. "
"Please check '--help' for more info.\n\nNow quitting...\n",
config.romLimit);
exit(0);
}
}
printf("\n");
if (!doCacheScraping) {
printf("Starting scraping run on \033[1;32m%d\033[0m files using "
"\033[1;32m%d\033[0m threads.\nSit back, relax and let me do "
"the work! :)\n",
totalFiles, config.threads);
}
printf("\n");
timer.start();
currentFile = 1;
QList<QThread *> threadList;
for (int curThread = 1; curThread <= config.threads; ++curThread) {
QThread *thread = new QThread;
ScraperWorker *worker = new ScraperWorker(queue, cache, manager, config,
QString::number(curThread));
worker->moveToThread(thread);
connect(thread, &QThread::started, worker, &ScraperWorker::run);
connect(worker, &ScraperWorker::entryReady, this,
&Skyscraper::entryReady);
connect(worker, &ScraperWorker::allDone, this,
&Skyscraper::checkThreads);
connect(thread, &QThread::finished, worker,
&ScraperWorker::deleteLater);
threadList.append(thread);
// Do not start more threads if we have less files than allowed threads
if (curThread == totalFiles) {
config.threads = curThread;
break;
}
}
// Ready, set, GO! Start all threads
for (const auto thread : threadList) {
thread->start();
state = THREADED;
}
}
void Skyscraper::prepareFileQueue() {
QDir::Filters filter = QDir::Files;
// special case scummvm: users can use .svm in folder name to work around
// the limitation of the ScummVM / lr-scummvm launch integration in
// ES/RetroPie
if (config.platform == "scummvm") {
filter |= QDir::Dirs;
}
QDir inputDir(config.inputFolder, getPlatformFileExtensions(), QDir::Name,
filter);
if (!inputDir.exists()) {
printf("Input folder '\033[1;32m%s\033[0m' doesn't exist or can't be "
"accessed by current user. Please check path and permissions.\n",
inputDir.absolutePath().toStdString().c_str());
exit(1);
}
setFolder(doCacheScraping, config.gameListFolder);
setFolder(doCacheScraping, config.coversFolder);
setFolder(doCacheScraping, config.screenshotsFolder);
setFolder(doCacheScraping, config.wheelsFolder);
setFolder(doCacheScraping, config.marqueesFolder);
setFolder(doCacheScraping, config.texturesFolder);
if (config.videos) {
setFolder(doCacheScraping, config.videosFolder);
}
if (config.manuals) {
setFolder(doCacheScraping, config.manualsFolder);
}
setFolder(doCacheScraping, config.importFolder, false);
QList<QFileInfo> infoList = inputDir.entryInfoList();
if (!cacheScrapeMode &&
QFileInfo::exists(config.inputFolder + "/.skyscraperignore")) {
infoList.clear();
}
if (!config.startAt.isEmpty() && !infoList.isEmpty()) {
QFileInfo startAt(config.startAt);
if (!startAt.exists()) {
startAt.setFile(config.currentDir + "/" + config.startAt);
}
if (!startAt.exists()) {
startAt.setFile(config.inputFolder + "/" + config.startAt);
}
if (startAt.exists()) {
while (infoList.first().fileName() != startAt.fileName() &&
!infoList.isEmpty()) {
infoList.removeFirst();
}
}
}
if (!config.endAt.isEmpty() && !infoList.isEmpty()) {
QFileInfo endAt(config.endAt);
if (!endAt.exists()) {
endAt.setFile(config.currentDir + "/" + config.endAt);
}
if (!endAt.exists()) {
endAt.setFile(config.inputFolder + "/" + config.endAt);
}
if (endAt.exists()) {
while (infoList.last().fileName() != endAt.fileName() &&
!infoList.isEmpty()) {
infoList.removeLast();
}
}
}
queue = QSharedPointer<Queue>(new Queue());
queue->append(infoList);
if (config.subdirs) {
QDirIterator dirIt(config.inputFolder,
QDir::Dirs | QDir::NoDotAndDotDot,
QDirIterator::Subdirectories);
QString exclude = "";
while (dirIt.hasNext()) {
QString subdir = dirIt.next();
if (!cacheScrapeMode &&
QFileInfo::exists(subdir + "/.skyscraperignoretree")) {
exclude = subdir;
}
if (!exclude.isEmpty() &&
(subdir == exclude ||
(subdir.left(exclude.length()) == exclude &&
subdir.mid(exclude.length(), 1) == "/"))) {
continue;
} else {
exclude.clear();
}
if (!cacheScrapeMode &&
QFileInfo::exists(subdir + "/.skyscraperignore")) {
continue;
}
inputDir.setPath(subdir);
QList<QFileInfo> subFiles = inputDir.entryInfoList();
if (config.platform == "scummvm" &&
config.frontend == "emulationstation") {
// special case: avoid having files like
// .../scummvm/blarf.svm/blarf.svm added as game (as the folder
// blarf.svm/ acts as ROM file already)
for (auto i = subFiles.begin(), end = subFiles.end(); i != end;
++i) {
if (subdir.contains("/" % (*i).fileName())) {
subFiles.erase(i);
break;
}
}
}
queue->append(subFiles);
if (config.verbosity > 0 && subFiles.size() > 0) {
printf("Adding matching files from subdir: '%s'\n",
subdir.toStdString().c_str());
}
}
if (config.verbosity > 0)
printf("\n");
}
if (!config.excludePattern.isEmpty()) {
queue->filterFiles(config.excludePattern);
}
if (!config.includePattern.isEmpty()) {
queue->filterFiles(config.includePattern, true);
}
if (!cliFiles.isEmpty()) {
queue->clear();
for (const auto &cliFile : cliFiles) {
queue->append(QFileInfo(cliFile));
}
}
// Remove files from excludeFrom, if any
if (!config.excludeFrom.isEmpty()) {
queue->removeFiles(readFileListFrom(config.excludeFrom));
}
}
void Skyscraper::setFolder(const bool doCacheScraping, QString &outFolder,
const bool createMissingFolder) {
QDir dir(outFolder);
if (doCacheScraping) {
checkForFolder(dir, createMissingFolder);
}
outFolder = dir.absolutePath();
}
void Skyscraper::checkForFolder(QDir &folder, bool create) {
if (!folder.exists()) {
printf("Folder '%s' doesn't exist",
folder.absolutePath().toStdString().c_str());
if (create) {
printf(", trying to create it... ");
fflush(stdout);
if (folder.mkpath(folder.absolutePath())) {
printf("\033[1;32mSuccess!\033[0m\n");
} else {
printf("\033[1;32mFailed!\033[0m Please check path and "
"permissions, now exiting...\n");
exit(1);
}
} else {
printf(", can't continue...\n");
exit(1);
}
}
}
QString Skyscraper::secsToString(const int &secs) {
QString hours = QString::number(secs / 3600000 % 24);
QString minutes = QString::number(secs / 60000 % 60);
QString seconds = QString::number(secs / 1000 % 60);
if (hours.length() == 1) {
hours.prepend("0");
}
if (minutes.length() == 1) {
minutes.prepend("0");
}
if (seconds.length() == 1) {
seconds.prepend("0");
}
return hours + ":" + minutes + ":" + seconds;
}
void Skyscraper::entryReady(const GameEntry &entry, const QString &output,
const QString &debug) {
QMutexLocker locker(&entryMutex);
printf("\033[0;32m#%d/%d\033[0m %s\n", currentFile, totalFiles,
output.toStdString().c_str());
if (config.verbosity >= 3) {
printf("\033[1;33mDebug output:\033[0m\n%s\n",
debug.toStdString().c_str());
}
if (entry.found) {
found++;
avgCompleteness += entry.getCompleteness();
avgSearchMatch += entry.searchMatch;
gameEntries.append(entry);
} else {
notFound++;
QFile skippedFile(skippedFileString);
skippedFile.open(QIODevice::Append);
skippedFile.write(entry.absoluteFilePath.toUtf8() + "\n");
skippedFile.close();
if (config.skipped) {
gameEntries.append(entry);
}
}
printf(
"\033[1;34m#%d/%d\033[0m, (\033[1;32m%d\033[0m/\033[1;33m%d\033[0m)\n",
currentFile, totalFiles, found, notFound);
int elapsed = timer.elapsed();
int estTime = (elapsed / currentFile * totalFiles) - elapsed;
if (estTime < 0)
estTime = 0;
printf("Elapsed time : \033[1;33m%s\033[0m\n",
secsToString(elapsed).toStdString().c_str());
printf("Est. time left : \033[1;33m%s\033[0m\n\n",
secsToString(estTime).toStdString().c_str());
if (!config.onlyMissing && currentFile == config.maxFails &&
notFound == config.maxFails && config.scraper != "import" &&
config.scraper != "cache") {
printf("\033[1;31mThis is NOT going well! I guit! *slams the "
"door*\nNo, seriously, out of %d files we had %d misses. So "
"either the scraping source is down or you are using a scraping "
"source that doesn't support this platform. Please try another "
"scraping module (check '--help').\n\nNow exiting...\033[0m\n",
config.maxFails, config.maxFails);
exit(1);
}
currentFile++;
const qint64 spaceLimit = 200 * 1024 * 1024;
if (config.spaceCheck) {
QString storage;
if (config.scraper == "cache" && !config.pretend &&
QStorageInfo(QDir(config.screenshotsFolder)).bytesFree() <
spaceLimit) {
storage = "media export";
} else if (QStorageInfo(QDir(config.cacheFolder)).bytesFree() <
spaceLimit) {
storage = "resource cache";
}
if (!storage.isEmpty()) {
printf("\033[1;31mYou have very little disk space left on the "
"Skyscraper %s storage, please free up some space "
"and try again. Now aborting...\033[0m\n\n",
storage.toStdString().c_str());
printf("Note! You can disable this check by setting "
"'spaceCheck=\"false\"' in the '[main]' section of "
"config.ini.\n\n");
// By clearing the queue here we basically tell Skyscraper to stop
// and quit nicely
config.pretend = true;
queue->clearAll();
}
}
}
void Skyscraper::checkThreads() {
QMutexLocker locker(&checkThreadMutex);
doneThreads++;
if (doneThreads != config.threads)
return;
if (!config.pretend && config.scraper == "cache") {
printf("\033[1;34m---- Game list generation run completed! YAY! "
"----\033[0m\n");
state = NO_INTR;
cache->write(true);
state = SINGLE;
frontend->sortEntries(gameEntries);
printf("Assembling game list...");
QString finalOutput;
frontend->assembleList(finalOutput, gameEntries);
printf(" \033[1;32mDone!\033[0m\n");
QFile gameListFile(gameListFileString);
printf("Now writing '\033[1;33m%s\033[0m'... ",
gameListFileString.toStdString().c_str());
fflush(stdout);
if (gameListFile.open(QIODevice::WriteOnly)) {
state = NO_INTR;
gameListFile.write(finalOutput.toUtf8());
state = SINGLE;
gameListFile.close();
printf("\033[1;32mSuccess!\033[0m\n\n");
} else {
printf("\033[1;31mCouldn't open file for writing!\nAll that work "
"for nothing... :(\033[0m\n");
}
} else {
printf("\033[1;34m---- Resource gathering run completed! YAY! "
"----\033[0m\n");
state = NO_INTR;
cache->write();
state = SINGLE;
}
if (!doCacheScraping || totalFiles > 0) {
printf("\033[1;34m---- And here are some neat stats :) ----\033[0m\n");
}
if (!doCacheScraping) {
printf("Total completion time: \033[1;33m%s\033[0m\n\n",
secsToString(timer.elapsed()).toStdString().c_str());
}
if (totalFiles > 0) {
if (found > 0) {
printf("Average search match: \033[1;33m%d%%\033[0m\n",
(int)((double)avgSearchMatch / (double)found));
printf("Average entry completeness: \033[1;33m%d%%\033[0m\n\n",
(int)((double)avgCompleteness / (double)found));
}
printf("\033[1;34mTotal number of games: %d\033[0m\n", totalFiles);
printf("\033[1;32mSuccessfully processed games: %d\033[0m\n", found);
printf("\033[1;33mSkipped games: %d\033[0m", notFound);
if (notFound > 0) {
printf(" (Filenames saved to '\033[1;33m%s/%s\033[0m')",
Config::getSkyFolder(Config::SkyFolderType::LOG)
.toStdString()
.c_str(),
skippedFileString.toStdString().c_str());
}
printf("\n\n");
}
// All done, now clean up and exit to terminal
emit finished();
}
QList<QString> Skyscraper::readFileListFrom(const QString &filename) {
QList<QString> fileList;
QFileInfo fnInfo(filename);
if (!fnInfo.exists()) {
fnInfo.setFile(config.currentDir + "/" + filename);
}
if (fnInfo.exists()) {
QFile f(fnInfo.absoluteFilePath());
if (f.open(QIODevice::ReadOnly)) {
while (!f.atEnd()) {
fileList.append(QString(f.readLine().simplified()));
}
f.close();
} else {
printf("File '\033[1;32m%s\033[0m' can not be read.\n\nPlease "
"verify the file permissions and try again...\n",
fnInfo.absoluteFilePath().toStdString().c_str());
exit(1);
}
} else {
printf("File '\033[1;32m%s\033[0m' does not exist.\n\nPlease "
"verify the filename and try again...\n",
fnInfo.absoluteFilePath().toStdString().c_str());
exit(1);
}
return fileList;
}
void Skyscraper::loadConfig(const QCommandLineParser &parser) {
QString iniFile = parser.isSet("c") ? parser.value("c") : "config.ini";
QString absIniFile = Config::makeAbsolutePath(
parser.isSet("c") ? config.currentDir : Config::getSkyFolder(),
iniFile);
absIniFile = Config::lexicallyNormalPath(absIniFile);
if (!QFileInfo(absIniFile).exists()) {
printf(
"\nWARNING! Provided config file '\033[1;33m%s\033[0m' does not "
"exist.\nSkyscraper will use default configuration values...\n\n",
iniFile.toStdString().c_str());
}
config.configFile = absIniFile;
QSettings settings(absIniFile, QSettings::IniFormat);
RuntimeCfg *rtConf = new RuntimeCfg(&config, &parser);
// Start by setting frontend, since we need it to set default for game list
// and so on
if (parser.isSet("f")) {
QString fe = parser.value("f");
if (!rtConf->validateFrontend(fe)) {
exit(1);
}
config.frontend = fe;
}
bool inputFolderSet = false;
bool gameListFolderSet = false;
bool mediaFolderSet = false;
// 1. Main config, overrides defaults
settings.beginGroup("main");
rtConf->applyConfigIni(RuntimeCfg::CfgType::MAIN, &settings, inputFolderSet,
gameListFolderSet, mediaFolderSet);
settings.endGroup();
// 2. Platform specific configs, overrides main and defaults
settings.beginGroup(config.platform);
rtConf->applyConfigIni(RuntimeCfg::CfgType::PLATFORM, &settings,
inputFolderSet, gameListFolderSet, mediaFolderSet);
settings.endGroup();
// Check for command line scraping module here
QStringList scrapers = {"arcadedb", "cache", "esgamelist",
"gamebase", "igdb", "import",
"mobygames", "openretro", "screenscraper",
"thegamesdb", "worldofspectrum"};
if (parser.isSet("s")) {
QString _scraper = parser.value("s");
if (_scraper == "tgdb") {
_scraper = "thegamesdb";
} else if (_scraper == "wos" || _scraper == "zxinfo") {
/* not using zxinfo bc. backward compability, esp. for resource
* cache */
_scraper = "worldofspectrum";
}
if (scrapers.contains(_scraper)) {
config.scraper = _scraper;
} else {
printf("\033[1;31mBummer! Unknown scrapingmodule '%s'. Known "
"scrapers are: %s.\nHint: Try TAB-completion to avoid "
"typos.\033[0m\n",
_scraper.toStdString().c_str(),
scrapers.join(", ").toStdString().c_str());
exit(1);
}
}
// 3. Frontend specific configs, overrides platform, main and
// defaults
settings.beginGroup(config.frontend);
rtConf->applyConfigIni(RuntimeCfg::CfgType::FRONTEND, &settings,
inputFolderSet, gameListFolderSet, mediaFolderSet);
settings.endGroup();
// 4. Scraping module specific configs, overrides frontend, platform,
// main and defaults
settings.beginGroup(config.scraper);
rtConf->applyConfigIni(RuntimeCfg::CfgType::SCRAPER, &settings,
inputFolderSet, gameListFolderSet, mediaFolderSet);
settings.endGroup();
// 5. Command line configs, overrides all
rtConf->applyCli(inputFolderSet, gameListFolderSet, mediaFolderSet);
if (config.platform.isEmpty() && !config.cacheOptions.isEmpty()) {
return; // cache option to be applied to all platform
}
if (config.frontend == "emulationstation" ||
config.frontend == "retrobat") {
frontend = new EmulationStation;
} else if (config.frontend == "attractmode") {
frontend = new AttractMode;
} else if (config.frontend == "pegasus") {
frontend = new Pegasus;
} else if (config.frontend == "esde") {
frontend = new Esde;
}
frontend->setConfig(&config);
frontend->checkReqs();
// Fallback to defaults if they aren't already set, find the rest in
// settings.h
if (!inputFolderSet) {
config.inputFolder = frontend->getInputFolder();
}
if (!gameListFolderSet) {
config.gameListFolder = frontend->getGameListFolder();
}
if (!mediaFolderSet) {
if (config.frontend == "esde") {
config.mediaFolder = frontend->getMediaFolder();
} else {
// defaults to <gamelistfolder>/[.]media/
QString mf = "media";
if (config.mediaFolderHidden) {
mf = "." + mf;
}
config.mediaFolder = Config::concatPath(config.gameListFolder, mf);
}
}
// defaults are always absolute, thus input and mediafolder will be
// unchanged by these calls
config.inputFolder =
Config::makeAbsolutePath(config.gameListFolder, config.inputFolder);
config.mediaFolder =
Config::makeAbsolutePath(config.gameListFolder, config.mediaFolder);
config.inputFolder = Config::lexicallyNormalPath(config.inputFolder);
config.mediaFolder = Config::lexicallyNormalPath(config.mediaFolder);
// only resolve after config.mediaFolder is set
config.coversFolder = frontend->getCoversFolder();
config.screenshotsFolder = frontend->getScreenshotsFolder();
config.wheelsFolder = frontend->getWheelsFolder();
config.marqueesFolder = frontend->getMarqueesFolder();
config.texturesFolder = frontend->getTexturesFolder();
config.videosFolder = frontend->getVideosFolder();
config.manualsFolder = frontend->getManualsFolder();
// Choose default scraper for chosen platform if none has been set yet
if (config.scraper.isEmpty()) {
config.scraper = "cache";
}
if (config.importFolder.isEmpty()) {
config.importFolder =
Config::getSkyFolder(Config::SkyFolderType::IMPORT);
}
// If platform subfolder exists for import path, use it
QDir importFolder(config.importFolder);
if (importFolder.exists(config.platform)) {
config.importFolder =
Config::concatPath(config.importFolder, config.platform);
}
// Set minMatch to 0 for cache, arcadedb and screenscraper
// We know these results are always accurate
if (config.minMatchSet == false && config.isMatchOneScraper()) {
config.minMatch = 0;
}
skippedFileString =
"skipped-" + config.platform + "-" + config.scraper + ".txt";
// Grab all requested files from cli, if any
QList<QString> requestedFiles = parser.positionalArguments();
// Add files from '--includefrom', if any
if (!config.includeFrom.isEmpty()) {
requestedFiles += readFileListFrom(config.includeFrom);
}
// Verify requested files and add the ones that exist
for (const auto &requestedFile : requestedFiles) {
QFileInfo requestedFileInfo(requestedFile);
if (!requestedFileInfo.exists()) {
requestedFileInfo.setFile(config.currentDir + "/" + requestedFile);
}
if (!requestedFileInfo.exists()) {
requestedFileInfo.setFile(config.inputFolder + "/" + requestedFile);
}
if (requestedFileInfo.exists()) {
QString romPath = requestedFileInfo.absoluteFilePath();
if (config.frontend == "emulationstation" ||
config.frontend == "esde") {
romPath = normalizePath(requestedFileInfo);
}
if (!romPath.isEmpty()) {
cliFiles.append(romPath);
// Always set refresh and unattend true if user has supplied
// filenames on command line. That way they are cached, but game
// list is not changed and user isn't asked about skipping and
// overwriting.
config.refresh = true;
config.unattend = true;
continue;
}
}
printf("Filename: '\033[1;32m%s\033[0m' requested either on "
"command line or with '--includefrom' neither found in platform "