예제 #1
0
        public async Task TempBanWarnUser([RequireHierarchy] UserRef userRef, TimeSpan time, float size, [Remainder] string reason)
        {
            if (time.TotalMinutes < 1)
            {
                await ReplyAsync("Can't temp-ban for less than a minute");

                return;
            }
            if (!(Context.Message.Author as IGuildUser).HasAdmin())
            {
                ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>(false);
                if (settings?.maxTempAction != null && time > settings.maxTempAction)
                {
                    await ReplyAsync("You are not allowed to punish for that long");

                    return;
                }
            }
            await userRef.Warn(size, reason, Context.Channel as ITextChannel, "Discord");

            TempActionList actions = Context.Guild.LoadFromFile <TempActionList>(true);

            if (actions.tempBans.Any(tempBan => tempBan.User == userRef.ID))
            {
                await ReplyAsync($"{userRef.Name()} is already temp-banned (the warn did go through)");

                return;
            }
            await userRef.TempBan(time, reason, Context, actions);

            Context.Message.DeleteOrRespond($"Temporarily banned {userRef.Mention()} for {time.LimitedHumanize(3)} because of {reason}", Context.Guild);
        }
예제 #2
0
    private IEnumerator ProcessExitFromRoom(UserRef user, string roomName)
    {
        try
        {
            var t1 = user.ExitFromRoom(roomName);
            yield return(t1.WaitHandle);

            if (t1.Status != TaskStatus.RanToCompletion)
            {
                UiMessageBox.Show("Exit room error:\n" + t1.Exception.ToString());
                yield break;
            }

            RoomItem item;
            if (_roomItemMap.TryGetValue(roomName, out item) == false)
            {
                yield break;
            }

            _roomItemMap.Remove(roomName);
            Destroy(item.ChatPanel.gameObject);
            G.Communicator.ObserverRegistry.Remove(item.Observer);
            ControlPanel.DeleteRoomItem(roomName);
            if (item.Channel != G.Communicator.Channels[0])
            {
                item.Channel.Close();
            }

            OnRoomItemClick("#general");
        }
        finally
        {
            _isBusy = false;
        }
    }
 public TenancyContentContext(
     LogSink securityLog, ContentContext context, TenancyProvider tenancyProvider)
 {
     this.SecurityLog          = securityLog;
     this.DbContext            = context;
     this.AuthenticatedUserRef = tenancyProvider.AuthenticatedUser;
 }
예제 #4
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ForUser();
            modelBuilder.ForProduct();
            modelBuilder.ForFriendConnection();

            UserRef me       = new UserRef("DFE27E47-2BBE-4C7D-B419-25AC7835881F");
            UserRef neighbor = new UserRef("C8A9EFD2-F350-4437-ADA0-1CCB8C0DFA55");

            modelBuilder.Entity <User>().HasData(
                new User(1, "me", me),
                new User(2, "neighbor", neighbor));

            modelBuilder.Entity <Product>().HasData(
                new Product(1, "one", me),
                new Product(2, "two", me),
                new Product(3, "three", me),
                new Product(4, "square", neighbor),
                new Product(5, "pointy", neighbor),
                new Product(6, "round", neighbor));

            modelBuilder.Entity <FriendConnection>().HasData(
                new FriendConnection(1, neighbor, me));
        }
예제 #5
0
        public void Excecute(UserRef user, PollingCentreRef pollingCentre, List <ResultDetail> results)
        {
            ResultInfo resultInfo = new ResultInfo
            {
                OriginatingPollingCentre = pollingCentre,
                CommandGeneratedByUser   = user
            };

            var res = _referendumResultRepository.GetByPollingCentre(pollingCentre);

            if (res == null)
            {
                var    resultReference  = new ResultReference();
                string reference        = resultReference.Generate(pollingCentre.Name, user.Username);
                var    newResult        = _referendumResultWorkflow.Create(resultInfo, reference);
                var    resultWithDetail = _referendumResultWorkflow.AddReferendumResultLineItems(newResult, resultInfo, results);
                var    confirmResult    = _referendumResultWorkflow.Confirm(resultWithDetail, resultInfo);
                _referendumResultRepository.Save(confirmResult);
            }
            if (res != null)
            {
                var modifiedResult = _referendumResultWorkflow.Modify(res, resultInfo, results);
                _referendumResultRepository.Save(modifiedResult);
            }
        }
예제 #6
0
파일: Location.cs 프로젝트: SW801F20/P8
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (UserRef != null)
         {
             hashCode = hashCode * 59 + UserRef.GetHashCode();
         }
         if (Yaw != null)
         {
             hashCode = hashCode * 59 + Yaw.GetHashCode();
         }
         if (Position != null)
         {
             hashCode = hashCode * 59 + Position.GetHashCode();
         }
         if (Timestamp != null)
         {
             hashCode = hashCode * 59 + Timestamp.GetHashCode();
         }
         return(hashCode);
     }
 }
        public void ResultProcessing_WhenReceived_ValidResultSaved()
        {
            //Arrange
            UserRef          user          = new UserRef(Guid.NewGuid(), "Brian Mwasi", UserType.Clerk);
            PollingCentreRef pollingCentre = new PollingCentreRef(Guid.NewGuid(), "Jamuhuri Primary");
            ResultDetail     resultDetail  = new ResultDetail {
                Candidate = new CandidateRef(Guid.NewGuid(), "Sonko", CandidateType.PartyBacked), Result = 1000
            };
            ResultDetail resultDetail1 = new ResultDetail {
                Candidate = new CandidateRef(Guid.NewGuid(), "Waititu", CandidateType.PartyBacked), Result = 2000
            };
            List <ResultDetail> resultDetails = new List <ResultDetail>();

            resultDetails.Add(resultDetail);
            resultDetails.Add(resultDetail1);
            ISenatorialResultService    senatorialResultService    = _ioc.Resolve <ISenatorialResultService>();
            ISenatorialResultRepository senatorialResultRepository = _ioc.Resolve <ISenatorialResultRepository>();

            //Act
            senatorialResultService.Excecute(user, pollingCentre, resultDetails);
            //Assert
            var senatorialResult = senatorialResultRepository.GetAll().OrderByDescending(n => n.ResultSendDate).First();

            Assert.That(senatorialResult.Id, Is.Not.EqualTo(Guid.Empty));
            Assert.IsNotNull(senatorialResult.ResultReference);
            Assert.That(senatorialResult.ResultSender, Is.EqualTo(user));
            Assert.That(senatorialResult.PollingCentre, Is.EqualTo(pollingCentre));
            Assert.That(senatorialResult.Status, Is.EqualTo(ResultStatus.Confirmed));
            Assert.That(senatorialResult.ResultSender, Is.EqualTo(user));
            Assert.That(senatorialResult.LineItems.OrderBy(n => n.Candidate.FullName).First().Candidate, Is.EqualTo(resultDetail.Candidate));
            Assert.That(senatorialResult.LineItems.OrderBy(n => n.Candidate.FullName).Last().Candidate, Is.EqualTo(resultDetail1.Candidate));
            Assert.That(senatorialResult.LineItems.OrderBy(n => n.Candidate.FullName).First().ResultCount, Is.EqualTo(resultDetail.Result));
            Assert.That(senatorialResult.LineItems.OrderBy(n => n.Candidate.FullName).Last().ResultCount, Is.EqualTo(resultDetail1.Result));
        }
예제 #8
0
        /// <summary>
        /// Formats <see cref="UserRef"/> to a string depending on options set
        /// </summary>
        public static string Name(this UserRef userRef, bool showIDWithUser = false, bool showRealName = false)
        {
            if (userRef == null)
            {
                return("``ERROR``");
            }
            string name = null;

            if (userRef.GuildUser?.Nickname != null)
            {
                name = userRef.GuildUser.Nickname.StrippedOfPing();
                if (showRealName) //done since people with nicknames might have an inappropriate name under the nickname
                {
                    name += $" aka {userRef.GuildUser.Username.StrippedOfPing()}";
                }
            }
            if (name == null && userRef.User != null)
            {
                name = userRef.User.Username.StrippedOfPing();
            }
            if (name != null)
            {
                if (showIDWithUser)
                {
                    name += $" ({userRef.ID})";
                }
                return(name);
            }
            return($"User with ID:{userRef.ID}");
        }
예제 #9
0
파일: Location.cs 프로젝트: SW801F20/P8
        /// <summary>
        /// Returns true if Location instances are equal
        /// </summary>
        /// <param name="other">Instance of Location to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(Location other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     UserRef == other.UserRef ||
                     UserRef != null &&
                     UserRef.Equals(other.UserRef)
                     ) &&
                 (
                     Yaw == other.Yaw ||
                     Yaw != null &&
                     Yaw.Equals(other.Yaw)
                 ) &&
                 (
                     Position == other.Position ||
                     Position != null &&
                     Position.Equals(other.Position)
                 ) &&
                 (
                     Timestamp == other.Timestamp ||
                     Timestamp != null &&
                     Timestamp.Equals(other.Timestamp)
                 ));
        }
예제 #10
0
    public static void CheckIfUserIsRegistered(string uid, Action <bool> isRegistered)
    {
        UserRef
        .Child(FO.userId)
        .GetValueAsync()
        .ContinueWithOnMainThread(task => {
            if (task.IsFaulted)
            {
                // error handling here
            }
            else if (task.IsCompleted)
            {
                DataSnapshot s = task.Result;
                if (!s.Exists)
                {
                    Debug.Log("User is not registered.");
                    isRegistered.Invoke(false);
                }
                else
                {
                    Debug.Log("User is registered.");
                    isRegistered.Invoke(true);
                }
            }
        });


        // elapsedTime = 0;

        // if(FO.userId == "")
        // {
        //     yield break;
        // }

        // var task = UserRef.Child(FO.userId).GetValueAsync();
        // yield return new WaitWhile(() => IsTask(task.IsCompleted));

        // if(task.IsFaulted || task.IsCanceled)
        // {
        //     Debug.Log("Network error "+task.Exception);
        //     yield break;
        // }

        // var result = task.Result;

        // if(result == null || result.Value == null)
        // {
        //    Debug.Log("User is not registered. Creating new User...");
        //    isRegistered.Invoke(false);
        //     yield  break;
        // }
        // else
        // {
        //     Debug.Log("User is registered.");
        //     isRegistered.Invoke(true);
        //     yield return null;
        // }

        // yield return null;
    }
예제 #11
0
        public async Task TempMuteUser([RequireHierarchy] UserRef userRef, TimeSpan time, [Remainder] string reason)
        {
            if (time.TotalMinutes < 1)
            {
                await ReplyAsync("Can't temp-mute for less than a minute");

                return;
            }
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>();

            if (!(Context.Message.Author as IGuildUser).HasAdmin())
            {
                if (settings?.maxTempAction != null && time > settings.maxTempAction)
                {
                    await ReplyAsync("You are not allowed to punish for that long");

                    return;
                }
            }
            if (settings == null || settings.mutedRole == 0 || Context.Guild.GetRole(settings.mutedRole) == null)
            {
                await ReplyAsync("Muted role is null or invalid");

                return;
            }
            TempActionList actions = Context.Guild.LoadFromFile <TempActionList>(true);
            TempAct        oldAct  = actions.tempMutes.FirstOrDefault(tempMute => tempMute.User == userRef.ID);

            if (oldAct != null)
            {
                if (!(Context.Message.Author as IGuildUser).HasAdmin() && (oldAct.Length - (DateTime.UtcNow - oldAct.DateBanned)) >= time)
                {
                    await ReplyAsync($"{Context.User.Mention} please contact your admin(s) in order to shorten length of a punishment");

                    return;
                }
                string text    = $"{userRef.Name()} is already temp-muted for {oldAct.Length.LimitedHumanize()} ({(oldAct.Length - (DateTime.UtcNow - oldAct.DateBanned)).LimitedHumanize()} left), are you sure you want to change the length?";
                var    request = new ConfirmationBuilder()
                                 .WithContent(new PageBuilder().WithText(text))
                                 .Build();
                var result = await Interactivity.SendConfirmationAsync(request, Context.Channel, TimeSpan.FromMinutes(2));

                if (result.Value)
                {
                    actions.tempMutes.Remove(oldAct);
                    actions.SaveToFile();
                }
                else
                {
                    await ReplyAsync("Command canceled");

                    return;
                }
            }

            await userRef.TempMute(time, reason, Context, settings, actions);

            Context.Message.DeleteOrRespond($"Temporarily muted {userRef.Mention()} for {time.LimitedHumanize(3)} because of {reason}", Context.Guild);
        }
예제 #12
0
    public static void CreateNewUser(string uid, Action registrationSucceeded)
    {
        UserRef
        .Child(uid)
        .Child("point")
        .SetValueAsync(0)
        .ContinueWithOnMainThread(task => {
            if (task.IsFaulted)
            {
                // error handling here
            }
            else if (task.IsCompleted)
            {
                UserRef
                .Child(uid)
                .Child("visitedPlaces")
                .Child("t1")
                .SetValueAsync(0)
                .ContinueWithOnMainThread(task2 => {
                    if (task2.IsFaulted)
                    {
                        // error handling here
                    }
                    else if (task2.IsCompleted)
                    {
                        Debug.Log("New user created.");
                        registrationSucceeded.Invoke();
                    }
                });
            }
        });


        // yield return new WaitUntil(() => IsTask(task.IsCompleted));

        // if(task.IsFaulted || task.IsCanceled)
        // {
        //     Debug.Log("Creating new user failed or intterupted. Check your network connection." +task.Exception);
        //     yield break;
        // }

        // //If point successfully added, then add the visited place placeholder
        // elapsedTime = 0;
        // var nextTask = UserRef.Child(uid).Child("visitedPlaces").Child("t1").SetValueAsync(0);
        // yield return new WaitUntil(() => IsTask(nextTask.IsCompleted));

        // if (nextTask.IsFaulted || nextTask.IsCanceled)
        // {
        //     Debug.Log("Creating new user failed or intterupted. Check your network connection." + nextTask.Exception);
        //     yield break;
        // }

        // Debug.Log("New user created.");
        // registrationSucceeded.Invoke();

        // yield return null;
    }
예제 #13
0
 public BikeRent(BusinessEntities.Rents.BikeRent item)
     : base(item)
 {
     if (item != null)
     {
         this.Created   = item.CreatedUtc;
         this.CreatedBy = new UserRef(item.CreatedBy);
     }
 }
예제 #14
0
 public Bike(BusinessEntities.Bikes.Bike bike, Location?currentLocation)
     : base(bike, currentLocation)
 {
     if (bike != null)
     {
         this.Created   = bike.CreatedUtc;
         this.CreatedBy = new UserRef(bike.CreatedBy);
     }
 }
예제 #15
0
 /// <summary>
 /// Tries to mention a <see cref="UserRef"/>, otherwise returns their ID
 /// </summary>
 public static string Mention(this UserRef userRef)
 {
     if (userRef == null)
     {
         return("``ERROR``");
     }
     if (userRef.User != null)
     {
         return(userRef.User.Mention);
     }
     return($"User with ID:{userRef.ID}");
 }
예제 #16
0
 public static async Task <WarnResult> Warn(this UserRef userRef, float size, string reason, ITextChannel channel, string logLink = null)
 {
     Contract.Requires(userRef != null);
     if (userRef.GuildUser != null)
     {
         return(await userRef.GuildUser.Warn(size, reason, channel, logLink));
     }
     else
     {
         return(await userRef.ID.Warn(size, reason, channel, userRef.User, logLink));
     }
 }
        public AuthorizationContextProviderTestsFixture SetValidUserRef()
        {
            UserRef           = Guid.NewGuid();
            UserRefClaimValue = UserRef.ToString();

            var userRefClaimValue = UserRefClaimValue;

            AuthenticationService.Setup(a => a.IsUserAuthenticated()).Returns(true);
            AuthenticationService.Setup(a => a.TryGetCurrentUserClaimValue(DasClaimTypes.Id, out userRefClaimValue)).Returns(true);

            return(this);
        }
예제 #18
0
        public async Task CheckUserWarnsAsync(UserRef userRef = null, int amount = 5)
        {
            userRef ??= new UserRef(Context.User as IGuildUser);
            List <Infraction> infractions = userRef.LoadInfractions(Context.Guild, false);

            if (infractions?.Count is null or 0)
            {
                await ReplyAsync($"{userRef.Name()} has no infractions");

                return;
            }
            await ReplyAsync(embed : infractions.GetEmbed(userRef, Context.Guild, amount: amount, showLinks: true));
        }
예제 #19
0
 /// <summary>
 /// Sets the author of an <see cref="EmbedBuilder"/> using a <see cref="UserRef"/>
 /// </summary>
 public static EmbedBuilder WithAuthor(this EmbedBuilder embed, UserRef userRef)
 {
     Contract.Requires(embed != null);
     if (userRef.User != null)
     {
         embed.WithAuthor(userRef.User);
     }
     else
     {
         embed.WithAuthor($"Unknown user with ID:{userRef.ID}");
     }
     return(embed);
 }
예제 #20
0
        public async Task Ban([RequireHierarchy] UserRef userRef, [Remainder] string reason)
        {
            if (reason.Split(' ').First().ToTime() != null)
            {
                var query   = "Are you sure you don't mean to use !tempban?";
                var request = new ConfirmationBuilder()
                              .WithContent(new PageBuilder().WithText(query))
                              .Build();
                var result = await Interactivity.SendConfirmationAsync(request, Context.Channel, TimeSpan.FromMinutes(1));

                if (result.Value)
                {
                    await ReplyAsync("Command Canceled");

                    return;
                }
            }

            TempActionList actions = Context.Guild.LoadFromFile <TempActionList>(false);

            if (actions?.tempBans?.Any(tempBan => tempBan.User == userRef.ID) ?? false)
            {
                var query   = "User is already tempbanned, are you sure you want to ban?";
                var request = new ConfirmationBuilder()
                              .WithContent(new PageBuilder().WithText(query))
                              .Build();
                var result = await Interactivity.SendConfirmationAsync(request, Context.Channel, TimeSpan.FromMinutes(2));

                if (result.Value)
                {
                    await ReplyAsync("Command Canceled");

                    return;
                }
                actions.tempBans.Remove(actions.tempBans.First(tempban => tempban.User == userRef.ID));
            }
            else if ((await Context.Guild.GetBansAsync()).Any(ban => ban.User.Id == userRef.ID))
            {
                await ReplyAsync("User has already been banned permanently");

                return;
            }
            userRef.User?.TryNotify($"You have been perm banned in the {Context.Guild.Name} discord for {reason}");
            await Context.Guild.AddBanAsync(userRef.ID, reason : reason);

            DiscordLogging.LogTempAct(Context.Guild, Context.Message.Author, userRef, "Bann", reason, Context.Message.GetJumpUrl(), TimeSpan.Zero);
            Context.Message.DeleteOrRespond($"{userRef.Name(true)} has been banned for {reason}", Context.Guild);
        }
예제 #21
0
        private async Task LoginUser(string userId)
        {
            IActorRef user;

            try
            {
                var observer = CreateObserver <IUserEventObserver>();
                user = Context.System.ActorOf(
                    Props.Create(() => new UserActor(_clusterContext, userId, observer)),
                    "user_" + userId);
            }
            catch (Exception e)
            {
                _log.Error("Failed to create user.", e);
                return;
            }

            var registered = false;

            for (int i = 0; i < 10; i++)
            {
                var reply = await _clusterContext.UserTableContainer.Add(userId, user);

                if (reply.Added)
                {
                    registered = true;
                    break;
                }
                await Task.Delay(200);
            }

            if (registered == false)
            {
                _log.Error("Failed to register user.");
                user.Tell(InterfacedPoisonPill.Instance);
                return;
            }

            await _channel.BindActor(user, new TaggedType[] { typeof(IUser) }, ActorBindingFlags.OpenThenNotification);

            _user = user.Cast <UserRef>().WithRequestWaiter(this);
        }
예제 #22
0
        public async Task WarnWithSizeUserAsync([RequireHierarchy] UserRef userRef, float size, [Remainder] string reason)
        {
            IUserMessage logMessage = await DiscordLogging.LogWarn(Context.Guild, Context.Message.Author, userRef.ID, reason, Context.Message.GetJumpUrl());

            WarnResult result = await userRef.Warn(size, reason, Context.Channel as ITextChannel, logLink : logMessage?.GetJumpUrl());

            if (result.success)
            {
                Context.Message.DeleteOrRespond($"{userRef.Mention()} has gotten their {result.warnsAmount.Suffix()} infraction for {reason}", Context.Guild);
            }
            else
            {
                if (logMessage != null)
                {
                    DiscordLogging.deletedMessagesCache.Enqueue(logMessage.Id);
                    await logMessage.DeleteAsync();
                }
                await ReplyAsync(result.description.Truncate(1500));
            }
        }
예제 #23
0
        public override async Task <PreconditionResult> CheckPermissionsAsync(ICommandContext context,
                                                                              ParameterInfo parameter, object value, IServiceProvider services)
        {
            if (context.User is not IGuildUser guildUser)
            {
                return(PreconditionResult.FromError("This command cannot be used outside of a guild"));
            }
            var targetUser = value switch
            {
                UserRef userRef => userRef.GuildUser,
                IGuildUser targetGuildUser => targetGuildUser,
                ulong userId => await context.Guild.GetUserAsync(userId),
                _ => throw new ArgumentOutOfRangeException("Unknown Type used in parameter that requires hierarchy"),
            };

            if (targetUser == null)
            {
                if (value is UserRef)
                {
                    return(PreconditionResult.FromSuccess());
                }
                else
                {
                    return(PreconditionResult.FromError("Target user not found"));
                }
            }

            if (guildUser.GetHierarchy() <= targetUser.GetHierarchy())
            {
                return(PreconditionResult.FromError("You cannot target anyone else whose roles are higher than yours"));
            }

            var currentUser = await context.Guild.GetCurrentUserAsync();

            if (currentUser?.GetHierarchy() < targetUser.GetHierarchy())
            {
                return(PreconditionResult.FromError("The bot's role is lower than the targeted user."));
            }

            return(PreconditionResult.FromSuccess());
        }
예제 #24
0
        public async Task TempMuteWarnUser([RequireHierarchy] UserRef userRef, TimeSpan time, [Remainder] string reason)
        {
            if (time.TotalMinutes < 1)
            {
                await ReplyAsync("Can't temp-mute for less than a minute");

                return;
            }
            ModerationSettings settings = Context.Guild.LoadFromFile <ModerationSettings>();

            if (!(Context.Message.Author as IGuildUser).HasAdmin())
            {
                if (settings?.maxTempAction != null && time > settings.maxTempAction)
                {
                    await ReplyAsync("You are not allowed to punish for that long");

                    return;
                }
            }
            if (settings == null || settings.mutedRole == 0 || Context.Guild.GetRole(settings.mutedRole) == null)
            {
                await ReplyAsync("Muted role is null or invalid");

                return;
            }
            await userRef.Warn(1, reason, Context.Channel as ITextChannel, Context.Message.GetJumpUrl());

            TempActionList actions = Context.Guild.LoadFromFile <TempActionList>(true);

            if (actions.tempMutes.Any(tempMute => tempMute.User == userRef.ID))
            {
                await ReplyAsync($"{userRef.Name()} is already temp-muted, (the warn did go through)");

                return;
            }

            await userRef.TempMute(time, reason, Context, settings, actions);

            Context.Message.DeleteOrRespond($"Temporarily muted {userRef.Mention()} for {time.LimitedHumanize(3)} because of {reason}", Context.Guild);
        }
예제 #25
0
        private async Task<bool> LoginAsync(string userId, string password)
        {
            var userLogin = _comm.Channels[0].CreateRef<UserLoginRef>();
            var observer = _comm.ObserverRegistry.Create<IUserEventObserver>(this);

            try
            {
                _user = (UserRef)(await userLogin.Login(userId, password, observer));
                if (_user.IsChannelConnected() == false)
                    await _user.ConnectChannelAsync();
                _userEventObserver = (UserEventObserver)observer;
                _comm.Channels.Last().StateChanged += (_, state) => { if (state == ChannelStateType.Closed) _channelCloseCts?.Cancel(); };
                ConsoleUtil.Sys($"{userId} logined.");
                return true;
            }
            catch (Exception e)
            {
                _comm.ObserverRegistry.Remove(observer);
                ConsoleUtil.Err($"Failed to login {userId} with " + e);
                return false;
            }
        }
예제 #26
0
        public async Task <RuntimeResult> RemoveWarnAsync([RequireHierarchy] UserRef userRef, int index)
        {
            List <Infraction> infractions = userRef.LoadInfractions(Context.Guild, false);

            if (infractions?.Count is null or 0)
            {
                return(CommandResult.FromError("Infractions are null"));
            }
            if (infractions.Count < index || index <= 0)
            {
                return(CommandResult.FromError("Invalid infraction number"));
            }
            string reason = infractions[index - 1].Reason;

            infractions.RemoveAt(index - 1);

            userRef.SaveInfractions(infractions, Context.Guild);
            if (userRef.User != null) //Can't use null propagation on awaited tasks since it would be awaiting null
            {
                await userRef.User.TryNotify($"Your {index.Ordinalize()} warning in {Context.Guild.Name} discord for {reason} has been removed");
            }
            return(CommandResult.FromSuccess($"Removed {userRef.Mention()}'s warning for {reason}"));
        }
예제 #27
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.ForUser();
            modelBuilder.ForProduct();
            modelBuilder.ForFriendConnection();

            UserRef me       = new UserRef("DFE27E47-2BBE-4C7D-B419-25AC7835881F");
            UserRef neighbor = new UserRef("C8A9EFD2-F350-4437-ADA0-1CCB8C0DFA55");

            modelBuilder.Entity <User>().HasData(
                new User(1, "me", me),
                new User(2, "neighbor", neighbor));

            modelBuilder.Entity <Product>().HasData(
                new Product(1, "one", me, new ProductRef("5D1C71A1-2723-4FB6-B067-66F3BF5D0B60")),
                new Product(2, "two", me, new ProductRef("910500A0-F873-4B12-BFE0-73648AD89929")),
                new Product(3, "three", me, new ProductRef("2231D5B8-264D-4486-BCA3-E94D6FAA9F22")),
                new Product(4, "square", neighbor, new ProductRef("E306E9B6-D5E3-4714-B6BA-082C0F370F81")),
                new Product(5, "pointy", neighbor, new ProductRef("B2FF8A9E-A177-4929-A546-3BF014250394")),
                new Product(6, "round", neighbor, new ProductRef("B6D1FEF5-9DA2-4DCC-860C-BB07DDF7BF88")));
        }
예제 #28
0
        private ModifyPresidentialResultsCommand DefaultModifyPresidentialResultsCommand(int executionOrder, ResultRef result, PollingCentreRef pollingCentre, UserRef user)
        {
            var fixture = new Fixture();
            ModifyPresidentialResultsCommand cmd = fixture
                                                   .Build <ModifyPresidentialResultsCommand>()
                                                   .With(n => n.ApplyToResult, result)
                                                   .With(n => n.CommandGeneratedByUser, user)
                                                   .With(n => n.OriginatingPollingCentre, pollingCentre)
                                                   .Create();

            cmd.CommandId     = Guid.NewGuid();
            cmd.ApplyToResult = result;
            CandidateRef candidate = new CandidateRef(Guid.NewGuid(), "Pombe Magufuli", CandidateType.PartyBacked);
            var          res       = new ResultDetail {
                Candidate = candidate, Result = 1000
            };
            var resList = new List <ResultDetail>();

            resList.Add(res);
            cmd.ResultDetail             = resList;
            cmd.OriginatingPollingCentre = pollingCentre;
            cmd.CommandGeneratedByUser   = user;
            cmd.CommandExecutionOrder    = executionOrder;
            return(cmd);
        }
예제 #29
0
 private ConfirmPresidentialResultsCommand DefaultConfirmPresidentalResultsCommand(int executionOrder, ResultRef result, PollingCentreRef pollingCentre, UserRef user)
 {
     return(new ConfirmPresidentialResultsCommand
     {
         CommandId = Guid.NewGuid(),
         ApplyToResult = result,
         CommandGeneratedByUser = user,
         CommandExecutionOrder = executionOrder,
         OriginatingPollingCentre = pollingCentre
     });
 }
예제 #30
0
 public Product(int id, string name, UserRef owner)
 {
     this.Id       = id;
     this.Name     = name;
     this.OwnerKey = owner.Value;
 }