view mod_muc_media_metadata/mod_muc_media_metadata.lua @ 4738:5aee8d86629a

mod_bookmarks2: Fix handling of nick and password elements This form of child retrieval fails when the stanza elements internally don't have an 'xmlns' attribute, which can happen sometimes for some reason, including when they have been constructed via the stanza builder API. When that is the case then the explicit namespace arguemnt does not match the nil value of the internal attribute. Calling `:get_child()` without the namespace argument does the right thing here, with both nil and the parent namespace as valid values for the internal attribute.
author Kim Alvefur <zash@zash.se>
date Wed, 03 Nov 2021 21:11:55 +0100
parents d4537f045a78
children
line wrap: on
line source

local async = require "util.async";
local promise = require "util.promise";
local http = require "net.http";
local st = require "util.stanza";

local xmlns_metadata = "xmpp:prosody.im/protocol/media-metadata#0"

local fetch_headers = {
	bytes = "content-length";
	type = "content-type";
	etag = "etag";
	blurhash = "blurhash";
};

local function fetch_media_metadata(url)
	return promise.new(function (resolve)
		http.request(url, { method = "HEAD" }, function (body, code, response) --luacheck: ignore 212/body
			if code == 200 then
				local metadata = {};
				for metadata_name, header_name in pairs(fetch_headers) do
					metadata[metadata_name] = response.headers[header_name];
				end
				resolve(metadata);
			else
				resolve(nil);
			end
		end);
	end);
end

local function metadata_to_tag(metadata)
	if not metadata then return; end

	local metadata_tag = st.stanza("metadata", { xmlns = xmlns_metadata });
	for k, v in pairs(metadata) do
		metadata_tag:text_tag(k, v)
	end

	return metadata_tag;
end

module:hook("muc-occupant-groupchat", function (event)
	local stanza = event.stanza;

	local promises;

	for oob in stanza:childtags("x", "jabber:x:oob") do
		if not promises then promises = {}; end
		local url = oob:get_child_text("url");
		local p = fetch_media_metadata(url)
			:next(metadata_to_tag)
			:next(function (metadata_tag)
				oob:add_child(metadata_tag);
			end);
		table.insert(promises, p);
	end

	if not promises then return; end

	async.wait(promise.all(promises));
end);