aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorKim Alvefur <zash@zash.se>2022-08-17 19:04:30 +0200
committerKim Alvefur <zash@zash.se>2022-08-17 19:04:30 +0200
commit8959868a28fb74e55ce41a9cb93d7e3524c7dc2b (patch)
treee167e55ba83a8eb91210348f33a042d84ef34daf
parent2294d8b8e08fbf75985bd976bc32c79293a478ef (diff)
downloadprosody-8959868a28fb74e55ce41a9cb93d7e3524c7dc2b.tar.gz
prosody-8959868a28fb74e55ce41a9cb93d7e3524c7dc2b.zip
util.stanza: Add method for extracting a single attribute value
Sometimes you only care about a single attribute, but the child tag itself may be optional, leading to needing `tag and tag.attr.foo` or `stanza:find("tag@foo")`. The `:find()` method is fairly complex, so avoiding it for this kind of simpler use case is a win.
-rw-r--r--plugins/mod_pubsub/pubsub.lib.lua3
-rw-r--r--spec/util_dataforms_spec.lua2
-rw-r--r--util/stanza.lua8
3 files changed, 10 insertions, 3 deletions
diff --git a/plugins/mod_pubsub/pubsub.lib.lua b/plugins/mod_pubsub/pubsub.lib.lua
index 661bb65b..cd3efb09 100644
--- a/plugins/mod_pubsub/pubsub.lib.lua
+++ b/plugins/mod_pubsub/pubsub.lib.lua
@@ -678,8 +678,7 @@ end
function handlers.set_retract(origin, stanza, retract, service)
local node, notify = retract.attr.node, retract.attr.notify;
notify = (notify == "1") or (notify == "true");
- local item = retract:get_child("item");
- local id = item and item.attr.id
+ local id = retract:get_child_attr("item", nil, "id");
if not (node and id) then
origin.send(pubsub_error_reply(stanza, node and "item-not-found" or "nodeid-required"));
return true;
diff --git a/spec/util_dataforms_spec.lua b/spec/util_dataforms_spec.lua
index 5293238a..ab402fdb 100644
--- a/spec/util_dataforms_spec.lua
+++ b/spec/util_dataforms_spec.lua
@@ -130,7 +130,7 @@ describe("util.dataforms", function ()
assert.truthy(st.is_stanza(xform));
assert.equal("x", xform.name);
assert.equal("jabber:x:data", xform.attr.xmlns);
- assert.equal("FORM_TYPE", xform:find("field@var"));
+ assert.equal("FORM_TYPE", xform:get_child_attr("field", nil, "var"));
assert.equal("xmpp:prosody.im/spec/util.dataforms#1", xform:find("field/value#"));
local allowed_direct_children = {
title = true,
diff --git a/util/stanza.lua b/util/stanza.lua
index a14be5f0..b75a1f32 100644
--- a/util/stanza.lua
+++ b/util/stanza.lua
@@ -176,6 +176,14 @@ function stanza_mt:get_child_text(name, xmlns)
return nil;
end
+function stanza_mt:get_child_attr(name, xmlns, attr)
+ local tag = self:get_child(name, xmlns);
+ if tag then
+ return tag.attr[attr];
+ end
+ return nil;
+end
+
function stanza_mt:child_with_name(name)
for _, child in ipairs(self.tags) do
if child.name == name then return child; end