| 1 | local verse = require "verse"; |
| 2 | |
| 3 | local xmlns_carbons = "urn:xmpp:carbons:2"; |
| 4 | local xmlns_forward = "urn:xmpp:forward:0"; |
| 5 | local os_time = os.time; |
| 6 | local parse_datetime = require "prosody.util.datetime".parse; |
| 7 | local bare_jid = require "prosody.util.jid".bare; |
| 8 | |
| 9 | -- TODO Check disco for support |
| 10 | |
| 11 | function verse.plugins.carbons(stream) |
| 12 | local carbons = {}; |
| 13 | carbons.enabled = false; |
| 14 | stream.carbons = carbons; |
| 15 | |
| 16 | function carbons:enable(callback) |
| 17 | stream:send_iq(verse.iq{type="set"} |
| 18 | :tag("enable", { xmlns = xmlns_carbons }) |
| 19 | , function(result) |
| 20 | local success = result.attr.type == "result"; |
| 21 | if success then |
| 22 | carbons.enabled = true; |
| 23 | end |
| 24 | if callback then |
| 25 | callback(success); |
| 26 | end |
| 27 | end or nil); |
| 28 | end |
| 29 | |
| 30 | function carbons:disable(callback) |
| 31 | stream:send_iq(verse.iq{type="set"} |
| 32 | :tag("disable", { xmlns = xmlns_carbons }) |
| 33 | , function(result) |
| 34 | local success = result.attr.type == "result"; |
| 35 | if success then |
| 36 | carbons.enabled = false; |
| 37 | end |
| 38 | if callback then |
| 39 | callback(success); |
| 40 | end |
| 41 | end or nil); |
| 42 | end |
| 43 | |
| 44 | local my_bare; |
| 45 | stream:hook("bind-success", function() |
| 46 | my_bare = bare_jid(stream.jid); |
| 47 | end); |
| 48 | |
| 49 | stream:hook("message", function(stanza) |
| 50 | local carbon = stanza:get_child(nil, xmlns_carbons); |
| 51 | if stanza.attr.from == my_bare and carbon then |
| 52 | local carbon_dir = carbon.name; |
| 53 | local fwd = carbon:get_child("forwarded", xmlns_forward); |
| 54 | local fwd_stanza = fwd and fwd:get_child("message", "jabber:client"); |
| 55 | local delay = fwd:get_child("delay", "urn:xmpp:delay"); |
| 56 | local stamp = delay and delay.attr.stamp; |
| 57 | stamp = stamp and parse_datetime(stamp); |
| 58 | if fwd_stanza then |
| 59 | return stream:event("carbon", { |
| 60 | dir = carbon_dir, |
| 61 | stanza = fwd_stanza, |
| 62 | timestamp = stamp or os_time(), |
| 63 | }); |
| 64 | end |
| 65 | end |
| 66 | end, 1); |
| 67 | end |