aboutsummaryrefslogtreecommitdiff
path: root/src/fileurlreader.cpp
blob: 0baa003b96f084d2d2283c541e870586d81875ae (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
#include "fileurlreader.h"

#include <cstring>
#include <fstream>

#include "utils.h"

namespace newsboat {

FileUrlReader::FileUrlReader(const std::string& file)
	: filename(Utf8String::from_utf8(file))
{
}

std::string FileUrlReader::get_source()
{
	return filename.to_utf8();
}

nonstd::optional<std::string> FileUrlReader::reload()
{
	urls.clear();
	tags.clear();
	alltags.clear();

	auto result = utils::read_text_file(filename.to_utf8());
	if (!result) {
		return strprintf::fmt(_("Error: failed to read URLs from file \"%s\": %s"),
				filename,
				result.error().message);
	}
	std::vector<std::string> lines = result.value();

	for (const std::string& line : lines) {
		// skip empty lines and comments
		if (line.empty() || line[0] == '#') {
			continue;
		}

		std::vector<std::string> tokens = utils::tokenize_quoted(line);
		if (tokens.empty()) {
			continue;
		}

		std::string url = tokens[0];
		urls.push_back(url);

		tokens.erase(tokens.begin());
		if (!tokens.empty()) {
			tags[url] = tokens;
			for (const auto& token : tokens) {
				alltags.insert(token);
			}
		}
	};

	return {};
}

nonstd::optional<std::string> FileUrlReader::write_config()
{
	std::fstream f;
	f.open(filename.to_utf8(), std::fstream::out);
	if (!f.is_open()) {
		const auto error_message = strerror(errno);
		return strprintf::fmt(_("Error: failed to open file \"%s\": %s"),
				filename,
				error_message);
	}

	for (const auto& url : urls) {
		f << url;
		if (tags[url].size() > 0) {
			for (const auto& tag : tags[url]) {
				f << " \"" << tag << "\"";
			}
		}
		f << std::endl;
	}

	return {};
}

}