A platform for community discussion. Free, open, simple.
UX: Improve chat integration plugin provider setup (#38892)
Martin Brennan9eef8a8b14f7
diff --git a/app/models/site_setting.rb b/app/models/site_setting.rbindex f245ff4018c..8e6c2af0616 100644--- a/app/models/site_setting.rb+++ b/app/models/site_setting.rb@@ -136,6 +136,13 @@ class SiteSetting < ActiveRecord::BaseDir[File.join(Rails.root, "plugins", "*", "config", "settings.yml")].each do |file|load_settings(file, plugin: file.split("/")[-3])end++ # Sometimes plugins need to define their own fake site settings for testing+ if Rails.env.test?+ Dir[+ File.join(Rails.root, "plugins", "*", "spec", "support", "dummy_plugin_site_settings.yml")+ ].each { |file| load_settings(file, plugin: file.split("/")[-4]) }+ endendsetup_deprecated_methodsdiff --git a/frontend/discourse/app/lib/ajax-error.js b/frontend/discourse/app/lib/ajax-error.jsindex b7d549205fc..4932aaeaf9e 100644--- a/frontend/discourse/app/lib/ajax-error.js+++ b/frontend/discourse/app/lib/ajax-error.js@@ -80,6 +80,8 @@ export function extractErrorInfo(return {html,message: parsedError || defaultMessage || i18n("generic_error"),+ errorKey: parsedJSON?.error_key ?? null,+ status: error.status ?? null,};}diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/modal/edit-rule.gjs b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/modal/edit-rule.gjsindex 1ed0a4d0998..583d80f1db4 100644--- a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/modal/edit-rule.gjs+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/modal/edit-rule.gjs@@ -10,7 +10,7 @@ import CategoryChooser from "discourse/select-kit/components/category-chooser";import ComboBox from "discourse/select-kit/components/combo-box";import TagChooser from "discourse/select-kit/components/tag-chooser";import { i18n } from "discourse-i18n";-import getTagName from "../../lib/get-tag-name";+import getTagName from "../../lib/utilities";import ChannelData from "../channel-data";export default class EditRule extends Component {diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/modal/setup-provider.gjs b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/modal/setup-provider.gjsnew file mode 100644index 00000000000..1b04371d6c8--- /dev/null+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/modal/setup-provider.gjs@@ -0,0 +1,199 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { concat } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import { isEmpty } from "@ember/utils";+import DModal from "discourse/components/d-modal";+import Form from "discourse/components/form";+import { ajax } from "discourse/lib/ajax";+import { extractErrorInfo, popupAjaxError } from "discourse/lib/ajax-error";+import { i18n } from "discourse-i18n";+import { PROVIDER_LEARN_MORE_URLS } from "../../lib/utilities";+import SlackProviderSetupForm from "../provider-setup-form/slack";+import TelegramProviderSetupForm from "../provider-setup-form/telegram";++const PROVIDER_CONFIG = {+ slack: {+ component: SlackProviderSetupForm,+ primaryField: "chat_integration_slack_access_token",+ primaryFieldTitleKey:+ "chat_integration.setup_provider_modal.slack.access_token.title",+ },+ telegram: {+ component: TelegramProviderSetupForm,+ primaryField: "chat_integration_telegram_access_token",+ primaryFieldTitleKey:+ "chat_integration.setup_provider_modal.telegram.access_token.title",+ },+};++export default class SetupProvider extends Component {+ @service toasts;++ @tracked formKitApi = null;++ get formComponent() {+ return PROVIDER_CONFIG[this.args.model.provider.name].component;+ }++ get additionalInstructions() {+ return i18n(+ `chat_integration.setup_provider_modal.${this.args.model.provider.name}.instructions`+ );+ }++ get learnMoreUrl() {+ return PROVIDER_LEARN_MORE_URLS[this.args.model.provider.name];+ }++ get primaryFieldName() {+ return PROVIDER_CONFIG[this.args.model.provider.name].primaryField;+ }++ get primaryFieldTitleKey() {+ return PROVIDER_CONFIG[this.args.model.provider.name].primaryFieldTitleKey;+ }++ @action+ validateForm(data, { addError, removeError }) {+ if (this.args.model.provider.name === "slack") {+ this.validateSlackForm(data, addError, removeError);+ }+ }++ fieldAndTitleForErrorKey(errorKey) {+ if (this.args.model.provider.name === "slack") {+ if (+ errorKey ===+ "chat_integration.provider.slack.errors.invalid_webhook_url"+ ) {+ return {+ field: "chat_integration_slack_outbound_webhook_url",+ titleKey:+ "chat_integration.setup_provider_modal.slack.outbound_webhook_url.title",+ };+ }+ }++ return {+ field: this.primaryFieldName,+ titleKey: this.primaryFieldTitleKey,+ };+ }++ @action+ registerFormApi(api) {+ this.formKitApi = api;+ }++ validateSlackForm(data, addError, removeError) {+ const token = data.chat_integration_slack_access_token;+ const url = data.chat_integration_slack_outbound_webhook_url;++ const tokenField = "chat_integration_slack_access_token";++ if (isEmpty(token) && isEmpty(url)) {+ addError(tokenField, {+ title: i18n(+ "chat_integration.setup_provider_modal.slack.access_token.title"+ ),+ message: i18n(+ "chat_integration.setup_provider_modal.slack.at_least_one_required"+ ),+ });+ } else {+ removeError(tokenField);+ }+ }++ @action+ async save(data) {+ try {+ await ajax("/admin/plugins/discourse-chat-integration/setup-provider", {+ type: "POST",+ data: {+ provider: {+ name: this.args.model.provider.name,+ },+ provider_site_settings: data,+ },+ });+ this.toasts.success({+ data: {+ message: i18n("chat_integration.setup_provider_modal.success", {+ provider: this.args.model.provider.title,+ }),+ },+ duration: "short",+ });+ this.args.closeModal({ setupCompleted: true });+ } catch (error) {+ const errorInfo = extractErrorInfo(error, undefined, {+ skipConsoleError: true,+ });++ if (errorInfo.status === 422 && errorInfo.errorKey && this.formKitApi) {+ const { field, titleKey } = this.fieldAndTitleForErrorKey(+ errorInfo.errorKey+ );+ if (field && titleKey) {+ this.formKitApi.addError(field, {+ title: i18n(titleKey),+ message: errorInfo.message,+ });+ return;+ }+ }++ popupAjaxError(error);+ }+ }++ <template>+ <DModal+ @title={{i18n+ "chat_integration.setup_provider_modal.title"+ provider=(i18n+ (concat "chat_integration.provider." @model.provider.name ".title")+ )+ }}+ @closeModal={{@closeModal}}+ id="chat-integration-setup-provider-modal"+ class="chat-integration-setup-provider-modal"+ >+ <:body>+ <p class="chat-integration-setup-provider-modal__instructions">+ {{i18n+ "chat_integration.setup_provider_modal.setup_instructions"+ additionalInstructions=this.additionalInstructions+ }}+ {{trustHTML (i18n "learn_more_with_link" url=this.learnMoreUrl)}}+ </p>+ <Form+ @onSubmit={{this.save}}+ @validate={{this.validateForm}}+ @onRegisterApi={{this.registerFormApi}}+ as |form|+ >+ <this.formComponent @form={{form}} />++ <form.Actions>+ <form.Submit+ @label="chat_integration.setup_provider_modal.confirm_setup"+ class="btn-primary"+ id="save-provider"+ />+ <form.Button+ @label="cancel"+ @action={{@closeModal}}+ class="btn-default"+ />+ </form.Actions>+ </Form>+ </:body>+ </DModal>+ </template>+}diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/provider-setup-form/slack.gjs b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/provider-setup-form/slack.gjsnew file mode 100644index 00000000000..d3a3399f9e3--- /dev/null+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/provider-setup-form/slack.gjs@@ -0,0 +1,35 @@+import { i18n } from "discourse-i18n";++const SlackProviderSetupForm = <template>+ <@form.Field+ @name="chat_integration_slack_access_token"+ @title={{i18n+ "chat_integration.setup_provider_modal.slack.access_token.title"+ }}+ @description={{i18n+ "chat_integration.setup_provider_modal.slack.access_token.description"+ }}+ @type="password"+ @format="full"+ as |field|+ >+ <field.Control data-1p-ignore />+ </@form.Field>++ <@form.Field+ @name="chat_integration_slack_outbound_webhook_url"+ @title={{i18n+ "chat_integration.setup_provider_modal.slack.outbound_webhook_url.title"+ }}+ @description={{i18n+ "chat_integration.setup_provider_modal.slack.outbound_webhook_url.description"+ }}+ @type="input"+ @format="full"+ as |field|+ >+ <field.Control data-1p-ignore />+ </@form.Field>+</template>;++export default SlackProviderSetupForm;diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/provider-setup-form/telegram.gjs b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/provider-setup-form/telegram.gjsnew file mode 100644index 00000000000..c8a3f9a245f--- /dev/null+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/provider-setup-form/telegram.gjs@@ -0,0 +1,21 @@+import { i18n } from "discourse-i18n";++const TelegramProviderSetupForm = <template>+ <@form.Field+ @name="chat_integration_telegram_access_token"+ @title={{i18n+ "chat_integration.setup_provider_modal.telegram.access_token.title"+ }}+ @description={{i18n+ "chat_integration.setup_provider_modal.telegram.access_token.description"+ }}+ @validation="required"+ @type="password"+ @format="full"+ as |field|+ >+ <field.Control data-1p-ignore />+ </@form.Field>+</template>;++export default TelegramProviderSetupForm;diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/rule-row.gjs b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/rule-row.gjsindex 0b7c7f80268..3cabc0fffac 100644--- a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/rule-row.gjs+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/components/rule-row.gjs@@ -6,7 +6,7 @@ import DButton from "discourse/components/d-button";import categoryLink from "discourse/helpers/category-link";import { popupAjaxError } from "discourse/lib/ajax-error";import { i18n } from "discourse-i18n";-import getTagName from "../lib/get-tag-name";+import getTagName from "../lib/utilities";export default class RuleRow extends Component {@service siteSettings;diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/lib/get-tag-name.js b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/lib/get-tag-name.jsdeleted file mode 100644index 1db8025a8aa..00000000000--- a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/lib/get-tag-name.js+++ /dev/null@@ -1,3 +0,0 @@-export default function getTagName(tag) {- return typeof tag === "string" ? tag : tag.name;-}diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/lib/utilities.js b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/lib/utilities.jsnew file mode 100644index 00000000000..51bedf25a57--- /dev/null+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/lib/utilities.js@@ -0,0 +1,17 @@+export default function getTagName(tag) {+ return typeof tag === "string" ? tag : tag.name;+}++export const PROVIDER_LEARN_MORE_URLS = {+ discord: "https://meta.discourse.org/t/-/66600",+ gitter: "https://meta.discourse.org/t/-/69220",+ google: "https://meta.discourse.org/t/-/177362",+ mattermost: "https://meta.discourse.org/t/-/66811",+ matrix: "https://meta.discourse.org/t/-/66944",+ rocketchat: "https://meta.discourse.org/t/-/68633",+ slack: "https://meta.discourse.org/t/-/66730",+ teams: "https://meta.discourse.org/t/-/159193",+ telegram: "https://meta.discourse.org/t/-/66603",+ webex: "https://meta.discourse.org/t/-/173026",+ zulip: "https://meta.discourse.org/t/-/68501",+};diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers.js b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers.jsindex e7eae6a2567..626dfdbb960 100644--- a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers.js+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers.js@@ -1,7 +1,15 @@+import { ajax } from "discourse/lib/ajax";import DiscourseRoute from "discourse/routes/discourse";export default class DiscourseChatIntegrationProviders extends DiscourseRoute {model() {- return this.store.findAll("provider");+ return ajax(+ "/admin/plugins/discourse-chat-integration/providers.json"+ ).then((result) => {+ return {+ enabled_providers: result.enabled_providers,+ disabled_providers: result.disabled_providers,+ };+ });}}diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers/index.js b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers/index.jsindex 0b5b0fd5ea9..b786f120b68 100644--- a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers/index.js+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers/index.js@@ -8,10 +8,10 @@ export default class DiscourseChatIntegrationProvidersIndex extends DiscourseRouconst providers = this.modelFor("adminPlugins.show.discourse-chat-integration-providers");- if (providers.totalRows > 0) {+ if (providers.enabled_providers.length > 0) {this.router.transitionTo("adminPlugins.show.discourse-chat-integration-providers.show",- providers.content[0].name+ providers.enabled_providers[0].name);}}diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers/show.js b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers/show.jsindex eaf53eeee8c..efdc0b024f9 100644--- a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers/show.js+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-chat-integration-providers/show.js@@ -14,7 +14,7 @@ export default class DiscourseChatIntegrationProvidersShow extends DiscourseRoutGroup.findAll(),]);- const provider = providers.content.find(+ const provider = providers.enabled_providers.find((item) => item.id === params.provider);diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-chat-integration-providers.gjs b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-chat-integration-providers.gjsindex 60163b2a551..38aec4185e7 100644--- a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-chat-integration-providers.gjs+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-chat-integration-providers.gjs@@ -8,49 +8,44 @@ import DButton from "discourse/components/d-button";import DropdownMenu from "discourse/components/dropdown-menu";import NavItem from "discourse/components/nav-item";import DMenu from "discourse/float-kit/components/d-menu";+import concatClass from "discourse/helpers/concat-class";+import { ajax } from "discourse/lib/ajax";+import { popupAjaxError } from "discourse/lib/ajax-error";import { i18n } from "discourse-i18n";+import SetupProvider from "../../../components/modal/setup-provider";export default class DiscourseChatIntegrationProviders extends Component {@service router;+ @service modal;+ @service dialog;+ @service toasts;isProviderActive = (providerName) => {return this.currentProvider === providerName;};- get currentProvider() {- return this.router.currentRoute?.params?.provider;+ constructor() {+ super(...arguments);}- get enabledProviders() {- return this.args.controller.model.content || [];+ get currentProvider() {+ return this.router.currentRoute?.params?.provider;}// Sorted by popularity (number of customer sites using each provider)get allProviders() {- return [- "slack",- "discord",- "teams",- "telegram",- "google",- "matrix",- "zulip",- "mattermost",- "powerautomate",- "gitter",- "rocketchat",- "guilded",- "groupme",- "webex",- ].map((name) => ({- name,- settingsFilter: `chat_integration_${name}`,- }));+ const providers = (+ this.args.controller.model.disabled_providers || []+ ).concat(this.args.controller.model.enabled_providers || []);+ return providers;+ }++ get enabledProviders() {+ return this.args.controller.model.enabled_providers || [];}get disabledProviders() {- const enabledNames = this.enabledProviders.map((p) => p.name);- return this.allProviders.filter((p) => !enabledNames.includes(p.name));+ return this.args.controller.model.disabled_providers || [];}get popularProviders() {@@ -61,11 +56,75 @@ export default class DiscourseChatIntegrationProviders extends Component {return this.disabledProviders.slice(4);}+ providerTitle(provider) {+ return i18n(`chat_integration.provider.${provider.name}.title`);+ }+@action- configureProvider(provider) {- this.router.transitionTo("adminPlugins.show.settings", {- queryParams: { filter: provider.settingsFilter },+ async configureProvider(provider, menu = null) {+ const disabledProvider =+ this.disabledProviders.find((p) => p.name === provider.name) ?? provider;++ if (provider.additional_site_settings_required) {+ this.openProviderSetupModal(disabledProvider);+ menu?.close();+ } else {+ this.dialog.confirm({+ message: i18n("chat_integration.confirm_setup_provider", {+ provider: this.providerTitle(disabledProvider),+ }),+ didConfirm: async () => {+ try {+ await ajax(+ "/admin/plugins/discourse-chat-integration/setup-provider",+ {+ type: "POST",+ data: {+ provider: {+ name: disabledProvider.name,+ },+ },+ }+ );+ this.toasts.success({+ data: {+ message: i18n("chat_integration.setup_provider_modal.success", {+ provider: this.providerTitle(disabledProvider),+ }),+ },+ duration: "short",+ });+ this.navigateToProvider(disabledProvider);+ } catch (error) {+ popupAjaxError(error);+ }+ },+ });+ }+ }++ @action+ async openProviderSetupModal(provider) {+ const closeData = await this.modal.show(SetupProvider, {+ model: {+ provider: Object.assign({}, provider, {+ title: this.providerTitle(provider),+ }),+ },});++ if (closeData?.setupCompleted) {+ await this.navigateToProvider(provider);+ }+ }++ @action+ async navigateToProvider(provider) {+ await this.router.refresh();+ this.router.transitionTo(+ "adminPlugins.show.discourse-chat-integration-providers.show",+ provider.name+ );}<template>@@ -98,7 +157,7 @@ export default class DiscourseChatIntegrationProviders extends Component {@label={{i18n "chat_integration.add_provider"}}class="btn-default btn-small">- <:content>+ <:content as |menu|><DropdownMenu as |dropdown|>{{#each this.disabledProviders as |provider|}}<dropdown.item>@@ -108,8 +167,12 @@ export default class DiscourseChatIntegrationProviders extends Component {"chat_integration.provider." provider.name ".title")}}- @action={{fn this.configureProvider provider}}- class="btn-transparent"+ @action={{fn this.configureProvider provider menu}}+ class={{concatClass+ "btn-transparent"+ "chat-integration-add-provider-button"+ (concat "--" provider.name)+ }}/></dropdown.item>{{/each}}@@ -134,7 +197,11 @@ export default class DiscourseChatIntegrationProviders extends Component {(concat "chat_integration.provider." provider.name ".title")}}@action={{fn this.configureProvider provider}}- class="btn-default"+ class={{concatClass+ "btn-default"+ "chat-integration-popular-provider-setup"+ (concat "--" provider.name)+ }}/>{{/each}}{{#if this.otherProviders.length}}@@ -142,7 +209,7 @@ export default class DiscourseChatIntegrationProviders extends Component {@identifier="chat-integration-more-providers"@icon="ellipsis"@label={{i18n "chat_integration.more_providers"}}- class="btn-default"+ class="btn-default chat-integration-more-providers-setup"><:content><DropdownMenu as |dropdown|>@@ -157,7 +224,11 @@ export default class DiscourseChatIntegrationProviders extends Component {)}}@action={{fn this.configureProvider provider}}- class="btn-transparent"+ class={{concatClass+ "btn-transparent"+ "chat-integration-more-providers-setup"+ (concat "--" provider.name)+ }}/></dropdown.item>{{/each}}diff --git a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-chat-integration-providers/show.gjs b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-chat-integration-providers/show.gjsindex 7f712432733..150d5c0c427 100644--- a/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-chat-integration-providers/show.gjs+++ b/plugins/discourse-chat-integration/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-chat-integration-providers/show.gjs@@ -1,3 +1,7 @@+import Component from "@glimmer/component";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { service } from "@ember/service";import AdminConfigAreaEmptyList from "discourse/admin/components/admin-config-area-empty-list";import DBreadcrumbsItem from "discourse/components/d-breadcrumbs-item";import DPageSubheader from "discourse/components/d-page-subheader";@@ -5,67 +9,104 @@ import icon from "discourse/helpers/d-icon";import { i18n } from "discourse-i18n";import ChannelDetails from "../../../../components/channel-details";import InlineChannelForm from "../../../../components/inline-channel-form";+import { PROVIDER_LEARN_MORE_URLS } from "../../../../lib/utilities";-const providerTitle = (provider) =>- i18n(`chat_integration.provider.${provider.name}.title`);+export default class extends Component {+ @service router;-<template>- <DBreadcrumbsItem- @path="/admin/plugins/discourse-chat-integration/providers/{{@controller.model.provider.name}}"- @label={{providerTitle @controller.model.provider}}- />+ get providerTitle() {+ return i18n(+ `chat_integration.provider.${this.args.controller.model.provider.name}.title`+ );+ }- {{#if @controller.anyErrors}}- <div class="alert alert-error chat-integration-error-banner">- {{icon "triangle-exclamation"}}- <span class="error-message">- {{i18n "chat_integration.channels_with_errors"}}- </span>- </div>- {{/if}}+ get providerLearnMoreUrl() {+ return PROVIDER_LEARN_MORE_URLS[this.args.controller.model.provider.name];+ }- <div class="admin-detail">- <DPageSubheader @titleLabel={{i18n "chat_integration.channels_title"}}>- <:actions as |actions|>- {{#unless @controller.showNewChannelForm}}- <actions.Primary- @label="chat_integration.add_channel"- @title="chat_integration.add_channel"- @action={{@controller.createChannel}}- @icon="plus"- id="create-channel"- />- {{/unless}}- </:actions>- </DPageSubheader>+ @action+ configureProvider() {+ this.router.transitionTo("adminPlugins.show.settings", {+ queryParams: {+ filter: `chat_integration_${this.args.controller.model.provider.name}`,+ },+ });+ }- {{#if @controller.showNewChannelForm}}- <InlineChannelForm- @channel={{@controller.newChannel}}- @provider={{@controller.model.provider}}- @onSave={{@controller.onChannelSaved}}- @onCancel={{@controller.cancelNewChannel}}- />- {{/if}}+ <template>+ <DBreadcrumbsItem+ @path="/admin/plugins/discourse-chat-integration/providers/{{@controller.model.provider.name}}"+ @label={{this.providerTitle @controller.model.provider}}+ />- {{#if @controller.model.channels.content.length}}- <div class="chat-integration-channel-list">- {{#each @controller.model.channels.content as |channel|}}- <ChannelDetails- @channel={{channel}}- @provider={{@controller.model.provider}}- @refresh={{@controller.refresh}}- @test={{@controller.testChannel}}- @createRule={{@controller.createRule}}- @editRuleWithChannel={{@controller.editRuleWithChannel}}- @showError={{@controller.showError}}- />- {{/each}}+ {{#if @controller.anyErrors}}+ <div class="alert alert-error chat-integration-error-banner">+ {{icon "triangle-exclamation"}}+ <span class="error-message">+ {{i18n "chat_integration.channels_with_errors"}}+ </span></div>- {{else}}- {{#unless @controller.showNewChannelForm}}- <AdminConfigAreaEmptyList @emptyLabel="chat_integration.no_channels" />- {{/unless}}{{/if}}- </div>-</template>++ <div class="admin-detail">+ <DPageSubheader+ @titleLabel={{i18n "chat_integration.channels_title"}}+ @descriptionLabel={{i18n+ "chat_integration.channels_description"+ provider=this.providerTitle+ }}+ @learnMoreUrl={{this.providerLearnMoreUrl}}+ >+ <:actions as |actions|>+ <actions.Default+ @label="chat_integration.view_provider_settings"+ @title="chat_integration.view_provider_settings"+ @action={{fn this.configureProvider @controller.model.provider}}+ @icon="gear"+ id="view-provider-settings"+ />+ {{#unless @controller.showNewChannelForm}}+ <actions.Primary+ @label="chat_integration.add_channel"+ @title="chat_integration.add_channel"+ @action={{@controller.createChannel}}+ @icon="plus"+ id="create-channel"+ />+ {{/unless}}+ </:actions>+ </DPageSubheader>++ {{#if @controller.showNewChannelForm}}+ <InlineChannelForm+ @channel={{@controller.newChannel}}+ @provider={{@controller.model.provider}}+ @onSave={{@controller.onChannelSaved}}+ @onCancel={{@controller.cancelNewChannel}}+ />+ {{/if}}++ {{#if @controller.model.channels.content.length}}+ <div class="chat-integration-channel-list">+ {{#each @controller.model.channels.content as |channel|}}+ <ChannelDetails+ @channel={{channel}}+ @provider={{@controller.model.provider}}+ @refresh={{@controller.refresh}}+ @test={{@controller.testChannel}}+ @createRule={{@controller.createRule}}+ @editRuleWithChannel={{@controller.editRuleWithChannel}}+ @showError={{@controller.showError}}+ />+ {{/each}}+ </div>+ {{else}}+ {{#unless @controller.showNewChannelForm}}+ <AdminConfigAreaEmptyList+ @emptyLabel="chat_integration.no_channels"+ />+ {{/unless}}+ {{/if}}+ </div>+ </template>+}diff --git a/plugins/discourse-chat-integration/app/controllers/discourse_chat_integration/chat_controller.rb b/plugins/discourse-chat-integration/app/controllers/discourse_chat_integration/chat_controller.rbindex e850cd564e6..91dda2fa0f5 100644--- a/plugins/discourse-chat-integration/app/controllers/discourse_chat_integration/chat_controller.rb+++ b/plugins/discourse-chat-integration/app/controllers/discourse_chat_integration/chat_controller.rb@@ -3,21 +3,85 @@class DiscourseChatIntegration::ChatController < ApplicationControllerrequires_plugin DiscourseChatIntegration::PLUGIN_NAME+ SETUP_PROVIDER_SITE_SETTING_KEYS = {+ "slack" => %i[chat_integration_slack_access_token chat_integration_slack_outbound_webhook_url],+ "telegram" => %i[chat_integration_telegram_access_token],+ }.freeze+def respondrenderenddef list_providersproviders =- DiscourseChatIntegration::Provider.enabled_providers.map do |x|+ DiscourseChatIntegration::Provider.enabled_providers.map do |provider_klass|+ {+ name: provider_klass::PROVIDER_NAME,+ id: provider_klass::PROVIDER_NAME,+ channel_parameters:+ (+ if (defined?(provider_klass::CHANNEL_PARAMETERS))+ provider_klass::CHANNEL_PARAMETERS+ else+ []+ end+ ),+ }+ end++ disabled_providers =+ DiscourseChatIntegration::Provider.disabled_providers.map do |provider_klass|{- name: x::PROVIDER_NAME,- id: x::PROVIDER_NAME,- channel_parameters: (defined?(x::CHANNEL_PARAMETERS)) ? x::CHANNEL_PARAMETERS : [],+ name: provider_klass::PROVIDER_NAME,+ id: provider_klass::PROVIDER_NAME,+ additional_site_settings_required:+ if defined?(provider_klass::ADDITIONAL_SITE_SETTINGS_REQUIRED)+ provider_klass::ADDITIONAL_SITE_SETTINGS_REQUIRED+ else+ false+ end,}end- render json: providers, root: "providers"+ render json: { enabled_providers: providers, disabled_providers: }+ end++ def setup_provider+ hash = params.require(:provider).permit(:name)+ name = hash[:name].to_s.strip++ if name.blank?+ raise Discourse::InvalidParameters.new(+ I18n.t("chat_integration.errors.provider_not_found", name: "unknown"),+ )+ end++ provider_klass = DiscourseChatIntegration::Provider.get_by_name(name)+ if provider_klass.nil?+ raise Discourse::InvalidParameters.new(+ I18n.t("chat_integration.errors.provider_not_found", name: name),+ )+ end++ if DiscourseChatIntegration::Provider.is_enabled(provider_klass)+ raise Discourse::InvalidParameters.new(+ I18n.t("chat_integration.errors.provider_already_enabled", name: name),+ )+ end++ permitted_site_settings = permitted_provider_site_settings(name)++ DiscourseChatIntegration::Provider.setup(provider_klass, current_user, permitted_site_settings)+ render json: success_json+ rescue Discourse::InvalidParameters => err+ render json: { errors: [err.message] }, status: :unprocessable_entity+ rescue DiscourseChatIntegration::ProviderError => err+ if err.info[:error_key].present?+ Rails.logger.error("Chat integration setup failed error_key=#{err.info[:error_key]}")+ render json: { error_key: err.info[:error_key] }, status: :unprocessable_entity+ else+ render json: { errors: [err.message.presence || "error"] }, status: :unprocessable_entity+ endenddef test@@ -35,14 +99,14 @@ class DiscourseChatIntegration::ChatController < ApplicationControllerprovider.trigger_notification(post, channel, nil)render json: success_json- rescue Discourse::InvalidParameters, ActiveRecord::RecordNotFound => e- render json: { errors: [e.message] }, status: :unprocessable_entity- rescue DiscourseChatIntegration::ProviderError => e- Rails.logger.error("Test provider failed #{e.info}")- if e.info.key?(:error_key) && !e.info[:error_key].nil?- render json: { error_key: e.info[:error_key] }, status: :unprocessable_entity+ rescue Discourse::InvalidParameters, ActiveRecord::RecordNotFound => err+ render json: { errors: [err.message] }, status: :unprocessable_entity+ rescue DiscourseChatIntegration::ProviderError => err+ Rails.logger.error("Test provider failed #{err.info}")+ if err.info.key?(:error_key) && !err.info[:error_key].nil?+ render json: { error_key: err.info[:error_key] }, status: :unprocessable_entityelse- render json: { errors: [e.message] }, status: :unprocessable_entity+ render json: { errors: [err.message] }, status: :unprocessable_entityendendend@@ -150,4 +214,14 @@ class DiscourseChatIntegration::ChatController < ApplicationControllerrender json: success_jsonend++ private++ def permitted_provider_site_settings(provider_name)+ keys = SETUP_PROVIDER_SITE_SETTING_KEYS[provider_name]+ return {} unless keys+ return {} if params[:provider_site_settings].blank?++ params[:provider_site_settings].permit(*keys).to_h.with_indifferent_access+ endenddiff --git a/plugins/discourse-chat-integration/app/routes/discourse_chat_integration.rb b/plugins/discourse-chat-integration/app/routes/discourse_chat_integration.rbindex 9577761aec1..55920286f2c 100644--- a/plugins/discourse-chat-integration/app/routes/discourse_chat_integration.rb+++ b/plugins/discourse-chat-integration/app/routes/discourse_chat_integration.rb@@ -7,6 +7,7 @@ module DiscourseChatIntegrationget "" => "chat#respond"get "/providers" => "chat#list_providers"get "/providers/:provider" => "chat#respond"+ post "/setup-provider" => "chat#setup_provider"post "/test" => "chat#test"get "/channels" => "chat#list_channels"diff --git a/plugins/discourse-chat-integration/assets/stylesheets/chat-integration.scss b/plugins/discourse-chat-integration/assets/stylesheets/chat-integration.scssindex 3c95ac5c9d9..7c1f457fba0 100644--- a/plugins/discourse-chat-integration/assets/stylesheets/chat-integration.scss+++ b/plugins/discourse-chat-integration/assets/stylesheets/chat-integration.scss@@ -109,6 +109,12 @@}}+.chat-integration-setup-provider-modal {+ &__instructions {+ margin-top: 0;+ }+}+.chat-integration-modal {.provider-name {font-weight: 600;diff --git a/plugins/discourse-chat-integration/config/locales/client.en.yml b/plugins/discourse-chat-integration/config/locales/client.en.ymlindex 572d1213b06..4b462f7d693 100644--- a/plugins/discourse-chat-integration/config/locales/client.en.yml+++ b/plugins/discourse-chat-integration/config/locales/client.en.yml@@ -12,11 +12,33 @@ en:providers: "Providers"providers_description: "Configure chat provider integrations"add_provider: "Add provider"+ view_provider_settings: "View provider settings"more_providers: "More"+ confirm_setup_provider: "Are you sure you want to enable the %{provider} provider? It can be disabled later in the Settings tab."+ setup_provider_modal:+ title: "Setup %{provider} provider"+ setup_instructions: "Please provide the following details to setup the %{provider} provider. %{additionalInstructions}"+ confirm_setup: "Confirm setup"+ success: "Provider %{provider} setup successfully"+ slack:+ instructions: "Either access token or outbound webhook URL is required."+ at_least_one_required: "Enter an access token or outbound webhook URL."+ access_token:+ title: "Access token"+ description: "The Slack bot OAuth access token"+ outbound_webhook_url:+ title: "Outbound webhook URL"+ description: "The Slack outbound webhook URL"+ telegram:+ instructions: "Access token will be validated on save."+ access_token:+ title: "Access token"+ description: "The Telegram bot access token from BotFather"empty_state:title: "Connect your chat platform"body: "Send notifications from Discourse to your team's chat. Choose a provider to get started."channels_title: "Channels"+ channels_description: "Configure channels for the %{provider} provider."no_channels: "No channels have been configured yet."channel_actions: "Channel actions"add_first_channel: "Add your first %{provider} channel"@@ -93,6 +115,8 @@ en:title: Channelhelp: "For example #channel or @username"errors:+ at_least_one_required: "Enter an access token or outbound webhook URL."+ invalid_webhook_url: "The outbound webhook URL must be a valid https://hooks.slack.com/services/... link."auth_error: "The provided authentication token is invalid"action_prohibited: "The bot does not have permission to post to that channel"channel_not_found: "The specified channel does not exist on Slack"@@ -110,6 +134,8 @@ en:title: Chat IDhelp: A number given to you by the bot, or a broadcast channel identifier in the form @channelnameerrors:+ access_token_required: "A bot access token is required."+ webhook_setup_failed: "Could not register the webhook with Telegram. Check the token and try again."channel_not_found: "The specified channel does not exist on Telegram"forbidden: "The bot does not have permission to post to this channel"diff --git a/plugins/discourse-chat-integration/config/locales/server.en.yml b/plugins/discourse-chat-integration/config/locales/server.en.ymlindex 172f534ffd1..50238f5c833 100644--- a/plugins/discourse-chat-integration/config/locales/server.en.yml+++ b/plugins/discourse-chat-integration/config/locales/server.en.yml@@ -121,8 +121,8 @@ en:title: Send Slack messagesend_chat_integration_message:title: Send Chat-Integration message- chat_integration:+ chat_integration:all_categories: "(all categories)"deleted_category: "(deleted category)"deleted_group: "(deleted group)"@@ -130,12 +130,16 @@ en:group_mention_template: "mentions of: @%{name}"group_message_template: "messages to: @%{name}"-topic_tag_changed:added_and_removed: "Added %{added} and removed %{removed}"added: "Added %{added}"removed: "Removed %{removed}"+ errors:+ provider_already_enabled: "Provider '%{name}' is already enabled"+ provider_not_found: "Provider '%{name}' not found"+ setting_update_failed: "Failed to update settings: %{errors}"+provider:#######################################diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider.rbindex 5397a7d8bfd..84a02570840 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider.rb@@ -19,16 +19,26 @@ module DiscourseChatIntegrationself.providers.select { |provider| self.is_enabled(provider) }end+ def self.disabled_providers+ self+ .providers+ .reject { |provider| self.is_enabled(provider) }+ .sort_by do |provider|+ score = defined?(provider::POPULARITY_SCORE) ? provider::POPULARITY_SCORE : 0+ [-score, provider::PROVIDER_NAME]+ end+ end+def self.provider_names- self.providers.map! { |x| x::PROVIDER_NAME }+ self.providers.map! { |provider_klass| provider_klass::PROVIDER_NAME }enddef self.enabled_provider_names- self.enabled_providers.map! { |x| x::PROVIDER_NAME }+ self.enabled_providers.map! { |provider_klass| provider_klass::PROVIDER_NAME }enddef self.get_by_name(name)- self.providers.find { |p| p::PROVIDER_NAME == name }+ self.providers.find { |provider_klass| provider_klass::PROVIDER_NAME == name }enddef self.is_enabled(provider)@@ -41,6 +51,14 @@ module DiscourseChatIntegrationendend+ def self.setup(provider_klass, current_user, provider_site_settings)+ if provider_klass.respond_to?(:setup)+ provider_klass.setup(current_user, provider_site_settings)+ else+ SiteSetting.set_and_log(provider_klass::PROVIDER_ENABLED_SETTING, true, current_user)+ end+ end+class HookEngine < ::Rails::Engineengine_name PLUGIN_NAME + "-hooks"isolate_namespace Providerdiff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/discord/discord_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/discord/discord_provider.rbindex 9a2453eb2ca..09829e5d97e 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/discord/discord_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/discord/discord_provider.rb@@ -4,6 +4,7 @@ module DiscourseChatIntegrationmodule Providermodule DiscordProviderPROVIDER_NAME = "discord"+ POPULARITY_SCORE = 100PROVIDER_ENABLED_SETTING = :chat_integration_discord_enabledCHANNEL_IDENTIFIER_KEY = "name"CHANNEL_PARAMETERS = [diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/gitter/gitter_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/gitter/gitter_provider.rbindex d5051f405bb..4ba08c6251a 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/gitter/gitter_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/gitter/gitter_provider.rb@@ -4,6 +4,7 @@ module DiscourseChatIntegrationmodule Providermodule GitterProviderPROVIDER_NAME = "gitter"+ POPULARITY_SCORE = 80PROVIDER_ENABLED_SETTING = :chat_integration_gitter_enabledCHANNEL_IDENTIFIER_KEY = "name"CHANNEL_PARAMETERS = [diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/google/google_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/google/google_provider.rbindex c339b91cee7..8ed08d2e2ce 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/google/google_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/google/google_provider.rb@@ -4,6 +4,7 @@ module DiscourseChatIntegrationmodule Providermodule GoogleProviderPROVIDER_NAME = "google"+ POPULARITY_SCORE = 80PROVIDER_ENABLED_SETTING = :chat_integration_google_enabledCHANNEL_IDENTIFIER_KEY = "name"CHANNEL_PARAMETERS = [diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/groupme/groupme_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/groupme/groupme_provider.rbindex 02a7c9f3742..9699af436d1 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/groupme/groupme_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/groupme/groupme_provider.rb@@ -1,6 +1,7 @@# frozen_string_literal: truemodule DiscourseChatIntegration::Provider::GroupmeProviderPROVIDER_NAME = "groupme"+ POPULARITY_SCORE = 50PROVIDER_ENABLED_SETTING = :chat_integration_groupme_enabledCHANNEL_IDENTIFIER_KEY = "groupme_instance_name"CHANNEL_PARAMETERS = [{ key: "groupme_instance_name", regex: '[\s\S]*', unique: true }]diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/guilded/guilded_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/guilded/guilded_provider.rbindex ee117ae0c41..59da14a8b74 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/guilded/guilded_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/guilded/guilded_provider.rb@@ -4,6 +4,7 @@ module DiscourseChatIntegrationmodule Providermodule GuildedProviderPROVIDER_NAME = "guilded"+ POPULARITY_SCORE = 50PROVIDER_ENABLED_SETTING = :chat_integration_guilded_enabledCHANNEL_IDENTIFIER_KEY = "name"CHANNEL_PARAMETERS = [diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/matrix/matrix_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/matrix/matrix_provider.rbindex 16f166f752f..2e7683c84b0 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/matrix/matrix_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/matrix/matrix_provider.rb@@ -4,6 +4,7 @@ module DiscourseChatIntegrationmodule Providermodule MatrixProviderPROVIDER_NAME = "matrix"+ POPULARITY_SCORE = 80PROVIDER_ENABLED_SETTING = :chat_integration_matrix_enabledCHANNEL_IDENTIFIER_KEY = "name"CHANNEL_PARAMETERS = [diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/mattermost/mattermost_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/mattermost/mattermost_provider.rbindex d8e723bd6d3..b7796f21983 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/mattermost/mattermost_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/mattermost/mattermost_provider.rb@@ -4,6 +4,7 @@ module DiscourseChatIntegrationmodule Providermodule MattermostProviderPROVIDER_NAME = "mattermost"+ POPULARITY_SCORE = 80PROVIDER_ENABLED_SETTING = :chat_integration_mattermost_enabledCHANNEL_IDENTIFIER_KEY = "identifier"CHANNEL_PARAMETERS = [{ key: "identifier", regex: '^[@#]\S*$', unique: true }]diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/powerautomate/powerautomate_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/powerautomate/powerautomate_provider.rbindex 097343759e3..6c9857d5ff7 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/powerautomate/powerautomate_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/powerautomate/powerautomate_provider.rb@@ -2,6 +2,7 @@module DiscourseChatIntegration::Provider::PowerAutomateProviderPROVIDER_NAME = "powerautomate"+ POPULARITY_SCORE = 80PROVIDER_ENABLED_SETTING = :chat_integration_powerautomate_enabledCHANNEL_IDENTIFIER_KEY = "name"CHANNEL_PARAMETERS = [diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/rocketchat/rocketchat_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/rocketchat/rocketchat_provider.rbindex dbfa3f0fce8..445a0753b27 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/rocketchat/rocketchat_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/rocketchat/rocketchat_provider.rb@@ -2,6 +2,7 @@module DiscourseChatIntegration::Provider::RocketchatProviderPROVIDER_NAME = "rocketchat"+ POPULARITY_SCORE = 50PROVIDER_ENABLED_SETTING = :chat_integration_rocketchat_enabledCHANNEL_IDENTIFIER_KEY = "identifier"diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rbindex 9f4fae4a9f2..73e7dcf22e4 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/slack/slack_provider.rb@@ -2,6 +2,7 @@module DiscourseChatIntegration::Provider::SlackProviderPROVIDER_NAME = "slack"+ POPULARITY_SCORE = 100THREAD_CUSTOM_FIELD_PREFIX = "slack_thread_id_"# In the past, only one thread_ts was stored for each topic.@@ -14,6 +15,7 @@ module DiscourseChatIntegration::Provider::SlackProviderPROVIDER_ENABLED_SETTING = :chat_integration_slack_enabledCHANNEL_IDENTIFIER_KEY = "identifier"CHANNEL_PARAMETERS = [{ key: "identifier", regex: '^[@#]?\S*$', unique: true }]+ ADDITIONAL_SITE_SETTINGS_REQUIRED = truerequire_dependency "topic"::Topic.register_custom_field_type(@@ -21,6 +23,120 @@ module DiscourseChatIntegration::Provider::SlackProvider:string,)+ def self.setup(current_user, provider_site_settings = {})+ token = provider_site_settings[:chat_integration_slack_access_token].to_s.strip+ webhook_url = provider_site_settings[:chat_integration_slack_outbound_webhook_url].to_s.strip++ if token.blank? && webhook_url.blank?+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.slack.errors.at_least_one_required",+ },+ )+ end++ verify_slack_access_token!(token) if token.present?++ # Incoming webhooks have no auth.test equivalent; validate URL shape only (no live POST to avoid posting to the channel).+ if webhook_url.present? && !valid_slack_incoming_webhook_url?(webhook_url)+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.slack.errors.invalid_webhook_url",+ },+ )+ end++ settings = []++ if token.present?+ settings.push({ setting_name: :chat_integration_slack_access_token, value: token })+ end++ if webhook_url.present?+ settings.push(+ { setting_name: :chat_integration_slack_outbound_webhook_url, value: webhook_url },+ )+ end++ setting_update_result =+ SiteSetting::Update.call(params: { settings: }, guardian: current_user.guardian)++ if !setting_update_result.success?+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.errors.setting_update_failed",+ response_body: setting_update_result.errors,+ },+ )+ end++ # The enable setting update needs to be separate because we have a site+ # setting validator that depends on the other settings being set.+ setting_update_result =+ SiteSetting::Update.call(+ params: {+ settings: [{ setting_name: PROVIDER_ENABLED_SETTING, value: true }],+ },+ guardian: current_user.guardian,+ )++ if !setting_update_result.success?+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.errors.setting_update_failed",+ response_body: setting_update_result.errors,+ },+ )+ end+ end++ def self.verify_slack_access_token!(token)+ http = slack_api_http+ req = Net::HTTP::Post.new(URI("https://slack.com/api/auth.test"))+ req.set_form_data(token: token)+ response = http.request(req)++ unless response.kind_of?(Net::HTTPSuccess)+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.slack.errors.auth_error",+ response_code: response.code,+ response_body: response.body,+ },+ )+ end++ json =+ begin+ JSON.parse(response.body)+ rescue JSON::ParserError+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.slack.errors.auth_error",+ response_body: response.body,+ },+ )+ end++ unless json["ok"] == true+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.slack.errors.auth_error",+ response_body: json,+ },+ )+ end+ end++ def self.valid_slack_incoming_webhook_url?(url)+ uri = URI.parse(url)+ return false unless uri.is_a?(URI::HTTPS) && uri.host == "hooks.slack.com"++ uri.path.start_with?("/services/") || uri.path.start_with?("/workflows/")+ rescue URI::InvalidURIError+ false+ end+def self.excerpt(post, max_length = SiteSetting.chat_integration_slack_excerpt_length)doc =Nokogiri::HTML5.fragment(diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/teams/teams_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/teams/teams_provider.rbindex 8d6fa27bdc7..7c1e2a5bfde 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/teams/teams_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/teams/teams_provider.rb@@ -2,6 +2,7 @@module DiscourseChatIntegration::Provider::TeamsProviderPROVIDER_NAME = "teams"+ POPULARITY_SCORE = 100PROVIDER_ENABLED_SETTING = :chat_integration_teams_enabledCHANNEL_IDENTIFIER_KEY = "name"CHANNEL_PARAMETERS = [diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rbindex 986fd479e7d..54e6e77a480 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/telegram/telegram_provider.rb@@ -4,28 +4,76 @@ module DiscourseChatIntegrationmodule Providermodule TelegramProviderPROVIDER_NAME = "telegram"+ POPULARITY_SCORE = 100PROVIDER_ENABLED_SETTING = :chat_integration_telegram_enabledCHANNEL_IDENTIFIER_KEY = "name"CHANNEL_PARAMETERS = [{ key: "name", regex: '^\S+' },{ key: "chat_id", regex: '^(-?[0-9]+|@\S+)$', unique: true },]+ ADDITIONAL_SITE_SETTINGS_REQUIRED = true- def self.setup_webhook- newSecret = SecureRandom.hex- SiteSetting.chat_integration_telegram_secret = newSecret+ def self.setup(current_user, provider_site_settings = {})+ access_token = provider_site_settings[:chat_integration_telegram_access_token].to_s.strip- message = { url: Discourse.base_url + "/chat-integration/telegram/command/" + newSecret }+ if access_token.blank?+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.telegram.errors.access_token_required",+ },+ )+ end++ new_secret = SecureRandom.hex+ setup_webhook(access_token, new_secret)++ setting_update_result =+ SiteSetting::Update.call(+ params: {+ settings: [+ { setting_name: :chat_integration_telegram_access_token, value: access_token },+ { setting_name: :chat_integration_telegram_secret, value: new_secret },+ { setting_name: PROVIDER_ENABLED_SETTING, value: true },+ ],+ },+ guardian: current_user.guardian,+ options: {+ allow_changing_hidden: [:chat_integration_telegram_secret],+ },+ )++ if !setting_update_result.success?+ self.do_api_request("deleteWebhook", {})+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.errors.setting_update_failed",+ response_body: setting_update_result.errors,+ },+ )+ end+ end++ def self.setup_webhook(access_token, new_secret)+ webhook_message = {+ url: "#{Discourse.base_url}/chat-integration/telegram/command/#{new_secret}",+ }- response = self.do_api_request("setWebhook", message)+ response =+ begin+ self.do_api_request("setWebhook", webhook_message, access_token: access_token)+ rescue JSON::ParserError => err+ Rails.logger.error("Failed to parse telegram setWebhook response: #{err.message}")+ { "ok" => false, "description" => err.message }+ endif response["ok"] != true- # If setting up webhook failed, disable provider- SiteSetting.chat_integration_telegram_enabled = false- Rails.logger.error(- "Failed to setup telegram webhook. Message data= " + message.to_json + " response=" +- response.to_json,- )+ Rails.logger.error("Failed to setup telegram webhook. response=#{response.to_json}")+ raise DiscourseChatIntegration::ProviderError.new(+ info: {+ error_key: "chat_integration.provider.telegram.errors.webhook_setup_failed",+ response_body: response,+ },+ )endend@@ -33,21 +81,19 @@ module DiscourseChatIntegrationself.do_api_request("sendMessage", message)end- def self.do_api_request(methodName, message)+ def self.do_api_request(method_name, message, access_token: nil)http = FinalDestination::HTTP.new("api.telegram.org", 443)http.use_ssl = true- access_token = SiteSetting.chat_integration_telegram_access_token+ token = access_token.presence || SiteSetting.chat_integration_telegram_access_token- uri = URI("https://api.telegram.org/bot#{access_token}/#{methodName}")+ uri = URI("https://api.telegram.org/bot#{token}/#{method_name}")req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json")req.body = message.to_jsonresponse = http.request(req)- responseData = JSON.parse(response.body)-- responseData+ JSON.parse(response.body)enddef self.message_text(post)@@ -55,21 +101,6 @@ module DiscourseChatIntegrationtopic = post.topic- category = ""- if topic.category- category =- (- if (topic.category.parent_category)- "[#{topic.category.parent_category.name}/#{topic.category.name}]"- else- "[#{topic.category.name}]"- end- )- end-- tags = ""- tags = topic.tags.map(&:name).join(", ") if topic.tags.present?-I18n.t("chat_integration.provider.telegram.message",user: display_name,diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/webex/webex_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/webex/webex_provider.rbindex 5bd750c5007..a9dc4c9e101 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/webex/webex_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/webex/webex_provider.rb@@ -2,6 +2,7 @@module DiscourseChatIntegration::Provider::WebexProviderPROVIDER_NAME = "webex"+ POPULARITY_SCORE = 50PROVIDER_ENABLED_SETTING = :chat_integration_webex_enabledCHANNEL_IDENTIFIER_KEY = "name"CHANNEL_PARAMETERS = [diff --git a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/zulip/zulip_provider.rb b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/zulip/zulip_provider.rbindex e306bd62396..e871ae4089e 100644--- a/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/zulip/zulip_provider.rb+++ b/plugins/discourse-chat-integration/lib/discourse_chat_integration/provider/zulip/zulip_provider.rb@@ -4,6 +4,7 @@ module DiscourseChatIntegrationmodule Providermodule ZulipProviderPROVIDER_NAME = "zulip"+ POPULARITY_SCORE = 80PROVIDER_ENABLED_SETTING = :chat_integration_zulip_enabledCHANNEL_IDENTIFIER_KEY = "stream"CHANNEL_PARAMETERS = [diff --git a/plugins/discourse-chat-integration/plugin.rb b/plugins/discourse-chat-integration/plugin.rbindex 62b869f8896..8ac5eef0d0c 100644--- a/plugins/discourse-chat-integration/plugin.rb+++ b/plugins/discourse-chat-integration/plugin.rb@@ -29,26 +29,13 @@ after_initialize doregister_problem_check ProblemCheck::ChannelErrors- on(:site_setting_changed) do |setting_name, old_value, new_value|- is_enabled_setting = setting_name == :chat_integration_telegram_enabled- is_access_token = setting_name == :chat_integration_telegram_access_token-- if (is_enabled_setting || is_access_token)- enabled =- is_enabled_setting ? new_value == true : SiteSetting.chat_integration_telegram_enabled-- if enabled && SiteSetting.chat_integration_telegram_access_token.present?- Scheduler::Defer.later("Setup Telegram Webhook") do- DiscourseChatIntegration::Provider::TelegramProvider.setup_webhook- end- end- end- end-on(:post_created) do |post|# This will run for every post, even PMs. Don't worry, they're filtered out later.- time = SiteSetting.chat_integration_delay_seconds.seconds- Jobs.enqueue_in(time, :notify_chats, post_id: post.id)+ Jobs.enqueue_in(+ SiteSetting.chat_integration_delay_seconds.seconds,+ :notify_chats,+ post_id: post.id,+ )endadd_admin_route "chat_integration.menu_title",diff --git a/plugins/discourse-chat-integration/spec/dummy_provider.rb b/plugins/discourse-chat-integration/spec/dummy_provider.rbindex 3d3560abd33..be5ff80cb71 100644--- a/plugins/discourse-chat-integration/spec/dummy_provider.rb+++ b/plugins/discourse-chat-integration/spec/dummy_provider.rb@@ -4,7 +4,9 @@ RSpec.shared_context "with dummy provider" dobefore(:each) domodule DiscourseChatIntegration::Provider::DummyProviderPROVIDER_NAME = "dummy"- PROVIDER_ENABLED_SETTING = :chat_integration_enabled # Tie to main plugin enabled setting+ # Fake site settings come from the spec/support/dummy_plugin_site_settings.yml file+ PROVIDER_ENABLED_SETTING = :dummy_provider_enabled+ POPULARITY_SCORE = 5CHANNEL_PARAMETERS = []@@sent_messages = []@@ -39,8 +41,10 @@ RSpec.shared_context "with validated dummy provider" dobefore(:each) domodule DiscourseChatIntegration::Provider::Dummy2ProviderPROVIDER_NAME = "dummy2"- PROVIDER_ENABLED_SETTING = :chat_integration_enabled # Tie to main plugin enabled setting+ # Fake site settings come from the spec/support/dummy_plugin_site_settings.yml file+ PROVIDER_ENABLED_SETTING = :other_dummy_provider_enabledCHANNEL_IDENTIFIER_KEY = "val"+ POPULARITY_SCORE = 5CHANNEL_PARAMETERS = [{ key: "val", regex: '^\S+$', unique: true }]@@sent_messages = []diff --git a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/slack/slack_provider_spec.rb b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/slack/slack_provider_spec.rbindex fd18cc33bfb..c3174ac8c2d 100644--- a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/slack/slack_provider_spec.rb+++ b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/slack/slack_provider_spec.rb@@ -59,6 +59,50 @@ RSpec.describe DiscourseChatIntegration::Provider::SlackProvider doendend+ describe ".valid_slack_incoming_webhook_url?" do+ it "returns true for an incoming webhook URL under /services/" do+ expect(+ described_class.valid_slack_incoming_webhook_url?(+ "https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",+ ),+ ).to eq(true)+ end++ it "returns true for a workflow webhook URL under /workflows/" do+ expect(+ described_class.valid_slack_incoming_webhook_url?(+ "https://hooks.slack.com/workflows/0000000000000/0000000000000/XXXXXXXXXXXXXXXXXXXXXXXX",+ ),+ ).to eq(true)+ end++ it "returns false for http" do+ expect(+ described_class.valid_slack_incoming_webhook_url?(+ "http://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",+ ),+ ).to eq(false)+ end++ it "returns false when the host is not hooks.slack.com" do+ expect(+ described_class.valid_slack_incoming_webhook_url?(+ "https://evil.example.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX",+ ),+ ).to eq(false)+ end++ it "returns false when the path is not /services/ or /workflows/" do+ expect(+ described_class.valid_slack_incoming_webhook_url?("https://hooks.slack.com/other/path"),+ ).to eq(false)+ end++ it "returns false for an invalid URL" do+ expect(described_class.valid_slack_incoming_webhook_url?("not a url")).to eq(false)+ end+ end+describe ".trigger_notifications" dobefore doSiteSetting.chat_integration_slack_outbound_webhook_url =@@ -357,4 +401,160 @@ RSpec.describe DiscourseChatIntegration::Provider::SlackProvider doexpect(described_class.get_channel_by_name("#general")).to eq(expected)endend++ describe ".setup" do+ fab!(:admin)++ before do+ SiteSetting.chat_integration_slack_enabled = false+ SiteSetting.chat_integration_slack_access_token = ""+ SiteSetting.chat_integration_slack_outbound_webhook_url = ""+ end++ it "raises when both token and webhook URL are blank" do+ expect { described_class.setup(admin, {}) }.to raise_error(+ DiscourseChatIntegration::ProviderError,+ ) do |e|+ expect(e.info[:error_key]).to eq(+ "chat_integration.provider.slack.errors.at_least_one_required",+ )+ end+ end++ it "calls auth.test and persists token when token is provided" do+ stub =+ stub_request(:post, "https://slack.com/api/auth.test").to_return(+ body: { ok: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ described_class.setup(admin, { chat_integration_slack_access_token: "xoxb-test-token" })++ expect(stub).to have_been_requested.once+ expect(SiteSetting.chat_integration_slack_access_token).to eq("xoxb-test-token")+ expect(SiteSetting.chat_integration_slack_enabled).to eq(true)+ end++ it "raises when auth.test returns ok false" do+ stub_request(:post, "https://slack.com/api/auth.test").to_return(+ body: { ok: false, error: "invalid_auth" }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ expect {+ described_class.setup(admin, { chat_integration_slack_access_token: "bad" })+ }.to raise_error(DiscourseChatIntegration::ProviderError) do |e|+ expect(e.info[:error_key]).to eq("chat_integration.provider.slack.errors.auth_error")+ end+ end++ it "persists webhook URL and enables provider when only webhook is provided" do+ url = "https://hooks.slack.com/services/T00000000/B00000000/xxxxxxxxxxxxxxxxxxxxxxxx"++ described_class.setup(admin, { chat_integration_slack_outbound_webhook_url: url })++ expect(SiteSetting.chat_integration_slack_outbound_webhook_url).to eq(url)+ expect(SiteSetting.chat_integration_slack_enabled).to eq(true)+ end++ it "raises when webhook URL is not a valid Slack incoming webhook URL" do+ expect {+ described_class.setup(+ admin,+ { chat_integration_slack_outbound_webhook_url: "https://example.com/hook" },+ )+ }.to raise_error(DiscourseChatIntegration::ProviderError) do |e|+ expect(e.info[:error_key]).to eq(+ "chat_integration.provider.slack.errors.invalid_webhook_url",+ )+ end+ end++ it "raises when webhook URL uses HTTP instead of HTTPS" do+ expect {+ described_class.setup(+ admin,+ {+ chat_integration_slack_outbound_webhook_url:+ "http://hooks.slack.com/services/T00000000/B00000000/xxx",+ },+ )+ }.to raise_error(DiscourseChatIntegration::ProviderError) do |e|+ expect(e.info[:error_key]).to eq(+ "chat_integration.provider.slack.errors.invalid_webhook_url",+ )+ end+ end++ it "raises when webhook URL has wrong path prefix" do+ expect {+ described_class.setup(+ admin,+ { chat_integration_slack_outbound_webhook_url: "https://hooks.slack.com/other/path" },+ )+ }.to raise_error(DiscourseChatIntegration::ProviderError) do |e|+ expect(e.info[:error_key]).to eq(+ "chat_integration.provider.slack.errors.invalid_webhook_url",+ )+ end+ end++ it "accepts a valid /workflows/ webhook URL" do+ url = "https://hooks.slack.com/workflows/T00000000/B00000000/xxxxxxxxxxxxxxxxxxxxxxxx"++ described_class.setup(admin, { chat_integration_slack_outbound_webhook_url: url })++ expect(SiteSetting.chat_integration_slack_outbound_webhook_url).to eq(url)+ expect(SiteSetting.chat_integration_slack_enabled).to eq(true)+ end++ it "persists both token and webhook when both are provided" do+ stub_request(:post, "https://slack.com/api/auth.test").to_return(+ body: { ok: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ hook = "https://hooks.slack.com/services/T00000000/B00000000/xxxxxxxxxxxxxxxxxxxxxxxx"++ described_class.setup(+ admin,+ {+ chat_integration_slack_access_token: "xoxb-both",+ chat_integration_slack_outbound_webhook_url: hook,+ },+ )++ expect(SiteSetting.chat_integration_slack_access_token).to eq("xoxb-both")+ expect(SiteSetting.chat_integration_slack_outbound_webhook_url).to eq(hook)+ end++ it "raises when webhook URL is invalid even if the token is valid" do+ stub_request(:post, "https://slack.com/api/auth.test").to_return(+ body: { ok: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ expect {+ described_class.setup(+ admin,+ {+ chat_integration_slack_access_token: "xoxb-good",+ chat_integration_slack_outbound_webhook_url: "https://example.com/hook",+ },+ )+ }.to raise_error(DiscourseChatIntegration::ProviderError) do |e|+ expect(e.info[:error_key]).to eq(+ "chat_integration.provider.slack.errors.invalid_webhook_url",+ )+ end+ end+ endenddiff --git a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_provider_spec.rb b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_provider_spec.rbindex b505126293f..ba75d99b390 100644--- a/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_provider_spec.rb+++ b/plugins/discourse-chat-integration/spec/lib/discourse_chat_integration/provider/telegram/telegram_provider_spec.rb@@ -60,4 +60,65 @@ RSpec.describe DiscourseChatIntegration::Provider::TelegramProvider doexpect(described_class.get_channel_by_name("Awesome Channel")).to eq(expected)endend++ describe ".setup" do+ fab!(:admin)++ before do+ SiteSetting.chat_integration_telegram_enabled = false+ SiteSetting.chat_integration_telegram_access_token = ""+ SiteSetting.chat_integration_telegram_secret = ""+ end++ it "raises when access token is blank" do+ expect { described_class.setup(admin, {}) }.to raise_error(+ DiscourseChatIntegration::ProviderError,+ ) do |e|+ expect(e.info[:error_key]).to eq(+ "chat_integration.provider.telegram.errors.access_token_required",+ )+ end+ end++ it "persists settings when setWebhook succeeds" do+ stub =+ stub_request(:post, %r{https://api\.telegram\.org/botnewtok/setWebhook}).to_return(+ body: { ok: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ described_class.setup(admin, { chat_integration_telegram_access_token: "newtok" })++ expect(stub).to have_been_requested.once+ expect(SiteSetting.chat_integration_telegram_access_token).to eq("newtok")+ expect(SiteSetting.chat_integration_telegram_secret).to be_present+ expect(SiteSetting.chat_integration_telegram_enabled).to eq(true)+ end++ it "raises and does not change stored token when setWebhook fails" do+ SiteSetting.chat_integration_telegram_access_token = "unchanged"+ SiteSetting.chat_integration_telegram_secret = "existing-secret"++ stub_request(:post, %r{https://api\.telegram\.org/botbad/setWebhook}).to_return(+ body: { ok: false, description: "Bad Request" }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ expect {+ described_class.setup(admin, { chat_integration_telegram_access_token: "bad" })+ }.to raise_error(DiscourseChatIntegration::ProviderError) do |e|+ expect(e.info[:error_key]).to eq(+ "chat_integration.provider.telegram.errors.webhook_setup_failed",+ )+ end++ expect(SiteSetting.chat_integration_telegram_access_token).to eq("unchanged")+ expect(SiteSetting.chat_integration_telegram_secret).to eq("existing-secret")+ expect(SiteSetting.chat_integration_telegram_enabled).to eq(false)+ end+ endenddiff --git a/plugins/discourse-chat-integration/spec/requests/chat_controller_spec.rb b/plugins/discourse-chat-integration/spec/requests/chat_controller_spec.rbindex f1096bee7c7..adeba586693 100644--- a/plugins/discourse-chat-integration/spec/requests/chat_controller_spec.rb+++ b/plugins/discourse-chat-integration/spec/requests/chat_controller_spec.rb@@ -13,7 +13,10 @@ RSpec.describe "Chat Controller", type: :request doinclude_context "with dummy provider"include_context "with validated dummy provider"- before { SiteSetting.chat_integration_enabled = true }+ before do+ SiteSetting.chat_integration_enabled = true+ SiteSetting.dummy_provider_enabled = true+ endshared_examples "admin constraints" do |action, route|context "when user is not signed in" do@@ -47,14 +50,245 @@ RSpec.describe "Chat Controller", type: :request dojson = response.parsed_body- expect(json["providers"].size).to eq(2)+ expect(json["enabled_providers"].size).to eq(1)+ expect(json["disabled_providers"].size).to be > 0- expect(json["providers"].find { |h| h["name"] == "dummy" }).to eq(+ expect(json["enabled_providers"].find { |h| h["name"] == "dummy" }).to eq("name" => "dummy","id" => "dummy","channel_parameters" => [],)end++ it "returns available providers sorted by popularity descending then name" do+ get "/admin/plugins/discourse-chat-integration/providers.json"++ names = response.parsed_body["disabled_providers"].map { |p| p["name"] }++ expect(names).not_to be_empty+ expect(names).not_to include("dummy")++ # Providers with higher popularity scores should appear first+ slack_index = names.index("slack")+ webex_index = names.index("webex")+ expect(slack_index).not_to be_nil+ expect(webex_index).not_to be_nil+ expect(slack_index).to be < webex_index+ end+ end+ end++ describe "setup provider" do+ include_examples "admin constraints",+ "post",+ "/admin/plugins/discourse-chat-integration/setup-provider"++ context "when signed in as an admin" do+ before { sign_in(admin) }++ it "enables the provider site setting" do+ SiteSetting.dummy_provider_enabled = false+ post "/admin/plugins/discourse-chat-integration/setup-provider",+ params: {+ provider: {+ name: "dummy",+ },+ },+ as: :json+ expect(response.status).to eq(200)++ expect(SiteSetting.dummy_provider_enabled).to eq(true)+ end++ context "when the provider is unknown" do+ it "returns an error" do+ post "/admin/plugins/discourse-chat-integration/setup-provider",+ params: {+ provider: {+ name: "nonexistent_provider",+ },+ },+ as: :json++ expect(response.status).to eq(422)+ end+ end++ context "when the provider is already enabled" do+ it "returns an error" do+ SiteSetting.dummy_provider_enabled = true+ post "/admin/plugins/discourse-chat-integration/setup-provider",+ params: {+ provider: {+ name: "dummy",+ },+ },+ as: :json++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to include(+ I18n.t("chat_integration.errors.provider_already_enabled", name: "dummy"),+ )+ end+ end++ context "when setting up slack" do+ before do+ SiteSetting.chat_integration_slack_enabled = false+ SiteSetting.chat_integration_slack_access_token = ""+ end++ it "returns success and enables slack when the token is valid" do+ stub_request(:post, "https://slack.com/api/auth.test").to_return(+ body: { ok: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ post "/admin/plugins/discourse-chat-integration/setup-provider",+ params: {+ provider: {+ name: "slack",+ },+ provider_site_settings: {+ chat_integration_slack_access_token: "xoxb-from-request",+ },+ },+ as: :json++ expect(response.status).to eq(200)+ expect(SiteSetting.chat_integration_slack_enabled).to eq(true)+ expect(SiteSetting.chat_integration_slack_access_token).to eq("xoxb-from-request")+ end++ it "returns success when both token and webhook URL are provided" do+ stub_request(:post, "https://slack.com/api/auth.test").to_return(+ body: { ok: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ hook = "https://hooks.slack.com/services/t00000000/b00000000/xxxxxxxxxxxxxxxxxxxxxxxx"++ post "/admin/plugins/discourse-chat-integration/setup-provider",+ params: {+ provider: {+ name: "slack",+ },+ provider_site_settings: {+ chat_integration_slack_access_token: "xoxb-both",+ chat_integration_slack_outbound_webhook_url: hook,+ },+ },+ as: :json++ expect(response.status).to eq(200)+ expect(SiteSetting.chat_integration_slack_enabled).to eq(true)+ expect(SiteSetting.chat_integration_slack_access_token).to eq("xoxb-both")+ expect(SiteSetting.chat_integration_slack_outbound_webhook_url).to eq(hook)+ end++ it "returns success when only webhook URL is provided" do+ hook = "https://hooks.slack.com/services/t00000000/b00000000/xxxxxxxxxxxxxxxxxxxxxxxx"++ post "/admin/plugins/discourse-chat-integration/setup-provider",+ params: {+ provider: {+ name: "slack",+ },+ provider_site_settings: {+ chat_integration_slack_outbound_webhook_url: hook,+ },+ },+ as: :json+ expect(response.status).to eq(200)+ expect(SiteSetting.chat_integration_slack_enabled).to eq(true)+ expect(SiteSetting.chat_integration_slack_outbound_webhook_url).to eq(hook)+ end++ it "returns error_key when slack rejects the token" do+ stub_request(:post, "https://slack.com/api/auth.test").to_return(+ body: { ok: false, error: "invalid_auth" }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ post "/admin/plugins/discourse-chat-integration/setup-provider",+ params: {+ provider: {+ name: "slack",+ },+ provider_site_settings: {+ chat_integration_slack_access_token: "bad",+ },+ },+ as: :json++ expect(response.status).to eq(422)+ expect(response.parsed_body["error_key"]).to eq(+ "chat_integration.provider.slack.errors.auth_error",+ )+ end+ end++ context "when setting up telegram" do+ before do+ SiteSetting.chat_integration_telegram_enabled = false+ SiteSetting.chat_integration_telegram_access_token = ""+ end++ it "returns success when setWebhook succeeds" do+ stub_request(:post, %r{https://api\.telegram\.org/botreqtok/setWebhook}).to_return(+ body: { ok: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ post "/admin/plugins/discourse-chat-integration/setup-provider",+ params: {+ provider: {+ name: "telegram",+ },+ provider_site_settings: {+ chat_integration_telegram_access_token: "reqtok",+ },+ },+ as: :json++ expect(response.status).to eq(200)+ expect(SiteSetting.chat_integration_telegram_enabled).to eq(true)+ expect(SiteSetting.chat_integration_telegram_access_token).to eq("reqtok")+ end++ it "returns error_key when setWebhook fails" do+ stub_request(:post, %r{https://api\.telegram\.org/botbadtok/setWebhook}).to_return(+ body: { ok: false }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ post "/admin/plugins/discourse-chat-integration/setup-provider",+ params: {+ provider: {+ name: "telegram",+ },+ provider_site_settings: {+ chat_integration_telegram_access_token: "badtok",+ },+ },+ as: :json++ expect(response.status).to eq(422)+ expect(response.parsed_body["error_key"]).to eq(+ "chat_integration.provider.telegram.errors.webhook_setup_failed",+ )+ end+ endendenddiff --git a/plugins/discourse-chat-integration/spec/services/manager_spec.rb b/plugins/discourse-chat-integration/spec/services/manager_spec.rbindex ed038859ab5..c5180429272 100644--- a/plugins/discourse-chat-integration/spec/services/manager_spec.rb+++ b/plugins/discourse-chat-integration/spec/services/manager_spec.rb@@ -20,7 +20,10 @@ RSpec.describe DiscourseChatIntegration::Manager dolet(:chan2) { DiscourseChatIntegration::Channel.create!(provider: "dummy") }let(:chan3) { DiscourseChatIntegration::Channel.create!(provider: "dummy") }- before { SiteSetting.chat_integration_enabled = true }+ before do+ SiteSetting.chat_integration_enabled = true+ SiteSetting.dummy_provider_enabled = true+ endit "should fail gracefully when a provider throws an exception" doDiscourseChatIntegration::Rule.create!(@@ -52,7 +55,7 @@ RSpec.describe DiscourseChatIntegration::Manager doendit "should not send notifications when provider is disabled" do- SiteSetting.chat_integration_enabled = false+ SiteSetting.dummy_provider_enabled = falseDiscourseChatIntegration::Rule.create!(channel: chan1,filter: "watch",diff --git a/plugins/discourse-chat-integration/spec/services/problem_check/channel_errors_spec.rb b/plugins/discourse-chat-integration/spec/services/problem_check/channel_errors_spec.rbindex 64458b6d0c8..b8044184ec2 100644--- a/plugins/discourse-chat-integration/spec/services/problem_check/channel_errors_spec.rb+++ b/plugins/discourse-chat-integration/spec/services/problem_check/channel_errors_spec.rb@@ -7,14 +7,16 @@ RSpec.describe ProblemCheck::ChannelErrors dolet(:check) { described_class.new }+ before { SiteSetting.dummy_provider_enabled = true }+context "when chat integration is not enabled" do- before { SiteSetting.stubs(chat_integration_enabled: false) }+ before { SiteSetting.chat_integration_enabled = false }it { expect(check).to be_chill_about_it }endcontext "when chat integration is enabled" do- before { SiteSetting.stubs(chat_integration_enabled: true) }+ before { SiteSetting.chat_integration_enabled = true }context "when an enabled channel has errors" dobefore { Fabricate(:channel, provider: "dummy", error_key: "whoops") }diff --git a/plugins/discourse-chat-integration/spec/support/dummy_plugin_site_settings.yml b/plugins/discourse-chat-integration/spec/support/dummy_plugin_site_settings.ymlnew file mode 100644index 00000000000..5a1ac4aa346--- /dev/null+++ b/plugins/discourse-chat-integration/spec/support/dummy_plugin_site_settings.yml@@ -0,0 +1,5 @@+site_settings:+ dummy_provider_enabled:+ default: false+ other_dummy_provider_enabled:+ default: falsediff --git a/plugins/discourse-chat-integration/spec/system/create_channel_spec.rb b/plugins/discourse-chat-integration/spec/system/create_channel_spec.rbindex 9f4c81a2e20..82139fe7e04 100644--- a/plugins/discourse-chat-integration/spec/system/create_channel_spec.rb+++ b/plugins/discourse-chat-integration/spec/system/create_channel_spec.rb@@ -14,6 +14,7 @@ RSpec.describe "Create channel" dobefore doSiteSetting.chat_integration_enabled = trueSiteSetting.chat_integration_discord_enabled = true+ SiteSetting.dummy_provider_enabled = truesign_in(admin)enddiff --git a/plugins/discourse-chat-integration/spec/system/setup_provider_spec.rb b/plugins/discourse-chat-integration/spec/system/setup_provider_spec.rbnew file mode 100644index 00000000000..8955e80e658--- /dev/null+++ b/plugins/discourse-chat-integration/spec/system/setup_provider_spec.rb@@ -0,0 +1,161 @@+# frozen_string_literal: true++RSpec.describe "Chat integration setup provider" do+ fab!(:admin)++ let(:setup_page) { PageObjects::Pages::ChatIntegrationSetupProvider.new }+ let(:modal) { PageObjects::Modals::Base.new }+ let(:dialog) { PageObjects::Components::Dialog.new }++ before do+ enable_current_plugin+ SiteSetting.chat_integration_enabled = true+ sign_in(admin)+ end++ def setup_provider_from_menu(provider_name)+ visit "/admin/plugins/discourse-chat-integration/providers"++ setup_page.add_provider_menu.expand+ setup_page+ .add_provider_menu+ .option(".chat-integration-add-provider-button.--#{provider_name.downcase}")+ .click+ end++ describe "quick setup when no providers are enabled" do+ it "sets up Discord" do+ visit "/admin/plugins/discourse-chat-integration/providers"+ setup_page.setup_popular_provider("discord")++ expect(dialog).to be_open+ expect(dialog).to have_content(+ I18n.t("js.chat_integration.confirm_setup_provider", provider: "Discord"),+ )+ dialog.click_yes++ expect(page).to have_content(+ I18n.t("js.chat_integration.setup_provider_modal.success", provider: "Discord"),+ )+ expect(page).to have_current_path(+ %r{/admin/plugins/discourse-chat-integration/providers/discord},+ )+ expect(SiteSetting.chat_integration_discord_enabled).to eq(true)+ end+ end++ describe "adding more providers when at least one provider is enabled" do+ before { SiteSetting.chat_integration_teams_enabled = true }+ it "sets up Discord" do+ setup_provider_from_menu("discord")++ expect(dialog).to be_open+ expect(dialog).to have_content(+ I18n.t("js.chat_integration.confirm_setup_provider", provider: "Discord"),+ )+ dialog.click_yes++ expect(page).to have_content(+ I18n.t("js.chat_integration.setup_provider_modal.success", provider: "Discord"),+ )+ expect(page).to have_current_path(+ %r{/admin/plugins/discourse-chat-integration/providers/discord},+ )+ expect(SiteSetting.chat_integration_discord_enabled).to eq(true)+ end++ describe "providers which use the setup modal to fill additional fields" do+ it "sets up Slack from the modal when the token is valid" do+ stub_request(:post, "https://slack.com/api/auth.test").to_return(+ body: { ok: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ setup_provider_from_menu("slack")+ expect(modal).to be_open++ setup_page.fill_slack_access_token("xoxb-system-test")+ setup_page.submit++ expect(page).to have_content(+ I18n.t("js.chat_integration.setup_provider_modal.success", provider: "Slack"),+ )+ expect(page).to have_current_path(+ %r{/admin/plugins/discourse-chat-integration/providers/slack},+ )+ expect(SiteSetting.chat_integration_slack_enabled).to eq(true)+ end++ it "shows a field error on the webhook field when the URL is invalid" do+ setup_provider_from_menu("slack")+ expect(modal).to be_open++ setup_page.fill_slack_webhook_url("https://example.com/not-slack")+ setup_page.submit++ expect(setup_page.has_field_error?("chat_integration_slack_outbound_webhook_url")).to eq(+ true,+ )+ end++ it "shows a field error in the Slack modal when the token is rejected" do+ stub_request(:post, "https://slack.com/api/auth.test").to_return(+ body: { ok: false, error: "invalid_auth" }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ setup_provider_from_menu("slack")+ expect(modal).to be_open++ setup_page.fill_slack_access_token("xoxb-bad")+ setup_page.submit++ expect(setup_page.has_field_error?("chat_integration_slack_access_token")).to eq(true)+ end++ it "sets up Telegram from the modal when setWebhook succeeds" do+ stub_request(:post, %r{https://api\.telegram\.org/botsystok/setWebhook}).to_return(+ body: { ok: true }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ setup_provider_from_menu("telegram")+ expect(modal).to be_open++ setup_page.fill_telegram_access_token("systok")+ setup_page.submit++ expect(page).to have_content(+ I18n.t("js.chat_integration.setup_provider_modal.success", provider: "Telegram"),+ )+ expect(page).to have_current_path(+ %r{/admin/plugins/discourse-chat-integration/providers/telegram},+ )+ expect(SiteSetting.chat_integration_telegram_enabled).to eq(true)+ end++ it "shows a field error in the Telegram modal when setWebhook fails" do+ stub_request(:post, %r{https://api\.telegram\.org/botbadsys/setWebhook}).to_return(+ body: { ok: false }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ setup_provider_from_menu("telegram")+ expect(modal).to be_open++ setup_page.fill_telegram_access_token("badsys")+ setup_page.submit++ expect(setup_page.has_field_error?("chat_integration_telegram_access_token")).to eq(true)+ end+ end+ end+enddiff --git a/plugins/discourse-chat-integration/test/javascripts/acceptance/chat-integration-test.js b/plugins/discourse-chat-integration/test/javascripts/acceptance/chat-integration-test.jsindex 097769aeb58..47440f799bd 100755--- a/plugins/discourse-chat-integration/test/javascripts/acceptance/chat-integration-test.js+++ b/plugins/discourse-chat-integration/test/javascripts/acceptance/chat-integration-test.js@@ -24,17 +24,20 @@ acceptance("Chat Integration", function (needs) {});});- server.get("/admin/plugins/discourse-chat-integration/providers", () => {- return jsonResponse({- providers: [- {- name: "dummy",- id: "dummy",- channel_parameters: [{ key: "somekey", regex: "^\\S+$" }],- },- ],- });- });+ server.get(+ "/admin/plugins/discourse-chat-integration/providers.json",+ () => {+ return jsonResponse({+ enabled_providers: [+ {+ name: "dummy",+ id: "dummy",+ channel_parameters: [{ key: "somekey", regex: "^\\S+$" }],+ },+ ],+ });+ }+ );server.get("/admin/plugins/discourse-chat-integration/channels", () => {return jsonResponse({diff --git a/spec/system/page_objects/pages/chat_integration/setup_provider.rb b/spec/system/page_objects/pages/chat_integration/setup_provider.rbnew file mode 100644index 00000000000..5b3a99f7713--- /dev/null+++ b/spec/system/page_objects/pages/chat_integration/setup_provider.rb@@ -0,0 +1,48 @@+# frozen_string_literal: true++module PageObjects+ module Pages+ class ChatIntegrationSetupProvider < PageObjects::Pages::Base+ FORM_SCOPE = "#chat-integration-setup-provider-modal"++ def form+ @form ||= PageObjects::Components::FormKit.new(FORM_SCOPE)+ end++ def add_provider_menu+ PageObjects::Components::DMenu.new(find(".chat-integration-add-provider-trigger"))+ end++ def setup_popular_provider(provider_name)+ find(".chat-integration-providers-list").find(+ ".chat-integration-popular-provider-setup.--#{provider_name}",+ ).click+ self+ end++ def fill_slack_access_token(value)+ form.field("chat_integration_slack_access_token").fill_in(value)+ self+ end++ def fill_slack_webhook_url(value)+ form.field("chat_integration_slack_outbound_webhook_url").fill_in(value)+ self+ end++ def fill_telegram_access_token(value)+ form.field("chat_integration_telegram_access_token").fill_in(value)+ self+ end++ def submit+ form.submit+ self+ end++ def has_field_error?(field_name)+ within(FORM_SCOPE) { has_css?(".form-kit__field[data-name='#{field_name}'].has-error") }+ end+ end+ end+end