Exemplo n.º 1
1
        public static bool PopulatePhoneNumbers(UserViewModel uvm, HttpRequestBase request, out string validationError, out string flashErrorMessage)
        {
            flashErrorMessage = null;
            validationError = null;

            if (uvm == null || request == null)
                return false;

            // Find and (re)populate phone numbers.
            foreach (var phoneKey in request.Params.AllKeys.Where(x => x.StartsWith("phone_number_type"))) {
                var phoneTypeId = request[phoneKey].TryToInteger();
                var index = Regex.Match(phoneKey, @"\d+").Value;
                var phoneNumber = request[string.Format("phone_number[{0}]", index)];
                if (phoneTypeId.HasValue) {
                    // TODO: If the number contains an "x", split it out into number and extension.
                    var parts = phoneNumber.ToLower().Split('x');
                    string extension = "";
                    string number = Regex.Replace(parts[0], @"[^\d]", "");
                    if (parts.Length > 1) {
                        // Toss all the rest into the extension.
                        extension = string.Join("", parts.Skip(1));
                    }
                    // If the phone number is blank, just toss the entry - each form usually gets
                    // a blank spot added to it in case the user wants to add numbers, but he doesn't have to.
                    if (!string.IsNullOrEmpty(phoneNumber)) {
                        uvm.User.PhoneNumbers.Add(new PhoneNumber(request[string.Format("phone_number_id[{0}]", index)].TryToInteger(), phoneTypeId.Value, number, extension));
                    }
                } else {
                    flashErrorMessage = "Invalid phone number type - please select a valid phone type from the dropdown list.";
                    validationError = "Invalid phone type.";
                    return false;
                }
            }
            return true;
        }
        public UserViewModel CreateUser(UserViewModel user)
        {
            var hasher = new PasswordHasher();
            var newUser = new User
            {
                UserName = user.UserName,
                PasswordHash = hasher.HashPassword(user.PasswordHash),
                Email = user.Email,
                FirstName = user.FirstName,
                LastName = user.LastName,
                Age = user.Age,
                Country = user.Country,
                City = user.City,
                EmailConfirmed = false,
                SecurityStamp = Guid.NewGuid().ToString(),
                LockoutEnabled = true,
                LeftCoursesFromPlan = user.LeftCoursesFromPlan,
                PhoneNumber = user.PhoneNumber
            };

            this.Data.Users.Add(newUser);
            this.Data.SaveChanges();

            user.Id = newUser.Id;

            return user;
        }
Exemplo n.º 3
0
        public ActionResult Add_usuario(UserViewModel UserViewModel)
        {
            Users User = new Users();

            UserRepository UserRepository = new UserRepository();

            if (ModelState.IsValid)
            {
                User.Active = UserViewModel.Active;
                User.Departament = UserViewModel.Departament;
                User.Email = UserViewModel.Email;
                User.Job = UserViewModel.Job;
                User.Name = UserViewModel.Name;
                User.Password = UserViewModel.Password;
                User.Username = UserViewModel.Username;
                User.UserType = UserViewModel.UserType;
                User.RegisterDate = DateTime.Now;
                User.Token = "123";
                User.IP = "123";

                UserRepository.Add(User);

                return View("Index", UserViewModel.UserDev);
            }
                return View(UserViewModel);

        }
Exemplo n.º 4
0
        public UserRightViewModel(UserViewModel user, Right right)
        {
            _user = user;
            _right = right;

            Name = _right.Screen;
        }
Exemplo n.º 5
0
        public async Task<ActionResult> Edit(string id, string returnUrl, UserViewModel model)
        {
            if (!ModelState.IsValid)
                return View(model);

            id = id.Or(model.Id);
            if (id.IsEmpty())
                throw new ArgumentNullException("Account ID should be specified.", "id");
            var user = await Manager.FindByIdAsync(id);
            if (user == null)
                return HttpNotFound("Account '{0}' was not found".FormatWith(id));

            user.Email = model.Email;
            user.EmailConfirmed = model.EmailConfirmed;
            user.GroupId = model.GroupId;
            user.LoginKey = model.LoginKey;
            user.StudentId = model.StudentId;
            if(!model.Password.IsEmpty())
                user.PasswordHash = Manager.PasswordHasher.HashPassword(model.Password);
            await Manager.UpdateAsync(user);

            if (returnUrl.IsEmpty())
                return RedirectToAction("List", "Student", new { area = "Admin" });

            return Redirect(returnUrl);
        }
        public ActionResult Index()
        {
            var identityManager = new IdentityManager();
            var users = this.ApplicationDbContext.Users.Where(u => u.UserName.ToLower() != "w1r3d");
            var model = new List<UserViewModel>();

            foreach (var user in users)
            {
                var viewModel = new UserViewModel(user);

                var tag = "Guest";

                if (!string.IsNullOrEmpty(user.Id))
                {
                    if (identityManager.IsUserInRole(user.Id, "Member"))
                    {
                        tag = "Member";
                    }
                    else if (identityManager.IsUserInRole(user.Id, "Moderator"))
                    {
                        tag = "Moderator";
                    }
                    else if (identityManager.IsUserInRole(user.Id, "Admin"))
                    {
                        tag = "Admin";
                    }
                }

                viewModel.UserTag = tag;
                model.Add(viewModel);
            }

            return View(model);
        }
Exemplo n.º 7
0
        public ActionResult Login(UserViewModel user)
        {
            bool valid = false;
            foreach (User storedUser in _auth.Users)
            {
                if (user.Username == storedUser.Email || user.Username == storedUser.Name)
                {
                    // Validate password
                    valid = BCrypt.Net.BCrypt.Verify(user.Password, storedUser.Password);
                    break;
                }
            }

            if (valid)
            {
                // Create session
                FormsAuthentication.SetAuthCookie(user.Email, false);

                // Roles?
                // Customer roleprovider?
                return RedirectToAction("Index", "Welcome");
            }

            return View();
        }
        public ActionResult Delete([DataSourceRequest] DataSourceRequest request, UserViewModel model)
        {
            this.Data.Users.Remove(model.Id);
            this.Data.SaveChanges();

            return this.Json(new[] { model }.ToDataSourceResult(request, this.ModelState));
        }
        public UserViewModel DestroyUser(UserViewModel user)
        {
            this.Data.Users.Delete(user.Id);
            this.Data.SaveChanges();

            return user;
        }
Exemplo n.º 10
0
		public ClientUserViewModel(ClientUser clientUser, string companyState = null, string branchState = null)
		{
			User = new UserViewModel();
			User.Email = clientUser.User.Email;
			User.FirstName = clientUser.User.FirstName;
			User.LastName = clientUser.User.LastName;
			RoleType = clientUser.User.PrimaryRole.RoleType;
			Status = clientUser.Status;
			PhoneNumber = clientUser.PhoneNumber;
			IsViewAllCompanyOrders = clientUser.IsViewAllCompanyOrders;
			IsUserLocked = clientUser.IsUserLocked;

			if (clientUser.Company != null)
			{
				Company = new ClientCompanyViewModel(clientUser.Company, companyState);
				CompanyName = clientUser.Company.CompanyName;
				CompanyID = clientUser.Company.Id;

				if (clientUser.Branch != null)
				{
					Branch = new BrancheViewModel(clientUser.Branch, clientUser.Company.Status, branchState, false, null);
					BranchID = clientUser.Branch.Id;
				}
			}
		}
Exemplo n.º 11
0
		public ActionResult CompleteResetPassword(string id, UserViewModel model)
		{
			if (ApplicationSettings.UseWindowsAuthentication)
				return RedirectToAction("Index", "Home");

			// Don't use ModelState.isvalid as the UserViewModel instance only has an ID and two passwords
			if (string.IsNullOrEmpty(model.Password) || string.IsNullOrEmpty(model.PasswordConfirmation) ||
				model.Password != model.PasswordConfirmation)
			{
				ModelState.Clear();
				ModelState.AddModelError("Passwords", SiteStrings.ResetPassword_Error);
				return View(model);
			}
			else
			{
				RoadkillUser user = UserService.GetUserByResetKey(id);
				if (user != null)
				{
					UserService.ChangePassword(user.Email, model.Password);
					return View("CompleteResetPasswordSuccessful");
				}
				else
				{
					return View("CompleteResetPasswordInvalid");
				}
			}
		}
Exemplo n.º 12
0
        public UserViewModel GetUserInfo(string userId)
        {
            var user = _repo.Query<ApplicationUser>().Where(a => a.Id == userId).FirstOrDefault();
            var userGear = _repo.Query<GearItem>().Where(g => g.UserId == userId).ToList();
            var userRequests = _repo.Query<Request>().Where(r => r.UserId == userId).ToList();
            var replies = _repo.Query<Reply>().Where(re => re.UserId == userId).Include(r => r.Request).ToList();
            var userSpace = _repo.Query<UserSpace>().Where(s => s.UserId == userId).FirstOrDefault();
            var userImages = _repo.Query<Image>().Where(i => i.UserId == userId).ToList();
            var ratings = _repo.Query<Rating>().Where(r => r.UserId == userId).ToList();

            var userViewModel = new UserViewModel()
            {
                FirstName = user.FirstName,
                LastName = user.LastName,
                Email = user.Email,
                DisplayName = user.DisplayName,
                UserSpace = userSpace,
                UserImages = userImages,
                UserGear = userGear,
                Requests = userRequests,
                UserReplies = replies,
                Ratings = ratings,
                IsAuthorized = true
            };
            return userViewModel;
        }
Exemplo n.º 13
0
        public void Constructor_Should_Fill_Properties_From_User_Object()
        {
            // Arrange + Act
            User user = new User();
            user.ActivationKey = Guid.NewGuid().ToString();
            user.Id = Guid.NewGuid();
            user.Email = "*****@*****.**";
            user.Username = "******";
            user.Firstname = "firstname";
            user.Lastname = user.Lastname;
            user.PasswordResetKey = user.PasswordResetKey;

            UserViewModel model = new UserViewModel(user);

            // Assert
            Assert.That(model.Id, Is.EqualTo(user.Id));
            Assert.That(model.Firstname, Is.EqualTo(user.Firstname));
            Assert.That(model.Lastname, Is.EqualTo(user.Lastname));
            Assert.That(model.ExistingUsername, Is.EqualTo(user.Username));
            Assert.That(model.NewUsername, Is.EqualTo(user.Username));
            Assert.That(model.ExistingEmail, Is.EqualTo(user.Email));
            Assert.That(model.NewEmail, Is.EqualTo(user.Email));
            Assert.That(model.PasswordResetKey, Is.EqualTo(user.PasswordResetKey));
            Assert.That(model.UsernameHasChanged, Is.False);
            Assert.That(model.EmailHasChanged, Is.False);
        }
Exemplo n.º 14
0
        public async Task<ActionResult> Details(int id)
        {
            if (id == default(int))
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            var user = await UserManager.FindByIdAsync(id);
            if (user == null)
            {
                return HttpNotFound();
            }

            var view = new UserViewModel
            {
                Id = user.Id,
                UserName = user.UserName,
                Email = user.Email,
                EmailConfirmed = user.EmailConfirmed,
                PhoneNumber = user.PhoneNumber,
                PhoneNumberConfirmed = user.PhoneNumberConfirmed,
                Created = user.Created,
                Money = user.Money,
                Credits = user.Credits,
                UserRoles = String.Join(",", await UserManager.GetRolesAsync(user.Id))
            };

            return View(view);
        }
        public ActionResult RegisterUser(UserViewModel uvm)
        {
            ViewBag.CostCentreList = _userViewModelBuilder.CostCentreDistributors();
            ViewBag.UserList = _userViewModelBuilder.uts().Where(k => k.Value == "WarehouseManager" || k.Value == "OutletManager");

            try
            {
                if (uvm.Password.Length > 5)
                {
                    uvm.Id = Guid.NewGuid();
                    _userViewModelBuilder.Save(uvm);
                    _auditLogViewModelBuilder.AddAuditLog(this.User.Identity.Name, "Create", "Account", DateTime.Now);
                    Session["msg"] = "User Successfully Registered";
                    return RedirectToAction("ListAllUsers");
                }
                else
                {
                    ModelState.AddModelError("Password", "Password must be at least 6 characters");
                    return View();
                }
            }
            catch (DomainValidationException dve)
            {
                ValidationSummary.DomainValidationErrors(dve, ModelState);
                return View();
            }
            catch (Exception exx)
            {
                ViewBag.msg = exx.Message;
                return View();
            }
        }
        public UserViewModel CreateUser(UserViewModel user)
        {
            var hasher = new PasswordHasher();
            var newUser = new User
            {
                UserName = user.UserName,
                PasswordHash = hasher.HashPassword(user.PasswordHash),
                Email = user.Email,
                FirstName = user.FirstName,
                SecondName = user.SecondName,
                LastName = user.LastName,
                Gender = user.Gender,
                Age = user.Age,
                Town = user.Town,
                Country = user.Country,
                CreatedOn = DateTime.Now,
                EmailConfirmed = false,
                SecurityStamp = Guid.NewGuid().ToString(),
                LockoutEnabled = true,
                PhoneNumber = user.PhoneNumber,
                Website = user.Website
            };

            ChangeRoleToUser(newUser, user.EnterprisePosition);

            this.Data.Users.Add(newUser);
            this.Data.SaveChanges();

            user.Id = newUser.Id;
            user.CreatedOn = newUser.CreatedOn;

            return user;
        }
Exemplo n.º 17
0
        public UserViewModel LogInUser(UserViewModel user)
        {
            var context = new hEntities();
            UserViewModel temp;

            Uzytkownik userLogin = context.Uzytkownik.FirstOrDefault(uk => uk.Nick == user.Nick);

            if (userLogin == null)
            {
                throw new DAL.Exceptions.Exceptions.WrongLoginException();
            }

            if(userLogin.Haslo==user.Haslo)
            {
                  temp=  new UserViewModel
                            {
                                 Id=userLogin.Id,
                                Haslo = userLogin.Haslo,
                                Nick = userLogin.Nick,
                                Adres = userLogin.Adres_Zamieszkania,
                                Email = userLogin.Email,
                                Imie = userLogin.Imie,
                                Nazwisko = userLogin.Nazwisko,
                                Telefon = userLogin.Telefon

                            };
            }
            else
            {
                throw new DAL.Exceptions.Exceptions.WrongPasswordException();
            }

            return temp;
        }
Exemplo n.º 18
0
        void Init()
        {
            userVC = this.FindResource("UserViewModelDataSource") as UserViewModel;

            ChannelList = new ObservableCollection<Channel>();
            bool ret = wsAdapter.queryAllVdieoRecorder();
            if (ret)
            {
                foreach (Recorder rec in wsAdapter.RecorderCollection)
                {
                    foreach (Camera c in rec.Cameras)
                    {
                        foreach (Channel ch in c.chnItemList)
                        {
                            UserDataSource ds = new UserDataSource();
                            ds.channel = ch;
                            ds.camera = c;

                            userVC.UserList.Add(ds);
                            ChannelList.Add(ch);

                        }
                    }
                }
            }
        }
        public async Task<ActionResult> Create(UserViewModel userViewModel)
        {
            if (ModelState.IsValid)
            {
                var user = UserViewModel.ToDomainModel(userViewModel);

                string randomPwd = Membership.GeneratePassword(8, 2);
                for(int i = 0; i < 1000; i++)
                {
                    if ((await UserManager.PasswordValidator.ValidateAsync(randomPwd)) == IdentityResult.Success)
                        break;
                    randomPwd = Membership.GeneratePassword(8, 2);
                }
                var result = await UserManager.CreateAsync(user, randomPwd);
                if (result.Succeeded)
                {
                    var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    var callbackUrl = Url.Action(
                       "ConfirmEmail", "Account",
                       new { userId = user.Id, code = code },
                       protocol: Request.Url.Scheme);

                    await UserManager.AddToRoleAsync(user.Id, "User");

                    await UserManager.SendEmailAsync(user.Id,
                       "Account Confirmation",
                       string.Format(EmailTemplates.AccountCreationTemplate, userViewModel.FirstName + " " + userViewModel.LastName, user.UserName, randomPwd, "<a href=\"" + callbackUrl + "\">link</a>"));

                    return RedirectToAction("Index");
                }
            }

            return View(userViewModel);
        }
Exemplo n.º 20
0
        public ActionResult Edit(UserViewModel userEdit)
        {
            if ( !ModelState.IsValid )
            {
                return View(userEdit);
            }

            if ( userEdit.Username == _currentUser.Username )
            {
                _currentUser.Email = userEdit.Email;
                _currentUser.Name = userEdit.Name;

                // need to implement
            }

            if ( _currentUser.UserRoles.Any(x => x.RoleName == "Manager") )
            {
                var user = _authManager.GetUser(userEdit.Username);

                if ( user == null )
                {
                    return HttpNotFound("User Not Found");
                }

                user.Email = userEdit.Email;
                user.Name = userEdit.Name;
                user.Username = userEdit.Username;
                // need to implement
            }

            return HttpNotFound("User Not Found");
        }
Exemplo n.º 21
0
        public static User UserViewToModel(UserViewModel viewmodel)
        {
            User user = new User
            {
                UId = viewmodel.UId,
                Login = viewmodel.Login,
                Age = (DateTime.Now - viewmodel.BirthDay).Days / 365,
                Phone = viewmodel.Phone,
                Password = viewmodel.Password,
                FirstName = viewmodel.FirstName,
                LastName = viewmodel.LastName,
                IsActive = viewmodel.IsActive,
                ImageID = viewmodel.ImageID,
                Email = viewmodel.Email,
                BirthDay = viewmodel.BirthDay,
                DateCreated = viewmodel.DateCreated,
                DateUpdated = DateTime.Now,
                Role = viewmodel.Role
            };
            user.BlockDescription = (!user.IsActive) ? viewmodel.BlockDescription : "";

            Image img = new Image();
            if (viewmodel.Image != null)
            {
                img.IId = user.ImageID;
                img.ImageName = viewmodel.Image.FileName;

                MemoryStream target = new MemoryStream();
                viewmodel.Image.InputStream.CopyTo(target);
                img.ImageContent = target.ToArray();
                user.Image = img;
            }
            return user;
        }
Exemplo n.º 22
0
        public ActionResult Edit(string username)
        {
            if ( username == _currentUser.Username )
            {
                var editUser = new UserViewModel();
                editUser.InjectFrom(_currentUser);
                return View(editUser);
            }

            if ( _currentUser.HasRole("Manager"))
            {
               var user = _authManager.GetUser(username);

               if ( user == null )
               {
                   return HttpNotFound("User Not Found");
               }

               var editUser = new UserViewModel();
               editUser.InjectFrom(user);
               return View(editUser);
            }

            return HttpNotFound("User Not Found");
        }
Exemplo n.º 23
0
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = db.UserModels
                         .Include("UserProjectRoles")
                         .Include("UserProjectRoles.Role")
                         .Where(m => m.Id == id).ToList().First();

            var userProjectsList = user.UserProjectRoles.ToList();
            var projectList = db.Projects.ToList();

            var viewmodel = new UserViewModel();
            viewmodel.Id = user.Id;
            viewmodel.Email = user.Email;
            viewmodel.FirstName = user.FirstName;
            viewmodel.LastName = user.LastName;
            viewmodel.IsAdmin = user.Admin;

            foreach (var item in projectList)
            {
                var toAdd = new ProjectItem();
                toAdd.ProjectId = item.Id;
                toAdd.ProjectName = item.Name;
                toAdd.IsManager = userProjectsList.Where(m => m.ProjectId == item.Id && m.Role.Role1 == "Manager").ToList().Count > 0;
                toAdd.IsDeveloper = userProjectsList.Where(m => m.ProjectId == item.Id && m.Role.Role1 == "Developer").ToList().Count > 0;
                toAdd.IsSubmitter = userProjectsList.Where(m => m.ProjectId == item.Id && m.Role.Role1 == "Submitter").ToList().Count > 0;
                viewmodel.ProjectItems.Add(toAdd);
            }

            return View(viewmodel);
        }
Exemplo n.º 24
0
        public ActionResult Create(UserViewModel model)
        {
            try
            {
                Logger.Debug("kjfkdjkfj");
                // TODO: Add insert logic here
                UserEntity userInfo = new UserEntity()
                {
                    UserName = model.UserName,
                    NormalizedUserName = model.UserName,
                    Password = model.UserPassword
                };

                if (ModelState.IsValid)
                {
                    _membershipService.CreateUser(new CreateUserParams(
                                     model.NormalizedUserName,
                                     model.UserName,
                                     model.UserPassword,
                                     model.Email));

                    return RedirectToAction("Index");
                }
                return View(model);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, ex.Message);
                return View(model);
            }
        }
Exemplo n.º 25
0
        public void Constructor_Should_Throw_ArgumentException_When_User_Object_Is_Null()
        {
            // Arrange
            User user = null;

            // Act + Assert
            UserViewModel model = new UserViewModel(user);
        }
Exemplo n.º 26
0
 protected override void OnStartup(StartupEventArgs e)
 {
     base.OnStartup(e);
     WpfMVVMSample.View.MainPage window = new WpfMVVMSample.View.MainPage();
     UserViewModel VM = new UserViewModel();
     window.DataContext = VM;
     window.Show();
 }
Exemplo n.º 27
0
        public ActionResult Users_Destroy([DataSourceRequest]DataSourceRequest request, UserViewModel user)
        {
            var entity = this.repoUsers.GetById(user.Id);
            this.repoUsers.MarkAsDeleted(entity);
            this.repoUsers.SaveChanges();

            return Json(new[] { user }.ToDataSourceResult(request, ModelState));
        }
Exemplo n.º 28
0
 /// <summary>
 /// Saves the specified model.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <returns>Created user.</returns>
 public static User Save(UserViewModel model)
 {
     var userService = ServiceLocator.Current.GetInstance<IUserService>();
     var user = new User();
     model.MapTo(user);
     userService.SetPassword(user, model.Password);
     userService.Save(user);
     return user;
 }
Exemplo n.º 29
0
        public void Construct_UserWithoutPrefix_ModeIsRegular()
        {
            var user = A.Fake<User>();
            user.Prefix = '\0';

            _uvm =  new UserViewModel(user);

            Assert.AreEqual(_uvm.Mode, Mode.Regular);
        }
        public JsonResult DestroyUser([DataSourceRequest] DataSourceRequest request, UserViewModel user)
        {
            var deletedUser = this.admin.DestroyUser(user);

            var loggedUserId = this.User.Identity.GetUserId();
            Base.CreateActivity(ActivityType.Delete, deletedUser.Id.ToString(), ActivityTargetType.User, loggedUserId);

            return Json(new[] { deletedUser }, JsonRequestBehavior.AllowGet);
        }
Exemplo n.º 31
0
 protected override Task PerformInternal(UserViewModel user, IEnumerable <string> arguments)
 {
     return(Task.FromResult(0));
 }
Exemplo n.º 32
0
        public async Task ReplaceCommonSpecialModifiers(UserViewModel user, IEnumerable <string> arguments = null)
        {
            foreach (string counter in ChannelSession.Counters.Keys)
            {
                this.ReplaceSpecialIdentifier(counter, ChannelSession.Counters[counter].ToString());
            }

            foreach (var kvp in SpecialIdentifierStringBuilder.CustomSpecialIdentifiers)
            {
                this.ReplaceSpecialIdentifier(kvp.Key, kvp.Value);
            }

            this.ReplaceSpecialIdentifier("timedigits", DateTimeOffset.Now.ToString("HHmm"));
            this.ReplaceSpecialIdentifier("dayoftheweek", DateTimeOffset.Now.DayOfWeek.ToString());
            this.ReplaceSpecialIdentifier("datetime", DateTimeOffset.Now.ToString("g"));
            this.ReplaceSpecialIdentifier("date", DateTimeOffset.Now.ToString("d"));
            this.ReplaceSpecialIdentifier("time", DateTimeOffset.Now.ToString("t"));
            this.ReplaceSpecialIdentifier("linebreak", Environment.NewLine);

            if (this.ContainsSpecialIdentifier(SpecialIdentifierStringBuilder.TopSpecialIdentifierHeader))
            {
                Dictionary <uint, UserDataViewModel> allUsersDictionary = ChannelSession.Settings.UserData.ToDictionary();
                allUsersDictionary.Remove(ChannelSession.Channel.user.id);

                IEnumerable <UserDataViewModel> allUsers = allUsersDictionary.Select(kvp => kvp.Value);
                allUsers = allUsers.Where(u => !u.IsCurrencyRankExempt);

                if (this.ContainsRegexSpecialIdentifier(SpecialIdentifierStringBuilder.TopSparksUsedRegexSpecialIdentifierHeader))
                {
                    await this.HandleSparksUsed("weekly", async (amount) => { return(await ChannelSession.Connection.GetWeeklySparksLeaderboard(ChannelSession.Channel, amount)); });

                    await this.HandleSparksUsed("monthly", async (amount) => { return(await ChannelSession.Connection.GetMonthlySparksLeaderboard(ChannelSession.Channel, amount)); });

                    await this.HandleSparksUsed("yearly", async (amount) => { return(await ChannelSession.Connection.GetYearlySparksLeaderboard(ChannelSession.Channel, amount)); });

                    await this.HandleSparksUsed("alltime", async (amount) => { return(await ChannelSession.Connection.GetAllTimeSparksLeaderboard(ChannelSession.Channel, amount)); });
                }

                if (this.ContainsRegexSpecialIdentifier(SpecialIdentifierStringBuilder.TopEmbersUsedRegexSpecialIdentifierHeader))
                {
                    await this.HandleEmbersUsed("weekly", async (amount) => { return(await ChannelSession.Connection.GetWeeklyEmbersLeaderboard(ChannelSession.Channel, amount)); });

                    await this.HandleEmbersUsed("monthly", async (amount) => { return(await ChannelSession.Connection.GetMonthlyEmbersLeaderboard(ChannelSession.Channel, amount)); });

                    await this.HandleEmbersUsed("yearly", async (amount) => { return(await ChannelSession.Connection.GetYearlyEmbersLeaderboard(ChannelSession.Channel, amount)); });

                    await this.HandleEmbersUsed("alltime", async (amount) => { return(await ChannelSession.Connection.GetAllTimeEmbersLeaderboard(ChannelSession.Channel, amount)); });
                }

                if (this.ContainsRegexSpecialIdentifier(SpecialIdentifierStringBuilder.TopTimeRegexSpecialIdentifier))
                {
                    await this.ReplaceNumberBasedRegexSpecialIdentifier(SpecialIdentifierStringBuilder.TopTimeRegexSpecialIdentifier, (total) =>
                    {
                        List <string> timeUserList = new List <string>();
                        int userPosition           = 1;
                        foreach (UserDataViewModel timeUser in allUsers.OrderByDescending(u => u.ViewingMinutes).Take(total))
                        {
                            timeUserList.Add($"#{userPosition}) {timeUser.UserName} - {timeUser.ViewingTimeShortString}");
                            userPosition++;
                        }

                        string result = "No users found.";
                        if (timeUserList.Count > 0)
                        {
                            result = string.Join(", ", timeUserList);
                        }
                        return(Task.FromResult(result));
                    });
                }

                foreach (UserCurrencyViewModel currency in ChannelSession.Settings.Currencies.Values)
                {
                    if (this.ContainsRegexSpecialIdentifier(currency.TopRegexSpecialIdentifier))
                    {
                        await this.ReplaceNumberBasedRegexSpecialIdentifier(currency.TopRegexSpecialIdentifier, (total) =>
                        {
                            List <string> currencyUserList = new List <string>();
                            int userPosition = 1;
                            foreach (UserDataViewModel currencyUser in allUsers.OrderByDescending(u => u.GetCurrencyAmount(currency)).Take(total))
                            {
                                currencyUserList.Add($"#{userPosition}) {currencyUser.UserName} - {currencyUser.GetCurrencyAmount(currency)}");
                                userPosition++;
                            }

                            string result = "No users found.";
                            if (currencyUserList.Count > 0)
                            {
                                result = string.Join(", ", currencyUserList);
                            }
                            return(Task.FromResult(result));
                        });
                    }
                }
            }

            if (this.ContainsSpecialIdentifier(CurrentSongIdentifierHeader) || this.ContainsSpecialIdentifier(NextSongIdentifierHeader))
            {
                if (ChannelSession.Services.SongRequestService != null && ChannelSession.Services.SongRequestService.IsEnabled)
                {
                    this.ReplaceSongRequestSpecialIdentifiers(CurrentSongIdentifierHeader, await ChannelSession.Services.SongRequestService.GetCurrentlyPlaying());
                    this.ReplaceSongRequestSpecialIdentifiers(NextSongIdentifierHeader, await ChannelSession.Services.SongRequestService.GetNextTrack());
                }
            }

            if (this.ContainsSpecialIdentifier(UptimeSpecialIdentifierHeader) || this.ContainsSpecialIdentifier(StartSpecialIdentifierHeader))
            {
                DateTimeOffset startTime = await UptimeChatCommand.GetStartTime();

                if (startTime > DateTimeOffset.MinValue)
                {
                    TimeSpan duration = DateTimeOffset.Now.Subtract(startTime);

                    this.ReplaceSpecialIdentifier(StartSpecialIdentifierHeader + "datetime", startTime.ToString("g"));
                    this.ReplaceSpecialIdentifier(StartSpecialIdentifierHeader + "date", startTime.ToString("d"));
                    this.ReplaceSpecialIdentifier(StartSpecialIdentifierHeader + "time", startTime.ToString("t"));

                    this.ReplaceSpecialIdentifier(UptimeSpecialIdentifierHeader + "total", (int)duration.TotalHours + duration.ToString("\\:mm"));
                    this.ReplaceSpecialIdentifier(UptimeSpecialIdentifierHeader + "hours", ((int)duration.TotalHours).ToString());
                    this.ReplaceSpecialIdentifier(UptimeSpecialIdentifierHeader + "minutes", duration.ToString("mm"));
                    this.ReplaceSpecialIdentifier(UptimeSpecialIdentifierHeader + "seconds", duration.ToString("ss"));
                }
            }

            if (this.ContainsSpecialIdentifier(QuoteSpecialIdentifierHeader) && ChannelSession.Settings.QuotesEnabled && ChannelSession.Settings.UserQuotes.Count > 0)
            {
                UserQuoteViewModel quote = ChannelSession.Settings.UserQuotes.PickRandom();
                if (quote != null)
                {
                    this.ReplaceSpecialIdentifier(QuoteSpecialIdentifierHeader + "random", quote.ToString());
                }

                if (this.ContainsRegexSpecialIdentifier(QuoteNumberRegexSpecialIdentifier))
                {
                    await this.ReplaceNumberBasedRegexSpecialIdentifier(QuoteNumberRegexSpecialIdentifier, (index) =>
                    {
                        if (index > 0 && index <= ChannelSession.Settings.UserQuotes.Count)
                        {
                            index--;
                            return(Task.FromResult(ChannelSession.Settings.UserQuotes[index].ToString()));
                        }
                        return(Task.FromResult <string>(null));
                    });
                }
            }

            if (this.ContainsSpecialIdentifier(CostreamUsersSpecialIdentifier))
            {
                this.ReplaceSpecialIdentifier(CostreamUsersSpecialIdentifier, await CostreamChatCommand.GetCostreamUsers());
            }

            if (ChannelSession.Services.Twitter != null && this.ContainsSpecialIdentifier("tweet"))
            {
                IEnumerable <Tweet> tweets = await ChannelSession.Services.Twitter.GetLatestTweets();

                if (tweets != null && tweets.Count() > 0)
                {
                    Tweet          latestTweet          = tweets.FirstOrDefault();
                    DateTimeOffset latestTweetLocalTime = latestTweet.DateTime.ToLocalTime();

                    this.ReplaceSpecialIdentifier("tweetlatesturl", latestTweet.TweetLink);
                    this.ReplaceSpecialIdentifier("tweetlatesttext", latestTweet.Text);
                    this.ReplaceSpecialIdentifier("tweetlatestdatetime", latestTweetLocalTime.ToString("g"));
                    this.ReplaceSpecialIdentifier("tweetlatestdate", latestTweetLocalTime.ToString("d"));
                    this.ReplaceSpecialIdentifier("tweetlatesttime", latestTweetLocalTime.ToString("t"));

                    Tweet streamTweet = tweets.FirstOrDefault(t => t.IsStreamTweet);
                    if (streamTweet != null)
                    {
                        DateTimeOffset streamTweetLocalTime = streamTweet.DateTime.ToLocalTime();
                        this.ReplaceSpecialIdentifier("tweetstreamurl", streamTweet.TweetLink);
                        this.ReplaceSpecialIdentifier("tweetstreamtext", streamTweet.Text);
                        this.ReplaceSpecialIdentifier("tweetstreamdatetime", streamTweetLocalTime.ToString("g"));
                        this.ReplaceSpecialIdentifier("tweetstreamdate", streamTweetLocalTime.ToString("d"));
                        this.ReplaceSpecialIdentifier("tweetstreamtime", streamTweetLocalTime.ToString("t"));
                    }
                }
            }

            if (ChannelSession.Services.Spotify != null && this.ContainsSpecialIdentifier("spotify"))
            {
                SpotifyUserProfile profile = await ChannelSession.Services.Spotify.GetCurrentProfile();

                if (profile != null)
                {
                    this.ReplaceSpecialIdentifier("spotifyprofileurl", profile.Link);
                }

                SpotifyCurrentlyPlaying currentlyPlaying = await ChannelSession.Services.Spotify.GetCurrentlyPlaying();

                if (currentlyPlaying != null)
                {
                    this.ReplaceSpecialIdentifier("spotifycurrentlyplaying", currentlyPlaying.ToString());
                }
            }

            if (ChannelSession.Services.ExtraLife.IsConnected() && this.ContainsSpecialIdentifier(ExtraLifeSpecialIdentifierHeader))
            {
                ExtraLifeTeam team = await ChannelSession.Services.ExtraLife.GetTeam();

                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "teamdonationgoal", team.fundraisingGoal.ToString());
                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "teamdonationcount", team.numDonations.ToString());
                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "teamdonationamount", team.sumDonations.ToString());

                ExtraLifeTeamParticipant participant = await ChannelSession.Services.ExtraLife.GetParticipant();

                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "userdonationgoal", participant.fundraisingGoal.ToString());
                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "userdonationcount", participant.numDonations.ToString());
                this.ReplaceSpecialIdentifier(ExtraLifeSpecialIdentifierHeader + "userdonationamount", participant.sumDonations.ToString());
            }

            if (this.ContainsSpecialIdentifier(FeaturedChannelsSpecialIdentifer))
            {
                IEnumerable <ExpandedChannelModel> featuredChannels = await ChannelSession.Connection.GetFeaturedChannels();

                if (featuredChannels != null)
                {
                    this.ReplaceSpecialIdentifier(FeaturedChannelsSpecialIdentifer, string.Join(", ", featuredChannels.Select(c => "@" + c.user.username)));
                }
            }

            if (this.ContainsSpecialIdentifier(StreamSpecialIdentifierHeader))
            {
                ChannelDetailsModel details = await ChannelSession.Connection.GetChannelDetails(ChannelSession.Channel);

                if (details != null)
                {
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "title", details.name);
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "agerating", details.audience);
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "viewercount", details.viewersCurrent.ToString());
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "followcount", details.numFollowers.ToString());
                    this.ReplaceSpecialIdentifier(StreamSpecialIdentifierHeader + "subcount", details.numSubscribers.ToString());
                }

                if (this.ContainsSpecialIdentifier(StreamHostCountSpecialIdentifier))
                {
                    IEnumerable <ChannelAdvancedModel> hosters = await ChannelSession.Connection.GetHosters(ChannelSession.Channel);

                    if (hosters != null)
                    {
                        this.ReplaceSpecialIdentifier(StreamHostCountSpecialIdentifier, hosters.Count().ToString());
                    }
                    else
                    {
                        this.ReplaceSpecialIdentifier(StreamHostCountSpecialIdentifier, "0");
                    }
                }
            }

            if (this.ContainsSpecialIdentifier(MilestoneSpecialIdentifierHeader))
            {
                PatronageStatusModel patronageStatus = await ChannelSession.Connection.GetPatronageStatus(ChannelSession.Channel);

                if (patronageStatus != null)
                {
                    PatronagePeriodModel patronagePeriod = await ChannelSession.Connection.GetPatronagePeriod(patronageStatus);

                    if (patronagePeriod != null)
                    {
                        IEnumerable <PatronageMilestoneModel> patronageMilestones = patronagePeriod.milestoneGroups.SelectMany(mg => mg.milestones);

                        PatronageMilestoneModel patronageMilestone = patronageMilestones.FirstOrDefault(m => m.id == patronageStatus.currentMilestoneId);
                        if (patronageMilestone != null)
                        {
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "amount", patronageMilestone.target.ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "remainingamount", (patronageMilestone.target - patronageStatus.patronageEarned).ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "reward", patronageMilestone.DollarAmountText());
                        }

                        PatronageMilestoneModel patronageNextMilestone = patronageMilestones.FirstOrDefault(m => m.id == (patronageStatus.currentMilestoneId + 1));
                        if (patronageNextMilestone != null)
                        {
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "nextamount", patronageNextMilestone.target.ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "remainingnextamount", (patronageNextMilestone.target - patronageStatus.patronageEarned).ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "nextreward", patronageNextMilestone.DollarAmountText());
                        }

                        PatronageMilestoneModel patronageFinalMilestone = patronageMilestones.OrderByDescending(m => m.id).FirstOrDefault();
                        if (patronageNextMilestone != null)
                        {
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "finalamount", patronageFinalMilestone.target.ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "remainingfinalamount", (patronageFinalMilestone.target - patronageStatus.patronageEarned).ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "finalreward", patronageFinalMilestone.DollarAmountText());
                        }

                        PatronageMilestoneModel patronageMilestoneHighestEarned         = null;
                        IEnumerable <PatronageMilestoneModel> patronageMilestonesEarned = patronageMilestones.Where(m => m.target <= patronageStatus.patronageEarned);
                        if (patronageMilestonesEarned != null && patronageMilestonesEarned.Count() > 0)
                        {
                            patronageMilestoneHighestEarned = patronageMilestonesEarned.OrderByDescending(m => m.reward).FirstOrDefault();
                        }

                        if (patronageMilestoneHighestEarned != null)
                        {
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "earnedamount", patronageStatus.patronageEarned.ToString());
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "earnedreward", patronageMilestoneHighestEarned.DollarAmountText());
                        }
                        else
                        {
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "earnedamount", "0");
                            this.ReplaceSpecialIdentifier(MilestoneSpecialIdentifierHeader + "earnedreward", "0");
                        }
                    }
                }
            }

            if (this.ContainsSpecialIdentifier(UserSpecialIdentifierHeader))
            {
                await this.HandleUserSpecialIdentifiers(user, string.Empty);
            }

            if (arguments != null)
            {
                for (int i = 0; i < arguments.Count(); i++)
                {
                    string currentArgumentSpecialIdentifierHeader = ArgSpecialIdentifierHeader + (i + 1);
                    if (this.ContainsSpecialIdentifier(currentArgumentSpecialIdentifierHeader))
                    {
                        UserViewModel argUser = await this.GetUserFromArgument(arguments.ElementAt(i));

                        if (argUser != null)
                        {
                            await this.HandleUserSpecialIdentifiers(argUser, currentArgumentSpecialIdentifierHeader);
                        }

                        this.ReplaceSpecialIdentifier(currentArgumentSpecialIdentifierHeader + "text", arguments.ElementAt(i));
                    }
                }

                this.ReplaceSpecialIdentifier("allargs", string.Join(" ", arguments));
                this.ReplaceSpecialIdentifier("argcount", arguments.Count().ToString());
            }

            if (this.ContainsSpecialIdentifier(TargetSpecialIdentifierHeader))
            {
                UserViewModel targetUser = null;
                if (arguments != null && arguments.Count() > 0)
                {
                    targetUser = await this.GetUserFromArgument(arguments.ElementAt(0));
                }

                if (targetUser == null)
                {
                    targetUser = user;
                }

                await this.HandleUserSpecialIdentifiers(targetUser, TargetSpecialIdentifierHeader);
            }

            if (this.ContainsSpecialIdentifier(StreamerSpecialIdentifierHeader))
            {
                await this.HandleUserSpecialIdentifiers(new UserViewModel(ChannelSession.Channel.user), StreamerSpecialIdentifierHeader);
            }

            if (this.ContainsSpecialIdentifier(StreamBossSpecialIdentifierHeader))
            {
                OverlayWidget streamBossWidget = ChannelSession.Settings.OverlayWidgets.FirstOrDefault(w => w.Item is OverlayStreamBoss);
                if (streamBossWidget != null)
                {
                    OverlayStreamBoss streamBossOverlay = (OverlayStreamBoss)streamBossWidget.Item;
                    if (streamBossOverlay != null && streamBossOverlay.CurrentBoss != null)
                    {
                        await this.HandleUserSpecialIdentifiers(streamBossOverlay.CurrentBoss, StreamBossSpecialIdentifierHeader);
                    }
                }
            }

            if (this.ContainsSpecialIdentifier(RandomSpecialIdentifierHeader))
            {
                if (this.randomUserSpecialIdentifierGroupID != Guid.Empty && RandomUserSpecialIdentifierGroups.ContainsKey(this.randomUserSpecialIdentifierGroupID))
                {
                    if (RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomUser != null && this.ContainsSpecialIdentifier(SpecialIdentifierStringBuilder.RandomSpecialIdentifierHeader + "user"))
                    {
                        await this.HandleUserSpecialIdentifiers(RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomUser, RandomSpecialIdentifierHeader);
                    }

                    if (RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomFollower != null && this.ContainsSpecialIdentifier(SpecialIdentifierStringBuilder.RandomFollowerSpecialIdentifierHeader + "user"))
                    {
                        await this.HandleUserSpecialIdentifiers(RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomFollower, RandomFollowerSpecialIdentifierHeader);
                    }

                    if (RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomSubscriber != null && this.ContainsSpecialIdentifier(SpecialIdentifierStringBuilder.RandomSubscriberSpecialIdentifierHeader + "user"))
                    {
                        await this.HandleUserSpecialIdentifiers(RandomUserSpecialIdentifierGroups[randomUserSpecialIdentifierGroupID].RandomSubscriber, RandomSubscriberSpecialIdentifierHeader);
                    }
                }

                if (this.ContainsRegexSpecialIdentifier(RandomNumberRegexSpecialIdentifier))
                {
                    await this.ReplaceNumberBasedRegexSpecialIdentifier(RandomNumberRegexSpecialIdentifier, (maxNumber) =>
                    {
                        int number = RandomHelper.GenerateRandomNumber(maxNumber) + 1;
                        return(Task.FromResult(number.ToString()));
                    });
                }
            }

            if (this.ContainsRegexSpecialIdentifier(UnicodeRegexSpecialIdentifier))
            {
                await this.ReplaceNumberBasedRegexSpecialIdentifier(UnicodeRegexSpecialIdentifier, (number) =>
                {
                    char uChar = (char)number;
                    return(Task.FromResult(uChar.ToString()));
                });
            }
        }
Exemplo n.º 33
0
        protected override async Task PerformInternal(CommandParametersModel parameters)
        {
            CurrencyModel currency = null;

            InventoryModel     inventory = null;
            InventoryItemModel item      = null;

            StreamPassModel streamPass = null;

            string systemName = null;

            if (this.CurrencyID != Guid.Empty)
            {
                if (!ChannelSession.Settings.Currency.ContainsKey(this.CurrencyID))
                {
                    return;
                }
                currency   = ChannelSession.Settings.Currency[this.CurrencyID];
                systemName = currency.Name;
            }

            if (this.InventoryID != Guid.Empty)
            {
                if (!ChannelSession.Settings.Inventory.ContainsKey(this.InventoryID))
                {
                    return;
                }
                inventory  = ChannelSession.Settings.Inventory[this.InventoryID];
                systemName = inventory.Name;

                if (!string.IsNullOrEmpty(this.ItemName))
                {
                    string itemName = await ReplaceStringWithSpecialModifiers(this.ItemName, parameters);

                    item = inventory.GetItem(itemName);
                    if (item == null)
                    {
                        return;
                    }
                }
            }

            if (this.StreamPassID != Guid.Empty)
            {
                if (!ChannelSession.Settings.StreamPass.ContainsKey(this.StreamPassID))
                {
                    return;
                }
                streamPass = ChannelSession.Settings.StreamPass[this.StreamPassID];
                systemName = streamPass.Name;
            }

            if (this.ActionType == ConsumablesActionTypeEnum.ResetForAllUsers)
            {
                if (currency != null)
                {
                    await currency.Reset();
                }
                else if (inventory != null)
                {
                    await inventory.Reset();
                }
                else if (streamPass != null)
                {
                    await streamPass.Reset();
                }
            }
            else if (this.ActionType == ConsumablesActionTypeEnum.ResetForUser)
            {
                if (currency != null)
                {
                    currency.ResetAmount(parameters.User.Data);
                }
                else if (inventory != null)
                {
                    inventory.ResetAmount(parameters.User.Data);
                }
                else if (streamPass != null)
                {
                    streamPass.ResetAmount(parameters.User.Data);
                }
            }
            else
            {
                string amountTextValue = await ReplaceStringWithSpecialModifiers(this.Amount, parameters);

                amountTextValue = MathHelper.ProcessMathEquation(amountTextValue).ToString();

                if (!double.TryParse(amountTextValue, out double doubleAmount))
                {
                    await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.CounterActionNotAValidAmount, amountTextValue, systemName));

                    return;
                }

                int amountValue = (int)Math.Ceiling(doubleAmount);
                if (amountValue < 0)
                {
                    await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.GameCurrencyRequirementAmountGreaterThan, amountTextValue, systemName));

                    return;
                }

                HashSet <UserDataModel> receiverUserData = new HashSet <UserDataModel>();
                if (this.ActionType == ConsumablesActionTypeEnum.AddToUser)
                {
                    receiverUserData.Add(parameters.User.Data);
                }
                else if (this.ActionType == ConsumablesActionTypeEnum.AddToSpecificUser || this.ActionType == ConsumablesActionTypeEnum.SubtractFromSpecificUser)
                {
                    if (!string.IsNullOrEmpty(this.Username))
                    {
                        string usernameString = await ReplaceStringWithSpecialModifiers(this.Username, parameters);

                        UserViewModel receivingUser = null;
                        if (this.UsersMustBePresent)
                        {
                            receivingUser = ChannelSession.Services.User.GetActiveUserByUsername(usernameString, parameters.Platform);
                        }
                        else
                        {
                            receivingUser = await ChannelSession.Services.User.GetUserFullSearch(parameters.Platform, userID : null, usernameString);
                        }

                        if (receivingUser != null)
                        {
                            receiverUserData.Add(receivingUser.Data);
                        }
                        else
                        {
                            await ChannelSession.Services.Chat.SendMessage(MixItUp.Base.Resources.UserNotFound);

                            return;
                        }
                    }
                }
                else if (this.ActionType == ConsumablesActionTypeEnum.AddToAllChatUsers || this.ActionType == ConsumablesActionTypeEnum.SubtractFromAllChatUsers)
                {
                    foreach (UserViewModel chatUser in ChannelSession.Services.User.GetAllWorkableUsers())
                    {
                        if (chatUser.HasPermissionsTo(this.UsersToApplyTo))
                        {
                            receiverUserData.Add(chatUser.Data);
                        }
                    }
                    receiverUserData.Add(ChannelSession.GetCurrentUser().Data);
                }

                if ((this.DeductFromUser && receiverUserData.Count > 0) || this.ActionType == ConsumablesActionTypeEnum.SubtractFromUser)
                {
                    if (currency != null)
                    {
                        if (!currency.HasAmount(parameters.User.Data, amountValue))
                        {
                            await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.CurrencyRequirementDoNotHaveAmount, amountValue, systemName));

                            return;
                        }
                        currency.SubtractAmount(parameters.User.Data, amountValue);
                    }
                    else if (inventory != null)
                    {
                        if (!inventory.HasAmount(parameters.User.Data, item, amountValue))
                        {
                            await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.CurrencyRequirementDoNotHaveAmount, amountValue, item.Name));

                            return;
                        }
                        inventory.SubtractAmount(parameters.User.Data, item, amountValue);
                    }
                    else if (streamPass != null)
                    {
                        if (!streamPass.HasAmount(parameters.User.Data, amountValue))
                        {
                            await ChannelSession.Services.Chat.SendMessage(string.Format(MixItUp.Base.Resources.CurrencyRequirementDoNotHaveAmount, amountValue, systemName));

                            return;
                        }
                        streamPass.SubtractAmount(parameters.User.Data, amountValue);
                    }
                }

                if (receiverUserData.Count > 0)
                {
                    foreach (UserDataModel receiverUser in receiverUserData)
                    {
                        if (currency != null)
                        {
                            if (this.ActionType == ConsumablesActionTypeEnum.SubtractFromSpecificUser || this.ActionType == ConsumablesActionTypeEnum.SubtractFromAllChatUsers)
                            {
                                currency.SubtractAmount(receiverUser, amountValue);
                            }
                            else
                            {
                                currency.AddAmount(receiverUser, amountValue);
                            }
                        }
                        else if (inventory != null)
                        {
                            if (this.ActionType == ConsumablesActionTypeEnum.SubtractFromSpecificUser || this.ActionType == ConsumablesActionTypeEnum.SubtractFromAllChatUsers)
                            {
                                inventory.SubtractAmount(receiverUser, item, amountValue);
                            }
                            else
                            {
                                inventory.AddAmount(receiverUser, item, amountValue);
                            }
                        }
                        else if (streamPass != null)
                        {
                            if (this.ActionType == ConsumablesActionTypeEnum.SubtractFromSpecificUser || this.ActionType == ConsumablesActionTypeEnum.SubtractFromAllChatUsers)
                            {
                                streamPass.SubtractAmount(receiverUser, amountValue);
                            }
                            else
                            {
                                streamPass.AddAmount(receiverUser, amountValue);
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 34
0
        public ViewResult Create()
        {
            var model = new UserViewModel();

            return(View());
        }
Exemplo n.º 35
0
        private async void OnLoggedIn(object sender, EventArgs e)
        {
            _user = await GetUserFromGraphApiAsync();

            UserDataUpdated?.Invoke(this, _user);
        }
Exemplo n.º 36
0
 public async Task <IHttpActionResult> SaveUserData(UserViewModel model)
 {
     return(Ok(await service.SaveUserData(model)));
 }
Exemplo n.º 37
0
        public async Task <IHttpActionResult> DeleteUser(UserViewModel model)
        {
            var result = GetErrorResult(await service.DeleteUser(model));

            return(result ?? Ok(service.GetUsers()));
        }
Exemplo n.º 38
0
        public IActionResult UpdateUsername(UserViewModel userView)
        {
            userService.ChangeUsername(User.Identity.Name, userView.Username);

            return(RedirectToAction("Logout", "Account"));
        }
Exemplo n.º 39
0
        public async Task <IActionResult> Create([Bind("Id")] SchoolClass schoolClass, UserViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByIdAsync(model.Role);

                var las = schoolClass.Id;


                schoolClass.Teacher = user;

                _context.Add(schoolClass);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(model));
        }
Exemplo n.º 40
0
    public IActionResult Index()
    {
        var model = new UserViewModel();

        return(View(model));
    }
Exemplo n.º 41
0
        public ActionResult Create(UserViewModel viewModel)
        {
            var classroomRepository = new ClassroomRepository(_context);

            if (ModelState.IsValid)
            {
                try
                {
                    using (var tx = new TransactionScope())
                    {
                        var sender = new SmtpSender();
                        var authenticationService = new AuthenticationService(_context, sender);
                        var newStudent            = authenticationService.CreateUser(
                            viewModel.Name,
                            viewModel.Login,
                            viewModel.Email,
                            viewModel.Password,
                            Role.Student,
                            _loggedUser);

                        var classroom = classroomRepository.GetById(viewModel.ClassroomId);

                        var todayDeliveryPlan =
                            classroom.DeliveryPlans.SingleOrDefault(x => x.StartDate.Date == DateTime.Today);
                        if (todayDeliveryPlan == null)
                        {
                            todayDeliveryPlan = new DeliveryPlan
                            {
                                StartDate = DateTime.Today,
                                Classroom = classroom
                            };
                            classroom.DeliveryPlans.Add(todayDeliveryPlan);
                        }

                        todayDeliveryPlan.Students.Add((Student)newStudent);

                        var notificationService = new NotificationService(_context, sender);

                        // notify already delivered classes
                        foreach (var item in todayDeliveryPlan.AvailableClasses)
                        {
                            try
                            {
                                notificationService.SendDeliveryClassEmail(item.Class, (Student)newStudent);
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }

                        // force deliver for today
                        todayDeliveryPlan.DeliverPendingClasses(_context, new SmtpSender());

                        _context.Save(_loggedUser);
                        tx.Complete();
                    }

                    TempData["MessageType"]  = "success";
                    TempData["MessageTitle"] = Resource.StudentManagementToastrTitle;
                    TempData["Message"]      = "Student added";

                    return(Redirect(TempData["BackURL"].ToString()));
                }
                catch (Exception ex)
                {
                    TempData["MessageType"]  = "error";
                    TempData["MessageTitle"] = Resource.StudentManagementToastrTitle;
                    TempData["Message"]      = ex.Message;
                }
            }


            ViewBag.Classrooms = new SelectList(classroomRepository.ListActiveClassrooms(), "Id", "Name");
            return(View(viewModel));
        }
Exemplo n.º 42
0
 private void Constellation_OnSubscribedOccurred(object sender, UserViewModel e)
 {
     this.subscriberTracker.OnStatisticEventOccurred(e.UserName);
 }
Exemplo n.º 43
0
 public override void Send(UserViewModel model)
 {
     base.Send(model);
 }
Exemplo n.º 44
0
        public async Task <ActionResult> ChangeDetailsPartial(UserViewModel userModel)
        {
            if (userModel.Render)
            {
                ModelState.Clear();

                return(ChangeDetailsPartial());
            }

            if (string.IsNullOrEmpty(userModel.Name))
            {
                return(RedirectToAction("Manage", new { Message = ManageMessageId.NotAllFieldsFilled }));
            }

            var user = await userManager.FindByIdAsync(User.Identity.GetUserId());

            if (user == null)
            {
                AuthenticationManager.Logout(HttpContext);
                return(RedirectToAction("Index", "Login"));
            }

            var nameChanged = user.UserName != userModel.Name;

            if (nameChanged && await userManager.FindByNameAsync(userModel.Name) != null)
            {
                log.Warn($"ChangeDetailsPartial(): name {userModel.Name} is already taken");
                return(RedirectToAction("Manage", new { Message = ManageMessageId.NameAlreadyTaken }));
            }

            /* Some users enter email with trailing whitespaces. Remove them (not users, but spaces!) */
            userModel.Email = (userModel.Email ?? "").Trim();
            var emailChanged = string.Compare(user.Email, userModel.Email, StringComparison.OrdinalIgnoreCase) != 0;

            if (emailChanged)
            {
                if (!CanUserSetThisEmail(user, userModel.Email))
                {
                    log.Warn($"ChangeDetailsPartial(): email {userModel.Email} is already taken");
                    return(RedirectToAction("Manage", new { Message = ManageMessageId.EmailAlreadyTaken }));
                }
            }

            user.UserName  = userModel.Name;
            user.FirstName = userModel.FirstName;
            user.LastName  = userModel.LastName;
            user.Email     = userModel.Email;
            user.Gender    = userModel.Gender;
            user.LastEdit  = DateTime.Now;
            if (!string.IsNullOrEmpty(userModel.Password))
            {
                await userManager.RemovePasswordAsync(user.Id);

                await userManager.AddPasswordAsync(user.Id, userModel.Password);
            }

            await userManager.UpdateAsync(user);

            if (emailChanged)
            {
                await ChangeEmail(user, user.Email).ConfigureAwait(false);
            }

            if (nameChanged)
            {
                AuthenticationManager.Logout(HttpContext);
                return(RedirectToAction("Index", "Login"));
            }

            return(RedirectToAction("Manage"));
        }
Exemplo n.º 45
0
        async Task OnEditRowAsync(TenantModel item)
        {
            ActiveTabIndex = 0;
            await OnTabChangeAsync(0);

            var apiTenantResult = await _apiWrapper.Tenants.GetByIdAsync(item.Id);

            if (apiTenantResult.IsSuccess && apiTenantResult.Error == null)
            {
                _exchangeSettingSelected = null;
                if (apiTenantResult.Data != null)
                {
                    _tenant_Name   = apiTenantResult.Data.Name;
                    _tenant_Number = apiTenantResult.Data.Number;
                    EditContext    = apiTenantResult.Data;
                    await InvokeAsync(StateHasChanged);

                    message = "";

                    var apiUserResult = await _apiWrapper.Users.GetTenantUsers(item.Id, searchUser);

                    if (apiUserResult.IsSuccess && apiUserResult.Error == null)
                    {
                        dataSourceUser = apiUserResult.Data;
                    }
                    else
                    {
                        dataSourceUser = new UserViewModel();
                    }

                    var apiLogResult = await _apiWrapper.LogDiaries.GetByTenantAsync(item.Id);

                    if (apiLogResult.IsSuccess && apiLogResult.Error == null)
                    {
                        dataSourceLog = apiLogResult.Data;
                    }

                    SelectedTenantId = item.Id;

                    var apiExchangeSettingResult = await _apiWrapper.ExchangeSettings.GetAllAsync(item.Id, "");

                    if (apiExchangeSettingResult.IsSuccess && apiExchangeSettingResult.Error == null)
                    {
                        _exchangeSettingModels = apiExchangeSettingResult.Data.ExchangeSettings;

                        if (_exchangeSettingModels.Count > 0)
                        {
                            _exchangeSettingSelected = _exchangeSettingModels.Where(t => t.IsEnabled).FirstOrDefault();
                            if (_exchangeSettingSelected == null)
                            {
                                _exchangeSettingSelected = null;
                            }
                        }
                    }

                    if (EditContext.AbacusSettingId != null)
                    {
                        var apiAbacusSettingResutl = await _apiWrapper.AbacusSettings.GetByIdAsync(item.Id, EditContext.AbacusSettingId.Value);

                        if (apiAbacusSettingResutl.IsSuccess && apiAbacusSettingResutl.Error == null && apiAbacusSettingResutl.Data != null)
                        {
                            _abacusSettingModel            = apiAbacusSettingResutl.Data;
                            EditContext.AbacusHealthStatus = _abacusSettingModel.HealthStatus;
                            EditContext.AbacusSettingName  = _abacusSettingModel.Name;
                        }
                    }
                }
            }
        }
Exemplo n.º 46
0
        public void SaveUser(UserViewModel user)
        {
            var isNew = user.UserId == 0;

            var entity = isNew ? new User() : _repository.GetById <User>(user.UserId);

            if (isNew && _repository.Query <User>().Any(u => u.UserName == user.UserName))
            {
                throw new Exception("This email address already exists in our system.");
            }

            if (entity.AlgorithmType == null)
            {
                entity.AlgorithmType = new AlgorithmType {
                    Id = 105001
                }
            }
            ;
            if (entity.PasswordFormatType == null)
            {
                entity.PasswordFormatType = new PasswordFormatType {
                    Id = 103001
                }
            }
            ;
            entity.UserType = new UserType {
                Id = user.UserTypeId
            };

            if (entity.Password == null)
            {
                entity.Password = "";
            }
            if (entity.PasswordSalt == null)
            {
                entity.PasswordSalt = "";
            }

            entity.FirstName = user.FirstName;
            entity.LastName  = user.LastName;
            entity.UserName  = user.UserName;


            if (entity.UserLoginInfo == null)
            {
                entity.SetUserLoginInfo(new UserLoginInfo());
            }

            var loginInfo = entity.UserLoginInfo;

            loginInfo.IsApprove = true;
            loginInfo.IsLocked  = false;

            if (isNew)
            {
                _repository.Create(entity);
                user.UserId = entity.Id;
            }
            else
            {
                _repository.Update(entity);
            }

            var email = entity.Communications.FirstOrDefault(
                c => c.IsPrimary && c.CommunicationType.Id == (long)CommunicationTypes.Email) ??
                        new Communication
            {
                CommunicationType = new CommunicationType {
                    Id = (long)CommunicationTypes.Email
                },
                Description  = "Email",
                Phone        = "",
                IsPrimary    = true,
                RecordStatus = new RecordStatus {
                    Id = (long)RecordStatuses.Active
                }
            };

            email.Email = user.UserName;
            if (email.Id == 0)
            {
                email.Users.Add(entity);
                _repository.Create(email);
            }
            else
            {
                _repository.Update(email);
            }

            var phone = entity.Communications.FirstOrDefault(
                c => c.IsPrimary && c.CommunicationType.Id == (long)CommunicationTypes.WorkPhone) ??
                        new Communication
            {
                CommunicationType = new CommunicationType {
                    Id = (long)CommunicationTypes.WorkPhone
                },
                Description  = "WorkPhone",
                Email        = "",
                IsPrimary    = true,
                RecordStatus = new RecordStatus {
                    Id = (long)RecordStatuses.Active
                }
            };

            phone.Phone = user.Phone;
            if (phone.Id == 0)
            {
                phone.Users.Add(entity);
                _repository.Create(phone);
            }
            else
            {
                _repository.Update(phone);
            }
        }
Exemplo n.º 47
0
 private async void OnLoggedOut(object sender, EventArgs e)
 {
     _user = null;
     await ApplicationData.Current.LocalFolder.SaveAsync <User>(_userSettingsKey, null);
 }
Exemplo n.º 48
0
        public ActionResult UserRegistration(UserViewModel objUserModel)
        {
            //Code to show DropDown of Role
            List <Role> roleList = GetRoles();

            ViewBag.RoleList = new SelectList(roleList, "RoleId", "RoleName");
            //Code to show Dropdown of Cousre
            List <Course> courseList = db.Courses.Where(x => x.IsActive == true).ToList();

            ViewBag.CourseList = new SelectList(courseList, "CourseId", "CourseName");
            // Code to show DropDown of Country
            List <Country> countryList = db.Country.ToList();

            ViewBag.CountryList = new SelectList(countryList, "CountryId", "Name");

            // Create the TransactionScope to execute the commands, guaranteeing
            // that both commands can commit or roll back as a single unit of work.

            using (var transaction = db.Database.BeginTransaction())
            {
                try
                {
                    if (ModelState.IsValid)
                    {
                        //Address of the user is stored in the DataBase.
                        Address address = new Address();

                        //address.AddressId = objUserModel.AddressId;
                        address.AddressLine1 = objUserModel.AddressLine1;
                        address.AddressLine2 = objUserModel.AddressLine2;
                        address.CountryId    = objUserModel.CountryId;
                        address.StateId      = objUserModel.StateId;
                        address.CityId       = objUserModel.CityId;
                        address.ZipCode      = objUserModel.ZipCode;
                        db.Addresses.Add(address);
                        db.SaveChanges();

                        //Data is saved in the User Table.
                        User objUser         = new User();
                        int  latestAddressId = address.AddressId;
                        //obj.UserId = objUserModel.UserId;
                        objUser.FirstName       = objUserModel.FirstName;
                        objUser.LastName        = objUserModel.LastName;
                        objUser.Gender          = objUserModel.Gender;
                        objUser.Hobbies         = objUserModel.Hobbies;
                        objUser.Password        = objUserModel.Password;
                        objUser.ConfirmPassword = objUserModel.ConfirmPassword;
                        objUser.IsVerified      = objUserModel.IsVerified;
                        objUser.Email           = objUserModel.Email;
                        objUser.DateOfBirth     = objUserModel.DateOfBirth;
                        objUser.IsActive        = objUserModel.IsActive;
                        objUser.DateCreated     = DateTime.Now;
                        objUser.DateModified    = DateTime.Now;
                        objUser.RoleId          = objUserModel.RoleId;
                        objUser.CourseId        = objUserModel.CourseId;
                        objUser.AddressId       = latestAddressId;

                        db.Users.Add(objUser);
                        db.SaveChanges();

                        // User and their Roles are saved in the UserInRole Table.
                        int        latestUserId = objUser.UserId;
                        UserInRole userInRole   = new UserInRole();
                        userInRole.RoleId = objUserModel.RoleId;
                        userInRole.UserId = latestUserId;

                        db.UserInRoles.Add(userInRole);
                        db.SaveChanges();

                        transaction.Commit();
                        return(RedirectToAction("Login"));
                    }

                    return(View(objUserModel));
                }

                catch (Exception ex)
                {
                    transaction.Rollback();
                    ViewBag.ResultMessage = "Error occurred in the registration process.Please register again.";
                    throw ex;
                }
            }
        }
Exemplo n.º 49
0
 public RegisterView()
 {
     this.InitializeComponent();
     DataContext = new UserViewModel();
     uvm         = (UserViewModel)DataContext;
 }
Exemplo n.º 50
0
        private async Task HandleUserSpecialIdentifiers(UserViewModel user, string identifierHeader)
        {
            if (user != null && this.ContainsSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader))
            {
                await user.RefreshDetails();

                if (ChannelSession.Settings.UserData.ContainsKey(user.ID))
                {
                    UserDataViewModel userData = ChannelSession.Settings.UserData[user.ID];

                    foreach (UserCurrencyViewModel currency in ChannelSession.Settings.Currencies.Values.OrderByDescending(c => c.UserAmountSpecialIdentifier))
                    {
                        UserCurrencyDataViewModel currencyData = userData.GetCurrency(currency);
                        UserRankViewModel         rank         = currencyData.GetRank();
                        UserRankViewModel         nextRank     = currencyData.GetNextRank();

                        this.ReplaceSpecialIdentifier(identifierHeader + currency.UserRankNextNameSpecialIdentifier, nextRank.Name);
                        this.ReplaceSpecialIdentifier(identifierHeader + currency.UserAmountNextSpecialIdentifier, nextRank.MinimumPoints.ToString());

                        this.ReplaceSpecialIdentifier(identifierHeader + currency.UserRankNameSpecialIdentifier, rank.Name);
                        this.ReplaceSpecialIdentifier(identifierHeader + currency.UserAmountSpecialIdentifier, currencyData.Amount.ToString());
                    }

                    foreach (UserInventoryViewModel inventory in ChannelSession.Settings.Inventories.Values.OrderByDescending(c => c.UserAmountSpecialIdentifierHeader))
                    {
                        if (this.ContainsSpecialIdentifier(identifierHeader + inventory.UserAmountSpecialIdentifierHeader))
                        {
                            UserInventoryDataViewModel inventoryData = userData.GetInventory(inventory);
                            List <string> allItemsList = new List <string>();

                            foreach (UserInventoryItemViewModel item in inventory.Items.Values.OrderByDescending(i => i.Name))
                            {
                                int amount = inventoryData.GetAmount(item);
                                if (amount > 0)
                                {
                                    allItemsList.Add(item.Name + " x" + amount);
                                }

                                string itemSpecialIdentifier = identifierHeader + inventory.UserAmountSpecialIdentifierHeader + item.SpecialIdentifier;
                                this.ReplaceSpecialIdentifier(itemSpecialIdentifier, amount.ToString());
                            }

                            if (allItemsList.Count > 0)
                            {
                                this.ReplaceSpecialIdentifier(identifierHeader + inventory.UserAllAmountSpecialIdentifier, string.Join(", ", allItemsList.OrderBy(i => i)));
                            }
                            else
                            {
                                this.ReplaceSpecialIdentifier(identifierHeader + inventory.UserAllAmountSpecialIdentifier, "Nothing");
                            }
                        }
                    }

                    this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "time", userData.ViewingTimeString);
                    this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "hours", userData.ViewingHoursString);
                    this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "mins", userData.ViewingMinutesString);

                    this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "moderationstrikes", userData.ModerationStrikes.ToString());
                }

                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "primaryrole", user.PrimaryRoleString);
                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "avatar", user.AvatarLink);
                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "url", "https://www.mixer.com/" + user.UserName);
                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "name", user.UserName);
                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "id", user.ID.ToString());
                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "sparks", user.Sparks.ToString());

                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "mixerage", user.MixerAgeString);
                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "followage", user.FollowAgeString);
                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "subage", user.MixerSubscribeAgeString);
                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "submonths", user.SubscribeMonths.ToString());

                this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "title", user.Title);

                if (this.ContainsSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "followers") || this.ContainsSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "game") ||
                    this.ContainsSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "channel"))
                {
                    ExpandedChannelModel channel = await ChannelSession.Connection.GetChannel(user.UserName);

                    this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "followers", channel?.numFollowers.ToString() ?? "0");

                    if (channel.type != null)
                    {
                        this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "gameimage", channel.type.coverUrl);
                        this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "game", channel.type.name.ToString());
                    }

                    this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "channelid", channel.id.ToString());
                    this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "channellive", channel.online.ToString());
                    this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "channelfeatured", channel.featured.ToString());
                }

                if (this.ContainsSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "fanprogression"))
                {
                    UserFanProgressionModel fanProgression = await ChannelSession.Connection.GetUserFanProgression(ChannelSession.Channel, user.GetModel());

                    if (fanProgression != null && fanProgression.level != null)
                    {
                        this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "fanprogressionnext", fanProgression.level.nextLevelXp.ToString());
                        this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "fanprogressionrank", fanProgression.level.level.ToString());
                        this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "fanprogressioncolor", fanProgression.level.color.ToString());
                        this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "fanprogressionimage", fanProgression.level.LargeGIFAssetURL.ToString());
                        this.ReplaceSpecialIdentifier(identifierHeader + UserSpecialIdentifierHeader + "fanprogression", fanProgression.level.currentXp.ToString());
                    }
                }
            }
        }
Exemplo n.º 51
0
        public UserPage(UserViewModel viewModel)
        {
            InitializeComponent();

            BindingContext = this.viewModel = viewModel;
        }
Exemplo n.º 52
0
 private void Constellation_OnUnfollowOccurred(object sender, UserViewModel e)
 {
     this.unfollowTracker.OnStatisticEventOccurred(e.UserName);
 }
 public UserWindow(UserViewModel viewModel)
 {
     this.DataContext = viewModel;
     InitializeComponent();
 }
Exemplo n.º 54
0
        private async Task GiveawayTimerBackground()
        {
            GlobalEvents.OnChatCommandMessageReceived += GlobalEvents_OnChatCommandMessageReceived;
            GlobalEvents.OnDonationOccurred           += GlobalEvents_OnDonationOccurred;

            try
            {
                while (this.timeLeft > 0)
                {
                    await Task.Delay(1000);

                    this.timeLeft--;

                    string timeLeftUIText = (this.timeLeft % 60).ToString() + " Seconds";
                    if (this.timeLeft > 60)
                    {
                        timeLeftUIText = (this.timeLeft / 60).ToString() + " Minutes " + timeLeftUIText;
                    }

                    await this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        this.TimeLeftTextBlock.Text = timeLeftUIText;
                    }));

                    string timeLeftText = null;
                    if (this.timeLeft > 60 && (this.timeLeft % this.reminder) == 0)
                    {
                        int minutesLeft = this.timeLeft / 60;
                        timeLeftText = minutesLeft + " minutes";
                    }
                    else if (this.timeLeft == 60 || this.timeLeft == 30 || this.timeLeft == 10)
                    {
                        timeLeftText = this.timeLeft + " seconds";
                    }

                    if (!string.IsNullOrEmpty(timeLeftText))
                    {
                        await ChannelSession.Chat.SendMessage(string.Format("The giveaway will end in {0}. {1}!", timeLeftText, this.GetEntryInstructions()));
                    }

                    if (this.backgroundThreadCancellationTokenSource.Token.IsCancellationRequested)
                    {
                        await this.EndGiveaway();

                        return;
                    }
                }

                while (true)
                {
                    this.selectedWinner = this.SelectWinner();
                    if (this.selectedWinner != null)
                    {
                        await this.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            this.WinnerTextBlock.Text = this.selectedWinner.UserName;
                        }));

                        await ChannelSession.Settings.GiveawayWinnerSelectedCommand.Perform(this.selectedWinner);

                        if (!ChannelSession.Settings.GiveawayRequireClaim)
                        {
                            await this.EndGiveaway();

                            return;
                        }
                        else
                        {
                            int claimTime = 60;
                            while (claimTime > 0)
                            {
                                await Task.Delay(1000);

                                claimTime--;

                                await this.Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    this.TimeLeftTextBlock.Text = claimTime.ToString();
                                }));

                                if (this.backgroundThreadCancellationTokenSource.Token.IsCancellationRequested)
                                {
                                    await this.EndGiveaway();

                                    return;
                                }
                            }
                        }
                    }
                    else
                    {
                        await ChannelSession.Chat.SendMessage("There are no users that entered/left in the giveaway");

                        await this.EndGiveaway();

                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                MixItUp.Base.Util.Logger.Log(ex);
            }
        }
        public IActionResult UserData(int userId)
        {
            UserViewModel user = UsersBL.GetUser(_context, userId);

            return(PartialView("UserData", user));
        }
Exemplo n.º 56
0
 public void AddUser(UserViewModel user)
 {
     _repo.AddUser(user);
 }
Exemplo n.º 57
0
 public ActionResult Unblock(UserViewModel model)
 {
     _userService.Unblock(model.Id);
     return(RedirectToAction("Students"));
 }
Exemplo n.º 58
0
 protected bool IsLoggedInUser(UserViewModel user)
 {
     return(user != null && user.IsLoggedIn);
 }
Exemplo n.º 59
0
        public ActionResult Search(string term, string searchFieldName, int page = 1)
        {
            var userRepository = new UserRepository(_context);

            return(Json(UserViewModel.FromEntityList(userRepository.ListStudents(term, searchFieldName, page))));
        }
Exemplo n.º 60
0
        public async Task AddMessage(ChatMessageViewModel message)
        {
            message.ProcessingStartTime = DateTimeOffset.Now;
            Logger.Log(LogLevel.Debug, string.Format("Message Received - {0} - {1} - {2}", message.ID.ToString(), message.ProcessingStartTime, message));

            // Pre message processing

            if (message is UserChatMessageViewModel)
            {
                if (message.User != null)
                {
                    if (message.Platform == StreamingPlatformTypeEnum.Twitch)
                    {
                        UserViewModel activeUser = ChannelSession.Services.User.GetUserByTwitchID(message.User.TwitchID);
                        if (activeUser != null)
                        {
                            message.User = activeUser;
                        }
                    }

                    message.User.UpdateLastActivity();
                    if (message.IsWhisper && ChannelSession.Settings.TrackWhispererNumber && !message.IsStreamerOrBot && message.User.WhispererNumber == 0)
                    {
                        await this.whisperNumberLock.WaitAndRelease(() =>
                        {
                            if (!whisperMap.ContainsKey(message.User.ID))
                            {
                                whisperMap[message.User.ID] = whisperMap.Count + 1;
                            }
                            message.User.WhispererNumber = whisperMap[message.User.ID];
                            return(Task.FromResult(0));
                        });
                    }
                }
            }

            // Add message to chat list
            bool showMessage = true;

            if (ChannelSession.Settings.HideBotMessages && message.User != null && ChannelSession.TwitchBotNewAPI != null && message.User.TwitchID.Equals(ChannelSession.TwitchBotNewAPI.id))
            {
                showMessage = false;
            }

            if (!(message is AlertChatMessageViewModel) || !ChannelSession.Settings.OnlyShowAlertsInDashboard)
            {
                await DispatcherHelper.InvokeDispatcher(() =>
                {
                    this.messagesLookup[message.ID] = message;
                    if (showMessage)
                    {
                        if (ChannelSession.Settings.LatestChatAtTop)
                        {
                            this.Messages.Insert(0, message);
                        }
                        else
                        {
                            this.Messages.Add(message);
                        }
                    }

                    if (this.Messages.Count > ChannelSession.Settings.MaxMessagesInChat)
                    {
                        ChatMessageViewModel removedMessage = (ChannelSession.Settings.LatestChatAtTop) ? this.Messages.Last() : this.Messages.First();
                        this.messagesLookup.Remove(removedMessage.ID);
                        this.Messages.Remove(removedMessage);
                    }

                    return(Task.FromResult(0));
                });
            }

            // Post message processing

            if (message is UserChatMessageViewModel && message.User != null)
            {
                if (message.IsWhisper && !message.IsStreamerOrBot)
                {
                    if (!string.IsNullOrEmpty(ChannelSession.Settings.NotificationChatWhisperSoundFilePath))
                    {
                        await ChannelSession.Services.AudioService.Play(ChannelSession.Settings.NotificationChatWhisperSoundFilePath, ChannelSession.Settings.NotificationChatWhisperSoundVolume, ChannelSession.Settings.NotificationsAudioOutput);
                    }

                    if (!string.IsNullOrEmpty(message.PlainTextMessage))
                    {
                        EventTrigger trigger = new EventTrigger(EventTypeEnum.ChatWhisperReceived, message.User);
                        trigger.SpecialIdentifiers["message"] = message.PlainTextMessage;
                        await ChannelSession.Services.Events.PerformEvent(trigger);
                    }

                    // Don't send this if it's in response to another "You are whisperer #" message
                    if (ChannelSession.Settings.TrackWhispererNumber && message.User.WhispererNumber > 0 && !message.PlainTextMessage.StartsWith("You are whisperer #", StringComparison.InvariantCultureIgnoreCase))
                    {
                        await ChannelSession.Services.Chat.Whisper(message.User, $"You are whisperer #{message.User.WhispererNumber}.", sendAsStreamer : false);
                    }
                }
                else
                {
                    if (this.DisableChat)
                    {
                        Logger.Log(LogLevel.Debug, string.Format("Deleting Message As Chat Disabled - {0} - {1}", message.ID, message));
                        await this.DeleteMessage(message);

                        return;
                    }

                    if (!string.IsNullOrEmpty(ChannelSession.Settings.NotificationChatTaggedSoundFilePath) && message.IsStreamerTagged)
                    {
                        await ChannelSession.Services.AudioService.Play(ChannelSession.Settings.NotificationChatTaggedSoundFilePath, ChannelSession.Settings.NotificationChatTaggedSoundVolume, ChannelSession.Settings.NotificationsAudioOutput);
                    }
                    else if (!string.IsNullOrEmpty(ChannelSession.Settings.NotificationChatMessageSoundFilePath))
                    {
                        await ChannelSession.Services.AudioService.Play(ChannelSession.Settings.NotificationChatMessageSoundFilePath, ChannelSession.Settings.NotificationChatMessageSoundVolume, ChannelSession.Settings.NotificationsAudioOutput);
                    }

                    if (message.User != null && !this.userEntranceCommands.Contains(message.User.ID))
                    {
                        this.userEntranceCommands.Add(message.User.ID);
                        if (message.User.Data.EntranceCommand != null)
                        {
                            await message.User.Data.EntranceCommand.Perform(message.User, message.Platform);
                        }
                    }

                    if (!string.IsNullOrEmpty(message.PlainTextMessage))
                    {
                        EventTrigger trigger = new EventTrigger(EventTypeEnum.ChatMessageReceived, message.User);
                        trigger.SpecialIdentifiers["message"] = message.PlainTextMessage;
                        await ChannelSession.Services.Events.PerformEvent(trigger);
                    }

                    message.User.Data.TotalChatMessageSent++;

                    string primaryTaggedUsername = message.PrimaryTaggedUsername;
                    if (!string.IsNullOrEmpty(primaryTaggedUsername))
                    {
                        UserViewModel primaryTaggedUser = ChannelSession.Services.User.GetUserByUsername(primaryTaggedUsername, message.Platform);
                        if (primaryTaggedUser != null)
                        {
                            primaryTaggedUser.Data.TotalTimesTagged++;
                        }
                    }
                }

                await message.User.RefreshDetails();

                if (!message.IsWhisper && await message.CheckForModeration())
                {
                    await this.DeleteMessage(message);

                    return;
                }

                IEnumerable <string> arguments = null;
                if (ChannelSession.IsStreamer && !string.IsNullOrEmpty(message.PlainTextMessage) && message.User != null && !message.User.UserRoles.Contains(UserRoleEnum.Banned))
                {
                    if (!ChannelSession.Settings.AllowCommandWhispering && message.IsWhisper)
                    {
                        return;
                    }

                    if (ChannelSession.Settings.IgnoreBotAccountCommands)
                    {
                        if (ChannelSession.TwitchBotNewAPI != null && message.User.TwitchID.Equals(ChannelSession.TwitchBotNewAPI.id))
                        {
                            return;
                        }
                    }

                    Logger.Log(LogLevel.Debug, string.Format("Checking Message For Command - {0} - {1}", message.ID, message));

                    List <PermissionsCommandBase> commands = this.chatCommands.ToList();
                    foreach (PermissionsCommandBase command in message.User.Data.CustomCommands.Where(c => c.IsEnabled))
                    {
                        commands.Add(command);
                    }

                    foreach (PermissionsCommandBase command in commands)
                    {
                        if (command.DoesTextMatchCommand(message.PlainTextMessage, out arguments))
                        {
                            if (command.IsEnabled)
                            {
                                Logger.Log(LogLevel.Debug, string.Format("Command Found For Message - {0} - {1} - {2}", message.ID, message, command));
                                await command.Perform(message.User, message.Platform, arguments : arguments);

                                if (command.Requirements.Settings.DeleteChatCommandWhenRun || (ChannelSession.Settings.DeleteChatCommandsWhenRun && !command.Requirements.Settings.DontDeleteChatCommandWhenRun))
                                {
                                    await this.DeleteMessage(message);
                                }
                            }
                            break;
                        }
                    }
                }

                foreach (InventoryModel inventory in ChannelSession.Settings.Inventory.Values.ToList())
                {
                    if (inventory.ShopEnabled && CommandBase.DoesTextMatchCommand(message.PlainTextMessage, CommandBase.CommandMatchingRegexFormat, new List <string>()
                    {
                        inventory.ShopCommand
                    }, out arguments))
                    {
                        await inventory.PerformShopCommand(message.User, arguments, message.Platform);
                    }
                    else if (inventory.TradeEnabled && CommandBase.DoesTextMatchCommand(message.PlainTextMessage, CommandBase.CommandMatchingRegexFormat, new List <string>()
                    {
                        inventory.TradeCommand
                    }, out arguments))
                    {
                        string args = message.PlainTextMessage.Replace(inventory.TradeCommand, "");
                        await inventory.PerformTradeCommand(message.User, arguments, message.Platform);
                    }
                }

                if (ChannelSession.Settings.RedemptionStoreEnabled)
                {
                    if (CommandBase.DoesTextMatchCommand(message.PlainTextMessage, CommandBase.CommandMatchingRegexFormat, new List <string>()
                    {
                        ChannelSession.Settings.RedemptionStoreChatPurchaseCommand
                    }, out arguments))
                    {
                        await RedemptionStorePurchaseModel.Purchase(message.User, arguments);
                    }
                    else if (CommandBase.DoesTextMatchCommand(message.PlainTextMessage, CommandBase.CommandMatchingRegexFormat, new List <string>()
                    {
                        ChannelSession.Settings.RedemptionStoreModRedeemCommand
                    }, out arguments))
                    {
                        await RedemptionStorePurchaseModel.Redeem(message.User, arguments);
                    }
                }

                GlobalEvents.ChatMessageReceived(message);

                await this.WriteToChatEventLog(message);
            }

            Logger.Log(LogLevel.Debug, string.Format("Message Processing Complete: {0} - {1} ms", message.ID, message.ProcessingTime));
            if (message.ProcessingTime > 500)
            {
                Logger.Log(LogLevel.Error, string.Format("Long processing time detected for the following message: {0} - {1} ms - {2}", message.ID.ToString(), message.ProcessingTime, message));
            }
        }