-
Notifications
You must be signed in to change notification settings - Fork 177
/
EntityFrameworkTranscriptStore.cs
226 lines (197 loc) · 9.59 KB
/
EntityFrameworkTranscriptStore.cs
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
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Bot.Builder;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
namespace Bot.Builder.Community.Storage.EntityFramework
{
/// <summary>
/// The Entity Framework transcript store stores transcripts in Sql Server.
/// </summary>
/// <remarks>
/// Each activity is stored as json in the Activity field.
/// </remarks>
public class EntityFrameworkTranscriptStore : ITranscriptStore
{
private static readonly JsonSerializer _jsonSerializer = JsonSerializer.Create(new JsonSerializerSettings()
{
NullValueHandling = NullValueHandling.Ignore,
Formatting = Formatting.Indented,
});
private TranscriptStoreOptions _options;
/// <summary>
/// Initializes a new instance of the <see cref="EntityFrameworkTranscriptStore"/> class.
/// </summary>
/// <param name="connectionstring">Connection string to connect to Sql Server Storage.</param>
public EntityFrameworkTranscriptStore(string connectionString)
:this(new TranscriptStoreOptions() { ConnectionString = connectionString})
{
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentNullException(nameof(connectionString));
}
}
/// <summary>
/// Initializes a new instance of the <see cref="EntityFrameworkTranscriptStore"/> class.
/// </summary>
/// <param name="options">Options to use for the Transcript Store <see cref="TranscriptStoreOptions"/></param>
public EntityFrameworkTranscriptStore(TranscriptStoreOptions options)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (string.IsNullOrEmpty(options.ConnectionString))
{
throw new ArgumentNullException(nameof(options.ConnectionString) + " cannot be empty.");
}
_options = options;
}
/// <summary>
/// Get a TranscriptContext will by default use the connection string provided during EntityFrameworkTranscriptStore construction.
/// </summary>
public virtual TranscriptContext GetTranscriptContext => new TranscriptContext(_options.ConnectionString);
/// <summary>
/// Log an activity to the transcript.
/// </summary>
/// <param name="activity">Activity being logged.</param>
/// <returns>A <see cref="Task"/>A task that represents the work queued to execute.</returns>
public async Task LogActivityAsync(IActivity activity)
{
BotAssert.ActivityNotNull(activity);
using (var context = GetTranscriptContext)
{
var transcript = new TranscriptEntity()
{
Channel = activity.ChannelId,
Conversation = activity.Conversation.Id,
Activity = JsonConvert.SerializeObject(activity)
};
await context.Transcript.AddAsync(transcript);
await context.SaveChangesAsync();
}
}
/// <summary>
/// Get activities for a conversation (Aka the transcript).
/// </summary>
/// <param name="channelId">Channel Id.</param>
/// <param name="conversationId">Conversation Id.</param>
/// <param name="continuationToken">Continuatuation token to page through results. (Id of last record returned)</param>
/// <param name="startDate">Earliest time to include.</param>
/// <returns>PagedResult of activities.</returns>
public Task<PagedResult<IActivity>> GetTranscriptActivitiesAsync(string channelId, string conversationId, string continuationToken = null, DateTimeOffset startDate = default(DateTimeOffset))
{
if (string.IsNullOrEmpty(channelId))
{
throw new ArgumentNullException($"missing {nameof(channelId)}");
}
if (string.IsNullOrEmpty(conversationId))
{
throw new ArgumentNullException($"missing {nameof(conversationId)}");
}
int continuationId = 0;
if (!string.IsNullOrEmpty(continuationToken))
{
if (!int.TryParse(continuationToken, out continuationId))
{
throw new ArgumentException(nameof(continuationToken) + " must be an integer");
}
}
var pagedResult = new PagedResult<IActivity>();
using (var context = GetTranscriptContext)
{
var query = context.Transcript.Where(t => t.Channel == channelId && t.Conversation == conversationId);
// Filter on startDate, if present
if (startDate != default(DateTimeOffset))
{
query = query.Where(t => t.Timestamp >= startDate);
}
// Filter on continuationToken if present
if (!string.IsNullOrEmpty(continuationToken))
{
query = query.Where(t => t.Id > continuationId);
}
var finalItems = query.OrderBy(i => i.Id).Take(_options.PageSize).Select(i => new { i.Id, i.Activity }).ToArray();
// Take only PageSize, and convert to Activities
pagedResult.Items = finalItems.Select(i => JsonConvert.DeserializeObject<Activity>(i.Activity)).ToArray();
if (pagedResult.Items.Length == _options.PageSize)
{
pagedResult.ContinuationToken = finalItems.Last().Id.ToString();
}
}
return Task.FromResult(pagedResult);
}
/// <summary>
/// List conversations in the channelId.
/// </summary>
/// <param name="channelId">Channel Id.</param>
/// <param name="continuationToken">Continuatuation token to page through results.</param>
/// <returns>A <see cref="Task"/> A task that represents the work queued to execute.</returns>
public Task<PagedResult<TranscriptInfo>> ListTranscriptsAsync(string channelId, string continuationToken = null)
{
if (string.IsNullOrEmpty(channelId))
{
throw new ArgumentNullException($"missing {nameof(channelId)}");
}
DateTimeOffset continuationDate = default(DateTimeOffset);
if (!string.IsNullOrEmpty(continuationToken))
{
if (!DateTimeOffset.TryParse(continuationToken, out continuationDate))
{
throw new ArgumentException(nameof(continuationToken) + " must be an DateTimeOffset");
}
}
var pagedResult = new PagedResult<TranscriptInfo>();
using (var context = GetTranscriptContext)
{
var query = context.Transcript.Where(t => t.Channel == channelId);
// Get all conversation.ids with thier min Timestamps
var items = (from p in query
group p by p.Conversation into grp
let timestamp = grp.Min(p => p.Timestamp)
let conversationId = grp.Key
from p in grp
where p.Conversation == conversationId && p.Timestamp == timestamp
select new { p.Conversation, p.Timestamp });
// Filter on continuationToken if present
if (!string.IsNullOrEmpty(continuationToken))
{
// TODO: what if two activities have the same timestamp??? is that possible???
items = items.Where(i => i.Timestamp > continuationDate);
}
// Take only PageSize, and convert to Transcript Info
var finalItems = items.OrderBy(i => i.Timestamp).Take(_options.PageSize);
pagedResult.Items = finalItems.Select(i => new TranscriptInfo() { ChannelId = channelId, Id = i.Conversation, Created = i.Timestamp }).ToArray();
// Set ContinuationToken to last date
if (pagedResult.Items.Length == _options.PageSize)
{
pagedResult.ContinuationToken = finalItems.OrderByDescending(i => i.Timestamp).First().Timestamp.ToString();
}
}
return Task.FromResult(pagedResult);
}
/// <summary>
/// Delete a specific conversation and all of it's activities.
/// </summary>
/// <param name="channelId">Channel Id where conversation took place.</param>
/// <param name="conversationId">Id of the conversation to delete.</param>
/// <returns>A <see cref="Task"/>A task that represents the work queued to execute.</returns>
public async Task DeleteTranscriptAsync(string channelId, string conversationId)
{
if (string.IsNullOrEmpty(channelId))
{
throw new ArgumentNullException($"{nameof(channelId)} should not be null");
}
if (string.IsNullOrEmpty(conversationId))
{
throw new ArgumentNullException($"{nameof(conversationId)} should not be null");
}
using (var context = GetTranscriptContext)
{
context.RemoveRange(context.Transcript.Where(item => item.Conversation == conversationId && item.Channel == channelId));
await context.SaveChangesAsync();
}
}
}
}