public async Task SendMessage(string message) { ChatUserModel user = null; if (_userCache.TryGetValue(CurrentUserId(), out user)) { if (user.ChatBanEnd.HasValue && user.ChatBanEnd.Value > DateTime.UtcNow) { return; } if (await IsSpam(user)) { return; } var chatMessage = new ChatMessageModel { Message = message, Timestamp = GetTime(), UserName = CurrentUserName(), Icon = user.ChatIcon, IsEnabled = true, }; await SaveMessage(chatMessage); await Clients.All.NewMessage(chatMessage, GetTime()); } }
public void SetChatDetails(ChatUserModel chatUser) { if (this.ID > 0 && chatUser != null) { this.SetMixerRoles(chatUser.userRoles); } }
public async Task <IActionResult> CreateEvent(int?ID) { if (ID == null) { ChatUserModel admin = await _userManager.GetUserAsync(this.User); Models.Events.Event newCalendar = new Models.Events.Event(); if (admin.AdministratedCalendars == null) { admin.AdministratedCalendars = new List <Models.Events.Event>(); } admin.AdministratedCalendars.Add(newCalendar); if (admin.Calendars == null) { admin.Calendars = new List <ChatUserModel_Event>(); } ChatUserModel_Event JoinTable = new ChatUserModel_Event(); JoinTable.Calendar = newCalendar; JoinTable.ChatUserModel = admin; admin.Calendars.Add(JoinTable); newCalendar.Members.Add(JoinTable); _context.Events.Add(newCalendar); _context.ChatUserModel_Event.Add(JoinTable); _context.SaveChanges(); return(View(newCalendar.Id)); } //Create Calendar here stuff return(View(ID)); }
public async Task AddInvitedUser(string ID, string ChatUser) { if (Int32.TryParse(ID, out int _ID)) { var Calendar = _context.Events.Where(x => x.Id == _ID).FirstOrDefault(); if (Calendar != null) { if (Calendar.Members.Where(x => x.ChatUserModel.ChatUserName == ChatUser).Count() == 0) { ChatUserModel user = _context.ChatUserModels.Where(x => x.ChatUserName.ToLower() == ChatUser.ToLower()).FirstOrDefault(); if (user != null) { ChatUserModel_Event newrelation = new ChatUserModel_Event(); newrelation.Calendar = Calendar; newrelation.ChatUserModel = user; if (Calendar.Members == null) { Calendar.Members = new List <ChatUserModel_Event>(); } Calendar.Members.Add(newrelation); if (user.Calendars == null) { user.Calendars = new List <ChatUserModel_Event>(); } user.Calendars.Add(newrelation); _context.ChatUserModel_Event.Add(newrelation); await _context.SaveChangesAsync(); } } } } }
public User_GiveAwayItem(ChatUserModel user, GiveAwayItem item) { UserID = user.Id; User = user; GiveAwayItemID = item.Id; GiveAwayItem = item; }
public async Task <IActionResult> RollStats(string GM) { string stats = ""; int sum = 0; for (int i = 0; i < 6; i++) { int result = Roll(4, 6, 1); sum += result; stats += result.ToString() + $" ({getBoni(result)})"; if (i != 5) { stats += ","; } } ChatUserModel user = await _userManager.GetUserAsync(this.User); if (GM != user.ChatUserName) { _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = GM, Message = $"{user.ChatUserName} hat {stats} Stats ({sum}) für den Charakter gewürfelt " }); } _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = user.ChatUserName, Message = $"Du hast {stats} Stats ({sum}) für den Charakter gewürfelt." }); return(RedirectToAction("Index")); }
public async Task <UserViewModel> AddOrUpdateUser(ChatUserModel chatUser) { if (chatUser.userId.HasValue) { await this.LockWrapper(async() => { bool performFirstUserJoin = !ChannelSession.Settings.UserData.ContainsKey(chatUser.userId.GetValueOrDefault()); if (!this.users.ContainsKey(chatUser.userId.GetValueOrDefault())) { this.users[chatUser.userId.GetValueOrDefault()] = new UserViewModel(chatUser); await this.users[chatUser.userId.GetValueOrDefault()].RefreshDetails(getChatDetails: false); } this.users[chatUser.userId.GetValueOrDefault()].SetChatDetails(chatUser); if (performFirstUserJoin) { await this.PerformUserFirstJoin(this.users[chatUser.userId.GetValueOrDefault()]); } }); return(await this.GetUser(chatUser.userId.GetValueOrDefault())); } return(null); }
public void IsSubscribed_EmptyStreamName_Throws() { ChatUserModel model = new ChatUserModel(); string streamName = ""; Assert.That(() => model.IsSubscribed(streamName), Throws.ArgumentException); }
private static async Task CreateOrAddUserRoles(string role, string name, IServiceProvider serviceProvider) { try { var RoleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >(); var UserManager = serviceProvider.GetRequiredService <UserManager <ChatUserModel> >(); IdentityResult roleResult; //Adding Admin Role var roleCheck = await RoleManager.RoleExistsAsync(role); if (!roleCheck) { //create the roles and seed them to the database roleResult = await RoleManager.CreateAsync(new IdentityRole(role)); } //Assign Admin role to the main User here we have given our newly registered //login id for Admin management ChatUserModel user = await UserManager.FindByNameAsync(name); await UserManager.AddToRoleAsync(user, role); } catch (Exception) { } }
public void IsSubscribed_PreparedChatUserModelWithEmptySubscriptions_ReturnsFalse() { ChatUserModel model = new ChatUserModel(); string streamName = "StreamName"; Assert.That(model.IsSubscribed(streamName), Is.EqualTo(false)); }
private async void Client_OnSkillAttributionOccurred(object sender, ChatSkillAttributionEventModel skillAttribution) { if (!ChannelSession.Constellation.AvailableSkills.ContainsKey(skillAttribution.skill.skill_id)) { ChatUserModel chatUser = skillAttribution.GetUser(); UserViewModel user = await ChannelSession.ActiveUsers.AddOrUpdateUser(chatUser); if (user == null) { user = new UserViewModel(chatUser); } else { await user.RefreshDetails(); } user.UpdateLastActivity(); string message = null; if (skillAttribution.message != null && skillAttribution.message.message != null && skillAttribution.message.message.Length > 0) { ChatMessageViewModel messageModel = new ChatMessageViewModel(skillAttribution.message, user); message = messageModel.Message; } GlobalEvents.SkillUseOccurred(new SkillUsageModel(user, skillAttribution.skill, message)); } }
/// <summary> /// The details of the customer. /// </summary> /// <returns> /// The <see cref="ChatUserModel"/>. /// </returns> private ChatUserModel GetChatUserData() { var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); if (portalContext.User == null) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, "portalContext.User is null"); return(null); } var result = new ChatUserModel { Username = portalContext.User.GetAttributeValue <string>("adx_identity_username"), Id = portalContext.User.GetAttributeValue <Guid>("contactid"), FirstName = portalContext.User.GetAttributeValue <string>("firstname"), LastName = portalContext.User.GetAttributeValue <string>("lastname"), Email = portalContext.User.GetAttributeValue <string>("emailaddress1"), Phone = portalContext.User.GetAttributeValue <string>("telephone1") }; var customerType = portalContext.User.GetAttributeValue <OptionSetValue>("customertypecode"); if (customerType != null) { result.CustomerType = customerType.Value; } else { ADXTrace.Instance.TraceError(TraceCategory.Application, "customertypecode not set"); throw new NullReferenceException("customertypecode"); } return(result); }
public async Task <String> SubscriptionsData() { ChatUserModel usermodel = await _userManager.GetUserAsync(this.User); List <StreamSubscription> streamsubs = _context.StreamSubscriptions.Include(ss => ss.User).Include(ss => ss.Stream).Where(ss => ss.User == usermodel).ToList(); Table table = new Table(); Row row = new Row(false, true); row.AddColumn(new TextColumn(0, "StreamName", true)); row.AddColumn(new TextColumn(1, "Sub Status")); table.AddRow(row); //TODO Second Request for Streams not yet added foreach (var streamsub in streamsubs) { Row newrow = new Row(); newrow.AddColumn(new TextColumn(0, streamsub.Stream.StreamName)); if (streamsub.Subscribed == SubscriptionState.Subscribed) { newrow.AddColumn(new StreamSubColumn(1, true, streamsub.ID)); } else { newrow.AddColumn(new StreamSubColumn(1, false, streamsub.ID)); } table.AddRow(newrow); } return(table.getJson()); }
public static Command CreateCommandSendMessage(string botId, string userId, ChatUserModel from, Guid?reportType = null) { return(CreateCommandSendMessage(botId, new CommandSendMessageProperties() { UserId = userId, From = from, ReportType = reportType })); }
public async Task GetAndAddUser(uint userID) { ChatUserModel user = await ChannelSession.Connection.GetChatUser(ChannelSession.Channel, userID); if (user != null) { await this.AddUser(new UserViewModel(user)); } }
/// <summary> /// Gets information about the specified user. /// </summary> /// <param name="user">The user to get</param> /// <returns>The user's information</returns> public async Task <UserWithChannelModel> GetUser(ChatUserModel user) { Validator.ValidateVariable(user, "user"); if (user.userId != null) { return(await this.GetUser(user.userId.GetValueOrDefault())); } return(null); }
public async Task <IActionResult> OverViewData() { OverView data = new OverView(); data.AddCalendarLink = this.Url.Action("CreateEvent"); ChatUserModel user = await _userManager.GetUserAsync(this.User); data.Calendars = getRelevantCalendars(user); return(Json(data)); }
public void IsSubscribed_PreparedChatUserModelWithSubscriptions_ReturnsExpectedResult(string streamname, bool expectedResult) { Stream stream = new Stream("TestName"); ChatUserModel model = new ChatUserModel(new List <Stream>() { stream }); Assert.That(model.IsSubscribed(streamname), Is.EqualTo(expectedResult)); }
public void SetChatDetails(ChatUserModel chatUser, bool addToChat = true) { if (chatUser != null) { this.SetMixerRoles(chatUser.userRoles); if (addToChat) { this.IsInChat = true; } } }
public async Task RefreshChatDetails(bool addToChat = true) { if (!this.IsAnonymous && this.LastUpdated.TotalMinutesFromNow() >= 1) { ChatUserModel chatUser = await ChannelSession.Connection.GetChatUser(ChannelSession.Channel, this.ID); if (chatUser != null) { this.SetChatDetails(chatUser, addToChat); } } }
public override async Task OnDisconnected(bool stopCalled) { if (stopCalled) { var userId = CurrentUserId(); if (!string.IsNullOrEmpty(userId)) { ChatUserModel outVal = null; _userCache.TryRemove(userId, out outVal); } } await base.OnDisconnected(stopCalled); }
private static bool IsModelValid(ChatUserModel model) { if (null == model) { return(false); } if (Guid.Empty == model.User) { return(false); } return(true); }
private async Task <ChatUserModel> GenerateUser(SocketMessage arg) { using (var scope = _scopeFactory.CreateScope()) { var _context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); ChatUserModel newUser = new ChatUserModel(arg.Author.Username, _context.StreamModels.Where(x => x.StreamName != null)); newUser.SetInitialPassword(); var usermanager = scope.ServiceProvider.GetRequiredService <UserManager <ChatUserModel> >(); await usermanager.CreateAsync(newUser, newUser.InitialPassword); await CreateOrAddUserRoles("User", newUser.UserName); return(newUser); } }
public async Task RefreshDetails(bool getChatDetails = true) { if (this.ID > 0) { UserWithChannelModel user = await ChannelSession.Connection.GetUser(this.ID); if (user != null) { if (!string.IsNullOrEmpty(user.avatarUrl)) { this.AvatarLink = user.avatarUrl; } this.MixerAccountDate = user.createdAt; this.Sparks = (int)user.sparks; this.GameTypeID = user.channel.typeId.GetValueOrDefault(); this.Data.UpdateData(user); } if (getChatDetails) { ChatUserModel chatUser = await ChannelSession.Connection.GetChatUser(ChannelSession.Channel, this.ID); if (chatUser != null) { this.SetChatDetails(chatUser); } } this.FollowDate = await ChannelSession.Connection.CheckIfFollows(ChannelSession.Channel, this.GetModel()); if (this.IsSubscriber) { UserWithGroupsModel userGroups = await ChannelSession.Connection.GetUserInChannel(ChannelSession.Channel, this.ID); if (userGroups != null && userGroups.groups != null) { UserGroupModel subscriberGroup = userGroups.groups.FirstOrDefault(g => g.name.Equals("Subscriber") && g.deletedAt == null); if (subscriberGroup != null) { this.SubscribeDate = subscriberGroup.createdAt; } } } await this.SetCustomRoles(); } }
ChatModel InitializeChat(ChatDTO chat) { ChatModel chatModel = new ChatModel(); chatModel.Chat = chat; chatModel.DraftMessage = new MessageDTO(); foreach (var chatUser in NetworkManager.Client.GetChatUsers(chat)) { ChatUserModel chatUserModel = new ChatUserModel() { ChatUser = chatUser }; chatUserModel.User = new UserModel() { User = NetworkManager.Client.GetUser(chatUser.UserId) }; //if(chatUserModel.User.User.Photo != null) //{ // Stream photoStream ; // int photoId = (int)chatUserModel.User.User.Photo; // string downloadingFileName = Client.DownloadFile(ref photoId, out photoStream); // string downloadingFilePath = Path.Combine(fileDirectoryPath, downloadingFileName); // //if (!File.Exists(downloadingFilePath)) // //{ // // using(FileStream savingFileStream = new FileStream(downloadingFilePath,FileMode.Create)) // // { // // photoStream.Seek(0, SeekOrigin.Begin); // // photoStream.CopyTo(savingFileStream); // // } // //} // chatUserModel.User.UserPhoto = new System.Drawing.Bitmap(downloadingFilePath); //} chatModel.Members.Add(chatUserModel); } if (chatModel.Chat.IsPrivateChat) { chatModel.Chat.Name = chatModel.Members.FirstOrDefault((chatUserModel) => chatUserModel.User.User.UserId != NetworkManager.CurrentUser.UserId).User.User.Name; } foreach (var msg in NetworkManager.Client.GetMessages(chat)) { chatModel.Messages.Add(new MessageModel() { Message = msg, Sender = chatModel.Members.FirstOrDefault((chatMembers) => chatMembers.User.User.UserId == msg.SenderId).User }); } return(chatModel); }
private List <string> doRaffle(string channel) { List <string> winners = new List <string>(); bool repeatRaffle = false; using (var scope = _scopeFactory.CreateScope()) { var tmpcontext = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>(); var currentitem = tmpcontext.GiveAwayItems.Include(x => x.Applicants).ThenInclude(y => y.User).ThenInclude(x => x.ReceivedItems).Where(x => x.current).FirstOrDefault(); List <ChatUserModel> Applicants = null; ChatUserModel tmpwinner = null; if (currentitem != null && currentitem.Applicants.Count() > 0) { int min = getLeastGiveAwayCount(currentitem.Applicants); var elligableUsers = currentitem.Applicants.Where(x => x.User.ReceivedItems.Count() == min); int winnerindex = random.Next(elligableUsers.Count()); var winner = elligableUsers.ToArray()[winnerindex]; winners.Add(winner.User.ChatUserName); currentitem.Receiver = winner.User; tmpwinner = winner.User; currentitem.ReceiverID = winner.UserID; tmpcontext.SaveChanges(); _eventBus.TriggerEvent(EventType.CommandResponseReceived, new CommandResponseArgs { Channel = channel, MessageType = Eventbus.MessageType.ChannelMessage, Message = $"Gewonnen hat {winner.User.ChatUserName}" }); } if (currentitem.Applicants.Count() > 1 && tmpcontext.GiveAwayItems.Include(x => x.Applicants).ThenInclude(y => y.User).Where(x => x.Title == currentitem.Title && x.Id != currentitem.Id && x.ReceiverID == null).Count() > 0) { var newitem = tmpcontext.GiveAwayItems.Include(x => x.Applicants).ThenInclude(y => y.User).Where(x => x.Title == currentitem.Title && x.ReceiverID == null && x.current == false).FirstOrDefault(); foreach (var user in currentitem.Applicants.Where(x => x.UserID != tmpwinner.Id).ToList()) { var m_n_relation = new User_GiveAwayItem(user.User, newitem); newitem.Applicants.Add(m_n_relation); user.User.AppliedTo.Add(m_n_relation); } currentitem.current = false; newitem.current = true; tmpcontext.SaveChanges(); repeatRaffle = true; } } if (repeatRaffle) { winners.AddRange(doRaffle(channel)); } return(winners); }
public async Task <IActionResult> RollGold(string GM, int numdies, int die, int multiplikator) { int gold = Roll(numdies, die) * multiplikator; ChatUserModel user = await _userManager.GetUserAsync(this.User); if (GM != user.ChatUserName) { _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = GM, Message = $"{user.ChatUserName} hat {gold} gold für den Charakter gewürfelt." }); } _eventBus.TriggerEvent(EventType.DiscordMessageSendRequested, new MessageArgs { RecipientName = user.ChatUserName, Message = $"Du hast {gold} gold für den Charakter gewürfelt." }); return(RedirectToAction("Index")); }
public void GetUsers() { TestWrapper(async(MixerConnection connection) => { ChannelModel channel = await ChannelsServiceUnitTests.GetChannel(connection); IEnumerable <ChatUserModel> users = await connection.Chats.GetUsers(channel); Assert.IsNotNull(users); if (users.Count() > 0) { ChatUserModel user = await connection.Chats.GetUser(channel, users.First().userId.GetValueOrDefault()); } }); }
public async static Task Seed(IServiceProvider serviceProvider) { Contract.Ensures(Contract.Result <Task>() != null); using (var context = new Data.ApplicationDbContext(serviceProvider.GetRequiredService <DbContextOptions <Data.ApplicationDbContext> >())) { if (context.ChatUserModels.Any()) { return; } var usermanager = serviceProvider.GetRequiredService <UserManager <ChatUserModel> >(); var dev = new ChatUserModel { UserName = "******", ChatUserName = "******" }; await usermanager.CreateAsync(dev, "SetupPassword"); await SeedData.CreateOrAddUserRoles("Dev", "Dev", serviceProvider); } return; }
private async Task <bool> IsSpam(ChatUserModel user) { var messages = _messageCache .Where(x => x.IsEnabled) .OrderByDescending(x => x.Id) .Take(3); if (messages.Count() == 3 && messages.All(x => x.UserName == user.UserName)) { await NotificationService.SendNotification(new NotifyUser { Title = "Spam Filter", Message = "Blocked 3rd consecutive message.", Type = Enums.NotificationType.Error, UserId = CurrentUserId() }); return(true); } return(false); }