Exemple #1
0
        public UserRestModule()
        {
            Get["/getbasicusers"] = parameters =>
            {
                List <User> users;
                string      message = Globals.UserDB.LoadUsers(out users);
                if (String.IsNullOrWhiteSpace(message))
                {
                    List <RestUser> lst = new List <RestUser>();
                    foreach (User usr in users)
                    {
                        lst.Add(RestUser.UserToRest(usr, false));
                    }
                    return(Response.AsJson(lst));
                }

                Response error = new Response();
                error.StatusCode   = HttpStatusCode.NotImplemented;
                error.ReasonPhrase = message;
                return(error);
            };

            Get["/getusers"] = parameters =>
            {
                Response error;
                if (!Program.Handle.EnableGetUsers)
                {
                    error            = new Response();
                    error.StatusCode = HttpStatusCode.NotAcceptable;
                    return(error);
                }

                List <User> users;
                string      message = Globals.UserDB.LoadUsers(out users);
                if (String.IsNullOrWhiteSpace(message))
                {
                    List <RestUser> lst = new List <RestUser>();
                    foreach (User usr in users)
                    {
                        lst.Add(RestUser.UserToRest(usr));
                    }
                    return(Response.AsJson(lst));
                }
                error              = new Response();
                error.StatusCode   = HttpStatusCode.NotImplemented;
                error.ReasonPhrase = message;
                return(error);
            };

            Post["/remotelogin"] = parameters =>
            {
                Response error;

                int id = 0;
                if (!int.TryParse(this.Request.Form.id, out id))
                {
                    return(HttpStatusCode.BadRequest);
                }

                string password = this.Request.Form.password;
                if (this.LoginUser(id, password))
                {
                    return(Negotiate.WithStatusCode(HttpStatusCode.OK));
                }
                else
                {
                    error              = new Response();
                    error.StatusCode   = HttpStatusCode.NotFound;
                    error.ReasonPhrase = "Username and password do not match";
                    return(error);
                }
            };

            Post["/remotelogout"] = parameters =>
            {
                this.Logout();
                return(HttpStatusCode.OK);
            };

            Post["/deleteuser"] = parameters =>
            {
                RestUser restUser = this.Bind <RestUser>();
                Response error;
                if (!this.IsValidUser())
                {
                    error              = new Response();
                    error.StatusCode   = HttpStatusCode.Unauthorized;
                    error.ReasonPhrase = "Please log in to continue.";
                    return(error);
                }

                if (this.SecurityLevel < restUser.SecurityLevel)
                {
                    error              = new Response();
                    error.StatusCode   = HttpStatusCode.Unauthorized;
                    error.ReasonPhrase = "You are not authorised to do this.";
                    return(error);
                }

                string message;
                if (Globals.UserDB.DeleteUser(restUser.UserID, out message))
                {
                    return(Negotiate.WithStatusCode(HttpStatusCode.OK));
                }
                else
                {
                    error              = new Response();
                    error.StatusCode   = HttpStatusCode.ExpectationFailed;
                    error.ReasonPhrase = message;
                    return(error);
                }
            };

            Post["/addedituser"] = parameters =>
            {
                RestUser restUser = this.Bind <RestUser>();
                Response error;
                string   errormessage;
                if (!CheckModifyUser(restUser.UserID, restUser.SecurityLevel, out errormessage))
                {
                    error              = new Response();
                    error.StatusCode   = HttpStatusCode.Unauthorized;
                    error.ReasonPhrase = errormessage;
                    return(error);
                }

                errormessage = Globals.UserDB.AddEditUser(RestUser.RestToUser(restUser), false, true, false);

                if (String.IsNullOrWhiteSpace(errormessage))
                {
                    return(Negotiate.WithStatusCode(HttpStatusCode.OK));
                }
                else
                {
                    error              = new Response();
                    error.StatusCode   = HttpStatusCode.ExpectationFailed;
                    error.ReasonPhrase = errormessage;
                    return(error);
                }
            };


            Get["/readuserlastupdated"] = parameters =>
            {
                Response error;
                string   message;
                DateTime dtTime = Globals.UserDB.ReadUserLastUpdated(out message);
                if (String.IsNullOrWhiteSpace(message))
                {
                    return(Response.AsJson(new RestUserLastUpdated()
                    {
                        Date = dtTime
                    }));
                }
                error              = new Response();
                error.StatusCode   = HttpStatusCode.NotImplemented;
                error.ReasonPhrase = message;
                return(error);
            };
        }
Exemple #2
0
        public static async Task CheckTempActs(DiscordSocketClient client, bool debug = false, CancellationToken?ct = null)
        {
            RequestOptions requestOptions = RequestOptions.Default;

            requestOptions.RetryMode = RetryMode.AlwaysRetry;
            try
            {
                currentInfo.checkedGuilds = 0;
                foreach (SocketGuild sockGuild in client.Guilds)
                {
                    ct?.ThrowIfCancellationRequested();
                    currentInfo.checkedMutes = 0;
                    if (currentInfo.checkedGuilds > client.Guilds.Count)
                    {
                        await new LogMessage(LogSeverity.Error, "TempAct", $"Check went past all guilds (at #{currentInfo.checkedGuilds}) but has been stopped. This doesn't seem physically possible.").Log();
                        return;
                    }
                    RestGuild restGuild = await client.Rest.SuperGetRestGuild(sockGuild.Id);

                    if (debug)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write($"\nChecking {sockGuild.Name} discord ");
                    }
                    TempActionList actions  = sockGuild.LoadFromFile <TempActionList>(false);
                    bool           needSave = false;
                    currentInfo.checkedGuilds++;
                    if (actions != null)
                    {
                        if (actions.tempBans?.Count is not null or 0)
                        {
                            currentInfo.editedBans = new List <TempAct>(actions.tempBans);
                            foreach (TempAct tempBan in actions.tempBans)
                            {
                                try
                                {
                                    RestBan ban = await sockGuild.GetBanAsync(tempBan.User, requestOptions);

                                    if (ban == null)
                                    { //If manual unban
                                        var user = await client.Rest.GetUserAsync(tempBan.User);

                                        currentInfo.editedBans.Remove(tempBan);
                                        user?.TryNotify($"As you might know, you have been manually unbanned in {sockGuild.Name} discord");
                                        //_ = new LogMessage(LogSeverity.Warning, "TempAction", "Tempbanned person isn't banned").Log();
                                        if (user == null)
                                        {
                                            DiscordLogging.LogManualEndTempAct(sockGuild, tempBan.User, "bann", tempBan.DateBanned);
                                        }
                                        else
                                        {
                                            DiscordLogging.LogManualEndTempAct(sockGuild, user, "bann", tempBan.DateBanned);
                                        }
                                    }
                                    else if (DateTime.UtcNow >= tempBan.DateBanned.Add(tempBan.Length))
                                    {
                                        RestUser rUser = ban.User;
                                        await sockGuild.RemoveBanAsync(tempBan.User, requestOptions);

                                        currentInfo.editedBans.Remove(tempBan);
                                        DiscordLogging.LogEndTempAct(sockGuild, rUser, "bann", tempBan.Reason, tempBan.Length);
                                    }
                                }
                                catch (Exception e)
                                {
                                    await new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unbanning someone, continuing", e).Log();
                                }
                            }

                            //if all tempbans DON'T equal all edited tempbans (basically if there was a change
                            if (currentInfo.editedBans.Count != actions.tempBans.Count)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempBans.Count - currentInfo.editedBans.Count} tempbans are over, ");
                                }
                                needSave         = true;
                                actions.tempBans = currentInfo.editedBans;
                            }
                            else if (debug)
                            {
                                Console.Write($"tempbans checked, none over, ");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write($"no tempbans, ");
                        }
                        ModerationSettings settings = sockGuild.LoadFromFile <ModerationSettings>();
                        if (settings is not null && sockGuild.GetRole(settings.mutedRole) != null && actions.tempMutes?.Count is not null or 0)
                        {
                            var            mutedRole   = sockGuild.GetRole(settings.mutedRole);
                            List <TempAct> editedMutes = new List <TempAct>(actions.tempMutes);
                            foreach (TempAct tempMute in actions.tempMutes)
                            {
                                currentInfo.checkedMutes++;
                                try
                                {
                                    IGuildUser gUser = sockGuild.GetUser(tempMute.User) ?? await restGuild.SuperGetUser(tempMute.User);

                                    if (gUser != null && !gUser.RoleIds.Contains(settings.mutedRole))
                                    { //User missing muted role, must have been manually unmuted
                                        _ = gUser.TryNotify($"As you might know, you have been manually unmuted in {sockGuild.Name} discord");
                                        editedMutes.Remove(tempMute);
                                        DiscordLogging.LogManualEndTempAct(sockGuild, gUser, "mut", tempMute.DateBanned);
                                        _ = (!editedMutes.Contains(tempMute)).AssertAsync("Tempmute not removed?!");
                                    }
                                    else if (DateTime.UtcNow >= tempMute.DateBanned.Add(tempMute.Length))
                                    { //Normal mute end
                                        if (gUser != null)
                                        {
                                            await gUser.RemoveRoleAsync(mutedRole, requestOptions);
                                        } // if user not in guild || if user doesn't contain muted role (successfully removed?
                                        if (gUser == null || !gUser.RoleIds.Contains(settings.mutedRole))
                                        { //Doesn't remove tempmute if unmuting fails
                                            IUser user = gUser; //Gets user to try to message
                                            user ??= await client.SuperGetUser(tempMute.User);

                                            if (user != null)
                                            { // if possible to message, message and log
                                                DiscordLogging.LogEndTempAct(sockGuild, user, "mut", tempMute.Reason, tempMute.Length);
                                                _ = user.Notify("auto untempmuted", tempMute.Reason, sockGuild, client.CurrentUser);
                                            }
                                            editedMutes.Remove(tempMute);
                                        }
                                        else if (gUser != null)
                                        {
                                            await new LogMessage(LogSeverity.Warning, "TempAct", "User should've had role removed").Log();
                                        }
                                    }
                                }
                                catch (Exception e)
                                {
                                    await new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unmuting someone, continuing", e).Log();
                                }
                            }

                            //NOTE: Assertions fail if NOT true
                            _ = (currentInfo.checkedMutes == actions.tempMutes.Count).AssertAsync($"Checked incorrect number tempmutes ({currentInfo.checkedMutes}/{actions.tempMutes.Count}) in guild {sockGuild} owned by {sockGuild.Owner}");

                            if (editedMutes.Count != actions.tempMutes.Count)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempMutes.Count - editedMutes.Count}/{actions.tempMutes.Count} tempmutes are over");
                                }
                                actions.tempMutes = editedMutes;
                                needSave          = true;
                            }
                            else if (debug)
                            {
                                Console.Write($"none of {actions.tempMutes.Count} tempmutes over");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write("no tempmutes to check or no settings");
                        }
                        if (needSave)
                        {
                            actions.SaveToFile();
                        }
                    }
Exemple #3
0
        private async void OnTimedEvent()
        {
            List <PriorityTable> plist = new List <PriorityTable>();

            while (true)
            {
                try
                {
                    plist.Clear();
                    plist.AddRange(Repo.Priority.Priorities.Where(f => !f.Notified).ToList());
                    for (var index = 0; index < plist.Count; index++)
                    {
                        var priority = plist[index];
                        if (priority.Remining.TotalDays >= 0 && priority.Remining.TotalDays <= 2.1)
                        {
                            try
                            {
                                RestUser usr     = null;
                                string   namefor = "";
                                string   gid     = "";
                                if (priority.State == PriorityState.User)
                                {
                                    usr = DiscordRestApi.GetApi.GetUserAsync(priority.GetUlongId()).Result;
                                    if (usr == null)
                                    {
                                        continue;
                                    }
                                    namefor = $"{usr.Username}#{usr.Discriminator}";
                                    gid     = $" 'please specify your UserId(**{priority.GetUlongId()}**) on description'";
                                }
                                else if (priority.State == PriorityState.Guild)
                                {
                                    var guild = DiscordRestApi.GetApi.GetGuildAsync(priority.GetUlongId()).Result;
                                    if (guild == null)
                                    {
                                        continue;
                                    }
                                    usr = DiscordRestApi.GetApi.GetUserAsync(guild.OwnerId).Result;
                                    if (usr == null)
                                    {
                                        continue;
                                    }
                                    namefor = $"{guild.Name}";
                                    gid     = $" 'please specify your DiscordServerId(**{priority.GetUlongId()}**) on description'";
                                }
                                else
                                {
                                    throw new Exception("undefined PriorityState for PriorityManager");
                                }

                                DateTime dtx = new DateTime();
                                dtx = dtx.Add(priority.Remining);
                                EmbedBuilder embed = new EmbedBuilder()
                                {
                                    Author = new EmbedAuthorBuilder()
                                    {
                                        IconUrl = DiscordRestApi.GetApi.CurrentUser.GetAvatarUrl(),
                                        Name    = DiscordRestApi.GetApi.CurrentUser.Username
                                    },
                                    Color       = Color.Green,
                                    Title       = $"REMINDER FOR FTN POWER DISCORD PLAN",
                                    Description =
                                        $"\n Priority Feature plan for '**{namefor}**'[**{priority.State}**] \n__expires in__ **{dtx.Month - 1}**Months **{dtx.Day - 1}**days **{dtx.Hour}**hours\n\nif you like, you can get this discord-plan again (1 month for all discord members). [Plans](https://ftnpower.com/home/plans){gid}\nthank you for using **FTN Power** :heart:\n\n",
                                    Footer = new EmbedFooterBuilder()
                                    {
                                    }
                                };
                                priority.Notified = true;
                                if (priority.State == PriorityState.Guild)
                                {
                                    Repo.ResetFeatures(priority.GetUlongId().ToString());
                                }
                                var dm = await usr.GetOrCreateDMChannelAsync();

                                var msg = await dm.SendMessageAsync(string.Empty, false, embed.Build(), Core.Utils.RequestOption);

                                await dm.CloseAsync(Core.Utils.RequestOption);

                                Log.Information("{lt}: customer {CustomerState} name with '{CustomerName}', it's id {PriorityId}", "Service", priority.State.ToString(), namefor, priority.Id);

                                var usr2 = DiscordRestApi.GetApi.GetUserAsync(193749607107395585).Result;
                                var dm2  = await usr2.GetOrCreateDMChannelAsync();

                                var msg2 = await dm2.SendMessageAsync(string.Empty, false, embed.Build(), Core.Utils.RequestOption);

                                await dm2.CloseAsync(Core.Utils.RequestOption);

                                Thread.Sleep(10);
                            }
                            catch (Exception e)
                            {
                                Log.Write(Serilog.Events.LogEventLevel.Warning, "{lt}: Owner couldn't informed about subscription expiration priority is {PriorityId}", "Service", priority.Id);
                                var usr2 = DiscordRestApi.GetApi.GetUserAsync(193749607107395585).Result;
                                var dm2  = await usr2.GetOrCreateDMChannelAsync();

                                EmbedBuilder embed = new EmbedBuilder()
                                {
                                    Title       = $"ERROR WHILE CHECKING FTN POWER DISCORD PLAN",
                                    Description = $"ERROR_WHILE_CHECKING_PRIORITY_ID_{priority.Id}_[{e.Message}],**so they couldn't informed**",
                                    Color       = Color.DarkRed
                                };
                                var msg2 = await dm2.SendMessageAsync(string.Empty, false, embed.Build(), Core.Utils.RequestOption);

                                await dm2.CloseAsync(Core.Utils.RequestOption);

                                continue;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Exception(e, Serilog.Events.LogEventLevel.Fatal);
                }
                finally
                {
                    Thread.Sleep(new TimeSpan(0, 5, 0));
                }
            }
        }
Exemple #4
0
        public static async Task TempActChecker(DiscordSocketClient client, bool debug = false)
        {
            try {
                int checkedGuilds = 0;
                foreach (SocketGuild guild in client.Guilds)
                {
                    if (debug)
                    {
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.Write($"\nChecking {guild.Name} discord ");
                    }
                    TempActionList actions  = guild.LoadFromFile <TempActionList>(false);
                    bool           needSave = false;
                    checkedGuilds++;
                    if (actions != null)
                    {
                        if (!actions.tempBans.IsNullOrEmpty())
                        {
                            List <TempAct> editedBans = new List <TempAct>(actions.tempBans);
                            foreach (TempAct tempBan in actions.tempBans)
                            {
                                try {
                                    if (!guild.GetBansAsync().Result.Any(ban => ban.User.Id == tempBan.user))   //Need to add an embed for when this happens that's distinct
                                    {
                                        _ = client.GetUser(tempBan.user)?.TryNotify($"As you might know, you have been manually unbanned in {guild.Name} discord");
                                        //_ = new LogMessage(LogSeverity.Warning, "TempAction", "Tempbanned person isn't banned").Log();
                                        editedBans.Remove(tempBan);
                                    }
                                    else if (DateTime.Now >= tempBan.dateBanned.Add(tempBan.length))
                                    {
                                        RestUser rUser = guild.GetBansAsync().Result.First(ban => ban.User.Id == tempBan.user).User;
                                        await guild.RemoveBanAsync(tempBan.user);

                                        editedBans.Remove(tempBan);
                                        Logging.LogEndTempAct(guild, rUser, "bann", tempBan.reason, tempBan.length);
                                    }
                                } catch (Exception e) {
                                    _ = new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unbanning someone, continuing", e).Log();
                                }
                            }

                            if (editedBans != actions.tempBans)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempBans.Count - editedBans.Count} tempbans are over, ");
                                }
                                needSave         = true;
                                actions.tempBans = editedBans;
                            }
                            else if (debug)
                            {
                                Console.Write($"tempbans checked, none over, ");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write($"no tempbans, ");
                        }

                        ModerationSettings settings = guild.LoadFromFile <ModerationSettings>();
                        if (settings != null && guild.GetRole(settings.mutedRole) != null && !actions.tempMutes.IsNullOrEmpty())
                        {
                            List <TempAct> editedMutes  = new List <TempAct>(actions.tempMutes);
                            uint           checkedMutes = 0;
                            foreach (TempAct tempMute in actions.tempMutes)
                            {
                                checkedMutes++;
                                try {
                                    SocketUser user = guild.GetUser(tempMute.user);
                                    if (user != null && !(user as IGuildUser).RoleIds.Contains(settings.mutedRole))
                                    {
                                        _ = user.TryNotify($"As you might know, you have been manually unmuted in {guild.Name} discord");
                                        editedMutes.Remove(tempMute);
                                    }
                                    else if (DateTime.Now >= tempMute.dateBanned.Add(tempMute.length))
                                    {
                                        if (user != null)
                                        {
                                            await guild.GetUser(tempMute.user).RemoveRoleAsync(guild.GetRole(settings.mutedRole));
                                        }
                                        if (!(user as IGuildUser)?.RoleIds?.NotEmpty() ?? true || !(user as IGuildUser).RoleIds.Contains(settings.mutedRole))   //Doesn't remove tempmute if unmuting fails
                                        {
                                            user ??= client.GetUser(tempMute.user);
                                            if (user != null)
                                            {
                                                Logging.LogEndTempAct(guild, user, "mut", tempMute.reason, tempMute.length);
                                                _ = user.Notify($"untemp-muted", tempMute.reason, guild);
                                            }
                                            editedMutes.Remove(tempMute);
                                        }
                                    }
                                } catch (Exception e) {
                                    _ = new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unmuting someone, continuing", e).Log();
                                }
                            }

                            _ = (checkedMutes == actions.tempMutes.Count || checkedMutes == uint.MaxValue).AssertAsync("Didn't check all tempmutes");

                            if (editedMutes != actions.tempMutes)
                            {
                                if (debug)
                                {
                                    Console.Write($"{actions.tempMutes.Count - editedMutes.Count}/{actions.tempMutes.Count} tempmutes are over");
                                }
                                actions.tempMutes = editedMutes;
                                needSave          = true;
                            }
                            else if (debug)
                            {
                                Console.Write($"no tempmute changes");
                            }
                        }
                        else if (debug)
                        {
                            Console.Write("no tempmutes to check or no settings");
                        }
                        if (needSave)
                        {
                            actions.SaveToFile(guild);
                        }
                    }
                }
                if (debug)
                {
                    Console.Write("\n");
                }
                _ = (checkedGuilds > 0).AssertWarnAsync("Checked 0 guilds for tempbans?");
            } catch (Exception e) {
                _ = new LogMessage(LogSeverity.Error, "TempAct", "Something went wrong unbanning someone", e).Log();
            }
        }