File: ktfeed.cpp

package info (click to toggle)
ktorrent 25.04.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 25,104 kB
  • sloc: cpp: 40,482; xml: 1,163; python: 182; sh: 10; makefile: 5
file content (480 lines) | stat: -rw-r--r-- 13,390 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
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
/*
    SPDX-FileCopyrightText: 2008 Joris Guisson <joris.guisson@gmail.com>
    SPDX-FileCopyrightText: 2008 Ivan Vasic <ivasic@gmail.com>
    SPDX-License-Identifier: GPL-2.0-or-later
*/

#include <QDomElement>
#include <QFile>

#include <KLocalizedString>
#include <Syndication/Enclosure>

#include "feedretriever.h"
#include "filter.h"
#include "filterlist.h"
#include "ktfeed.h"
#include <bcodec/bdecoder.h>
#include <bcodec/bencoder.h>
#include <bcodec/bnode.h>
#include <util/file.h>
#include <util/fileops.h>
#include <util/log.h>

using namespace bt;

namespace kt
{
const int DEFAULT_REFRESH_RATE = 60;

Feed::Feed(const QString &dir)
    : dir(dir)
    , status(UNLOADED)
    , refresh_rate(DEFAULT_REFRESH_RATE)
{
    connect(&update_timer, &QTimer::timeout, this, &Feed::refresh);
}

Feed::Feed(const QString &feed_url, const QString &dir)
    : dir(dir)
    , status(UNLOADED)
    , refresh_rate(DEFAULT_REFRESH_RATE)
{
    parseUrl(feed_url);
    connect(&update_timer, &QTimer::timeout, this, &Feed::refresh);
    refresh();
    save();
}

Feed::Feed(const QString &feed_url, Syndication::FeedPtr feed, const QString &dir)
    : feed(feed)
    , dir(dir)
    , status(OK)
    , refresh_rate(DEFAULT_REFRESH_RATE)
{
    parseUrl(feed_url);
    connect(&update_timer, &QTimer::timeout, this, &Feed::refresh);
    update_timer.start(refresh_rate * 60 * 1000);
}

Feed::~Feed()
{
}

void Feed::parseUrl(const QString &feed_url)
{
    QStringList sl = feed_url.split(QStringLiteral(":COOKIE:"));
    if (sl.size() == 2) {
        url = QUrl(sl.first());
        cookie = sl.last();
    } else
        url = QUrl(feed_url);
}

void Feed::save()
{
    QString file = dir + QStringLiteral("info");
    File fptr;
    if (!fptr.open(file, QStringLiteral("wt"))) {
        Out(SYS_SYN | LOG_DEBUG) << "Failed to open " << file << " : " << fptr.errorString() << endl;
        return;
    }

    BEncoder enc(&fptr);
    enc.beginDict();
    enc.write(QByteArrayLiteral("url"));
    enc.write(url.toEncoded());
    if (!cookie.isEmpty()) {
        enc.write(QByteArrayLiteral("cookie"));
        enc.write(cookie.toUtf8());
    }
    enc.write(QByteArrayLiteral("filters"));
    enc.beginList();
    for (Filter *f : std::as_const(filters))
        enc.write(f->filterID().toUtf8());
    enc.end();
    enc.write(QByteArrayLiteral("loaded"));
    enc.beginList();
    for (const QString &id : std::as_const(loaded))
        enc.write(id.toUtf8());
    enc.end();
    enc.write(QByteArrayLiteral("downloaded_se_items"));
    enc.beginList();
    QMap<Filter *, QList<SeasonEpisodeItem>>::iterator i = downloaded_se_items.begin();
    while (i != downloaded_se_items.end()) {
        Filter *f = i.key();
        const QList<SeasonEpisodeItem> &se = i.value();
        enc.write(f->filterID().toUtf8());
        enc.beginList();
        for (const SeasonEpisodeItem &item : se) {
            enc.write((bt::Uint32)item.season);
            enc.write((bt::Uint32)item.episode);
        }
        enc.end();
        i++;
    }
    enc.end();
    if (!custom_name.isEmpty())
        enc.write(QByteArrayLiteral("custom_name"), custom_name.toUtf8());
    enc.write(QByteArrayLiteral("refresh_rate"), refresh_rate);
    enc.end();
}

void Feed::load(FilterList *filter_list)
{
    QString file = dir + QStringLiteral("info");
    QFile fptr(file);
    if (!fptr.open(QIODevice::ReadOnly)) {
        Out(SYS_SYN | LOG_DEBUG) << "Failed to open " << file << " : " << fptr.errorString() << endl;
        return;
    }

    QByteArray data = fptr.readAll();
    BDecoder dec(data, false);
    BNode *n = dec.decode();
    if (!n || n->getType() != BNode::DICT) {
        delete n;
        return;
    }

    BDictNode *dict = (BDictNode *)n;

    try {
        url = QUrl(dict->getString("url"));
        cookie = dict->getValue("cookie") ? dict->getString("cookie") : QString();
        custom_name = dict->getValue("custom_name") ? dict->getString("custom_name") : QString();
        refresh_rate = dict->getValue("refresh_rate") ? dict->getInt("refresh_rate") : DEFAULT_REFRESH_RATE;

        BListNode *fl = dict->getList("filters");
        if (fl) {
            for (Uint32 i = 0; i < fl->getNumChildren(); i++) {
                Filter *f = filter_list->filterByID(fl->getString(i));
                if (f)
                    filters.append(f);
            }
        }

        BListNode *ll = dict->getList("loaded");
        if (ll) {
            for (Uint32 i = 0; i < ll->getNumChildren(); i++) {
                loaded.insert(ll->getString(i));
            }
        }

        BListNode *se_list = dict->getList("downloaded_se_items");
        if (se_list) {
            for (Uint32 i = 0; i < se_list->getNumChildren(); i += 2) {
                BListNode *se = se_list->getList(i + 1);
                if (!se)
                    continue;

                Filter *f = filter_list->filterByID(se_list->getString(i));
                if (!f)
                    continue;

                QList<SeasonEpisodeItem> &sel = downloaded_se_items[f];
                for (Uint32 j = 0; j < se->getNumChildren(); j += 2) {
                    SeasonEpisodeItem item;
                    item.episode = se->getInt(j);
                    item.season = se->getInt(j + 1);
                    sel.append(item);
                }
            }
        }
    } catch (...) {
        delete n;
        throw;
    }

    Out(SYS_SYN | LOG_DEBUG) << "Loaded feed from " << file << " : " << endl;
    status = OK;
    delete n;

    if (bt::Exists(dir + QStringLiteral("feed.xml")))
        loadFromDisk();
    else
        refresh();
}

void Feed::loadingComplete(Syndication::Loader *loader, Syndication::FeedPtr feed, Syndication::ErrorCode status)
{
    Q_UNUSED(loader);
    if (status != Syndication::Success) {
        update_error = SyndicationErrorString(status);
        Out(SYS_SYN | LOG_NOTICE) << "Failed to load feed " << url.toDisplayString() << ": " << update_error << endl;
        this->status = FAILED_TO_DOWNLOAD;
        update_timer.start(refresh_rate * 60 * 1000);
        Q_EMIT updated();
        return;
    }

    Out(SYS_SYN | LOG_NOTICE) << "Loaded feed " << url.toDisplayString() << endl;
    this->feed = feed;
    update_timer.start(refresh_rate * 60 * 1000);
    this->status = OK;

    // refresh cache of feed_items_ids
    feed_items_id.clear();
    const QList<Syndication::ItemPtr> feedItems = feed->items();
    for (const Syndication::ItemPtr &item : feedItems)
        feed_items_id.insert(item->id());

    checkLoaded();
    runFilters();
    Q_EMIT updated();
}

void Feed::refresh()
{
    status = DOWNLOADING;
    update_error.clear();
    update_timer.stop();
    Syndication::Loader *loader = Syndication::Loader::create(this, SLOT(loadingComplete(Syndication::Loader *, Syndication::FeedPtr, Syndication::ErrorCode)));
    FeedRetriever *retr = new FeedRetriever(dir + QStringLiteral("feed.xml"));
    if (!cookie.isEmpty())
        retr->setAuthenticationCookie(cookie);
    loader->loadFrom(url, retr);
    Q_EMIT updated();
}

void Feed::loadingFromDiskComplete(Syndication::Loader *loader, Syndication::FeedPtr feed, Syndication::ErrorCode status)
{
    loadingComplete(loader, feed, status);
    refresh();
}

void Feed::loadFromDisk()
{
    status = DOWNLOADING;
    update_timer.stop();
    Syndication::Loader *loader =
        Syndication::Loader::create(this, SLOT(loadingFromDiskComplete(Syndication::Loader *, Syndication::FeedPtr, Syndication::ErrorCode)));
    loader->loadFrom(QUrl::fromLocalFile(dir + QStringLiteral("feed.xml")), new FeedRetriever());
    Q_EMIT updated();
}

QString Feed::title() const
{
    if (feed)
        return feed->title();
    else
        return url.toDisplayString();
}

QString Feed::newFeedDir(const QString &base)
{
    int cnt = 0;
    QString dir = QStringLiteral("%1feed%2/").arg(base).arg(cnt);
    while (bt::Exists(dir)) {
        cnt++;
        dir = QStringLiteral("%1feed%2/").arg(base).arg(cnt);
    }

    bt::MakeDir(dir);
    return dir;
}

void Feed::addFilter(Filter *f)
{
    filters.append(f);
    Q_EMIT updated();
}

void Feed::removeFilter(Filter *f)
{
    filters.removeAll(f);
    downloaded_se_items.remove(f);
    Q_EMIT updated();
}

bool Feed::needToDownload(Syndication::ItemPtr item, Filter *filter)
{
    bool m = filter->match(item);
    if ((m && filter->downloadMatching()) || (!m && filter->downloadNonMatching())) {
        if (filter->useSeasonAndEpisodeMatching() && filter->noDuplicateSeasonAndEpisodeMatches()) {
            int s = 0;
            int e = 0;
            Filter::getSeasonAndEpisode(item->title(), s, e);
            if (!downloaded_se_items.contains(filter)) {
                downloaded_se_items[filter].append(SeasonEpisodeItem(s, e));
            } else {
                // If we have already downloaded this season and episode, return
                QList<SeasonEpisodeItem> &ses = downloaded_se_items[filter];
                SeasonEpisodeItem se(s, e);
                if (ses.contains(se))
                    return false;

                ses.append(se);
            }
        }

        return true;
    }

    return false;
}

void Feed::runFilters()
{
    if (!feed)
        return;

    Out(SYS_SYN | LOG_NOTICE) << "Running filters on " << feed->title() << endl;
    for (Filter *f : std::as_const(filters)) {
        f->startMatching();
        const QList<Syndication::ItemPtr> items = feed->items();
        for (const Syndication::ItemPtr &item : items) {
            // Skip already loaded items
            if (loaded.contains(item->id()))
                continue;

            if (needToDownload(item, f)) {
                Out(SYS_SYN | LOG_NOTICE) << "Downloading item " << item->title() << " (filter: " << f->filterName() << ")" << endl;
                downloadItem(item, f->group(), f->downloadLocation(), f->moveOnCompletionLocation(), f->openSilently());
            }
        }
    }
}

QString TorrentUrlFromItem(Syndication::ItemPtr item);

void Feed::downloadItem(Syndication::ItemPtr item, const QString &group, const QString &location, const QString &move_on_completion, bool silently)
{
    loaded.insert(item->id());
    QString url = TorrentUrlFromItem(item);
    if (!url.isEmpty())
        Q_EMIT downloadLink(QUrl(url), group, location, move_on_completion, silently);
    else
        Q_EMIT downloadLink(QUrl(item->link()), group, location, move_on_completion, silently);
    save();
}

void Feed::clearFilters()
{
    filters.clear();
    Q_EMIT updated();
}

void Feed::checkLoaded()
{
    // remove all id's which are in loaded but no longer in
    // the item list
    bool need_to_save = false;

    QList<QString> itemsToRemove;
    for (const QString &loadedItem : std::as_const(loaded)) {
        if (!feed_items_id.contains(loadedItem)) {
            itemsToRemove.push_front(loadedItem);
            need_to_save = true;
        }
    }

    for (const QString &itemToRemove : std::as_const(itemsToRemove))
        loaded.remove(itemToRemove);

    if (need_to_save)
        save();
}

bool Feed::downloaded(Syndication::ItemPtr item) const
{
    return loaded.contains(item->id());
}

QString Feed::displayName() const
{
    if (!custom_name.isEmpty())
        return custom_name;
    else if (ok())
        return feed->title();
    else
        return url.toDisplayString();
}

void Feed::setDisplayName(const QString &dname)
{
    if (custom_name != dname) {
        custom_name = dname;
        save();
        Q_EMIT feedRenamed(this);
    }
}

void Feed::setRefreshRate(bt::Uint32 r)
{
    if (r > 0) {
        refresh_rate = r;
        save();
        update_timer.setInterval(refresh_rate * 60 * 1000);
    }
}

//////////////////////////////////
SeasonEpisodeItem::SeasonEpisodeItem()
    : season(-1)
    , episode(-1)
{
}

SeasonEpisodeItem::SeasonEpisodeItem(int s, int e)
    : season(s)
    , episode(e)
{
}

SeasonEpisodeItem::SeasonEpisodeItem(const SeasonEpisodeItem &item)
    : season(item.season)
    , episode(item.episode)
{
}

bool SeasonEpisodeItem::operator==(const SeasonEpisodeItem &item) const
{
    return season == item.season && episode == item.episode;
}

SeasonEpisodeItem &SeasonEpisodeItem::operator=(const SeasonEpisodeItem &item)
{
    season = item.season;
    episode = item.episode;
    return *this;
}

/////////////////////////////////////
QString SyndicationErrorString(Syndication::ErrorCode err)
{
    switch (err) {
    case Syndication::Aborted:
        return i18n("Aborted");
    case Syndication::Timeout:
        return i18n("Timeout when downloading feed");
    case Syndication::UnknownHost:
        return i18n("Unknown hostname");
    case Syndication::FileNotFound:
        return i18n("File not found");
    case Syndication::OtherRetrieverError:
        return i18n("Unknown retriever error");
    case Syndication::InvalidXml:
    case Syndication::XmlNotAccepted:
    case Syndication::InvalidFormat:
        return i18n("Invalid feed data");
    case Syndication::Success:
        return i18n("Success");
    default:
        return QString();
    }
}

QString Feed::filterNamesString() const
{
    if (filters.empty())
        return i18n("None");
    QStringList names;
    for (Filter *f : std::as_const(filters))
        names << f->filterName();
    return names.join(QStringLiteral(", "));
}

}

#include "moc_ktfeed.cpp"