-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzdb.cpp
More file actions
1530 lines (1312 loc) · 48.6 KB
/
Copy pathzdb.cpp
File metadata and controls
1530 lines (1312 loc) · 48.6 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
#include <utility>
#include <algorithm>
#include <execution>
#include <QApplication>
#include <QTemporaryFile>
#include <QTextStream>
#include <QStandardPaths>
#include <QBuffer>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlDriver>
#include <QSqlRecord>
#include <QSqlField>
#include <QVariant>
#include <QElapsedTimer>
#include <QRegularExpression>
#include <QDebug>
#include "zdb.h"
#include "global.h"
ZDB::ZDB(QObject *parent) :
QObject(parent)
{
m_dbHost = QSL("localhost");
m_dbBase = QSL("qmanga");
}
int ZDB::getAlbumsCount()
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return 0;
QSqlQuery qr(QSL("SELECT COUNT(name) FROM `albums` ORDER BY name ASC"),db);
int cnt = 0;
while (qr.next())
cnt = qr.value(0).toInt();
sqlCloseBase(db);
return cnt;
}
ZStrMap ZDB::getDynAlbums() const
{
return m_dynAlbums;
}
Z::Ordering ZDB::getDynAlbumOrdering(const QString& album, Qt::SortOrder &order) const
{
if (!album.startsWith(QSL("# "))) return Z::ordUndefined;
const QString name = album.mid(2);
order = Qt::AscendingOrder;
const QString qr = m_dynAlbums.value(name,QString());
if (!qr.isEmpty()) {
QRegularExpression rx(QSL(R"(ORDER\sBY\s(\S+)\s(ASC|DESC)?)"));
QRegularExpressionMatch mrx = rx.match(qr);
if (mrx.hasMatch()) {
QString col = mrx.captured(1).trimmed();
QString ord = mrx.captured(2).trimmed();
if (!ord.isEmpty() &&
(ord.compare(QSL("DESC"),Qt::CaseInsensitive)==0))
order = Qt::DescendingOrder;
if (!col.isEmpty()) {
if (!col.at(0).isLetterOrNumber())
col.remove(col.at(0));
const auto columns = ZGenericFuncs::getSqlColumns();
for(auto it = columns.constKeyValueBegin(),
end = columns.constKeyValueEnd(); it != end; ++it) {
if (col.compare((*it).second,Qt::CaseInsensitive)==0) {
return (*it).first;
}
}
}
}
}
return Z::ordUndefined;
}
bool ZDB::isDynamicAlbumParent(int parentId)
{
return (parentId == dynamicAlbumParent);
}
int ZDB::getDynamicAlbumParent()
{
return dynamicAlbumParent;
}
ZStrHash ZDB::getConfigProblems() const
{
return m_problems;
}
void ZDB::setCredentials(const QString &host, const QString &base, const QString &user, const QString &password)
{
m_dbHost = host;
m_dbBase = base;
m_dbUser = user;
m_dbPass = password;
}
void ZDB::setCoverCacheSize(int size)
{
QMutexLocker locker(&m_coverCacheMutex);
if (m_coverCache.maxCost() != size)
m_coverCache.setMaxCost(size);
}
void ZDB::setDynAlbums(const ZStrMap &albums)
{
m_dynAlbums = albums;
}
void ZDB::sqlCheckBase()
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
sqlCheckBasePriv(db,false);
sqlCloseBase(db);
Q_EMIT baseCheckComplete();
}
bool ZDB::sqlCheckBasePriv(QSqlDatabase& db, bool silent)
{
static const QStringList tables { QSL("files"), QSL("albums"), QSL("ignored_files") };
int cnt=0;
const QStringList list = db.tables(QSql::Tables);
for (const QString& s : list) {
if (tables.contains(s,Qt::CaseInsensitive))
cnt++;
}
bool noTables = (cnt!=3);
if (noTables) {
if (!silent)
Q_EMIT needTableCreation();
return false;
}
if (silent) return true;
return checkTablesParams(db);
}
bool ZDB::checkTablesParams(QSqlDatabase &db)
{
if (sqlDbEngine(db)!=Z::dbmsMySQL) return true;
QSqlQuery qr(db);
QStringList cols;
// Add parent column to albums
qr.exec(QSL("SHOW COLUMNS FROM albums"));
while (qr.next())
cols << qr.value(0).toString();
if (!cols.contains(QSL("parent"),Qt::CaseInsensitive)) {
if (!qr.exec(QSL("ALTER TABLE `albums` ADD COLUMN `parent` "
"INT(11) DEFAULT -1"))) {
qWarning() << tr("Unable to add column for albums table.")
<< qr.lastError().databaseText() << qr.lastError().driverText();
m_problems[tr("Adding column")] = tr("Unable to add column for qmanga albums table.\n"
"ALTER TABLE query failed.");
return false;
}
}
// Check for preferred rendering column
qr.exec(QSL("SHOW COLUMNS FROM files"));
while (qr.next())
cols << qr.value(0).toString();
if (!cols.contains(QSL("preferredRendering"),Qt::CaseInsensitive)) {
if (!qr.exec(QSL("ALTER TABLE `files` ADD COLUMN `preferredRendering` "
"INT(11) DEFAULT 0"))) {
qWarning() << tr("Unable to add column for files table.")
<< qr.lastError().databaseText() << qr.lastError().driverText();
m_problems[tr("Adding column")] = tr("Unable to add column for qmanga files table.\n"
"ALTER TABLE query failed.");
return false;
}
}
// Add fulltext index for manga names
if (!qr.exec(QSL("SELECT index_type FROM information_schema.statistics "
"WHERE table_schema=DATABASE() AND table_name='files' AND index_name='name_ft'"))) {
qWarning() << tr("Unable to get indexes list.")
<< qr.lastError().databaseText() << qr.lastError().driverText();
m_problems[tr("Check for indexes")] = tr("Unable to check indexes for qmanga tables.\n"
"SELECT query failed.\n");
return false;
}
QString idxn;
if (qr.next())
idxn = qr.value(0).toString();
if (idxn.isEmpty()) {
if (!qr.exec(QSL("ALTER TABLE files ADD FULLTEXT INDEX name_ft(name)"))) {
qWarning() << tr("Unable to add fulltext index for files table.")
<< qr.lastError().databaseText() << qr.lastError().driverText();
m_problems[tr("Creating indexes")] = tr("Unable to add FULLTEXT index for qmanga files table.\n"
"ALTER TABLE query failed.\n"
"Fulltext index in necessary for search feature.");
return false;
}
checkConfigOpts(db,false);
}
checkConfigOpts(db,true);
return true;
}
void ZDB::checkConfigOpts(QSqlDatabase &db, bool silent)
{
static const QString ftDetails = QSL("1. Edit my.cnf file and save\n"
"--> ft_stopword_file = \"\" (or link an empty file \"empty_stopwords.txt\")\n"
"--> ft_min_word_len = 2\n"
"2. Restart your server (this cannot be done dynamically)\n"
"3. Change the table engine (if needed) - ALTER TABLE tbl_name ENGINE = MyISAM;\n"
"4. Perform repair - REPAIR TABLE tbl_name QUICK;");
if (sqlDbEngine(db)!=Z::dbmsMySQL) return;
QSqlQuery qr(db);
if (!qr.exec(QSL("SELECT @@ft_min_word_len"))) {
qWarning() << tr("Unable to check MySQL config options");
m_problems[tr("MySQL config")] = tr("Unable to check my.cnf options via global variables.\n"
"SELECT query failed.\n"
"QManga needs specific fulltext ft_* options in config.");
return;
}
if (qr.next()) {
bool okconv = false;
int ftlen = qr.value(0).toInt(&okconv);
if (!okconv || (ftlen>2)) {
if (!silent)
Q_EMIT errorMsg(ftDetails);
m_problems[tr("MySQL config fulltext")] = ftDetails;
}
}
}
void ZDB::sqlCreateTables()
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
checkConfigOpts(db,false);
QSqlQuery qr(db);
if (sqlDbEngine(db)==Z::dbmsMySQL) {
if (!qr.exec(QSL("CREATE TABLE IF NOT EXISTS `albums` ("
"`id` int(11) NOT NULL AUTO_INCREMENT,"
"`name` varchar(2048) NOT NULL,"
"`parent` int(11) default -1,"
"PRIMARY KEY (`id`)"
") ENGINE=MyISAM DEFAULT CHARSET=utf8"))) {
Q_EMIT errorMsg(tr("Unable to create table `albums`\n\n%1\n%2")
.arg(qr.lastError().databaseText(),qr.lastError().driverText()));
m_problems[tr("Create tables - albums")] = tr("Unable to create table `albums`.\n"
"CREATE TABLE query failed.");
sqlCloseBase(db);
return;
}
if (!qr.exec(QSL("CREATE TABLE IF NOT EXISTS `ignored_files` ("
"`id` int(11) NOT NULL AUTO_INCREMENT,"
"`filename` varchar(16383) NOT NULL,"
"PRIMARY KEY (`id`)"
") ENGINE=MyISAM DEFAULT CHARSET=utf8"))) {
Q_EMIT errorMsg(tr("Unable to create table `ignored_files`\n\n%1\n%2")
.arg(qr.lastError().databaseText(),qr.lastError().driverText()));
m_problems[tr("Create tables - ignored_files")] = tr("Unable to create table `ignored_files`.\n"
"CREATE TABLE query failed.");
sqlCloseBase(db);
return;
}
if (!qr.exec(QSL("CREATE TABLE IF NOT EXISTS `files` ("
"`id` int(11) NOT NULL AUTO_INCREMENT,"
"`name` varchar(2048) NOT NULL,"
"`filename` varchar(16383) NOT NULL,"
"`album` int(11) NOT NULL,"
"`cover` mediumblob,"
"`pagesCount` int(11) NOT NULL,"
"`fileSize` bigint(20) NOT NULL,"
"`fileMagic` varchar(32) NOT NULL,"
"`fileDT` datetime NOT NULL,"
"`addingDT` datetime NOT NULL,"
"`preferredRendering` int(11) default 0,"
"PRIMARY KEY (`id`),"
"FULLTEXT KEY `name_ft` (`name`)"
") ENGINE=MyISAM DEFAULT CHARSET=utf8"))) {
Q_EMIT errorMsg(tr("Unable to create table `files`\n\n%1\n%2")
.arg(qr.lastError().databaseText(),qr.lastError().driverText()));
m_problems[tr("Create tables - files")] = tr("Unable to create table `files`.\n"
"CREATE TABLE query failed.");
sqlCloseBase(db);
return;
}
} else if (sqlDbEngine(db)==Z::dbmsSQLite){
if (!qr.exec(QSL("CREATE TABLE IF NOT EXISTS `albums` ("
"`id` INTEGER PRIMARY KEY AUTOINCREMENT,"
"`name` TEXT,"
"`parent` INTEGER DEFAULT -1)"))) {
Q_EMIT errorMsg(tr("Unable to create table `albums`\n\n%1\n%2")
.arg(qr.lastError().databaseText(),qr.lastError().driverText()));
m_problems[tr("Create tables - albums")] = tr("Unable to create table `albums`.\n"
"CREATE TABLE query failed.");
sqlCloseBase(db);
return;
}
if (!qr.exec(QSL("CREATE TABLE IF NOT EXISTS `ignored_files` ("
"`id` INTEGER PRIMARY KEY,"
"`filename` TEXT)"))) {
Q_EMIT errorMsg(tr("Unable to create table `ignored_files`\n\n%1\n%2")
.arg(qr.lastError().databaseText(),qr.lastError().driverText()));
m_problems[tr("Create tables - ignored_files")] = tr("Unable to create table `ignored_files`.\n"
"CREATE TABLE query failed.");
sqlCloseBase(db);
return;
}
if (!qr.exec(QSL("CREATE TABLE IF NOT EXISTS `files` ("
"`id` INTEGER PRIMARY KEY,"
"`name` TEXT,"
"`filename` TEXT,"
"`album` INTEGER,"
"`cover` BLOB,"
"`pagesCount` INTEGER,"
"`fileSize` INTEGER,"
"`fileMagic` TEXT,"
"`fileDT` TEXT,"
"`addingDT` TEXT,"
"`preferredRendering` INTEGER DEFAULT 0)"))) {
Q_EMIT errorMsg(tr("Unable to create table `files`\n\n%1\n%2")
.arg(qr.lastError().databaseText(),qr.lastError().driverText()));
m_problems[tr("Create tables - files")] = tr("Unable to create table `files`.\n"
"CREATE TABLE query failed.");
sqlCloseBase(db);
return;
}
} else {
Q_EMIT errorMsg(tr("Unable to create tables. Unknown DB engine"));
m_problems[tr("Create tables")] = tr("Unable to create tables.\n"
"Unknown DB engine.");
}
sqlCloseBase(db);
}
QSqlDatabase ZDB::sqlOpenBase(bool silent)
{
QSqlDatabase db;
if (zF->global()==nullptr) return db;
if (zF->global()->getDbEngine()==Z::dbmsMySQL) {
db = QSqlDatabase::addDatabase(QSL("QMYSQL"),QUuid::createUuid().toString());
if (!db.isValid()) {
db = QSqlDatabase();
if (!silent) {
Q_EMIT errorMsg(tr("Unable to create MySQL driver instance."));
m_problems[tr("Connection")] = tr("Unable to create MySQL driver instance.");
}
return db;
}
db.setHostName(m_dbHost);
db.setDatabaseName(m_dbBase);
db.setUserName(m_dbUser);
db.setPassword(m_dbPass);
} else if (zF->global()->getDbEngine()==Z::dbmsSQLite) {
db = QSqlDatabase::addDatabase(QSL("QSQLITE"),QUuid::createUuid().toString());
if (!db.isValid()) {
db = QSqlDatabase();
if (!silent) {
Q_EMIT errorMsg(tr("Unable to create SQLite driver instance."));
m_problems[tr("Connection")] = tr("Unable to create SQLite driver instance.");
}
return db;
}
QString dir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
QDir dbDir(dir);
if (!dbDir.exists()) {
if (!dbDir.mkpath(dir)) {
db = QSqlDatabase();
if (!silent) {
Q_EMIT errorMsg(tr("Unable to create SQLite database file. Check file permissions.\n%1")
.arg(dir));
m_problems[tr("Connection")] = tr("Unable to create SQLite database file.");
}
return db;
}
}
db.setDatabaseName(dbDir.filePath(QSL("qmanga.sqlite")));
} else {
return db;
}
if (!db.open()) {
db = QSqlDatabase();
if (!silent) {
Q_EMIT errorMsg(tr("Unable to open database connection. Check connection info.\n%1\n%2")
.arg(db.lastError().driverText(),db.lastError().databaseText()));
m_problems[tr("Connection")] = tr("Unable to connect to database.\n"
"Check credentials and SQL server running.");
}
}
return db;
}
void ZDB::sqlCloseBase(QSqlDatabase &db)
{
if (db.isOpen())
db.close();
}
void ZDB::sqlUpdateIgnoredFiles(QSqlDatabase &db)
{
QStringList sl;
QSqlQuery qr(QSL("SELECT filename FROM ignored_files"),db);
while (qr.next())
sl << qr.value(0).toString();
m_ignoredFiles = sl;
}
void ZDB::sqlGetAlbums()
{
ZAlbumVector result;
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
QSqlQuery qr(QSL("SELECT id, parent, name FROM `albums` ORDER BY name ASC"),db);
while (qr.next()) {
bool ok1 = false;
int id = qr.value(0).toInt(&ok1);
bool ok2 = false;
int parent = qr.value(1).toInt(&ok2);
if (ok1 && ok2)
result << ZAlbumEntry(id,parent,qr.value(2).toString());
}
sqlUpdateIgnoredFiles(db);
sqlCloseBase(db);
int id = -1;
for (auto it = m_dynAlbums.constKeyValueBegin(), end = m_dynAlbums.constKeyValueEnd();
it != end; ++it)
result << ZAlbumEntry(id--,dynamicAlbumParent,QSL("# %1").arg((*it).first));
result << ZAlbumEntry(id--,-1,QSL("% Deleted"));
Q_EMIT gotAlbums(result);
}
void ZDB::sqlGetFiles(const QString &album, const QString &search, const QSize& preferredCoverSize)
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
QElapsedTimer tmr;
tmr.start();
const int fldName = 0;
const int fldPagesCount = 3;
const int fldFileSize = 4;
const int fldFileMagic = 5;
const int fldFileDate = 6;
const int fldFileAdded = 7;
const int fldID = 8;
const int fldAlbumName = 9;
const int fldPreferredRendering = 10;
QString tqr = QSL("SELECT files.name, filename, cover, pagesCount, fileSize, "
"fileMagic, fileDT, addingDT, files.id, albums.name, "
"files.preferredRendering "
"FROM files LEFT JOIN albums ON files.album=albums.id ");
bool checkFS = false;
bool albumBind = false;
bool searchBind = false;
if (!album.isEmpty()) {
if (album.startsWith(QSL("# "))) {
QString name = album.mid(2);
if (m_dynAlbums.contains(name)){
tqr += m_dynAlbums.value(name);
}
} else if (album.startsWith(QSL("% Deleted"))) {
checkFS = true;
} else {
tqr += QSL("WHERE (album="
" (SELECT id FROM albums WHERE (name = ?))"
") ");
albumBind = true;
}
} else if (!search.isEmpty()) {
QString sqr;
if (sqlDbEngine(db)==Z::dbmsMySQL)
sqr = prepareSearchQuery(search);
if (sqr.isEmpty()) {
sqr = QSL("WHERE (files.name LIKE ?) ");
searchBind = true;
}
tqr += sqr;
}
int idx = 0;
QSqlQuery qr(db);
qr.prepare(tqr);
if (albumBind)
qr.addBindValue(album);
if (searchBind)
qr.addBindValue(QSL("%%%1%%").arg(search));
if (qr.exec()) {
m_preferredRendering.clear();
while (qr.next()) {
QImage p = QImage();
QByteArray ba = qr.value(2).toByteArray();
if (!ba.isEmpty()) {
if (ba.startsWith(ZDefaults::coverBase64Header))
ba = QByteArray::fromBase64(ba.mid(ZDefaults::coverBase64Header.size()));
p.loadFromData(ba);
}
QString fileName = qr.value(1).toString();
if (checkFS) {
QFileInfo fi(fileName);
if (fi.exists()) continue;
}
int prefRendering = qr.value(fldPreferredRendering).toInt();
m_preferredRendering[fileName] = prefRendering;
idx++;
const ZSQLMangaEntry entry(ZSQLMangaEntry(qr.value(fldName).toString(),
fileName,
qr.value(fldAlbumName).toString(),
p,
qr.value(fldPagesCount).toInt(),
qr.value(fldFileSize).toInt(),
qr.value(fldFileMagic).toString(),
qr.value(fldFileDate).toDateTime(),
qr.value(fldFileAdded).toDateTime(),
qr.value(fldID).toInt(),
static_cast<Z::PDFRendering>(prefRendering)));
{
QMutexLocker mlock(&m_coverCacheMutex);
const auto *cached = m_coverCache.object(entry.filename);
if (cached && (cached->first == preferredCoverSize)) {
const QImage res(cached->second);
ZSQLMangaEntry e = entry;
if (!res.isNull()) {
e.cover = res;
Q_EMIT gotFile(e);
continue;
}
}
}
m_fastResamplersPool.start([this,entry,preferredCoverSize](){
const QImage res = entry.cover.scaled(preferredCoverSize,Qt::KeepAspectRatio,
Qt::FastTransformation);
ZSQLMangaEntry e = entry;
if (!res.isNull())
e.cover = res;
Q_EMIT gotFile(e);
m_searchResamplersPool.start([this,entry,preferredCoverSize](){
const QImage res = ZGenericFuncs::resizeImage(entry.cover,preferredCoverSize,true,
zF->global()->getDownscaleSearchTabFilter());
if (!res.isNull()) {
QMutexLocker mlock(&m_coverCacheMutex);
m_coverCache.insert(entry.filename,
new QPair<QSize,QImage>(preferredCoverSize, res),
res.sizeInBytes());
QMetaObject::invokeMethod(this,[this,entry,res](){
Q_EMIT gotResampledCover(entry.dbid,res);
},Qt::QueuedConnection);
}
});
});
}
} else {
qWarning() << qr.lastError().databaseText() << qr.lastError().driverText();
}
sqlCloseBase(db);
m_fastResamplersPool.waitForDone();
Q_EMIT filesLoaded(idx,tmr.elapsed());
}
void ZDB::sqlChangeFilePreview(const QString &fileName, int pageNum)
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
QString fname(fileName);
bool dynManga = fname.startsWith(QSL("#DYN#"));
if (dynManga)
fname.remove(QRegularExpression(QSL("^#DYN#")));
QSqlQuery qr(db);
qr.prepare(QSL("SELECT name FROM files WHERE (filename=?)"));
qr.addBindValue(fname);
if (!qr.exec()) {
qWarning() << "file search query failed";
sqlCloseBase(db);
return;
}
if (!qr.next()) {
Q_EMIT errorMsg(tr("Opened file not found in library."));
sqlCloseBase(db);
return;
}
QFileInfo fi(fname);
if (!fi.isReadable()) {
qWarning() << "skipping" << fname << "as unreadable";
Q_EMIT errorMsg(tr("%1 file is unreadable.").arg(fname));
sqlCloseBase(db);
return;
}
bool mimeOk = false;
ZAbstractReader* za = ZGenericFuncs::readerFactory(this,fileName,&mimeOk,Z::rffSkipSingleImageReader,
Z::rfmCreateReader);
if (za == nullptr) {
qWarning() << fname << "File format not supported";
Q_EMIT errorMsg(tr("%1 file format not supported.").arg(fname));
sqlCloseBase(db);
return;
}
if (!za->openFile()) {
qWarning() << fname << "Unable to open file.";
Q_EMIT errorMsg(tr("Unable to open file %1.").arg(fname));
za->setParent(nullptr);
delete za;
sqlCloseBase(db);
return;
}
const QByteArray pba = createMangaPreview(za,pageNum);
qr.prepare(QSL("UPDATE files SET cover=? WHERE (filename=?)"));
qr.bindValue(0,pba);
qr.bindValue(1,fname);
if (!qr.exec()) {
QString msg = tr("Unable to change cover for '%1'.\n%2\n%3")
.arg(fname,qr.lastError().databaseText(),qr.lastError().driverText());
qWarning() << msg;
Q_EMIT errorMsg(msg);
}
za->closeFile();
za->setParent(nullptr);
delete za;
sqlCloseBase(db);
QMutexLocker mlock(&m_coverCacheMutex);
m_coverCache.remove(fname);
}
void ZDB::sqlRescanIndexedDirs()
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
QStringList dirs;
QSqlQuery qr(QSL("SELECT filename "
"FROM files "
"WHERE NOT(fileMagic='DYN')"),db);
while (qr.next()) {
QFileInfo fi(qr.value(0).toString());
if (!fi.exists()) continue;
if (!dirs.contains(fi.absoluteDir().absolutePath()))
dirs << fi.absoluteDir().absolutePath();
}
sqlCloseBase(db);
m_indexedDirs.clear();
if (!dirs.isEmpty()) {
m_indexedDirs.append(dirs);
Q_EMIT updateWatchDirList(dirs);
}
Q_EMIT albumsListUpdated();
}
void ZDB::sqlUpdateFileStats(const QString &fileName)
{
bool dynManga = false;
QString fname = fileName;
if (fname.startsWith(QSL("#DYN#"))) {
fname.remove(QRegularExpression(QSL("^#DYN#")));
dynManga = true;
}
QFileInfo fi(fname);
if (!fi.isReadable()) {
qWarning() << "updating aborted for" << fname << "as unreadable";
return;
}
bool mimeOk = false;
ZAbstractReader* za = ZGenericFuncs::readerFactory(this,fileName,&mimeOk,Z::rffSkipSingleImageReader,
Z::rfmCreateReader);
if (za == nullptr) {
qWarning() << fname << "File format not supported.";
return;
}
if (!za->openFile()) {
qWarning() << fname << "Unable to open file.";
za->setParent(nullptr);
delete za;
return;
}
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
QSqlQuery qr(db);
qr.prepare(QSL("UPDATE files SET pagesCount=?, fileSize=?, fileMagic=?, fileDT=? "
"WHERE (filename=?)"));
qr.bindValue(0,za->getPageCount());
if (dynManga) {
qr.bindValue(1,0);
} else {
qr.bindValue(1,fi.size());
}
qr.bindValue(2,za->getMagic());
qr.bindValue(3,fi.birthTime());
qr.bindValue(4,fname);
za->closeFile();
za->setParent(nullptr);
delete za;
if (!qr.exec()) {
qWarning() << fname << "unable to update file stats" <<
qr.lastError().databaseText() << qr.lastError().driverText();
}
sqlCloseBase(db);
}
void ZDB::sqlSearchMissingManga()
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
QStringList ignoredFiles;
QSqlQuery qr(QSL("SELECT filename FROM ignored_files"),db);
while (qr.next())
ignoredFiles.append(qr.value(0).toString());
QStringList filenames;
for (const QString& d : std::as_const(m_indexedDirs)) {
QDir dir(d);
const QFileInfoList fl = dir.entryInfoList(
QStringList(QSL("*")), QDir::Files | QDir::Readable);
for (const QFileInfo &fi : fl) {
const QString fname = fi.absoluteFilePath();
if (!ignoredFiles.contains(fname))
filenames.append(fname);
}
}
QStringList indexedFiles;
QSqlQuery qr2(QSL("SELECT filename "
"FROM files "
"WHERE NOT(fileMagic='DYN')"),
db);
while (qr2.next())
indexedFiles.append(qr2.value(0).toString());
sqlCloseBase(db);
std::sort(std::execution::par, filenames.begin(), filenames.end());
std::sort(std::execution::par, indexedFiles.begin(), indexedFiles.end());
QStringList foundFiles;
std::set_difference(filenames.constBegin(),
filenames.constEnd(),
indexedFiles.constBegin(),
indexedFiles.constEnd(),
std::inserter(foundFiles, foundFiles.begin()));
Q_EMIT foundNewFiles(foundFiles);
}
void ZDB::sqlAddIgnoredFiles(const QStringList& files)
{
sqlInsertIgnoredFilesPrivate(files,false);
}
void ZDB::sqlSetIgnoredFiles(const QStringList& files)
{
sqlInsertIgnoredFilesPrivate(files,true);
}
void ZDB::sqlInsertIgnoredFilesPrivate(const QStringList &files, bool cleanTable)
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
if (!sqlHaveTables(db)) {
sqlCloseBase(db);
return;
}
QSqlQuery qr(db);
if (cleanTable) {
qr.prepare(QSL("DELETE FROM `ignored_files`"));
if (!qr.exec()) {
Q_EMIT errorMsg(tr("Unable to delete from table `ignored_files`\n\n%1\n%2")
.arg(qr.lastError().databaseText(),qr.lastError().driverText()));
m_problems[tr("Delete from table - ignored_files")] =
tr("Unable to delete from table `ignored_files`.\n"
"DELETE FROM query failed.");
sqlCloseBase(db);
return;
}
m_ignoredFiles.clear();
}
for (const QString& file : files) {
qr.prepare(QSL("INSERT INTO ignored_files (filename) VALUES (?)"));
qr.addBindValue(file);
if (!qr.exec()) {
Q_EMIT errorMsg(tr("Unable to add ignored file `%1`\n%2\n%3").
arg(file,qr.lastError().databaseText(),qr.lastError().driverText()));
sqlCloseBase(db);
return;
}
m_ignoredFiles << file;
}
sqlCloseBase(db);
}
Z::DBMS ZDB::sqlDbEngine(QSqlDatabase &db)
{
if (db.isValid() && db.driver()!=nullptr) {
if (db.driver()->dbmsType()==QSqlDriver::MySqlServer) return Z::dbmsMySQL;
if (db.driver()->dbmsType()==QSqlDriver::SQLite) return Z::dbmsSQLite;
}
return Z::dbmsUndefinedDB;
}
bool ZDB::sqlHaveTables(QSqlDatabase &db)
{
return sqlCheckBasePriv(db,true);
}
int ZDB::sqlFindAndAddAlbum(const QString &name, const QString &parent, bool createNew)
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return -1;
QSqlQuery qr(db);
qr.prepare(QSL("SELECT id FROM albums WHERE (name=?)"));
qr.addBindValue(name);
if (qr.exec()) {
if (qr.next()) {
sqlCloseBase(db);
return qr.value(0).toInt();
}
}
if (!createNew)
return -1;
int idParent = -1;
if (!parent.isEmpty()) {
qr.prepare(QSL("SELECT id FROM albums WHERE (name=?)"));
qr.addBindValue(parent);
if (qr.exec()) {
if (qr.next())
idParent = qr.value(0).toInt();
}
}
qr.prepare(QSL("INSERT INTO albums (name,parent) VALUES (?,?)"));
qr.bindValue(0,name);
qr.bindValue(1,idParent);
if (!qr.exec()) {
Q_EMIT errorMsg(tr("Unable to create album `%1`\n%2\n%3").
arg(name,qr.lastError().databaseText(),qr.lastError().driverText()));
sqlCloseBase(db);
return -1;
}
bool ok = false;
int ialbum = qr.lastInsertId().toInt(&ok);
if (!ok) {
ialbum = -1;
qr.prepare(QSL("SELECT id FROM albums WHERE (name=?)"));
qr.addBindValue(name);
if (qr.exec()) {
if (qr.next())
ialbum = qr.value(0).toInt();
}
}
sqlCloseBase(db);
return ialbum;
}
QStringList ZDB::sqlGetIgnoredFiles() const
{
return m_ignoredFiles;
}
Z::PDFRendering ZDB::getPreferredRendering(const QString &filename) const
{
if (m_preferredRendering.contains(filename))
return static_cast<Z::PDFRendering>(m_preferredRendering.value(filename));
return Z::PDFRendering::pdfAutodetect;
}
void ZDB::sqlSetPreferredRendering(const QString &filename, int mode)
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
QSqlQuery qr(db);
qr.prepare(QSL("UPDATE files SET preferredRendering=? WHERE filename=?"));
qr.bindValue(0,mode);
qr.bindValue(1,filename);
if (!qr.exec()) {
QString msg = tr("Unable to change preferred rendering for '%1'.\n%2\n%3").
arg(filename,qr.lastError().databaseText(),qr.lastError().driverText());
qWarning() << msg;
Q_EMIT errorMsg(msg);
}
m_preferredRendering[filename] = mode;
sqlCloseBase(db);
}
void ZDB::sqlGetTablesDescription()
{
QSqlDatabase db = sqlOpenBase();
if (!db.isValid()) return;
if (db.driver()==nullptr) {
sqlCloseBase(db);
return;
}
QSqlRecord rec = db.driver()->record(QSL("files"));
if (rec.isEmpty()) {
sqlCloseBase(db);
return;
}
QStringList names;
QStringList types;
names.reserve(rec.count());
int nl = 0; int tl = 0;
for (int i=0; i < rec.count(); i++)
{
names.append(rec.field(i).name());