plugins/bookmarks.lua

1
local st = require "prosody.util.stanza";
2
 
3
-- set allow_add_bookmarks = true; in config to enable the bookmark command
4
 
5
function riddim.plugins.bookmarks(bot)
6
	local my_bookmarks = {};
7
 
8
	bot.stream:add_plugin("private");
9
 
10
	local function get_bookmarks(callback) 
11
		bot.stream:private_get("storage", "storage:bookmarks", function(storage)
12
			if not storage then
13
				storage = st.tag("storage", { xmlns = "storage:bookmarks" });
14
			end
15
			if callback and type(callback) == "function" then
16
				callback(storage);
17
			end
18
		end);
19
	end
20
 
21
	local function add_bookmark(bookmark, callback)
22
		-- TODO Check if a room is bookmarked already
23
		if not bookmark or type(bookmark) ~= "table" or not bookmark.jid then return end
24
		if not bookmark.name then
25
			bookmark.name = jid.split(bookmark.jid);
26
		end
27
		local nick = bot.config.nick;
28
		if bookmark.nick then
29
			nick = bookmark.nick;
30
			bookmark.nick = nil;
31
		end
32
		get_bookmarks(function(storage)
33
			storage:tag("conference", bookmark)
34
				:tag("nick"):text(nick):up()
35
			:up();
36
			bot.stream:private_set("storage", "storage:bookmarks", storage, callback);
37
		end);
38
	end
39
 
40
	local function join_bookmarked_rooms()
41
		get_bookmarks(function(storage)
42
			for i, room in ipairs(storage) do
43
				if room.name == "conference" and room.attr.jid then
44
					my_bookmarks[room.attr.jid] = true; -- to know which rooms are bookmarked
45
					if room.attr.autojoin == "true" or room.attr.autojoin == "1" then
46
						nick = room:get_child("nick");
47
						nick = nick and nick[1] or nil;
48
						bot:join_room(room.attr.jid, nick);
49
					end
50
					-- TODO Passwords
51
					-- Maybe get the hook in before the groupchat is loaded
52
					-- and add to the bot.config.autojoin variable?
53
				end
54
			end
55
		end);
56
	end
57
 
58
	bot:hook("started", join_bookmarked_rooms);
59
 
60
	if bot.config.allow_add_bookmarks then
61
		bot:hook("commands/bookmark", function(command)
62
			local room = command.param and jid.bare(command.param) or command.room.jid;
63
			if my_bookmarks[room] then return "Already bookmarked" end
64
			my_bookmarks[room] = true;
65
				
66
			add_bookmark({ jid = room, autojoin = "true" }, function() command:reply("Bookmarked " .. room) end);
67
		end);
68
	end
69
 
70
end