aboutsummaryrefslogtreecommitdiff
path: root/src/newsblurapi.cpp
blob: e09e4612f223fba2d4e3d304a3774e6cce8db5a5 (plain) (blame)
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
#include "newsblurapi.h"

#include <algorithm>
#include <string.h>
#include <time.h>

#include "logger.h"
#include "remoteapi.h"
#include "strprintf.h"
#include "utils.h"

/* json-c 0.13.99 does not define TRUE/FALSE anymore
 * the json-c maintainers replaced them with pure 1/0
 * https://github.com/json-c/json-c/commit/0992aac61f8b
 */
#if defined JSON_C_VERSION_NUM && JSON_C_VERSION_NUM >= ((13 << 8) | 99)
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE  1
#endif
#endif

#define NEWSBLUR_ITEMS_PER_PAGE 6

using HTTPMethod = newsboat::utils::HTTPMethod;

namespace newsboat {

NewsBlurApi::NewsBlurApi(ConfigContainer& c)
	: RemoteApi(c)
{
	api_location = cfg.get_configvalue("newsblur-url");
	min_pages = (cfg.get_configvalue_as_int("newsblur-min-items") +
			(NEWSBLUR_ITEMS_PER_PAGE + 1)) /
		NEWSBLUR_ITEMS_PER_PAGE;

	if (cfg.get_configvalue("cookie-cache").empty()) {
		LOG(Level::CRITICAL,
			"NewsBlurApi::NewsBlurApi: No cookie-cache has been "
			"configured the login won't work.");
	}
}

bool NewsBlurApi::authenticate()
{
	json_object* response{};
	json_object* status{};

	std::string auth = retrieve_auth();
	if (auth.empty()) {
		return false;
	}

	response = NewsBlurApi::query_api("/api/login", &auth, HTTPMethod::POST);
	json_object_object_get_ex(response, "authenticated", &status);
	bool result = json_object_get_boolean(status);

	LOG(Level::INFO,
		"NewsBlurApi::authenticate: authentication resulted in %u, "
		"cached "
		"in %s",
		result,
		cfg.get_configvalue("cookie-cache"));

	return result;
}

std::string NewsBlurApi::retrieve_auth()
{
	Credentials cred = get_credentials("newsblur", "NewsBlur");
	if (cred.user.empty() || cred.pass.empty()) {
		LOG(Level::CRITICAL,
			"NewsBlurApi::retrieve_auth: No user and/or password "
			"set");
		return "";
	}

	return strprintf::fmt("username=%s&password=%s", cred.user, cred.pass);
}

std::vector<TaggedFeedUrl> NewsBlurApi::get_subscribed_urls()
{
	std::vector<TaggedFeedUrl> result;

	json_object* response = query_api("/reader/feeds/", nullptr);

	json_object* feeds{};
	json_object_object_get_ex(response, "feeds", &feeds);

	json_object_iterator it = json_object_iter_begin(feeds);
	json_object_iterator itEnd = json_object_iter_end(feeds);

	json_object* folders{};
	json_object_object_get_ex(response, "folders", &folders);

	std::map<std::string, std::vector<std::string>> feeds_to_tags =
			mk_feeds_to_tags(folders);

	while (!json_object_iter_equal(&it, &itEnd)) {
		const char* feed_id = json_object_iter_peek_name(&it);
		json_object* node{};
		rsspp::Feed current_feed;

		current_feed.rss_version = rsspp::Feed::NEWSBLUR_JSON;

		json_object* feed_json = json_object_iter_peek_value(&it);
		json_object_object_get_ex(feed_json, "feed_title", &node);
		const auto title = json_object_get_string(node);
		if (title != nullptr) {
			current_feed.title = title;
		} else {
			LOG(Level::WARN, "Subscription has no title, so let's call it \"%s\"", feed_id);
			current_feed.title = feed_id;
		}
		json_object_object_get_ex(feed_json, "feed_link", &node);
		if (node) {
			const auto link = json_object_get_string(node);
			if (link == nullptr) {
				LOG(Level::WARN, "Skipping a subscription without a link");
				continue;
			}
			current_feed.link = link;

			known_feeds[feed_id] = current_feed;
			std::string std_feed_id(feed_id);
			std::vector<std::string> tags =
				feeds_to_tags[std_feed_id];
			result.push_back(TaggedFeedUrl(std_feed_id, tags));
		} else {
			LOG(Level::ERROR,
				"NewsBlurApi::get_subscribed_urls: feed fetch "
				"for "
				"%s failed, please check in NewsBlur",
				current_feed.title);
		}

		json_object_iter_next(&it);
	}

	return result;
}

std::map<std::string, std::vector<std::string>> NewsBlurApi::mk_feeds_to_tags(
		json_object* folders)
{
	std::map<std::string, std::vector<std::string>> result;
	array_list* tags = json_object_get_array(folders);
	int tags_len = array_list_length(tags);
	for (int i = 0; i < tags_len; ++i) {
		json_object* tag_to_feed_ids =
			json_object_array_get_idx(folders, i);

		if (!json_object_is_type(tag_to_feed_ids, json_type_object))
			// "folders" array contains not only dictionaries
			// describing folders but also numbers, which are IDs of
			// feeds that don't belong to any folder. This check
			// skips these IDs.
		{
			continue;
		}

		// invariant: `tag_to_feed_ids` is a JSON object

		json_object_object_foreach(tag_to_feed_ids, key, feeds_with_tag_obj) {
			std::string std_key(key);
			array_list* feeds_with_tag_arr = json_object_get_array(feeds_with_tag_obj);
			int feeds_with_tag_len = array_list_length(feeds_with_tag_arr);
			for (int j = 0; j < feeds_with_tag_len; ++j) {
				json_object* feed_id_obj = json_object_array_get_idx(feeds_with_tag_obj, j);
				const auto id = json_object_get_string(feed_id_obj);
				if (id == nullptr) {
					LOG(Level::WARN, "Skipping subscription's tag whose name is a null value");
					continue;
				}
				result[std::string(id)].push_back(std_key);
			}
		}
	}
	return result;
}

void NewsBlurApi::add_custom_headers(curl_slist** /* custom_headers */)
{
	// nothing required
}

bool request_successfull(json_object* payload)
{
	json_object* result{};
	if (json_object_object_get_ex(payload, "result", &result) == FALSE) {
		return false;
	} else {
		const auto result_str = json_object_get_string(result);
		return result_str != nullptr && strcmp("ok", result_str) == 0;
	}
}

bool NewsBlurApi::mark_all_read(const std::string& feed_url)
{
	std::string post_data = strprintf::fmt("feed_id=%s", feed_url);
	json_object* query_result =
		query_api("/reader/mark_feed_as_read", &post_data, HTTPMethod::POST);
	return request_successfull(query_result);
}

bool NewsBlurApi::mark_article_read(const std::string& guid, bool read)
{
	// handle dummy articles
	if (guid.empty()) {
		return false;
	}
	std::string endpoint;
	int separator = guid.find(ID_SEPARATOR);
	std::string feed_id = guid.substr(0, separator);
	std::string article_id =
		guid.substr(separator + sizeof(ID_SEPARATOR) - 1);

	std::string post_data =
		"feed_id=" + feed_id + "&" + "story_id=" + article_id;
	if (read) {
		endpoint = "/reader/mark_story_as_read";
	} else {
		endpoint = "/reader/mark_story_as_unread";
	}

	json_object* query_result = query_api(endpoint, &post_data, HTTPMethod::POST);
	return request_successfull(query_result);
}

bool NewsBlurApi::update_article_flags(const std::string& /* oldflags */,
	const std::string& /* newflags */,
	const std::string& /* guid */)
{
	return false;
}

time_t parse_date(const char* raw)
{
	struct tm tm;
	memset(&tm, 0, sizeof(tm));

	strptime(raw, "%Y-%m-%d %H:%M:%S", &tm);
	return mktime(&tm);
}

rsspp::Feed NewsBlurApi::fetch_feed(const std::string& id)
{
	rsspp::Feed f = known_feeds[id];

	LOG(Level::INFO,
		"NewsBlurApi::fetch_feed: about to fetch %u pages of feed %s",
		min_pages,
		id);

	for (unsigned int i = 1; i <= min_pages; i++) {
		std::string page = std::to_string(i);

		json_object* query_result = query_api(
				"/reader/feed/" + id + "?page=" + page, nullptr);

		if (!query_result) {
			return f;
		}

		json_object* stories{};
		if (json_object_object_get_ex(
				query_result, "stories", &stories) == FALSE) {
			LOG(Level::ERROR,
				"NewsBlurApi::fetch_feed: request returned no "
				"stories");
			return f;
		}

		if (json_object_get_type(stories) != json_type_array) {
			LOG(Level::ERROR,
				"NewsBlurApi::fetch_feed: content is not an "
				"array");
			return f;
		}

		struct array_list* items = json_object_get_array(stories);
		int items_size = array_list_length(items);
		LOG(Level::DEBUG,
			"NewsBlurApi::fetch_feed: %d items",
			items_size);

		for (int i = 0; i < items_size; i++) {
			json_object* item_obj = (json_object*)array_list_get_idx(items, i);

			rsspp::Item item;

			json_object* node{};

			if (json_object_object_get_ex(item_obj, "story_title", &node) == TRUE) {
				const auto title = json_object_get_string(node);
				if (title != nullptr) {
					item.title = title;
				}
			}

			if (json_object_object_get_ex(item_obj, "story_authors", &node) == TRUE) {
				const auto author = json_object_get_string(node);
				if (author != nullptr) {
					item.author = author;
				}
			}

			if (json_object_object_get_ex(item_obj, "story_permalink", &node) == TRUE) {
				const auto link = json_object_get_string(node);
				if (link != nullptr) {
					item.link = link;
				}
			}

			if (json_object_object_get_ex(item_obj, "story_content", &node) == TRUE) {
				const auto content_encoded = json_object_get_string(node);
				if (content_encoded != nullptr) {
					item.content_encoded = content_encoded;
				}
			}

			const char* article_id{};
			if (json_object_object_get_ex(item_obj, "id", &node) == TRUE) {
				article_id = json_object_get_string(node);
			}
			item.guid = id + ID_SEPARATOR + (article_id ? article_id : "");

			if (json_object_object_get_ex(item_obj, "read_status", &node) == TRUE) {
				if (!static_cast<bool>(json_object_get_int(node))) {
					item.labels.push_back("newsblur:unread");
				} else {
					item.labels.push_back("newsblur:read");
				}
			}

			if (json_object_object_get_ex(item_obj, "story_date", &node) == TRUE) {
				const char* pub_date = json_object_get_string(node);
				if (pub_date != nullptr) {
					item.pubDate_ts = parse_date(pub_date);
				} else {
					item.pubDate_ts = ::time(nullptr);
				}

				item.pubDate = utils::mt_strf_localtime(
						"%a, %d %b %Y %H:%M:%S %z",
						item.pubDate_ts);
			}

			f.items.push_back(item);
		}
	}

	std::sort(f.items.begin(),
		f.items.end(),
	[](const rsspp::Item& a, const rsspp::Item& b) {
		return a.pubDate_ts > b.pubDate_ts;
	});

	return f;
}

json_object* NewsBlurApi::query_api(const std::string& endpoint,
	const std::string* body,
	const HTTPMethod method /* = GET */)
{
	std::string url = api_location + endpoint;
	std::string data = utils::retrieve_url(url, cfg, "", body, method);

	json_object* result = json_tokener_parse(data.c_str());
	if (!result)
		LOG(Level::WARN,
			"NewsBlurApi::query_api: request to %s failed",
			url);
	return result;
}

} // namespace newsboat