Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

seanaye/fix/ios notifications (#603)

Sean Aye9be9301c6a8e
diff --git a/js/app/packages/app/component/Soup.tsx b/js/app/packages/app/component/Soup.tsx
index 85ae7e9ead..12aadf04ba 100644
--- a/js/app/packages/app/component/Soup.tsx
+++ b/js/app/packages/app/component/Soup.tsx
@@ -286,7 +286,7 @@ export function Soup() {
});
entityQueryClient.invalidateQueries({
queryKey: queryKeys.notification({
- eventItemId: notification.eventItemId,
+ entity_id: notification.entity_id,
}),
});
}
diff --git a/js/app/packages/app/component/UnifiedListView.tsx b/js/app/packages/app/component/UnifiedListView.tsx
index de316fbf7b..a59e7f6925 100644
--- a/js/app/packages/app/component/UnifiedListView.tsx
+++ b/js/app/packages/app/component/UnifiedListView.tsx
@@ -934,7 +934,7 @@ export function UnifiedListView(props: UnifiedListViewProps) {
let thread_id: string | null | undefined;
const blockHandle = await blockOrchestrator.getBlockHandle(
- notification.eventItemId,
+ notification.entity_id,
'channel'
);
if (!blockHandle) return;
diff --git a/js/app/packages/app/component/dock/QuickAccess.tsx b/js/app/packages/app/component/dock/QuickAccess.tsx
index c61f8baa72..1f0a8c6124 100644
--- a/js/app/packages/app/component/dock/QuickAccess.tsx
+++ b/js/app/packages/app/component/dock/QuickAccess.tsx
@@ -35,7 +35,7 @@ function isHighPriorityNotification(
notification: UnifiedNotification
): boolean {
return (
- notification.eventItemType === 'channel' &&
+ notification.entity_type === 'channel' &&
!notificationIsRead(notification) &&
(notification.notificationEventType ===
NotificationEventType.channel_mention ||
@@ -92,7 +92,7 @@ function QuickAccessItem(props: QuickAccessItemProps) {
const notifications = unreadNotifications();
const index = currentNotificationIndex();
const notification = notifications[index] || notifications[0];
- const channelId = notification.eventItemId;
+ const channelId = notification.entity_id;
if (isChannelMention(notification) || isChannelMessageReply(notification)) {
const metadata = notification.notificationMetadata;
@@ -191,7 +191,7 @@ export function QuickAccess() {
.map((channel) => {
const channelNotifications = notifications
.filter((notification) => {
- if (notification.eventItemId !== channel.id) return false;
+ if (notification.entity_id !== channel.id) return false;
if (!isHighPriorityNotification(notification)) return false;
// For DM channels, include all message notifications
diff --git a/js/app/packages/core/component/GlobalNotificationBell.tsx b/js/app/packages/core/component/GlobalNotificationBell.tsx
index c96702c1ed..dbad698c8e 100644
--- a/js/app/packages/core/component/GlobalNotificationBell.tsx
+++ b/js/app/packages/core/component/GlobalNotificationBell.tsx
@@ -23,7 +23,7 @@ export function GlobalNotificationBell(props: GlobalNotificationBellProps) {
const unreadNotifications = () =>
allUnreadNotifications().filter(
- (n) => !n.done && n.eventItemType !== 'email'
+ (n) => !n.done && n.entity_type !== 'email'
);
const unreadCount = () => unreadNotifications().length;
diff --git a/js/app/packages/macro-entity/src/components/Sort.tsx b/js/app/packages/macro-entity/src/components/Sort.tsx
index 2cbeabdd46..4a6c278388 100644
--- a/js/app/packages/macro-entity/src/components/Sort.tsx
+++ b/js/app/packages/macro-entity/src/components/Sort.tsx
@@ -195,14 +195,6 @@ export function notifiedSortFn<T extends WithNotification<EntityData>>(
const bNotification = b.notifications?.()[0];
if (aNotification && bNotification) {
- if (aNotification.isImportantV0 && bNotification.isImportantV0) {
- return bNotification.createdAt - aNotification.createdAt;
- } else if (aNotification.isImportantV0) {
- return -1;
- } else if (bNotification.isImportantV0) {
- return 1;
- }
-
return bNotification.createdAt - aNotification.createdAt;
} else if (aNotification) {
return -1;
diff --git a/js/app/packages/macro-entity/src/queries/notification.ts b/js/app/packages/macro-entity/src/queries/notification.ts
index 6b58ddc7be..40eb2719ec 100644
--- a/js/app/packages/macro-entity/src/queries/notification.ts
+++ b/js/app/packages/macro-entity/src/queries/notification.ts
@@ -152,7 +152,7 @@ export function createUnseenNotificationIds(
const unseen = unseenNotifications().flatMap((notification) => {
if (notification.viewedAt) return [];
- return [notification.eventItemId];
+ return [notification.entity_id];
});
return [...new Set(unseen)];
@@ -235,14 +235,6 @@ export function enhanceWithNotifications<T extends EntityData>(
? notificationsQuery.data
.filter(({ viewedAt }) => !viewedAt)
.toSorted((a, b) => {
- if (a.isImportantV0 && b.isImportantV0) {
- return b.createdAt - a.createdAt;
- } else if (a.isImportantV0) {
- return -1;
- } else if (b.isImportantV0) {
- return 1;
- }
-
return b.createdAt - a.createdAt;
})
: [];
diff --git a/js/app/packages/macro-entity/src/utils/filter.ts b/js/app/packages/macro-entity/src/utils/filter.ts
index 1eca4f819f..bbfcd71271 100644
--- a/js/app/packages/macro-entity/src/utils/filter.ts
+++ b/js/app/packages/macro-entity/src/utils/filter.ts
@@ -36,10 +36,7 @@ export function unreadFilterFn(entity: WithNotification<EntityData>) {
export function importantFilterFn(entity: WithNotification<EntityData>) {
if (entity.type === 'email') return entity.isImportant;
- return (
- !!entity.notifications &&
- entity.notifications().some(({ isImportantV0 }) => isImportantV0)
- );
+ return !!entity.notifications && entity.notifications().length > 0;
}
export function notDoneFilterFn(entity: WithNotification<EntityData>) {
diff --git a/js/app/packages/notifications/notification-helpers.ts b/js/app/packages/notifications/notification-helpers.ts
index 0714f509e1..94517e2430 100644
--- a/js/app/packages/notifications/notification-helpers.ts
+++ b/js/app/packages/notifications/notification-helpers.ts
@@ -30,8 +30,8 @@ export function notificationIsOfEntity(
entity: Entity
): boolean {
return (
- notification.eventItemType === entity.type &&
- notification.eventItemId === entity.id
+ notification.entity_type === entity.type &&
+ notification.entity_id === entity.id
);
}
@@ -39,7 +39,7 @@ export function notificationIsOfEntityType(
notification: UnifiedNotification,
entityType: string
): boolean {
- return notification.eventItemType === entityType;
+ return notification.entity_type === entityType;
}
/**
@@ -151,7 +151,7 @@ export function markNotificationForEntityIdAsRead(
return notificationSource.bulkMarkAsRead(
notificationSource
.notifications()
- .filter((n) => n.eventItemId === id && !notificationIsRead(n))
+ .filter((n) => n.entity_id === id && !notificationIsRead(n))
);
}
diff --git a/js/app/packages/notifications/notification-navigation.ts b/js/app/packages/notifications/notification-navigation.ts
index 40e1085733..9d27dfab10 100644
--- a/js/app/packages/notifications/notification-navigation.ts
+++ b/js/app/packages/notifications/notification-navigation.ts
@@ -58,7 +58,7 @@ async function openChannelNotification(
notification: TypedNotification<ChannelNotificationType>,
layoutManager: SplitManager
) {
- const channelId = notification.eventItemId;
+ const channelId = notification.entity_id;
const messageId = notification.notificationMetadata.messageId;
const threadId =
'threadId' in notification.notificationMetadata
@@ -102,7 +102,7 @@ function getSupportedHandler(
.with(
{ notificationEventType: 'channel_invite' },
(n) => async (lm: SplitManager) =>
- openSplitIfNotOpen(lm, 'channel', n.eventItemId)
+ openSplitIfNotOpen(lm, 'channel', n.entity_id)
)
.with(
{
@@ -115,7 +115,7 @@ function getSupportedHandler(
openSplitIfNotOpen(
lm,
safeFileTypeToBlockName(n.notificationMetadata.itemType),
- n.eventItemId
+ n.entity_id
)
)
.with(
@@ -129,7 +129,7 @@ function getSupportedHandler(
openSplitIfNotOpen(
lm,
safeFileTypeToBlockName(n.notificationMetadata.fileType),
- n.eventItemId
+ n.entity_id
)
)
.with(
diff --git a/js/app/packages/notifications/notification-preview.ts b/js/app/packages/notifications/notification-preview.ts
index 8968aed5ac..33608fd8a8 100644
--- a/js/app/packages/notifications/notification-preview.ts
+++ b/js/app/packages/notifications/notification-preview.ts
@@ -96,7 +96,7 @@ const extractors: {
action: 'mentioned you in',
target: {
type: 'channel',
- id: n.eventItemId,
+ id: n.entity_id,
show: n.notificationMetadata.channelType !== 'direct_message',
},
content: m.messageContent,
@@ -112,7 +112,7 @@ const extractors: {
type: n.notificationEventType,
actor: n.senderId ? { id: n.senderId! } : undefined,
action: 'mentioned you in',
- target: { type: 'document', id: n.eventItemId, name: m.documentName },
+ target: { type: 'document', id: n.entity_id, name: m.documentName },
content: m.documentName,
meta: {
fileType: m.fileType,
@@ -126,7 +126,7 @@ const extractors: {
type: n.notificationEventType,
actor: m.invitedBy ? { id: m.invitedBy! } : undefined,
action: 'invited you to',
- target: { type: 'channel', id: n.eventItemId, name: m.channelName },
+ target: { type: 'channel', id: n.entity_id, name: m.channelName },
content: m.channelName,
};
},
@@ -139,7 +139,7 @@ const extractors: {
action: 'sent a message in',
target: {
type: 'channel',
- id: n.eventItemId,
+ id: n.entity_id,
show: n.notificationMetadata.channelType !== 'direct_message',
},
content: m.messageContent,
@@ -157,7 +157,7 @@ const extractors: {
action: 'replied in',
target: {
type: 'channel',
- id: n.eventItemId,
+ id: n.entity_id,
show: n.notificationMetadata.channelType !== 'direct_message',
},
content: m.messageContent,
@@ -174,7 +174,7 @@ const extractors: {
type: n.notificationEventType,
actor: m.owner ? { id: m.owner! } : undefined,
action: 'shared with you',
- target: { type: 'document', id: n.eventItemId, name: m.documentName },
+ target: { type: 'document', id: n.entity_id, name: m.documentName },
content: m.documentName,
meta: {
fileType: m.fileType,
@@ -188,7 +188,7 @@ const extractors: {
type: n.notificationEventType,
actor: m.sender ? { id: m.sender! } : undefined,
action: 'sent a new email',
- target: { type: 'email', id: n.eventItemId, show: false },
+ target: { type: 'email', id: n.entity_id, show: false },
content: m.subject,
meta: {
sender: m.sender,
@@ -204,7 +204,7 @@ const extractors: {
type: n.notificationEventType,
actor: m.invitedBy ? { id: m.invitedBy! } : undefined,
action: 'invited you to',
- target: { type: 'team', id: n.eventItemId, name: m.teamName },
+ target: { type: 'team', id: n.entity_id, name: m.teamName },
content: m.teamName,
};
},
@@ -215,7 +215,7 @@ const extractors: {
type: n.notificationEventType,
actor: undefined,
action: 'rejected your team invitation',
- target: { type: 'team', id: n.eventItemId },
+ target: { type: 'team', id: n.entity_id },
content: undefined,
};
},
diff --git a/js/app/packages/notifications/types.ts b/js/app/packages/notifications/types.ts
index f02a478bb2..2955a0aea9 100644
--- a/js/app/packages/notifications/types.ts
+++ b/js/app/packages/notifications/types.ts
@@ -11,7 +11,7 @@ export function compositeEntity(entity: Entity): CompositeEntity {
export function notificationEntity(notification: UnifiedNotification): Entity {
return {
- id: notification.eventItemId,
- type: notification.eventItemType as EntityType,
+ id: notification.entity_id,
+ type: notification.entity_type as EntityType,
};
}
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageDocumentMetadata.ts b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageDocumentMetadata.ts
new file mode 100644
index 0000000000..c7bc75301d
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/channelMessageDocumentMetadata.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentMentionMetadata } from './documentMentionMetadata';
+
+export type ChannelMessageDocumentMetadata = DocumentMentionMetadata;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/createNotification.ts b/js/app/packages/service-clients/service-notification/generated/schemas/createNotification.ts
index 43bbf4427b..4ff98a2a08 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/createNotification.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/createNotification.ts
@@ -4,16 +4,7 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
+import type { Entity } from './entity';
+import type { CreateNotificationAllOf } from './createNotificationAllOf';
-export interface CreateNotification {
- /** The item id the notification event was created for */
- event_item_id: string;
- /** The item type (document, chat, project...) */
- event_item_type: string;
- /** Custom metadata that may be needed for the notification */
- metadata?: unknown;
- /** The type of notification */
- notification_event_type: string;
- /** The service that created the notification */
- service_sender: string;
-}
+export type CreateNotification = Entity & CreateNotificationAllOf;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/createNotificationAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/createNotificationAllOf.ts
new file mode 100644
index 0000000000..ce0fd798cd
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/createNotificationAllOf.ts
@@ -0,0 +1,15 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type CreateNotificationAllOf = {
+ /** Custom metadata that may be needed for the notification */
+ metadata?: unknown;
+ /** The type of notification */
+ notification_event_type: string;
+ /** The service that created the notification */
+ service_sender: string;
+};
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/entity.ts b/js/app/packages/service-clients/service-notification/generated/schemas/entity.ts
new file mode 100644
index 0000000000..aebf5efcac
--- /dev/null
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/entity.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * notification_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { EntityType } from './entityType';
+
+/**
+ * The Entity describes the minimum amount of information required to describe a unique thing in Macro
+This contains the type of the entity [EntityType] and the string id of that entity
+ */
+export interface Entity {
+ /** The id of that entity */
+ entity_id: string;
+ /** The type of entity we are describing */
+ entity_type: EntityType;
+}
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
index 518bd541f6..d9be9b1ce3 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/index.ts
@@ -12,6 +12,7 @@ export * from './channelInviteMetadataAllOf';
export * from './channelMentionMetadata';
export * from './channelMentionMetadataAllOf';
export * from './channelMentionMetadataAllOfThreadId';
+export * from './channelMessageDocumentMetadata';
export * from './channelMessageSendMetadata';
export * from './channelMessageSendMetadataAllOf';
export * from './channelReplyMetadata';
@@ -19,12 +20,14 @@ export * from './channelReplyMetadataAllOf';
export * from './channelType';
export * from './commonChannelMetadata';
export * from './createNotification';
+export * from './createNotificationAllOf';
export * from './deviceRequest';
export * from './deviceType';
export * from './documentMentionMetadata';
export * from './documentMentionMetadataAllOf';
export * from './documentMentionMetadataAllOfFileType';
export * from './emptyResponse';
+export * from './entity';
export * from './entityType';
export * from './errorResponse';
export * from './getAllUserNotificationsResponse';
@@ -45,7 +48,6 @@ export * from './notification';
export * from './notificationAllOf';
export * from './notificationAllOfSenderId';
export * from './notificationBulkRequest';
-export * from './notificationEntity';
export * from './notificationEvent';
export * from './notificationEventOneOf';
export * from './notificationEventOneOfFive';
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notification.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notification.ts
index 70cff70b3b..7ba0d0e679 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/notification.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/notification.ts
@@ -4,9 +4,9 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
-import type { NotificationEntity } from './notificationEntity';
+import type { Entity } from './entity';
import type { NotificationTemporalData } from './notificationTemporalData';
import type { NotificationEvent } from './notificationEvent';
import type { NotificationAllOf } from './notificationAllOf';
-export type Notification = NotificationEntity & NotificationTemporalData & NotificationEvent & NotificationAllOf;
+export type Notification = Entity & NotificationTemporalData & NotificationEvent & NotificationAllOf;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEntity.ts b/js/app/packages/service-clients/service-notification/generated/schemas/notificationEntity.ts
deleted file mode 100644
index 813388ae12..0000000000
--- a/js/app/packages/service-clients/service-notification/generated/schemas/notificationEntity.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * notification_service
- * OpenAPI spec version: 0.1.0
- */
-import type { EntityType } from './entityType';
-
-/**
- * The entity that triggered the notification
-This is a combination of an [EntityType] and an id (Uuid or string)
- */
-export interface NotificationEntity {
- eventItemId: string;
- eventItemType: EntityType;
-}
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/pushNotificationData.ts b/js/app/packages/service-clients/service-notification/generated/schemas/pushNotificationData.ts
index f6e9296fa7..9dd3b2f726 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/pushNotificationData.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/pushNotificationData.ts
@@ -4,7 +4,7 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
-import type { NotificationEntity } from './notificationEntity';
+import type { Entity } from './entity';
import type { PushNotificationDataAllOf } from './pushNotificationDataAllOf';
-export type PushNotificationData = NotificationEntity & PushNotificationDataAllOf;
+export type PushNotificationData = Entity & PushNotificationDataAllOf;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/userNotification.ts b/js/app/packages/service-clients/service-notification/generated/schemas/userNotification.ts
index 83ffea402c..faf8b73db8 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/userNotification.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/userNotification.ts
@@ -4,9 +4,9 @@
* notification_service
* OpenAPI spec version: 0.1.0
*/
-import type { NotificationEntity } from './notificationEntity';
+import type { Entity } from './entity';
import type { NotificationTemporalData } from './notificationTemporalData';
import type { NotificationEvent } from './notificationEvent';
import type { UserNotificationAllOf } from './userNotificationAllOf';
-export type UserNotification = NotificationEntity & NotificationTemporalData & NotificationEvent & UserNotificationAllOf;
+export type UserNotification = Entity & NotificationTemporalData & NotificationEvent & UserNotificationAllOf;
diff --git a/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOf.ts b/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOf.ts
index 96e7d4cc49..cc1fa3741d 100644
--- a/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOf.ts
+++ b/js/app/packages/service-clients/service-notification/generated/schemas/userNotificationAllOf.ts
@@ -11,8 +11,6 @@ export type UserNotificationAllOf = {
done: boolean;
/** The id of the notification. Self-generated uuidv7 */
id: string;
- /** if notification is important or not */
- isImportantV0: boolean;
/** user id of the macro user who generated the notification */
senderId?: UserNotificationAllOfSenderId;
/** If the notification has been sent */
diff --git a/js/app/packages/service-clients/service-notification/openapi.json b/js/app/packages/service-clients/service-notification/openapi.json
index 2b84aece96..82ab46ade5 100644
--- a/js/app/packages/service-clients/service-notification/openapi.json
+++ b/js/app/packages/service-clients/service-notification/openapi.json
@@ -777,6 +777,9 @@
}
]
},
+ "ChannelMessageDocumentMetadata": {
+ "$ref": "#/components/schemas/DocumentMentionMetadata"
+ },
"ChannelMessageSendMetadata": {
"allOf": [
{ "$ref": "#/components/schemas/CommonChannelMetadata" },
@@ -841,34 +844,29 @@
}
},
"CreateNotification": {
- "type": "object",
- "required": [
- "notification_event_type",
- "event_item_id",
- "event_item_type",
- "service_sender"
- ],
- "properties": {
- "event_item_id": {
- "type": "string",
- "description": "The item id the notification event was created for"
- },
- "event_item_type": {
- "type": "string",
- "description": "The item type (document, chat, project...)"
- },
- "metadata": {
- "description": "Custom metadata that may be needed for the notification"
- },
- "notification_event_type": {
- "type": "string",
- "description": "The type of notification"
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/Entity",
+ "description": "The [Entity] the notification event was created for"
},
- "service_sender": {
- "type": "string",
- "description": "The service that created the notification"
+ {
+ "type": "object",
+ "required": ["notification_event_type", "service_sender"],
+ "properties": {
+ "metadata": {
+ "description": "Custom metadata that may be needed for the notification"
+ },
+ "notification_event_type": {
+ "type": "string",
+ "description": "The type of notification"
+ },
+ "service_sender": {
+ "type": "string",
+ "description": "The service that created the notification"
+ }
+ }
}
- }
+ ]
},
"DeviceRequest": {
"type": "object",
@@ -906,6 +904,21 @@
"type": "object",
"description": "Empty response is required due to custom fetch forcing `response.json()`"
},
+ "Entity": {
+ "type": "object",
+ "description": "The Entity describes the minimum amount of information required to describe a unique thing in Macro\nThis contains the type of the entity [EntityType] and the string id of that entity",
+ "required": ["entity_type", "entity_id"],
+ "properties": {
+ "entity_id": {
+ "type": "string",
+ "description": "The id of that entity"
+ },
+ "entity_type": {
+ "$ref": "#/components/schemas/EntityType",
+ "description": "The type of entity we are describing"
+ }
+ }
+ },
"EntityType": {
"type": "string",
"description": "The type of an entity in Macro",
@@ -1038,7 +1051,7 @@
},
"Notification": {
"allOf": [
- { "$ref": "#/components/schemas/NotificationEntity" },
+ { "$ref": "#/components/schemas/Entity" },
{ "$ref": "#/components/schemas/NotificationTemporalData" },
{ "$ref": "#/components/schemas/NotificationEvent" },
{
@@ -1063,15 +1076,6 @@
}
}
},
- "NotificationEntity": {
- "type": "object",
- "description": "The entity that triggered the notification\nThis is a combination of an [EntityType] and an id (Uuid or string)",
- "required": ["eventItemId", "eventItemType"],
- "properties": {
- "eventItemId": { "type": "string" },
- "eventItemType": { "$ref": "#/components/schemas/EntityType" }
- }
- },
"NotificationEvent": {
"oneOf": [
{
@@ -1189,7 +1193,7 @@
"enum": ["channel_message_document"]
},
"notificationMetadata": {
- "$ref": "#/components/schemas/DocumentMentionMetadata",
+ "$ref": "#/components/schemas/ChannelMessageDocumentMetadata",
"description": "If a document is included via mention or attachment on a message"
}
}
@@ -1267,7 +1271,7 @@
},
"PushNotificationData": {
"allOf": [
- { "$ref": "#/components/schemas/NotificationEntity" },
+ { "$ref": "#/components/schemas/Entity" },
{
"type": "object",
"required": ["openRoute"],
@@ -1295,12 +1299,12 @@
},
"UserNotification": {
"allOf": [
- { "$ref": "#/components/schemas/NotificationEntity" },
+ { "$ref": "#/components/schemas/Entity" },
{ "$ref": "#/components/schemas/NotificationTemporalData" },
{ "$ref": "#/components/schemas/NotificationEvent" },
{
"type": "object",
- "required": ["id", "sent", "done", "isImportantV0"],
+ "required": ["id", "sent", "done"],
"properties": {
"done": {
"type": "boolean",
@@ -1311,10 +1315,6 @@
"format": "uuid",
"description": "The id of the notification. Self-generated uuidv7"
},
- "isImportantV0": {
- "type": "boolean",
- "description": "if notification is important or not"
- },
"senderId": {
"type": ["string", "null"],
"description": "user id of the macro user who generated the notification"
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index e702d3a41b..b3daec0b23 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -529,6 +529,7 @@ dependencies = [
"maud",
"mockall",
"model",
+ "model-entity",
"model_notifications",
"models_team",
"native_app_service",
@@ -5066,6 +5067,7 @@ dependencies = [
"nom 8.0.0",
"serde",
"thiserror 2.0.17",
+ "tracing",
]
[[package]]
@@ -5234,9 +5236,13 @@ name = "mention_utils"
version = "0.1.0"
dependencies = [
"anyhow",
+ "cool_asserts",
+ "macro_user_id",
+ "nom 8.0.0",
"regex",
"serde",
"serde_json",
+ "thiserror 2.0.17",
]
[[package]]
@@ -5443,6 +5449,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
+ "macro_user_id",
"model-entity",
"models_comms",
"models_pagination",
@@ -5782,8 +5789,10 @@ version = "0.1.0"
dependencies = [
"anyhow",
"chrono",
+ "macro_user_id",
"macro_uuid",
"model",
+ "model-entity",
"model_notifications",
"models_pagination",
"serde",
@@ -5818,10 +5827,12 @@ dependencies = [
"macro_env",
"macro_middleware",
"macro_notify",
+ "macro_user_id",
"macro_uuid",
"mention_utils",
"model",
"model-entity",
+ "model_file_type",
"model_notifications",
"models_comms",
"models_pagination",
@@ -8144,6 +8155,10 @@ version = "0.1.0"
dependencies = [
"anyhow",
"aws-sdk-sns",
+ "model-entity",
+ "serde",
+ "serde_json",
+ "tracing",
]
[[package]]
diff --git a/rust/cloud-storage/ai_tools/src/list/file.rs b/rust/cloud-storage/ai_tools/src/list/file.rs
index 0b68388eb0..e665377695 100644
--- a/rust/cloud-storage/ai_tools/src/list/file.rs
+++ b/rust/cloud-storage/ai_tools/src/list/file.rs
@@ -341,6 +341,6 @@ mod tests {
assert_eq!(list_docs.min_access_level, None);
assert_eq!(list_docs.page_offset, 0);
assert_eq!(list_docs.page_size, DEFAULT_PAGE_SIZE);
- assert_eq!(list_docs.exhaustive_search, false);
+ assert!(!list_docs.exhaustive_search);
}
}
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 7d92881d9c..db3cece739 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -74,6 +74,7 @@ macro_uuid = { path = "../macro_uuid" }
maud = { version = "0.27.0" }
mockall = { workspace = true }
model = { path = "../model" }
+model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
models_team = { path = "../models_team" }
native_app_service = { path = "../native_app_service" }
diff --git a/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs b/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs
index 8837801d4e..e8b3aa2743 100644
--- a/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs
+++ b/rust/cloud-storage/authentication_service/src/api/team/invite_to_team.rs
@@ -5,6 +5,7 @@ use axum::{
response::{IntoResponse, Response},
};
use macro_user_id::{cowlike::CowLike, email::Email, lowercased::Lowercase, user_id::MacroUserId};
+use model_entity::EntityType;
use teams::domain::{
model::{InviteUsersToTeamError, TeamInvite},
team_repo::TeamService,
@@ -21,9 +22,7 @@ use crate::api::{
use model::{response::ErrorResponse, tracking::IPContext, user::UserContext};
-use model_notifications::{
- InviteToTeamMetadata, NotificationEntity, NotificationEvent, NotificationQueueMessage,
-};
+use model_notifications::{InviteToTeamMetadata, NotificationEvent, NotificationQueueMessage};
/// The request body to invite a user to a team
#[derive(serde::Serialize, serde::Deserialize, utoipa::ToSchema)]
@@ -192,13 +191,11 @@ pub(in crate::api::team) async fn notify_team_invite(
for team_invite in team_invites {
let notification_queue_message = NotificationQueueMessage {
- notification_entity: NotificationEntity::new_team(
- team_invite.team_invite_id.to_string(),
- ),
+ notification_entity: EntityType::Team
+ .with_entity_string(team_invite.team_invite_id.to_string()),
notification_event: NotificationEvent::InviteToTeam(notification_metadata.clone()),
sender_id: Some(invited_by.to_string()),
recipient_ids: Some(vec![format!("macro|{}", team_invite.email.as_ref())]),
- is_important_v0: Some(false),
};
macro_notify_client
diff --git a/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs b/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs
index 4a5d6fa746..74a10e9215 100644
--- a/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs
+++ b/rust/cloud-storage/authentication_service/src/api/team/reinvite_to_team.rs
@@ -4,9 +4,8 @@ use axum::{
http::StatusCode,
response::{IntoResponse, Response},
};
-use model_notifications::{
- InviteToTeamMetadata, NotificationEntity, NotificationEvent, NotificationQueueMessage,
-};
+use model_entity::EntityType;
+use model_notifications::{InviteToTeamMetadata, NotificationEvent, NotificationQueueMessage};
use crate::api::{
context::ApiContext,
@@ -140,11 +139,10 @@ async fn notify_team_invite(
};
let notification_queue_message = NotificationQueueMessage {
- notification_entity: NotificationEntity::new_team(team_invite_id.to_string()),
+ notification_entity: EntityType::Team.with_entity_string(team_invite_id.to_string()),
notification_event: NotificationEvent::InviteToTeam(notification_metadata),
sender_id: Some(invited_by.to_string()),
recipient_ids: Some(vec![format!("macro|{normalized_email}")]),
- is_important_v0: Some(false),
};
macro_notify_client
diff --git a/rust/cloud-storage/comms_service/src/notification.rs b/rust/cloud-storage/comms_service/src/notification.rs
index c9a6b452e0..8ca88c893b 100644
--- a/rust/cloud-storage/comms_service/src/notification.rs
+++ b/rust/cloud-storage/comms_service/src/notification.rs
@@ -7,11 +7,10 @@ use comms_db_client::{
use model::{comms::ChannelParticipant, document_storage_service_internal::DocumentMetadata};
use model_entity::EntityType;
use model_notifications::{
- ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,
- ChannelReplyMetadata, CommonChannelMetadata, DocumentMentionMetadata, NotificationEntity,
- NotificationEvent, NotificationQueueMessage,
+ ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageDocumentMetadata,
+ ChannelMessageSendMetadata, ChannelReplyMetadata, CommonChannelMetadata,
+ DocumentMentionMetadata, NotificationEvent, NotificationQueueMessage,
};
-use models_comms::ChannelType;
use std::{collections::HashSet, iter::once};
use uuid::Uuid;
@@ -45,26 +44,17 @@ fn recipients_excluding<'a>(
.collect()
}
-pub fn is_channel_type_important(channel_type: &ChannelType) -> bool {
- matches!(channel_type, ChannelType::DirectMessage)
-}
-
fn create_notification_queue_message(
channel_id: &Uuid,
sender_id: &str,
recipients: &[String],
notification_event: NotificationEvent,
- important: bool,
) -> NotificationQueueMessage {
NotificationQueueMessage {
- notification_entity: NotificationEntity {
- event_item_id: channel_id.to_string(),
- event_item_type: EntityType::Channel,
- },
+ notification_entity: EntityType::Channel.with_entity_string(channel_id.to_string()),
sender_id: Some(sender_id.to_string()),
recipient_ids: Some(recipients.to_vec()),
notification_event,
- is_important_v0: Some(important),
}
}
@@ -84,7 +74,6 @@ impl<'a> ChannelInviteEvent<'a> {
invited_by: self.invited_by_user_id.to_string(),
common: self.common.clone(),
}),
- true,
));
}
@@ -110,7 +99,6 @@ impl ChannelMessageEvent<'_> {
thread_id: self.message.thread_id.map(|t| t.to_string()),
common: self.channel_metadata.clone(),
}),
- true,
));
}
@@ -125,13 +113,14 @@ impl ChannelMessageEvent<'_> {
self.channel_id,
&self.message.sender_id,
&recipients_excluding_mentions,
- NotificationEvent::ChannelMessageDocument(DocumentMentionMetadata {
- document_name: mention.item_name.clone(),
- owner: mention.item_owner.clone(),
- file_type: mention.file_type.clone(),
- metadata: None,
- }),
- true,
+ NotificationEvent::ChannelMessageDocument(ChannelMessageDocumentMetadata(
+ DocumentMentionMetadata {
+ document_name: mention.item_name.clone(),
+ owner: mention.item_owner.clone(),
+ file_type: mention.file_type.clone(),
+ metadata: None,
+ },
+ )),
));
}
}
@@ -166,7 +155,6 @@ impl ChannelMessageEvent<'_> {
message_content: self.message.content.clone(),
common: self.channel_metadata.clone(),
}),
- true,
));
} else {
tracing::warn!("thread participants is empty, but message has thread id");
@@ -182,7 +170,6 @@ impl ChannelMessageEvent<'_> {
invited_by: self.message.sender_id.clone(),
common: self.channel_metadata.clone(),
}),
- true,
));
}
// Channel has messages, send message send notification
@@ -197,7 +184,6 @@ impl ChannelMessageEvent<'_> {
message_content: self.message.content.to_string(),
common: self.channel_metadata.clone(),
}),
- is_channel_type_important(&self.channel_metadata.channel_type),
));
}
}
@@ -298,11 +284,11 @@ pub async fn dispatch_notifications_for_message(
#[cfg(test)]
mod tests {
- use std::collections::HashMap;
-
use super::*;
use model::comms::ParticipantRole;
use model_notifications::NotificationEventType;
+ use models_comms::ChannelType;
+ use std::collections::HashMap;
use uuid::Uuid;
fn participant(user_id: &str, channel_id: Uuid) -> ChannelParticipant {
@@ -345,13 +331,6 @@ mod tests {
}
}
- fn dm_metadata() -> CommonChannelMetadata {
- CommonChannelMetadata {
- channel_type: ChannelType::DirectMessage,
- channel_name: "dm".to_string(),
- }
- }
-
// Ensures that each recipient receives only one message notification
fn assert_single_message_notification_per_recipient(
notifications: &[NotificationQueueMessage],
@@ -661,31 +640,4 @@ mod tests {
assert!(!has_reply);
}
-
- #[test]
- fn dm_message_marked_important() {
- let channel_id = Uuid::new_v4();
- let participants = vec![
- participant("sender", channel_id),
- participant("alice", channel_id),
- ];
- let msg = message(channel_id, "sender", None);
- let metadata = dm_metadata();
-
- let event = ChannelMessageEvent {
- channel_id: &channel_id,
- message: &msg,
- channel_metadata: &metadata,
- channel_message_count: 2,
- user_mentions: &[],
- document_mentions: &[],
- participants: &participants,
- thread_participants: &[],
- };
-
- let notifications = event.generate_notifications();
- assert_single_message_notification_per_recipient(&notifications);
-
- assert_eq!(notifications[0].is_important_v0, Some(true));
- }
}
diff --git a/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs b/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs
index 8dd2ad3c45..12aef76881 100644
--- a/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/mentions/upsert_user_mentions.rs
@@ -13,9 +13,8 @@ use model::{
document::DocumentBasic,
response::{EmptyResponse, GenericErrorResponse, GenericResponse},
};
-use model_notifications::{
- DocumentMentionMetadata, NotificationEntity, NotificationEvent, NotificationQueueMessage,
-};
+use model_entity::EntityType;
+use model_notifications::{DocumentMentionMetadata, NotificationEvent, NotificationQueueMessage};
use models_permissions::share_permission::access_level::CommentAccessLevel;
#[derive(serde::Deserialize)]
@@ -62,11 +61,10 @@ pub async fn handler(
};
let notification_queue_message = NotificationQueueMessage {
- notification_entity: NotificationEntity::new_document(document_id),
+ notification_entity: EntityType::Document.with_entity_string(document_id),
notification_event: NotificationEvent::DocumentMention(metadata),
sender_id: Some(user_context.user_id.clone()),
recipient_ids: Some(req.mentions.clone()),
- is_important_v0: Some(false),
};
if let Err(err) = macro_notify_client
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
index e2afa64ae4..a766ab16a7 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
@@ -15,9 +15,8 @@ use model::insight_context::email_insights::{
EMAIL_INSIGHT_PROVIDER_SOURCE_NAME, EmailInfo, GenerateEmailInsightContext, NewMessagePayload,
NewMessagesPayload,
};
-use model_notifications::{
- NewEmailMetadata, NotificationEntity, NotificationEvent, NotificationQueueMessage,
-};
+use model_entity::EntityType;
+use model_notifications::{NewEmailMetadata, NotificationEvent, NotificationQueueMessage};
use models_email::db::address::EmailRecipientType;
use models_email::email::service;
use models_email::email::service::link;
@@ -588,11 +587,10 @@ async fn send_notifications(
};
let notification_queue_message = NotificationQueueMessage {
- notification_entity: NotificationEntity::new_email(message.db_id.to_string()),
+ notification_entity: EntityType::Email.with_entity_string(message.db_id.to_string()),
notification_event: NotificationEvent::NewEmail(notification_metadata),
sender_id,
recipient_ids: Some(vec![link.macro_id.to_string()]),
- is_important_v0: Some(false),
};
if let Err(e) = ctx
diff --git a/rust/cloud-storage/macro_share_permissions/src/notification.rs b/rust/cloud-storage/macro_share_permissions/src/notification.rs
index 1990ed3fa8..25bb58870a 100644
--- a/rust/cloud-storage/macro_share_permissions/src/notification.rs
+++ b/rust/cloud-storage/macro_share_permissions/src/notification.rs
@@ -1,11 +1,9 @@
-use std::str::FromStr;
-
use anyhow::Context;
use model_entity::EntityType;
use model_notifications::{
- ItemSharedMetadata, ItemSharedOrganizationMetadata, NotificationEntity, NotificationEvent,
- NotificationQueueMessage,
+ ItemSharedMetadata, ItemSharedOrganizationMetadata, NotificationEvent, NotificationQueueMessage,
};
+use std::str::FromStr;
#[derive(Debug)]
pub struct ItemShareNotifications {
@@ -33,14 +31,10 @@ pub fn create_notifications_from_item_shared(
let build_message =
|recipients: &[String], event_type: NotificationEvent| -> NotificationQueueMessage {
NotificationQueueMessage {
- notification_entity: NotificationEntity {
- event_item_id: item_id.to_string(),
- event_item_type: entity_type,
- },
+ notification_entity: entity_type.with_entity_string(item_id.to_string()),
notification_event: event_type,
sender_id: Some(user_id.to_string()),
recipient_ids: Some(recipients.to_vec()),
- is_important_v0: Some(false),
}
};
diff --git a/rust/cloud-storage/macro_user_id/Cargo.toml b/rust/cloud-storage/macro_user_id/Cargo.toml
index af11cc8cd6..f92945dda5 100644
--- a/rust/cloud-storage/macro_user_id/Cargo.toml
+++ b/rust/cloud-storage/macro_user_id/Cargo.toml
@@ -9,3 +9,4 @@ doppleganger = { workspace = true }
nom = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
+tracing = { workspace = true }
diff --git a/rust/cloud-storage/macro_user_id/src/user_id.rs b/rust/cloud-storage/macro_user_id/src/user_id.rs
index 856eaca10d..0985793ec5 100644
--- a/rust/cloud-storage/macro_user_id/src/user_id.rs
+++ b/rust/cloud-storage/macro_user_id/src/user_id.rs
@@ -66,6 +66,11 @@ where
#[serde(try_from = "String", into = "String")]
pub struct MacroUserIdStr<'a>(pub MacroUserId<ArcCowStr<'a>>);
+/// Deserialize a MacroUserId to a guaranteed borrowed lifetime from the 'de argument
+#[derive(Debug, Clone, Deserialize)]
+#[serde(try_from = "&str")]
+pub struct BorrowedUserIdStr<'a>(#[serde(borrow)] pub MacroUserId<ArcCowStr<'a>>);
+
impl<'a> doppleganger::Primitive for MacroUserIdStr<'a> {}
impl<'a> std::fmt::Display for MacroUserIdStr<'a> {
@@ -84,6 +89,7 @@ impl<'a> Deref for MacroUserIdStr<'a> {
impl<'a> MacroUserIdStr<'a> {
/// parse the inner value from the input string
+ #[tracing::instrument(err)]
pub fn parse_from_str(s: &'a str) -> Result<Self, ParseErr> {
MacroUserId::parse_from_str(s).map(MacroUserIdStr)
}
@@ -106,6 +112,14 @@ impl TryFrom<String> for MacroUserIdStr<'static> {
}
}
+impl<'a> TryFrom<&'a str> for BorrowedUserIdStr<'a> {
+ type Error = ParseErr;
+
+ fn try_from(value: &'a str) -> Result<Self, Self::Error> {
+ MacroUserId::parse_from_str(value).map(BorrowedUserIdStr)
+ }
+}
+
impl<'a> From<MacroUserIdStr<'a>> for String {
fn from(value: MacroUserIdStr<'a>) -> Self {
value.0.as_ref().to_string()
diff --git a/rust/cloud-storage/mention_utils/Cargo.toml b/rust/cloud-storage/mention_utils/Cargo.toml
index 1cfa46a8b3..5e09b795c5 100644
--- a/rust/cloud-storage/mention_utils/Cargo.toml
+++ b/rust/cloud-storage/mention_utils/Cargo.toml
@@ -6,6 +6,12 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
+nom = { workspace = true }
regex = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
+thiserror = { workspace = true }
+
+[dev-dependencies]
+cool_asserts = { version = "2" }
diff --git a/rust/cloud-storage/mention_utils/src/lib.rs b/rust/cloud-storage/mention_utils/src/lib.rs
index f5b20879a5..5ce9f7b758 100644
--- a/rust/cloud-storage/mention_utils/src/lib.rs
+++ b/rust/cloud-storage/mention_utils/src/lib.rs
@@ -1,460 +1,4 @@
-use anyhow::Context;
-use regex::Regex;
-use serde::Deserialize;
-
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-pub enum Mention {
- User(UserMention),
- Document(DocumentMention),
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct UserMention {
- pub user_id: String,
- pub email: String,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct DocumentMention {
- pub document_name: String,
-}
-
-#[derive(Deserialize, Debug)]
-#[serde(rename_all = "camelCase")]
-struct ContactMention {
- name: String,
-}
-
-#[derive(Deserialize, Debug)]
-#[serde(rename_all = "camelCase")]
-struct DateMention {
- display_format: String,
-}
-
-#[derive(Deserialize, Debug)]
-#[serde(rename_all = "camelCase")]
-struct LinkMention {
- text: String,
- url: String,
-}
-
-pub const USER_MENTION_REGEX: &str = r#"<m-user-mention>(.*?)<\/m-user-mention>"#;
-pub const DOCUMENT_MENTION_REGEX: &str = r#"<m-document-mention>(.*?)<\/m-document-mention>"#;
-pub const CONTACT_MENTION_REGEX: &str = r#"<m-contact-mention>(.*?)<\/m-contact-mention>"#;
-pub const DATE_MENTION_REGEX: &str = r#"<m-date-mention>(.*?)<\/m-date-mention>"#;
-pub const LINK_REGEX: &str = r#"<m-link>(.*?)<\/m-link>"#;
-
-pub fn parse_document_mentions(message: &str) -> anyhow::Result<Vec<Mention>> {
- let re = regex::Regex::new(DOCUMENT_MENTION_REGEX).unwrap();
- let mut mentions = Vec::new();
-
- for capture in re.captures_iter(message) {
- let document_mention_match = capture
- .get(1)
- .context("no document mention match")?
- .as_str();
- let document_mention: DocumentMention = serde_json::from_str(document_mention_match)
- .context("unable to parse document mention")?;
- mentions.push(Mention::Document(document_mention));
- }
-
- Ok(mentions)
-}
-
-pub fn parse_user_mentions(message: &str) -> anyhow::Result<Vec<Mention>> {
- let re = regex::Regex::new(USER_MENTION_REGEX).unwrap();
- let mut mentions = Vec::new();
-
- for capture in re.captures_iter(message) {
- let user_mention_match = capture.get(1).context("no user mention match")?.as_str();
- let user_mention: UserMention =
- serde_json::from_str(user_mention_match).context("unable to parse user mention")?;
- mentions.push(Mention::User(user_mention));
- }
-
- Ok(mentions)
-}
-
-/// Takes a message and updates it to have the mentions replaced with the correct mention information
-/// NOTE: we will soon use lexical package to parse this stuff for document search.
-pub fn format_message_mentions(message: &str) -> String {
- // We'll use regex to replace each mention in the original order
- let mut result = message.to_string();
-
- // Process contact mentions
- result = process_mentions::<ContactMention, _>(&result, CONTACT_MENTION_REGEX, |contact| {
- format!("@{}", contact.name)
- });
-
- // Process user mentions
- result = process_mentions::<UserMention, _>(&result, USER_MENTION_REGEX, |user| {
- format!("@{}", user.email.split('@').next().unwrap_or(&user.email))
- });
-
- // Process document mentions
- result = process_mentions::<DocumentMention, _>(&result, DOCUMENT_MENTION_REGEX, |document| {
- format!("[{}]", document.document_name.clone())
- });
-
- // Process date mentions
- result = process_mentions::<DateMention, _>(&result, DATE_MENTION_REGEX, |date| {
- date.display_format.clone()
- });
-
- // Process link mentions
- result = process_mentions::<LinkMention, _>(&result, LINK_REGEX, |link| {
- if link.url == link.text {
- link.url.clone()
- } else {
- format!("[{}]({})", link.text, link.url)
- }
- });
-
- result
-}
-
-/// Process mentions of a specific type in a message
-fn process_mentions<T, F>(message: &str, regex_pattern: &str, format_fn: F) -> String
-where
- T: for<'de> Deserialize<'de>,
- F: Fn(&T) -> String,
-{
- let re = Regex::new(regex_pattern).unwrap();
- let mut result = message.to_string();
-
- for cap in re.captures_iter(message) {
- let full_match = cap.get(0).unwrap().as_str();
- let json_content = cap.get(1).unwrap().as_str();
-
- if let Ok(mention) = serde_json::from_str::<T>(json_content) {
- let replacement = format_fn(&mention);
- result = result.replace(full_match, &replacement);
- }
- }
-
- result
-}
-
-pub fn remove_mentions_from_content(content: &str) -> String {
- let mut result = content.to_string();
-
- let document_re = regex::Regex::new(DOCUMENT_MENTION_REGEX).unwrap();
- result = document_re
- .replace_all(&result, |_caps: &regex::Captures| "".to_string())
- .to_string();
-
- let user_re = regex::Regex::new(USER_MENTION_REGEX).unwrap();
- result = user_re
- .replace_all(&result, |_caps: &regex::Captures| "".to_string())
- .to_string();
-
- let contact_re = regex::Regex::new(CONTACT_MENTION_REGEX).unwrap();
- result = contact_re
- .replace_all(&result, |_caps: &regex::Captures| "".to_string())
- .to_string();
-
- let date_re = regex::Regex::new(DATE_MENTION_REGEX).unwrap();
- result = date_re
- .replace_all(&result, |_caps: &regex::Captures| "".to_string())
- .to_string();
-
- // Replace all " " with " "
- result = result.replace(" ", " ");
-
- result
-}
+pub mod parse;
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn test_parse_document_mentions() -> anyhow::Result<()> {
- let message = r#"I'm testing sending a message with a document <m-document-mention>{"documentId":"doc-1","blockName":"md","documentName":"Document 1","blockParams":{}}</m-document-mention> mention <m-document-mention>{"documentId":"doc-2","blockName":"md","documentName":"Document 2","blockParams":{}}</m-document-mention>"#;
- let mentions = parse_document_mentions(message)?;
- assert_eq!(
- mentions,
- vec![
- Mention::Document(DocumentMention {
- document_name: "Document 1".to_string()
- }),
- Mention::Document(DocumentMention {
- document_name: "Document 2".to_string()
- })
- ]
- );
-
- let message = r#"I'm testing a regular message"#;
- let mentions = parse_document_mentions(message)?;
- assert_eq!(mentions, Vec::new());
-
- Ok(())
- }
-
- #[test]
- fn test_parse_user_mentions() -> anyhow::Result<()> {
- let message = r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>"#;
- let mentions = parse_user_mentions(message)?;
- assert_eq!(
- mentions,
- vec![Mention::User(UserMention {
- user_id: "macro|[email protected]".to_string(),
- email: "[email protected]".to_string()
- }),]
- );
-
- let message = r#"I'm testing a regular message"#;
- let mentions = parse_user_mentions(message)?;
- assert_eq!(mentions, Vec::new());
-
- Ok(())
- }
-
- #[test]
- fn test_remove_mentions_from_content() -> anyhow::Result<()> {
- let message = r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> I'm testing sending a message with a document <m-document-mention>{"documentId":"doc-1","blockName":"md","documentName":"Document 1","blockParams":{}}</m-document-mention> mention <m-document-mention>{"documentId":"doc-2","blockName":"md","documentName":"Document 2","blockParams":{}}</m-document-mention>"#;
- let message = remove_mentions_from_content(message);
-
- assert_eq!(
- message,
- r#" I'm testing sending a message with a document mention "#
- );
-
- Ok(())
- }
-
- #[test]
- fn test_sanitize_contact_mention() {
- let input = r#"asdf <m-contact-mention>{"contactId":"[email protected]","name":"Ness Chu","emailOrDomain":"[email protected]","isCompany":false}</m-contact-mention> asdf"#;
- let expected = "asdf @Ness Chu asdf";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_user_mention() {
- let input = r#"asdf <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> asdf"#;
- let expected = "asdf @chase asdf";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_document_mention() {
- let input = r#"asdf <m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","documentName":"Test Doc 34","blockParams":{},"collapsed":false}</m-document-mention> asdf"#;
- let expected = "asdf [Test Doc 34] asdf";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_date_mention() {
- let input = r#"asdf <m-date-mention>{"date":"2025-12-01T05:00:00.000Z","displayFormat":"Mon, Dec 1, 2025"}</m-date-mention>"#;
- let expected = "asdf Mon, Dec 1, 2025";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_mixed_mentions() {
- let input = r#"Hi <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>, let's discuss <m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","documentName":"Test Doc 34","blockParams":{},"collapsed":false}</m-document-mention> with <m-contact-mention>{"contactId":"[email protected]","name":"Ness Chu","emailOrDomain":"[email protected]","isCompany":false}</m-contact-mention> on <m-date-mention>{"date":"2025-12-01T05:00:00.000Z","displayFormat":"Mon, Dec 1, 2025"}</m-date-mention>"#;
- let expected = "Hi @chase, let's discuss [Test Doc 34] with @Ness Chu on Mon, Dec 1, 2025";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_message_no_mentions() {
- let input = "Just a regular message with no mentions";
- let expected = "Just a regular message with no mentions";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_message_invalid_json() {
- let input =
- r#"<m-user-mention>{"userId":"macro|[email protected]",INVALID}</m-user-mention> asdf"#;
-
- // Should still return a result, but without replacing the invalid tag
- let result = format_message_mentions(input);
- assert_eq!(result, input);
- }
-
- #[test]
- fn test_missing_field_contact_mention() {
- // Missing "name" field which is used in the replacement
- let input = r#"<m-contact-mention>{"contactId":"[email protected]","emailOrDomain":"[email protected]","isCompany":false}</m-contact-mention> asdf"#;
-
- // Should keep the original text since the name field is missing
- let result = format_message_mentions(input);
- assert_eq!(result, input);
- }
-
- #[test]
- fn test_missing_field_user_mention() {
- // Missing "email" field which is used to extract username
- let input = r#"<m-user-mention>{"userId":"macro|[email protected]"}</m-user-mention> asdf"#;
-
- // Should keep the original text since the email field is missing
- let result = format_message_mentions(input);
- assert_eq!(result, input);
- }
-
- #[test]
- fn test_missing_field_document_mention() {
- // Missing "documentName" field which is used in the replacement
- let input = r#"<m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","blockParams":{},"collapsed":false}</m-document-mention> asdf"#;
-
- // Should keep the original text since the documentName field is missing
- let result = format_message_mentions(input);
- assert_eq!(result, input);
- }
-
- #[test]
- fn test_missing_field_date_mention() {
- // Missing "displayFormat" field which is used in the replacement
- let input = r#"<m-date-mention>{"date":"2025-12-01T05:00:00.000Z"}</m-date-mention>"#;
-
- // Should keep the original text since the displayFormat field is missing
- let result = format_message_mentions(input);
- assert_eq!(result, input);
- }
-
- #[test]
- fn test_partial_mentions_mixed() {
- // A message with a mix of valid and invalid mentions
- let input = r#"Valid user <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>
- and invalid user <m-user-mention>{"userId":"macro|[email protected]"}</m-user-mention>
- and valid doc <m-document-mention>{"documentId":"123","blockName":"md","documentName":"Valid Doc","blockParams":{},"collapsed":false}</m-document-mention>
- and invalid doc <m-document-mention>{"documentId":"456","blockName":"md","blockParams":{},"collapsed":false}</m-document-mention>"#;
-
- // The valid mentions should be replaced, but invalid ones should remain unchanged
- let expected = r#"Valid user @chase
- and invalid user <m-user-mention>{"userId":"macro|[email protected]"}</m-user-mention>
- and valid doc [Valid Doc]
- and invalid doc <m-document-mention>{"documentId":"456","blockName":"md","blockParams":{},"collapsed":false}</m-document-mention>"#;
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_link_mention_same_text_and_url() {
- let input = r#"Check out this link <m-link>{"text":"https://www.example.com","url":"https://www.example.com"}</m-link> for more info"#;
- let expected = "Check out this link https://www.example.com for more info";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_link_mention_different_text_and_url() {
- let input = r#"Visit <m-link>{"text":"Example Website","url":"https://www.example.com"}</m-link> today"#;
- let expected = "Visit [Example Website](https://www.example.com) today";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_multiple_link_mentions() {
- let input = r#"Check out <m-link>{"text":"Google","url":"https://google.com"}</m-link> and also <m-link>{"text":"https://github.com","url":"https://github.com"}</m-link>"#;
- let expected = "Check out [Google](https://google.com) and also https://github.com";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_link_mention_empty_text() {
- let input = r#"Link: <m-link>{"text":"","url":"https://www.example.com"}</m-link>"#;
- let expected = "Link: [](https://www.example.com)";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_link_mention_with_special_characters() {
- let input = r#"Complex link <m-link>{"text":"Search: \"hello world\"","url":"https://example.com?q=hello%20world&sort=date"}</m-link>"#;
- let expected = r#"Complex link [Search: "hello world"](https://example.com?q=hello%20world&sort=date)"#;
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_link_mention_missing_text_field() {
- let input = r#"<m-link>{"url":"https://www.example.com"}</m-link> missing text field"#;
-
- // Should keep the original text since the text field is missing
- let result = format_message_mentions(input);
- assert_eq!(result, input);
- }
-
- #[test]
- fn test_sanitize_link_mention_missing_url_field() {
- let input = r#"<m-link>{"text":"Example Link"}</m-link> missing url field"#;
-
- // Should keep the original text since the url field is missing
- let result = format_message_mentions(input);
- assert_eq!(result, input);
- }
-
- #[test]
- fn test_sanitize_link_mention_invalid_json() {
- let input = r#"<m-link>{"text":"Example","url":INVALID}</m-link> invalid json"#;
-
- // Should keep the original text since the JSON is invalid
- let result = format_message_mentions(input);
- assert_eq!(result, input);
- }
-
- #[test]
- fn test_sanitize_mixed_mentions_with_links() {
- let input = r#"Hi <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>, check out <m-link>{"text":"Our Docs","url":"https://docs.example.com"}</m-link> and <m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","documentName":"Test Doc 34","blockParams":{},"collapsed":false}</m-document-mention> on <m-date-mention>{"date":"2025-12-01T05:00:00.000Z","displayFormat":"Mon, Dec 1, 2025"}</m-date-mention> or visit <m-link>{"text":"https://example.com","url":"https://example.com"}</m-link>"#;
- let expected = "Hi @chase, check out [Our Docs](https://docs.example.com) and [Test Doc 34] on Mon, Dec 1, 2025 or visit https://example.com";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_remove_mentions_includes_links() {
- let message = r#"Check out <m-link>{"text":"Example","url":"https://example.com"}</m-link> and <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> this doc <m-document-mention>{"documentId":"doc-1","blockName":"md","documentName":"Document 1","blockParams":{}}</m-document-mention>"#;
-
- // Note: Current remove_mentions_from_content doesn't handle links, so they remain
- let result = remove_mentions_from_content(message);
- let expected = r#"Check out <m-link>{"text":"Example","url":"https://example.com"}</m-link> and this doc "#;
-
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_link_mention_markdown_characters_in_text() {
- let input = r#"Link with special chars <m-link>{"text":"[Already] (Markdown) *Format*","url":"https://example.com"}</m-link>"#;
- let expected =
- "Link with special chars [[Already] (Markdown) *Format*](https://example.com)";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-
- #[test]
- fn test_sanitize_link_mention_unicode_characters() {
- let input = r#"Unicode link <m-link>{"text":"测试链接 🔗","url":"https://example.com/测试"}</m-link>"#;
- let expected = "Unicode link [测试链接 🔗](https://example.com/测试)";
-
- let result = format_message_mentions(input);
- assert_eq!(result, expected);
- }
-}
+mod tests;
diff --git a/rust/cloud-storage/mention_utils/src/parse.rs b/rust/cloud-storage/mention_utils/src/parse.rs
new file mode 100644
index 0000000000..2eb0a07e77
--- /dev/null
+++ b/rust/cloud-storage/mention_utils/src/parse.rs
@@ -0,0 +1,270 @@
+use macro_user_id::user_id::BorrowedUserIdStr;
+use nom::{
+ Finish, IResult, Parser,
+ branch::alt,
+ bytes::complete::{tag, tag_no_case, take_till1},
+ character::complete::anychar,
+ combinator::{eof, peek, recognize},
+ multi::{many_till, many0},
+ sequence::delimited,
+};
+use serde::Deserialize;
+use std::{
+ borrow::Cow,
+ fmt::{Formatter, Write},
+ marker::PhantomData,
+};
+use thiserror::Error;
+
+fn xml_tag(
+ start_delimiter: &'static str,
+ tag_name: &'static str,
+) -> impl Fn(&str) -> IResult<&str, &str> {
+ move |s: &str| delimited(tag(start_delimiter), tag_no_case(tag_name), tag(">")).parse(s)
+}
+
+fn xml_tag_open(tag_name: &'static str) -> impl Fn(&str) -> IResult<&str, &str> {
+ move |s: &str| xml_tag("<", tag_name).parse(s)
+}
+
+fn xml_tag_close(tag_name: &'static str) -> impl Fn(&str) -> IResult<&str, &str> {
+ move |s: &str| xml_tag("</", tag_name).parse(s)
+}
+
+fn tag_content(tag_name: &'static str) -> impl Fn(&str) -> IResult<&str, &str> {
+ move |s: &str| {
+ delimited(
+ xml_tag_open(tag_name),
+ recognize(many_till(anychar, peek(xml_tag_close(tag_name)))),
+ xml_tag_close(tag_name),
+ )
+ .parse(s)
+ }
+}
+
+pub trait XmlTaggedParsed<'de>: Deserialize<'de> {
+ const TAG_NAME: &'static str;
+
+ fn parse(s: &'de str) -> IResult<&'de str, Self> {
+ tag_content(Self::TAG_NAME)
+ .map_res(serde_json::from_str)
+ .parse(s)
+ }
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[non_exhaustive]
+pub struct ParsedUserMention<'a> {
+ #[serde(borrow)]
+ pub user_id: BorrowedUserIdStr<'a>,
+ #[serde(borrow)]
+ pub email: Cow<'a, str>,
+}
+
+impl<'de> XmlTaggedParsed<'de> for ParsedUserMention<'de> {
+ const TAG_NAME: &'static str = "m-user-mention";
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[non_exhaustive]
+pub struct ParsedContactMention<'a> {
+ #[serde(borrow)]
+ pub name: Cow<'a, str>,
+}
+
+impl<'de> XmlTaggedParsed<'de> for ParsedContactMention<'de> {
+ const TAG_NAME: &'static str = "m-contact-mention";
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[non_exhaustive]
+pub struct ParsedDateMention<'a> {
+ #[serde(borrow)]
+ pub display_format: Cow<'a, str>,
+}
+
+impl<'de> XmlTaggedParsed<'de> for ParsedDateMention<'de> {
+ const TAG_NAME: &'static str = "m-date-mention";
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[non_exhaustive]
+pub struct ParsedDocumentMention<'a> {
+ #[serde(borrow)]
+ pub document_name: Cow<'a, str>,
+}
+
+impl<'de> XmlTaggedParsed<'de> for ParsedDocumentMention<'de> {
+ const TAG_NAME: &'static str = "m-document-mention";
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[non_exhaustive]
+pub struct ParsedLink<'a> {
+ #[serde(borrow)]
+ pub text: Cow<'a, str>,
+ #[serde(borrow)]
+ pub url: Cow<'a, str>,
+}
+
+impl<'de> XmlTaggedParsed<'de> for ParsedLink<'de> {
+ const TAG_NAME: &'static str = "m-link";
+}
+
+#[derive(Debug)]
+pub enum XmlTag<'de> {
+ Link(ParsedLink<'de>),
+ Document(ParsedDocumentMention<'de>),
+ User(ParsedUserMention<'de>),
+ Contact(ParsedContactMention<'de>),
+ Date(ParsedDateMention<'de>),
+}
+
+fn parse_xml_tag(s: &str) -> IResult<&str, XmlTag<'_>> {
+ alt((
+ ParsedLink::parse.map(XmlTag::Link),
+ ParsedDocumentMention::parse.map(XmlTag::Document),
+ ParsedUserMention::parse.map(XmlTag::User),
+ ParsedContactMention::parse.map(XmlTag::Contact),
+ ParsedDateMention::parse.map(XmlTag::Date),
+ ))
+ .parse(s)
+}
+
+#[derive(Debug)]
+pub enum TextSegment<'de> {
+ Xml(XmlTag<'de>),
+ Plain(&'de str),
+}
+
+#[non_exhaustive]
+pub struct ParsedXmlText<'de>(pub Vec<TextSegment<'de>>);
+
+#[derive(Debug, Error)]
+#[error(transparent)]
+pub struct ParseErr(#[from] nom::error::Error<String>);
+
+impl<'de> ParsedXmlText<'de> {
+ pub fn parse(s: &'de str) -> Result<Self, ParseErr> {
+ let (_, (out, _)) = many0(alt((
+ parse_xml_tag.map(TextSegment::Xml),
+ take_till1(|c| c == '<').map(TextSegment::Plain),
+ )))
+ .and(eof)
+ .parse(s)
+ .finish()
+ .map_err(|e| e.cloned())?;
+ Ok(ParsedXmlText(out))
+ }
+}
+
+pub struct ReformattedXmlText<T>(pub String, PhantomData<T>);
+
+pub trait XmlFormatter: Sized {
+ fn format_plain_text(s: &str, f: &mut Formatter<'_>) -> std::fmt::Result;
+ fn format_link(link: &ParsedLink<'_>, f: &mut Formatter<'_>) -> std::fmt::Result;
+ fn format_doc(doc: &ParsedDocumentMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result;
+ fn format_user(user: &ParsedUserMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result;
+ fn format_contact(
+ contact: &ParsedContactMention<'_>,
+ f: &mut Formatter<'_>,
+ ) -> std::fmt::Result;
+ fn format_date(date: &ParsedDateMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result;
+
+ fn format_xml_text(text: ParsedXmlText<'_>) -> ReformattedXmlText<Self> {
+ use std::fmt::Display;
+
+ struct Adapter<F>(F);
+ impl<F: Fn(&mut Formatter<'_>) -> std::fmt::Result> Display for Adapter<F> {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ (self.0)(f)
+ }
+ }
+
+ let s = text.0.into_iter().fold(String::new(), |mut acc, cur| {
+ let _ = match cur {
+ TextSegment::Xml(XmlTag::Link(l)) => {
+ write!(
+ acc,
+ "{}",
+ Adapter(|f: &mut Formatter<'_>| Self::format_link(&l, f))
+ )
+ }
+ TextSegment::Xml(XmlTag::Document(d)) => {
+ write!(
+ acc,
+ "{}",
+ Adapter(|f: &mut Formatter<'_>| Self::format_doc(&d, f))
+ )
+ }
+ TextSegment::Xml(XmlTag::User(u)) => {
+ write!(
+ acc,
+ "{}",
+ Adapter(|f: &mut Formatter<'_>| Self::format_user(&u, f))
+ )
+ }
+ TextSegment::Xml(XmlTag::Contact(c)) => {
+ write!(
+ acc,
+ "{}",
+ Adapter(|f: &mut Formatter<'_>| Self::format_contact(&c, f))
+ )
+ }
+ TextSegment::Xml(XmlTag::Date(d)) => {
+ write!(
+ acc,
+ "{}",
+ Adapter(|f: &mut Formatter<'_>| Self::format_date(&d, f))
+ )
+ }
+ TextSegment::Plain(s) => {
+ write!(
+ acc,
+ "{}",
+ Adapter(|f: &mut Formatter<'_>| Self::format_plain_text(s, f))
+ )
+ }
+ };
+ acc
+ });
+ ReformattedXmlText(s, PhantomData)
+ }
+}
+
+/// xml formatter which completely removes the inner text of all xml tags
+pub struct NullXmlFormatter;
+
+impl XmlFormatter for NullXmlFormatter {
+ fn format_plain_text(s: &str, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{s}")
+ }
+
+ fn format_link(_link: &ParsedLink<'_>, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(f, "")
+ }
+
+ fn format_doc(_doc: &ParsedDocumentMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(f, "")
+ }
+
+ fn format_user(_user: &ParsedUserMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(f, "")
+ }
+
+ fn format_contact(
+ _contact: &ParsedContactMention<'_>,
+ f: &mut Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(f, "")
+ }
+
+ fn format_date(_date: &ParsedDateMention<'_>, f: &mut Formatter<'_>) -> std::fmt::Result {
+ write!(f, "")
+ }
+}
diff --git a/rust/cloud-storage/mention_utils/src/tests.rs b/rust/cloud-storage/mention_utils/src/tests.rs
new file mode 100644
index 0000000000..2138a0e4d1
--- /dev/null
+++ b/rust/cloud-storage/mention_utils/src/tests.rs
@@ -0,0 +1,616 @@
+use cool_asserts::assert_matches;
+
+use crate::parse::{
+ ParsedContactMention, ParsedDateMention, ParsedDocumentMention, ParsedLink, ParsedUserMention,
+ ParsedXmlText, TextSegment, XmlTag,
+};
+
+// =============================================================================
+// Basic parsing tests
+// =============================================================================
+
+#[test]
+fn plain_message() {
+ let input = "I'm testing a regular message";
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [TextSegment::Plain("I'm testing a regular message")]);
+}
+
+#[test]
+fn empty_string() {
+ let out = ParsedXmlText::parse("").unwrap();
+ assert!(out.0.is_empty());
+}
+
+// =============================================================================
+// Document mention tests
+// =============================================================================
+
+#[test]
+fn parse_single_document_mention() {
+ let input = r#"<m-document-mention>{"documentName":"My Doc"}</m-document-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name }))
+ ] => {
+ assert_eq!(document_name.as_ref(), "My Doc");
+ });
+}
+
+#[test]
+fn parse_document_mentions_with_text() {
+ let input = r#"I'm testing sending a message with a document <m-document-mention>{"documentId":"doc-1","blockName":"md","documentName":"Document 1","blockParams":{}}</m-document-mention> mention <m-document-mention>{"documentId":"doc-2","blockName":"md","documentName":"Document 2","blockParams":{}}</m-document-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+
+ assert_matches!(out.0, [
+ TextSegment::Plain("I'm testing sending a message with a document "),
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name: name1 })),
+ TextSegment::Plain(" mention "),
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name: name2 })),
+ ] => {
+ assert_eq!(name1.as_ref(), "Document 1");
+ assert_eq!(name2.as_ref(), "Document 2");
+ });
+}
+
+#[test]
+fn parse_document_mention_missing_name() {
+ // Missing "documentName" field - should fail to parse as document mention
+ let input = r#"<m-document-mention>{"documentId":"123","blockName":"md","blockParams":{}}</m-document-mention>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_document_mention_invalid_json() {
+ let input = r#"<m-document-mention>???</m-document-mention>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+// =============================================================================
+// User mention tests
+// =============================================================================
+
+#[test]
+fn parse_single_user_mention() {
+ let input = r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id, email }))
+ ] => {
+ assert_eq!(user_id.0.as_ref(), "macro|[email protected]");
+ assert_eq!(email.as_ref(), "[email protected]");
+ });
+}
+
+#[test]
+fn parse_multiple_user_mentions() {
+ let input = r#"Hello <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> and <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Hello "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id: uid1, email: email1 })),
+ TextSegment::Plain(" and "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { user_id: uid2, email: email2 })),
+ ] => {
+ assert_eq!(uid1.0.as_ref(), "macro|[email protected]");
+ assert_eq!(email1.as_ref(), "[email protected]");
+ assert_eq!(uid2.0.as_ref(), "macro|[email protected]");
+ assert_eq!(email2.as_ref(), "[email protected]");
+ });
+}
+
+#[test]
+fn parse_user_mention_missing_email() {
+ // Missing "email" field - should fail to parse
+ let input = r#"<m-user-mention>{"userId":"macro|[email protected]"}</m-user-mention>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_user_mention_invalid_json() {
+ let input = r#"<m-user-mention>invalid</m-user-mention>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+// =============================================================================
+// Contact mention tests
+// =============================================================================
+
+#[test]
+fn parse_contact_mention() {
+ let input = r#"asdf <m-contact-mention>{"contactId":"[email protected]","name":"Ness Chu","emailOrDomain":"[email protected]","isCompany":false}</m-contact-mention> asdf"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("asdf "),
+ TextSegment::Xml(XmlTag::Contact(ParsedContactMention { name })),
+ TextSegment::Plain(" asdf"),
+ ] => {
+ assert_eq!(name.as_ref(), "Ness Chu");
+ });
+}
+
+#[test]
+fn parse_contact_mention_missing_name() {
+ // Missing "name" field - should fail to parse
+ let input = r#"<m-contact-mention>{"contactId":"[email protected]","emailOrDomain":"[email protected]"}</m-contact-mention>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_contact_mention_invalid_json() {
+ let input = r#"<m-contact-mention>not-json</m-contact-mention>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+// =============================================================================
+// Date mention tests
+// =============================================================================
+
+#[test]
+fn parse_date_mention() {
+ let input = r#"asdf <m-date-mention>{"date":"2025-12-01T05:00:00.000Z","displayFormat":"Mon, Dec 1, 2025"}</m-date-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("asdf "),
+ TextSegment::Xml(XmlTag::Date(ParsedDateMention { display_format })),
+ ] => {
+ assert_eq!(display_format.as_ref(), "Mon, Dec 1, 2025");
+ });
+}
+
+#[test]
+fn parse_date_mention_missing_display_format() {
+ // Missing "displayFormat" field - should fail to parse
+ let input = r#"<m-date-mention>{"date":"2025-12-01T05:00:00.000Z"}</m-date-mention>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_date_mention_invalid_json() {
+ let input = r#"<m-date-mention>{broken</m-date-mention>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+// =============================================================================
+// Link tests
+// =============================================================================
+
+#[test]
+fn parse_link_different_text_and_url() {
+ let input = r#"Visit <m-link>{"text":"Example Website","url":"https://www.example.com"}</m-link> today"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Visit "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ TextSegment::Plain(" today"),
+ ] => {
+ assert_eq!(text.as_ref(), "Example Website");
+ assert_eq!(url.as_ref(), "https://www.example.com");
+ });
+}
+
+#[test]
+fn parse_link_same_text_and_url() {
+ let input = r#"<m-link>{"url":"https://example.com","text":"https://example.com"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ ] => {
+ assert_eq!(text.as_ref(), "https://example.com");
+ assert_eq!(url.as_ref(), "https://example.com");
+ });
+}
+
+#[test]
+fn parse_multiple_links() {
+ let input = r#"Check out <m-link>{"text":"Google","url":"https://google.com"}</m-link> and also <m-link>{"text":"https://github.com","url":"https://github.com"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Check out "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text: t1, url: u1 })),
+ TextSegment::Plain(" and also "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text: t2, url: u2 })),
+ ] => {
+ assert_eq!(t1.as_ref(), "Google");
+ assert_eq!(u1.as_ref(), "https://google.com");
+ assert_eq!(t2.as_ref(), "https://github.com");
+ assert_eq!(u2.as_ref(), "https://github.com");
+ });
+}
+
+#[test]
+fn parse_link_empty_text() {
+ let input = r#"<m-link>{"text":"","url":"https://www.example.com"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ ] => {
+ assert_eq!(text.as_ref(), "");
+ assert_eq!(url.as_ref(), "https://www.example.com");
+ });
+}
+
+#[test]
+fn parse_link_with_special_characters() {
+ let input = r#"<m-link>{"text":"Search: \"hello world\"","url":"https://example.com?q=hello%20world&sort=date"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ ] => {
+ assert_eq!(text.as_ref(), "Search: \"hello world\"");
+ assert_eq!(url.as_ref(), "https://example.com?q=hello%20world&sort=date");
+ });
+}
+
+#[test]
+fn parse_link_missing_text() {
+ // Missing "text" field - should fail to parse
+ let input = r#"<m-link>{"url":"https://www.example.com"}</m-link>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_link_missing_url() {
+ // Missing "url" field - should fail to parse
+ let input = r#"<m-link>{"text":"Example Link"}</m-link>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_link_invalid_json() {
+ let input = r#"<m-link>{"text":"Example","url":INVALID}</m-link>"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_link_with_title_field() {
+ // Title field should be ignored, only text and url matter
+ let input =
+ r#"<m-link>{"url":"https://example.com","text":"Example","title":"A title"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ ] => {
+ assert_eq!(text.as_ref(), "Example");
+ assert_eq!(url.as_ref(), "https://example.com");
+ });
+}
+
+#[test]
+fn parse_link_unicode_characters() {
+ let input = r#"<m-link>{"text":"测试链接 🔗","url":"https://example.com/测试"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ ] => {
+ assert_eq!(text.as_ref(), "测试链接 🔗");
+ assert_eq!(url.as_ref(), "https://example.com/测试");
+ });
+}
+
+// =============================================================================
+// Mixed mention tests
+// =============================================================================
+
+#[test]
+fn parse_mixed_mentions() {
+ let input = r#"Hi <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>, let's discuss <m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","documentName":"Test Doc 34","blockParams":{},"collapsed":false}</m-document-mention> with <m-contact-mention>{"contactId":"[email protected]","name":"Ness Chu","emailOrDomain":"[email protected]","isCompany":false}</m-contact-mention> on <m-date-mention>{"date":"2025-12-01T05:00:00.000Z","displayFormat":"Mon, Dec 1, 2025"}</m-date-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Hi "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Plain(", let's discuss "),
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name })),
+ TextSegment::Plain(" with "),
+ TextSegment::Xml(XmlTag::Contact(ParsedContactMention { name })),
+ TextSegment::Plain(" on "),
+ TextSegment::Xml(XmlTag::Date(ParsedDateMention { display_format })),
+ ] => {
+ assert_eq!(email.as_ref(), "[email protected]");
+ assert_eq!(document_name.as_ref(), "Test Doc 34");
+ assert_eq!(name.as_ref(), "Ness Chu");
+ assert_eq!(display_format.as_ref(), "Mon, Dec 1, 2025");
+ });
+}
+
+#[test]
+fn parse_mixed_mentions_with_links() {
+ let input = r#"Hi <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>, check out <m-link>{"text":"Our Docs","url":"https://docs.example.com"}</m-link> and <m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","documentName":"Test Doc 34","blockParams":{},"collapsed":false}</m-document-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Hi "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Plain(", check out "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ TextSegment::Plain(" and "),
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name })),
+ ] => {
+ assert_eq!(email.as_ref(), "[email protected]");
+ assert_eq!(text.as_ref(), "Our Docs");
+ assert_eq!(url.as_ref(), "https://docs.example.com");
+ assert_eq!(document_name.as_ref(), "Test Doc 34");
+ });
+}
+
+#[test]
+fn parse_content_with_multiple_document_and_user_mentions() {
+ let input = r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> I'm testing sending a message with a document <m-document-mention>{"documentId":"doc-1","blockName":"md","documentName":"Document 1","blockParams":{}}</m-document-mention> mention <m-document-mention>{"documentId":"doc-2","blockName":"md","documentName":"Document 2","blockParams":{}}</m-document-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Plain(" I'm testing sending a message with a document "),
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name: name1 })),
+ TextSegment::Plain(" mention "),
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name: name2 })),
+ ] => {
+ assert_eq!(email.as_ref(), "[email protected]");
+ assert_eq!(name1.as_ref(), "Document 1");
+ assert_eq!(name2.as_ref(), "Document 2");
+ });
+}
+
+// =============================================================================
+// Edge cases
+// =============================================================================
+
+#[test]
+fn parse_text_with_angle_brackets_but_no_mentions() {
+ // Text with < that isn't a valid tag should fail since we can't parse it
+ let input = "5 < 10 and 10 > 5";
+ let result = ParsedXmlText::parse(input);
+ // This will fail because < starts something that isn't a valid tag
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_consecutive_mentions_no_space() {
+ let input = r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention><m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email: e1, .. })),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email: e2, .. })),
+ ] => {
+ assert_eq!(e1.as_ref(), "[email protected]");
+ assert_eq!(e2.as_ref(), "[email protected]");
+ });
+}
+
+#[test]
+fn parse_mention_at_start() {
+ let input =
+ r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> hello"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Plain(" hello"),
+ ] => {
+ assert_eq!(email.as_ref(), "[email protected]");
+ });
+}
+
+#[test]
+fn parse_mention_at_end() {
+ let input =
+ r#"hello <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("hello "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ ] => {
+ assert_eq!(email.as_ref(), "[email protected]");
+ });
+}
+
+// =============================================================================
+// Additional tests to match original test coverage
+// =============================================================================
+
+#[test]
+fn parse_user_mention_with_surrounding_text() {
+ let input = r#"asdf <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> asdf"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("asdf "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Plain(" asdf"),
+ ] => {
+ assert_eq!(email.as_ref(), "[email protected]");
+ });
+}
+
+#[test]
+fn parse_document_mention_with_surrounding_text() {
+ let input = r#"asdf <m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","documentName":"Test Doc 34","blockParams":{},"collapsed":false}</m-document-mention> asdf"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("asdf "),
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name })),
+ TextSegment::Plain(" asdf"),
+ ] => {
+ assert_eq!(document_name.as_ref(), "Test Doc 34");
+ });
+}
+
+#[test]
+fn parse_plain_message_no_mentions() {
+ let input = "Just a regular message with no mentions";
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(
+ out.0,
+ [TextSegment::Plain(
+ "Just a regular message with no mentions"
+ )]
+ );
+}
+
+#[test]
+fn parse_user_mention_invalid_json_with_suffix() {
+ let input =
+ r#"<m-user-mention>{"userId":"macro|[email protected]",INVALID}</m-user-mention> asdf"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_link_same_text_url_with_surrounding_text() {
+ let input = r#"Check out this link <m-link>{"text":"https://www.example.com","url":"https://www.example.com"}</m-link> for more info"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Check out this link "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ TextSegment::Plain(" for more info"),
+ ] => {
+ assert_eq!(text.as_ref(), "https://www.example.com");
+ assert_eq!(url.as_ref(), "https://www.example.com");
+ });
+}
+
+#[test]
+fn parse_link_empty_text_with_prefix() {
+ let input = r#"Link: <m-link>{"text":"","url":"https://www.example.com"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Link: "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ ] => {
+ assert_eq!(text.as_ref(), "");
+ assert_eq!(url.as_ref(), "https://www.example.com");
+ });
+}
+
+#[test]
+fn parse_link_special_chars_with_prefix() {
+ let input = r#"Complex link <m-link>{"text":"Search: \"hello world\"","url":"https://example.com?q=hello%20world&sort=date"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Complex link "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ ] => {
+ assert_eq!(text.as_ref(), "Search: \"hello world\"");
+ assert_eq!(url.as_ref(), "https://example.com?q=hello%20world&sort=date");
+ });
+}
+
+#[test]
+fn parse_link_missing_text_with_suffix() {
+ let input = r#"<m-link>{"url":"https://www.example.com"}</m-link> missing text field"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_link_missing_url_with_suffix() {
+ let input = r#"<m-link>{"text":"Example Link"}</m-link> missing url field"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_link_invalid_json_with_suffix() {
+ let input = r#"<m-link>{"text":"Example","url":INVALID}</m-link> invalid json"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_mixed_mentions_with_multiple_links() {
+ let input = r#"Hi <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>, check out <m-link>{"text":"Our Docs","url":"https://docs.example.com"}</m-link> and <m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","documentName":"Test Doc 34","blockParams":{},"collapsed":false}</m-document-mention> on <m-date-mention>{"date":"2025-12-01T05:00:00.000Z","displayFormat":"Mon, Dec 1, 2025"}</m-date-mention> or visit <m-link>{"text":"https://example.com","url":"https://example.com"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Hi "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Plain(", check out "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text: t1, .. })),
+ TextSegment::Plain(" and "),
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name })),
+ TextSegment::Plain(" on "),
+ TextSegment::Xml(XmlTag::Date(ParsedDateMention { display_format })),
+ TextSegment::Plain(" or visit "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text: t2, url: u2 })),
+ ] => {
+ assert_eq!(email.as_ref(), "[email protected]");
+ assert_eq!(t1.as_ref(), "Our Docs");
+ assert_eq!(document_name.as_ref(), "Test Doc 34");
+ assert_eq!(display_format.as_ref(), "Mon, Dec 1, 2025");
+ assert_eq!(t2.as_ref(), "https://example.com");
+ assert_eq!(u2.as_ref(), "https://example.com");
+ });
+}
+
+#[test]
+fn parse_link_user_document_mixed() {
+ let input = r#"Check out <m-link>{"text":"Example","url":"https://example.com"}</m-link> and <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> this doc <m-document-mention>{"documentId":"doc-1","blockName":"md","documentName":"Document 1","blockParams":{}}</m-document-mention>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Check out "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ TextSegment::Plain(" and "),
+ TextSegment::Xml(XmlTag::User(ParsedUserMention { email, .. })),
+ TextSegment::Plain(" this doc "),
+ TextSegment::Xml(XmlTag::Document(ParsedDocumentMention { document_name })),
+ ] => {
+ assert_eq!(text.as_ref(), "Example");
+ assert_eq!(url.as_ref(), "https://example.com");
+ assert_eq!(email.as_ref(), "[email protected]");
+ assert_eq!(document_name.as_ref(), "Document 1");
+ });
+}
+
+#[test]
+fn parse_link_markdown_characters_in_text() {
+ let input = r#"Link with special chars <m-link>{"text":"[Already] (Markdown) *Format*","url":"https://example.com"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Link with special chars "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ ] => {
+ assert_eq!(text.as_ref(), "[Already] (Markdown) *Format*");
+ assert_eq!(url.as_ref(), "https://example.com");
+ });
+}
+
+#[test]
+fn parse_link_unicode_with_prefix() {
+ let input =
+ r#"Unicode link <m-link>{"text":"测试链接 🔗","url":"https://example.com/测试"}</m-link>"#;
+ let out = ParsedXmlText::parse(input).unwrap();
+ assert_matches!(out.0, [
+ TextSegment::Plain("Unicode link "),
+ TextSegment::Xml(XmlTag::Link(ParsedLink { text, url })),
+ ] => {
+ assert_eq!(text.as_ref(), "测试链接 🔗");
+ assert_eq!(url.as_ref(), "https://example.com/测试");
+ });
+}
+
+#[test]
+fn parse_contact_mention_missing_name_with_suffix() {
+ let input = r#"<m-contact-mention>{"contactId":"[email protected]","emailOrDomain":"[email protected]","isCompany":false}</m-contact-mention> asdf"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_user_mention_missing_email_with_suffix() {
+ let input = r#"<m-user-mention>{"userId":"macro|[email protected]"}</m-user-mention> asdf"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_document_mention_missing_name_with_suffix() {
+ let input = r#"<m-document-mention>{"documentId":"6e01eaf5-f497-4b2e-96d0-ea3d527ef47d","blockName":"md","blockParams":{},"collapsed":false}</m-document-mention> asdf"#;
+ let result = ParsedXmlText::parse(input);
+ assert!(result.is_err());
+}
diff --git a/rust/cloud-storage/model-entity/src/lib.rs b/rust/cloud-storage/model-entity/src/lib.rs
index 9b43f24984..1e2a73f57f 100644
--- a/rust/cloud-storage/model-entity/src/lib.rs
+++ b/rust/cloud-storage/model-entity/src/lib.rs
@@ -81,8 +81,12 @@ impl TryFrom<String> for EntityType {
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, Hash, PartialEq, Eq)]
pub struct Entity<'a> {
/// The type of entity we are describing
+ // TODO: we can remove this alias after a few weeks
+ #[serde(alias = "eventItemType")]
pub entity_type: EntityType,
/// The id of that entity
+ // TODO: we can remove this alias after a few weeks
+ #[serde(alias = "eventItemId")]
pub entity_id: Cow<'a, str>,
}
diff --git a/rust/cloud-storage/model_notifications/Cargo.toml b/rust/cloud-storage/model_notifications/Cargo.toml
index 38062a88cc..85ad54010b 100644
--- a/rust/cloud-storage/model_notifications/Cargo.toml
+++ b/rust/cloud-storage/model_notifications/Cargo.toml
@@ -7,6 +7,7 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
model-entity = { path = "../model-entity" }
models_comms = { path = "../models_comms" }
models_pagination = { path = "../models_pagination" }
diff --git a/rust/cloud-storage/model_notifications/src/lib.rs b/rust/cloud-storage/model_notifications/src/lib.rs
index b08712995e..b96902e26f 100644
--- a/rust/cloud-storage/model_notifications/src/lib.rs
+++ b/rust/cloud-storage/model_notifications/src/lib.rs
@@ -1,18 +1,17 @@
use anyhow::Context;
use chrono::{DateTime, serde::ts_seconds_option};
-use model_entity::EntityType;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
use models_pagination::{CreatedAt, Identify, SortOn};
use serde::{Deserialize, Serialize};
use strum::{Display, EnumDiscriminants, EnumString};
use utoipa::ToSchema;
mod device;
mod metadata;
-mod push;
mod raw;
mod unsubscribe;
pub use device::*;
pub use metadata::*;
-pub use push::*;
pub use raw::*;
pub use unsubscribe::*;
use uuid::Uuid;
@@ -43,7 +42,7 @@ pub enum NotificationEvent {
/// Someone replied to a thread in a channel that the user is part of
ChannelMessageReply(ChannelReplyMetadata),
/// If a document is included via mention or attachment on a message
- ChannelMessageDocument(DocumentMentionMetadata),
+ ChannelMessageDocument(ChannelMessageDocumentMetadata),
/// A new email has been sent to the user
NewEmail(NewEmailMetadata),
/// A user was invited to a team
@@ -52,20 +51,15 @@ pub enum NotificationEvent {
RejectTeamInvite,
}
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[serde(transparent)]
+pub struct ChannelMessageDocumentMetadata(pub DocumentMentionMetadata);
+
impl NotificationEvent {
pub fn event_type(&self) -> NotificationEventType {
NotificationEventType::from(self)
}
- pub fn get_message_content_mut(&mut self) -> Option<&mut String> {
- match self {
- NotificationEvent::ChannelMessageSend(meta) => Some(&mut meta.message_content),
- NotificationEvent::ChannelMessageReply(meta) => Some(&mut meta.message_content),
- NotificationEvent::ChannelMention(meta) => Some(&mut meta.message_content),
- _ => None,
- }
- }
-
pub fn metadata_json(&self) -> Option<serde_json::Value> {
match self {
NotificationEvent::ItemSharedUser(meta) => serde_json::to_value(meta).ok(),
@@ -145,78 +139,51 @@ pub struct NotificationTemporalData {
pub deleted_at: TimestampOption,
}
-/// The entity that triggered the notification
-/// This is a combination of an [EntityType] and an id (Uuid or string)
-#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct NotificationEntity {
- pub event_item_id: String,
- pub event_item_type: EntityType,
-}
-
-macro_rules! impl_new_entity_with_type {
- ($method:ident, $variant:ident) => {
- pub fn $method(event_item_id: String) -> Self {
- Self {
- event_item_id,
- event_item_type: EntityType::$variant,
- }
- }
- };
-}
-
-impl NotificationEntity {
- pub fn new(event_item_id: String, event_item_type: EntityType) -> Self {
- Self {
- event_item_id,
- event_item_type,
- }
- }
-
- impl_new_entity_with_type!(new_channel, Channel);
- impl_new_entity_with_type!(new_chat, Chat);
- impl_new_entity_with_type!(new_document, Document);
- impl_new_entity_with_type!(new_email, Email);
- impl_new_entity_with_type!(new_project, Project);
- impl_new_entity_with_type!(new_team, Team);
-}
-
-#[derive(Serialize, Deserialize, Debug, ToSchema)]
+#[derive(Serialize, Deserialize, Debug, ToSchema, Clone)]
#[serde(rename_all = "camelCase")]
pub struct UserNotification {
/// The id of the notification. Self-generated uuidv7
pub id: Uuid,
#[serde(flatten)]
- pub notification_entity: NotificationEntity,
+ pub notification_entity: Entity<'static>,
/// If the notification has been sent
pub sent: bool,
/// If the notification is "done"
pub done: bool,
/// user id of the macro user who generated the notification
pub sender_id: Option<String>,
- /// if notification is important or not
- pub is_important_v0: bool,
#[serde(flatten)]
pub temporal: NotificationTemporalData,
#[serde(flatten)]
pub notification_event: NotificationEvent,
}
+// CAUTION: for hash map purposes we need Hash+Eq impl on UserNotification
+// User notifications are considered equal based only on their id
+
+impl PartialEq for UserNotification {
+ fn eq(&self, other: &Self) -> bool {
+ self.id == other.id
+ }
+}
+
+impl Eq for UserNotification {}
+
+impl std::hash::Hash for UserNotification {
+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
+ self.id.hash(state);
+ }
+}
+
impl UserNotification {
/// Create a new UserNotification from a Notification
- pub fn from_new_notification(
- notification: Notification,
- is_important_v0: bool,
- sent: bool,
- done: bool,
- ) -> Self {
+ pub fn from_new_notification(notification: Notification, sent: bool, done: bool) -> Self {
Self {
id: notification.id,
notification_entity: notification.notification_entity,
sent,
done,
sender_id: notification.sender_id,
- is_important_v0,
temporal: notification.temporal,
notification_event: notification.notification_event,
}
@@ -228,7 +195,7 @@ impl UserNotification {
pub struct Notification {
pub id: Uuid,
#[serde(flatten)]
- pub notification_entity: NotificationEntity,
+ pub notification_entity: Entity<'static>,
pub service_sender: String,
pub sender_id: Option<String>,
#[serde(flatten)]
@@ -237,7 +204,7 @@ pub struct Notification {
pub notification_event: NotificationEvent,
}
-#[derive(Serialize, Deserialize, Debug, ToSchema)]
+#[derive(Serialize, Deserialize, Debug, ToSchema, Hash, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct NotificationWithRecipient {
#[serde(flatten)]
@@ -245,21 +212,33 @@ pub struct NotificationWithRecipient {
// USER-SPECIFIC FIELDS
/// The user actually receiving the notification. used in intermediary processing
#[serde(skip_serializing)]
- pub recipient_id: String,
- /// If the notification should show up in the "Important" vs "Other" view
- pub is_important_v0: bool,
+ pub recipient_id: MacroUserIdStr<'static>,
+}
+
+#[derive(Debug, Clone)]
+pub enum DeviceEndpoint {
+ Android(String),
+ Ios(String),
+}
+
+impl DeviceEndpoint {
+ pub fn arn(&self) -> &str {
+ match self {
+ DeviceEndpoint::Android(a) => a.as_ref(),
+ DeviceEndpoint::Ios(i) => i.as_ref(),
+ }
+ }
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NotificationQueueMessage {
#[serde(flatten)]
- pub notification_entity: NotificationEntity,
+ pub notification_entity: Entity<'static>,
#[serde(flatten, rename = "metadata")]
pub notification_event: NotificationEvent,
pub sender_id: Option<String>,
pub recipient_ids: Option<Vec<String>>,
- pub is_important_v0: Option<bool>,
}
impl Identify for UserNotification {
diff --git a/rust/cloud-storage/model_notifications/src/push.rs b/rust/cloud-storage/model_notifications/src/push.rs
deleted file mode 100644
index 6d3fbd2c92..0000000000
--- a/rust/cloud-storage/model_notifications/src/push.rs
+++ /dev/null
@@ -1,26 +0,0 @@
-use serde::{Deserialize, Serialize};
-use utoipa::ToSchema;
-
-use crate::NotificationEntity;
-
-#[derive(Serialize, Deserialize, Debug)]
-#[serde(rename_all = "camelCase")]
-pub struct APNSPushNotification {
- pub aps: serde_json::Value,
-
- #[serde(flatten)]
- pub push_notification_data: PushNotificationData,
-}
-
-#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
-#[serde(rename_all = "camelCase")]
-pub struct PushNotificationData {
- #[serde(flatten)]
- pub notification_entity: NotificationEntity,
- /// user id of the macro user who generated the notification
- #[serde(skip_serializing_if = "Option::is_none")]
- pub sender_id: Option<String>,
- /// The route to open the notification in the app
- /// example: /channel/{channel_id}
- pub open_route: String,
-}
diff --git a/rust/cloud-storage/model_notifications/src/raw.rs b/rust/cloud-storage/model_notifications/src/raw.rs
index d98066dae6..e95984d7df 100644
--- a/rust/cloud-storage/model_notifications/src/raw.rs
+++ b/rust/cloud-storage/model_notifications/src/raw.rs
@@ -1,10 +1,10 @@
use crate::{
- Notification, NotificationEntity, NotificationEvent, NotificationEventType,
- NotificationTemporalData, UserNotification,
+ Notification, NotificationEvent, NotificationEventType, NotificationTemporalData,
+ UserNotification,
};
use anyhow::Context;
use chrono::{DateTime, serde::ts_seconds_option};
-use model_entity::EntityType;
+use model_entity::{Entity, EntityType};
use models_pagination::{CreatedAt, CursorVal, Identify, SortOn};
use serde::{Deserialize, Serialize};
use sqlx::types::Uuid;
@@ -20,10 +20,9 @@ pub struct RawNotification {
pub id: Uuid,
/// The type of notification
pub notification_event_type: String,
- /// The item id the notification event was created for
- pub event_item_id: String,
- /// The item type (document, chat, project...)
- pub event_item_type: String,
+ /// The [Entity] the notification event was created for
+ #[serde(flatten)]
+ pub entity: Entity<'static>,
/// The service that created the notification
pub service_sender: String,
/// The time the notification was created
@@ -47,10 +46,9 @@ pub struct RawUserNotification {
pub notification_id: Uuid,
/// The type of notification
pub notification_event_type: String,
- /// The id of the event item
- pub event_item_id: String,
- /// The type of the event item
- pub event_item_type: String,
+ /// The [Entity] which the notification is related to
+ #[serde(flatten)]
+ pub entity: Entity<'static>,
/// If the notification has been sent
pub sent: bool,
/// If the notification is "done"
@@ -71,8 +69,6 @@ pub struct RawUserNotification {
pub notification_metadata: Option<serde_json::Value>,
/// user id of the macro user who generated the notification
pub sender_id: Option<String>,
- /// if notification is important or not
- pub is_important_v0: bool,
/// The time the notification was updated.
/// This is the exact same as created_at and only used to make soup
/// bettter on the frontend.
@@ -86,9 +82,9 @@ impl TryFrom<&RawNotification> for NotificationEventType {
type Error = anyhow::Error;
fn try_from(raw: &RawNotification) -> Result<Self, Self::Error> {
if raw.notification_event_type == "mention" {
- match raw.event_item_type.as_str() {
- "channel" => Ok(NotificationEventType::ChannelMention),
- "document" => Ok(NotificationEventType::DocumentMention),
+ match raw.entity.entity_type {
+ EntityType::Channel => Ok(NotificationEventType::ChannelMention),
+ EntityType::Document => Ok(NotificationEventType::DocumentMention),
_ => anyhow::bail!("Unknown event item type"),
}
} else {
@@ -105,9 +101,9 @@ impl TryFrom<&RawUserNotification> for NotificationEventType {
type Error = anyhow::Error;
fn try_from(raw: &RawUserNotification) -> Result<Self, Self::Error> {
if raw.notification_event_type == "mention" {
- match raw.event_item_type.as_str() {
- "channel" => Ok(NotificationEventType::ChannelMention),
- "document" => Ok(NotificationEventType::DocumentMention),
+ match &raw.entity.entity_type {
+ EntityType::Channel => Ok(NotificationEventType::ChannelMention),
+ EntityType::Document => Ok(NotificationEventType::DocumentMention),
_ => anyhow::bail!("Unknown event item type"),
}
} else {
@@ -128,11 +124,7 @@ impl From<UserNotification> for RawUserNotification {
.notification_event
.event_type()
.to_string(),
- event_item_id: user_notification.notification_entity.event_item_id,
- event_item_type: user_notification
- .notification_entity
- .event_item_type
- .to_string(),
+ entity: user_notification.notification_entity,
sent: user_notification.sent,
done: user_notification.done,
created_at: user_notification.temporal.created_at,
@@ -140,7 +132,6 @@ impl From<UserNotification> for RawUserNotification {
deleted_at: user_notification.temporal.deleted_at,
notification_metadata: user_notification.notification_event.metadata_json(),
sender_id: user_notification.sender_id,
- is_important_v0: user_notification.is_important_v0,
updated_at: user_notification.temporal.updated_at,
}
}
@@ -155,21 +146,13 @@ impl TryFrom<RawNotification> for Notification {
&raw.notification_event_type
))?;
- let entity_type = EntityType::from_str(&raw.event_item_type).context(format!(
- "Failed to parse entity type: {:?}",
- &raw.event_item_type
- ))?;
-
let notification_event =
NotificationEvent::try_from_type_and_meta(event_type, raw.metadata)
.context("Failed to parse notification event")?;
Ok(Notification {
id: raw.id,
- notification_entity: NotificationEntity {
- event_item_id: raw.event_item_id,
- event_item_type: entity_type,
- },
+ notification_entity: raw.entity,
service_sender: raw.service_sender,
sender_id: raw.sender_id,
temporal: NotificationTemporalData {
@@ -192,25 +175,16 @@ impl TryFrom<RawUserNotification> for UserNotification {
&raw.notification_event_type
))?;
- let entity_type = EntityType::from_str(&raw.event_item_type).context(format!(
- "Failed to parse entity type: {:?}",
- &raw.event_item_type
- ))?;
-
let notification_event =
NotificationEvent::try_from_type_and_meta(event_type, raw.notification_metadata)
.context("Failed to parse notification event ")?;
Ok(UserNotification {
id: raw.notification_id,
- notification_entity: NotificationEntity {
- event_item_id: raw.event_item_id,
- event_item_type: entity_type,
- },
+ notification_entity: raw.entity,
sent: raw.sent,
done: raw.done,
sender_id: raw.sender_id,
- is_important_v0: raw.is_important_v0,
temporal: NotificationTemporalData {
created_at: raw.created_at,
viewed_at: raw.viewed_at,
@@ -227,8 +201,7 @@ impl From<Notification> for RawNotification {
RawNotification {
id: notification.id,
notification_event_type: notification.notification_event.event_type().to_string(),
- event_item_id: notification.notification_entity.event_item_id,
- event_item_type: notification.notification_entity.event_item_type.to_string(),
+ entity: notification.notification_entity,
service_sender: notification.service_sender,
created_at: notification.temporal.created_at,
metadata: notification.notification_event.metadata_json(),
diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-0182200e099205f7ee44e0f386afdd1dcc859021fbcda234ddab7b89f304f4ab.json b/rust/cloud-storage/notification_db_client/.sqlx/query-0182200e099205f7ee44e0f386afdd1dcc859021fbcda234ddab7b89f304f4ab.json
new file mode 100644
index 0000000000..00c64194de
--- /dev/null
+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-0182200e099205f7ee44e0f386afdd1dcc859021fbcda234ddab7b89f304f4ab.json
@@ -0,0 +1,44 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT d.device_endpoint,\n d.user_id,\n d.device_type as \"device_type: DeviceType\"\n FROM user_device_registration d\n WHERE d.user_id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "device_endpoint",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "device_type: DeviceType",
+ "type_info": {
+ "Custom": {
+ "name": "device_type_option",
+ "kind": {
+ "Enum": [
+ "ios",
+ "android"
+ ]
+ }
+ }
+ }
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "0182200e099205f7ee44e0f386afdd1dcc859021fbcda234ddab7b89f304f4ab"
+}
diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-1cda071d563e9fde67f2f34358745816f44b853633fc0491397aaad92d08800c.json b/rust/cloud-storage/notification_db_client/.sqlx/query-1cda071d563e9fde67f2f34358745816f44b853633fc0491397aaad92d08800c.json
deleted file mode 100644
index 84d4165a7c..0000000000
--- a/rust/cloud-storage/notification_db_client/.sqlx/query-1cda071d563e9fde67f2f34358745816f44b853633fc0491397aaad92d08800c.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO user_notification (\"notification_id\", \"user_id\", \"is_important_v0\") \n SELECT $1, user_id, $3\n FROM UNNEST($2::text[]) as user_id\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "TextArray",
- "Bool"
- ]
- },
- "nullable": []
- },
- "hash": "1cda071d563e9fde67f2f34358745816f44b853633fc0491397aaad92d08800c"
-}
diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-e9c68f229a0be9bbf5df4b69ad8e5e90c296e454f91fbc9d1c9ac66c953f6183.json b/rust/cloud-storage/notification_db_client/.sqlx/query-351653537c0ddfcbb030e0e1ef6514ae6006b5a4fdbe2d6803cb5aa94723ff82.json
similarity index 76%
rename from rust/cloud-storage/notification_db_client/.sqlx/query-e9c68f229a0be9bbf5df4b69ad8e5e90c296e454f91fbc9d1c9ac66c953f6183.json
rename to rust/cloud-storage/notification_db_client/.sqlx/query-351653537c0ddfcbb030e0e1ef6514ae6006b5a4fdbe2d6803cb5aa94723ff82.json
index 150de005b5..769aafa63a 100644
--- a/rust/cloud-storage/notification_db_client/.sqlx/query-e9c68f229a0be9bbf5df4b69ad8e5e90c296e454f91fbc9d1c9ac66c953f6183.json
+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-351653537c0ddfcbb030e0e1ef6514ae6006b5a4fdbe2d6803cb5aa94723ff82.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as notification_metadata,\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id,\n un.is_important_v0 as is_important_v0\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($3::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($3, $4))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $2\n ",
+ "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as notification_metadata,\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND n.event_item_id = ANY($2)\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($4::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($4, $5))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $3\n ",
"describe": {
"columns": [
{
@@ -67,16 +67,12 @@
"ordinal": 12,
"name": "sender_id",
"type_info": "Text"
- },
- {
- "ordinal": 13,
- "name": "is_important_v0",
- "type_info": "Bool"
}
],
"parameters": {
"Left": [
"Text",
+ "TextArray",
"Int8",
"Timestamptz",
"Uuid"
@@ -95,9 +91,8 @@
null,
true,
false,
- true,
- false
+ true
]
},
- "hash": "e9c68f229a0be9bbf5df4b69ad8e5e90c296e454f91fbc9d1c9ac66c953f6183"
+ "hash": "351653537c0ddfcbb030e0e1ef6514ae6006b5a4fdbe2d6803cb5aa94723ff82"
}
diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-4949502ccbbb7db60f4d9872491d5c5d0feb6e76428e12407c7a3ec5ed0f1743.json b/rust/cloud-storage/notification_db_client/.sqlx/query-4949502ccbbb7db60f4d9872491d5c5d0feb6e76428e12407c7a3ec5ed0f1743.json
new file mode 100644
index 0000000000..be9734c451
--- /dev/null
+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-4949502ccbbb7db60f4d9872491d5c5d0feb6e76428e12407c7a3ec5ed0f1743.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO user_notification (\"notification_id\", \"user_id\") \n SELECT $1, user_id\n FROM UNNEST($2::text[]) as user_id\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "TextArray"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "4949502ccbbb7db60f4d9872491d5c5d0feb6e76428e12407c7a3ec5ed0f1743"
+}
diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-a1d528f70a7607549708ab45a2381c4ff7d27a466e24b51e83af85d353c8e321.json b/rust/cloud-storage/notification_db_client/.sqlx/query-8ee1ed46995a46966f90c8fb0051e3f70826d1b3203603802d8bc24b97144290.json
similarity index 75%
rename from rust/cloud-storage/notification_db_client/.sqlx/query-a1d528f70a7607549708ab45a2381c4ff7d27a466e24b51e83af85d353c8e321.json
rename to rust/cloud-storage/notification_db_client/.sqlx/query-8ee1ed46995a46966f90c8fb0051e3f70826d1b3203603802d8bc24b97144290.json
index 38d1a02955..7cccc25c20 100644
--- a/rust/cloud-storage/notification_db_client/.sqlx/query-a1d528f70a7607549708ab45a2381c4ff7d27a466e24b51e83af85d353c8e321.json
+++ b/rust/cloud-storage/notification_db_client/.sqlx/query-8ee1ed46995a46966f90c8fb0051e3f70826d1b3203603802d8bc24b97144290.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as notification_metadata,\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id,\n un.is_important_v0 as is_important_v0\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND n.event_item_id = ANY($2)\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($4::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($4, $5))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $3\n ",
+ "query": "\n SELECT\n un.user_id as owner_id,\n un.notification_id,\n n.event_item_id,\n n.event_item_type,\n un.sent,\n un.done,\n un.created_at::timestamptz,\n un.seen_at::timestamptz as viewed_at,\n un.created_at::timestamptz as updated_at,\n un.deleted_at::timestamptz,\n n.metadata as notification_metadata,\n n.notification_event_type as notification_event_type,\n n.sender_id as sender_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.deleted_at IS NULL\n AND un.done = false\n AND (($3::timestamptz IS NULL)\n OR (un.created_at, un.notification_id) < ($3, $4))\n ORDER BY un.created_at DESC, un.notification_id DESC\n LIMIT $2\n ",
"describe": {
"columns": [
{
@@ -67,17 +67,11 @@
"ordinal": 12,
"name": "sender_id",
"type_info": "Text"
- },
- {
- "ordinal": 13,
- "name": "is_important_v0",
- "type_info": "Bool"
}
],
"parameters": {
"Left": [
"Text",
- "TextArray",
"Int8",
"Timestamptz",
"Uuid"
@@ -96,9 +90,8 @@
null,
true,
false,
- true,
- false
+ true
]
},
- "hash": "a1d528f70a7607549708ab45a2381c4ff7d27a466e24b51e83af85d353c8e321"
+ "hash": "8ee1ed46995a46966f90c8fb0051e3f70826d1b3203603802d8bc24b97144290"
}
diff --git a/rust/cloud-storage/notification_db_client/.sqlx/query-a9afd1f89a89404966f0b0043b549667f4f290ad3310996406d3f7b7ba6bd494.json b/rust/cloud-storage/notification_db_client/.sqlx/query-a9afd1f89a89404966f0b0043b549667f4f290ad3310996406d3f7b7ba6bd494.json
deleted file mode 100644
index 94f5336ec8..0000000000
--- a/rust/cloud-storage/notification_db_client/.sqlx/query-a9afd1f89a89404966f0b0043b549667f4f290ad3310996406d3f7b7ba6bd494.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT d.device_endpoint,\n d.user_id\n FROM user_device_registration d\n WHERE d.user_id = ANY($1)\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "device_endpoint",
- "type_info": "Text"
- },
- {
- "ordinal": 1,
- "name": "user_id",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "TextArray"
- ]
- },
- "nullable": [
- false,
- false
- ]
- },
- "hash": "a9afd1f89a89404966f0b0043b549667f4f290ad3310996406d3f7b7ba6bd494"
-}
diff --git a/rust/cloud-storage/notification_db_client/Cargo.toml b/rust/cloud-storage/notification_db_client/Cargo.toml
index 1fff36b387..c15af209d2 100644
--- a/rust/cloud-storage/notification_db_client/Cargo.toml
+++ b/rust/cloud-storage/notification_db_client/Cargo.toml
@@ -7,8 +7,10 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
+model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
models_pagination = { path = "../models_pagination" }
serde = { workspace = true }
diff --git a/rust/cloud-storage/notification_db_client/fixtures/user_notifications.sql b/rust/cloud-storage/notification_db_client/fixtures/user_notifications.sql
index 91f0e14d17..4f0aee84c5 100644
--- a/rust/cloud-storage/notification_db_client/fixtures/user_notifications.sql
+++ b/rust/cloud-storage/notification_db_client/fixtures/user_notifications.sql
@@ -13,7 +13,7 @@ VALUES
'0193b1ea-a542-7589-893b-2b4a509c1e76',
'test',
'test',
- 'test',
+ 'document',
'test',
NULL,
@@ -34,7 +34,7 @@ VALUES
'0193b1ea-a542-7589-893b-2b4a509c1e75',
'test',
'test',
- 'test',
+ 'document',
'test',
NULL,
NULL
@@ -55,7 +55,7 @@ VALUES
'0193b1ea-a542-7589-893b-2b4a509c1e74',
'test',
'test',
- 'test',
+ 'document',
'test',
NULL,
NULL
diff --git a/rust/cloud-storage/notification_db_client/src/device/mod.rs b/rust/cloud-storage/notification_db_client/src/device/mod.rs
index 2bc2bc6717..0538084fcc 100644
--- a/rust/cloud-storage/notification_db_client/src/device/mod.rs
+++ b/rust/cloud-storage/notification_db_client/src/device/mod.rs
@@ -1,3 +1,4 @@
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model_notifications::DeviceType;
use std::collections::HashMap;
@@ -56,29 +57,38 @@ pub async fn upsert_user_device(
#[tracing::instrument(skip(db))]
pub async fn get_users_device_endpoints(
db: &sqlx::Pool<sqlx::Postgres>,
- user_ids: &[String],
-) -> anyhow::Result<HashMap<String, Vec<String>>> {
+ user_ids: &[MacroUserIdStr<'static>],
+) -> anyhow::Result<HashMap<MacroUserIdStr<'static>, Vec<(String, DeviceType)>>> {
// initialize hashmap
// we need to initialize the hashmap here with *all* user ids so we can ensure we have empty
// vectors for users that don't have any device endpoints
- let mut result: HashMap<String, Vec<String>> =
+ let mut result: HashMap<MacroUserIdStr<'static>, Vec<(String, DeviceType)>> =
user_ids.iter().map(|id| (id.clone(), Vec::new())).collect();
- let device_endpoints: Vec<(String, String)> = sqlx::query!(
+ let ids: Vec<_> = user_ids.iter().map(|r| r.as_ref().to_string()).collect();
+
+ let device_endpoints: Vec<(String, String, DeviceType)> = sqlx::query!(
r#"
SELECT d.device_endpoint,
- d.user_id
+ d.user_id,
+ d.device_type as "device_type: DeviceType"
FROM user_device_registration d
WHERE d.user_id = ANY($1)
"#,
- user_ids
+ ids.as_slice()
)
- .map(|row| (row.user_id, row.device_endpoint))
+ .map(|row| (row.user_id, row.device_endpoint, row.device_type))
.fetch_all(db)
.await?;
- for (user_id, device_endpoint) in device_endpoints {
- result.entry(user_id).or_default().push(device_endpoint);
+ for (user_id, device_endpoint, device_type) in device_endpoints {
+ let Ok(res) = MacroUserIdStr::parse_from_str(&user_id) else {
+ continue;
+ };
+ result
+ .entry(res.into_owned())
+ .or_default()
+ .push((device_endpoint, device_type));
}
Ok(result)
diff --git a/rust/cloud-storage/notification_db_client/src/notification/create.rs b/rust/cloud-storage/notification_db_client/src/notification/create.rs
index f4a0bd0ab7..09c0726a2f 100644
--- a/rust/cloud-storage/notification_db_client/src/notification/create.rs
+++ b/rust/cloud-storage/notification_db_client/src/notification/create.rs
@@ -8,6 +8,7 @@ pub async fn create_notification(
pool: sqlx::Pool<sqlx::Postgres>,
notification: RawNotification,
) -> anyhow::Result<RawNotification> {
+ let entity_type: &'static str = notification.entity.entity_type.into();
let created_at: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar!(
r#"
INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)
@@ -16,8 +17,8 @@ pub async fn create_notification(
"#,
&notification.id,
notification.notification_event_type.to_string(),
- notification.event_item_id,
- notification.event_item_type,
+ &notification.entity.entity_id,
+ entity_type,
notification.service_sender,
notification.metadata,
notification.sender_id,
@@ -28,8 +29,7 @@ pub async fn create_notification(
Ok(RawNotification {
id: notification.id,
notification_event_type: notification.notification_event_type,
- event_item_id: notification.event_item_id,
- event_item_type: notification.event_item_type,
+ entity: notification.entity,
service_sender: notification.service_sender,
created_at,
metadata: notification.metadata,
@@ -45,6 +45,7 @@ pub async fn create_notification_transaction(
transaction: &mut Transaction<'_, Postgres>,
notification: RawNotification,
) -> anyhow::Result<RawNotification> {
+ let entity_type: &'static str = notification.entity.entity_type.into();
let created_at: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar!(
r#"
INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata, sender_id)
@@ -53,8 +54,8 @@ pub async fn create_notification_transaction(
"#,
&notification.id,
notification.notification_event_type.to_string(),
- notification.event_item_id,
- notification.event_item_type,
+ &notification.entity.entity_id,
+ entity_type,
notification.service_sender,
notification.metadata,
notification.sender_id,
@@ -65,8 +66,7 @@ pub async fn create_notification_transaction(
Ok(RawNotification {
id: notification.id,
notification_event_type: notification.notification_event_type,
- event_item_id: notification.event_item_id,
- event_item_type: notification.event_item_type,
+ entity: notification.entity,
service_sender: notification.service_sender,
created_at,
metadata: notification.metadata,
@@ -77,6 +77,7 @@ pub async fn create_notification_transaction(
#[cfg(test)]
mod tests {
use super::*;
+ use model_entity::EntityType;
use model_notifications::NotificationEventType;
use sqlx::{Pool, Postgres};
@@ -86,8 +87,7 @@ mod tests {
let notification = RawNotification {
id: uuid,
notification_event_type: NotificationEventType::ChannelInvite.to_string(),
- event_item_id: "test".to_string(),
- event_item_type: "test".to_string(),
+ entity: EntityType::Document.with_entity_str("test"),
service_sender: "test".to_string(),
created_at: None,
metadata: None,
@@ -107,8 +107,7 @@ mod tests {
let notification = RawNotification {
id: uuid,
notification_event_type: NotificationEventType::ChannelInvite.to_string(),
- event_item_id: "test".to_string(),
- event_item_type: "test".to_string(),
+ entity: EntityType::Document.with_entity_str("test"),
service_sender: "test".to_string(),
created_at: None,
metadata: None,
diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/create.rs b/rust/cloud-storage/notification_db_client/src/user_notification/create.rs
index cb01b92bcd..0d37f2486f 100644
--- a/rust/cloud-storage/notification_db_client/src/user_notification/create.rs
+++ b/rust/cloud-storage/notification_db_client/src/user_notification/create.rs
@@ -6,17 +6,15 @@ pub async fn create_bulk_user_notifications(
transaction: &mut sqlx::Transaction<'_, sqlx::Postgres>,
notification_id: &Uuid,
user_ids: &[String],
- is_important_v0: bool,
) -> anyhow::Result<()> {
sqlx::query!(
r#"
- INSERT INTO user_notification ("notification_id", "user_id", "is_important_v0")
- SELECT $1, user_id, $3
+ INSERT INTO user_notification ("notification_id", "user_id")
+ SELECT $1, user_id
FROM UNNEST($2::text[]) as user_id
"#,
notification_id,
user_ids,
- is_important_v0,
)
.execute(transaction.as_mut())
.await?;
@@ -39,7 +37,6 @@ mod tests {
"macro|[email protected]".to_string(),
"macro|[email protected]".to_string(),
],
- true,
)
.await?;
diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs
index 317204afce..0c569251e9 100644
--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs
+++ b/rust/cloud-storage/notification_db_client/src/user_notification/get/get_all.rs
@@ -1,3 +1,6 @@
+use std::str::FromStr;
+
+use model_entity::EntityType;
use model_notifications::RawUserNotification;
use models_pagination::{CreatedAt, Query};
use sqlx::types::Uuid;
@@ -13,8 +16,7 @@ pub async fn get_all_user_notifications(
let query_limit = limit as i64;
let (cursor_id, cursor_timestamp) = cursor.vals();
- let notifications = sqlx::query_as!(
- RawUserNotification,
+ let notifications = sqlx::query!(
r#"
SELECT
un.user_id as owner_id,
@@ -29,8 +31,7 @@ pub async fn get_all_user_notifications(
un.deleted_at::timestamptz,
n.metadata as notification_metadata,
n.notification_event_type as notification_event_type,
- n.sender_id as sender_id,
- un.is_important_v0 as is_important_v0
+ n.sender_id as sender_id
FROM user_notification un
JOIN notification n ON n.id = un.notification_id
WHERE un.user_id = $1
@@ -46,6 +47,24 @@ pub async fn get_all_user_notifications(
cursor_timestamp,
cursor_id as _, // have to cast to Option<Uuid> since notification id is a uuid
)
+ .try_map(|row| {
+ Ok(RawUserNotification {
+ owner_id: row.owner_id,
+ notification_id: row.notification_id,
+ notification_event_type: row.notification_event_type,
+ entity: EntityType::from_str(&row.event_item_type)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .with_entity_string(row.event_item_id),
+ sent: row.sent,
+ done: row.done,
+ created_at: row.created_at,
+ viewed_at: row.viewed_at,
+ deleted_at: row.deleted_at,
+ notification_metadata: row.notification_metadata,
+ sender_id: row.sender_id,
+ updated_at: row.updated_at,
+ })
+ })
.fetch_all(db)
.await?;
@@ -67,8 +86,7 @@ pub async fn get_all_user_notifications_by_event_item_ids(
let event_item_id: Vec<String> = event_item_id.iter().map(|e| e.to_string()).collect();
- let notifications = sqlx::query_as!(
- RawUserNotification,
+ let notifications = sqlx::query!(
r#"
SELECT
un.user_id as owner_id,
@@ -83,8 +101,7 @@ pub async fn get_all_user_notifications_by_event_item_ids(
un.deleted_at::timestamptz,
n.metadata as notification_metadata,
n.notification_event_type as notification_event_type,
- n.sender_id as sender_id,
- un.is_important_v0 as is_important_v0
+ n.sender_id as sender_id
FROM user_notification un
JOIN notification n ON n.id = un.notification_id
WHERE un.user_id = $1
@@ -102,6 +119,24 @@ pub async fn get_all_user_notifications_by_event_item_ids(
cursor_timestamp,
cursor_id as _, // have to cast to Option<Uuid> since notification id is a uuid
)
+ .try_map(|row| {
+ Ok(RawUserNotification {
+ owner_id: row.owner_id,
+ notification_id: row.notification_id,
+ notification_event_type: row.notification_event_type,
+ entity: EntityType::from_str(&row.event_item_type)
+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
+ .with_entity_string(row.event_item_id),
+ sent: row.sent,
+ done: row.done,
+ created_at: row.created_at,
+ viewed_at: row.viewed_at,
+ deleted_at: row.deleted_at,
+ notification_metadata: row.notification_metadata,
+ sender_id: row.sender_id,
+ updated_at: row.updated_at,
+ })
+ })
.fetch_all(db)
.await?;
diff --git a/rust/cloud-storage/notification_db_client/src/user_notification/get/unsent.rs b/rust/cloud-storage/notification_db_client/src/user_notification/get/unsent.rs
index 6f22949361..d53bfc2dbf 100644
--- a/rust/cloud-storage/notification_db_client/src/user_notification/get/unsent.rs
+++ b/rust/cloud-storage/notification_db_client/src/user_notification/get/unsent.rs
@@ -1,11 +1,14 @@
+use std::str::FromStr;
+
+use model_entity::{Entity, EntityType};
use model_notifications::NotificationEventType;
use sqlx::types::Uuid;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UnsentNotification {
pub user_id: String,
- pub event_item_id: String,
- pub event_item_type: String,
+ #[serde(flatten)]
+ pub entity: Entity<'static>,
pub notification_id: Uuid,
pub created_at: chrono::NaiveDateTime,
}
@@ -45,14 +48,13 @@ pub async fn get_unsent_notifications_for_users(
offset,
hours_ago
)
- .map(|row| {
- UnsentNotification {
+ .try_map(|row| {
+ Ok(UnsentNotification {
user_id: row.user_id,
- event_item_id: row.event_item_id,
- event_item_type: row.event_item_type,
+ entity: EntityType::from_str(&row.event_item_type).map_err(|e| sqlx::Error::Decode(Box::new(e)))?.with_entity_string(row.event_item_id),
notification_id: row.id,
created_at: row.created_at,
- }
+ })
})
.fetch_all(db)
.await?;
@@ -74,25 +76,25 @@ mod tests {
(
"11111111-1111-1111-1111-111111111111",
"item_id",
- "item_type",
+ "document",
notification_event_type,
),
(
"22222222-2222-2222-2222-222222222222",
"item_id2",
- "item_type",
+ "document",
notification_event_type,
),
(
"33333333-3333-3333-3333-333333333333",
"item_id3",
- "item_type",
+ "document",
notification_event_type,
),
(
"44444444-4444-4444-4444-444444444444",
"item_id4",
- "item_type",
+ "document",
notification_event_type,
),
];
diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.toml
index 3292a785b6..c571e6c74b 100644
--- a/rust/cloud-storage/notification_service/Cargo.toml
+++ b/rust/cloud-storage/notification_service/Cargo.toml
@@ -30,6 +30,7 @@ send_email_notifications = ["notification_worker"]
[dependencies]
anyhow = { workspace = true }
+authentication_service_client = { path = "../authentication_service_client" }
aws-config = { workspace = true }
aws-sdk-secretsmanager = { workspace = true }
aws-sdk-sesv2 = { workspace = true }
@@ -53,10 +54,12 @@ macro_env = { path = "../macro_env", features = ["frontend_url"] }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
] }
+macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
mention_utils = { path = "../mention_utils" }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
+model_file_type = { path = "../model_file_type" }
model_notifications = { path = "../model_notifications" }
models_comms = { path = "../models_comms" }
models_pagination = { path = "../models_pagination", features = ["axum"] }
@@ -80,7 +83,6 @@ tracing = { workspace = true }
url = { workspace = true }
utoipa = { workspace = true }
utoipa-swagger-ui = { workspace = true }
-authentication_service_client = { path = "../authentication_service_client" }
uuid = { workspace = true }
[dev-dependencies]
diff --git a/rust/cloud-storage/notification_service/examples/send_push_notification.rs b/rust/cloud-storage/notification_service/examples/send_push_notification.rs
index b5f0f1c933..d5b22ca4a2 100644
--- a/rust/cloud-storage/notification_service/examples/send_push_notification.rs
+++ b/rust/cloud-storage/notification_service/examples/send_push_notification.rs
@@ -3,7 +3,11 @@ use std::collections::HashMap;
use anyhow::Context;
use aws_sdk_sns::types::MessageAttributeValue;
use macro_entrypoint::MacroEntrypoint;
-use model_notifications::{APNSPushNotification, PushNotificationData};
+use serde::Serialize;
+use sns_client::{
+ APNSPushNotification, Alert, AlertDictionary, Aps, FCMMessage, MessageAttributes,
+ NotifCollapseKey, SnsTarget,
+};
/// Sends a push notification to the provided ENDPOINT_ARN environment variable
#[tokio::main]
@@ -72,38 +76,27 @@ async fn send_first(
endpoint_arn: &str,
collapse_key: &str,
) -> anyhow::Result<()> {
- let push_notification_data = PushNotificationData {
- notification_entity: model_notifications::NotificationEntity {
- event_item_id: "abc".to_string(),
- event_item_type: "document".parse().unwrap(),
+ let apns = SnsTarget::Ios(Box::new(APNSPushNotification {
+ aps: Aps {
+ alert: Some(Alert::Dictionary(AlertDictionary {
+ title: Some("GO AWAY 2".to_string()),
+ body: Some("TESTING".to_string()),
+ ..Default::default()
+ })),
+ ..Default::default()
},
- open_route: "".to_string(),
- sender_id: None,
- };
-
- let notification_body = serde_json::json!({
- "title": "GO AWAY 2",
- "body": "THIS IS ME TESTING SEND",
- });
-
- let apns = APNSPushNotification {
- aps: serde_json::json!({
- "alert": notification_body
- }),
- push_notification_data: push_notification_data.clone(),
- };
-
- let message_json = serde_json::json!({
- "APNS": serde_json::to_string(&apns).unwrap_or_else(|_| serde_json::json!({
- "aps": apns.aps
- }).to_string()),
- });
+ push_notification_data: &(),
+ }));
sns_client
.push_notification(
endpoint_arn,
- &message_json.to_string(),
- message_attributes(collapse_key),
+ &apns,
+ MessageAttributes {
+ push_type: sns_client::PushType::Alert,
+ apns_bundle_id: "com.macro.app.prod",
+ collapse_key: NotifCollapseKey::new_str(collapse_key),
+ },
)
.await
.context("unable to send push notification")?;
@@ -116,22 +109,30 @@ async fn send_empty(
endpoint_arn: &str,
collapse_key: &str,
) -> anyhow::Result<()> {
- let apns = serde_json::json!({
- "aps": {
- "content-available": 1,
+ #[derive(Debug, Serialize)]
+ struct ExtraData {
+ identifier: String,
+ }
+
+ let apns = SnsTarget::Ios(Box::new(APNSPushNotification {
+ aps: Aps {
+ content_available: Some(1),
+ ..Default::default()
},
- "identifier": collapse_key,
- });
-
- let message_json = serde_json::json!({
- "APNS": serde_json::to_string(&apns).context("could not convert apns to string")?,
- });
+ push_notification_data: ExtraData {
+ identifier: collapse_key.to_string(),
+ },
+ }));
sns_client
.push_notification(
endpoint_arn,
- &message_json.to_string(),
- message_attributes(collapse_key),
+ &apns,
+ MessageAttributes {
+ push_type: sns_client::PushType::Alert,
+ apns_bundle_id: "com.macro.app.prod",
+ collapse_key: NotifCollapseKey::new_str(collapse_key),
+ },
)
.await
.context("unable to send push notification")?;
diff --git a/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs b/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs
index 1c205ecc8d..f63d3524ed 100644
--- a/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs
+++ b/rust/cloud-storage/notification_service/src/api/notification/create_notification.rs
@@ -1,5 +1,4 @@
-use std::str::FromStr;
-
+use crate::{api::context::ApiContext, model::notification::CreateNotification};
use axum::{
Extension, Json,
extract::{self, State},
@@ -7,12 +6,11 @@ use axum::{
response::{IntoResponse, Response},
};
use model::response::ErrorResponse;
+use model::user::UserContext;
use model_notifications::{
Notification, NotificationEvent, NotificationEventType, RawNotification,
};
-
-use crate::{api::context::ApiContext, model::notification::CreateNotification};
-use model::user::UserContext;
+use std::str::FromStr;
/// Creates a notification.
/// Will generate an id for the notification.
@@ -32,18 +30,6 @@ pub async fn handler(
) -> Result<Response, Response> {
let id = macro_uuid::generate_uuid_v7();
- // Parse event item type from string to EntityType
- let event_item_type = req.event_item_type.parse().map_err(|e| {
- tracing::error!(error=?e, "invalid event item type");
- (
- StatusCode::BAD_REQUEST,
- Json(ErrorResponse {
- message: "invalid event item type",
- }),
- )
- .into_response()
- })?;
-
let notification_event_type = NotificationEventType::from_str(&req.notification_event_type)
.map_err(|e| {
tracing::error!(error=?e, "invalid notification event type");
@@ -72,10 +58,7 @@ pub async fn handler(
let notification = Notification {
id,
- notification_entity: model_notifications::NotificationEntity {
- event_item_id: req.event_item_id,
- event_item_type,
- },
+ notification_entity: req.entity,
service_sender: req.service_sender,
sender_id: Some(user_context.user_id.clone()),
temporal: Default::default(),
diff --git a/rust/cloud-storage/notification_service/src/api/swagger.rs b/rust/cloud-storage/notification_service/src/api/swagger.rs
index e538539414..601ab56ec6 100644
--- a/rust/cloud-storage/notification_service/src/api/swagger.rs
+++ b/rust/cloud-storage/notification_service/src/api/swagger.rs
@@ -1,3 +1,4 @@
+use crate::notification::send::push::PushNotificationData;
use model::{
response::{EmptyResponse, ErrorResponse},
version::NotificationServiceApiVersion,
@@ -6,7 +7,7 @@ use model_notifications::{
ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,
ChannelReplyMetadata, CommonChannelMetadata, DeviceType, DocumentMentionMetadata,
InviteToTeamMetadata, ItemSharedMetadata, NewEmailMetadata, Notification, NotificationEvent,
- NotificationEventType, PushNotificationData, UserNotification, UserUnsubscribe,
+ NotificationEventType, UserNotification, UserUnsubscribe,
};
use utoipa::OpenApi;
diff --git a/rust/cloud-storage/notification_service/src/model/notification.rs b/rust/cloud-storage/notification_service/src/model/notification.rs
index 7ecfa9ffd0..442c50c945 100644
--- a/rust/cloud-storage/notification_service/src/model/notification.rs
+++ b/rust/cloud-storage/notification_service/src/model/notification.rs
@@ -4,10 +4,9 @@ use utoipa::ToSchema;
pub struct CreateNotification {
/// The type of notification
pub notification_event_type: String,
- /// The item id the notification event was created for
- pub event_item_id: String,
- /// The item type (document, chat, project...)
- pub event_item_type: String,
+ /// The [Entity] the notification event was created for
+ #[serde(flatten)]
+ pub entity: model_entity::Entity<'static>,
/// The service that created the notification
pub service_sender: String,
/// Custom metadata that may be needed for the notification
diff --git a/rust/cloud-storage/notification_service/src/notification/create.rs b/rust/cloud-storage/notification_service/src/notification/create.rs
index fc5355ee29..df70bcc922 100644
--- a/rust/cloud-storage/notification_service/src/notification/create.rs
+++ b/rust/cloud-storage/notification_service/src/notification/create.rs
@@ -9,7 +9,6 @@ pub async fn create_notification(
db: &sqlx::Pool<sqlx::Postgres>,
notification: Notification,
user_ids: &[String],
- is_important_v0: bool,
) -> anyhow::Result<Option<Notification>> {
let mut notification_transaction = db
.begin()
@@ -43,7 +42,6 @@ pub async fn create_notification(
&mut notification_transaction,
&notification.id,
user_ids,
- is_important_v0,
)
.await?;
diff --git a/rust/cloud-storage/notification_service/src/notification/process.rs b/rust/cloud-storage/notification_service/src/notification/process.rs
index 6b241c2873..3fcba810a7 100644
--- a/rust/cloud-storage/notification_service/src/notification/process.rs
+++ b/rust/cloud-storage/notification_service/src/notification/process.rs
@@ -7,11 +7,13 @@ use crate::notification::user_ids::utils::filter_sender_id_from_recipient_ids;
use crate::notification::{rate_limit, send};
use anyhow::Context;
use futures::StreamExt;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
use model_notifications::{Notification, NotificationEventType, NotificationQueueMessage};
/// Processes a message from the notification queue.
/// If the processing is successful, the message is deleted.
-#[tracing::instrument(skip(ctx, message), fields(message_id=message.message_id))]
+#[tracing::instrument(err, skip(ctx, message), fields(message_id=message.message_id))]
pub(crate) async fn process_message(
ctx: QueueWorkerContext,
message: &aws_sdk_sqs::types::Message,
@@ -68,7 +70,6 @@ pub(crate) async fn process_message(
let sender_id = message_body.sender_id.as_ref();
let recipient_ids = message_body.recipient_ids.as_ref();
- let is_important_v0 = message_body.is_important_v0.unwrap_or(false);
let notification = Notification {
id: notification_id,
@@ -88,8 +89,7 @@ pub(crate) async fn process_message(
notification_id=%notification_id,
notification_event_type=?notification.notification_event.event_type(),
sender_id=?sender_id,
- event_item_type=?notification.notification_entity.event_item_type,
- event_item_id=%notification.notification_entity.event_item_id,
+ event_item=?notification.notification_entity,
"rate limited notification"
);
ctx.worker.cleanup_message(message).await?;
@@ -100,7 +100,7 @@ pub(crate) async fn process_message(
notification_id=%notification_id,
notification_event_type=%notification.notification_event.event_type(),
sender_id=?sender_id,
- event_item_type=%notification.notification_entity.event_item_type, event_item_id=%notification.notification_entity.event_item_id,
+ event_item=?notification.notification_entity,
"processing message"
);
@@ -117,49 +117,32 @@ pub(crate) async fn process_message(
// Filter out all user ids that have this type of notification muted or all notifications muted
let user_ids = filter_user_ids(
&ctx.db,
- &notification.notification_entity.event_item_id,
+ &notification.notification_entity.entity_id,
user_ids,
)
- .await
- .context("failed to filter user ids")?;
+ .await?;
+
+ let macro_user_ids: Vec<_> = user_ids
+ .iter()
+ .filter_map(|id| {
+ Some(
+ MacroUserIdStr::parse_from_str(id.as_ref())
+ .ok()?
+ .into_owned(),
+ )
+ })
+ .collect();
// Handle cleanup
if notification.notification_event.event_type() == NotificationEventType::RejectTeamInvite {
notification_db_client::notification::delete::delete_notification_by_event_item(
&ctx.db,
- &notification.notification_entity.event_item_id,
- &notification.notification_entity.event_item_type.to_string(),
+ &notification.notification_entity.entity_id,
+ &notification.notification_entity.entity_type.to_string(),
)
- .await
- .context("unable to delete notification")?;
+ .await?;
}
- // TODO: [BAC-44] should use connection gateway instead of emit only notifications
- // Handle short circuit for notifications that are not meant to be saved to the database
- // if notification
- // .notification_event
- // .event_type()
- // .is_emit_only_notification()
- // {
- // tracing::info!(
- // notification_id=%notification_id,
- // notification_event_type=%notification.notification_event.event_type(),
- // sender_id=?sender_id,
- // event_item_type=%notification.notification_entity.event_item_type, event_item_id=%notification.notification_entity.event_item_id,
- // user_ids=?user_ids,
- // "emitting simple notification"
- // );
- //
- // let notifications_with_user_data =
- // populate_user_data(notification, &user_ids, is_important_v0).await;
- //
- // emit_simple_notification(&ctx, notifications_with_user_data)
- // .await
- // .context("unable to emit simple notification")?;
- // ctx.worker.cleanup_message(message).await?;
- // return Ok(());
- // }
-
// Second check to see if user ids is now empty after filtering
// If there are no users to notify, we can skip the notification
if user_ids.is_empty() {
@@ -171,9 +154,7 @@ pub(crate) async fn process_message(
tracing::trace!(user_ids=?user_ids, "got user ids to notify");
// Create notification/user_notification(s)
- let notification = create_notification(&ctx.db, notification, &user_ids, is_important_v0)
- .await
- .context("unable to create notification")?;
+ let notification = create_notification(&ctx.db, notification, &user_ids).await?;
// If there is no notification returned, it means the notification already exists
let notification = match notification {
@@ -187,30 +168,28 @@ pub(crate) async fn process_message(
let notification_id = notification.id;
- let mut notifications_with_user_data =
- populate_user_data(notification, &user_ids, is_important_v0).await;
+ let notifications_with_user_data = populate_user_data(notification, &macro_user_ids);
+
+ let list_user_notifications: Vec<_> = notifications_with_user_data
+ .values()
+ .flatten()
+ .cloned()
+ .collect();
let users_sent_connection_gateway = send::connection_gateway::send_connection_gateway(
&ctx.conn_gateway_client,
- &notifications_with_user_data,
+ list_user_notifications.as_slice(),
)
.await
.context("unable to process connection gateway")?;
tracing::trace!(users_sent_connection_gateway=?users_sent_connection_gateway, "users sent via connection gateway");
- // transform the message content of the notifications into a human-readable format for push/email notifs
- notifications_with_user_data.iter_mut().for_each(|n| {
- if let Some(message_content) = n.inner.notification_event.get_message_content_mut() {
- *message_content = mention_utils::format_message_mentions(message_content);
- }
- });
-
// Get the user ids to attempt sending push notifications to
- let users_to_push = user_ids
+ let users_to_push = macro_user_ids
.iter()
.filter(|user_id| !users_sent_connection_gateway.contains(*user_id))
- .collect::<HashSet<&String>>();
+ .collect::<HashSet<_>>();
tracing::trace!(users_to_push=?users_to_push, "users to push");
@@ -222,15 +201,13 @@ pub(crate) async fn process_message(
&ctx.db,
&ctx.sns_client,
&notifications_with_user_data,
- &users_to_push,
)
- .await
- .context("unable to process push notifications")?
+ .await?
}
#[cfg(not(feature = "push_notification"))]
{
tracing::info!("bypassing push notifications");
- vec![]
+ HashSet::new()
}
};
@@ -243,18 +220,15 @@ pub(crate) async fn process_message(
None
}
})
- .collect::<HashSet<&String>>();
+ .collect::<HashSet<_>>();
tracing::trace!(users_to_email=?users_to_email, "users to email");
- // Transform the Vec into a HashSet
- let users_sent_push = users_sent_push.into_iter().collect::<HashSet<String>>();
-
tracing::trace!(users_sent_push=?users_sent_push, "users sent push notification");
let users_sent_notification = users_sent_connection_gateway
.union(&users_sent_push)
- .cloned()
- .collect::<Vec<String>>();
+ .map(|x| x.as_ref().to_string())
+ .collect::<Vec<_>>();
tracing::trace!("updating notifications sent status");
if let Err(e) = notification_db_client::user_notification::patch::sent::bulk_patch_sent(
@@ -272,17 +246,13 @@ pub(crate) async fn process_message(
// TODO: update email processing logic to handle NotificationsWithUserData instead of calling concurrently
// Process email notifications concurrently for each notification
let email_results: Vec<anyhow::Result<()>> =
- futures::stream::iter(notifications_with_user_data.iter())
+ futures::stream::iter(notifications_with_user_data.values().flatten())
.then(|notification| {
let ctx_clone = ctx.clone();
async move {
- send::email::process_email_notifications(
- &ctx_clone,
- notification,
- std::slice::from_ref(&notification.recipient_id),
- )
- .await
- .context("unable to process email notification")
+ send::email::process_email_notifications(&ctx_clone, notification)
+ .await
+ .context("unable to process email notification")
}
})
.collect()
diff --git a/rust/cloud-storage/notification_service/src/notification/rate_limit.rs b/rust/cloud-storage/notification_service/src/notification/rate_limit.rs
index 6b7354aea4..c453431ef2 100644
--- a/rust/cloud-storage/notification_service/src/notification/rate_limit.rs
+++ b/rust/cloud-storage/notification_service/src/notification/rate_limit.rs
@@ -5,7 +5,7 @@ use model_notifications::{Notification, NotificationEventType};
/// Performs a basic rate limit check on the notification
/// If this returns false, the notification can proceed
/// If this returns true, the notification should be skipped.
-#[tracing::instrument(skip(macro_cache_client, notification), fields(notification_id=?notification.id, notification_event_type=?notification.notification_event.event_type(), event_item_id=?notification.notification_entity.event_item_id, event_item_type=?notification.notification_entity.event_item_type, sender_id=?notification.sender_id))]
+#[tracing::instrument(skip(macro_cache_client, notification), fields(notification_id=?notification.id, notification_event_type=?notification.notification_event.event_type(), event_id=?notification.notification_entity, sender_id=?notification.sender_id))]
pub async fn rate_limit(
macro_cache_client: &MacroCache,
notification: &Notification,
diff --git a/rust/cloud-storage/notification_service/src/notification/send/connection_gateway.rs b/rust/cloud-storage/notification_service/src/notification/send/connection_gateway.rs
index f58ab11d1f..e9c9e19cf1 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/connection_gateway.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/connection_gateway.rs
@@ -1,4 +1,5 @@
use connection_gateway_client::model::sender::MessageReceipt;
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use model_notifications::NotificationWithRecipient;
use std::collections::HashSet;
@@ -7,7 +8,7 @@ use std::collections::HashSet;
pub async fn send_connection_gateway(
conn_gateway_client: &connection_gateway_client::client::ConnectionGatewayClient,
notifications: &[NotificationWithRecipient],
-) -> anyhow::Result<HashSet<String>> {
+) -> anyhow::Result<HashSet<MacroUserIdStr<'static>>> {
let start_time = std::time::Instant::now();
let batch_send_results: Vec<MessageReceipt> = {
#[cfg(not(feature = "connection_gateway"))]
@@ -60,12 +61,14 @@ pub async fn send_connection_gateway(
.iter()
.filter_map(|r| {
if r.delivery_count != 0 && r.active {
- Some(r.user_id.clone())
+ MacroUserIdStr::parse_from_str(&r.user_id)
+ .ok()
+ .map(CowLike::into_owned)
} else {
None
}
})
- .collect::<HashSet<String>>();
+ .collect::<HashSet<_>>();
Ok(users_sent_connection_gateway)
}
diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs b/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs
index c3e4b40ee3..3ec41f655d 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/email/filter.rs
@@ -81,11 +81,11 @@ async fn should_email(
let result = should_email_based_on_user_notification_bulk(
db,
&notification.inner.notification_event.event_type(),
- &notification.inner.notification_entity.event_item_id,
+ &notification.inner.notification_entity.entity_id,
&notification
.inner
.notification_entity
- .event_item_type
+ .entity_type
.to_string(),
user_ids,
)
@@ -107,7 +107,7 @@ async fn should_email(
NotificationEventType::ChannelInvite => comms_utils::should_email_channel_notification(
auth_service_client,
db,
- &notification.inner.notification_entity.event_item_id,
+ &notification.inner.notification_entity.entity_id,
user_ids,
)
.await
diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs b/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs
index 8f7d040869..5f79992108 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/email/mod.rs
@@ -16,12 +16,7 @@ use crate::{env::SENDER_ADDRESS, notification::context::QueueWorkerContext};
pub async fn process_email_notifications(
queue_worker_context: &QueueWorkerContext,
notification: &NotificationWithRecipient,
- user_ids: &[String],
) -> anyhow::Result<()> {
- let user_ids = user_ids
- .iter()
- .map(|user_id| user_id.to_string())
- .collect::<Vec<String>>();
// Only include valid events we want to send emails for
match notification.inner.notification_event.event_type() {
// NotificationEventType::CloudStorageItemSharedUser => {}
@@ -53,7 +48,12 @@ pub async fn process_email_notifications(
let sender_address = &*SENDER_ADDRESS;
- let emails = filter_emails(queue_worker_context, notification, &user_ids).await?;
+ let emails = filter_emails(
+ queue_worker_context,
+ notification,
+ &[notification.recipient_id.as_ref().to_string()],
+ )
+ .await?;
if emails.is_empty() {
tracing::info!("no valid emails to send emails to");
@@ -77,7 +77,7 @@ pub async fn process_email_notifications(
notification_db_client::channel_notification_email_sent::upsert::upsert_channel_notification_email_sent_bulk(
&queue_worker_context.db,
- &notification.inner.notification_entity.event_item_id,
+ &notification.inner.notification_entity.entity_id,
&channel_invite_sent_user_ids,
)
.await.context("unable to upsert channel notification email sent")?;
diff --git a/rust/cloud-storage/notification_service/src/notification/send/email/template.rs b/rust/cloud-storage/notification_service/src/notification/send/email/template.rs
index d5601d25e7..3f45ba5483 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/email/template.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/email/template.rs
@@ -5,6 +5,7 @@ use crate::{
};
use anyhow::Context;
use macro_env::{Environment, ext::frontend_url::FrontendUrl};
+use model_entity::EntityType;
use model_notifications::{
ChannelInviteMetadata, ChannelMessageSendMetadata, NotificationEventType,
NotificationWithRecipient,
@@ -63,13 +64,10 @@ pub fn fill_email_template(
let item_url = get_item_share_url(notification).context("unable to create item url")?;
- if notification
- .inner
- .notification_entity
- .event_item_type
- .to_string()
- == "document"
- {
+ if matches!(
+ notification.inner.notification_entity.entity_type,
+ EntityType::Document
+ ) {
let file_type =
metadata_utils::get_metadata_value::<String>(notification, "file_type")?;
@@ -85,7 +83,7 @@ pub fn fill_email_template(
&notification
.inner
.notification_entity
- .event_item_type
+ .entity_type
.to_string(),
))
}
diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
index 6702712b25..b1e9d2e08e 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/push/generate.rs
@@ -1,64 +1,17 @@
-use crate::config::APPLE_BUNDLE_ID;
-use anyhow::Context;
-use aws_sdk_sns::types::MessageAttributeValue;
+use crate::notification::send::push::PushNotificationData;
+use macro_user_id::email::ReadEmailParts;
+use macro_user_id::user_id::MacroUserIdStr;
+use mention_utils::parse::{ParsedXmlText, XmlFormatter};
use model::document::{FileType, FileTypeExt};
use model_notifications::NotificationWithRecipient;
use model_notifications::{
- APNSPushNotification, ChannelInviteMetadata, ChannelMentionMetadata,
- ChannelMessageSendMetadata, ChannelReplyMetadata, DocumentMentionMetadata,
- NotificationEventType, PushNotificationData,
+ ChannelInviteMetadata, ChannelMentionMetadata, ChannelMessageSendMetadata,
+ ChannelReplyMetadata, DocumentMentionMetadata,
};
use models_comms::ChannelType;
+use sns_client::{APNSPushNotification, Aps};
use std::str::FromStr;
-use std::{
- collections::HashMap,
- hash::{DefaultHasher, Hash, Hasher},
-};
-
-/// Builds the message attributes for the push notification
-pub fn build_message_attributes(
- collapse_key: &str,
-) -> Option<HashMap<String, MessageAttributeValue>> {
- Some(HashMap::from([
- (
- "AWS.SNS.MOBILE.APNS.TOPIC".to_string(),
- MessageAttributeValue::builder()
- .data_type("String")
- .string_value(&*APPLE_BUNDLE_ID)
- .build()
- .unwrap(),
- ),
- (
- "AWS.SNS.MOBILE.APNS.PUSH_TYPE".to_string(),
- MessageAttributeValue::builder()
- .data_type("String")
- .string_value("alert")
- .build()
- .unwrap(),
- ),
- (
- "AWS.SNS.MOBILE.APNS.PRIORITY".to_string(),
- MessageAttributeValue::builder()
- .data_type("String")
- .string_value("5") // 5 is normal, 10 is high
- .build()
- .unwrap(),
- ),
- (
- "AWS.SNS.MOBILE.APNS.COLLAPSE_ID".to_string(),
- MessageAttributeValue::builder()
- .data_type("String")
- .string_value(collapse_key)
- .build()
- .unwrap(),
- ),
- ]))
-}
-
-type PushNotificationResult = Option<(
- serde_json::Value,
- Option<HashMap<String, MessageAttributeValue>>,
-)>;
+use thiserror::Error;
/// Given a notification, this generates a push notification object
/// Returns (message_json, message_attributes) if the notification is valid
@@ -66,281 +19,589 @@ type PushNotificationResult = Option<(
/// NOTE: @synoet - I think push notifications should be generated using the new
/// [NotificationEvnet] type instead of the [NotificationWithRecipient] type
/// Simmilarly, each of these should implement some sort of PushDisplay trait
-pub fn generate_push_notification(
- notification: &NotificationWithRecipient,
-) -> anyhow::Result<PushNotificationResult> {
- let (title, message, open_route): (String, String, String) =
- match notification.inner.notification_event.event_type() {
- NotificationEventType::ChannelInvite => {
- let metadata = if let Some(metadata) = notification
- .inner
- .notification_event
- .metadata_json()
- .as_ref()
- {
- metadata.clone()
- } else {
- return Err(anyhow::anyhow!("notification does not have metadata"));
- };
- let metadata: ChannelInviteMetadata = serde_json::from_value(metadata.clone())?;
-
- let title = format!(
- "{} invited you to join {}",
- metadata.invited_by, metadata.common.channel_name
- );
-
- let open_route = format!(
- "/channel/{}",
- notification.inner.notification_entity.event_item_id
- );
-
- (title, "".to_string(), open_route)
- }
- NotificationEventType::ChannelMessageSend => {
- let metadata = if let Some(metadata) = notification
- .inner
- .notification_event
- .metadata_json()
- .as_ref()
- {
- metadata.clone()
- } else {
- return Err(anyhow::anyhow!("notification does not have metadata"));
- };
- let metadata: ChannelMessageSendMetadata =
- serde_json::from_value(metadata.clone())?;
- let message: String = metadata.message_content;
- let email = notification
- .inner
- .sender_id
- .clone()
- .context("expected sender id")?
- .replace("macro|", "");
-
- let message_item = if message.is_empty() {
- "an attachment"
- } else {
- "a message"
- };
-
- let channel_name = metadata.common.channel_name;
-
- let title = match metadata.common.channel_type {
- ChannelType::DirectMessage => {
- format!("{} sent you {}", email, message_item)
- }
- _ => {
- format!("{} sent {} to #{}", email, message_item, channel_name)
- }
- };
-
- let message_id = format!("?message_id={}", metadata.message_id);
-
- let open_route = format!(
- "/channel/{}{}",
- notification.inner.notification_entity.event_item_id, message_id
- );
-
- (title, message, open_route)
- }
- NotificationEventType::ChannelMessageReply => {
- let metadata = if let Some(metadata) = notification
- .inner
- .notification_event
- .metadata_json()
- .as_ref()
- {
- metadata.clone()
- } else {
- return Err(anyhow::anyhow!("notification does not have metadata"));
- };
- let metadata: ChannelReplyMetadata = serde_json::from_value(metadata.clone())?;
- let message = metadata.message_content;
-
- let email = notification
- .inner
- .sender_id
- .clone()
- .context("expected sender id")?
- .replace("macro|", "");
-
- let title = format!("{} replied to thread", email);
- let open_route = format!(
- "/channel/{}?message_id={}&thread_id={}",
- notification.inner.notification_entity.event_item_id,
- metadata.message_id,
- metadata.thread_id
- );
-
- (title, message, open_route)
- }
- NotificationEventType::ChannelMention => {
- let channel_metadata = if let Some(channel_metadata) =
- &notification.inner.notification_event.metadata_json()
- {
- channel_metadata.clone()
- } else {
- return Err(anyhow::anyhow!("no channel metadata was provided"));
- };
-
- let metadata: ChannelMentionMetadata = serde_json::from_value(channel_metadata)?;
-
- let email = notification
- .inner
- .sender_id
- .clone()
- .context("expected sender id")?
- .replace("macro|", "");
-
- let message = metadata.message_content;
-
- let title = format!(
- "{} mentioned you in #{}",
- email, metadata.common.channel_name
- );
-
- let thread_id = if let Some(thread_id) = metadata.thread_id {
- format!("&thread_id={}", thread_id)
- } else {
- "".to_string()
- };
-
- let open_route = format!(
- "/channel/{}?message_id={}{}",
- notification.inner.notification_entity.event_item_id,
- metadata.message_id,
- thread_id
- );
-
- (title, message, open_route)
- }
- NotificationEventType::DocumentMention => {
- let document_metadata = if let Some(document_metadata) =
- &notification.inner.notification_event.metadata_json()
- {
- document_metadata.clone()
- } else {
- return Err(anyhow::anyhow!("no document metadata was provided"));
- };
-
- let metadata: DocumentMentionMetadata = serde_json::from_value(document_metadata)?;
-
- let sender_id = notification
- .inner
- .sender_id
- .as_ref()
- .context("expected sender id")?;
-
- if let Some(file_type) = metadata.file_type {
- let email = sender_id.replace("macro|", "");
- let message = format!(
- "{} mentioned you in {}.{}",
- email, metadata.document_name, file_type
- );
- let file_type = FileType::from_str(file_type.as_str())?;
-
- let block_route = if file_type.is_image() {
- "image"
- } else {
- match file_type {
- FileType::Pdf => "pdf",
- FileType::Docx => "write",
- FileType::Md => "md",
- _ => "code", // Default to code block
- }
- };
-
- let open_route = format!(
- "/{}/{}",
- block_route, notification.inner.notification_entity.event_item_id
- );
-
- ("New Mention".to_string(), message, open_route)
- } else {
- return Err(anyhow::anyhow!("no file type was provided"));
- }
- }
- // no push notifs for email yet
-
- // NotificationEventType::NewEmail => {
- // let metadata = if let Some(metadata) = notification.inner.notification_event.metadata_as_json().as_ref() {
- // metadata.clone()
- // } else {
- // return Err(anyhow::anyhow!("notification does not have metadata"));
- // };
- // let metadata: NewEmailMetadata = serde_json::from_value(metadata)?;
- //
- // let title = if let Some(from_email) = metadata.sender {
- // format!("New email from {}", from_email)
- // } else {
- // "New email".to_string()
- // };
- // let message = metadata.subject;
- // let open_route = format!(
- // "/email/{}?message_id={}",
- // metadata.thread_id, notification.inner.notification_entity.event_item_id
- // );
- //
- // (title, message, open_route)
- // }
- _ => return Ok(None), // unsupported push notification
- };
-
- tracing::trace!(message=?message, "created message");
-
- let collapse_key = format!(
- "{}{}",
- notification.inner.notification_entity.event_item_id,
- notification.inner.notification_event.event_type()
- );
-
- // hash the collapse key to shorten it
- let mut hasher = DefaultHasher::new();
- collapse_key.hash(&mut hasher);
- let hash = hasher.finish();
- let collapse_key = format!("{:x}", hash);
-
- let push_notification_data = PushNotificationData {
- notification_entity: notification.inner.notification_entity.clone(),
- sender_id: notification.inner.sender_id.clone(),
- open_route: open_route.clone(),
- };
+// pub fn generate_push_notification(notification: &NotificationWithRecipient) {
+// let (title, message, open_route): (String, String, String) = match notification
+// .inner
+// .notification_event
+// .event_type()
+// {
+// NotificationEventType::ChannelInvite => {
+// let metadata = if let Some(metadata) = notification
+// .inner
+// .notification_event
+// .metadata_json()
+// .as_ref()
+// {
+// metadata.clone()
+// } else {
+// return Err(anyhow::anyhow!("notification does not have metadata"));
+// };
+// let metadata: ChannelInviteMetadata = serde_json::from_value(metadata.clone())?;
+
+// let title = format!(
+// "{} invited you to join {}",
+// metadata.invited_by, metadata.common.channel_name
+// );
+
+// let open_route = format!(
+// "/channel/{}",
+// notification.inner.notification_entity.entity_id
+// );
+
+// (title, "".to_string(), open_route)
+// }
+// NotificationEventType::ChannelMessageSend => {
+// let metadata = if let Some(metadata) = notification
+// .inner
+// .notification_event
+// .metadata_json()
+// .as_ref()
+// {
+// metadata.clone()
+// } else {
+// return Err(anyhow::anyhow!("notification does not have metadata"));
+// };
+// let metadata: ChannelMessageSendMetadata = serde_json::from_value(metadata.clone())?;
+// let message: String = metadata.message_content;
+// let email = notification
+// .inner
+// .sender_id
+// .clone()
+// .context("expected sender id")?
+// .replace("macro|", "");
+
+// let message_item = if message.is_empty() {
+// "an attachment"
+// } else {
+// "a message"
+// };
+
+// let channel_name = metadata.common.channel_name;
+
+// let title = match metadata.common.channel_type {
+// ChannelType::DirectMessage => {
+// format!("{} sent you {}", email, message_item)
+// }
+// _ => {
+// format!("{} sent {} to #{}", email, message_item, channel_name)
+// }
+// };
+
+// let message_id = format!("?message_id={}", metadata.message_id);
+
+// let open_route = format!(
+// "/channel/{}{}",
+// notification.inner.notification_entity.entity_id, message_id
+// );
+
+// (title, message, open_route)
+// }
+// NotificationEventType::ChannelMessageReply => {
+// let metadata = if let Some(metadata) = notification
+// .inner
+// .notification_event
+// .metadata_json()
+// .as_ref()
+// {
+// metadata.clone()
+// } else {
+// return Err(anyhow::anyhow!("notification does not have metadata"));
+// };
+// let metadata: ChannelReplyMetadata = serde_json::from_value(metadata.clone())?;
+// let message = metadata.message_content;
+
+// let email = notification
+// .inner
+// .sender_id
+// .clone()
+// .context("expected sender id")?
+// .replace("macro|", "");
+
+// let title = format!("{} replied to thread", email);
+// let open_route = format!(
+// "/channel/{}?message_id={}&thread_id={}",
+// notification.inner.notification_entity.entity_id,
+// metadata.message_id,
+// metadata.thread_id
+// );
+
+// (title, message, open_route)
+// }
+// NotificationEventType::ChannelMention => {
+// let channel_metadata = if let Some(channel_metadata) =
+// &notification.inner.notification_event.metadata_json()
+// {
+// channel_metadata.clone()
+// } else {
+// return Err(anyhow::anyhow!("no channel metadata was provided"));
+// };
+
+// let metadata: ChannelMentionMetadata = serde_json::from_value(channel_metadata)?;
+
+// let email = notification
+// .inner
+// .sender_id
+// .clone()
+// .context("expected sender id")?
+// .replace("macro|", "");
+
+// let message = metadata.message_content;
+
+// let title = format!(
+// "{} mentioned you in #{}",
+// email, metadata.common.channel_name
+// );
+
+// let thread_id = if let Some(thread_id) = metadata.thread_id {
+// format!("&thread_id={}", thread_id)
+// } else {
+// "".to_string()
+// };
+
+// let open_route = format!(
+// "/channel/{}?message_id={}{}",
+// notification.inner.notification_entity.entity_id, metadata.message_id, thread_id
+// );
+
+// (title, message, open_route)
+// }
+// NotificationEventType::DocumentMention => {
+// let document_metadata = if let Some(document_metadata) =
+// &notification.inner.notification_event.metadata_json()
+// {
+// document_metadata.clone()
+// } else {
+// return Err(anyhow::anyhow!("no document metadata was provided"));
+// };
+
+// let metadata: DocumentMentionMetadata = serde_json::from_value(document_metadata)?;
+
+// let sender_id = notification
+// .inner
+// .sender_id
+// .as_ref()
+// .context("expected sender id")?;
+
+// if let Some(file_type) = metadata.file_type {
+// let email = sender_id.replace("macro|", "");
+// let message = format!(
+// "{} mentioned you in {}.{}",
+// email, metadata.document_name, file_type
+// );
+// let file_type = FileType::from_str(file_type.as_str())?;
+
+// let block_route = if file_type.is_image() {
+// "image"
+// } else {
+// match file_type {
+// FileType::Pdf => "pdf",
+// FileType::Docx => "write",
+// FileType::Md => "md",
+// _ => "code", // Default to code block
+// }
+// };
+
+// let open_route = format!(
+// "/{}/{}",
+// block_route, notification.inner.notification_entity.entity_id
+// );
+
+// ("New Mention".to_string(), message, open_route)
+// } else {
+// return Err(anyhow::anyhow!("no file type was provided"));
+// }
+// }
+// // no push notifs for email yet
+
+// // NotificationEventType::NewEmail => {
+// // let metadata = if let Some(metadata) = notification.inner.notification_event.metadata_as_json().as_ref() {
+// // metadata.clone()
+// // } else {
+// // return Err(anyhow::anyhow!("notification does not have metadata"));
+// // };
+// // let metadata: NewEmailMetadata = serde_json::from_value(metadata)?;
+// //
+// // let title = if let Some(from_email) = metadata.sender {
+// // format!("New email from {}", from_email)
+// // } else {
+// // "New email".to_string()
+// // };
+// // let message = metadata.subject;
+// // let open_route = format!(
+// // "/email/{}?message_id={}",
+// // metadata.thread_id, notification.inner.notification_entity.event_item_id
+// // );
+// //
+// // (title, message, open_route)
+// // }
+// _ => return Ok(None), // unsupported push notification
+// };
+
+// tracing::trace!(message=?message, "created message");
+
+// let collapse_key = format!(
+// "{}{}",
+// notification.inner.notification_entity.entity_id,
+// notification.inner.notification_event.event_type()
+// );
+
+// // hash the collapse key to shorten it
+// let mut hasher = DefaultHasher::new();
+// collapse_key.hash(&mut hasher);
+// let hash = hasher.finish();
+// let collapse_key = format!("{:x}", hash);
+
+// let push_notification_data = PushNotificationData {
+// notification_entity: notification.inner.notification_entity.clone(),
+// sender_id: notification.inner.sender_id.clone(),
+// open_route: open_route.clone(),
+// };
+
+// let notification_body = serde_json::json!({
+// "title": title,
+// "body": message,
+// });
+
+// let apns = APNSPushNotification {
+// aps: Aps {
+// alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
+// title: Some(title),
+// body: Some(message),
+// ..Default::default()
+// })),
+// ..Default::default()
+// },
+// push_notification_data: push_notification_data.clone(),
+// };
+
+// let message_json = serde_json::json!({
+// "default": serde_json::json!({
+// "notification": notification_body
+// }).to_string(),
+// "APNS": serde_json::to_string(&apns).unwrap_or_else(|_| serde_json::json!({
+// "aps": apns.aps
+// }).to_string()),
+// "GCM": serde_json::json!({
+// "fcmV1Message": {
+// "message": {
+// "android": {
+// "notification": notification_body,
+// "priority": "normal", // options are normal and high
+// "collapse_key": collapse_key.clone()
+// },
+// "data": push_notification_data,
+// },
+// }
+// }).to_string()
+// });
+
+// Ok(Some((
+// SnsPayload {
+// default: todo!(),
+// apns: todo!(),
+// apns_sandbox: todo!(),
+// gcm: todo!(),
+// },
+// // build_message_attributes(&collapse_key),
+// )))
+// }
+
+#[derive(Debug, Error)]
+pub enum NotificationErr {
+ #[error("The sender_id field was None for a notification which must have a sender")]
+ SenderDoesntExist,
+ #[error("File type did not exist for a notification expecting a file type")]
+ FileTypeDoesntExist,
+ #[error(transparent)]
+ InvalidFileType(#[from] model_file_type::ValueError<FileType>),
+ #[error(transparent)]
+ UserId(#[from] macro_user_id::error::ParseErr),
+ #[error(transparent)]
+ XmlErr(#[from] mention_utils::parse::ParseErr),
+}
- let notification_body = serde_json::json!({
- "title": title,
- "body": message,
- });
+pub struct PlainTextFormatter;
+
+impl XmlFormatter for PlainTextFormatter {
+ fn format_plain_text(s: &str, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", s)
+ }
+
+ fn format_link(
+ link: &mention_utils::parse::ParsedLink<'_>,
+ f: &mut std::fmt::Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(f, "{}", link.text)
+ }
+
+ fn format_doc(
+ doc: &mention_utils::parse::ParsedDocumentMention<'_>,
+ f: &mut std::fmt::Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(f, "{}", doc.document_name)
+ }
+
+ fn format_user(
+ user: &mention_utils::parse::ParsedUserMention<'_>,
+ f: &mut std::fmt::Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(f, "{}", user.user_id.0.email_part().email_str())
+ }
+
+ fn format_contact(
+ contact: &mention_utils::parse::ParsedContactMention<'_>,
+ f: &mut std::fmt::Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(f, "{}", contact.name)
+ }
+
+ fn format_date(
+ date: &mention_utils::parse::ParsedDateMention<'_>,
+ f: &mut std::fmt::Formatter<'_>,
+ ) -> std::fmt::Result {
+ write!(f, "{}", date.display_format)
+ }
+}
- let apns = APNSPushNotification {
- aps: serde_json::json!({
- "alert": notification_body
- }),
- push_notification_data: push_notification_data.clone(),
+pub fn generate_apns_notification<T: XmlFormatter>(
+ notif: &NotificationWithRecipient,
+) -> Result<Option<APNSPushNotification<PushNotificationData>>, NotificationErr> {
+ let create_push_data = |route: Route| PushNotificationData {
+ notification_entity: notif.inner.notification_entity.clone(),
+ sender_id: notif.inner.sender_id.clone(),
+ open_route: route.0,
};
- let message_json = serde_json::json!({
- "default": serde_json::json!({
- "notification": notification_body
- }).to_string(),
- "APNS": serde_json::to_string(&apns).unwrap_or_else(|_| serde_json::json!({
- "aps": apns.aps
- }).to_string()),
- "GCM": serde_json::json!({
- "fcmV1Message": {
- "message": {
- "android": {
- "notification": notification_body,
- "priority": "normal", // options are normal and high
- "collapse_key": collapse_key.clone()
- },
- "data": push_notification_data,
- },
- }
- }).to_string()
- });
-
- Ok(Some((
- message_json,
- build_message_attributes(&collapse_key),
- )))
+ let parse_user = || -> Result<MacroUserIdStr<'_>, NotificationErr> {
+ Ok(MacroUserIdStr::parse_from_str(
+ notif
+ .inner
+ .sender_id
+ .as_ref()
+ .ok_or(NotificationErr::SenderDoesntExist)?,
+ )?)
+ };
+
+ Ok(match &notif.inner.notification_event {
+ model_notifications::NotificationEvent::ItemSharedUser(_) => None,
+ model_notifications::NotificationEvent::ItemSharedOrganization(_) => None,
+ model_notifications::NotificationEvent::ChannelMention(channel_mention_metadata) => Some(
+ channel_mention_metadata
+ .build_apns_notification::<T>(parse_user()?)?
+ .map(|()| {
+ create_push_data(Route(format!(
+ "/channel/{}?message_id={}{}",
+ notif.inner.notification_entity.entity_id,
+ channel_mention_metadata.message_id,
+ format_args!(
+ "{}{}",
+ if channel_mention_metadata.thread_id.is_some() {
+ "&thread_id="
+ } else {
+ ""
+ },
+ channel_mention_metadata.thread_id.as_deref().unwrap_or("")
+ )
+ )))
+ }),
+ ),
+ model_notifications::NotificationEvent::DocumentMention(document_mention_metadata) => {
+ let file_type_str = document_mention_metadata
+ .file_type
+ .as_ref()
+ .ok_or(NotificationErr::FileTypeDoesntExist)?;
+ let file_type = FileType::from_str(file_type_str)?;
+
+ let block_route = match file_type {
+ x if x.is_image() => "image",
+ FileType::Pdf => "pdf",
+ FileType::Docx => "write",
+ FileType::Md => "md",
+ _ => "code",
+ };
+
+ let open_route = format!(
+ "/{}/{}",
+ block_route, notif.inner.notification_entity.entity_id
+ );
+
+ Some(
+ document_mention_metadata
+ .build_apns_notification::<T>(parse_user()?)?
+ .map(|()| create_push_data(Route(open_route))),
+ )
+ }
+ model_notifications::NotificationEvent::ChannelInvite(channel_invite_metadata) => Some(
+ channel_invite_metadata
+ .build_apns_notification::<T>(())?
+ .map(|()| {
+ create_push_data(Route(format!(
+ "/channel/{}",
+ notif.inner.notification_entity.entity_id
+ )))
+ }),
+ ),
+ model_notifications::NotificationEvent::ChannelMessageSend(
+ channel_message_send_metadata,
+ ) => Some(
+ channel_message_send_metadata
+ .build_apns_notification::<T>(())?
+ .map(|()| {
+ create_push_data(Route(format!(
+ "/channel/{}?message_id={}",
+ notif.inner.notification_entity.entity_id,
+ channel_message_send_metadata.message_id
+ )))
+ }),
+ ),
+ model_notifications::NotificationEvent::ChannelMessageReply(channel_reply_metadata) => {
+ Some(
+ channel_reply_metadata
+ .build_apns_notification::<T>(parse_user()?)?
+ .map(|()| {
+ create_push_data(Route(format!(
+ "/channel/{}?message_id={}&thread_id={}",
+ notif.inner.notification_entity.entity_id,
+ channel_reply_metadata.message_id,
+ channel_reply_metadata.thread_id
+ )))
+ }),
+ )
+ }
+ model_notifications::NotificationEvent::ChannelMessageDocument(
+ _document_mention_metadata,
+ ) => None,
+ model_notifications::NotificationEvent::NewEmail(_new_email_metadata) => None,
+ model_notifications::NotificationEvent::InviteToTeam(_invite_to_team_metadata) => None,
+ model_notifications::NotificationEvent::RejectTeamInvite => None,
+ })
+}
+
+trait BuildNotification {
+ type Ctx<'a>;
+ fn build_apns_notification<T: XmlFormatter>(
+ &self,
+ ctx: Self::Ctx<'_>,
+ ) -> Result<APNSPushNotification<()>, NotificationErr>;
+}
+
+/// the route the notification should navigate to on click
+struct Route(String);
+
+impl BuildNotification for ChannelMessageSendMetadata {
+ type Ctx<'a> = ();
+ fn build_apns_notification<T: XmlFormatter>(
+ &self,
+ _ctx: Self::Ctx<'_>,
+ ) -> Result<APNSPushNotification<()>, NotificationErr> {
+ Ok(APNSPushNotification {
+ aps: Aps {
+ alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
+ title: Some(match self.common.channel_type {
+ ChannelType::DirectMessage => self.common.channel_name.to_string(),
+ _ => format!("{} <{}>", self.sender, self.common.channel_name),
+ }),
+ body: Some(T::format_xml_text(ParsedXmlText::parse(&self.message_content)?).0),
+ ..Default::default()
+ })),
+ ..Default::default()
+ },
+ push_notification_data: (),
+ })
+ }
+}
+
+impl BuildNotification for ChannelMentionMetadata {
+ type Ctx<'a> = MacroUserIdStr<'a>;
+ fn build_apns_notification<T: XmlFormatter>(
+ &self,
+ ctx: Self::Ctx<'_>,
+ ) -> Result<APNSPushNotification<()>, NotificationErr> {
+ Ok(APNSPushNotification {
+ aps: Aps {
+ alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
+ title: Some(format!(
+ "{} mentioned you in #{}",
+ ctx.email_part().as_ref(),
+ &self.common.channel_name
+ )),
+ body: Some(T::format_xml_text(ParsedXmlText::parse(&self.message_content)?).0),
+ ..Default::default()
+ })),
+ ..Default::default()
+ },
+ push_notification_data: (),
+ })
+ }
+}
+
+impl BuildNotification for DocumentMentionMetadata {
+ type Ctx<'a> = MacroUserIdStr<'a>;
+ fn build_apns_notification<T: XmlFormatter>(
+ &self,
+ ctx: Self::Ctx<'_>,
+ ) -> Result<APNSPushNotification<()>, NotificationErr> {
+ Ok(APNSPushNotification {
+ aps: Aps {
+ alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
+ title: Some(ctx.0.email_part().email_str().to_string()),
+ body: Some(format!(
+ "You were mentioned in {}.{}",
+ self.document_name,
+ self.file_type
+ .as_ref()
+ .ok_or(NotificationErr::FileTypeDoesntExist)?
+ )),
+ ..Default::default()
+ })),
+ ..Default::default()
+ },
+ push_notification_data: (),
+ })
+ }
+}
+
+impl BuildNotification for ChannelReplyMetadata {
+ type Ctx<'a> = MacroUserIdStr<'a>;
+
+ fn build_apns_notification<T: XmlFormatter>(
+ &self,
+ ctx: Self::Ctx<'_>,
+ ) -> Result<APNSPushNotification<()>, NotificationErr> {
+ Ok(APNSPushNotification {
+ aps: Aps {
+ alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
+ title: Some(format!("{} Replied", ctx.0.email_part().email_str())),
+ body: Some(T::format_xml_text(ParsedXmlText::parse(&self.message_content)?).0),
+ ..Default::default()
+ })),
+ ..Default::default()
+ },
+ push_notification_data: (),
+ })
+ }
+}
+
+impl BuildNotification for ChannelInviteMetadata {
+ type Ctx<'a> = ();
+
+ fn build_apns_notification<T: XmlFormatter>(
+ &self,
+ _ctx: Self::Ctx<'_>,
+ ) -> Result<APNSPushNotification<()>, NotificationErr> {
+ Ok(APNSPushNotification {
+ aps: Aps {
+ alert: Some(sns_client::Alert::Dictionary(sns_client::AlertDictionary {
+ title: Some(format!("{} Invite", self.common.channel_name)),
+ body: Some(format!(
+ "{} invited you to join the channel",
+ self.invited_by
+ )),
+ ..Default::default()
+ })),
+ ..Default::default()
+ },
+ push_notification_data: (),
+ })
+ }
}
diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs b/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs
index fa6802a227..9aacd7e35a 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/push/mod.rs
@@ -1,3 +1,19 @@
+use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
+
pub mod generate;
pub mod process;
pub mod remove;
+
+#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct PushNotificationData {
+ #[serde(flatten)]
+ pub notification_entity: model_entity::Entity<'static>,
+ /// user id of the macro user who generated the notification
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sender_id: Option<String>,
+ /// The route to open the notification in the app
+ /// example: /channel/{channel_id}
+ pub open_route: String,
+}
diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/process.rs b/rust/cloud-storage/notification_service/src/notification/send/push/process.rs
index 19dc059238..afd5d70c46 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/push/process.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/push/process.rs
@@ -1,109 +1,126 @@
-use std::collections::{HashMap, HashSet};
+use crate::{
+ config::APPLE_BUNDLE_ID,
+ notification::send::push::generate::{PlainTextFormatter, generate_apns_notification},
+};
+use aws_sdk_sns::operation::publish::PublishOutput;
+use futures::{Stream, StreamExt};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_notifications::{DeviceEndpoint, NotificationWithRecipient, UserNotification};
+use sns_client::{NotifCollapseKey, SnsTarget};
+use std::{
+ borrow::Cow,
+ collections::{HashMap, HashSet},
+ hash::{DefaultHasher, Hash, Hasher},
+};
-use anyhow::Context;
-use futures::StreamExt;
-use model_notifications::NotificationWithRecipient;
+trait NotifCollapseKeyExt {
+ fn collapse_key(&self) -> NotifCollapseKey<'static>;
+}
+
+impl NotifCollapseKeyExt for UserNotification {
+ fn collapse_key(&self) -> NotifCollapseKey<'static> {
+ let collapse_key = format!(
+ "{}{}",
+ self.notification_entity.entity_id,
+ self.notification_event.event_type()
+ );
+
+ // hash the collapse key to shorten it
+ let mut hasher = DefaultHasher::new();
+ collapse_key.hash(&mut hasher);
+ let hash = hasher.finish();
+ let collapse_key = format!("{:x}", hash);
+ NotifCollapseKey(Cow::Owned(collapse_key))
+ }
+}
-use super::generate::generate_push_notification;
+pub type NotificationsForDevices<'a> = HashMap<&'a NotificationWithRecipient, Vec<DeviceEndpoint>>;
+pub type NotificationResult = (PublishOutput, MacroUserIdStr<'static>, DeviceEndpoint);
+
+pub fn stream_push_notifs_to_user<'a>(
+ sns_client: &'a sns_client::SNS,
+ notifs: &'a NotificationsForDevices<'a>,
+) -> impl Stream<Item = Result<NotificationResult, anyhow::Error>> + 'a {
+ futures::stream::iter(
+ notifs
+ .iter()
+ .flat_map(|(notif, devices)| devices.iter().map(move |d| (notif, d))),
+ )
+ .filter_map(
+ async |(notif, endpoint)| -> Option<Result<NotificationResult, anyhow::Error>> {
+ let payload = match endpoint {
+ DeviceEndpoint::Android(_) => {
+ return Some(Err(anyhow::anyhow!("android not implemented")));
+ }
+ DeviceEndpoint::Ios(_) => {
+ match generate_apns_notification::<PlainTextFormatter>(notif).transpose()? {
+ Ok(n) => SnsTarget::Ios(Box::new(n)),
+ Err(e) => return Some(Err(anyhow::Error::from(e))),
+ }
+ }
+ };
+ let res = sns_client
+ .push_notification(
+ endpoint.arn(),
+ &payload,
+ sns_client::MessageAttributes {
+ push_type: sns_client::PushType::Alert,
+ apns_bundle_id: &APPLE_BUNDLE_ID,
+ collapse_key: notif.inner.collapse_key(),
+ },
+ )
+ .await;
+ let out: Result<NotificationResult, anyhow::Error> =
+ res.map(|r| (r, notif.recipient_id.clone(), endpoint.clone()));
+ Some(out)
+ },
+ )
+}
/// Attempts to send push notifications to provided users
/// Returns a list of users who were sent push notifications.
-#[tracing::instrument(skip(db, sns_client, user_ids))]
+#[tracing::instrument(skip(db, sns_client))]
pub async fn process_push_notifications(
db: &sqlx::Pool<sqlx::Postgres>,
sns_client: &sns_client::SNS,
- notifications: &[NotificationWithRecipient],
- user_ids: &HashSet<&String>,
-) -> anyhow::Result<Vec<String>> {
- let user_ids = user_ids
- .iter()
- .map(|user_id| user_id.to_string())
- .collect::<Vec<String>>();
+ notifications: &HashMap<MacroUserIdStr<'static>, Vec<NotificationWithRecipient>>,
+) -> Result<HashSet<MacroUserIdStr<'static>>, anyhow::Error> {
+ let user_ids: Vec<_> = notifications.keys().cloned().collect();
- let user_device_endpoints: HashMap<String, Vec<String>> =
- notification_db_client::device::get_users_device_endpoints(db, &user_ids).await?;
- tracing::trace!(device_endpoints=?user_device_endpoints, "got device endpoints to send push notifications to");
+ let mut user_device_endpoints =
+ notification_db_client::device::get_users_device_endpoints(db, user_ids.as_slice()).await?;
- // create a map where key is recipient_id and value is the push notif to send
- let notification_map = notifications
+ let to_send: HashMap<_, _> = notifications
.iter()
- .filter_map(|n| {
- let push_notification = generate_push_notification(n)
- .context("unable to generate push notification for user")
- .ok()?; // Return None if error
-
- push_notification.map(|pn| (n.recipient_id.clone(), pn))
+ .flat_map(|(user_id, notifs)| {
+ notifs
+ .iter()
+ .filter_map(|notif| {
+ let endpoints = user_device_endpoints.remove(user_id).map(|endpoints| {
+ endpoints
+ .into_iter()
+ .map(|(arn, device)| match device {
+ model_notifications::DeviceType::Ios => DeviceEndpoint::Ios(arn),
+ model_notifications::DeviceType::Android => {
+ DeviceEndpoint::Android(arn)
+ }
+ })
+ .collect::<Vec<_>>()
+ })?;
+ Some((notif, endpoints))
+ })
+ .collect::<Vec<_>>()
})
- .collect::<HashMap<String, _>>();
+ .collect();
- if notification_map.is_empty() {
- // There are no push notifications to send
- return Ok(user_ids.to_vec());
- }
-
- // Goes through each user attempting to send a push notification, returning the user id and
- // PushNotificationStatus
- let result: Vec<(String, PushNotificationStatus)> = futures::stream::iter(
- // Only include items where the user ID exists in notification_map
- user_device_endpoints
- .iter()
- .filter(|(user_id, _)| notification_map.contains_key(*user_id)),
- )
- .then(|(user_id, endpoints)| {
- // safe to unwrap because we filter above
- let push_notification = notification_map.get(user_id).unwrap();
- let message_json = push_notification.0.clone();
- let message_attributes = push_notification.1.clone();
- async move {
- tracing::trace!(user_id=%user_id, "sending push notification");
- if endpoints.is_empty() {
- return (user_id.clone(), PushNotificationStatus::Empty);
- }
- let mut success = false;
-
- // while most users will have 1 endpoint, we need to handle the case where a user
- // has multiple endpoints
- for item in endpoints {
- if let Err(e) = sns_client
- .push_notification(item, &message_json.to_string(), message_attributes.clone())
- .await
- {
- tracing::warn!(error=?e, "unable to send push notification");
- continue;
- }
- // we successfully sent at least one push notification to a user's device
- success = true;
- }
- let status = if success {
- PushNotificationStatus::Success
- } else {
- PushNotificationStatus::Fail
- };
- (user_id.clone(), status)
- }
- })
- .collect::<Vec<_>>()
- .await;
-
- let users_notified = result
- .iter()
- .filter_map(|r| {
- let (user_id, status) = r;
- match status {
- PushNotificationStatus::Success => Some(user_id.clone()),
- PushNotificationStatus::Empty | PushNotificationStatus::Fail => None,
+ let mut users_sent_push = HashSet::new();
+ stream_push_notifs_to_user(sns_client, &to_send)
+ .for_each_concurrent(10, |res| {
+ if let Ok(r) = res.inspect_err(|e| tracing::error!("{e}")) {
+ users_sent_push.insert(r.1);
}
+ async {}
})
- .collect::<Vec<String>>();
-
- Ok(users_notified)
-}
-
-pub enum PushNotificationStatus {
- /// No push notifications were sent
- Empty,
- /// Successfully sent a push notification for the user
- Success,
- /// Failed to send push notifications for the user
- Fail,
+ .await;
+ Ok(users_sent_push)
}
diff --git a/rust/cloud-storage/notification_service/src/notification/send/push/remove.rs b/rust/cloud-storage/notification_service/src/notification/send/push/remove.rs
index 73e909f8f9..3cfed2b30a 100644
--- a/rust/cloud-storage/notification_service/src/notification/send/push/remove.rs
+++ b/rust/cloud-storage/notification_service/src/notification/send/push/remove.rs
@@ -1,14 +1,10 @@
-use std::{
- collections::HashMap,
- hash::{DefaultHasher, Hash, Hasher},
-};
-
+use crate::{api::context::ApiContext, config::APPLE_BUNDLE_ID};
use anyhow::Context;
-use aws_sdk_sns::types::MessageAttributeValue;
use futures::StreamExt;
use notification_db_client::notification::get::BasicNotification;
-
-use crate::{api::context::ApiContext, config::APPLE_BUNDLE_ID};
+use serde::Serialize;
+use sns_client::{APNSPushNotification, MessageAttributes, NotifCollapseKey, PushType, SnsTarget};
+use std::hash::{DefaultHasher, Hash, Hasher};
/// Clears out push notifications for a user in bulk
#[tracing::instrument(skip(ctx))]
@@ -75,46 +71,6 @@ pub fn clear_push_notifications(
Ok(())
}
-/// Builds the message attributes for the remove push notification
-pub fn build_message_attributes(
- collapse_key: &str,
-) -> Option<HashMap<String, MessageAttributeValue>> {
- Some(HashMap::from([
- (
- "AWS.SNS.MOBILE.APNS.TOPIC".to_string(),
- MessageAttributeValue::builder()
- .data_type("String")
- .string_value(&*APPLE_BUNDLE_ID)
- .build()
- .unwrap(),
- ),
- (
- "AWS.SNS.MOBILE.APNS.PUSH_TYPE".to_string(),
- MessageAttributeValue::builder()
- .data_type("String")
- .string_value("background")
- .build()
- .unwrap(),
- ),
- (
- "AWS.SNS.MOBILE.APNS.PRIORITY".to_string(),
- MessageAttributeValue::builder()
- .data_type("String")
- .string_value("5") // 5 is normal, 10 is high
- .build()
- .unwrap(),
- ),
- (
- "AWS.SNS.MOBILE.APNS.COLLAPSE_ID".to_string(),
- MessageAttributeValue::builder()
- .data_type("String")
- .string_value(collapse_key)
- .build()
- .unwrap(),
- ),
- ]))
-}
-
/// When a notification is marked as "done" or "seen" for a user, we need to potentially send a
/// remove notification sns notification to the user to clear it from their device.
#[tracing::instrument(skip(db, sns_client))]
@@ -150,38 +106,37 @@ pub async fn clear_push_notification(
let hash = hasher.finish();
let collapse_key = format!("{:x}", hash);
- let message_attributes = build_message_attributes(&collapse_key);
+ #[derive(Debug, Serialize, Clone)]
+ struct CustomData {
+ identifier: String,
+ }
- let apns = serde_json::json!({
- "aps": {
- "content-available": 1,
+ let apns = SnsTarget::Ios(Box::new(APNSPushNotification {
+ aps: sns_client::Aps {
+ content_available: Some(1),
+ ..Default::default()
},
- "identifier": collapse_key, // The collapse key is needed to identify what notification needs to be cleared
- });
-
- let message_json = serde_json::json!({
- "APNS": serde_json::to_string(&apns).context("could not convert apns to string")?,
- });
+ push_notification_data: CustomData {
+ identifier: collapse_key.clone(),
+ },
+ }));
+ let attributes = MessageAttributes {
+ push_type: PushType::Background,
+ apns_bundle_id: &APPLE_BUNDLE_ID,
+ collapse_key: NotifCollapseKey::new_str(&collapse_key),
+ };
futures::stream::iter(device_endpoints.iter())
- .then(|endpoint| {
- let message_json = message_json.clone();
- let message_attributes = message_attributes.clone();
- async move {
- if !endpoint.contains("APNS") {
- tracing::trace!("skipping non-apns endpoint");
- return;
- }
- if let Err(e) = sns_client
- .push_notification(
- endpoint,
- &message_json.to_string(),
- message_attributes.clone(),
- )
- .await
- {
- tracing::warn!(error=?e, "unable to send push notification");
- }
+ .then(|endpoint| async {
+ if !endpoint.contains("APNS") {
+ tracing::trace!("skipping non-apns endpoint");
+ return;
+ }
+ if let Err(e) = sns_client
+ .push_notification(endpoint, &apns, attributes.clone())
+ .await
+ {
+ tracing::warn!(error=?e, "unable to send push notification");
}
})
.collect::<Vec<_>>()
diff --git a/rust/cloud-storage/notification_service/src/notification/user_data.rs b/rust/cloud-storage/notification_service/src/notification/user_data.rs
index 63e315301a..9f1e211a64 100644
--- a/rust/cloud-storage/notification_service/src/notification/user_data.rs
+++ b/rust/cloud-storage/notification_service/src/notification/user_data.rs
@@ -1,26 +1,28 @@
+use macro_user_id::user_id::MacroUserIdStr;
use model_notifications::{Notification, NotificationWithRecipient, UserNotification};
+use std::collections::HashMap;
// convert the Notification object from a single generic notification to a list of user-specific
// notifications that may have different values depending on the user.
-pub async fn populate_user_data(
+pub fn populate_user_data(
notification: Notification,
- user_ids: &[String],
- is_important: bool,
-) -> Vec<NotificationWithRecipient> {
+ user_ids: &[MacroUserIdStr<'static>],
+) -> HashMap<MacroUserIdStr<'static>, Vec<NotificationWithRecipient>> {
// Determine importance and create new notification object
- let notifications: Vec<NotificationWithRecipient> = user_ids
+ user_ids
.iter()
- .map(|user_id| NotificationWithRecipient {
- inner: UserNotification::from_new_notification(
- notification.clone(),
- is_important,
- false,
- false,
- ),
- recipient_id: user_id.to_string(),
- is_important_v0: is_important,
+ .map(|user_id| {
+ (
+ user_id.clone(),
+ vec![NotificationWithRecipient {
+ inner: UserNotification::from_new_notification(
+ notification.clone(),
+ false,
+ false,
+ ),
+ recipient_id: user_id.clone(),
+ }],
+ )
})
- .collect();
-
- notifications
+ .collect()
}
diff --git a/rust/cloud-storage/notification_service/src/notification_email_poller_worker.rs b/rust/cloud-storage/notification_service/src/notification_email_poller_worker.rs
index 34dc09e94d..a935b539dc 100644
--- a/rust/cloud-storage/notification_service/src/notification_email_poller_worker.rs
+++ b/rust/cloud-storage/notification_service/src/notification_email_poller_worker.rs
@@ -261,7 +261,7 @@ async fn process_user_notifications(
// Filter out notifications where the channel id is in the `channel_notification_email_sent`
let channel_ids = notifications
.iter()
- .map(|n| n.event_item_id.clone())
+ .map(|n| n.entity.entity_id.to_string())
.collect::<Vec<String>>();
tracing::trace!(channel_ids=?channel_ids, "got channel ids");
@@ -273,7 +273,7 @@ async fn process_user_notifications(
let notifications = notifications
.iter()
- .filter(|n| !channel_notification_email_sent.contains(&n.event_item_id))
+ .filter(|n| !channel_notification_email_sent.contains(n.entity.entity_id.as_ref()))
.collect::<Vec<&UnsentNotification>>();
if notifications.is_empty() {
@@ -300,8 +300,8 @@ async fn process_user_notifications(
let notifications = notifications
.into_iter()
.filter(|notification| {
- if user_unsubscribed_channel_ids.contains(&notification.event_item_id) {
- tracing::debug!(notification=?notification, "unsubscribed channel {}", notification.event_item_id);
+ if user_unsubscribed_channel_ids.contains(notification.entity.entity_id.as_ref()) {
+ tracing::debug!(notification=?notification, "unsubscribed channel {}", notification.entity.entity_id);
false
} else {
true
diff --git a/rust/cloud-storage/search_processing_service/src/process/channel.rs b/rust/cloud-storage/search_processing_service/src/process/channel.rs
index c1cd427554..8b45db547f 100644
--- a/rust/cloud-storage/search_processing_service/src/process/channel.rs
+++ b/rust/cloud-storage/search_processing_service/src/process/channel.rs
@@ -1,5 +1,6 @@
use anyhow::Context;
use comms_service_client::CommsServiceClient;
+use mention_utils::parse::{NullXmlFormatter, ParsedXmlText, XmlFormatter};
use opensearch_client::{
OpensearchClient, date_format::EpochSeconds, upsert::channel_message::UpsertChannelMessageArgs,
};
@@ -20,10 +21,9 @@ pub async fn process_channel_message_update(
return Ok(());
}
- let transformed_content =
- mention_utils::remove_mentions_from_content(&channel_message_info.channel_message.content);
+ let parsed = ParsedXmlText::parse(&channel_message_info.channel_message.content)?;
- let transformed_content = transformed_content.trim();
+ let transformed_content = NullXmlFormatter::format_xml_text(parsed);
let upsert_channel_message_args = UpsertChannelMessageArgs {
channel_id: channel_message_info.channel_id.to_string(),
@@ -36,7 +36,7 @@ pub async fn process_channel_message_update(
.map(|id| id.to_string()),
sender_id: channel_message_info.channel_message.sender_id,
mentions: channel_message_info.channel_message.mentions,
- content: transformed_content.to_string(),
+ content: transformed_content.0.trim().to_string(),
created_at_seconds: EpochSeconds::new(
channel_message_info.channel_message.created_at.timestamp(),
)?,
diff --git a/rust/cloud-storage/sns_client/Cargo.toml b/rust/cloud-storage/sns_client/Cargo.toml
index 11bb90d683..f767bf8c73 100644
--- a/rust/cloud-storage/sns_client/Cargo.toml
+++ b/rust/cloud-storage/sns_client/Cargo.toml
@@ -7,3 +7,7 @@ version = "0.1.0"
[dependencies]
anyhow = { workspace = true }
aws-sdk-sns = { workspace = true }
+model-entity = { path = "../model-entity" }
+serde = { workspace = true }
+serde_json = { workspace = true }
+tracing = { workspace = true }
diff --git a/rust/cloud-storage/sns_client/src/lib.rs b/rust/cloud-storage/sns_client/src/lib.rs
index 854c047973..adacc4fa0e 100644
--- a/rust/cloud-storage/sns_client/src/lib.rs
+++ b/rust/cloud-storage/sns_client/src/lib.rs
@@ -1,12 +1,317 @@
-use std::collections::HashMap;
-
-use aws_sdk_sns::operation::publish::PublishOutput;
+use aws_sdk_sns::{operation::publish::PublishOutput, types::MessageAttributeValue};
+use serde::{Serialize, Serializer};
+use std::{borrow::Cow, collections::HashMap};
#[derive(Clone, Debug)]
pub struct SNS {
inner: aws_sdk_sns::Client,
}
+#[derive(Serialize, Debug, Default)]
+#[serde(rename_all = "kebab-case")]
+pub struct Aps {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub alert: Option<Alert>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub badge: Option<u32>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sound: Option<Sound>,
+
+ /// Set to 1 for background/silent notifications
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub content_available: Option<u8>,
+
+ /// Set to 1 to allow Notification Service Extension to modify
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mutable_content: Option<u8>,
+
+ /// Category identifier for actionable notifications
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub category: Option<String>,
+
+ /// Identifier for grouping notifications
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub thread_id: Option<String>,
+
+ /// Relevance score for notification summary (0.0 to 1.0)
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub relevance_score: Option<f64>,
+
+ /// Interruption level: passive, active, time-sensitive, critical
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub interruption_level: Option<InterruptionLevel>,
+}
+
+#[derive(Serialize, Debug)]
+#[serde(untagged)]
+pub enum Alert {
+ Simple(String),
+ Dictionary(AlertDictionary),
+}
+
+#[derive(Serialize, Debug, Default)]
+#[serde(rename_all = "kebab-case")]
+pub struct AlertDictionary {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub title: Option<String>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub subtitle: Option<String>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub body: Option<String>,
+
+ /// Localization key for title
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub title_loc_key: Option<String>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub title_loc_args: Option<Vec<String>>,
+
+ /// Localization key for body
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub loc_key: Option<String>,
+
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub loc_args: Option<Vec<String>>,
+
+ /// Custom launch image filename
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub launch_image: Option<String>,
+}
+
+#[derive(Serialize, Debug)]
+#[serde(untagged)]
+pub enum Sound {
+ Default(String), // Usually "default"
+ Critical(CriticalSound),
+}
+
+#[derive(Serialize, Debug)]
+pub struct CriticalSound {
+ pub critical: u8, // 1 for critical
+ pub name: String,
+ pub volume: f64, // 0.0 to 1.0
+}
+
+#[derive(Serialize, Debug)]
+#[serde(rename_all = "kebab-case")]
+pub enum InterruptionLevel {
+ Passive,
+ Active,
+ TimeSensitive,
+ Critical,
+}
+
+// Your updated struct
+#[derive(Serialize, Debug)]
+#[serde(rename_all = "camelCase")]
+pub struct APNSPushNotification<T> {
+ pub aps: Aps,
+
+ #[serde(flatten)]
+ pub push_notification_data: T,
+}
+
+impl<T> APNSPushNotification<T> {
+ pub fn map<F, U>(self, cb: F) -> APNSPushNotification<U>
+ where
+ F: FnOnce(T) -> U,
+ {
+ let APNSPushNotification {
+ aps,
+ push_notification_data,
+ } = self;
+ APNSPushNotification {
+ aps,
+ push_notification_data: cb(push_notification_data),
+ }
+ }
+}
+
+#[derive(Debug, Serialize)]
+pub struct GCMPushNotification<T> {
+ fcm_v1_message: FCMMessage<T>,
+}
+
+#[derive(Debug, Serialize)]
+pub struct FCMMessage<T> {
+ android: AndroidData,
+ data: T,
+}
+
+impl<T> FCMMessage<T> {
+ /// temporary method since android is currently out of scope for mobile
+ /// this just instantiates a majority blank notif
+ pub fn new_temporary_empty(data: T) -> Self {
+ FCMMessage {
+ android: AndroidData {
+ notification: "Temporary placeholder".to_string(),
+ priority: AndroidNotifPrio::Normal,
+ collapse_key: String::new(),
+ },
+ data,
+ }
+ }
+}
+
+#[derive(Debug, Serialize)]
+enum AndroidNotifPrio {
+ Normal,
+ #[expect(dead_code)]
+ High,
+}
+
+#[derive(Debug, Serialize)]
+pub struct AndroidData {
+ notification: String,
+ priority: AndroidNotifPrio,
+ collapse_key: String,
+}
+
+#[derive(Debug)]
+pub enum SnsTarget<T> {
+ Ios(Box<APNSPushNotification<T>>),
+ Android(FCMMessage<T>),
+}
+
+impl<T> SnsTarget<T> {
+ fn default_string(&self) -> String {
+ match self {
+ SnsTarget::Ios(apnspush_notification) => apnspush_notification
+ .aps
+ .alert
+ .as_ref()
+ .and_then(|a| match a {
+ Alert::Simple(s) => Some(s.clone()),
+ Alert::Dictionary(alert_dictionary) => alert_dictionary.title.clone(),
+ })
+ .unwrap_or(String::new()),
+ SnsTarget::Android(fcmmessage) => fcmmessage.android.notification.clone(),
+ }
+ }
+ fn as_payload(&self) -> SnsPayload<'_, T> {
+ match self {
+ SnsTarget::Ios(apnspush_notification) => SnsPayload::Ios {
+ default: self.default_string(),
+ apns: apnspush_notification,
+ apns_sandbox: apnspush_notification,
+ },
+ SnsTarget::Android(fcmmessage) => SnsPayload::Android {
+ default: self.default_string(),
+ gcm: fcmmessage,
+ },
+ }
+ }
+}
+
+#[derive(Debug, Serialize)]
+#[serde(bound = "T: Serialize", untagged)]
+pub enum SnsPayload<'a, T> {
+ Ios {
+ default: String,
+ #[serde(rename = "APNS", serialize_with = "stringified_json")]
+ apns: &'a APNSPushNotification<T>,
+ #[serde(rename = "APNS_SANDBOX", serialize_with = "stringified_json")]
+ apns_sandbox: &'a APNSPushNotification<T>,
+ },
+ Android {
+ default: String,
+ #[serde(rename = "GCM", serialize_with = "stringified_json")]
+ gcm: &'a FCMMessage<T>,
+ },
+}
+
+fn stringified_json<T, S>(val: &T, ser: S) -> Result<S::Ok, S::Error>
+where
+ S: Serializer,
+ T: Serialize,
+{
+ let s = serde_json::to_string(val).expect("json serialize cant fail");
+ ser.serialize_str(&s)
+}
+
+impl<'a, T> SnsPayload<'a, T>
+where
+ T: Serialize,
+{
+ fn as_json(&self) -> Result<String, serde_json::Error> {
+ serde_json::to_string(self)
+ }
+}
+
+#[derive(Debug, Clone)]
+pub enum PushType {
+ Background,
+ Alert,
+}
+
+impl PushType {
+ fn as_static_str(&self) -> &'static str {
+ match self {
+ PushType::Background => "background",
+ PushType::Alert => "alert",
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct NotifCollapseKey<'a>(pub Cow<'a, str>);
+
+impl<'a> NotifCollapseKey<'a> {
+ pub fn new_str(s: &'a str) -> Self {
+ NotifCollapseKey(Cow::Borrowed(s))
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct MessageAttributes<'a> {
+ pub push_type: PushType,
+ pub apns_bundle_id: &'static str,
+ pub collapse_key: NotifCollapseKey<'a>,
+}
+
+impl<'a> MessageAttributes<'a> {
+ pub fn into_json(self) -> HashMap<String, MessageAttributeValue> {
+ HashMap::from([
+ (
+ "AWS.SNS.MOBILE.APNS.TOPIC".to_string(),
+ MessageAttributeValue::builder()
+ .data_type("String")
+ .string_value(self.apns_bundle_id)
+ .build()
+ .unwrap(),
+ ),
+ (
+ "AWS.SNS.MOBILE.APNS.PUSH_TYPE".to_string(),
+ MessageAttributeValue::builder()
+ .data_type("String")
+ .string_value(self.push_type.as_static_str())
+ .build()
+ .unwrap(),
+ ),
+ (
+ "AWS.SNS.MOBILE.APNS.PRIORITY".to_string(),
+ MessageAttributeValue::builder()
+ .data_type("String")
+ .string_value("5") // 5 is normal, 10 is high
+ .build()
+ .unwrap(),
+ ),
+ (
+ "AWS.SNS.MOBILE.APNS.COLLAPSE_ID".to_string(),
+ MessageAttributeValue::builder()
+ .data_type("String")
+ .string_value(self.collapse_key.0.into_owned())
+ .build()
+ .unwrap(),
+ ),
+ ])
+ }
+}
+
impl SNS {
pub fn new(inner: aws_sdk_sns::Client) -> Self {
Self { inner }
@@ -100,19 +405,23 @@ impl SNS {
///
/// * `Ok(())` if the notification was sent successfully
/// * `Err` if there was an error sending the notification
- pub async fn push_notification(
+ #[tracing::instrument(err, skip(self))]
+ pub async fn push_notification<T>(
&self,
endpoint_arn: &str,
- message_json: &str,
- message_attributes: Option<HashMap<String, aws_sdk_sns::types::MessageAttributeValue>>,
- ) -> anyhow::Result<PublishOutput> {
+ message_json: &SnsTarget<T>,
+ message_attributes: MessageAttributes<'_>,
+ ) -> anyhow::Result<PublishOutput>
+ where
+ T: Serialize + std::fmt::Debug,
+ {
let result = self
.inner
.publish()
.target_arn(endpoint_arn)
.message_structure("json")
- .message(message_json)
- .set_message_attributes(message_attributes)
+ .message(message_json.as_payload().as_json().unwrap())
+ .set_message_attributes(Some(message_attributes.into_json()))
.send()
.await?;