view mod_groups_internal/README.md @ 6299:5cf5ee23b361

mod_voipms: New Module to send and receive SMS/MMS via VoIP.ms APIs. diff --git a/mod_voipms/README.md b/mod_voipms/README.md new file mode 100644 --- /dev/null +++ b/mod_voipms/README.md @@ -0,0 +1,51 @@ +--- +labels: +- 'Stage-Alpha' +- 'Type-Web' +summary: Send and receive SMS/MMS via VoIP.ms APIs. +rockspec: + build: + modules: + mod_voipms: mod_voipms.lua +... + +Introduction +============ + +This is a Prosody module to map JIDs to DIDs on VoIP.ms and support sending/receiving SMS/MMS. + +Configuration +============= + +| option | type | default | +|-----------------------|--------|---------| +| voipms\_api\_username | string | nil | +| voipms\_api\_password | string | nil | +| voipms\_query\_key | string | nil | +| voipms\_jid\_map | table | nil | +``` +VirtualHost "sms.example.com" +modules_enabled = { + "voipms"; +} +voipms_api_username = john@example.com -- E-mail registered with VoIP.ms +voipms_api_password = abcd1234 -- API password configured in VoIP.ms +voipms_query_key = some_query_key -- query param 'key' part of your URL callback +voipms_jid_map = { + ["your_jid@your_domain.com"] = "+1234567890" +} +``` + +HTTP +==== + +The module is served on Prosody's default HTTP ports at the path /voipms. More details on configuring HTTP modules in Prosody can be found in the HTTP documentation. + +VoIP.ms Webhook URL +=================== + +This module receives the VoIP.ms Webhook URL (POST) at the /voipms endpoint. It uses the sendSMS/sendMMS GET methods against the VoIP.ms APIs. This is an example webhook to use in VoIP.ms: + +``` +https://sms.example.com/voipms?key=some_query_key +``` diff --git a/mod_voipms/mod_voipms.lua b/mod_voipms/mod_voipms.lua new file mode 100644 --- /dev/null +++ b/mod_voipms/mod_voipms.lua @@ -0,0 +1,166 @@ +local http = require "net.http" +local json = require "util.json" +local st = require "util.stanza" + +local api_username = module:get_option_string("voipms_api_username") +local api_password = module:get_option_string("voipms_api_password") +local query_key = module:get_option("voipms_query_key") +local jid_map = module:get_option("voipms_jid_map") or {} +local rest_endpoint = "https://voip.ms/api/v1/rest.php" + +if not api_username or not api_password or not query_key then + module:log("error", "Missing required config values (voipms_api_username, voipms_api_password, voipms_query_key)") + return +end + +module:depends("http") + +local function normalize_number(num) + if not num then return nil end + if num:sub(1, 1) ~= "+" then + return "+1" .. num + end + return num +end + +local function extract_query_key(event) + return (event.request.url.query or ""):match("key=([^&]+)") +end + +module:provides("http", { + route = { + ["POST"] = function(event) + local req = event.request + local body = req.body or "" + + if extract_query_key(event) ~= query_key then + module:log("warn", "Unauthorized webhook: missing or invalid key") + return { status_code = 403 } + end + + local json_payload, err = json.decode(body) + if not json_payload then + module:log("warn", "Invalid JSON: %s", err or "unknown error") + return { status_code = 400 } + end + + local payload = json_payload.data and json_payload.data.payload + if not payload then + module:log("warn", "Missing payload in JSON") + return { status_code = 400 } + end + + local from = payload.from and payload.from.phone_number + local to_list = payload.to or {} + local to = #to_list > 0 and to_list[1].phone_number or nil + + if not from or not to then + module:log("warn", "Missing phone numbers (from: %s, to: %s)", tostring(from), tostring(to)) + return { status_code = 400 } + end + + local normalized_to = normalize_number(to) + local target_jid = nil + + for jid, did in pairs(jid_map) do + if normalize_number(did) == normalized_to then + target_jid = jid + break + end + end + + if not target_jid then + module:log("warn", "No JID mapping for DID %s", normalized_to) + return { status_code = 404 } + end + + local normalized_from = normalize_number(from) + local message_text = payload.text or "" + + local message = st.message({ + from = normalized_from .. "@" .. module.host, + to = target_jid, + type = "chat" + }):tag("body"):text(message_text):up() + + if payload.media and #payload.media > 0 then + for _, media_item in ipairs(payload.media) do + if media_item.url then + message_text = message_text .. "\n" .. media_item.url + message:tag("x", { xmlns = "jabber:x:oob" }) + :tag("url"):text(media_item.url):up():up() + end + end + end + + module:send(message) + module:log("info", "Delivered SMS from %s to %s", normalized_from, target_jid) + + return { status_code = 204 } + end + } +}) + +module:hook("message/bare", function(event) + local stanza = event.stanza + if stanza.attr.type ~= "chat" then return end + + local from_jid = stanza.attr.from + local to_jid = stanza.attr.to + local body = stanza:get_child_text("body") + if not body or body == "" then return end + + local from_number = jid_map[from_jid] + if not from_number then + module:log("warn", "No DID mapping for JID %s", from_jid) + return + end + + local to_number = to_jid:match("^([^@]+)") + if not to_number then + module:log("warn", "Malformed JID in message.to: %s", to_jid) + return + end + + to_number = normalize_number(to_number) + + local media_urls = {} + for line in body:gmatch("[^\r\n]+") do + if line:match("^https?://") then + table.insert(media_urls, line) + end + end + + local method = (#media_urls > 0) and "sendMMS" or "sendSMS" + local query = { + api_username = api_username, + api_password = api_password, + method = method, + did = from_number, + dst = to_number, + message = body + } + + if method == "sendMMS" then + for i, url in ipairs(media_urls) do + query["media_url[" .. (i - 1) .. "]"] = url + end + end + + local query_str = http.formencode(query) + + http.request(rest_endpoint .. "?" .. query_str, { + method = "GET"; + }, function(response_body, code) + if code == 200 then + local resp, err = json.decode(response_body) + if not resp or resp.status ~= "success" then + module:log("error", "Failed to send %s: %s", method, err or (resp and resp.status) or "unknown") + else + module:log("info", "Sent %s from %s to %s", method, from_number, to_number) + end + else + module:log("error", "HTTP error sending %s: code %s", method, tostring(code)) + end + end) +end)
author Chaz <menel@snikket.de>
date Mon, 21 Jul 2025 23:57:37 +0200
parents d0a117e11cb8
children
line wrap: on
line source

---
labels:
- 'Stage-Beta'
summary: Equivalent of mod_groups but without a configuration file
---

## Introduction

This module is functionally similar to [`mod_groups`], but it differs by working without a configuration file (allowing changes without a restart of the server) and by permanently adding users to each other's contact lists. To paraphrase [`mod_groups`]:

> `mod_groups_internal` was designed to allow administrators to create virtual groups of users that automatically see each other in their contact lists. There is no need for the user to authorise these contacts in their contact list - this is done automatically on the server.
>
> As an example, if you have a team of people working together on a project, you can create a group for that team. They will automatically be added to each others' contact lists, and the list can easily be modified on the server at any time to add and remove people.

::: {.alert .alert-info}
On `user-deleted` events, `mod_groups_internal` will automatically remove the deleted user from every group they were part of.
:::

## Setup

```lua
modules_enabled = {
    -- Other modules
    "groups_internal"; -- Enable mod_groups_internal
}
```

## Configuration

| Option | Type | Default | Notes |
| ------ | ---- | ------- | ----- |
| `groups_muc_host` | string? | nil | Host where the group chats will be created. |

## Usage

### Exposed functions

- #### `create(group_info, create_default_muc, group_id)` {#create}

  Creates a new group, optionally creating a default MUC chat on [`groups_muc_host`](#configuration).

  **Parameters:**

  1. `group_info: { name: string }`
  2. `create_default_muc: boolean | nil`: Whether or not to create the default MUC chat. Defaults to `false`.
  3. `group_id: string | nil`: The desired group JID node part. Defaults to [`util.id.short`](https://prosody.im/doc/developers/util/id) (9-chars URL-safe base64).

  **Returns:** `group_id: string | nil, error: string`

- #### `get_info(group_id)` {#get_info}

  Retrieves information about a group.

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.

  **Returns:**

  ```lua
  group_info: {
    name: string,
    muc_jid: string | nil
  }
  | nil
  ```

- #### `set_info(group_id, info)` {#set_info}

  Allows one to change a group's name. If `muc_jid` is specified, this function will also update the group chat's name.

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.
  2. `group_info: { name: string, muc_jid: string | nil }`

  **Returns:** `true | nil, error: string`

- #### `get_members(group_id)` {#get_members}

  Retrieves the list of members in a given group.

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.

  **Returns:** `group_members: {string}`

- #### `exists(group_id)` {#exists}

  Returns whether or not a group exists.

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.

  **Returns:** `group_exists: boolean`

- #### `get_user_groups(username)` {#get_user_groups}

  Lists which groups a given user is a part of.

  **Parameters:**

  1. `username: string`: Node part of the user's JID.

  **Returns:** `user_groups: {string}`

- #### `delete(group_id)` {#delete}

  Deletes a given group and its associated group chats.

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.

  **Returns:** `true | nil, error: string`

- #### `add_member(group_id, username, delay_update)` {#add_member}

  Adds a member to a given group, optionally delaying subscriptions until [`sync`](#sync) is called.

  ::: {.alert .alert-info}
  This function emits a [`group-user-added`](#group-user-added) event on successful execution.
  :::

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.
  2. `delay_update: boolean | nil`: Do not update subscriptions until [`sync`](#sync) is called. Defaults to `false`.

  **Returns:** `true | nil, error: string`

- #### `remove_member(group_id, username)` {#remove_member}

  Removes a member from a given group.

  ::: {.alert .alert-info}
  This function emits a [`group-user-removed`](#group-user-removed) event on successful execution.
  :::

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.
  2. `username: string`: Node part of the user's JID.

  **Returns:** `true | nil, error: string`

- #### `sync(group_id)` {#sync}

  Updates group subscriptions (used to apply pending changes from [`add_member`](#add_member)).

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.

  **Returns:** `nil`

- #### `add_group_chat(group_id, name)` {#add_group_chat}

  Creates a new group chat for a given group.

  ::: {.alert .alert-info}
  Its JID will be `<`[`util.id.short`](https://prosody.im/doc/developers/util/id)`>@<`[`option:groups_muc_host`](#configuration)`>`.
  :::

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.
  2. `name: string`: Desired name of the group chat.

  **Returns:**

  ```lua
  muc: {
    jid: string,
    name: string,
  }
  | nil, error: string
  ```

- #### `remove_group_chat(group_id, muc_id)` {#remove_group_chat}

  Removes a group chat for a given group.

  ::: {.alert .alert-info}
  This function emits a [`group-chat-removed`](#group-chat-removed) event on successful execution.
  :::

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.
  2. `muc_id: string`: Node part of the MUC JID.

  **Returns:** `true | nil, error: string`

- #### `get_group_chats(group_id)` {#get_group_chats}

  Lists group chats associated to a given group.

  ::: {.alert .alert-warning}
  Make sure to check the `deleted` property on each chat as this function might return information about deleted chats.
  :::

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.

  **Returns:**

  ```lua
  group_chats: {
    {
      id: string, -- muc_id (node part of the MUC JID)
      jid: string,
      name: string,
      deleted: boolean,
    }
  }
  | nil
  ```

- #### `emit_member_events(group_id)` {#emit_member_events}

  Emits [`group-user-added`](#group-user-added) events for every member of a group.

  **Parameters:**

  1. `group_id: string`: Node part of the group's JID.

  **Returns:** `true | false, error: string`

- #### `groups()` {#groups}

  Returns info about all groups (for every `group_id` key, the value is the equivalent of calling `get_info(group_id)`).

  **Returns:**

  ```lua
  groups: {
    <group_id>: {
      name: string,
      muc_jid: string | nil
    }
  }
  ```

  (Where `<group_id>` is a

### Emitted events {#events}

- #### `group-user-added` {#group-user-added}

  Emitted on successful [`add_member`](#add_member) and on [`emit_member_events`](#emit_member_events).

  **Payload structure:**

  ```lua
  {
    id: string, -- group_id (node part of the group's JID)
    user: string, -- username (node part of the user's JID)
    host: string, -- <module.host>
    group_info: {
      name: string,
      muc_jid: string | nil,
      mucs: {string} | nil,
    },
  }
  ```

- #### `group-user-removed` {#group-user-removed}

  Emitted on successful [`remove_member`](#remove_member).

  **Payload structure:**

  ```lua
  {
    id: string, -- group_id (node part of the group's JID)
    user: string, -- username (node part of the user's JID)
    host: string, -- <module.host>
    group_info: {
      name: string,
      muc_jid: string | nil,
      mucs: {string} | nil,
    },
  }
  ```

- #### `group-chat-added` {#group-chat-added}

  Emitted on successful [`add_group_chat`](#add_group_chat).

  **Payload structure:**

  ```lua
  {
    group_id: string,
    group_info: {
      name: string,
      mucs: {string},
    },
    muc: {
      jid: string,
      name: string,
    },
  }
  ```

- #### `group-chat-removed` {#group-chat-removed}

  Emitted on successful [`remove_group_chat`](#remove_group_chat).

  **Payload structure:**

  ```lua
  {
    group_id: string, -- group_id (node part of the group's JID)
    group_info: {
      name: string,
      mucs: {string},
    },
    muc: {
      id: string, -- muc_id (node part of the MUC JID)
      jid: string,
    },
  }
  ```

[`mod_groups`]: https://prosody.im/doc/modules/mod_groups "mod_groups – Prosody IM"