File: filewatcher.cpp

package info (click to toggle)
nixnote2 2.0~beta11-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 9,448 kB
  • ctags: 7,058
  • sloc: cpp: 68,338; java: 1,096; sh: 834; makefile: 27
file content (223 lines) | stat: -rw-r--r-- 6,999 bytes parent folder | download
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
/*********************************************************************************
NixNote - An open-source client for the Evernote service.
Copyright (C) 2013 Randy Baumgarte

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
***********************************************************************************/

#include "filewatcher.h"
#include "global.h"
#include "sql/configstore.h"
#include "sql/notetable.h"
#include "sql/notebooktable.h"
#include "sql/resourcetable.h"
#include "utilities/mimereference.h"
#include "sql/filewatchertable.h"
#include "xml/batchimport.h"

#include <QDirIterator>

extern Global global;

FileWatcher::FileWatcher(QString dir, ScanType type, qint32 notebookLid, bool subdirs, QObject *parent) :
    QFileSystemWatcher(parent)
{
    this->notebookLid = notebookLid;
    this->dir = dir;
    this->scanType = type;
    this->includeSubdirectories = subdirs;
    addDirectory(dir);

    connect(this, SIGNAL(directoryChanged(QString)), this, SLOT(saveDirectory(QString)));
    connect(this, SIGNAL(fileChanged(QString)), this, SLOT(saveFile(QString)));
}


void FileWatcher::saveDirectory(QString dir){
    QStringList files;
    QStringList dirs;
    setupSubDirectories(dirs, files, dir);
    for (int i=0; i<files.size(); i++) {
        if (!saveFiles.contains(files[i]) || scanType == ImportDelete) {
            saveFiles.append(files[i]);
            saveFile(files[i]);
        }
    }
}

void FileWatcher::saveFile(QString file) {
    QFileInfo fileInfo(file);

    // If we have a dbi import file
    QLOG_DEBUG() << fileInfo.dir().absolutePath() + QDir::separator();
    QLOG_DEBUG() << global.fileManager.getDbiDirPath();
    if ((fileInfo.dir().absolutePath() + QDir::separator()) == global.fileManager.getDbiDirPath()) {
        BatchImport importer;
        importer.import(file);
        emit(nnexImported());
        QFile f(file);
        if (!f.remove()) {
            QLOG_ERROR() << tr("Error removing file: ") << f.errorString();
        }
        return;
    }


    // If we have a user-import file
    QFile f(file);
    f.open(QIODevice::ReadOnly);
    QByteArray data = f.readAll();
    f.close();
    if (f.size() == 0)
        return;

    Note newNote;
    NoteTable ntable(global.db);
    ConfigStore cs(global.db);
    qint32 lid = cs.incrementLidCounter();

    QCryptographicHash md5hash(QCryptographicHash::Md5);
    QByteArray hash = md5hash.hash(data, QCryptographicHash::Md5);

    // * Start setting up the new note
    newNote.guid = QString::number(lid);
    newNote.title = file;

    NotebookTable bookTable(global.db);
    QString notebook;
    bookTable.getGuid(notebook, notebookLid);
    newNote.notebookGuid = notebook;

    QString newNoteBody = QString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")+
           QString("<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">")+
           QString("<en-note style=\"word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;\">");

    MimeReference mimeRef;
    QString mime = mimeRef.getMimeFromFileName(file);
    QString enMedia =QString("<en-media hash=\"") +hash.toHex() +QString("\" border=\"0\"")
            +QString(" type=\"" +mime +"\" ")
            +QString("/>");
    newNoteBody.append(enMedia + QString("</en-note>"));
    newNote.content = newNoteBody;
    newNote.active = true;
    newNote.created = QDateTime::currentMSecsSinceEpoch();;
    newNote.updated = newNote.created;
    newNote.updateSequenceNum = 0;
    NoteAttributes na;
// Windows Check
#ifndef _WIN32
    na.sourceURL = "file://" + file;
#else
    na.sourceURL = "file:///"+file;
#endif  // end Windows cehck
    newNote.attributes = na;

    qint32 noteLid = lid;
    ntable.add(lid, newNote, true);
    QString noteGuid = ntable.getGuid(lid);
    lid = cs.incrementLidCounter();


    // Start creating the new resource
    Resource newRes;
    Data d;
    d.body = data;
    d.bodyHash = hash;
    d.size = data.size();
    newRes.data = d;
    newRes.mime = mime;
    ResourceAttributes ra;
    ra.fileName = QFileInfo(f).fileName();
    if (mime.startsWith("image", Qt::CaseInsensitive) || mime.endsWith("pdf", Qt::CaseInsensitive))
        ra.attachment = false;
    else
        ra.attachment = true;
    newRes.active = true;
    newRes.guid = QString::number(lid);
    newRes.noteGuid = noteGuid;
    newRes.updateSequenceNum = 0;
    newRes.attributes = ra;
    ResourceTable restable(global.db);
    restable.add(lid, newRes, true, noteLid);

    emit(fileImported(noteLid, lid));

    if (scanType == FileWatcher::ImportDelete) {
        QLOG_DEBUG() << f.remove();
    }
}


void FileWatcher::setupSubDirectories(QStringList &directories, QStringList &files, QString root) {
    QDirIterator it(root, QDirIterator::Subdirectories);
    while (it.hasNext()) {
        QString entry = it.next();
        QFileInfo fileInfo;
        fileInfo.setFile(entry);
        if (fileInfo.isFile() && !files.contains(fileInfo.absoluteFilePath())) {
            files.append(fileInfo.absoluteFilePath());
        }
        if (fileInfo.isDir() && !entry.endsWith("..") && !directories.contains(fileInfo.absoluteFilePath())) {
            directories.append(fileInfo.absoluteFilePath());
        }
    }
}



void FileWatcher::setupDirectory(QStringList &files, QString root) {
    QDirIterator it(root);
    files.clear();
    while (it.hasNext()) {
        QString entry = it.next();
        QFileInfo fileInfo;
        fileInfo.setFile(entry);
        if (fileInfo.isFile() && !files.contains(fileInfo.absoluteFilePath())) {
            files.append(fileInfo.absoluteFilePath());
        }
    }
}




void FileWatcher::addDirectory(QString root) {
    if (directories().contains(root))
        return;

    QStringList dirs;
    QStringList files;
    if (includeSubdirectories) {
        setupSubDirectories(dirs, files, root);
        if (!dirs.isEmpty())
           addPaths(dirs);
        if (!files.isEmpty())
            addPaths(files);
    } else {
        setupDirectory(files, root);
        if (!root.isEmpty())
            addPath(root);
        if (!files.isEmpty())
            addPaths(files);
    }
    if (scanType == ImportDelete) {
        for (int i=0; i<files.size(); i++) {
            saveFile(files[i]);
        }
    }
    if (scanType == ImportKeep)
        saveFiles = files;

}