-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.cpp
executable file
·2403 lines (2316 loc) · 81.7 KB
/
app.cpp
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 "app.h"
#include "timer.h"
#include "com/global.h"
#include <QDesktopServices>
#include <QDir>
#include <QFile>
#include <QImage>
#include <QJsonDocument>
#include <QJsonObject>
#include <QPdfWriter>
#include <QProcess>
#include <QSettings>
#include <QTimer>
#include <QCryptographicHash>
#include <QHotkey>
#include <QWindow>
#include <string>
#include "com/mypinyin.h"
#include <QResource>
#include <QSettings>
#include <QSslCertificate>
#include <QSslKey>
#include <QThreadPool>
#include "com/runmain.h"
#include "com/future.h"
#include "com/sslhelper.h"
tuple<QList<Work*>, QList<Note*>> parseNote(QString* cont);
QString parseBookName(const QString& note);
QString parseAuthorName(const QString& note);
tuple<uint, uint> parsePos(const QString& note);
qint64 parseTime(const QString& note);
void redoDuplicates(const QList<Note*>& list);
QMap<uint, QHotkey*> hotkMap;
void initPath();
void initLog();
void initDB();
App::App(): QObject() {
QDir dir(cfg->tmpDir);
QFileInfoList list = dir.entryInfoList();
for (int i = 0; i < list.size(); i++) {
QFileInfo fileInfo = list.at(i);
tmpFileLSTMap.insert(fileInfo.fileName(), fileInfo.lastModified().toMSecsSinceEpoch());
}
}
App::~App() {
}
int App::getPlatform() {
#ifdef Q_OS_MAC
return MAC;
#endif
#ifdef Q_OS_WIN
return WIN;
#else
return UNIX;
#endif
}
QString App::getCfgFile() {
return cfg->cfgFile;
}
QString App::getDataDir() {
return cfg->dataDir + "/xxmoon";
}
QString App::getBaseDir() {
return cfg->userBaseDir;
}
QString App::getFileDir() {
return cfg->fileDir;
}
QString App::getImgDir() {
return cfg->imgDir;
}
QString App::getCfgVal(QString k) {
return cfg->toVMap().value(k, "").toString();
}
QString App::getCtrl() {
return cfg->ctrl;
}
void App::import(QString path, QObject *obj) {
path = ut::str::removePrefix(path, getFilePre());
DB_Async->exe("import", [=] {
QString cont = ut::file::readFile(path);
cont = QString(ut::byte::removeBom(cont.toUtf8()));
tuple<QList<Work*>, QList<Note*>> tup = parseNote(&cont);
QList<Work*> works = get<0>(tup);
QList<Note*> notes = get<1>(tup);
if(lg->isDebug()){
lg->debug(QString("parsed path %1 cont length %2 works %3 notes %4")
.arg(path)
.arg(cont.length())
.arg(works.size())
.arg(notes.size()));
}
qint64 t1 = QDateTime::currentDateTime().currentMSecsSinceEpoch();
int size = notes.size();
workDao->add(works);
QList<Note*> dups = noteDao->insert(notes, [obj,size](int i){
if(obj!=nullptr) {
if(i+1 < size) {
QMetaObject::invokeMethod(obj, "onFinished",
Q_ARG(QVariant, QVariant::fromValue(CONT_TYPE_BOOK)),
Q_ARG(QVariant, QVariant::fromValue(i+1)),
Q_ARG(QVariant, QVariant::fromValue(size)),
Q_ARG(QVariant, QVariant::fromValue(0)));
}
}
});
redoDuplicates(dups);
for(Work* w:works) {
delete w;
}
for(Note* n:notes) {
delete n;
}
envDao->set(ENV_K_LAST_IMP_PATH, path);
envDao->set(ENV_K_LAST_IMP_TIME, QDateTime::currentDateTime().toMSecsSinceEpoch());
if(obj != nullptr) {
QMetaObject::invokeMethod(obj, "onFinished",
Q_ARG(QVariant, QVariant::fromValue(CONT_TYPE_BOOK)),
Q_ARG(QVariant, QVariant::fromValue(size)),
Q_ARG(QVariant, QVariant::fromValue(size)),
Q_ARG(QVariant, QVariant::fromValue(0)));
}
qint64 t2 = QDateTime::currentDateTime().currentMSecsSinceEpoch();
lg->info(QString("import finished %1 cost %2 ms").arg(size).arg(t2-t1));
});
}
tuple<QList<Work*>, QList<Note*>> parseNote(QString* cont) {
QList<Work*> works;
QList<Note*> list;
QString flag = cfg->kindleFlag;
if(cont->indexOf(flag) < 0) {
return make_tuple(works, list);
}
QStringList arr = cont->split(flag);
for(QString& note:arr) {
note = note.trimmed();
if(lg->isDebug()) {
lg->debug(QString("parsing note -> %1").arg(note));
}
if(note.length() > 0) {
QStringList lines = note.split("\n");
if(lines.length() > 1) {
QString str = lines[1];
bool matching = Reg_Kindle_Note.match(str).hasMatch();
if(lg->isDebug()) {
lg->debug(QString("parsing note matching -> %1 lines len %2 %3").arg(matching).arg(lines.size()).arg(str));
}
if (matching && lines.size() >= 3) {
Note *n = new Note();
n->time = parseTime(lines[1]);
uint id = noteDao->getIdByTime(n->time);
bool exists = id > 0;
if(!exists) {
n->book = parseBookName(lines[0]);
n->author = parseAuthorName(lines[0]);
tuple<uint, uint> posArr = parsePos(lines[1]);
n->pos0 = get<0>(posArr);
n->pos1 = get<1>(posArr);
for(int i = 2; i < lines.size(); i++) {
QString s = lines[i];
n->cont += s+ "\n";
}
n->cont = n->cont.trimmed();
n->bj = str.contains(cfg->kindleFlagBj);
if(n->bj) {
n->cont = ":["+n->cont+"]";
}
//
uint wid = 0;
for(Work* w : works) {
if(w->name == n->book && w->author == n->author) {
if(n->time < w->time) {
w->time = n->time;
}
wid = w->id;
break;
}
}
Work *w = nullptr;
if(wid == 0) {
w = workDao->get(n->book, n->author);
}
if(w != nullptr) {
if(n->time < w->time) {
w->time = n->time;
workDao->update(w);
}
wid = w->id;
}
if(wid == 0) {
wid = workDao->increID();
w = new Work();
w->id = wid;
w->name = n->book;
w->author = n->author;
w->time = n->time;
works << w;
}
n->wid = wid;
list << n;
}
}
}
}
}
return make_tuple(works, list);
}
QString parseBookName(const QString& line) {
if (line.length() > 0) {
int i = line.lastIndexOf("(");
if (i >= 0) {
return line.mid(0, i).trimmed();
} else {
return line.trimmed();
}
}
return "";
}
QString parseAuthorName(const QString& line) {
if (line.length() > 0) {
int i = line.lastIndexOf("(") + 1;
int j = line.lastIndexOf(")");
if (i >= 0 && j >= 0) {
return line.mid(i, j-i).trimmed();
}
}
return "";
}
vector<uint> findPos(string s) {
QString pos[] = {"", ""};
ushort i = 0;
bool start = false;
for(char c : s) {
if(c >= '0' && c <= '9') {
start = true;
pos[i] += c;
} else {
if(start) {
i++;
if(i>1){
break;
}
}
}
}
return {pos[0].toUInt(), pos[1].toUInt()};
}
tuple<uint, uint> parsePos(const QString& line) {
string s = line.toStdString();
QString pos[] = {"", ""};
ushort i = 0;
bool start = false;
for(char c : s) {
if(c >= '0' && c <= '9') {
start = true;
pos[i] += c;
} else {
if(start) {
i++;
if(i>1){
break;
}
}
}
}
return make_tuple(pos[0].toUInt(), pos[1].toUInt());
}
qint64 parseTime(const QString& line) {
if (line.length() > 0) {
int i = line.indexOf("添加于");
if (i >= 0) {
int addHours = 0;
int time_index = line.indexOf("下午");
if(time_index >= 0){
addHours = 12;
}
QString datePart = line.mid(i + 3, time_index - i - 3).trimmed(),
timePart = line.mid(time_index + 2, line.length() - time_index - 2).trimmed();
int yIndex = datePart.indexOf("年"),
mIndex = datePart.indexOf("月"),
dIndex = datePart.indexOf("日");
int y = datePart.mid(0, yIndex).toInt(),
m = datePart.mid(yIndex+1, mIndex - yIndex - 1).toInt(),
d = datePart.mid(mIndex+1, dIndex - mIndex - 1).toInt();
//
QStringList timeArr = timePart.split(":");
int h = timeArr[0].toInt() + addHours;
int min = timeArr[1].toInt();
int sec = timeArr[2].toInt();
QDateTime time(QDate(y,m,d), QTime(h, min, sec));
// qDebug("%d-%d-%d %d:%d:%d", y, m, d, h, min, sec);
return time.toMSecsSinceEpoch() / 1000;
}
}
return 0;
}
//重新处理插入错误的项(time相同导致),如果内容也相同则移除,内容不同则把time+1,加1还重复一直加
void redoDuplicates(const QList<Note*>& list) {
int c = 0;
for(Note* n:list) {
if(lg->isDebug()){
lg->debug("-> " + n->toString());
}
int max = 10000;
while(max-->0) {
uint existsId = noteDao->getIdByTime(n->time);
if(existsId <= 0) {
c++;
noteDao->insert(n);
if(lg->isDebug()){
lg->debug("<- " + n->toString());
}
break;
}
Note* existsNote = noteDao->get(existsId);
if(existsNote->cont == n->cont) {
break;
} else {
n->time += 1;
}
}
}
if(lg->isDebug()){
lg->debug(QString("redo dups %1/%2").arg(c).arg(list.size()));
}
}
//检测是否上次未导入完成就关闭了,是就继续
void App::checkImport() {
DB_Async->exe("checkImport",[=]{
l->debug("checkImport");
QString lastPath = envDao->get(ENV_K_LAST_IMP_PATH);
lastPath = ut::str::removePrefix(lastPath, getFilePre());
QFileInfo fi(lastPath);
if(fi.exists()){
uint lastTime = envDao->getUInt(ENV_K_LAST_IMP_TIME);
uint lm = fi.lastModified().toMSecsSinceEpoch();
if(lm > lastTime) {
// qDebug() << "import" << lastPath << lastTime << lm;
import(lastPath, nullptr);
}
}
});
}
void App::checkExport() {
if(cfg->exchangeDataDir.isEmpty()) {
return;
}
DB_Async->exe("checkExport", [=] {
QFileInfo fi(cfg->exchangeDataDir + "/" + cfg->dbFileName);
if(fi.exists()) {
// uint lastExchangeVersion = envDao->getUInt(ENV_K_LAST_EXCHANGE_VERSION);
}
});
}
void App::getLastPath(QObject *obj){
DB_Async->exe("getLastPath", [=]{
l->info("getLastPath");
QString lastPath = envDao->get(ENV_K_LAST_IMP_PATH);
QString lastTime = envDao->get(ENV_K_LAST_IMP_TIME);
QVariantList list;
list.append(lastPath);
list.append(lastTime);
QMetaObject::invokeMethod(obj, "onGetLastPath", Q_ARG(QVariant, QVariant::fromValue(list)));
});
}
void App::showOrHide() {
QObject* root = engine->rootObjects().at(0);
QMetaObject::invokeMethod(root, "showOrHide");
}
void App::showCmdPanel() {
if(cfg->cmdSrc > 0) {
QObject* root = engine->rootObjects().at(0);
QVariant closeCmdPanelIfVisible;
QMetaObject::invokeMethod(root, "closeCmdPanelIfVisible", Q_RETURN_ARG(QVariant, closeCmdPanelIfVisible));
if(closeCmdPanelIfVisible.isValid() && !closeCmdPanelIfVisible.toBool()) {
DB_Async->exe("showCmdPanel", [=]{
XM* xm = xmDao->getXM(cfg->cmdSrc);
if(xm != nullptr) {
QStringList lines = xm->cont.trimmed().split("\n");
QVariantMap m;
QString key = ut::cpb::getText();
QVariantList list;
for(QString& line: lines){
line = line.trimmed();
if(line.startsWith("//")) {
continue;
}
QStringList arr = line.split(",");
if(arr.length() > 2) {
m["n"] = arr[0].trimmed();
m["script"] = arr[1].trimmed();
m["tip"] = arr[2].trimmed();
m["ty"] = arr.length() < 4 ? 0 : arr[3].trimmed().toUInt();
m["tk"] = arr.length() < 5 ? 0 : arr[4].trimmed().toUInt();
list << m;
}
}
QMetaObject::invokeMethod(root, "showCmdPanel",
Q_ARG(QVariant, QVariant::fromValue(key)),
Q_ARG(QVariant, QVariant::fromValue(list)));
delete xm;
}
});
}
}
}
void App::setGlobalHotkey(uint ty, QString k) {
lg->info(QString("setGlobalHotkey %1 %2").arg(ty).arg(k));
QString hotv = k;
#ifdef Q_OS_MAC
//mac的cmd在qt里是ctrl,当配置cmd时实际要换成ctrl
if(k.startsWith("Cmd+")) {
hotv = hotv.replace("Cmd+", "Ctrl+");
}
if(k.startsWith("Ctrl+")) {
hotv = hotv.replace("Ctrl+", "Meta+");
}
#endif
QHotkey* hk = new QHotkey(QKeySequence(hotv), true);
hotkMap.insert(ty, hk);
QObject::connect(hk, &QHotkey::activated, qApp, [=](){
if(ty == 0) {
this->xm();
} else if(ty == 1) {
this->showOrHide();
} else if(ty == 2) {
this->showCmdPanel();
}
});
}
void App::xm() {
DB_Async->exe("xm", [=] {
QString cont = ut::cpb::getText();
QImage img = ut::cpb::getImage();
if(lg->isDebug()) {
lg->debug(QString("xm cont len %1 img [%2x%3]").arg(cont.length()).arg(img.size().width()).arg(img.size().height()));
}
if(cont == "" && img.isNull()) {
return;
}
QObject *qmlRoot = engine->rootObjects().at(0);
QVariant suc;
QMetaObject::invokeMethod(qmlRoot, "startXM",
Qt::ConnectionType::DirectConnection,
Q_RETURN_ARG(QVariant, suc));
xmAction->xm(&img, cont, "");
if(suc.toBool()) {
if(img.isNull()) {
if(cont.length() > 0) {
QString s = trans->tr("Words")+QString(": %1").arg(cont.length());
notify(s);
}
} else {
QString s = trans->tr("Picture");
notify(s);
}
} else {
lg->error(QString("xm failure cont len %1 img [%2*%3]").arg(cont.length()).arg(img.size().width()).arg(img.size().height()));
}
});
}
///tag
void App::tagList(QString k, uint target, QObject* obj) {
DB_Async->exe("tagList", [=] {
vector<Tag> list = tagDao->list(k);
QMap<uint,uint> countMap = tagDao->countTag(target);
QVariantList resp;
for(Tag t:list) {
t.n = countMap[t.id];
resp << t.toVMap();
}
if(lg->isDebug()) {
lg->trace(QString("app.cpp tagList k %2 target %3").arg(k).arg(target));
}
bool all = k.length() == 0;
QMetaObject::invokeMethod(obj, "onTagList",
Q_ARG(QVariant, QVariant::fromValue(all)),
Q_ARG(QVariant, QVariant::fromValue(resp)));
});
}
void App::addTag(QString tag, QObject *obj) {
DB_Async->exe("addTag", [=] {
Tag *t = tagDao->getByName(tag);
int st = 0;
if(t == nullptr) {
t = new Tag();
t->tag = tag;
tagDao->add(t);
} else {
st = 1;
}
alert(trans->tr("Add Success!"));
QMetaObject::invokeMethod(obj, "onAddTag",
Q_ARG(QVariant, QVariant::fromValue(st)),
Q_ARG(QVariant, QVariant::fromValue(t->toVMap())));
delete t;
});
}
void App::delTag(uint tid, QObject *obj) {
DB_Async->exe("delTag", [=] {
uint ref_pk = tagDao->countTag(tid, 0);
uint ref_note = tagDao->countTag(tid, 1);
uint ref = ref_pk + ref_note;
if (ref == 0) {
tagDao->del(tid);
}
QMetaObject::invokeMethod(obj, "onDelete",
Q_ARG(QVariant, QVariant::fromValue(tid)),
Q_ARG(QVariant, QVariant::fromValue(ref)));
});
}
void App::getTagById(uint id, uint cbid) {
DB_Async->exe("getTagById", [=] {
Tag *tag = tagDao->get(id);
if(tag != nullptr) {
sendMsg(cbid, tag->toVMap());
delete tag;
}
});
}
void App::setLocal(QString k, QString v) {
QString s;
QStringList localCfgLines = ut::file::allLines(cfg->localCfgFileName);
bool up = false;
if(localCfgLines.length() > 0) {
for(int i = 0; i < localCfgLines.length(); i++) {
QString line = localCfgLines.at(i);
line = line.trimmed();
if(!line.isEmpty()) {
QStringList kv = line.split("=");
if(kv.length() > 1) {
QString k_ = kv.at(0).trimmed();
if(k == k_) {
line = k + "=" + v;
up = true;
}
}
}
s += line + "\n";
}
}
if(!up) {
s += k + "=" + v + "\n";
}
ut::file::writeText(cfg->localCfgFileName, s.trimmed());
}
void App::set(QString k, QString v, bool init) {
DB_Async->exe("set", [=]{
envDao->set(k,v);
if(init) {
RunMain::INS().exec([this]{
init0();
});
}
});
}
void App::init0() {
QObject *obj = engine->rootObjects().at(0);
QMetaObject::invokeMethod(obj, "init",
Q_ARG(QVariant, QVariant::fromValue(this->getUIData())));
}
QVariantMap App::getUIData() {
uint lastCategoryLeftWidth = 0;
uint lastBookLeftWidth = 0;
QString wh = "";
uint maxWindow = 0;
QStringList localCfgLines = ut::file::allLines(cfg->localCfgFileName);
if(localCfgLines.length() > 0) {
for(QString line : localCfgLines) {
line = line.trimmed();
if(!line.isEmpty()) {
QStringList kv = line.split("=");
if(kv.length() > 1) {
QString k = kv.at(0).trimmed();
QString v = kv.at(1).trimmed();
if(k == ENV_K_LAST_BOOK_LEFT_WIDTH) {
lastBookLeftWidth = v.toUInt();
} else if(k == ENV_K_LAST_CATEGORY_LEFT_WIDTH) {
lastCategoryLeftWidth = v.toUInt();
} else if(k == ENV_K_LAST_WH) {
wh = v;
} else if(k == "maxWindow") {
maxWindow = v.toUInt();
}
}
}
}
}
QVariantMap *data = new QVariantMap();
Future *f = new Future();
DB_Async->exe("get_view_type_sort", [f]{
uint vt = envDao->getUInt(ENV_K_LAST_VIEW_TYPE);
QString sort = envDao->get(ENV_K_LAST_SORT, "p");
f->setList(QVariantList() << vt << sort);
});
QVariantList l = f->getList();
data->insert(ENV_K_LAST_VIEW_TYPE, l.at(0));
data->insert(ENV_K_LAST_SORT, l.at(1));
data->insert(ENV_K_LAST_WH, wh.split(","));
data->insert(ENV_K_LAST_CATEGORY_LEFT_WIDTH, lastCategoryLeftWidth);
data->insert(ENV_K_LAST_BOOK_LEFT_WIDTH, lastBookLeftWidth);
data->insert("maxWindow", maxWindow);
QVariantMap d = *data;
delete data;
delete f;
return d;
}
void App::encrypt(uint id, QString k, uint listWidth, uint cbid) {
if(lg->isDebug()){
lg->debug(QString("encrypt xm id %1").arg(id));
}
DB_Async->exe("encrypt", [=]{
XM *xm = xmDao->getXM(id);
Com_Async->exe("encrypt", [=]{
if(xm != nullptr) {
if(!xm->jm) {
if(xm->cont.length() > 0) {
uint len = xm->cont.length();
xm->cont = ut::cipher::encryptTextAES(k, xm->cont);
if(lg->isDebug()){
lg->debug(QString("encrypt pk cont len %1 -> %2").arg(len).arg(xm->cont.length()));
}
}
if(xm->img.length() > 0) {
QString imgPath = cfg->imgDir + "/" + xm->img;
QByteArray imgData = ut::img::toByteArray(imgPath);
QByteArray encodeData = ut::cipher::encryptAES(k, imgData);
QFileInfo tmpImgFile(cfg->tmpDir + "/" + xm->img);
QDir d;
if(!d.exists(tmpImgFile.path())) {
d.mkpath(tmpImgFile.path());
}
ut::file::writeData(tmpImgFile.filePath(), encodeData);
if(lg->isDebug()){
lg->debug(QString("encrypt pk img %1 %2 tmp img %3 %4")
.arg(imgData.size()).arg(imgPath)
.arg(encodeData.size()).arg(tmpImgFile.filePath()));
}
}
}
xm->simpleCont = extractXMSimpleCont(xm->cont, "");
sendMsg(cbid, xm->toVMap(1, 1, listWidth));
delete xm;
}
});
});
}
void App::decrypt(uint id, QString k, uint listWidth, uint cbid) {
if(lg->isDebug()) {
lg->debug(QString("decrypt %1").arg(id));
}
DB_Async->exe("decrypt", [=]{
XM *xm = xmDao->getXM(id);
Com_Async->exe("decrypt", [=]{
if(xm && xm->jm) {
if(xm->cont.length() > 0) {
uint len = xm->cont.length();
xm->cont = ut::cipher::decryptTextAES(k, xm->cont);
if(lg->isDebug()){
lg->debug(QString("decrypt id %1 cont len %2 -> %3")
.arg(id).arg(len).arg(xm->cont.length()));
}
}
if(xm->img.length() > 0) {
QString imgPath = cfg->imgDir + "/" + xm->img;
QByteArray data = ut::file::toByteArray(imgPath);
QByteArray decodeData = ut::cipher::decryptAES(k, data);
QFileInfo tmpImgFile(cfg->tmpDir + "/" + xm->img);
QDir d;
if(!d.exists(tmpImgFile.path())) {
d.mkpath(tmpImgFile.path());
}
ut::file::writeData(tmpImgFile.filePath(), decodeData);
if(lg->isDebug()) {
lg->debug(QString("decrypt id %1 img %2 len %3 tmpImg %4 len %5")
.arg(id).arg(imgPath).arg(data.size()).arg(tmpImgFile.filePath()).arg(decodeData.size()));
}
}
}
if(xm != nullptr) {
xm->simpleCont = extractXMSimpleCont(xm->cont, "");
sendMsg(cbid, xm->toVMap(1,1,listWidth));
delete xm;
}
});
});
}
void App::ensureEncryptOrDecrypt(uint id, QString cont, uint cbid) {
DB_Async->exe("ensureEncryptOrDecrypt", [=]{
int st = 0;
XM *pk = xmDao->getXM(id);
if(pk) {
bool up = false;
if(cont.length() > 0) {
if(lg->isDebug()){
lg->debug(QString("ensureEncryptOrDecrypt id %1 jm %2").arg(id).arg(pk->jm));
}
pk->cont = cont;
up = true;
}
QString imgPath = cfg->imgDir + "/" + pk->img;
QString enOrDecryptFile = cfg->tmpDir + "/" + pk->img;
if(ut::file::exists(enOrDecryptFile)) {
if(lg->isDebug()) {
lg->debug(QString("ensureEncryptOrDecrypt exists enOrDecryptFile %1 id %2 jm %3")
.arg(imgPath).arg(id).arg(pk->jm));
}
ut::file::rm(imgPath);
ut::file::rename(enOrDecryptFile, imgPath);
up = true;
}
if(up) {
pk->jm = !pk->jm;
xmDao->updateXM(id, pk->cont, pk->jm);
}
} else {
st = 1;
}
sendMsg(cbid, st);
delete pk;
});
}
QString mainImgConvHtml(QString img) {
if(img.length() > 0){
QString imgPath = cfg->imgDir + "/" + img;
QVariantList r = calWinHeight(img, GEN_PDF_MAX_WIDTH);
return "<img src='" + getFilePre() + imgPath+"' width='"+r[1].toString()+"' height='"+r[2].toString()+"'/>";
}
return "";
}
QString extractName(QString cont, int len=16) {
QString name = cont.mid(0, 200);
//
static QRegularExpression reg_title("# (.+)");
QRegularExpressionMatch match = reg_title.match(cont);
if(match.hasMatch()) {
name = match.captured(1);
}
return name.replace(",", "")
// .replace(".", "")
.replace("`", "")
.replace(":", "")
.replace(":", "")
.replace("/", "")
.replace("\\", "")
.replace("*", "")
.replace("?", "")
.replace("\"", "")
.replace("'", "")
.replace("<", "")
.replace(">", "")
.replace("|", "")
// .replace(" ", "_")
.replace("\n", "")
.trimmed().mid(0, len);
}
void setXMBlogTag(uint id) {
DB_Async->exe("setXMBlogTag", [id] {
Tag *tag = tagDao->getByName(cfg->siteXmblogTag);
if(!tag) {
tag = new Tag();
tag->tag = cfg->siteXmblogTag;
tagDao->add(tag);
}
XM *pk = xmDao->getXM(id);
QString tagId_ = QString("#%1#").arg(tag->id);
if(!pk->tags.contains(tagId_)) {
QString tags = pk->tags;
if(tags.isEmpty()) {
tags = tagId_;
} else {
tags = tags + QString::number(tag->id) + "#";
}
xmDao->updateXMTags(id, tags);
pushMsg(PUSH_UP_TAGS, ut::col::createMap("id", id, "tags", tags));
}
delete tag;
delete pk;
});
}
void delXMBlogTag(uint id) {
DB_Async->exe("delXMBlogTag", [id] {
Tag *tag = tagDao->getByName(cfg->siteXmblogTag);
if(!tag) {
return;
}
XM *pk = xmDao->getXM(id);
if(pk) {
QString tagId_ = QString("#%1#").arg(tag->id);
if(pk->tags.contains(tagId_)) {
//#1#2#3#4#5#
pk->tags = pk->tags.replace("#"+QString::number(tag->id), "");
xmDao->updateXMTags(id, pk->tags);
pushMsg(PUSH_UP_TAGS, ut::col::createMap("id", id, "tags", pk->tags));
}
delete pk;
}
delete tag;
});
}
void App::genFile(uint fileType, uint type, uint gid, uint id, bool batch, QString pwd) {
if(lg->isDebug()) {
lg->debug(QString("genFile fileType %1 type %2 gid %3 id %4").arg(fileType).arg(type).arg(gid).arg(id));
}
DB_Async->exe("genFile", [=]{
QString *cont = new QString();
QString filename = "";
QString file = cfg->fileDir;
uint maxWidth = fileType == FILE_TYPE_PDF ? GEN_PDF_MAX_WIDTH : 0;
if(type == CONT_TYPE_PK) {
if(gid > 0) {
uint fromId = 0;
while(true) {
QList<XM*> list = xmDao->getXMList("", gid, fromId);
if(lg->isDebug()) {
lg->debug(QString("gen pk file %1 %2 %3 fromId %4").arg(fileType).arg(gid).arg(list.size()).arg(fromId));
}
if(list.size() == 0) {
break;
}
for(int i = 0; i < list.size(); i++) {
XM *xm = list.at(i);
if(fileType == FILE_TYPE_XM) {
if(batch) {
if(!xm->jm) {
file = xm_format->createXMFile(extractName(xm->cont), xm->img, xm->cont, pwd);
}
} else {
if(!xm->jm) {
if(xm->img.length() > 0) {
cont->append("!(" + xm->img + ")\n");
}
if(xm->cont.length() > 0) {
cont->append(xm->cont+"\n\n");
}
}
}
} else {
if(!xm->jm) {
if(xm->img.length() > 0) {
cont->append("<p>"+mainImgConvHtml(xm->img)+"</p>");
}
if(xm->cont.length() > 0){
cont->append("<p>"+doc_parser->parseHtml(xm->cont, maxWidth)+"</p>");
}
}
}
delete xm;
}
fromId = list.last()->id;
}
Category *c = categoryDao->getCategory(gid);
if(c) {
filename = extractName(c->name, c->name.length());
}
delete c;
} else if(id > 0) {
if(lg->isDebug()) {
lg->debug(QString("gen pk file %1 %2").arg(fileType).arg(id));
}
XM *pk = xmDao->getXM(id);
if(pk) {
filename = extractName(pk->cont, fileType == FILE_TYPE_SITE?50:16);
if(fileType == FILE_TYPE_XM) {
file = xm_format->createXMFile(filename, pk->img, pk->cont, pwd);
} else {
if(pk->img.length() > 0) {
cont->append(mainImgConvHtml(pk->img));
}
if(pk->cont.length() > 0) {
cont->append(doc_parser->parseHtml(pk->cont, maxWidth));
}
if(fileType == FILE_TYPE_SITE) {
file = createSiteFile(filename, *cont, pk->time);
setXMBlogTag(pk->id);
}
}
}
delete pk;
}
} else if(type == CONT_TYPE_BOOK) {
if(gid > 0) {
uint page = 0;
QString xmCont;
l->info("genFile CONT_TYPE_BOOK");
while(true) {
QString sort = envDao->get(ENV_K_LAST_SORT);
QList<Note*> list = noteDao->getNoteList("", gid, page, sort);
if(list.size() == 0) {
break;
}
for(int i = 0; i < list.size(); i++) {
Note *n = list.at(i);
if(n->cont.length() > 0) {
if(fileType == FILE_TYPE_XM) {
xmCont += n->cont + "\n\n";
} else {
if(n->bj) {
cont->append("<p class='item-bj'>"+doc_parser->parseHtml(n->cont, maxWidth)+"</p>");
} else {
cont->append("<p class='item'>"+doc_parser->parseHtml(n->cont, maxWidth)+"</p>");
}
}
}
delete n;
}
page++;
}
Work *w = workDao->get(gid);
if(w) {
filename = "《" + w->name + "》笔记";
filename = extractName(filename, filename.length());
delete w;
}
if(fileType == FILE_TYPE_XM) {
file = xm_format->createXMFile(filename, "", xmCont, "");
} else {
if(fileType == FILE_TYPE_SITE) {
if(w != nullptr) {
file = createSiteFile(filename, *cont, w->time);
}
// setXMBlogTag(w->id);
}
}
} else if(id > 0) {
Note *n = noteDao->get(id);
if(n) {
if(n->cont.length() > 0) {
filename = extractName(n->cont);
if(fileType == FILE_TYPE_XM){
file = xm_format->createXMFile(filename, "", n->cont, "");
} else {
if(n->bj) {
cont->append("<p"+QString(NOTE_BJ_STYLE)+">"+doc_parser->parseHtml(n->cont, maxWidth)+"</p>");
} else {
cont->append(doc_parser->parseHtml(n->cont, maxWidth));
}
}
}
delete n;
}
}
}
//
if(cont->length() > 0) {
if(filename.length() == 0) {
filename = "xxmoon_" + ut::time::getCurrentTimeStr();
}
if(fileType == FILE_TYPE_PDF) {
file = cfg->fileDir + "/" + (filename+".pdf");
QFile pdf_file(file);
pdf_file.open(QIODevice::WriteOnly);
QPdfWriter *pdf_writer = new QPdfWriter(&pdf_file);
pdf_writer->setPageSize(QPageSize::A4);
// pdf_writer->setResolution(30);
// qDebug() << "pdf" << pdf_writer->pageSize() << pdf_writer->pageSizeMM();
pdf_writer->setCreator("xxmoon");
pdf_writer->setTitle("xxmoon");
QTextDocument doc;
doc.setHtml(*cont);
doc.print(pdf_writer);
delete pdf_writer;
} else if(fileType == FILE_TYPE_HTML) {
file = cfg->fileDir + "/" + (filename+".html");
QString css = "<style>"+ut::file::readFile(":assets/com.css")+"</style><div class='main'>";
cont->insert(0, css);
cont->append("</div>");
ut::file::writeText(file, *cont);
} else if(fileType == FILE_TYPE_XM) {
file = xm_format->createXMFile(filename, "", *cont, "");
}