forked from dasrick/go-teams-notify
-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathadaptivecard.go
2225 lines (1874 loc) · 64.9 KB
/
adaptivecard.go
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
// Copyright 2022 Adam Chalkley
//
// https://github.com/atc0005/go-teams-notify
//
// Licensed under the MIT License. See LICENSE file in the project root for
// full license information.
package adaptivecard
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"regexp"
"strconv"
"strings"
goteamsnotify "github.com/atc0005/go-teams-notify/v2"
"github.com/atc0005/go-teams-notify/v2/internal/validator"
)
// General constants.
const (
// TypeMessage is the type for an Adaptive Card Message.
TypeMessage string = "message"
)
// Card & TopLevelCard specific constants.
const (
// TypeAdaptiveCard is the supported type value for an Adaptive Card.
TypeAdaptiveCard string = "AdaptiveCard"
// AdaptiveCardSchema represents the URI of the Adaptive Card schema.
AdaptiveCardSchema string = "http://adaptivecards.io/schemas/adaptive-card.json"
// AdaptiveCardMaxVersion represents the highest supported version of the
// Adaptive Card schema supported in Microsoft Teams messages.
//
// https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#support-for-adaptive-cards
// https://adaptivecards.io/designer
AdaptiveCardMaxVersion float64 = 1.5
AdaptiveCardMinVersion float64 = 1.0
AdaptiveCardVersionTmpl string = "%0.1f"
)
// Mention constants.
const (
// TypeMention is the type for a user mention for a Adaptive Card Message.
TypeMention string = "mention"
// MentionTextFormatTemplate is the expected format of the Mention.Text
// field value.
MentionTextFormatTemplate string = "<at>%s</at>"
// defaultMentionTextSeparator is the default separator used between the
// contents of the Mention.Text field and a TextBlock.Text field.
defaultMentionTextSeparator string = " "
)
// Attachment constants.
//
// https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference
// https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.schema.attachmentlayouttypes
// https://docs.microsoft.com/en-us/javascript/api/botframework-schema/attachmentlayouttypes
// https://github.com/matthidinger/ContosoScubaBot/blob/master/Cards/1-Schools.JSON
const (
// AttachmentContentType is the supported type value for an attached
// Adaptive Card for a Microsoft Teams message.
AttachmentContentType string = "application/vnd.microsoft.card.adaptive"
AttachmentLayoutList string = "list"
AttachmentLayoutCarousel string = "carousel"
)
// TextBlock specific constants.
// https://adaptivecards.io/explorer/TextBlock.html
const (
// TextBlockStyleDefault indicates that the TextBlock uses the default
// style which provides no special styling or behavior.
TextBlockStyleDefault string = "default"
// TextBlockStyleHeading indicates that the TextBlock is a heading. This
// will apply the heading styling defaults and mark the text block as a
// heading for accessibility.
TextBlockStyleHeading string = "heading"
)
// Column specific constants.
// https://adaptivecards.io/explorer/Column.html
const (
// TypeColumn is the type for an Adaptive Card Column.
TypeColumn string = "Column"
// ColumnWidthAuto indicates that a column's width should be determined
// automatically based on other columns in the column group.
ColumnWidthAuto string = "auto"
// ColumnWidthStretch indicates that a column's width should be stretched
// to fill the enclosing column group.
ColumnWidthStretch string = "stretch"
// ColumnWidthPixelRegex is a regular expression pattern intended to match
// specific pixel width values (e.g., 50px).
ColumnWidthPixelRegex string = "^[0-9]+px$"
// ColumnWidthPixelWidthExample is an example of a valid pixel width for a
// Column.
ColumnWidthPixelWidthExample string = "50px"
)
// Text size for TextBlock or TextRun elements.
const (
SizeSmall string = "small"
SizeDefault string = "default"
SizeMedium string = "medium"
SizeLarge string = "large"
SizeExtraLarge string = "extraLarge"
)
// Text weight for TextBlock or TextRun elements.
const (
WeightBolder string = "bolder"
WeightLighter string = "lighter"
WeightDefault string = "default"
)
// Supported colors for TextBlock or TextRun elements.
const (
ColorDefault string = "default"
ColorDark string = "dark"
ColorLight string = "light"
ColorAccent string = "accent"
ColorGood string = "good"
ColorWarning string = "warning"
ColorAttention string = "attention"
)
// Image specific constants.
// https://adaptivecards.io/explorer/Image.html
const (
ImageStyleDefault string = ""
ImageStylePerson string = ""
)
// ChoiceInput specific constants.
const (
ChoiceInputStyleCompact string = "compact"
ChoiceInputStyleExpanded string = "expanded"
ChoiceInputStyleFiltered string = "filtered" // Introduced in version 1.5
)
// TextInput specific constants.
const (
TextInputStyleText string = "text"
TextInputStyleTel string = "tel"
TextInputStyleURL string = "url"
TextInputStyleEmail string = "email"
TextInputStylePassword string = "password" // Introduced in version 1.5
)
// Container specific constants.
const (
ContainerStyleDefault string = "default"
ContainerStyleEmphasis string = "emphasis"
ContainerStyleGood string = "good"
ContainerStyleAttention string = "attention"
ContainerStyleWarning string = "warning"
ContainerStyleAccent string = "accent"
)
// Supported spacing values for FactSet, Container and other container element
// types.
const (
SpacingDefault string = "default"
SpacingNone string = "none"
SpacingSmall string = "small"
SpacingMedium string = "medium"
SpacingLarge string = "large"
SpacingExtraLarge string = "extraLarge"
SpacingPadding string = "padding"
)
// Supported width values for the msteams property used in in Adaptive Card
// messages sent via Microsoft Teams.
const (
MSTeamsWidthFull string = "Full"
)
// Supported Actions
const (
// TeamsActionsDisplayLimit is the observed limit on the number of visible
// URL "buttons" in a Microsoft Teams message.
//
// Unlike the MessageCard format which has a clearly documented limit of 4
// actions, testing reveals that Desktop / Web displays 6 without the
// option to expand and see any additional defined actions. Mobile
// displays 6 with an ellipsis to expand into a list of other Actions.
//
// This results in a maximum limit of 6 actions in the Actions array for a
// Card.
//
// A workaround is to create multiple ActionSet elements and limit the
// number of Actions in each set ot 6.
//
// https://docs.microsoft.com/en-us/outlook/actionable-messages/message-card-reference#actions
TeamsActionsDisplayLimit int = 6
// TypeActionExecute is an action that gathers input fields, merges with
// optional data field, and sends an event to the client. Clients process
// the event by sending an Invoke activity of type adaptiveCard/action to
// the target Bot. The inputs that are gathered are those on the current
// card, and in the case of a show card those on any parent cards. See
// Universal Action Model documentation for more details:
// https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model
//
// TypeActionExecute was introduced in Adaptive Cards schema version 1.4.
// TypeActionExecute actions may not render with earlier versions of the
// Teams client.
TypeActionExecute string = "Action.Execute"
// ActionExecuteMinCardVersionRequired is the minimum version of the
// Adaptive Card schema required to support Action.Execute.
ActionExecuteMinCardVersionRequired float64 = 1.4
// TypeActionSubmit is used in Adaptive Cards schema version 1.3 and
// earlier or as a fallback for TypeActionExecute in schema version 1.4.
// TypeActionSubmit is not supported in Incoming Webhooks.
TypeActionSubmit string = "Action.Submit"
// TypeActionOpenURL (when invoked) shows the given url either by
// launching it in an external web browser or showing within an embedded
// web browser.
TypeActionOpenURL string = "Action.OpenUrl"
// TypeActionShowCard defines an AdaptiveCard which is shown to the user
// when the button or link is clicked.
TypeActionShowCard string = "Action.ShowCard"
// TypeActionToggleVisibility toggles the visibility of associated card
// elements.
TypeActionToggleVisibility string = "Action.ToggleVisibility"
)
// Supported Fallback options.
const (
TypeFallbackActionExecute string = TypeActionExecute
TypeFallbackActionOpenURL string = TypeActionOpenURL
TypeFallbackActionShowCard string = TypeActionShowCard
TypeFallbackActionSubmit string = TypeActionSubmit
TypeFallbackActionToggleVisibility string = TypeActionToggleVisibility
// TypeFallbackOptionDrop causes this element to be dropped immediately
// when unknown elements are encountered. The unknown element doesn't
// bubble up any higher.
TypeFallbackOptionDrop string = "drop"
)
// Valid types for an Adaptive Card element. Not all types are supported by
// Microsoft Teams.
//
// https://adaptivecards.io/explorer/AdaptiveCard.html
//
// TODO: Confirm whether all types are supported.
// NOTE: Based on current docs, version 1.4 is the latest supported at this
// time.
// https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#support-for-adaptive-cards
// https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model#schema
const (
TypeElementActionSet string = "ActionSet"
TypeElementColumnSet string = "ColumnSet"
TypeElementContainer string = "Container"
TypeElementFactSet string = "FactSet"
TypeElementImage string = "Image"
TypeElementImageSet string = "ImageSet"
TypeElementInputChoiceSet string = "Input.ChoiceSet"
TypeElementInputDate string = "Input.Date"
TypeElementInputNumber string = "Input.Number"
TypeElementInputText string = "Input.Text"
TypeElementInputTime string = "Input.Time"
TypeElementInputToggle string = "Input.Toggle"
TypeElementMedia string = "Media" // Introduced in version 1.1 (TODO: Is this supported in Teams message?)
TypeElementRichTextBlock string = "RichTextBlock" // Introduced in version 1.2
TypeElementTextBlock string = "TextBlock"
TypeElementTextRun string = "TextRun" // Introduced in version 1.2
)
// Sentinel errors for this package.
var (
// ErrInvalidType indicates that an invalid type was specified.
ErrInvalidType = errors.New("invalid type value")
// ErrInvalidFieldValue indicates that an invalid value was specified.
ErrInvalidFieldValue = errors.New("invalid field value")
// ErrMissingValue indicates that an expected value was missing.
ErrMissingValue = errors.New("missing expected value")
// ErrValueNotFound indicates that a requested value was not found.
ErrValueNotFound = errors.New("requested value not found")
)
// Message represents a Microsoft Teams message containing one or more
// Adaptive Cards.
type Message struct {
// Type is required; must be set to "message".
Type string `json:"type"`
// Attachments is a collection of one or more Adaptive Cards.
//
// NOTE: Including multiple attachment *without* AttachmentLayout set to
// "carousel" hides cards after the first. Not sure if this is a bug, or
// if it's intentional.
Attachments []Attachment `json:"attachments"`
// AttachmentLayout controls the layout for Adaptive Cards in the
// Attachments collection.
AttachmentLayout string `json:"attachmentLayout,omitempty"`
// ValidateFunc is an optional user-specified validation function that is
// responsible for validating a Message. If not specified, default
// validation is performed.
ValidateFunc func() error `json:"-"`
// payload is a prepared Message in JSON format for submission or pretty
// printing.
payload *bytes.Buffer `json:"-"`
}
// Attachments is a collection of Adaptive Cards for a Microsoft Teams
// message.
type Attachments []Attachment
// Attachment represents an attached Adaptive Card for a Microsoft Teams
// message.
type Attachment struct {
// ContentType is required; must be set to
// "application/vnd.microsoft.card.adaptive".
ContentType string `json:"contentType"`
// ContentURL appears to be related to support for tabs. Most examples
// have this value set to null.
//
// TODO: Update this description with confirmed details.
ContentURL NullString `json:"contentUrl,omitempty"`
// Content represents the content of an Adaptive Card.
//
// TODO: Should this be a pointer?
Content TopLevelCard `json:"content"`
}
// TopLevelCard represents the outer or top-level Card for a Microsoft Teams
// Message attachment.
type TopLevelCard struct {
Card
}
// Card represents the content of an Adaptive Card. The TopLevelCard is a
// superset of this one, asserting that the Version field is properly set.
// That type is used exclusively for Message Attachments. This type is used
// directly for the Action.ShowCard Card field.
type Card struct {
// Type is required; must be set to "AdaptiveCard"
Type string `json:"type"`
// Schema represents the URI of the Adaptive Card schema.
Schema string `json:"$schema"`
// Version is required for top-level cards (i.e., the outer card in an
// attachment); the schema version that the content for an Adaptive Card
// requires.
//
// The TopLevelCard type is a superset of the Card type and asserts that
// this field is properly set, whereas the validation logic for this
// (Card) type skips that assertion.
Version string `json:"version"`
// FallbackText is the text shown when the client doesn't support the
// version specified (may contain markdown).
FallbackText string `json:"fallbackText,omitempty"`
// Body represents the body of an Adaptive Card. The body is made up of
// building-blocks known as elements. Elements can be composed to create
// many types of cards. These elements are shown in the primary card
// region.
Body []Element `json:"body"`
// Actions is a collection of actions to show in the card's action bar.
// The action bar is displayed at the bottom of a Card.
//
// NOTE: The max display limit has been observed to be a fixed value for
// web/desktop app and a matching value as an initial display limit for
// mobile app with the option to expand remaining actions in a list.
//
// This value is recorded in this package as "TeamsActionsDisplayLimit".
//
// To work around this limit, create multiple ActionSets each limited to
// the value of TeamsActionsDisplayLimit.
Actions []Action `json:"actions,omitempty"`
// MSTeams is a container for properties specific to Microsoft Teams
// messages, including formatting properties and user mentions.
//
// NOTE: Using pointer in order to omit unused field from JSON output.
// https://stackoverflow.com/questions/18088294/how-to-not-marshal-an-empty-struct-into-json-with-go
// MSTeams *MSTeams `json:"msteams,omitempty"`
//
// TODO: Revisit this and use a pointer if remote API doesn't like
// receiving an empty object, though brief testing doesn't show this to be
// a problem.
MSTeams MSTeams `json:"msteams,omitempty"`
// MinHeight specifies the minimum height of the card.
MinHeight string `json:"minHeight,omitempty"`
// VerticalContentAlignment defines how the content should be aligned
// vertically within the container. Only relevant for fixed-height cards,
// or cards with a minHeight specified. If MinHeight field is specified,
// this field is required.
VerticalContentAlignment string `json:"verticalContentAlignment,omitempty"`
}
// Elements is a collection of Element values.
type Elements []Element
// Element is a "building block" for an Adaptive Card. Elements are shown
// within the primary card region (aka, "body"), columns and other container
// types. Not all fields of this Go struct type are supported by all Adaptive
// Card element types.
type Element struct {
// Type is required and indicates the type of the element used in the body
// of an Adaptive Card.
// https://adaptivecards.io/explorer/AdaptiveCard.html
Type string `json:"type"`
// ID is a unique identifier associated with this Element.
ID string `json:"id,omitempty"`
// Text is required by the TextBlock and TextRun element types. Text is
// used to display text. A subset of markdown is supported for text used
// in TextBlock elements, but no formatting is permitted in text used in
// TextRun elements.
//
// https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/text-features
// https://adaptivecards.io/explorer/TextBlock.html
// https://adaptivecards.io/explorer/TextRun.html
Text string `json:"text,omitempty"`
// URL is required for the Image element type. URL is the URL to an Image
// in an ImageSet element type.
//
// https://adaptivecards.io/explorer/Image.html
// https://adaptivecards.io/explorer/ImageSet.html
URL string `json:"url,omitempty"`
// Size controls the size of text within a TextBlock element.
Size string `json:"size,omitempty"`
// Weight controls the weight of text in TextBlock or TextRun elements.
Weight string `json:"weight,omitempty"`
// Color controls the color of TextBlock elements or text used in TextRun
// elements.
Color string `json:"color,omitempty"`
// Spacing controls the amount of spacing between this element and the
// preceding element.
Spacing string `json:"spacing,omitempty"`
// The style of the element for accessibility purposes. Valid values
// differ based on the element type. For example, a TextBlock element
// supports the "heading" style, whereas the Column element supports the
// "attention" style (TextBlock does not).
Style string `json:"style,omitempty"`
// Items is required for the Container element type. Items is a collection
// of card elements to render inside the Container.
Items []Element `json:"items,omitempty"`
// Columns is a collection of Columns used to divide a region. This field
// is used by a ColumnSet element type.
Columns []Column `json:"columns,omitempty"`
// Actions is required for the ActionSet element type. Actions is a
// collection of Actions to show for an ActionSet element type.
//
// TODO: Should this be a pointer?
Actions []Action `json:"actions,omitempty"`
// Facts is required for the FactSet element type. Actions is a collection
// of Fact values that are part of a FactSet element type. Each Fact value
// is a key/value pair displayed in tabular form.
//
// TODO: Should this be a pointer?
Facts []Fact `json:"facts,omitempty"`
// Wrap controls whether text is allowed to wrap or is clipped for
// TextBlock elements.
Wrap bool `json:"wrap,omitempty"`
// Separator, when true, indicates that a separating line shown should
// drawn at the top of the element.
Separator bool `json:"separator,omitempty"`
}
// Container is an Element type that allows grouping items together.
type Container Element
// FactSet is an Element type that groups and displays a series of facts (i.e.
// name/value pairs) in a tabular form.
type FactSet Element
// Columns is a collection of Column values.
type Columns []Column
// ColumnItems is a collection of card elements that should be rendered inside
// of the column.
type ColumnItems []*Element
// Column is a container used by a ColumnSet element type. Each container
// may contain one or more elements.
//
// https://adaptivecards.io/explorer/Column.html
type Column struct {
// Type is required; must be set to "Column".
Type string `json:"type"`
// ID is a unique identifier associated with this Column.
ID string `json:"id,omitempty"`
// Width represents the width of a column in the column group. Valid
// values consist of fixed strings OR a number representing the relative
// width.
//
// "auto", "stretch", a number representing relative width of the column
// in the column group, or in version 1.1 and higher, a specific pixel
// width, like "50px".
Width interface{} `json:"width,omitempty"`
// Items are the card elements that should be rendered inside of the
// column.
Items []*Element `json:"items,omitempty"`
// SelectAction is an action that will be invoked when the Column is
// tapped or selected. Action.ShowCard is not supported.
SelectAction *ISelectAction `json:"selectAction,omitempty"`
}
// Facts is a collection of Fact values.
type Facts []Fact
// Fact represents a Fact in a FactSet as a key/value pair.
type Fact struct {
// Title is required; the title of the fact.
Title string `json:"title"`
// Value is required; the value of the fact.
Value string `json:"value"`
}
// Actions is a collection of Action values.
type Actions []Action
// Action represents an action that a user may take on a card. Actions
// typically get rendered in an "action bar" at the bottom of a card.
//
// https://adaptivecards.io/explorer/ActionSet.html
// https://adaptivecards.io/explorer/AdaptiveCard.html
// https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference
//
// TODO: Extend with additional supported fields.
type Action struct {
// Type is required; specific values are supported.
//
// Action.Submit is not supported for Incoming Webhooks.
//
// Action.Execute was added in Adaptive Card schema version 1.4. which
// Teams MAY not fully support.
//
// The supported actions are Action.OpenURL, Action.ShowCard,
// Action.ToggleVisibility, and Action.Execute (see above).
//
// https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference#support-for-adaptive-cards
// https://docs.microsoft.com/en-us/adaptive-cards/authoring-cards/universal-action-model#schema
Type string `json:"type"`
// ID is a unique identifier associated with this Action.
ID string `json:"id,omitempty"`
// Title is a label for the button or link that represents this action.
Title string `json:"title,omitempty"`
// URL to open; required for the Action.OpenUrl type, optional for other
// action types.
URL string `json:"url,omitempty"`
// Fallback describes what to do when an unknown element is encountered or
// the requirements of this or any children can't be met.
Fallback string `json:"fallback,omitempty"`
// Card property is used by Action.ShowCard type.
//
// NOTE: Based on a review of JSON content, it looks like `ActionCard` is
// really just a `Card` type.
//
// refs https://github.com/matthidinger/ContosoScubaBot/blob/master/Cards/SubscriberNotification.JSON
Card *Card `json:"card,omitempty"`
}
// ISelectAction represents an Action that will be invoked when a container
// type (e.g., Column, ColumnSet, Container) is tapped or selected.
// Action.ShowCard is not supported.
//
// https://adaptivecards.io/explorer/Container.html
// https://adaptivecards.io/explorer/ColumnSet.html
// https://adaptivecards.io/explorer/Column.html
//
// TODO: Extend with additional supported fields.
type ISelectAction struct {
// Type is required; specific values are supported.
//
// The supported actions are Action.Execute, Action.OpenUrl,
// Action.ToggleVisibility.
//
// See also https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-reference
Type string `json:"type"`
// ID is a unique identifier associated with this ISelectAction.
ID string `json:"id,omitempty"`
// Title is a label for the button or link that represents this action.
Title string `json:"title,omitempty"`
// URL is required for the Action.OpenUrl type, optional for other action
// types.
URL string `json:"url,omitempty"`
// Fallback describes what to do when an unknown element is encountered or
// the requirements of this or any children can't be met.
Fallback string `json:"fallback,omitempty"`
}
// MSTeams represents a container for properties specific to Microsoft Teams
// messages, including formatting properties and user mentions.
type MSTeams struct {
// Width controls the width of Adaptive Cards within a Microsoft Teams
// messages.
// https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#full-width-adaptive-card
Width string `json:"width,omitempty"`
// AllowExpand controls whether images can be displayed in stage view
// selectively.
//
// https://docs.microsoft.com/en-us/microsoftteams/platform/task-modules-and-cards/cards/cards-format#stage-view-for-images-in-adaptive-cards
AllowExpand bool `json:"allowExpand,omitempty"`
// Entities is a collection of user mentions.
// TODO: Should this be a slice of pointers?
Entities []Mention `json:"entities,omitempty"`
}
// Mentions is a collection of Mention values.
type Mentions []Mention
// Mention represents a mention in the message for a specific user.
type Mention struct {
// Type is required; must be set to "mention".
Type string `json:"type"`
// Text must match a portion of the message text field. If it does not,
// the mention is ignored.
//
// Brief testing indicates that this needs to wrap a name/value in <at>NAME
// HERE</at> tags.
Text string `json:"text"`
// Mentioned represents a user that is mentioned.
Mentioned Mentioned `json:"mentioned"`
}
// Mentioned represents the user id and name of a user that is mentioned.
type Mentioned struct {
// ID is the unique identifier for a user that is mentioned. This value
// can be an object ID (e.g., 5e8b0f4d-2cd4-4e17-9467-b0f6a5c0c4d0) or a
// UserPrincipalName (e.g., [email protected]).
ID string `json:"id"`
// Name is the DisplayName of the user mentioned.
Name string `json:"name"`
}
// NewMessage creates a new Message with required fields predefined.
func NewMessage() *Message {
return &Message{
Type: TypeMessage,
}
}
// NewSimpleMessage creates a new simple Message using the specified text and
// optional title. If specified, text wrapping is enabled. An error is
// returned if an empty text string is specified.
func NewSimpleMessage(text string, title string, wrap bool) (*Message, error) {
if text == "" {
return nil, fmt.Errorf(
"required field text is empty: %w",
ErrMissingValue,
)
}
msg := Message{
Type: TypeMessage,
}
textCard, err := NewTextBlockCard(text, title, wrap)
if err != nil {
return nil, fmt.Errorf(
"failed to create TextBlock card: %w",
err,
)
}
if err := msg.Attach(textCard); err != nil {
return nil, fmt.Errorf(
"failed to create simple message: %w",
err,
)
}
return &msg, nil
}
// NewTextBlockCard creates a new Card using the specified text and optional
// title. If specified, the TextBlock has text wrapping enabled.
func NewTextBlockCard(text string, title string, wrap bool) (Card, error) {
if text == "" {
return Card{}, fmt.Errorf(
"required field text is empty: %w",
ErrMissingValue,
)
}
textBlock := Element{
Type: TypeElementTextBlock,
Wrap: wrap,
Text: text,
}
card := Card{
Type: TypeAdaptiveCard,
Schema: AdaptiveCardSchema,
Version: fmt.Sprintf(AdaptiveCardVersionTmpl, AdaptiveCardMaxVersion),
Body: []Element{
textBlock,
},
}
if title != "" {
titleTextBlock := NewTitleTextBlock(title, wrap)
card.Body = append([]Element{titleTextBlock}, card.Body...)
}
return card, nil
}
// NewCard creates and returns an empty Card.
func NewCard() Card {
return Card{
Type: TypeAdaptiveCard,
Schema: AdaptiveCardSchema,
Version: fmt.Sprintf(AdaptiveCardVersionTmpl, AdaptiveCardMaxVersion),
}
}
// Attach receives and adds one or more Card values to the Attachments
// collection for a Microsoft Teams message.
//
// NOTE: Including multiple cards in the attachments collection *without*
// attachmentLayout set to "carousel" hides cards after the first. Not sure if
// this is a bug, or if it's intentional.
func (m *Message) Attach(cards ...Card) error {
if len(cards) == 0 {
return fmt.Errorf(
"received empty collection of cards: %w",
ErrMissingValue,
)
}
for _, card := range cards {
attachment := Attachment{
ContentType: AttachmentContentType,
// Explicitly convert Card to TopLevelCard in order to assert that
// TopLevelCard specific requirements are checked during
// validation.
Content: TopLevelCard{card},
}
m.Attachments = append(m.Attachments, attachment)
}
return nil
}
// Carousel sets the Message Attachment layout to Carousel display mode.
func (m *Message) Carousel() *Message {
m.AttachmentLayout = AttachmentLayoutCarousel
return m
}
// PrettyPrint returns a formatted JSON payload of the Message if the
// Prepare() method has been called, or an empty string otherwise.
func (m *Message) PrettyPrint() string {
if m.payload != nil {
var prettyJSON bytes.Buffer
_ = json.Indent(&prettyJSON, m.payload.Bytes(), "", "\t")
return prettyJSON.String()
}
return ""
}
// Prepare handles tasks needed to construct a payload from a Message for
// delivery to an endpoint.
func (m *Message) Prepare() error {
jsonMessage, err := json.Marshal(m)
if err != nil {
return fmt.Errorf(
"error marshalling Message to JSON: %w",
err,
)
}
switch {
case m.payload == nil:
m.payload = &bytes.Buffer{}
default:
m.payload.Reset()
}
_, err = m.payload.Write(jsonMessage)
if err != nil {
return fmt.Errorf(
"error updating JSON payload for Message: %w",
err,
)
}
return nil
}
// Payload returns the prepared Message payload. The caller should call
// Prepare() prior to calling this method, results are undefined otherwise.
func (m *Message) Payload() io.Reader {
return m.payload
}
// Validate performs validation for Message using ValidateFunc if defined,
// otherwise applying default validation.
func (m Message) Validate() error {
if m.ValidateFunc != nil {
return m.ValidateFunc()
}
v := validator.Validator{}
v.FieldHasSpecificValue(
m.Type,
"type",
TypeMessage,
"message",
ErrInvalidType,
)
// We need an attachment (containing one or more Adaptive Cards) in order
// to generate a valid Message for Microsoft Teams delivery.
v.NotEmptyCollection("Attachments", m.Type, ErrMissingValue, m.Attachments)
v.SelfValidate(Attachments(m.Attachments))
// Optional field, but only specific values permitted if set.
v.InListIfFieldValNotEmpty(
m.AttachmentLayout,
"AttachmentLayout",
"message",
supportedAttachmentLayoutValues(),
ErrInvalidFieldValue,
)
return v.Err()
}
// Validate asserts that fields have valid values.
func (a Attachment) Validate() error {
v := validator.Validator{}
v.FieldHasSpecificValue(
a.ContentType,
"attachment type",
AttachmentContentType,
"attachment",
ErrInvalidType,
)
return v.Err()
}
// Validate asserts that the collection of Attachment values are all valid.
func (a Attachments) Validate() error {
for _, attachment := range a {
if err := attachment.Validate(); err != nil {
return err
}
}
return nil
}
// Validate asserts that fields have valid values.
func (c Card) Validate() error {
v := validator.Validator{}
// TODO: Version field validation
//
// The Version field is required for top-level cards, optional for Cards
// nested within an Action.ShowCard. Because we don't have a reliable way
// to assert that relationship, we skip applying validation for that value
// for now.
v.FieldHasSpecificValue(
c.Type,
"type",
TypeAdaptiveCard,
"card",
ErrInvalidType,
)
// While the schema value should be set it is not strictly required. If it
// is set, we assert that it is the correct value.
v.FieldHasSpecificValueIfFieldNotEmpty(
c.Schema,
"Schema",
AdaptiveCardSchema,
"card",
ErrInvalidFieldValue,
)
// Both are optional fields, unless MinHeight is set in which case
// VerticalContentAlignment is required.
v.SuccessfulFuncCall(
func() error {
return assertHeightAlignmentFieldsSetWhenRequired(
c.MinHeight, c.VerticalContentAlignment,
)
},
)
v.SuccessfulFuncCall(
func() error {
return assertCardBodyHasMention(c.Body, c.MSTeams.Entities)
},
)
v.SelfValidate(Elements(c.Body))
v.SelfValidate(Actions(c.Actions))
return v.Err()
}
// Validate asserts that fields have valid values.
func (tc TopLevelCard) Validate() error {
// Validate embedded Card first as those validation requirements apply
// here also.
if err := tc.Card.Validate(); err != nil {
return err
}
// The Version field is required for top-level cards (this one), optional
// for Cards nested within an Action.ShowCard.
switch {
case strings.TrimSpace(tc.Version) == "":
return fmt.Errorf(
"required field Version is empty for top-level Card: %w",
ErrMissingValue,
)
default:
// Assert that Version value can be converted to the expected format.
versionNum, err := strconv.ParseFloat(tc.Version, 64)