-
Notifications
You must be signed in to change notification settings - Fork 460
Expand file tree
/
Copy pathMicrosoftTeams.ts
More file actions
3488 lines (3073 loc) · 110 KB
/
Copy pathMicrosoftTeams.ts
File metadata and controls
3488 lines (3073 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { WorkspaceChannelMessage } from "../Workspace";
import HTTPErrorResponse from "../../../../Types/API/HTTPErrorResponse";
import HTTPResponse from "../../../../Types/API/HTTPResponse";
import URL from "../../../../Types/API/URL";
import { JSONObject } from "../../../../Types/JSON";
import API from "../../../../Utils/API";
import WorkspaceMessagePayload, {
WorkspaceCheckboxBlock,
WorkspaceDateTimePickerBlock,
WorkspaceDropdownBlock,
WorkspaceMessageBlock,
WorkspaceMessagePayloadButton,
WorkspaceModalBlock,
WorkspacePayloadButtons,
WorkspacePayloadHeader,
WorkspacePayloadImage,
WorkspacePayloadMarkdown,
WorkspaceTextAreaBlock,
WorkspaceTextBoxBlock,
} from "../../../../Types/Workspace/WorkspaceMessagePayload";
import logger from "../../Logger";
import Dictionary from "../../../../Types/Dictionary";
import WorkspaceBase, {
WorkspaceChannel,
WorkspaceSendMessageResponse,
WorkspaceThread,
} from "../WorkspaceBase";
import WorkspaceType from "../../../../Types/Workspace/WorkspaceType";
import CaptureSpan from "../../Telemetry/CaptureSpan";
import BadDataException from "../../../../Types/Exception/BadDataException";
import ObjectID from "../../../../Types/ObjectID";
import WorkspaceProjectAuthTokenService from "../../../Services/WorkspaceProjectAuthTokenService";
import WorkspaceProjectAuthToken, {
MicrosoftTeamsMiscData,
} from "../../../../Models/DatabaseModels/WorkspaceProjectAuthToken";
import Incident from "../../../../Models/DatabaseModels/Incident";
import IncidentState from "../../../../Models/DatabaseModels/IncidentState";
import Alert from "../../../../Models/DatabaseModels/Alert";
import AlertState from "../../../../Models/DatabaseModels/AlertState";
import ScheduledMaintenance from "../../../../Models/DatabaseModels/ScheduledMaintenance";
import Monitor from "../../../../Models/DatabaseModels/Monitor";
import OneUptimeDate from "../../../../Types/Date";
import {
MicrosoftTeamsAppClientId,
MicrosoftTeamsAppClientSecret,
MicrosoftTeamsAppTenantId,
} from "../../../EnvironmentConfig";
// Import services for bot commands
import IncidentService from "../../../Services/IncidentService";
import AlertService from "../../../Services/AlertService";
import ScheduledMaintenanceService from "../../../Services/ScheduledMaintenanceService";
import IncidentStateService from "../../../Services/IncidentStateService";
import AlertStateService from "../../../Services/AlertStateService";
// Import user services
import User from "../../../../Models/DatabaseModels/User";
import UserService from "../../../Services/UserService";
import WorkspaceUserAuthToken from "../../../../Models/DatabaseModels/WorkspaceUserAuthToken";
import WorkspaceUserAuthTokenService from "../../../Services/WorkspaceUserAuthTokenService";
// Import database utilities
import QueryHelper from "../../../Types/Database/QueryHelper";
import SortOrder from "../../../../Types/BaseDatabase/SortOrder";
// Bot Framework SDK imports
import {
CloudAdapter,
ConfigurationBotFrameworkAuthentication,
TeamsActivityHandler,
TurnContext,
ConversationReference,
MessageFactory,
ConfigurationBotFrameworkAuthenticationOptions,
Activity,
ResourceResponse,
} from "botbuilder";
import { ExpressRequest, ExpressResponse } from "../../Express";
// Teams action handlers and types
import MicrosoftTeamsAuthAction, {
MicrosoftTeamsRequest,
} from "./Actions/Auth";
import MicrosoftTeamsIncidentActions from "./Actions/Incident";
import {
MicrosoftTeamsActionType,
MicrosoftTeamsScheduledMaintenanceActionType,
MicrosoftTeamsOnCallDutyActionType,
} from "./Actions/ActionTypes";
import MicrosoftTeamsAlertActions from "./Actions/Alert";
import MicrosoftTeamsAlertEpisodeActions from "./Actions/AlertEpisode";
import MicrosoftTeamsIncidentEpisodeActions from "./Actions/IncidentEpisode";
import MicrosoftTeamsMonitorActions from "./Actions/Monitor";
import MicrosoftTeamsScheduledMaintenanceActions from "./Actions/ScheduledMaintenance";
import MicrosoftTeamsOnCallDutyActions from "./Actions/OnCallDutyPolicy";
// Microsoft Teams apps should always be single-tenant
const MICROSOFT_TEAMS_APP_TYPE: string = "SingleTenant";
// Maximum number of pages to fetch when paginating teams
const MICROSOFT_TEAMS_MAX_PAGES: number = 500;
export default class MicrosoftTeamsUtil extends WorkspaceBase {
private static cachedAdapter: CloudAdapter | null = null;
private static readonly WELCOME_CARD_STATE_KEY: string =
"oneuptime.microsoftTeams.welcomeCardSent";
// Get or create Bot Framework adapter for a specific tenant
private static getBotAdapter(): CloudAdapter {
if (this.cachedAdapter) {
return this.cachedAdapter;
}
if (!MicrosoftTeamsAppClientId || !MicrosoftTeamsAppClientSecret) {
throw new BadDataException(
"Microsoft Teams App credentials not configured",
);
}
if (!MicrosoftTeamsAppTenantId) {
throw new BadDataException(
"Microsoft Teams app tenant ID is not configured",
);
}
logger.debug(
"Creating Bot Framework adapter with authentication configuration",
);
logger.debug(`App ID: ${MicrosoftTeamsAppClientId}`);
logger.debug(`App Type: ${MICROSOFT_TEAMS_APP_TYPE}`);
logger.debug(`Tenant ID: ${MicrosoftTeamsAppTenantId}`);
const authConfig: ConfigurationBotFrameworkAuthenticationOptions = {
MicrosoftAppId: MicrosoftTeamsAppClientId,
MicrosoftAppPassword: MicrosoftTeamsAppClientSecret,
MicrosoftAppType: MICROSOFT_TEAMS_APP_TYPE,
MicrosoftAppTenantId: MicrosoftTeamsAppTenantId,
};
const botFrameworkAuthentication: ConfigurationBotFrameworkAuthentication =
new ConfigurationBotFrameworkAuthentication(authConfig);
const adapter: CloudAdapter = new CloudAdapter(botFrameworkAuthentication);
this.cachedAdapter = adapter;
logger.debug("Bot Framework adapter created successfully");
return adapter;
}
// Helper method to get a valid access token, refreshing if necessary
public static async getValidAccessToken(data: {
authToken: string;
projectId: ObjectID;
}): Promise<string> {
logger.debug("=== getValidAccessToken called ===", {
projectId: data.projectId?.toString(),
});
if (!data.projectId) {
throw new BadDataException(
"projectId is required to get Microsoft Teams access token",
);
}
logger.debug(`Project ID: ${data.projectId.toString()}`);
logger.debug(
`Auth token (first 20 chars): ${data.authToken?.substring(0, 20)}...`,
);
// Get project auth and check token expiration
const projectAuth: WorkspaceProjectAuthToken | null =
await WorkspaceProjectAuthTokenService.getProjectAuth({
projectId: data.projectId,
workspaceType: WorkspaceType.MicrosoftTeams,
});
logger.debug(`Project auth found: ${Boolean(projectAuth)}`);
if (projectAuth) {
logger.debug(
`Project auth has miscData: ${Boolean(projectAuth.miscData)}`,
);
}
if (!projectAuth || !projectAuth.miscData) {
logger.error(
"Microsoft Teams integration not found for this project - no project auth or miscData",
{
projectId: data.projectId.toString(),
},
);
throw new BadDataException(
"Microsoft Teams integration not found for this project",
);
}
const miscData: MicrosoftTeamsMiscData =
projectAuth.miscData as MicrosoftTeamsMiscData;
const tenantId: string | undefined = projectAuth.workspaceProjectId;
logger.debug(`Resolved tenant ID: ${tenantId}`);
if (!tenantId) {
logger.error(
"Microsoft Teams tenant ID missing from project auth configuration",
{
projectId: data.projectId.toString(),
},
);
throw new BadDataException(
"Microsoft Teams tenant ID not found for this project",
);
}
logger.debug(
`MiscData appAccessToken exists: ${Boolean(miscData.appAccessToken)}`,
);
logger.debug(
`MiscData appAccessTokenExpiresAt: ${miscData.appAccessTokenExpiresAt}`,
);
// Check if token exists and is valid
if (miscData.appAccessToken && miscData.appAccessToken.includes(".")) {
logger.debug("Found app access token in miscData");
// Check if token is expired
if (miscData.appAccessTokenExpiresAt) {
const expiryDate: Date = OneUptimeDate.fromString(
miscData.appAccessTokenExpiresAt,
);
const now: Date = OneUptimeDate.getCurrentDate();
const isExpired: boolean = OneUptimeDate.isAfter(now, expiryDate);
const secondsToExpiry: number = OneUptimeDate.getSecondsTo(expiryDate);
logger.debug(`Token expires in ${secondsToExpiry} seconds`);
logger.debug(`Token is expired: ${isExpired}`);
// If token is already expired or expires within the next 5 minutes, refresh it
if (isExpired || secondsToExpiry <= 300) {
logger.debug(
"Access token is expired or expiring soon, attempting to refresh",
);
const newToken: string | null = await this.refreshAccessToken({
projectId: data.projectId,
miscData,
tenantId,
});
if (newToken) {
logger.debug("Successfully refreshed token");
return newToken;
}
logger.warn("Failed to refresh token, falling back to cached token");
} else {
logger.debug(
"Using cached appAccessToken from miscData for Microsoft Graph API call",
);
return miscData.appAccessToken;
}
} else {
// No expiry information, use the token but it might be expired
logger.debug(
"Using appAccessToken from miscData (no expiry info available)",
);
return miscData.appAccessToken;
}
}
// If we couldn't find a valid token, try to refresh
logger.debug("No valid app access token found, attempting to refresh");
const newToken: string | null = await this.refreshAccessToken({
projectId: data.projectId,
miscData,
tenantId,
});
if (newToken) {
logger.debug("Successfully refreshed token");
return newToken;
}
// If refresh failed, throw error
logger.error("Could not obtain valid access token for Microsoft Teams", {
projectId: data.projectId.toString(),
});
throw new BadDataException(
"Could not obtain valid access token for Microsoft Teams",
);
}
// Method to refresh the Microsoft Teams access token
private static async refreshAccessToken(data: {
projectId: ObjectID;
miscData: MicrosoftTeamsMiscData;
tenantId: string;
}): Promise<string | null> {
logger.debug("=== refreshAccessToken called ===", {
projectId: data.projectId?.toString(),
});
if (!data.projectId) {
throw new BadDataException(
"projectId is required to refresh Microsoft Teams access token",
);
}
if (!data.miscData) {
throw new BadDataException(
"miscData is required to refresh Microsoft Teams access token",
);
}
logger.debug(`Project ID: ${data.projectId.toString()}`);
logger.debug(`Tenant ID: ${data.tenantId}`);
try {
// Check if we have the necessary client credentials
if (!MicrosoftTeamsAppClientId || !MicrosoftTeamsAppClientSecret) {
logger.error(
"Microsoft Teams app client credentials are not configured",
);
logger.error(
"Please set MICROSOFT_TEAMS_APP_CLIENT_ID and MICROSOFT_TEAMS_APP_CLIENT_SECRET environment variables",
);
return null;
}
logger.debug("Client credentials are configured");
if (!data.tenantId) {
logger.error("Tenant ID not provided, cannot refresh token");
return null;
}
logger.debug(
`Attempting to refresh Microsoft Teams access token for project ${data.projectId.toString()}`,
);
logger.debug(`Using tenant ID: ${data.tenantId}`);
// Use OAuth 2.0 client credentials flow to get a new app access token
const tokenUrl: string = `https://login.microsoftonline.com/${data.tenantId}/oauth2/v2.0/token`;
logger.debug(`Token URL: ${tokenUrl}`);
const tokenRequestBody: JSONObject = {
client_id: MicrosoftTeamsAppClientId,
client_secret: MicrosoftTeamsAppClientSecret,
grant_type: "client_credentials",
scope: "https://graph.microsoft.com/.default",
};
logger.debug("Making token refresh request to Microsoft");
const response: HTTPErrorResponse | HTTPResponse<JSONObject> =
await API.post({
url: URL.fromString(tokenUrl),
data: tokenRequestBody,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Accept: "application/json",
},
});
if (response instanceof HTTPErrorResponse) {
logger.error("Error refreshing Microsoft Teams access token:");
logger.error(response);
return null;
}
logger.debug("Token refresh response received successfully");
const tokenData: JSONObject = response.data;
const newAccessToken: string = tokenData["access_token"] as string;
const expiresIn: number = tokenData["expires_in"] as number; // seconds
logger.debug(`New access token received: ${Boolean(newAccessToken)}`);
logger.debug(`Token expires in: ${expiresIn} seconds`);
if (!newAccessToken) {
logger.error("No access token received in token refresh response");
return null;
}
// Calculate expiry time
const now: Date = OneUptimeDate.getCurrentDate();
const expiryDate: Date = OneUptimeDate.addRemoveSeconds(
now,
expiresIn - 300,
); // Subtrutes buffer
logger.debug(
`Token expiry calculated: ${OneUptimeDate.toString(expiryDate)}`,
);
// Update the miscData with new token and expiry
const updatedMiscData: MicrosoftTeamsMiscData = {
...data.miscData,
appAccessToken: newAccessToken,
appAccessTokenExpiresAt: OneUptimeDate.toString(expiryDate),
lastAppTokenIssuedAt: OneUptimeDate.toString(now),
tenantId: data.tenantId,
};
logger.debug("Saving updated token to database");
// Save the updated token to the database
await WorkspaceProjectAuthTokenService.refreshAuthToken({
projectId: data.projectId,
workspaceType: WorkspaceType.MicrosoftTeams,
authToken: newAccessToken,
workspaceProjectId: data.tenantId,
miscData: updatedMiscData as any,
});
logger.debug("Microsoft Teams access token refreshed successfully");
logger.debug(
`New token expires at: ${updatedMiscData.appAccessTokenExpiresAt}`,
);
return newAccessToken;
} catch (error) {
logger.error("Error refreshing Microsoft Teams access token:", {
projectId: data.projectId.toString(),
});
logger.error(error);
return null;
}
}
// Extract action type and value from Teams Adaptive Card submit value
private static extractActionFromValue(value: JSONObject): {
actionType: MicrosoftTeamsActionType;
actionValue: string;
} {
/*
* Support multiple shapes that Teams may send for Adaptive Card submits
* 1) { action: "ack-incident", actionValue: "<id>" }
* 2) { data: { action: "ack-incident", actionValue: "<id>" } }
* 3) { action: { type: "Action.Submit", data: { action: "ack-incident", actionValue: "<id>" } } }
*/
let actionType: string = (value["action"] as string) || "";
let actionValue: string = (value["actionValue"] as string) || "";
const valData: JSONObject | undefined =
(value["data"] as JSONObject) || undefined;
if ((!actionType || !actionValue) && valData) {
actionType = (valData["action"] as string) || actionType;
actionValue = (valData["actionValue"] as string) || actionValue;
}
const actionObj: JSONObject | undefined = value[
"action"
] as unknown as JSONObject;
if (
(!actionType || !actionValue) &&
actionObj &&
typeof actionObj === "object"
) {
const embeddedData: JSONObject | undefined =
(actionObj["data"] as JSONObject) || undefined;
if (embeddedData) {
actionType = (embeddedData["action"] as string) || actionType;
actionValue = (embeddedData["actionValue"] as string) || actionValue;
}
}
return { actionType: actionType as MicrosoftTeamsActionType, actionValue };
}
/**
* Converts markdown tables to HTML tables for Teams MessageCard.
* Teams MessageCard supports HTML in the text field.
*/
private static convertMarkdownTablesToHtml(markdown: string): string {
// Regular expression to match markdown tables
const tableRegex: RegExp =
/(?:^|\n)((?:\|[^\n]+\|\n)+(?:\|[-:\s|]+\|\n)(?:\|[^\n]+\|\n?)+)/g;
return markdown.replace(
tableRegex,
(_match: string, table: string): string => {
const lines: Array<string> = table.trim().split("\n");
if (lines.length < 2) {
return table;
}
// Parse header row
const headerLine: string = lines[0] || "";
const headers: Array<string> = headerLine
.split("|")
.map((cell: string) => {
return cell.trim();
})
.filter((cell: string) => {
return cell.length > 0;
});
// Skip separator line (line with dashes) and get data rows
const dataRows: Array<string> = lines.slice(2);
// Build HTML table
let html: string =
'<table style="border-collapse: collapse; width: 100%;">';
// Header row
html += "<tr>";
for (const header of headers) {
html += `<th style="border: 1px solid #ddd; padding: 8px; background-color: #f2f2f2; text-align: left;"><strong>${header}</strong></th>`;
}
html += "</tr>";
// Data rows
for (const row of dataRows) {
const cells: Array<string> = row
.split("|")
.map((cell: string) => {
return cell.trim();
})
.filter((cell: string) => {
return cell.length > 0;
});
if (cells.length === 0) {
continue;
}
html += "<tr>";
for (const cell of cells) {
html += `<td style="border: 1px solid #ddd; padding: 8px;">${cell}</td>`;
}
html += "</tr>";
}
html += "</table>";
return "\n" + html + "\n";
},
);
}
private static buildMessageCardFromMarkdown(markdown: string): JSONObject {
/*
* Teams MessageCard has limited markdown support. Headings like '##' are not supported
* and single newlines can collapse. Convert common patterns to a structured card.
*/
// First, convert markdown tables to HTML
const markdownWithHtmlTables: string =
this.convertMarkdownTablesToHtml(markdown);
const lines: Array<string> = markdownWithHtmlTables
.split("\n")
.map((l: string) => {
return l.trim();
})
.filter((l: string) => {
return l.length > 0;
});
let title: string = "";
const facts: Array<JSONObject> = [];
const actions: Array<JSONObject> = [];
const bodyTextParts: Array<string> = [];
// Extract title from the first non-empty line and strip markdown heading markers
if (lines.length > 0) {
const firstLine: string = lines[0] ?? "";
title = firstLine
.replace(/^#+\s*/, "") // remove leading markdown headers like ##
.replace(/^\*\*|\*\*$/g, "") // remove stray bold markers if any
.trim();
// Remove markdown link syntax from title for cleaner rendering
const titleLinkRegex: RegExp = /\[([^\]]+)\]\(([^)]+)\)/g;
title = title.replace(titleLinkRegex, "$1");
// Sanitize unmatched bold markers if any remain
const boldCountTitle: number = (title.match(/\*\*/g) || []).length;
if (boldCountTitle % 2 !== 0) {
title = title.replace(/\*\*/g, "");
}
lines.shift();
}
const linkRegex: RegExp = /\[([^\]]+)\]\(([^)]+)\)/g; // [text](url)
// Helper to clean up unmatched bold markers that can break rendering
const sanitizeMarkdownText: (text: string) => string = (
text: string,
): string => {
const boldCount: number = (text.match(/\*\*/g) || []).length;
// If we have an odd number of **, remove them all to avoid raw markers showing
if (boldCount % 2 !== 0) {
text = text.replace(/\*\*/g, "");
}
// Collapse multiple spaces introduced by replacements
return text.replace(/\s{2,}/g, " ");
};
for (const line of lines) {
// Extract links to actions and keep link display text in-place (without markdown)
let lineWithoutLinks: string = line;
let match: RegExpExecArray | null = null;
while ((match = linkRegex.exec(line))) {
const name: string = match[1] ?? "";
const url: string = match[2] ?? "";
actions.push({
["@type"]: "OpenUri",
name: name,
targets: [
{
os: "default",
uri: url,
},
],
});
// Replace markdown link with just the display text to preserve sentence flow
lineWithoutLinks = lineWithoutLinks.replace(match[0], name).trim();
}
// Parse facts of the form **Label:** value
const factMatch: RegExpExecArray | null = new RegExp(
"\\*\\*(.*?):\\*\\*\\s*(.*)",
).exec(lineWithoutLinks);
if (factMatch) {
const name: string = (factMatch[1] ?? "").trim();
const value: string = (factMatch[2] ?? "").trim();
if (
name.toLowerCase() === "description" ||
name.toLowerCase() === "note"
) {
bodyTextParts.push(`**${name}:** ${value}`);
} else {
facts.push({ name: name, value: value });
}
} else if (lineWithoutLinks) {
bodyTextParts.push(sanitizeMarkdownText(lineWithoutLinks));
}
}
const payload: JSONObject = {
["@type"]: "MessageCard",
["@context"]: "https://schema.org/extensions",
title: title,
summary: title,
};
// Build a single section so we can enable markdown explicitly
const section: JSONObject = { markdown: true } as any;
if (bodyTextParts.length > 0) {
section["text"] = bodyTextParts.join("\n\n");
}
if (facts.length > 0) {
section["facts"] = facts;
}
if (section["text"] || section["facts"]) {
payload["sections"] = [section];
}
if (actions.length > 0) {
payload["potentialAction"] = actions;
}
return payload;
}
@CaptureSpan()
public static override async sendMessageToChannelViaIncomingWebhook(data: {
url: URL;
text: string;
}): Promise<HTTPResponse<JSONObject> | HTTPErrorResponse> {
logger.debug("Sending message to Teams channel via incoming webhook:");
logger.debug(data);
// Build a structured MessageCard from markdown for better rendering in Teams
const payload: JSONObject = this.buildMessageCardFromMarkdown(data.text);
const apiResult: HTTPResponse<JSONObject> | HTTPErrorResponse | null =
await API.post({
url: data.url,
data: payload,
});
if (!apiResult) {
logger.error(
"Could not send message to Teams channel via incoming webhook.",
);
throw new Error(
"Could not send message to Teams channel via incoming webhook.",
);
}
if (apiResult instanceof HTTPErrorResponse) {
logger.error(
"Error sending message to Teams channel via incoming webhook:",
);
logger.error(apiResult);
throw apiResult;
}
logger.debug(
"Message sent to Teams channel via incoming webhook successfully:",
);
logger.debug(apiResult);
return apiResult;
}
public static isValidMicrosoftTeamsIncomingWebhookUrl(
incomingWebhookUrl: URL,
): boolean {
// Check if the URL contains outlook.office.com or office.com webhook pattern
const urlString: string = incomingWebhookUrl.toString();
return (
urlString.includes("outlook.office.com") ||
urlString.includes("office.com")
);
}
@CaptureSpan()
public static override async getUsernameFromUserId(data: {
authToken: string;
userId: string;
projectId: ObjectID;
}): Promise<string | null> {
logger.debug("Getting username from user ID with data:", {
projectId: data.projectId.toString(),
userId: data.userId,
});
logger.debug(data);
// Get valid access token
const accessToken: string = await this.getValidAccessToken({
authToken: data.authToken,
projectId: data.projectId,
});
const response: HTTPErrorResponse | HTTPResponse<JSONObject> =
await API.get<JSONObject>({
url: URL.fromString(
`https://graph.microsoft.com/v1.0/users/${data.userId}`,
),
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
});
logger.debug("Response from Microsoft Graph API for getting user info:");
logger.debug(response);
if (response instanceof HTTPErrorResponse) {
logger.error("Error response from Microsoft Graph API:", {
projectId: data.projectId.toString(),
userId: data.userId,
});
logger.error(response);
throw response;
}
const userData: JSONObject = response.data;
const username: string =
(userData["displayName"] as string) ||
(userData["userPrincipalName"] as string);
logger.debug("Username obtained:");
logger.debug(username);
return username;
}
@CaptureSpan()
public static override async sendDirectMessageToUser(data: {
authToken: string;
workspaceUserId: string;
messageBlocks: Array<WorkspaceMessageBlock>;
}): Promise<void> {
// Send direct message to user via Microsoft Graph API
const adaptiveCard: JSONObject = this.buildAdaptiveCardFromMessageBlocks({
messageBlocks: data.messageBlocks,
});
const chatMessage: JSONObject = {
body: {
contentType: "html",
content: this.convertAdaptiveCardToHtml(adaptiveCard),
},
attachments: [
{
contentType: "application/vnd.microsoft.card.adaptive",
content: adaptiveCard,
},
],
};
await API.post({
url: URL.fromString(
`https://graph.microsoft.com/v1.0/chats/${data.workspaceUserId}/messages`,
),
data: chatMessage,
headers: {
Authorization: `Bearer ${data.authToken}`,
"Content-Type": "application/json",
},
});
}
@CaptureSpan()
public static override async createChannelsIfDoesNotExist(data: {
authToken: string;
channelNames: Array<string>;
projectId: ObjectID;
teamId: string; // Required team ID
}): Promise<Array<WorkspaceChannel>> {
logger.debug("Creating channels if they do not exist with data:");
logger.debug(data);
const workspaceChannels: Array<WorkspaceChannel> = [];
for (const channelName of data.channelNames) {
/*
* Normalize channel name: replace spaces with hyphens, then strip
* characters not valid in Teams channel names (e.g. #, %, &, *, etc.).
*/
const normalizedChannelName: string = channelName
.replace(/\s+/g, "-")
.replace(/[^a-zA-Z0-9\-_]/g, "");
// Check if channel exists
const existingChannel: WorkspaceChannel | null =
await this.getWorkspaceChannelByName({
authToken: data.authToken,
channelName: normalizedChannelName,
projectId: data.projectId,
teamId: data.teamId,
});
if (existingChannel) {
logger.debug(`Channel ${channelName} already exists.`);
workspaceChannels.push(existingChannel);
continue;
}
logger.debug(`Channel ${channelName} does not exist. Creating channel.`);
const createChannelData: {
authToken: string;
channelName: string;
projectId: ObjectID;
teamId: string;
} = {
authToken: data.authToken,
channelName: normalizedChannelName,
projectId: data.projectId,
teamId: data.teamId,
};
const channel: WorkspaceChannel =
await this.createChannel(createChannelData);
if (channel) {
logger.debug(`Channel ${channelName} created successfully.`);
workspaceChannels.push(channel);
}
}
logger.debug("Channels created or found:");
logger.debug(workspaceChannels);
return workspaceChannels;
}
@CaptureSpan()
public static override async createChannel(data: {
authToken: string;
channelName: string;
projectId: ObjectID;
teamId: string; // Required team ID
isPrivate?: boolean;
}): Promise<WorkspaceChannel> {
const teamId: string = data.teamId;
// Sanitize channel name: strip characters not valid in Teams channel names.
data.channelName = data.channelName.replace(/[^a-zA-Z0-9\-_\s]/g, "");
// Get valid access token
const accessToken: string = await this.getValidAccessToken({
authToken: data.authToken,
projectId: data.projectId,
});
const channelPayload: JSONObject = {
displayName: data.channelName,
description: `OneUptime notifications for ${data.channelName}`,
membershipType: data.isPrivate ? "private" : "standard",
};
logger.debug("Creating Teams channel with payload:");
logger.debug(channelPayload);
const response: HTTPErrorResponse | HTTPResponse<JSONObject> =
await API.post({
url: URL.fromString(
`https://graph.microsoft.com/v1.0/teams/${teamId}/channels`,
),
data: channelPayload,
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
});
if (response instanceof HTTPErrorResponse) {
logger.error("Error response from Microsoft Graph API:");
logger.error(response);
throw response;
}
const channelData: JSONObject = response.data;
const channel: WorkspaceChannel = {
id: channelData["id"] as string,
name: channelData["displayName"] as string,
workspaceType: WorkspaceType.MicrosoftTeams,
teamId: data.teamId,
};
logger.debug("Channel created successfully:");
logger.debug(channel);
return channel;
}
@CaptureSpan()
public static override async getWorkspaceChannelFromChannelName(data: {
authToken: string;
channelName: string;
projectId: ObjectID;
teamId: string;
}): Promise<WorkspaceChannel> {
const channel: WorkspaceChannel | null =
await this.getWorkspaceChannelByName({
authToken: data.authToken,
channelName: data.channelName,
projectId: data.projectId,
teamId: data.teamId,
});
if (!channel) {
throw new BadDataException("Channel not found.");
}
return channel;
}
@CaptureSpan()
public static async getWorkspaceChannelByName(data: {
authToken: string;
channelName: string;
projectId: ObjectID;
teamId: string;
}): Promise<WorkspaceChannel | null> {
if (!data.projectId) {
throw new BadDataException(
"projectId is required to get Microsoft Teams channel by name",
);
}
if (!data.teamId) {
throw new BadDataException(
"teamId is required to get Microsoft Teams channel by name",
);
}
if (!data.channelName) {
throw new BadDataException(
"channelName is required to get Microsoft Teams channel by name",
);
}
logger.debug(`Getting workspace channel by name: ${data.channelName}`);
// Get project auth to get available teams
const projectAuth: WorkspaceProjectAuthToken | null =
await WorkspaceProjectAuthTokenService.getProjectAuth({
projectId: data.projectId,
workspaceType: WorkspaceType.MicrosoftTeams,
});
if (!projectAuth?.miscData) {
logger.error("Microsoft Teams integration not found for this project");
throw new BadDataException(
"Microsoft Teams integration not found for this project",
);
}
// Get valid access token
const accessToken: string | null = await this.getValidAccessToken({
authToken: data.authToken,
projectId: data.projectId,
});
// Get channels for this team
const response: HTTPErrorResponse | HTTPResponse<JSONObject> =
await API.get({
url: URL.fromString(
`https://graph.microsoft.com/v1.0/teams/${data.teamId}/channels`,
),
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
});
if (response instanceof HTTPErrorResponse) {
logger.error("Error response from Microsoft Graph API:");
logger.error(response);
throw response;