Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion docs/using-seerr/notifications/slack.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,28 @@ sidebar_position: 9

# Slack

The Slack notification agent enables you to post notifications to a channel in a workspace you manage.

:::info
Users can opt-in to being mentioned in Slack notifications by configuring their [Slack member ID(s)](https://slack.com/help/articles/221769328-Locate-your-Slack-URL-or-ID) in their user settings.
:::

## Configuration

### Webhook URL

Simply [create a webhook](https://my.slack.com/services/new/incoming-webhook/) and enter the URL in this field.

### Enable Mentions

When enabled, users who have configured their Slack member ID(s) will be mentioned in notifications relevant to their requests.

Slack surfaces mentions in the Activity feed even for muted channels, so users can mute the notification channel in Slack and still catch updates to their own requests.

:::info
Please refer to the [Slack API documentation](https://api.slack.com/messaging/webhooks) for more details on configuring these notifications.
:::

### Notification Language

Sets the language for notifications sent to this Slack channel.
Sets the language for notifications sent to this Slack channel.
12 changes: 12 additions & 0 deletions seerr-api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1435,6 +1435,8 @@ components:
properties:
webhookUrl:
type: string
enableMentions:
type: boolean
WebPushSettings:
type: object
properties:
Expand Down Expand Up @@ -1976,6 +1978,16 @@ components:
pushoverSound:
type: string
nullable: true
slackEnabled:
type: boolean
slackEnabledTypes:
type: number
nullable: true
slackIds:
type: array
items:
type: string
nullable: true
telegramEnabled:
type: boolean
telegramBotUsername:
Expand Down
1 change: 1 addition & 0 deletions server/constants/slack.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const SLACK_USER_ID_REGEX = /^[UW][A-Z0-9]{2,}$/;
3 changes: 3 additions & 0 deletions server/entity/UserSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@ export class UserSettings {
@Column({ type: 'text', nullable: true, transformer: jsonArrayTransformer })
public discordIds: string[];

@Column({ type: 'text', nullable: true, transformer: jsonArrayTransformer })
public slackIds: string[];

@Column({ nullable: true })
public pushbulletAccessToken?: string;

Expand Down
3 changes: 3 additions & 0 deletions server/interfaces/api/userSettingsInterfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ export interface UserSettingsNotificationsResponse {
pushoverApplicationToken?: string;
pushoverUserKey?: string;
pushoverSound?: string;
slackEnabled?: boolean;
slackEnabledTypes?: number;
slackIds?: string[];
telegramEnabled?: boolean;
telegramBotUsername?: string;
telegramChatId?: string;
Expand Down
113 changes: 107 additions & 6 deletions server/lib/notifications/agents/slack.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { IssueStatus, IssueTypeName } from '@server/constants/issue';
import { SLACK_USER_ID_REGEX } from '@server/constants/slack';
import { getRepository } from '@server/datasource';
import { User } from '@server/entity/User';
import { getIntl } from '@server/i18n';
import globalMessages from '@server/i18n/globalMessages';
import type { NotificationAgentSlack } from '@server/lib/settings';
import { getSettings } from '@server/lib/settings';
import { NotificationAgentKey, getSettings } from '@server/lib/settings';
import logger from '@server/logger';
import axios from 'axios';
import { Notification, hasNotificationType } from '..';
import {
Notification,
hasNotificationType,
shouldSendAdminNotification,
} from '..';
import type { NotificationAgent, NotificationPayload } from './agent';
import { BaseAgent } from './agent';

const isValidSlackUserId = (id: string): boolean =>
SLACK_USER_ID_REGEX.test(id);

interface EmbedField {
type: 'plain_text' | 'mrkdwn';
text: string;
Expand Down Expand Up @@ -47,6 +57,11 @@ interface SlackBlockEmbed {
blocks: EmbedBlock[];
}

interface SlackMentions {
notifyUser: string[];
admin: string[];
}

class SlackAgent
extends BaseAgent<NotificationAgentSlack>
implements NotificationAgent
Expand All @@ -63,7 +78,8 @@ class SlackAgent

public buildEmbed(
type: Notification,
payload: NotificationPayload
payload: NotificationPayload,
mentions: SlackMentions = { notifyUser: [], admin: [] }
): SlackBlockEmbed {
const settings = this.getSettings();
const intl = getIntl(settings.options.locale);
Expand All @@ -72,10 +88,24 @@ class SlackAgent

const fields: EmbedField[] = [];

const notifyUserMention = mentions.notifyUser.join(' ');
let notifyUserMentionInlined = false;

if (payload.request) {
if (
notifyUserMention &&
payload.notifyUser?.id === payload.request.requestedBy.id
) {
notifyUserMentionInlined = true;
}

fields.push({
type: 'mrkdwn',
text: `*${intl.formatMessage(globalMessages.requestedBy)}*\n${payload.request.requestedBy.displayName}`,
text: `*${intl.formatMessage(globalMessages.requestedBy)}*\n${
notifyUserMentionInlined
? notifyUserMention
: payload.request.requestedBy.displayName
}`,
});

let status = '';
Expand Down Expand Up @@ -110,10 +140,21 @@ class SlackAgent
text: `*${intl.formatMessage(globalMessages.commentFrom, { userName: payload.comment.user.displayName })}*\n${payload.comment.message}`,
});
} else if (payload.issue) {
if (
notifyUserMention &&
payload.notifyUser?.id === payload.issue.createdBy.id
) {
notifyUserMentionInlined = true;
}

fields.push(
{
type: 'mrkdwn',
text: `*${intl.formatMessage(globalMessages.reportedBy)}*\n${payload.issue.createdBy.displayName}`,
text: `*${intl.formatMessage(globalMessages.reportedBy)}*\n${
notifyUserMentionInlined
? notifyUserMention
: payload.issue.createdBy.displayName
}`,
},
{
type: 'mrkdwn',
Expand Down Expand Up @@ -184,6 +225,23 @@ class SlackAgent
});
}

const remainingMentions = [
...(notifyUserMentionInlined ? [] : mentions.notifyUser),
...mentions.admin,
];

if (remainingMentions.length > 0) {
blocks.push({
type: 'context',
elements: [
{
type: 'mrkdwn',
text: remainingMentions.join(' '),
},
],
});
}

const url = applicationUrl
? payload.issue
? `${applicationUrl}/issues/${payload.issue.id}`
Expand Down Expand Up @@ -248,10 +306,53 @@ class SlackAgent
type: Notification[type],
subject: payload.subject,
});

const mentions: SlackMentions = { notifyUser: [], admin: [] };

try {
if (settings.options.enableMentions) {
if (payload.notifyUser) {
if (
payload.notifyUser.settings?.hasNotificationType(
NotificationAgentKey.SLACK,
type
) &&
payload.notifyUser.settings.slackIds?.length
) {
const validIds = payload.notifyUser.settings.slackIds.filter((id) =>
isValidSlackUserId(id)
);
mentions.notifyUser.push(...validIds.map((id) => `<@${id}>`));
}
}

if (payload.notifyAdmin) {
const userRepository = getRepository(User);
const users = await userRepository.find();

mentions.admin.push(
...users
.filter(
(user) =>
user.settings?.hasNotificationType(
NotificationAgentKey.SLACK,
type
) &&
user.settings.slackIds?.length &&
shouldSendAdminNotification(type, user, payload)
)
.flatMap((user) =>
user
.settings!.slackIds.filter((id) => isValidSlackUserId(id))
.map((id) => `<@${id}>`)
)
);
}
}

await axios.post(
settings.options.webhookUrl,
this.buildEmbed(type, payload)
this.buildEmbed(type, payload, mentions)
);

return true;
Expand Down
2 changes: 2 additions & 0 deletions server/lib/settings/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ export interface NotificationAgentDiscord extends NotificationAgentConfig {
export interface NotificationAgentSlack extends NotificationAgentConfig {
options: {
webhookUrl: string;
enableMentions: boolean;
locale: AvailableLocale;
};
}
Expand Down Expand Up @@ -498,6 +499,7 @@ class Settings {
types: 0,
options: {
webhookUrl: '',
enableMentions: true,
locale: 'en',
},
},
Expand Down
15 changes: 15 additions & 0 deletions server/migration/postgres/1786670794836-AddSlackIdsColumn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { MigrationInterface, QueryRunner } from 'typeorm';

export class AddSlackIdsColumn1786670794836 implements MigrationInterface {
name = 'AddSlackIdsColumn1786670794836';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "user_settings" ADD "slackIds" text`);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "user_settings" DROP COLUMN "slackIds"`
);
}
}
31 changes: 31 additions & 0 deletions server/migration/sqlite/1786670782811-AddSlackIdsColumn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { MigrationInterface, QueryRunner } from 'typeorm';

export class AddSlackIdsColumn1786670782811 implements MigrationInterface {
name = 'AddSlackIdsColumn1786670782811';

public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`CREATE TABLE "temporary_user_settings" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "locale" varchar NOT NULL DEFAULT (''), "discoverRegion" varchar, "streamingRegion" varchar, "originalLanguage" varchar, "pgpKey" varchar, "discordIds" text, "pushbulletAccessToken" varchar, "pushoverApplicationToken" varchar, "pushoverUserKey" varchar, "pushoverSound" varchar, "telegramChatId" varchar, "telegramSendSilently" boolean, "watchlistSyncMovies" boolean, "watchlistSyncTv" boolean, "notificationTypes" text, "userId" integer, "telegramMessageThreadId" varchar, "slackIds" text, CONSTRAINT "REL_986a2b6d3c05eb4091bb8066f7" UNIQUE ("userId"), CONSTRAINT "FK_986a2b6d3c05eb4091bb8066f78" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`
);
await queryRunner.query(
`INSERT INTO "temporary_user_settings"("id", "locale", "discoverRegion", "streamingRegion", "originalLanguage", "pgpKey", "discordIds", "pushbulletAccessToken", "pushoverApplicationToken", "pushoverUserKey", "pushoverSound", "telegramChatId", "telegramSendSilently", "watchlistSyncMovies", "watchlistSyncTv", "notificationTypes", "userId", "telegramMessageThreadId") SELECT "id", "locale", "discoverRegion", "streamingRegion", "originalLanguage", "pgpKey", "discordIds", "pushbulletAccessToken", "pushoverApplicationToken", "pushoverUserKey", "pushoverSound", "telegramChatId", "telegramSendSilently", "watchlistSyncMovies", "watchlistSyncTv", "notificationTypes", "userId", "telegramMessageThreadId" FROM "user_settings"`
);
await queryRunner.query(`DROP TABLE "user_settings"`);
await queryRunner.query(
`ALTER TABLE "temporary_user_settings" RENAME TO "user_settings"`
);
}

public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "user_settings" RENAME TO "temporary_user_settings"`
);
await queryRunner.query(
`CREATE TABLE "user_settings" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "locale" varchar NOT NULL DEFAULT (''), "discoverRegion" varchar, "streamingRegion" varchar, "originalLanguage" varchar, "pgpKey" varchar, "discordIds" text, "pushbulletAccessToken" varchar, "pushoverApplicationToken" varchar, "pushoverUserKey" varchar, "pushoverSound" varchar, "telegramChatId" varchar, "telegramSendSilently" boolean, "watchlistSyncMovies" boolean, "watchlistSyncTv" boolean, "notificationTypes" text, "userId" integer, "telegramMessageThreadId" varchar, CONSTRAINT "REL_986a2b6d3c05eb4091bb8066f7" UNIQUE ("userId"), CONSTRAINT "FK_986a2b6d3c05eb4091bb8066f78" FOREIGN KEY ("userId") REFERENCES "user" ("id") ON DELETE CASCADE ON UPDATE NO ACTION)`
);
await queryRunner.query(
`INSERT INTO "user_settings"("id", "locale", "discoverRegion", "streamingRegion", "originalLanguage", "pgpKey", "discordIds", "pushbulletAccessToken", "pushoverApplicationToken", "pushoverUserKey", "pushoverSound", "telegramChatId", "telegramSendSilently", "watchlistSyncMovies", "watchlistSyncTv", "notificationTypes", "userId", "telegramMessageThreadId") SELECT "id", "locale", "discoverRegion", "streamingRegion", "originalLanguage", "pgpKey", "discordIds", "pushbulletAccessToken", "pushoverApplicationToken", "pushoverUserKey", "pushoverSound", "telegramChatId", "telegramSendSilently", "watchlistSyncMovies", "watchlistSyncTv", "notificationTypes", "userId", "telegramMessageThreadId" FROM "temporary_user_settings"`
);
await queryRunner.query(`DROP TABLE "temporary_user_settings"`);
}
}
14 changes: 13 additions & 1 deletion server/routes/user/usersettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -620,6 +620,13 @@ userSettingsRoutes.get<{ id: string }, UserSettingsNotificationsResponse>(
pushoverApplicationToken: user.settings?.pushoverApplicationToken,
pushoverUserKey: user.settings?.pushoverUserKey,
pushoverSound: user.settings?.pushoverSound,
slackEnabled:
settings?.slack.enabled && settings.slack.options.enableMentions,
slackEnabledTypes:
settings?.slack.enabled && settings.slack.options.enableMentions
? settings.slack.types
: 0,
slackIds: user.settings?.slackIds ?? [],
telegramEnabled: settings.telegram.enabled,
telegramBotUsername: settings.telegram.options.botUsername,
telegramChatId: user.settings?.telegramChatId,
Expand Down Expand Up @@ -659,12 +666,15 @@ userSettingsRoutes.post<{ id: string }, UserSettingsNotificationsResponse>(

const discordIds =
req.body.discordIds?.filter((id: string) => id !== '') ?? [];
const slackIds =
req.body.slackIds?.filter((id: string) => id !== '') ?? [];

if (!user.settings) {
user.settings = new UserSettings({
user: req.user,
user,
pgpKey: req.body.pgpKey,
discordIds,
slackIds,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
pushbulletAccessToken: req.body.pushbulletAccessToken,
pushoverApplicationToken: req.body.pushoverApplicationToken,
pushoverUserKey: req.body.pushoverUserKey,
Expand All @@ -676,6 +686,7 @@ userSettingsRoutes.post<{ id: string }, UserSettingsNotificationsResponse>(
} else {
user.settings.pgpKey = req.body.pgpKey;
user.settings.discordIds = discordIds;
user.settings.slackIds = slackIds;
user.settings.pushbulletAccessToken = req.body.pushbulletAccessToken;
user.settings.pushoverApplicationToken =
req.body.pushoverApplicationToken;
Expand All @@ -697,6 +708,7 @@ userSettingsRoutes.post<{ id: string }, UserSettingsNotificationsResponse>(
return res.status(200).json({
pgpKey: user.settings.pgpKey,
discordIds: user.settings.discordIds ?? [],
slackIds: user.settings.slackIds ?? [],
pushbulletAccessToken: user.settings.pushbulletAccessToken,
pushoverApplicationToken: user.settings.pushoverApplicationToken,
pushoverUserKey: user.settings.pushoverUserKey,
Expand Down
Loading