microsoft/teams.net

Public

mirrored from https://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
99620f7f6ecccb78c4ebfb54686bb2a4e56dcea8

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

core/src/Microsoft.Teams.Bot.Core/Schema/CoreActivity.cs

234lines · modecode

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4using System.Text.Json;
5using System.Text.Json.Nodes;
6using System.Text.Json.Serialization.Metadata;
7
8namespace Microsoft.Teams.Bot.Core.Schema;
9
10/// <summary>
11/// Represents a dictionary for storing extended properties as key-value pairs.
12/// </summary>
13public class ExtendedPropertiesDictionary : Dictionary<string, object?> { }
14
15/// <summary>
16/// Represents a core activity object that encapsulates the data and metadata for a bot interaction.
17/// </summary>
18/// <remarks>
19/// This class provides the foundational structure for bot activities including message exchanges,
20/// conversation updates, and other bot-related events. It supports serialization to and from JSON
21/// and includes extension properties for channel-specific data.
22/// Follows the Activity Protocol Specification: https://github.com/microsoft/Agents/blob/main/specs/activity/protocol-activity.md
23/// </remarks>
24public class CoreActivity
25{
26 /// <summary>
27 /// Gets or sets the type of the activity. See <see cref="ActivityType"/> for common values.
28 /// </summary>
29 /// <remarks>
30 /// Common activity types include "message", "conversationUpdate", "contactRelationUpdate", etc.
31 /// </remarks>
32 [JsonPropertyName("type")] public string Type { get; set; }
33 /// <summary>
34 /// Gets or sets the unique identifier for the channel on which this activity is occurring.
35 /// </summary>
36 [JsonPropertyName("channelId")] public string? ChannelId { get; set; }
37 /// <summary>
38 /// Gets or sets the unique identifier for the activity.
39 /// </summary>
40 [JsonPropertyName("id")] public string? Id { get; set; }
41 /// <summary>
42 /// Gets or sets the URL of the service endpoint for this activity.
43 /// </summary>
44 /// <remarks>
45 /// This URL is used to send responses back to the channel.
46 /// </remarks>
47 [JsonPropertyName("serviceUrl")] public Uri? ServiceUrl { get; set; }
48 /// <summary>
49 /// Gets or sets channel-specific data associated with this activity.
50 /// </summary>
51 [JsonPropertyName("channelData")] public ChannelData? ChannelData { get; set; }
52 /// <summary>
53 /// Gets or sets the account that sent this activity.
54 /// </summary>
55 [JsonPropertyName("from")] public ConversationAccount? From { get; set; }
56 /// <summary>
57 /// Gets or sets the account that should receive this activity.
58 /// </summary>
59 [JsonPropertyName("recipient")] public ConversationAccount? Recipient { get; set; }
60 /// <summary>
61 /// Gets or sets the conversation in which this activity is taking place.
62 /// </summary>
63 [JsonPropertyName("conversation")] public Conversation? Conversation { get; set; }
64
65 /// <summary>
66 /// Gets the collection of entities contained in this activity.
67 /// </summary>
68 /// <remarks>
69 /// Entities are structured objects that represent mentions, places, or other data.
70 /// </remarks>
71 [JsonPropertyName("entities")] public JsonArray? Entities { get; set; }
72
73 /// <summary>
74 /// Gets the collection of attachments associated with this activity.
75 /// </summary>
76 [JsonPropertyName("attachments")] public JsonArray? Attachments { get; set; }
77
78 // TODO: Can value need be a JSONObject?
79 /// <summary>
80 /// Gets or sets the value payload of the activity.
81 /// </summary>
82 [JsonPropertyName("value")] public JsonNode? Value { get; set; }
83
84 /// <summary>
85 /// Reply to Id
86 /// </summary>
87 [JsonPropertyName("replyToId")] public string? ReplyToId { get; set; }
88
89 /// <summary>
90 /// Gets the extension data dictionary for storing additional properties not defined in the schema.
91 /// </summary>
92 [JsonExtensionData] public ExtendedPropertiesDictionary Properties { get; set; } = [];
93
94 /// <summary>
95 /// Gets the default JSON serializer options used for serializing and deserializing activities.
96 /// </summary>
97 /// <remarks>
98 /// Uses the source-generated JSON context for AOT-compatible serialization.
99 /// </remarks>
100 public static readonly JsonSerializerOptions DefaultJsonOptions = CoreActivityJsonContext.Default.Options;
101
102 /// <summary>
103 /// Gets the JSON serializer options used for reflection-based serialization of extended activity types.
104 /// </summary>
105 /// <remarks>
106 /// Uses reflection-based serialization to support custom activity types that extend CoreActivity.
107 /// This is used when serializing/deserializing types not registered in the source-generated context.
108 /// </remarks>
109 private static readonly JsonSerializerOptions ReflectionJsonOptions = new()
110 {
111 WriteIndented = true,
112 DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
113 PropertyNamingPolicy = JsonNamingPolicy.CamelCase
114 };
115
116 /// <summary>
117 /// Creates a new instance of the <see cref="CoreActivity"/> class with the specified activity type.
118 /// </summary>
119 /// <param name="type"></param>
120 public CoreActivity(string type = ActivityType.Message)
121 {
122 Type = type;
123 }
124
125
126 /// <summary>
127 /// Creates a new instance of the <see cref="CoreActivity"/> class. As Message type by default.
128 /// </summary>
129 public CoreActivity()
130 {
131 Type = ActivityType.Message;
132 }
133
134 /// <summary>
135 /// Creates a new instance of the <see cref="CoreActivity"/> class by copying properties from another activity.
136 /// </summary>
137 /// <param name="activity">The source activity to copy from.</param>
138 protected CoreActivity(CoreActivity activity)
139 {
140 ArgumentNullException.ThrowIfNull(activity);
141
142 Id = activity.Id;
143 ServiceUrl = activity.ServiceUrl;
144 ChannelId = activity.ChannelId;
145 Type = activity.Type;
146 // TODO: Figure out why this is needed...
147 // ReplyToId = activity.ReplyToId;
148 ChannelData = activity.ChannelData;
149 From = activity.From;
150 Recipient = activity.Recipient;
151 Conversation = activity.Conversation;
152 Entities = activity.Entities;
153 Attachments = activity.Attachments;
154 Properties = activity.Properties;
155 Value = activity.Value;
156
157 }
158
159 /// <summary>
160 /// Serializes the current activity to a JSON string.
161 /// </summary>
162 /// <returns>A JSON string representation of the activity.</returns>
163 public virtual string ToJson()
164 => JsonSerializer.Serialize(this, CoreActivityJsonContext.Default.CoreActivity);
165
166 /// <summary>
167 /// Serializes the current activity to a JSON string using the specified JsonTypeInfo options.
168 /// </summary>
169 /// <typeparam name="T"></typeparam>
170 /// <param name="ops"></param>
171 /// <returns></returns>
172 public string ToJson<T>(JsonTypeInfo<T> ops) where T : CoreActivity
173 => JsonSerializer.Serialize(this, ops);
174
175 /// <summary>
176 /// Serializes the specified activity instance to a JSON string using the default serialization options.
177 /// </summary>
178 /// <remarks>The serialization uses the default JSON options defined by DefaultJsonOptions. The resulting
179 /// JSON reflects the public properties of the activity instance.</remarks>
180 /// <typeparam name="T">The type of the activity to serialize. Must inherit from CoreActivity.</typeparam>
181 /// <param name="instance">The activity instance to serialize. Cannot be null.</param>
182 /// <returns>A JSON string representation of the specified activity instance.</returns>
183 public static string ToJson<T>(T instance) where T : CoreActivity
184 => JsonSerializer.Serialize<T>(instance, ReflectionJsonOptions);
185
186 /// <summary>
187 /// Deserializes a JSON string into a <see cref="CoreActivity"/> object.
188 /// </summary>
189 /// <param name="json">The JSON string to deserialize.</param>
190 /// <returns>A <see cref="CoreActivity"/> instance.</returns>
191 public static CoreActivity FromJsonString(string json)
192 => JsonSerializer.Deserialize(json, CoreActivityJsonContext.Default.CoreActivity)!;
193
194 /// <summary>
195 /// Asynchronously deserializes a JSON stream into a <see cref="CoreActivity"/> object.
196 /// </summary>
197 /// <param name="stream">The stream containing JSON data to deserialize.</param>
198 /// <param name="cancellationToken">A cancellation token to cancel the operation.</param>
199 /// <returns>A task that represents the asynchronous operation. The task result contains the deserialized <see cref="CoreActivity"/> instance, or null if deserialization fails.</returns>
200 public static ValueTask<CoreActivity?> FromJsonStreamAsync(Stream stream, CancellationToken cancellationToken = default)
201 => JsonSerializer.DeserializeAsync(stream, CoreActivityJsonContext.Default.CoreActivity, cancellationToken);
202
203 /// <summary>
204 /// Deserializes a JSON stream into an instance of type T using the specified JsonTypeInfo options.
205 /// </summary>
206 /// <typeparam name="T"></typeparam>
207 /// <param name="stream"></param>
208 /// <param name="ops"></param>
209 /// <param name="cancellationToken"></param>
210 /// <returns></returns>
211 public static ValueTask<T?> FromJsonStreamAsync<T>(Stream stream, JsonTypeInfo<T> ops, CancellationToken cancellationToken = default) where T : CoreActivity
212 => JsonSerializer.DeserializeAsync(stream, ops, cancellationToken);
213
214 /// <summary>
215 /// Asynchronously deserializes a JSON value from the specified stream into an instance of type T.
216 /// </summary>
217 /// <remarks>The caller is responsible for managing the lifetime of the provided stream. The method uses
218 /// default JSON serialization options.</remarks>
219 /// <typeparam name="T">The type of the object to deserialize. Must derive from CoreActivity.</typeparam>
220 /// <param name="stream">The stream containing the JSON data to deserialize. The stream must be readable and positioned at the start of
221 /// the JSON content.</param>
222 /// <param name="cancellationToken">A cancellation token that can be used to cancel the asynchronous operation.</param>
223 /// <returns>A ValueTask that represents the asynchronous operation. The result contains an instance of type T if
224 /// deserialization is successful; otherwise, null.</returns>
225 public static ValueTask<T?> FromJsonStreamAsync<T>(Stream stream, CancellationToken cancellationToken = default) where T : CoreActivity
226 => JsonSerializer.DeserializeAsync<T>(stream, ReflectionJsonOptions, cancellationToken);
227
228 /// <summary>
229 /// Creates a new instance of the <see cref="CoreActivityBuilder"/> to construct activity instances.
230 /// </summary>
231 /// <returns></returns>
232 public static CoreActivityBuilder CreateBuilder() => new();
233
234}
235