clix/presence.lua

1
local verse = require "verse";
2
local presence_values = { online = "1", chat = "2", away = "3", xa = "4", dnd = "5", offline = "6" };
3
 
4
return function (opts)
5
	if opts.short_help then
6
		print("Display Presence Status");
7
		return;
8
	end
9
	local DELIM = opts.delim or "\t";
10
	local function on_presence(presence)
11
		local pres_num = presence_values.offline;
12
		local pres_str;
13
		if presence.attr.type then
14
			if presence.attr.type == "unavailable" then
15
				pres_str = "show=" .. presence.attr.type .. DELIM .. DELIM;
16
			else
17
				return;	-- Ignore all other presence type's
18
			end
19
		else
20
			local show = presence:get_child("show");
21
			local priority = presence:get_child("priority");
22
			local status = presence:get_child("status");
23
			local show_str = show and show:get_text():lower() or "online";
24
			pres_str = "show=" .. show_str;
25
			pres_num = presence_values[show_str] or pres_num;
26
			if priority then
27
				pres_str = pres_str .. DELIM .. "priority=" .. priority:get_text();
28
			else
29
				pres_str = pres_str .. DELIM;
30
			end
31
			if status then
32
				local status_str = status:get_text();
33
				-- sanitize status string
34
				status_str = status_str:gsub("\n", " "):gsub("[\r"..DELIM.."]", "");
35
				pres_str = pres_str .. DELIM .. "status=" .. status_str;
36
			else
37
				pres_str = pres_str .. DELIM;
38
			end
39
		end
40
		if presence.attr.from then
41
			if opts.to then
42
				if opts.to:find("/", 1, true) and opts.to ~= presence.attr.from then
43
					return;	-- Ignore non-exact match when --to= is defined with a resource
44
				elseif opts.to ~= presence.attr.from:sub(1, #opts.to) then
45
					return;	-- Ignore non-matching JID when --to= is defined without a resource
46
				end
47
			end
48
			pres_str = pres_str .. DELIM .. "from=" .. presence.attr.from;
49
		else
50
			pres_str = pres_str .. DELIM;
51
		end
52
		pres_str = pres_num .. DELIM .. pres_str .. DELIM;
53
		print(pres_str);
54
	end
55
	local function on_connect(conn)
56
		conn:hook("presence", on_presence);
57
		if opts.to then
58
			conn:send(verse.presence{to=opts.to, type="probe"});
59
		end
60
		if not tonumber(opts.close_delay) then
61
			opts.close_delay = 1;
62
		end
63
		conn:close();
64
	end
65
	clix_connect(opts, on_connect);
66
end