File: rss.cpp

package info (click to toggle)
newsbeuter 2.9-5+deb9u2
  • links: PTS
  • area: main
  • in suites: stretch
  • size: 4,692 kB
  • ctags: 3,693
  • sloc: cpp: 18,663; ruby: 1,797; xml: 350; sh: 199; makefile: 171; perl: 101
file content (628 lines) | stat: -rw-r--r-- 17,333 bytes parent folder | download | duplicates (2)
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
#include <rss.h>
#include <config.h>
#include <cache.h>
#include <tagsouppullparser.h>
#include <utils.h>
#include <logger.h>
#include <exceptions.h>
#include <sstream>
#include <iostream>
#include <configcontainer.h>
#include <cstring>
#include <algorithm>
#include <curl/curl.h>
#include <sys/utsname.h>
#include <htmlrenderer.h>

#include <langinfo.h>

#include <cerrno>

#include <functional>

namespace newsbeuter {

rss_item::rss_item(cache * c) : pubDate_(0), unread_(true), ch(c), enqueued_(false), deleted_(0), idx(0), override_unread_(false), size_(0) {
	// LOG(LOG_CRITICAL, "new rss_item");
}

rss_item::~rss_item() {
	// LOG(LOG_CRITICAL, "delete rss_item");
}

rss_feed::rss_feed(cache * c) : ch(c), empty(true), is_rtl_(false), idx(0), status_(SUCCESS) {
	// LOG(LOG_CRITICAL, "new rss_feed");
}

rss_feed::~rss_feed() {
	// LOG(LOG_CRITICAL, "delete rss_feed");
	clear_items();
}

// rss_item setters

void rss_item::set_title(const std::string& t) {
	title_ = t;
	utils::trim(title_);
}


void rss_item::set_link(const std::string& l) {
	link_ = l;
	utils::trim(link_);
}

void rss_item::set_author(const std::string& a) {
	author_ = a;
}

void rss_item::set_description(const std::string& d) {
	description_ = d;
}

void rss_item::set_size(unsigned int size) {
	size_ = size;
}

std::string rss_item::length() const {
	std::string::size_type l(size_);
	if (!l)
		return "";
	if (l < 1000)
		return utils::strprintf("%u ", l);
	if (l < 1024*1000)
		return utils::strprintf("%.1fK", l/1024.0);

	return utils::strprintf("%.1fM", l/1024.0/1024.0);
}

void rss_item::set_pubDate(time_t t) {
	pubDate_ = t;
}

void rss_item::set_guid(const std::string& g) {
	guid_ = g;
}

void rss_item::set_unread_nowrite(bool u) {
	unread_ = u;
}

void rss_item::set_unread_nowrite_notify(bool u, bool notify) {
	unread_ = u;
	std::shared_ptr<rss_feed> feedptr = feedptr_.lock();
	if (feedptr && notify) {
		feedptr->get_item_by_guid(guid_)->set_unread_nowrite(unread_); // notify parent feed
	}
}

void rss_item::set_unread(bool u) {
	if (unread_ != u) {
		bool old_u = unread_;
		unread_ = u;
		std::shared_ptr<rss_feed> feedptr = feedptr_.lock();
		if (feedptr)
			feedptr->get_item_by_guid(guid_)->set_unread_nowrite(unread_); // notify parent feed
		try {
			if (ch) ch->update_rssitem_unread_and_enqueued(this, feedurl_);
		} catch (const dbexception& e) {
			// if the update failed, restore the old unread flag and rethrow the exception
			unread_ = old_u;
			throw;
		}
	}
}

std::string rss_item::pubDate() const {
	char text[1024];
	strftime(text,sizeof(text), _("%a, %d %b %Y %T %z"), localtime(&pubDate_));
	return std::string(text);
}

unsigned int rss_feed::unread_item_count() {
	std::lock_guard<std::mutex> lock(item_mutex);
	unsigned int count = 0;
	for (auto item : items_) {
		if (item->unread())
			++count;
	}
	return count;
}


bool rss_feed::matches_tag(const std::string& tag) {
	for (auto t : tags_) {
		if (tag == t)
			return true;
	}
	return false;
}

std::string rss_feed::get_firsttag() {
	if (tags_.size() == 0)
		return "";
	return tags_[0];
}

std::string rss_feed::get_tags() {
	std::string tags;
	for (auto t : tags_) {
		if (t.substr(0,1) != "~" && t.substr(0,1) != "!") {
			tags.append(t);
			tags.append(" ");
		}
	}
	return tags;
}

void rss_feed::set_tags(const std::vector<std::string>& tags) {
	tags_.clear();
	for (auto tag : tags) {
		tags_.push_back(tag);
	}
}

void rss_item::set_enclosure_url(const std::string& url) {
	enclosure_url_ = url;
}

void rss_item::set_enclosure_type(const std::string& type) {
	enclosure_type_ = type;
}

std::string rss_item::title() const {
	std::string retval;
	if (title_.length()>0)
		retval = utils::convert_text(title_, nl_langinfo(CODESET), "utf-8");
	return retval;
}

std::string rss_item::author() const {
	return utils::convert_text(author_, nl_langinfo(CODESET), "utf-8");
}

std::string rss_item::description() const {
	return utils::convert_text(description_, nl_langinfo(CODESET), "utf-8");
}

std::string rss_feed::title() const {
	bool found_title = false;
	std::string alt_title;
	for (auto tag : tags_) {
		if (tag.substr(0,1) == "~" || tag.substr(0,1) == "!") {
			found_title = true;
			alt_title = tag.substr(1, tag.length()-1);
			break;
		}
	}
	return found_title ? alt_title : utils::convert_text(title_, nl_langinfo(CODESET), "utf-8");
}

std::string rss_feed::description() const {
	return utils::convert_text(description_, nl_langinfo(CODESET), "utf-8");
}

bool rss_feed::hidden() const {
	for (auto tag : tags_) {
		if (tag.substr(0,1) == "!") {
			return true;
		}
	}
	return false;
}

std::shared_ptr<rss_item> rss_feed::get_item_by_guid(const std::string& guid) {
	std::lock_guard<std::mutex> lock(item_mutex);
	return get_item_by_guid_unlocked(guid);
}

std::shared_ptr<rss_item> rss_feed::get_item_by_guid_unlocked(const std::string& guid) {
	auto it = items_guid_map.find(guid);
	if (it != items_guid_map.end()) {
		return it->second;
	}
	LOG(LOG_DEBUG, "rss_feed::get_item_by_guid_unlocked: hit dummy item!");
	LOG(LOG_DEBUG, "rss_feed::get_item_by_guid_unlocked: items_guid_map.size = %d", items_guid_map.size());
	// abort();
	return std::shared_ptr<rss_item>(new rss_item(ch)); // should never happen!
}

bool rss_item::has_attribute(const std::string& attribname) {
	// LOG(LOG_DEBUG, "rss_item::has_attribute(%s) called", attribname.c_str());
	if (attribname == "title" ||
	        attribname == "link" ||
	        attribname == "author" ||
	        attribname == "content" ||
	        attribname == "date"  ||
	        attribname == "guid" ||
	        attribname == "unread" ||
	        attribname == "enclosure_url" ||
	        attribname == "enclosure_type" ||
	        attribname == "flags" ||
	        attribname == "age" ||
	        attribname == "articleindex")
		return true;

	// if we have a feed, then forward the request
	std::shared_ptr<rss_feed> feedptr = feedptr_.lock();
	if (feedptr)
		return feedptr->rss_feed::has_attribute(attribname);

	return false;
}

std::string rss_item::get_attribute(const std::string& attribname) {
	if (attribname == "title")
		return title();
	else if (attribname == "link")
		return link();
	else if (attribname == "author")
		return author();
	else if (attribname == "content")
		return description();
	else if (attribname == "date")
		return pubDate();
	else if (attribname == "guid")
		return guid();
	else if (attribname == "unread")
		return unread_ ? "yes" : "no";
	else if (attribname == "enclosure_url")
		return enclosure_url();
	else if (attribname == "enclosure_type")
		return enclosure_type();
	else if (attribname == "flags")
		return flags();
	else if (attribname == "age")
		return utils::to_string<unsigned int>((time(NULL) - pubDate_timestamp()) / 86400);
	else if (attribname == "articleindex")
		return utils::to_string<unsigned int>(idx);

	// if we have a feed, then forward the request
	std::shared_ptr<rss_feed> feedptr = feedptr_.lock();
	if (feedptr)
		return feedptr->rss_feed::get_attribute(attribname);

	return "";
}

void rss_item::update_flags() {
	if (ch) {
		ch->update_rssitem_flags(this);
	}
}

void rss_item::set_flags(const std::string& ff) {
	oldflags_ = flags_;
	flags_ = ff;
	sort_flags();
}

void rss_item::sort_flags() {
	std::sort(flags_.begin(), flags_.end());

	for (auto it=flags_.begin(); flags_.size() > 0 && it!=flags_.end(); ++it) {
		if (!isalpha(*it)) {
			flags_.erase(it);
			it = flags_.begin();
		}
	}

	for (unsigned int i=0; i<flags_.size(); ++i) {
		if (i < (flags_.size()-1)) {
			if (flags_[i] == flags_[i+1]) {
				flags_.erase(i+1,i+1);
				--i;
			}
		}
	}
}

bool rss_feed::has_attribute(const std::string& attribname) {
	if (attribname == "feedtitle" ||
	        attribname == "description" ||
	        attribname == "feedlink" ||
	        attribname == "feeddate" ||
	        attribname == "rssurl" ||
	        attribname == "unread_count" ||
	        attribname == "total_count" ||
	        attribname == "tags" ||
	        attribname == "feedindex")
		return true;
	return false;
}

std::string rss_feed::get_attribute(const std::string& attribname) {
	if (attribname == "feedtitle")
		return title();
	else if (attribname == "description")
		return description();
	else if (attribname == "feedlink")
		return title();
	else if (attribname == "feeddate")
		return pubDate();
	else if (attribname == "rssurl")
		return rssurl();
	else if (attribname == "unread_count") {
		return utils::to_string<unsigned int>(unread_item_count());
	} else if (attribname == "total_count") {
		return utils::to_string<unsigned int>(items_.size());
	} else if (attribname == "tags") {
		return get_tags();
	} else if (attribname == "feedindex") {
		return utils::to_string<unsigned int>(idx);
	}
	return "";
}

void rss_ignores::handle_action(const std::string& action, const std::vector<std::string>& params) {
	if (action == "ignore-article") {
		if (params.size() < 2)
			throw confighandlerexception(AHS_TOO_FEW_PARAMS);
		std::string ignore_rssurl = params[0];
		std::string ignore_expr = params[1];
		matcher m;
		if (!m.parse(ignore_expr))
			throw confighandlerexception(utils::strprintf(_("couldn't parse filter expression `%s': %s"), ignore_expr.c_str(), m.get_parse_error().c_str()));
		ignores.push_back(feedurl_expr_pair(ignore_rssurl, new matcher(ignore_expr)));
	} else if (action == "always-download") {
		for (auto param : params) {
			ignores_lastmodified.push_back(param);
		}
	} else if (action == "reset-unread-on-update") {
		for (auto param : params) {
			resetflag.push_back(param);
		}
	} else
		throw confighandlerexception(AHS_INVALID_COMMAND);
}

void rss_ignores::dump_config(std::vector<std::string>& config_output) {
	for (auto ign : ignores) {
		std::string configline = "ignore-article ";
		if (ign.first == "*")
			configline.append("*");
		else
			configline.append(utils::quote(ign.first));
		configline.append(" ");
		configline.append(utils::quote(ign.second->get_expression()));
		config_output.push_back(configline);
	}
	for (auto ign_lm : ignores_lastmodified) {
		config_output.push_back(utils::strprintf("always-download %s", utils::quote(ign_lm).c_str()));
	}
	for (auto rf : resetflag) {
		config_output.push_back(utils::strprintf("reset-unread-on-update %s", utils::quote(rf).c_str()));
	}
}

rss_ignores::~rss_ignores() {
	for (auto ign : ignores) {
		delete ign.second;
	}
}

bool rss_ignores::matches(rss_item* item) {
	for (auto ign : ignores) {
		LOG(LOG_DEBUG, "rss_ignores::matches: ign.first = `%s' item->feedurl = `%s'", ign.first.c_str(), item->feedurl().c_str());
		if (ign.first == "*" || item->feedurl() == ign.first) {
			if (ign.second->matches(item)) {
				LOG(LOG_DEBUG, "rss_ignores::matches: found match");
				return true;
			}
		}
	}
	return false;
}

bool rss_ignores::matches_lastmodified(const std::string& url) {
	for (auto ignore_url : ignores_lastmodified) {
		if (url == ignore_url)
			return true;
	}
	return false;
}

bool rss_ignores::matches_resetunread(const std::string& url) {
	for (auto rf : resetflag) {
		if (url == rf)
			return true;
	}
	return false;
}

void rss_feed::update_items(std::vector<std::shared_ptr<rss_feed>> feeds) {
	std::lock_guard<std::mutex> lock(item_mutex);
	if (query.length() == 0)
		return;

	LOG(LOG_DEBUG, "rss_feed::update_items: query = `%s'", query.c_str());


	struct timeval tv1, tv2, tvx;
	gettimeofday(&tv1, NULL);

	matcher m(query);

	items_.clear();
	items_guid_map.clear();

	for (auto feed : feeds) {
		if (feed->rssurl().substr(0,6) != "query:") { // don't fetch items from other query feeds!
			for (auto item : feed->items()) {
				if (m.matches(item.get())) {
					LOG(LOG_DEBUG, "rss_feed::update_items: matcher matches!");
					item->set_feedptr(feed);
					items_.push_back(item);
					items_guid_map[item->guid()] = item;
				}
			}
		}
	}

	gettimeofday(&tvx, NULL);

	std::sort(items_.begin(), items_.end());

	gettimeofday(&tv2, NULL);
	unsigned long diff = (((tv2.tv_sec - tv1.tv_sec) * 1000000) + tv2.tv_usec) - tv1.tv_usec;
	unsigned long diffx = (((tv2.tv_sec - tvx.tv_sec) * 1000000) + tv2.tv_usec) - tvx.tv_usec;
	LOG(LOG_DEBUG, "rss_feed::update_items matching took %lu.%06lu s", diff / 1000000, diff % 1000000);
	LOG(LOG_DEBUG, "rss_feed::update_items sorting took %lu.%06lu s", diffx / 1000000, diffx % 1000000);
}

void rss_feed::set_rssurl(const std::string& u) {
	rssurl_ = u;
	if (rssurl_.substr(0,6) == "query:") {
		/* Query string looks like this:
		 *
		 * "query:Title:unread = \"yes\" and age between 0:7" tag1 "tag two"
		 *
		 * At this point, we're only interested in the first part enclosed in
		 * the quotes. Thus, we first tokenize using space as delimiter... */
		std::vector<std::string> tokens = utils::tokenize_quoted(u, " ");
		// and then further split by colon, so as to extract title and query
		tokens = utils::tokenize_quoted(u, ":");

		if (tokens.size() < 3) {
			throw std::string(_("too few arguments"));
		}

		/* "Between" operator requires a range, which contains a colon. Since
		 * we've been tokenizing by colon, we might've inadertently split the
		 * query itself. Let's reconstruct it! */
		auto query = tokens[2];
		for (auto it = tokens.begin() + 3; it != tokens.end(); ++it)
		{
			query += ":";
			query += *it;
		}
		// Have to check if the result is a valid query, just in case
		matcher m;
		if (!m.parse(query)) {
			throw utils::strprintf(
			    _("`%s' is not a valid filter expression"), query.c_str());
		}

		LOG(LOG_DEBUG,
		    "rss_feed::set_rssurl: query name = `%s' expr = `%s'",
		    tokens[1].c_str(),
		    query.c_str());

		set_title(tokens[1]);
		set_query(query);
	}
}

void rss_feed::sort(const std::string& method) {
	std::lock_guard<std::mutex> lock(item_mutex);
	sort_unlocked(method);
}

void rss_feed::sort_unlocked(const std::string& method) {
	std::vector<std::string> methods = utils::tokenize(method,"-");
	bool reverse = false;

	if (!methods.empty() && methods[0] == "date") { // date is descending by default
		if (methods.size() > 1 && methods[1] == "asc") {
			reverse = true;
		}
	} else { // all other sort methods are ascending by default
		if (methods.size() > 1 && methods[1] == "desc") {
			reverse = true;
		}
	}

	if (!methods.empty()) {
		if (methods[0] == "title") {
			std::stable_sort(items_.begin(), items_.end(), [&](std::shared_ptr<rss_item> a, std::shared_ptr<rss_item> b) {
				return reverse ?  (strcasecmp(a->title().c_str(), b->title().c_str()) > 0) : (strcasecmp(a->title().c_str(), b->title().c_str()) < 0);
			});
		} else if (methods[0] == "flags") {
			std::stable_sort(items_.begin(), items_.end(), [&](std::shared_ptr<rss_item> a, std::shared_ptr<rss_item> b) {
				return reverse ?  (strcmp(a->flags().c_str(), b->flags().c_str()) > 0) : (strcmp(a->flags().c_str(), b->flags().c_str()) < 0);
			});
		} else if (methods[0] == "author") {
			std::stable_sort(items_.begin(), items_.end(), [&](std::shared_ptr<rss_item> a, std::shared_ptr<rss_item> b) {
				return reverse ?  (strcmp(a->author().c_str(), b->author().c_str()) > 0) : (strcmp(a->author().c_str(), b->author().c_str()) < 0);
			});
		} else if (methods[0] == "link") {
			std::stable_sort(items_.begin(), items_.end(), [&](std::shared_ptr<rss_item> a, std::shared_ptr<rss_item> b) {
				return reverse ?  (strcmp(a->link().c_str(), b->link().c_str()) >  0) : (strcmp(a->link().c_str(), b->link().c_str()) < 0);
			});
		} else if (methods[0] == "guid") {
			std::stable_sort(items_.begin(), items_.end(), [&](std::shared_ptr<rss_item> a, std::shared_ptr<rss_item> b) {
				return reverse ?  (strcmp(a->guid().c_str(), b->guid().c_str()) > 0) : (strcmp(a->guid().c_str(), b->guid().c_str()) < 0);
			});
		} else if (methods[0] == "date") {
			std::stable_sort(items_.begin(), items_.end(), [&](std::shared_ptr<rss_item> a, std::shared_ptr<rss_item> b) {
				return reverse ?  (a->pubDate_timestamp() > b->pubDate_timestamp()) : (a->pubDate_timestamp() < b->pubDate_timestamp());
			});
		}
	}
}

void rss_feed::remove_old_deleted_items() {
	std::lock_guard<std::mutex> lock(item_mutex);
	std::vector<std::string> guids;
	for (auto item : items_) {
		guids.push_back(item->guid());
	}
	ch->remove_old_deleted_items(rssurl_, guids);
}

void rss_feed::purge_deleted_items() {
	std::lock_guard<std::mutex> lock(item_mutex);
	scope_measure m1("rss_feed::purge_deleted_items");
	auto it=items_.begin();
	while (it!=items_.end()) {
		if ((*it)->deleted()) {
			{
				std::lock_guard<std::mutex> lock2(items_guid_map_mutex);
				items_guid_map.erase((*it)->guid());
			}
			items_.erase(it);
			it = items_.begin(); // items_ modified -> iterator invalidated
		} else {
			++it;
		}
	}
}

void rss_feed::set_feedptrs(std::shared_ptr<rss_feed> self) {
	std::lock_guard<std::mutex> lock(item_mutex);
	for (auto item : items_) {
		item->set_feedptr(self);
	}
}

void rss_item::set_feedptr(std::shared_ptr<rss_feed> ptr) {
	feedptr_ = std::weak_ptr<rss_feed>(ptr);
}

std::string rss_feed::get_status() {
	switch (status_) {
	case SUCCESS:
		return " ";
	case TO_BE_DOWNLOADED:
		return "_";
	case DURING_DOWNLOAD:
		return ".";
	case DL_ERROR:
		return "x";
	}
	return "?";
}

void rss_feed::unload() {
	std::lock_guard<std::mutex> lock(item_mutex);
	for (auto item : items_) {
		item->unload();
	}
}

void rss_feed::load() {
	std::lock_guard<std::mutex> lock(item_mutex);
	ch->fetch_descriptions(this);
}

}