summaryrefslogtreecommitdiff
path: root/sfeed_mbox.c
blob: fdcd17d5fc1fc7e7fdda1ddd783f61ec626b723f (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
#include <sys/types.h>

#include <err.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "util.h"

static char *line = NULL;
static size_t linesize = 0;

static void
printfeed(FILE *fp, const char *feedname)
{
	struct tm tm;
	char *fields[FieldLast], timebuf[32], mtimebuf[32];
	char host[HOST_NAME_MAX + 1], *user;
	time_t parsedtime;
	int r;

	if (!(user = getenv("USER")))
		user = "you";
	if (gethostname(host, sizeof(host)) == -1)
		err(1, "gethostname");

	if ((parsedtime = time(NULL)) == -1)
		err(1, "time");
	if (!gmtime_r(&parsedtime, &tm))
		errx(1, "gmtime_r: can't get current time");
	if (!strftime(mtimebuf, sizeof(mtimebuf), "%a %b %d %H:%M:%S %Y", &tm))
		errx(1, "can't format current time");

	while (parseline(&line, &linesize, fields, FieldLast, '\t', fp) > 0) {
		if ((r = strtotime(fields[FieldUnixTimestamp], &parsedtime)) == -1)
			continue; /* invalid date */
		if (!gmtime_r(&parsedtime, &tm))
			continue; /* invalid date */
		if (!strftime(timebuf, sizeof(timebuf),
		    "%a, %d %b %Y %H:%M +0000", &tm))
			continue; /* invalid date */

		/* mbox + mail header */
		printf("From MAILER-DAEMON %s\n"
			"Date: %s\n"
			"From: %s <sfeed@>\n"
			"To: %s <%s@%s>\n"
			"Subject: %s\n"
			"Message-ID: <%s-%s-sfeed>\n"
			"Content-Type: text/%s; charset=UTF-8\n"
			"Content-Transfer-Encoding: binary\n"
			"X-Feedname: %s\n"
			"\n",
			mtimebuf, timebuf, fields[FieldAuthor],
			user, user, host, fields[FieldTitle],
			fields[FieldUnixTimestamp], fields[FieldId],
			fields[FieldContentType], feedname);

		if (!strcmp(fields[FieldContentType], "html")) {
			fputs("<p>Link: <a href=\"", stdout);
			print(fields[FieldLink], stdout, fputc);
			fputs("\">", stdout);
			print(fields[FieldLink], stdout, fputc);
			fputs("</a></p>\n\n", stdout);
			decodefield(fields[FieldContent], stdout, fputc);
		} else {
			fputs("Link: ", stdout);
			print(fields[FieldLink], stdout, fputc);
			fputs("\n\n", stdout);
			decodefield(fields[FieldContent], stdout, fputc);
		}
		fputs("\n\n", stdout);
	}
}

int
main(int argc, char *argv[])
{
	FILE *fp;
	char *name;
	int i;

	if (argc == 1) {
		printfeed(stdin, "");
	} else {
		for (i = 1; i < argc; i++) {
			fp = fopen(argv[i], "r");
			if (!fp)
				err(1, "fopen: %s", argv[i]);
			name = xbasename(argv[i]);
			printfeed(fp, name);
			free(name);
			if (ferror(fp))
				err(1, "ferror: %s", argv[i]);
			fclose(fp);
		}
	}
	return 0;
}