summaryrefslogtreecommitdiff
path: root/sfeed_opml_import.c
blob: a25473337885afa4f484118d12e184a4ee483822 (plain)
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
#include <sys/types.h>

#include <ctype.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>

#include "util.h"
#include "xml.h"

static XMLParser parser; /* XML parser state */
static char url[2048], text[256], title[256];

static void
printsafe(const char *s)
{
	for (; *s; s++) {
		if (iscntrl((int)*s))
			continue;
		else if (*s == '\\')
			fputs("\\\\", stdout);
		else if (*s == '\'')
			fputs("'\\''", stdout);
		else
			putchar((int)*s);
	}
}

static void
xml_handler_end_element(XMLParser *p, const char *tag, size_t taglen,
	int isshort)
{
	if (strcasecmp(tag, "outline"))
		return;

	if (url[0]) {
		fputs("\tfeed '", stdout);
		if (title[0])
			printsafe(title);
		else if (text[0])
			printsafe(text);
		else
			fputs("unnamed", stdout);
		fputs("' '", stdout);
		printsafe(url);
		fputs("'\n", stdout);
	}
	url[0] = text[0] = title[0] = '\0';
}

static void
xml_handler_attr(XMLParser *p, const char *tag, size_t taglen,
	const char *name, size_t namelen, const char *value, size_t valuelen)
{
	if (strcasecmp(tag, "outline"))
		return;

	if (!strcasecmp(name, "title"))
		strlcat(title, value, sizeof(title));
	else if (!strcasecmp(name, "text"))
		strlcat(text, value, sizeof(text));
	else if (!strcasecmp(name, "xmlurl"))
		strlcat(url, value, sizeof(url));
}

static void
xml_handler_attrentity(XMLParser *p, const char *tag, size_t taglen,
	const char *name, size_t namelen, const char *value, size_t valuelen)
{
	char buf[16];
	ssize_t len;

	if ((len = xml_entitytostr(value, buf, sizeof(buf))) < 0)
		return;
	if (len > 0)
		xml_handler_attr(p, tag, taglen, name, namelen, buf, len);
	else
		xml_handler_attr(p, tag, taglen, name, namelen, value, valuelen);
}

int
main(void)
{
	if (pledge("stdio", NULL) == -1)
		err(1, "pledge");

	parser.xmlattr = xml_handler_attr;
	parser.xmlattrentity = xml_handler_attrentity;
	parser.xmltagend = xml_handler_end_element;

	fputs(
	    "#sfeedpath=\"$HOME/.sfeed/feeds\"\n"
	    "\n"
	    "# list of feeds to fetch:\n"
	    "feeds() {\n"
	    "	# feed <name> <feedurl> [basesiteurl] [encoding]\n", stdout);
	parser.getnext = getchar;
	xml_parse(&parser);
	fputs("}\n", stdout);

	return 0;
}