feeds.lua

changeset 0
319733864f05
child 3
ab02540afcf3
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/feeds.lua	Sat Jul 17 02:52:26 2010 +0100
@@ -0,0 +1,80 @@
+local io = io;
+local http = require "socket.http";
+local st = require "stanza";
+local new_stream = require "xmppstream".new;
+
+local xmlns_atom = "http://www.w3.org/2005/Atom";
+
+module "feeds"
+
+local function new_feed_stream(feed)
+	local callbacks = {
+		default_ns = xmlns_atom;
+		stream_ns = xmlns_atom; stream_tag = "feed";
+		
+		streamopened = function (feed, attr)
+			feed.notopen = nil;
+		end;
+		
+		streamclosed = function (feed)
+		end;
+		
+		handlestanza = function (feed, stanza)
+			-- Skip tags not in the feed's default namespace
+			if stanza.attr.xmlns ~= nil then
+				return;
+			end
+			
+			if stanza.name == "entry" then
+				feed[#feed+1] = stanza;
+			else
+				feed[stanza.name] = stanza:get_text();
+			end
+		end;
+	};
+	
+	return new_stream(feed, callbacks);
+end
+
+function feed_from_string(data)
+	local feed = {notopen = true};
+	
+	local stream = new_feed_stream(feed);
+	stream:feed(data);
+	
+	return feed;
+end
+
+function open(url)
+	if url:match("^file://") then
+		return open_file(url);
+	elseif url:match("^https?://") then
+		return open_http(url);
+	else
+		return false, "Could not understand URL: "..url;
+	end
+end
+
+function open_file(filename)
+	local file, err = io.open((filename:gsub("^file://", "")));
+	if not file then
+		return file, err;
+	end
+	
+	local feed = feed_from_string(file:read("*a"));
+	
+	file:close();
+	
+	return feed;
+end
+
+function open_http(url)
+	local data, err = http.request(url);
+	if not data then
+		return data, err;
+	end
+	
+	local feed = feed_from_string(data);
+	
+	return feed;
+end

mercurial