Debian Codegraph @

src/Library/Library.cpp

raw symbols SCIP
1 /*
2 * Copyright 2014 Mihai Niculescu <[email protected]>
3 *
4 * This file is part of EqualX Project (https://launchpad.net/equalx/)
5 *
6 * EqualX is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * EqualX is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <QDebug>
21
22 #include <QDateTime>
23 #include <QDir>
24 #include <QFile>
25 #include <QFileInfo>
26 #include <QSqlDriver>
27 #include <QSqlError>
28 #include <QSqlQuery>
29 #include <QVariant>
30
31 #include "File.h"
32 #include "Library/Library.h"
33
34 #define DB_NAME "library.db"
35 #define LIB_DIR_NAME ".equalx"
36 #define BOOKMARKS_DIR "bookmarks"
37 #define HISTORY_DIR "history"
38 #define BOOKMARKSTOOLBAR_DIR "bookmarks-toolbar"
39
40 LibraryManager* LibraryManager::mInstance=NULL;
41
42 LibraryManager* LibraryManager::Instance()
43 {
44 if(!mInstance) mInstance = new LibraryManager;
45
46 return mInstance;
47 }
48
49 LibraryManager::LibraryManager(QObject *parent) :
50 QObject(parent)
51 {
52 mDB = QSqlDatabase::addDatabase("QSQLITE");
53
54 if(!mDB.driver()->hasFeature(QSqlDriver::QuerySize)){
55 qDebug() << "SQL Driver doesn't support QuerySize";
56 }
57
58 if(!mDB.driver()->hasFeature(QSqlDriver::Transactions)){
59 qDebug() << "SQL Driver doesn't support transactions";
60 }
61
62 setup();
63 }
64
65 LibraryManager::~LibraryManager()
66 {
67 mDB.close();
68 }
69
70 inline QString LibraryManager::path() const
71 {
72 QString libDirPath(QDir::homePath());
73
74 libDirPath.append(QDir::separator()).append(LIB_DIR_NAME);
75
76 return QDir::toNativeSeparators(libDirPath);
77 }
78
79 bool LibraryManager::setup()
80 {
81 mBookmarksDirStr = path().append(QDir::separator()).append(BOOKMARKS_DIR).append(QDir::separator());
82 mHistoryDirStr = path().append(QDir::separator()).append(HISTORY_DIR).append(QDir::separator());
83
84 QString libDirPath(path());
85
86 QDir libDir(libDirPath);
87
88 if(!libDir.exists()) createLibrary(libDirPath);
89
90 // check existance and permissions of library database
91 libDirPath.append(QDir::separator()).append(DB_NAME);
92 QFileInfo lib(libDirPath);
93
94 mDB.setDatabaseName(lib.filePath());
95 if(!mDB.open())
96 {
97 qDebug() << "Couldn't Open the Database. Report:" << mDB.lastError().text();
98 }
99
100 QSqlQuery query;
101 if(!query.exec("PRAGMA foreign_keys=ON;")){
102 qDebug() << "SQL Driver Failed Trying set FOREIGN KEYS=ON";
103 }
104 if(!query.exec("PRAGMA foreign_keys;")){
105 qDebug() << "SQL Driver Failed Trying get FOREIGN KEYS status";
106 }
107
108 query.next();
109 qDebug() << "FOREIGN KEYS="<<query.value(0).toInt();
110
111 if(mDB.tables().isEmpty()) createDatabaseTablesFromFile("://resources/createLibraryTables.sql");
112 if(!lib.isReadable() && !lib.isWritable()){
113 mErrStr = tr("EqualX can not read or write library database. Make sure you have the correct permissions on file: ").append(lib.absolutePath());
114 return false;
115 }
116
117 return mDB.isOpen();
118
119 }
120
121 bool LibraryManager::createLibrary(const QString &path)
122 {
123 QDir libDir(path);
124 libDir.mkpath(path); // create all directories for library
125 libDir.cd(path);
126
127 libDir.mkdir(BOOKMARKS_DIR); // create a subdirectory holding all equations added to the library
128 libDir.mkdir(HISTORY_DIR); // create a subdirectory to hold all history
129 libDir.mkdir(BOOKMARKSTOOLBAR_DIR); // create a subdirectory to hold all equations from bookmarks toolbar
130
131 return true;
132 }
133
134 bool LibraryManager::createDatabaseTablesFromFile(const QString &sqlFile)
135 {
136 bool status = false;
137
138 mDB.open();
139
140 QSqlQuery query;
141 QFile file(sqlFile);
142 file.open(QIODevice::ReadOnly);
143
144 char buf[2048];
145 while(file.readLine(buf, sizeof(buf))!=-1){
146 status = query.exec(buf);
147
148 if(!status) qDebug() << "CreateTables() Reports:"<< query.lastError().text();
149 }
150 file.close();
151
152 return status;
153 }
154
155 int LibraryManager::addBookmark(const QString &title, const QString &description, const QString &fromFile, int parentId)
156 {
157 Bookmark newBookmark;
158 newBookmark.idparent= parentId;
159 newBookmark.title= title;
160 newBookmark.description=description;
161 newBookmark.filePath=fromFile;
162
163 return addBookmark(newBookmark, parentId);
164 }
165
166 int LibraryManager::addBookmark(const Bookmark &bookmark, int parentId)
167 {
168 int lastId=0;
169
170 if(!mDB.isOpen()){
171 mErrStr = tr("Cannot add bookmark because the database is closed.");
172 return lastId;
173 }
174
175 if(parentId<1) parentId=1;
176
177 QSqlQuery query;
178 QString parentPath; // a null path means its parent is the root node
179
180 if(parentId>1){ // parent is a folder
181 query.prepare("SELECT dirPath FROM bookmarks_folders WHERE id=?");
182 query.addBindValue(parentId);
183
184 if(!query.exec()){
185 mErrStr = tr("Cannot add equation to Bookmarks because I can not find its parent path. Database Reports: ").arg(query.lastError().text());
186 return lastId;
187 }
188 // parent found
189 query.next();
190 parentPath = QString("%1/%2").arg(query.value(0).toString()).arg(parentId);
191 }
192
193 QFileInfo fromFileInfo(bookmark.filePath);
194 QString fileType = fromFileInfo.completeSuffix();
195 qint64 created=QDateTime::currentMSecsSinceEpoch();
196 qint64 modified=created;
197
198 query.clear();
199 query.prepare("INSERT INTO bookmarks (idparent, title, description, fileType, dirPath, created, modified) "
200 "values(?,?,?,?,?,?,?)");
201 query.addBindValue(parentId);
202 query.addBindValue(bookmark.title);
203 query.addBindValue(bookmark.description);
204 query.addBindValue(fileType);
205 query.addBindValue(parentPath);
206 query.addBindValue(created);
207 query.addBindValue(modified);
208
209 if(!query.exec()){
210 mErrStr = tr("Cannot add equation to Bookmarks. Database Reports: ").arg(query.lastError().text());
211 return lastId;
212 }
213
214 // the query was successful, now copy the file to the bookmarks folder
215 QString toFile = QString("%1/%2.%3").arg(mBookmarksDirStr, query.lastInsertId().toString(),fileType); // each file copyied is named after its index in the table
216
217 qDebug() << "Copying [" << bookmark.filePath <<"] -> [" << toFile <<"] ";
218 QFile::copy(bookmark.filePath, toFile);
219
220 lastId = query.lastInsertId().toInt();
221
222 EqualX::FileInfo eqInfo;
223 EqualX::File::fetchInfo(bookmark.filePath, &eqInfo);
224
225 QString eqLatexContent = eqInfo.equation().simplified();
226 eqLatexContent=eqLatexContent.replace(" ","");
227
228 query.clear();
229 query.prepare("INSERT INTO bookmarks_content (refId, latexContent, created) "
230 "values(?,?,?)");
231 query.addBindValue(lastId);
232 query.addBindValue(eqLatexContent);
233 query.addBindValue(created);
234
235 if(!query.exec()){
236 mErrStr = tr("Cannot add equation content to Bookmarks. Database Reports: ").arg(query.lastError().text());
237 return -1;
238 }
239
240 emit bookmarkFolderChanged(parentPath);
241
242 return lastId;
243 }
244
245 int LibraryManager::addBookmarkFolder(const QString &name, const QString& description, int parentId)
246 {
247 BookmarkFolder folder;
248 folder.idparent=parentId;
249 folder.name=name;
250 folder.description=description;
251
252 return addBookmarkFolder(folder, parentId);
253 }
254
255 int LibraryManager::addBookmarkFolder(const BookmarkFolder &folder, int parentId)
256 {
257 qDebug() << "LibraryManager::addBookmarkFolder() "<<folder.name<<" with parentId:"<< parentId;
258
259 int lastId=-1;
260
261 if(!mDB.isOpen()){
262 mErrStr = tr("Cannot add folder in Bookmarks because the database is closed.");
263 qDebug() << mErrStr;
264 return lastId;
265 }
266 if(parentId<1) parentId=1;
267
268 QSqlQuery query;
269 QString parentPath;
270
271 if(parentId>1){ // parent is an existing folder (and not the ROOT)
272 query.prepare("SELECT dirPath FROM bookmarks_folders WHERE id=?");
273 query.addBindValue(parentId);
274
275 if(!query.exec()){
276 mErrStr = tr("Cannot add folder to Bookmarks because I can not find its parent path. Database Reports: ").arg(query.lastError().text());
277 qDebug() << mErrStr;
278 return lastId;
279 }
280 // parent found
281 query.next();
282 parentPath = QString("%1/%2").arg(query.value(0).toString()).arg(parentId);
283 }
284
285 query.clear();
286 query.prepare("INSERT INTO bookmarks_folders (idparent,name,description,dirPath,created, modified) "
287 "VALUES (?,?,?,?,?,?)");
288 query.addBindValue(parentId);
289 query.addBindValue(folder.name);
290 query.addBindValue(folder.description);
291 query.addBindValue(parentPath);
292 query.addBindValue(QDateTime::currentMSecsSinceEpoch());
293 query.addBindValue(QDateTime::currentMSecsSinceEpoch());
294
295 if(!query.exec()){
296 mErrStr = tr("Cannot add folder to Bookmarks. Database Reports: %1").arg(query.lastError().text());
297 qDebug() << mErrStr;
298 return lastId;
299 }
300
301 lastId = query.lastInsertId().toInt();
302
303 qDebug() << "LibraryManager::addBookmarkFolder() lastInsertedId=" << lastId;
304
305 emit bookmarkFolderChanged(parentPath);
306
307 return lastId;
308 }
309
310 int LibraryManager::addHistoryItem(const QString &title, const QString &fromFile)
311 { int lastId = -1;
312
313 if(!mDB.isOpen()){
314 mErrStr = tr("Can not add equation to History because the database is closed.");
315 qDebug() << mErrStr;
316 return lastId;
317 }
318
319 QSqlQuery query;
320 query.prepare("INSERT INTO history (title, created) values(?,?)");
321 query.addBindValue(title);
322 query.addBindValue(QDateTime::currentMSecsSinceEpoch());
323
324 if(!query.exec()){
325 mErrStr = query.lastError().text();
326 qDebug() << mErrStr;
327 return lastId;
328 }
329
330 // the query was successful, than copy the file to the history folder
331 QString toFile(mHistoryDirStr);
332 toFile.append(query.lastInsertId().toString()); // each file copyied is named after its index in the table
333
334 qDebug() << "Copying [" << fromFile <<"] -> [" << toFile <<"] ";
335 QFile::copy(fromFile, toFile);
336
337 HistoryRow row;
338 row.id = query.lastInsertId().toInt();
339 row.title=title;
340 row.filePath = toFile;
341 row.created = QDateTime::currentMSecsSinceEpoch();
342
343 emit historyChanged();
344 emit historyChanged(row);
345
346 lastId = query.lastInsertId().toInt();
347 return lastId;
348 }
349
350 LibraryRowsList LibraryManager::getAllHistory()
351 {
352 LibraryRowsList rows;
353
354 if(!mDB.isOpen()){
355 mErrStr = tr("Cannot access equations from History because the database is closed.");
356 qDebug() << mErrStr;
357 return rows;
358 }
359
360 QSqlQuery query;
361 if(!query.exec("SELECT id,created FROM history ORDER BY id DESC")){
362 qDebug() << "Cannot access History. Error: " << query.lastError().text();
363 return rows;
364 }
365
366 while(query.next()){
367 LibraryModelData allocated;
368 allocated.id = query.value(0).toInt();
369 allocated.name.append(mHistoryDirStr).append(query.value(0).toString());
370 allocated.created = query.value(1).toULongLong();
371 allocated.type = LibraryModelData::TypeHistory;
372
373 rows.append(allocated);
374 }
375
376 return rows;
377
378 }
379
380 const HistoryRow LibraryManager::getHistoryRow(int id)
381 {
382 if(id<1) id=1;
383
384 HistoryRow allocated;
385
386 if(!mDB.isOpen()){
387 mErrStr = tr("Cannot access History because the database is closed.");
388 qDebug() << mErrStr;
389 return allocated;
390 }
391
392
393 QSqlQuery query;
394 if(!query.exec(QString("SELECT id,title,created FROM history WHERE id=%1").arg(id))){
395
396 qDebug() << "Cannot access History. Error: " << query.lastError().text();
397 return allocated;
398 }
399
400 if(query.next()){
401 allocated.id = query.value(0).toInt();
402 allocated.title = query.value(1).toString();
403 allocated.filePath.append(mHistoryDirStr).append(query.value(0).toString());
404 allocated.created = query.value(2).toULongLong();
405 }
406
407 return allocated;
408 }
409
410 bool LibraryManager::clearHistory()
411 {
412 if(!mDB.isOpen()){
413 mErrStr = tr("Cannot access History because the database is closed.");
414 qDebug() << mErrStr;
415 return false;
416 }
417
418 /* Remove db entries */
419 QSqlQuery query;
420 if(query.exec("DELETE FROM history")){
421 query.clear();
422 query.exec("UPDATE sqlite_sequence SET seq=0 WHERE name='history' ");
423
424 /* Remove files from history dir */
425
426 //save current working directory
427 QString saveDir = QDir::currentPath();
428
429 QDir histDir(mHistoryDirStr);
430 QDir::setCurrent(mHistoryDirStr);
431 QStringList filesInHistory = histDir.entryList();
432
433 foreach(QString file, filesInHistory){
434 histDir.remove(file);
435 }
436
437 // restore working dir
438 QDir::setCurrent(saveDir);
439
440 emit historyChanged();
441
442 return true;
443 }
444
445 mErrStr = query.lastError().text();
446 qDebug() << mErrStr;
447
448 return false;
449 }
450
451 Bookmark LibraryManager::getBookmark(int id)
452 {
453 if(id<1) id=1;
454
455 if(!mDB.isOpen()){
456 mErrStr = tr("Cannot access Bookmarks because the database is closed.");
457 qDebug() << mErrStr;
458 return Bookmark();
459 }
460
461 QSqlQuery query;
462 query.prepare("SELECT idparent,title,description,fileType,dirPath,created,modified FROM bookmarks where id=?");
463 query.addBindValue(id);
464
465 if(!query.exec()){
466 mErrStr = "Cannot query Bookmarks. Error: " + query.lastError().text();
467 qDebug() << mErrStr;
468 return Bookmark();
469 }
470
471 if(!query.next()){
472 mErrStr = "Cannot get bookmark from database. Error: " + query.lastError().text();
473 qDebug() << mErrStr;
474 return Bookmark();
475 }
476
477 Bookmark b;
478 b.id = id;
479 b.idparent = query.value(0).toInt();
480 b.title = query.value(1).toString();
481 b.description=query.value(2).toString();
482 b.filePath= QDir::toNativeSeparators(QString("%1%2.%3").arg(mBookmarksDirStr).arg(id).arg(query.value(3).toString()));
483 b.dirPath=query.value(4).toString();
484 b.created = query.value(5).toULongLong();
485 b.modified = query.value(6).toULongLong();
486
487 return b;
488 }
489
490 LibraryRowsList LibraryManager::getChildren(int idparent)
491 {
492 LibraryRowsList rows;
493
494 if(!mDB.isOpen()){
495 mErrStr = tr("Cannot access Bookmarks because the database is closed.");
496 qDebug() << mErrStr;
497 return rows;
498 }
499
500 if(idparent<1) idparent=1;
501
502 /** First, retrieve Bookmarks folders **/
503 QSqlQuery query;
504 query.prepare("SELECT id,name,created FROM bookmarks_folders WHERE idparent=? ORDER BY name ASC");
505 query.addBindValue(idparent);
506
507 if(!query.exec()){
508 mErrStr = tr("Cannot query Bookmarks Folders. Error: ") + query.lastError().text();
509 qDebug() << mErrStr;
510 return rows;
511 }
512
513 while(query.next()){
514 LibraryModelData allocated;
515 allocated.id = query.value(0).toInt();
516 allocated.name=query.value(1).toString();
517 allocated.created = query.value(2).toULongLong();
518 allocated.type = LibraryModelData::TypeFolder;
519
520 rows.append(allocated);
521 }
522
523 /** Finally, retrieve Bookmarks **/
524 query.clear();
525 if(!query.exec(QString("SELECT id,created FROM bookmarks WHERE idparent=%1 ORDER BY created ASC").arg(idparent) )){
526 mErrStr = "Cannot access Bookmarks. Error: " + query.lastError().text();
527 qDebug() << mErrStr;
528 return rows;
529 }
530
531 while(query.next()){
532 LibraryModelData allocated;
533 allocated.id = query.value(0).toInt();
534 allocated.name.append(mBookmarksDirStr).append(query.value(0).toString());
535 allocated.created = query.value(1).toULongLong();
536 allocated.type = LibraryModelData::TypeBookmark;
537
538 rows.append(allocated);
539 }
540
541
542
543 return rows;
544 }
545
546 LibraryRowsList LibraryManager::getAllBookmarkedFolders()
547 {
548 LibraryRowsList rows;
549
550 if(!mDB.isOpen()){
551 mErrStr = tr("Cannot access Bookmarks because the database is closed.");
552 qDebug() << mErrStr;
553 return rows;
554 }
555
556 /** First, retrieve Bookmarks folders **/
557 QSqlQuery query;
558 if(!query.exec("SELECT id,name,created FROM bookmarks_folders WHERE id>1 ORDER BY created DESC")){
559 mErrStr = tr("Cannot query Bookmarks Folders. Error: ") + query.lastError().text();
560 qDebug() << mErrStr;
561 return rows;
562 }
563
564 while(query.next()){
565 LibraryModelData allocated;
566 allocated.id = query.value(0).toInt();
567 allocated.name=query.value(1).toString();
568 allocated.created = query.value(2).toULongLong();
569 allocated.type = LibraryModelData::TypeFolder;
570
571 rows.append(allocated);
572 }
573
574 return rows;
575 }
576
577 BookmarkFolder LibraryManager::getBookmarkFolder(int id)
578 {
579 if(!mDB.isOpen()){
580 mErrStr = tr("Cannot access Bookmarks because the database is closed.");
581 qDebug() << mErrStr;
582 return BookmarkFolder();
583 }
584
585 QSqlQuery query;
586 query.prepare("SELECT idparent,name,description,dirPath,created,modified FROM bookmarks_folders where id=?");
587 query.addBindValue(id);
588
589 if(!query.exec()){
590 mErrStr = tr("Cannot query Bookmarks. Error: ") + query.lastError().text();
591 qDebug() << mErrStr;
592 return BookmarkFolder();
593 }
594
595 if(!query.next()){
596 mErrStr = tr("Cannot get Folder. Error: ") + query.lastError().text();
597 qDebug() << mErrStr;
598 return BookmarkFolder();
599 }
600
601 BookmarkFolder f;
602 f.id = id;
603 f.idparent=query.value(0).toInt();
604 f.name = query.value(1).toString();
605 f.description=query.value(2).toString();
606 f.dirPath=query.value(3).toString();
607 f.created = query.value(4).toULongLong();
608 f.modified = query.value(5).toULongLong();
609
610 return f;
611 }
612
613 int LibraryManager::childrenCountInFolder(int id)
614 {
615 if(!mDB.isOpen()){
616 mErrStr = tr("Cannot access Bookmarked equations because the database is closed.");
617 qDebug() << mErrStr;
618 return false;
619 }
620
621 if(id<1) id=1;
622
623 int nChildren=0;
624
625 /** Count Bookmarks folders **/
626 QSqlQuery query;
627 query.prepare("SELECT COUNT(id) FROM bookmarks_folders WHERE idparent=?");
628 query.addBindValue(id);
629
630 if(!query.exec()){
631 mErrStr = tr("Couldnt count subfolders.");
632 // qDebug() << mErrStr;
633 } else {
634 query.next();
635 nChildren = query.value(0).toInt();
636 }
637
638 /** Count Bookmarks **/
639 query.clear();
640 query.prepare("SELECT COUNT(id) FROM bookmarks WHERE idparent=?");
641 query.addBindValue(id);
642
643 if(!query.exec()){
644 mErrStr = tr("Couldnt count bookmarks in this folder.");
645 // qDebug() << mErrStr;
646 } else {
647 query.next();
648 nChildren += query.value(0).toInt();
649 }
650
651 // qDebug() << "Folder:"<<id<<" has "<< nChildren << " children";
652
653 return nChildren;
654 }
655
656 int LibraryManager::historySize()
657 {
658 if(!mDB.isOpen()){
659 mErrStr = tr("Cannot access History because the database is closed.");
660 qDebug() << mErrStr;
661 return false;
662 }
663
664 int nChildren=0;
665
666 QSqlQuery query;
667 if(!query.exec("SELECT COUNT(id) FROM history")){
668 mErrStr = tr("Couldnt count history.");
669 // qDebug() << mErrStr;
670 } else {
671 query.next();
672 nChildren = query.value(0).toInt();
673 }
674
675 return nChildren;
676 }
677
678 Bookmark LibraryManager::copyBookmark(int id, int idparent)
679 {
680 qDebug() << "LibraryManager::copyBookmark("<<id<<") => Folder:"<<idparent;
681
682 Bookmark bookmark = getBookmark(id);
683 //BookmarkFolder folder = getBookmarkFolder(idparent);
684
685 if(bookmark.isValid()){ // we have valid objects in database
686 int newId = addBookmark(bookmark, idparent);
687
688 // the query was successful, now copy the file to the bookmarks folder
689 QString toFile = QString("%1/%2.%3").arg(mBookmarksDirStr).arg(newId).arg(bookmark.fileExt()); // each file copyied is named after its index in the table
690
691 qDebug() << "Copying [" << bookmark.filePath <<"] -> [" << toFile <<"] ";
692 QFile::copy(bookmark.filePath, toFile);
693
694 // no need since addBookmark() above will emit the signal
695 //emit bookmarkFolderChanged(parentDirPath);
696
697 return getBookmark(newId);
698 }
699
700 return Bookmark();
701
702 }
703
704 BookmarkFolder LibraryManager::copyBookmarkFolder(int id, int idparent)
705 {
706 qDebug() << "LibraryManager::copyBookmarkFolder("<<id<<" "<< idparent<<")";
707
708 BookmarkFolder folder = getBookmarkFolder(id);
709 BookmarkFolder toParentfolder = getBookmarkFolder(idparent);
710
711 if(folder.isValid() && toParentfolder.isValid()){ // we have valid objects in database
712 int newid = addBookmarkFolder(folder, idparent);
713
714 copyChildren(id, newid);
715
716 // no need since addBookmarkFolder() above will emit the signal
717 //emit bookmarkFolderChanged(parentDirPath);
718
719 return getBookmarkFolder(newid);
720 }
721
722 return BookmarkFolder();
723 }
724
725 void LibraryManager::copyChildren(int ofFolderId, int toNewFolderId)
726 {
727 qDebug() << "LibraryManager::copyChildren("<<ofFolderId<<" "<< toNewFolderId<<")";
728
729 if(ofFolderId<=1 || toNewFolderId<1) return;
730
731 // copy children
732 foreach(LibraryModelData row, getChildren(ofFolderId)){
733 if(row.isFolder()){
734 qDebug() << "\t Has Subfolder: " << row.name << " id:"<<row.id;
735 BookmarkFolder folder = getBookmarkFolder(row.id);
736 // copy the folder
737 qDebug() << "\t Adding Subfolder: " << row.name << " id:"<<row.id;
738 int newId = addBookmarkFolder(folder, toNewFolderId);
739 qDebug() << "\t New Subfolder has id:"<<newId;
740 if(newId>0){
741 copyChildren(row.id, newId);
742 }
743 }
744 else if(row.isBookmark()){
745 qDebug() << "\t Has Bookmark: " << row.name;
746 copyBookmark(row.id, toNewFolderId);
747 }
748
749
750 }
751
752 }
753
754 bool LibraryManager::moveData(const LibraryModelData &data, int newParentId)
755 {
756 bool status = false;
757 if(data.isValid()){ // if the object is already in database
758 if(data.isFolder())
759 status = moveBookmarkFolder(data.id, newParentId);
760 else if(data.isBookmark())
761 status = moveBookmark(data.id, newParentId);
762 }
763 else {
764 if(data.isFolder())
765 status = addBookmarkFolder(BookmarkFolder(data), newParentId);
766 else if(data.isBookmark())
767 status = addBookmark(Bookmark(data), newParentId);
768 }
769
770 return status;
771 }
772
773 bool LibraryManager::moveBookmark(int id, int newParentId)
774 {
775 /****************************************************************************************/
776 /* We want to re-parent the bookmark */
777 /*--------------------------------------------------------------------------------------*/
778 /* - we must also change the its field 'dirPath' in database */
779 /*--------------------------------------------------------------------------------------*/
780
781 // First lets find the current dirPath
782 QSqlQuery query;
783 QString oldDirPath;
784
785
786 query.prepare("SELECT dirPath FROM bookmarks WHERE id=?");
787 query.addBindValue(id);
788
789 if(!query.exec()){
790 qDebug() << "Cannot find bookmark with id="<< id <<" . Error: " << query.lastError().text();
791 return false;
792 }
793
794 if(!query.next()){
795 qDebug() << "Cannot fetch dirPath of bookmark. Error: " << query.lastError().text();
796 return false;
797 }
798
799 oldDirPath = query.value(0).toString();
800
801 QString newDirPath;
802 if(newParentId>1){
803 // Now, find its new dirPath
804 query.prepare("SELECT dirPath FROM bookmarks_folders WHERE id=?");
805 query.addBindValue(newParentId);
806
807 if(!query.exec()){
808 qDebug() << "Cannot find Folder in Bookmarks. Error: " << query.lastError().text();
809 return false;
810 }
811
812 if(!query.next()){
813 qDebug() << "Cannot fetch dirPath of new parent Folder in Bookmarks. Error: " << query.lastError().text();
814 return false;
815 }
816
817 newDirPath = QString("%1/%2").arg(query.value(0).toString()).arg(newParentId);
818 }
819 // now update bookmark to the new parent ID and new dirPath
820 query.clear();
821 query.prepare("UPDATE bookmarks SET idparent=?,dirPath=?,modified=? WHERE id=?");
822 query.addBindValue(newParentId);
823 query.addBindValue(newDirPath);
824 query.addBindValue(QDateTime::currentMSecsSinceEpoch());
825 query.addBindValue(id);
826
827 if(!query.exec()){
828 qDebug() << "Cannot reparent bookmark . Error: " << query.lastError().text();
829 return false;
830 }
831
832 emit bookmarkFolderChanged(oldDirPath);
833 emit bookmarkFolderChanged(newDirPath);
834
835 return true;
836 }
837
838 bool LibraryManager::moveBookmarkFolder(int id, int newParentId)
839 {
840 /****************************************************************************************/
841 /* We want to re-parent the folder */
842 /*--------------------------------------------------------------------------------------*/
843 /* - we must also change the field 'dirPath' in database of its subfolders and bookmarks*/
844 /*--------------------------------------------------------------------------------------*/
845
846 // First lets find the current folders 'dirPath'
847 QSqlQuery query;
848 query.prepare("SELECT dirPath FROM bookmarks_folders WHERE id=?");
849 query.addBindValue(id);
850
851 if(!query.exec()){
852 qDebug() << "Cannot find Folder in Bookmarks. Error: " << query.lastError().text();
853 return false;
854 }
855
856 query.next();
857 QString oldDirPath = QString("%1/%2").arg(query.value(0).toString()).arg(id);
858
859 QString newDirPath;
860 if(newParentId>1){
861 // then lets find the new parents 'dirPath'
862 query.clear();
863 query.prepare("SELECT dirPath FROM bookmarks_folders WHERE id=?");
864 query.addBindValue(newParentId);
865
866 if(!query.exec()){
867 qDebug() << "Cannot find parent of Folder from Bookmarks. Error: " << query.lastError().text();
868 return false;
869 }
870
871 query.next();
872 newDirPath = QString("%1/%2").arg(query.value(0).toString()).arg(newParentId);
873 }
874
875 // now update folder to the new parent ID and new dirPath
876 query.clear();
877 query.prepare("UPDATE bookmarks_folders SET idparent=?,dirPath=? WHERE id=?");
878 query.addBindValue(newParentId);
879 query.addBindValue(newDirPath);
880 query.addBindValue(id);
881
882 if(!query.exec()){
883 qDebug() << "Cannot reparent Folder from Bookmarks. Error: " << query.lastError().text();
884 return false;
885 }
886
887 // now update all subfolders to the new dirPath
888 newDirPath = QString("%1/%2").arg(newDirPath).arg(id);
889 query.clear();
890 query.prepare("UPDATE bookmarks_folders SET dirPath=replace(dirPath,?,?) WHERE dirPath LIKE ? || '%' ");
891 query.addBindValue(oldDirPath);
892 query.addBindValue(newDirPath);
893 query.addBindValue(oldDirPath);
894
895 if(!query.exec()){
896 qDebug() << "Cannot reparent subfolders of this Folder from Bookmarks. Error: " << query.lastError().text();
897 return false;
898 }
899
900 // now update all bookmarks from this folder and its subfolders to the new dirPath
901 query.clear();
902 query.prepare("UPDATE bookmarks SET dirPath=replace(dirPath,?,?) WHERE dirPath LIKE ? || '%' ");
903 query.addBindValue(oldDirPath);
904 query.addBindValue(newDirPath);
905 query.addBindValue(oldDirPath);
906
907 if(!query.exec()){
908 qDebug() << "Cannot reparent subfolders of this Folder from Bookmarks. Error: " << query.lastError().text();
909 return false;
910 }
911
912 emit bookmarkFolderChanged(oldDirPath);
913 emit bookmarkFolderChanged(newDirPath);
914
915 return true;
916 }
917
918
919 bool LibraryManager::updateData(const LibraryModelData &data)
920 {
921 bool status = false;
922 if(data.isValid()){ // if the object is already in database
923 if(data.isFolder())
924 status = updateBookmarkFolder(BookmarkFolder(data));
925 else if(data.isBookmark())
926 status = updateBookmark(Bookmark(data));
927 }
928
929 return status;
930 }
931
932 bool LibraryManager::updateBookmark(const Bookmark &bookmark)
933 {
934 qDebug() << "updateing Bookmark id:" << bookmark.id << " parentid=" << bookmark.idparent;
935
936 if(!mDB.isOpen()){
937 mErrStr = tr("Cannot access Bookmarks because the database is closed.");
938 return false;
939 }
940
941 // we dont want to re-parent the bookmark, we simply want to update its own fields
942 QSqlQuery query;
943 query.prepare("UPDATE bookmarks SET title=?,description=?,modified=? WHERE id=?");
944 query.addBindValue(bookmark.title);
945 query.addBindValue(bookmark.description);
946 query.addBindValue(QVariant(QDateTime::currentMSecsSinceEpoch()));
947 query.addBindValue(bookmark.id);
948
949 if(!query.exec()){
950 qDebug() << "Cannot update Bookmarks. Error: " << query.lastError().text();
951 return false;
952 }
953
954 return true;
955 }
956
957 bool LibraryManager::updateBookmarkFolder(const BookmarkFolder &folder)
958 {
959 qDebug() << "updateing Folder in id:" << folder.id << " with parentid=" << folder.idparent;
960
961 if(!mDB.isOpen()){
962 mErrStr = tr("Cannot access Bookmarks because the database is closed.");
963 return false;
964 }
965
966 // we dont want to re-parent the folder, we simply want to update its own fields
967 QSqlQuery query;
968 query.prepare("UPDATE bookmarks_folders SET name=?,description=?,modified=? WHERE id=?");
969 query.addBindValue(QVariant(folder.name));
970 query.addBindValue(QVariant(folder.description));
971 query.addBindValue(QVariant(QDateTime::currentMSecsSinceEpoch()));
972 query.addBindValue(folder.id);
973
974 if(!query.exec()){
975 qDebug() << "Cannot update Folders from Bookmarks. Error: " << query.lastError().text();
976 return false;
977 }
978
979 emit bookmarkFolderChanged(folder.dirPath);
980
981 return true;
982 }
983
984 bool LibraryManager::removeBookmark(int id)
985 {
986 qDebug() << "LibraryManager::removeBookmark("<< id <<")";
987
988 if(!mDB.isOpen()){
989 mErrStr = tr("Cannot access Library because the database is closed.");
990 return false;
991 }
992
993 QString parentDirPath;
994
995 QSqlQuery query;
996 query.prepare("SELECT fileType,dirPath FROM bookmarks WHERE id=?");
997 query.addBindValue(id);
998
999 if(!query.exec()){
1000 mErrStr = tr("Cannot find bookmark. Error: ") + query.lastError().text();
1001 qDebug() << mErrStr;
1002
1003 return false;
1004 }
1005 if(!query.next()){
1006 mErrStr = tr("Cannot get bookmark. Error: ") + query.lastError().text();
1007 qDebug() << mErrStr;
1008
1009 return false;
1010 }
1011
1012 QString fileType = query.value(0).toString();
1013 parentDirPath = query.value(1).toString();
1014
1015 query.clear();
1016 query.prepare("DELETE FROM bookmarks WHERE id=?");
1017 query.addBindValue(id);
1018
1019 if(!query.exec()){
1020 mErrStr = tr("Cannot delete bookmark. Error: ") + query.lastError().text();
1021 qDebug() << mErrStr;
1022
1023 return false;
1024 }
1025
1026 emit bookmarkFolderChanged(parentDirPath);
1027
1028 return removeBookmarkFromFS(id, fileType);
1029
1030 }
1031
1032 bool LibraryManager::removeBookmarkFolder(int id)
1033 {
1034 qDebug() << "LibraryManager::removeBookmarkFolder("<< id <<")";
1035
1036 if(!mDB.isOpen()){
1037 mErrStr = tr("Cannot access Library because the database is closed.");
1038 return false;
1039 }
1040
1041 if(id<=1)
1042 return false;
1043
1044 // fetch the dirPath of the folder
1045 QString dirPath;
1046 QString parentDirPath;
1047
1048 //mDB.transaction();
1049
1050 QSqlQuery query;
1051 query.prepare("SELECT dirPath FROM bookmarks_folders WHERE id=?");
1052 query.addBindValue(id);
1053
1054 if(!query.exec()){
1055 qDebug() << "Cannot select Folder from Bookmarks. Error: " << query.lastError().text();
1056 return false;
1057 }
1058
1059 query.next();
1060 parentDirPath = query.value(0).toString();
1061 dirPath = QString("%1/%2").arg(parentDirPath).arg(id);
1062
1063 //! before deleteing the bookmarks, we must remove the bookmarks files from file system
1064 // find all bookmarks in this folder and its subfolders
1065 query.clear();
1066 query.prepare("SELECT id,fileType FROM bookmarks WHERE dirPath LIKE ? || '%' ");
1067 query.addBindValue(dirPath);
1068 if(!query.exec()){
1069 qDebug() << "Cannot find bookmarks in this Folder in Library. Error: " << query.lastError().text();
1070 return false;
1071 }
1072
1073 int fileId;
1074 QString fileType;
1075 while(query.next()){
1076 fileId = query.value(0).toInt();
1077 fileType = query.value(1).toString();
1078
1079 removeBookmarkFromFS(fileId, fileType);
1080 }
1081
1082 /****************************************/
1083 /* delete the folder from the database */
1084 /****************************************/
1085 query.clear();
1086 query.prepare("DELETE FROM bookmarks_folders WHERE id=?");
1087 query.addBindValue(id);
1088
1089 if(!query.exec()){
1090 qDebug() << "Cannot delete Folder from Bookmarks. Error: " << query.lastError().text();
1091 return false;
1092 }
1093
1094 // mDB.commit();
1095
1096 emit bookmarkFolderChanged(parentDirPath);
1097
1098 return true;
1099 }
1100
1101
1102 bool LibraryManager::removeSystemDir(const QString &dirName)
1103 {
1104 bool result = true;
1105 QDir dir(dirName);
1106
1107 if (dir.exists(dirName)) {
1108 foreach(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
1109 if (info.isDir()) {
1110 result = removeSystemDir(info.absoluteFilePath());
1111 }
1112 else {
1113 result = QFile::remove(info.absoluteFilePath());
1114 }
1115
1116 if (!result) {
1117 return result;
1118 }
1119 }
1120 result = dir.rmdir(dirName);
1121 }
1122 return result;
1123 }
1124
1125 inline bool LibraryManager::removeBookmarkFromFS(int id, const QString &filetype)
1126 {
1127 QString filePath = QDir::toNativeSeparators(QString("%1/%2.%3").arg(mBookmarksDirStr).arg(id).arg(filetype));
1128
1129 return QFile::remove(filePath);
1130 }
1131
1132 LibraryRowsList LibraryManager::searchBookmarks(QString searchText, SEARCH_MODE searchType)
1133 {
1134 qDebug() << "LibraryManager::searchBookmarks("<< searchText <<") Search Mode="<<searchType;
1135
1136 LibraryRowsList rows;
1137
1138 if(!mDB.isOpen()){
1139 mErrStr = tr("Cannot search Bookmarks because the database is closed.");
1140 return rows;
1141 }
1142
1143 QSqlQuery q;
1144 QString searchQuery;
1145
1146 switch (searchType) {
1147 case SEARCH_BY_TITLE:
1148 searchQuery = "SELECT id,created FROM bookmarks WHERE title LIKE '%' || ? || '%' ORDER BY created DESC";
1149 break;
1150 case SEARCH_BY_DESCRIPTION:
1151 searchQuery = "SELECT id,created FROM bookmarks WHERE description LIKE '%' || ? || '%' ORDER BY created DESC";
1152 break;
1153 case SEARCH_BY_CONTENT:
1154 searchQuery = "SELECT refid,created FROM bookmarks_content WHERE latexContent LIKE '%' || ? || '%' ORDER BY created DESC";
1155 searchText=searchText.simplified().replace(" ","");
1156 break;
1157 default: // Title and Description
1158 searchQuery = "SELECT id,created FROM bookmarks WHERE (title LIKE '%' || ? || '%') | (description LIKE '%' || ? || '%') ORDER BY created DESC";
1159 break;
1160 }
1161
1162 q.prepare(searchQuery);
1163 q.addBindValue(searchText);
1164 if(searchType==SEARCH_BY_TITLE_DESCRIPTION) q.addBindValue(searchText);
1165
1166 if(!q.exec() ){
1167 mErrStr = "Cannot access Bookmarks. Error: " + q.lastError().text();
1168 qDebug() << mErrStr;
1169 return rows;
1170 }
1171
1172 while(q.next()){
1173 LibraryModelData allocated;
1174 allocated.id = q.value(0).toInt();
1175 allocated.name.append(mBookmarksDirStr).append(q.value(0).toString());
1176 allocated.created = q.value(1).toULongLong();
1177 allocated.type = LibraryModelData::TypeBookmark;
1178
1179 rows.append(allocated);
1180 }
1181
1182 return rows;
1183 }