diff --git a/docs/configuring-playbook-bridge-mautrix-discord.md b/docs/configuring-playbook-bridge-mautrix-discord.md new file mode 100644 index 000000000..73c762a8c --- /dev/null +++ b/docs/configuring-playbook-bridge-mautrix-discord.md @@ -0,0 +1,43 @@ +# Setting up Mautrix Discord (optional) + +The playbook can install and configure [mautrix-discord](https://github.com/mautrix/discord) for you. + +See the project's [documentation](https://docs.mau.fi/bridges/go/discord/index.html) to learn what it does and why it might be useful to you. + +Use the following playbook configuration: + +```yaml +matrix_mautrix_discord_enabled: true +``` + +## Set up Double Puppeting + +If you'd like to use [Double Puppeting](https://docs.mau.fi/bridges/general/double-puppeting.html) (hint: you most likely do), you have 2 ways of going about it. + +### Method 1: automatically, by enabling Shared Secret Auth + +The bridge will automatically perform Double Puppeting if you enable [Shared Secret Auth](configuring-playbook-shared-secret-auth.md) for this playbook. + +This is the recommended way of setting up Double Puppeting, as it's easier to accomplish, works for all your users automatically, and has less of a chance of breaking in the future. + +### Method 2: manually, by asking each user to provide a working access token + +**Note**: This method for enabling Double Puppeting can be configured only after you've already set up bridging (see [Usage](#usage)). + +When using this method, **each user** that wishes to enable Double Puppeting needs to follow the following steps: + +- retrieve a Matrix access token for yourself. You can use the following command: + +``` +curl \ +--data '{"identifier": {"type": "m.id.user", "user": "YOUR_MATRIX_USERNAME" }, "password": "YOUR_MATRIX_PASSWORD", "type": "m.login.password", "device_id": "Mautrix-Discord", "initial_device_display_name": "Mautrix-Discord"}' \ +https://matrix.DOMAIN/_matrix/client/r0/login +``` + +- send the access token to the bot. Example: `login-matrix MATRIX_ACCESS_TOKEN_HERE` + +- make sure you don't log out the `Mautrix-Discord` device some time in the future, as that would break the Double Puppeting feature + +## Usage + +You then need to start a chat with `@discordbot:YOUR_DOMAIN` (where `YOUR_DOMAIN` is your base domain, not the `matrix.` domain). diff --git a/docs/configuring-playbook.md b/docs/configuring-playbook.md index 88f81607d..1e1719017 100644 --- a/docs/configuring-playbook.md +++ b/docs/configuring-playbook.md @@ -92,6 +92,8 @@ When you're done with all the configuration you'd like to do, continue with [Ins ### Bridging other networks +- [Setting up Mautrix Discord bridging](configuring-playbook-bridge-mautrix-discord.md) (optional) + - [Setting up Mautrix Telegram bridging](configuring-playbook-bridge-mautrix-telegram.md) (optional) - [Setting up Mautrix Whatsapp bridging](configuring-playbook-bridge-mautrix-whatsapp.md) (optional) diff --git a/group_vars/matrix_servers b/group_vars/matrix_servers index ea17edb40..1d52c3ad2 100755 --- a/group_vars/matrix_servers +++ b/group_vars/matrix_servers @@ -624,6 +624,44 @@ matrix_mautrix_whatsapp_database_password: "{{ '%s' | format(matrix_homeserver_g # ###################################################################### +###################################################################### +# +# matrix-bridge-mautrix-discord +# +###################################################################### + +# We don't enable bridges by default. +matrix_mautrix_discord_enabled: false + +matrix_mautrix_discord_container_image_self_build: "{{ matrix_architecture not in ['arm64', 'amd64'] }}" + +matrix_mautrix_discord_systemd_required_services_list: | + {{ + ['docker.service'] + + + ['matrix-' + matrix_homeserver_implementation + '.service'] + + + (['matrix-postgres.service'] if matrix_postgres_enabled else []) + + + (['matrix-nginx-proxy.service'] if matrix_nginx_proxy_enabled else []) + }} + +matrix_mautrix_discord_appservice_token: "{{ '%s' | format(matrix_homeserver_generic_secret_key) | password_hash('sha512', 'maudiscord.as.token') | to_uuid }}" + +matrix_mautrix_discord_homeserver_token: "{{ '%s' | format(matrix_homeserver_generic_secret_key) | password_hash('sha512', 'maudiscord.hs.token') | to_uuid }}" + +matrix_mautrix_discord_login_shared_secret: "{{ matrix_synapse_ext_password_provider_shared_secret_auth_shared_secret if matrix_synapse_ext_password_provider_shared_secret_auth_enabled else '' }}" + +# Postgres is the default, except if not using `matrix_postgres` (internal postgres) +matrix_mautrix_discord_database_engine: "{{ 'postgres' if matrix_postgres_enabled else 'sqlite' }}" +matrix_mautrix_discord_database_password: "{{ '%s' | format(matrix_homeserver_generic_secret_key) | password_hash('sha512', 'maudiscord.db') | to_uuid }}" + +###################################################################### +# +# /matrix-bridge-mautrix-discord +# +###################################################################### + ###################################################################### # # matrix-sms-bridge @@ -1871,6 +1909,12 @@ matrix_postgres_additional_databases: | 'password': matrix_mautrix_whatsapp_database_password, }] if (matrix_mautrix_whatsapp_enabled and matrix_mautrix_whatsapp_database_engine == 'postgres' and matrix_mautrix_whatsapp_database_hostname == 'matrix-postgres') else []) + + ([{ + 'name': matrix_mautrix_discord_database_name, + 'username': matrix_mautrix_discord_database_username, + 'password': matrix_mautrix_discord_database_password, + }] if (matrix_mautrix_discord_enabled and matrix_mautrix_discord_database_engine == 'postgres' and matrix_mautrix_discord_database_hostname == 'matrix-postgres') else []) + + ([{ 'name': matrix_mx_puppet_slack_database_name, 'username': matrix_mx_puppet_slack_database_username, diff --git a/roles/matrix-bridge-mautrix-discord/defaults/main.yml b/roles/matrix-bridge-mautrix-discord/defaults/main.yml new file mode 100644 index 000000000..a1ff83cd2 --- /dev/null +++ b/roles/matrix-bridge-mautrix-discord/defaults/main.yml @@ -0,0 +1,136 @@ +--- +# mautrix-discord is a Matrix <-> Discord bridge +# Project source code URL: https://github.com/mautrix/discord + +matrix_mautrix_discord_enabled: true + +matrix_mautrix_discord_container_image_self_build: false +matrix_mautrix_discord_container_image_self_build_repo: "https://mau.dev/mautrix/discord.git" +matrix_mautrix_discord_container_image_self_build_branch: "{{ 'main' if matrix_mautrix_discord_version == 'latest' else matrix_mautrix_discord_version }}" + +matrix_mautrix_discord_version: latest +# See: https://mau.dev/mautrix/discord/container_registry +matrix_mautrix_discord_docker_image: "{{ matrix_mautrix_discord_docker_image_name_prefix }}mautrix/discord:{{ matrix_mautrix_discord_version }}" +matrix_mautrix_discord_docker_image_name_prefix: "{{ 'localhost/' if matrix_mautrix_discord_container_image_self_build else 'dock.mau.dev/' }}" +matrix_mautrix_discord_docker_image_force_pull: "{{ matrix_mautrix_discord_docker_image.endswith(':latest') }}" + +matrix_mautrix_discord_base_path: "{{ matrix_base_data_path }}/mautrix-discord" +matrix_mautrix_discord_config_path: "{{ matrix_mautrix_discord_base_path }}/config" +matrix_mautrix_discord_data_path: "{{ matrix_mautrix_discord_base_path }}/data" +matrix_mautrix_discord_docker_src_files_path: "{{ matrix_mautrix_discord_base_path }}/docker-src" + +matrix_mautrix_discord_homeserver_address: "{{ matrix_homeserver_container_url }}" +matrix_mautrix_discord_homeserver_domain: "{{ matrix_domain }}" +matrix_mautrix_discord_appservice_address: "http://matrix-mautrix-discord:8080" + +matrix_mautrix_discord_command_prefix: "!discord" + +# A list of extra arguments to pass to the container +matrix_mautrix_discord_container_extra_arguments: [] + +# List of systemd services that matrix-mautrix-discord.service depends on. +matrix_mautrix_discord_systemd_required_services_list: ['docker.service'] + +# List of systemd services that matrix-mautrix-discord.service wants +matrix_mautrix_discord_systemd_wanted_services_list: [] + +matrix_mautrix_discord_appservice_token: '' +matrix_mautrix_discord_homeserver_token: '' + +matrix_mautrix_discord_appservice_bot_username: discordbot + +# Minimum severity of journal log messages. +# Options: debug, info, warn, error, fatal +matrix_mautrix_discord_logging_level: 'warn' + +# Whether or not created rooms should have federation enabled. +# If false, created portal rooms will never be federated. +matrix_mautrix_discord_federate_rooms: true + +# Database-related configuration fields. +# +# To use SQLite, stick to these defaults. +# +# To use Postgres: +# - change the engine (`matrix_mautrix_discord_database_engine: 'postgres'`) +# - adjust your database credentials via the `matrix_mautrix_discord_database_*` variables +matrix_mautrix_discord_database_engine: 'sqlite' + +matrix_mautrix_discord_sqlite_database_path_local: "{{ matrix_mautrix_discord_data_path }}/mautrix-discord.db" +matrix_mautrix_discord_sqlite_database_path_in_container: "/data/mautrix-discord.db" + +matrix_mautrix_discord_database_username: 'matrix_mautrix_discord' +matrix_mautrix_discord_database_password: 'some-password' +matrix_mautrix_discord_database_hostname: 'matrix-postgres' +matrix_mautrix_discord_database_port: 5432 +matrix_mautrix_discord_database_name: 'matrix_mautrix_discord' + +matrix_mautrix_discord_database_connection_string: 'postgresql://{{ matrix_mautrix_discord_database_username }}:{{ matrix_mautrix_discord_database_password }}@{{ matrix_mautrix_discord_database_hostname }}:{{ matrix_mautrix_discord_database_port }}/{{ matrix_mautrix_discord_database_name }}?sslmode=disable' + +matrix_mautrix_discord_appservice_database_type: "{{ + { + 'sqlite': 'sqlite3', + 'postgres':'postgres', + }[matrix_mautrix_discord_database_engine] +}}" + +matrix_mautrix_discord_appservice_database_uri: "{{ + { + 'sqlite': matrix_mautrix_discord_sqlite_database_path_in_container, + 'postgres': matrix_mautrix_discord_database_connection_string, + }[matrix_mautrix_discord_database_engine] +}}" + +# Can be set to enable automatic double-puppeting via Shared Secret Auth (https://github.com/devture/matrix-synapse-shared-secret-auth). +matrix_mautrix_discord_login_shared_secret: '' +matrix_mautrix_discord_bridge_login_shared_secret_map: + "{{ {matrix_mautrix_discord_homeserver_domain: matrix_mautrix_discord_login_shared_secret} if matrix_mautrix_discord_login_shared_secret else {} }}" + +# Servers to always allow double puppeting from +matrix_mautrix_discord_bridge_double_puppet_server_map: + "{{ matrix_mautrix_discord_homeserver_domain : matrix_mautrix_discord_homeserver_address }}" + +# Default mautrix-discord configuration template which covers the generic use case. +# You can customize it by controlling the various variables inside it. +# +# For a more advanced customization, you can extend the default (see `matrix_mautrix_discord_configuration_extension_yaml`) +# or completely replace this variable with your own template. +matrix_mautrix_discord_configuration_yaml: "{{ lookup('template', 'templates/config.yaml.j2') }}" + +matrix_mautrix_discord_configuration_extension_yaml: | + # Your custom YAML configuration goes here. + # This configuration extends the default starting configuration (`matrix_mautrix_discord_configuration_yaml`). + # + # You can override individual variables from the default configuration, or introduce new ones. + # + # If you need something more special, you can take full control by + # completely redefining `matrix_mautrix_discord_configuration_yaml`. + +matrix_mautrix_discord_configuration_extension: "{{ matrix_mautrix_discord_configuration_extension_yaml | from_yaml if matrix_mautrix_discord_configuration_extension_yaml | from_yaml is mapping else {} }}" + +# Holds the final configuration (a combination of the default and its extension). +# You most likely don't need to touch this variable. Instead, see `matrix_mautrix_discord_configuration_yaml`. +matrix_mautrix_discord_configuration: "{{ matrix_mautrix_discord_configuration_yaml | from_yaml | combine(matrix_mautrix_discord_configuration_extension, recursive=True) }}" + +matrix_mautrix_discord_registration_yaml: | + id: discord + url: {{ matrix_mautrix_discord_appservice_address }} + as_token: "{{ matrix_mautrix_discord_appservice_token }}" + hs_token: "{{ matrix_mautrix_discord_homeserver_token }}" + # See https://github.com/mautrix/signal/issues/43 + sender_localpart: _bot_{{ matrix_mautrix_discord_appservice_bot_username }} + rate_limited: false + namespaces: + users: + - regex: '^@discord_[0-9]+:{{ matrix_mautrix_discord_homeserver_domain | regex_escape }}$' + exclusive: true + - exclusive: true + regex: '^@{{ matrix_mautrix_discord_appservice_bot_username | regex_escape }}:{{ matrix_mautrix_discord_homeserver_domain | regex_escape }}$' + de.sorunome.msc2409.push_ephemeral: true + +matrix_mautrix_discord_registration: "{{ matrix_mautrix_discord_registration_yaml | from_yaml }}" + +# Enable End-to-bridge encryption +matrix_mautrix_discord_bridge_encryption_allow: false +matrix_mautrix_discord_bridge_encryption_default: "{{ matrix_mautrix_discord_bridge_encryption_allow }}" +matrix_mautrix_discord_bridge_encryption_key_sharing_allow: "{{ matrix_mautrix_discord_bridge_encryption_allow }}" diff --git a/roles/matrix-bridge-mautrix-discord/tasks/init.yml b/roles/matrix-bridge-mautrix-discord/tasks/init.yml new file mode 100644 index 000000000..30baf0178 --- /dev/null +++ b/roles/matrix-bridge-mautrix-discord/tasks/init.yml @@ -0,0 +1,21 @@ +--- +- ansible.builtin.set_fact: + matrix_systemd_services_list: "{{ matrix_systemd_services_list + ['matrix-mautrix-discord.service'] }}" + when: matrix_mautrix_discord_enabled | bool + +# If the matrix-synapse role is not used, these variables may not exist. +- ansible.builtin.set_fact: + matrix_synapse_container_extra_arguments: > + {{ + matrix_synapse_container_extra_arguments | default([]) + + + ["--mount type=bind,src={{ matrix_mautrix_discord_config_path }}/registration.yaml,dst=/matrix-mautrix-discord-registration.yaml,ro"] + }} + + matrix_synapse_app_service_config_files: > + {{ + matrix_synapse_app_service_config_files | default([]) + + + ["/matrix-mautrix-discord-registration.yaml"] + }} + when: matrix_mautrix_discord_enabled | bool diff --git a/roles/matrix-bridge-mautrix-discord/tasks/main.yml b/roles/matrix-bridge-mautrix-discord/tasks/main.yml new file mode 100644 index 000000000..9eaadf684 --- /dev/null +++ b/roles/matrix-bridge-mautrix-discord/tasks/main.yml @@ -0,0 +1,22 @@ +--- +- ansible.builtin.import_tasks: "{{ role_path }}/tasks/init.yml" + tags: + - always + +- ansible.builtin.import_tasks: "{{ role_path }}/tasks/validate_config.yml" + when: "run_setup | bool and matrix_mautrix_discord_enabled | bool" + tags: + - setup-all + - setup-mautrix-discord + +- ansible.builtin.import_tasks: "{{ role_path }}/tasks/setup_install.yml" + when: "run_setup and matrix_mautrix_discord_enabled" + tags: + - setup-all + - setup-mautrix-discord + +- ansible.builtin.import_tasks: "{{ role_path }}/tasks/setup_uninstall.yml" + when: "run_setup and not matrix_mautrix_discord_enabled" + tags: + - setup-all + - setup-mautrix-discord diff --git a/roles/matrix-bridge-mautrix-discord/tasks/setup_install.yml b/roles/matrix-bridge-mautrix-discord/tasks/setup_install.yml new file mode 100644 index 000000000..935371ef7 --- /dev/null +++ b/roles/matrix-bridge-mautrix-discord/tasks/setup_install.yml @@ -0,0 +1,149 @@ +--- + +# If the matrix-synapse role is not used, `matrix_synapse_role_executed` won't exist. +# We don't want to fail in such cases. +- name: Fail if matrix-synapse role already executed + ansible.builtin.fail: + msg: >- + The matrix-bridge-mautrix-discord role needs to execute before the matrix-synapse role. + when: "matrix_synapse_role_executed | default(False)" + +- ansible.builtin.set_fact: + matrix_mautrix_discord_requires_restart: false + +- block: + - name: Check if an SQLite database already exists + ansible.builtin.stat: + path: "{{ matrix_mautrix_discord_sqlite_database_path_local }}" + register: matrix_mautrix_discord_sqlite_database_path_local_stat_result + + - block: + - ansible.builtin.set_fact: + matrix_postgres_db_migration_request: + src: "{{ matrix_mautrix_discord_sqlite_database_path_local }}" + dst: "{{ matrix_mautrix_discord_database_connection_string }}" + caller: "{{ role_path | basename }}" + engine_variable_name: 'matrix_mautrix_discord_database_engine' + engine_old: 'sqlite' + systemd_services_to_stop: ['matrix-mautrix-discord.service'] + pgloader_options: ['--with "quote identifiers"'] + + - ansible.builtin.import_role: + name: matrix-postgres + tasks_from: migrate_db_to_postgres + + - ansible.builtin.set_fact: + matrix_mautrix_discord_requires_restart: true + when: "matrix_mautrix_discord_sqlite_database_path_local_stat_result.stat.exists | bool" + when: "matrix_mautrix_discord_database_engine == 'postgres'" + + +- name: Ensure Mautrix Discord paths exists + ansible.builtin.file: + path: "{{ item.path }}" + state: directory + mode: 0750 + owner: "{{ matrix_user_username }}" + group: "{{ matrix_user_groupname }}" + with_items: + - {path: "{{ matrix_mautrix_discord_base_path }}", when: true} + - {path: "{{ matrix_mautrix_discord_config_path }}", when: true} + - {path: "{{ matrix_mautrix_discord_data_path }}", when: true} + - {path: "{{ matrix_mautrix_discord_docker_src_files_path }}", when: "{{ matrix_mautrix_discord_container_image_self_build }}"} + when: item.when | bool + +- name: Ensure Mautrix Discord image is pulled + docker_image: + name: "{{ matrix_mautrix_discord_docker_image }}" + source: "{{ 'pull' if ansible_version.major > 2 or ansible_version.minor > 7 else omit }}" + force_source: "{{ matrix_mautrix_discord_docker_image_force_pull if ansible_version.major > 2 or ansible_version.minor >= 8 else omit }}" + force: "{{ omit if ansible_version.major > 2 or ansible_version.minor >= 8 else matrix_mautrix_discord_docker_image_force_pull }}" + when: not matrix_mautrix_discord_container_image_self_build + register: result + retries: "{{ matrix_container_retries_count }}" + delay: "{{ matrix_container_retries_delay }}" + until: result is not failed + +- name: Ensure Mautrix discord repository is present on self-build + ansible.builtin.git: + repo: "{{ matrix_mautrix_discord_container_image_self_build_repo }}" + dest: "{{ matrix_mautrix_discord_docker_src_files_path }}" + version: "{{ matrix_mautrix_discord_container_image_self_build_branch }}" + force: "yes" + become: true + become_user: "{{ matrix_user_username }}" + register: matrix_mautrix_discord_git_pull_results + when: "matrix_mautrix_discord_container_image_self_build | bool" + +- name: Ensure Mautrix discord Docker image is built + docker_image: + name: "{{ matrix_mautrix_discord_docker_image }}" + source: build + force_source: "{{ matrix_mautrix_discord_git_pull_results.changed if ansible_version.major > 2 or ansible_version.minor >= 8 else omit }}" + force: "{{ omit if ansible_version.major > 2 or ansible_version.minor >= 8 else matrix_mautrix_discord_git_pull_results.changed }}" + build: + dockerfile: Dockerfile + path: "{{ matrix_mautrix_discord_docker_src_files_path }}" + pull: true + when: "matrix_mautrix_discord_container_image_self_build | bool" + +- name: Check if an old database file exists + ansible.builtin.stat: + path: "{{ matrix_mautrix_discord_base_path }}/mautrix-discord.db" + register: matrix_mautrix_discord_stat_database + +- name: Check if an old matrix state file exists + ansible.builtin.stat: + path: "{{ matrix_mautrix_discord_base_path }}/mx-state.json" + register: matrix_mautrix_discord_stat_mx_state + +- name: (Data relocation) Ensure matrix-mautrix-discord.service is stopped + ansible.builtin.service: + name: matrix-mautrix-discord + state: stopped + enabled: false + daemon_reload: true + failed_when: false + when: "matrix_mautrix_discord_stat_database.stat.exists" + +- name: (Data relocation) Move mautrix-discord database file to ./data directory + ansible.builtin.command: "mv {{ matrix_mautrix_discord_base_path }}/mautrix-discord.db {{ matrix_mautrix_discord_data_path }}/mautrix-discord.db" + when: "matrix_mautrix_discord_stat_database.stat.exists" + +- name: (Data relocation) Move mautrix-discord mx-state file to ./data directory + ansible.builtin.command: "mv {{ matrix_mautrix_discord_base_path }}/mx-state.json {{ matrix_mautrix_discord_data_path }}/mx-state.json" + when: "matrix_mautrix_discord_stat_mx_state.stat.exists" + +- name: Ensure mautrix-discord config.yaml installed + ansible.builtin.copy: + content: "{{ matrix_mautrix_discord_configuration | to_nice_yaml(indent=2, width=999999) }}" + dest: "{{ matrix_mautrix_discord_config_path }}/config.yaml" + mode: 0644 + owner: "{{ matrix_user_username }}" + group: "{{ matrix_user_groupname }}" + +- name: Ensure mautrix-discord registration.yaml installed + ansible.builtin.copy: + content: "{{ matrix_mautrix_discord_registration | to_nice_yaml(indent=2, width=999999) }}" + dest: "{{ matrix_mautrix_discord_config_path }}/registration.yaml" + mode: 0644 + owner: "{{ matrix_user_username }}" + group: "{{ matrix_user_groupname }}" + +- name: Ensure matrix-mautrix-discord.service installed + ansible.builtin.template: + src: "{{ role_path }}/templates/systemd/matrix-mautrix-discord.service.j2" + dest: "{{ matrix_systemd_path }}/matrix-mautrix-discord.service" + mode: 0644 + register: matrix_mautrix_discord_systemd_service_result + +- name: Ensure systemd reloaded after matrix-mautrix-discord.service installation + ansible.builtin.service: + daemon_reload: true + when: "matrix_mautrix_discord_systemd_service_result.changed" + +- name: Ensure matrix-mautrix-discord.service restarted, if necessary + ansible.builtin.service: + name: "matrix-mautrix-discord.service" + state: restarted + when: "matrix_mautrix_discord_requires_restart | bool" diff --git a/roles/matrix-bridge-mautrix-discord/tasks/setup_uninstall.yml b/roles/matrix-bridge-mautrix-discord/tasks/setup_uninstall.yml new file mode 100644 index 000000000..94fef89a2 --- /dev/null +++ b/roles/matrix-bridge-mautrix-discord/tasks/setup_uninstall.yml @@ -0,0 +1,25 @@ +--- + +- name: Check existence of matrix-mautrix-discord service + ansible.builtin.stat: + path: "{{ matrix_systemd_path }}/matrix-mautrix-discord.service" + register: matrix_mautrix_discord_service_stat + +- name: Ensure matrix-mautrix-discord is stopped + ansible.builtin.service: + name: matrix-mautrix-discord + state: stopped + enabled: false + daemon_reload: true + when: "matrix_mautrix_discord_service_stat.stat.exists" + +- name: Ensure matrix-mautrix-discord.service doesn't exist + ansible.builtin.file: + path: "{{ matrix_systemd_path }}/matrix-mautrix-discord.service" + state: absent + when: "matrix_mautrix_discord_service_stat.stat.exists" + +- name: Ensure systemd reloaded after matrix-mautrix-discord.service removal + ansible.builtin.service: + daemon_reload: true + when: "matrix_mautrix_discord_service_stat.stat.exists" diff --git a/roles/matrix-bridge-mautrix-discord/tasks/validate_config.yml b/roles/matrix-bridge-mautrix-discord/tasks/validate_config.yml new file mode 100644 index 000000000..ddf785243 --- /dev/null +++ b/roles/matrix-bridge-mautrix-discord/tasks/validate_config.yml @@ -0,0 +1,20 @@ +--- + +- name: Fail if required settings not defined + ansible.builtin.fail: + msg: >- + You need to define a required configuration setting (`{{ item }}`). + when: "vars[item] == ''" + with_items: + - "matrix_mautrix_discord_appservice_token" + - "matrix_mautrix_discord_homeserver_token" + + +- name: (Deprecation) Catch and report renamed settings + ansible.builtin.fail: + msg: >- + Your configuration contains a variable, which now has a different name. + Please change your configuration to rename the variable (`{{ item.old }}` -> `{{ item.new }}`). + when: "item.old in vars" + with_items: + - {'old': 'matrix_mautrix_discord_log_level', 'new': 'matrix_mautrix_discord_logging_level'} diff --git a/roles/matrix-bridge-mautrix-discord/templates/config.yaml.j2 b/roles/matrix-bridge-mautrix-discord/templates/config.yaml.j2 new file mode 100644 index 000000000..fb10b1ac5 --- /dev/null +++ b/roles/matrix-bridge-mautrix-discord/templates/config.yaml.j2 @@ -0,0 +1,225 @@ +#jinja2: lstrip_blocks: "True" +# Homeserver details. +homeserver: + # The address that this appservice can use to connect to the homeserver. + address: {{ matrix_mautrix_discord_homeserver_address }} + # The domain of the homeserver (for MXIDs, etc). + domain: {{ matrix_mautrix_discord_homeserver_domain }} + # Is the homeserver actually mautrix-asmux? + asmux: false + # The URL to push real-time bridge status to. + # If set, the bridge will make POST requests to this URL whenever a user's discord connection state changes. + # The bridge will use the appservice as_token to authorize requests. + status_endpoint: null + # Endpoint for reporting per-message status. + message_send_checkpoint_endpoint: null + # Does the homeserver support https://github.com/matrix-org/matrix-spec-proposals/pull/2246? + async_media: false + +# Application service host/registration related details. +# Changing these values requires regeneration of the registration. +appservice: + # The address that the homeserver can use to connect to this appservice. + address: {{ matrix_mautrix_discord_appservice_address }} + + # The hostname and port where this appservice should listen. + hostname: 0.0.0.0 + port: 8080 + + # Database config. + database: + # The database type. "sqlite3" and "postgres" are supported. + type: {{ matrix_mautrix_discord_appservice_database_type|to_json }} + # The database URI. + # SQLite: File name is enough. https://github.com/mattn/go-sqlite3#connection-string + # Postgres: Connection string. For example, postgres://user:password@host/database?sslmode=disable + # To connect via Unix socket, use something like postgres:///dbname?host=/var/run/postgresql + uri: {{ matrix_mautrix_discord_appservice_database_uri|to_json }} + # Maximum number of connections. Mostly relevant for Postgres. + max_open_conns: 20 + max_idle_conns: 2 + # Maximum connection idle time and lifetime before they're closed. Disabled if null. + # Parsed with https://pkg.go.dev/time#ParseDuration + max_conn_idle_time: null + max_conn_lifetime: null + + # The unique ID of this appservice. + id: discord + # Appservice bot details. + bot: + # Username of the appservice bot. + username: {{ matrix_mautrix_discord_appservice_bot_username|to_json }} + # Display name and avatar for bot. Set to "remove" to remove display name/avatar, leave empty + # to leave display name/avatar as-is. + displayname: Discord bridge bot + avatar: mxc://maunium.net/nIdEykemnwdisvHbpxflpDlC + # Whether or not to receive ephemeral events via appservice transactions. + # Requires MSC2409 support (i.e. Synapse 1.22+). + ephemeral_events: true + + # Authentication tokens for AS <-> HS communication. Autogenerated; do not modify. + as_token: "{{ matrix_mautrix_discord_appservice_token }}" + hs_token: "{{ matrix_mautrix_discord_homeserver_token }}" + +# Bridge config +bridge: + # Localpart template of MXIDs for Discord users. + # {{ '{{.}}' }} is replaced with the internal ID of the Discord user. + username_template: "{{ 'discord_{{.}}' }}" + # Displayname template for Discord users. This is also used as the room name in DMs if private_chat_portal_meta is enabled. + # Available variables: + # {{ '{{.ID}}' }} - Internal user ID + # {{ '{{.Username}}' }} - User's displayname on Discord + # {{ '{{.Discriminator}}' }} - The 4 numbers after the name on Discord + # {{ '{{.Bot}}' }} - Whether the user is a bot + # {{ '{{.System}}' }} - Whether the user is an official system user + displayname_template: "{{ '{{.Username}} {{if .Bot}} (bot){{end}}' }}" + # Displayname template for Discord channels (bridged as rooms, or spaces when type=4). + # Available variables: + # {{ '{{.Name}}' }} - Channel name, or user displayname (pre-formatted with displayname_template) in DMs. + # {{ '{{.ParentName}}' }} - Parent channel name (used for categories). + # {{ '{{.GuildName}}' }} - Guild name. + # {{ '{{.NSFW}}' }} - Whether the channel is marked as NSFW. + # {{ '{{.Type}}' }} - Channel type (see values at https://github.com/bwmarrin/discordgo/blob/v0.25.0/structs.go#L251-L267) + channel_name_template: "{{ '{{if or (eq .Type 3) (eq .Type 4)}}{{.Name}}{{else}}#{{.Name}}{{end}}' }}" + # Displayname template for Discord guilds (bridged as spaces). + # Available variables: + # {{ '{{.Name}}' }} - Guild name + guild_name_template: "{{ '{{.Name}}' }}" + # Should the bridge explicitly set the avatar and room name for DM portal rooms? + # This is implicitly enabled in encrypted rooms. + private_chat_portal_meta: false + portal_message_buffer: 128 + # Number of private channel portals to create on bridge startup. + # Other portals will be created when receiving messages. + startup_private_channel_create_limit: 5 + # Should the bridge send a read receipt from the bridge bot when a message has been sent to Discord? + delivery_receipts: false + # Whether the bridge should send the message status as a custom com.beeper.message_send_status event. + message_status_events: true + # Whether the bridge should send error notices via m.notice events when a message fails to bridge. + message_error_notices: true + # Should the bridge use space-restricted join rules instead of invite-only for guild rooms? + # This can avoid unnecessary invite events in guild rooms when members are synced in. + restricted_rooms: true + # Should the bridge update the m.direct account data event when double puppeting is enabled. + # Note that updating the m.direct event is not atomic (except with mautrix-asmux) + # and is therefore prone to race conditions. + sync_direct_chat_list: false + # Set this to true to tell the bridge to re-send m.bridge events to all rooms on the next run. + # This field will automatically be changed back to false after it, except if the config file is not writable. + resend_bridge_info: false + # Should the bridge attempt to completely delete portal rooms when a channel is deleted on Discord? + # If true, the bridge will try to kick Matrix users from the room. Otherwise, the bridge only makes ghosts leave. + delete_portal_on_channel_delete: false + # Whether or not created rooms should have federation enabled. + # If false, created portal rooms will never be federated. + federate_rooms: {{ matrix_mautrix_discord_federate_rooms|to_json }} + # Servers to always allow double puppeting from + double_puppet_server_map: + "{{ matrix_mautrix_discord_homeserver_domain }}": {{ matrix_mautrix_discord_homeserver_address }} + # Allow using double puppeting from any server with a valid client .well-known file. + double_puppet_allow_discovery: false + # Shared secrets for https://github.com/devture/matrix-synapse-shared-secret-auth + # + # If set, double puppeting will be enabled automatically for local users + # instead of users having to find an access token and run `login-matrix` + # manually. + login_shared_secret_map: {{ matrix_mautrix_discord_bridge_login_shared_secret_map|to_json }} + + # The prefix for commands. Only required in non-management rooms. + command_prefix: "{{ matrix_mautrix_discord_command_prefix }}" + + # Messages sent upon joining a management room. + # Markdown is supported. The defaults are listed below. + management_room_text: + # Sent when joining a room. + welcome: "Hello, I'm a Discord bridge bot." + # Sent when joining a management room and the user is already logged in. + welcome_connected: "Use `help` for help." + # Sent when joining a management room and the user is not logged in. + welcome_unconnected: "Use `help` for help or `login` to log in." + # Optional extra text sent when joining a management room. + additional_help: "" + + # End-to-bridge encryption support options. + # + # See https://docs.mau.fi/bridges/general/end-to-bridge-encryption.html for more info. + encryption: + # Allow encryption, work in group chat rooms with e2ee enabled + allow: {{ matrix_mautrix_discord_bridge_encryption_allow|to_json }} + # Default to encryption, force-enable encryption in all portals the bridge creates + # This will cause the bridge bot to be in private chats for the encryption to work properly. + default: {{ matrix_mautrix_discord_bridge_encryption_default|to_json }} + # Require encryption, drop any unencrypted messages. + require: false + # Enable key sharing? If enabled, key requests for rooms where users are in will be fulfilled. + # You must use a client that supports requesting keys from other users to use this feature. + allow_key_sharing: {{ matrix_mautrix_discord_bridge_encryption_key_sharing_allow|to_json }} + # What level of device verification should be required from users? + # + # Valid levels: + # unverified - Send keys to all device in the room. + # cross-signed-untrusted - Require valid cross-signing, but trust all cross-signing keys. + # cross-signed-tofu - Require valid cross-signing, trust cross-signing keys on first use (and reject changes). + # cross-signed-verified - Require valid cross-signing, plus a valid user signature from the bridge bot. + # Note that creating user signatures from the bridge bot is not currently possible. + # verified - Require manual per-device verification + # (currently only possible by modifying the `trust` column in the `crypto_device` database table). + verification_levels: + # Minimum level for which the bridge should send keys to when bridging messages from WhatsApp to Matrix. + receive: unverified + # Minimum level that the bridge should accept for incoming Matrix messages. + send: unverified + # Minimum level that the bridge should require for accepting key requests. + share: cross-signed-tofu + # Options for Megolm room key rotation. These options allow you to + # configure the m.room.encryption event content. See: + # https://spec.matrix.org/v1.3/client-server-api/#mroomencryption for + # more information about that event. + rotation: + # Enable custom Megolm room key rotation settings. Note that these + # settings will only apply to rooms created after this option is + # set. + enable_custom: false + # The maximum number of milliseconds a session should be used + # before changing it. The Matrix spec recommends 604800000 (a week) + # as the default. + milliseconds: 604800000 + # The maximum number of messages that should be sent with a given a + # session before changing it. The Matrix spec recommends 100 as the + # default. + messages: 100 + + # Settings for provisioning API + provisioning: + # Prefix for the provisioning API paths. + prefix: /_matrix/provision + # Shared secret for authentication. If set to "generate", a random secret will be generated, + # or if set to "disable", the provisioning API will be disabled. + shared_secret: generate + + # Permissions for using the bridge. + # Permitted values: + # relay - Talk through the relaybot (if enabled), no access otherwise + # user - Access to use the bridge to chat with a Discord account. + # admin - User level and some additional administration tools + # Permitted keys: + # * - All Matrix users + # domain - All users on that homeserver + # mxid - Specific user + permissions: + "{{ matrix_mautrix_discord_homeserver_domain }}": user + {% if matrix_admin %} + "{{ matrix_admin }}": admin + {% endif %} + +logging: + directory: ./logs + file_name_format: '' + file_date_format: "2006-01-02" + file_mode: 384 + timestamp_format: Jan _2, 2006 15:04:05 + print_level: {{ matrix_mautrix_discord_logging_level }} + print_json: false + file_json: false diff --git a/roles/matrix-bridge-mautrix-discord/templates/systemd/matrix-mautrix-discord.service.j2 b/roles/matrix-bridge-mautrix-discord/templates/systemd/matrix-mautrix-discord.service.j2 new file mode 100644 index 000000000..76046b441 --- /dev/null +++ b/roles/matrix-bridge-mautrix-discord/templates/systemd/matrix-mautrix-discord.service.j2 @@ -0,0 +1,43 @@ +#jinja2: lstrip_blocks: "True" +[Unit] +Description=Matrix Mautrix Discord bridge +{% for service in matrix_mautrix_discord_systemd_required_services_list %} +Requires={{ service }} +After={{ service }} +{% endfor %} +{% for service in matrix_mautrix_discord_systemd_wanted_services_list %} +Wants={{ service }} +{% endfor %} +DefaultDependencies=no + +[Service] +Type=simple +Environment="HOME={{ matrix_systemd_unit_home_path }}" +ExecStartPre=-{{ matrix_host_command_sh }} -c '{{ matrix_host_command_docker }} kill matrix-mautrix-discord 2>/dev/null || true' +ExecStartPre=-{{ matrix_host_command_sh }} -c '{{ matrix_host_command_docker }} rm matrix-mautrix-discord 2>/dev/null || true' + +# Intentional delay, so that the homeserver (we likely depend on) can manage to start. +ExecStartPre={{ matrix_host_command_sleep }} 5 + +ExecStart={{ matrix_host_command_docker }} run --rm --name matrix-mautrix-discord \ + --log-driver=none \ + --user={{ matrix_user_uid }}:{{ matrix_user_gid }} \ + --cap-drop=ALL \ + --network={{ matrix_docker_network }} \ + -v {{ matrix_mautrix_discord_config_path }}:/config:z \ + -v {{ matrix_mautrix_discord_data_path }}:/data:z \ + --workdir=/data \ + {% for arg in matrix_mautrix_discord_container_extra_arguments %} + {{ arg }} \ + {% endfor %} + {{ matrix_mautrix_discord_docker_image }} \ + /usr/bin/mautrix-discord -c /config/config.yaml -r /config/registration.yaml + +ExecStop=-{{ matrix_host_command_sh }} -c '{{ matrix_host_command_docker }} kill matrix-mautrix-discord 2>/dev/null || true' +ExecStop=-{{ matrix_host_command_sh }} -c '{{ matrix_host_command_docker }} rm matrix-mautrix-discord 2>/dev/null || true' +Restart=always +RestartSec=30 +SyslogIdentifier=matrix-mautrix-discord + +[Install] +WantedBy=multi-user.target diff --git a/setup.yml b/setup.yml index 49612a8cd..60d40346d 100755 --- a/setup.yml +++ b/setup.yml @@ -27,6 +27,7 @@ - matrix-bridge-mautrix-signal - matrix-bridge-mautrix-telegram - matrix-bridge-mautrix-whatsapp + - matrix-bridge-mautrix-discord - matrix-bridge-mx-puppet-discord - matrix-bridge-mx-puppet-groupme - matrix-bridge-mx-puppet-steam