@backstage/plugin-notifications-backend 0.4.2 → 0.4.3-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,16 +1,22 @@
1
1
  # @backstage/plugin-notifications-backend
2
2
 
3
- ## 0.4.2
3
+ ## 0.4.3-next.0
4
4
 
5
5
  ### Patch Changes
6
6
 
7
+ - 97ba58f: Add support for user specific notification settings
7
8
  - Updated dependencies
8
- - @backstage/plugin-events-node@0.4.2
9
- - @backstage/plugin-signals-node@0.1.13
10
- - @backstage/backend-plugin-api@1.0.1
11
- - @backstage/plugin-auth-node@0.5.3
12
- - @backstage/plugin-catalog-node@1.13.1
13
- - @backstage/plugin-notifications-node@0.2.8
9
+ - @backstage/plugin-events-node@0.4.3-next.0
10
+ - @backstage/plugin-auth-node@0.5.4-next.0
11
+ - @backstage/plugin-catalog-node@1.14.0-next.0
12
+ - @backstage/plugin-notifications-common@0.0.6-next.0
13
+ - @backstage/catalog-client@1.8.0-next.0
14
+ - @backstage/backend-plugin-api@1.0.2-next.0
15
+ - @backstage/catalog-model@1.7.0
16
+ - @backstage/config@1.2.0
17
+ - @backstage/errors@1.2.4
18
+ - @backstage/plugin-notifications-node@0.2.9-next.0
19
+ - @backstage/plugin-signals-node@0.1.14-next.0
14
20
 
15
21
  ## 0.4.1
16
22
 
@@ -71,6 +71,28 @@ class DatabaseNotificationsStore {
71
71
  }
72
72
  }));
73
73
  };
74
+ mapToNotificationSettings = (rows) => {
75
+ return rows.reduce(
76
+ (acc, row) => {
77
+ let chan = acc.channels.find(
78
+ (channel) => channel.id === row.channel
79
+ );
80
+ if (!chan) {
81
+ acc.channels.push({
82
+ id: row.channel,
83
+ origins: []
84
+ });
85
+ chan = acc.channels[acc.channels.length - 1];
86
+ }
87
+ chan.origins.push({
88
+ id: row.origin,
89
+ enabled: Boolean(row.enabled)
90
+ });
91
+ return acc;
92
+ },
93
+ { channels: [] }
94
+ );
95
+ };
74
96
  mapNotificationToDbRow = (notification) => {
75
97
  return {
76
98
  id: notification.id,
@@ -212,7 +234,7 @@ class DatabaseNotificationsStore {
212
234
  if (!rows || rows.length === 0) {
213
235
  return null;
214
236
  }
215
- return rows[0];
237
+ return this.mapToNotifications(rows)[0];
216
238
  }
217
239
  async getExistingScopeBroadcast(options) {
218
240
  const query = this.db("broadcast").where("scope", options.scope).where("origin", options.origin).limit(1);
@@ -220,7 +242,7 @@ class DatabaseNotificationsStore {
220
242
  if (!rows || rows.length === 0) {
221
243
  return null;
222
244
  }
223
- return rows[0];
245
+ return this.mapToNotifications(rows)[0];
224
246
  }
225
247
  async restoreExistingNotification({
226
248
  id,
@@ -269,7 +291,9 @@ class DatabaseNotificationsStore {
269
291
  ).onConflict(["broadcast_id", "user"]).merge(["read", "saved"]);
270
292
  } else {
271
293
  for (const b of broadcasts) {
272
- const baseQuery = this.db("broadcast_user_status").where("broadcast_id", b.id).where("user", user);
294
+ const baseQuery = this.db(
295
+ "broadcast_user_status"
296
+ ).where("broadcast_id", b.id).where("user", user);
273
297
  const exists = await baseQuery.clone().limit(1).select().first();
274
298
  if (exists) {
275
299
  await baseQuery.clone().update({ read, saved });
@@ -291,6 +315,41 @@ class DatabaseNotificationsStore {
291
315
  async markUnsaved(options) {
292
316
  await this.markReadSaved(options.ids, options.user, void 0, null);
293
317
  }
318
+ async getUserNotificationOrigins(options) {
319
+ const rows = await this.db(
320
+ "notification"
321
+ ).where("user", options.user).select("origin").distinct();
322
+ return { origins: rows.map((row) => row.origin) };
323
+ }
324
+ async getNotificationSettings(options) {
325
+ const settingsQuery = this.db("user_settings").where(
326
+ "user",
327
+ options.user
328
+ );
329
+ if (options.origin) {
330
+ settingsQuery.where("origin", options.origin);
331
+ }
332
+ if (options.channel) {
333
+ settingsQuery.where("channel", options.channel);
334
+ }
335
+ const settings = await settingsQuery.select();
336
+ return this.mapToNotificationSettings(settings);
337
+ }
338
+ async saveNotificationSettings(options) {
339
+ const rows = [];
340
+ options.settings.channels.map((channel) => {
341
+ channel.origins.map((origin) => {
342
+ rows.push({
343
+ user: options.user,
344
+ channel: channel.id,
345
+ origin: origin.id,
346
+ enabled: origin.enabled
347
+ });
348
+ });
349
+ });
350
+ await this.db("user_settings").where("user", options.user).delete();
351
+ await this.db("user_settings").insert(rows);
352
+ }
294
353
  }
295
354
 
296
355
  exports.DatabaseNotificationsStore = DatabaseNotificationsStore;
@@ -1 +1 @@
1
- {"version":3,"file":"DatabaseNotificationsStore.cjs.js","sources":["../../src/database/DatabaseNotificationsStore.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { PluginDatabaseManager } from '@backstage/backend-common';\nimport { resolvePackagePath } from '@backstage/backend-plugin-api';\nimport {\n NotificationGetOptions,\n NotificationModifyOptions,\n NotificationsStore,\n} from './NotificationsStore';\nimport {\n Notification,\n NotificationSeverity,\n notificationSeverities,\n} from '@backstage/plugin-notifications-common';\nimport { Knex } from 'knex';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-notifications-backend',\n 'migrations',\n);\n\nconst NOTIFICATION_COLUMNS = [\n 'id',\n 'title',\n 'description',\n 'severity',\n 'link',\n 'origin',\n 'scope',\n 'topic',\n 'icon',\n 'created',\n 'updated',\n 'user',\n 'read',\n 'saved',\n];\n\nexport const normalizeSeverity = (input?: string): NotificationSeverity => {\n let lower = (input ?? 'normal').toLowerCase() as NotificationSeverity;\n if (notificationSeverities.indexOf(lower) < 0) {\n lower = 'normal';\n }\n return lower;\n};\n\n/** @internal */\nexport class DatabaseNotificationsStore implements NotificationsStore {\n private readonly isSQLite = false;\n\n private constructor(private readonly db: Knex) {\n this.isSQLite = this.db.client.config.client.includes('sqlite3');\n }\n\n static async create({\n database,\n skipMigrations,\n }: {\n database: PluginDatabaseManager;\n skipMigrations?: boolean;\n }): Promise<DatabaseNotificationsStore> {\n const client = await database.getClient();\n\n if (!database.migrations?.skip && !skipMigrations) {\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n return new DatabaseNotificationsStore(client);\n }\n\n private mapToInteger = (val: string | number | undefined): number => {\n return typeof val === 'string' ? Number.parseInt(val, 10) : val ?? 0;\n };\n\n private mapToNotifications = (rows: any[]): Notification[] => {\n return rows.map(row => ({\n id: row.id,\n user: row.user,\n created: new Date(row.created),\n saved: row.saved,\n read: row.read,\n updated: row.updated,\n origin: row.origin,\n payload: {\n title: row.title,\n description: row.description,\n link: row.link,\n topic: row.topic,\n severity: row.severity,\n scope: row.scope,\n icon: row.icon,\n },\n }));\n };\n\n private mapNotificationToDbRow = (notification: Notification) => {\n return {\n id: notification.id,\n user: notification.user,\n origin: notification.origin,\n created: notification.created,\n topic: notification.payload?.topic,\n link: notification.payload?.link,\n title: notification.payload?.title,\n description: notification.payload?.description,\n severity: normalizeSeverity(notification.payload?.severity),\n scope: notification.payload?.scope,\n icon: notification.payload.icon,\n saved: notification.saved,\n read: notification.read,\n };\n };\n\n private mapBroadcastToDbRow = (notification: Notification) => {\n return {\n id: notification.id,\n origin: notification.origin,\n created: notification.created,\n topic: notification.payload?.topic,\n link: notification.payload?.link,\n title: notification.payload?.title,\n description: notification.payload?.description,\n severity: normalizeSeverity(notification.payload?.severity),\n icon: notification.payload.icon,\n scope: notification.payload?.scope,\n };\n };\n\n private getBroadcastUnion = (user?: string | null) => {\n return this.db('broadcast')\n .leftJoin('broadcast_user_status', function clause() {\n const join = this.on('id', '=', 'broadcast_user_status.broadcast_id');\n if (user !== null && user !== undefined) {\n join.andOnVal('user', '=', user);\n }\n })\n .select(NOTIFICATION_COLUMNS);\n };\n\n private getNotificationsBaseQuery = (\n options: NotificationGetOptions | NotificationModifyOptions,\n ) => {\n const { user, orderField } = options;\n\n const subQuery = this.db('notification')\n .select(NOTIFICATION_COLUMNS)\n .unionAll([this.getBroadcastUnion(user)])\n .as('notifications');\n\n const query = this.db.from(subQuery).where(q => {\n q.where('user', user).orWhereNull('user');\n });\n\n if (orderField && orderField.length > 0) {\n orderField.forEach(orderBy => {\n query.orderBy(orderBy.field, orderBy.order);\n });\n } else if (!orderField) {\n query.orderBy('created', 'desc');\n }\n\n if (options.createdAfter) {\n if (this.isSQLite) {\n query.where('created', '>=', options.createdAfter.valueOf());\n } else {\n query.where('created', '>=', options.createdAfter.toISOString());\n }\n }\n\n if (options.limit) {\n query.limit(options.limit);\n }\n\n if (options.offset) {\n query.offset(options.offset);\n }\n\n if (options.search) {\n query.whereRaw(\n `(LOWER(title) LIKE LOWER(?) OR LOWER(description) LIKE LOWER(?))`,\n [`%${options.search}%`, `%${options.search}%`],\n );\n }\n\n if (options.ids) {\n query.whereIn('id', options.ids);\n }\n\n if (options.read) {\n query.whereNotNull('read');\n } else if (options.read === false) {\n query.whereNull('read');\n } // or match both if undefined\n\n if (options.topic) {\n query.where('topic', '=', options.topic);\n }\n\n if (options.saved) {\n query.whereNotNull('saved');\n } else if (options.saved === false) {\n query.whereNull('saved');\n } // or match both if undefined\n\n if (options.minimumSeverity !== undefined) {\n const idx = notificationSeverities.indexOf(options.minimumSeverity);\n const equalOrHigher = notificationSeverities.slice(0, idx + 1);\n query.whereIn('severity', equalOrHigher);\n }\n\n return query;\n };\n\n async getNotifications(options: NotificationGetOptions) {\n const notificationQuery = this.getNotificationsBaseQuery(options);\n const notifications = await notificationQuery.select(NOTIFICATION_COLUMNS);\n return this.mapToNotifications(notifications);\n }\n\n async getNotificationsCount(options: NotificationGetOptions) {\n const countOptions: NotificationGetOptions = { ...options };\n countOptions.limit = undefined;\n countOptions.offset = undefined;\n countOptions.orderField = [];\n const notificationQuery = this.getNotificationsBaseQuery(countOptions);\n const response = await notificationQuery.count('id as CNT');\n return Number(response[0].CNT);\n }\n\n async saveNotification(notification: Notification) {\n await this.db\n .insert(this.mapNotificationToDbRow(notification))\n .into('notification');\n }\n\n async saveBroadcast(notification: Notification) {\n await this.db\n .insert(this.mapBroadcastToDbRow(notification))\n .into('broadcast');\n if (notification.saved || notification.read) {\n await this.db\n .insert({\n user: notification.user,\n broadcast_id: notification.id,\n saved: notification.saved,\n read: notification.read,\n })\n .into('broadcast_user_status');\n }\n }\n\n async getStatus(options: NotificationGetOptions) {\n const notificationQuery = this.getNotificationsBaseQuery({\n ...options,\n orderField: [],\n });\n const readSubQuery = notificationQuery\n .clone()\n .count('id')\n .whereNotNull('read')\n .as('READ');\n const unreadSubQuery = notificationQuery\n .clone()\n .count('id')\n .whereNull('read')\n .as('UNREAD');\n\n const query = await notificationQuery\n .select(readSubQuery, unreadSubQuery)\n .first();\n\n return {\n unread: this.mapToInteger((query as any)?.UNREAD),\n read: this.mapToInteger((query as any)?.READ),\n };\n }\n\n async getExistingScopeNotification(options: {\n user: string;\n scope: string;\n origin: string;\n }) {\n const query = this.db('notification')\n .where('user', options.user)\n .where('scope', options.scope)\n .where('origin', options.origin)\n .limit(1);\n\n const rows = await query;\n if (!rows || rows.length === 0) {\n return null;\n }\n return rows[0] as Notification;\n }\n\n async getExistingScopeBroadcast(options: { scope: string; origin: string }) {\n const query = this.db('broadcast')\n .where('scope', options.scope)\n .where('origin', options.origin)\n .limit(1);\n\n const rows = await query;\n if (!rows || rows.length === 0) {\n return null;\n }\n return rows[0] as Notification;\n }\n\n async restoreExistingNotification({\n id,\n notification,\n }: {\n id: string;\n notification: Notification;\n }) {\n const updateColumns = {\n title: notification.payload.title,\n description: notification.payload.description,\n link: notification.payload.link,\n topic: notification.payload.topic,\n updated: new Date(),\n severity: normalizeSeverity(notification.payload?.severity),\n read: null,\n };\n\n const notificationQuery = this.db('notification')\n .where('id', id)\n .where('user', notification.user);\n const broadcastQuery = this.db('broadcast').where('id', id);\n\n await Promise.all([\n notificationQuery.update(updateColumns),\n broadcastQuery.update({ ...updateColumns, read: undefined }),\n ]);\n\n return await this.getNotification({ id, user: notification.user });\n }\n\n async getNotification(options: {\n id: string;\n user?: string | null;\n }): Promise<Notification | null> {\n const rows = await this.db\n .select('*')\n .from(\n this.db('notification')\n .select(NOTIFICATION_COLUMNS)\n .unionAll([this.getBroadcastUnion(options.user)])\n .as('notifications'),\n )\n .where('id', options.id)\n .limit(1);\n if (!rows || rows.length === 0) {\n return null;\n }\n return this.mapToNotifications(rows)[0];\n }\n\n private markReadSaved = async (\n ids: string[],\n user: string,\n read?: Date | null,\n saved?: Date | null,\n ) => {\n await this.db('notification')\n .whereIn('id', ids)\n .where('user', user)\n .update({ read, saved });\n\n const broadcasts = this.mapToNotifications(\n await this.db('broadcast').whereIn('id', ids).select(),\n );\n\n if (broadcasts.length > 0)\n if (!this.isSQLite) {\n await this.db('broadcast_user_status')\n .insert(\n broadcasts.map(b => ({\n broadcast_id: b.id,\n user,\n read,\n saved,\n })),\n )\n .onConflict(['broadcast_id', 'user'])\n .merge(['read', 'saved']);\n } else {\n // SQLite does not support upsert so fall back to this (mostly for tests and local dev)\n for (const b of broadcasts) {\n const baseQuery = this.db('broadcast_user_status')\n .where('broadcast_id', b.id)\n .where('user', user);\n const exists = await baseQuery.clone().limit(1).select().first();\n if (exists) {\n await baseQuery.clone().update({ read, saved });\n } else {\n await baseQuery\n .clone()\n .insert({ broadcast_id: b.id, user, read, saved });\n }\n }\n }\n };\n\n async markRead(options: NotificationModifyOptions): Promise<void> {\n await this.markReadSaved(options.ids, options.user, new Date(), undefined);\n }\n\n async markUnread(options: NotificationModifyOptions): Promise<void> {\n await this.markReadSaved(options.ids, options.user, null, undefined);\n }\n\n async markSaved(options: NotificationModifyOptions): Promise<void> {\n await this.markReadSaved(options.ids, options.user, undefined, new Date());\n }\n\n async markUnsaved(options: NotificationModifyOptions): Promise<void> {\n await this.markReadSaved(options.ids, options.user, undef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3E;AAAA,EAEA,MAAM,YAAY,OAAmD,EAAA;AACnE,IAAA,MAAM,KAAK,aAAc,CAAA,OAAA,CAAQ,KAAK,OAAQ,CAAA,IAAA,EAAM,QAAW,IAAI,CAAA,CAAA;AAAA,GACrE;AACF;;;;;"}
1
+ {"version":3,"file":"DatabaseNotificationsStore.cjs.js","sources":["../../src/database/DatabaseNotificationsStore.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n DatabaseService,\n resolvePackagePath,\n} from '@backstage/backend-plugin-api';\nimport {\n NotificationGetOptions,\n NotificationModifyOptions,\n NotificationsStore,\n} from './NotificationsStore';\nimport {\n Notification,\n NotificationSettings,\n notificationSeverities,\n NotificationSeverity,\n} from '@backstage/plugin-notifications-common';\nimport { Knex } from 'knex';\n\nconst migrationsDir = resolvePackagePath(\n '@backstage/plugin-notifications-backend',\n 'migrations',\n);\n\nconst NOTIFICATION_COLUMNS = [\n 'id',\n 'title',\n 'description',\n 'severity',\n 'link',\n 'origin',\n 'scope',\n 'topic',\n 'icon',\n 'created',\n 'updated',\n 'user',\n 'read',\n 'saved',\n];\n\ntype NotificationRowType = {\n id: string;\n user: string;\n title: string;\n description?: string | null;\n severity: string;\n link: string | null;\n origin: string;\n scope: string | null;\n topic: string | null;\n created: Date;\n updated: Date | null;\n read: Date | null;\n saved: Date | null;\n icon: string | null;\n};\n\ntype BroadcastRowType = {\n id: string;\n title: string;\n description: string | null;\n link: string | null;\n origin: string;\n scope: string | null;\n topic: string | null;\n created: Date;\n updated: Date | null;\n icon: string | null;\n};\n\ntype BroadcastUserStatusRowType = {\n broadcast_id: string;\n user: string;\n read: Date | null;\n saved: Date | null;\n};\n\ntype UserSettingsRowType = {\n user: string;\n channel: string;\n origin: string;\n enabled: boolean;\n};\n\nexport const normalizeSeverity = (input?: string): NotificationSeverity => {\n let lower = (input ?? 'normal').toLowerCase() as NotificationSeverity;\n if (notificationSeverities.indexOf(lower) < 0) {\n lower = 'normal';\n }\n return lower;\n};\n\n/** @internal */\nexport class DatabaseNotificationsStore implements NotificationsStore {\n private readonly isSQLite = false;\n\n private constructor(private readonly db: Knex) {\n this.isSQLite = this.db.client.config.client.includes('sqlite3');\n }\n\n static async create({\n database,\n skipMigrations,\n }: {\n database: DatabaseService;\n skipMigrations?: boolean;\n }): Promise<DatabaseNotificationsStore> {\n const client = await database.getClient();\n\n if (!database.migrations?.skip && !skipMigrations) {\n await client.migrate.latest({\n directory: migrationsDir,\n });\n }\n\n return new DatabaseNotificationsStore(client);\n }\n\n private mapToInteger = (val: string | number | undefined): number => {\n return typeof val === 'string' ? Number.parseInt(val, 10) : val ?? 0;\n };\n\n private mapToNotifications = (rows: any[]): Notification[] => {\n return rows.map(row => ({\n id: row.id,\n user: row.user,\n created: new Date(row.created),\n saved: row.saved,\n read: row.read,\n updated: row.updated,\n origin: row.origin,\n payload: {\n title: row.title,\n description: row.description,\n link: row.link,\n topic: row.topic,\n severity: row.severity,\n scope: row.scope,\n icon: row.icon,\n },\n }));\n };\n\n private mapToNotificationSettings = (rows: any[]): NotificationSettings => {\n return rows.reduce(\n (acc, row) => {\n let chan = acc.channels.find(\n (channel: { id: string }) => channel.id === row.channel,\n );\n if (!chan) {\n acc.channels.push({\n id: row.channel,\n origins: [],\n });\n chan = acc.channels[acc.channels.length - 1];\n }\n chan.origins.push({\n id: row.origin,\n enabled: Boolean(row.enabled),\n });\n return acc;\n },\n { channels: [] },\n );\n };\n\n private mapNotificationToDbRow = (notification: Notification) => {\n return {\n id: notification.id,\n user: notification.user,\n origin: notification.origin,\n created: notification.created,\n topic: notification.payload?.topic,\n link: notification.payload?.link,\n title: notification.payload?.title,\n description: notification.payload?.description,\n severity: normalizeSeverity(notification.payload?.severity),\n scope: notification.payload?.scope,\n icon: notification.payload.icon,\n saved: notification.saved,\n read: notification.read,\n };\n };\n\n private mapBroadcastToDbRow = (notification: Notification) => {\n return {\n id: notification.id,\n origin: notification.origin,\n created: notification.created,\n topic: notification.payload?.topic,\n link: notification.payload?.link,\n title: notification.payload?.title,\n description: notification.payload?.description,\n severity: normalizeSeverity(notification.payload?.severity),\n icon: notification.payload.icon,\n scope: notification.payload?.scope,\n };\n };\n\n private getBroadcastUnion = (user?: string | null) => {\n return this.db<BroadcastRowType>('broadcast')\n .leftJoin('broadcast_user_status', function clause() {\n const join = this.on('id', '=', 'broadcast_user_status.broadcast_id');\n if (user !== null && user !== undefined) {\n join.andOnVal('user', '=', user);\n }\n })\n .select(NOTIFICATION_COLUMNS);\n };\n\n private getNotificationsBaseQuery = (\n options: NotificationGetOptions | NotificationModifyOptions,\n ) => {\n const { user, orderField } = options;\n\n const subQuery = this.db<NotificationRowType>('notification')\n .select(NOTIFICATION_COLUMNS)\n .unionAll([this.getBroadcastUnion(user)])\n .as('notifications');\n\n const query = this.db.from(subQuery).where(q => {\n q.where('user', user).orWhereNull('user');\n });\n\n if (orderField && orderField.length > 0) {\n orderField.forEach(orderBy => {\n query.orderBy(orderBy.field, orderBy.order);\n });\n } else if (!orderField) {\n query.orderBy('created', 'desc');\n }\n\n if (options.createdAfter) {\n if (this.isSQLite) {\n query.where('created', '>=', options.createdAfter.valueOf());\n } else {\n query.where('created', '>=', options.createdAfter.toISOString());\n }\n }\n\n if (options.limit) {\n query.limit(options.limit);\n }\n\n if (options.offset) {\n query.offset(options.offset);\n }\n\n if (options.search) {\n query.whereRaw(\n `(LOWER(title) LIKE LOWER(?) OR LOWER(description) LIKE LOWER(?))`,\n [`%${options.search}%`, `%${options.search}%`],\n );\n }\n\n if (options.ids) {\n query.whereIn('id', options.ids);\n }\n\n if (options.read) {\n query.whereNotNull('read');\n } else if (options.read === false) {\n query.whereNull('read');\n } // or match both if undefined\n\n if (options.topic) {\n query.where('topic', '=', options.topic);\n }\n\n if (options.saved) {\n query.whereNotNull('saved');\n } else if (options.saved === false) {\n query.whereNull('saved');\n } // or match both if undefined\n\n if (options.minimumSeverity !== undefined) {\n const idx = notificationSeverities.indexOf(options.minimumSeverity);\n const equalOrHigher = notificationSeverities.slice(0, idx + 1);\n query.whereIn('severity', equalOrHigher);\n }\n\n return query;\n };\n\n async getNotifications(options: NotificationGetOptions) {\n const notificationQuery = this.getNotificationsBaseQuery(options);\n const notifications = await notificationQuery.select(NOTIFICATION_COLUMNS);\n return this.mapToNotifications(notifications);\n }\n\n async getNotificationsCount(options: NotificationGetOptions) {\n const countOptions: NotificationGetOptions = { ...options };\n countOptions.limit = undefined;\n countOptions.offset = undefined;\n countOptions.orderField = [];\n const notificationQuery = this.getNotificationsBaseQuery(countOptions);\n const response = await notificationQuery.count('id as CNT');\n return Number(response[0].CNT);\n }\n\n async saveNotification(notification: Notification) {\n await this.db\n .insert(this.mapNotificationToDbRow(notification))\n .into('notification');\n }\n\n async saveBroadcast(notification: Notification) {\n await this.db\n .insert(this.mapBroadcastToDbRow(notification))\n .into('broadcast');\n if (notification.saved || notification.read) {\n await this.db\n .insert({\n user: notification.user,\n broadcast_id: notification.id,\n saved: notification.saved,\n read: notification.read,\n })\n .into('broadcast_user_status');\n }\n }\n\n async getStatus(options: NotificationGetOptions) {\n const notificationQuery = this.getNotificationsBaseQuery({\n ...options,\n orderField: [],\n });\n const readSubQuery = notificationQuery\n .clone()\n .count('id')\n .whereNotNull('read')\n .as('READ');\n const unreadSubQuery = notificationQuery\n .clone()\n .count('id')\n .whereNull('read')\n .as('UNREAD');\n\n const query = await notificationQuery\n .select(readSubQuery, unreadSubQuery)\n .first();\n\n return {\n unread: this.mapToInteger((query as any)?.UNREAD),\n read: this.mapToInteger((query as any)?.READ),\n };\n }\n\n async getExistingScopeNotification(options: {\n user: string;\n scope: string;\n origin: string;\n }) {\n const query = this.db<NotificationRowType>('notification')\n .where('user', options.user)\n .where('scope', options.scope)\n .where('origin', options.origin)\n .limit(1);\n\n const rows = await query;\n if (!rows || rows.length === 0) {\n return null;\n }\n return this.mapToNotifications(rows)[0];\n }\n\n async getExistingScopeBroadcast(options: { scope: string; origin: string }) {\n const query = this.db<BroadcastRowType>('broadcast')\n .where('scope', options.scope)\n .where('origin', options.origin)\n .limit(1);\n\n const rows = await query;\n if (!rows || rows.length === 0) {\n return null;\n }\n return this.mapToNotifications(rows)[0];\n }\n\n async restoreExistingNotification({\n id,\n notification,\n }: {\n id: string;\n notification: Notification;\n }) {\n const updateColumns = {\n title: notification.payload.title,\n description: notification.payload.description,\n link: notification.payload.link,\n topic: notification.payload.topic,\n updated: new Date(),\n severity: normalizeSeverity(notification.payload?.severity),\n read: null,\n };\n\n const notificationQuery = this.db('notification')\n .where('id', id)\n .where('user', notification.user);\n const broadcastQuery = this.db('broadcast').where('id', id);\n\n await Promise.all([\n notificationQuery.update(updateColumns),\n broadcastQuery.update({ ...updateColumns, read: undefined }),\n ]);\n\n return await this.getNotification({ id, user: notification.user });\n }\n\n async getNotification(options: {\n id: string;\n user?: string | null;\n }): Promise<Notification | null> {\n const rows = await this.db\n .select('*')\n .from(\n this.db<NotificationRowType>('notification')\n .select(NOTIFICATION_COLUMNS)\n .unionAll([this.getBroadcastUnion(options.user)])\n .as('notifications'),\n )\n .where('id', options.id)\n .limit(1);\n if (!rows || rows.length === 0) {\n return null;\n }\n return this.mapToNotifications(rows)[0];\n }\n\n private markReadSaved = async (\n ids: string[],\n user: string,\n read?: Date | null,\n saved?: Date | null,\n ) => {\n await this.db<NotificationRowType>('notification')\n .whereIn('id', ids)\n .where('user', user)\n .update({ read, saved });\n\n const broadcasts = this.mapToNotifications(\n await this.db('broadcast').whereIn('id', ids).select(),\n );\n\n if (broadcasts.length > 0)\n if (!this.isSQLite) {\n await this.db<BroadcastUserStatusRowType>('broadcast_user_status')\n .insert(\n broadcasts.map(b => ({\n broadcast_id: b.id,\n user,\n read,\n saved,\n })),\n )\n .onConflict(['broadcast_id', 'user'])\n .merge(['read', 'saved']);\n } else {\n // SQLite does not support upsert so fall back to this (mostly for tests and local dev)\n for (const b of broadcasts) {\n const baseQuery = this.db<BroadcastUserStatusRowType>(\n 'broadcast_user_status',\n )\n .where('broadcast_id', b.id)\n .where('user', user);\n const exists = await baseQuery.clone().limit(1).select().first();\n if (exists) {\n await baseQuery.clone().update({ read, saved });\n } else {\n await baseQuery\n .clone()\n .insert({ broadcast_id: b.id, user, read, saved });\n }\n }\n }\n };\n\n async markRead(options: NotificationModifyOptions): Promise<void> {\n await this.markReadSaved(options.ids, options.user, new Date(), undefined);\n }\n\n async markUnread(options: NotificationModifyOptions): Promise<void> {\n await this.markReadSaved(options.ids, options.user, null, undefined);\n }\n\n async markSaved(options: NotificationModifyOptions): Promise<void> {\n await this.markReadSaved(options.ids, options.user, undefined, new Date());\n }\n\n async markUnsaved(options: NotificationModifyOptions): Promise<void> {\n await this.markReadSaved(options.ids, options.user, undefined, null);\n }\n\n async getUserNotificationOrigins(options: {\n user: string;\n }): Promise<{ origins: string[] }> {\n const rows: { origin: string }[] = await this.db<NotificationRowType>(\n 'notification',\n )\n .where('user', options.user)\n .select('origin')\n .distinct();\n return { origins: rows.map(row => row.origin) };\n }\n\n async getNotificationSettings(options: {\n user: string;\n origin?: string;\n channel?: string;\n }): Promise<NotificationSettings> {\n const settingsQuery = this.db<UserSettingsRowType>('user_settings').where(\n 'user',\n options.user,\n );\n if (options.origin) {\n settingsQuery.where('origin', options.origin);\n }\n\n if (options.channel) {\n settingsQuery.where('channel', options.channel);\n }\n const settings = await settingsQuery.select();\n return this.mapToNotificationSettings(settings);\n }\n\n async saveNotificationSettings(options: {\n user: string;\n settings: NotificationSettings;\n }): Promise<void> {\n const rows: {\n user: string;\n channel: string;\n origin: string;\n enabled: boolean;\n }[] = [];\n options.settings.channels.map(channel => {\n channel.origins.map(origin => {\n rows.push({\n user: options.user,\n channel: channel.id,\n origin: origin.id,\n enabled: origin.enabled,\n });\n });\n });\n\n await this.db<UserSettingsRowType>('user_settings')\n .where('user', options.user)\n .delete();\n await this.db<UserSettingsRowType>('user_settings').insert(rows);\n }\n}\n"],"names":["resolvePackagePath","notificationSeverities"],"mappings":";;;;;AAgCA,MAAM,aAAgB,GAAAA,mCAAA;AAAA,EACpB,yCAAA;AAAA,EACA,YAAA;AACF,CAAA,CAAA;AAEA,MAAM,oBAAuB,GAAA;AAAA,EAC3B,IAAA;AAAA,EACA,OAAA;AAAA,EACA,aAAA;AAAA,EACA,UAAA;AAAA,EACA,MAAA;AAAA,EACA,QAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA,MAAA;AAAA,EACA,SAAA;AAAA,EACA,SAAA;AAAA,EACA,MAAA;AAAA,EACA,MAAA;AAAA,EACA,OAAA;AACF,CAAA,CAAA;AA8Ca,MAAA,iBAAA,GAAoB,CAAC,KAAyC,KAAA;AACzE,EAAI,IAAA,KAAA,GAAA,CAAS,KAAS,IAAA,QAAA,EAAU,WAAY,EAAA,CAAA;AAC5C,EAAA,IAAIC,gDAAuB,CAAA,OAAA,CAAQ,KAAK,CAAA,GAAI,CAAG,EAAA;AAC7C,IAAQ,KAAA,GAAA,QAAA,CAAA;AAAA,GACV;AACA,EAAO,OAAA,KAAA,CAAA;AACT,EAAA;AAGO,MAAM,0BAAyD,CAAA;AAAA,EAG5D,YAA6B,EAAU,EAAA;AAAV,IAAA,IAAA,CAAA,EAAA,GAAA,EAAA,CAAA;AACnC,IAAA,IAAA,CAAK,WAAW,IAAK,CAAA,EAAA,CAAG,OAAO,MAAO,CAAA,MAAA,CAAO,SAAS,SAAS,CAAA,CAAA;AAAA,GACjE;AAAA,EAJiB,QAAW,GAAA,KAAA,CAAA;AAAA,EAM5B,aAAa,MAAO,CAAA;AAAA,IAClB,QAAA;AAAA,IACA,cAAA;AAAA,GAIsC,EAAA;AACtC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,UACjB,QAAQ,MAAO,CAAA,EAAA;AAAA,UACf,SAAS,MAAO,CAAA,OAAA;AAAA,SACjB,CAAA,CAAA;AAAA,OACF,CAAA,CAAA;AAAA,KACF,CAAA,CAAA;AAED,IAAM,MAAA,IAAA,CAAK,GAAwB,eAAe,CAAA,CAC/C,MAAM,MAAQ,EAAA,OAAA,CAAQ,IAAI,CAAA,CAC1B,MAAO,EAAA,CAAA;AACV,IAAA,MAAM,IAAK,CAAA,EAAA,CAAwB,eAAe,CAAA,CAAE,OAAO,IAAI,CAAA,CAAA;AAAA,GACjE;AACF;;;;;"}
@@ -27,6 +27,7 @@ async function createRouter(options) {
27
27
  processors = [],
28
28
  signals
29
29
  } = options;
30
+ const WEB_NOTIFICATION_CHANNEL = "Web";
30
31
  const store = await DatabaseNotificationsStore.DatabaseNotificationsStore.create({ database });
31
32
  const frontendBaseUrl = config.getString("app.baseUrl");
32
33
  const getUser = async (req) => {
@@ -34,9 +35,48 @@ async function createRouter(options) {
34
35
  const info = await userInfo.getUserInfo(credentials);
35
36
  return info.userEntityRef;
36
37
  };
37
- const filterProcessors = (payload) => {
38
+ const getNotificationChannels = () => {
39
+ return [WEB_NOTIFICATION_CHANNEL, ...processors.map((p) => p.getName())];
40
+ };
41
+ const getNotificationSettings = async (user) => {
42
+ const { origins } = await store.getUserNotificationOrigins({ user });
43
+ const settings = await store.getNotificationSettings({ user });
44
+ const channels = getNotificationChannels();
45
+ const response = {
46
+ channels: channels.map((channel) => {
47
+ const channelSettings = settings.channels.find((c) => c.id === channel);
48
+ if (channelSettings) {
49
+ return channelSettings;
50
+ }
51
+ return {
52
+ id: channel,
53
+ origins: origins.map((origin) => ({
54
+ id: origin,
55
+ enabled: true
56
+ }))
57
+ };
58
+ })
59
+ };
60
+ return response;
61
+ };
62
+ const isNotificationsEnabled = async (opts) => {
63
+ const settings = await getNotificationSettings(opts.user);
64
+ return pluginNotificationsCommon.isNotificationsEnabledFor(settings, opts.channel, opts.origin);
65
+ };
66
+ const filterProcessors = async (notification) => {
38
67
  const result = [];
68
+ const { payload, user, origin } = notification;
39
69
  for (const processor of processors) {
70
+ if (user) {
71
+ const enabled = await isNotificationsEnabled({
72
+ user,
73
+ origin,
74
+ channel: processor.getName()
75
+ });
76
+ if (!enabled) {
77
+ continue;
78
+ }
79
+ }
40
80
  if (processor.getNotificationFilters) {
41
81
  const filters = processor.getNotificationFilters();
42
82
  if (filters.minSeverity) {
@@ -59,8 +99,8 @@ async function createRouter(options) {
59
99
  }
60
100
  return result;
61
101
  };
62
- const processOptions = async (opts) => {
63
- const filtered = filterProcessors(opts.payload);
102
+ const processOptions = async (opts, origin) => {
103
+ const filtered = await filterProcessors({ ...opts, origin, user: null });
64
104
  let ret = opts;
65
105
  for (const processor of filtered) {
66
106
  try {
@@ -74,7 +114,7 @@ async function createRouter(options) {
74
114
  return ret;
75
115
  };
76
116
  const preProcessNotification = async (notification, opts) => {
77
- const filtered = filterProcessors(notification.payload);
117
+ const filtered = await filterProcessors(notification);
78
118
  let ret = notification;
79
119
  for (const processor of filtered) {
80
120
  try {
@@ -88,7 +128,7 @@ async function createRouter(options) {
88
128
  return ret;
89
129
  };
90
130
  const postProcessNotification = async (notification, opts) => {
91
- const filtered = filterProcessors(notification.payload);
131
+ const filtered = await filterProcessors(notification);
92
132
  for (const processor of filtered) {
93
133
  if (processor.postProcess) {
94
134
  try {
@@ -174,6 +214,28 @@ async function createRouter(options) {
174
214
  const status = await store.getStatus({ user });
175
215
  res.json(status);
176
216
  });
217
+ router.get(
218
+ "/settings",
219
+ async (req, res) => {
220
+ const user = await getUser(req);
221
+ const response = await getNotificationSettings(user);
222
+ res.json(response);
223
+ }
224
+ );
225
+ router.post(
226
+ "/settings",
227
+ async (req, res) => {
228
+ const user = await getUser(req);
229
+ const channels = getNotificationChannels();
230
+ const settings = req.body;
231
+ if (settings.channels.some((c) => !channels.includes(c.id))) {
232
+ throw new errors.InputError("Invalid channel");
233
+ }
234
+ await store.saveNotificationSettings({ user, settings });
235
+ const response = await getNotificationSettings(user);
236
+ res.json(response);
237
+ }
238
+ );
177
239
  router.get("/:id", async (req, res) => {
178
240
  const user = await getUser(req);
179
241
  const opts = {
@@ -272,34 +334,41 @@ async function createRouter(options) {
272
334
  user
273
335
  };
274
336
  const notification = await preProcessNotification(userNotification, opts);
275
- let existingNotification;
276
- if (scope) {
277
- existingNotification = await store.getExistingScopeNotification({
278
- user,
279
- scope,
280
- origin
281
- });
282
- }
337
+ const enabled = await isNotificationsEnabled({
338
+ user,
339
+ channel: WEB_NOTIFICATION_CHANNEL,
340
+ origin: userNotification.origin
341
+ });
283
342
  let ret = notification;
284
- if (existingNotification) {
285
- const restored = await store.restoreExistingNotification({
286
- id: existingNotification.id,
287
- notification
288
- });
289
- ret = restored ?? notification;
290
- } else {
291
- await store.saveNotification(notification);
292
- }
293
- notifications.push(ret);
294
- if (signals) {
295
- await signals.publish({
296
- recipients: { type: "user", entityRef: [user] },
297
- message: {
298
- action: "new_notification",
299
- notification_id: ret.id
300
- },
301
- channel: "notifications"
302
- });
343
+ if (enabled) {
344
+ let existingNotification;
345
+ if (scope) {
346
+ existingNotification = await store.getExistingScopeNotification({
347
+ user,
348
+ scope,
349
+ origin
350
+ });
351
+ }
352
+ if (existingNotification) {
353
+ const restored = await store.restoreExistingNotification({
354
+ id: existingNotification.id,
355
+ notification
356
+ });
357
+ ret = restored ?? notification;
358
+ } else {
359
+ await store.saveNotification(notification);
360
+ }
361
+ notifications.push(ret);
362
+ if (signals) {
363
+ await signals.publish({
364
+ recipients: { type: "user", entityRef: [user] },
365
+ message: {
366
+ action: "new_notification",
367
+ notification_id: ret.id
368
+ },
369
+ channel: "notifications"
370
+ });
371
+ }
303
372
  }
304
373
  postProcessNotification(ret, opts);
305
374
  }
@@ -308,14 +377,15 @@ async function createRouter(options) {
308
377
  router.post(
309
378
  "/",
310
379
  async (req, res) => {
311
- const opts = await processOptions(req.body);
312
- const { recipients, payload } = opts;
313
- const notifications = [];
314
- let users = [];
315
380
  const credentials = await httpAuth.credentials(req, {
316
381
  allow: ["service"]
317
382
  });
383
+ const origin = credentials.principal.subject;
384
+ const opts = await processOptions(req.body, origin);
385
+ const { recipients, payload } = opts;
318
386
  const { title, link } = payload;
387
+ const notifications = [];
388
+ let users = [];
319
389
  if (!recipients || !title) {
320
390
  logger.error(`Invalid notification request received`);
321
391
  throw new errors.InputError(`Invalid notification request received`);
@@ -327,7 +397,6 @@ async function createRouter(options) {
327
397
  throw new errors.InputError("Invalid link provided", e);
328
398
  }
329
399
  }
330
- const origin = credentials.principal.subject;
331
400
  const baseNotification = {
332
401
  payload: {
333
402
  ...payload,
@@ -1 +1 @@
1
- {"version":3,"file":"router.cjs.js","sources":["../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorHandler, PluginDatabaseManager } from '@backstage/backend-common';\nimport express, { Request } from 'express';\nimport Router from 'express-promise-router';\nimport {\n DatabaseNotificationsStore,\n normalizeSeverity,\n NotificationGetOptions,\n} from '../database';\nimport { v4 as uuid } from 'uuid';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n NotificationProcessor,\n NotificationSendOptions,\n} from '@backstage/plugin-notifications-node';\nimport { InputError, NotFoundError } from '@backstage/errors';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n UserInfoService,\n} from '@backstage/backend-plugin-api';\nimport { SignalsService } from '@backstage/plugin-signals-node';\nimport {\n NewNotificationSignal,\n Notification,\n NotificationPayload,\n NotificationReadSignal,\n notificationSeverities,\n NotificationStatus,\n} from '@backstage/plugin-notifications-common';\nimport { parseEntityOrderFieldParams } from './parseEntityOrderFieldParams';\nimport { getUsersForEntityRef } from './getUsersForEntityRef';\nimport { Config } from '@backstage/config';\n\n/** @internal */\nexport interface RouterOptions {\n logger: LoggerService;\n config: Config;\n database: PluginDatabaseManager;\n auth: AuthService;\n httpAuth: HttpAuthService;\n userInfo: UserInfoService;\n signals?: SignalsService;\n catalog: CatalogApi;\n processors?: NotificationProcessor[];\n}\n\n/** @internal */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n config,\n logger,\n database,\n auth,\n httpAuth,\n userInfo,\n catalog,\n processors = [],\n signals,\n } = options;\n\n const store = await DatabaseNotificationsStore.create({ database });\n const frontendBaseUrl = config.getString('app.baseUrl');\n\n const getUser = async (req: Request<unknown>) => {\n const credentials = await httpAuth.credentials(req, { allow: ['user'] });\n const info = await userInfo.getUserInfo(credentials);\n return info.userEntityRef;\n };\n\n const filterProcessors = (payload: NotificationPayload) => {\n const result: NotificationProcessor[] = [];\n\n for (const processor of processors) {\n if (processor.getNotificationFilters) {\n const filters = processor.getNotificationFilters();\n if (filters.minSeverity) {\n if (\n notificationSeverities.indexOf(payload.severity ?? 'normal') >\n notificationSeverities.indexOf(filters.minSeverity)\n ) {\n continue;\n }\n }\n\n if (filters.maxSeverity) {\n if (\n notificationSeverities.indexOf(payload.severity ?? 'normal') <\n notificationSeverities.indexOf(filters.maxSeverity)\n ) {\n continue;\n }\n }\n\n if (filters.excludedTopics && payload.topic) {\n if (filters.excludedTopics.includes(payload.topic)) {\n continue;\n }\n }\n }\n result.push(processor);\n }\n\n return result;\n };\n\n const processOptions = async (opts: NotificationSendOptions) => {\n const filtered = filterProcessors(opts.payload);\n let ret = opts;\n for (const processor of filtered) {\n try {\n ret = processor.processOptions\n ? await processor.processOptions(ret)\n : ret;\n } catch (e) {\n logger.error(\n `Error while processing notification options with ${processor.getName()}: ${e}`,\n );\n }\n }\n return ret;\n };\n\n const preProcessNotification = async (\n notification: Notification,\n opts: NotificationSendOptions,\n ) => {\n const filtered = filterProcessors(notification.payload);\n let ret = notification;\n for (const processor of filtered) {\n try {\n ret = processor.preProcess\n ? await processor.preProcess(ret, opts)\n : ret;\n } catch (e) {\n logger.error(\n `Error while pre processing notification with ${processor.getName()}: ${e}`,\n );\n }\n }\n return ret;\n };\n\n const postProcessNotification = async (\n notification: Notification,\n opts: NotificationSendOptions,\n ) => {\n const filtered = filterProcessors(notification.payload);\n for (const processor of filtered) {\n if (processor.postProcess) {\n try {\n await processor.postProcess(notification, opts);\n } catch (e) {\n logger.error(\n `Error while post processing notification with ${processor.getName()}: ${e}`,\n );\n }\n }\n }\n };\n\n const validateLink = (link: string) => {\n const stripLeadingSlash = (s: string) => s.replace(/^\\//, '');\n const ensureTrailingSlash = (s: string) => s.replace(/\\/?$/, '/');\n const url = new URL(\n stripLeadingSlash(link),\n ensureTrailingSlash(frontendBaseUrl),\n );\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new Error('Only HTTP/HTTPS links are allowed');\n }\n };\n\n // TODO: Move to use OpenAPI router instead\n const router = Router();\n router.use(express.json());\n\n router.get('/health', (_, response) => {\n logger.info('PONG!');\n response.json({ status: 'ok' });\n });\n\n router.get('/', async (req, res) => {\n const user = await getUser(req);\n const opts: NotificationGetOptions = {\n user: user,\n };\n if (req.query.offset) {\n opts.offset = Number.parseInt(req.query.offset.toString(), 10);\n }\n if (req.query.limit) {\n opts.limit = Number.parseInt(req.query.limit.toString(), 10);\n }\n if (req.query.orderField) {\n opts.orderField = parseEntityOrderFieldParams(req.query);\n }\n if (req.query.search) {\n opts.search = req.query.search.toString();\n }\n if (req.query.read === 'true') {\n opts.read = true;\n } else if (req.query.read === 'false') {\n opts.read = false;\n // or keep undefined\n }\n\n if (req.query.topic) {\n opts.topic = req.query.topic.toString();\n }\n\n if (req.query.saved === 'true') {\n opts.saved = true;\n } else if (req.query.saved === 'false') {\n opts.saved = false;\n // or keep undefined\n }\n if (req.query.createdAfter) {\n const sinceEpoch = Date.parse(String(req.query.createdAfter));\n if (isNaN(sinceEpoch)) {\n throw new InputError('Unexpected date format');\n }\n opts.createdAfter = new Date(sinceEpoch);\n }\n if (req.query.minimumSeverity) {\n opts.minimumSeverity = normalizeSeverity(\n req.query.minimumSeverity.toString(),\n );\n }\n\n const [notifications, totalCount] = await Promise.all([\n store.getNotifications(opts),\n store.getNotificationsCount(opts),\n ]);\n res.json({\n totalCount,\n notifications,\n });\n });\n\n router.get('/status', async (req: Request<any, NotificationStatus>, res) => {\n const user = await getUser(req);\n const status = await store.getStatus({ user });\n res.json(status);\n });\n\n // Make sure this is the last \"GET\" handler\n router.get('/:id', async (req, res) => {\n const user = await getUser(req);\n const opts: NotificationGetOptions = {\n user: user,\n limit: 1,\n ids: [req.params.id],\n };\n const notifications = await store.getNotifications(opts);\n if (notifications.length !== 1) {\n throw new NotFoundError('Not found');\n }\n res.json(notifications[0]);\n });\n\n router.post('/update', async (req, res) => {\n const user = await getUser(req);\n const { ids, read, saved } = req.body;\n if (!ids || !Array.isArray(ids)) {\n throw new InputError();\n }\n\n if (read === true) {\n await store.markRead({ user, ids });\n\n if (signals) {\n await signals.publish<NotificationReadSignal>({\n recipients: { type: 'user', entityRef: [user] },\n message: { action: 'notification_read', notification_ids: ids },\n channel: 'notifications',\n });\n }\n } else if (read === false) {\n await store.markUnread({ user: user, ids });\n\n if (signals) {\n await signals.publish<NotificationReadSignal>({\n recipients: { type: 'user', entityRef: [user] },\n message: { action: 'notification_unread', notification_ids: ids },\n channel: 'notifications',\n });\n }\n }\n\n if (saved === true) {\n await store.markSaved({ user: user, ids });\n } else if (saved === false) {\n await store.markUnsaved({ user: user, ids });\n }\n\n const notifications = await store.getNotifications({ ids, user: user });\n res.json(notifications);\n });\n\n const sendBroadcastNotification = async (\n baseNotification: Omit<Notification, 'user' | 'id'>,\n opts: NotificationSendOptions,\n origin: string,\n ) => {\n const { scope } = opts.payload;\n const broadcastNotification = {\n ...baseNotification,\n user: null,\n id: uuid(),\n };\n const notification = await preProcessNotification(\n broadcastNotification,\n opts,\n );\n let existingNotification;\n if (scope) {\n existingNotification = await store.getExistingScopeBroadcast({\n scope,\n origin,\n });\n }\n\n let ret = notification;\n if (existingNotification) {\n const restored = await store.restoreExistingNotification({\n id: existingNotification.id,\n notification: { ...notification, user: '' },\n });\n ret = restored ?? notification;\n } else {\n await store.saveBroadcast(notification);\n }\n\n if (signals) {\n await signals.publish<NewNotificationSignal>({\n recipients: { type: 'broadcast' },\n message: {\n action: 'new_notification',\n notification_id: ret.id,\n },\n channel: 'notifications',\n });\n postProcessNotification(ret, opts);\n }\n return notification;\n };\n\n const sendUserNotifications = async (\n baseNotification: Omit<Notification, 'user' | 'id'>,\n users: string[],\n opts: NotificationSendOptions,\n origin: string,\n ) => {\n const notifications = [];\n const { scope } = opts.payload;\n const uniqueUsers = [...new Set(users)];\n for (const user of uniqueUsers) {\n const userNotification = {\n ...baseNotification,\n id: uuid(),\n user,\n };\n const notification = await preProcessNotification(userNotification, opts);\n\n let existingNotification;\n if (scope) {\n existingNotification = await store.getExistingScopeNotification({\n user,\n scope,\n origin,\n });\n }\n\n let ret = notification;\n if (existingNotification) {\n const restored = await store.restoreExistingNotification({\n id: existingNotification.id,\n notification,\n });\n ret = restored ?? notification;\n } else {\n await store.saveNotification(notification);\n }\n\n notifications.push(ret);\n\n if (signals) {\n await signals.publish<NewNotificationSignal>({\n recipients: { type: 'user', entityRef: [user] },\n message: {\n action: 'new_notification',\n notification_id: ret.id,\n },\n channel: 'notifications',\n });\n }\n postProcessNotification(ret, opts);\n }\n return notifications;\n };\n\n // Add new notification\n router.post(\n '/',\n async (req: Request<any, Notification[], NotificationSendOptions>, res) => {\n const opts = await processOptions(req.body);\n const { recipients, payload } = opts;\n const notifications: Notification[] = [];\n let users = [];\n\n const credentials = await httpAuth.credentials(req, {\n allow: ['service'],\n });\n\n const { title, link } = payload;\n\n if (!recipients || !title) {\n logger.error(`Invalid notification request received`);\n throw new InputError(`Invalid notification request received`);\n }\n\n if (link) {\n try {\n validateLink(link);\n } catch (e) {\n throw new InputError('Invalid link provided', e);\n }\n }\n\n const origin = credentials.principal.subject;\n const baseNotification = {\n payload: {\n ...payload,\n severity: payload.severity ?? 'normal',\n },\n origin,\n created: new Date(),\n };\n\n if (recipients.type === 'broadcast') {\n const broadcast = await sendBroadcastNotification(\n baseNotification,\n opts,\n origin,\n );\n notifications.push(broadcast);\n } else {\n const entityRef = recipients.entityRef;\n\n try {\n users = await getUsersForEntityRef(\n entityRef,\n recipients.excludeEntityRef ?? [],\n { auth, catalogClient: catalog },\n );\n } catch (e) {\n logger.error(`Failed to resolve notification receivers: ${e}`);\n throw new InputError('Failed to resolve notification receivers', e);\n }\n\n const userNotifications = await sendUserNotifications(\n baseNotification,\n users,\n opts,\n origin,\n );\n notifications.push(...userNotifications);\n }\n\n res.json(notifications);\n },\n );\n\n router.use(errorHandler());\n return router;\n}\n"],"names":["DatabaseNotificationsStore","notificationSeverities","Router","express","parseEntityOrderFieldParams","InputError","normalizeSeverity","NotFoundError","uuid","getUsersForEntityRef","errorHandler"],"mappings":";;;;;;;;;;;;;;;;;AAgEA,eAAsB,aACpB,OACyB,EAAA;AACzB,EAAM,MAAA;AAAA,IACJ,MAAA;AAAA,IACA,MAAA;AAAA,IACA,QAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;AAAA,IACA,QAAA;AAAA,IACA,OAAA;AAAA,IACA,aAAa,EAAC;AAAA,IACd,OAAA;AAAA,GACE,GAAA,OAAA,CAAA;AAEJ,EAAA,MAAM,QAAQ,MAAMA,qDAAA,CAA2B,MAAO,CAAA,EAAE,UAAU,CAAA,CAAA;AAClE,EAAM,MAAA,eAAA,GAAkB,MAAO,CAAA,SAAA,CAAU,aAAa,CAAA,CAAA;AAEtD,EAAM,MAAA,OAAA,GAAU,OAAO,GAA0B,KAAA;AAC/C,IAAM,MAAA,WAAA,GAAc,MAAM,QAAA,CAAS,WAAY,CAAA,GAAA,EAAK,EAAE,KAAO,EAAA,CA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;;;"}
1
+ {"version":3,"file":"router.cjs.js","sources":["../../src/service/router.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { errorHandler, PluginDatabaseManager } from '@backstage/backend-common';\nimport express, { Request } from 'express';\nimport Router from 'express-promise-router';\nimport {\n DatabaseNotificationsStore,\n normalizeSeverity,\n NotificationGetOptions,\n} from '../database';\nimport { v4 as uuid } from 'uuid';\nimport { CatalogApi } from '@backstage/catalog-client';\nimport {\n NotificationProcessor,\n NotificationSendOptions,\n} from '@backstage/plugin-notifications-node';\nimport { InputError, NotFoundError } from '@backstage/errors';\nimport {\n AuthService,\n HttpAuthService,\n LoggerService,\n UserInfoService,\n} from '@backstage/backend-plugin-api';\nimport { SignalsService } from '@backstage/plugin-signals-node';\nimport {\n isNotificationsEnabledFor,\n NewNotificationSignal,\n Notification,\n NotificationReadSignal,\n NotificationSettings,\n notificationSeverities,\n NotificationStatus,\n} from '@backstage/plugin-notifications-common';\nimport { parseEntityOrderFieldParams } from './parseEntityOrderFieldParams';\nimport { getUsersForEntityRef } from './getUsersForEntityRef';\nimport { Config } from '@backstage/config';\n\n/** @internal */\nexport interface RouterOptions {\n logger: LoggerService;\n config: Config;\n database: PluginDatabaseManager;\n auth: AuthService;\n httpAuth: HttpAuthService;\n userInfo: UserInfoService;\n signals?: SignalsService;\n catalog: CatalogApi;\n processors?: NotificationProcessor[];\n}\n\n/** @internal */\nexport async function createRouter(\n options: RouterOptions,\n): Promise<express.Router> {\n const {\n config,\n logger,\n database,\n auth,\n httpAuth,\n userInfo,\n catalog,\n processors = [],\n signals,\n } = options;\n\n const WEB_NOTIFICATION_CHANNEL = 'Web';\n const store = await DatabaseNotificationsStore.create({ database });\n const frontendBaseUrl = config.getString('app.baseUrl');\n\n const getUser = async (req: Request<unknown>) => {\n const credentials = await httpAuth.credentials(req, { allow: ['user'] });\n const info = await userInfo.getUserInfo(credentials);\n return info.userEntityRef;\n };\n\n const getNotificationChannels = () => {\n return [WEB_NOTIFICATION_CHANNEL, ...processors.map(p => p.getName())];\n };\n\n const getNotificationSettings = async (user: string) => {\n const { origins } = await store.getUserNotificationOrigins({ user });\n const settings = await store.getNotificationSettings({ user });\n const channels = getNotificationChannels();\n\n const response: NotificationSettings = {\n channels: channels.map(channel => {\n const channelSettings = settings.channels.find(c => c.id === channel);\n if (channelSettings) {\n return channelSettings;\n }\n return {\n id: channel,\n origins: origins.map(origin => ({\n id: origin,\n enabled: true,\n })),\n };\n }),\n };\n return response;\n };\n\n const isNotificationsEnabled = async (opts: {\n user: string;\n channel: string;\n origin: string;\n }) => {\n const settings = await getNotificationSettings(opts.user);\n return isNotificationsEnabledFor(settings, opts.channel, opts.origin);\n };\n\n const filterProcessors = async (\n notification:\n | Notification\n | ({ origin: string; user: null } & NotificationSendOptions),\n ) => {\n const result: NotificationProcessor[] = [];\n const { payload, user, origin } = notification;\n\n for (const processor of processors) {\n if (user) {\n const enabled = await isNotificationsEnabled({\n user,\n origin,\n channel: processor.getName(),\n });\n if (!enabled) {\n continue;\n }\n }\n\n if (processor.getNotificationFilters) {\n const filters = processor.getNotificationFilters();\n if (filters.minSeverity) {\n if (\n notificationSeverities.indexOf(payload.severity ?? 'normal') >\n notificationSeverities.indexOf(filters.minSeverity)\n ) {\n continue;\n }\n }\n\n if (filters.maxSeverity) {\n if (\n notificationSeverities.indexOf(payload.severity ?? 'normal') <\n notificationSeverities.indexOf(filters.maxSeverity)\n ) {\n continue;\n }\n }\n\n if (filters.excludedTopics && payload.topic) {\n if (filters.excludedTopics.includes(payload.topic)) {\n continue;\n }\n }\n }\n result.push(processor);\n }\n\n return result;\n };\n\n const processOptions = async (\n opts: NotificationSendOptions,\n origin: string,\n ) => {\n const filtered = await filterProcessors({ ...opts, origin, user: null });\n let ret = opts;\n for (const processor of filtered) {\n try {\n ret = processor.processOptions\n ? await processor.processOptions(ret)\n : ret;\n } catch (e) {\n logger.error(\n `Error while processing notification options with ${processor.getName()}: ${e}`,\n );\n }\n }\n return ret;\n };\n\n const preProcessNotification = async (\n notification: Notification,\n opts: NotificationSendOptions,\n ) => {\n const filtered = await filterProcessors(notification);\n let ret = notification;\n for (const processor of filtered) {\n try {\n ret = processor.preProcess\n ? await processor.preProcess(ret, opts)\n : ret;\n } catch (e) {\n logger.error(\n `Error while pre processing notification with ${processor.getName()}: ${e}`,\n );\n }\n }\n return ret;\n };\n\n const postProcessNotification = async (\n notification: Notification,\n opts: NotificationSendOptions,\n ) => {\n const filtered = await filterProcessors(notification);\n for (const processor of filtered) {\n if (processor.postProcess) {\n try {\n await processor.postProcess(notification, opts);\n } catch (e) {\n logger.error(\n `Error while post processing notification with ${processor.getName()}: ${e}`,\n );\n }\n }\n }\n };\n\n const validateLink = (link: string) => {\n const stripLeadingSlash = (s: string) => s.replace(/^\\//, '');\n const ensureTrailingSlash = (s: string) => s.replace(/\\/?$/, '/');\n const url = new URL(\n stripLeadingSlash(link),\n ensureTrailingSlash(frontendBaseUrl),\n );\n if (url.protocol !== 'https:' && url.protocol !== 'http:') {\n throw new Error('Only HTTP/HTTPS links are allowed');\n }\n };\n\n // TODO: Move to use OpenAPI router instead\n const router = Router();\n router.use(express.json());\n\n router.get('/health', (_, response) => {\n logger.info('PONG!');\n response.json({ status: 'ok' });\n });\n\n router.get('/', async (req, res) => {\n const user = await getUser(req);\n const opts: NotificationGetOptions = {\n user: user,\n };\n if (req.query.offset) {\n opts.offset = Number.parseInt(req.query.offset.toString(), 10);\n }\n if (req.query.limit) {\n opts.limit = Number.parseInt(req.query.limit.toString(), 10);\n }\n if (req.query.orderField) {\n opts.orderField = parseEntityOrderFieldParams(req.query);\n }\n if (req.query.search) {\n opts.search = req.query.search.toString();\n }\n if (req.query.read === 'true') {\n opts.read = true;\n } else if (req.query.read === 'false') {\n opts.read = false;\n // or keep undefined\n }\n\n if (req.query.topic) {\n opts.topic = req.query.topic.toString();\n }\n\n if (req.query.saved === 'true') {\n opts.saved = true;\n } else if (req.query.saved === 'false') {\n opts.saved = false;\n // or keep undefined\n }\n if (req.query.createdAfter) {\n const sinceEpoch = Date.parse(String(req.query.createdAfter));\n if (isNaN(sinceEpoch)) {\n throw new InputError('Unexpected date format');\n }\n opts.createdAfter = new Date(sinceEpoch);\n }\n if (req.query.minimumSeverity) {\n opts.minimumSeverity = normalizeSeverity(\n req.query.minimumSeverity.toString(),\n );\n }\n\n const [notifications, totalCount] = await Promise.all([\n store.getNotifications(opts),\n store.getNotificationsCount(opts),\n ]);\n res.json({\n totalCount,\n notifications,\n });\n });\n\n router.get('/status', async (req: Request<any, NotificationStatus>, res) => {\n const user = await getUser(req);\n const status = await store.getStatus({ user });\n res.json(status);\n });\n\n router.get(\n '/settings',\n async (req: Request<any, NotificationSettings>, res) => {\n const user = await getUser(req);\n const response = await getNotificationSettings(user);\n res.json(response);\n },\n );\n\n router.post(\n '/settings',\n async (\n req: Request<any, NotificationSettings, NotificationSettings>,\n res,\n ) => {\n const user = await getUser(req);\n const channels = getNotificationChannels();\n const settings: NotificationSettings = req.body;\n if (settings.channels.some(c => !channels.includes(c.id))) {\n throw new InputError('Invalid channel');\n }\n await store.saveNotificationSettings({ user, settings });\n const response = await getNotificationSettings(user);\n res.json(response);\n },\n );\n\n // Make sure this is the last \"GET\" handler\n router.get('/:id', async (req, res) => {\n const user = await getUser(req);\n const opts: NotificationGetOptions = {\n user: user,\n limit: 1,\n ids: [req.params.id],\n };\n const notifications = await store.getNotifications(opts);\n if (notifications.length !== 1) {\n throw new NotFoundError('Not found');\n }\n res.json(notifications[0]);\n });\n\n router.post('/update', async (req, res) => {\n const user = await getUser(req);\n const { ids, read, saved } = req.body;\n if (!ids || !Array.isArray(ids)) {\n throw new InputError();\n }\n\n if (read === true) {\n await store.markRead({ user, ids });\n\n if (signals) {\n await signals.publish<NotificationReadSignal>({\n recipients: { type: 'user', entityRef: [user] },\n message: { action: 'notification_read', notification_ids: ids },\n channel: 'notifications',\n });\n }\n } else if (read === false) {\n await store.markUnread({ user: user, ids });\n\n if (signals) {\n await signals.publish<NotificationReadSignal>({\n recipients: { type: 'user', entityRef: [user] },\n message: { action: 'notification_unread', notification_ids: ids },\n channel: 'notifications',\n });\n }\n }\n\n if (saved === true) {\n await store.markSaved({ user: user, ids });\n } else if (saved === false) {\n await store.markUnsaved({ user: user, ids });\n }\n\n const notifications = await store.getNotifications({ ids, user: user });\n res.json(notifications);\n });\n\n const sendBroadcastNotification = async (\n baseNotification: Omit<Notification, 'user' | 'id'>,\n opts: NotificationSendOptions,\n origin: string,\n ) => {\n const { scope } = opts.payload;\n const broadcastNotification = {\n ...baseNotification,\n user: null,\n id: uuid(),\n };\n const notification = await preProcessNotification(\n broadcastNotification,\n opts,\n );\n let existingNotification;\n if (scope) {\n existingNotification = await store.getExistingScopeBroadcast({\n scope,\n origin,\n });\n }\n\n let ret = notification;\n if (existingNotification) {\n const restored = await store.restoreExistingNotification({\n id: existingNotification.id,\n notification: { ...notification, user: '' },\n });\n ret = restored ?? notification;\n } else {\n await store.saveBroadcast(notification);\n }\n\n if (signals) {\n await signals.publish<NewNotificationSignal>({\n recipients: { type: 'broadcast' },\n message: {\n action: 'new_notification',\n notification_id: ret.id,\n },\n channel: 'notifications',\n });\n postProcessNotification(ret, opts);\n }\n return notification;\n };\n\n const sendUserNotifications = async (\n baseNotification: Omit<Notification, 'user' | 'id'>,\n users: string[],\n opts: NotificationSendOptions,\n origin: string,\n ) => {\n const notifications = [];\n const { scope } = opts.payload;\n const uniqueUsers = [...new Set(users)];\n for (const user of uniqueUsers) {\n const userNotification = {\n ...baseNotification,\n id: uuid(),\n user,\n };\n const notification = await preProcessNotification(userNotification, opts);\n\n const enabled = await isNotificationsEnabled({\n user,\n channel: WEB_NOTIFICATION_CHANNEL,\n origin: userNotification.origin,\n });\n\n let ret = notification;\n if (enabled) {\n let existingNotification;\n if (scope) {\n existingNotification = await store.getExistingScopeNotification({\n user,\n scope,\n origin,\n });\n }\n\n if (existingNotification) {\n const restored = await store.restoreExistingNotification({\n id: existingNotification.id,\n notification,\n });\n ret = restored ?? notification;\n } else {\n await store.saveNotification(notification);\n }\n\n notifications.push(ret);\n\n if (signals) {\n await signals.publish<NewNotificationSignal>({\n recipients: { type: 'user', entityRef: [user] },\n message: {\n action: 'new_notification',\n notification_id: ret.id,\n },\n channel: 'notifications',\n });\n }\n }\n postProcessNotification(ret, opts);\n }\n return notifications;\n };\n\n // Add new notification\n router.post(\n '/',\n async (req: Request<any, Notification[], NotificationSendOptions>, res) => {\n const credentials = await httpAuth.credentials(req, {\n allow: ['service'],\n });\n\n const origin = credentials.principal.subject;\n const opts = await processOptions(req.body, origin);\n const { recipients, payload } = opts;\n const { title, link } = payload;\n const notifications: Notification[] = [];\n let users = [];\n\n if (!recipients || !title) {\n logger.error(`Invalid notification request received`);\n throw new InputError(`Invalid notification request received`);\n }\n\n if (link) {\n try {\n validateLink(link);\n } catch (e) {\n throw new InputError('Invalid link provided', e);\n }\n }\n\n const baseNotification = {\n payload: {\n ...payload,\n severity: payload.severity ?? 'normal',\n },\n origin,\n created: new Date(),\n };\n\n if (recipients.type === 'broadcast') {\n const broadcast = await sendBroadcastNotification(\n baseNotification,\n opts,\n origin,\n );\n notifications.push(broadcast);\n } else {\n const entityRef = recipients.entityRef;\n\n try {\n users = await getUsersForEntityRef(\n entityRef,\n recipients.excludeEntityRef ?? [],\n { auth, catalogClient: catalog },\n );\n } catch (e) {\n logger.error(`Failed to resolve notification receivers: ${e}`);\n throw new InputError('Failed to resolve notification receivers', e);\n }\n\n const userNotifications = await sendUserNotifications(\n baseNotification,\n users,\n opts,\n origin,\n );\n notifications.push(...userNotifications);\n }\n\n res.json(notifications);\n },\n );\n\n router.use(errorHandler());\n return router;\n}\n"],"names":["DatabaseNotificationsStore","isNotificationsEnabledFor","notificationSeverities","Router","express","parseEntityOrderFieldParams","InputError","normalizeSeverity","NotFoundError","uuid","getUsersForEntityRef","errorHandler"],"mappings":";;;;;;;;;;;;;;;;;AAiEA,eAAsB,aACpB,OACyB,EAAA;AACzB,EAAM,MAAA;AAAA,IACJ,MAAA;AAAA,IACA,MAAA;AAAA,IACA,QAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;AAAA,IACA,QAAA;AAAA,IACA,OAAA;AAAA,IACA,aAAa,EAAC;AAAA,IACd,OAAA;AAAA,GACE,GAAA,OAAA,CAAA;AAEJ,EAAA,MAAM,wBAA2B,GAAA,KAAA,CAAA;AACjC,EAAA,MAAM,QAAQ,MAAMA,qDAAA,CAA2B,MAAO,CAAA,EAAE,UAAU,CAAA,CAAA;AAClE,EAAM,MAAA,eAAA,GAAkB,MAAO,CAAA,SAAA,CAAU,aAAa,CAAA,CAAA;AAEtD,EAAM,MAAA,OAAA,GAAU,OAAO,GAA0B,KAAA;AAC/C,IAAM,MAAA,WAAA,GAAc,MAAM,QAAA,CAAS,WAAY,CAAA,GAAA,EAAK,EAAE,KAAO,EAAA,CAAC,MAAM,CAAA,EAAG,CAAA,CAAA;AACvE,IAAA,MAAM,IAAO,GAAA,MAAM,QAAS,CAAA,WAAA,CAAY,WAAW,CAAA,CAAA;AACnD,IAAA,OAAO,IAAK,CAAA,aAAA,CAAA;AAAA,GACd,CAAA;AAEA,EAAA,MAAM,0BAA0B,MAAM;AACpC,IAAO,OAAA,CAAC,0BAA0B,GAAG,UAAA,CAAW,IAAI,CAAK,CAAA,KAAA,CAAA,CAAE,OAAQ,EAAC,CAAC,CAAA,CAAA;AAAA,GACvE,CAAA;AAEA,EAAM,MAAA,uBAAA,GAA0B,OAAO,IAAiB,KAAA;AACtD,IAAM,MAAA,EAAE,SAAY,GAAA,MAAM,MAAM,0BAA2B,CAA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IAAA,QAAA;AAAA,SAChC;AAAA,QACA,MAAA;AAAA,QACA,OAAA,sBAAa,IAAK,EAAA;AAAA,OACpB,CAAA;AAEA,MAAI,IAAA,UAAA,CAAW,SAAS,WAAa,EAAA;AACnC,QAAA,MAAM,YAAY,MAAM,yBAAA;AAAA,UACtB,gBAAA;AAAA,UACA,IAAA;AAAA,UACA,MAAA;AAAA,SACF,CAAA;AACA,QAAA,aAAA,CAAc,KAAK,SAAS,CAAA,CAAA;AAAA,OACvB,MAAA;AACL,QAAA,MAAM,YAAY,UAAW,CAAA,SAAA,CAAA;AAE7B,QAAI,IAAA;AACF,UAAA,KAAA,GAAQ,MAAMI,yCAAA;AAAA,YACZ,SAAA;AAAA,YACA,UAAA,CAAW,oBAAoB,EAAC;AAAA,YAChC,EAAE,IAAM,EAAA,aAAA,EAAe,OAAQ,EAAA;AAAA,WACjC,CAAA;AAAA,iBACO,CAAG,EAAA;AACV,UAAO,MAAA,CAAA,KAAA,CAAM,CAA6C,0CAAA,EAAA,CAAC,CAAE,CAAA,CAAA,CAAA;AAC7D,UAAM,MAAA,IAAIJ,iBAAW,CAAA,0CAAA,EAA4C,CAAC,CAAA,CAAA;AAAA,SACpE;AAEA,QAAA,MAAM,oBAAoB,MAAM,qBAAA;AAAA,UAC9B,gBAAA;AAAA,UACA,KAAA;AAAA,UACA,IAAA;AAAA,UACA,MAAA;AAAA,SACF,CAAA;AACA,QAAc,aAAA,CAAA,IAAA,CAAK,GAAG,iBAAiB,CAAA,CAAA;AAAA,OACzC;AAEA,MAAA,GAAA,CAAI,KAAK,aAAa,CAAA,CAAA;AAAA,KACxB;AAAA,GACF,CAAA;AAEA,EAAO,MAAA,CAAA,GAAA,CAAIK,4BAAc,CAAA,CAAA;AACzB,EAAO,OAAA,MAAA,CAAA;AACT;;;;"}
@@ -0,0 +1,34 @@
1
+ /*
2
+ * Copyright 2024 The Backstage Authors
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ exports.up = async function up(knex) {
17
+ await knex.schema.createTable('user_settings', table => {
18
+ table.string('user').notNullable();
19
+ table.string('channel').notNullable();
20
+ table.string('origin').notNullable();
21
+ table.boolean('enabled').defaultTo(true).notNullable();
22
+ table.index(['user'], 'user_settings_user_idx');
23
+ table.unique(['user', 'channel', 'origin'], {
24
+ indexName: 'user_settings_unique_idx',
25
+ });
26
+ });
27
+ };
28
+
29
+ /**
30
+ * @param {import('knex').Knex} knex
31
+ */
32
+ exports.down = async function down(knex) {
33
+ await knex.schema.dropTable('user_settings');
34
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-notifications-backend",
3
- "version": "0.4.2",
3
+ "version": "0.4.3-next.0",
4
4
  "backstage": {
5
5
  "role": "backend-plugin",
6
6
  "pluginId": "notifications",
@@ -39,17 +39,17 @@
39
39
  },
40
40
  "dependencies": {
41
41
  "@backstage/backend-common": "^0.25.0",
42
- "@backstage/backend-plugin-api": "^1.0.1",
43
- "@backstage/catalog-client": "^1.7.1",
44
- "@backstage/catalog-model": "^1.7.0",
45
- "@backstage/config": "^1.2.0",
46
- "@backstage/errors": "^1.2.4",
47
- "@backstage/plugin-auth-node": "^0.5.3",
48
- "@backstage/plugin-catalog-node": "^1.13.1",
49
- "@backstage/plugin-events-node": "^0.4.2",
50
- "@backstage/plugin-notifications-common": "^0.0.5",
51
- "@backstage/plugin-notifications-node": "^0.2.8",
52
- "@backstage/plugin-signals-node": "^0.1.13",
42
+ "@backstage/backend-plugin-api": "1.0.2-next.0",
43
+ "@backstage/catalog-client": "1.8.0-next.0",
44
+ "@backstage/catalog-model": "1.7.0",
45
+ "@backstage/config": "1.2.0",
46
+ "@backstage/errors": "1.2.4",
47
+ "@backstage/plugin-auth-node": "0.5.4-next.0",
48
+ "@backstage/plugin-catalog-node": "1.14.0-next.0",
49
+ "@backstage/plugin-events-node": "0.4.3-next.0",
50
+ "@backstage/plugin-notifications-common": "0.0.6-next.0",
51
+ "@backstage/plugin-notifications-node": "0.2.9-next.0",
52
+ "@backstage/plugin-signals-node": "0.1.14-next.0",
53
53
  "express": "^4.17.1",
54
54
  "express-promise-router": "^4.1.0",
55
55
  "knex": "^3.0.0",
@@ -59,13 +59,13 @@
59
59
  "yn": "^4.0.0"
60
60
  },
61
61
  "devDependencies": {
62
- "@backstage/backend-defaults": "^0.5.2",
63
- "@backstage/backend-test-utils": "^1.0.2",
64
- "@backstage/cli": "^0.28.0",
65
- "@backstage/plugin-auth-backend": "^0.23.1",
66
- "@backstage/plugin-auth-backend-module-guest-provider": "^0.2.1",
67
- "@backstage/plugin-events-backend": "^0.3.14",
68
- "@backstage/plugin-signals-backend": "^0.2.2",
62
+ "@backstage/backend-defaults": "0.5.3-next.0",
63
+ "@backstage/backend-test-utils": "1.0.3-next.0",
64
+ "@backstage/cli": "0.29.0-next.0",
65
+ "@backstage/plugin-auth-backend": "0.24.0-next.0",
66
+ "@backstage/plugin-auth-backend-module-guest-provider": "0.2.2-next.0",
67
+ "@backstage/plugin-events-backend": "0.3.15-next.0",
68
+ "@backstage/plugin-signals-backend": "0.2.3-next.0",
69
69
  "@types/express": "^4.17.6",
70
70
  "@types/supertest": "^2.0.8",
71
71
  "msw": "^1.0.0",