e2ecbc3be5e994d6b5eb348c0bd5b0dddc5d7a44
[prosody.git] / plugins / muc / affiliation_notify.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2014 Daurnimator
3 --
4 -- This project is MIT/X11 licensed. Please see the
5 -- COPYING file in the source package for more information.
6 --
7
8 --[[
9 Out of courtesy, a MUC service MAY send an out-of-room <message/>
10 if a user's affiliation changes while the user is not in the room;
11 the message SHOULD be sent from the room to the user's bare JID,
12 MAY contain a <body/> element describing the affiliation change,
13 and MUST contain a status code of 101.
14 ]]
15
16
17 local st = require "util.stanza";
18
19 local function get_affiliation_notify(room)
20         return room._data.affiliation_notify;
21 end
22
23 local function set_affiliation_notify(room, affiliation_notify)
24         affiliation_notify = affiliation_notify and true or nil;
25         if room._data.affiliation_notify == affiliation_notify then return false; end
26         room._data.affiliation_notify = affiliation_notify;
27         if room.save then room:save(true); end
28         return true;
29 end
30
31 module:hook("muc-config-form", function(event)
32         table.insert(event.form, {
33                 name = "muc#roomconfig_affiliationnotify";
34                 type = "boolean";
35                 label = "Notify users when their affiliation changes when they are not in the room?";
36                 value = get_affiliation_notify(event.room);
37         });
38 end);
39
40 module:hook("muc-config-submitted", function(event)
41         local new = event.fields["muc#roomconfig_affiliationnotify"];
42         if new ~= nil and set_affiliation_notify(event.room, new) then
43                 event.status_codes["104"] = true;
44         end
45 end);
46
47 module:hook("muc-set-affiliation", function(event)
48         local room = event.room;
49         if not event.in_room and get_affiliation_notify(room) then
50                 local body = string.format("Your affiliation in room %s is now %s.", room.jid, event.affiliation);
51                 local stanza = st.message({
52                                 type = "headline";
53                                 from = room.jid;
54                                 to = event.jid;
55                         }, body)
56                         :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
57                                 :tag("status", {code="101"}):up()
58                         :up();
59                 room:route_stanza(stanza);
60         end
61 end);
62
63 return {
64         get = get_affiliation_notify;
65         set = set_affiliation_notify;
66 };