comparison mod_muc_media_metadata/mod_muc_media_metadata.lua @ 3682:47e1c94fb6fb

mod_muc_media_metadata: Module to automatically fetch metadata for posted media
author Matthew Wild <mwild1@gmail.com>
date Sun, 29 Sep 2019 16:47:57 +0100
parents
children 26dc8320b81b
comparison
equal deleted inserted replaced
3681:d267e381255f 3682:47e1c94fb6fb
1 local async = require "util.async";
2 local promise = require "util.promise";
3 local http = require "net.http";
4 local st = require "util.stanza";
5
6 local xmlns_metadata = "https://prosody.im/protocol/media-metadata#0"
7
8 local fetch_headers = {
9 bytes = "content-length";
10 type = "content-type";
11 etag = "etag";
12 blurhash = "blurhash";
13 };
14
15 local function fetch_media_metadata(url)
16 return promise.new(function (resolve)
17 http.request(url, { method = "HEAD" }, function (body, code, response) --luacheck: ignore 212/body
18 if code == 200 then
19 local metadata = {};
20 for metadata_name, header_name in pairs(fetch_headers) do
21 metadata[metadata_name] = response.headers[header_name];
22 end
23 resolve(metadata);
24 else
25 resolve(nil);
26 end
27 end);
28 end);
29 end
30
31 local function metadata_to_tag(metadata)
32 if not metadata then return; end
33
34 local metadata_tag = st.stanza("metadata", { xmlns = xmlns_metadata });
35 for k, v in pairs(metadata) do
36 metadata_tag:text_tag(k, v)
37 end
38
39 return metadata_tag;
40 end
41
42 module:hook("muc-occupant-groupchat", function (event)
43 local stanza = event.stanza;
44
45 local promises;
46
47 for oob in stanza:childtags("x", "jabber:x:oob") do
48 if not promises then promises = {}; end
49 local url = oob:get_child_text("url");
50 local p = fetch_media_metadata(url)
51 :next(metadata_to_tag)
52 :next(function (metadata_tag)
53 oob:add_child(metadata_tag);
54 end);
55 table.insert(promises, p);
56 end
57
58 if not promises then return; end
59
60 async.wait(promise.all(promises));
61 end);