plugins/youtube.lua

1
-- Copyright (C) 2010 Thilo Cestonaro
2
-- 
3
-- This project is MIT/X11 licensed.
4
--
5
local http = require("prosody.net.http");
6
local st = require("prosody.util.stanza");
7
local tostring = tostring;
8
 
9
function riddim.plugins.youtube(bot)
10
	local youtubelink_pattern = "http:%/%/www.youtube.com%/watch%?v=([%a%-%_%d]+)";
11
 
12
	local function bare_reply(event, reply)
13
		if event.stanza.attr.type == 'groupchat' then
14
			local r = st.reply(event.stanza)
15
			local room_jid = jid.bare(event.sender.jid);
16
			if bot.rooms[room_jid] then
17
				bot.rooms[room_jid]:send(r:tag("body"):text(reply));
18
			end
19
		else
20
			return event:reply(reply);
21
		end
22
	end
23
 
24
	local function findYoutubeLink(event)
25
		local body = event.body;
26
		if not body then return; end
27
		if event.delay then return; end -- Don't process old messages from groupchat
28
 
29
		local videoId = body:match(youtubelink_pattern);
30
 
31
		if videoId then
32
			print("VideoID: "..tostring(videoId));
33
			http.request("http://gdata.youtube.com/feeds/api/videos/"..tostring(videoId).."?v=2", nil, function (data, code, request)
34
				print("returned code: "..tostring(code));
35
				print("-------------------------------------------------------------------------------------------");
36
				print("returned data: "..tostring(data));
37
				print("-------------------------------------------------------------------------------------------");
38
				if code ~= 200 then
39
					if code > 0 then
40
						event:reply("Received HTTP "..code.." error (video gone?)");
41
					else
42
						event:reply("Unable to fetch the XEP list from xmpp.org: "..data:gsub("%-", " "));
43
					end
44
					return;
45
				end
46
				bare_reply(event, "Title: " .. data:match("<title>(.-)</title>"))
47
			end);
48
		end
49
	end
50
 
51
	bot:hook("message", findYoutubeLink);
52
	bot:hook("groupchat/joining", function (room)
53
		room:hook("message", findYoutubeLink);
54
	end);
55
end