From 5c0d90e813c19334761b76185f9bfa0475139019 Mon Sep 17 00:00:00 2001 From: Tobias Diez Date: Mon, 25 Mar 2024 10:55:16 +0800 Subject: [PATCH] Add wechat bridge --- group_vars/matrix_servers | 58 ++++ .../matrix-bridge-go-wechat/defaults/main.yml | 150 +++++++++++ .../matrix-bridge-go-wechat/tasks/main.yml | 20 ++ .../tasks/setup_install.yml | 179 +++++++++++++ .../tasks/setup_uninstall.yml | 39 +++ .../tasks/validate_config.yml | 18 ++ .../templates/config.yaml.j2 | 249 ++++++++++++++++++ .../systemd/matrix-go-wechat-agent.service.j2 | 45 ++++ .../systemd/matrix-go-wechat.service.j2 | 48 ++++ setup.yml | 1 + 10 files changed, 807 insertions(+) create mode 100644 roles/custom/matrix-bridge-go-wechat/defaults/main.yml create mode 100644 roles/custom/matrix-bridge-go-wechat/tasks/main.yml create mode 100644 roles/custom/matrix-bridge-go-wechat/tasks/setup_install.yml create mode 100644 roles/custom/matrix-bridge-go-wechat/tasks/setup_uninstall.yml create mode 100644 roles/custom/matrix-bridge-go-wechat/tasks/validate_config.yml create mode 100644 roles/custom/matrix-bridge-go-wechat/templates/config.yaml.j2 create mode 100644 roles/custom/matrix-bridge-go-wechat/templates/systemd/matrix-go-wechat-agent.service.j2 create mode 100644 roles/custom/matrix-bridge-go-wechat/templates/systemd/matrix-go-wechat.service.j2 diff --git a/group_vars/matrix_servers b/group_vars/matrix_servers index 1ee9226d8..50acdcd32 100755 --- a/group_vars/matrix_servers +++ b/group_vars/matrix_servers @@ -85,6 +85,8 @@ matrix_homeserver_container_extra_arguments_auto: | + (['--mount type=bind,src=' + matrix_go_skype_bridge_config_path + '/registration.yaml,dst=/matrix-go-skype-bridge-registration.yaml,ro'] if matrix_go_skype_bridge_enabled else []) + + (['--mount type=bind,src=' + matrix_go_wechat_config_path + '/registration.yaml,dst=/matrix-go-wechat-registration.yaml,ro'] if matrix_go_wechat_enabled else []) + + (['--mount type=bind,src=' + matrix_heisenbridge_base_path + '/registration.yaml,dst=/heisenbridge-registration.yaml,ro'] if matrix_heisenbridge_enabled else []) + (['--mount type=bind,src=' + matrix_hookshot_base_path + '/registration.yml,dst=/hookshot-registration.yml,ro'] if matrix_hookshot_enabled else []) @@ -154,6 +156,8 @@ matrix_homeserver_app_service_config_files_auto: | + (['/matrix-go-skype-bridge-registration.yaml'] if matrix_go_skype_bridge_enabled else []) + + (['/matrix-go-wechat-registration.yaml'] if matrix_go_wechat_enabled else []) + + (['/heisenbridge-registration.yaml'] if matrix_heisenbridge_enabled else []) + (['/hookshot-registration.yml'] if matrix_hookshot_enabled else []) @@ -290,6 +294,10 @@ devture_systemd_service_manager_services_list_auto: | + ([{'name': 'matrix-go-skype-bridge.service', 'priority': 2000, 'groups': ['matrix', 'bridges', 'go-skype']}] if matrix_go_skype_bridge_enabled else []) + + ([{'name': 'matrix-go-wechat.service', 'priority': 2000, 'groups': ['matrix', 'bridges', 'go-wechat']}] if matrix_go_wechat_enabled else []) + + + ([{'name': 'matrix-go-wechat-agent.service', 'priority': 2000, 'groups': ['matrix', 'bridges', 'go-wechat']}] if matrix_go_wechat_enabled else []) + + ([{'name': 'matrix-heisenbridge.service', 'priority': 2000, 'groups': ['matrix', 'bridges', 'heisenbridge']}] if matrix_heisenbridge_enabled else []) + ([{'name': 'matrix-hookshot.service', 'priority': 2000, 'groups': ['matrix', 'bridges', 'hookshot', 'bridge-hookshot']}] if matrix_hookshot_enabled else []) @@ -1709,6 +1717,50 @@ matrix_mautrix_wsproxy_syncproxy_database_password: "{{ '%s' | format(matrix_hom # ###################################################################### +###################################################################### +# +# matrix-bridge-go-wechat +# +###################################################################### + +# We don't enable bridges by default. +matrix_go_wechat_enabled: false + +matrix_go_wechat_systemd_required_services_list_auto: | + {{ + matrix_addons_homeserver_systemd_services_list + + + ([devture_postgres_identifier ~ '.service'] if (devture_postgres_enabled and matrix_go_wechat_database_hostname == devture_postgres_connection_hostname) else []) + }} + +matrix_go_wechat_container_image_self_build: "{{ matrix_architecture not in ['amd64', 'arm64'] }}" + +matrix_go_wechat_agent_container_image_self_build: "{{ matrix_architecture not in ['amd64', 'arm64'] }}" + +matrix_go_wechat_container_network: "{{ matrix_addons_container_network }}" + +matrix_go_wechat_container_additional_networks_auto: |- + {{ + ( + ([] if matrix_addons_homeserver_container_network == '' else [matrix_addons_homeserver_container_network]) + + + ([devture_postgres_container_network] if (devture_postgres_enabled and matrix_go_wechat_database_hostname == devture_postgres_connection_hostname and matrix_go_wechat_container_network != devture_postgres_container_network) else []) + ) | unique + }} + +matrix_go_wechat_appservice_token: "{{ '%s' | format(matrix_homeserver_generic_secret_key) | password_hash('sha512', 'wechat.as.token', rounds=655555) | to_uuid }}" + +matrix_go_wechat_homeserver_address: "{{ matrix_addons_homeserver_client_api_url }}" +matrix_go_wechat_homeserver_token: "{{ '%s' | format(matrix_homeserver_generic_secret_key) | password_hash('sha512', 'wechat.hs.token', rounds=655555) | to_uuid }}" + +matrix_go_wechat_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 internal Postgres server +matrix_go_wechat_database_engine: "{{ 'postgres' if devture_postgres_enabled else 'sqlite' }}" +matrix_go_wechat_database_hostname: "{{ devture_postgres_connection_hostname if devture_postgres_enabled else '' }}" +matrix_go_wechat_database_password: "{{ '%s' | format(matrix_homeserver_generic_secret_key) | password_hash('sha512', 'gowechat.db', rounds=655555) | to_uuid }}" + + ###################################################################### # # matrix-bridge-mautrix-whatsapp @@ -3680,6 +3732,12 @@ devture_postgres_managed_databases_auto: | 'password': matrix_go_skype_bridge_database_password, }] if (matrix_go_skype_bridge_enabled and matrix_go_skype_bridge_database_engine == 'postgres' and matrix_go_skype_bridge_database_hostname == devture_postgres_connection_hostname) else []) + + ([{ + 'name': matrix_go_wechat_database_name, + 'username': matrix_go_wechat_database_username, + 'password': matrix_go_wechat_database_password, + }] if (matrix_go_wechat_enabled and matrix_go_wechat_database_engine == 'postgres' and matrix_go_wechat_database_hostname == devture_postgres_connection_hostname) else []) + + ([{ 'name': matrix_mautrix_facebook_database_name, 'username': matrix_mautrix_facebook_database_username, diff --git a/roles/custom/matrix-bridge-go-wechat/defaults/main.yml b/roles/custom/matrix-bridge-go-wechat/defaults/main.yml new file mode 100644 index 000000000..8765adba0 --- /dev/null +++ b/roles/custom/matrix-bridge-go-wechat/defaults/main.yml @@ -0,0 +1,150 @@ +--- +# Go WeChat Bridge is a Matrix <-> WeChat bridge +# Project source code URL: https://github.com/duo/matrix-wechat + +matrix_go_wechat_enabled: true + +matrix_go_wechat_container_image_self_build: false +matrix_go_wechat_container_image_self_build_repo: "https://github.com/duo/matrix-wechat.git" +matrix_go_wechat_container_image_self_build_branch: "{{ 'master' if matrix_go_wechat_version == 'latest' else matrix_go_wechat_version }}" +matrix_go_wechat_agent_container_image_self_build: true +matrix_go_wechat_agent_container_image_self_build_repo: "https://github.com/duo/matrix-wechat-agent.git" +matrix_go_wechat_agent_container_image_self_build_branch: "{{ 'master' if matrix_go_wechat_version == 'latest' else matrix_go_wechat_version }}" + +# renovate: datasource=docker depName=lxduo/matrix-wechat +matrix_go_wechat_version: latest +matrix_go_wechat_docker_image: "{{ matrix_go_wechat_docker_image_name_prefix }}lxduo/matrix-wechat:{{ matrix_go_wechat_version }}" +matrix_go_wechat_agent_docker_image: "{{ matrix_go_wechat_agent_docker_image_name_prefix }}lxduo/matrix-wechat-agent:{{ matrix_go_wechat_version }}" +matrix_go_wechat_docker_image_name_prefix: "{{ 'localhost/' if matrix_go_wechat_container_image_self_build else matrix_container_global_registry_prefix }}" +matrix_go_wechat_agent_docker_image_name_prefix: "{{ 'localhost/' if matrix_go_wechat_agent_container_image_self_build else matrix_container_global_registry_prefix }}" +matrix_go_wechat_docker_image_force_pull: "{{ matrix_go_wechat_docker_image.endswith(':latest') }}" +matrix_go_wechat_agent_docker_image_force_pull: "{{ matrix_go_wechat_agent_docker_image.endswith(':latest') }}" + +matrix_go_wechat_base_path: "{{ matrix_base_data_path }}/go-wechat" +matrix_go_wechat_config_path: "{{ matrix_go_wechat_base_path }}/config" +matrix_go_wechat_data_path: "{{ matrix_go_wechat_base_path }}/data" +matrix_go_wechat_docker_src_files_path: "{{ matrix_go_wechat_base_path }}/docker-src" +matrix_go_wechat_agent_docker_src_files_path: "{{ matrix_go_wechat_base_path }}/docker-agent-src" + +matrix_go_wechat_homeserver_address: "" +matrix_go_wechat_homeserver_domain: "{{ matrix_domain }}" +matrix_go_wechat_appservice_address: 'http://matrix-go-wechat:8080' + +matrix_go_wechat_container_network: "" + +matrix_go_wechat_container_additional_networks: "{{ matrix_go_wechat_container_additional_networks_auto + matrix_go_wechat_container_additional_networks_custom }}" +matrix_go_wechat_container_additional_networks_auto: [] +matrix_go_wechat_container_additional_networks_custom: [] + +# A list of extra arguments to pass to the container +matrix_go_wechat_container_extra_arguments: [] + +# List of systemd services that matrix-go-wechat.service depends on. +matrix_go_wechat_systemd_required_services_list: "{{ matrix_go_wechat_systemd_required_services_list_default + matrix_go_wechat_systemd_required_services_list_auto + matrix_go_wechat_systemd_required_services_list_custom }}" +matrix_go_wechat_systemd_required_services_list_default: ['docker.service'] +matrix_go_wechat_systemd_required_services_list_auto: [] +matrix_go_wechat_systemd_required_services_list_custom: [] + +# List of systemd services that matrix-go-wechat.service wants +matrix_go_wechat_systemd_wanted_services_list: [] + +matrix_go_wechat_appservice_token: '' +matrix_go_wechat_homeserver_token: '' + +matrix_go_wechat_appservice_bot_username: wechatbot + +matrix_go_wechat_command_prefix: "!wechat" + +# Whether or not created rooms should have federation enabled. +# If false, created portal rooms will never be federated. +matrix_go_wechat_federate_rooms: true + +# Database-related configuration fields. +matrix_go_wechat_database_engine: 'postgres' +matrix_go_wechat_database_username: 'matrix_go_wechat' +matrix_go_wechat_database_password: 'some-password' +matrix_go_wechat_database_hostname: '' +matrix_go_wechat_database_port: 5432 +matrix_go_wechat_database_name: 'matrix_go_wechat' +matrix_go_wechat_database_sslmode: disable +matrix_go_wechat_database_connection_string: 'postgresql://{{ matrix_go_wechat_database_username }}:{{ matrix_go_wechat_database_password }}@{{ matrix_go_wechat_database_hostname }}:{{ matrix_go_wechat_database_port }}/{{ matrix_go_wechat_database_name }}?sslmode={{ matrix_go_wechat_database_sslmode }}' + +# Can be set to enable automatic double-puppeting via Shared Secret Auth (https://github.com/devture/matrix-synapse-shared-secret-auth). +matrix_go_wechat_login_shared_secret: '' +matrix_go_wechat_login_shared_secret_map: + "{{ {matrix_go_wechat_homeserver_domain: matrix_go_wechat_login_shared_secret} if matrix_go_wechat_login_shared_secret else {} }}" + +# Servers to always allow double puppeting from +matrix_go_wechat_double_puppet_server_map: + "{{ matrix_go_wechat_homeserver_domain : matrix_go_wechat_homeserver_address }}" + +# Enable End-to-bridge encryption +matrix_go_wechat_encryption_allow: "{{ matrix_bridges_encryption_enabled }}" +matrix_go_wechat_encryption_default: "{{ matrix_go_wechat_encryption_allow }}" + +# Minimum severity of journal log messages. +# Options: debug, info, warn, error, fatal +matrix_go_wechat_log_level: 'warn' + +matrix_go_wechat_permissions: | + {{ + {matrix_go_wechat_homeserver_domain: 'user'} + | combine({matrix_admin: 'admin'} if matrix_admin else {}) + }} + +# Default go-wechat 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_go_wechat_configuration_extension_yaml`) +# or completely replace this variable with your own template. +matrix_go_wechat_configuration_yaml: "{{ lookup('template', 'templates/config.yaml.j2') }}" + +matrix_go_wechat_configuration_extension_yaml: | + # Your custom YAML configuration goes here. + # This configuration extends the default starting configuration (`matrix_go_wechat_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_go_wechat_configuration_yaml`. + +matrix_go_wechat_configuration_extension: "{{ matrix_go_wechat_configuration_extension_yaml | from_yaml if matrix_go_wechat_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_go_wechat_configuration_yaml`. +matrix_go_wechat_configuration: "{{ matrix_go_wechat_configuration_yaml | from_yaml | combine(matrix_go_wechat_configuration_extension, recursive=True) }}" + +matrix_go_wechat_registration_yaml: | + id: wechat + url: {{ matrix_go_wechat_appservice_address }} + as_token: "{{ matrix_go_wechat_appservice_token }}" + hs_token: "{{ matrix_go_wechat_homeserver_token }}" + # See https://github.com/mautrix/signal/issues/43 + sender_localpart: _bot_{{ matrix_go_wechat_appservice_bot_username }} + rate_limited: false + namespaces: + users: + - regex: '^@_wechat_(.*):{{ matrix_go_wechat_homeserver_domain | regex_escape }}$' + exclusive: true + - exclusive: true + regex: '^@{{ matrix_go_wechat_appservice_bot_username | regex_escape }}:{{ matrix_go_wechat_homeserver_domain | regex_escape }}$' + de.sorunome.msc2409.push_ephemeral: true + +matrix_go_wechat_registration: "{{ matrix_go_wechat_registration_yaml | from_yaml }}" + +matrix_go_wechat_agent_configuration_yaml: | + wechat: + version: 3.8.1.26 + listen_port: 22222 + init_timeout: 10s + request_timeout: 30s + + service: + addr: ws://matrix-wechat:20002 + secret: "foobar" + ping_interval: 30s + + log: + level: info + +matrix_go_wechat_agent_configuration: "{{ matrix_go_wechat_agent_configuration_yaml | from_yaml }}" diff --git a/roles/custom/matrix-bridge-go-wechat/tasks/main.yml b/roles/custom/matrix-bridge-go-wechat/tasks/main.yml new file mode 100644 index 000000000..7eb28f01a --- /dev/null +++ b/roles/custom/matrix-bridge-go-wechat/tasks/main.yml @@ -0,0 +1,20 @@ +--- + +- tags: + - setup-all + - setup-go-wechat + - install-all + - install-go-wechat + block: + - when: matrix_go_wechat_enabled | bool + ansible.builtin.include_tasks: "{{ role_path }}/tasks/validate_config.yml" + + - when: matrix_go_wechat_enabled | bool + ansible.builtin.include_tasks: "{{ role_path }}/tasks/setup_install.yml" + +- tags: + - setup-all + - setup-go-wechat + block: + - when: not matrix_go_wechat_enabled | bool + ansible.builtin.include_tasks: "{{ role_path }}/tasks/setup_uninstall.yml" diff --git a/roles/custom/matrix-bridge-go-wechat/tasks/setup_install.yml b/roles/custom/matrix-bridge-go-wechat/tasks/setup_install.yml new file mode 100644 index 000000000..78a6b2c3b --- /dev/null +++ b/roles/custom/matrix-bridge-go-wechat/tasks/setup_install.yml @@ -0,0 +1,179 @@ +--- + +- ansible.builtin.set_fact: + matrix_go_wechat_requires_restart: false + +- name: Ensure Go WeChat Bridge paths exists + ansible.builtin.file: + path: "{{ item.path }}" + state: directory + mode: 0750 + owner: "{{ matrix_user_username }}" + group: "{{ matrix_user_groupname }}" + with_items: + - {path: "{{ matrix_go_wechat_base_path }}", when: true} + - {path: "{{ matrix_go_wechat_config_path }}", when: true} + - {path: "{{ matrix_go_wechat_data_path }}", when: true} + - {path: "{{ matrix_go_wechat_docker_src_files_path }}", when: "{{ matrix_go_wechat_container_image_self_build }}"} + - {path: "{{ matrix_go_wechat_agent_docker_src_files_path }}", when: "{{ matrix_go_wechat_agent_container_image_self_build }}"} + when: item.when | bool + +- name: Ensure Go WeChat Bridge image is pulled + community.docker.docker_image: + name: "{{ matrix_go_wechat_docker_image }}" + source: "{{ 'pull' if ansible_version.major > 2 or ansible_version.minor > 7 else omit }}" + force_source: "{{ matrix_go_wechat_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_go_wechat_docker_image_force_pull }}" + when: not matrix_go_wechat_container_image_self_build + register: result + retries: "{{ devture_playbook_help_container_retries_count }}" + delay: "{{ devture_playbook_help_container_retries_delay }}" + until: result is not failed + +- name: Ensure Go WeChat Agent image is pulled + community.docker.docker_image: + name: "{{ matrix_go_wechat_agent_docker_image }}" + source: "{{ 'pull' if ansible_version.major > 2 or ansible_version.minor > 7 else omit }}" + force_source: "{{ matrix_go_wechat_agent_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_go_wechat_agent_docker_image_force_pull }}" + when: not matrix_go_wechat_agent_container_image_self_build + register: result + retries: "{{ devture_playbook_help_container_retries_count }}" + delay: "{{ devture_playbook_help_container_retries_delay }}" + until: result is not failed + +- name: Ensure Go WeChat Bridge repository is present on self-build + ansible.builtin.git: + repo: "{{ matrix_go_wechat_container_image_self_build_repo }}" + dest: "{{ matrix_go_wechat_docker_src_files_path }}" + version: "{{ matrix_go_wechat_container_image_self_build_branch }}" + force: "yes" + become: true + become_user: "{{ matrix_user_username }}" + register: matrix_go_wechat_git_pull_results + when: "matrix_go_wechat_container_image_self_build | bool" + +- name: Ensure Go WeChat Agent repository is present on self-build + ansible.builtin.git: + repo: "{{ matrix_go_wechat_agent_container_image_self_build_repo }}" + dest: "{{ matrix_go_wechat_agent_docker_src_files_path }}" + version: "{{ matrix_go_wechat_agent_container_image_self_build_branch }}" + force: "yes" + become: true + become_user: "{{ matrix_user_username }}" + register: matrix_go_wechat_agent_git_pull_results + when: "matrix_go_wechat_agent_container_image_self_build | bool" + +- name: Ensure Go WeChat Bridge Docker image is built + community.docker.docker_image: + name: "{{ matrix_go_wechat_docker_image }}" + source: build + force_source: "{{ matrix_go_wechat_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_go_wechat_git_pull_results.changed }}" + build: + dockerfile: Dockerfile + path: "{{ matrix_go_wechat_docker_src_files_path }}" + pull: true + when: "matrix_go_wechat_container_image_self_build | bool" + +- name: Ensure Go WeChat Agent Docker image is built + community.docker.docker_image: + name: "{{ matrix_go_wechat_agent_docker_image }}" + source: build + force_source: "{{ matrix_go_wechat_agent_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_go_wechat_agent_git_pull_results.changed }}" + build: + dockerfile: Dockerfile + path: "{{ matrix_go_wechat_agent_docker_src_files_path }}" + pull: true + when: "matrix_go_wechat_agent_container_image_self_build | bool" + +- name: Check if an old database file exists + ansible.builtin.stat: + path: "{{ matrix_go_wechat_base_path }}/go-wechat.db" + register: matrix_go_wechat_stat_database + +- name: Check if an old matrix state file exists + ansible.builtin.stat: + path: "{{ matrix_go_wechat_base_path }}/mx-state.json" + register: matrix_go_wechat_stat_mx_state + +- name: (Data relocation) Ensure matrix-go-wechat.service is stopped + ansible.builtin.service: + name: matrix-go-wechat + state: stopped + enabled: false + daemon_reload: true + failed_when: false + when: "matrix_go_wechat_stat_database.stat.exists" + +- name: (Data relocation) Move go-wechat database file to ./data directory + ansible.builtin.command: + cmd: "mv {{ matrix_go_wechat_base_path }}/go-wechat.db {{ matrix_go_wechat_data_path }}/go-wechat.db" + creates: "{{ matrix_go_wechat_data_path }}/go-wechat.db" + removes: "{{ matrix_go_wechat_base_path }}/go-wechat.db" + when: "matrix_go_wechat_stat_database.stat.exists" + +- name: (Data relocation) Move go-wechat mx-state file to ./data directory + ansible.builtin.command: + cmd: "mv {{ matrix_go_wechat_base_path }}/mx-state.json {{ matrix_go_wechat_data_path }}/mx-state.json" + creates: "{{ matrix_go_wechat_data_path }}/mx-state.json" + removes: "{{ matrix_go_wechat_base_path }}/mx-state.json" + when: "matrix_go_wechat_stat_mx_state.stat.exists" + +- name: Ensure go-wechat config.yaml installed + ansible.builtin.copy: + content: "{{ matrix_go_wechat_configuration | to_nice_yaml(indent=2, width=999999) }}" + dest: "{{ matrix_go_wechat_config_path }}/config.yaml" + mode: 0644 + owner: "{{ matrix_user_username }}" + group: "{{ matrix_user_groupname }}" + +- name: Ensure go-wechat registration.yaml installed + ansible.builtin.copy: + content: "{{ matrix_go_wechat_registration | to_nice_yaml(indent=2, width=999999) }}" + dest: "{{ matrix_go_wechat_config_path }}/registration.yaml" + mode: 0644 + owner: "{{ matrix_user_username }}" + group: "{{ matrix_user_groupname }}" + +- name: Ensure go-wechat-agent configure.yaml installed + ansible.builtin.copy: + content: "{{ matrix_go_wechat_agent_configuration | to_nice_yaml(indent=2, width=999999) }}" + dest: "{{ matrix_go_wechat_config_path }}/configure.yaml" + mode: 0644 + owner: "{{ matrix_user_username }}" + group: "{{ matrix_user_groupname }}" + +- name: Ensure matrix-go-wechat container network is created + community.general.docker_network: + name: "{{ matrix_go_wechat_container_network }}" + driver: bridge + +- name: Ensure matrix-go-wechat.service installed + ansible.builtin.template: + src: "{{ role_path }}/templates/systemd/matrix-go-wechat.service.j2" + dest: "{{ devture_systemd_docker_base_systemd_path }}/matrix-go-wechat.service" + mode: 0644 + register: matrix_go_wechat_systemd_service_result + +- name: Ensure matrix-go-wechat-agent.service installed + ansible.builtin.template: + src: "{{ role_path }}/templates/systemd/matrix-go-wechat-agent.service.j2" + dest: "{{ devture_systemd_docker_base_systemd_path }}/matrix-go-wechat-agent.service" + mode: 0644 + register: matrix_go_wechat_agent_systemd_service_result + +- name: Ensure matrix-go-wechat.service restarted, if necessary + ansible.builtin.service: + name: "matrix-go-wechat.service" + state: restarted + daemon_reload: true + when: "matrix_go_wechat_requires_restart | bool" + +- name: Ensure matrix-go-wechat-agent.service restarted, if necessary + ansible.builtin.service: + name: "matrix-go-wechat-agent.service" + state: restarted + daemon_reload: true + when: "matrix_go_wechat_requires_restart | bool" diff --git a/roles/custom/matrix-bridge-go-wechat/tasks/setup_uninstall.yml b/roles/custom/matrix-bridge-go-wechat/tasks/setup_uninstall.yml new file mode 100644 index 000000000..f0103cbce --- /dev/null +++ b/roles/custom/matrix-bridge-go-wechat/tasks/setup_uninstall.yml @@ -0,0 +1,39 @@ +--- + +- name: Check existence of matrix-go-wechat service + ansible.builtin.stat: + path: "/etc/systemd/system/matrix-go-wechat.service" + register: matrix_go_wechat_service_stat + +- when: matrix_go_wechat_service_stat.stat.exists | bool + block: + - name: Ensure matrix-go-wechat is stopped + ansible.builtin.service: + name: matrix-go-wechat + state: stopped + enabled: false + daemon_reload: true + + - name: Ensure matrix-go-wechat.service doesn't exist + ansible.builtin.file: + path: "/etc/systemd/system/matrix-go-wechat.service" + state: absent + +- name: Check existence of matrix-go-wechat-agent service + ansible.builtin.stat: + path: "/etc/systemd/system/matrix-go-wechat-agent.service" + register: matrix_go_wechat_agent_service_stat + +- when: matrix_go_wechat_agent_service_stat.stat.exists | bool + block: + - name: Ensure matrix-go-wechat-agent is stopped + ansible.builtin.service: + name: matrix-go-wechat-agent + state: stopped + enabled: false + daemon_reload: true + + - name: Ensure matrix-go-wechat-agent.service doesn't exist + ansible.builtin.file: + path: "/etc/systemd/system/matrix-go-wechat-agent.service" + state: absent diff --git a/roles/custom/matrix-bridge-go-wechat/tasks/validate_config.yml b/roles/custom/matrix-bridge-go-wechat/tasks/validate_config.yml new file mode 100644 index 000000000..0238568fa --- /dev/null +++ b/roles/custom/matrix-bridge-go-wechat/tasks/validate_config.yml @@ -0,0 +1,18 @@ +--- + +- name: Fail if required go-wechat settings not defined + ansible.builtin.fail: + msg: >- + You need to define a required configuration setting (`{{ item.name }}`). + when: "item.when | bool and vars[item.name] == ''" + with_items: + - {'name': 'matrix_go_wechat_appservice_token', when: true} + - {'name': 'matrix_go_wechat_homeserver_address', when: true} + - {'name': 'matrix_go_wechat_homeserver_token', when: true} + - {'name': 'matrix_go_wechat_database_hostname', when: "{{ matrix_go_wechat_database_engine == 'postgres' }}"} + - {'name': 'matrix_go_wechat_container_network', when: true} + +- name: Ensure we are not running on ARM64 (which is not supported yet by the wechat agent) + when: matrix_architecture not in ['amd64'] + fail: + msg: "The Go WeChat Agent does not support the '{{ matrix_architecture }}' architecture yet." diff --git a/roles/custom/matrix-bridge-go-wechat/templates/config.yaml.j2 b/roles/custom/matrix-bridge-go-wechat/templates/config.yaml.j2 new file mode 100644 index 000000000..e3c42cf82 --- /dev/null +++ b/roles/custom/matrix-bridge-go-wechat/templates/config.yaml.j2 @@ -0,0 +1,249 @@ +#jinja2: lstrip_blocks: "True" +# Homeserver details. +homeserver: + # The address that this appservice can use to connect to the homeserver. + address: {{ matrix_go_wechat_homeserver_address }} + # The domain of the homeserver (for MXIDs, etc). + domain: {{ matrix_go_wechat_homeserver_domain }} + # What software is the homeserver running? + # Standard Matrix homeservers like Synapse, Dendrite and Conduit should just use "standard" here. + software: standard + # The URL to push real-time bridge status to. + # If set, the bridge will make POST requests to this URL whenever a user's 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_go_wechat_appservice_address }} + + # The hostname and port where this appservice should listen. + hostname: 0.0.0.0 + port: 8080 + + # Database config. + database: + # The database type. Currently only "postgres" is supported. + type: "postgres" + # The database URI. + uri: {{ matrix_go_wechat_database_connection_string|to_json }} + # Maximum number of connections. Mostly relevant for Postgres. + max_open_conns: 20 + max_idle_conns: 2 + + # The unique ID of this appservice. + id: wechat + # Appservice bot details. + bot: + # Username of the appservice bot. + username: {{ matrix_go_wechat_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: WeChat bridge bot + avatar: mxc://matrix.org/rddVQBTjOOmNkNLXWfYJNfPW + + # Whether or not to receive ephemeral events via appservice transactions. + # Requires MSC2409 support (i.e. Synapse 1.22+). + ephemeral_events: true + + # Should incoming events be handled asynchronously? + # This may be necessary for large public instances with lots of messages going through. + # However, messages will not be guaranteed to be bridged in the same order they were sent in. + async_transactions: false + + # Authentication tokens for AS <-> HS communication. Autogenerated; do not modify. + as_token: "{{ matrix_go_wechat_appservice_token }}" + hs_token: "{{ matrix_go_wechat_homeserver_token }}" + +# Bridge config +bridge: + # Localpart template of MXIDs for WeChat users. + # {{ '{{.}}' }} is replaced with the uin of the WeChat user. + username_template: {{ 'wechat-{{.}}' }} + # Displayname template for WeChat users. + # {{ '{{.Notify}}' }} - nickname set by the wechat user + # {{ '{{.Jid}}' }} - phone number (international format) + # The following variables are also available, but will cause problems on multi-user instances: + # {{ '{{.Name}}' }} - display name from contact list + # {{ '{{.Short}}' }} - short display name from contact list + # To use multiple if's, you need to use: {{ '{{else if .Name}}' }}, for example: + # "{{ '{{if .Notify}}' }}{{ '{{.Notify}}' }}{{ '{{else if .Name}}' }}{{ '{{.Name}}' }}{{ '{{else}}' }}{{ '{{.Jid}}' }}{{ '{{end}}' }} (WA)" + displayname_template: "{{ '{{if .Name }}' }}{{ '{{.Name}}' }}{{ '{{else}}' }}{{ '{{.Uin}}' }}{{ '{{end}}' }} (WeChat)" + # Localpart template for per-user room grouping community IDs. + # On startup, the bridge will try to create these communities, add all of the specific user's + # portals to the community, and invite the Matrix user to it. + # (Note that, by default, non-admins might not have your homeserver's permission to create + # communities.) + # {{ '{{.Localpart}}' }} is the MXID localpart and {{ '{{.Server}}' }} is the MXID server part of the user. + community_template: wechat-{{ '{{.Localpart}}' }}={{ '{{.Server}}' }} + # WeChat listen address (for agent connection) + listen_address: "0.0.0.0:20002" + listen_secret: "foobar" + + # wechat connection timeout in seconds. + connection_timeout: 20 + # If wechat doesn't respond within connection_timeout, should the bridge try to fetch the message + # to see if it was actually bridged? Use this if you have problems with sends timing out but actually + # succeeding. + fetch_message_on_timeout: false + # Whether or not the bridge should send a read receipt from the bridge bot when a message has been + # sent to wechat. If fetch_message_on_timeout is enabled, a successful post-timeout fetch will + # trigger a read receipt too. + delivery_receipts: false + # Number of times to regenerate QR code when logging in. + # The regenerated QR code is sent as an edit and essentially multiplies the login timeout (20 seconds) + login_qr_regen_count: 2 + # Maximum number of times to retry connecting on connection error. + max_connection_attempts: 3 + # Number of seconds to wait between connection attempts. + # Negative numbers are exponential backoff: -connection_retry_delay + 1 + 2^attempts + connection_retry_delay: -1 + # Whether or not the bridge should send a notice to the user's management room when it retries connecting. + # If false, it will only report when it stops retrying. + report_connection_retry: true + # Maximum number of seconds to wait for chats to be sent at startup. + # If this is too low and you have lots of chats, it could cause backfilling to fail. + chat_list_wait: 30 + # Maximum number of seconds to wait to sync portals before force unlocking message processing. + # If this is too low and you have lots of chats, it could cause backfilling to fail. + portal_sync_wait: 600 + + # Whether or not to send call start/end notices to Matrix. + call_notices: + start: true + end: true + + # Number of chats to sync for new users. + # Since some of the obtained conversations are not the conversations that the user needs to see, + # the actual number of conversations displayed on the matrix client will be slightly less than the set value + initial_chat_sync_count: 10 + # Number of old messages to fill when creating new portal rooms. + initial_history_fill_count: 20 + # Whether or not notifications should be turned off while filling initial history. + # Only applicable when using double puppeting. + initial_history_disable_notifications: false + # Maximum number of chats to sync when recovering from downtime. + # Set to -1 to sync all new chats during downtime. + recovery_chat_sync_limit: -1 + # Whether or not to sync history when recovering from downtime. + recovery_history_backfill: true + # Maximum number of seconds since last message in chat to skip + # syncing the chat in any case. This setting will take priority + # over both recovery_chat_sync_limit and initial_chat_sync_count. + # Default is 3 days = 259200 seconds + sync_max_chat_age: 259200 + + # sync contact, Non-martix-standard parameter, defaults to false + sync_contact: false + + # Whether or not to sync with custom puppets to receive EDUs that + # are not normally sent to appservices. + sync_with_custom_puppets: true + + # Servers to always allow double puppeting from + double_puppet_server_map: + "{{ matrix_go_wechat_homeserver_domain }}": {{ matrix_go_wechat_homeserver_address }} + # Allow using double puppeting from any server with a valid client .well-known file. + double_puppet_allow_discovery: false + # Shared secret for https://github.com/devture/matrix-synapse-shared-secret-auth + # + # If set, custom puppets 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_go_wechat_login_shared_secret_map|to_json }} + + # Whether or not to invite own wechat user's Matrix puppet into private + # chat portals when backfilling if needed. + # This always uses the default puppet instead of custom puppets due to + # rate limits and timestamp massaging. + invite_own_puppet_for_backfilling: true + # Whether or not to explicitly set the avatar and room name for private + # chat portal rooms. This can be useful if the previous field works fine, + # but causes room avatar/name bugs. + private_chat_portal_meta: true + + # Whether or not thumbnails from wechat should be sent. + # They're disabled by default due to very low resolution. + wechat_thumbnail: false + + # Allow invite permission for user. User can invite any bots to room with wechat + # users (private chat and groups) + allow_user_invite: false + + # The prefix for commands. Only required in non-management rooms. + command_prefix: "{{ matrix_go_wechat_command_prefix }}" + + # End-to-bridge encryption support options. This requires login_shared_secret to be configured + # in order to get a device for the bridge bot. + # + # Additionally, https://github.com/matrix-org/synapse/pull/5758 is required if using a normal + # application service. + encryption: + # Allow encryption, work in group chat rooms with e2ee enabled + allow: {{ matrix_go_wechat_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. + # It is recommended to also set private_chat_portal_meta to true when using this. + default: {{ matrix_go_wechat_encryption_default|to_json }} + + puppet_id: + # when set to true, the matrixid of the contact (puppet) from the bridge to the matrix will be encrypted into another string + allow: false + # 8 characters + key: '12dsf323' + # Use the username_template prefix. (Warning: At present, username_template cannot be too complicated, otherwise this function may cause unknown errors) + username_template_prefix: 'wechat-' + + # Permissions for using the bridge. + # Permitted values: + # relaybot - Talk through the relaybot (if enabled), no access otherwise + # user - Access to use the bridge to chat with a wechat 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_go_wechat_permissions|to_json }} + + relaybot: + # Whether or not relaybot support is enabled. + enabled: false + # The management room for the bot. This is where all status notifications are posted and + # in this room, you can use `!wa ` instead of `!wa relaybot `. Omitting + # the command prefix completely like in user management rooms is not possible. + management: '!foo:example.com' + # List of users to invite to all created rooms that include the relaybot. + invites: [] + # The formats to use when sending messages to wechat via the relaybot. + message_formats: + m.text: "{{ '{{ .Sender.Displayname }}' }}: {{ '{{ .Message }}' }}" + m.notice: "{{ '{{ .Sender.Displayname }}' }}:: {{ '{{ .Message }}' }}" + m.emote: "* {{ '{{ .Sender.Displayname }}' }}: {{ '{{ .Message }}' }}" + m.file: "{{ '{{ .Sender.Displayname }}' }}: sent a file" + m.image: "{{ '{{ .Sender.Displayname }}' }}: sent an image" + m.audio: "{{ '{{ .Sender.Displayname }}' }}: sent an audio file" + m.video: "{{ '{{ .Sender.Displayname }}' }}: sent a video" + m.location: "{{ '{{ .Sender.Displayname }}' }}: sent a location" + +# Logging config. +logging: + # The directory for log files. Will be created if not found. + directory: ./logs + # Available variables: .Date for the file date and .Index for different log files on the same day. + # empy/null = journal logging only + file_name_format: + # Date format for file names in the Go time format: https://golang.org/pkg/time/#pkg-constants + file_date_format: "2006-01-02" + # Log file permissions. + file_mode: 0600 + # Timestamp format for log entries in the Go time format. + timestamp_format: "Jan _2, 2006 15:04:05" + # Minimum severity for log messages. + # Options: debug, info, warn, error, fatal + print_level: {{ matrix_go_wechat_log_level }} diff --git a/roles/custom/matrix-bridge-go-wechat/templates/systemd/matrix-go-wechat-agent.service.j2 b/roles/custom/matrix-bridge-go-wechat/templates/systemd/matrix-go-wechat-agent.service.j2 new file mode 100644 index 000000000..fd859a140 --- /dev/null +++ b/roles/custom/matrix-bridge-go-wechat/templates/systemd/matrix-go-wechat-agent.service.j2 @@ -0,0 +1,45 @@ +#jinja2: lstrip_blocks: "True" +[Unit] +Description=Matrix Go WeChat Agent +{% for service in matrix_go_wechat_systemd_required_services_list %} +Requires={{ service }} +After={{ service }} +{% endfor %} +{% for service in matrix_go_wechat_systemd_wanted_services_list %} +Wants={{ service }} +{% endfor %} +DefaultDependencies=no + +[Service] +Type=simple +Environment="HOME={{ devture_systemd_docker_base_systemd_unit_home_path }}" +ExecStartPre=-{{ devture_systemd_docker_base_host_command_sh }} -c '{{ devture_systemd_docker_base_host_command_docker }} stop --time={{ devture_systemd_docker_base_container_stop_grace_time_seconds }} matrix-go-wechat-agent 2>/dev/null || true' +ExecStartPre=-{{ devture_systemd_docker_base_host_command_sh }} -c '{{ devture_systemd_docker_base_host_command_docker }} rm matrix-go-wechat-agent 2>/dev/null || true' + +ExecStartPre={{ devture_systemd_docker_base_host_command_docker }} create \ + --rm \ + --name=matrix-go-wechat-agent \ + --log-driver=none \ + --user={{ matrix_user_uid }}:{{ matrix_user_gid }} \ + --cap-drop=ALL \ + --network={{ matrix_go_wechat_container_network }} \ + --volume {{ matrix_go_wechat_config_path }}/configure.yaml:/home/user/matrix-wechat-agent/configure.yaml \ + {% for arg in matrix_go_wechat_container_extra_arguments %} + {{ arg }} \ + {% endfor %} + {{ matrix_go_wechat_agent_docker_image }} + +{% for network in matrix_go_wechat_container_additional_networks %} +ExecStartPre={{ devture_systemd_docker_base_host_command_docker }} network connect {{ network }} matrix-go-wechat-agent +{% endfor %} + +ExecStart={{ devture_systemd_docker_base_host_command_docker }} start --attach matrix-go-wechat-agent + +ExecStop=-{{ devture_systemd_docker_base_host_command_sh }} -c '{{ devture_systemd_docker_base_host_command_docker }} stop --time={{ devture_systemd_docker_base_container_stop_grace_time_seconds }} matrix-go-wechat-agent 2>/dev/null || true' +ExecStop=-{{ devture_systemd_docker_base_host_command_sh }} -c '{{ devture_systemd_docker_base_host_command_docker }} rm matrix-go-wechat-agent 2>/dev/null || true' +Restart=always +RestartSec=30 +SyslogIdentifier=matrix-go-wechat-agent + +[Install] +WantedBy=multi-user.target diff --git a/roles/custom/matrix-bridge-go-wechat/templates/systemd/matrix-go-wechat.service.j2 b/roles/custom/matrix-bridge-go-wechat/templates/systemd/matrix-go-wechat.service.j2 new file mode 100644 index 000000000..74f637d73 --- /dev/null +++ b/roles/custom/matrix-bridge-go-wechat/templates/systemd/matrix-go-wechat.service.j2 @@ -0,0 +1,48 @@ +#jinja2: lstrip_blocks: "True" +[Unit] +Description=Matrix Go WeChat Bridge +{% for service in matrix_go_wechat_systemd_required_services_list %} +Requires={{ service }} +After={{ service }} +{% endfor %} +{% for service in matrix_go_wechat_systemd_wanted_services_list %} +Wants={{ service }} +{% endfor %} +DefaultDependencies=no + +[Service] +Type=simple +Environment="HOME={{ devture_systemd_docker_base_systemd_unit_home_path }}" +ExecStartPre=-{{ devture_systemd_docker_base_host_command_sh }} -c '{{ devture_systemd_docker_base_host_command_docker }} stop --time={{ devture_systemd_docker_base_container_stop_grace_time_seconds }} matrix-go-wechat 2>/dev/null || true' +ExecStartPre=-{{ devture_systemd_docker_base_host_command_sh }} -c '{{ devture_systemd_docker_base_host_command_docker }} rm matrix-go-wechat 2>/dev/null || true' + +ExecStartPre={{ devture_systemd_docker_base_host_command_docker }} create \ + --rm \ + --name=matrix-go-wechat \ + --log-driver=none \ + --user={{ matrix_user_uid }}:{{ matrix_user_gid }} \ + --cap-drop=ALL \ + --network={{ matrix_go_wechat_container_network }} \ + --mount type=bind,src={{ matrix_go_wechat_config_path }},dst=/config \ + --mount type=bind,src={{ matrix_go_wechat_data_path }},dst=/data \ + --workdir=/data \ + {% for arg in matrix_go_wechat_container_extra_arguments %} + {{ arg }} \ + {% endfor %} + {{ matrix_go_wechat_docker_image }} \ + /usr/bin/matrix-wechat -c /config/config.yaml -r /config/registration.yaml + +{% for network in matrix_go_wechat_container_additional_networks %} +ExecStartPre={{ devture_systemd_docker_base_host_command_docker }} network connect {{ network }} matrix-go-wechat +{% endfor %} + +ExecStart={{ devture_systemd_docker_base_host_command_docker }} start --attach matrix-go-wechat + +ExecStop=-{{ devture_systemd_docker_base_host_command_sh }} -c '{{ devture_systemd_docker_base_host_command_docker }} stop --time={{ devture_systemd_docker_base_container_stop_grace_time_seconds }} matrix-go-wechat 2>/dev/null || true' +ExecStop=-{{ devture_systemd_docker_base_host_command_sh }} -c '{{ devture_systemd_docker_base_host_command_docker }} rm matrix-go-wechat 2>/dev/null || true' +Restart=always +RestartSec=30 +SyslogIdentifier=matrix-go-wechat + +[Install] +WantedBy=multi-user.target diff --git a/setup.yml b/setup.yml index 5b371a9f3..75df8b7cb 100644 --- a/setup.yml +++ b/setup.yml @@ -57,6 +57,7 @@ - custom/matrix-bridge-appservice-kakaotalk - custom/matrix-bridge-beeper-linkedin - custom/matrix-bridge-go-skype-bridge + - custom/matrix-bridge-go-wechat - custom/matrix-bridge-mautrix-facebook - custom/matrix-bridge-mautrix-twitter - custom/matrix-bridge-mautrix-hangouts