Skip to content

The open alternative to Salesforce, designed for AI.

Subscribe to Teams transcripts in Microsoft Graph when a connection is added (#27586)

nitin6f6fefbc9458
diff --git a/packages/twenty-apps/public/teams/SETUP.md b/packages/twenty-apps/public/teams/SETUP.md
index 3159e4b9375..d35d2875329 100644
--- a/packages/twenty-apps/public/teams/SETUP.md
+++ b/packages/twenty-apps/public/teams/SETUP.md
@@ -52,9 +52,15 @@ three credentials before bot operations can run.
Open **Settings > Applications > Microsoft Teams > Settings**, select
**Add connection**, and sign in with your Microsoft work or school account.
-Connecting an account does not import transcripts or register webhooks. The
-transcript release flag and workspace setting remain off. Connecting an account
-does not enable them.
+The transcript release flag and workspace setting are off by default, and
+connecting an account does not enable them. With both on, connecting an account
+also creates a Microsoft Graph subscription to the transcripts of the meetings
+that account organizes. Graph delivers its notifications to
+`https://<your-twenty-host>/webhooks/server/d62e36e1-82bb-4f78-b2ab-54a31faaafab`,
+so the Twenty server must be reachable from the internet over HTTPS. A
+connection added while transcripts were off has no subscription: reconnect it
+after turning transcripts on. Disconnecting the account or uninstalling the app
+deletes the subscription.
## Test the transcript actions
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-register-connection.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-register-connection.ts
index 0fee3bb9d41..5c0a9f91690 100644
--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-register-connection.ts
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-register-connection.ts
@@ -2,12 +2,32 @@ import { defineLogicFunction } from 'twenty-sdk/define';
import { TEAMS_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER } from 'src/features/chat/constants/universal-identifiers';
import { registerTeamsConnection } from 'src/features/chat/logic-functions/utils/register-teams-connection';
+import { registerTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/register-teams-transcript-subscription';
+
+export const teamsRegisterConnectionHandler = async (payload: {
+ connectedAccountId: string;
+}) => {
+ const [chatRegistration, transcriptRegistration] = await Promise.allSettled([
+ registerTeamsConnection(payload),
+ registerTeamsTranscriptSubscription(payload),
+ ]);
+
+ if (chatRegistration.status === 'rejected') {
+ throw chatRegistration.reason;
+ }
+
+ if (transcriptRegistration.status === 'rejected') {
+ throw transcriptRegistration.reason;
+ }
+
+ return { ...chatRegistration.value, ...transcriptRegistration.value };
+};
export default defineLogicFunction({
universalIdentifier: TEAMS_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER,
name: 'teams-register-connection',
description:
- 'Runs when a Microsoft Teams connection is added. For a workspace-shared connection with chat enabled, reads the Microsoft tenant id from Graph and claims it for this workspace under the server-scoped teams-tenant:<tenant_id> key, so activities from that tenant route here. Personal connections are left alone.',
+ 'Runs when a Microsoft Teams connection is added. For a workspace-shared connection with chat enabled, reads the Microsoft tenant id from Graph and claims it for this workspace under the server-scoped teams-tenant:<tenant_id> key, so activities from that tenant route here. Personal connections are left alone. With transcripts enabled, also subscribes to the transcripts of the meetings the account organizes, so Microsoft Graph notifies the app when one is ready.',
timeoutSeconds: 30,
- handler: registerTeamsConnection,
+ handler: teamsRegisterConnectionHandler,
});
diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-tenant-release.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-tenant-release.ts
index d8427c32f89..f9a4ee40cc9 100644
--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-tenant-release.ts
+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-tenant-release.ts
@@ -2,12 +2,32 @@ import { defineLogicFunction } from 'twenty-sdk/define';
import { TEAMS_TENANT_RELEASE_UNIVERSAL_IDENTIFIER } from 'src/features/chat/constants/universal-identifiers';
import { releaseTeamsConnectionTenant } from 'src/features/chat/logic-functions/utils/release-teams-connection-tenant';
+import { unregisterTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription';
+
+export const teamsTenantReleaseHandler = async (payload: {
+ connectedAccountId: string;
+}) => {
+ const [tenantRelease, transcriptUnregistration] = await Promise.allSettled([
+ releaseTeamsConnectionTenant(payload),
+ unregisterTeamsTranscriptSubscription(payload),
+ ]);
+
+ if (tenantRelease.status === 'rejected') {
+ throw tenantRelease.reason;
+ }
+
+ if (transcriptUnregistration.status === 'rejected') {
+ throw transcriptUnregistration.reason;
+ }
+
+ return { ...tenantRelease.value, ...transcriptUnregistration.value };
+};
export default defineLogicFunction({
universalIdentifier: TEAMS_TENANT_RELEASE_UNIVERSAL_IDENTIFIER,
name: 'teams-tenant-release',
description:
- 'Runs when a Microsoft Teams connection is removed. Releases the teams-tenant:<tenant_id> claim that connection took, unless another connection in this workspace still holds the same tenant, so another workspace can connect it.',
+ 'Runs when a Microsoft Teams connection is removed. Releases the teams-tenant:<tenant_id> claim that connection took, unless another connection in this workspace still holds the same tenant, so another workspace can connect it. Also deletes the Microsoft Graph transcript subscription of that connection.',
timeoutSeconds: 30,
- handler: releaseTeamsConnectionTenant,
+ handler: teamsTenantReleaseHandler,
});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts
index f13161e36b8..e61571d7f7e 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts
@@ -9,3 +9,12 @@ export const TEAMS_LIST_ORGANIZER_TRANSCRIPTS_UNIVERSAL_IDENTIFIER =
export const TEAMS_SYNC_TRANSCRIPT_UNIVERSAL_IDENTIFIER =
'c7772775-d871-428f-960e-a43ca365ba22';
+
+export const TEAMS_TRANSCRIPTS_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER =
+ 'd62e36e1-82bb-4f78-b2ab-54a31faaafab';
+
+export const TEAMS_TRANSCRIPTS_WEBHOOK_UNIVERSAL_IDENTIFIER =
+ 'fa920860-ffe0-4f83-9ea5-3f68f07dc31f';
+
+export const TEAMS_UNINSTALL_UNIVERSAL_IDENTIFIER =
+ '962da060-1263-4892-9bf5-2b0637818de9';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-reauthorization-required-lifecycle-event.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-reauthorization-required-lifecycle-event.ts
new file mode 100644
index 00000000000..d0b9f8aa428
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-reauthorization-required-lifecycle-event.ts
@@ -0,0 +1,2 @@
+export const GRAPH_REAUTHORIZATION_REQUIRED_LIFECYCLE_EVENT =
+ 'reauthorizationRequired';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-subscription-kv-key-prefix.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-subscription-kv-key-prefix.ts
new file mode 100644
index 00000000000..c66907595ed
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-subscription-kv-key-prefix.ts
@@ -0,0 +1,2 @@
+export const TEAMS_TRANSCRIPT_SUBSCRIPTION_KV_KEY_PREFIX =
+ 'teams-transcript-subscription';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-subscription-lifetime-milliseconds.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-subscription-lifetime-milliseconds.ts
new file mode 100644
index 00000000000..f565e368658
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-subscription-lifetime-milliseconds.ts
@@ -0,0 +1,3 @@
+// Graph caps transcript subscriptions at 4,320 minutes; the margin absorbs clock skew.
+export const TEAMS_TRANSCRIPT_SUBSCRIPTION_LIFETIME_MILLISECONDS =
+ (4_320 - 5) * 60 * 1_000;
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcripts-connection-kv-key-prefix.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcripts-connection-kv-key-prefix.ts
new file mode 100644
index 00000000000..39a3ecebd73
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcripts-connection-kv-key-prefix.ts
@@ -0,0 +1,2 @@
+export const TEAMS_TRANSCRIPTS_CONNECTION_KV_KEY_PREFIX =
+ 'teams-transcripts-connection';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcripts-webhook-connection-query-parameter.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcripts-webhook-connection-query-parameter.ts
new file mode 100644
index 00000000000..6bd2e2ea3fd
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcripts-webhook-connection-query-parameter.ts
@@ -0,0 +1,2 @@
+export const TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER =
+ 'connectedAccountId';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook-resolver.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook-resolver.ts
new file mode 100644
index 00000000000..0975c3d6c70
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook-resolver.ts
@@ -0,0 +1,66 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';
+import {
+ kv,
+ Response,
+ type ServerRouteResolverResult,
+} from 'twenty-sdk/logic-function';
+
+import {
+ TEAMS_TRANSCRIPTS_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER,
+ TEAMS_TRANSCRIPTS_WEBHOOK_UNIVERSAL_IDENTIFIER,
+} from 'src/features/transcripts/constants/universal-identifiers';
+import { TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/features/transcripts/logic-functions/constants/teams-transcripts-webhook-connection-query-parameter';
+import { buildTeamsTranscriptsConnectionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcripts-connection-kv-key';
+
+export const teamsTranscriptsWebhookResolverHandler = async (
+ routePayload: RoutePayload<unknown>,
+): Promise<ServerRouteResolverResult> => {
+ const validationToken = routePayload.queryStringParameters?.validationToken;
+
+ // Graph validates the URL before the subscription exists and expects the token back as plain text.
+ if (isNonEmptyString(validationToken)) {
+ return new Response(validationToken, {
+ status: 200,
+ headers: { 'Content-Type': 'text/plain' },
+ });
+ }
+
+ const connectedAccountId =
+ routePayload.queryStringParameters?.[
+ TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER
+ ];
+
+ if (!isNonEmptyString(connectedAccountId)) {
+ return new Response(
+ { error: 'Missing Teams connection identifier' },
+ { status: 400 },
+ );
+ }
+
+ const workspaceId = await kv.get<string>(
+ buildTeamsTranscriptsConnectionKvKey(connectedAccountId),
+ { scope: 'SERVER' },
+ );
+
+ if (!isNonEmptyString(workspaceId)) {
+ return new Response({ error: 'Unknown Teams connection' }, { status: 404 });
+ }
+
+ return {
+ workspaceId,
+ targetLogicFunctionUniversalIdentifier:
+ TEAMS_TRANSCRIPTS_WEBHOOK_UNIVERSAL_IDENTIFIER,
+ payload: routePayload,
+ };
+};
+
+export default defineLogicFunction({
+ universalIdentifier: TEAMS_TRANSCRIPTS_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER,
+ name: 'teams-transcripts-webhook-resolver',
+ description:
+ 'Answers Microsoft Graph endpoint validation and routes transcript subscription notifications to the workspace that claimed the connection named in the query string.',
+ timeoutSeconds: 15,
+ handler: teamsTranscriptsWebhookResolverHandler,
+ serverRouteTriggerSettings: { httpMethods: ['POST'] },
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts
new file mode 100644
index 00000000000..725f162d814
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts
@@ -0,0 +1,93 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';
+import { getConnection, kv } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { FEATURE_FLAGS } from 'src/constants/feature-flags';
+import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';
+import { TEAMS_TRANSCRIPTS_WEBHOOK_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';
+import { GRAPH_REAUTHORIZATION_REQUIRED_LIFECYCLE_EVENT } from 'src/features/transcripts/logic-functions/constants/graph-reauthorization-required-lifecycle-event';
+import { TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/features/transcripts/logic-functions/constants/teams-transcripts-webhook-connection-query-parameter';
+import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/types/teams-transcript-subscription.type';
+import { buildTeamsTranscriptSubscriptionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-subscription-kv-key';
+import { parseTeamsTranscriptSubscriptionNotifications } from 'src/features/transcripts/logic-functions/utils/parse-teams-transcript-subscription-notifications';
+import { renewTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/renew-teams-transcript-subscription';
+import { isFeatureEnabled } from 'src/utils/is-feature-enabled';
+
+type TeamsTranscriptsWebhookResult =
+ | { success: true; expirationDateTime?: string }
+ | { success: true; skipped: true; reason: string }
+ | { success: false; error: string };
+
+export const teamsTranscriptsWebhookHandler = async (
+ routePayload: RoutePayload<unknown>,
+): Promise<TeamsTranscriptsWebhookResult> => {
+ const connectedAccountId =
+ routePayload.queryStringParameters?.[
+ TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER
+ ];
+
+ if (!isNonEmptyString(connectedAccountId)) {
+ return { success: false, error: 'Missing Teams connection identifier' };
+ }
+
+ const subscriptionKvKey =
+ buildTeamsTranscriptSubscriptionKvKey(connectedAccountId);
+ const subscription =
+ await kv.get<TeamsTranscriptSubscription>(subscriptionKvKey);
+
+ if (!isDefined(subscription)) {
+ return { success: false, error: 'Unknown Teams transcript subscription' };
+ }
+
+ const notifications = parseTeamsTranscriptSubscriptionNotifications({
+ body: routePayload.body,
+ subscription,
+ });
+
+ if (!isDefined(notifications)) {
+ return { success: false, error: 'Invalid Microsoft Graph notification' };
+ }
+
+ const isReauthorizationRequired = notifications.some(
+ (notification) =>
+ notification.lifecycleEvent ===
+ GRAPH_REAUTHORIZATION_REQUIRED_LIFECYCLE_EVENT,
+ );
+
+ if (!isReauthorizationRequired) {
+ return { success: true };
+ }
+
+ if (
+ !isFeatureEnabled({
+ isAvailable: FEATURE_FLAGS.IS_TRANSCRIPT_IMPORT_ENABLED,
+ settingValue: process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY],
+ })
+ ) {
+ return {
+ success: true,
+ skipped: true,
+ reason: 'Teams transcripts are not enabled',
+ };
+ }
+
+ const { accessToken } = await getConnection(connectedAccountId);
+ const expirationDateTime = await renewTeamsTranscriptSubscription({
+ accessToken,
+ subscriptionId: subscription.subscriptionId,
+ });
+
+ await kv.set(subscriptionKvKey, { ...subscription, expirationDateTime });
+
+ return { success: true, expirationDateTime };
+};
+
+export default defineLogicFunction({
+ universalIdentifier: TEAMS_TRANSCRIPTS_WEBHOOK_UNIVERSAL_IDENTIFIER,
+ name: 'teams-transcripts-webhook',
+ description:
+ 'Checks Microsoft Graph transcript notifications against the subscription stored for the connection, and renews the subscription when Graph asks for reauthorization.',
+ timeoutSeconds: 60,
+ handler: teamsTranscriptsWebhookHandler,
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-uninstall.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-uninstall.ts
new file mode 100644
index 00000000000..3ff7533ac9b
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-uninstall.ts
@@ -0,0 +1,36 @@
+import { defineUninstallLogicFunction } from 'twenty-sdk/define';
+import { listConnections } from 'twenty-sdk/logic-function';
+
+import { TEAMS_PROVIDER_NAME } from 'src/features/transcripts/constants/teams-provider-name';
+import { TEAMS_UNINSTALL_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';
+import { unregisterTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription';
+
+export const teamsUninstallHandler = async (): Promise<{
+ failedConnectionCount: number;
+}> => {
+ const connections = await listConnections({
+ providerName: TEAMS_PROVIDER_NAME,
+ });
+ const results = await Promise.allSettled(
+ connections.map((connection) =>
+ unregisterTeamsTranscriptSubscription({
+ connectedAccountId: connection.id,
+ }),
+ ),
+ );
+
+ return {
+ failedConnectionCount: results.filter(
+ (result) => result.status === 'rejected',
+ ).length,
+ };
+};
+
+export default defineUninstallLogicFunction({
+ universalIdentifier: TEAMS_UNINSTALL_UNIVERSAL_IDENTIFIER,
+ name: 'teams-uninstall',
+ description:
+ 'Deletes the Microsoft Graph transcript subscription of every Teams connection when the app is uninstalled.',
+ timeoutSeconds: 60,
+ handler: teamsUninstallHandler,
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-change-notification.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-change-notification.type.ts
new file mode 100644
index 00000000000..6e54648b703
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-change-notification.type.ts
@@ -0,0 +1,7 @@
+export type GraphChangeNotification = {
+ subscriptionId?: unknown;
+ clientState?: unknown;
+ changeType?: unknown;
+ resource?: unknown;
+ lifecycleEvent?: unknown;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-request-method.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-request-method.type.ts
new file mode 100644
index 00000000000..070d42f576c
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-request-method.type.ts
@@ -0,0 +1 @@
+export type GraphRequestMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE';
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-subscription.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-subscription.type.ts
new file mode 100644
index 00000000000..b7618c9617d
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/graph-subscription.type.ts
@@ -0,0 +1,4 @@
+export type GraphSubscription = {
+ id?: unknown;
+ expirationDateTime?: unknown;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-subscription.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-subscription.type.ts
new file mode 100644
index 00000000000..2d2183d9029
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-subscription.type.ts
@@ -0,0 +1,5 @@
+export type TeamsTranscriptSubscription = {
+ subscriptionId: string;
+ clientState: string;
+ expirationDateTime: string;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/parse-teams-transcript-subscription-notifications.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/parse-teams-transcript-subscription-notifications.test.ts
new file mode 100644
index 00000000000..367d4e3f58a
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/parse-teams-transcript-subscription-notifications.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, it } from 'vitest';
+
+import { parseTeamsTranscriptSubscriptionNotifications } from 'src/features/transcripts/logic-functions/utils/parse-teams-transcript-subscription-notifications';
+
+const SUBSCRIPTION = {
+ subscriptionId: '516220d0-0f88-46cc-ac39-02b687687526',
+ clientState: 'q3N9Hk2xYqk7aWb0p1sTqgk4jXv8dLr2mZc6eFh5uIo',
+};
+
+const TRANSCRIPT_NOTIFICATION = {
+ subscriptionId: SUBSCRIPTION.subscriptionId,
+ clientState: SUBSCRIPTION.clientState,
+ changeType: 'created',
+ resource:
+ "users/976f4b31-fd01-4e0b-9178-29cc40c14438/onlineMeetings('MSo1')/transcripts('MSM1')",
+};
+
+const REAUTHORIZATION_NOTIFICATION = {
+ subscriptionId: SUBSCRIPTION.subscriptionId,
+ clientState: SUBSCRIPTION.clientState,
+ lifecycleEvent: 'reauthorizationRequired',
+};
+
+describe('parseTeamsTranscriptSubscriptionNotifications', () => {
+ it('should return every notification when all of them carry the subscription credentials', () => {
+ expect(
+ parseTeamsTranscriptSubscriptionNotifications({
+ body: {
+ value: [TRANSCRIPT_NOTIFICATION, REAUTHORIZATION_NOTIFICATION],
+ },
+ subscription: SUBSCRIPTION,
+ }),
+ ).toEqual([TRANSCRIPT_NOTIFICATION, REAUTHORIZATION_NOTIFICATION]);
+ });
+
+ it('should reject the whole delivery when one notification has another client state', () => {
+ expect(
+ parseTeamsTranscriptSubscriptionNotifications({
+ body: {
+ value: [
+ TRANSCRIPT_NOTIFICATION,
+ { ...REAUTHORIZATION_NOTIFICATION, clientState: 'forged' },
+ ],
+ },
+ subscription: SUBSCRIPTION,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('should reject a notification for another subscription or without a client state', () => {
+ expect(
+ parseTeamsTranscriptSubscriptionNotifications({
+ body: {
+ value: [{ ...TRANSCRIPT_NOTIFICATION, subscriptionId: 'other' }],
+ },
+ subscription: SUBSCRIPTION,
+ }),
+ ).toBeUndefined();
+ expect(
+ parseTeamsTranscriptSubscriptionNotifications({
+ body: {
+ value: [{ ...TRANSCRIPT_NOTIFICATION, clientState: undefined }],
+ },
+ subscription: SUBSCRIPTION,
+ }),
+ ).toBeUndefined();
+ });
+
+ it('should reject a body that is not a Graph notification collection', () => {
+ expect(
+ parseTeamsTranscriptSubscriptionNotifications({
+ body: TRANSCRIPT_NOTIFICATION,
+ subscription: SUBSCRIPTION,
+ }),
+ ).toBeUndefined();
+ expect(
+ parseTeamsTranscriptSubscriptionNotifications({
+ body: { value: ['not a notification'] },
+ subscription: SUBSCRIPTION,
+ }),
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcript-subscription-kv-key.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcript-subscription-kv-key.ts
new file mode 100644
index 00000000000..6b3f917625d
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcript-subscription-kv-key.ts
@@ -0,0 +1,6 @@
+import { TEAMS_TRANSCRIPT_SUBSCRIPTION_KV_KEY_PREFIX } from 'src/features/transcripts/logic-functions/constants/teams-transcript-subscription-kv-key-prefix';
+
+export const buildTeamsTranscriptSubscriptionKvKey = (
+ connectedAccountId: string,
+): string =>
+ `${TEAMS_TRANSCRIPT_SUBSCRIPTION_KV_KEY_PREFIX}:${connectedAccountId}`;
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-connection-kv-key.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-connection-kv-key.ts
new file mode 100644
index 00000000000..fe1c57faa6b
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-connection-kv-key.ts
@@ -0,0 +1,6 @@
+import { TEAMS_TRANSCRIPTS_CONNECTION_KV_KEY_PREFIX } from 'src/features/transcripts/logic-functions/constants/teams-transcripts-connection-kv-key-prefix';
+
+export const buildTeamsTranscriptsConnectionKvKey = (
+ connectedAccountId: string,
+): string =>
+ `${TEAMS_TRANSCRIPTS_CONNECTION_KV_KEY_PREFIX}:${connectedAccountId}`;
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-webhook-url.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-webhook-url.ts
new file mode 100644
index 00000000000..4aa938dc7f1
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcripts-webhook-url.ts
@@ -0,0 +1,21 @@
+import { TEAMS_TRANSCRIPTS_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';
+import { TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/features/transcripts/logic-functions/constants/teams-transcripts-webhook-connection-query-parameter';
+
+export const buildTeamsTranscriptsWebhookUrl = ({
+ apiUrl,
+ connectedAccountId,
+}: {
+ apiUrl: string;
+ connectedAccountId: string;
+}): string => {
+ const webhookUrl = new URL(apiUrl);
+ const apiBasePath = webhookUrl.pathname.replace(/\/+$/, '');
+
+ webhookUrl.pathname = `${apiBasePath}/webhooks/server/${TEAMS_TRANSCRIPTS_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER}`;
+ webhookUrl.searchParams.set(
+ TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER,
+ connectedAccountId,
+ );
+
+ return webhookUrl.toString();
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/create-teams-transcript-subscription.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/create-teams-transcript-subscription.ts
new file mode 100644
index 00000000000..0f094c3a595
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/create-teams-transcript-subscription.ts
@@ -0,0 +1,57 @@
+import { randomBytes } from 'node:crypto';
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { TEAMS_TRANSCRIPT_SUBSCRIPTION_LIFETIME_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-transcript-subscription-lifetime-milliseconds';
+import { type GraphSubscription } from 'src/features/transcripts/logic-functions/types/graph-subscription.type';
+import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/types/teams-transcript-subscription.type';
+import { fetchGraphJson } from 'src/features/transcripts/logic-functions/utils/fetch-graph-json';
+
+export const createTeamsTranscriptSubscription = async ({
+ accessToken,
+ notificationUrl,
+}: {
+ accessToken: string;
+ notificationUrl: string;
+}): Promise<TeamsTranscriptSubscription> => {
+ const user = await fetchGraphJson<{ id?: unknown }>({
+ accessToken,
+ url: 'me?$select=id',
+ });
+
+ if (!isNonEmptyString(user.id)) {
+ throw new Error('Microsoft Graph returned no user for the connection');
+ }
+
+ const clientState = randomBytes(32).toString('base64url');
+ const subscription = await fetchGraphJson<GraphSubscription>({
+ accessToken,
+ url: 'subscriptions',
+ method: 'POST',
+ body: {
+ changeType: 'created',
+ notificationUrl,
+ lifecycleNotificationUrl: notificationUrl,
+ resource: `users/${user.id}/onlineMeetings/getAllTranscripts`,
+ includeResourceData: false,
+ expirationDateTime: new Date(
+ Date.now() + TEAMS_TRANSCRIPT_SUBSCRIPTION_LIFETIME_MILLISECONDS,
+ ).toISOString(),
+ clientState,
+ },
+ });
+
+ if (
+ !isNonEmptyString(subscription.id) ||
+ !isNonEmptyString(subscription.expirationDateTime)
+ ) {
+ throw new Error(
+ 'Microsoft Graph returned an invalid transcript subscription',
+ );
+ }
+
+ return {
+ subscriptionId: subscription.id,
+ clientState,
+ expirationDateTime: subscription.expirationDateTime,
+ };
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/delete-teams-transcript-subscription.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/delete-teams-transcript-subscription.ts
new file mode 100644
index 00000000000..74c0a1dc0de
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/delete-teams-transcript-subscription.ts
@@ -0,0 +1,25 @@
+import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';
+import { fetchGraphResponse } from 'src/features/transcripts/logic-functions/utils/fetch-graph-response';
+
+export const deleteTeamsTranscriptSubscription = async ({
+ accessToken,
+ subscriptionId,
+}: {
+ accessToken: string;
+ subscriptionId: string;
+}): Promise<void> => {
+ try {
+ await fetchGraphResponse({
+ accessToken,
+ url: `subscriptions/${encodeURIComponent(subscriptionId)}`,
+ accept: 'application/json',
+ method: 'DELETE',
+ });
+ } catch (error) {
+ if (error instanceof GraphRequestError && error.status === 404) {
+ return;
+ }
+
+ throw error;
+ }
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-json.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-json.ts
index 6c7989d6945..36f5da28117 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-json.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-json.ts
@@ -1,19 +1,26 @@
+import { type GraphRequestMethod } from 'src/features/transcripts/logic-functions/types/graph-request-method.type';
import { fetchGraphResponse } from 'src/features/transcripts/logic-functions/utils/fetch-graph-response';
export const fetchGraphJson = async <TResponse>({
accessToken,
url,
+ method,
+ body,
}: {
accessToken: string;
url: string;
+ method?: GraphRequestMethod;
+ body?: object;
}): Promise<TResponse> => {
const response = await fetchGraphResponse({
accessToken,
url,
accept: 'application/json',
+ method,
+ body,
});
- const body: TResponse = await response.json();
+ const responseBody: TResponse = await response.json();
- return body;
+ return responseBody;
};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-response.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-response.ts
index 56e15113ae9..66ab4d7cef5 100644
--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-response.ts
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/fetch-graph-response.ts
@@ -1,9 +1,11 @@
import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-sdk/utils';
import { GRAPH_REQUEST_MAX_ATTEMPTS } from 'src/features/transcripts/logic-functions/constants/graph-request-max-attempts';
import { GRAPH_REQUEST_RETRY_BASE_DELAY_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/graph-request-retry-base-delay-milliseconds';
import { GRAPH_RETRYABLE_STATUSES } from 'src/features/transcripts/logic-functions/constants/graph-retryable-statuses';
import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';
+import { type GraphRequestMethod } from 'src/features/transcripts/logic-functions/types/graph-request-method.type';
import { resolveGraphUrlOrThrow } from 'src/features/transcripts/logic-functions/utils/resolve-graph-url-or-throw';
import { sleepForMilliseconds } from 'src/features/transcripts/logic-functions/utils/sleep-for-milliseconds';
@@ -14,23 +16,31 @@ type GraphErrorBody = {
};
};
+type GraphRequest = {
+ accessToken: string;
+ url: string;
+ accept: string;
+ method?: GraphRequestMethod;
+ body?: object;
+};
+
const fetchGraphResponseWithRetries = async ({
accessToken,
url,
accept,
+ method,
+ body,
attempt,
-}: {
- accessToken: string;
- url: string;
- accept: string;
- attempt: number;
-}): Promise<Response> => {
+}: GraphRequest & { attempt: number }): Promise<Response> => {
const response = await fetch(url, {
+ method,
redirect: 'error',
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: accept,
+ ...(isDefined(body) ? { 'Content-Type': 'application/json' } : {}),
},
+ body: isDefined(body) ? JSON.stringify(body) : undefined,
});
if (response.ok) {
@@ -53,16 +63,18 @@ const fetchGraphResponseWithRetries = async ({
accessToken,
url,
accept,
+ method,
+ body,
attempt: attempt + 1,
});
}
- const body: GraphErrorBody = await response.json().catch(() => ({}));
- const innerErrorCode = isNonEmptyString(body.error?.innerError?.code)
- ? body.error.innerError.code
+ const errorBody: GraphErrorBody = await response.json().catch(() => ({}));
+ const innerErrorCode = isNonEmptyString(errorBody.error?.innerError?.code)
+ ? errorBody.error.innerError.code
: undefined;
- const message = isNonEmptyString(body.error?.message)
- ? body.error.message
+ const message = isNonEmptyString(errorBody.error?.message)
+ ? errorBody.error.message
: response.statusText;
throw new GraphRequestError({
@@ -73,17 +85,11 @@ const fetchGraphResponseWithRetries = async ({
};
export const fetchGraphResponse = ({
- accessToken,
url,
- accept,
-}: {
- accessToken: string;
- url: string;
- accept: string;
-}): Promise<Response> =>
+ ...request
+}: GraphRequest): Promise<Response> =>
fetchGraphResponseWithRetries({
- accessToken,
+ ...request,
url: resolveGraphUrlOrThrow(url),
- accept,
attempt: 0,
});
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/parse-teams-transcript-subscription-notifications.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/parse-teams-transcript-subscription-notifications.ts
new file mode 100644
index 00000000000..f303dfbe1a0
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/parse-teams-transcript-subscription-notifications.ts
@@ -0,0 +1,59 @@
+import { timingSafeEqual } from 'node:crypto';
+import { isNonEmptyString, isObject } from '@sniptt/guards';
+
+import { type GraphChangeNotification } from 'src/features/transcripts/logic-functions/types/graph-change-notification.type';
+import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/types/teams-transcript-subscription.type';
+
+type SubscriptionCredentials = Pick<
+ TeamsTranscriptSubscription,
+ 'subscriptionId' | 'clientState'
+>;
+
+const isMatchingClientState = (
+ receivedClientState: unknown,
+ expectedClientState: string,
+): boolean => {
+ if (!isNonEmptyString(receivedClientState)) {
+ return false;
+ }
+
+ const received = Buffer.from(receivedClientState);
+ const expected = Buffer.from(expectedClientState);
+
+ return (
+ received.length === expected.length && timingSafeEqual(received, expected)
+ );
+};
+
+const isSubscriptionNotification = (
+ notification: unknown,
+ subscription: SubscriptionCredentials,
+): notification is GraphChangeNotification =>
+ isObject<Record<string, unknown>, unknown>(notification) &&
+ notification.subscriptionId === subscription.subscriptionId &&
+ isMatchingClientState(notification.clientState, subscription.clientState);
+
+export const parseTeamsTranscriptSubscriptionNotifications = ({
+ body,
+ subscription,
+}: {
+ body: unknown;
+ subscription: SubscriptionCredentials;
+}): GraphChangeNotification[] | undefined => {
+ if (
+ !isObject<Record<string, unknown>, unknown>(body) ||
+ !Array.isArray(body.value)
+ ) {
+ return undefined;
+ }
+
+ const notifications: unknown[] = body.value;
+ const subscriptionNotifications = notifications.filter(
+ (notification): notification is GraphChangeNotification =>
+ isSubscriptionNotification(notification, subscription),
+ );
+
+ return subscriptionNotifications.length === notifications.length
+ ? subscriptionNotifications
+ : undefined;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/register-teams-transcript-subscription.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/register-teams-transcript-subscription.ts
new file mode 100644
index 00000000000..48f4554f7ac
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/register-teams-transcript-subscription.ts
@@ -0,0 +1,132 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { getConnection, kv, listConnections } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { FEATURE_FLAGS } from 'src/constants/feature-flags';
+import { TEAMS_PROVIDER_NAME } from 'src/features/transcripts/constants/teams-provider-name';
+import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';
+import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';
+import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/types/teams-transcript-subscription.type';
+import { buildTeamsTranscriptSubscriptionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-subscription-kv-key';
+import { buildTeamsTranscriptsConnectionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcripts-connection-kv-key';
+import { buildTeamsTranscriptsWebhookUrl } from 'src/features/transcripts/logic-functions/utils/build-teams-transcripts-webhook-url';
+import { createTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/create-teams-transcript-subscription';
+import { deleteTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/delete-teams-transcript-subscription';
+import { renewTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/renew-teams-transcript-subscription';
+import { unregisterTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription';
+import { isFeatureEnabled } from 'src/utils/is-feature-enabled';
+
+const renewStoredSubscriptionOrUndefined = async ({
+ accessToken,
+ subscriptionKvKey,
+ subscription,
+}: {
+ accessToken: string;
+ subscriptionKvKey: string;
+ subscription: TeamsTranscriptSubscription;
+}): Promise<TeamsTranscriptSubscription | undefined> => {
+ try {
+ const expirationDateTime = await renewTeamsTranscriptSubscription({
+ accessToken,
+ subscriptionId: subscription.subscriptionId,
+ });
+ const renewedSubscription = { ...subscription, expirationDateTime };
+
+ await kv.set(subscriptionKvKey, renewedSubscription);
+
+ return renewedSubscription;
+ } catch (error) {
+ if (error instanceof GraphRequestError && error.status === 404) {
+ return undefined;
+ }
+
+ throw error;
+ }
+};
+
+const isTeamsConnectionListed = async (
+ connectedAccountId: string,
+): Promise<boolean> =>
+ (await listConnections({ providerName: TEAMS_PROVIDER_NAME })).some(
+ (connection) => connection.id === connectedAccountId,
+ );
+
+export const registerTeamsTranscriptSubscription = async ({
+ connectedAccountId,
+}: {
+ connectedAccountId: string;
+}): Promise<{ transcriptSubscriptionId: string | null }> => {
+ const isTranscriptImportEnabled = isFeatureEnabled({
+ isAvailable: FEATURE_FLAGS.IS_TRANSCRIPT_IMPORT_ENABLED,
+ settingValue: process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY],
+ });
+
+ if (!isTranscriptImportEnabled) {
+ await unregisterTeamsTranscriptSubscription({ connectedAccountId });
+
+ return { transcriptSubscriptionId: null };
+ }
+
+ const apiUrl = process.env.TWENTY_API_URL;
+
+ if (!isNonEmptyString(apiUrl)) {
+ throw new Error(
+ 'TWENTY_API_URL is required to subscribe to Teams transcripts',
+ );
+ }
+
+ const subscriptionKvKey =
+ buildTeamsTranscriptSubscriptionKvKey(connectedAccountId);
+ const connectionKvKey =
+ buildTeamsTranscriptsConnectionKvKey(connectedAccountId);
+ const storedSubscription =
+ await kv.get<TeamsTranscriptSubscription>(subscriptionKvKey);
+ const { accessToken } = await getConnection(connectedAccountId);
+
+ const renewedSubscription = isDefined(storedSubscription)
+ ? await renewStoredSubscriptionOrUndefined({
+ accessToken,
+ subscriptionKvKey,
+ subscription: storedSubscription,
+ })
+ : undefined;
+
+ if (isDefined(renewedSubscription)) {
+ return { transcriptSubscriptionId: renewedSubscription.subscriptionId };
+ }
+
+ await kv.set(connectionKvKey, null, { scope: 'SERVER' });
+
+ const subscription = await createTeamsTranscriptSubscription({
+ accessToken,
+ notificationUrl: buildTeamsTranscriptsWebhookUrl({
+ apiUrl,
+ connectedAccountId,
+ }),
+ });
+
+ try {
+ await kv.set(subscriptionKvKey, subscription);
+ } catch (error) {
+ await deleteTeamsTranscriptSubscription({
+ accessToken,
+ subscriptionId: subscription.subscriptionId,
+ });
+
+ throw error;
+ }
+
+ // A disconnect during the Graph call found nothing to delete, so the new subscription is dropped here.
+ if (!(await isTeamsConnectionListed(connectedAccountId))) {
+ await deleteTeamsTranscriptSubscription({
+ accessToken,
+ subscriptionId: subscription.subscriptionId,
+ });
+ await kv.delete(subscriptionKvKey);
+ await kv.delete(connectionKvKey, { scope: 'SERVER' });
+
+ return { transcriptSubscriptionId: null };
+ }
+
+ return { transcriptSubscriptionId: subscription.subscriptionId };
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/renew-teams-transcript-subscription.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/renew-teams-transcript-subscription.ts
new file mode 100644
index 00000000000..42a840cbaee
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/renew-teams-transcript-subscription.ts
@@ -0,0 +1,32 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
+import { TEAMS_TRANSCRIPT_SUBSCRIPTION_LIFETIME_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-transcript-subscription-lifetime-milliseconds';
+import { type GraphSubscription } from 'src/features/transcripts/logic-functions/types/graph-subscription.type';
+import { fetchGraphJson } from 'src/features/transcripts/logic-functions/utils/fetch-graph-json';
+
+export const renewTeamsTranscriptSubscription = async ({
+ accessToken,
+ subscriptionId,
+}: {
+ accessToken: string;
+ subscriptionId: string;
+}): Promise<string> => {
+ const subscription = await fetchGraphJson<GraphSubscription>({
+ accessToken,
+ url: `subscriptions/${encodeURIComponent(subscriptionId)}`,
+ method: 'PATCH',
+ body: {
+ expirationDateTime: new Date(
+ Date.now() + TEAMS_TRANSCRIPT_SUBSCRIPTION_LIFETIME_MILLISECONDS,
+ ).toISOString(),
+ },
+ });
+
+ if (!isNonEmptyString(subscription.expirationDateTime)) {
+ throw new Error(
+ 'Microsoft Graph returned an invalid transcript subscription',
+ );
+ }
+
+ return subscription.expirationDateTime;
+};
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription.ts
new file mode 100644
index 00000000000..90247786384
--- /dev/null
+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription.ts
@@ -0,0 +1,47 @@
+import { getConnection, kv } from 'twenty-sdk/logic-function';
+import { isDefined } from 'twenty-sdk/utils';
+
+import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/types/teams-transcript-subscription.type';
+import { buildTeamsTranscriptSubscriptionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-subscription-kv-key';
+import { buildTeamsTranscriptsConnectionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcripts-connection-kv-key';
+import { deleteTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/delete-teams-transcript-subscription';
+import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';
+
+export const unregisterTeamsTranscriptSubscription = async ({
+ connectedAccountId,
+}: {
+ connectedAccountId: string;
+}): Promise<{ deletedTranscriptSubscriptionId: string | null }> => {
+ const subscriptionKvKey =
+ buildTeamsTranscriptSubscriptionKvKey(connectedAccountId);
+ const connectionKvKey =
+ buildTeamsTranscriptsConnectionKvKey(connectedAccountId);
+ const subscription =
+ await kv.get<TeamsTranscriptSubscription>(subscriptionKvKey);
+
+ if (!isDefined(subscription)) {
+ await kv.delete(connectionKvKey, { scope: 'SERVER' });
+
+ return { deletedTranscriptSubscriptionId: null };
+ }
+
+ try {
+ const { accessToken } = await getConnection(connectedAccountId);
+
+ await deleteTeamsTranscriptSubscription({
+ accessToken,
+ subscriptionId: subscription.subscriptionId,
+ });
+ } catch (error) {
+ console.error(
+ `[teams] leaked transcript subscription ${subscription.subscriptionId} for connected account ${connectedAccountId}: ${toErrorMessage(error)}`,
+ );
+
+ throw error;
+ } finally {
+ await kv.delete(subscriptionKvKey);
+ await kv.delete(connectionKvKey, { scope: 'SERVER' });
+ }
+
+ return { deletedTranscriptSubscriptionId: subscription.subscriptionId };
+};