root/src/library.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
#include "library.h"
#include "nwutils.h"
#include <QDebug>
#include "server.h"
#include "directoryscanner.h"
#include "tvshowscanner.h"
#include <QStandardPaths>
#include "videofile.h"
#include "config.h"

Library::Library(QString path, QObject *parent) :
    QObject(parent),
    directory(path),
    onlineSync(*this),
    didInit(false),
    mFilter(tvShows, directory),
    searchThread(NULL),
    fileSystemWatcher(NULL)
{
    connect(this, SIGNAL(initDone()), this, SLOT(onInitDone()));
}

Library::~Library() {
    // terminate
    foreach (WallpaperDownload::FetchThread* t, runningWallpaperDownloaders) {
        t->terminate();
    }
    if (searchThread) {
        searchThread->terminate();
    }
    onlineSync.terminate();

    // wait
    foreach (WallpaperDownload::FetchThread* t, runningWallpaperDownloaders) {
        t->wait();
    }
    if (searchThread) {
        searchThread->wait();
    }
    onlineSync.wait();
}

bool Library::initDirectory() const {
    if (!directory.exists() && !QDir::root().mkpath(directory.absolutePath())) {
        qDebug() << "could not create library dir" << directory.absolutePath();
        return false;
    }
    return true;
}

void Library::watchFilesystem() {
    fileSystemWatcher = new QFileSystemWatcher(this);
    connect(fileSystemWatcher, SIGNAL(fileChanged(QString)), this, SLOT(fileChangedInSearchDirectory(QString)));
    connect(fileSystemWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(fileChangedInSearchDirectory(QString)));
}

void Library::initWallpaperDownloaders() {
    addWallpaperDownloader(new Moebooru::Client(("http://konachan.com")));
    addWallpaperDownloader(new Moebooru::Client(("https://yande.re")));
    addWallpaperDownloader(new Gelbooru::Client());
}

void Library::initOnlineSync(const BaseConfig& config) {
    onlineSync.init(config);
    connect(&onlineSync, SIGNAL(allFinished()),
            this, SLOT(fetchingFinished()));
}

bool Library::handleApiRequest(QHttpRequest *req, QHttpResponse *resp) {
    if (req->path().startsWith("/api/library/filter")) {
        return filter().handleApiRequest(req, resp);
    } else if (req->path().startsWith("/api/library/tvshow/")) {
        const int prefixOffset = sizeof("/api/library/tvshow/")-1;
        const QString encodedPath = req->url().path();
        const int commandPathOffset = encodedPath.indexOf('/', prefixOffset);
        QString encodedShowName = encodedPath.mid(prefixOffset, commandPathOffset-prefixOffset);
        QString showName = QUrl::fromPercentEncoding(encodedShowName.toUtf8());


        TvShow* show = existingTvShow(showName);
        if (show) {
            QString commandPath = encodedPath.mid(commandPathOffset, encodedPath.length() - commandPathOffset);

            if (commandPath.startsWith("/dropUrl")) {
                const QUrl droppedUrl = req->url().query(QUrl::FullyDecoded);
                this->onlineSync.handleDropUrl(show, droppedUrl);
            } else {
                show->handleApiRequest(commandPath, req, resp);
            }
        } else {
            Server::simpleWrite(resp, 400, "{\"error\":\"invalid show name\"}");
        }
    } else if (req->path().startsWith("/api/library/toggleWatched")) {
        Episode* episode = filter().getEpisodeForPath(req->url().query(QUrl::FullyDecoded));
        if (episode) {
            episode->setWatched(!episode->getWatched());
            Server::simpleWrite(resp, 200, QString("{\"watched\":%1}").arg(episode->getWatched() ? "true" : "false"), mime::json);
        } else {
            Server::simpleWrite(resp, 400, QString("{\"error\":\"Episode not found\"}"), mime::json);
        }
    } else if (req->path().startsWith("/api/library/movieFileMetaData")) {
        QString path = req->url().query(QUrl::FullyDecoded);
        Episode* ep = filter().getEpisodeForPath(path);
        if (ep) {
            MetaData data = metaDataParser->parse(path);
            Server::simpleWrite(resp, 200, data.toJson(), mime::json);
        }
        Server::simpleWrite(resp, 404, "File for path does not exist, or is not in Library" "text/plain");
    } else if (req->path().startsWith("/api/library/removeFiles") &&
               req->method() == QHttpRequest::HTTP_DELETE) {

        RequestBodyListener* bodyListener = new RequestBodyListener(resp, this);
        connect(req, SIGNAL(data(QByteArray)), bodyListener, SLOT(onDataReceived(QByteArray)));
        connect(bodyListener, SIGNAL(bodyReceived(QHttpResponse*,const QByteArray&)), this, SLOT(onBodyForRemoveFiles(QHttpResponse*,QByteArray)));
    } else if (req->path().startsWith("/api/library/scan")) {
        this->startSearch();
        Server::simpleWrite(resp, 200, "{\"status\":\"new search running\"}");
    } else {
        return false;
    }
    return true;
}

void Library::onBodyForRemoveFiles(QHttpResponse* resp, const QByteArray& body) {
    std::stringstream ss;
    ss << body.data();
    nw::JsonReader jr(ss);
    jr.describeValueArray("paths", -1);
    QStringList paths;
    NwUtils::describeValueArray(jr, "paths", paths);

    foreach (const QString& path, paths) {
        foreach (TvShow* show, this->tvShows) {
            if (show->episodeList().removeFileFromList(path)) {
                if(show->episodeList().hasNoFiles()) {
                    // TODO maybe also remove the directory and it's wallpapers from file system?
                    // right now this will only take it out of the library.json, but keep the $name directory
                    this->tvShows.removeOne(show); // Memory leak, TODO have manged pointers
                }
                break;
            }
        }
    }
    Server::simpleWrite(resp, 200, "removed" "text/plain");
}

TvShow& Library::tvShow(const QString name, bool setQParent) {
    TvShow* show = existingTvShow(name);
    if (show) {
        return *show;
    }
    show = new TvShow(name, setQParent ? this : NULL);
    this->tvShows.push_back(show);
    emit showAdded(show);
    connect(&show->episodeList(), SIGNAL(beforeWatchCountChanged(int,int)), this, SIGNAL(beforeWatchCountChanged(int,int)));
    return *show;
}

// TODO FIXME not actually const, since it returns a pointer to internal state,
// but c++ is a fucking piece of shit and I don't see how to do it without code duplication
TvShow* Library::existingTvShow(const QString name) const {
    foreach (TvShow* show, tvShows) {
        if (show->matchesNameOrSynonym(name)) {
            return show;
        }
    }
    return NULL;
}

const LibraryFilter& Library::filter() const {
    return mFilter;
}

void Library::importTvShowEpisode(QString episodePath) {
    const VideoFile* movieFile = new VideoFile(episodePath);
    if (!movieFile->showName.isEmpty()) {
        TvShow& show = this->tvShow(movieFile->showName);
        show.importVideoFile(movieFile); // takes ownage
    } else {
        qDebug() << "could not import (no show name parsed):" << movieFile->showName;
        delete movieFile;
    }
}

/*
void Library::xbmcLinkExport(QDir outputDir) {
    if (!outputDir.exists()) {
        outputDir.mkpath(".");
    }

    for (QList<TvShow*>::iterator it = tvShows.begin(); it != tvShows.end(); ++it) {
        (*it)->exportXbmcLinks((*it)->directory(outputDir));
    }
}
*/

void Library::fetchMetaData() {
    foreach (TvShow* show, tvShows) {
        onlineSync.addShowToFetch(show);
        onlineSync.addShowToUpdate(show);
    }
}

void Library::startWallpaperDownloaders() {
    if (getWallpaperDownloadRunning()) {
        foreach (WallpaperDownload::FetchThread* ft, runningWallpaperDownloaders) { 
            if (ft->isRunning()) {
                ft->append(filter().all());
            }
        }
        return;
    }
    for (int i=0; i < wallpaperDownloaders.size(); ++i) {
        WallpaperDownload::Client* downloader = wallpaperDownloaders[i];
        WallpaperDownload::FetchThread* ft = new WallpaperDownload::FetchThread(*downloader, filter().all(), directory, this);
        //connect(this, SIGNAL(destroyed()), ft, SLOT(terminate()));
        connect(ft, SIGNAL(finished()), this, SLOT(wallpaperDownloaderFinished()));
        connect(ft, SIGNAL(finished()), ft, SLOT(deleteLater()));
        runningWallpaperDownloaders.push_back(ft);
        ft->start(QThread::LowPriority);
    }
}

void Library::startSearch() {
    if (didInit) {
        startSearch(searchDirectories);
    }
}

void Library::startSearch(const QList<SearchDirectory> dirs) {
    if (this->searchThread) {
        if (this->searchThread->isFinished()) {
            QThread* t = this->searchThread;
            this->searchThread = NULL;
            delete t;
        } else {
            return;
        }
    }
    DirectoryScanner* scanner = new DirectoryScanner();
    scanner->addScanner(new TvShowScanner(*this));
    this->searchThread = new DirectoryScannerThread(scanner, dirs, this);
    connect(searchThread, SIGNAL(done()), this, SIGNAL(searchFinished()));
    connect(searchThread, SIGNAL(machingFile(QString)), this, SLOT(importTvShowEpisode(QString)));
    connect(searchThread, SIGNAL(done()), this, SLOT(startWallpaperDownloaders()));
    connect(searchThread, SIGNAL(done()), this, SLOT(fetchMetaData()));
    this->searchThread->start(QThread::HighPriority);
}

Library::searchStatus Library::getSearchStatus() const {
    if (this->searchThread) {
        return this->searchThread->isRunning() ? inProgress : done;
    }
    return notStarted;
}

bool Library::getWallpaperDownloadRunning() const {
    return !runningWallpaperDownloaders.empty();
}

const QList<SearchDirectory>& Library::getSearchDirectories() const {
    return searchDirectories;
}

bool Library::addSearchDirectory(SearchDirectory dir) {
    if (getSearchDirectory(dir.dir.absolutePath()) == NULL) {
        searchDirectories.append(dir);
        if (fileSystemWatcher) {
            fileSystemWatcher->addPath(dir.dir.absolutePath());
            qDebug() << fileSystemWatcher->directories();
        }
        return true;
    }
    return false;
}

void Library::addWallpaperDownloader(WallpaperDownload::Client* client) {
    wallpaperDownloaders.push_back(client);
    client->setParent(this);
    connect(client, SIGNAL(wallpaperDownloaded(QString)), this, SIGNAL(wallpaperDownloaded(QString)));
}

SearchDirectory *Library::getSearchDirectory(const QString path) {
    for (int i=0; i < searchDirectories.length(); ++i) {
        if (searchDirectories.at(i).dir.absolutePath() == QDir(path).absolutePath()) {
            return &searchDirectories[i];
        }
    }
    return NULL;
}

bool Library::removeSearchDirectory(QString path) {
    for (int i=0; i < searchDirectories.length(); ++i) {
        if (searchDirectories.at(i).dir.absolutePath() == QDir(path).absolutePath()) {
            searchDirectories.removeAt(i);
            return true;
        }
    }
    return false;
}

void Library::generateFrenchises() {
    /*
    foreach (TvShow* show, tvShows) {
        show->syncRelations(*this);
    }
    foreach (const TvShow* show, tvShows) {
        addToFrenchise(show);
    }
    foreach (Franchise* franchise, franchises) {
        franchise->generateName();
    }
    */
}

void Library::onInitDone() {
    didInit = true;
    this->startSearch();
}

void Library::fileChangedInSearchDirectory(QString path) {
    SearchDirectory* sd = getSearchDirectory(path);
    if (sd) {
        startSearch(QList<SearchDirectory>() << SearchDirectory(sd->dir));
    }
}

void Library::onVideoPlaybackEndedNormally(TvShow* show) {
    if (show) {
        this->onlineSync.addShowToUpdate(show);
    }
}

void Library::addToFrenchise(const TvShow* show) {
    bool added = false;
    foreach (Franchise* f, franchises) {
        if (f->hasRelationTo(show)) {
            f->addTvShow(show);
            added = true;
            break;
        }
    }
    if (!added) {
        Franchise* newFranchise = new Franchise(this);
        newFranchise->addTvShow(show);
        franchises.push_back(newFranchise);
    }
}

void Library::fetchingFinished() {
    qDebug() << "finished mal fetching, writing things now";
    generateFrenchises();
    this->write();
    qDebug() << "writing done!";
}

void Library::wallpaperDownloaderFinished() {
    runningWallpaperDownloaders.removeOne(dynamic_cast<WallpaperDownload::FetchThread*>(sender()));
    if (!getWallpaperDownloadRunning()) {
        emit wallpaperDownloadersFinished();
    }
}

bool Library::readAll(bool setQParent) {
    QString filepath = directory.absoluteFilePath("library.json");
    if (!QFile(filepath).exists()) {
        return false;
    }

    nw::JsonReader jr(filepath.toStdString());
    jr.describeArray("searchDirectories", "directory", searchDirectories.length());
    for (int i=0; jr.enterNextElement(i); ++i) {
        QString dirpath;
        bool enabled = false;
        NwUtils::describe(jr, "path", dirpath);
        NwUtils::describe(jr, "enabled", enabled);
        addSearchDirectory(SearchDirectory(dirpath, enabled));
    }

    jr.describeValueArray("tvShows", tvShows.length());
    for (int i=0; jr.enterNextElement(i); ++i) {
        std::string name;
        jr.describeValue(name);
        TvShow& show = tvShow(QString(name.data()), setQParent);

        QDir showDir = show.directory(directory);
        if (!showDir.exists()) {
            qDebug() << "show does not have a directory: " << show.name();
            break;
        }
        show.read(showDir);
    }
    jr.close();
    generateFrenchises();
    return true;
}

void Library::write() {
    if (didInit) {
        this->writeIndex();
        for (TvShow* show : tvShows) {
            this->writeShow(show);
        }
    }
}

bool Library::writeIndex() {
    if (!directory.exists()) {
        return false;
    }

    nw::JsonWriter jw(directory.absoluteFilePath("library.json").toStdString());
    jw.describeArray("searchDirectories", "directory", searchDirectories.length());
    for (int i=0; jw.enterNextElement(i); ++i) {
        QString dirpath = searchDirectories.at(i).dir.path();
        NwUtils::describe(jw, "path", dirpath);
        NwUtils::describe(jw, "enabled", searchDirectories[i].enabled);
    }
    jw.describeValueArray("tvShows", tvShows.length());
    for (int i=0; jw.enterNextElement(i); ++i) {
        TvShow* show = tvShows[i];
        std::string name = show->name().toStdString();
        jw.describeValue(name);
    }
    jw.close();
    return jw.getErrorMessage().empty();
}

bool Library::writeShow(TvShow* show) {
    QDir showDir = show->directory(directory);
    if (!showDir.exists() && !directory.mkdir(showDir.dirName())) {
        qDebug() << "error can not write Library item in: " << showDir.absolutePath();
        return false;
    }
    nw::JsonWriter jw(showDir.absoluteFilePath("tvShow.json").toStdString());
    show->write(jw);
    jw.close();
    return jw.getErrorMessage().empty();
}

MetaDataParser *Library::getMetaDataParser() const {
    return metaDataParser;
}

void Library::setMetaDataParser(MetaDataParser *value) {
    metaDataParser = value;
}

QDir Library::getDirectory() const {
    return directory;
}