/// <summary> /// Updates a RolePersist entity in the database /// </summary> /// <param name="rolePersist">The updated entity</param> /// <returns>The Updated entity</returns> public async Task <RolePersist> UpdateRolePersist(RolePersist rolePersist) { var result = _dbContext.RolePersists.Update(rolePersist); await _dbContext.SaveChangesAsync(); return(result.Entity); }
/// <summary> /// Removes a RolePersist entity from the database /// </summary> /// <param name="rolePersist">The RolePersist entity to remove</param> public async Task RemoveRolePersist(RolePersist rolePersist) { // Remove the role from the user if they have it SocketGuild guild = _discord.GetGuild(rolePersist.GuildId); SocketGuildUser user = guild.GetUser(rolePersist.UserId); SocketRole role = guild.GetRole(rolePersist.RoleId); await user.RemoveRoleAsync(role); // Remove if from the database _dbContext.RolePersists.Remove(rolePersist); await _dbContext.SaveChangesAsync(); }
/// <summary> /// Starts a timer to remove a role persist when it is no longer active /// </summary> /// <param name="rolePersist">The role persist</param> private void StartTaskForRolePersist(RolePersist rolePersist) { // If it's indefinite don't bother starting a task if (!rolePersist.Duration.HasValue) { return; } // Find out how long it should go for TimeSpan timeout = rolePersist.Duration.Value - (DateTime.Now - rolePersist.Timestamp); if (timeout < TimeSpan.Zero) { timeout = TimeSpan.Zero; } // Create a new Task and delay the appropriate time Task.Delay(timeout).ContinueWith(t => { // Fetch the RolePersist entity from the database again in case it changed or was removed RolePersist rp = _dbContext.RolePersists.Find(rolePersist.Id); // If it was removed, return if (rp == null) { return; } // Otherwise continue with removing it SocketGuild guild = _discord.GetGuild(rp.GuildId); SocketRole role = guild.GetRole(rp.RoleId); SocketGuildUser user = guild.GetUser(rp.UserId); user.RemoveRoleAsync(role).GetAwaiter().GetResult(); RemoveRolePersist(rp).GetAwaiter().GetResult(); }); }