feeds.lua

Fri, 17 Sep 2010 14:43:38 +0100

author
Matthew Wild <mwild1@gmail.com>
date
Fri, 17 Sep 2010 14:43:38 +0100
changeset 1
ee74a5e9419b
parent 0
319733864f05
child 3
ab02540afcf3
permissions
-rw-r--r--

demo.lua: Example usage

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