/*
 * Feeds: reading RSS 2.0, RSS 1.0 (RDF) and Atom with libxml2, keeping
 * the file as last downloaded in the cache so the app has stories to show
 * before the network answers.
 */
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "news.h"

#define STORIES_MAX 60

/* XML helpers: elements by local name, and optionally namespace prefix */

static bool el(const xmlNode *n, const char *prefix, const char *name) {
	if (n->type != XML_ELEMENT_NODE || strcmp((const char *)n->name, name) != 0) {
		return false;
	}
	if (prefix == NULL) {
		return true;
	}
	return n->ns && n->ns->prefix &&
		strcmp((const char *)n->ns->prefix, prefix) == 0;
}

/* Elements of the feed's own vocabulary (no prefix, or Atom's default
 * namespace), not another namespace's element of the same name */
static bool own(const xmlNode *n, const char *name) {
	return el(n, NULL, name) && (n->ns == NULL || n->ns->prefix == NULL);
}

static char *text_of(xmlNode *n) {
	xmlChar *c = xmlNodeGetContent(n);
	char *s = c ? g_strstrip(g_strdup((const char *)c)) : NULL;
	if (c) {
		xmlFree(c);
	}
	return s;
}

static char *attr(xmlNode *n, const char *name) {
	xmlChar *v = xmlGetProp(n, (const xmlChar *)name);
	char *s = v ? g_strdup((const char *)v) : NULL;
	if (v) {
		xmlFree(v);
	}
	return s;
}

/* Children serialised, for Atom's type="xhtml" content */
static char *inner_xml(xmlNode *n) {
	GString *out = g_string_new(NULL);
	for (xmlNode *c = n->children; c; c = c->next) {
		xmlBufferPtr buf = xmlBufferCreate();
		xmlNodeDump(buf, n->doc, c, 0, 0);
		g_string_append(out, (const char *)xmlBufferContent(buf));
		xmlBufferFree(buf);
	}
	return g_string_free(out, FALSE);
}

/* Dates */

static int64_t parse_date(const char *s) {
	if (s == NULL || s[0] == '\0') {
		return 0;
	}
	GDateTime *dt = g_date_time_new_from_iso8601(s, NULL);
	if (dt) {
		int64_t t = g_date_time_to_unix(dt);
		g_date_time_unref(dt);
		return t;
	}
	/* RFC 822: [Mon,] 02 Jan 2006 15:04:05 +0200 */
	static const char *months = "janfebmaraprmayjunjulaugsepoctnovdec";
	const char *p = strchr(s, ',');
	p = p ? p + 1 : s;
	int day, year, h = 0, mi = 0, sec = 0;
	char mon[8] = { 0 };
	int n = sscanf(p, " %d %3s %d %d:%d:%d", &day, mon, &year, &h, &mi, &sec);
	if (n < 3) {
		return 0;
	}
	for (char *c = mon; *c; c++) {
		*c = g_ascii_tolower(*c);
	}
	const char *m = strstr(months, mon);
	if (m == NULL || (m - months) % 3 != 0) {
		return 0;
	}
	if (year < 100) {
		year += year < 70 ? 2000 : 1900;
	}
	struct tm tm = { .tm_mday = day, .tm_mon = (int)(m - months) / 3,
		.tm_year = year - 1900, .tm_hour = h, .tm_min = mi, .tm_sec = sec };
	int64_t t = timegm(&tm);
	/* The zone: +hhmm, or a name */
	const char *tail = strrchr(p, ' ');
	tail = tail ? tail + 1 : "";
	if ((tail[0] == '+' || tail[0] == '-') && strlen(tail) >= 5) {
		int hhmm = atoi(tail + 1);
		int off = (hhmm / 100) * 3600 + (hhmm % 100) * 60;
		t -= tail[0] == '-' ? -off : off;
	} else {
		static const struct { const char *name; int hours; } zones[] = {
			{ "EST", -5 }, { "EDT", -4 }, { "CST", -6 }, { "CDT", -5 },
			{ "MST", -7 }, { "MDT", -6 }, { "PST", -8 }, { "PDT", -7 },
		};
		for (size_t i = 0; i < G_N_ELEMENTS(zones); i++) {
			if (strcmp(tail, zones[i].name) == 0) {
				t -= zones[i].hours * 3600;
			}
		}
	}
	return t;
}

char *news_age(int64_t date) {
	int64_t d = (int64_t)time(NULL) - date;
	if (date == 0) {
		return g_strdup("");
	}
	if (d < 90) {
		return g_strdup("now");
	}
	if (d < 3600) {
		return g_strdup_printf("%d min", (int)(d / 60));
	}
	if (d < 86400) {
		return g_strdup_printf("%d h", (int)(d / 3600));
	}
	if (d < 2 * 86400) {
		return g_strdup("yesterday");
	}
	if (d < 30 * 86400) {
		return g_strdup_printf("%d days", (int)(d / 86400));
	}
	GDateTime *dt = g_date_time_new_from_unix_local(date);
	char *s = g_date_time_format(dt, "%e %b");
	g_date_time_unref(dt);
	return g_strstrip(s);
}

/* Stories */

void news_story_free(struct story *s) {
	g_free(s->id);
	g_free(s->title);
	g_free(s->summary);
	g_free(s->link);
	g_free(s->author);
	g_free(s->image_url);
	g_free(s->markup);
	g_free(s->html);
	g_free(s);
}

const char *news_story_markup(struct story *s) {
	if (s->markup == NULL && s->html) {
		s->markup = html_to_markup(s->html, NULL);
		g_clear_pointer(&s->html, g_free);
	}
	return s->markup;
}

static bool image_type(const char *type) {
	return type && g_ascii_strncasecmp(type, "image/", 6) == 0;
}

/* Fills a story from an RSS <item> or an Atom <entry> */
static struct story *read_story(struct feed *feed, xmlNode *item, bool atom,
		int64_t fallback_date) {
	struct story *s = g_new0(struct story, 1);
	s->feed = feed;
	char *description = NULL, *content = NULL, *guid = NULL, *title = NULL;
	char *pub = NULL, *dc_date = NULL, *image = NULL;
	for (xmlNode *c = item->children; c; c = c->next) {
		if (c->type != XML_ELEMENT_NODE) {
			continue;
		}
		if (own(c, "title") && !title) {
			xmlChar *type = xmlGetProp(c, (const xmlChar *)"type");
			title = type && strcmp((const char *)type, "xhtml") == 0 ?
				inner_xml(c) : text_of(c);
			if (type) {
				xmlFree(type);
			}
		} else if (own(c, "link")) {
			if (atom) {
				char *rel = attr(c, "rel"), *href = attr(c, "href");
				if (href && (rel == NULL || strcmp(rel, "alternate") == 0) &&
						s->link == NULL) {
					s->link = g_strdup(href);
				} else if (href && rel && strcmp(rel, "enclosure") == 0 &&
						image == NULL) {
					char *type = attr(c, "type");
					if (image_type(type)) {
						image = g_strdup(href);
					}
					g_free(type);
				}
				g_free(rel);
				g_free(href);
			} else if (s->link == NULL) {
				s->link = text_of(c);
			}
		} else if ((own(c, "guid") || own(c, "id")) && !guid) {
			guid = text_of(c);
		} else if ((own(c, "pubDate") || own(c, "published") ||
				own(c, "updated")) && !pub) {
			pub = text_of(c);
		} else if (el(c, "dc", "date") && !dc_date) {
			dc_date = text_of(c);
		} else if (own(c, "description") || own(c, "summary")) {
			if (!description) {
				description = text_of(c);
			}
		} else if (el(c, "content", "encoded") || (atom && own(c, "content"))) {
			if (!content) {
				xmlChar *type = xmlGetProp(c, (const xmlChar *)"type");
				content = type && strcmp((const char *)type, "xhtml") == 0 ?
					inner_xml(c) : text_of(c);
				if (type) {
					xmlFree(type);
				}
			}
		} else if (own(c, "author") || el(c, "dc", "creator")) {
			if (!s->author) {
				if (atom) {
					for (xmlNode *a = c->children; a; a = a->next) {
						if (own(a, "name")) {
							s->author = text_of(a);
						}
					}
				} else {
					s->author = text_of(c);
				}
			}
		} else if (own(c, "enclosure") && !atom) {
			char *type = attr(c, "type"), *url = attr(c, "url");
			if (url && image_type(type) && !image) {
				image = g_strdup(url);
			}
			g_free(type);
			g_free(url);
		} else if ((el(c, "media", "thumbnail") || el(c, "media", "content")) &&
				!image) {
			char *url = attr(c, "url"), *type = attr(c, "type"),
				*medium = attr(c, "medium");
			if (url && (image_type(type) || (medium && strcmp(medium, "image") == 0) ||
					el(c, "media", "thumbnail"))) {
				image = g_strdup(url);
			}
			g_free(url);
			g_free(type);
			g_free(medium);
		} else if (el(c, "media", "group") && !image) {
			for (xmlNode *g = c->children; g; g = g->next) {
				if (el(g, "media", "thumbnail") || el(g, "media", "content")) {
					char *url = attr(g, "url"), *type = attr(g, "type");
					if (url && (image_type(type) || el(g, "media", "thumbnail"))) {
						image = g_strdup(url);
					}
					g_free(url);
					g_free(type);
					if (image) {
						break;
					}
				}
			}
		} else if (el(c, "itunes", "image") && !image) {
			image = attr(c, "href");
		}
	}

	char *body = content && content[0] ? content : description;
	char *html_image = NULL;
	if (image) {
		/* The text isn't needed for its picture: later, if it's read */
		s->html = g_strdup(body);
	} else {
		s->markup = html_to_markup(body, &html_image);
	}
	s->summary = html_to_text(description && description[0] ? description :
		content, 240);
	s->title = title ? html_to_text(title, 300) : g_strdup("");
	if (s->title[0] == '\0') {
		g_free(s->title);
		s->title = g_strdup(s->summary[0] ? s->summary : "Untitled");
	}
	/* The picture: the feed's own, else the first in the text */
	s->image_url = image ? image : html_image;
	if (image && html_image) {
		g_free(html_image);
	}
	if (s->image_url && s->link) {
		char *abs = g_uri_resolve_relative(s->link, s->image_url,
			G_URI_FLAGS_NONE, NULL);
		if (abs) {
			g_free(s->image_url);
			s->image_url = abs;
		}
	}
	s->id = guid && guid[0] ? g_strdup(guid) : s->link ? g_strdup(s->link) :
		g_strdup(s->title);
	s->date = parse_date(pub ? pub : dc_date);
	if (s->date == 0) {
		s->date = fallback_date;
	}
	s->read = news_is_read(s->id, feed->url);
	g_free(description);
	g_free(content);
	g_free(guid);
	g_free(title);
	g_free(pub);
	g_free(dc_date);
	return s;
}

static int by_date(gconstpointer a, gconstpointer b) {
	const struct story *x = *(struct story *const *)a, *y = *(struct story *const *)b;
	return x->date < y->date ? 1 : x->date > y->date ? -1 : 0;
}

/* No external entities. libxml2 before 2.14 (Debian 13's) never loads
 * them unless asked (NOENT, DTDLOAD) and has no flag to refuse them */
#if LIBXML_VERSION < 21400
#define XML_PARSE_NO_XXE 0
#endif

/* Replaces the feed's stories with those in the document; false if it is
 * not a feed */
static bool parse_feed(struct feed *feed, const char *data, size_t len) {
	xmlDocPtr doc = xmlReadMemory(data, (int)len, feed->url, NULL,
		XML_PARSE_NONET | XML_PARSE_NOERROR | XML_PARSE_NOWARNING |
		XML_PARSE_RECOVER | XML_PARSE_NO_XXE);
	if (doc == NULL) {
		return false;
	}
	xmlNode *root = xmlDocGetRootElement(doc);
	bool atom = root && strcmp((const char *)root->name, "feed") == 0;
	bool rss = root && (strcmp((const char *)root->name, "rss") == 0 ||
		strcmp((const char *)root->name, "RDF") == 0);
	if (!atom && !rss) {
		xmlFreeDoc(doc);
		return false;
	}
	/* RSS 2: items are in <channel>; RSS 1: beside it */
	xmlNode *channel = root;
	if (rss) {
		for (xmlNode *c = root->children; c; c = c->next) {
			if (own(c, "channel")) {
				channel = c;
			}
		}
	}
	GPtrArray *stories = g_ptr_array_new();
	char *title = NULL, *site = NULL, *logo = NULL;
	int64_t now = (int64_t)time(NULL);
	int index = 0;
	for (int pass = 0; pass < (rss ? 2 : 1); pass++) {
		xmlNode *parent = pass == 0 ? channel : root;
		for (xmlNode *c = parent->children; c; c = c->next) {
			if (c->type != XML_ELEMENT_NODE) {
				continue;
			}
			if (own(c, "title") && !title && pass == 0) {
				title = text_of(c);
			} else if (rss && own(c, "image") && !logo) {
				/* RSS 2 in <channel>, RSS 1 beside it */
				for (xmlNode *u = c->children; u; u = u->next) {
					if (own(u, "url") && !logo) {
						logo = text_of(u);
					}
				}
			} else if (atom && own(c, "icon")) {
				/* The square one: better than a wide <logo> */
				g_free(logo);
				logo = text_of(c);
			} else if (atom && own(c, "logo") && !logo) {
				logo = text_of(c);
			} else if (own(c, "link") && !site && pass == 0) {
				if (atom) {
					char *rel = attr(c, "rel");
					if (rel == NULL || strcmp(rel, "alternate") == 0) {
						site = attr(c, "href");
					}
					g_free(rel);
				} else {
					site = text_of(c);
				}
			} else if ((atom && own(c, "entry")) || (rss && own(c, "item"))) {
				if (stories->len < STORIES_MAX) {
					/* No date: older than the ones before it */
					g_ptr_array_add(stories, read_story(feed, c, atom,
						now - index * 60));
					index++;
				}
			}
		}
	}
	xmlFreeDoc(doc);

	g_ptr_array_sort(stories, by_date);
	/* The same story twice (a feed that repeats itself): once */
	GHashTable *seen = g_hash_table_new(g_str_hash, g_str_equal);
	for (guint i = 0; i < stories->len;) {
		struct story *s = stories->pdata[i];
		if (g_hash_table_contains(seen, s->id)) {
			g_ptr_array_remove_index(stories, i);
			news_story_free(s);
		} else {
			g_hash_table_add(seen, s->id);
			i++;
		}
	}
	g_hash_table_destroy(seen);

	for (guint i = 0; i < feed->stories->len; i++) {
		news_story_free(feed->stories->pdata[i]);
	}
	g_ptr_array_unref(feed->stories);
	feed->stories = stories;
	if (title && title[0] && !feed->named) {
		g_free(feed->name);
		feed->name = title;
	} else {
		g_free(title);
	}
	if (site) {
		g_free(feed->site);
		feed->site = site;
		g_clear_pointer(&feed->favicon, g_free);
	}
	g_clear_pointer(&feed->logo, g_free);
	if (logo && logo[0]) {
		/* Atom's may be relative */
		feed->logo = g_uri_resolve_relative(feed->url, g_strstrip(logo),
			G_URI_FLAGS_NONE, NULL);
	}
	g_free(logo);
	return true;
}

/* The cache */

static char *cache_file(struct feed *feed, const char *ext) {
	char *hash = g_compute_checksum_for_string(G_CHECKSUM_SHA1, feed->url, -1);
	char *name = g_strconcat(hash, ext, NULL);
	char *path = news_cache_path(name);
	g_free(hash);
	g_free(name);
	return path;
}

/* A synced feed's stories, as rssnail gave them */
static char *remote_cache(struct feed *feed) {
	char *name = g_strdup_printf("rssnail-%" G_GINT64_FORMAT ".json",
		feed->remote);
	char *path = news_cache_path(name);
	g_free(name);
	return path;
}

static bool take_posts(struct feed *feed, const char *path) {
	char *text = NULL;
	if (!g_file_get_contents(path, &text, NULL, NULL)) {
		return false;
	}
	GPtrArray *stories = rssnail_parse_posts(feed, text);
	g_free(text);
	if (stories == NULL) {
		return false;
	}
	g_ptr_array_sort(stories, by_date);
	for (guint i = 0; i < feed->stories->len; i++) {
		news_story_free(feed->stories->pdata[i]);
	}
	g_ptr_array_unref(feed->stories);
	feed->stories = stories;
	return true;
}

void feed_load_cache(struct feed *feed) {
	if (feed->remote) {
		char *path = remote_cache(feed);
		take_posts(feed, path);
		g_free(path);
		return;
	}
	char *path = cache_file(feed, ".xml"), *meta = cache_file(feed, ".meta");
	char *data = NULL;
	gsize len = 0;
	if (g_file_get_contents(path, &data, &len, NULL)) {
		parse_feed(feed, data, len);
		g_free(data);
		GKeyFile *kf = g_key_file_new();
		if (g_key_file_load_from_file(kf, meta, G_KEY_FILE_NONE, NULL)) {
			g_free(feed->etag);
			g_free(feed->modified);
			feed->etag = g_key_file_get_string(kf, "feed", "etag", NULL);
			feed->modified = g_key_file_get_string(kf, "feed", "modified", NULL);
			feed->fetched = g_key_file_get_int64(kf, "feed", "fetched", NULL);
		}
		g_key_file_free(kf);
	}
	g_free(path);
	g_free(meta);
}

/* Refreshing */

struct refresh {
	struct feed *feed; // NULL once it was forgotten
	feed_done_fn fn;
	void *data;
};

static GHashTable *running; // feed -> struct refresh

void feed_forget(struct feed *feed) {
	struct refresh *r = running ? g_hash_table_lookup(running, feed) : NULL;
	if (r) {
		r->feed = NULL;
		g_hash_table_remove(running, feed);
	}
}

static void fetched(int status, const char *etag, const char *modified,
		void *data);

static void remote_fetched(int status, const char *etag, const char *modified,
		void *data);

static void start_fetch(struct refresh *r) {
	struct feed *feed = r->feed;
	if (feed->remote) {
		char *path = remote_cache(feed);
		rssnail_posts(feed, path, remote_fetched, r);
		g_free(path);
		return;
	}
	char *path = cache_file(feed, ".xml");
	fetch_start(feed->url, path, feed->etag, feed->modified, fetched, r);
	g_free(path);
}

static void finish(struct refresh *r, bool changed) {
	struct feed *feed = r->feed;
	if (feed) {
		feed->loading = false;
		g_hash_table_remove(running, feed);
		if (r->fn) {
			r->fn(feed, changed, r->data);
		}
	}
	g_free(r);
}

static void fetched(int status, const char *etag, const char *modified,
		void *data) {
	struct refresh *r = data;
	struct feed *feed = r->feed;
	if (feed == NULL) {
		g_free(r);
		return;
	}
	if (status == 304) {
		feed->failed = false;
		feed->fetched = time(NULL);
		finish(r, false);
		return;
	}
	if (status != 200) {
		feed->failed = true;
		g_free(feed->error);
		feed->error = status ? g_strdup_printf("The server said %d", status) :
			g_strdup("Couldn't reach it");
		finish(r, false);
		return;
	}
	char *path = cache_file(feed, ".xml");
	char *text = NULL;
	gsize len = 0;
	bool ok = g_file_get_contents(path, &text, &len, NULL);
	if (ok && !parse_feed(feed, text, len)) {
		/* A web page: its feed may be linked from it, once */
		char *found = feed->rediscovered ? NULL : feed_discover(text, len,
			feed->url);
		feed->rediscovered = true;
		/* Already followed under its real address: this one is a copy */
		for (guint i = 0; found && i < news_feeds->len; i++) {
			if (news_feeds->pdata[i] != feed &&
					strcmp(((struct feed *)news_feeds->pdata[i])->url, found) == 0) {
				g_free(found);
				found = NULL;
				g_unlink(path);
				g_free(text);
				g_free(path);
				feed->failed = true;
				g_free(feed->error);
				feed->error = g_strdup("You follow that feed already");
				finish(r, false);
				return;
			}
		}
		if (found && strcmp(found, feed->url) != 0) {
			g_unlink(path);
			g_free(feed->url);
			feed->url = found;
			g_free(feed->etag);
			g_free(feed->modified);
			feed->etag = feed->modified = NULL;
			news_save_feeds();
			g_free(text);
			g_free(path);
			start_fetch(r);
			return;
		}
		g_free(found);
		ok = false;
		g_unlink(path);
	}
	g_free(text);
	g_free(path);
	if (!ok) {
		feed->failed = true;
		g_free(feed->error);
		feed->error = g_strdup("That isn't a feed");
		finish(r, false);
		return;
	}
	feed->failed = false;
	feed->fetched = time(NULL);
	g_free(feed->etag);
	g_free(feed->modified);
	feed->etag = g_strdup(etag);
	feed->modified = g_strdup(modified);
	char *meta = cache_file(feed, ".meta");
	GKeyFile *kf = g_key_file_new();
	if (feed->etag) {
		g_key_file_set_string(kf, "feed", "etag", feed->etag);
	}
	if (feed->modified) {
		g_key_file_set_string(kf, "feed", "modified", feed->modified);
	}
	g_key_file_set_int64(kf, "feed", "fetched", feed->fetched);
	g_key_file_save_to_file(kf, meta, NULL);
	g_key_file_free(kf);
	g_free(meta);
	finish(r, true);
}

static void remote_fetched(int status, const char *etag, const char *modified,
		void *data) {
	struct refresh *r = data;
	struct feed *feed = r->feed;
	if (feed == NULL) {
		g_free(r);
		return;
	}
	char *path = remote_cache(feed);
	bool ok = status == 200 && take_posts(feed, path);
	g_free(path);
	feed->failed = !ok;
	g_free(feed->error);
	feed->error = ok ? NULL : status ? g_strdup_printf("rssnail said %d",
		status) : g_strdup("Couldn't reach rssnail");
	if (ok) {
		feed->fetched = time(NULL);
	}
	finish(r, ok);
}

void feed_refresh(struct feed *feed, feed_done_fn fn, void *data) {
	if (feed->loading) {
		return;
	}
	if (running == NULL) {
		running = g_hash_table_new(g_direct_hash, g_direct_equal);
	}
	feed->loading = true;
	struct refresh *r = g_new0(struct refresh, 1);
	r->feed = feed;
	r->fn = fn;
	r->data = data;
	g_hash_table_insert(running, feed, r);
	start_fetch(r);
}

/* Across feeds */

GPtrArray *news_latest(int max) {
	GPtrArray *all = g_ptr_array_new();
	for (guint i = 0; i < news_feeds->len; i++) {
		struct feed *f = news_feeds->pdata[i];
		for (guint k = 0; k < f->stories->len; k++) {
			g_ptr_array_add(all, f->stories->pdata[k]);
		}
	}
	g_ptr_array_sort(all, by_date);
	if (max > 0 && all->len > (guint)max) {
		g_ptr_array_set_size(all, max);
	}
	return all;
}

const char *news_feed_logo(struct feed *feed) {
	if (feed->logo) {
		return feed->logo;
	}
	if (feed->favicon == NULL) {
		GUri *uri = g_uri_parse(feed->site ? feed->site : feed->url,
			G_URI_FLAGS_NONE, NULL);
		const char *scheme = uri ? g_uri_get_scheme(uri) : NULL;
		if (uri && g_uri_get_host(uri) && scheme &&
				(strcmp(scheme, "http") == 0 || strcmp(scheme, "https") == 0)) {
			feed->favicon = g_strdup_printf("%s://%s/favicon.ico", scheme,
				g_uri_get_host(uri));
		}
		if (uri) {
			g_uri_unref(uri);
		}
	}
	return feed->favicon;
}
