/// <summary> /// Remove all authentication data from user data saved as user data in bot data /// </summary> /// <param name="botData">Bot data</param> /// <param name="token">Cancellation token</param> /// <returns>Task</returns> public static Task LogoutAsync(this IBotData botData, IAuthProvider authProvider, CancellationToken token) { botData.UserData.RemoveValue($"{authProvider.Name}{ContextConstants.AuthResultKey}"); botData.UserData.RemoveValue($"{authProvider.Name}{ContextConstants.MagicNumberKey}"); botData.UserData.RemoveValue($"{authProvider.Name}{ContextConstants.MagicNumberValidated}"); return(Task.CompletedTask); }
public DeleteProfileScorable(IDialogStack stack, IBotData botData, IBotToUser botToUser, Func <IDialog <object> > makeroot) { SetField.NotNull(out this.stack, nameof(stack), stack); SetField.NotNull(out this.botData, nameof(botData), botData); SetField.NotNull(out this.botToUser, nameof(botToUser), botToUser); SetField.NotNull(out this.makeroot, nameof(makeroot), makeroot); }
/// <summary> /// Get access token for accessing resource. /// </summary> /// <param name="botData">Bot data</param> /// <param name="resourceId">Resource ID</param> /// <param name="token">Cancellation token</param> /// <returns>Access token as an awaitable task.</returns> public async static Task <string> GetTokenAsync(this IBotData botData, AuthenticationOptions authOptions, IAuthProvider authProvider, CancellationToken token) { AuthResult authResult = default; if (botData.UserData.TryGetValue($"{authProvider.Name}{ContextConstants.AuthResultKey}", out authResult)) { try { InMemoryTokenCacheADAL tokenCache = new InMemoryTokenCacheADAL(authResult.TokenCache); AuthenticationContext authContext = new AuthenticationContext(authOptions.Authority, tokenCache); var result = await authContext.AcquireTokenSilentAsync(authOptions.ResourceId, new ClientCredential(authOptions.ClientId, authOptions.ClientSecret), new UserIdentifier(authResult.UserUniqueId, UserIdentifierType.UniqueId)); authResult = result.FromADALAuthenticationResult(tokenCache); await botData.StoreAuthResultAsync(authResult, authProvider, token); } catch (Exception) { return(null); } return(authResult.AccessToken); } return(null); }
public DialogContext(IBotToUser botToUser, IBotData botData, IDialogStack stack, CancellationToken token) { SetField.NotNull(out this.botToUser, nameof(botToUser), botToUser); SetField.NotNull(out this.botData, nameof(botData), botData); SetField.NotNull(out this.stack, nameof(stack), stack); this.token = token; }
public static bool IsAgent(this IBotData botData) { bool isAgent = false; botData.ConversationData.TryGetValue(ISAGENT, out isAgent); return(isAgent); }
public DeleteProfileScorable(IDialogStack stack, IBotData botData, IBotToUser botToUser, Regex regex) { SetField.NotNull(out this.stack, nameof(stack), stack); SetField.NotNull(out this.botData, nameof(botData), botData); SetField.NotNull(out this.botToUser, nameof(botToUser), botToUser); SetField.NotNull(out this.regex, nameof(regex), regex); }
public WikiScorable(QnAMakerScorable inner, IDialogStack stack, IBotData botData, WikiQnAKnowledgeBaseService wikiService) { SetField.NotNull(out this.inner, nameof(inner), inner); SetField.NotNull(out this.stack, nameof(stack), stack); SetField.NotNull(out this.botData, nameof(botData), botData); SetField.NotNull(out this.wikiService, nameof(wikiService), wikiService); }
/// <summary> /// Initialize authentication scorable. /// </summary> /// <param name="botdata">Bot data</param> /// <param name="dialogTask">Dialog task</param> /// <param name="botToUser">Bot to user</param> /// <param name="resourceId">Azure active directory resource identifier.</param> public AuthenticationScorable(IBotData botdata, IDialogTask dialogTask, IBotToUser botToUser, AuthenticationOptions authOptions, IAuthProvider authProvider) { _botData = botdata; _dialogTask = dialogTask; this.authOptions = authOptions; this.authProvider = authProvider; }
/// <summary> /// Deletes all of the users private BotData. /// </summary> /// <param name="botData">Mandatory. User's private bot data to delete.</param> public void DeleteUserData(IBotData botData) { botData.RemoveValue(DataStoreKey.PreferredFirstName); botData.RemoveValue(DataStoreKey.PreferredBotPersona); botData.RemoveValue(DataStoreKey.PreferredWeatherLocation); botData.RemoveValue(DataStoreKey.HasCompletedGetStarted); }
public static void RemoveValue(this IBotData botData, DataStoreKey key) { DataStoreEntryAttribute attribute = key.GetDataStoreEntry(); if (attribute != null) { switch (attribute.DataStore) { case DataStore.User: botData.UserData.RemoveValue(key.GetKey()); break; case DataStore.Conversation: botData.ConversationData.RemoveValue(key.GetKey()); break; case DataStore.PrivateConversation: botData.PrivateConversationData.RemoveValue(key.GetKey()); break; default: throw new ArgumentOutOfRangeException(); } } }
public static void SetGet <T>(IBotData data, Func <IBotData, IBotDataBag> findBag, string key, T value) { int count; { var bag = findBag(data); count = bag.Count; T existing; Assert.IsFalse(bag.TryGetValue(key, out existing)); bag.SetValue(key, value); Assert.IsTrue(bag.TryGetValue(key, out existing)); Assert.AreEqual(existing, value); existing = bag.Get <T>(key); Assert.AreEqual(existing, value); Assert.AreEqual(count + 1, bag.Count); } { var bag = findBag(data); Assert.IsTrue(bag.RemoveValue(key)); Assert.AreEqual(count, bag.Count); Assert.IsFalse(bag.RemoveValue(key)); Assert.AreEqual(count, bag.Count); T existing; Assert.IsFalse(bag.TryGetValue(key, out existing)); } }
public DialogTaskManagerBotDataLoader(IBotData inner, IDialogTaskManager dialogTaskManager, IActivity activity, ILocaleFinder localeFinder) { SetField.NotNull(out this.inner, nameof(inner), inner); SetField.NotNull(out this.dialogTaskManager, nameof(dialogTaskManager), dialogTaskManager); SetField.NotNull(out this.localeFinder, nameof(localeFinder), localeFinder); SetField.NotNull(out this.activity, nameof(activity), activity); }
private async Task <Activity> HandleSystemMessage(Activity message) { if (message.Type == ActivityTypes.DeleteUserData) { // Implement user deletion here // If we handle user deletion, return a real message } else if (message.Type == ActivityTypes.ConversationUpdate) { Trace.TraceInformation("Conversation update"); ConnectorClient client = new ConnectorClient(new Uri(message.ServiceUrl)); using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, message)) { IBotData botData = scope.Resolve <IBotData>(); await botData.LoadAsync(CancellationToken.None); if (!botData.ConversationData.GetValueOrDefault <bool>("init")) { botData.ConversationData.SetValue("init", true); var reply = message.CreateReply("Hi!I'll post some random question every morning."); await client.Conversations.SendToConversationAsync(reply); var reply2 = message.CreateReply("Commands: " + Environment.NewLine + "\t\t - type `tours` to get a list of tours;" + Environment.NewLine + "\t\t - type `new` to get a new question;" + Environment.NewLine + "\t\t - type `answer` to get an answer to the current question;" + Environment.NewLine + "\t\t - type `level` to select a complexity level"); await client.Conversations.SendToConversationAsync(reply2); var reply3 = message.CreateReply("*All questions are taken from* " + "https://db.chgk.info/" + Environment.NewLine + "Copyright: " + "https://db.chgk.info/copyright"); await client.Conversations.SendToConversationAsync(reply3); var reply4 = message.CreateReply("Good luck! ;-)"); await client.Conversations.SendToConversationAsync(reply4); } } // Handle conversation state changes, like members being added and removed // Use Activity.MembersAdded and Activity.MembersRemoved and Activity.Action for info // Not available in all channels } else if (message.Type == ActivityTypes.ContactRelationUpdate) { // Handle add/remove from contact lists // Activity.From + Activity.Action represent what happened } else if (message.Type == ActivityTypes.Typing) { // Handle knowing tha the user is typing } else if (message.Type == ActivityTypes.Ping) { } return(null); }
public static bool IsInRole(this IBotData context, string role) { var userContext = LoadUser(context); return(userContext.Roles != null && userContext.Roles.Any( r => r.ToLower() == role.ToLower() )); }
public BotDialogContextArgs(IActivity activity, IDialogTask task, IBotData data, IBotToUser botToUser, ILifetimeScope scope) { Activity = activity; Task = task; BotData = data; DialogScope = scope; BotToUser = botToUser; }
public DialogTaskManager(string blobKeyPrefix, IBotData botData, IStackStoreFactory <DialogTask> stackStoreFactory, Func <IDialogStack, CancellationToken, IDialogContext> contextFactory) { SetField.NotNull(out this.blobKeyPrefix, nameof(blobKeyPrefix), blobKeyPrefix); SetField.NotNull(out this.botData, nameof(botData), botData); SetField.NotNull(out this.contextFactory, nameof(contextFactory), contextFactory); SetField.NotNull(out this.stackStoreFactory, nameof(stackStoreFactory), stackStoreFactory); }
public static UserContext LoadUser(this IBotData context) { UserContext user; if (!context.UserData.TryGetValue("User", out user)) { return(new UserContext()); } return(user); }
public FavoriteLocation GetFavoriteByIndex(IBotData botData, int index) { var favorites = this.GetFavorites(botData); if (index >= 0 && index < favorites.Count) { return(favorites[index]); } return(null); }
public static bool IsAuthenticated(this IBotData context) { if (context == null) { return(false); } var userContext = LoadUser(context); return(!string.IsNullOrEmpty(userContext?.Username)); }
public IList <FavoriteLocation> GetFavorites(IBotData botData) { List <FavoriteLocation> favorites; if (!botData.UserData.TryGetValue(FavoritesKey, out favorites)) { // User currently has no favorite locations. Return an empty list. favorites = new List <FavoriteLocation>(); } return(favorites); }
public void Add(IBotData botData, FavoriteLocation value) { var favorites = this.GetFavorites(botData); if (favorites.Count >= MaxFavoriteCount) { throw new InvalidOperationException("The max allowed number of favorite locations has already been reached."); } favorites.Add(value); botData.UserData.SetValue(FavoritesKey, favorites); }
/// <summary> /// Logs an IActivity as a Custom Event to AppInishgts. /// </summary> public static async Task TrackActivity(IActivity activity, IBotData botData = null, IDictionary <string, string> customProperties = null) { var et = BuildEventTelemetry(activity, customProperties); TelemetryClient.TrackEvent(et); // Track sentiment only for incoming messages. if (et.Name == TelemetryEventTypes.MessageReceived) { await TrackMessageSentiment(activity); } }
public void Delete(IBotData botData, FavoriteLocation value) { var favorites = this.GetFavorites(botData); var newFavorites = new List <FavoriteLocation>(); foreach (var favoriteItem in favorites) { if (!AreEqual(favoriteItem.Location, value.Location)) { newFavorites.Add(favoriteItem); } } botData.UserData.SetValue(FavoritesKey, newFavorites); }
/// <summary> /// POST: api/Messages /// Receive a message from a user and reply to it /// </summary> public async Task <HttpResponseMessage> Post([FromBody] Activity activity) { switch (activity.GetActivityType()) { // all messages pass through one dialog for now case ActivityTypes.Message: LuisModelAttribute attr = new LuisModelAttribute(ConfigurationManager.AppSettings[Constants.LuisModelIdKey], ConfigurationManager.AppSettings[Constants.LuisSubscriptionKey]); LuisService luisSvc = new LuisService(attr); await Conversation.SendAsync(activity, () => new GitHubLuisDialog(luisSvc)); break; // send a "hello" to someone who just joined the conversation (not all channels support this) case ActivityTypes.ConversationUpdate: IConversationUpdateActivity update = activity; using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, activity)) { IConnectorClient client = scope.Resolve <IConnectorClient>(); if (update.MembersAdded.Any()) { Activity reply = activity.CreateReply(); IEnumerable <ChannelAccount> newMembers = update.MembersAdded?.Where(t => t.Id != activity.Recipient.Id); foreach (var newMember in newMembers) { reply.Text = Constants.DemoText + $"Welcome {newMember.Name}! I can help you with getting information about your GitHub repos."; IBotData data = scope.Resolve <IBotData>(); await data.LoadAsync(CancellationToken.None); if (data.UserData.ContainsKey(Constants.AuthTokenKey)) { reply.Text += " It looks like you're already logged in, so what can I help you with?"; } else { reply.Text += " To get started, type **login** to authorize me to talk to GitHub on your behalf, or type **help** to get more information."; } await client.Conversations.ReplyToActivityAsync(reply); } } } break; } return(new HttpResponseMessage(HttpStatusCode.Accepted)); }
public static async Task Resume(ConversationHistory history) { Activity message = null; Trace.TraceInformation($"Resuming {history.PartitionKey} {history.PartitionKey}"); try { message = JsonConvert.DeserializeObject <ConversationReference>(history.Conversation).GetPostToBotMessage(); ConnectorClient client = new ConnectorClient(new Uri(message.ServiceUrl)); using (ILifetimeScope scope = DialogModule.BeginLifetimeScope(Conversation.Container, message)) { IBotData botData = scope.Resolve <IBotData>(); await botData.LoadAsync(CancellationToken.None); string todayDate = DateTime.UtcNow.ToShortDateString(); if (botData.ConversationData.GetValueOrDefault <string>("today") != todayDate) { botData.ConversationData.SetValue("today", todayDate); await botData.FlushAsync(CancellationToken.None); await botData.LoadAsync(CancellationToken.None); IMessageActivity temp = message.CreateReply().AsMessageActivity(); IMessageActivity reply = await RootDialog.PostNewQuestion(botData.ConversationData, temp); if (reply != null) { await client.Conversations.SendToConversationAsync((Activity)reply); } //flush dialog stack await botData.FlushAsync(CancellationToken.None); } } } catch (Exception ex) { Trace.TraceError($"Exception when resuming conversation {message.Conversation?.Id}", ex); } }
public void Update(IBotData botData, FavoriteLocation currentValue, FavoriteLocation newValue) { var favorites = this.GetFavorites(botData); var newFavorites = new List <FavoriteLocation>(); foreach (var item in favorites) { if (AreEqual(item.Location, currentValue.Location)) { newFavorites.Add(newValue); } else { newFavorites.Add(item); } } botData.UserData.SetValue(FavoritesKey, newFavorites); }
public static void Clear(this IBotData botData, DataStore store) { switch (store) { case DataStore.User: botData.UserData.Clear(); break; case DataStore.Conversation: botData.ConversationData.Clear(); break; case DataStore.PrivateConversation: botData.PrivateConversationData.Clear(); break; default: throw new ArgumentOutOfRangeException(); } }
/// <summary> /// Ensures that the request is valid. /// </summary> /// <param name="botData">Private bot data</param> /// <param name="stateData">Data extracted from the state parameter.</param> /// <returns><c>true</c> if the request is valid; otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="botData"/> is null. /// or /// <paramref name="stateData"/> is null. /// </exception> private static bool Validate(IBotData botData, IDictionary <string, string> stateData) { string uniqueId; botData.AssertNotNull(nameof(botData)); stateData.AssertNotNull(nameof(stateData)); if (botData.PrivateConversationData.TryGetValue(BotConstants.UniqueIdentifierKey, out uniqueId)) { if (!uniqueId.Equals(stateData[BotConstants.UniqueIdentifierKey], StringComparison.CurrentCultureIgnoreCase)) { return(false); } } else { return(false); } return(stateData[BotConstants.UniqueIdentifierKey].Equals(uniqueId, StringComparison.CurrentCultureIgnoreCase)); }
public static T GetValueOrDefault <T>(this IBotData botData, DataStoreKey key, T defaultValue = default(T)) { DataStoreEntryAttribute attribute = key.GetDataStoreEntry(); if (attribute != null) { switch (attribute.DataStore) { case DataStore.User: return(botData.UserData.GetValueOrDefault(key.GetKey(), defaultValue)); case DataStore.Conversation: return(botData.ConversationData.GetValueOrDefault(key.GetKey(), defaultValue)); case DataStore.PrivateConversation: return(botData.PrivateConversationData.GetValueOrDefault(key.GetKey(), defaultValue)); default: throw new ArgumentOutOfRangeException(); } } return(defaultValue); }
public AgentLoginScorable(IBotData botData, Provider provider) { SetField.NotNull(out this.botData, nameof(botData), botData); SetField.NotNull(out this.provider, nameof(provider), provider); }