1-- Prosody IM
2-- Copyright (C) 2008-2017 Matthew Wild
3-- Copyright (C) 2008-2017 Waqas Hussain
4-- Copyright (C) 2011-2017 Kim Alvefur
5-- Copyright (C) 2018 Emmanuel Gil Peyrot
6--
7-- This project is MIT/X11 licensed. Please see the
8-- COPYING file in the source package for more information.
9--
10-- XEP-0313: Message Archive Management for Prosody
11--
12
13local st = require"util.stanza";
14local jid_prep = require"util.jid".prep;
15local xmlns_mam = "urn:xmpp:mam:2";
16
17local default_attrs = {
18	always = true, [true] = "always",
19	never = false, [false] = "never",
20	roster = "roster",
21}
22
23local function tostanza(prefs)
24	local default = prefs[false];
25	default = default_attrs[default];
26	local prefstanza = st.stanza("prefs", { xmlns = xmlns_mam, default = default });
27	local always = st.stanza("always");
28	local never = st.stanza("never");
29	for jid, choice in pairs(prefs) do
30		if jid then
31			(choice and always or never):tag("jid"):text(jid):up();
32		end
33	end
34	prefstanza:add_child(always):add_child(never);
35	return prefstanza;
36end
37local function fromstanza(prefstanza)
38	local prefs = {};
39	local default = prefstanza.attr.default;
40	if default then
41		prefs[false] = default_attrs[default];
42	end
43
44	local always = prefstanza:get_child("always");
45	if always then
46		for rule in always:childtags("jid") do
47			local jid = jid_prep(rule:get_text());
48			if jid then
49				prefs[jid] = true;
50			end
51		end
52	end
53
54	local never = prefstanza:get_child("never");
55	if never then
56		for rule in never:childtags("jid") do
57			local jid = jid_prep(rule:get_text());
58			if jid then
59				prefs[jid] = false;
60			end
61		end
62	end
63
64	return prefs;
65end
66
67return {
68	tostanza = tostanza;
69	fromstanza = fromstanza;
70}
71