Ejabberd 用Elixir开发一个包过滤模块

过滤模块主要用于

创建一个模块骨架

在Ejabberd源码根目录下的lib目录中创建 filter_packet_demo.ex模块文件, 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
defmodule FilterPacketDemo do
import Ejabberd.Logger
@behaviour :gen_mod

def start(_host, _opts) do
info('Starting ejabberd module Filter Packet Demo')
Ejabberd.Hooks.add(:filter_packet, :global, __ENV__.module, :on_filter_packet, 50)
:ok
end

def stop(_host) do
info('Stopping ejabberd module Filter Packet Demo')
Ejabberd.Hooks.delete(:filter_packet, :global, __ENV__.module, :on_filter_packet, 50)
:ok
end

def on_filter_packet({from, to, xml={:xmlel, "message", attributes, children}} = packet) do
info("Filtering packet: #{inspect {from, to, xml}}")
# 访问XML元素属性
# attributes 是一个形如 [{"type", "chat"}, ...]的元组列表, 为了方便访问, 使用如下函数转换为关键字列表
convert = fn {k,v} ->
{String.to_atom(k), v}
end
attribute_keywords = attributes |> Enum.map convert
type = attribute_keywords[:type]
cond do
type == "chat" ->
dosomething()
type == "headline" ->
dosomething()
type == "groupchat" ->
dosomething()
true ->
true
end
packet
end

def dosomething do
IO.puts "Do something."
end
end

编译,安装,动态更新

1
# 编译
make
make install

启动

1
ejabberdctl live

进入调试控制台

1
ejabberdctl debug

在调试控制台中运行

1
(ejabberd@localhost)1> ejabberd_update:update().
{ok,[]}

参考资料

  1. Elixir Sips: ejabberd with Elixir – Part 2
    https://blog.process-one.net/ejabberd-with-elixir-packet-filters/