aboutsummaryrefslogtreecommitdiff
path: root/src/feedbinapi.cpp
blob: 83849a9544e6deb9022c648cd918632868d9ca04 (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
#include "feedbinapi.h"

#include <cinttypes>
#include <cstdint>
#include <curl/curl.h>
#include <string>

#include "3rd-party/json.hpp"
#include "curlhandle.h"
#include "logger.h"
#include "rss/feed.h"
#include "strprintf.h"
#include "utils.h"

#define FEEDBIN_AUTHENTICATION_PATH "/v2/authentication.json"
#define FEEDBIN_STARRED_ENTRIES_PATH "/v2/starred_entries.json"
#define FEEDBIN_TAGGINGS_PATH "/v2/taggings.json"
#define FEEDBIN_SUBSCRIPTIONS_PATH "/v2/subscriptions.json"
#define FEEDBIN_UNREAD_ENTRIES_PATH "/v2/unread_entries.json"

using json = nlohmann::json;

namespace newsboat {

FeedbinApi::FeedbinApi(ConfigContainer& c) : RemoteApi(c)
{
	const std::string http_auth_method = cfg.get_configvalue("http-auth-method");
	if (http_auth_method == "any") {
		// default to basic HTTP auth to prevent Newsboat from doubling up on HTTP
		// requests, since it doesn't "guess" the correct auth type on the first
		// try.
		cfg.set_configvalue("http-auth-method", "basic");
	}
}

bool FeedbinApi::authenticate()
{
	// error check handled in Controller
	const Credentials creds = get_credentials("feedbin", "");
	auth_info = strprintf::fmt("%s:%s", creds.user, creds.pass);

	CurlHandle handle;
	long response_code = 0;
	run_op(FEEDBIN_AUTHENTICATION_PATH, json(), handle);
	curl_easy_getinfo(handle.ptr(), CURLINFO_RESPONSE_CODE, &response_code);

	return response_code == 200;
}

TaggedFeedUrl FeedbinApi::feed_from_json(const json& jfeed,
	const std::vector<std::string>& addtags)
{
	const int feed_id = jfeed["feed_id"];
	const std::string feed_title = jfeed["title"];
	const std::string feed_url = jfeed["feed_url"];

	std::vector<std::string> tags;
	// automatically tag by feedtitle
	tags.push_back(std::string("~") + feed_title);

	// add additional tags
	tags.insert(tags.end(), addtags.cbegin(), addtags.cend());

	auto url = strprintf::fmt("%s#%d", feed_url, feed_id);
	return TaggedFeedUrl(url, tags);
}

std::vector<TaggedFeedUrl> FeedbinApi::get_subscribed_urls()
{
	std::vector<TaggedFeedUrl> feeds;

	const json taggings = run_op(FEEDBIN_TAGGINGS_PATH, json());
	if (taggings.is_null()) {
		LOG(Level::ERROR, "FeedbinApi::get_subscribed_urls: Failed to "
			"retrieve taggings");
		return feeds;
	}

	const json feed_list = run_op(FEEDBIN_SUBSCRIPTIONS_PATH, json());
	if (feed_list.is_null()) {
		LOG(Level::ERROR, "FeedbinApi::get_subscribed_urls: Failed to "
			"retrieve feedlist");
		return feeds;
	}

	for (const json& feed : feed_list) {
		const int feed_id = feed["feed_id"];

		std::vector<std::string> tags;
		for (const auto& tagging : taggings) {
			if (tagging["feed_id"] != feed_id) {
				continue;
			}

			const std::string tag_name = tagging["name"];
			tags.push_back(tagging["name"]);
		}

		feeds.push_back(feed_from_json(feed, tags));
	}

	return feeds;
}

bool FeedbinApi::mark_entries_read(const std::vector<std::string>& ids,
	bool read)
{
	CurlHandle handle;
	long response_code = 0;
	HTTPMethod method = read ? HTTPMethod::DELETE : HTTPMethod::POST;
	json body;
	body["unread_entries"] = ids;
	run_op(FEEDBIN_UNREAD_ENTRIES_PATH, body, handle, method);
	curl_easy_getinfo(handle.ptr(), CURLINFO_RESPONSE_CODE, &response_code);

	return response_code == 200;
}

bool FeedbinApi::mark_all_read(const std::string& combined_feed_url)
{
	std::string feed_id;
	const std::string::size_type pound = combined_feed_url.find_first_of('#');
	if (pound != std::string::npos) {
		feed_id = combined_feed_url.substr(pound + 1);
	} else {
		LOG(Level::ERROR, "FeedbinApi::mark_all_read: Failed to "
			"get feed ID from URL: %s", combined_feed_url);
		return false;
	}

	const std::string feed_entries_query =
		strprintf::fmt("/v2/feeds/%s/entries.json", feed_id);
	const json entries = run_op(feed_entries_query, json());

	std::vector<std::string> entry_ids;
	for (const auto& entry : entries) {
		uint64_t entry_id = entry["id"];
		entry_ids.push_back(std::to_string(entry_id));
	}

	return mark_entries_read(entry_ids, true);
}

bool FeedbinApi::mark_article_read(const std::string& guid, bool read)
{
	std::vector<std::string> entry_ids;
	entry_ids.push_back(guid);
	return mark_entries_read(entry_ids, read);
}

rsspp::Feed FeedbinApi::fetch_feed(const std::string& id,
	CurlHandle& cached_handle)
{
	rsspp::Feed feed;
	feed.rss_version = rsspp::Feed::FEEDBIN_JSON;

	const json unread_entry_ids = run_op(FEEDBIN_UNREAD_ENTRIES_PATH, json());
	if (!unread_entry_ids.is_array()) {
		LOG(Level::ERROR,
			"FeedbinApi::fetch_feed: unread_entry_ids is not an array");
		return feed;
	}

	std::map<int, bool> unread_entry_id_map;
	for (int entry_id : unread_entry_ids) {
		unread_entry_id_map[entry_id] = true;
	}

	const std::string query = strprintf::fmt("/v2/feeds/%s/entries.json", id);

	const json entries = run_op(query, json(), cached_handle, HTTPMethod::GET);
	if (!entries.is_array()) {
		LOG(Level::ERROR, "FeedbinApi::fetch_feed: entries is not an array");
		return feed;
	}

	LOG(Level::INFO, "FeedbinApi::fetch_feed: %" PRIu64 " items",
		static_cast<uint64_t>(entries.size()));
	try {
		for (const auto& entry : entries) {
			rsspp::Item item;

			if (!entry["title"].is_null()) {
				item.title = entry["title"];
			}

			if (!entry["url"].is_null()) {
				item.link = entry["url"];
			}

			if (!entry["author"].is_null()) {
				item.author = entry["author"];
			}

			if (!entry["content"].is_null()) {
				item.content_encoded = entry["content"];
			}

			const int64_t entry_id = entry["id"];
			item.guid = std::to_string(entry_id);

			item.pubDate = entry["published"];

			if (unread_entry_id_map[entry_id]) {
				item.labels.push_back("feedbin:unread");
			} else {
				item.labels.push_back("feedbin:read");
			}

			feed.items.push_back(item);
		}
	} catch (json::exception& e) {
		LOG(Level::ERROR, "Exception occurred while parsing feed: ", e.what());
	}

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

	return feed;
}

bool FeedbinApi::update_article_flags(const std::string& oldflags,
	const std::string& newflags,
	const std::string& guid)
{
	std::string star_flag = cfg.get_configvalue("feedbin-flag-star");
	bool success = true;

	if (!star_flag.empty()) {
		update_flag(oldflags, newflags, star_flag[0],
		[&](bool added) {
			success = star_article(guid, added);
		});
	}

	return success;
}

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

bool FeedbinApi::star_article(const std::string& article_id, bool star)
{
	std::vector<std::string> ids;
	ids.push_back(article_id);
	json body;
	body["starred_entries"] = ids;

	CurlHandle handle;

	HTTPMethod method = star ? HTTPMethod::POST : HTTPMethod::DELETE;

	run_op(FEEDBIN_STARRED_ENTRIES_PATH, body, handle, method);

	long response_code = 0;
	curl_easy_getinfo(handle.ptr(), CURLINFO_RESPONSE_CODE, &response_code);

	return response_code == 200;
}

json FeedbinApi::run_op(const std::string& path, const json& args,
	const HTTPMethod method /* = GET */)
{
	CurlHandle handle;
	return run_op(path, args, handle, method);
}

json FeedbinApi::run_op(const std::string& path, const json& args,
	CurlHandle& easyhandle,
	const HTTPMethod method /* = GET */)
{
	if (method == HTTPMethod::POST || method == HTTPMethod::DELETE) {
		curl_slist* headers = NULL;
		headers = curl_slist_append(headers, "Content-Type: application/json");
		curl_easy_setopt(easyhandle.ptr(), CURLOPT_HTTPHEADER, headers);
	}

	// follow redirects and keep the same request type
	curl_easy_setopt(easyhandle.ptr(), CURLOPT_FOLLOWLOCATION, 1);
	curl_easy_setopt(easyhandle.ptr(), CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL);

	const std::string server = cfg.get_configvalue("feedbin-url");
	const std::string url = server + path;

	std::string* body = nullptr;
	std::string arg_dump;
	if (!args.empty()) {
		arg_dump = args.dump();
		body = &arg_dump;
	}

	const std::string result =
		utils::retrieve_url(url, easyhandle, cfg, auth_info, body, method);

	LOG(Level::INFO, "Feedbin::run_op(%s %s,...): body=%s reply = %s",
		utils::http_method_str(method), path, arg_dump, result);

	json content;
	if (!result.empty()) {
		try {
			content = json::parse(result);
		} catch (json::parse_error& e) {
			LOG(Level::ERROR, "Feedbin::run_op: reply failed to parse: %s", result);
			content = json(nullptr);
		}
	}

	return content;
}

} // namespace newsboat