Line data Source code
1 : #include "BatchNewsParser.h"
2 : #include "NewsParser.h"
3 : #include <QDebug>
4 :
5 56 : BatchNewsParser::BatchNewsParser(QObject *parent)
6 56 : : FangObject{parent}
7 56 : {}
8 :
9 13 : void BatchNewsParser::parse(const QList<QUrl> &urls)
10 : {
11 : // Clear any existing parsers and results, in case this object is being reused. This will
12 : // also remove the feed data owned by these objects.
13 14 : for (ParserInterface* parser : parsers.values()) {
14 1 : delete parser;
15 13 : }
16 13 : parsers.clear();
17 13 : results.clear();
18 :
19 : // Clear feed map as the pointers are no longer valid (they were deleted above.)
20 13 : feeds.clear();
21 :
22 : // Set up parsers.
23 33 : for (const QUrl& url : urls) {
24 : // Skip this URL if we've already seen it.
25 20 : if (parsers.keys().contains(url)) {
26 2 : continue;
27 : }
28 :
29 18 : ParserInterface *parser = createParser();
30 18 : connect(parser, &ParserInterface::done, this, &BatchNewsParser::onParserDone);
31 18 : parser->parse(url);
32 18 : parsers[url] = parser;
33 : }
34 13 : }
35 :
36 0 : ParserInterface* BatchNewsParser::createParser()
37 : {
38 0 : return new NewsParser(this);
39 : }
40 :
41 18 : void BatchNewsParser::onParserDone()
42 : {
43 18 : ParserInterface* parser = qobject_cast<ParserInterface*>(sender());
44 18 : if (!parser) {
45 0 : qWarning() << "BatchNewsParser: onParserDone called but sender is not a ParserInterface";
46 0 : return;
47 : }
48 :
49 18 : QUrl url = parser->getURL();
50 18 : if (!parsers.keys().contains(url)) {
51 0 : qWarning() << "BatchNewsParser: URL returned but not found:" << url;
52 0 : return;
53 : }
54 :
55 : // Store result in our map.
56 18 : results[url] = parser->getResult();
57 :
58 : // Store feed if parser succeeded.
59 18 : if (parser->getResult() == ParserInterface::OK) {
60 12 : RawFeed* feed = parser->getFeed();
61 12 : if (feed) {
62 : // Store reference to the feed (owned by the parser)
63 12 : feeds[url] = feed;
64 : }
65 : }
66 :
67 : // Check if we're done.
68 56 : for (ParserInterface* p : parsers.values()) {
69 38 : if (p->getResult() == ParserInterface::IN_PROGRESS) {
70 : // Not done yet!
71 0 : return;
72 : }
73 18 : }
74 :
75 : // We're done!
76 18 : emit ready();
77 18 : }
78 :
79 15 : RawFeed* BatchNewsParser::getFeed(const QUrl& url)
80 : {
81 15 : return feeds.value(url, nullptr);
82 : }
|